From 0dda46f0b93cdbeac2317721537f4475cfa38609 Mon Sep 17 00:00:00 2001 From: Peng-Yu Chen Date: Mon, 5 Aug 2024 03:15:55 +0000 Subject: [PATCH] LeetCode --- .clang-format | 21 + .github/workflows/main.yaml | 92 ++++ .prettierrc | 13 + LICENSE | 21 + README.md | 43 ++ STYLEGUIDE.md | 517 ++++++++++++++++++ solutions/1. Two Sum/1.cpp | 15 + solutions/1. Two Sum/1.java | 13 + solutions/1. Two Sum/1.py | 8 + .../10. Regular Expression Matching/10.cpp | 31 ++ .../10. Regular Expression Matching/10.java | 30 + .../10. Regular Expression Matching/10.py | 26 + solutions/100. Same Tree/100.cpp | 10 + solutions/100. Same Tree/100.java | 9 + solutions/100. Same Tree/100.py | 7 + .../1000-2.cpp | 30 + .../1000-2.java | 31 ++ .../1000-3.cpp | 36 ++ .../1000-3.java | 36 ++ .../1000-4.cpp | 30 + .../1000-4.java | 31 ++ .../1000.cpp | 37 ++ .../1000.java | 39 ++ solutions/1001. Grid Illumination/1001.cpp | 50 ++ solutions/1001. Grid Illumination/1001.java | 46 ++ solutions/1001. Grid Illumination/1001.py | 32 ++ .../1002. Find Common Characters/1002.cpp | 21 + .../1002. Find Common Characters/1002.java | 21 + .../1002. Find Common Characters/1002.py | 4 + .../1003.cpp | 22 + .../1003.java | 21 + .../1003.py | 14 + .../1004. Max Consecutive Ones III/1004.cpp | 17 + .../1004. Max Consecutive Ones III/1004.java | 16 + .../1004. Max Consecutive Ones III/1004.py | 15 + .../1005.cpp | 16 + .../1005.java | 14 + .../1005.py | 11 + solutions/1006. Clumsy Factorial/1006.cpp | 20 + solutions/1006. Clumsy Factorial/1006.java | 19 + solutions/1006. Clumsy Factorial/1006.py | 17 + .../1007.cpp | 22 + .../1007.java | 21 + .../1007.py | 6 + .../1008.cpp | 23 + .../1008.java | 22 + .../1008.py | 19 + .../1009.cpp | 9 + .../1009.java | 8 + .../1009.py | 6 + solutions/101. Symmetric Tree/101.cpp | 16 + solutions/101. Symmetric Tree/101.java | 12 + solutions/101. Symmetric Tree/101.py | 11 + .../1010.cpp | 15 + .../1010.java | 14 + .../1010.py | 11 + .../1011.cpp | 31 ++ .../1011.java | 29 + .../1011.py | 17 + .../1012.cpp | 44 ++ .../1012.java | 39 ++ .../1012.py | 35 ++ .../1013.cpp | 23 + .../1013.java | 22 + .../1013.py | 18 + .../1014. Best Sightseeing Pair/1014.cpp | 14 + .../1014. Best Sightseeing Pair/1014.java | 13 + solutions/1014. Best Sightseeing Pair/1014.py | 10 + .../1015.cpp | 21 + .../1015.java | 20 + .../1015.py | 17 + .../1016.cpp | 16 + .../1016.java | 12 + .../1016.py | 10 + solutions/1017. Convert to Base -2/1017.cpp | 13 + solutions/1017. Convert to Base -2/1017.java | 12 + solutions/1017. Convert to Base -2/1017.py | 9 + .../1018.cpp | 14 + .../1018.java | 13 + .../1018.py | 10 + .../1019.cpp | 22 + .../1019.java | 20 + .../1019.py | 17 + .../102.cpp | 26 + .../102.java | 24 + .../102.py | 20 + solutions/1020. Number of Enclaves/1020.cpp | 32 ++ solutions/1020. Number of Enclaves/1020.java | 27 + .../1021.cpp | 17 + .../1021.java | 16 + .../1021.py | 16 + .../1022.cpp | 19 + .../1022.java | 18 + .../1022.py | 16 + solutions/1023. Camelcase Matching/1023.cpp | 20 + solutions/1023. Camelcase Matching/1023.java | 18 + solutions/1023. Camelcase Matching/1023.py | 12 + solutions/1024. Video Stitching/1024.cpp | 22 + solutions/1024. Video Stitching/1024.java | 21 + solutions/1024. Video Stitching/1024.py | 19 + solutions/1025. Divisor Game/1025.cpp | 6 + solutions/1025. Divisor Game/1025.java | 5 + solutions/1025. Divisor Game/1025.py | 3 + .../1026.cpp | 18 + .../1026.java | 16 + .../1027.cpp | 19 + .../1027.java | 18 + .../1027.py | 15 + .../1028.cpp | 25 + .../1028.java | 24 + .../1028.py | 22 + solutions/1029. Two City Scheduling/1029.cpp | 22 + solutions/1029. Two City Scheduling/1029.java | 20 + solutions/1029. Two City Scheduling/1029.py | 13 + .../103-2.cpp | 30 + .../103-2.java | 29 + .../103-2.py | 24 + .../103.cpp | 37 ++ .../103.java | 34 ++ .../103.py | 30 + .../1030.cpp | 29 + .../1030.java | 27 + .../1030.py | 21 + .../1031.cpp | 40 ++ .../1031.java | 37 ++ .../1031.py | 27 + solutions/1032. Stream of Characters/1032.cpp | 44 ++ .../1032. Stream of Characters/1032.java | 41 ++ solutions/1032. Stream of Characters/1032.py | 30 + .../1033.cpp | 13 + .../1033.java | 12 + .../1033.py | 8 + solutions/1034. Coloring A Border/1034.cpp | 38 ++ solutions/1034. Coloring A Border/1034.java | 35 ++ solutions/1034. Coloring A Border/1034.py | 27 + solutions/1035. Uncrossed Lines/1035.cpp | 16 + solutions/1035. Uncrossed Lines/1035.java | 14 + solutions/1035. Uncrossed Lines/1035.py | 13 + solutions/1036. Escape a Large Maze/1036.cpp | 34 ++ solutions/1036. Escape a Large Maze/1036.java | 30 + solutions/1036. Escape a Large Maze/1036.py | 16 + solutions/1037. Valid Boomerang/1037.cpp | 7 + solutions/1037. Valid Boomerang/1037.java | 7 + solutions/1037. Valid Boomerang/1037.py | 4 + .../1038.cpp | 21 + .../1039.cpp | 18 + .../1039.java | 15 + .../1039.py | 13 + .../104. Maximum Depth of Binary Tree/104.cpp | 8 + .../104.java | 7 + .../104. Maximum Depth of Binary Tree/104.py | 5 + .../1040.cpp | 22 + .../1040.java | 21 + .../1040.py | 18 + .../1041. Robot Bounded In Circle/1041.cpp | 21 + .../1041. Robot Bounded In Circle/1041.java | 20 + .../1041. Robot Bounded In Circle/1041.py | 17 + .../1042.cpp | 27 + .../1042.java | 29 + .../1042.py | 21 + .../1043.cpp | 17 + .../1043.java | 16 + .../1043.py | 12 + .../1044.cpp | 65 +++ .../1044.java | 64 +++ .../1044. Longest Duplicate Substring/1044.py | 47 ++ .../1045.sql | 6 + solutions/1046. Last Stone Weight/1046.cpp | 17 + solutions/1046. Last Stone Weight/1046.java | 17 + solutions/1046. Last Stone Weight/1046.py | 12 + .../1047.cpp | 14 + .../1047.java | 15 + .../1048. Longest String Chain/1048-2.cpp | 22 + .../1048. Longest String Chain/1048-2.java | 20 + .../1048. Longest String Chain/1048-2.py | 9 + solutions/1048. Longest String Chain/1048.cpp | 29 + .../1048. Longest String Chain/1048.java | 29 + solutions/1048. Longest String Chain/1048.py | 15 + solutions/1049. Last Stone Weight II/1049.cpp | 19 + .../1049. Last Stone Weight II/1049.java | 18 + solutions/1049. Last Stone Weight II/1049.py | 14 + .../105.cpp | 31 ++ .../105.java | 28 + .../105.py | 20 + .../1050.sql | 4 + solutions/1051. Height Checker/1051.cpp | 21 + solutions/1051. Height Checker/1051.java | 20 + solutions/1051. Height Checker/1051.py | 17 + .../1052. Grumpy Bookstore Owner/1052.cpp | 20 + .../1052. Grumpy Bookstore Owner/1052.java | 19 + .../1052. Grumpy Bookstore Owner/1052.py | 14 + .../1053.cpp | 18 + .../1053.java | 23 + .../1053.py | 15 + solutions/1054. Distant Barcodes/1054.cpp | 27 + solutions/1054. Distant Barcodes/1054.java | 32 ++ solutions/1054. Distant Barcodes/1054.py | 19 + .../1055-2.cpp | 39 ++ .../1055-2.java | 40 ++ .../1055.cpp | 19 + .../1055.java | 18 + solutions/1056. Confusing Number/1056.cpp | 17 + solutions/1056. Confusing Number/1056.java | 15 + solutions/1056. Confusing Number/1056.py | 12 + solutions/1057. Campus Bikes/1057.cpp | 30 + solutions/1057. Campus Bikes/1057.java | 35 ++ solutions/1057. Campus Bikes/1057.py | 21 + .../1058.cpp | 37 ++ .../1058.java | 39 ++ .../1058.py | 24 + .../1059.cpp | 34 ++ .../1059.java | 33 ++ .../106.cpp | 31 ++ .../106.java | 27 + .../106.py | 20 + .../1060.cpp | 21 + .../1060.java | 22 + .../1061.cpp | 38 ++ .../1061.java | 37 ++ .../1062.cpp | 18 + .../1062.java | 17 + .../1062. Longest Repeating Substring/1062.py | 14 + .../1063. Number of Valid Subarrays/1063.cpp | 24 + .../1063. Number of Valid Subarrays/1063.java | 23 + .../1063. Number of Valid Subarrays/1063.py | 20 + solutions/1064. Fixed Point/1064.cpp | 19 + solutions/1064. Fixed Point/1064.java | 18 + solutions/1064. Fixed Point/1064.py | 15 + .../1065. Index Pairs of a String/1065.cpp | 38 ++ .../1065. Index Pairs of a String/1065.java | 36 ++ .../1065. Index Pairs of a String/1065.py | 29 + solutions/1066. Campus Bikes II/1066.cpp | 32 ++ solutions/1066. Campus Bikes II/1066.java | 28 + solutions/1066. Campus Bikes II/1066.py | 18 + solutions/1067. Digit Count in Range/1067.cpp | 25 + .../1067. Digit Count in Range/1067.java | 23 + .../1068. Product Sales Analysis I/1068.sql | 7 + .../1069. Product Sales Analysis II/1069.sql | 3 + .../107.cpp | 27 + .../107.java | 25 + .../107.py | 20 + .../1070. Product Sales Analysis III/1070.sql | 14 + .../1071.cpp | 19 + .../1071.java | 17 + .../1071.py | 14 + .../1072.cpp | 26 + .../1072.java | 25 + .../1072.py | 4 + .../1073.cpp | 23 + .../1073.java | 22 + .../1073.py | 17 + .../1074.cpp | 30 + .../1074.java | 28 + .../1074.py | 23 + solutions/1075. Project Employees I/1075.sql | 7 + solutions/1076. Project Employees II/1076.sql | 9 + .../1077. Project Employees III/1077.sql | 16 + .../1078. Occurrences After Bigram/1078.cpp | 16 + .../1078. Occurrences After Bigram/1078.java | 12 + .../1078. Occurrences After Bigram/1078.py | 4 + .../1079. Letter Tile Possibilities/1079.cpp | 29 + .../1079. Letter Tile Possibilities/1079.java | 26 + .../1079. Letter Tile Possibilities/1079.py | 19 + .../108.cpp | 14 + .../108.java | 12 + .../108.py | 11 + .../1080.cpp | 12 + .../1080.java | 11 + .../1080.py | 9 + .../1081.cpp | 25 + .../1081.java | 28 + .../1081.py | 17 + solutions/1082. Sales Analysis I/1082.sql | 12 + solutions/1083. Sales Analysis II/1083.sql | 8 + solutions/1084. Sales Analysis III/1084.sql | 11 + .../1085.cpp | 14 + .../1085.java | 13 + .../1085.py | 3 + solutions/1086. High Five/1086.cpp | 25 + solutions/1086. High Five/1086.java | 27 + solutions/1086. High Five/1086.py | 10 + solutions/1087. Brace Expansion/1087.cpp | 38 ++ solutions/1087. Brace Expansion/1087.java | 28 + solutions/1087. Brace Expansion/1087.py | 21 + solutions/1088. Confusing Number II/1088.cpp | 23 + solutions/1088. Confusing Number II/1088.java | 23 + solutions/1088. Confusing Number II/1088.py | 17 + solutions/1089. Duplicate Zeros/1089.cpp | 14 + solutions/1089. Duplicate Zeros/1089.java | 17 + solutions/1089. Duplicate Zeros/1089.py | 15 + .../109-2.cpp | 24 + .../109-2.java | 22 + .../109-2.py | 21 + .../109-3.cpp | 38 ++ .../109-3.java | 36 ++ .../109-3.py | 32 ++ .../109.cpp | 32 ++ .../109.java | 30 + .../109.py | 26 + .../1090. Largest Values From Labels/1090.cpp | 27 + .../1091.cpp | 40 ++ .../1091.java | 39 ++ .../1092.cpp | 42 ++ .../1092.java | 42 ++ .../1093.cpp | 56 ++ .../1093.java | 64 +++ .../1093.py | 26 + solutions/1094. Car Pooling/1094-2.cpp | 23 + solutions/1094. Car Pooling/1094-2.java | 22 + solutions/1094. Car Pooling/1094.cpp | 23 + solutions/1094. Car Pooling/1094.java | 22 + .../1095. Find in Mountain Array/1095.cpp | 63 +++ .../1095. Find in Mountain Array/1095.java | 59 ++ .../1095. Find in Mountain Array/1095.py | 50 ++ solutions/1096. Brace Expansion II/1096.cpp | 45 ++ solutions/1096. Brace Expansion II/1096.java | 44 ++ solutions/1096. Brace Expansion II/1096.py | 33 ++ solutions/1097. Game Play Analysis V/1097.sql | 18 + solutions/1098. Unpopular Books/1098.sql | 11 + solutions/1099. Two Sum Less Than K/1099.cpp | 23 + solutions/1099. Two Sum Less Than K/1099.java | 22 + solutions/1099. Two Sum Less Than K/1099.py | 19 + .../11. Container With Most Water/11.cpp | 19 + .../11. Container With Most Water/11.java | 18 + solutions/11. Container With Most Water/11.py | 15 + solutions/110. Balanced Binary Tree/110-2.cpp | 19 + .../110. Balanced Binary Tree/110-2.java | 19 + solutions/110. Balanced Binary Tree/110-2.py | 17 + solutions/110. Balanced Binary Tree/110-3.cpp | 24 + .../110. Balanced Binary Tree/110-3.java | 22 + solutions/110. Balanced Binary Tree/110-3.py | 19 + solutions/110. Balanced Binary Tree/110.cpp | 16 + solutions/110. Balanced Binary Tree/110.java | 15 + solutions/110. Balanced Binary Tree/110.py | 12 + .../1100.cpp | 19 + .../1100.java | 18 + .../1100.py | 18 + .../1101.cpp | 58 ++ .../1101.java | 57 ++ .../1101.py | 42 ++ .../1102.cpp | 41 ++ .../1102.java | 44 ++ .../1103.cpp | 22 + .../1103.java | 23 + .../1103.py | 22 + .../1104.cpp | 28 + .../1104.java | 26 + .../1104.py | 20 + .../1105. Filling Bookcase Shelves/1105.cpp | 25 + .../1105. Filling Bookcase Shelves/1105.java | 26 + .../1105. Filling Bookcase Shelves/1105.py | 18 + .../1106.cpp | 40 ++ .../1106.java | 45 ++ .../1106.py | 33 ++ .../1107. New Users Daily Count/1107.sql | 15 + .../1108. Defanging an IP Address/1108.cpp | 6 + .../1108. Defanging an IP Address/1108.java | 5 + .../1108. Defanging an IP Address/1108.py | 3 + .../1109. Corporate Flight Bookings/1109.cpp | 17 + .../1109. Corporate Flight Bookings/1109.java | 16 + .../1109. Corporate Flight Bookings/1109.py | 13 + .../111-2.cpp | 26 + .../111-2.java | 24 + .../111-2.py | 18 + .../111. Minimum Depth of Binary Tree/111.cpp | 12 + .../111.java | 11 + .../111. Minimum Depth of Binary Tree/111.py | 9 + .../1110.cpp | 24 + .../1110.java | 23 + .../1110.py | 20 + .../1111.cpp | 17 + .../1111.java | 16 + .../1111.py | 15 + .../1112.sql | 18 + solutions/1113. Reported Posts/1113.sql | 8 + solutions/1114. Print in Order/1114.cpp | 27 + solutions/1114. Print in Order/1114.java | 22 + solutions/1114. Print in Order/1114.py | 22 + .../1115. Print FooBar Alternately/1115.cpp | 37 ++ .../1115. Print FooBar Alternately/1115.java | 25 + .../1115. Print FooBar Alternately/1115.py | 20 + solutions/1116. Print Zero Even Odd/1116.cpp | 49 ++ solutions/1116. Print Zero Even Odd/1116.java | 35 ++ solutions/1116. Print Zero Even Odd/1116.py | 28 + solutions/1117. Building H2O/1117.cpp | 39 ++ .../1118. Number of Days in a Month/1118.cpp | 13 + .../1118. Number of Days in a Month/1118.java | 10 + .../1118. Number of Days in a Month/1118.py | 6 + .../1119.cpp | 14 + .../1119.java | 5 + .../1119. Remove Vowels from a String/1119.py | 3 + solutions/112. Path Sum/112.cpp | 11 + solutions/112. Path Sum/112.java | 11 + solutions/112. Path Sum/112.py | 8 + .../1120. Maximum Average Subtree/1120.cpp | 27 + .../1120. Maximum Average Subtree/1120.java | 30 + .../1120. Maximum Average Subtree/1120.py | 22 + .../1121.cpp | 19 + .../1121.java | 18 + .../1121.py | 7 + solutions/1122. Relative Sort Array/1122.cpp | 20 + solutions/1122. Relative Sort Array/1122.java | 20 + solutions/1122. Relative Sort Array/1122.py | 18 + .../1123.cpp | 24 + .../1123.java | 26 + .../1124.cpp | 22 + .../1124.py | 17 + .../1125. Smallest Sufficient Team/1125.cpp | 40 ++ .../1125. Smallest Sufficient Team/1125.java | 38 ++ solutions/1126. Active Businesses/1126.sql | 12 + .../1127. User Purchase Platform/1127.sql | 32 ++ .../1128.cpp | 15 + .../1128.java | 14 + .../1128.py | 11 + .../1129.cpp | 38 ++ .../1129.java | 46 ++ .../1129.py | 35 ++ solutions/113. Path Sum II/113.cpp | 26 + solutions/113. Path Sum II/113.java | 23 + solutions/113. Path Sum II/113.py | 16 + .../1130-2.cpp | 23 + .../1130-2.java | 22 + .../1130-2.py | 14 + .../1130-3.py | 9 + .../1130.cpp | 30 + .../1130.java | 28 + .../1130.py | 25 + .../1131.cpp | 24 + .../1131.java | 24 + .../1131.py | 8 + solutions/1132. Reported Posts II/1132.sql | 13 + .../1133. Largest Unique Number/1133.cpp | 16 + .../1133. Largest Unique Number/1133.java | 15 + solutions/1133. Largest Unique Number/1133.py | 4 + solutions/1134. Armstrong Number/1134.cpp | 10 + solutions/1134. Armstrong Number/1134.java | 9 + solutions/1134. Armstrong Number/1134.py | 5 + .../1135.cpp | 59 ++ .../1135.java | 57 ++ .../1135.py | 43 ++ solutions/1136. Parallel Courses/1136-2.cpp | 36 ++ solutions/1136. Parallel Courses/1136-2.java | 37 ++ solutions/1136. Parallel Courses/1136-2.py | 25 + solutions/1136. Parallel Courses/1136.cpp | 41 ++ solutions/1136. Parallel Courses/1136.java | 42 ++ solutions/1136. Parallel Courses/1136.py | 36 ++ .../1137. N-th Tribonacci Number/1137-2.cpp | 11 + .../1137. N-th Tribonacci Number/1137-2.java | 10 + .../1137. N-th Tribonacci Number/1137-2.py | 8 + .../1137. N-th Tribonacci Number/1137.cpp | 18 + .../1137. N-th Tribonacci Number/1137.java | 17 + .../1137. N-th Tribonacci Number/1137.py | 11 + solutions/1138. Alphabet Board Path/1138.cpp | 20 + .../1139. Largest 1-Bordered Square/1139.cpp | 32 ++ .../1139. Largest 1-Bordered Square/1139.java | 31 ++ .../1139. Largest 1-Bordered Square/1139.py | 26 + .../114-2.cpp | 20 + .../114-2.java | 20 + .../114-2.py | 16 + .../114-3.cpp | 22 + .../114-3.java | 21 + .../114-3.py | 17 + .../114.cpp | 22 + .../114.java | 21 + .../114.py | 19 + solutions/1140. Stone Game II/1140.cpp | 28 + solutions/1140. Stone Game II/1140.java | 27 + .../1141.sql | 6 + .../1142.sql | 10 + .../1143. Longest Common Subsequence/1143.cpp | 17 + .../1143.java | 16 + .../1143. Longest Common Subsequence/1143.py | 14 + .../1144.cpp | 14 + .../1144.java | 13 + .../1144.py | 10 + .../1145. Binary Tree Coloring Game/1145.cpp | 23 + .../1145. Binary Tree Coloring Game/1145.java | 21 + solutions/1146. Snapshot Array/1146.cpp | 30 + solutions/1146. Snapshot Array/1146.java | 32 ++ solutions/1146. Snapshot Array/1146.py | 19 + .../1147.cpp | 15 + .../1147.java | 16 + solutions/1148. Article Views I/1148.sql | 4 + solutions/1149. Article Views II/1149.sql | 5 + .../115. Distinct Subsequences/115-2.cpp | 16 + .../115. Distinct Subsequences/115-2.java | 15 + solutions/115. Distinct Subsequences/115-2.py | 12 + solutions/115. Distinct Subsequences/115.cpp | 20 + solutions/115. Distinct Subsequences/115.java | 19 + solutions/115. Distinct Subsequences/115.py | 17 + .../1150.cpp | 8 + .../1150.java | 20 + .../1150.py | 5 + .../1151.cpp | 18 + .../1151.java | 17 + .../1151.py | 14 + .../1152.py | 15 + .../1153.cpp | 21 + .../1153.java | 20 + .../1153.py | 15 + solutions/1154. Day of the Year/1154.cpp | 17 + solutions/1154. Day of the Year/1154.java | 18 + solutions/1154. Day of the Year/1154.py | 12 + .../1155.cpp | 20 + .../1155.java | 19 + .../1155.py | 14 + .../1156.cpp | 27 + .../1156.java | 28 + .../1156.py | 13 + .../1157.cpp | 26 + .../1157.java | 34 ++ .../1157.py | 20 + solutions/1158. Market Analysis I/1158.sql | 8 + solutions/1159. Market Analysis II/1159.sql | 22 + .../116-2.cpp | 20 + .../116-2.java | 19 + .../116-2.py | 17 + .../116.cpp | 19 + .../116.java | 17 + .../116.py | 15 + .../1160.cpp | 22 + .../1160.java | 21 + .../1160.py | 15 + .../1161-2.cpp | 20 + .../1161-2.java | 19 + .../1161-2.py | 16 + .../1161.cpp | 27 + .../1161.java | 25 + .../1161.py | 22 + .../1162.cpp | 41 ++ .../1162.java | 41 ++ .../1162.py | 37 ++ .../1163.cpp | 27 + .../1163.java | 26 + .../1163.py | 22 + .../1164.sql | 24 + solutions/1165. Single-Row Keyboard/1165.cpp | 19 + solutions/1165. Single-Row Keyboard/1165.java | 18 + solutions/1165. Single-Row Keyboard/1165.py | 6 + solutions/1166. Design File System/1166.cpp | 51 ++ solutions/1166. Design File System/1166.java | 41 ++ solutions/1166. Design File System/1166.py | 33 ++ .../1167.cpp | 21 + .../1167.java | 18 + .../1167.py | 12 + .../1168.cpp | 42 ++ .../1168.java | 47 ++ .../1168.py | 30 + solutions/1169. Invalid Transactions/1169.cpp | 47 ++ .../1169. Invalid Transactions/1169.java | 47 ++ solutions/1169. Invalid Transactions/1169.py | 22 + .../117.cpp | 24 + .../117.java | 23 + .../117.py | 19 + .../1170.cpp | 35 ++ .../1170.java | 43 ++ .../1170.py | 11 + .../1171.cpp | 23 + .../1171.java | 22 + .../1171.py | 20 + solutions/1172. Dinner Plate Stacks/1172.cpp | 48 ++ solutions/1172. Dinner Plate Stacks/1172.java | 44 ++ solutions/1172. Dinner Plate Stacks/1172.py | 35 ++ .../1173. Immediate Food Delivery I/1173.sql | 6 + .../1174. Immediate Food Delivery II/1174.sql | 12 + solutions/1175. Prime Arrangements/1175.cpp | 29 + solutions/1175. Prime Arrangements/1175.java | 32 ++ solutions/1175. Prime Arrangements/1175.py | 24 + .../1176. Diet Plan Performance/1176.cpp | 21 + .../1176. Diet Plan Performance/1176.java | 20 + solutions/1176. Diet Plan Performance/1176.py | 17 + .../1177.cpp | 17 + .../1177.java | 16 + .../1177.py | 11 + .../1178.cpp | 31 ++ .../1178.java | 29 + .../1178.py | 24 + .../1179. Reformat Department Table/1179.sql | 16 + solutions/118. Pascal's Triangle/118.cpp | 15 + solutions/118. Pascal's Triangle/118.java | 17 + solutions/118. Pascal's Triangle/118.py | 12 + .../1180.cpp | 21 + .../1180.java | 20 + .../1180.py | 15 + .../1181. Before and After Puzzle/1181.cpp | 42 ++ .../1182.cpp | 38 ++ .../1182.java | 36 ++ .../1182.py | 29 + .../1183. Maximum Number of Ones/1183-2.cpp | 17 + .../1183. Maximum Number of Ones/1183-2.java | 21 + .../1183. Maximum Number of Ones/1183-2.py | 12 + .../1183. Maximum Number of Ones/1183.cpp | 21 + .../1183. Maximum Number of Ones/1183.java | 20 + .../1183. Maximum Number of Ones/1183.py | 9 + .../1184. Distance Between Bus Stops/1184.cpp | 20 + .../1184.java | 21 + .../1184. Distance Between Bus Stops/1184.py | 15 + solutions/1185. Day of the Week/1185.cpp | 23 + solutions/1185. Day of the Week/1185.java | 19 + solutions/1185. Day of the Week/1185.py | 18 + .../1186-2.cpp | 18 + .../1186-2.java | 17 + .../1186-2.py | 13 + .../1186.cpp | 19 + .../1186.java | 17 + .../1186.py | 14 + .../1187.cpp | 30 + .../1187.java | 33 ++ .../1187.py | 22 + .../1188.cpp | 39 ++ .../1188.java | 26 + .../1188.py | 22 + .../1189. Maximum Number of Balloons/1189.cpp | 18 + .../1189.java | 17 + .../1189. Maximum Number of Balloons/1189.py | 4 + solutions/119. Pascal's Triangle II/119.cpp | 12 + solutions/119. Pascal's Triangle II/119.java | 12 + solutions/119. Pascal's Triangle II/119.py | 9 + .../1190-2.cpp | 28 + .../1190-2.java | 26 + .../1190-2.py | 25 + .../1190.cpp | 21 + .../1190.java | 23 + .../1190.py | 16 + .../1191.cpp | 26 + .../1191.java | 24 + .../1191. K-Concatenation Maximum Sum/1191.py | 20 + .../1192.cpp | 47 ++ .../1192.java | 49 ++ .../1193. Monthly Transactions I/1193.sql | 9 + solutions/1194. Tournament Winners/1194.sql | 37 ++ .../1195. Fizz Buzz Multithreaded/1195.cpp | 74 +++ .../1195. Fizz Buzz Multithreaded/1195.java | 58 ++ .../1195. Fizz Buzz Multithreaded/1195.py | 48 ++ .../1196.cpp | 16 + .../1196.java | 15 + .../1196.py | 10 + solutions/1197. Minimum Knight Moves/1197.cpp | 27 + .../1197. Minimum Knight Moves/1197.java | 23 + .../1198.cpp | 14 + .../1198.java | 13 + .../1198.py | 12 + .../1199.cpp | 18 + .../1199.java | 16 + .../1199.py | 11 + solutions/12. Integer to Roman/12-2.cpp | 14 + solutions/12. Integer to Roman/12-2.java | 9 + solutions/12. Integer to Roman/12-2.py | 7 + solutions/12. Integer to Roman/12.cpp | 21 + solutions/12. Integer to Roman/12.java | 19 + solutions/12. Integer to Roman/12.py | 18 + solutions/120. Triangle/120.cpp | 9 + solutions/120. Triangle/120.java | 9 + solutions/120. Triangle/120.py | 8 + .../1200.cpp | 21 + .../1200.java | 20 + .../1200. Minimum Absolute Difference/1200.py | 16 + solutions/1201. Ugly Number III/1201.cpp | 21 + solutions/1201. Ugly Number III/1201.java | 24 + solutions/1201. Ugly Number III/1201.py | 9 + .../1202. Smallest String With Swaps/1202.cpp | 49 ++ .../1202.java | 49 ++ .../1202. Smallest String With Swaps/1202.py | 43 ++ .../1203.cpp | 51 ++ .../1203.java | 50 ++ .../1204.sql | 12 + .../1205. Monthly Transactions II/1205.sql | 30 + solutions/1206. Design Skiplist/1206.cpp | 63 +++ solutions/1206. Design Skiplist/1206.java | 63 +++ solutions/1206. Design Skiplist/1206.py | 63 +++ .../1207.cpp | 16 + .../1207.java | 15 + .../1207.py | 11 + .../1208.cpp | 13 + .../1208.java | 12 + .../1208.py | 10 + .../1209.cpp | 18 + .../1209.java | 33 ++ .../1209.py | 13 + .../121.cpp | 14 + .../121.java | 13 + .../121.py | 10 + .../1210.cpp | 65 +++ .../1210.java | 63 +++ .../1210.py | 54 ++ .../1211.sql | 6 + .../1212.sql | 29 + .../1213.cpp | 28 + .../1213.java | 26 + solutions/1214. Two Sum BSTs/1214.cpp | 51 ++ solutions/1214. Two Sum BSTs/1214.java | 48 ++ solutions/1214. Two Sum BSTs/1214.py | 42 ++ solutions/1215. Stepping Numbers/1215-2.cpp | 28 + solutions/1215. Stepping Numbers/1215-2.java | 26 + solutions/1215. Stepping Numbers/1215-2.py | 21 + solutions/1215. Stepping Numbers/1215.cpp | 29 + solutions/1215. Stepping Numbers/1215.java | 27 + solutions/1215. Stepping Numbers/1215.py | 18 + solutions/1216. Valid Palindrome III/1216.cpp | 28 + .../1216. Valid Palindrome III/1216.java | 26 + solutions/1216. Valid Palindrome III/1216.py | 22 + solutions/1217. Play with Chips/1217.cpp | 9 + solutions/1217. Play with Chips/1217.java | 8 + solutions/1217. Play with Chips/1217.py | 6 + .../1218.cpp | 17 + .../1218.java | 13 + .../1218.py | 10 + .../1219. Path with Maximum Gold/1219.cpp | 27 + .../1219. Path with Maximum Gold/1219.java | 25 + .../1219. Path with Maximum Gold/1219.py | 18 + .../122.cpp | 14 + .../122.java | 13 + .../122.py | 10 + .../1220. Count Vowels Permutation/1220.py | 14 + .../1221.cpp | 15 + .../1222.cpp | 28 + .../1222.java | 25 + .../1222.py | 16 + solutions/1223. Dice Roll Simulation/1223.py | 27 + .../1224. Maximum Equal Frequency/1224.cpp | 22 + .../1224. Maximum Equal Frequency/1224.java | 22 + .../1224. Maximum Equal Frequency/1224.py | 16 + .../1225. Report Contiguous Dates/1225.sql | 31 ++ .../1226. The Dining Philosophers/1226.cpp | 16 + .../1227.cpp | 6 + .../1227.java | 5 + .../1227.py | 3 + .../1228.cpp | 19 + .../1228.java | 18 + .../1228.py | 15 + solutions/1229. Meeting Scheduler/1229.cpp | 24 + solutions/1229. Meeting Scheduler/1229.java | 22 + solutions/1229. Meeting Scheduler/1229.py | 19 + .../123.cpp | 18 + .../123.java | 17 + .../123.py | 14 + solutions/1230. Toss Strange Coins/1230-2.cpp | 14 + .../1230. Toss Strange Coins/1230-2.java | 13 + solutions/1230. Toss Strange Coins/1230-2.py | 10 + solutions/1230. Toss Strange Coins/1230.cpp | 15 + solutions/1230. Toss Strange Coins/1230.java | 13 + solutions/1230. Toss Strange Coins/1230.py | 12 + solutions/1231. Divide Chocolate/1231.cpp | 35 ++ solutions/1231. Divide Chocolate/1231.java | 33 ++ solutions/1231. Divide Chocolate/1231.py | 26 + .../1232.cpp | 20 + .../1232.java | 19 + .../1232.py | 7 + .../1233.cpp | 18 + .../1233.java | 17 + .../1233.py | 14 + .../1234.cpp | 24 + .../1234.java | 22 + .../1234.py | 14 + .../1235-2.cpp | 41 ++ .../1235-2.java | 49 ++ .../1235-2.py | 14 + .../1235-3.cpp | 44 ++ .../1235-3.java | 45 ++ .../1235-3.py | 16 + .../1235.cpp | 49 ++ .../1235.java | 54 ++ .../1235.py | 17 + solutions/1236. Web Crawler/1236.cpp | 39 ++ solutions/1236. Web Crawler/1236.java | 29 + solutions/1236. Web Crawler/1236.py | 23 + .../1237.cpp | 20 + .../1237.java | 19 + .../1237.py | 18 + .../1238.cpp | 11 + .../1238.java | 10 + .../1238.py | 3 + .../1239-2.cpp | 30 + .../1239-3.cpp | 37 ++ .../1239.cpp | 34 ++ .../124. Binary Tree Maximum Path Sum/124.cpp | 21 + .../124.java | 20 + .../124. Binary Tree Maximum Path Sum/124.py | 20 + .../1240.cpp | 45 ++ .../1240.java | 49 ++ .../1240.py | 24 + .../1241.sql | 13 + .../1242. Web Crawler Multithreaded/1242.cpp | 60 ++ solutions/1243. Array Transformation/1243.cpp | 21 + .../1243. Array Transformation/1243.java | 19 + solutions/1243. Array Transformation/1243.py | 16 + solutions/1244. Design A Leaderboard/1244.cpp | 29 + .../1244. Design A Leaderboard/1244.java | 27 + solutions/1244. Design A Leaderboard/1244.py | 12 + solutions/1245. Tree Diameter/1245.cpp | 39 ++ solutions/1245. Tree Diameter/1245.java | 41 ++ solutions/1246. Palindrome Removal/1246.cpp | 29 + solutions/1246. Palindrome Removal/1246.java | 28 + solutions/1246. Palindrome Removal/1246.py | 24 + .../1247.cpp | 23 + .../1247.java | 22 + .../1247.py | 19 + .../1248.cpp | 28 + .../1248.java | 25 + .../1248.py | 22 + .../1249.cpp | 23 + .../1249.java | 22 + .../1249.py | 19 + solutions/125. Valid Palindrome/125.cpp | 20 + solutions/125. Valid Palindrome/125.java | 19 + solutions/125. Valid Palindrome/125.py | 16 + .../1250.cpp | 11 + .../1251. Average Selling Price/1251.sql | 15 + .../1252-2.cpp | 21 + .../1252-2.java | 29 + .../1252-2.py | 17 + .../1252-3.cpp | 19 + .../1252.cpp | 21 + .../1252.java | 21 + .../1252.py | 14 + .../1253.cpp | 36 ++ .../1253.java | 39 ++ .../1253.py | 26 + .../1254. Number of Closed Islands/1254.cpp | 40 ++ .../1254. Number of Closed Islands/1254.java | 38 ++ .../1254. Number of Closed Islands/1254.py | 34 ++ .../1255.cpp | 41 ++ .../1255.java | 36 ++ .../1255.py | 29 + solutions/1256. Encode Number/1256.cpp | 8 + solutions/1256. Encode Number/1256.java | 5 + solutions/1256. Encode Number/1256.py | 3 + .../1257. Smallest Common Region/1257.cpp | 24 + .../1257. Smallest Common Region/1257.java | 22 + solutions/1258. Synonymous Sentences/1258.cpp | 56 ++ .../1258. Synonymous Sentences/1258.java | 32 ++ solutions/1258. Synonymous Sentences/1258.py | 26 + .../1259.cpp | 18 + .../1259.java | 17 + .../1259. Handshakes That Don't Cross/1259.py | 13 + solutions/126. Word Ladder II/126-2.cpp | 106 ++++ solutions/126. Word Ladder II/126-3.cpp | 38 ++ solutions/126. Word Ladder II/126-4.cpp | 90 +++ solutions/126. Word Ladder II/126-5.cpp | 81 +++ solutions/126. Word Ladder II/126.cpp | 85 +++ solutions/126. Word Ladder II/126.java | 84 +++ solutions/126. Word Ladder II/126.py | 63 +++ solutions/126. Word Ladder II/127-2.py | 75 +++ solutions/1260. Shift 2D Grid/1260.cpp | 20 + solutions/1260. Shift 2D Grid/1260.java | 23 + solutions/1260. Shift 2D Grid/1260.py | 16 + .../1261.cpp | 23 + .../1261.java | 21 + .../1261.py | 16 + .../1262.cpp | 12 + .../1262.java | 11 + .../1263.cpp | 93 ++++ .../1263.java | 91 +++ .../1263.py | 69 +++ solutions/1264. Page Recommendations/1264.sql | 19 + .../1265-2.cpp | 24 + .../1265.cpp | 20 + .../1266.cpp | 12 + .../1266.java | 11 + .../1266.py | 9 + .../1267.cpp | 24 + .../1267.java | 23 + .../1267.py | 20 + .../1268. Search Suggestions System/1268.cpp | 61 +++ .../1268. Search Suggestions System/1268.java | 57 ++ .../1268. Search Suggestions System/1268.py | 47 ++ .../1269.cpp | 25 + .../1269.java | 24 + .../1269.py | 19 + solutions/127. Word Ladder/127.cpp | 34 ++ solutions/127. Word Ladder/127.java | 33 ++ solutions/127. Word Ladder/127.py | 25 + .../1270.sql | 9 + solutions/1271. Hexspeak/1271.cpp | 20 + solutions/1271. Hexspeak/1271.java | 7 + solutions/1271. Hexspeak/1271.py | 4 + solutions/1272. Remove Interval/1272.cpp | 22 + solutions/1272. Remove Interval/1272.java | 20 + solutions/1272. Remove Interval/1272.py | 14 + solutions/1273. Delete Tree Nodes/1273.cpp | 32 ++ solutions/1273. Delete Tree Nodes/1273.java | 37 ++ .../1274.cpp | 35 ++ .../1274.java | 33 ++ .../1274.py | 38 ++ .../1275.cpp | 20 + .../1275.java | 19 + .../1275.py | 18 + .../1276.cpp | 12 + .../1276.java | 10 + .../1276.py | 8 + .../1277.cpp | 14 + .../1277.java | 10 + .../1277.py | 8 + .../1278-2.cpp | 24 + .../1278-2.java | 24 + .../1278.cpp | 32 ++ .../1278.java | 31 ++ .../1279.cpp | 27 + .../1279.java | 23 + .../1279.py | 21 + .../128. Longest Consecutive Sequence/128.cpp | 19 + .../128.java | 18 + .../128. Longest Consecutive Sequence/128.py | 16 + .../1280. Students and Examinations/1280.sql | 13 + .../1281.cpp | 14 + .../1281.java | 13 + .../1281.py | 11 + .../1282.cpp | 23 + .../1282.java | 27 + .../1282.py | 17 + .../1283.cpp | 25 + .../1283.java | 23 + .../1283.py | 13 + .../1284.cpp | 52 ++ .../1284.java | 49 ++ .../1284.py | 43 ++ .../1285.sql | 12 + .../1286. Iterator for Combination/1286.java | 33 ++ .../1287.cpp | 13 + .../1287.java | 12 + .../1287.py | 8 + .../1288. Remove Covered Intervals/1288.cpp | 22 + .../1288. Remove Covered Intervals/1288.java | 19 + .../1288. Remove Covered Intervals/1288.py | 14 + .../1289.cpp | 31 ++ .../1289.java | 29 + .../1289. Minimum Falling Path Sum II/1289.py | 14 + .../129. Sum Root to Leaf Numbers/129.cpp | 21 + .../129. Sum Root to Leaf Numbers/129.java | 20 + .../129. Sum Root to Leaf Numbers/129.py | 17 + .../1290.cpp | 11 + .../1290.java | 10 + .../1290.py | 9 + solutions/1291. Sequential Digits/1291.cpp | 21 + solutions/1291. Sequential Digits/1291.java | 19 + solutions/1291. Sequential Digits/1291.py | 16 + .../1292.cpp | 30 + .../1292.java | 26 + .../1292.py | 23 + .../1293.cpp | 41 ++ .../1293.java | 52 ++ .../1293.py | 32 ++ .../1294.sql | 14 + .../1295.cpp | 12 + .../1295.java | 11 + .../1295.py | 9 + .../1296.cpp | 21 + .../1296.java | 18 + .../1296.py | 13 + .../1297.cpp | 22 + .../1297.java | 21 + .../1297.py | 24 + .../1298.cpp | 42 ++ .../1298.java | 39 ++ .../1298.py | 32 ++ .../1299.cpp | 9 + .../1299.java | 11 + .../1299.py | 6 + solutions/13. Roman to Integer/13.cpp | 23 + solutions/13. Roman to Integer/13.java | 22 + solutions/13. Roman to Integer/13.py | 13 + solutions/130. Surrounded Regions/130-2.cpp | 36 ++ solutions/130. Surrounded Regions/130-2.java | 34 ++ solutions/130. Surrounded Regions/130-2.py | 28 + solutions/130. Surrounded Regions/130.cpp | 44 ++ solutions/130. Surrounded Regions/130.java | 42 ++ solutions/130. Surrounded Regions/130.py | 33 ++ .../1300.cpp | 20 + .../1300.java | 19 + .../1300.py | 13 + .../1301.cpp | 41 ++ .../1301.java | 40 ++ .../1301.py | 35 ++ solutions/1302. Deepest Leaves Sum/1302.cpp | 22 + solutions/1302. Deepest Leaves Sum/1302.java | 20 + solutions/1303. Find the Team Size/1303.sql | 4 + .../1304.cpp | 11 + .../1304.java | 10 + .../1304.py | 3 + .../1305.cpp | 60 ++ .../1305.java | 55 ++ solutions/1306. Jump Game III/1306-2.cpp | 20 + solutions/1306. Jump Game III/1306-2.java | 17 + solutions/1306. Jump Game III/1306.cpp | 28 + solutions/1306. Jump Game III/1306.java | 26 + .../1307. Verbal Arithmetic Puzzle/1307.cpp | 48 ++ .../1307. Verbal Arithmetic Puzzle/1307.java | 44 ++ .../1307. Verbal Arithmetic Puzzle/1307.py | 37 ++ .../1308.sql | 9 + .../1309.cpp | 18 + .../1309.java | 17 + .../1309.py | 14 + .../131. Palindrome Partitioning/131.cpp | 31 ++ .../131. Palindrome Partitioning/131.java | 28 + solutions/131. Palindrome Partitioning/131.py | 18 + .../1310. XOR Queries of a Subarray/1310.cpp | 18 + .../1310. XOR Queries of a Subarray/1310.java | 18 + .../1310. XOR Queries of a Subarray/1310.py | 12 + .../1311.cpp | 37 ++ .../1311.java | 29 + .../1311.py | 21 + .../1312.cpp | 28 + .../1312.java | 26 + .../1312.py | 22 + .../1313.cpp | 11 + .../1313.java | 11 + .../1313.py | 8 + solutions/1314. Matrix Block Sum/1314.cpp | 26 + solutions/1314. Matrix Block Sum/1314.java | 24 + solutions/1314. Matrix Block Sum/1314.py | 22 + .../1315.cpp | 15 + .../1315.java | 13 + .../1316. Distinct Echo Substrings/1316.cpp | 24 + .../1316. Distinct Echo Substrings/1316.java | 23 + .../1316. Distinct Echo Substrings/1316.py | 20 + .../1317.cpp | 13 + .../1317.java | 11 + .../1317.py | 6 + .../1318.cpp | 15 + .../1318.java | 14 + .../1318.py | 12 + .../1319.cpp | 34 ++ .../1319.java | 35 ++ .../132. Palindrome Partitioning II/132.cpp | 28 + .../132. Palindrome Partitioning II/132.java | 30 + .../132. Palindrome Partitioning II/132.py | 25 + .../1320.cpp | 34 ++ .../1320.java | 30 + .../1320.py | 24 + solutions/1321. Restaurant Growth/1321.sql | 17 + solutions/1322. Ads Performance/1322.sql | 12 + solutions/1323. Maximum 69 Number/1323.cpp | 14 + solutions/1323. Maximum 69 Number/1323.java | 13 + solutions/1323. Maximum 69 Number/1323.py | 3 + .../1324. Print Words Vertically/1324.cpp | 31 ++ .../1324. Print Words Vertically/1324.java | 21 + .../1324. Print Words Vertically/1324.py | 13 + .../1325.cpp | 15 + .../1325.java | 13 + .../1325.py | 10 + .../1326.cpp | 26 + .../1326.java | 25 + .../1326.py | 20 + .../1327.sql | 9 + solutions/1328. Break a Palindrome/1328.cpp | 16 + solutions/1328. Break a Palindrome/1328.java | 17 + solutions/1328. Break a Palindrome/1328.py | 14 + .../1329. Sort the Matrix Diagonally/1329.cpp | 19 + .../1329.java | 18 + .../1329. Sort the Matrix Diagonally/1329.py | 19 + solutions/133. Clone Graph/133-2.cpp | 20 + solutions/133. Clone Graph/133-2.java | 18 + solutions/133. Clone Graph/133-2.py | 16 + solutions/133. Clone Graph/133.cpp | 24 + solutions/133. Clone Graph/133.java | 23 + solutions/133. Clone Graph/133.py | 17 + .../1330.cpp | 27 + .../1330.java | 26 + .../1330.py | 16 + .../1331. Rank Transform of an Array/1331.cpp | 18 + .../1331.java | 16 + .../1331. Rank Transform of an Array/1331.py | 9 + .../1332.cpp | 6 + .../1332.java | 5 + .../1332.py | 3 + .../1333.cpp | 23 + .../1333.java | 10 + .../1333.py | 4 + .../1334.cpp | 45 ++ .../1334.java | 43 ++ .../1334.py | 30 + .../1335.cpp | 23 + .../1335.java | 24 + .../1335.py | 18 + .../1336.sql | 30 + .../1337.cpp | 19 + .../1337.java | 18 + .../1337.py | 10 + .../1338.cpp | 27 + .../1338.java | 28 + .../1338.py | 12 + .../1339.cpp | 26 + .../1339.java | 24 + solutions/134. Gas Station/134.cpp | 23 + solutions/134. Gas Station/134.java | 22 + solutions/134. Gas Station/134.py | 15 + solutions/1340. Jump Game V/1340.cpp | 30 + solutions/1340. Jump Game V/1340.java | 28 + solutions/1340. Jump Game V/1340.py | 23 + solutions/1341. Movie Rating/1341.sql | 20 + .../1342.cpp | 10 + .../1342.java | 9 + .../1342.py | 7 + .../1343.cpp | 17 + .../1343.java | 16 + .../1343.py | 13 + .../1344.cpp | 9 + .../1344.java | 8 + .../1344.py | 7 + solutions/1345. Jump Game IV/1345.cpp | 37 ++ solutions/1345. Jump Game IV/1345.java | 37 ++ solutions/1345. Jump Game IV/1345.py | 29 + .../1346.cpp | 14 + .../1346.java | 13 + .../1346.py | 10 + .../1347.cpp | 16 + .../1347.java | 13 + .../1347.py | 5 + .../1348. Tweet Counts Per Frequency/1348.cpp | 25 + .../1348.java | 22 + .../1348. Tweet Counts Per Frequency/1348.py | 21 + .../1349.cpp | 55 ++ .../1349.java | 57 ++ .../1349.py | 36 ++ solutions/135. Candy/135.cpp | 22 + solutions/135. Candy/135.java | 24 + solutions/135. Candy/135.py | 20 + .../1350.sql | 7 + .../1351.cpp | 21 + .../1351.java | 20 + .../1351.py | 16 + .../1352.cpp | 19 + .../1352.java | 19 + .../1352.py | 12 + .../1353.cpp | 31 ++ .../1353.java | 30 + .../1353.py | 27 + .../1354.cpp | 30 + .../1354.java | 28 + .../1354.py | 23 + .../1355. Activity Participants/1355.sql | 12 + .../1356.cpp | 11 + .../1356.java | 11 + .../1357.cpp | 22 + .../1357.java | 21 + .../1357.py | 14 + .../1358-2.cpp | 17 + .../1358-2.java | 16 + .../1358-2.py | 13 + .../1358.cpp | 19 + .../1358.java | 18 + .../1358.py | 16 + .../1359.cpp | 12 + .../1359.java | 11 + .../1359.py | 9 + solutions/136. Single Number/136.cpp | 11 + solutions/136. Single Number/136.java | 10 + solutions/136. Single Number/136.py | 3 + .../1360.cpp | 28 + .../1360.java | 25 + .../1360.py | 13 + .../1361. Validate Binary Tree Nodes/1361.cpp | 41 ++ .../1361.java | 37 ++ solutions/1362. Closest Divisors/1362.cpp | 11 + solutions/1362. Closest Divisors/1362.java | 10 + solutions/1362. Closest Divisors/1362.py | 6 + .../1363. Largest Multiple of Three/1363.cpp | 26 + .../1363. Largest Multiple of Three/1363.java | 27 + .../1363. Largest Multiple of Three/1363.py | 19 + .../1364.sql | 15 + .../1365.cpp | 19 + .../1365.java | 18 + .../1365.py | 10 + solutions/1366. Rank Teams by Votes/1366.cpp | 30 + solutions/1366. Rank Teams by Votes/1366.java | 40 ++ solutions/1366. Rank Teams by Votes/1366.py | 17 + .../1367. Linked List in Binary Tree/1367.cpp | 20 + .../1367.java | 17 + .../1367. Linked List in Binary Tree/1367.py | 16 + .../1368.cpp | 37 ++ .../1368.java | 37 ++ .../1368.py | 30 + .../1369.sql | 18 + solutions/137. Single Number II/137-2.cpp | 14 + solutions/137. Single Number II/137-2.java | 13 + solutions/137. Single Number II/137-2.py | 10 + solutions/137. Single Number II/137.cpp | 16 + solutions/137. Single Number II/137.java | 15 + solutions/137. Single Number II/137.py | 10 + .../1370.cpp | 27 + .../1370.java | 26 + .../1370.py | 11 + .../1371.cpp | 20 + .../1371.java | 19 + .../1371.py | 15 + .../1372.cpp | 25 + .../1372.java | 29 + .../1372.py | 21 + .../1373.cpp | 37 ++ .../1373.java | 45 ++ .../1373.py | 34 ++ .../1374.cpp | 9 + .../1374.java | 10 + .../1374.py | 6 + .../1375.cpp | 17 + .../1375.java | 16 + .../1375.py | 13 + .../1376.cpp | 25 + .../1376.java | 22 + .../1377.cpp | 38 ++ .../1377.java | 41 ++ .../1377.py | 28 + .../1378.sql | 6 + .../1379.cpp | 24 + .../1379.java | 22 + .../1379.py | 19 + .../138.cpp | 18 + .../138.java | 16 + .../138. Copy List with Random Pointer/138.py | 14 + .../1380. Lucky Numbers in a Matrix/1380.cpp | 19 + .../1380. Lucky Numbers in a Matrix/1380.java | 25 + .../1380. Lucky Numbers in a Matrix/1380.py | 7 + .../1381.cpp | 36 ++ .../1381.java | 35 ++ .../1381.py | 25 + .../1382.cpp | 25 + .../1382.java | 23 + .../1382.py | 23 + .../1383.cpp | 28 + .../1383.java | 28 + .../1383.py | 18 + .../1384. Total Sales Amount by Year/1384.sql | 26 + .../1385-2.cpp | 14 + .../1385.cpp | 17 + .../1385.java | 16 + .../1385.py | 12 + .../1386. Cinema Seat Allocation/1386.cpp | 26 + .../1386. Cinema Seat Allocation/1386.java | 25 + .../1386. Cinema Seat Allocation/1386.py | 20 + .../1387.cpp | 20 + .../1387.java | 17 + .../1387.py | 10 + solutions/1388. Pizza With 3n Slices/1388.py | 24 + .../1389.cpp | 9 + .../1389.java | 8 + .../1389.py | 6 + solutions/139. Word Break/139-2.cpp | 24 + solutions/139. Word Break/139-2.java | 19 + solutions/139. Word Break/139-2.py | 12 + solutions/139. Word Break/139-3.cpp | 21 + solutions/139. Word Break/139-3.java | 20 + solutions/139. Word Break/139-3.py | 16 + solutions/139. Word Break/139-4.cpp | 32 ++ solutions/139. Word Break/139-4.java | 28 + solutions/139. Word Break/139-4.py | 19 + solutions/139. Word Break/139.cpp | 26 + solutions/139. Word Break/139.java | 27 + solutions/139. Word Break/139.py | 12 + solutions/1390. Four Divisors/1390.cpp | 23 + solutions/1390. Four Divisors/1390.java | 22 + solutions/1390. Four Divisors/1390.py | 17 + .../1391.cpp | 60 ++ .../1391.java | 57 ++ solutions/1392. Longest Happy Prefix/1392.cpp | 27 + .../1392. Longest Happy Prefix/1392.java | 25 + solutions/1392. Longest Happy Prefix/1392.py | 23 + .../1393.sql" | 5 + .../1394.cpp | 16 + .../1394.java | 15 + .../1394.py | 13 + .../1395. Count Number of Teams/1395.cpp | 28 + .../1395. Count Number of Teams/1395.java | 27 + solutions/1395. Count Number of Teams/1395.py | 24 + .../1396. Design Underground System/1396.cpp | 34 ++ .../1396. Design Underground System/1396.java | 40 ++ .../1396. Design Underground System/1396.py | 19 + .../1397. Find All Good Strings/1397.cpp | 72 +++ .../1397. Find All Good Strings/1397.java | 65 +++ solutions/1397. Find All Good Strings/1397.py | 57 ++ .../1398.sql | 11 + solutions/1399. Count Largest Group/1399.cpp | 19 + solutions/1399. Count Largest Group/1399.java | 18 + solutions/1399. Count Largest Group/1399.py | 9 + solutions/14. Longest Common Prefix/14.cpp | 14 + solutions/14. Longest Common Prefix/14.java | 13 + solutions/14. Longest Common Prefix/14.py | 11 + solutions/140. Word Break II/140.cpp | 33 ++ solutions/140. Word Break II/140.java | 31 ++ solutions/140. Word Break II/140.py | 23 + .../1400.cpp | 17 + .../1400.java | 16 + .../1400.py | 7 + .../1401.cpp | 21 + solutions/1402. Reducing Dishes/1402.cpp | 18 + solutions/1402. Reducing Dishes/1402.java | 21 + solutions/1402. Reducing Dishes/1402.py | 12 + .../1403.cpp | 15 + .../1403.java | 16 + .../1403.py | 12 + .../1404.cpp | 26 + .../1404.java | 26 + .../1404.py | 18 + solutions/1405. Longest Happy String/1405.cpp | 17 + solutions/1406. Stone Game III/1406-2.cpp | 20 + solutions/1406. Stone Game III/1406-2.java | 19 + solutions/1406. Stone Game III/1406-2.py | 18 + solutions/1406. Stone Game III/1406.cpp | 25 + solutions/1406. Stone Game III/1406.java | 24 + solutions/1406. Stone Game III/1406.py | 25 + solutions/1407. Top Travellers/1407.sql | 8 + .../1408-2.cpp | 52 ++ .../1408-2.java | 46 ++ .../1408-2.py | 35 ++ .../1408-3.cpp | 51 ++ .../1408-3.java | 47 ++ .../1408-3.py | 34 ++ .../1408.cpp | 13 + .../1408.java | 12 + .../1408. String Matching in an Array/1408.py | 9 + .../1409.cpp | 55 ++ .../1409.java | 55 ++ .../1409.py | 43 ++ solutions/141. Linked List Cycle/141.cpp | 16 + solutions/141. Linked List Cycle/141.java | 15 + solutions/141. Linked List Cycle/141.py | 12 + solutions/1410. HTML Entity Parser/1410.cpp | 32 ++ solutions/1410. HTML Entity Parser/1410.java | 15 + solutions/1410. HTML Entity Parser/1410.py | 10 + .../1411.cpp" | 17 + .../1411.java" | 16 + .../1412.sql | 15 + .../1413.cpp | 12 + .../1413.java | 11 + .../1413.py | 10 + .../1414-2.cpp | 30 + .../1414-2.java | 29 + .../1414-2.py | 20 + .../1414.cpp | 20 + .../1414.java | 19 + .../1414.py | 14 + .../1415.cpp | 22 + .../1415.java | 19 + .../1415.py | 11 + solutions/1416. Restore The Array/1416-2.cpp | 24 + solutions/1416. Restore The Array/1416.cpp | 32 ++ .../1417. Reformat The String/1417-2.cpp | 26 + solutions/1417. Reformat The String/1417.cpp | 24 + solutions/1417. Reformat The String/1417.java | 31 ++ solutions/1417. Reformat The String/1417.py | 19 + .../1418.cpp | 53 ++ .../1419.cpp | 23 + .../1419.java | 22 + .../1419.py | 18 + solutions/142. Linked List Cycle II/142.cpp | 22 + solutions/142. Linked List Cycle II/142.java | 21 + solutions/142. Linked List Cycle II/142.py | 16 + .../1420-2.cpp | 38 ++ .../1420-2.java | 33 ++ .../1420-2.py | 24 + .../1420.cpp | 33 ++ .../1420.java | 31 ++ .../1420.py | 22 + solutions/1421. NPV Queries/1421.sql | 7 + .../1422.cpp | 18 + .../1422.java | 17 + .../1422.py | 14 + .../1423.cpp | 18 + .../1423.java | 19 + .../1423.py | 13 + solutions/1424. Diagonal Traverse II/1424.cpp | 21 + .../1424. Diagonal Traverse II/1424.java | 21 + .../1425.cpp | 24 + .../1425.java | 23 + .../1425. Constrained Subsequence Sum/1425.py | 20 + solutions/1426. Counting Elements/1426.cpp | 8 + solutions/1426. Counting Elements/1426.java | 15 + solutions/1426. Counting Elements/1426.py | 6 + .../1427. Perform String Shifts/1427.cpp | 19 + .../1427. Perform String Shifts/1427.java | 18 + solutions/1427. Perform String Shifts/1427.py | 12 + .../1428-2.cpp | 29 + .../1428-2.java | 27 + .../1428-2.py | 23 + .../1428.cpp | 41 ++ .../1428.java | 38 ++ .../1428.py | 24 + solutions/1429. First Unique Number/1429.cpp | 28 + solutions/1429. First Unique Number/1429.java | 24 + solutions/1429. First Unique Number/1429.py | 18 + solutions/143. Reorder List/143.cpp | 50 ++ solutions/143. Reorder List/143.java | 48 ++ solutions/143. Reorder List/143.py | 40 ++ .../1430.cpp | 17 + .../1430.java | 14 + .../1430.py | 10 + .../1431.cpp | 12 + .../1431.java | 11 + .../1431.py | 4 + .../1432.cpp | 18 + .../1432.java | 17 + .../1432.py | 15 + .../1433-2.cpp | 18 + .../1433-2.java | 16 + .../1433-2.py | 10 + .../1433.cpp | 28 + .../1433.java | 26 + .../1433.py | 16 + .../1434-2.cpp | 35 ++ .../1434-2.java | 37 ++ .../1434-3.cpp | 28 + .../1434-3.java | 30 + .../1434.cpp | 47 ++ .../1434.java | 46 ++ .../1435. Create a Session Bar Chart/1435.sql | 21 + solutions/1436. Destination City/1436.py | 14 + .../1437.py | 18 + .../1438.cpp | 27 + .../1439.cpp | 39 ++ .../1439.java | 40 ++ .../144-2.cpp | 21 + .../144-2.java | 21 + .../144-2.py | 17 + .../144.cpp | 18 + .../144.java | 16 + .../144.py | 14 + .../1440.sql | 17 + .../1441.py | 17 + .../1442.py | 19 + .../1443.cpp | 32 ++ .../1443.java | 32 ++ .../1444.cpp | 53 ++ .../1444.java | 50 ++ .../1444.py | 36 ++ solutions/1445. Apples & Oranges/1445.sql | 5 + .../1446. Consecutive Characters/1446.cpp | 14 + .../1446. Consecutive Characters/1446.java | 13 + .../1446. Consecutive Characters/1446.py | 10 + solutions/1447. Simplified Fractions/1447.cpp | 11 + .../1447. Simplified Fractions/1447.java | 14 + solutions/1447. Simplified Fractions/1447.py | 8 + .../1448.cpp | 11 + .../1448.java | 13 + .../1449.cpp | 27 + .../1449.java | 27 + .../145-2.cpp | 22 + .../145-2.java | 22 + .../145-2.py | 17 + .../145.cpp | 18 + .../145.java | 16 + .../145.py | 14 + .../1450.cpp | 13 + .../1451.py | 19 + .../1452.py | 18 + .../1453.cpp | 49 ++ .../1453.java | 50 ++ .../1453.py | 34 ++ solutions/1454. Active Users/1454.sql | 28 + .../1455.py | 9 + .../1456.py | 14 + .../1457.cpp | 23 + .../1457.java | 22 + .../1457.py | 19 + .../1458.cpp | 17 + .../1458.java | 17 + .../1458.py | 14 + solutions/1459. Rectangles Area/1459.sql | 10 + solutions/146. LRU Cache/146-2.cpp | 48 ++ solutions/146. LRU Cache/146.cpp | 64 +++ solutions/146. LRU Cache/146.java | 46 ++ solutions/146. LRU Cache/146.py | 51 ++ .../1460.cpp | 7 + .../1460.java | 9 + .../1460.py | 3 + .../1461.cpp | 22 + .../1461.java | 21 + .../1461.py | 18 + solutions/1462. Course Schedule IV/1462-2.cpp | 30 + .../1462. Course Schedule IV/1462-2.java | 27 + solutions/1462. Course Schedule IV/1462-2.py | 16 + solutions/1462. Course Schedule IV/1462.cpp | 38 ++ solutions/1462. Course Schedule IV/1462.java | 77 +++ solutions/1462. Course Schedule IV/1462.py | 21 + solutions/1463. Cherry Pickup II/1463-2.cpp | 22 + solutions/1463. Cherry Pickup II/1463-2.java | 20 + solutions/1463. Cherry Pickup II/1463.cpp | 33 ++ solutions/1463. Cherry Pickup II/1463.java | 32 ++ .../1464-2.cpp | 10 + .../1464.cpp | 15 + .../1464.java | 16 + .../1464.py | 12 + .../1465.cpp | 21 + .../1465.java | 19 + .../1465.py | 9 + .../1466.cpp | 30 + .../1466.java | 31 ++ .../1467.cpp | 38 ++ .../1467.java | 34 ++ .../1467.py | 35 ++ solutions/1468. Calculate Salaries/1468.sql | 19 + .../1469. Find All The Lonely Nodes/1469.cpp | 21 + .../1469. Find All The Lonely Nodes/1469.java | 19 + solutions/147. Insertion Sort List/147.cpp | 20 + solutions/147. Insertion Sort List/147.java | 19 + solutions/147. Insertion Sort List/147.py | 16 + solutions/1470. Shuffle the Array/1470.cpp | 11 + solutions/1470. Shuffle the Array/1470.java | 10 + solutions/1470. Shuffle the Array/1470.py | 7 + .../1471-2.cpp | 17 + .../1471.cpp | 18 + .../1471.java | 17 + .../1471.py | 18 + .../1472. Design Browser History/1472-2.cpp | 27 + .../1472. Design Browser History/1472-2.java | 25 + .../1472. Design Browser History/1472-2.py | 20 + .../1472. Design Browser History/1472-3.cpp | 34 ++ .../1472. Design Browser History/1472-3.java | 34 ++ .../1472. Design Browser History/1472-3.py | 27 + .../1472. Design Browser History/1472.cpp | 29 + .../1472. Design Browser History/1472.java | 27 + .../1472. Design Browser History/1472.py | 22 + solutions/1473. Paint House III/1473.cpp | 38 ++ solutions/1473. Paint House III/1473.java | 33 ++ .../1474.cpp | 22 + .../1474.java | 21 + .../1474.py | 21 + .../1475.cpp | 16 + .../1475.java | 15 + .../1475.py | 12 + solutions/1476. Subrectangle Queries/1476.cpp | 22 + .../1476. Subrectangle Queries/1476.java | 26 + solutions/1476. Subrectangle Queries/1476.py | 13 + .../1477-2.cpp | 25 + .../1477-2.java | 25 + .../1477.cpp | 29 + .../1477.java | 27 + solutions/1478. Allocate Mailboxes/1478.cpp | 41 ++ solutions/1478. Allocate Mailboxes/1478.java | 38 ++ .../1479. Sales by Day of the Week/1479.sql | 14 + solutions/148. Sort List/148.cpp | 57 ++ solutions/148. Sort List/148.java | 58 ++ solutions/148. Sort List/148.py | 49 ++ .../1480. Running Sum of 1d Array/1480.cpp | 10 + .../1480. Running Sum of 1d Array/1480.java | 9 + .../1480. Running Sum of 1d Array/1480.py | 3 + .../1481.cpp | 20 + .../1481.java | 16 + .../1481.py | 10 + .../1482.cpp | 38 ++ .../1482.java | 36 ++ .../1482.py | 35 ++ .../1483.cpp | 27 + .../1483.java | 27 + .../1483. Kth Ancestor of a Tree Node/1483.py | 24 + .../1484.sql | 6 + .../1485.cpp | 20 + .../1485.java | 18 + .../1486. XOR Operation in an Array/1486.cpp | 9 + .../1486. XOR Operation in an Array/1486.java | 8 + .../1486. XOR Operation in an Array/1486.py | 4 + .../1487. Making File Names Unique/1487.cpp | 28 + .../1487. Making File Names Unique/1487.java | 28 + .../1487. Making File Names Unique/1487.py | 23 + .../1488. Avoid Flood in The City/1488.cpp | 35 ++ .../1488. Avoid Flood in The City/1488.java | 35 ++ .../1488. Avoid Flood in The City/1488.py | 32 ++ .../1489.cpp | 94 ++++ .../1489.java | 89 +++ .../1489.py | 71 +++ solutions/149. Max Points on a Line/149.cpp | 41 ++ solutions/149. Max Points on a Line/149.java | 40 ++ solutions/149. Max Points on a Line/149.py | 32 ++ solutions/1490. Clone N-ary Tree/1490.cpp | 20 + solutions/1490. Clone N-ary Tree/1490.java | 18 + .../1491.cpp | 9 + .../1491.java | 8 + .../1491.py | 3 + solutions/1492. The kth Factor of n/1492.cpp | 19 + solutions/1492. The kth Factor of n/1492.java | 18 + solutions/1492. The kth Factor of n/1492.py | 23 + .../1493-2.cpp | 16 + .../1493-2.java | 15 + .../1493-2.py | 14 + .../1493.cpp | 18 + .../1493.java | 17 + .../1493.py | 16 + solutions/1494. Parallel Courses II/1494.cpp | 39 ++ solutions/1494. Parallel Courses II/1494.java | 38 ++ solutions/1494. Parallel Courses II/1494.py | 33 ++ .../1495.sql | 8 + solutions/1496. Path Crossing/1496.cpp | 34 ++ .../1497.cpp | 20 + .../1497.java | 19 + .../1497.py | 10 + .../1498.cpp | 25 + .../1498.java | 25 + .../1498.py | 18 + .../1499. Max Value of Equation/1499-2.cpp | 23 + .../1499. Max Value of Equation/1499-2.java | 22 + .../1499. Max Value of Equation/1499-2.py | 17 + .../1499. Max Value of Equation/1499.cpp | 19 + .../1499. Max Value of Equation/1499.java | 22 + solutions/1499. Max Value of Equation/1499.py | 13 + solutions/15. 3Sum/15.cpp | 36 ++ solutions/15. 3Sum/15.java | 35 ++ solutions/15. 3Sum/15.py | 32 ++ .../150.cpp | 24 + .../150.java | 18 + .../150.py | 19 + .../1500.cpp | 45 ++ .../1500.java | 35 ++ .../1500.py | 34 ++ .../1501.sql | 10 + .../1502-2.cpp | 28 + .../1502.cpp | 25 + .../1503.cpp | 8 + .../1504-2.cpp | 39 ++ .../1504-2.java | 36 ++ .../1504.cpp | 32 ++ .../1504.java | 31 ++ .../1505.cpp | 63 +++ .../1506. Find Root of N-Ary Tree/1506.cpp | 18 + .../1506. Find Root of N-Ary Tree/1506.java | 17 + .../1506. Find Root of N-Ary Tree/1506.py | 12 + solutions/1507. Reformat Date/1507.cpp | 17 + solutions/1507. Reformat Date/1507.java | 28 + solutions/1507. Reformat Date/1507.py | 10 + .../1508.cpp | 49 ++ .../1509.cpp | 19 + .../1509.java | 18 + .../1509.py | 16 + .../151. Reverse Words in a String/151.cpp | 41 ++ .../151. Reverse Words in a String/151.java | 47 ++ .../151. Reverse Words in a String/151.py | 3 + solutions/1510. Stone Game IV/1510.cpp | 16 + solutions/1510. Stone Game IV/1510.java | 15 + .../1511. Customer Order Frequency/1511.sql | 24 + solutions/1512. Number of Good Pairs/1512.cpp | 12 + .../1513.cpp | 17 + .../1514.cpp | 37 ++ .../1514.java | 42 ++ .../1514.py | 24 + .../1515.cpp | 38 ++ .../1515.java | 35 ++ .../1515.py | 27 + .../1516.cpp | 43 ++ .../1516. Move Sub-Tree of N-Ary Tree/1516.py | 33 ++ .../1517.sql | 3 + solutions/1518. Water Bottles/1518-2.cpp | 6 + solutions/1518. Water Bottles/1518.cpp | 13 + .../1519.cpp | 35 ++ .../1519.java | 35 ++ .../152. Maximum Product Subarray/152.cpp | 24 + .../152. Maximum Product Subarray/152.java | 23 + .../152. Maximum Product Subarray/152.py | 20 + .../1520.cpp | 44 ++ .../1521.cpp | 22 + .../1521.java | 21 + .../1521.py | 13 + .../1522. Diameter of N-Ary Tree/1522.cpp | 26 + .../1522. Diameter of N-Ary Tree/1522.java | 25 + .../1522. Diameter of N-Ary Tree/1522.py | 21 + .../1523.cpp | 6 + .../1524-2.cpp | 22 + .../1524.cpp | 25 + .../1525.cpp | 30 + .../1525.java | 27 + .../1525.py | 23 + .../1526.cpp | 12 + .../1526.java | 11 + .../1526.py | 9 + .../1527. Patients With a Condition/1527.sql | 5 + solutions/1528. Shuffle String/1528.cpp | 11 + solutions/1529. Minimum Suffix Flips/1529.cpp | 15 + .../1529. Minimum Suffix Flips/1529.java | 14 + .../153.cpp | 17 + .../153.java | 16 + .../153.py | 13 + .../1530.cpp | 34 ++ .../1530.java | 32 ++ .../1531. String Compression II/1531.cpp | 48 ++ .../1531. String Compression II/1531.java | 46 ++ solutions/1531. String Compression II/1531.py | 36 ++ .../1532.sql | 22 + .../1533-2.cpp | 35 ++ .../1533-2.java | 33 ++ .../1533-2.py | 31 ++ .../1533.cpp | 47 ++ .../1533.java | 45 ++ .../1533.py | 40 ++ solutions/1534. Count Good Triplets/1534.cpp | 14 + solutions/1534. Count Good Triplets/1534.java | 13 + solutions/1534. Count Good Triplets/1534.py | 8 + .../1535.cpp | 17 + .../1535.java | 16 + .../1535.py | 15 + .../1536.cpp | 32 ++ .../1536.java | 40 ++ .../1536.py | 19 + .../1537. Get the Maximum Score/1537.cpp | 38 ++ .../1537. Get the Maximum Score/1537.java | 36 ++ solutions/1537. Get the Maximum Score/1537.py | 35 ++ .../1538.cpp | 69 +++ .../1538.java | 66 +++ .../1538.py | 48 ++ .../1539.cpp | 23 + .../1539.java | 22 + .../154.cpp | 19 + .../154.java | 18 + .../154.py | 15 + .../1540-2.cpp | 24 + .../1540-2.java | 23 + .../1540-2.py | 20 + .../1540.cpp | 22 + .../1540.java | 21 + .../1540.py | 19 + .../1541.cpp | 24 + .../1541.java | 23 + .../1541.py | 21 + .../1542.cpp | 19 + .../1542.java | 19 + .../1542.py | 15 + .../1543. Fix Product Name Format/1543.sql | 7 + .../1544. Make The String Great/1544.cpp | 16 + .../1544. Make The String Great/1544.java | 15 + solutions/1544. Make The String Great/1544.py | 12 + .../1545.cpp | 13 + .../1545.java | 12 + .../1545.py | 10 + .../1546.cpp | 25 + .../1546.java | 24 + .../1546.py | 20 + .../1547-2.cpp | 21 + .../1547-2.java | 23 + .../1547-2.py | 14 + .../1547.cpp | 25 + .../1547.java | 26 + .../1547. Minimum Cost to Cut a Stick/1547.py | 12 + .../1548.cpp | 66 +++ .../1548.java | 69 +++ .../1548.py | 48 ++ .../1549.sql | 23 + solutions/155. Min Stack/155.cpp | 24 + solutions/155. Min Stack/155.java | 22 + solutions/155. Min Stack/155.py | 16 + .../1550. Three Consecutive Odds/1550.cpp | 13 + .../1550. Three Consecutive Odds/1550.java | 11 + .../1550. Three Consecutive Odds/1550.py | 8 + .../1551.cpp | 24 + .../1551.java | 22 + .../1551.py | 19 + .../1552.cpp | 31 ++ .../1552.java | 29 + .../1552.py | 24 + .../1553.cpp | 14 + .../1553.java | 15 + .../1553.py | 7 + .../1554-2.cpp | 54 ++ .../1554-2.java | 51 ++ .../1554-2.py | 35 ++ .../1554.cpp | 23 + solutions/1555. Bank Account Summary/1555.sql | 21 + solutions/1556. Thousand Separator/1556.cpp | 15 + solutions/1556. Thousand Separator/1556.java | 14 + solutions/1556. Thousand Separator/1556.py | 3 + .../1557.cpp | 16 + .../1557.java | 15 + .../1557.py | 8 + .../1558.cpp | 10 + .../1558.java | 7 + .../1558.py | 5 + .../1559. Detect Cycles in 2D Grid/1559.cpp | 43 ++ .../1559. Detect Cycles in 2D Grid/1559.java | 40 ++ .../156. Binary Tree Upside Down/156-2.cpp | 18 + .../156. Binary Tree Upside Down/156-2.java | 17 + .../156. Binary Tree Upside Down/156-2.py | 14 + .../156. Binary Tree Upside Down/156.cpp | 14 + .../156. Binary Tree Upside Down/156.java | 13 + solutions/156. Binary Tree Upside Down/156.py | 11 + .../1560.cpp | 28 + .../1560.java | 27 + .../1560.py | 18 + .../1561.cpp | 14 + .../1561.java | 13 + .../1561.py | 3 + .../1562.cpp | 26 + .../1562.java | 25 + .../1562. Find Latest Group of Size M/1562.py | 22 + solutions/1563. Stone Game V/1563.cpp | 40 ++ solutions/1563. Stone Game V/1563.java | 37 ++ .../1564-2.cpp | 14 + .../1564-2.java | 16 + .../1564-2.py | 9 + .../1564.cpp | 17 + .../1564.java | 17 + .../1564.py | 14 + .../1565.sql | 7 + .../1566.cpp | 12 + .../1566.java | 11 + .../1566.py | 8 + .../1567.cpp | 20 + .../1567.java | 22 + .../1567.py | 16 + .../1568.cpp | 51 ++ .../1568.java | 49 ++ .../1568.py | 44 ++ .../1569.cpp | 45 ++ .../1569.java | 46 ++ .../157-2.cpp | 39 ++ .../157.cpp | 31 ++ .../157.java | 30 + .../157. Read N Characters Given Read4/157.py | 31 ++ .../1570-2.cpp | 26 + .../1570-2.java | 34 ++ .../1570.cpp | 25 + .../1570.java | 23 + solutions/1571. Warehouse Manager/1571.sql | 9 + solutions/1572. Matrix Diagonal Sum/1572.cpp | 14 + solutions/1572. Matrix Diagonal Sum/1572.java | 13 + solutions/1572. Matrix Diagonal Sum/1572.py | 10 + .../1573.cpp | 34 ++ .../1573.java | 33 ++ .../1573.py | 29 + .../1574.cpp | 33 ++ .../1574.java | 32 ++ .../1574.py | 29 + .../1575-2.cpp | 27 + .../1575-2.java | 26 + .../1575. Count All Possible Routes/1575-2.py | 22 + .../1575. Count All Possible Routes/1575.cpp | 31 ++ .../1575. Count All Possible Routes/1575.java | 27 + .../1575. Count All Possible Routes/1575.py | 23 + .../1576.cpp | 23 + .../1576.java | 20 + .../1576.py | 18 + .../1577.cpp | 30 + .../1577.java | 30 + .../1577.py | 20 + .../1578.cpp | 22 + .../1578.java | 20 + .../1578.py | 18 + .../1579.cpp | 75 +++ .../1579.java | 72 +++ .../1579.py | 53 ++ .../158-2.cpp | 46 ++ .../158.cpp | 33 ++ .../158.java | 31 ++ .../158.py | 23 + .../1580.cpp | 20 + .../1580.java | 23 + .../1580.py | 14 + .../1581.sql | 8 + .../1582.cpp | 24 + .../1582.java | 23 + .../1582.py | 20 + .../1583. Count Unhappy Friends/1583.cpp | 32 ++ .../1583. Count Unhappy Friends/1583.java | 33 ++ solutions/1583. Count Unhappy Friends/1583.py | 23 + .../1584.cpp | 25 + .../1584.java | 29 + .../1584.py | 19 + .../1585.cpp | 37 ++ .../1585.java | 37 ++ .../1585.py | 25 + .../1586.cpp | 40 ++ .../1586.java | 38 ++ .../1586.py | 27 + .../1587. Bank Account Summary II/1587.sql | 8 + .../1588.cpp | 25 + .../1588.java | 24 + .../1588.py | 21 + .../1589.cpp | 30 + .../1589.java | 29 + .../1589.py | 20 + .../159.cpp | 19 + .../159.java | 18 + .../159.py | 19 + .../1590. Make Sum Divisible by P/1590.cpp | 25 + .../1590. Make Sum Divisible by P/1590.java | 24 + .../1590. Make Sum Divisible by P/1590.py | 20 + solutions/1591. Strange Printer II/1591.cpp | 58 ++ solutions/1591. Strange Printer II/1591.java | 57 ++ solutions/1591. Strange Printer II/1591.py | 54 ++ .../1592.cpp | 26 + .../1592.java | 10 + .../1593.cpp | 26 + .../1593.java | 24 + .../1594.cpp | 33 ++ .../1594.java | 32 ++ .../1595.cpp | 46 ++ .../1595.java | 42 ++ .../1595.py | 20 + .../1596.sql | 21 + .../1597.cpp | 51 ++ .../1597.java | 37 ++ solutions/1598. Crawler Log Folder/1598.cpp | 17 + solutions/1598. Crawler Log Folder/1598.java | 16 + .../1599.cpp | 28 + .../1599.java | 26 + solutions/16. 3Sum Closest/16.cpp | 30 + solutions/16. 3Sum Closest/16.java | 29 + solutions/16. 3Sum Closest/16.py | 25 + .../160.cpp | 14 + .../160.java | 13 + .../160.py | 10 + solutions/1600. Throne Inheritance/1600.cpp | 33 ++ solutions/1600. Throne Inheritance/1600.java | 34 ++ .../1601.cpp | 29 + .../1601.java | 27 + .../1602.cpp | 26 + .../1602.java | 24 + .../1602.py | 21 + .../1603. Design Parking System/1603.cpp | 13 + .../1603. Design Parking System/1603.java | 11 + solutions/1603. Design Parking System/1603.py | 7 + .../1604.cpp | 38 ++ .../1604.java | 38 ++ .../1604.py | 23 + .../1605.cpp | 17 + .../1605.java | 16 + .../1605.py | 13 + .../1606.cpp | 43 ++ .../1606.java | 40 ++ .../1607. Sellers With No Sales/1607.sql | 8 + .../1608.cpp | 17 + .../1608.java | 16 + .../1608.py | 13 + solutions/1609. Even Odd Tree/1609.cpp | 26 + solutions/1609. Even Odd Tree/1609.java | 24 + solutions/1609. Even Odd Tree/1609.py | 21 + solutions/161. One Edit Distance/161.cpp | 18 + solutions/161. One Edit Distance/161.java | 17 + solutions/161. One Edit Distance/161.py | 14 + .../1610.cpp | 39 ++ .../1610.java | 36 ++ .../1610.py | 25 + .../1611.cpp | 34 ++ .../1611.java | 33 ++ .../1611.py | 29 + .../1612.cpp | 19 + .../1612.java | 17 + .../1612.py | 15 + solutions/1613. Find the Missing IDs/1613.sql | 17 + .../1614.cpp | 15 + .../1614.java | 14 + .../1614.py | 13 + solutions/1615. Maximal Network Rank/1615.cpp | 71 +++ .../1615. Maximal Network Rank/1615.java | 64 +++ solutions/1615. Maximal Network Rank/1615.py | 55 ++ .../1616.cpp | 23 + .../1616.java | 21 + .../1616.py | 22 + .../1617.cpp | 58 ++ .../1617.java | 58 ++ .../1617.py | 47 ++ .../1618.cpp | 44 ++ .../1618.java | 38 ++ .../1618.py | 31 ++ .../1619.cpp | 10 + .../1619.java | 7 + .../1619.py | 5 + solutions/162. Find Peak Element/162.cpp | 17 + solutions/162. Find Peak Element/162.java | 16 + solutions/162. Find Peak Element/162.py | 13 + .../1620.cpp | 33 ++ .../1620.java | 33 ++ .../1620.py | 24 + .../1621.cpp | 32 ++ .../1621.java | 28 + .../1621.py | 19 + solutions/1622. Fancy Sequence/1622.cpp | 44 ++ solutions/1622. Fancy Sequence/1622.java | 42 ++ solutions/1622. Fancy Sequence/1622.py | 31 ++ .../1623.sql | 12 + .../1624.cpp | 17 + .../1624.java | 17 + .../1624.py | 12 + .../1625.cpp | 33 ++ .../1625.java | 35 ++ .../1626.cpp | 35 ++ .../1626.java | 34 ++ .../1627.cpp | 51 ++ .../1627.java | 50 ++ .../1627.py | 34 ++ .../1628.cpp | 61 +++ .../1628.java | 52 ++ .../1628.py | 54 ++ solutions/1629. Slowest Key/1629.cpp | 18 + solutions/1629. Slowest Key/1629.java | 16 + solutions/1629. Slowest Key/1629.py | 12 + solutions/163. Missing Ranges/163.cpp | 28 + solutions/163. Missing Ranges/163.java | 26 + solutions/163. Missing Ranges/163.py | 23 + solutions/1630. Arithmetic Subarrays/1630.cpp | 39 ++ .../1630. Arithmetic Subarrays/1630.java | 36 ++ solutions/1630. Arithmetic Subarrays/1630.py | 23 + .../1631. Path With Minimum Effort/1631.cpp | 47 ++ .../1631. Path With Minimum Effort/1631.java | 51 ++ .../1631. Path With Minimum Effort/1631.py | 29 + .../1632. Rank Transform of a Matrix/1632.cpp | 64 +++ .../1632.java | 74 +++ .../1632. Rank Transform of a Matrix/1632.py | 53 ++ .../1633.sql | 12 + .../1634.cpp | 55 ++ .../1634.java | 57 ++ .../1634.py | 42 ++ .../1635. Hopper Company Queries I/1635.sql | 29 + .../1636.cpp | 32 ++ .../1636.java | 33 ++ .../1636.py | 25 + .../1637.cpp | 19 + .../1637.java | 16 + .../1637.py | 4 + .../1638.cpp | 39 ++ .../1638.java | 37 ++ .../1638.py | 32 ++ .../1639-2.cpp | 30 + .../1639-2.java | 28 + .../1639-2.py | 27 + .../1639-3.cpp | 23 + .../1639-3.java | 21 + .../1639-3.py | 14 + .../1639.cpp | 33 ++ .../1639.java | 30 + .../1639.py | 21 + solutions/164. Maximum Gap/164.cpp | 39 ++ solutions/164. Maximum Gap/164.java | 45 ++ solutions/164. Maximum Gap/164.py | 35 ++ .../1640.cpp | 17 + .../1640.java | 15 + .../1640.py | 9 + .../1641-2.cpp | 6 + .../1641-2.java | 5 + .../1641. Count Sorted Vowel Strings/1641.cpp | 21 + .../1641.java | 21 + .../1642.cpp | 20 + .../1642.java | 19 + .../1642.py | 16 + .../1643. Kth Smallest Instructions/1643.cpp | 37 ++ .../1643. Kth Smallest Instructions/1643.java | 34 ++ .../1643. Kth Smallest Instructions/1643.py | 17 + .../1644-2.cpp | 22 + .../1644-2.java | 20 + .../1644-2.py | 17 + .../1644.cpp | 30 + .../1644.java | 28 + .../1644.py | 25 + .../1645. Hopper Company Queries II/1645.sql | 33 ++ .../1646.cpp | 19 + .../1646.java | 18 + .../1646.py | 17 + .../1647.cpp | 19 + .../1647.java | 20 + .../1647.py | 13 + .../1648.cpp | 40 ++ .../1648.java | 35 ++ .../1648.py | 25 + .../1649-2.cpp | 89 +++ .../1649-3.cpp | 78 +++ .../1649.cpp | 45 ++ .../165. Compare Version Numbers/165.cpp | 23 + .../165. Compare Version Numbers/165.java | 17 + solutions/165. Compare Version Numbers/165.py | 15 + .../1650.cpp | 15 + .../1650.java | 14 + .../1650.py | 11 + .../1651. Hopper Company Queries III/1651.sql | 49 ++ solutions/1652. Defuse the Bomb/1652.cpp | 24 + solutions/1652. Defuse the Bomb/1652.java | 23 + solutions/1652. Defuse the Bomb/1652.py | 22 + .../1653.cpp | 20 + .../1653.java | 18 + .../1653.py | 15 + .../1654.cpp | 37 ++ .../1654.java | 36 ++ .../1654. Minimum Jumps to Reach Home/1654.py | 35 ++ .../1655.cpp | 60 ++ .../1655.java | 53 ++ .../1655.py | 38 ++ .../1656. Design an Ordered Stream/1656.cpp | 18 + .../1656. Design an Ordered Stream/1656.java | 21 + .../1656. Design an Ordered Stream/1656.py | 13 + .../1657.cpp | 40 ++ .../1657.java | 25 + .../1657.py | 11 + .../1658.cpp | 30 + .../1658.java | 28 + .../1658.py | 23 + .../1659. Maximize Grid Happiness/1659.cpp | 78 +++ .../1659. Maximize Grid Happiness/1659.java | 66 +++ .../1659. Maximize Grid Happiness/1659.py | 49 ++ .../166.cpp | 35 ++ .../166.java | 34 ++ .../166. Fraction to Recurring Decimal/166.py | 31 ++ .../1660. Correct a Binary Tree/1660.cpp | 16 + .../1660. Correct a Binary Tree/1660.java | 14 + solutions/1660. Correct a Binary Tree/1660.py | 13 + .../1661.sql | 13 + .../1662.cpp | 25 + .../1662.java | 23 + .../1662.py | 20 + .../1663.cpp | 15 + .../1663.java | 14 + .../1663.py | 11 + .../1664-2.cpp | 25 + .../1664-2.java | 24 + .../1664. Ways to Make a Fair Array/1664.cpp | 29 + .../1664. Ways to Make a Fair Array/1664.java | 28 + .../1665.cpp | 24 + .../1665.java | 21 + .../1665.py | 13 + .../1666.cpp | 28 + .../1666.java | 26 + solutions/1667. Fix Names in a Table/1667.sql | 8 + .../1668.cpp | 12 + .../1668.java | 8 + .../1668. Maximum Repeating Substring/1668.py | 6 + .../1669.cpp | 22 + .../1669.java | 21 + .../1669.py | 19 + .../167.cpp | 15 + .../167.java | 14 + .../167.py | 13 + .../1670.cpp | 80 +++ .../1670.java | 59 ++ .../1670.py | 49 ++ .../1671.cpp | 40 ++ .../1671.java | 51 ++ .../1671.py | 26 + .../1672. Richest Customer Wealth/1672.cpp | 9 + .../1672. Richest Customer Wealth/1672.java | 8 + .../1672. Richest Customer Wealth/1672.py | 3 + .../1673.cpp | 18 + .../1673.java | 20 + .../1673.py | 13 + .../1674.cpp | 26 + .../1674.java | 25 + .../1674.py | 22 + .../1675.cpp | 24 + .../1675.java | 22 + .../1675. Minimize Deviation in Array/1675.py | 18 + .../1676.cpp | 20 + .../1676.java | 18 + .../1676.py | 16 + .../1677.sql | 11 + .../1678. Goal Parser Interpretation/1678.cpp | 18 + .../1678.java | 17 + .../1678. Goal Parser Interpretation/1678.py | 3 + .../1679. Max Number of K-Sum Pairs/1679.cpp | 16 + .../1679. Max Number of K-Sum Pairs/1679.java | 17 + .../1679. Max Number of K-Sum Pairs/1679.py | 5 + .../168. Excel Sheet Column Title/168.cpp | 7 + .../168. Excel Sheet Column Title/168.java | 5 + .../168. Excel Sheet Column Title/168.py | 4 + .../1680-2.cpp | 16 + .../1680-2.java | 15 + .../1680-2.py | 12 + .../1680.cpp | 17 + .../1680.java | 15 + .../1680.py | 12 + .../1681. Minimum Incompatibility/1681.cpp | 71 +++ .../1681. Minimum Incompatibility/1681.java | 69 +++ .../1681. Minimum Incompatibility/1681.py | 65 +++ .../1682-2.cpp | 21 + .../1682-2.java | 20 + .../1682-2.py | 17 + .../1682.cpp | 22 + .../1682.java | 18 + .../1682.py | 17 + solutions/1683. Invalid Tweets/1683.sql | 3 + .../1684.cpp | 11 + .../1684.java | 7 + .../1684.py | 4 + .../1685.cpp | 27 + .../1685.java | 24 + .../1685.py | 6 + solutions/1686. Stone Game VI/1686.cpp | 24 + solutions/1686. Stone Game VI/1686.java | 22 + .../1687.cpp | 37 ++ .../1687.java | 36 ++ .../1687.py | 31 ++ .../1688.cpp | 6 + .../1688.java | 5 + .../1688.py | 3 + .../1689.cpp | 6 + .../1689.java | 5 + .../1689.py | 3 + solutions/169. Majority Element/169.cpp | 15 + solutions/169. Majority Element/169.java | 14 + solutions/169. Majority Element/169.py | 11 + solutions/1690. Stone Game VII/1690-2.cpp | 21 + solutions/1690. Stone Game VII/1690-2.java | 20 + solutions/1690. Stone Game VII/1690.cpp | 28 + solutions/1690. Stone Game VII/1690.java | 27 + .../1691.cpp | 25 + .../1691.java | 33 ++ .../1692-2.cpp | 16 + .../1692-2.java | 15 + .../1692.cpp | 21 + .../1692.java | 20 + .../1693. Daily Leads and Partners/1693.sql | 7 + .../1694. Reformat Phone Number/1694.cpp | 21 + .../1694. Reformat Phone Number/1694.java | 19 + solutions/1694. Reformat Phone Number/1694.py | 18 + .../1695. Maximum Erasure Value/1695.cpp | 19 + .../1695. Maximum Erasure Value/1695.java | 18 + solutions/1695. Maximum Erasure Value/1695.py | 17 + solutions/1696. Jump Game VI/1696.cpp | 23 + solutions/1696. Jump Game VI/1696.java | 22 + solutions/1696. Jump Game VI/1696.py | 19 + .../1697.cpp | 57 ++ .../1697.java | 59 ++ .../1698.cpp | 39 ++ .../1698.java | 36 ++ .../1698.py | 29 + .../1699.sql | 7 + .../17-2.cpp | 21 + .../17-2.java | 21 + .../17-2.py | 17 + .../17.cpp | 29 + .../17.java | 27 + .../17.py | 21 + .../170.cpp | 21 + .../170.java | 20 + .../170.py | 16 + .../1700.cpp | 17 + .../1700.java | 16 + .../1700.py | 10 + solutions/1701. Average Waiting Time/1701.cpp | 14 + .../1701. Average Waiting Time/1701.java | 13 + .../1702.cpp | 19 + .../1702.java | 18 + .../1702.py | 16 + .../1703.cpp | 34 ++ .../1703.java | 38 ++ .../1704.cpp | 18 + .../1704.java | 13 + .../1704.py | 6 + .../1705.cpp | 28 + .../1705.java | 27 + .../1705.py | 23 + .../1706. Where Will the Ball Fall/1706.cpp | 35 ++ .../1706. Where Will the Ball Fall/1706.java | 36 ++ .../1706. Where Will the Ball Fall/1706.py | 27 + .../1707.cpp | 85 +++ .../1707.java | 76 +++ .../1707.py | 65 +++ .../1708. Largest Subarray Length K/1708.cpp | 7 + .../1708. Largest Subarray Length K/1708.java | 9 + .../1708. Largest Subarray Length K/1708.py | 5 + .../1709.sql | 18 + .../171. Excel Sheet Column Number/171.cpp | 8 + .../171. Excel Sheet Column Number/171.java | 5 + .../171. Excel Sheet Column Number/171.py | 4 + .../1710. Maximum Units on a Truck/1710.cpp | 21 + .../1710. Maximum Units on a Truck/1710.java | 18 + .../1710. Maximum Units on a Truck/1710.py | 11 + solutions/1711. Count Good Meals/1711.cpp | 21 + solutions/1711. Count Good Meals/1711.java | 19 + solutions/1711. Count Good Meals/1711.py | 15 + .../1712-2.cpp | 28 + .../1712-2.java | 28 + .../1712-2.py | 24 + .../1712.cpp | 55 ++ .../1712.java | 55 ++ .../1712.py | 47 ++ .../1713.cpp | 35 ++ .../1713.java | 33 ++ .../1713.py | 22 + .../1714.cpp | 38 ++ .../1714.java | 37 ++ .../1714.py | 18 + .../1715. Count Apples and Oranges/1715.sql | 6 + .../1716.cpp | 15 + .../1716.java | 14 + .../1716.py | 11 + .../1717.cpp | 41 ++ .../1717.java | 38 ++ .../1717.py | 34 ++ .../1718.cpp | 39 ++ .../1718.java | 37 ++ .../1718.py | 33 ++ .../1719.cpp | 70 +++ .../1719.java | 67 +++ .../1719.py | 50 ++ .../172. Factorial Trailing Zeroes/172.cpp | 6 + .../172. Factorial Trailing Zeroes/172.java | 5 + .../172. Factorial Trailing Zeroes/172.py | 3 + solutions/1720. Decode XORed Array/1720.cpp | 12 + solutions/1720. Decode XORed Array/1720.java | 11 + solutions/1720. Decode XORed Array/1720.py | 8 + .../1721.cpp | 19 + .../1721.java | 20 + .../1721.py | 17 + .../1722.cpp | 60 ++ .../1722.java | 62 +++ .../1722.py | 48 ++ .../1723.cpp | 28 + .../1723.java | 29 + .../1723.py | 27 + .../1724.cpp | 58 ++ .../1724.java | 53 ++ .../1725.cpp | 15 + .../1725.java | 14 + .../1725.py | 4 + .../1726. Tuple with Same Product/1726.cpp | 13 + .../1726. Tuple with Same Product/1726.java | 15 + .../1726. Tuple with Same Product/1726.py | 15 + .../1727.cpp | 24 + .../1727.java | 23 + .../1727.py | 18 + solutions/1728. Cat and Mouse II/1728.cpp | 95 ++++ solutions/1728. Cat and Mouse II/1728.java | 86 +++ solutions/1728. Cat and Mouse II/1728.py | 75 +++ solutions/1729. Find Followers Count/1729.sql | 6 + .../173-2.cpp | 27 + .../173-2.java | 24 + .../173. Binary Search Tree Iterator/173-2.py | 17 + .../173. Binary Search Tree Iterator/173.cpp | 26 + .../173. Binary Search Tree Iterator/173.java | 24 + .../173. Binary Search Tree Iterator/173.py | 19 + .../1730. Shortest Path to Get Food/1730.cpp | 38 ++ .../1730. Shortest Path to Get Food/1730.java | 36 ++ .../1730. Shortest Path to Get Food/1730.py | 31 ++ .../1731.sql | 10 + .../1732. Find the Highest Altitude/1732.cpp | 12 + .../1732. Find the Highest Altitude/1732.java | 11 + .../1732. Find the Highest Altitude/1732.py | 8 + .../1733.cpp | 43 ++ .../1733.java | 40 ++ .../1733.py | 19 + .../1734. Decode XORed Permutation/1734.cpp | 36 ++ .../1734. Decode XORed Permutation/1734.java | 36 ++ .../1734. Decode XORed Permutation/1734.py | 29 + .../1735.cpp | 68 +++ .../1735.java | 67 +++ .../1735.py | 45 ++ .../1736.cpp | 15 + .../1736.java | 14 + .../1736.py | 12 + .../1737.cpp | 31 ++ .../1737.java | 30 + .../1738.cpp | 20 + .../1738.java | 18 + solutions/1739. Building Boxes/1739.cpp | 32 ++ solutions/1739. Building Boxes/1739.java | 31 ++ solutions/1739. Building Boxes/1739.py | 27 + solutions/174. Dungeon Game/174.cpp | 18 + solutions/174. Dungeon Game/174.java | 18 + solutions/174. Dungeon Game/174.py | 13 + .../1740.cpp | 26 + .../1740.java | 26 + .../1740.py | 22 + .../1741.sql | 6 + .../1742.cpp | 23 + .../1742.java | 21 + .../1742.py | 15 + .../1743.cpp | 33 ++ .../1743.java | 33 ++ .../1743.py | 25 + .../1744.cpp | 24 + .../1744.java | 23 + .../1744.py | 4 + .../1745-2.cpp | 25 + .../1745-2.java | 24 + .../1745-2.py | 21 + .../1745. Palindrome Partitioning IV/1745.cpp | 29 + .../1745.java | 27 + .../1745. Palindrome Partitioning IV/1745.py | 17 + .../1746.cpp | 16 + .../1746.java | 15 + .../1746.py | 12 + .../1747. Leetflex Banned Accounts/1747.sql | 19 + .../1748. Sum of Unique Elements/1748.cpp | 17 + .../1748. Sum of Unique Elements/1748.java | 16 + .../1748. Sum of Unique Elements/1748.py | 5 + .../1749-2.cpp | 16 + .../1749-2.java | 15 + .../1749-2.py | 12 + .../1749.cpp | 16 + .../1749.java | 15 + .../1749.py | 12 + solutions/175. Combine Two Tables/175.sql | 8 + .../1750.cpp | 17 + .../1750.java | 16 + .../1750.py | 13 + .../1751.cpp | 28 + .../1751.java | 33 ++ .../1751.py | 19 + .../1752.cpp | 13 + .../1752.java | 12 + .../1753.cpp | 10 + .../1753.java | 9 + .../1754.cpp | 11 + .../1754.java | 10 + .../1754.py | 9 + .../1755. Closest Subsequence Sum/1755.cpp | 39 ++ .../1755. Closest Subsequence Sum/1755.java | 38 ++ .../1755. Closest Subsequence Sum/1755.py | 26 + .../1756.py | 16 + .../1757.sql | 3 + .../1758.cpp | 13 + .../1758.java | 12 + .../1758.py | 7 + .../1759.cpp | 18 + .../1759.java | 17 + .../1759.py | 14 + solutions/176. Second Highest Salary/176.sql | 8 + .../1760.cpp | 26 + .../1760.java | 24 + .../1760.py | 7 + .../1761.cpp | 25 + .../1761.java | 27 + .../1761.py | 21 + .../1762.cpp | 14 + .../1762.java | 16 + .../1762.py | 10 + .../1763. Longest Nice Substring/1763.cpp | 26 + .../1763. Longest Nice Substring/1763.java | 21 + .../1763. Longest Nice Substring/1763.py | 17 + .../1764.cpp | 28 + .../1764.java | 26 + .../1764.py | 22 + solutions/1765. Map of Highest Peak/1765.cpp | 34 ++ solutions/1765. Map of Highest Peak/1765.java | 34 ++ solutions/1765. Map of Highest Peak/1765.py | 27 + solutions/1766. Tree of Coprimes/1766.cpp | 48 ++ solutions/1766. Tree of Coprimes/1766.java | 54 ++ solutions/1766. Tree of Coprimes/1766.py | 32 ++ .../1767.sql | 10 + .../1768. Merge Strings Alternately/1768.cpp | 14 + .../1768. Merge Strings Alternately/1768.java | 13 + .../1768. Merge Strings Alternately/1768.py | 3 + .../1769.cpp | 20 + .../1769.java | 19 + solutions/177. Nth Highest Salary/177.sql | 13 + .../1770.cpp | 29 + .../1770.java | 23 + .../1770.py | 17 + .../1771.cpp | 27 + .../1771.java | 26 + .../1772.cpp | 31 ++ .../1772.java | 21 + .../1773.cpp | 10 + .../1773.java | 16 + solutions/1774. Closest Dessert Cost/1774.cpp | 24 + .../1774. Closest Dessert Cost/1774.java | 19 + .../1775.cpp | 32 ++ .../1775.java | 28 + solutions/1776. Car Fleet II/1776.cpp | 39 ++ solutions/1776. Car Fleet II/1776.java | 40 ++ solutions/1776. Car Fleet II/1776.py | 25 + .../1777.sql | 7 + .../1778.cpp | 77 +++ .../1778.java | 76 +++ .../1779.cpp | 21 + .../1779.java | 20 + solutions/178. Rank Scores/178.sql | 4 + .../1780.cpp | 13 + .../1780.java | 12 + .../1780.py | 7 + .../1781.cpp | 26 + .../1781.java | 24 + .../1781.py | 11 + solutions/1782. Count Pairs Of Nodes/1782.cpp | 45 ++ .../1782. Count Pairs Of Nodes/1782.java | 49 ++ solutions/1782. Count Pairs Of Nodes/1782.py | 37 ++ solutions/1783. Grand Slam Titles/1783.sql | 15 + .../1784.cpp | 6 + .../1784.java | 5 + .../1784.py | 3 + .../1785.cpp | 8 + .../1785.java | 7 + .../1786.cpp | 50 ++ .../1786.java | 54 ++ .../1786.py | 34 ++ .../1787.cpp | 38 ++ .../1787.java | 44 ++ .../1787.py | 31 ++ .../1788.cpp | 19 + .../1788.java | 16 + .../1788.py | 13 + .../1789.sql | 12 + solutions/179. Largest Number/179.cpp | 15 + solutions/179. Largest Number/179.java | 9 + solutions/179. Largest Number/179.py | 8 + .../1790.cpp | 13 + .../1790.java | 14 + .../1790.py | 8 + .../1791. Find Center of Star Graph/1791.cpp | 8 + .../1791. Find Center of Star Graph/1791.java | 7 + .../1791. Find Center of Star Graph/1791.py | 5 + .../1792. Maximum Average Pass Ratio/1792.cpp | 36 ++ .../1792.java | 33 ++ .../1792. Maximum Average Pass Ratio/1792.py | 15 + .../1793-2.cpp | 26 + .../1793-2.java | 25 + .../1793-2.py | 22 + .../1793.cpp | 22 + .../1793.java | 19 + .../1793.py | 15 + .../1794.cpp | 31 ++ .../1794.java | 32 ++ .../1794.py | 26 + .../1795. Rearrange Products Table/1795.sql | 20 + .../1796.cpp | 20 + .../1796.java | 19 + .../1796.py | 15 + .../1797.cpp | 31 ++ .../1797.java | 30 + .../1797.py | 27 + .../1798.cpp | 16 + .../1798.java | 15 + .../1798.py | 10 + .../1799.cpp | 30 + .../1799.java | 30 + .../1799.py | 25 + solutions/18. 4Sum/18.cpp | 50 ++ solutions/18. 4Sum/18.java | 47 ++ solutions/18. 4Sum/18.py | 31 ++ solutions/180. Consecutive Numbers/180.sql | 13 + .../1800.cpp | 17 + .../1800.java | 16 + .../1800.py | 13 + .../1801.cpp | 43 ++ .../1801.java | 37 ++ .../1802.cpp | 30 + .../1802.java | 28 + .../1803.cpp | 54 ++ .../1803.java | 51 ++ .../1804.cpp | 55 ++ .../1804.java | 52 ++ .../1805-2.py | 3 + .../1805.cpp | 25 + .../1805.java | 25 + .../1805.py | 20 + .../1806.cpp | 17 + .../1806.java | 16 + .../1807.cpp | 24 + .../1807.java | 22 + .../1808.cpp | 23 + .../1808.java | 21 + solutions/1809. Ad-Free Sessions/1809.sql | 7 + .../181.sql | 5 + .../1810.cpp | 79 +++ .../1810.java | 74 +++ .../1811. Find Interview Candidates/1811.sql | 36 ++ .../1812.cpp | 8 + .../1812.java | 7 + .../1812.py | 4 + .../1813. Sentence Similarity III/1813.cpp | 33 ++ .../1813. Sentence Similarity III/1813.java | 21 + .../1813. Sentence Similarity III/1813.py | 18 + .../1814.cpp | 28 + .../1814.java | 26 + .../1814.py | 4 + .../1815.cpp | 45 ++ .../1815.java | 52 ++ .../1815.py | 29 + solutions/1816. Truncate Sentence/1816.cpp | 9 + solutions/1816. Truncate Sentence/1816.java | 11 + solutions/1816. Truncate Sentence/1816.py | 3 + .../1817.cpp | 15 + .../1817.java | 16 + .../1817.py | 9 + .../1818.cpp | 21 + .../1818.java | 24 + .../1818.py | 16 + .../1819.cpp | 23 + .../1819.java | 26 + solutions/182. Duplicate Emails/182.sql | 4 + .../1820.cpp | 33 ++ .../1820.java | 32 ++ .../1820.py | 25 + .../1821.sql | 3 + .../1822.cpp | 15 + .../1822.java | 14 + .../1822.py | 11 + .../1823-2.cpp | 25 + .../1823-2.java | 23 + .../1823-2.py | 20 + .../1823-3.cpp | 27 + .../1823-3.java | 25 + .../1823-3.py | 22 + .../1823.cpp | 22 + .../1823.java | 21 + .../1823.py | 21 + .../1824. Minimum Sideway Jumps/1824.cpp | 19 + .../1824. Minimum Sideway Jumps/1824.java | 18 + solutions/1824. Minimum Sideway Jumps/1824.py | 16 + solutions/1825. Finding MK Average/1825-2.cpp | 70 +++ .../1825. Finding MK Average/1825-2.java | 70 +++ solutions/1825. Finding MK Average/1825.cpp | 80 +++ solutions/1825. Finding MK Average/1825.java | 81 +++ solutions/1826. Faulty Sensor/1826.cpp | 30 + solutions/1826. Faulty Sensor/1826.java | 28 + solutions/1826. Faulty Sensor/1826.py | 25 + .../1827.cpp | 14 + .../1827.java | 13 + .../1827.py | 10 + .../1828.cpp | 28 + .../1828.java | 25 + .../1828.py | 12 + .../1829. Maximum XOR for Each Query/1829.cpp | 16 + .../1829.java | 15 + .../1829. Maximum XOR for Each Query/1829.py | 11 + .../183. Customers Who Never Order/183.sql | 5 + .../1830.cpp | 39 ++ .../1830.java | 40 ++ .../1830.py | 25 + .../1831.sql | 14 + .../1832-2.cpp | 11 + .../1832-2.java | 10 + .../1832-2.py | 8 + .../1832.cpp | 6 + .../1832.java | 10 + .../1832.py | 3 + .../1833. Maximum Ice Cream Bars/1833.cpp | 14 + .../1833. Maximum Ice Cream Bars/1833.java | 13 + .../1833. Maximum Ice Cream Bars/1833.py | 9 + solutions/1834. Single-Threaded CPU/1834.cpp | 31 ++ solutions/1834. Single-Threaded CPU/1834.java | 46 ++ solutions/1834. Single-Threaded CPU/1834.py | 22 + .../1835.cpp | 8 + .../1835.java | 7 + .../1835.py | 3 + .../1836.cpp | 21 + .../1836.java | 19 + .../1836.py | 18 + .../1837. Sum of Digits in Base K/1837.cpp | 13 + .../1837. Sum of Digits in Base K/1837.java | 12 + .../1837. Sum of Digits in Base K/1837.py | 9 + .../1838.cpp | 18 + .../1838.java | 17 + .../1838.py | 16 + .../1839.cpp | 23 + .../1839.java | 22 + .../1839.py | 19 + .../184. Department Highest Salary/184.sql | 19 + .../1840. Maximum Building Height/1840.cpp | 32 ++ .../1840. Maximum Building Height/1840.java | 33 ++ .../1840. Maximum Building Height/1840.py | 18 + solutions/1841. League Statistics/1841.sql | 44 ++ .../1842.cpp | 54 ++ .../1842.java | 57 ++ .../1842.py | 42 ++ .../1843. Suspicious Bank Accounts/1843.sql | 18 + .../1844.cpp | 8 + .../1844.java | 10 + .../1844.py | 8 + .../1845. Seat Reservation Manager/1845.cpp | 21 + .../1845. Seat Reservation Manager/1845.java | 16 + .../1845. Seat Reservation Manager/1845.py | 9 + .../1846.cpp | 12 + .../1846.java | 11 + .../1846.py | 9 + solutions/1847. Closest Room/1847.cpp | 38 ++ solutions/1847. Closest Room/1847.java | 36 ++ solutions/1847. Closest Room/1847.py | 32 ++ .../1848.cpp | 12 + .../1848.java | 11 + .../1848.py | 9 + .../1849.cpp | 25 + .../1849.java | 21 + .../1849.py | 17 + .../185.sql | 20 + .../1850.cpp | 29 + .../1850.java | 64 +++ .../1850.py | 50 ++ .../1851.cpp | 36 ++ .../1851.java | 37 ++ .../1852.cpp | 19 + .../1852.java | 18 + .../1852.py | 18 + solutions/1853. Convert Date Format/1853.sql | 2 + .../1854. Maximum Population Year/1854.cpp | 29 + .../1854. Maximum Population Year/1854.java | 28 + .../1854. Maximum Population Year/1854.py | 21 + .../1855-2.cpp | 13 + .../1855-2.java | 12 + .../1855-2.py | 11 + .../1855.cpp | 16 + .../1855.java | 15 + .../1855.py | 14 + .../1856.cpp | 26 + .../1856.java | 22 + .../1856.py | 14 + .../1857.cpp | 40 ++ .../1857.java | 41 ++ .../1857.py | 33 ++ .../1858.cpp | 50 ++ .../1858.java | 47 ++ .../1858.py | 33 ++ solutions/1859. Sorting the Sentence/1859.cpp | 27 + .../1859. Sorting the Sentence/1859.java | 18 + solutions/1859. Sorting the Sentence/1859.py | 3 + .../186. Reverse Words in a String II/186.cpp | 21 + .../186.java | 27 + .../186. Reverse Words in a String II/186.py | 21 + .../1860. Incremental Memory Leak/1860.cpp | 16 + .../1860. Incremental Memory Leak/1860.java | 15 + .../1860. Incremental Memory Leak/1860.py | 12 + solutions/1861. Rotating the Box/1861.cpp | 18 + solutions/1861. Rotating the Box/1861.java | 18 + solutions/1861. Rotating the Box/1861.py | 16 + solutions/1862. Sum of Floored Pairs/1862.cpp | 30 + .../1862. Sum of Floored Pairs/1862.java | 29 + solutions/1862. Sum of Floored Pairs/1862.py | 26 + .../1863-2.cpp | 7 + .../1863-2.java | 5 + .../1863-2.py | 3 + .../1863.cpp | 16 + .../1863.java | 14 + .../1863.py | 11 + .../1864.cpp | 25 + .../1864.java | 23 + .../1864.py | 20 + .../1865.cpp | 29 + .../1865.java | 25 + .../1865.py | 16 + .../1866.cpp | 18 + .../1866.java | 16 + .../1866.py | 11 + .../1867.sql | 12 + .../1868.cpp | 26 + .../1868.java | 24 + .../1868.py | 22 + .../1869.cpp | 20 + .../1869.java | 19 + .../1869.py | 18 + solutions/187. Repeated DNA Sequences/187.cpp | 16 + .../187. Repeated DNA Sequences/187.java | 15 + solutions/187. Repeated DNA Sequences/187.py | 12 + .../1870.cpp | 28 + .../1870.java | 26 + .../1870.py | 21 + solutions/1871. Jump Game VII/1871.cpp | 17 + solutions/1871. Jump Game VII/1871.java | 16 + solutions/1871. Jump Game VII/1871.py | 12 + solutions/1872. Stone Game VIII/1872.cpp | 20 + solutions/1872. Stone Game VIII/1872.java | 21 + solutions/1872. Stone Game VIII/1872.py | 15 + .../1873. Calculate Special Bonus/1873.sql | 5 + .../1874.cpp | 14 + .../1874.java | 15 + .../1874.py | 3 + .../1875.sql | 15 + .../1876.cpp | 17 + .../1876.java | 16 + .../1876.py | 10 + .../1877.cpp | 13 + .../1877.java | 12 + .../1877.py | 4 + .../1878.cpp | 46 ++ .../1878.java | 44 ++ .../1878.py | 55 ++ .../1879.cpp | 25 + .../1879.java | 22 + .../1879.py | 10 + .../188.cpp | 27 + .../188.java | 27 + .../188.py | 21 + .../1880.cpp | 17 + .../1880.java | 15 + .../1880.py | 12 + .../1881.cpp | 12 + .../1881.java | 11 + .../1881.py | 9 + .../1882.cpp | 56 ++ .../1882.java | 53 ++ .../1882. Process Tasks Using Servers/1882.py | 24 + .../1883.cpp | 26 + .../1883.java | 26 + .../1883.py | 21 + .../1884.cpp | 48 ++ .../1884.java | 41 ++ .../1885. Count Pairs in Two Arrays/1885.cpp | 19 + .../1885. Count Pairs in Two Arrays/1885.java | 31 ++ .../1885. Count Pairs in Two Arrays/1885.py | 10 + .../1886.cpp | 19 + .../1886.java | 24 + .../1886.py | 7 + .../1887.cpp | 14 + .../1887.java | 13 + .../1887.py | 11 + .../1888.cpp | 26 + .../1888.java | 25 + .../1888.py | 22 + .../1889.cpp | 32 ++ .../1889.java | 39 ++ .../1889.py | 19 + solutions/189. Rotate Array/189.cpp | 15 + solutions/189. Rotate Array/189.java | 19 + solutions/189. Rotate Array/189.py | 12 + .../1890. The Latest Login in 2020/1890.sql | 6 + solutions/1891. Cutting Ribbons/1891.cpp | 25 + solutions/1891. Cutting Ribbons/1891.java | 23 + solutions/1891. Cutting Ribbons/1891.py | 19 + .../1892. Page Recommendations II/1892.sql | 19 + .../1893-2.cpp | 20 + .../1893-2.java | 19 + .../1893-2.py | 12 + .../1893.cpp | 17 + .../1893.java | 16 + .../1893.py | 4 + .../1894.cpp | 16 + .../1894.java | 15 + .../1894.py | 10 + solutions/1895. Largest Magic Square/1895.cpp | 62 +++ .../1895. Largest Magic Square/1895.java | 56 ++ solutions/1895. Largest Magic Square/1895.py | 46 ++ .../1896.cpp | 64 +++ .../1896.java | 61 +++ .../1896.py | 50 ++ .../1897.cpp | 13 + .../1897.java | 11 + .../1897.py | 3 + .../1898.cpp | 35 ++ .../1898.java | 33 ++ .../1898.py | 29 + .../1899.cpp | 14 + .../1899.java | 12 + .../1899.py | 10 + .../19.cpp | 20 + .../19.java | 19 + .../19.py | 16 + solutions/190. Reverse Bits/190.cpp | 12 + solutions/190. Reverse Bits/190.java | 12 + solutions/190. Reverse Bits/190.py | 9 + .../1900.cpp | 39 ++ .../1900.java | 33 ++ .../1900.py | 30 + .../1901. Find a Peak Element II/1901.cpp | 26 + .../1901. Find a Peak Element II/1901.java | 24 + .../1901. Find a Peak Element II/1901.py | 13 + .../1902.cpp | 19 + .../1902.java | 18 + .../1903.cpp | 9 + .../1903.java | 8 + .../1903.py | 6 + .../1904.cpp | 17 + .../1904.java | 13 + .../1904.py | 12 + solutions/1905. Count Sub Islands/1905.cpp | 28 + solutions/1905. Count Sub Islands/1905.java | 25 + solutions/1905. Count Sub Islands/1905.py | 24 + .../1906.cpp | 33 ++ .../1906.java | 41 ++ .../1906.py | 26 + .../1907. Count Salary Categories/1907.sql | 14 + solutions/1908. Game of Nim/1908.cpp | 6 + solutions/1908. Game of Nim/1908.java | 5 + solutions/1908. Game of Nim/1908.py | 3 + .../1909.cpp | 17 + .../1909.java | 16 + .../1909.py | 13 + solutions/191. Number of 1 Bits/191-2.cpp | 6 + solutions/191. Number of 1 Bits/191-2.java | 6 + solutions/191. Number of 1 Bits/191-2.py | 3 + solutions/191. Number of 1 Bits/191.cpp | 12 + solutions/191. Number of 1 Bits/191.java | 12 + solutions/191. Number of 1 Bits/191.py | 9 + .../1910.cpp | 18 + .../1910.java | 17 + .../1910.py | 15 + .../1911.cpp | 14 + .../1911.java | 13 + .../1911.py | 10 + .../1912. Design Movie Rental System/1912.cpp | 66 +++ .../1912.java | 65 +++ .../1912. Design Movie Rental System/1912.py | 28 + .../1913.cpp | 26 + .../1913.java | 25 + .../1913.py | 20 + .../1914. Cyclically Rotating a Grid/1914.cpp | 34 ++ .../1914.java | 33 ++ .../1914. Cyclically Rotating a Grid/1914.py | 29 + .../1915.cpp | 21 + .../1915.java | 20 + .../1915.py | 16 + .../1916.py | 23 + .../1917.sql | 27 + .../1918. Kth Smallest Subarray Sum/1918.cpp | 30 + .../1918. Kth Smallest Subarray Sum/1918.java | 28 + .../1918. Kth Smallest Subarray Sum/1918.py | 16 + .../1919. Leetcodify Similar Friends/1919.sql | 15 + solutions/192. Word Frequency/192.sh | 1 + .../1920.cpp | 14 + .../1920.java | 13 + .../1920.py | 11 + .../1921.cpp | 18 + .../1921.java | 17 + .../1921.py | 6 + solutions/1922. Count Good Numbers/1922.cpp | 17 + solutions/1922. Count Good Numbers/1922.java | 15 + solutions/1922. Count Good Numbers/1922.py | 12 + .../1923. Longest Common Subpath/1923.cpp | 56 ++ .../1923. Longest Common Subpath/1923.java | 52 ++ .../1923. Longest Common Subpath/1923.py | 49 ++ solutions/1924. Erect the Fence II/1924.cpp | 103 ++++ solutions/1924. Erect the Fence II/1924.java | 106 ++++ solutions/1924. Erect the Fence II/1924.py | 89 +++ .../1925. Count Square Sum Triples/1925.cpp | 17 + .../1925. Count Square Sum Triples/1925.java | 16 + .../1925. Count Square Sum Triples/1925.py | 14 + .../1926.cpp | 34 ++ .../1926.java | 33 ++ .../1926.py | 26 + solutions/1927. Sum Game/1927.cpp | 20 + solutions/1927. Sum Game/1927.java | 18 + solutions/1927. Sum Game/1927.py | 15 + .../1928.cpp | 57 ++ .../1928.java | 60 ++ .../1928.py | 40 ++ .../1929. Concatenation of Array/1929.cpp | 11 + .../1929. Concatenation of Array/1929.java | 12 + .../1929. Concatenation of Array/1929.py | 3 + solutions/193. Valid Phone Numbers/193.sh | 1 + .../1930.cpp | 21 + .../1930.java | 21 + .../1930.py | 16 + .../1931.cpp | 52 ++ .../1931.java | 50 ++ .../1931.py | 31 ++ .../1932.cpp | 46 ++ .../1932.java | 44 ++ .../1932.py | 35 ++ .../1933.cpp | 27 + .../1933.java | 26 + .../1933.py | 14 + solutions/1934. Confirmation Rate/1934.sql | 7 + .../1935.cpp | 24 + .../1935.java | 21 + .../1935.py | 9 + .../1936.cpp | 14 + .../1936.java | 13 + .../1936. Add Minimum Number of Rungs/1936.py | 10 + .../1937.cpp | 32 ++ .../1937.java | 31 ++ .../1937.py | 24 + .../1938.cpp | 84 +++ .../1938.java | 85 +++ .../1938.py | 66 +++ .../1939.sql | 16 + solutions/194. Transpose File/194.sh | 13 + .../1940-2.py | 3 + .../1940.cpp | 15 + .../1940.java | 14 + .../1940.py | 13 + .../1941.cpp | 15 + .../1941.java | 12 + .../1941.py | 3 + .../1942.cpp | 30 + .../1942.java | 33 ++ .../1942.py | 23 + .../1943. Describe the Painting/1943.cpp | 26 + .../1943. Describe the Painting/1943.java | 26 + solutions/1943. Describe the Painting/1943.py | 21 + .../1944.cpp | 18 + .../1944.java | 17 + .../1944.py | 13 + .../1945.cpp | 29 + .../1945.java | 27 + .../1945.py | 12 + .../1946.cpp | 17 + .../1946.java | 18 + .../1946.py | 14 + .../1947.cpp | 35 ++ .../1947.java | 30 + .../1947.py | 20 + .../1948.cpp | 61 +++ .../1948.java | 69 +++ .../1948.py | 44 ++ solutions/1949. Strong Friendship/1949.sql | 24 + solutions/195. Tenth Line/195.sh | 1 + .../1950.cpp | 40 ++ .../1950.java | 41 ++ .../1950.py | 33 ++ .../1951.sql | 15 + solutions/1952. Three Divisors/1952.cpp | 19 + solutions/1952. Three Divisors/1952.java | 17 + solutions/1952. Three Divisors/1952.py | 10 + .../1953.cpp | 10 + .../1953.java | 9 + .../1953.py | 6 + .../1954.cpp | 41 ++ .../1954.java | 39 ++ .../1954.py | 28 + .../1955-2.cpp | 39 ++ .../1955-2.java | 38 ++ .../1955-2.py | 35 ++ .../1955-3.cpp | 27 + .../1955-3.java | 26 + .../1955-3.py | 23 + .../1955.cpp | 39 ++ .../1955.java | 36 ++ .../1955.py | 32 ++ .../1956.cpp | 23 + .../1956.java | 22 + .../1956.py | 16 + .../1957.cpp | 10 + .../1957.java | 10 + .../1957.py | 7 + .../1958. Check if Move is Legal/1958.cpp | 30 + .../1958. Check if Move is Legal/1958.java | 29 + .../1958. Check if Move is Legal/1958.py | 24 + .../1959.cpp | 34 ++ .../1959.java | 31 ++ .../1959.py | 27 + .../196. Delete Duplicate Emails/196.sql | 5 + .../1960-2.cpp | 72 +++ .../1960-2.java | 65 +++ .../1960-2.py | 55 ++ .../1960.cpp | 43 ++ .../1960.java | 53 ++ .../1960.py | 30 + .../1961.cpp | 12 + .../1961.java | 12 + .../1961.py | 8 + .../1962.cpp | 19 + .../1962.java | 17 + .../1962.py | 9 + .../1963.cpp | 16 + .../1963.java | 15 + .../1963.py | 13 + .../1964.cpp | 27 + .../1964.java | 34 ++ .../1964.py | 18 + .../1965.sql | 12 + .../1966.cpp | 27 + .../1966.java | 26 + .../1966.py | 19 + .../1967.cpp | 8 + .../1967.java | 5 + .../1967.py | 3 + .../1968.cpp | 9 + .../1968.java | 11 + .../1968.py | 6 + .../1969.cpp | 21 + .../1969.java | 19 + .../1969.py | 7 + solutions/197. Rising Temperature/197.sql | 5 + .../1970.cpp | 59 ++ .../1970.java | 57 ++ .../1970.py | 46 ++ .../1971.cpp | 45 ++ .../1971.java | 44 ++ .../1971.py | 32 ++ .../1972.sql | 26 + .../1973.cpp | 22 + .../1973.java | 16 + .../1973.py | 21 + .../1974.cpp | 15 + .../1974.java | 14 + .../1974.py | 11 + solutions/1975. Maximum Matrix Sum/1975.cpp | 20 + solutions/1975. Maximum Matrix Sum/1975.java | 19 + solutions/1975. Maximum Matrix Sum/1975.py | 16 + .../1976.cpp | 48 ++ .../1976.java | 52 ++ .../1976.py | 33 ++ .../1977.cpp | 52 ++ .../1977.java | 51 ++ .../1977.py | 45 ++ .../1978.sql | 9 + .../1979.cpp | 6 + .../1979.java | 11 + .../1979.py | 3 + solutions/198. House Robber/198-2.cpp | 15 + solutions/198. House Robber/198-2.java | 14 + solutions/198. House Robber/198-2.py | 11 + solutions/198. House Robber/198.cpp | 19 + solutions/198. House Robber/198.java | 19 + solutions/198. House Robber/198.py | 16 + .../1980-2.cpp | 12 + .../1980-2.java | 11 + .../1980. Find Unique Binary String/1980-2.py | 3 + .../1980. Find Unique Binary String/1980.cpp | 17 + .../1980. Find Unique Binary String/1980.java | 16 + .../1980. Find Unique Binary String/1980.py | 9 + .../1981.cpp | 39 ++ .../1981.java | 22 + .../1981.py | 13 + .../1982.cpp | 44 ++ .../1982.java | 42 ++ .../1982.py | 32 ++ .../1983.cpp | 19 + .../1983.java | 18 + .../1983.py | 11 + .../1984.cpp | 13 + .../1984.java | 12 + .../1984.py | 9 + .../1985.cpp | 18 + .../1985.java | 15 + .../1985.py | 11 + .../1986.cpp | 35 ++ .../1986.java | 33 ++ .../1986.py | 28 + .../1987.cpp | 22 + .../1987.java | 19 + .../1987.py | 16 + .../1988.sql | 7 + .../1989.cpp | 24 + .../1989.java | 23 + .../1989.py | 20 + .../199-2.cpp | 19 + .../199-2.java | 17 + .../199. Binary Tree Right Side View/199-2.py | 15 + .../199. Binary Tree Right Side View/199.cpp | 26 + .../199. Binary Tree Right Side View/199.java | 24 + .../199. Binary Tree Right Side View/199.py | 20 + .../1990.sql | 24 + .../1991.cpp | 16 + .../1991.java | 15 + .../1991.py | 12 + .../1992.cpp | 30 + .../1992.java | 27 + .../1992. Find All Groups of Farmland/1992.py | 23 + solutions/1993. Operations on Tree/1993.cpp | 57 ++ solutions/1993. Operations on Tree/1993.java | 59 ++ solutions/1993. Operations on Tree/1993.py | 51 ++ .../1994. The Number of Good Subsets/1994.cpp | 52 ++ .../1994.java | 49 ++ .../1994. The Number of Good Subsets/1994.py | 26 + .../1995-2.cpp | 19 + .../1995-2.java | 16 + .../1995. Count Special Quadruplets/1995-2.py | 13 + .../1995-3.cpp | 20 + .../1995-3.java | 18 + .../1995. Count Special Quadruplets/1995-3.py | 15 + .../1995. Count Special Quadruplets/1995.cpp | 16 + .../1995. Count Special Quadruplets/1995.java | 15 + .../1995. Count Special Quadruplets/1995.py | 8 + .../1996-2.cpp | 30 + .../1996-2.java | 26 + .../1996-2.py | 18 + .../1996.cpp | 22 + .../1996.java | 19 + .../1996.py | 13 + .../1997.cpp | 22 + .../1997.java | 21 + .../1997.py | 19 + solutions/1998. GCD Sort of an Array/1998.cpp | 75 +++ .../1998. GCD Sort of an Array/1998.java | 75 +++ solutions/1998. GCD Sort of an Array/1998.py | 59 ++ .../1999-2.cpp | 22 + .../1999-2.java | 20 + .../1999-2.py | 17 + .../1999.cpp | 31 ++ .../1999.java | 28 + .../1999.py | 23 + solutions/2. Add Two Numbers/2.cpp | 24 + solutions/2. Add Two Numbers/2.java | 23 + solutions/2. Add Two Numbers/2.py | 18 + solutions/20. Valid Parentheses/20.cpp | 25 + solutions/20. Valid Parentheses/20.java | 17 + solutions/20. Valid Parentheses/20.py | 15 + solutions/200. Number of Islands/200-2.cpp | 29 + solutions/200. Number of Islands/200-2.java | 27 + solutions/200. Number of Islands/200-2.py | 26 + solutions/200. Number of Islands/200.cpp | 37 ++ solutions/200. Number of Islands/200.java | 36 ++ solutions/200. Number of Islands/200.py | 30 + .../2000. Reverse Prefix of Word/2000.cpp | 7 + .../2000. Reverse Prefix of Word/2000.java | 9 + .../2000. Reverse Prefix of Word/2000.py | 4 + .../2001-2.cpp | 26 + .../2001-2.java | 22 + .../2001-2.py | 12 + .../2001.cpp | 18 + .../2001.java | 17 + .../2001.py | 9 + .../2002.cpp | 39 ++ .../2002.java | 38 ++ .../2002.py | 28 + .../2003.cpp | 53 ++ .../2003.java | 53 ++ .../2003.py | 43 ++ .../2004.sql | 39 ++ .../2005.cpp | 6 + .../2005.java | 5 + .../2005.py | 3 + .../2006.cpp | 16 + .../2006.java | 15 + .../2006.py | 4 + .../2007.cpp | 19 + .../2007.java | 18 + .../2007.py | 13 + .../2008-2.cpp | 24 + .../2008-2.java | 29 + .../2008-2.py | 16 + .../2008. Maximum Earnings From Taxi/2008.cpp | 24 + .../2008.java | 29 + .../2008. Maximum Earnings From Taxi/2008.py | 16 + .../2009.cpp | 25 + .../2009.java | 24 + .../2009.py | 13 + .../201. Bitwise AND of Numbers Range/201.cpp | 14 + .../201.java | 13 + .../201. Bitwise AND of Numbers Range/201.py | 3 + .../2010.sql | 38 ++ .../2011.cpp | 11 + .../2011.java | 10 + .../2011.py | 3 + .../2012. Sum of Beauty in the Array/2012.cpp | 24 + .../2012.java | 23 + .../2012. Sum of Beauty in the Array/2012.py | 19 + solutions/2013. Detect Squares/2013.cpp | 32 ++ solutions/2013. Detect Squares/2013.java | 31 ++ solutions/2013. Detect Squares/2013.py | 14 + .../2014.cpp | 46 ++ .../2014.java | 43 ++ .../2014.py | 38 ++ .../2015.cpp | 37 ++ .../2015.java | 39 ++ .../2015.py | 26 + .../2016.cpp | 15 + .../2016.java | 14 + .../2016.py | 11 + solutions/2017. Grid Game/2017.cpp | 17 + solutions/2017. Grid Game/2017.java | 16 + solutions/2017. Grid Game/2017.py | 13 + .../2018.cpp | 54 ++ .../2018.java | 30 + .../2018.py | 10 + .../2019.cpp | 67 +++ .../2019.java | 73 +++ .../2019.py | 30 + solutions/202. Happy Number/202.cpp | 24 + solutions/202. Happy Number/202.java | 22 + solutions/202. Happy Number/202.py | 17 + .../2020.sql | 7 + .../2021.cpp | 26 + .../2021.java | 26 + .../2021.py | 23 + .../2022.cpp | 14 + .../2022.java | 13 + .../2022.py | 11 + .../2023.cpp | 21 + .../2023.java | 20 + .../2023.py | 14 + .../2024.cpp | 17 + .../2024.java | 16 + .../2024.py | 16 + .../2025.cpp | 32 ++ .../2025.java | 32 ++ .../2025.py | 27 + solutions/2026. Low-Quality Problems/2026.sql | 4 + .../2027.cpp | 16 + .../2027.java | 15 + .../2027.py | 13 + .../2028. Find Missing Observations/2028.cpp | 16 + .../2028. Find Missing Observations/2028.java | 16 + .../2028. Find Missing Observations/2028.py | 12 + solutions/2029. Stone Game IX/2029.cpp | 13 + solutions/2029. Stone Game IX/2029.java | 12 + solutions/2029. Stone Game IX/2029.py | 6 + .../203. Remove Linked List Elements/203.cpp | 16 + .../203. Remove Linked List Elements/203.java | 15 + .../203. Remove Linked List Elements/203.py | 13 + .../2030.cpp | 35 ++ .../2030.java | 30 + .../2030.py | 26 + .../2031.cpp | 56 ++ .../2031.java | 51 ++ .../2031.py | 35 ++ solutions/2032. Two Out of Three/2032.cpp | 23 + solutions/2032. Two Out of Three/2032.java | 20 + solutions/2032. Two Out of Three/2032.py | 6 + .../2033.cpp | 19 + .../2033.java | 22 + .../2033.py | 12 + .../2034. Stock Price Fluctuation/2034-2.cpp | 28 + .../2034. Stock Price Fluctuation/2034.cpp | 28 + .../2034. Stock Price Fluctuation/2034.java | 26 + .../2034. Stock Price Fluctuation/2034.py | 25 + .../2035.cpp | 52 ++ .../2035.java | 55 ++ .../2035.py | 37 ++ .../2036.cpp | 26 + .../2036.java | 25 + .../2036.py | 21 + .../2037.cpp | 14 + .../2037.java | 13 + .../2037.py | 3 + .../2038.cpp | 16 + .../2038.java | 15 + .../2038.py | 12 + .../2039.cpp | 39 ++ .../2039.java | 41 ++ .../2039.py | 28 + solutions/204. Count Primes/204.cpp | 21 + solutions/204. Count Primes/204.java | 24 + solutions/204. Count Primes/204.py | 15 + .../2040.cpp | 63 +++ .../2040.java | 59 ++ .../2040.py | 40 ++ .../2041.sql | 7 + .../2042.cpp | 17 + .../2042.java | 15 + .../2042.py | 12 + solutions/2043. Simple Bank System/2043.cpp | 33 ++ solutions/2043. Simple Bank System/2043.java | 33 ++ solutions/2043. Simple Bank System/2043.py | 25 + .../2044.cpp | 21 + .../2044.java | 20 + .../2044.py | 17 + .../2045.cpp | 42 ++ .../2045.java | 44 ++ .../2045.py | 31 ++ .../2046.cpp | 20 + .../2046.java | 19 + .../2046.py | 16 + .../2047-2.cpp | 14 + .../2047-2.java | 12 + .../2047-2.py | 4 + .../2047.cpp | 35 ++ .../2047.java | 32 ++ .../2047.py | 21 + .../2048.cpp | 23 + .../2048.java | 21 + .../2048.py | 15 + .../2049.cpp | 36 ++ .../2049.java | 39 ++ .../2049.py | 31 ++ solutions/205. Isomorphic Strings/205.cpp | 16 + solutions/205. Isomorphic Strings/205.java | 12 + solutions/205. Isomorphic Strings/205.py | 3 + solutions/2050. Parallel Courses III/2050.cpp | 34 ++ .../2050. Parallel Courses III/2050.java | 35 ++ solutions/2050. Parallel Courses III/2050.py | 25 + .../2051.sql | 15 + .../2052.cpp | 41 ++ .../2052.java | 30 + .../2052.py | 28 + .../2053.cpp | 15 + .../2053.java | 14 + .../2053.py | 11 + .../2054.cpp | 36 ++ .../2054.java | 36 ++ .../2054.py | 20 + .../2055. Plates Between Candles/2055-2.cpp | 45 ++ .../2055. Plates Between Candles/2055-2.java | 41 ++ .../2055. Plates Between Candles/2055-2.py | 34 ++ .../2055. Plates Between Candles/2055.cpp | 27 + .../2055. Plates Between Candles/2055.java | 29 + .../2055. Plates Between Candles/2055.py | 16 + .../2056.cpp | 89 +++ .../2056.java | 91 +++ .../2056.py | 42 ++ .../2057.cpp | 9 + .../2057.java | 8 + .../2057.py | 3 + .../2058.cpp | 29 + .../2058.java | 28 + .../2058.py | 24 + .../2059.cpp | 29 + .../2059.java | 27 + .../2059.py | 20 + solutions/206. Reverse Linked List/206-2.cpp | 15 + solutions/206. Reverse Linked List/206-2.java | 14 + solutions/206. Reverse Linked List/206-2.py | 12 + solutions/206. Reverse Linked List/206.cpp | 12 + solutions/206. Reverse Linked List/206.java | 11 + solutions/206. Reverse Linked List/206.py | 9 + .../2060.cpp | 67 +++ .../2060.java | 68 +++ .../2060.py | 51 ++ .../2061.cpp | 35 ++ .../2061.java | 34 ++ .../2061.py | 28 + .../2062.cpp | 36 ++ .../2062.java | 32 ++ .../2062.py | 29 + .../2063. Vowels of All Substrings/2063-2.cpp | 18 + .../2063-2.java | 15 + .../2063. Vowels of All Substrings/2063-2.py | 5 + .../2063. Vowels of All Substrings/2063.cpp | 22 + .../2063. Vowels of All Substrings/2063.java | 19 + .../2063. Vowels of All Substrings/2063.py | 12 + .../2064.cpp | 25 + .../2064.java | 21 + .../2064.py | 16 + .../2065-2.py | 21 + .../2065.cpp | 38 ++ .../2065.java | 40 ++ .../2065.py | 26 + solutions/2066. Account Balance/2066.sql | 9 + .../2067.cpp | 23 + .../2067.java | 21 + .../2067.py | 20 + .../2068.cpp | 14 + .../2068.java | 13 + .../2068.py | 5 + .../2069.cpp | 32 ++ .../2069.java | 30 + .../2069. Walking Robot Simulation II/2069.py | 19 + solutions/207. Course Schedule/207.cpp | 38 ++ solutions/207. Course Schedule/207.java | 38 ++ solutions/207. Course Schedule/207.py | 31 ++ .../2070.cpp | 23 + .../2070.java | 32 ++ .../2070.py | 9 + .../2071.cpp | 56 ++ .../2071.java | 59 ++ .../2071.py | 45 ++ .../2072. The Winner University/2072.sql | 18 + .../2073. Time Needed to Buy Tickets/2073.cpp | 14 + .../2073.java | 13 + .../2073. Time Needed to Buy Tickets/2073.py | 11 + .../2074.cpp | 55 ++ .../2074.java | 53 ++ .../2074.py | 44 ++ .../2075-2.py | 12 + .../2075.py | 21 + .../2076.cpp | 58 ++ .../2076.java | 57 ++ .../2076.py | 45 ++ .../2077.py | 15 + .../2078.cpp | 14 + .../2078.java | 12 + .../2078.py | 11 + solutions/2079. Watering Plants/2079.py | 13 + .../208. Implement Trie (Prefix Tree)/208.cpp | 42 ++ .../208.java | 39 ++ .../208. Implement Trie (Prefix Tree)/208.py | 30 + .../2080. Range Frequency Queries/2080.py | 11 + .../2081. Sum of k-Mirror Numbers/2081.py | 26 + .../2082.sql | 3 + .../2083.cpp | 12 + .../2083.java | 11 + .../2083.py | 10 + .../2084.sql | 13 + .../2085.cpp | 16 + .../2085.java | 14 + .../2085.py | 9 + .../2086.cpp | 20 + .../2086.java | 21 + .../2086.py | 18 + .../2087.cpp | 18 + .../2087.java | 16 + .../2087.py | 15 + .../2088.cpp | 23 + .../2088.java | 24 + .../2088.py | 15 + .../2089.cpp | 14 + .../2089.java | 12 + .../2089.py | 5 + .../209. Minimum Size Subarray Sum/209.cpp | 17 + .../209. Minimum Size Subarray Sum/209.java | 16 + .../209. Minimum Size Subarray Sum/209.py | 14 + .../2090. K Radius Subarray Averages/2090.cpp | 20 + .../2090.java | 23 + .../2090. K Radius Subarray Averages/2090.py | 16 + .../2091.cpp | 11 + .../2091.java | 29 + .../2091.py | 8 + .../2092.cpp | 70 +++ .../2092.java | 73 +++ .../2092. Find All People With Secret/2092.py | 51 ++ .../2093.cpp | 45 ++ .../2093.java | 50 ++ .../2093.py | 23 + .../2094.cpp | 20 + .../2094.java | 19 + .../2094.py | 13 + .../2095.cpp | 17 + .../2095.java | 16 + .../2095.py | 13 + .../2096-2.cpp | 31 ++ .../2096-2.java | 29 + .../2096-2.py | 23 + .../2096.cpp | 39 ++ .../2096.java | 33 ++ .../2096.py | 27 + .../2097. Valid Arrangement of Pairs/2097.cpp | 44 ++ .../2097.java | 39 ++ .../2097. Valid Arrangement of Pairs/2097.py | 27 + .../2098.cpp | 34 ++ .../2098.java | 36 ++ .../2098.py | 31 ++ .../2099.cpp | 22 + .../2099.java | 21 + .../2099.py | 15 + solutions/21. Merge Two Sorted Lists/21.cpp | 11 + solutions/21. Merge Two Sorted Lists/21.java | 13 + solutions/21. Merge Two Sorted Lists/21.py | 8 + solutions/210. Course Schedule II/210-2.cpp | 33 ++ solutions/210. Course Schedule II/210-2.java | 36 ++ solutions/210. Course Schedule II/210-2.py | 24 + solutions/210. Course Schedule II/210.cpp | 41 ++ solutions/210. Course Schedule II/210.java | 40 ++ solutions/210. Course Schedule II/210.py | 36 ++ .../2100.cpp | 25 + .../2100.java | 24 + .../2100.py | 16 + .../2101. Detonate the Maximum Bombs/2101.cpp | 43 ++ .../2101.java | 41 ++ .../2101. Detonate the Maximum Bombs/2101.py | 26 + .../2102.cpp | 45 ++ .../2102.java | 30 + .../2102.py | 30 + solutions/2103. Rings and Rods/2103.cpp | 14 + solutions/2103. Rings and Rods/2103.java | 13 + solutions/2103. Rings and Rods/2103.py | 9 + .../2104. Sum of Subarray Ranges/2104.cpp | 31 ++ .../2104. Sum of Subarray Ranges/2104.java | 37 ++ .../2104. Sum of Subarray Ranges/2104.py | 24 + solutions/2105. Watering Plants II/2105.cpp | 22 + solutions/2105. Watering Plants II/2105.java | 21 + solutions/2105. Watering Plants II/2105.py | 20 + .../2106.cpp | 36 ++ .../2106.java | 36 ++ .../2106.py | 25 + .../2107.cpp | 25 + .../2107.java | 27 + .../2107.py | 19 + .../2108.cpp | 19 + .../2108.java | 17 + .../2108.py | 12 + .../2109. Adding Spaces to a String/2109.cpp | 4 + .../2109. Adding Spaces to a String/2109.java | 16 + .../2109. Adding Spaces to a String/2109.py | 12 + .../211.cpp | 42 ++ .../211.java | 39 ++ .../211.py | 26 + .../2110.cpp | 17 + .../2110.java | 16 + .../2110.py | 13 + .../2111.cpp | 30 + .../2111.java | 29 + .../2111.py | 12 + .../2112.sql | 18 + .../2113.cpp | 25 + .../2113.java | 23 + .../2113.py | 12 + .../2114.cpp | 11 + .../2114.java | 8 + .../2114.py | 3 + .../2115.cpp | 38 ++ .../2115.java | 39 ++ .../2115.py | 29 + .../2116.cpp | 37 ++ .../2116.java | 32 ++ .../2116.py | 25 + .../2117.cpp | 36 ++ .../2117.java | 34 ++ .../2117.py | 26 + solutions/2118. Build the Equation/2118.sql | 22 + .../2119-2.cpp | 6 + .../2119-2.java | 5 + .../2119-2.py | 3 + .../2119.cpp | 18 + .../2119.java | 16 + .../2119.py | 12 + solutions/212. Word Search II/212.cpp | 59 ++ solutions/212. Word Search II/212.java | 55 ++ solutions/212. Word Search II/212.py | 49 ++ .../2120.cpp | 42 ++ .../2120.java | 39 ++ .../2120.py | 27 + .../2121.cpp | 32 ++ .../2121.java | 32 ++ .../2121.py | 21 + .../2122. Recover the Original Array/2122.cpp | 41 ++ .../2122.java | 38 ++ .../2122. Recover the Original Array/2122.py | 25 + .../2123.cpp | 47 ++ .../2123.java | 47 ++ .../2123.py | 33 ++ .../2124.cpp | 6 + .../2124.java | 5 + .../2124.py | 3 + .../2125.cpp | 17 + .../2125.java | 16 + .../2125.py | 12 + solutions/2126. Destroying Asteroids/2126.cpp | 16 + .../2126. Destroying Asteroids/2126.java | 15 + solutions/2126. Destroying Asteroids/2126.py | 8 + .../2127.cpp | 76 +++ .../2127.java | 78 +++ .../2127.py | 66 +++ .../2128.cpp | 16 + .../2128.java | 14 + .../2128.py | 4 + solutions/2129. Capitalize the Title/2129.cpp | 20 + .../2129. Capitalize the Title/2129.java | 19 + solutions/2129. Capitalize the Title/2129.py | 3 + solutions/213. House Robber II/213.cpp | 24 + solutions/213. House Robber II/213.java | 22 + solutions/213. House Robber II/213.py | 20 + .../2130.cpp | 37 ++ .../2130.java | 35 ++ .../2130.py | 29 + .../2131.cpp | 24 + .../2131.java | 23 + .../2131.py | 19 + solutions/2132. Stamping the Grid/2132.cpp | 40 ++ solutions/2132. Stamping the Grid/2132.java | 38 ++ solutions/2132. Stamping the Grid/2132.py | 33 ++ .../2133.cpp | 19 + .../2133.java | 18 + .../2133.py | 4 + .../2134.cpp | 19 + .../2134.java | 18 + .../2134.py | 15 + .../2135.cpp | 30 + .../2135.java | 25 + .../2135.py | 20 + .../2136.cpp | 26 + .../2136.java | 28 + .../2136.py | 10 + .../2137.cpp | 31 ++ .../2137.java | 29 + .../2137.py | 25 + .../2138.cpp | 13 + .../2138.java | 12 + .../2138.py | 7 + .../2139.cpp | 18 + .../2139.java | 17 + .../2139.py | 13 + solutions/214. Shortest Palindrome/214.cpp | 16 + solutions/214. Shortest Palindrome/214.java | 11 + solutions/214. Shortest Palindrome/214.py | 9 + .../2140.cpp | 18 + .../2140.java | 17 + .../2140.py | 13 + .../2141.cpp | 19 + .../2141.java | 19 + .../2141.py | 15 + .../2142.sql | 20 + .../2143.cpp | 34 ++ .../2143.java | 32 ++ .../2143.py | 25 + .../2144.cpp | 14 + .../2144.java | 17 + .../2144.py | 3 + .../2145-2.cpp | 16 + .../2145-2.java | 15 + .../2145-2.py | 12 + .../2145. Count the Hidden Sequences/2145.cpp | 15 + .../2145.java | 14 + .../2145. Count the Hidden Sequences/2145.py | 4 + .../2146.cpp | 62 +++ .../2146.java | 62 +++ .../2146.py | 40 ++ .../2147.cpp | 19 + .../2147.java | 18 + .../2147.py | 15 + .../2148.cpp | 9 + .../2148.java | 7 + .../2148.py | 5 + .../2149.cpp | 18 + .../2149.java | 17 + .../2149.py | 13 + .../215-2.cpp | 24 + .../215-2.java | 28 + .../215-2.py | 20 + .../215-3.cpp | 26 + .../215-3.java | 30 + .../215-3.py | 22 + .../215.cpp | 14 + .../215.java | 13 + .../215.py | 10 + .../2150.cpp | 16 + .../2150.java | 15 + .../2150.py | 7 + .../2151-2.cpp | 28 + .../2151-2.java | 26 + .../2151-2.py | 19 + .../2151.cpp | 38 ++ .../2151.java | 36 ++ .../2151.py | 31 ++ .../2152.cpp | 53 ++ .../2152.java | 54 ++ .../2152.py | 43 ++ .../2153.sql | 62 +++ .../2155-2.cpp | 14 + .../2155-2.java | 13 + .../2155-2.py | 11 + .../2155.cpp | 9 + .../2155.java | 8 + .../2155.py | 6 + .../2155.cpp | 26 + .../2155.java | 26 + .../2155.py | 21 + .../2156.cpp | 22 + .../2156.java | 23 + .../2156.py | 16 + solutions/2157. Groups of Strings/2157.cpp | 79 +++ solutions/2157. Groups of Strings/2157.java | 80 +++ solutions/2157. Groups of Strings/2157.py | 62 +++ .../2158-2.cpp | 24 + .../2158.cpp | 52 ++ .../2158.java | 48 ++ .../2158.py | 31 ++ .../2159.sql | 21 + solutions/216. Combination Sum III/216.cpp | 24 + solutions/216. Combination Sum III/216.java | 22 + solutions/216. Combination Sum III/216.py | 16 + .../2160.cpp | 9 + .../2160.java | 7 + .../2160.py | 4 + .../2161.cpp | 20 + .../2161.java | 20 + .../2161.py | 5 + .../2162.cpp | 30 + .../2162.java | 28 + .../2162.py | 23 + .../2163.cpp | 35 ++ .../2163.java | 34 ++ .../2163.py | 28 + .../2164-2.py | 5 + .../2164.cpp | 31 ++ .../2164.java | 30 + .../2164.py | 21 + .../2165.cpp | 10 + .../2165.java | 15 + .../2165.py | 6 + solutions/2166. Design Bitset/2166.cpp | 44 ++ solutions/2166. Design Bitset/2166.java | 49 ++ solutions/2166. Design Bitset/2166.py | 33 ++ .../2167-2.cpp | 15 + .../2167-2.java | 14 + .../2167-2.py | 11 + .../2167.cpp | 24 + .../2167.java | 24 + .../2167.py | 20 + .../2168.cpp | 39 ++ .../2168.java | 36 ++ .../2168.py | 31 ++ .../2169.cpp | 15 + .../2169.java | 17 + .../2169.py | 11 + solutions/217. Contains Duplicate/217.cpp | 12 + solutions/217. Contains Duplicate/217.java | 11 + solutions/217. Contains Duplicate/217.py | 3 + .../2170.cpp | 32 ++ .../2170.java | 33 ++ .../2170.py | 29 + .../2171.cpp | 15 + .../2171.java | 14 + .../2171.py | 6 + .../2172. Maximum AND Sum of Array/2172.cpp | 22 + .../2172. Maximum AND Sum of Array/2172.java | 20 + .../2172. Maximum AND Sum of Array/2172.py | 18 + .../2173. Longest Winning Streak/2173.sql | 34 ++ .../2174-2.cpp | 38 ++ .../2174-2.java | 37 ++ .../2174-2.py | 32 ++ .../2174.cpp | 43 ++ .../2174.java | 42 ++ .../2174.py | 34 ++ .../2175.sql | 17 + .../2176.cpp | 23 + .../2176.java | 28 + .../2176.py | 18 + .../2177.cpp | 9 + .../2177.java | 8 + .../2177.py | 6 + .../2178.cpp | 20 + .../2178.java | 19 + .../2178.py | 15 + .../2179.cpp | 66 +++ .../2179.java | 65 +++ .../2179.py | 44 ++ solutions/218. The Skyline Problem/218-2.cpp | 40 ++ solutions/218. The Skyline Problem/218.cpp | 58 ++ solutions/218. The Skyline Problem/218.java | 56 ++ solutions/218. The Skyline Problem/218.py | 48 ++ .../2180.cpp | 16 + .../2180.java | 16 + .../2180.py | 6 + .../2181-2.cpp | 20 + .../2181-2.java | 19 + .../2181-2.py | 16 + .../2181.cpp | 16 + .../2181.java | 15 + .../2181.py | 12 + .../2182.cpp | 37 ++ .../2182.java | 35 ++ .../2182.py | 27 + .../2183.cpp | 17 + .../2183.java | 20 + .../2183.py | 13 + .../2184.cpp | 45 ++ .../2184.java | 46 ++ .../2184.py | 35 ++ .../2185.cpp | 7 + .../2185.java | 5 + .../2185.py | 3 + .../2186.cpp | 15 + .../2186.java | 8 + .../2186.py | 5 + .../2187.cpp | 22 + .../2187.java | 20 + .../2187.py | 13 + .../2188-2.cpp | 20 + .../2188.cpp | 33 ++ .../2188.java | 34 ++ .../2188.py | 25 + .../2189.cpp | 16 + .../2189.java | 14 + .../2189.py | 11 + solutions/219. Contains Duplicate II/219.cpp | 15 + solutions/219. Contains Duplicate II/219.java | 14 + solutions/219. Contains Duplicate II/219.py | 12 + .../2190.cpp | 12 + .../2190.java | 16 + .../2190.py | 9 + .../2191. Sort the Jumbled Numbers/2191-2.cpp | 23 + .../2191-2.java | 25 + .../2191. Sort the Jumbled Numbers/2191.cpp | 25 + .../2191. Sort the Jumbled Numbers/2191.java | 19 + .../2191. Sort the Jumbled Numbers/2191.py | 9 + .../2192-2.cpp | 42 ++ .../2192-2.java | 44 ++ .../2192-2.py | 25 + .../2192.cpp | 30 + .../2192.java | 33 ++ .../2192.py | 20 + .../2193.cpp | 21 + .../2193.java | 21 + .../2193.py | 17 + .../2194.cpp | 16 + .../2194.java | 15 + .../2194.py | 10 + .../2195.cpp | 27 + .../2195.java | 34 ++ .../2195.py | 22 + .../2196.cpp | 30 + .../2196.java | 27 + .../2196.py | 16 + .../2197.cpp | 14 + .../2197.java | 21 + .../2197.py | 10 + .../2198.cpp | 32 ++ .../2198.java | 30 + .../2198.py | 28 + .../2199.sql | 13 + solutions/22. Generate Parentheses/22.cpp | 27 + solutions/22. Generate Parentheses/22.java | 25 + solutions/22. Generate Parentheses/22.py | 18 + .../220. Contains Duplicate III/220-2.cpp | 36 ++ .../220. Contains Duplicate III/220-2.java | 33 ++ .../220. Contains Duplicate III/220-2.py | 27 + solutions/220. Contains Duplicate III/220.cpp | 19 + .../220. Contains Duplicate III/220.java | 20 + .../2200.cpp | 19 + .../2200.java | 18 + .../2200.py | 16 + .../2201.cpp | 26 + .../2201.java | 22 + .../2201.py | 12 + .../2202.cpp | 18 + .../2202.java | 24 + .../2202.py | 15 + .../2203.cpp | 55 ++ .../2203.java | 61 +++ .../2203.py | 31 ++ .../2204.cpp | 71 +++ .../2204.java | 70 +++ .../2204.py | 53 ++ .../2205.sql | 10 + .../2206.cpp | 11 + .../2206.java | 10 + .../2206.py | 3 + .../2207.cpp | 21 + .../2207.java | 20 + .../2207.py | 16 + .../2208.cpp | 18 + .../2208.java | 20 + .../2208.py | 16 + .../2209-2.cpp | 21 + .../2209-2.java | 20 + .../2209-2.py | 17 + .../2209.cpp | 27 + .../2209.java | 23 + .../2209.py | 18 + solutions/221. Maximal Square/221-2.cpp | 23 + solutions/221. Maximal Square/221-2.java | 22 + solutions/221. Maximal Square/221-2.py | 19 + solutions/221. Maximal Square/221.cpp | 20 + solutions/221. Maximal Square/221.java | 19 + solutions/221. Maximal Square/221.py | 17 + .../2210.cpp | 16 + .../2210.java | 15 + .../2210.py | 13 + .../2211. Count Collisions on a Road/2211.cpp | 16 + .../2211.java | 19 + .../2211. Count Collisions on a Road/2211.py | 12 + .../2212.cpp | 43 ++ .../2212.java | 40 ++ .../2212.py | 30 + .../2213.cpp | 128 +++++ .../2214.cpp | 8 + .../2214.java | 7 + .../2214. Minimum Health to Beat Game/2214.py | 3 + .../2215.cpp | 18 + .../2215.java | 9 + .../2215.py | 5 + .../2216.cpp | 13 + .../2216.java | 12 + .../2216.py | 11 + .../2217.cpp | 32 ++ .../2217.java | 30 + .../2217.py | 19 + .../2218.cpp | 29 + .../2218.java | 26 + .../2218.py | 20 + .../2219. Maximum Sum Score of Array/2219.cpp | 15 + .../2219.java | 14 + .../2219. Maximum Sum Score of Array/2219.py | 11 + .../222. Count Complete Tree Nodes/222-2.cpp | 26 + .../222. Count Complete Tree Nodes/222-2.java | 25 + .../222. Count Complete Tree Nodes/222-2.py | 21 + .../222. Count Complete Tree Nodes/222.cpp | 8 + .../222. Count Complete Tree Nodes/222.java | 7 + .../222. Count Complete Tree Nodes/222.py | 5 + .../2220.cpp | 6 + .../2220.java | 5 + .../2220.py | 3 + .../2221.cpp | 9 + .../2221.java | 8 + .../2221.py | 6 + .../2222.cpp | 24 + .../2222.java | 23 + .../2222.py | 20 + .../2223.cpp | 24 + .../2223.java | 23 + .../2223.py | 19 + .../2224.cpp | 20 + .../2224.java | 18 + .../2224.py | 15 + .../2225.cpp | 21 + .../2225.java | 22 + .../2225.py | 15 + .../2226.cpp | 23 + .../2226.java | 20 + .../2226.py | 16 + .../2227-2.cpp | 26 + .../2227-2.java | 23 + .../2227-2.py | 8 + .../2227.cpp | 70 +++ .../2227.java | 68 +++ .../2227. Encrypt and Decrypt Strings/2227.py | 45 ++ .../2228.sql | 9 + .../2229.cpp | 10 + .../2229.java | 8 + .../2229.py | 3 + solutions/223. Rectangle Area/223.cpp | 9 + solutions/223. Rectangle Area/223.java | 7 + solutions/223. Rectangle Area/223.py | 5 + .../2230.sql | 9 + .../2231.cpp | 23 + .../2231.java | 24 + .../2231.py | 17 + .../2232.cpp | 28 + .../2232.java | 26 + .../2232.py | 23 + .../2233.cpp | 24 + .../2233.java | 22 + .../2233.py | 16 + .../2234.cpp | 55 ++ .../2234.java | 49 ++ .../2234.py | 41 ++ solutions/2235. Add Two Integers/2235.cpp | 6 + solutions/2235. Add Two Integers/2235.java | 5 + solutions/2235. Add Two Integers/2235.py | 2 + .../2236.cpp | 6 + .../2236.java | 5 + .../2236. Root Equals Sum of Children/2236.py | 3 + .../2237.cpp | 24 + .../2237.java | 22 + .../2237.py | 16 + .../2238.sql | 11 + .../2239.cpp | 8 + .../2239.java | 16 + .../2239. Find Closest Number to Zero/2239.py | 4 + solutions/224. Basic Calculator/224.cpp | 24 + solutions/224. Basic Calculator/224.java | 25 + solutions/224. Basic Calculator/224.py | 20 + .../2240.cpp | 12 + .../2240.java | 11 + .../2240.py | 5 + .../2241. Design an ATM Machine/2241.cpp | 29 + .../2241. Design an ATM Machine/2241.java | 25 + solutions/2241. Design an ATM Machine/2241.py | 22 + .../2242.cpp | 33 ++ .../2242.java | 36 ++ .../2242.py | 24 + .../2243.cpp | 14 + .../2243.java | 15 + .../2243.py | 11 + .../2244.cpp | 24 + .../2244.java | 23 + .../2244.py | 4 + .../2245.cpp | 66 +++ .../2245.java | 64 +++ .../2245.py | 56 ++ .../2246.cpp | 36 ++ .../2246.java | 37 ++ .../2246.py | 29 + .../2247.cpp | 46 ++ .../2247.java | 49 ++ .../2247.py | 30 + .../2248.cpp | 17 + .../2248.java | 16 + .../2248.py | 10 + .../2249-2.cpp | 22 + .../2249-2.java | 21 + .../2249-2.py | 14 + .../2249.cpp | 15 + .../2249.java | 15 + .../2249.py | 5 + .../225. Implement Stack using Queues/225.cpp | 27 + .../225.java | 21 + .../225. Implement Stack using Queues/225.py | 17 + .../2250.cpp | 25 + .../2250.java | 31 ++ .../2250.py | 19 + .../2251.cpp | 25 + .../2251.java | 49 ++ .../2251.py | 7 + .../2252.sql | 24 + .../2253.sql | 25 + .../2254.cpp | 66 +++ .../2254.java | 59 ++ .../2254.py | 52 ++ .../2255.cpp | 7 + .../2255.java | 5 + .../2255.py | 3 + .../2256. Minimum Average Difference/2256.cpp | 24 + .../2256.java | 23 + .../2256. Minimum Average Difference/2256.py | 19 + .../2257.cpp | 52 ++ .../2257.java | 54 ++ .../2257.py | 50 ++ .../2258. Escape the Spreading Fire/2258.cpp | 97 ++++ .../2258. Escape the Spreading Fire/2258.java | 93 ++++ .../2258. Escape the Spreading Fire/2258.py | 74 +++ .../2259.cpp | 9 + .../2259.java | 8 + .../2259.py | 0 solutions/226. Invert Binary Tree/226.cpp | 13 + solutions/226. Invert Binary Tree/226.java | 12 + solutions/226. Invert Binary Tree/226.py | 10 + .../2260.cpp | 15 + .../2260.java | 14 + .../2260.py | 11 + .../2261.cpp | 29 + .../2261.java | 25 + .../2261.py | 24 + .../2262. Total Appeal of A String/2262-2.cpp | 16 + .../2262-2.java | 16 + .../2262. Total Appeal of A String/2262-2.py | 10 + .../2262. Total Appeal of A String/2262.cpp | 21 + .../2262. Total Appeal of A String/2262.java | 21 + .../2262. Total Appeal of A String/2262.py | 16 + .../2263.cpp | 30 + .../2263.java | 28 + .../2263.py | 15 + .../2264.cpp | 12 + .../2264.java | 12 + .../2264.py | 5 + .../2265.cpp | 21 + .../2265.java | 20 + .../2265.py | 18 + .../2266. Count Number of Texts/2266.cpp | 35 ++ .../2266. Count Number of Texts/2266.java | 33 ++ solutions/2266. Count Number of Texts/2266.py | 28 + .../2267.cpp | 28 + .../2267.java | 24 + .../2267.py | 18 + .../2268.cpp | 17 + .../2268.java | 17 + .../2268.py | 4 + .../2269.cpp | 15 + .../2269.java | 14 + .../2269.py | 11 + solutions/227. Basic Calculator II/227-2.cpp | 29 + solutions/227. Basic Calculator II/227-2.java | 28 + solutions/227. Basic Calculator II/227-2.py | 22 + solutions/227. Basic Calculator II/227.cpp | 60 ++ solutions/227. Basic Calculator II/227.java | 46 ++ solutions/227. Basic Calculator II/227.py | 25 + .../2270.cpp | 17 + .../2270.java | 16 + .../2270.py | 13 + .../2271.cpp | 34 ++ .../2271.java | 35 ++ .../2271.py | 22 + .../2272.cpp | 47 ++ .../2272.java | 45 ++ .../2272.py | 35 ++ .../2273.cpp | 32 ++ .../2273.java | 30 + .../2273.py | 18 + .../2274.cpp | 13 + .../2274.java | 12 + .../2274.py | 10 + .../2275.cpp | 17 + .../2275.java | 16 + .../2275.py | 3 + .../2276.cpp | 30 + .../2276.java | 28 + .../2276. Count Integers in Intervals/2276.py | 25 + .../2277.cpp | 47 ++ .../2277.java | 44 ++ .../2277.py | 27 + .../2278.cpp | 6 + .../2278.java | 5 + .../2278.py | 3 + .../2279.cpp | 21 + .../2279.java | 19 + .../2279.py | 7 + solutions/228. Summary Ranges/228.cpp | 19 + solutions/228. Summary Ranges/228.java | 18 + solutions/228. Summary Ranges/228.py | 17 + .../2280.cpp | 29 + .../2280.java | 31 ++ .../2280.py | 23 + .../2281.cpp | 54 ++ .../2281.java | 53 ++ .../2281.py | 37 ++ .../2282.cpp | 41 ++ .../2282.java | 40 ++ .../2282.py | 32 ++ .../2283.cpp | 15 + .../2283.java | 14 + .../2283.py | 5 + .../2284.cpp | 25 + .../2284.java | 23 + .../2284.py | 18 + .../2285.cpp | 21 + .../2285.java | 20 + .../2285.py | 10 + .../2286.cpp | 128 +++++ .../2287.cpp | 19 + .../2287.java | 18 + .../2287.py | 5 + .../2288. Apply Discount to Prices/2288.cpp | 27 + .../2288. Apply Discount to Prices/2288.java | 24 + .../2288. Apply Discount to Prices/2288.py | 19 + .../2289.cpp | 19 + .../2289.java | 18 + .../2289.py | 15 + solutions/229. Majority Element II/229.cpp | 35 ++ solutions/229. Majority Element II/229.java | 40 ++ solutions/229. Majority Element II/229.py | 23 + .../2290.cpp | 34 ++ .../2290.java | 35 ++ .../2290.py | 24 + .../2291-2.cpp | 14 + .../2291-2.java | 13 + .../2291-2.py | 11 + .../2291.cpp | 19 + .../2291.java | 18 + .../2291.py | 15 + .../2292.sql | 16 + solutions/2293. Min Max Game/2293.cpp | 13 + solutions/2293. Min Max Game/2293.java | 12 + solutions/2293. Min Max Game/2293.py | 10 + .../2294.cpp | 17 + .../2294.java | 16 + .../2294.py | 13 + .../2295.cpp | 20 + .../2295.java | 19 + .../2295.py | 11 + solutions/2296. Design a Text Editor/2296.cpp | 35 ++ .../2296. Design a Text Editor/2296.java | 35 ++ solutions/2296. Design a Text Editor/2296.py | 31 ++ solutions/2297. Jump Game IX/2297.cpp | 23 + solutions/2297. Jump Game IX/2297.java | 23 + solutions/2297. Jump Game IX/2297.py | 18 + .../2298. Tasks Count in the Weekend/2298.sql | 4 + .../2299. Strong Password Checker II/2299.cpp | 33 ++ .../2299.java | 27 + .../2299. Strong Password Checker II/2299.py | 13 + solutions/23. Merge k Sorted Lists/23.cpp | 25 + solutions/23. Merge k Sorted Lists/23.java | 21 + solutions/23. Merge k Sorted Lists/23.py | 21 + .../230-2.cpp | 22 + .../230-2.java | 21 + .../230-2.py | 20 + .../230-3.cpp | 22 + .../230-3.java | 21 + .../230-3.py | 16 + .../230.cpp | 19 + .../230.java | 17 + .../230. Kth Smallest Element in a BST/230.py | 14 + .../2300.cpp | 29 + .../2300.java | 25 + .../2300.py | 17 + .../2301.cpp | 34 ++ .../2301.java | 31 ++ .../2301.py | 24 + .../2302.cpp | 16 + .../2302.java | 15 + .../2302.py | 14 + .../2303.cpp | 18 + .../2303.java | 17 + .../2303.py | 12 + .../2304.cpp | 18 + .../2304.java | 17 + .../2304. Minimum Path Cost in a Grid/2304.py | 15 + .../2305.cpp | 23 + .../2305.java | 21 + .../2305.py | 17 + solutions/2306. Naming a Company/2306.cpp | 23 + solutions/2306. Naming a Company/2306.java | 25 + solutions/2306. Naming a Company/2306.py | 16 + .../2307.cpp | 47 ++ .../2307.java | 45 ++ .../2307.py | 30 + .../2308. Arrange Table by Gender/2308.sql | 9 + .../2309.cpp | 15 + .../2309.java | 14 + .../2309.py | 10 + solutions/231. Power of Two/231.cpp | 6 + solutions/231. Power of Two/231.java | 5 + solutions/231. Power of Two/231.py | 3 + .../2310.cpp | 17 + .../2310.java | 16 + .../2310.py | 16 + .../2311.cpp | 19 + .../2311.java | 18 + .../2311.py | 16 + .../2312. Selling Pieces of Wood/2312.cpp | 24 + .../2312. Selling Pieces of Wood/2312.java | 23 + .../2312. Selling Pieces of Wood/2312.py | 16 + .../2313.cpp | 43 ++ .../2313.py | 19 + .../2314.sql | 13 + solutions/2315. Count Asterisks/2315.cpp | 16 + solutions/2315. Count Asterisks/2315.java | 15 + solutions/2315. Count Asterisks/2315.py | 12 + .../2316.cpp | 33 ++ .../2316.java | 36 ++ .../2316.py | 27 + .../2317.cpp | 15 + .../2317.java | 14 + .../2317.py | 12 + .../2318.cpp | 30 + .../2318.java | 29 + .../2318.py | 21 + .../2319.cpp | 17 + .../2319.java | 16 + .../2319. Check if Matrix Is X-Matrix/2319.py | 13 + .../232. Implement Queue using Stacks/232.cpp | 28 + .../232.java | 24 + .../232. Implement Queue using Stacks/232.py | 20 + .../2320.cpp | 17 + .../2320.java | 16 + .../2320.py | 13 + .../2321.cpp | 21 + .../2321.java | 18 + .../2321.py | 17 + .../2322.cpp | 61 +++ .../2322.java | 78 +++ .../2322.py | 42 ++ .../2323.cpp | 14 + .../2323.java | 13 + .../2323.py | 11 + .../2324. Product Sales Analysis IV/2324.sql | 17 + solutions/2325. Decode the Message/2325.cpp | 16 + solutions/2325. Decode the Message/2325.java | 17 + solutions/2325. Decode the Message/2325.py | 11 + solutions/2326. Spiral Matrix IV/2326.cpp | 21 + solutions/2326. Spiral Matrix IV/2326.java | 21 + solutions/2326. Spiral Matrix IV/2326.py | 19 + .../2327.cpp | 25 + .../2327.java | 25 + .../2327.py | 19 + .../2328.cpp | 43 ++ .../2328.java | 40 ++ .../2328.py | 25 + .../2329. Product Sales Analysis V/2329.sql | 8 + solutions/233. Number of Digit One/233.cpp | 18 + solutions/233. Number of Digit One/233.java | 17 + solutions/233. Number of Digit One/233.py | 16 + solutions/2330. Valid Palindrome IV/2330.cpp | 17 + solutions/2330. Valid Palindrome IV/2330.java | 16 + solutions/2330. Valid Palindrome IV/2330.py | 15 + .../2331.cpp | 11 + .../2331.java | 10 + .../2331.py | 8 + .../2332.cpp | 34 ++ .../2332.java | 31 ++ .../2332.py | 27 + .../2333.cpp | 54 ++ .../2333.java | 55 ++ .../2334.cpp | 32 ++ .../2334.java | 34 ++ .../2334.py | 25 + .../2335.cpp | 8 + .../2335.java | 7 + .../2335.py | 3 + .../2336.cpp | 19 + .../2336.java | 17 + .../2337.cpp | 27 + .../2337.java | 26 + .../2337.py | 23 + .../2338.cpp | 63 +++ .../2339.sql | 6 + solutions/234. Palindrome Linked List/234.cpp | 39 ++ .../234. Palindrome Linked List/234.java | 37 ++ solutions/234. Palindrome Linked List/234.py | 32 ++ .../2340.cpp | 32 ++ .../2340.java | 30 + .../2340.py | 24 + .../2341.cpp | 18 + .../2341.java | 18 + .../2341.py | 10 + .../2342.cpp | 30 + .../2342.java | 31 ++ .../2342.py | 19 + .../2343.cpp | 24 + .../2344.cpp | 22 + .../2344.java | 24 + .../2344.py | 9 + .../2345-2.cpp | 26 + .../2345.cpp | 45 ++ .../2345.java | 39 ++ .../2345.py | 20 + .../2346.sql | 11 + solutions/2347. Best Poker Hand/2347.cpp | 21 + solutions/2347. Best Poker Hand/2347.java | 19 + solutions/2347. Best Poker Hand/2347.py | 12 + .../2348.cpp | 15 + .../2348.java | 14 + .../2348.py | 12 + .../2349.cpp | 26 + .../2349.java | 22 + .../2349.py | 21 + .../235.cpp | 10 + .../235.java | 9 + .../235.py | 7 + .../2350.cpp | 19 + .../2350.java | 18 + .../2350.py | 14 + .../2351.cpp | 14 + .../2351.java | 13 + .../2351.py | 8 + .../2352. Equal Row and Column Pairs/2352.cpp | 19 + .../2352.java | 18 + .../2352. Equal Row and Column Pairs/2352.py | 16 + .../2353.cpp | 30 + .../2353.java | 32 ++ .../2353. Design a Food Rating System/2353.py | 25 + .../2354. Number of Excellent Pairs/2354.cpp | 19 + .../2354. Number of Excellent Pairs/2354.java | 18 + .../2354. Number of Excellent Pairs/2354.py | 7 + .../2355.cpp | 30 + .../2355.java | 28 + .../2355.py | 25 + .../2356.sql | 5 + .../2357.cpp | 7 + .../2357.java | 6 + .../2357.py | 3 + .../2358.cpp | 17 + .../2358.java | 16 + .../2358.py | 14 + .../2359.cpp | 32 ++ .../2359.java | 31 ++ .../2359.py | 25 + .../236-2.cpp | 33 ++ .../236-2.java | 33 ++ .../236-2.py | 26 + .../236.cpp | 12 + .../236.java | 11 + .../236.py | 9 + .../2360. Longest Cycle in a Graph/2360.cpp | 23 + .../2360. Longest Cycle in a Graph/2360.java | 22 + .../2360. Longest Cycle in a Graph/2360.py | 19 + .../2361.cpp | 22 + .../2361.java | 20 + .../2361.py | 17 + solutions/2362. Generate the Invoice/2362.sql | 21 + solutions/2363. Merge Similar Items/2363.cpp | 21 + solutions/2363. Merge Similar Items/2363.java | 19 + solutions/2363. Merge Similar Items/2363.py | 3 + .../2364. Count Number of Bad Pairs/2364.cpp | 14 + .../2364. Count Number of Bad Pairs/2364.java | 15 + .../2364. Count Number of Bad Pairs/2364.py | 12 + solutions/2365. Task Scheduler II/2365.cpp | 14 + solutions/2365. Task Scheduler II/2365.java | 13 + solutions/2365. Task Scheduler II/2365.py | 10 + .../2366.cpp | 15 + .../2366.java | 14 + .../2366.py | 11 + .../2367.cpp | 16 + .../2367.java | 15 + .../2367.py | 12 + .../2368.cpp | 34 ++ .../2368.java | 34 ++ .../2368.py | 16 + .../2369.cpp | 19 + .../2369.java | 16 + .../2369.py | 14 + .../237. Delete Node in a Linked List/237.cpp | 7 + .../237.java | 6 + .../237. Delete Node in a Linked List/237.py | 4 + .../2370. Longest Ideal Subsequence/2370.cpp | 24 + .../2370. Longest Ideal Subsequence/2370.java | 22 + .../2370. Longest Ideal Subsequence/2370.py | 18 + .../2371.cpp | 26 + .../2371.java | 32 ++ .../2371.py | 22 + .../2372.sql | 10 + .../2373.cpp | 15 + .../2373.java | 14 + .../2373.py | 12 + .../2374.cpp | 9 + .../2374.java | 15 + .../2374.py | 6 + .../2375.cpp | 22 + .../2375.java | 21 + .../2375.py | 17 + .../2376. Count Special Integers/2376.cpp | 39 ++ .../2376. Count Special Integers/2376.java | 35 ++ .../2376. Count Special Integers/2376.py | 32 ++ .../2377. Sort the Olympic Table/2377.sql | 11 + .../2378.cpp | 33 ++ .../2378.java | 40 ++ .../2378.py | 26 + .../2379.cpp | 17 + .../2379.java | 16 + .../2379.py | 13 + .../238-2.cpp | 19 + .../238-2.java | 19 + .../238-2.py | 15 + .../238. Product of Array Except Self/238.cpp | 20 + .../238.java | 21 + .../238. Product of Array Except Self/238.py | 13 + .../2380.cpp | 15 + .../2380.java | 14 + .../2380.py | 12 + solutions/2381. Shifting Letters II/2381.cpp | 24 + solutions/2381. Shifting Letters II/2381.java | 24 + solutions/2381. Shifting Letters II/2381.py | 17 + .../2382.cpp | 39 ++ .../2382.java | 37 ++ .../2382.py | 34 ++ .../2383.cpp | 27 + .../2383.java | 23 + .../2383.py | 16 + .../2384. Largest Palindromic Number/2384.cpp | 44 ++ .../2384.java | 44 ++ .../2384. Largest Palindromic Number/2384.py | 12 + .../2385.cpp | 47 ++ .../2385.java | 48 ++ .../2385.py | 36 ++ .../2386. Find the K-Sum of an Array/2386.cpp | 41 ++ .../2386.java | 39 ++ .../2386. Find the K-Sum of an Array/2386.py | 17 + .../2387.cpp | 26 + .../2387.java | 37 ++ .../2387.py | 15 + .../2388.sql | 20 + .../2389.cpp | 24 + .../2389.java | 22 + .../2389.py | 13 + solutions/239. Sliding Window Maximum/239.cpp | 19 + .../239. Sliding Window Maximum/239.java | 18 + solutions/239. Sliding Window Maximum/239.py | 15 + .../2390.cpp | 12 + .../2390.java | 11 + .../2390.py | 9 + .../2391.cpp | 25 + .../2391.java | 24 + .../2391.py | 14 + .../2392.cpp | 59 ++ .../2392.java | 58 ++ .../2392.py | 44 ++ .../2393.cpp | 14 + .../2393.java | 13 + .../2393.py | 11 + .../2394. Employees With Deductions/2394.sql | 15 + .../2395.cpp | 12 + .../2395.java | 14 + .../2395.py | 11 + .../2396.cpp | 6 + .../2396.java | 5 + .../2396. Strictly Palindromic Number/2396.py | 3 + .../2397.cpp | 40 ++ .../2397.java | 38 ++ .../2397.py | 32 ++ .../2398.cpp | 23 + .../2398.java | 22 + .../2398.py | 18 + .../2399.cpp | 16 + .../2399.java | 16 + .../2399.py | 12 + solutions/24. Swap Nodes in Pairs/24.cpp | 28 + solutions/24. Swap Nodes in Pairs/24.java | 26 + solutions/24. Swap Nodes in Pairs/24.py | 23 + solutions/240. Search a 2D Matrix II/240.cpp | 18 + solutions/240. Search a 2D Matrix II/240.java | 17 + solutions/240. Search a 2D Matrix II/240.py | 14 + .../2400.cpp | 35 ++ .../2400.java | 32 ++ .../2400.py | 27 + .../2401. Longest Nice Subarray/2401.cpp | 16 + .../2401. Longest Nice Subarray/2401.java | 15 + solutions/2401. Longest Nice Subarray/2401.py | 14 + solutions/2402. Meeting Rooms III/2402.cpp | 45 ++ solutions/2402. Meeting Rooms III/2402.java | 49 ++ solutions/2402. Meeting Rooms III/2402.py | 25 + .../2403.cpp | 23 + .../2403.java | 21 + .../2403.py | 17 + .../2404. Most Frequent Even Element/2404.cpp | 18 + .../2404.java | 17 + .../2404. Most Frequent Even Element/2404.py | 15 + .../2405.cpp | 19 + .../2405.java | 18 + .../2405. Optimal Partition of String/2405.py | 14 + .../2406.cpp | 18 + .../2406.java | 17 + .../2406.py | 12 + .../2407.cpp | 89 +++ solutions/2408. Design SQL/2408.cpp | 15 + solutions/2408. Design SQL/2408.java | 16 + solutions/2408. Design SQL/2408.py | 12 + .../2409. Count Days Spent Together/2409.cpp | 29 + .../2409. Count Days Spent Together/2409.java | 27 + .../2409. Count Days Spent Together/2409.py | 23 + .../241.cpp | 27 + .../241.java | 30 + .../241.py | 12 + .../2410.cpp | 15 + .../2410.java | 14 + .../2410.py | 16 + .../2411.cpp | 18 + .../2411.java | 19 + .../2411.py | 14 + .../2412.cpp | 31 ++ .../2412.java | 30 + .../2412.py | 22 + .../2413. Smallest Even Multiple/2413.cpp | 6 + .../2413. Smallest Even Multiple/2413.java | 5 + .../2413. Smallest Even Multiple/2413.py | 3 + .../2414.cpp | 15 + .../2414.java | 14 + .../2414.py | 13 + .../2415.cpp | 17 + .../2415.java | 18 + .../2415.py | 12 + .../2416.cpp | 44 ++ .../2416.java | 41 ++ .../2416.py | 28 + solutions/2417. Closest Fair Integer/2417.cpp | 30 + .../2417. Closest Fair Integer/2417.java | 28 + solutions/2417. Closest Fair Integer/2417.py | 24 + solutions/2418. Sort the People/2418.cpp | 17 + solutions/2418. Sort the People/2418.java | 15 + solutions/2418. Sort the People/2418.py | 4 + .../2419.cpp | 21 + .../2419.java | 20 + .../2419.py | 18 + solutions/242. Valid Anagram/242.cpp | 20 + solutions/242. Valid Anagram/242.java | 19 + solutions/242. Valid Anagram/242.py | 8 + .../2420. Find All Good Indices/2420.cpp | 26 + .../2420. Find All Good Indices/2420.java | 28 + solutions/2420. Find All Good Indices/2420.py | 17 + solutions/2421. Number of Good Paths/2421.cpp | 66 +++ .../2421. Number of Good Paths/2421.java | 73 +++ .../2422.cpp | 24 + .../2422.java | 23 + .../2422.py | 24 + .../2423.cpp | 34 ++ .../2423.java | 32 ++ .../2423.py | 15 + .../2424. Longest Uploaded Prefix/2424.cpp | 18 + .../2424. Longest Uploaded Prefix/2424.java | 16 + .../2424. Longest Uploaded Prefix/2424.py | 12 + .../2425.cpp | 10 + .../2425.java | 9 + .../2425. Bitwise XOR of All Pairings/2425.py | 7 + .../2426.cpp | 60 ++ .../2427. Number of Common Factors/2427.cpp | 11 + .../2427. Number of Common Factors/2427.java | 14 + .../2427. Number of Common Factors/2427.py | 6 + .../2428.cpp | 15 + .../2428.java | 12 + .../2428. Maximum Sum of an Hourglass/2428.py | 6 + solutions/2429. Minimize XOR/2429.cpp | 30 + solutions/2429. Minimize XOR/2429.java | 29 + solutions/2429. Minimize XOR/2429.py | 27 + solutions/243. Shortest Word Distance/243.cpp | 23 + .../243. Shortest Word Distance/243.java | 22 + solutions/243. Shortest Word Distance/243.py | 17 + .../2430.cpp | 20 + .../2430.java | 20 + .../2430.py | 16 + .../2431-2.cpp | 21 + .../2431-2.java | 17 + .../2431-2.py | 13 + .../2431.cpp | 38 ++ .../2431.java | 33 ++ .../2431.py | 31 ++ .../2432.cpp | 20 + .../2432.java | 19 + .../2432.py | 14 + .../2433.cpp | 12 + .../2433.java | 11 + .../2433.py | 9 + .../2434.cpp | 32 ++ .../2434.java | 30 + .../2434.py | 20 + .../2435-2.cpp | 24 + .../2435-2.java | 23 + .../2435-2.py | 20 + .../2435.cpp | 26 + .../2435.java | 22 + .../2435.py | 19 + .../2436.cpp | 19 + .../2436.java | 22 + .../2436.py | 14 + .../2437.cpp | 18 + .../2437.java | 17 + .../2437. Number of Valid Clock Times/2437.py | 15 + .../2438.cpp | 26 + .../2438.java | 25 + .../2438.py | 15 + .../2439. Minimize Maximum of Array/2439.cpp | 15 + .../2439. Minimize Maximum of Array/2439.java | 14 + .../2439. Minimize Maximum of Array/2439.py | 11 + .../244. Shortest Word Distance II/244.cpp | 26 + .../244. Shortest Word Distance II/244.java | 26 + .../244. Shortest Word Distance II/244.py | 21 + .../2440.cpp | 46 ++ .../2440.java | 45 ++ .../2440.py | 37 ++ .../2441.cpp | 15 + .../2441.java | 14 + .../2441.py | 12 + .../2442.cpp | 21 + .../2443.cpp | 19 + .../2444.cpp | 23 + .../2444.java | 22 + .../2444.py | 19 + .../2445.cpp | 23 + .../2445.java | 21 + .../2445.py | 16 + .../2446.cpp | 6 + .../2446.java | 5 + .../2446.py | 0 .../2447.cpp | 21 + .../2447.java | 28 + .../2447.py | 18 + .../2448.cpp | 29 + .../2448.java | 27 + .../2448.py | 20 + .../2449.cpp | 25 + .../2449.java | 26 + .../2449.py | 5 + .../245. Shortest Word Distance III/245.cpp | 24 + .../245. Shortest Word Distance III/245.java | 21 + .../245. Shortest Word Distance III/245.py | 19 + .../2450.cpp | 19 + .../2450.java | 17 + .../2450.py | 5 + .../2451. Odd String Difference/2451.cpp | 36 ++ .../2451. Odd String Difference/2451.java | 33 ++ solutions/2451. Odd String Difference/2451.py | 14 + .../2452.cpp | 17 + .../2452.java | 22 + .../2452.py | 5 + .../2453-2.cpp | 15 + .../2453. Destroy Sequential Targets/2453.cpp | 17 + .../2453.java | 16 + .../2453. Destroy Sequential Targets/2453.py | 5 + .../2454. Next Greater Element IV/2454.cpp | 27 + .../2454. Next Greater Element IV/2454.java | 27 + .../2454. Next Greater Element IV/2454.py | 23 + .../2455.cpp | 15 + .../2455.java | 14 + .../2455.py | 11 + .../2456. Most Popular Video Creator/2456.cpp | 42 ++ .../2456.java | 40 ++ .../2456. Most Popular Video Creator/2456.py | 31 ++ .../2457.cpp | 28 + .../2457.java | 26 + .../2457.py | 14 + .../2458.cpp | 37 ++ .../2458.java | 36 ++ .../2458.py | 21 + .../2459.py | 33 ++ solutions/246. Strobogrammatic Number/246.cpp | 15 + .../246. Strobogrammatic Number/246.java | 13 + solutions/246. Strobogrammatic Number/246.py | 15 + .../2460-2.cpp | 14 + .../2460-2.java | 20 + .../2460-2.py | 11 + .../2460.cpp | 19 + .../2460.java | 18 + .../2460.py | 16 + .../2461.cpp | 24 + .../2461.java | 23 + .../2461.py | 21 + .../2462.cpp | 28 + .../2462.java | 27 + .../2462.py | 26 + .../2463.cpp | 35 ++ .../2463.java | 25 + .../2463.py | 22 + .../2464.cpp | 15 + .../2464.java | 20 + .../2464.py | 11 + .../2465.cpp | 14 + .../2465.java | 13 + .../2465. Number of Distinct Averages/2465.py | 11 + .../2466.cpp | 21 + .../2466.java | 20 + .../2466.py | 16 + .../2467.cpp | 57 ++ .../2467.java | 56 ++ .../2467.py | 48 ++ .../2468.cpp | 36 ++ .../2468.java | 34 ++ .../2468.py | 31 ++ .../2469. Convert the Temperature/2469.cpp | 6 + .../2469. Convert the Temperature/2469.java | 5 + .../2469. Convert the Temperature/2469.py | 3 + .../247. Strobogrammatic Number II/247.cpp | 27 + .../247. Strobogrammatic Number II/247.java | 25 + .../247. Strobogrammatic Number II/247.py | 21 + .../2470.cpp | 19 + .../2470.java | 26 + .../2470.py | 13 + .../2471.cpp | 32 ++ .../2471.java | 37 ++ .../2471.py | 28 + .../2472.cpp | 36 ++ .../2472.java | 34 ++ .../2472.py | 32 ++ .../2473. Minimum Cost to Buy Apples/2473.cpp | 46 ++ .../2473.java | 48 ++ .../2473. Minimum Cost to Buy Apples/2473.py | 28 + .../2474.sql | 18 + .../2475.cpp | 37 ++ .../2475.java | 36 ++ .../2475.py | 29 + .../2476.cpp | 32 ++ .../2476.java | 35 ++ .../2476.py | 23 + .../2477.cpp | 32 ++ .../2477.java | 33 ++ .../2477.py | 23 + .../2478.cpp | 36 ++ .../2478.java | 33 ++ .../2478.py | 31 ++ .../2479.cpp | 93 ++++ .../2479.java | 98 ++++ .../2479.py | 71 +++ .../248. Strobogrammatic Number III/248.cpp | 39 ++ .../248. Strobogrammatic Number III/248.java | 37 ++ .../248. Strobogrammatic Number III/248.py | 28 + solutions/2480. Form a Chemical Bond/2480.sql | 7 + .../2481.cpp | 8 + .../2481.java | 7 + .../2481.py | 5 + .../2482.cpp | 27 + .../2482.java | 25 + .../2482.py | 14 + .../2483. Minimum Penalty for a Shop/2483.cpp | 20 + .../2483.java | 18 + .../2483. Minimum Penalty for a Shop/2483.py | 14 + .../2484.cpp | 25 + .../2484.java | 24 + .../2484.py | 19 + .../2485. Find the Pivot Integer/2485.cpp | 13 + .../2485. Find the Pivot Integer/2485.java | 12 + .../2485. Find the Pivot Integer/2485.py | 10 + .../2486.cpp | 13 + .../2486.java | 12 + .../2486.py | 11 + .../2487.cpp | 10 + .../2487.java | 8 + .../2487.py | 6 + .../2488.cpp | 28 + .../2488.java | 34 ++ .../2488.py | 25 + .../2489.cpp | 25 + .../2489.java | 25 + .../2489.py | 21 + solutions/249. Group Shifted Strings/249.cpp | 29 + solutions/249. Group Shifted Strings/249.java | 23 + solutions/249. Group Shifted Strings/249.py | 21 + solutions/2490. Circular Sentence/2490.cpp | 9 + solutions/2490. Circular Sentence/2490.java | 8 + solutions/2490. Circular Sentence/2490.py | 6 + .../2491.cpp | 22 + .../2491.java | 22 + .../2491.py | 14 + .../2492.cpp | 32 ++ .../2492.java | 35 ++ .../2492.py | 21 + .../2493.cpp | 87 +++ .../2494.sql | 33 ++ .../2495.cpp | 19 + .../2495.java | 18 + .../2495.py | 15 + .../2496.cpp | 11 + .../2496.java | 9 + .../2496.py | 4 + .../2497.cpp | 28 + .../2497.java | 32 ++ .../2497. Maximum Star Sum of a Graph/2497.py | 22 + solutions/2498. Frog Jump II/2498.cpp | 12 + solutions/2498. Frog Jump II/2498.java | 11 + solutions/2498. Frog Jump II/2498.py | 9 + .../2499.cpp | 43 ++ .../2499.java | 42 ++ .../2499.py | 38 ++ .../25. Reverse Nodes in k-Group/25-2.cpp | 33 ++ .../25. Reverse Nodes in k-Group/25-2.java | 31 ++ .../25. Reverse Nodes in k-Group/25-2.py | 27 + solutions/25. Reverse Nodes in k-Group/25.cpp | 34 ++ .../25. Reverse Nodes in k-Group/25.java | 32 ++ solutions/25. Reverse Nodes in k-Group/25.py | 27 + .../250. Count Univalue Subtrees/250.cpp | 22 + .../250. Count Univalue Subtrees/250.java | 20 + solutions/250. Count Univalue Subtrees/250.py | 17 + .../2500.cpp | 18 + .../2500.java | 17 + .../2500.py | 5 + .../2501.cpp | 21 + .../2502. Design Memory Allocator/2502.cpp | 32 ++ .../2502. Design Memory Allocator/2502.java | 35 ++ .../2502. Design Memory Allocator/2502.py | 23 + .../2503.cpp | 67 +++ .../2503.java | 65 +++ .../2503.py | 43 ++ .../2504.sql | 5 + .../2505.cpp | 14 + .../2505.java | 13 + .../2505.py | 10 + .../2506-2.py | 5 + .../2506.cpp | 25 + .../2506.java | 23 + .../2506.py | 18 + .../2507.cpp | 22 + .../2507.java | 20 + .../2507.py | 15 + .../2508.cpp | 44 ++ .../2508.java | 45 ++ .../2508.py | 21 + .../2509.cpp | 21 + .../2509.java | 20 + .../2509.py | 13 + solutions/251. Flatten 2D Vector/251-2.cpp | 27 + solutions/251. Flatten 2D Vector/251.cpp | 20 + solutions/251. Flatten 2D Vector/251.java | 18 + solutions/251. Flatten 2D Vector/251.py | 15 + .../2510.cpp | 31 ++ .../2510.java | 28 + .../2510.py | 21 + .../2511.cpp | 15 + .../2511.java | 14 + .../2511.py | 12 + .../2512. Reward Top K Students/2512.cpp | 33 ++ .../2512. Reward Top K Students/2512.java | 29 + solutions/2512. Reward Top K Students/2512.py | 16 + .../2513.cpp | 30 + .../2513.java | 35 ++ .../2513.py | 23 + solutions/2514. Count Anagrams/2514.cpp | 38 ++ solutions/2514. Count Anagrams/2514.java | 37 ++ solutions/2514. Count Anagrams/2514.py | 11 + .../2515.cpp | 15 + .../2515.java | 14 + .../2515.py | 11 + .../2516.cpp | 23 + .../2516.java | 22 + .../2516.py | 17 + .../2517.cpp | 32 ++ .../2517.java | 30 + .../2517.py | 17 + .../2518. Number of Great Partitions/2518.cpp | 35 ++ .../2518.java | 31 ++ .../2518. Number of Great Partitions/2518.py | 20 + .../2519.cpp | 57 ++ .../2519.java | 56 ++ .../2519.py | 40 ++ solutions/252. Meeting Rooms/252.cpp | 12 + solutions/252. Meeting Rooms/252.java | 11 + solutions/252. Meeting Rooms/252.py | 9 + .../2520.cpp | 12 + .../2520.java | 11 + .../2520.py | 3 + .../2521.cpp | 21 + .../2521.java | 19 + .../2521.py | 15 + .../2522.cpp | 19 + .../2522.java | 18 + .../2522.py | 14 + .../2523.cpp | 41 ++ .../2523.java | 40 ++ .../2523.py | 30 + .../2524.cpp | 50 ++ .../2524.java | 51 ++ .../2524.py | 33 ++ .../2525.cpp | 16 + .../2525.java | 14 + .../2525.py | 12 + .../2526.cpp | 22 + .../2526.java | 20 + .../2526.py | 14 + .../2527. Find Xor-Beauty of Array/2527.cpp | 6 + .../2527. Find Xor-Beauty of Array/2527.java | 5 + .../2527. Find Xor-Beauty of Array/2527.py | 3 + .../2528.cpp | 46 ++ .../2528.java | 46 ++ .../2528.py | 37 ++ .../2529.cpp | 7 + .../2529.java | 6 + .../2529.py | 3 + solutions/253. Meeting Rooms II/253-2.cpp | 25 + solutions/253. Meeting Rooms II/253-2.java | 25 + solutions/253. Meeting Rooms II/253-2.py | 22 + solutions/253. Meeting Rooms II/253.cpp | 18 + solutions/253. Meeting Rooms II/253.java | 17 + solutions/253. Meeting Rooms II/253.py | 11 + .../2530.cpp | 19 + .../2530.java | 17 + .../2530.py | 12 + .../2531.cpp | 44 ++ .../2531.java | 42 ++ .../2531.py | 23 + .../2532. Time to Cross a Bridge/2532.cpp | 62 +++ .../2532. Time to Cross a Bridge/2532.java | 68 +++ .../2532. Time to Cross a Bridge/2532.py | 46 ++ .../2533.cpp | 28 + .../2533.java | 31 ++ .../2533.py | 20 + .../2534.cpp | 36 ++ .../2535.cpp | 25 + .../2535.java | 23 + .../2535.py | 11 + .../2536.cpp | 28 + .../2537.cpp | 21 + .../2538.cpp | 62 +++ .../2538.java | 62 +++ .../2538.py | 50 ++ .../2539.cpp | 65 +++ .../2539.java | 65 +++ .../2539.py | 27 + solutions/254. Factor Combinations/254.cpp | 24 + solutions/254. Factor Combinations/254.java | 22 + solutions/254. Factor Combinations/254.py | 18 + solutions/2540. Minimum Common Value/2540.cpp | 18 + .../2540. Minimum Common Value/2540.java | 17 + solutions/2540. Minimum Common Value/2540.py | 14 + .../2541.cpp | 24 + .../2541.java | 22 + .../2541.py | 19 + .../2542. Maximum Subsequence Score/2542.cpp | 27 + .../2542. Maximum Subsequence Score/2542.java | 28 + .../2542. Maximum Subsequence Score/2542.py | 19 + .../2543.cpp | 6 + .../2543.java | 9 + .../2543. Check if Point Is Reachable/2543.py | 3 + .../2544. Alternating Digit Sum/2544.cpp | 14 + .../2544. Alternating Digit Sum/2544.java | 13 + solutions/2544. Alternating Digit Sum/2544.py | 11 + .../2545.cpp | 9 + .../2545.java | 6 + .../2545.py | 3 + .../2546.cpp | 6 + .../2546.java | 5 + .../2546.py | 3 + .../2547.cpp | 31 ++ .../2547.java | 31 ++ .../2547.py | 27 + .../2548.cpp | 24 + .../2548.java | 25 + .../2548. Maximum Price to Fill a Bag/2548.py | 13 + .../2549.cpp | 6 + .../2549.java | 5 + .../2549.py | 3 + .../255-2.cpp | 17 + .../255-2.java | 16 + .../255-2.py | 13 + .../255-3.cpp | 17 + .../255-3.java | 16 + .../255-3.py | 15 + .../255.cpp | 20 + .../255.java | 19 + .../255.py | 18 + .../2550.cpp | 18 + .../2550.java | 16 + .../2550.py | 5 + solutions/2551. Put Marbles in Bags/2551.cpp | 25 + solutions/2551. Put Marbles in Bags/2551.java | 24 + solutions/2551. Put Marbles in Bags/2551.py | 11 + .../2552.cpp | 25 + .../2552.java | 23 + .../2552.py | 21 + .../2553.cpp | 12 + .../2553.java | 11 + .../2553.py | 3 + .../2554.cpp | 16 + .../2554.java | 15 + .../2554.py | 12 + .../2555.cpp | 19 + .../2555.java | 18 + .../2555.py | 16 + .../2556.cpp | 26 + .../2556.java | 24 + .../2556.py | 21 + .../2557.cpp | 28 + .../2557.java | 30 + .../2557.py | 18 + .../2558.cpp | 21 + .../2558.java | 19 + .../2558.py | 10 + .../2559.cpp | 31 ++ .../2559.java | 26 + .../2559.py | 11 + solutions/256. Paint House/256.cpp | 12 + solutions/256. Paint House/256.java | 13 + solutions/256. Paint House/256.py | 8 + solutions/2560. House Robber IV/2560.cpp | 28 + solutions/2560. House Robber IV/2560.java | 26 + solutions/2560. House Robber IV/2560.py | 14 + solutions/2561. Rearranging Fruits/2561.cpp | 28 + solutions/2561. Rearranging Fruits/2561.java | 30 + solutions/2561. Rearranging Fruits/2561.py | 18 + .../2562.cpp | 14 + .../2563.cpp | 20 + .../2563.java | 18 + .../2563.py | 18 + .../2564. Substring XOR Queries/2564.cpp | 41 ++ .../2564. Substring XOR Queries/2564.java | 40 ++ solutions/2564. Substring XOR Queries/2564.py | 20 + .../2565.py | 46 ++ .../2566.cpp | 31 ++ .../2566.java | 29 + .../2566.py | 12 + .../2567.cpp | 14 + .../2567.java | 13 + .../2567.py | 10 + .../2568. Minimum Impossible OR/2568.cpp | 12 + .../2568. Minimum Impossible OR/2568.java | 11 + solutions/2568. Minimum Impossible OR/2568.py | 9 + .../2569.cpp | 84 +++ solutions/257. Binary Tree Paths/257.cpp | 30 + solutions/257. Binary Tree Paths/257.java | 22 + solutions/257. Binary Tree Paths/257.py | 18 + .../2570.cpp | 27 + .../2570.java | 24 + .../2570.py | 10 + .../2571.cpp | 33 ++ .../2571.java | 32 ++ .../2571.py | 29 + .../2572.cpp | 52 ++ .../2572.java | 47 ++ .../2572.py | 36 ++ .../2573. Find the String with LCP/2573.cpp | 34 ++ .../2574-2.cpp | 16 + .../2574-2.java | 15 + .../2574-2.py | 12 + .../2574.cpp | 28 + .../2574.java | 27 + .../2574.py | 19 + .../2575.cpp | 15 + .../2575.java | 14 + .../2575.py | 11 + .../2576-2.cpp | 13 + .../2576-2.java | 12 + .../2576-2.py | 12 + .../2576.cpp | 27 + .../2576.java | 25 + .../2576.py | 13 + .../2577.cpp | 38 ++ .../2577.java | 38 ++ .../2577.py | 26 + .../2578. Split With Minimum Sum/2578.cpp | 18 + .../2578. Split With Minimum Sum/2578.java | 17 + .../2578. Split With Minimum Sum/2578.py | 4 + .../2579.cpp | 6 + .../2579.java | 5 + .../2579.py | 3 + solutions/258. Add Digits/258.cpp | 6 + solutions/258. Add Digits/258.java | 5 + solutions/258. Add Digits/258.py | 3 + .../2580.cpp | 20 + .../2580.java | 19 + .../2580.py | 12 + .../2581.cpp | 65 +++ .../2581.java | 66 +++ .../2581.py | 46 ++ solutions/2582. Pass the Pillow/2582.cpp | 10 + solutions/2582. Pass the Pillow/2582.java | 9 + solutions/2582. Pass the Pillow/2582.py | 7 + .../2583.cpp | 24 + .../2583.java | 21 + .../2583.py | 18 + .../2584.cpp | 45 ++ .../2584.java | 44 ++ .../2584.py | 37 ++ .../2585-2.cpp | 22 + .../2585-2.java | 21 + .../2585-2.py | 14 + .../2585.cpp | 22 + .../2585.java | 21 + .../2585.py | 17 + .../2586.cpp | 15 + .../2586.java | 13 + .../2586.py | 5 + .../2587.cpp | 16 + .../2587.java | 19 + .../2587.py | 4 + .../2588.cpp | 16 + .../2588.java | 17 + .../2588.py | 13 + .../2589.cpp | 30 + .../2589.java | 32 ++ .../2589.py | 19 + solutions/259. 3Sum Smaller/259.cpp | 29 + solutions/259. 3Sum Smaller/259.java | 28 + solutions/259. 3Sum Smaller/259.py | 24 + solutions/2590. Design a Todo List/2590.cpp | 66 +++ solutions/2590. Design a Todo List/2590.java | 49 ++ solutions/2590. Design a Todo List/2590.py | 47 ++ .../2591.cpp | 25 + .../2591.java | 24 + .../2591.py | 22 + .../2592.cpp | 14 + .../2592.java | 13 + .../2592.py | 11 + .../2593.cpp | 24 + .../2593.java | 28 + .../2593.py | 14 + .../2594.cpp | 27 + .../2594.java | 25 + .../2594. Minimum Time to Repair Cars/2594.py | 10 + .../2595.cpp | 15 + .../2595.java | 14 + .../2595. Number of Even and Odd Bits/2595.py | 11 + .../2596.cpp | 38 ++ .../2596.java | 37 ++ .../2596.py | 30 + .../2597.cpp | 59 ++ .../2597.java | 58 ++ .../2597.py | 50 ++ .../2598.cpp | 15 + .../2598.java | 16 + .../2598.py | 10 + .../2599.cpp | 20 + .../2599.java | 19 + .../2599.py | 15 + .../26.cpp | 12 + .../26.java | 11 + .../26.py | 10 + solutions/260. Single Number III/260.cpp | 17 + solutions/260. Single Number III/260.java | 16 + solutions/260. Single Number III/260.py | 14 + .../2600.cpp | 10 + .../2600.java | 9 + .../2600.py | 7 + .../2601.cpp | 35 ++ .../2601.java | 40 ++ .../2601. Prime Subtraction Operation/2601.py | 26 + .../2602.cpp | 25 + .../2602.java | 27 + .../2602.py | 9 + .../2603. Collect Coins in a Tree/2603.cpp | 50 ++ .../2603. Collect Coins in a Tree/2603.java | 48 ++ .../2603. Collect Coins in a Tree/2603.py | 33 ++ .../2604.cpp | 44 ++ .../2604.java | 49 ++ .../2604.py | 25 + .../2605.cpp | 10 + .../2605.java | 9 + .../2605.py | 5 + .../2606.cpp | 20 + .../2606.java | 20 + .../2606.py | 14 + .../2607. Make K-Subarray Sums Equal/2607.cpp | 28 + .../2607.java | 26 + .../2607. Make K-Subarray Sums Equal/2607.py | 22 + .../2608. Shortest Cycle in a Graph/2608.cpp | 43 ++ .../2608. Shortest Cycle in a Graph/2608.java | 44 ++ .../2608. Shortest Cycle in a Graph/2608.py | 30 + .../2609-2.cpp | 21 + .../2609-2.java | 20 + .../2609-2.py | 16 + .../2609.cpp | 22 + .../2609.java | 21 + .../2609.py | 17 + solutions/261. Graph Valid Tree/261-2.cpp | 53 ++ solutions/261. Graph Valid Tree/261-2.java | 54 ++ solutions/261. Graph Valid Tree/261-2.py | 37 ++ solutions/261. Graph Valid Tree/261.cpp | 30 + solutions/261. Graph Valid Tree/261.java | 31 ++ solutions/261. Graph Valid Tree/261.py | 21 + .../2610.cpp | 17 + .../2610.java | 16 + .../2610.py | 14 + solutions/2611. Mice and Cheese/2611.cpp | 14 + solutions/2611. Mice and Cheese/2611.java | 13 + solutions/2611. Mice and Cheese/2611.py | 3 + .../2612. Minimum Reverse Operations/2612.cpp | 33 ++ .../2612.java | 35 ++ .../2612. Minimum Reverse Operations/2612.py | 32 ++ solutions/2613. Beautiful Pairs/2613.cpp | 135 +++++ solutions/2614. Prime In Diagonal/2614.cpp | 25 + solutions/2614. Prime In Diagonal/2614.java | 23 + solutions/2614. Prime In Diagonal/2614.py | 16 + solutions/2615. Sum of Distances/2615.cpp | 26 + solutions/2615. Sum of Distances/2615.java | 28 + solutions/2615. Sum of Distances/2615.py | 21 + .../2616.cpp | 33 ++ .../2616.java | 31 ++ .../2616.py | 23 + .../2617.cpp | 78 +++ .../2618.ts | 9 + solutions/2619. Array Prototype Last/2619.ts | 11 + solutions/262. Trips and Users/262.sql | 12 + solutions/2620. Counter/2620.ts | 5 + solutions/2621. Sleep/2621.ts | 5 + .../2622. Cache With Time Limit/2622-2.ts | 28 + solutions/2622. Cache With Time Limit/2622.ts | 34 ++ solutions/2623. Memoize/2623.ts | 9 + solutions/2624. Snail Traversal/2624.ts | 24 + .../2625. Flatten Deeply Nested Array/2625.ts | 23 + .../2626. Array Reduce Transformation/2626.ts | 9 + solutions/2627. Debounce/2627.ts | 9 + solutions/2628. JSON Deep Equal/2628.ts | 31 ++ solutions/2629. Function Composition/2629.ts | 7 + solutions/263. Ugly Number/263.cpp | 13 + solutions/263. Ugly Number/263.java | 12 + solutions/263. Ugly Number/263.py | 10 + solutions/2630. Memoize II/2630.ts | 23 + solutions/2631. Group By/2631.ts | 17 + solutions/2632. Curry/2632.ts | 7 + .../2633.ts | 28 + .../2634. Filter Elements from Array/2634.ts | 11 + .../2635.ts | 7 + solutions/2636. Promise Pool/2636.ts | 6 + solutions/2637. Promise Time Limit/2637.ts | 11 + .../2638.cpp | 24 + .../2638.java | 24 + .../2638.py | 18 + .../2639.cpp | 14 + .../2639.java | 13 + .../2639.py | 3 + solutions/264. Ugly Number II/264.cpp | 25 + solutions/264. Ugly Number II/264.java | 25 + solutions/264. Ugly Number II/264.py | 21 + .../2640.cpp | 16 + .../2640.java | 15 + .../2640.py | 10 + .../2641. Cousins in Binary Tree II/2641.cpp | 39 ++ .../2641. Cousins in Binary Tree II/2641.java | 35 ++ .../2641. Cousins in Binary Tree II/2641.py | 28 + .../2642.cpp | 41 ++ .../2642.java | 45 ++ .../2642.py | 26 + .../2643. Row With Maximum Ones/2643.cpp | 16 + .../2643. Row With Maximum Ones/2643.java | 15 + solutions/2643. Row With Maximum Ones/2643.py | 11 + .../2644.cpp | 20 + .../2644.java | 18 + .../2644.py | 14 + .../2645.cpp | 18 + .../2645.java | 17 + .../2645.py | 14 + .../2646.cpp | 66 +++ .../2646.java | 63 +++ .../2646.py | 43 ++ .../2647. Color the Triangle Red/2647.cpp | 33 ++ .../2647. Color the Triangle Red/2647.java | 31 ++ .../2647. Color the Triangle Red/2647.py | 28 + .../2648. Generate Fibonacci Sequence/2648.ts | 9 + .../2649. Nested Array Generator/2649.ts | 13 + solutions/265. Paint House II/265.cpp | 33 ++ solutions/265. Paint House II/265.java | 32 ++ solutions/265. Paint House II/265.py | 28 + .../2650. Design Cancellable Function/2650.ts | 22 + .../2651.cpp | 6 + .../2651.java | 5 + .../2651.py | 3 + solutions/2652. Sum Multiples/2652-2.cpp | 15 + solutions/2652. Sum Multiples/2652-2.java | 15 + solutions/2652. Sum Multiples/2652-2.py | 12 + solutions/2652. Sum Multiples/2652.cpp | 10 + solutions/2652. Sum Multiples/2652.java | 9 + solutions/2652. Sum Multiples/2652.py | 7 + .../2653. Sliding Subarray Beauty/2653.cpp | 29 + .../2653. Sliding Subarray Beauty/2653.java | 27 + .../2653. Sliding Subarray Beauty/2653.py | 22 + .../2654.cpp | 27 + .../2654.java | 30 + .../2654.py | 20 + .../2655.cpp | 24 + .../2655.java | 22 + .../2655.py | 15 + .../2656.cpp | 8 + .../2656.java | 7 + .../2656.py | 3 + .../2657.cpp | 19 + .../2657.java | 18 + .../2657.py | 17 + .../2658.cpp | 26 + .../2658.java | 24 + .../2658.py | 16 + solutions/2659. Make Array Empty/2659.cpp | 23 + solutions/2659. Make Array Empty/2659.java | 22 + solutions/2659. Make Array Empty/2659.py | 20 + solutions/266. Palindrome Permutation/266.cpp | 12 + .../266. Palindrome Permutation/266.java | 11 + solutions/266. Palindrome Permutation/266.py | 11 + .../2660.cpp | 25 + .../2660.java | 23 + .../2660.py | 19 + .../2661.cpp | 30 + .../2661.java | 29 + .../2661.py | 25 + .../2662.cpp | 59 ++ .../2662.java | 56 ++ .../2662.py | 38 ++ .../2663.cpp | 31 ++ .../2663.java | 33 ++ .../2663.py | 30 + .../2664.cpp" | 27 + .../2664.java" | 26 + .../2664.py" | 22 + solutions/2665. Counter II/2665.ts | 14 + .../2666. Allow One Function Call/2666.ts | 19 + .../2667. Create Hello World Function/2667.ts | 5 + solutions/2668. Find Latest Salaries/2668.sql | 9 + .../2669.sql | 6 + .../267. Palindrome Permutation II/267.cpp | 59 ++ .../267. Palindrome Permutation II/267.java | 58 ++ .../267. Palindrome Permutation II/267.py | 42 ++ .../2670.cpp | 25 + .../2670.java | 24 + .../2670.py | 24 + solutions/2671. Frequency Tracker/2671.cpp | 25 + solutions/2671. Frequency Tracker/2671.java | 23 + solutions/2671. Frequency Tracker/2671.py | 20 + .../2672.cpp | 29 + .../2672.java | 28 + .../2672.py | 21 + .../2673.cpp | 17 + .../2673.java | 16 + .../2673.py | 13 + .../2674.cpp | 25 + .../2674.java | 24 + .../2674.py | 21 + .../2675. Array of Objects to Matrix/2675.ts | 51 ++ solutions/2676. Throttle/2676.ts | 14 + solutions/2677. Chunk Array/2677.ts | 16 + .../2678. Number of Senior Citizens/2678.cpp | 8 + .../2678. Number of Senior Citizens/2678.java | 7 + .../2678. Number of Senior Citizens/2678.py | 3 + solutions/2679. Sum in a Matrix/2679.cpp | 18 + solutions/2679. Sum in a Matrix/2679.java | 17 + solutions/2679. Sum in a Matrix/2679.py | 6 + solutions/268. Missing Number/268.cpp | 11 + solutions/268. Missing Number/268.java | 10 + solutions/268. Missing Number/268.py | 8 + solutions/2680. Maximum OR/2680.cpp | 23 + solutions/2680. Maximum OR/2680.java | 23 + solutions/2680. Maximum OR/2680.py | 16 + solutions/2681. Power of Heroes/2681.cpp | 17 + solutions/2681. Power of Heroes/2681.java | 16 + solutions/2681. Power of Heroes/2681.py | 12 + .../2682.cpp | 19 + .../2682.java | 18 + .../2682.py | 15 + .../2683. Neighboring Bitwise XOR/2683.cpp | 9 + .../2683. Neighboring Bitwise XOR/2683.java | 8 + .../2683. Neighboring Bitwise XOR/2683.py | 3 + .../2684.cpp | 25 + .../2684.java | 24 + .../2684.py | 17 + .../2685.cpp | 65 +++ .../2685.java | 69 +++ .../2685.py | 52 ++ .../2686.sql | 9 + solutions/2687. Bikes Last Time Used/2687.sql | 3 + solutions/2688. Find Active Users/2688.sql | 14 + .../2589-2.py | 12 + .../2689-2.cpp | 18 + .../2689-2.java | 14 + .../2689.cpp | 13 + .../2689.java | 8 + .../2689.py | 10 + solutions/269. Alien Dictionary/269.cpp | 63 +++ solutions/269. Alien Dictionary/269.java | 56 ++ solutions/269. Alien Dictionary/269.py | 48 ++ .../2690. Infinite Method Object/2690.ts | 8 + solutions/2691. Immutability Helper/2691.ts | 114 ++++ solutions/2692. Make Object Immutable/2692.ts | 49 ++ .../2693.ts | 27 + solutions/2694. Event Emitter/2694.ts | 37 ++ solutions/2695. Array Wrapper/2695.ts | 15 + .../2696.cpp | 21 + .../2696.java | 19 + .../2696.py | 16 + .../2697.cpp | 11 + .../2697.java | 11 + .../2697.py | 14 + .../2698.cpp | 21 + .../2698.java | 19 + .../2698.py | 19 + .../2699. Modify Graph Edge Weights/2699.cpp | 76 +++ .../2699. Modify Graph Edge Weights/2699.java | 79 +++ .../2699. Modify Graph Edge Weights/2699.py | 56 ++ solutions/27. Remove Element/27.cpp | 12 + solutions/27. Remove Element/27.java | 11 + solutions/27. Remove Element/27.py | 10 + .../270.cpp | 20 + .../270.java | 19 + .../270.py | 15 + .../2700.ts | 33 ++ .../2701.sql | 36 ++ .../2702.cpp | 29 + .../2702.java | 26 + .../2702.py | 13 + .../2703.ts | 11 + solutions/2704. To Be Or Not To Be/2704.ts | 21 + solutions/2705. Compact Object/2705.ts | 31 ++ solutions/2706. Buy Two Chocolates/2706.cpp | 18 + solutions/2706. Buy Two Chocolates/2706.java | 17 + solutions/2706. Buy Two Chocolates/2706.py | 14 + .../2707.cpp | 23 + .../2707.java | 22 + .../2707.py | 16 + .../2708.cpp | 35 ++ .../2708.java | 34 ++ .../2708. Maximum Strength of a Group/2708.py | 31 ++ .../2709.cpp | 81 +++ .../2709.java | 81 +++ .../2709.py | 60 ++ .../271. Encode and Decode Strings/271.cpp | 26 + .../271. Encode and Decode Strings/271.java | 25 + .../271. Encode and Decode Strings/271.py | 17 + .../2710.cpp | 6 + .../2710.java | 5 + .../2710.py | 3 + .../2711.cpp | 40 ++ .../2711.java | 37 ++ .../2711.py | 36 ++ .../2712.cpp | 14 + .../2712.java | 13 + .../2712.py | 11 + .../2713.cpp | 33 ++ .../2713.java | 40 ++ .../2713.py | 26 + .../2714.cpp | 52 ++ .../2714.java | 55 ++ .../2714.py | 32 ++ solutions/2715. Timeout Cancellation/2715.ts | 15 + .../2716. Minimize String Length/2716.cpp | 6 + .../2716. Minimize String Length/2716.java | 5 + .../2716. Minimize String Length/2716.py | 3 + .../2717. Semi-Ordered Permutation/2717.cpp | 9 + .../2717. Semi-Ordered Permutation/2717.java | 14 + .../2717. Semi-Ordered Permutation/2717.py | 6 + .../2718.cpp | 24 + .../2718.java | 24 + .../2718. Sum of Matrix After Queries/2718.py | 16 + solutions/2719. Count of Integers/2719.cpp | 46 ++ .../272.cpp | 26 + .../272.java | 24 + .../272.py | 21 + .../2720. Popularity Percentage/2720.sql | 15 + .../2721.ts | 20 + solutions/2722. Join Two Arrays by ID/2722.ts | 31 ++ solutions/2723. Add Two Promises/2723.ts | 6 + solutions/2724. Sort By/2724.ts | 13 + solutions/2725. Interval Cancellation/2725.ts | 16 + .../2726.ts | 37 ++ solutions/2727. Is Object Empty/2727.ts | 15 + .../2728.cpp | 32 ++ .../2728.java | 28 + .../2728.py | 25 + .../2729.cpp | 8 + .../2729.java | 8 + .../2729.py | 4 + .../273. Integer to English Words/273.cpp | 42 ++ .../273. Integer to English Words/273.java | 31 ++ .../273. Integer to English Words/273.py | 32 ++ .../2730.cpp | 19 + .../2730.java | 18 + .../2730.py | 14 + solutions/2731. Movement of Robots/2731.cpp | 26 + solutions/2731. Movement of Robots/2731.java | 24 + solutions/2731. Movement of Robots/2731.py | 13 + .../2732.cpp | 28 + .../2732.java | 26 + .../2732.py | 22 + .../2733.cpp | 9 + .../2733.java | 8 + .../2733. Neither Minimum nor Maximum/2733.py | 3 + .../2734.cpp | 19 + .../2734.java | 19 + .../2734.py | 17 + .../2735. Collecting Chocolates/2735.cpp | 18 + .../2735. Collecting Chocolates/2735.java | 17 + solutions/2735. Collecting Chocolates/2735.py | 13 + solutions/2736. Maximum Sum Queries/2736.cpp | 58 ++ solutions/2736. Maximum Sum Queries/2736.java | 63 +++ solutions/2736. Maximum Sum Queries/2736.py | 58 ++ .../2737.cpp | 46 ++ .../2737.java | 50 ++ .../2737.py | 27 + .../2738. Count Occurrences in Text/2738.sql | 5 + .../2739. Total Distance Traveled/2739.cpp | 8 + .../2739. Total Distance Traveled/2739.java | 7 + .../2739. Total Distance Traveled/2739.py | 5 + solutions/274. H-Index/274-2.cpp | 14 + solutions/274. H-Index/274-2.java | 13 + solutions/274. H-Index/274-2.py | 11 + solutions/274. H-Index/274.cpp | 21 + solutions/274. H-Index/274.java | 20 + solutions/274. H-Index/274.py | 15 + .../2740.cpp | 13 + .../2740.java | 12 + .../2740.py | 3 + solutions/2741. Special Permutations/2741.cpp | 42 ++ .../2741. Special Permutations/2741.java | 39 ++ solutions/2741. Special Permutations/2741.py | 27 + solutions/2742. Painting the Walls/2742-2.cpp | 16 + .../2742. Painting the Walls/2742-2.java | 16 + solutions/2742. Painting the Walls/2742-2.py | 12 + solutions/2742. Painting the Walls/2742.cpp | 26 + solutions/2742. Painting the Walls/2742.java | 22 + solutions/2742. Painting the Walls/2742.py | 16 + .../2743.cpp | 16 + .../2743.java | 15 + .../2743.py | 14 + .../2744.cpp | 20 + .../2744.java | 18 + .../2744.py | 14 + .../2745.cpp | 13 + .../2745.java | 8 + .../2745.py | 10 + .../2746.cpp | 34 ++ .../2746.java | 29 + .../2746.py | 20 + .../2747. Count Zero Request Servers/2747.cpp | 46 ++ .../2747.java | 37 ++ .../2747. Count Zero Request Servers/2747.py | 38 ++ .../2748. Number of Beautiful Pairs/2748.cpp | 22 + .../2748. Number of Beautiful Pairs/2748.java | 24 + .../2748. Number of Beautiful Pairs/2748.py | 11 + .../2749.cpp | 19 + .../2749.java | 18 + .../2749.py | 15 + solutions/275. H-Index II/275.cpp | 18 + solutions/275. H-Index II/275.java | 17 + solutions/275. H-Index II/275.py | 5 + .../2750.cpp | 20 + .../2750.java | 19 + .../2750.py | 17 + solutions/2751. Robot Collisions/2751.cpp | 55 ++ solutions/2751. Robot Collisions/2751.java | 54 ++ solutions/2751. Robot Collisions/2751.py | 36 ++ .../2752.sql | 21 + .../2753.cpp | 34 ++ .../2753.java | 32 ++ .../2753.py | 27 + .../2754. Bind Function to Context/2754.ts | 11 + .../2755. Deep Merge of Two Objects/2755.ts | 28 + solutions/2756. Query Batching/2756.ts | 53 ++ .../2757.ts | 11 + solutions/2758. Next Day/2758.ts | 11 + .../2759.ts | 141 +++++ solutions/276. Paint Fence/276.cpp | 22 + solutions/276. Paint Fence/276.java | 21 + solutions/276. Paint Fence/276.py | 19 + .../2760.cpp | 26 + .../2760.java | 24 + .../2760.py | 20 + .../2761.cpp | 25 + .../2761.java | 24 + .../2761. Prime Pairs With Target Sum/2761.py | 16 + solutions/2762. Continuous Subarrays/2762.cpp | 37 ++ .../2762. Continuous Subarrays/2762.java | 36 ++ solutions/2762. Continuous Subarrays/2762.py | 31 ++ .../2763-2.cpp | 42 ++ .../2763-2.java | 42 ++ .../2763-2.py | 35 ++ .../2764.cpp" | 22 + .../2764.java" | 21 + .../2764.py" | 15 + .../2765.cpp | 23 + .../2765.java | 22 + .../2765.py | 19 + solutions/2766. Relocate Marbles/2766.cpp | 14 + solutions/2766. Relocate Marbles/2766.java | 12 + solutions/2766. Relocate Marbles/2766.py | 9 + .../2767.cpp | 29 + .../2767.java | 28 + .../2767.py | 21 + .../2768. Number of Black Blocks/2768.cpp | 27 + .../2768. Number of Black Blocks/2768.java | 25 + .../2768. Number of Black Blocks/2768.py | 20 + .../2769.cpp | 6 + .../2769.java | 5 + .../2769.py | 3 + solutions/277. Find the Celebrity/277.cpp | 21 + solutions/277. Find the Celebrity/277.java | 20 + solutions/277. Find the Celebrity/277.py | 22 + .../2770.cpp | 16 + .../2770.java | 16 + .../2770.py | 13 + .../2771.cpp | 20 + .../2771.java | 19 + .../2771.py | 16 + .../2772.cpp | 25 + .../2772.java | 22 + .../2772.py | 19 + .../2773.cpp | 11 + .../2773.java | 10 + .../2773.py | 8 + solutions/2774. Array Upper Bound/2774.ts | 19 + solutions/2775. Undefined to Null/2775-2.ts | 39 ++ solutions/2775. Undefined to Null/2775.ts | 35 ++ .../2776.ts | 13 + solutions/2777. Date Range Generator/2777.ts | 14 + .../2778.cpp | 13 + .../2778.java | 12 + .../2778.py | 4 + .../2779-2.cpp | 16 + .../2779-2.java | 15 + .../2779-2.py | 11 + .../2779.cpp | 16 + .../2779.java | 15 + .../2779.py | 13 + solutions/278. First Bad Version/278.cpp | 19 + solutions/278. First Bad Version/278.java | 16 + solutions/278. First Bad Version/278.py | 13 + .../2780.cpp | 20 + .../2780.java | 19 + .../2780.py | 12 + .../2781-2.cpp | 56 ++ .../2781-2.java | 53 ++ .../2781-2.py | 43 ++ .../2781.cpp | 20 + .../2781.java | 19 + .../2781.py | 14 + .../2782.cpp | 30 + .../2782.java | 24 + .../2782. Number of Unique Categories/2782.py | 14 + .../2783.sql | 9 + .../2784. Check if Array is Good/2784.cpp | 15 + .../2784. Check if Array is Good/2784.java | 12 + .../2784. Check if Array is Good/2784.py | 5 + .../2785. Sort Vowels in a String/2785.cpp | 25 + .../2785. Sort Vowels in a String/2785.java | 22 + .../2785. Sort Vowels in a String/2785.py | 15 + .../2786.cpp | 20 + .../2786.java | 19 + .../2786.py | 17 + .../2787.cpp | 19 + .../2787.java | 18 + .../2787.py | 15 + .../2788. Split Strings by Separator/2788.cpp | 15 + .../2788.java | 8 + .../2788. Split Strings by Separator/2788.py | 6 + .../2789.cpp | 14 + .../2789.java | 13 + .../2789.py | 11 + solutions/279. Perfect Squares/279.cpp | 14 + solutions/279. Perfect Squares/279.java | 14 + solutions/279. Perfect Squares/279.py | 13 + .../2790.cpp | 18 + .../2790.java | 17 + .../2790.py | 12 + .../2791.cpp | 38 ++ .../2791.java | 39 ++ .../2791.py | 31 ++ .../2792.cpp | 26 + .../2792.java | 25 + .../2792.py | 17 + .../2793. Status of Flight Tickets/2793.sql | 14 + .../2794.ts | 21 + .../2795.ts | 30 + solutions/2796. Repeat String/2796.ts | 9 + .../2797.ts | 18 + .../2798.cpp | 7 + .../2798.java | 5 + .../2798.py | 3 + .../2799.cpp | 25 + .../2799.java | 23 + .../2799.py | 19 + solutions/28. Implement strStr()/28.cpp | 13 + solutions/28. Implement strStr()/28.java | 12 + solutions/28. Implement strStr()/28.py | 10 + solutions/280. Wiggle Sort/280.cpp | 11 + solutions/280. Wiggle Sort/280.java | 16 + solutions/280. Wiggle Sort/280.py | 8 + .../2800.cpp | 40 ++ .../2800.java | 37 ++ .../2800.py | 32 ++ .../2801.cpp | 48 ++ .../2801.java | 41 ++ .../2801.py | 34 ++ .../2802. Find The K-th Lucky Number/2802.cpp | 12 + .../2802.java | 10 + .../2802. Find The K-th Lucky Number/2802.py | 3 + solutions/2803. Factorial Generator/2803.ts | 10 + .../2804. Array Prototype ForEach/2804.ts | 22 + solutions/2805. Custom Interval/2805.ts | 18 + .../2806.cpp | 6 + .../2806.java | 5 + .../2806.py | 3 + .../2807.cpp | 12 + .../2807.java | 14 + .../2807.py | 8 + .../2808.cpp | 26 + .../2808.java | 26 + .../2808.py | 20 + .../2809-2.cpp | 36 ++ .../2809-2.java | 36 ++ .../2809-2.py | 26 + .../2809.cpp | 36 ++ .../2809.java | 34 ++ .../2809.py | 26 + solutions/281. Zigzag Iterator/281.cpp | 25 + solutions/281. Zigzag Iterator/281.java | 22 + solutions/281. Zigzag Iterator/281.py | 16 + solutions/2810. Faulty Keyboard/2810.cpp | 18 + solutions/2810. Faulty Keyboard/2810.java | 20 + solutions/2810. Faulty Keyboard/2810.py | 14 + .../2811.cpp | 13 + .../2811.java | 12 + .../2811.py | 3 + .../2812.cpp | 86 +++ .../2812.java | 84 +++ .../2812.py | 63 +++ .../2813.cpp | 46 ++ .../2813.java | 39 ++ .../2813.py | 32 ++ .../2814.cpp | 74 +++ .../2814.java | 74 +++ .../2814.py | 66 +++ .../2815. Max Pair Sum in an Array/2815.cpp | 27 + .../2815. Max Pair Sum in an Array/2815.java | 25 + .../2815. Max Pair Sum in an Array/2815.py | 20 + .../2816-2.cpp | 16 + .../2816-2.java | 15 + .../2816-2.py | 15 + .../2816.cpp | 18 + .../2816.java | 15 + .../2816.py | 12 + .../2817.cpp | 19 + .../2817.java | 18 + .../2817.py | 17 + .../2818.cpp | 97 ++++ .../2818.java | 98 ++++ .../2818.py | 67 +++ .../2819.cpp | 75 +++ .../2819.java | 73 +++ .../2819.py | 59 ++ .../282. Expression Add Operators/282.cpp | 49 ++ .../282. Expression Add Operators/282.java | 35 ++ .../282. Expression Add Operators/282.py | 32 ++ solutions/2820. Election Results/2820.sql | 22 + .../2821.ts | 15 + solutions/2822. Inversion of Object/2822.ts | 27 + solutions/2823. Deep Object Filter/2823.ts | 28 + .../2824.cpp | 13 + .../2824.java | 12 + .../2824.py | 5 + .../2825.cpp | 13 + .../2825.java | 12 + .../2825.py | 11 + solutions/2826. Sorting Three Groups/2826.cpp | 16 + .../2826. Sorting Three Groups/2826.java | 14 + solutions/2826. Sorting Three Groups/2826.py | 11 + .../2827.cpp | 49 ++ .../2828.cpp | 13 + .../2828.java | 12 + .../2828.py | 4 + .../2829.cpp | 20 + .../2829.java | 18 + .../2829.py | 16 + solutions/283. Move Zeroes/283.cpp | 12 + solutions/283. Move Zeroes/283.java | 11 + solutions/283. Move Zeroes/283.py | 10 + .../2830.cpp | 24 + .../2830.java | 29 + .../2830.py | 16 + .../2831-2.cpp | 16 + .../2831-2.java | 15 + .../2831-2.py | 15 + .../2831.cpp | 15 + .../2831.java | 14 + .../2831.py | 14 + .../2832.cpp | 20 + .../2832.java | 17 + .../2832.py | 13 + .../2833. Furthest Point From Origin/2833.cpp | 18 + .../2833.java | 17 + .../2833. Furthest Point From Origin/2833.py | 3 + .../2834.cpp | 24 + .../2834.java | 21 + .../2834.py | 18 + .../2835.cpp | 37 ++ .../2835.java | 36 ++ .../2835.py | 28 + .../2836.cpp | 44 ++ .../2836.java | 43 ++ .../2836.py | 37 ++ .../2837. Total Traveled Distance/2837.sql | 9 + .../2838.cpp | 42 ++ .../2838.java | 36 ++ .../2838.py | 16 + .../2839.cpp | 18 + .../2839.java | 19 + .../2839.py | 12 + solutions/284. Peeking Iterator/284.cpp | 21 + solutions/284. Peeking Iterator/284.java | 31 ++ solutions/284. Peeking Iterator/284.py | 18 + .../2840.cpp | 17 + .../2840.java | 16 + .../2840.py | 10 + .../2841.cpp | 23 + .../2841.java | 23 + .../2841.py | 19 + .../2842.cpp | 58 ++ .../2842.java | 54 ++ .../2842.py | 18 + .../2843. Count Symmetric Integers/2843.cpp | 24 + .../2843. Count Symmetric Integers/2843.java | 22 + .../2843. Count Symmetric Integers/2843.py | 12 + .../2844.cpp | 23 + .../2844.java | 22 + .../2844.py | 19 + .../2845.cpp | 17 + .../2845.java | 17 + .../2845.py | 13 + .../2846.cpp | 86 +++ .../2846.java | 86 +++ .../2846.py | 66 +++ .../2847.cpp | 17 + .../2847.java | 16 + .../2847.py | 13 + .../2848.cpp | 24 + .../2848.java | 23 + .../2848.py | 17 + .../2849.cpp | 7 + .../2849.java | 6 + .../2849.py | 4 + .../285. Inorder Successor in BST/285.cpp | 12 + .../285. Inorder Successor in BST/285.java | 11 + .../285. Inorder Successor in BST/285.py | 7 + .../2850.cpp | 29 + .../2850.java | 28 + .../2850.py | 21 + .../2851. String Transformation/2851.cpp | 78 +++ .../2851. String Transformation/2851.java | 77 +++ solutions/2851. String Transformation/2851.py | 52 ++ .../2852.cpp | 49 ++ .../2852.java | 48 ++ .../2852.py | 37 ++ .../2853.sql | 11 + .../2854. Rolling Average Steps/2854.sql | 25 + .../2855.cpp | 19 + .../2855.java | 18 + .../2855.py | 14 + .../2856.cpp | 20 + .../2856.java | 19 + .../2856.py | 11 + .../2857.cpp | 27 + .../2857.java | 18 + .../2857.py | 12 + .../2858.cpp | 51 ++ .../2858.java | 55 ++ .../2858.py | 38 ++ .../2859.cpp | 10 + .../2859.java | 9 + .../2859.py | 4 + solutions/286. Walls and Gates/286.cpp | 29 + solutions/286. Walls and Gates/286.java | 29 + solutions/286. Walls and Gates/286.py | 24 + solutions/2860. Happy Students/2860.cpp | 17 + solutions/2860. Happy Students/2860.java | 16 + solutions/2860. Happy Students/2860.py | 5 + .../2861. Maximum Number of Alloys/2861.cpp | 37 ++ .../2861. Maximum Number of Alloys/2861.java | 33 ++ .../2861. Maximum Number of Alloys/2861.py | 27 + .../2862-2.cpp | 15 + .../2862-2.java | 14 + .../2862-2.py | 13 + .../2862.cpp | 22 + .../2862.java | 20 + .../2862.py | 17 + .../2863.cpp | 19 + .../2863.java | 18 + .../2863.py | 16 + .../2864. Maximum Odd Binary Number/2864.cpp | 8 + .../2864. Maximum Odd Binary Number/2864.java | 7 + .../2864. Maximum Odd Binary Number/2864.py | 3 + solutions/2865. Beautiful Towers I/2865.cpp | 39 ++ solutions/2865. Beautiful Towers I/2865.java | 37 ++ solutions/2865. Beautiful Towers I/2865.py | 28 + solutions/2866. Beautiful Towers II/2866.cpp | 40 ++ solutions/2866. Beautiful Towers II/2866.java | 38 ++ solutions/2866. Beautiful Towers II/2866.py | 29 + .../2867.cpp | 53 ++ .../2867.java | 56 ++ .../2867. Count Valid Paths in a Tree/2867.py | 41 ++ solutions/2868. The Wording Game/2868.cpp | 35 ++ solutions/2868. The Wording Game/2868.java | 34 ++ solutions/2868. The Wording Game/2868.py | 36 ++ .../2869.cpp | 16 + .../2869.java | 15 + .../2869.py | 10 + .../287. Find the Duplicate Number/287.cpp | 21 + .../287. Find the Duplicate Number/287.java | 20 + .../287. Find the Duplicate Number/287.py | 16 + .../2870.cpp | 21 + .../2870.java | 20 + .../2870.py | 6 + .../2871.cpp | 15 + .../2871.java | 14 + .../2871.py | 11 + .../2872.cpp | 32 ++ .../2872.java | 32 ++ .../2872.py | 23 + .../2873.cpp | 16 + .../2873.java | 15 + .../2873.py | 12 + .../2874.cpp | 17 + .../2874.java | 16 + .../2874.py | 13 + .../2875.cpp | 26 + .../2875.java | 25 + .../2875.py | 22 + .../2876.cpp | 56 ++ .../2876.java | 51 ++ .../2876.py | 47 ++ .../2877.py | 5 + .../2878. Get the Size of a DataFrame/2878.py | 5 + .../2879.py | 5 + .../288. Unique Word Abbreviation/288.cpp | 28 + .../288. Unique Word Abbreviation/288.java | 26 + .../288. Unique Word Abbreviation/288.py | 19 + solutions/2880. Select Data/2880.py | 5 + solutions/2881. Create a New Column/2881.py | 6 + solutions/2882. Drop Duplicate Rows/2882.py | 6 + solutions/2883. Drop Missing Data/2883.py | 6 + solutions/2884. Modify Columns/2884.py | 6 + solutions/2885. Rename Columns/2885.py | 12 + solutions/2886. Change Data Type/2886.py | 5 + solutions/2887. Fill Missing Data/2887.py | 6 + .../2888. Reshape Data: Concatenate/2888.py | 5 + solutions/2889. Reshape Data: Pivot/2889.py | 10 + solutions/289. Game of Life/289.cpp | 27 + solutions/289. Game of Life/289.java | 26 + solutions/289. Game of Life/289.py | 23 + solutions/2890. Reshape Data: Melt/2890.py | 10 + solutions/2891. Method Chaining/2891.py | 8 + .../2892.cpp | 20 + .../2892.java | 19 + .../2892.py | 15 + .../2893.sql | 6 + .../2894.cpp | 20 + .../2894.java | 18 + .../2894.py | 15 + .../2895. Minimum Processing Time/2895.cpp | 16 + .../2895. Minimum Processing Time/2895.java | 15 + .../2895. Minimum Processing Time/2895.py | 4 + .../2896-2.cpp | 31 ++ .../2896-2.java | 30 + .../2896-2.py | 20 + .../2896-3.cpp | 34 ++ .../2896-3.java | 32 ++ .../2896-3.py | 24 + .../2896.cpp | 37 ++ .../2896.java | 33 ++ .../2896.py | 22 + .../2897.cpp | 22 + .../2897.java | 21 + .../2897.py | 21 + .../2898. Maximum Linear Stock Score/2898.cpp | 21 + .../2898.java | 16 + .../2898. Maximum Linear Stock Score/2898.py | 8 + .../2899. Last Visited Integers/2899.cpp | 19 + .../2899. Last Visited Integers/2899.java | 18 + solutions/2899. Last Visited Integers/2899.py | 15 + solutions/29. Divide Two Integers/29.cpp | 23 + solutions/29. Divide Two Integers/29.java | 22 + solutions/29. Divide Two Integers/29.py | 19 + solutions/290. Word Pattern/290.cpp | 21 + solutions/290. Word Pattern/290.java | 16 + solutions/290. Word Pattern/290.py | 4 + .../2900.cpp | 16 + .../2900.java | 14 + .../2900.py | 11 + .../2901.cpp | 43 ++ .../2901.java | 51 ++ .../2901.py | 27 + .../2902.cpp | 34 ++ .../2902.java | 34 ++ .../2902.py | 21 + .../2903.cpp | 25 + .../2903.java | 23 + .../2903.py | 20 + .../2904.cpp | 27 + .../2904.java | 27 + .../2904.py | 22 + .../2905.cpp | 25 + .../2905.java | 21 + .../2905.py | 18 + .../2906. Construct Product Matrix/2906.cpp | 23 + .../2906. Construct Product Matrix/2906.java | 22 + .../2906. Construct Product Matrix/2906.py | 19 + .../2907.cpp | 53 ++ .../2907.java | 52 ++ .../2907.py | 40 ++ .../2908.cpp | 21 + .../2908.java | 23 + .../2908.py | 12 + .../2909.cpp | 22 + .../2909.java | 24 + .../2909.py | 12 + solutions/291. Word Pattern II/291.cpp | 50 ++ solutions/291. Word Pattern II/291.java | 45 ++ solutions/291. Word Pattern II/291.py | 39 ++ .../2910.cpp | 44 ++ .../2910.java | 42 ++ .../2910.py | 29 + .../2911.cpp | 62 +++ .../2911.java | 60 ++ .../2911.py | 49 ++ .../2912-2.cpp | 38 ++ .../2912-2.java | 35 ++ .../2912-2.py | 29 + .../2912.cpp | 39 ++ .../2912.java | 36 ++ .../2912.py | 30 + .../2913.cpp | 72 +++ .../2914.cpp | 12 + .../2914.java | 11 + .../2914.py | 3 + .../2915-2.cpp | 15 + .../2915-2.java | 14 + .../2915-2.py | 12 + .../2915.cpp | 25 + .../2915.java | 26 + .../2915.py | 21 + .../2916.cpp | 72 +++ .../2917. Find the K-or of an Array/2917.cpp | 0 .../2917. Find the K-or of an Array/2917.java | 17 + .../2917. Find the K-or of an Array/2917.py | 6 + .../2918.cpp | 14 + .../2918.java | 13 + .../2918.py | 11 + .../2919.cpp | 20 + .../2919.java | 19 + .../2919.py | 16 + solutions/292. Nim Game/292.cpp | 6 + solutions/292. Nim Game/292.java | 5 + solutions/292. Nim Game/292.py | 3 + .../2920.cpp | 44 ++ .../2920.java | 45 ++ .../2920.py | 30 + .../2921.cpp | 54 ++ .../2921.java | 53 ++ .../2921.py | 41 ++ solutions/2922. Market Analysis III/2922.sql | 23 + solutions/2923. Find Champion I/2923-2.cpp | 9 + solutions/2923. Find Champion I/2923-2.java | 8 + solutions/2923. Find Champion I/2923-2.py | 3 + solutions/2923. Find Champion I/2923.cpp | 24 + solutions/2923. Find Champion I/2923.java | 26 + solutions/2923. Find Champion I/2923.py | 16 + solutions/2924. Find Champion II/2924.cpp | 21 + solutions/2924. Find Champion II/2924.java | 20 + solutions/2924. Find Champion II/2924.py | 9 + .../2925.cpp | 30 + .../2925.java | 27 + .../2925.py | 17 + .../2926.cpp | 60 ++ .../2926.java | 59 ++ .../2926.py | 40 ++ .../2927.cpp | 30 + .../2927.java | 27 + .../2927.py | 20 + .../2928.cpp | 31 ++ .../2928.java | 28 + .../2928.py | 20 + .../2929.cpp | 31 ++ .../2929.java | 28 + .../2929.py | 20 + solutions/293. Flip Game/293.cpp | 13 + solutions/293. Flip Game/293.java | 15 + solutions/293. Flip Game/293.py | 5 + .../2930.cpp | 32 ++ .../2930.java | 30 + .../2930.py | 19 + .../2931.cpp | 21 + .../2931.java | 11 + .../2931.py | 4 + .../2932. Maximum Strong Pair XOR I/2932.cpp | 74 +++ .../2932. Maximum Strong Pair XOR I/2932.java | 71 +++ .../2932. Maximum Strong Pair XOR I/2932.py | 60 ++ .../2933. High-Access Employees/2933.cpp | 20 + .../2933. High-Access Employees/2933.java | 24 + solutions/2933. High-Access Employees/2933.py | 16 + .../2934.cpp | 29 + .../2934.java | 28 + .../2934.py | 23 + .../2935. Maximum Strong Pair XOR II/2935.cpp | 74 +++ .../2935.java | 71 +++ .../2935. Maximum Strong Pair XOR II/2935.py | 60 ++ .../2936.cpp | 32 ++ .../2936.java | 27 + .../2936.py | 22 + .../2937. Make Three Strings Equal/2937.cpp | 10 + .../2937. Make Three Strings Equal/2937.java | 9 + .../2937. Make Three Strings Equal/2937.py | 7 + .../2938.cpp | 15 + .../2938.java | 14 + .../2938.py | 12 + solutions/2939. Maximum Xor Product/2939.cpp | 14 + solutions/2939. Maximum Xor Product/2939.java | 13 + solutions/2939. Maximum Xor Product/2939.py | 9 + solutions/294. Flip Game II/294.cpp | 20 + solutions/294. Flip Game II/294.java | 20 + solutions/294. Flip Game II/294.py | 9 + .../2940.cpp | 64 +++ .../2940.java | 71 +++ .../2940.py | 62 +++ .../2941.cpp | 29 + .../2941.java | 39 ++ .../2941.py | 21 + .../2942.cpp | 12 + .../2943.cpp | 20 + .../2944-2.cpp | 21 + .../2944-2.java | 19 + .../2944-2.py | 15 + .../2944-3.cpp | 21 + .../2944-3.java | 21 + .../2944-3.py | 17 + .../2944.cpp | 14 + .../2944.java | 14 + .../2944.py | 13 + .../2945-2.py | 25 + .../2945.py | 28 + .../2946.cpp | 11 + .../2946.java | 10 + .../2946.py | 8 + .../2947.cpp | 43 ++ .../2947.java | 36 ++ .../2947.py | 25 + .../2948.cpp | 43 ++ .../2948.java | 43 ++ .../2948.py | 23 + .../2949.cpp | 44 ++ .../2949.java | 37 ++ .../2949.py | 26 + .../295. Find Median from Data Stream/295.cpp | 26 + .../295.java | 24 + .../295. Find Median from Data Stream/295.py | 22 + .../2950.cpp | 26 + .../2950.java | 26 + .../2950.py | 20 + solutions/2951. Find the Peaks/2951.cpp | 10 + solutions/2951. Find the Peaks/2951.java | 9 + solutions/2951. Find the Peaks/2951.py | 4 + .../2952.cpp | 23 + .../2952.java | 22 + .../2952.py | 20 + .../2953. Count Complete Substrings/2953.cpp | 45 ++ .../2953. Count Complete Substrings/2953.java | 39 ++ .../2953. Count Complete Substrings/2953.py | 29 + .../2954.cpp | 57 ++ .../2954.java | 57 ++ .../2954.py | 33 ++ .../2955.cpp | 32 ++ .../2955.java | 31 ++ .../2955.py | 25 + .../2956.cpp | 12 + .../2956.java | 9 + .../2956.py | 6 + .../2957.cpp | 17 + .../2957.java | 16 + .../2957.py | 11 + .../2958.cpp | 16 + .../2958.java | 15 + .../2958.py | 14 + .../2959.cpp | 52 ++ .../2959.java | 48 ++ .../2959.py | 38 ++ solutions/296. Best Meeting Point/296.cpp | 32 ++ solutions/296. Best Meeting Point/296.java | 30 + solutions/296. Best Meeting Point/296.py | 21 + .../2960.cpp | 12 + .../2960.java | 11 + .../2960.py | 9 + .../2961.cpp | 24 + .../2961.java | 22 + .../2961.py | 4 + .../2962.cpp | 23 + .../2962.java | 22 + .../2962.py | 21 + .../2963.cpp | 26 + .../2963.java | 26 + .../2963.py | 21 + .../2964.cpp | 16 + .../2964.java | 15 + .../2964.py | 12 + .../2965.cpp | 24 + .../2965.java | 23 + .../2965.py | 9 + .../2966.cpp | 16 + .../2966.java | 15 + .../2966.py | 12 + .../2967.cpp | 32 ++ .../2967.java | 27 + .../2967.py | 22 + .../2968.cpp | 18 + .../2968.java | 19 + .../2968.py | 15 + .../2969-2.cpp | 22 + .../2969-2.java | 20 + .../2969-2.py | 16 + .../2969-3.cpp | 22 + .../2969-3.java | 22 + .../2969-3.py | 18 + .../2969.cpp | 15 + .../2969.java | 15 + .../2969.py | 14 + .../297-2.cpp | 44 ++ .../297-2.java | 37 ++ .../297-2.py | 32 ++ .../297.cpp | 53 ++ .../297.java | 47 ++ .../297.py | 39 ++ .../2970-2.cpp | 39 ++ .../2970-2.java | 42 ++ .../2970-2.py | 32 ++ .../2970.cpp | 38 ++ .../2970.java | 40 ++ .../2970.py | 29 + .../2971.cpp | 18 + .../2971.java | 17 + .../2971.py | 12 + .../2972-2.cpp | 40 ++ .../2972-2.java | 43 ++ .../2972-2.py | 33 ++ .../2972.cpp | 39 ++ .../2972.java | 41 ++ .../2972.py | 30 + .../2973.cpp | 69 +++ .../2973.java | 67 +++ .../2973.py | 49 ++ solutions/2974. Minimum Number Game/2974.cpp | 9 + solutions/2974. Minimum Number Game/2974.java | 13 + solutions/2974. Minimum Number Game/2974.py | 6 + .../2975.cpp | 34 ++ .../2975.java | 34 ++ .../2975.py | 14 + .../2976.cpp | 34 ++ .../2976.java | 34 ++ .../2976.py | 28 + .../2977.cpp | 71 +++ .../2977.java | 68 +++ .../2977.py | 51 ++ .../2978. Symmetric Coordinates/2978.sql | 17 + .../2979.cpp | 7 + .../2979.java | 6 + .../2979.py | 4 + .../298.cpp | 20 + .../298.java | 18 + .../298.py | 17 + .../2980.cpp | 12 + .../2980.java | 11 + .../2980.py | 3 + .../2981.cpp | 37 ++ .../2981.java | 36 ++ .../2981.py | 27 + .../2982.cpp | 37 ++ .../2982.java | 36 ++ .../2982.py | 27 + .../2983.cpp | 85 +++ .../2983.java | 81 +++ .../2983.py | 68 +++ .../2984.sql | 25 + .../2985. Calculate Compressed Mean/2985.sql | 6 + .../2986. Find Third Transaction/2986.sql | 27 + .../2987. Find Expensive Cities/2987.sql | 5 + .../2988.sql | 20 + solutions/2989. Class Performance/2989.sql | 7 + solutions/299. Bulls and Cows/299.cpp | 22 + solutions/299. Bulls and Cows/299.java | 21 + solutions/299. Bulls and Cows/299.py | 5 + solutions/2990. Loan Types/2990.sql | 6 + solutions/2991. Top Three Wineries/2991.sql | 35 ++ .../2992.cpp | 19 + .../2992.java | 17 + .../2992.py | 14 + solutions/2993. Friday Purchases I/2993.sql | 11 + solutions/2994. Friday Purchases II/2994.sql | 19 + .../2995. Viewers Turned Streamers/2995.sql | 22 + .../2996.cpp | 18 + .../2996.java | 17 + .../2996.py | 14 + .../2997.cpp | 7 + .../2997.java | 6 + .../2997.py | 3 + .../2998.cpp | 30 + .../2998.java | 28 + .../2998.py | 24 + .../2999.cpp | 49 ++ .../3-2.cpp | 19 + .../3-2.java | 19 + .../3-2.py | 15 + .../3.cpp | 16 + .../3.java | 15 + .../3.py | 14 + .../30.cpp | 29 + .../30.java | 29 + .../30.py | 23 + .../300-2.cpp | 21 + .../300-2.java | 20 + .../300-2.py | 13 + .../300.cpp | 17 + .../300.java | 17 + .../300.py | 14 + .../3000.cpp | 12 + .../3000.java | 12 + .../3000.py | 4 + .../3001.cpp | 23 + .../3001.java | 22 + .../3001.py | 20 + .../3002.cpp | 20 + .../3002.java | 19 + .../3002.py | 13 + .../3003.cpp | 42 ++ .../3003.java | 38 ++ .../3003.py | 28 + .../3004.cpp | 37 ++ .../3004.java | 38 ++ .../3004.py | 30 + .../3005.cpp | 13 + .../3005.java | 18 + .../3005.py | 5 + .../3006.cpp | 61 +++ .../3006.java | 58 ++ .../3006.py | 53 ++ .../3007.cpp | 39 ++ .../3007.java | 35 ++ .../3007.py | 17 + .../3008.cpp | 62 +++ .../3008.java | 59 ++ .../3008.py | 54 ++ .../3009.cpp | 23 + .../3009.java | 22 + .../3009.py | 17 + .../301. Remove Invalid Parentheses/301.cpp | 58 ++ .../301. Remove Invalid Parentheses/301.java | 56 ++ .../301. Remove Invalid Parentheses/301.py | 48 ++ .../3010.cpp | 18 + .../3010.java | 17 + .../3010.py | 14 + .../3011.cpp | 30 + .../3011.java | 29 + .../3011. Find if Array Can Be Sorted/3011.py | 25 + .../3012.cpp | 15 + .../3012.java | 15 + .../3012.py | 12 + .../3013.cpp | 58 ++ .../3013.java | 88 +++ .../3013.py | 48 ++ .../3014.cpp | 17 + .../3014.java | 16 + .../3014.py | 4 + .../3015.cpp | 104 ++++ .../3015.java | 104 ++++ .../3015.py | 92 ++++ .../3016.cpp | 18 + .../3016.java | 17 + .../3016.py | 5 + .../3017.cpp | 106 ++++ .../3017.java | 105 ++++ .../3017.py | 93 ++++ .../3018.cpp | 33 ++ .../3018.java | 32 ++ .../3018.py | 25 + .../3019. Number of Changing Keys/3019.cpp | 10 + .../3019. Number of Changing Keys/3019.java | 9 + .../3019. Number of Changing Keys/3019.py | 4 + .../302-2.cpp | 47 ++ .../302-2.java | 49 ++ .../302-2.py | 31 ++ .../302.cpp | 35 ++ .../302.java | 34 ++ .../302.py | 29 + .../3020.cpp | 30 + .../3020.java | 29 + .../3020.py | 21 + .../3021.cpp | 13 + .../3021.java | 12 + .../3021.py | 10 + .../3022.cpp | 35 ++ .../3022.java | 33 ++ .../3022.py | 30 + .../3023.cpp | 53 ++ .../3023.java | 52 ++ .../3023.py | 44 ++ .../3024. Type of Triangle II Easy/3024.cpp | 13 + .../3024. Type of Triangle II Easy/3024.java | 12 + .../3024. Type of Triangle II Easy/3024.py | 10 + .../3025.cpp | 21 + .../3025.java | 18 + .../3025.py | 18 + .../3026. Maximum Good Subarray Sum/3026.cpp | 25 + .../3026. Maximum Good Subarray Sum/3026.java | 19 + .../3026. Maximum Good Subarray Sum/3026.py | 16 + .../3027.cpp | 22 + .../3027.java | 19 + .../3027.py | 19 + solutions/3028. Ant on the Boundary/3028.cpp | 7 + solutions/3028. Ant on the Boundary/3028.java | 14 + solutions/3028. Ant on the Boundary/3028.py | 3 + .../3029.cpp | 35 ++ .../3029.java | 34 ++ .../3029.py | 33 ++ .../303. Range Sum Query - Immutable/303.cpp | 13 + .../303. Range Sum Query - Immutable/303.java | 13 + .../303. Range Sum Query - Immutable/303.py | 6 + .../3030.cpp | 49 ++ .../3030.java | 47 ++ .../3030.py | 34 ++ .../3031.cpp | 35 ++ .../3031.java | 34 ++ .../3031.py | 33 ++ .../3032.cpp | 23 + .../3032.java | 21 + .../3032.py | 4 + solutions/3033. Modify the Matrix/3033.cpp | 19 + solutions/3033. Modify the Matrix/3033.java | 18 + solutions/3033. Modify the Matrix/3033.py | 13 + .../3034.cpp | 62 +++ .../3034.java | 60 ++ .../3034.py | 48 ++ .../3035.cpp | 40 ++ .../3035.java | 38 ++ .../3035.py | 14 + .../3036.cpp | 63 +++ .../3036.java | 61 +++ .../3036.py | 49 ++ .../3037.cpp | 54 ++ .../3037.java | 53 ++ .../3037.py | 45 ++ .../3038.cpp | 16 + .../3038.java | 15 + .../3038.py | 12 + .../3039.cpp | 18 + .../3039.java | 17 + .../3039.py | 12 + .../304.cpp | 25 + .../304.java | 22 + .../304.py | 19 + .../3040.cpp | 39 ++ .../3040.java | 31 ++ .../3040.py | 22 + .../3041-2.cpp | 34 ++ .../3041-2.java | 33 ++ .../3041-2.py | 27 + .../3041.cpp | 18 + .../3041.java | 17 + .../3041.py | 12 + .../3042.cpp | 42 ++ .../3042.java | 36 ++ .../3042.py | 25 + .../3043.cpp | 49 ++ .../3043.java | 45 ++ .../3043.py | 34 ++ solutions/3044. Most Frequent Prime/3044.cpp | 42 ++ solutions/3044. Most Frequent Prime/3044.java | 45 ++ solutions/3044. Most Frequent Prime/3044.py | 27 + .../3045.cpp | 43 ++ .../3045.java | 37 ++ .../3045.py | 26 + solutions/3046. Split the Array/3046.cpp | 12 + solutions/3046. Split the Array/3046.java | 11 + solutions/3046. Split the Array/3046.py | 3 + .../3047.cpp | 24 + .../3047.java | 22 + .../3047.py | 10 + .../3048.cpp | 48 ++ .../3048.java | 45 ++ .../3048.py | 31 ++ .../3049.cpp | 86 +++ .../3049.java | 80 +++ .../3049.py | 51 ++ solutions/305. Number of Islands II/305.cpp | 75 +++ solutions/305. Number of Islands II/305.java | 75 +++ solutions/305. Number of Islands II/305.py | 59 ++ .../3050.sql | 9 + .../3051.sql | 6 + solutions/3052. Maximize Items/3052.sql | 17 + .../3053.sql | 13 + solutions/3054. Binary Tree Nodes/3054.sql | 13 + solutions/3055. Top Percentile Fraud/3055.sql | 16 + solutions/3056. Snaps Analysis/3056.sql | 16 + .../3057.sql | 20 + .../3058.sql | 22 + .../3059.sql | 7 + solutions/306. Additive Number/306.cpp | 35 ++ solutions/306. Additive Number/306.java | 33 ++ solutions/306. Additive Number/306.py | 30 + .../3060.sql | 15 + .../3061.sql | 11 + .../3062.cpp | 21 + .../3062.java | 20 + .../3062.py | 17 + .../3063. Linked List Frequency/3063.cpp | 22 + .../3063. Linked List Frequency/3063.java | 21 + solutions/3063. Linked List Frequency/3063.py | 17 + .../3064.cpp | 16 + .../3064.java | 15 + .../3064.py | 7 + .../3065.cpp | 6 + .../3065.java | 5 + .../3065.py | 3 + .../3066.cpp | 21 + .../3066.java | 18 + .../3066.py | 13 + .../3067.cpp | 50 ++ .../3067.java | 54 ++ .../3067.py | 25 + .../3068.cpp | 19 + .../3068.java | 17 + .../3068.py | 8 + .../3069.cpp | 16 + .../3069.java | 15 + .../3069.py | 12 + .../307. Range Sum Query - Mutable/307-2.cpp | 75 +++ .../307. Range Sum Query - Mutable/307-3.cpp | 81 +++ .../307. Range Sum Query - Mutable/307.cpp | 48 ++ .../307. Range Sum Query - Mutable/307.java | 48 ++ .../307. Range Sum Query - Mutable/307.py | 34 ++ .../3070.cpp | 19 + .../3070.java | 17 + .../3070.py | 17 + .../3071.cpp | 27 + .../3071.java | 25 + .../3071.py | 22 + .../3072.cpp | 73 +++ .../3072.java | 72 +++ .../3072.py | 57 ++ .../3073.cpp | 22 + .../3073.java | 20 + .../3073.py | 19 + .../3074.cpp | 17 + .../3074.java | 16 + .../3074.py | 11 + .../3075.cpp | 16 + .../3075.java | 16 + .../3075.py | 12 + .../3076.cpp | 50 ++ .../3076.java | 47 ++ .../3076.py | 40 ++ .../3077.cpp | 36 ++ .../3077.java | 30 + .../3077.py | 25 + .../3078.cpp | 36 ++ .../3078.java | 31 ++ .../3078.py | 26 + .../3079.cpp | 18 + .../3079.java | 17 + .../3079.py | 12 + .../308. Range Sum Query 2D - Mutable/308.cpp | 49 ++ .../308.java | 48 ++ .../308. Range Sum Query 2D - Mutable/308.py | 45 ++ .../3080.cpp | 35 ++ .../3080.java | 36 ++ .../3080.py | 22 + .../3081.cpp | 37 ++ .../3081.java | 35 ++ .../3081.py | 32 ++ .../3082-2.cpp | 26 + .../3082-2.java | 25 + .../3082-2.py | 22 + .../3082-3.cpp | 23 + .../3082-3.java | 22 + .../3082-3.py | 14 + .../3082.cpp | 36 ++ .../3082.java | 33 ++ .../3082.py | 18 + .../3083.cpp | 10 + .../3083.java | 9 + .../3083.py | 3 + .../3084.cpp | 7 + .../3084.java | 6 + .../3084.py | 4 + .../3085.cpp | 22 + .../3085.java | 21 + .../3085.py | 15 + .../3086.cpp | 54 ++ .../3086.java | 53 ++ .../3086.py | 42 ++ .../3087. Find Trending Hashtags/3087.sql | 11 + .../3088.cpp | 31 ++ .../3088.java | 34 ++ .../3088. Make String Anti-palindrome/3088.py | 29 + solutions/3089. Find Bursty Behavior/3089.sql | 34 ++ .../309.cpp | 17 + .../309.java | 16 + .../309.py | 13 + .../3090.cpp | 16 + .../3090.java | 15 + .../3090.py | 14 + .../3091-2.cpp | 15 + .../3091-2.java | 14 + .../3091-2.py | 12 + .../3091.cpp | 15 + .../3091.java | 14 + .../3091.py | 12 + solutions/3092. Most Frequent IDs/3092.cpp | 28 + solutions/3092. Most Frequent IDs/3092.java | 27 + solutions/3092. Most Frequent IDs/3092.py | 24 + .../3093.cpp | 56 ++ .../3093.java | 53 ++ .../3093.py | 38 ++ .../3094-2.cpp | 18 + .../3094-2.java | 17 + .../3094-2.py | 8 + .../3094.cpp | 21 + .../3094.java | 20 + .../3094.py | 14 + .../3095.cpp | 38 ++ .../3095.java | 36 ++ .../3095.py | 31 ++ .../3096.cpp | 24 + .../3096.java | 23 + .../3096.py | 11 + .../3097.cpp | 39 ++ .../3097.java | 37 ++ .../3097.py | 32 ++ .../3098-2.py | 20 + .../3098.cpp | 52 ++ .../3098.java | 44 ++ .../3098.py | 25 + solutions/3099. Harshad Number/3099.cpp | 17 + solutions/3099. Harshad Number/3099.java | 15 + solutions/3099. Harshad Number/3099.py | 7 + solutions/31. Next Permutation/31.cpp | 30 + solutions/31. Next Permutation/31.java | 34 ++ solutions/31. Next Permutation/31.py | 26 + solutions/310. Minimum Height Trees/310.cpp | 35 ++ solutions/310. Minimum Height Trees/310.java | 40 ++ solutions/310. Minimum Height Trees/310.py | 27 + solutions/3100. Water Bottles II/3100.cpp | 14 + solutions/3100. Water Bottles II/3100.java | 13 + solutions/3100. Water Bottles II/3100.py | 10 + .../3101.cpp | 13 + .../3101.java | 13 + .../3101. Count Alternating Subarrays/3101.py | 10 + .../3102.cpp | 49 ++ .../3102.java | 54 ++ .../3102.py | 41 ++ .../3103. Find Trending Hashtags II/3103.sql | 24 + .../3104.cpp | 48 ++ .../3104.java | 45 ++ .../3104.py | 37 ++ .../3105.cpp | 25 + .../3105.java | 24 + .../3105.py | 20 + .../3106.cpp | 23 + .../3106.java | 22 + .../3106.py | 18 + .../3107.cpp | 17 + .../3107.java | 16 + .../3107.py | 14 + .../3108.cpp | 66 +++ .../3108.java | 67 +++ .../3108.py | 44 ++ .../3109.cpp | 52 ++ .../3109.java | 52 ++ .../3109.py | 41 ++ .../311-2.cpp | 30 + .../311-2.java | 28 + .../311-2.py | 20 + .../311. Sparse Matrix Multiplication/311.cpp | 17 + .../311.java | 15 + .../311. Sparse Matrix Multiplication/311.py | 13 + solutions/3110. Score of a String/3110.cpp | 11 + solutions/3110. Score of a String/3110.java | 10 + solutions/3110. Score of a String/3110.py | 4 + .../3111.cpp | 23 + .../3111.java | 20 + .../3111.py | 12 + .../3112.cpp | 46 ++ .../3112.java | 49 ++ .../3112.py | 27 + .../3113.cpp | 17 + .../3113.java | 17 + .../3113.py | 14 + .../3114.cpp | 16 + .../3114.java | 15 + .../3114.py | 13 + .../3115. Maximum Prime Difference/3115.cpp | 30 + .../3115. Maximum Prime Difference/3115.java | 29 + .../3115. Maximum Prime Difference/3115.py | 24 + .../3116.cpp | 47 ++ .../3116.java | 54 ++ .../3116.py | 23 + .../3117.cpp | 39 ++ .../3117.java | 41 ++ .../3117.py | 27 + solutions/3118. Friday Purchase III/3118.sql | 27 + .../3119.cpp | 29 + .../3119.java | 23 + .../3119.py | 12 + solutions/312. Burst Balloons/312-2.cpp | 22 + solutions/312. Burst Balloons/312-2.java | 23 + solutions/312. Burst Balloons/312-2.py | 19 + solutions/312. Burst Balloons/312.cpp | 27 + solutions/312. Burst Balloons/312.java | 27 + solutions/312. Burst Balloons/312.py | 16 + .../3120.cpp | 20 + .../3120.java | 19 + .../3120.py | 14 + .../3121.cpp | 20 + .../3121.java | 19 + .../3121.py | 14 + .../3122.cpp | 35 ++ .../3122.java | 31 ++ .../3122.py | 28 + .../3123.cpp | 55 ++ .../3123.java | 60 ++ .../3123.py | 31 ++ solutions/3124. Find Longest Calls/3124.sql | 25 + .../3125.cpp | 11 + .../3125.java | 10 + .../3125.py | 7 + .../3126. Server Utilization Time/3126.sql | 19 + .../3127.cpp | 19 + .../3127.java | 18 + .../3127.py | 15 + solutions/3128. Right Triangles/3128.cpp | 24 + solutions/3128. Right Triangles/3128.java | 23 + solutions/3128. Right Triangles/3128.py | 15 + .../3129.cpp | 30 + .../3129.java | 28 + .../3129.py | 25 + solutions/313. Super Ugly Number/313-2.cpp | 34 ++ solutions/313. Super Ugly Number/313-2.java | 31 ++ solutions/313. Super Ugly Number/313-2.py | 22 + solutions/313. Super Ugly Number/313.cpp | 21 + solutions/313. Super Ugly Number/313.java | 21 + solutions/313. Super Ugly Number/313.py | 17 + .../3130.cpp | 30 + .../3130.java | 28 + .../3130.py | 25 + .../3131.cpp | 6 + .../3131.java | 5 + .../3131.py | 3 + .../3132.cpp | 40 ++ .../3132.java | 37 ++ .../3132.py | 35 ++ solutions/3133. Minimum Array End/3133.cpp | 22 + solutions/3133. Minimum Array End/3133.java | 25 + solutions/3133. Minimum Array End/3133.py | 16 + .../3134.cpp | 38 ++ .../3134.java | 36 ++ .../3134.py | 28 + .../3135.cpp | 20 + .../3135.java | 16 + .../3135.py | 13 + solutions/3136. Valid Word/3136.cpp | 18 + solutions/3136. Valid Word/3136.java | 15 + solutions/3136. Valid Word/3136.py | 11 + .../3137.cpp | 15 + .../3137.java | 11 + .../3137.py | 4 + .../3138.cpp | 29 + .../3138.java | 27 + .../3138.py | 13 + .../3139.cpp | 25 + .../3139.java | 24 + .../3139.py | 23 + .../314.cpp | 37 ++ .../314.java | 39 ++ .../314.py | 31 ++ .../3140.sql | 21 + .../3141. Maximum Hamming Distances/3141.cpp | 24 + .../3141. Maximum Hamming Distances/3141.java | 24 + .../3141. Maximum Hamming Distances/3141.py | 16 + .../3142.cpp | 19 + .../3142.java | 18 + .../3142.py | 10 + .../3143.cpp | 29 + .../3143.java | 29 + .../3143.py | 20 + .../3144.cpp | 34 ++ .../3144.java | 33 ++ .../3144.py | 15 + .../3145.cpp | 84 +++ .../3145.java | 81 +++ .../3145.py | 40 ++ .../3146.cpp | 15 + .../3146.java | 14 + .../3146.py | 4 + .../3147.cpp | 9 + .../3147.java | 8 + .../3147.py | 7 + .../3148.cpp | 17 + .../3148.java | 17 + .../3148.py | 13 + .../3149.cpp | 51 ++ .../3149.java | 47 ++ .../3149.py | 33 ++ .../315-2.cpp | 85 +++ .../315-3.cpp | 91 +++ .../315-4.cpp | 60 ++ .../315-4.java | 61 +++ .../315-4.py | 57 ++ .../315.cpp | 54 ++ .../315.java | 55 ++ .../315.py | 40 ++ solutions/3150. Invalid Tweets II/3150.sql | 7 + solutions/3151. Special Array I/3151.cpp | 9 + solutions/3151. Special Array I/3151.java | 8 + solutions/3151. Special Array I/3151.py | 3 + solutions/3152. Special Array II/3152.cpp | 23 + solutions/3152. Special Array II/3152.java | 23 + solutions/3152. Special Array II/3152.py | 16 + .../3153.cpp | 18 + .../3153.java | 17 + .../3153.py | 15 + .../3154.cpp | 37 ++ .../3154.java | 36 ++ .../3154.py | 20 + .../3155.cpp | 16 + .../3155.java | 12 + .../3155.py | 6 + .../3156.sql | 47 ++ .../3157-2.cpp | 21 + .../3157-2.java | 20 + .../3157-2.py | 17 + .../3157.cpp | 28 + .../3157.java | 26 + .../3157.py | 23 + .../3158.cpp | 17 + .../3158.java | 16 + .../3158.py | 5 + .../3159.cpp | 22 + .../3159.java | 19 + .../3159.py | 5 + .../316. Remove Duplicate Letters/316.cpp | 25 + .../316. Remove Duplicate Letters/316.java | 28 + .../316. Remove Duplicate Letters/316.py | 17 + .../3160.cpp | 23 + .../3160.java | 22 + .../3160.py | 17 + .../3161. Block Placement Queries/3161.cpp | 69 +++ .../3161. Block Placement Queries/3161.java | 71 +++ .../3161. Block Placement Queries/3161.py | 56 ++ .../3162.cpp | 11 + .../3162.java | 10 + .../3162.py | 5 + .../3163. String Compression III/3163.cpp | 18 + .../3163. String Compression III/3163.java | 17 + .../3163. String Compression III/3163.py | 16 + .../3164.cpp | 20 + .../3164.java | 19 + .../3164.py | 13 + .../3165.cpp | 98 ++++ .../3166.sql | 37 ++ .../3167.cpp | 21 + .../3167.java | 20 + .../3167.py | 16 + .../3168.cpp | 14 + .../3168.java | 13 + .../3168.py | 10 + .../3169.cpp | 19 + .../3169.java | 18 + .../3169. Count Days Without Meetings/3169.py | 11 + .../317.cpp | 70 +++ .../317.java | 76 +++ .../317.py | 53 ++ .../3170.cpp | 21 + .../3170.java | 22 + .../3170.py | 14 + .../3171.cpp | 23 + .../3171.java | 22 + .../3171.py | 14 + .../3172. Second Day Verification/3172.sql | 8 + .../3173.cpp | 9 + .../3173.java | 8 + .../3173.py | 3 + solutions/3174. Clear Digits/3174.cpp | 16 + solutions/3174. Clear Digits/3174.java | 15 + solutions/3174. Clear Digits/3174.py | 13 + .../3175.cpp | 18 + .../3175.java | 17 + .../3175.py | 16 + .../3176.cpp | 22 + .../3176.java | 24 + .../3176.py | 18 + .../3177.cpp | 23 + .../3177.java | 25 + .../3177.py | 19 + .../3178.cpp | 9 + .../3178.java | 8 + .../3178.py | 6 + .../3179.cpp | 29 + .../3179.java | 29 + .../3179.py | 3 + .../318.cpp | 25 + .../318.java | 23 + .../318.py | 18 + .../3180.cpp | 51 ++ .../3180.java | 45 ++ .../3180.py | 36 ++ .../3181.cpp | 26 + .../3181.java | 20 + .../3181.py | 11 + .../3182. Find Top Scoring Students/3182.sql | 28 + .../3183.cpp | 20 + .../3183.java | 19 + .../3183.py | 16 + .../3184.cpp | 14 + .../3184.java | 13 + .../3184.py | 10 + .../3185.cpp | 15 + .../3185.java | 14 + .../3185.py | 11 + .../3186.cpp | 45 ++ .../3186.java | 41 ++ .../3186.py | 22 + solutions/3187. Peaks in Array/3187-2.cpp | 99 ++++ solutions/3187. Peaks in Array/3187.cpp | 80 +++ solutions/3187. Peaks in Array/3187.java | 78 +++ solutions/3187. Peaks in Array/3187.py | 60 ++ .../3188.sql | 39 ++ .../3189.cpp | 24 + .../3189.java | 18 + .../3189.py | 7 + solutions/319. Bulb Switcher/319.cpp | 11 + solutions/319. Bulb Switcher/319.java | 10 + solutions/319. Bulb Switcher/319.py | 8 + .../3190.cpp | 6 + .../3190.java | 5 + .../3190.py | 3 + .../3191.cpp | 16 + .../3191.java | 15 + .../3191.py | 11 + .../3192.cpp | 15 + .../3192.java | 14 + .../3192.py | 11 + .../3193.cpp | 32 ++ .../3193.java | 32 ++ .../3193.py | 22 + .../3194.cpp | 16 + .../3194.java | 15 + .../3194.py | 5 + .../3195.cpp | 20 + .../3195.java | 19 + .../3195.py | 16 + .../3196-2.cpp | 18 + .../3196-2.java | 17 + .../3196-2.py | 11 + .../3196.cpp | 16 + .../3196.java | 15 + .../3196.py | 12 + .../3197.cpp | 72 +++ .../3197.java | 65 +++ .../3197.py | 62 +++ .../3198. Find Cities in Each State/3198.sql | 6 + .../3199.cpp | 24 + .../3199.java | 27 + .../3199.py | 14 + .../32. Longest Valid Parentheses/32.cpp | 15 + .../32. Longest Valid Parentheses/32.java | 14 + solutions/32. Longest Valid Parentheses/32.py | 12 + .../320. Generalized Abbreviation/320.cpp | 36 ++ .../320. Generalized Abbreviation/320.java | 28 + .../320. Generalized Abbreviation/320.py | 22 + .../3200.cpp | 24 + .../3200.java | 21 + .../3200.py | 21 + .../3201.cpp | 18 + .../3201.java | 14 + .../3201.py | 12 + .../3202.cpp | 19 + .../3202.java | 15 + .../3202.py | 13 + .../3203.cpp | 48 ++ .../3203.java | 47 ++ .../3203.py | 35 ++ .../3204.sql | 4 + .../3205-2.cpp | 15 + .../3205-2.java | 14 + .../3205-2.py | 4 + .../3205.cpp | 15 + .../3205.java | 14 + .../3205.py | 12 + solutions/3206. Alternating Groups I/3206.cpp | 14 + .../3206. Alternating Groups I/3206.java | 12 + solutions/3206. Alternating Groups I/3206.py | 6 + .../3207.cpp | 12 + .../3207.java | 9 + .../3207.py | 5 + .../3208. Alternating Groups II/3208.cpp | 17 + .../3208. Alternating Groups II/3208.java | 15 + solutions/3208. Alternating Groups II/3208.py | 13 + .../3209.cpp | 23 + .../3209.java | 27 + .../3209.py | 19 + solutions/321. Create Maximum Number/321.cpp | 40 ++ solutions/321. Create Maximum Number/321.java | 45 ++ solutions/321. Create Maximum Number/321.py | 18 + .../3210. Find the Encrypted String/3210.cpp | 7 + .../3210. Find the Encrypted String/3210.java | 6 + .../3210. Find the Encrypted String/3210.py | 4 + .../3211.cpp | 24 + .../3211.java | 22 + .../3211.py | 18 + .../3212.cpp | 24 + .../3212.java | 21 + .../3212.py | 18 + .../3213.cpp | 60 ++ .../3213.java | 54 ++ .../3213.py | 44 ++ .../3214. Year on Year Growth Rate/3214.sql | 21 + .../3215.cpp | 27 + .../3215.java | 29 + .../3215.py | 15 + .../3216.cpp | 11 + .../3216.java | 14 + .../3216.py | 8 + .../3217.cpp | 15 + .../3217.java | 14 + .../3217.py | 13 + .../3218.cpp | 23 + .../3218.java | 21 + .../3218.py | 18 + .../3219.cpp | 24 + .../3219.java | 22 + .../3219.py | 19 + solutions/322. Coin Change/322-2.cpp | 15 + solutions/322. Coin Change/322-2.java | 14 + solutions/322. Coin Change/322.cpp | 14 + solutions/322. Coin Change/322.java | 13 + solutions/322. Coin Change/322.py | 10 + .../3220. Odd and Even Transactions/3220.sql | 7 + .../3221.cpp | 16 + .../3221.java | 15 + .../3221.py | 5 + .../3222.cpp | 6 + .../3222.java | 5 + .../3222.py | 3 + .../3223.cpp | 16 + .../3223.java | 15 + .../3223.py | 4 + .../3224.cpp | 35 ++ .../3224.java | 36 ++ .../3224.py | 23 + .../3225.cpp | 45 ++ .../3225.java | 44 ++ .../3225.py | 40 ++ .../3226.cpp | 7 + .../3226.java | 6 + .../3226.py | 4 + .../3227. Vowels Game in a String/3227.cpp | 19 + .../3227. Vowels Game in a String/3227.java | 16 + .../3227. Vowels Game in a String/3227.py | 11 + .../3228.cpp | 15 + .../3228.java | 14 + .../3228.py | 12 + .../3229.cpp | 21 + .../3229.java | 19 + .../3229.py | 17 + .../323-2.cpp | 30 + .../323-2.java | 31 ++ .../323-2.py | 23 + .../323-3.cpp | 50 ++ .../323-3.java | 51 ++ .../323-3.py | 34 ++ .../323.cpp | 40 ++ .../323.java | 39 ++ .../323.py | 27 + .../3230.sql | 36 ++ .../3231.cpp | 33 ++ .../3231.java | 42 ++ .../3231.py | 14 + .../3232.cpp | 8 + .../3232.java | 5 + .../3232.py | 3 + .../3233.cpp | 26 + .../3233.java | 25 + .../3233.py | 21 + .../3234.cpp | 32 ++ .../3234.java | 31 ++ .../3234.py | 33 ++ .../3235.cpp | 69 +++ .../3235.java | 67 +++ .../3235.py | 51 ++ .../3236. CEO Subordinate Hierarchy/3236.sql | 38 ++ .../3237. Alt and Tab Simulation/3237.cpp | 21 + .../3237. Alt and Tab Simulation/3237.java | 21 + .../3237. Alt and Tab Simulation/3237.py | 16 + solutions/324. Wiggle Sort II/324.cpp | 20 + solutions/324. Wiggle Sort II/324.java | 45 ++ solutions/324. Wiggle Sort II/324.py | 44 ++ .../3241.py | 72 +++ .../325.cpp | 20 + .../325.java | 18 + .../325.py | 15 + solutions/326. Power of Three/326.cpp | 6 + solutions/326. Power of Three/326.java | 5 + solutions/326. Power of Three/326.py | 3 + solutions/327. Count of Range Sum/327.cpp | 62 +++ solutions/327. Count of Range Sum/327.java | 59 ++ solutions/327. Count of Range Sum/327.py | 58 ++ solutions/328. Odd Even Linked List/328.cpp | 22 + solutions/328. Odd Even Linked List/328.java | 21 + solutions/328. Odd Even Linked List/328.py | 21 + .../329.cpp | 34 ++ .../329.java | 31 ++ .../329.py | 19 + .../33. Search in Rotated Sorted Array/33.cpp | 26 + .../33.java | 25 + .../33. Search in Rotated Sorted Array/33.py | 21 + solutions/330. Patching Array/330.cpp | 20 + solutions/330. Patching Array/330.java | 19 + solutions/330. Patching Array/330.py | 17 + .../331.cpp | 16 + .../331.java | 14 + .../331.py | 12 + solutions/332. Reconstruct Itinerary/332.cpp | 25 + solutions/332. Reconstruct Itinerary/332.java | 21 + solutions/332. Reconstruct Itinerary/332.py | 15 + solutions/333. Largest BST Subtree/333.cpp | 28 + solutions/333. Largest BST Subtree/333.java | 25 + solutions/333. Largest BST Subtree/333.py | 27 + .../334.cpp | 17 + .../334.java | 16 + .../334.py | 14 + solutions/335. Self Crossing/335.cpp | 19 + solutions/335. Self Crossing/335.java | 18 + solutions/335. Self Crossing/335.py | 14 + solutions/336. Palindrome Pairs/336.cpp | 43 ++ solutions/336. Palindrome Pairs/336.java | 35 ++ solutions/336. Palindrome Pairs/336.py | 18 + solutions/337. House Robber III/337.cpp | 22 + solutions/337. House Robber III/337.java | 24 + solutions/337. House Robber III/337.py | 13 + solutions/338. Counting Bits/338.cpp | 13 + solutions/338. Counting Bits/338.java | 12 + solutions/338. Counting Bits/338.py | 10 + .../339. Nested List Weight Sum/339-2.cpp | 17 + .../339. Nested List Weight Sum/339-2.java | 16 + .../339. Nested List Weight Sum/339-2.py | 14 + solutions/339. Nested List Weight Sum/339.cpp | 31 ++ .../339. Nested List Weight Sum/339.java | 27 + solutions/339. Nested List Weight Sum/339.py | 22 + .../34.cpp | 10 + .../34.java | 22 + .../34.py | 7 + .../340-2.cpp | 25 + .../340.cpp | 19 + .../340.java | 18 + .../340.py | 19 + .../341-2.cpp | 32 ++ .../341-2.java | 29 + .../341-2.py | 19 + .../341. Flatten Nested List Iterator/341.cpp | 27 + .../341.java | 25 + .../341. Flatten Nested List Iterator/341.py | 17 + solutions/342. Power of Four/342.cpp | 11 + solutions/342. Power of Four/342.java | 10 + solutions/342. Power of Four/342.py | 8 + solutions/343. Integer Break/343.cpp | 24 + solutions/343. Integer Break/343.java | 23 + solutions/343. Integer Break/343.py | 20 + solutions/344. Reverse String/344.cpp | 10 + solutions/344. Reverse String/344.java | 12 + solutions/344. Reverse String/344.py | 9 + .../345. Reverse Vowels of a String/345.cpp | 23 + .../345. Reverse Vowels of a String/345.java | 24 + .../345. Reverse Vowels of a String/345.py | 17 + .../346.cpp | 17 + .../346.java | 17 + .../346.py | 12 + .../347. Top K Frequent Elements/347-2.cpp | 24 + .../347. Top K Frequent Elements/347-2.java | 27 + .../347. Top K Frequent Elements/347-2.py | 12 + .../347. Top K Frequent Elements/347.cpp | 30 + .../347. Top K Frequent Elements/347.java | 33 ++ solutions/348. Design Tic-Tac-Toe/348.cpp | 50 ++ solutions/348. Design Tic-Tac-Toe/348.java | 52 ++ solutions/348. Design Tic-Tac-Toe/348.py | 43 ++ .../349. Intersection of Two Arrays/349.cpp | 13 + .../349. Intersection of Two Arrays/349.java | 12 + .../349. Intersection of Two Arrays/349.py | 11 + solutions/35. Search Insert Position/35.cpp | 19 + solutions/35. Search Insert Position/35.java | 18 + solutions/35. Search Insert Position/35.py | 15 + .../350-2.cpp | 24 + .../350-3.cpp | 37 ++ .../350.cpp | 20 + .../350.java | 20 + .../350. Intersection of Two Arrays II/350.py | 14 + .../351. Android Unlock Patterns/351.cpp | 41 ++ .../351. Android Unlock Patterns/351.java | 38 ++ solutions/351. Android Unlock Patterns/351.py | 32 ++ .../352.cpp | 53 ++ .../352.java | 34 ++ .../352.py | 45 ++ solutions/353. Design Snake Game/353.cpp | 70 +++ solutions/353. Design Snake Game/353.java | 75 +++ solutions/353. Design Snake Game/353.py | 72 +++ solutions/354. Russian Doll Envelopes/354.cpp | 29 + .../354. Russian Doll Envelopes/354.java | 20 + solutions/354. Russian Doll Envelopes/354.py | 21 + solutions/355. Design Twitter/355.cpp | 106 ++++ solutions/355. Design Twitter/355.java | 97 ++++ solutions/355. Design Twitter/355.py | 21 + solutions/356. Line Reflection/356.cpp | 34 ++ solutions/356. Line Reflection/356.java | 26 + solutions/356. Line Reflection/356.py | 17 + .../357.cpp | 17 + .../357.java | 16 + .../357.py | 16 + .../358.cpp | 41 ++ .../358.java | 37 ++ .../358.py | 29 + solutions/359. Logger Rate Limiter/359-2.cpp | 13 + solutions/359. Logger Rate Limiter/359-2.java | 11 + solutions/359. Logger Rate Limiter/359-2.py | 10 + solutions/359. Logger Rate Limiter/359.cpp | 25 + solutions/359. Logger Rate Limiter/359.java | 23 + solutions/359. Logger Rate Limiter/359.py | 21 + solutions/36. Valid Sudoku/36.cpp | 20 + solutions/36. Valid Sudoku/36.java | 18 + solutions/36. Valid Sudoku/36.py | 18 + solutions/360. Sort Transformed Array/360.cpp | 27 + .../360. Sort Transformed Array/360.java | 25 + solutions/360. Sort Transformed Array/360.py | 34 ++ solutions/361. Bomb Enemy/361.cpp | 43 ++ solutions/361. Bomb Enemy/361.java | 43 ++ solutions/361. Bomb Enemy/361.py | 36 ++ solutions/362. Design Hit Counter/362.cpp | 24 + solutions/362. Design Hit Counter/362.java | 22 + solutions/362. Design Hit Counter/362.py | 15 + .../363.cpp | 29 + .../363.java | 28 + .../363.py | 26 + .../364. Nested List Weight Sum II/364.cpp | 24 + .../364. Nested List Weight Sum II/364.java | 20 + .../364. Nested List Weight Sum II/364.py | 17 + solutions/365. Water and Jug Problem/365.cpp | 8 + solutions/365. Water and Jug Problem/365.java | 10 + solutions/365. Water and Jug Problem/365.py | 5 + .../366. Find Leaves of Binary Tree/366.cpp | 24 + .../366. Find Leaves of Binary Tree/366.java | 22 + .../366. Find Leaves of Binary Tree/366.py | 21 + solutions/367. Valid Perfect Square/367.cpp | 17 + solutions/367. Valid Perfect Square/367.java | 16 + solutions/367. Valid Perfect Square/367.py | 5 + .../368. Largest Divisible Subset/368.cpp | 39 ++ .../368. Largest Divisible Subset/368.java | 40 ++ .../368. Largest Divisible Subset/368.py | 25 + solutions/369. Plus One Linked List/369-2.cpp | 23 + .../369. Plus One Linked List/369-2.java | 22 + solutions/369. Plus One Linked List/369-2.py | 18 + solutions/369. Plus One Linked List/369.cpp | 18 + solutions/369. Plus One Linked List/369.java | 16 + solutions/369. Plus One Linked List/369.py | 13 + solutions/37. Sudoku Solver/37.cpp | 36 ++ solutions/37. Sudoku Solver/37.java | 34 ++ solutions/37. Sudoku Solver/37.py | 30 + solutions/370. Range Addition/370.cpp | 24 + solutions/370. Range Addition/370.java | 23 + solutions/370. Range Addition/370.py | 10 + solutions/371. Sum of Two Integers/371.cpp | 11 + solutions/371. Sum of Two Integers/371.java | 10 + solutions/371. Sum of Two Integers/371.py | 9 + solutions/372. Super Pow/372.cpp | 23 + solutions/372. Super Pow/372.java | 21 + solutions/372. Super Pow/372.py | 9 + .../373.cpp | 29 + .../373.java | 30 + .../373.py | 15 + .../374. Guess Number Higher or Lower/374.cpp | 30 + .../374.java | 29 + .../374. Guess Number Higher or Lower/374.py | 21 + .../375-2.cpp | 17 + .../375-2.java | 16 + .../375-2.py | 13 + .../375.cpp | 23 + .../375.java | 22 + .../375.py | 12 + solutions/376. Wiggle Subsequence/376.cpp | 15 + solutions/376. Wiggle Subsequence/376.java | 14 + solutions/376. Wiggle Subsequence/376.py | 12 + solutions/377. Combination Sum IV/377.cpp | 14 + solutions/377. Combination Sum IV/377.java | 14 + solutions/377. Combination Sum IV/377.py | 14 + .../378-2.cpp | 31 ++ .../378-2.java | 29 + .../378-2.py | 15 + .../378.cpp | 26 + .../378.java | 28 + .../378.py | 16 + solutions/379. Design Phone Directory/379.cpp | 32 ++ .../379. Design Phone Directory/379.java | 32 ++ solutions/379. Design Phone Directory/379.py | 23 + solutions/38. Count and Say/38.cpp | 21 + solutions/38. Count and Say/38.java | 20 + solutions/38. Count and Say/38.py | 17 + .../380. Insert Delete GetRandom O(1)/380.cpp | 31 ++ .../380.java | 35 ++ .../380. Insert Delete GetRandom O(1)/380.py | 26 + .../381.cpp | 37 ++ .../381.java | 49 ++ .../381.py | 24 + .../382. Linked List Random Node/382.cpp | 22 + .../382. Linked List Random Node/382.java | 24 + solutions/382. Linked List Random Node/382.py | 22 + solutions/383. Ransom Note/383.cpp | 18 + solutions/383. Ransom Note/383.java | 16 + solutions/383. Ransom Note/383.py | 5 + solutions/384. Shuffle an Array/384.cpp | 22 + solutions/384. Shuffle an Array/384.java | 29 + solutions/384. Shuffle an Array/384.py | 19 + solutions/385. Mini Parser/385.cpp | 41 ++ solutions/385. Mini Parser/385.java | 38 ++ solutions/385. Mini Parser/385.py | 26 + .../386. Lexicographical Numbers/386.cpp | 20 + .../386. Lexicographical Numbers/386.java | 19 + solutions/386. Lexicographical Numbers/386.py | 15 + .../387.cpp | 15 + .../387.java | 14 + .../387.py | 9 + .../388. Longest Absolute File Path/388.cpp | 32 ++ .../388. Longest Absolute File Path/388.java | 33 ++ .../388. Longest Absolute File Path/388.py | 16 + solutions/389. Find the Difference/389-2.cpp | 17 + solutions/389. Find the Difference/389-2.java | 16 + solutions/389. Find the Difference/389-2.py | 8 + solutions/389. Find the Difference/389.cpp | 8 + solutions/389. Find the Difference/389.java | 7 + solutions/389. Find the Difference/389.py | 5 + solutions/39. Combination Sum/39.cpp | 26 + solutions/39. Combination Sum/39.java | 24 + solutions/39. Combination Sum/39.py | 19 + solutions/390. Elimination Game/390.cpp | 6 + solutions/390. Elimination Game/390.java | 5 + solutions/390. Elimination Game/390.py | 3 + solutions/391. Perfect Rectangle/391.cpp | 37 ++ solutions/391. Perfect Rectangle/391.java | 36 ++ solutions/391. Perfect Rectangle/391.py | 31 ++ solutions/392. Is Subsequence/392.cpp | 14 + solutions/392. Is Subsequence/392.java | 13 + solutions/392. Is Subsequence/392.py | 13 + solutions/393. UTF-8 Validation/393.cpp | 26 + solutions/393. UTF-8 Validation/393.java | 25 + solutions/393. UTF-8 Validation/393.py | 22 + solutions/394. Decode String/394-2.cpp | 25 + solutions/394. Decode String/394-2.java | 23 + solutions/394. Decode String/394-2.py | 21 + solutions/394. Decode String/394.cpp | 36 ++ solutions/394. Decode String/394.java | 35 ++ solutions/394. Decode String/394.py | 21 + .../395.cpp | 37 ++ .../395.java | 35 ++ .../395.py | 31 ++ solutions/396. Rotate Function/396.cpp | 20 + solutions/396. Rotate Function/396.java | 19 + solutions/396. Rotate Function/396.py | 11 + solutions/397. Integer Replacement/397.cpp | 16 + solutions/397. Integer Replacement/397.java | 15 + solutions/397. Integer Replacement/397.py | 14 + solutions/398. Random Pick Index/398.cpp | 18 + solutions/398. Random Pick Index/398.java | 19 + solutions/398. Random Pick Index/398.py | 13 + solutions/399. Evaluate Division/399.cpp | 50 ++ solutions/399. Evaluate Division/399.java | 48 ++ solutions/399. Evaluate Division/399.py | 34 ++ .../4. Median of Two Sorted Arrays/4.cpp | 31 ++ .../4. Median of Two Sorted Arrays/4.java | 30 + solutions/4. Median of Two Sorted Arrays/4.py | 23 + solutions/40. Combination Sum II/40.cpp | 28 + solutions/40. Combination Sum II/40.java | 26 + solutions/40. Combination Sum II/40.py | 21 + solutions/400. Nth Digit/400.cpp | 19 + solutions/400. Nth Digit/400.java | 18 + solutions/400. Nth Digit/400.py | 23 + solutions/401. Binary Watch/401-2.cpp | 13 + solutions/401. Binary Watch/401-2.java | 12 + solutions/401. Binary Watch/401-2.py | 10 + solutions/401. Binary Watch/401.cpp | 26 + solutions/401. Binary Watch/401.java | 24 + solutions/401. Binary Watch/401.py | 20 + solutions/402. Remove K Digits/402.cpp | 29 + solutions/402. Remove K Digits/402.java | 28 + solutions/402. Remove K Digits/402.py | 23 + solutions/403. Frog Jump/403-2.cpp | 21 + solutions/403. Frog Jump/403-2.java | 20 + solutions/403. Frog Jump/403-2.py | 16 + solutions/403. Frog Jump/403.cpp | 21 + solutions/403. Frog Jump/403.java | 20 + solutions/403. Frog Jump/403.py | 17 + solutions/404. Sum of Left Leaves/404-2.cpp | 24 + solutions/404. Sum of Left Leaves/404-2.java | 24 + solutions/404. Sum of Left Leaves/404-2.py | 19 + solutions/404. Sum of Left Leaves/404.cpp | 19 + solutions/404. Sum of Left Leaves/404.java | 18 + solutions/404. Sum of Left Leaves/404.py | 15 + .../405.cpp | 18 + .../405.java | 17 + .../405.py | 19 + .../406.cpp | 15 + .../406.java | 12 + .../406.py | 10 + solutions/407. Trapping Rain Water II/407.cpp | 55 ++ .../407. Trapping Rain Water II/407.java | 58 ++ solutions/407. Trapping Rain Water II/407.py | 39 ++ .../408. Valid Word Abbreviation/408.cpp | 25 + .../408. Valid Word Abbreviation/408.java | 24 + solutions/408. Valid Word Abbreviation/408.py | 19 + solutions/409. Longest Palindrome/409.cpp | 17 + solutions/409. Longest Palindrome/409.java | 15 + solutions/409. Longest Palindrome/409.py | 10 + solutions/41. First Missing Positive/41.cpp | 20 + solutions/41. First Missing Positive/41.java | 25 + solutions/41. First Missing Positive/41.py | 17 + .../410. Split Array Largest Sum/410-2.cpp | 22 + .../410. Split Array Largest Sum/410-2.java | 22 + .../410. Split Array Largest Sum/410-2.py | 17 + .../410. Split Array Largest Sum/410-3.cpp | 33 ++ .../410. Split Array Largest Sum/410-3.java | 31 ++ .../410. Split Array Largest Sum/410-3.py | 26 + .../410. Split Array Largest Sum/410.cpp | 28 + .../410. Split Array Largest Sum/410.java | 30 + solutions/410. Split Array Largest Sum/410.py | 16 + .../411.cpp | 84 +++ .../411.java | 84 +++ .../411.py | 61 +++ solutions/412. Fizz Buzz/412.cpp | 17 + solutions/412. Fizz Buzz/412.java | 16 + solutions/412. Fizz Buzz/412.py | 4 + solutions/413. Arithmetic Slices/413-2.cpp | 15 + solutions/413. Arithmetic Slices/413-2.java | 15 + solutions/413. Arithmetic Slices/413-2.py | 13 + solutions/413. Arithmetic Slices/413.cpp | 17 + solutions/413. Arithmetic Slices/413.java | 15 + solutions/413. Arithmetic Slices/413.py | 13 + solutions/414. Third Maximum Number/414-2.cpp | 20 + .../414. Third Maximum Number/414-2.java | 18 + solutions/414. Third Maximum Number/414-2.py | 16 + solutions/414. Third Maximum Number/414.cpp | 22 + solutions/414. Third Maximum Number/414.java | 21 + solutions/414. Third Maximum Number/414.py | 18 + solutions/415. Add Strings/415.cpp | 21 + solutions/415. Add Strings/415.java | 19 + solutions/415. Add Strings/415.py | 18 + .../416. Partition Equal Subset Sum/416-2.cpp | 22 + .../416-2.java | 21 + .../416. Partition Equal Subset Sum/416-2.py | 17 + .../416. Partition Equal Subset Sum/416.cpp | 28 + .../416. Partition Equal Subset Sum/416.java | 26 + .../416. Partition Equal Subset Sum/416.py | 22 + .../417-2.cpp | 42 ++ .../417-2.java | 39 ++ .../417. Pacific Atlantic Water Flow/417-2.py | 31 ++ .../417. Pacific Atlantic Water Flow/417.cpp | 55 ++ .../417. Pacific Atlantic Water Flow/417.java | 55 ++ .../417. Pacific Atlantic Water Flow/417.py | 40 ++ .../418. Sentence Screen Fitting/418.cpp | 28 + .../418. Sentence Screen Fitting/418.java | 19 + solutions/418. Sentence Screen Fitting/418.py | 15 + solutions/419. Battleships in a Board/419.cpp | 19 + .../419. Battleships in a Board/419.java | 18 + solutions/419. Battleships in a Board/419.py | 15 + solutions/42. Trapping Rain Water/42-2.cpp | 24 + solutions/42. Trapping Rain Water/42-2.java | 23 + solutions/42. Trapping Rain Water/42-2.py | 22 + solutions/42. Trapping Rain Water/42.cpp | 20 + solutions/42. Trapping Rain Water/42.java | 19 + solutions/42. Trapping Rain Water/42.py | 14 + .../420. Strong Password Checker/420.cpp | 54 ++ .../420. Strong Password Checker/420.java | 50 ++ solutions/420. Strong Password Checker/420.py | 47 ++ .../421-2.cpp | 60 ++ .../421-2.java | 58 ++ .../421-2.py | 48 ++ .../421.cpp | 35 ++ .../421.java | 34 ++ .../421.py | 28 + solutions/422. Valid Word Square/422.cpp | 13 + solutions/422. Valid Word Square/422.java | 12 + solutions/422. Valid Word Square/422.py | 9 + .../423.cpp | 42 ++ .../423.java | 41 ++ .../423.py | 33 ++ .../424-2.cpp | 19 + .../424-2.java | 18 + .../424-2.py | 15 + .../424.cpp | 17 + .../424.java | 16 + .../424.py | 16 + solutions/425. Word Squares/425.cpp | 87 +++ solutions/425. Word Squares/425.java | 81 +++ solutions/425. Word Squares/425.py | 67 +++ .../426-2.cpp | 32 ++ .../426-2.java | 31 ++ .../426-2.py | 25 + .../426.cpp | 32 ++ .../426.java | 30 + .../426.py | 27 + solutions/427. Construct Quad Tree/427.cpp | 27 + solutions/427. Construct Quad Tree/427.java | 25 + .../428.cpp | 69 +++ .../428.java | 52 ++ .../429.cpp | 24 + .../429.java | 22 + solutions/43. Multiply Strings/43.cpp | 17 + solutions/43. Multiply Strings/43.java | 23 + solutions/43. Multiply Strings/43.py | 16 + .../430-2.cpp | 20 + .../430-2.java | 19 + .../430-2.py | 19 + .../430.cpp | 13 + .../430.java | 16 + .../430.py | 13 + .../431-2.cpp | 39 ++ .../431-2.java | 38 ++ .../431-2.py | 33 ++ .../431.cpp | 53 ++ .../431.java | 52 ++ .../431.py | 43 ++ .../432. All O`one Data Structure/432.cpp | 75 +++ .../433. Minimum Genetic Mutation/433.cpp | 34 ++ .../433. Minimum Genetic Mutation/433.java | 33 ++ .../434.cpp | 12 + .../434.java | 11 + .../434.py | 3 + .../435. Non-overlapping Intervals/435.cpp | 21 + .../435. Non-overlapping Intervals/435.java | 19 + .../435. Non-overlapping Intervals/435.py | 12 + solutions/436. Find Right Interval/436.cpp | 20 + solutions/436. Find Right Interval/436.java | 21 + solutions/437. Path Sum III/437.cpp | 19 + solutions/437. Path Sum III/437.java | 15 + solutions/437. Path Sum III/437.py | 15 + .../438.cpp | 24 + .../438.java | 23 + .../438. Find All Anagrams in a String/438.py | 18 + .../439. Ternary Expression Parser/439.cpp | 19 + .../439. Ternary Expression Parser/439.java | 17 + .../439. Ternary Expression Parser/439.py | 15 + solutions/44. Wildcard Matching/44.cpp | 30 + solutions/44. Wildcard Matching/44.java | 29 + solutions/44. Wildcard Matching/44.py | 25 + .../440.cpp | 29 + .../440.java | 28 + solutions/441. Arranging Coins/441.cpp | 6 + solutions/441. Arranging Coins/441.java | 5 + solutions/441. Arranging Coins/441.py | 3 + .../442.cpp | 14 + .../442.java | 13 + .../442.py | 10 + solutions/443. String Compression/443.cpp | 21 + solutions/443. String Compression/443.java | 20 + solutions/443. String Compression/443.py | 19 + .../444. Sequence Reconstruction/444.cpp | 49 ++ .../444. Sequence Reconstruction/444.java | 49 ++ solutions/444. Sequence Reconstruction/444.py | 36 ++ solutions/445. Add Two Numbers II/445.cpp | 33 ++ solutions/445. Add Two Numbers II/445.java | 32 ++ solutions/445. Add Two Numbers II/445.py | 27 + .../446.cpp | 26 + .../446.java | 26 + solutions/447. Number of Boomerangs/447.cpp | 23 + solutions/447. Number of Boomerangs/447.java | 21 + solutions/447. Number of Boomerangs/447.py | 11 + .../448.cpp | 17 + .../448.java | 16 + .../448.py | 7 + .../449.cpp | 50 ++ .../449.java | 50 ++ solutions/45. Jump Game II/45.cpp | 23 + solutions/45. Jump Game II/45.java | 22 + solutions/45. Jump Game II/45.py | 17 + solutions/450. Delete Node in a BST/450.cpp | 30 + solutions/450. Delete Node in a BST/450.java | 28 + solutions/450. Delete Node in a BST/450.py | 24 + .../451. Sort Characters By Frequency/451.cpp | 25 + .../451.java | 29 + .../451. Sort Characters By Frequency/451.py | 13 + .../452.cpp | 18 + .../452.java | 16 + .../452.py | 11 + .../453.cpp | 9 + .../453.java | 7 + .../453.py | 4 + solutions/454. 4Sum II/454.cpp | 19 + solutions/454. 4Sum II/454.java | 17 + solutions/454. 4Sum II/454.py | 5 + solutions/455. Assign Cookies/455.cpp | 14 + solutions/455. Assign Cookies/455.java | 13 + solutions/456. 132 Pattern/456.cpp | 18 + solutions/456. 132 Pattern/456.java | 17 + solutions/457. Circular Array Loop/457.cpp | 39 ++ solutions/457. Circular Array Loop/457.java | 38 ++ solutions/457. Circular Array Loop/457.py | 30 + solutions/458. Poor Pigs/458.cpp | 10 + solutions/458. Poor Pigs/458.java | 9 + solutions/458. Poor Pigs/458.py | 9 + .../459. Repeated Substring Pattern/459.cpp | 7 + .../459. Repeated Substring Pattern/459.java | 6 + .../459. Repeated Substring Pattern/459.py | 3 + solutions/46. Permutations/46.cpp | 28 + solutions/46. Permutations/46.java | 25 + solutions/46. Permutations/46.py | 21 + solutions/460. LFU Cache/460.cpp | 68 +++ solutions/460. LFU Cache/460.java | 55 ++ solutions/461. Hamming Distance/461.cpp | 14 + solutions/461. Hamming Distance/461.java | 13 + .../462.cpp | 11 + .../462.java | 37 ++ .../462.py | 7 + solutions/463. Island Perimeter/463.cpp | 19 + solutions/463. Island Perimeter/463.java | 18 + solutions/463. Island Perimeter/463.py | 18 + solutions/464. Can I Win/464.cpp | 34 ++ solutions/464. Can I Win/464.java | 32 ++ .../465. Optimal Account Balancing/465.cpp | 40 ++ .../465. Optimal Account Balancing/465.java | 38 ++ .../465. Optimal Account Balancing/465.py | 27 + solutions/466. Count The Repetitions/466.cpp | 35 ++ solutions/466. Count The Repetitions/466.java | 37 ++ .../467.cpp | 19 + .../467.java | 18 + solutions/468. Validate IP Address/468.cpp | 51 ++ solutions/468. Validate IP Address/468.java | 46 ++ solutions/469. Convex Polygon/469.cpp | 25 + solutions/469. Convex Polygon/469.java | 23 + solutions/469. Convex Polygon/469.py | 17 + solutions/47. Permutations II/47.cpp | 30 + solutions/47. Permutations II/47.java | 27 + solutions/47. Permutations II/47.py | 24 + .../470.cpp | 15 + .../470.java | 16 + .../471-2.cpp | 40 ++ .../471-2.java | 37 ++ .../471.cpp | 44 ++ .../471.java | 41 ++ solutions/472. Concatenated Words/472.cpp | 31 ++ solutions/472. Concatenated Words/472.java | 31 ++ solutions/472. Concatenated Words/472.py | 15 + solutions/473. Matchsticks to Square/473.cpp | 31 ++ solutions/473. Matchsticks to Square/473.java | 31 ++ solutions/473. Matchsticks to Square/473.py | 26 + solutions/474. Ones and Zeroes/474.cpp | 18 + solutions/474. Ones and Zeroes/474.java | 17 + solutions/474. Ones and Zeroes/474.py | 14 + solutions/475. Heaters/475.cpp | 19 + solutions/475. Heaters/475.java | 17 + solutions/476. Number Complement/476.cpp | 8 + solutions/476. Number Complement/476.java | 7 + solutions/477. Total Hamming Distance/477.cpp | 16 + .../477. Total Hamming Distance/477.java | 15 + solutions/477. Total Hamming Distance/477.py | 11 + .../478.cpp | 21 + .../478.java | 19 + .../478.py | 12 + .../479. Largest Palindrome Product/479.cpp | 27 + .../479. Largest Palindrome Product/479.java | 24 + .../479. Largest Palindrome Product/479.py | 16 + solutions/48. Rotate Image/48-2.cpp | 16 + solutions/48. Rotate Image/48-2.java | 15 + solutions/48. Rotate Image/48-2.py | 11 + solutions/48. Rotate Image/48.cpp | 9 + solutions/48. Rotate Image/48.java | 16 + solutions/48. Rotate Image/48.py | 7 + solutions/480. Sliding Window Median/480.cpp | 23 + solutions/481. Magical String/481.cpp | 14 + solutions/482. License Key Formatting/482.cpp | 18 + .../482. License Key Formatting/482.java | 17 + solutions/482. License Key Formatting/482.py | 14 + solutions/483. Smallest Good Base/483.cpp | 20 + solutions/483. Smallest Good Base/483.java | 20 + solutions/483. Smallest Good Base/483.py | 10 + solutions/484. Find Permutation/484-2.cpp | 30 + solutions/484. Find Permutation/484-2.java | 40 ++ solutions/484. Find Permutation/484-2.py | 22 + solutions/484. Find Permutation/484.cpp | 20 + solutions/484. Find Permutation/484.java | 20 + solutions/484. Find Permutation/484.py | 16 + solutions/485. Max Consecutive Ones/485.cpp | 15 + solutions/485. Max Consecutive Ones/485.java | 14 + solutions/485. Max Consecutive Ones/485.py | 13 + solutions/486. Predict the Winner/486-2.cpp | 16 + solutions/486. Predict the Winner/486-2.java | 15 + solutions/486. Predict the Winner/486.cpp | 20 + solutions/486. Predict the Winner/486.java | 18 + .../487. Max Consecutive Ones II/487-2.cpp | 18 + .../487. Max Consecutive Ones II/487-2.java | 18 + .../487. Max Consecutive Ones II/487-2.py | 15 + .../487. Max Consecutive Ones II/487-3.cpp | 17 + .../487. Max Consecutive Ones II/487-3.java | 16 + .../487. Max Consecutive Ones II/487-3.py | 13 + .../487. Max Consecutive Ones II/487.cpp | 18 + .../487. Max Consecutive Ones II/487.java | 17 + solutions/487. Max Consecutive Ones II/487.py | 16 + solutions/488. Zuma Game/488.cpp | 52 ++ solutions/488. Zuma Game/488.java | 54 ++ solutions/488. Zuma Game/488.py | 36 ++ solutions/489. Robot Room Cleaner/489.cpp | 59 ++ solutions/489. Robot Room Cleaner/489.java | 49 ++ solutions/49. Group Anagrams/49.cpp | 18 + solutions/49. Group Anagrams/49.java | 14 + solutions/49. Group Anagrams/49.py | 9 + solutions/490. The Maze/490-2.cpp | 40 ++ solutions/490. The Maze/490-2.java | 34 ++ solutions/490. The Maze/490-2.py | 31 ++ solutions/490. The Maze/490.cpp | 39 ++ solutions/490. The Maze/490.java | 35 ++ solutions/490. The Maze/490.py | 27 + .../491. Increasing Subsequences/491.cpp | 28 + .../491. Increasing Subsequences/491.java | 25 + solutions/491. Increasing Subsequences/491.py | 19 + .../492. Construct the Rectangle/492.cpp | 11 + .../492. Construct the Rectangle/492.java | 10 + solutions/493. Reverse Pairs/493-2.cpp | 88 +++ solutions/493. Reverse Pairs/493-3.cpp | 95 ++++ solutions/493. Reverse Pairs/493-4.cpp | 52 ++ solutions/493. Reverse Pairs/493.cpp | 56 ++ solutions/494. Target Sum/494-2.cpp | 22 + solutions/494. Target Sum/494-2.java | 20 + solutions/494. Target Sum/494-2.py | 18 + solutions/494. Target Sum/494.cpp | 28 + solutions/494. Target Sum/494.java | 26 + solutions/494. Target Sum/494.py | 17 + solutions/495. Teemo Attacking/495.cpp | 14 + solutions/495. Teemo Attacking/495.java | 13 + solutions/495. Teemo Attacking/495.py | 11 + solutions/496. Next Greater Element I/496.cpp | 23 + .../496. Next Greater Element I/496.java | 21 + solutions/496. Next Greater Element I/496.py | 11 + .../497.cpp | 24 + .../497.java | 31 ++ .../497.py | 10 + solutions/498. Diagonal Traverse/498.cpp | 28 + solutions/498. Diagonal Traverse/498.java | 37 ++ solutions/499. The Maze III/499.cpp | 42 ++ solutions/499. The Maze III/499.java | 40 ++ solutions/499. The Maze III/499.py | 34 ++ .../5. Longest Palindromic Substring/5-2.cpp | 54 ++ .../5. Longest Palindromic Substring/5-2.java | 50 ++ .../5. Longest Palindromic Substring/5-2.py | 30 + .../5. Longest Palindromic Substring/5.cpp | 33 ++ .../5. Longest Palindromic Substring/5.java | 31 ++ .../5. Longest Palindromic Substring/5.py | 30 + solutions/50. Pow(x, n)/50.cpp | 12 + solutions/50. Pow(x, n)/50.java | 11 + solutions/50. Pow(x, n)/50.py | 9 + solutions/500. Keyboard Row/500.cpp | 20 + solutions/500. Keyboard Row/500.java | 17 + solutions/500. Keyboard Row/500.py | 11 + .../501.cpp | 40 ++ .../501.java | 39 ++ .../501.py | 31 ++ solutions/502. IPO/502.cpp | 29 + solutions/502. IPO/502.java | 28 + .../503. Next Greater Element II/503.cpp | 18 + .../503. Next Greater Element II/503.java | 18 + solutions/503. Next Greater Element II/503.py | 14 + solutions/504. Base 7/504.cpp | 10 + solutions/504. Base 7/504.java | 9 + solutions/505. The Maze II/505-2.cpp | 43 ++ solutions/505. The Maze II/505-2.java | 39 ++ solutions/505. The Maze II/505.cpp | 43 ++ solutions/505. The Maze II/505.java | 38 ++ solutions/506. Relative Ranks/506.cpp | 25 + solutions/506. Relative Ranks/506.java | 24 + solutions/507. Perfect Number/507.cpp | 15 + solutions/507. Perfect Number/507.java | 14 + solutions/507. Perfect Number/507.py | 3 + .../508. Most Frequent Subtree Sum/508.cpp | 30 + .../508. Most Frequent Subtree Sum/508.java | 27 + .../508. Most Frequent Subtree Sum/508.py | 18 + solutions/509. Fibonacci Number/509.cpp | 17 + solutions/509. Fibonacci Number/509.java | 16 + solutions/509. Fibonacci Number/509.py | 13 + solutions/51. N-Queens/51.cpp | 29 + solutions/51. N-Queens/51.java | 37 ++ solutions/51. N-Queens/51.py | 21 + .../510. Inorder Successor in BST II/510.cpp | 17 + .../510. Inorder Successor in BST II/510.java | 16 + solutions/511. Game Play Analysis I/511.sql | 3 + solutions/512. Game Play Analysis II/512.sql | 7 + .../513-2.cpp | 21 + .../513-2.java | 21 + .../513. Find Bottom Left Tree Value/513-2.py | 19 + .../513. Find Bottom Left Tree Value/513.cpp | 18 + .../513. Find Bottom Left Tree Value/513.java | 16 + .../513. Find Bottom Left Tree Value/513.py | 12 + solutions/514. Freedom Trail/514.cpp | 33 ++ solutions/514. Freedom Trail/514.java | 32 ++ solutions/514. Freedom Trail/514.py | 23 + .../515-2.cpp | 21 + .../515-2.java | 19 + .../515-2.py | 17 + .../515.cpp | 26 + .../515.java | 24 + .../515.py | 20 + .../516-2.cpp | 22 + .../516-2.java | 21 + .../516-2.py | 18 + .../516.cpp | 22 + .../516.java | 20 + .../516.py | 14 + solutions/517. Super Washing Machines/517.cpp | 19 + .../517. Super Washing Machines/517.java | 18 + solutions/517. Super Washing Machines/517.py | 16 + solutions/518. Coin Change 2/518.cpp | 13 + solutions/518. Coin Change 2/518.java | 12 + solutions/518. Coin Change 2/518.py | 9 + solutions/519. Random Flip Matrix/519.cpp | 26 + solutions/519. Random Flip Matrix/519.java | 27 + solutions/52. N-Queens II/52.cpp | 26 + solutions/52. N-Queens II/52.java | 23 + solutions/52. N-Queens II/52.py | 22 + solutions/520. Detect Capital/520.cpp | 10 + solutions/520. Detect Capital/520.java | 6 + solutions/520. Detect Capital/520.py | 3 + .../521.cpp | 6 + .../521.java | 5 + .../521.py | 3 + .../522.cpp | 39 ++ .../522.java | 35 ++ .../522.py | 33 ++ .../523. Continuous Subarray Sum/523.cpp | 23 + .../523. Continuous Subarray Sum/523.java | 22 + solutions/523. Continuous Subarray Sum/523.py | 17 + .../524.cpp | 24 + .../524.java | 22 + .../524.py | 14 + solutions/525. Contiguous Array/525.cpp | 19 + solutions/525. Contiguous Array/525.java | 18 + solutions/525. Contiguous Array/525.py | 11 + solutions/526. Beautiful Arrangement/526.cpp | 25 + solutions/526. Beautiful Arrangement/526.java | 29 + solutions/527. Word Abbreviation/527-2.cpp | 54 ++ solutions/527. Word Abbreviation/527-2.java | 52 ++ solutions/527. Word Abbreviation/527-2.py | 43 ++ solutions/527. Word Abbreviation/527-3.cpp | 70 +++ solutions/527. Word Abbreviation/527-3.java | 69 +++ solutions/527. Word Abbreviation/527-3.py | 55 ++ solutions/527. Word Abbreviation/527.cpp | 39 ++ solutions/527. Word Abbreviation/527.java | 36 ++ solutions/527. Word Abbreviation/527.py | 31 ++ .../528. Random Pick with Weight/528-2.cpp | 14 + .../528. Random Pick with Weight/528-2.py | 6 + .../528. Random Pick with Weight/528.cpp | 25 + .../528. Random Pick with Weight/528.java | 26 + solutions/528. Random Pick with Weight/528.py | 8 + solutions/529. Minesweeper/529.cpp | 46 ++ solutions/529. Minesweeper/529.java | 43 ++ solutions/529. Minesweeper/529.py | 36 ++ solutions/53. Maximum Subarray/53-2.cpp | 14 + solutions/53. Maximum Subarray/53-2.java | 13 + solutions/53. Maximum Subarray/53-2.py | 10 + solutions/53. Maximum Subarray/53-3.cpp | 35 ++ solutions/53. Maximum Subarray/53-3.java | 29 + solutions/53. Maximum Subarray/53-3.py | 33 ++ solutions/53. Maximum Subarray/53.cpp | 13 + solutions/53. Maximum Subarray/53.java | 12 + solutions/53. Maximum Subarray/53.py | 10 + .../530.cpp | 23 + .../530.java | 22 + solutions/531. Lonely Pixel I/531.cpp | 29 + solutions/531. Lonely Pixel I/531.java | 28 + solutions/531. Lonely Pixel I/531.py | 24 + .../532. K-diff Pairs in an Array/532.cpp | 21 + .../532. K-diff Pairs in an Array/532.java | 19 + .../532. K-diff Pairs in an Array/532.py | 12 + solutions/533. Lonely Pixel II/533.cpp | 33 ++ solutions/533. Lonely Pixel II/533.java | 32 ++ solutions/533. Lonely Pixel II/533.py | 17 + solutions/534. Game Play Analysis III/534.sql | 11 + .../535. Encode and Decode TinyURL/535.cpp | 27 + .../535. Encode and Decode TinyURL/535.java | 29 + .../535. Encode and Decode TinyURL/535.py | 15 + .../536-2.cpp | 29 + .../536-2.java | 28 + .../536.cpp | 37 ++ .../536.java | 36 ++ .../537.cpp | 15 + .../537.java | 14 + .../537. Complex Number Multiplication/537.py | 9 + .../538. Convert BST to Greater Tree/538.cpp | 19 + .../538. Convert BST to Greater Tree/538.java | 18 + .../538. Convert BST to Greater Tree/538.py | 16 + .../539. Minimum Time Difference/539.cpp | 26 + .../539. Minimum Time Difference/539.java | 26 + solutions/539. Minimum Time Difference/539.py | 10 + solutions/54. Spiral Matrix/54.cpp | 30 + solutions/54. Spiral Matrix/54.java | 32 ++ solutions/54. Spiral Matrix/54.py | 37 ++ .../540.cpp | 19 + .../540.java | 18 + .../540.py | 15 + solutions/541. Reverse String II/541.cpp | 13 + solutions/541. Reverse String II/541.java | 18 + solutions/541. Reverse String II/541.py | 3 + solutions/542. 01 Matrix/542-2.cpp | 33 ++ solutions/542. 01 Matrix/542-2.java | 32 ++ solutions/542. 01 Matrix/542-2.py | 27 + solutions/542. 01 Matrix/542.cpp | 35 ++ solutions/542. 01 Matrix/542.java | 34 ++ solutions/542. 01 Matrix/542.py | 28 + .../543. Diameter of Binary Tree/543.cpp | 19 + .../543. Diameter of Binary Tree/543.java | 18 + solutions/543. Diameter of Binary Tree/543.py | 16 + .../544. Output Contest Matches/544-2.cpp | 17 + .../544. Output Contest Matches/544-2.java | 16 + .../544. Output Contest Matches/544-2.py | 10 + solutions/544. Output Contest Matches/544.cpp | 25 + .../544. Output Contest Matches/544.java | 22 + solutions/544. Output Contest Matches/544.py | 15 + .../545. Boundary of Binary Tree/545.cpp | 32 ++ .../545. Boundary of Binary Tree/545.java | 30 + solutions/545. Boundary of Binary Tree/545.py | 31 ++ solutions/546. Remove Boxes/546.cpp | 34 ++ solutions/546. Remove Boxes/546.java | 30 + solutions/546. Remove Boxes/546.py | 24 + solutions/547. Friend Circles/547.cpp | 50 ++ solutions/547. Friend Circles/547.java | 51 ++ solutions/547. Friend Circles/547.py | 37 ++ .../548. Split Array with Equal Sum/548.cpp | 25 + .../548. Split Array with Equal Sum/548.java | 25 + .../549.cpp | 41 ++ .../549.java | 45 ++ solutions/55. Jump Game/55.cpp | 11 + solutions/55. Jump Game/55.java | 10 + solutions/55. Jump Game/55.py | 10 + solutions/550. Game Play Analysis IV/550.sql | 18 + .../551. Student Attendance Record I/551.cpp | 18 + .../551. Student Attendance Record I/551.java | 5 + .../551. Student Attendance Record I/551.py | 3 + .../552. Student Attendance Record II/552.cpp | 38 ++ .../552.java | 35 ++ .../552. Student Attendance Record II/552.py | 30 + solutions/553. Optimal Division/553.cpp | 17 + solutions/553. Optimal Division/553.java | 16 + solutions/553. Optimal Division/553.py | 14 + solutions/554. Brick Wall/554.cpp | 17 + solutions/554. Brick Wall/554.java | 16 + solutions/554. Brick Wall/554.py | 13 + .../555. Split Concatenated Strings/555.cpp | 34 ++ .../555. Split Concatenated Strings/555.java | 32 ++ .../555. Split Concatenated Strings/555.py | 12 + .../556. Next Greater Element III/556.cpp | 35 ++ .../556. Next Greater Element III/556.java | 39 ++ .../556. Next Greater Element III/556.py | 27 + .../557.cpp | 17 + .../557.java | 25 + .../558.cpp | 23 + .../558.java | 21 + .../559. Maximum Depth of N-ary Tree/559.cpp | 14 + .../559. Maximum Depth of N-ary Tree/559.java | 13 + .../559. Maximum Depth of N-ary Tree/559.py | 7 + solutions/56. Merge Intervals/56.cpp | 16 + solutions/56. Merge Intervals/56.java | 15 + solutions/56. Merge Intervals/56.py | 11 + solutions/560. Subarray Sum Equals K/560.cpp | 18 + solutions/560. Subarray Sum Equals K/560.java | 16 + solutions/560. Subarray Sum Equals K/560.py | 12 + solutions/561. Array Partition I/561.cpp | 13 + solutions/561. Array Partition I/561.java | 12 + solutions/561. Array Partition I/561.py | 3 + .../562.cpp | 25 + .../562.java | 25 + .../562.py | 21 + solutions/563. Binary Tree Tilt/563.cpp | 19 + solutions/563. Binary Tree Tilt/563.java | 18 + solutions/563. Binary Tree Tilt/563.py | 16 + .../564. Find the Closest Palindrome/564.cpp | 46 ++ .../564. Find the Closest Palindrome/564.java | 45 ++ .../564. Find the Closest Palindrome/564.py | 33 ++ solutions/565. Array Nesting/565.cpp | 22 + solutions/565. Array Nesting/565.java | 21 + solutions/565. Array Nesting/565.py | 17 + solutions/566. Reshape the Matrix/566.cpp | 18 + solutions/566. Reshape the Matrix/566.java | 17 + solutions/566. Reshape the Matrix/566.py | 14 + .../567. Permutation in String/567-2.cpp | 22 + .../567. Permutation in String/567-2.java | 21 + solutions/567. Permutation in String/567-2.py | 17 + solutions/567. Permutation in String/567.cpp | 23 + solutions/567. Permutation in String/567.java | 22 + .../568. Maximum Vacation Days/568-2.cpp | 20 + .../568. Maximum Vacation Days/568-2.java | 19 + .../568. Maximum Vacation Days/568-3.cpp | 22 + .../568. Maximum Vacation Days/568-3.java | 21 + solutions/568. Maximum Vacation Days/568.cpp | 27 + solutions/568. Maximum Vacation Days/568.java | 23 + solutions/569. Median Employee Salary/569.sql | 18 + solutions/57. Insert Interval/57.cpp | 26 + solutions/57. Insert Interval/57.java | 24 + solutions/57. Insert Interval/57.py | 23 + .../570.sql | 6 + .../571.sql | 11 + .../572. Subtree of Another Tree/572.cpp | 19 + .../572. Subtree of Another Tree/572.java | 15 + solutions/573. Squirrel Simulation/573.cpp | 20 + solutions/573. Squirrel Simulation/573.java | 17 + solutions/573. Squirrel Simulation/573.py | 8 + solutions/574. Winning Candidate/574.sql | 7 + solutions/575. Distribute Candies/575.cpp | 11 + solutions/575. Distribute Candies/575.java | 10 + solutions/575. Distribute Candies/575.py | 3 + .../576. Out of Boundary Paths/576-2.cpp | 29 + .../576. Out of Boundary Paths/576-2.java | 28 + solutions/576. Out of Boundary Paths/576-2.py | 24 + solutions/576. Out of Boundary Paths/576.cpp | 28 + solutions/576. Out of Boundary Paths/576.java | 24 + solutions/576. Out of Boundary Paths/576.py | 18 + solutions/577. Employee Bonus/577.sql | 5 + .../578.sql | 7 + .../579.sql | 17 + solutions/58. Length of Last Word/58.cpp | 14 + solutions/58. Length of Last Word/58.java | 13 + solutions/58. Length of Last Word/58.py | 11 + .../580.sql | 8 + .../581.cpp | 36 ++ .../581.java | 35 ++ .../581.py | 29 + solutions/582. Kill Process/582.cpp | 26 + solutions/582. Kill Process/582.java | 22 + solutions/582. Kill Process/582.py | 17 + .../583.cpp | 24 + .../583.java | 22 + .../583.py | 19 + solutions/584. Find Customer Referee/584.sql | 3 + solutions/585. Investments in 2016/585.sql | 12 + .../586.sql | 5 + solutions/587. Erect the Fence/587.cpp | 44 ++ solutions/587. Erect the Fence/587.java | 30 + solutions/587. Erect the Fence/587.py | 24 + .../588. Design In-Memory File System/588.cpp | 65 +++ .../589.cpp | 19 + .../589.java | 19 + solutions/59. Spiral Matrix II/59.cpp | 24 + solutions/59. Spiral Matrix II/59.java | 23 + solutions/59. Spiral Matrix II/59.py | 24 + .../590.cpp | 20 + .../590.java | 20 + solutions/591. Tag Validator/591.cpp | 69 +++ solutions/591. Tag Validator/591.java | 55 ++ solutions/591. Tag Validator/591.py | 47 ++ .../592.cpp | 24 + .../592.java | 26 + .../592.py | 14 + solutions/593. Valid Square/593.cpp | 20 + solutions/593. Valid Square/593.java | 16 + solutions/593. Valid Square/593.py | 9 + .../594.cpp | 16 + .../594.java | 15 + .../594.py | 10 + solutions/595. Big Countries/595.sql | 3 + .../596. Classes More Than 5 Students/596.sql | 4 + .../597.sql | 15 + solutions/598. Range Addition II/598.cpp | 14 + solutions/598. Range Addition II/598.java | 13 + solutions/598. Range Addition II/598.py | 10 + .../599.cpp | 27 + .../599.java | 26 + .../599.py | 17 + solutions/6. ZigZag Conversion/6.cpp | 22 + solutions/6. ZigZag Conversion/6.java | 24 + solutions/6. ZigZag Conversion/6.py | 13 + solutions/60. Permutation Sequence/60.cpp | 24 + solutions/60. Permutation Sequence/60.java | 25 + solutions/60. Permutation Sequence/60.py | 18 + .../600.cpp | 29 + .../600.java | 31 ++ .../601. Human Traffic of Stadium/601-2.sql | 19 + .../601. Human Traffic of Stadium/601.sql | 24 + .../602.sql | 13 + .../603. Consecutive Available Seats/603.sql | 12 + .../604-2.cpp | 30 + .../604-2.java | 30 + .../604-2.py | 25 + .../604.cpp | 28 + .../604.java | 28 + .../604.py | 23 + solutions/605. Can Place Flowers/605.cpp | 17 + solutions/605. Can Place Flowers/605.java | 16 + solutions/605. Can Place Flowers/605.py | 10 + .../606.cpp | 19 + .../606.java | 15 + .../606.py | 11 + solutions/607. Sales Person/607.sql | 7 + solutions/608. Tree Node/608.sql | 11 + .../609.cpp | 32 ++ .../609.java | 30 + .../609. Find Duplicate File in System/609.py | 19 + solutions/61. Rotate List/61.cpp | 21 + solutions/61. Rotate List/61.java | 20 + solutions/61. Rotate List/61.py | 19 + solutions/610. Triangle Judgement/610.sql | 4 + solutions/611. Valid Triangle Number/611.cpp | 29 + solutions/611. Valid Triangle Number/611.java | 28 + solutions/611. Valid Triangle Number/611.py | 17 + .../612. Shortest Distance in a Plane/612.sql | 7 + .../613. Shortest Distance in a Line/613.sql | 3 + solutions/614. Second Degree Follower/614.sql | 8 + .../615.sql | 25 + .../616. Add Bold Tag in String/616-2.cpp | 66 +++ .../616. Add Bold Tag in String/616-2.java | 63 +++ .../616. Add Bold Tag in String/616-2.py | 54 ++ .../616. Add Bold Tag in String/616-3.cpp | 39 ++ solutions/616. Add Bold Tag in String/616.cpp | 33 ++ .../616. Add Bold Tag in String/616.java | 32 ++ solutions/616. Add Bold Tag in String/616.py | 29 + solutions/617. Merge Two Binary Trees/617.cpp | 15 + .../617. Merge Two Binary Trees/617.java | 11 + solutions/617. Merge Two Binary Trees/617.py | 11 + .../618. Students Report By Geography/618.sql | 14 + solutions/619. Biggest Single Number/619.sql | 9 + solutions/62. Unique Paths/62-2.cpp | 12 + solutions/62. Unique Paths/62-2.java | 12 + solutions/62. Unique Paths/62-2.py | 9 + solutions/62. Unique Paths/62.cpp | 13 + solutions/62. Unique Paths/62.java | 13 + solutions/62. Unique Paths/62.py | 10 + solutions/620. Not Boring Movies/620.sql | 6 + solutions/621. Task Scheduler/621.cpp | 24 + solutions/621. Task Scheduler/621.java | 20 + solutions/621. Task Scheduler/621.py | 14 + solutions/622. Design Circular Queue/622.cpp | 55 ++ solutions/622. Design Circular Queue/622.java | 55 ++ solutions/623. Add One Row to Tree/623.cpp | 37 ++ solutions/623. Add One Row to Tree/623.java | 35 ++ .../624. Maximum Distance in Arrays/624-2.py | 12 + .../624. Maximum Distance in Arrays/624.cpp | 16 + .../624. Maximum Distance in Arrays/624.java | 15 + .../624. Maximum Distance in Arrays/624.py | 12 + solutions/625. Minimum Factorization/625.cpp | 19 + solutions/625. Minimum Factorization/625.java | 18 + solutions/625. Minimum Factorization/625.py | 15 + solutions/626. Exchange Seats/626.sql | 4 + solutions/627. Swap Salary/627.sql | 2 + .../628-2.cpp | 31 ++ .../628-2.java | 30 + .../628-2.py | 26 + .../628.cpp | 9 + .../628.java | 7 + .../628.py | 5 + solutions/629. K Inverse Pairs Array/629.cpp | 22 + solutions/629. K Inverse Pairs Array/629.java | 20 + solutions/629. K Inverse Pairs Array/629.py | 17 + solutions/63. Unique Paths II/63-2.cpp | 18 + solutions/63. Unique Paths II/63-2.java | 17 + solutions/63. Unique Paths II/63-2.py | 15 + solutions/63. Unique Paths II/63.cpp | 17 + solutions/63. Unique Paths II/63.java | 16 + solutions/63. Unique Paths II/63.py | 14 + solutions/630. Course Schedule III/630.cpp | 24 + solutions/630. Course Schedule III/630.java | 22 + solutions/630. Course Schedule III/630.py | 15 + .../631. Design Excel Sum Formula/631.cpp | 59 ++ .../631. Design Excel Sum Formula/631.java | 70 +++ .../631. Design Excel Sum Formula/631.py | 32 ++ .../632.cpp | 42 ++ .../632.java | 44 ++ .../632.py | 19 + solutions/633. Sum of Square Numbers/633.cpp | 19 + solutions/633. Sum of Square Numbers/633.java | 18 + solutions/633. Sum of Square Numbers/633.py | 15 + .../634-2.cpp | 14 + .../634-2.java | 13 + .../634-2.py | 9 + .../634.cpp | 23 + .../634.java | 21 + .../634.py | 13 + .../635. Design Log Storage System/635.cpp | 27 + .../635. Design Log Storage System/635.java | 33 ++ .../635. Design Log Storage System/635.py | 15 + .../636. Exclusive Time of Functions/636.cpp | 29 + .../636. Exclusive Time of Functions/636.java | 26 + .../637.cpp | 24 + .../637.java | 22 + solutions/638. Shopping Offers/638.cpp | 36 ++ solutions/638. Shopping Offers/638.java | 34 ++ solutions/638. Shopping Offers/638.py | 21 + solutions/639. Decode Ways II/639-2.cpp | 44 ++ solutions/639. Decode Ways II/639-2.java | 42 ++ solutions/639. Decode Ways II/639.cpp | 45 ++ solutions/639. Decode Ways II/639.java | 43 ++ solutions/64. Minimum Path Sum/64.cpp | 18 + solutions/64. Minimum Path Sum/64.java | 17 + solutions/64. Minimum Path Sum/64.py | 15 + solutions/640. Solve the Equation/640.cpp | 43 ++ solutions/640. Solve the Equation/640.java | 40 ++ solutions/640. Solve the Equation/640.py | 34 ++ solutions/641. Design Circular Deque/641.cpp | 78 +++ solutions/641. Design Circular Deque/641.java | 76 +++ .../642.java | 73 +++ .../642.py | 56 ++ .../643. Maximum Average Subarray I/643.cpp | 14 + .../643. Maximum Average Subarray I/643.java | 15 + .../643. Maximum Average Subarray I/643.py | 10 + .../644. Maximum Average Subarray II/644.cpp | 41 ++ .../644. Maximum Average Subarray II/644.java | 39 ++ .../644. Maximum Average Subarray II/644.py | 35 ++ solutions/645. Set Mismatch/645.cpp | 18 + solutions/645. Set Mismatch/645.java | 18 + solutions/645. Set Mismatch/645.py | 11 + .../646. Maximum Length of Pair Chain/646.cpp | 18 + .../646.java | 18 + .../646. Maximum Length of Pair Chain/646.py | 11 + solutions/647. Palindromic Substrings/647.cpp | 26 + .../647. Palindromic Substrings/647.java | 24 + solutions/647. Palindromic Substrings/647.py | 19 + solutions/648. Replace Words/648.cpp | 49 ++ solutions/648. Replace Words/648.java | 45 ++ solutions/648. Replace Words/648.py | 28 + solutions/649. Dota2 Senate/649.cpp | 27 + solutions/65. Valid Number/65.cpp | 47 ++ solutions/65. Valid Number/65.java | 40 ++ solutions/65. Valid Number/65.py | 30 + solutions/650. 2 Keys Keyboard/650.cpp | 22 + solutions/650. 2 Keys Keyboard/650.java | 17 + solutions/650. 2 Keys Keyboard/650.py | 16 + solutions/651. 4 Keys Keyboard/651-2.cpp | 16 + solutions/651. 4 Keys Keyboard/651-2.java | 14 + solutions/651. 4 Keys Keyboard/651.cpp | 11 + solutions/651. 4 Keys Keyboard/651.java | 10 + .../652. Find Duplicate Subtrees/652.cpp | 23 + .../652. Find Duplicate Subtrees/652.java | 19 + solutions/652. Find Duplicate Subtrees/652.py | 19 + .../653. Two Sum IV - Input is a BST/653.cpp | 47 ++ .../653. Two Sum IV - Input is a BST/653.java | 48 ++ .../653. Two Sum IV - Input is a BST/653.py | 40 ++ solutions/654. Maximum Binary Tree/654.cpp | 21 + solutions/654. Maximum Binary Tree/654.java | 20 + solutions/654. Maximum Binary Tree/654.py | 15 + solutions/655. Print Binary Tree/655.cpp | 28 + solutions/655. Print Binary Tree/655.java | 33 ++ solutions/655. Print Binary Tree/655.py | 21 + solutions/656. Coin Path/656-2.cpp | 42 ++ solutions/656. Coin Path/656-2.java | 43 ++ solutions/656. Coin Path/656-2.py | 33 ++ solutions/656. Coin Path/656.cpp | 50 ++ solutions/656. Coin Path/656.java | 49 ++ solutions/656. Coin Path/656.py | 41 ++ solutions/657. Robot Return to Origin/657.cpp | 26 + .../657. Robot Return to Origin/657.java | 25 + solutions/657. Robot Return to Origin/657.py | 3 + .../658. Find K Closest Elements/658.cpp | 17 + .../658. Find K Closest Elements/658.java | 16 + solutions/658. Find K Closest Elements/658.py | 13 + .../659.cpp | 30 + .../659.java | 29 + solutions/66. Plus One/66.cpp | 15 + solutions/66. Plus One/66.java | 15 + solutions/66. Plus One/66.py | 9 + solutions/660. Remove 9/660.cpp | 11 + solutions/660. Remove 9/660.java | 5 + solutions/660. Remove 9/660.py | 7 + solutions/661. Image Smoother/661.cpp | 22 + solutions/661. Image Smoother/661.java | 21 + solutions/661. Image Smoother/661.py | 17 + .../662-2.cpp | 24 + .../662. Maximum Width of Binary Tree/662.cpp | 25 + .../662.java | 25 + solutions/663. Equal Tree Partition/663.cpp | 21 + solutions/663. Equal Tree Partition/663.java | 19 + solutions/663. Equal Tree Partition/663.py | 17 + solutions/664. Strange Printer/664-2.cpp | 21 + solutions/664. Strange Printer/664-2.java | 22 + solutions/664. Strange Printer/664.cpp | 27 + solutions/664. Strange Printer/664.java | 25 + solutions/665. Non-decreasing Array/665.cpp | 19 + solutions/665. Non-decreasing Array/665.java | 16 + solutions/665. Non-decreasing Array/665.py | 12 + solutions/666. Path Sum IV/666.cpp | 30 + solutions/666. Path Sum IV/666.java | 30 + solutions/666. Path Sum IV/666.py | 24 + .../667. Beautiful Arrangement II/667.cpp | 17 + .../667. Beautiful Arrangement II/667.java | 17 + .../667. Beautiful Arrangement II/667.py | 11 + .../668.cpp | 25 + .../668.java | 24 + .../669. Trim a Binary Search Tree/669.cpp | 14 + .../669. Trim a Binary Search Tree/669.java | 13 + solutions/67. Add Binary/67.cpp | 21 + solutions/67. Add Binary/67.java | 19 + solutions/67. Add Binary/67.py | 18 + solutions/670. Maximum Swap/670.cpp | 19 + solutions/670. Maximum Swap/670.java | 19 + solutions/670. Maximum Swap/670.py | 14 + .../671.cpp | 23 + .../671.java | 21 + solutions/672. Bulb Switcher II/672.cpp | 15 + solutions/672. Bulb Switcher II/672.java | 14 + solutions/672. Bulb Switcher II/672.py | 12 + .../673.cpp | 34 ++ .../673.java | 36 ++ .../673.py | 28 + .../674.cpp | 14 + .../674.java | 13 + .../674.py | 11 + .../675. Cut Off Trees for Golf Event/675.cpp | 71 +++ .../675.java | 72 +++ .../676. Implement Magic Dictionary/676-2.cpp | 59 ++ .../676-2.java | 56 ++ .../676. Implement Magic Dictionary/676-2.py | 44 ++ .../676. Implement Magic Dictionary/676.cpp | 27 + .../676. Implement Magic Dictionary/676.java | 24 + .../676. Implement Magic Dictionary/676.py | 19 + solutions/677. Map Sum Pairs/677.cpp | 36 ++ solutions/677. Map Sum Pairs/677.java | 33 ++ solutions/677. Map Sum Pairs/677.py | 26 + .../678. Valid Parenthesis String/678.cpp | 28 + .../678. Valid Parenthesis String/678.java | 27 + .../678. Valid Parenthesis String/678.py | 21 + solutions/679. 24 Game/679.cpp | 37 ++ solutions/679. 24 Game/679.java | 34 ++ solutions/679. 24 Game/679.py | 26 + solutions/68. Text Justification/68.cpp | 52 ++ solutions/68. Text Justification/68.java | 43 ++ solutions/68. Text Justification/68.py | 20 + solutions/680. Valid Palindrome II/680.cpp | 18 + solutions/680. Valid Palindrome II/680.java | 15 + solutions/680. Valid Palindrome II/680.py | 12 + solutions/681. Next Closest Time/681.cpp | 28 + solutions/681. Next Closest Time/681.java | 27 + solutions/681. Next Closest Time/681.py | 23 + solutions/682. Baseball Game/682.cpp | 18 + solutions/682. Baseball Game/682.java | 26 + solutions/682. Baseball Game/682.py | 16 + solutions/683. K Empty Slots/683.cpp | 28 + solutions/683. K Empty Slots/683.java | 27 + solutions/683. K Empty Slots/683.py | 26 + solutions/684. Redundant Connection/684.cpp | 46 ++ solutions/684. Redundant Connection/684.java | 46 ++ solutions/684. Redundant Connection/684.py | 33 ++ .../685. Redundant Connection II/685.cpp | 71 +++ .../685. Redundant Connection II/685.java | 71 +++ solutions/685. Redundant Connection II/685.py | 56 ++ solutions/686. Repeated String Match/686.cpp | 16 + solutions/686. Repeated String Match/686.java | 11 + solutions/686. Repeated String Match/686.py | 9 + solutions/687. Longest Univalue Path/687.cpp | 23 + solutions/687. Longest Univalue Path/687.java | 20 + solutions/687. Longest Univalue Path/687.py | 18 + .../688.cpp | 32 ++ .../688.java | 27 + .../688.py | 20 + .../689.cpp | 47 ++ .../689.java | 46 ++ .../689.py | 40 ++ solutions/69. Sqrt(x)/69.cpp | 18 + solutions/69. Sqrt(x)/69.java | 17 + solutions/69. Sqrt(x)/69.py | 4 + solutions/690. Employee Importance/690.cpp | 21 + solutions/690. Employee Importance/690.java | 19 + solutions/690. Employee Importance/690.py | 11 + solutions/691. Stickers to Spell Word/691.cpp | 30 + .../691. Stickers to Spell Word/691.java | 30 + solutions/691. Stickers to Spell Word/691.py | 23 + solutions/692. Top K Frequent Words/692-2.cpp | 35 ++ .../692. Top K Frequent Words/692-2.java | 35 ++ solutions/692. Top K Frequent Words/692-2.py | 28 + solutions/692. Top K Frequent Words/692.cpp | 26 + solutions/692. Top K Frequent Words/692.java | 30 + solutions/692. Top K Frequent Words/692.py | 13 + .../693.cpp | 12 + .../693.java | 11 + .../693.py | 9 + .../694. Number of Distinct Islands/694.cpp | 36 ++ .../694. Number of Distinct Islands/694.java | 34 ++ .../694. Number of Distinct Islands/694.py | 27 + solutions/695. Max Area of Island/695.cpp | 26 + solutions/695. Max Area of Island/695.java | 24 + solutions/695. Max Area of Island/695.py | 13 + .../696. Count Binary Substrings/696.cpp | 19 + .../696. Count Binary Substrings/696.java | 18 + solutions/696. Count Binary Substrings/696.py | 15 + solutions/697. Degree of an Array/697.cpp | 23 + solutions/697. Degree of an Array/697.java | 21 + solutions/697. Degree of an Array/697.py | 17 + .../698.cpp | 36 ++ .../698.java | 32 ++ .../698.py | 28 + solutions/699. Falling Squares/699.cpp | 39 ++ solutions/7. Reverse Integer/7.cpp | 13 + solutions/7. Reverse Integer/7.java | 12 + solutions/7. Reverse Integer/7.py | 11 + solutions/70. Climbing Stairs/70-2.cpp | 15 + solutions/70. Climbing Stairs/70-2.java | 14 + solutions/70. Climbing Stairs/70-2.py | 11 + solutions/70. Climbing Stairs/70.cpp | 14 + solutions/70. Climbing Stairs/70.java | 13 + solutions/70. Climbing Stairs/70.py | 9 + .../700.cpp | 12 + .../700.java | 11 + .../700.py | 9 + .../701.cpp | 12 + .../701.java | 11 + .../701.py | 9 + .../702.cpp | 26 + .../702.java | 24 + .../702.py | 12 + .../703.cpp | 22 + .../703.java | 21 + solutions/704. Binary Search/704.cpp | 8 + solutions/704. Binary Search/704.java | 6 + solutions/704. Binary Search/704.py | 4 + solutions/705. Design HashSet/705.cpp | 21 + solutions/705. Design HashSet/705.java | 21 + solutions/705. Design HashSet/705.py | 12 + solutions/706. Design HashMap/706.cpp | 36 ++ solutions/706. Design HashMap/706.java | 34 ++ solutions/707. Design Linked List/707.cpp | 62 +++ solutions/707. Design Linked List/707.java | 62 +++ solutions/707. Design Linked List/707.py | 52 ++ .../708.cpp | 32 ++ .../708.java | 30 + solutions/709. To Lower Case/709.cpp | 12 + solutions/709. To Lower Case/709.java | 13 + solutions/709. To Lower Case/709.py | 3 + solutions/71. Simplify Path/71.cpp | 24 + solutions/71. Simplify Path/71.java | 19 + solutions/71. Simplify Path/71.py | 14 + .../710. Random Pick with Blacklist/710.cpp | 27 + .../710. Random Pick with Blacklist/710.java | 27 + .../710. Random Pick with Blacklist/710.py | 25 + .../711.cpp | 66 +++ .../711.java | 81 +++ .../711. Number of Distinct Islands II/711.py | 52 ++ .../712.cpp | 26 + .../712.java | 25 + .../713. Subarray Product Less Than K/713.cpp | 19 + .../713.java | 18 + .../713. Subarray Product Less Than K/713.py | 17 + .../714.cpp | 14 + .../714.java | 13 + .../714.py | 10 + solutions/715. Range Module/715-2.cpp | 51 ++ solutions/715. Range Module/715-2.java | 33 ++ solutions/715. Range Module/715-3.py | 18 + solutions/715. Range Module/715.cpp | 90 +++ solutions/716. Max Stack/716.cpp | 40 ++ .../717. 1-bit and 2-bit Characters/717.cpp | 15 + .../717. 1-bit and 2-bit Characters/717.java | 14 + .../717. 1-bit and 2-bit Characters/717.py | 7 + .../718-2.cpp | 17 + .../718-2.java | 16 + .../718-2.py | 11 + .../718.cpp | 20 + .../718.java | 19 + .../718.py | 16 + .../719.cpp | 33 ++ .../719.java | 31 ++ .../719.py | 18 + solutions/72. Edit Distance/72.cpp | 25 + solutions/72. Edit Distance/72.java | 24 + solutions/72. Edit Distance/72.py | 22 + .../720. Longest Word in Dictionary/720.cpp | 41 ++ .../720. Longest Word in Dictionary/720.java | 38 ++ .../720. Longest Word in Dictionary/720.py | 24 + solutions/721. Accounts Merge/721.cpp | 63 +++ solutions/721. Accounts Merge/721.java | 54 ++ solutions/722. Remove Comments/722.cpp | 42 ++ solutions/722. Remove Comments/722.java | 41 ++ solutions/722. Remove Comments/722.py | 35 ++ solutions/723. Candy Crush/723.cpp | 48 ++ solutions/723. Candy Crush/723.java | 45 ++ solutions/724. Find Pivot Index/724.cpp | 15 + solutions/724. Find Pivot Index/724.java | 14 + solutions/724. Find Pivot Index/724.py | 11 + .../725. Split Linked List in Parts/725.cpp | 32 ++ .../725. Split Linked List in Parts/725.java | 30 + .../725. Split Linked List in Parts/725.py | 24 + solutions/726. Number of Atoms/726.cpp | 52 ++ solutions/726. Number of Atoms/726.java | 56 ++ solutions/726. Number of Atoms/726.py | 47 ++ .../727. Minimum Window Subsequence/727.cpp | 32 ++ .../727. Minimum Window Subsequence/727.java | 31 ++ solutions/728. Self Dividing Numbers/728.cpp | 20 + solutions/728. Self Dividing Numbers/728.java | 18 + solutions/728. Self Dividing Numbers/728.py | 3 + solutions/729. My Calendar I/729-2.cpp | 16 + solutions/729. My Calendar I/729-2.java | 14 + solutions/729. My Calendar I/729-3.py | 40 ++ solutions/729. My Calendar I/729.cpp | 13 + solutions/729. My Calendar I/729.java | 11 + solutions/729. My Calendar I/729.py | 10 + solutions/73. Set Matrix Zeroes/73.cpp | 45 ++ solutions/73. Set Matrix Zeroes/73.java | 44 ++ solutions/73. Set Matrix Zeroes/73.py | 28 + .../730.cpp | 37 ++ .../730.java | 36 ++ .../730.py | 32 ++ solutions/731. My Calendar II/731-2.cpp | 25 + solutions/731. My Calendar II/731-2.java | 23 + solutions/731. My Calendar II/731.cpp | 22 + solutions/731. My Calendar II/731.java | 20 + solutions/732. My Calendar III/732.cpp | 20 + solutions/732. My Calendar III/732.java | 18 + solutions/732. My Calendar III/732.py | 19 + solutions/733. Flood Fill/733.cpp | 27 + solutions/733. Flood Fill/733.java | 22 + solutions/733. Flood Fill/733.py | 22 + solutions/734. Sentence Similarity/734.cpp | 27 + solutions/734. Sentence Similarity/734.java | 28 + solutions/734. Sentence Similarity/734.py | 21 + solutions/735. Asteroid Collision/735.cpp | 23 + solutions/735. Asteroid Collision/735.java | 22 + solutions/735. Asteroid Collision/735.py | 19 + solutions/736. Parse Lisp Expression/736.cpp | 53 ++ solutions/736. Parse Lisp Expression/736.java | 53 ++ solutions/736. Parse Lisp Expression/736.py | 44 ++ solutions/737. Sentence Similarity II/737.cpp | 46 ++ .../737. Sentence Similarity II/737.java | 45 ++ solutions/737. Sentence Similarity II/737.py | 35 ++ .../738. Monotone Increasing Digits/738.cpp | 19 + .../738. Monotone Increasing Digits/738.java | 18 + solutions/739. Daily Temperatures/739.cpp | 18 + solutions/739. Daily Temperatures/739.java | 16 + solutions/739. Daily Temperatures/739.py | 12 + solutions/74. Search a 2D Matrix/74.cpp | 26 + solutions/74. Search a 2D Matrix/74.java | 25 + solutions/74. Search a 2D Matrix/74.py | 22 + solutions/740. Delete and Earn/740.cpp | 21 + solutions/740. Delete and Earn/740.java | 20 + solutions/741. Cherry Pickup/741-2.cpp | 31 ++ solutions/741. Cherry Pickup/741-2.java | 32 ++ solutions/741. Cherry Pickup/741.cpp | 43 ++ solutions/741. Cherry Pickup/741.java | 39 ++ .../742.cpp | 56 ++ .../742.java | 54 ++ solutions/743. Network Delay Time/743.cpp | 40 ++ solutions/743. Network Delay Time/743.java | 45 ++ solutions/743. Network Delay Time/743.py | 26 + .../744.cpp | 17 + .../744.java | 16 + .../744.py | 5 + .../745. Prefix and Suffix Search/745-2.cpp | 49 ++ .../745. Prefix and Suffix Search/745.cpp | 29 + .../745. Prefix and Suffix Search/745.java | 27 + .../746. Min Cost Climbing Stairs/746.cpp | 11 + .../746. Min Cost Climbing Stairs/746.java | 10 + .../746. Min Cost Climbing Stairs/746.py | 8 + .../747.cpp | 19 + .../747.java | 18 + .../747.py | 14 + .../748. Shortest Completing Word/748.cpp | 33 ++ .../748. Shortest Completing Word/748.java | 31 ++ .../748. Shortest Completing Word/748.py | 18 + solutions/749. Contain Virus/749.cpp | 85 +++ solutions/749. Contain Virus/749.java | 80 +++ solutions/75. Sort Colors/75-2.cpp | 17 + solutions/75. Sort Colors/75-2.java | 22 + solutions/75. Sort Colors/75-2.py | 18 + solutions/75. Sort Colors/75.cpp | 20 + solutions/75. Sort Colors/75.java | 19 + solutions/75. Sort Colors/75.py | 22 + .../750. Number Of Corner Rectangles/750.cpp | 17 + .../750. Number Of Corner Rectangles/750.java | 16 + solutions/751. IP to CIDR/751.cpp | 61 +++ solutions/751. IP to CIDR/751.java | 67 +++ solutions/751. IP to CIDR/751.py | 49 ++ solutions/752. Open the Lock/752.cpp | 44 ++ solutions/752. Open the Lock/752.java | 44 ++ solutions/753. Cracking the Safe/753.cpp | 32 ++ solutions/753. Cracking the Safe/753.java | 31 ++ solutions/753. Cracking the Safe/753.py | 21 + solutions/754. Reach a Number/754.cpp | 15 + solutions/754. Reach a Number/754.java | 14 + solutions/754. Reach a Number/754.py | 15 + solutions/755. Pour Water/755.cpp | 18 + solutions/755. Pour Water/755.java | 17 + solutions/755. Pour Water/755.py | 15 + .../756. Pyramid Transition Matrix/756.cpp | 30 + .../756. Pyramid Transition Matrix/756.java | 30 + .../756. Pyramid Transition Matrix/756.py | 20 + .../757.cpp | 31 ++ .../757.java | 28 + solutions/758. Bold Words in String/758-2.cpp | 68 +++ .../758. Bold Words in String/758-2.java | 65 +++ solutions/758. Bold Words in String/758-2.py | 54 ++ solutions/758. Bold Words in String/758-3.cpp | 39 ++ solutions/758. Bold Words in String/758.cpp | 33 ++ solutions/758. Bold Words in String/758.java | 32 ++ solutions/758. Bold Words in String/758.py | 29 + solutions/759. Employee Free Time/759.cpp | 24 + solutions/759. Employee Free Time/759.java | 19 + solutions/759. Employee Free Time/759.py | 18 + solutions/76. Minimum Window Substring/76.cpp | 27 + .../76. Minimum Window Substring/76.java | 26 + solutions/76. Minimum Window Substring/76.py | 22 + solutions/760. Find Anagram Mappings/760.cpp | 15 + solutions/760. Find Anagram Mappings/760.java | 16 + solutions/760. Find Anagram Mappings/760.py | 8 + solutions/761. Special Binary String/761.cpp | 27 + solutions/761. Special Binary String/761.java | 17 + solutions/761. Special Binary String/761.py | 14 + .../762.cpp | 15 + .../762.java | 14 + solutions/763. Partition Labels/763.cpp | 23 + solutions/763. Partition Labels/763.java | 22 + solutions/763. Partition Labels/763.py | 15 + solutions/764. Largest Plus Sign/764.cpp | 36 ++ solutions/764. Largest Plus Sign/764.java | 36 ++ solutions/765. Couples Holding Hands/765.cpp | 51 ++ solutions/765. Couples Holding Hands/765.java | 52 ++ solutions/766. Toeplitz Matrix/766-2.cpp | 25 + solutions/766. Toeplitz Matrix/766-2.java | 24 + solutions/766. Toeplitz Matrix/766.cpp | 10 + solutions/766. Toeplitz Matrix/766.java | 9 + solutions/766. Toeplitz Matrix/766.py | 8 + solutions/767. Reorganize String/767-2.cpp | 41 ++ solutions/767. Reorganize String/767-2.java | 41 ++ solutions/767. Reorganize String/767-2.py | 26 + solutions/767. Reorganize String/767.cpp | 36 ++ solutions/767. Reorganize String/767.java | 37 ++ solutions/767. Reorganize String/767.py | 24 + .../768. Max Chunks To Make Sorted II/768.cpp | 21 + .../768.java | 20 + .../768. Max Chunks To Make Sorted II/768.py | 16 + .../769. Max Chunks To Make Sorted/769.cpp | 15 + .../769. Max Chunks To Make Sorted/769.java | 14 + .../769. Max Chunks To Make Sorted/769.py | 11 + solutions/77. Combinations/77.cpp | 22 + solutions/77. Combinations/77.java | 20 + solutions/77. Combinations/77.py | 16 + solutions/770. Basic Calculator IV/770.cpp | 196 +++++++ solutions/770. Basic Calculator IV/770.java | 182 ++++++ solutions/770. Basic Calculator IV/770.py | 141 +++++ solutions/771. Jewels and Stones/771.cpp | 13 + solutions/771. Jewels and Stones/771.java | 12 + solutions/771. Jewels and Stones/771.py | 4 + solutions/772. Basic Calculator III/772.cpp | 63 +++ solutions/772. Basic Calculator III/772.java | 58 ++ solutions/772. Basic Calculator III/772.py | 58 ++ solutions/773. Sliding Puzzle/773.cpp | 50 ++ solutions/773. Sliding Puzzle/773.java | 51 ++ .../774.cpp | 33 ++ .../774.java | 31 ++ .../774.py | 27 + .../775-2.cpp | 9 + .../775-2.java | 8 + .../775. Global and Local Inversions/775-2.py | 6 + .../775. Global and Local Inversions/775.cpp | 14 + .../775. Global and Local Inversions/775.java | 13 + .../775. Global and Local Inversions/775.py | 10 + solutions/776. Split BST/776.cpp | 16 + solutions/776. Split BST/776.java | 15 + solutions/776. Split BST/776.py | 12 + .../777. Swap Adjacent in LR String/777.cpp | 38 ++ .../777. Swap Adjacent in LR String/777.java | 30 + .../777. Swap Adjacent in LR String/777.py | 27 + solutions/778. Swim in Rising Water/778.cpp | 34 ++ solutions/778. Swim in Rising Water/778.java | 34 ++ solutions/779. K-th Symbol in Grammar/779.cpp | 10 + .../779. K-th Symbol in Grammar/779.java | 9 + solutions/78. Subsets/78.cpp | 20 + solutions/78. Subsets/78.java | 17 + solutions/78. Subsets/78.py | 12 + solutions/780. Reaching Points/780.cpp | 13 + solutions/780. Reaching Points/780.java | 13 + solutions/780. Reaching Points/780.py | 7 + solutions/781. Rabbits in Forest/781.cpp | 15 + solutions/781. Rabbits in Forest/781.java | 14 + solutions/781. Rabbits in Forest/781.py | 11 + .../782. Transform to Chessboard/782.cpp | 42 ++ .../782. Transform to Chessboard/782.java | 43 ++ solutions/782. Transform to Chessboard/782.py | 28 + .../783.cpp | 22 + .../783.java | 20 + .../784. Letter Case Permutation/784.cpp | 25 + .../784. Letter Case Permutation/784.java | 23 + solutions/785. Is Graph Bipartite?/785-2.cpp | 33 ++ solutions/785. Is Graph Bipartite?/785-2.java | 29 + solutions/785. Is Graph Bipartite?/785-2.py | 26 + solutions/785. Is Graph Bipartite?/785.cpp | 32 ++ solutions/785. Is Graph Bipartite?/785.java | 33 ++ solutions/785. Is Graph Bipartite?/785.py | 31 ++ .../786. K-th Smallest Prime Fraction/786.cpp | 38 ++ .../786.java | 37 ++ .../786. K-th Smallest Prime Fraction/786.py | 29 + .../787.cpp | 43 ++ .../787.java | 47 ++ .../787.py | 27 + solutions/788. Rotated Digits/788.cpp | 28 + solutions/788. Rotated Digits/788.java | 26 + solutions/788. Rotated Digits/788.py | 16 + solutions/789. Escape The Ghosts/789.cpp | 12 + solutions/789. Escape The Ghosts/789.java | 11 + solutions/789. Escape The Ghosts/789.py | 6 + solutions/79. Word Search/79.cpp | 31 ++ solutions/79. Word Search/79.java | 28 + solutions/79. Word Search/79.py | 25 + .../790. Domino and Tromino Tiling/790.cpp | 15 + .../790. Domino and Tromino Tiling/790.java | 14 + .../790. Domino and Tromino Tiling/790.py | 9 + solutions/791. Custom Sort String/791.cpp | 20 + solutions/791. Custom Sort String/791.java | 19 + solutions/791. Custom Sort String/791.py | 18 + .../792-2.cpp | 26 + .../792-2.java | 31 ++ .../792-2.py | 23 + .../792.cpp | 43 ++ .../792.java | 40 ++ .../792.py | 32 ++ .../793.cpp | 23 + .../793.java | 21 + .../794. Valid Tic-Tac-Toe State/794.cpp | 48 ++ .../794. Valid Tic-Tac-Toe State/794.java | 42 ++ solutions/794. Valid Tic-Tac-Toe State/794.py | 17 + .../795.cpp | 18 + .../795.java | 17 + .../795.py | 14 + solutions/796. Rotate String/796.cpp | 6 + solutions/796. Rotate String/796.java | 5 + solutions/796. Rotate String/796.py | 3 + .../797.cpp | 23 + .../797.java | 20 + .../797.py | 14 + .../798.cpp | 20 + .../798.java | 28 + solutions/799. Champagne Tower/799-2.cpp | 19 + solutions/799. Champagne Tower/799-2.java | 18 + solutions/799. Champagne Tower/799.cpp | 16 + solutions/799. Champagne Tower/799.java | 15 + solutions/8. String to Integer (atoi)/8.cpp | 32 ++ solutions/8. String to Integer (atoi)/8.java | 25 + solutions/8. String to Integer (atoi)/8.py | 22 + .../80.cpp | 12 + .../80.java | 11 + .../80.py | 10 + solutions/800. Similar RGB Color/800.cpp | 36 ++ solutions/800. Similar RGB Color/800.java | 33 ++ solutions/800. Similar RGB Color/800.py | 13 + .../801-2.cpp | 26 + .../801-2.java | 25 + .../801.cpp | 22 + .../801.java | 24 + .../801.py | 16 + .../802. Find Eventual Safe States/802.cpp | 32 ++ .../802. Find Eventual Safe States/802.java | 29 + .../802. Find Eventual Safe States/802.py | 25 + .../803. Bricks Falling When Hit/803.cpp | 102 ++++ .../803. Bricks Falling When Hit/803.java | 100 ++++ .../804. Unique Morse Code Words/804.cpp | 19 + .../804. Unique Morse Code Words/804.java | 17 + solutions/804. Unique Morse Code Words/804.py | 11 + .../805.cpp | 31 ++ .../805.java | 32 ++ .../805. Split Array With Same Average/805.py | 20 + .../806.cpp | 19 + .../806.java | 18 + .../806.py | 14 + .../807.cpp | 21 + .../807.java | 20 + .../807.py | 5 + solutions/808. Soup Servings/808.cpp | 23 + solutions/808. Soup Servings/808.java | 20 + solutions/808. Soup Servings/808.py | 16 + solutions/809. Expressive Words/809.cpp | 31 ++ solutions/809. Expressive Words/809.java | 30 + solutions/809. Expressive Words/809.py | 20 + .../81.cpp | 29 + .../81.java | 28 + .../81.py | 24 + solutions/810. Chalkboard XOR Game/810.cpp | 7 + solutions/810. Chalkboard XOR Game/810.java | 6 + solutions/810. Chalkboard XOR Game/810.py | 3 + solutions/811. Subdomain Visit Count/811.cpp | 22 + solutions/811. Subdomain Visit Count/811.java | 23 + solutions/811. Subdomain Visit Count/811.py | 12 + solutions/812. Largest Triangle Area/812.cpp | 14 + solutions/812. Largest Triangle Area/812.java | 13 + solutions/812. Largest Triangle Area/812.py | 11 + .../813. Largest Sum of Averages/813-2.cpp | 23 + .../813. Largest Sum of Averages/813-2.java | 22 + .../813. Largest Sum of Averages/813.cpp | 29 + .../813. Largest Sum of Averages/813.java | 27 + solutions/814. Binary Tree Pruning/814.cpp | 12 + solutions/814. Binary Tree Pruning/814.java | 11 + solutions/814. Binary Tree Pruning/814.py | 9 + solutions/815. Bus Routes/815.cpp | 35 ++ solutions/815. Bus Routes/815.java | 33 ++ solutions/815. Bus Routes/815.py | 28 + solutions/816. Ambiguous Coordinates/816.cpp | 29 + solutions/816. Ambiguous Coordinates/816.java | 27 + solutions/816. Ambiguous Coordinates/816.py | 20 + solutions/817. Linked List Components/817.cpp | 14 + .../817. Linked List Components/817.java | 15 + solutions/817. Linked List Components/817.py | 11 + solutions/818. Race Car/818.cpp | 25 + solutions/818. Race Car/818.java | 24 + solutions/819. Most Common Word/819.cpp | 27 + solutions/819. Most Common Word/819.java | 15 + solutions/819. Most Common Word/819.py | 5 + .../82.cpp | 19 + .../82.java | 18 + .../82.py | 15 + .../820. Short Encoding of Words/820-2.cpp | 17 + .../820. Short Encoding of Words/820.cpp | 37 ++ .../820. Short Encoding of Words/820.java | 33 ++ solutions/820. Short Encoding of Words/820.py | 23 + .../821.cpp | 22 + .../821.java | 21 + .../821.py | 17 + solutions/822. Card Flipping Game/822.cpp | 22 + solutions/822. Card Flipping Game/822.java | 21 + solutions/822. Card Flipping Game/822.py | 7 + .../823. Binary Trees With Factors/823.cpp | 27 + .../823. Binary Trees With Factors/823.java | 27 + .../823. Binary Trees With Factors/823.py | 18 + solutions/824. Goat Latin/824.cpp | 26 + solutions/824. Goat Latin/824.java | 22 + solutions/824. Goat Latin/824.py | 17 + .../825. Friends Of Appropriate Ages/825.cpp | 25 + .../825. Friends Of Appropriate Ages/825.java | 26 + .../825. Friends Of Appropriate Ages/825.py | 16 + .../826. Most Profit Assigning Work/826.cpp | 25 + .../826. Most Profit Assigning Work/826.java | 23 + .../826. Most Profit Assigning Work/826.py | 16 + solutions/827. Making A Large Island/827.cpp | 54 ++ solutions/827. Making A Large Island/827.java | 53 ++ .../828-2.cpp | 24 + .../828-2.java | 25 + .../828-2.py | 18 + .../828.cpp | 25 + .../828.java | 25 + .../828.py | 20 + .../829. Consecutive Numbers Sum/829.cpp | 10 + .../829. Consecutive Numbers Sum/829.java | 9 + solutions/829. Consecutive Numbers Sum/829.py | 11 + .../83.cpp | 14 + .../83.java | 13 + .../83.py | 10 + .../830. Positions of Large Groups/830.cpp | 16 + .../830. Positions of Large Groups/830.java | 15 + .../830. Positions of Large Groups/830.py | 15 + .../831. Masking Personal Information/831.cpp | 20 + .../831.java | 19 + .../831. Masking Personal Information/831.py | 12 + solutions/832. Flipping an Image/832.cpp | 15 + solutions/832. Flipping an Image/832.java | 14 + solutions/832. Flipping an Image/832.py | 9 + .../833. Find And Replace in String/833.cpp | 21 + .../833. Find And Replace in String/833.java | 21 + .../833. Find And Replace in String/833.py | 7 + .../834. Sum of Distances in Tree/834.cpp | 43 ++ .../834. Sum of Distances in Tree/834.java | 44 ++ .../834. Sum of Distances in Tree/834.py | 30 + solutions/835. Image Overlap/835.cpp | 28 + solutions/835. Image Overlap/835.java | 29 + solutions/835. Image Overlap/835.py | 18 + solutions/836. Rectangle Overlap/836.cpp | 7 + solutions/836. Rectangle Overlap/836.java | 7 + solutions/836. Rectangle Overlap/836.py | 3 + solutions/837. New 21 Game/837.cpp | 29 + solutions/837. New 21 Game/837.java | 28 + solutions/837. New 21 Game/837.py | 24 + solutions/838. Push Dominoes/838.cpp | 32 ++ solutions/838. Push Dominoes/838.java | 32 ++ solutions/838. Push Dominoes/838.py | 31 ++ .../839. Similar String Groups/839-2.cpp | 58 ++ .../839. Similar String Groups/839-2.java | 58 ++ solutions/839. Similar String Groups/839.cpp | 31 ++ solutions/839. Similar String Groups/839.java | 29 + .../84. Largest Rectangle in Histogram/84.cpp | 20 + .../84.java | 17 + .../84. Largest Rectangle in Histogram/84.py | 13 + solutions/840. Magic Squares In Grid/840.cpp | 24 + solutions/840. Magic Squares In Grid/840.java | 24 + solutions/840. Magic Squares In Grid/840.py | 15 + solutions/841. Keys and Rooms/841.cpp | 16 + solutions/841. Keys and Rooms/841.java | 14 + solutions/841. Keys and Rooms/841.py | 12 + .../842.cpp | 34 ++ .../842.java | 30 + solutions/843. Guess the Word/843.cpp | 35 ++ solutions/843. Guess the Word/843.java | 32 ++ solutions/843. Guess the Word/843.py | 24 + .../844. Backspace String Compare/844-2.cpp | 30 + .../844. Backspace String Compare/844-2.java | 29 + .../844. Backspace String Compare/844-2.py | 23 + .../844. Backspace String Compare/844.cpp | 17 + .../844. Backspace String Compare/844.java | 15 + .../844. Backspace String Compare/844.py | 12 + .../845. Longest Mountain in Array/845.cpp | 29 + .../845. Longest Mountain in Array/845.java | 28 + .../845. Longest Mountain in Array/845.py | 24 + solutions/846. Hand of Straights/846.cpp | 21 + solutions/846. Hand of Straights/846.java | 18 + solutions/846. Hand of Straights/846.py | 13 + .../847.cpp | 31 ++ .../847.java | 30 + .../847.py | 25 + solutions/848. Shifting Letters/848.cpp | 14 + solutions/848. Shifting Letters/848.java | 13 + solutions/848. Shifting Letters/848.py | 11 + .../849.cpp | 16 + .../849.java | 15 + .../849.py | 12 + solutions/85. Maximal Rectangle/85.cpp | 37 ++ solutions/85. Maximal Rectangle/85.java | 33 ++ solutions/85. Maximal Rectangle/85.py | 27 + solutions/850. Rectangle Area II/850.cpp | 62 +++ solutions/850. Rectangle Area II/850.java | 63 +++ solutions/850. Rectangle Area II/850.py | 38 ++ solutions/851. Loud and Rich/851.cpp | 36 ++ solutions/851. Loud and Rich/851.java | 38 ++ solutions/851. Loud and Rich/851.py | 19 + .../852.cpp | 17 + .../852.java | 16 + .../852.py | 13 + solutions/853. Car Fleet/853.cpp | 29 + solutions/853. Car Fleet/853.java | 32 ++ solutions/853. Car Fleet/853.py | 15 + solutions/854. K-Similar Strings/854.cpp | 43 ++ solutions/854. K-Similar Strings/854.java | 47 ++ solutions/854. K-Similar Strings/854.py | 34 ++ solutions/855. Exam Room/855.cpp | 46 ++ solutions/855. Exam Room/855.java | 74 +++ solutions/856. Score of Parentheses/856.cpp | 17 + solutions/856. Score of Parentheses/856.java | 16 + solutions/856. Score of Parentheses/856.py | 11 + .../857.cpp | 26 + .../857.java | 27 + .../857.py | 17 + solutions/858. Mirror Reflection/858.cpp | 15 + solutions/858. Mirror Reflection/858.java | 14 + solutions/858. Mirror Reflection/858.py | 11 + solutions/859. Buddy Strings/859.cpp | 27 + solutions/859. Buddy Strings/859.java | 25 + solutions/859. Buddy Strings/859.py | 11 + solutions/86. Partition List/86.cpp | 23 + solutions/86. Partition List/86.java | 22 + solutions/86. Partition List/86.py | 20 + solutions/860. Lemonade Change/860.cpp | 27 + solutions/860. Lemonade Change/860.java | 26 + solutions/860. Lemonade Change/860.py | 21 + .../861-2.cpp | 18 + .../861-2.java | 17 + .../861. Score After Flipping Matrix/861-2.py | 12 + .../861. Score After Flipping Matrix/861.cpp | 49 ++ .../861. Score After Flipping Matrix/861.java | 47 ++ .../861. Score After Flipping Matrix/861.py | 28 + .../862.cpp | 22 + .../862.java | 21 + .../862.py | 15 + .../863.cpp | 47 ++ .../863.java | 45 ++ .../864.cpp | 67 +++ .../864.java | 69 +++ .../865.cpp | 25 + .../865.java | 28 + solutions/866. Prime Palindrome/866.cpp | 49 ++ solutions/866. Prime Palindrome/866.java | 44 ++ solutions/866. Prime Palindrome/866.py | 30 + solutions/867. Transpose Matrix/867.cpp | 12 + solutions/867. Transpose Matrix/867.java | 11 + solutions/867. Transpose Matrix/867.py | 9 + solutions/868. Binary Gap/868.cpp | 15 + solutions/868. Binary Gap/868.java | 14 + solutions/868. Binary Gap/868.py | 13 + solutions/869. Reordered Power of 2/869.cpp | 22 + solutions/869. Reordered Power of 2/869.java | 20 + solutions/869. Reordered Power of 2/869.py | 4 + solutions/87. Scramble String/87.cpp | 34 ++ solutions/87. Scramble String/87.java | 40 ++ solutions/87. Scramble String/87.py | 15 + solutions/870. Advantage Shuffle/870.cpp | 15 + solutions/870. Advantage Shuffle/870.java | 19 + solutions/870. Advantage Shuffle/870.py | 13 + .../871-2.cpp | 21 + .../871-2.java | 20 + .../871-2.py | 18 + .../871.cpp | 19 + .../871.java | 18 + .../871.py | 15 + solutions/872. Leaf-Similar Trees/872.cpp | 22 + solutions/872. Leaf-Similar Trees/872.java | 21 + solutions/872. Leaf-Similar Trees/872.py | 13 + .../873.cpp | 24 + .../873.java | 24 + .../873.py | 16 + .../874. Walking Robot Simulation/874.cpp | 39 ++ .../874. Walking Robot Simulation/874.java | 31 ++ .../874. Walking Robot Simulation/874.py | 24 + solutions/875. Koko Eating Bananas/875.cpp | 26 + solutions/875. Koko Eating Bananas/875.java | 22 + solutions/875. Koko Eating Bananas/875.py | 7 + .../876. Middle of the Linked List/876.cpp | 14 + .../876. Middle of the Linked List/876.java | 13 + .../876. Middle of the Linked List/876.py | 10 + solutions/877. Stone Game/877-2.cpp | 15 + solutions/877. Stone Game/877-2.java | 14 + solutions/877. Stone Game/877-2.py | 11 + solutions/877. Stone Game/877.cpp | 20 + solutions/877. Stone Game/877.java | 18 + solutions/877. Stone Game/877.py | 16 + solutions/878. Nth Magical Number/878.cpp | 19 + solutions/878. Nth Magical Number/878.java | 22 + solutions/878. Nth Magical Number/878.py | 6 + solutions/879. Profitable Schemes/879-2.cpp | 25 + solutions/879. Profitable Schemes/879-2.java | 23 + solutions/879. Profitable Schemes/879.cpp | 31 ++ solutions/879. Profitable Schemes/879.java | 27 + solutions/88. Merge Sorted Array/88.cpp | 14 + solutions/88. Merge Sorted Array/88.java | 13 + solutions/88. Merge Sorted Array/88.py | 15 + .../880. Decoded String at Index/880.cpp | 24 + .../880. Decoded String at Index/880.java | 23 + solutions/880. Decoded String at Index/880.py | 18 + solutions/881. Boats to Save People/881.cpp | 16 + solutions/881. Boats to Save People/881.java | 15 + solutions/881. Boats to Save People/881.py | 16 + .../882.cpp | 58 ++ .../882.java | 63 +++ .../882.py | 39 ++ .../883. Projection Area of 3D Shapes/883.cpp | 20 + .../883.java | 19 + .../883. Projection Area of 3D Shapes/883.py | 3 + .../884.cpp | 17 + .../884.java | 15 + .../884.py | 4 + solutions/885. Spiral Matrix III/885.cpp | 19 + solutions/885. Spiral Matrix III/885.java | 17 + solutions/885. Spiral Matrix III/885.py | 16 + solutions/886. Possible Bipartition/886.cpp | 42 ++ solutions/886. Possible Bipartition/886.java | 41 ++ solutions/886. Possible Bipartition/886.py | 32 ++ solutions/887. Super Egg Drop/887-2.cpp | 43 ++ solutions/887. Super Egg Drop/887-2.java | 36 ++ solutions/887. Super Egg Drop/887-3.cpp | 15 + solutions/887. Super Egg Drop/887-3.java | 14 + solutions/887. Super Egg Drop/887-3.py | 12 + solutions/887. Super Egg Drop/887.cpp | 30 + solutions/887. Super Egg Drop/887.java | 29 + solutions/888. Fair Candy Swap/888.cpp | 17 + solutions/888. Fair Candy Swap/888.java | 14 + solutions/888. Fair Candy Swap/888.py | 9 + .../889.cpp | 33 ++ .../889.java | 30 + .../889.py | 23 + solutions/89. Gray Code/89.cpp | 12 + solutions/89. Gray Code/89.java | 12 + solutions/89. Gray Code/89.py | 9 + .../890. Find and Replace Pattern/890.cpp | 27 + .../890. Find and Replace Pattern/890.java | 22 + .../890. Find and Replace Pattern/890.py | 5 + .../891. Sum of Subsequence Widths/891.cpp | 18 + .../891. Sum of Subsequence Widths/891.java | 17 + .../891. Sum of Subsequence Widths/891.py | 15 + .../892. Surface Area of 3D Shapes/892.cpp | 18 + .../892. Surface Area of 3D Shapes/892.java | 17 + .../892. Surface Area of 3D Shapes/892.py | 14 + .../893.cpp | 21 + .../893.java | 22 + .../893.py | 4 + .../894.cpp | 28 + .../894.java | 27 + .../894.py | 19 + .../895. Maximum Frequency Stack/895.cpp | 21 + .../895. Maximum Frequency Stack/895.java | 20 + solutions/895. Maximum Frequency Stack/895.py | 17 + solutions/896. Monotonic Array/896.cpp | 14 + solutions/896. Monotonic Array/896.java | 13 + solutions/896. Monotonic Array/896.py | 10 + .../897. Increasing Order Search Tree/897.cpp | 12 + .../897.java | 15 + .../897. Increasing Order Search Tree/897.py | 9 + .../898. Bitwise ORs of Subarrays/898.cpp | 19 + .../898. Bitwise ORs of Subarrays/898.java | 18 + solutions/899. Orderly Queue/899.cpp | 16 + solutions/899. Orderly Queue/899.java | 19 + solutions/899. Orderly Queue/899.py | 4 + solutions/9. Palindrome Number/9.cpp | 17 + solutions/9. Palindrome Number/9.java | 16 + solutions/9. Palindrome Number/9.py | 13 + solutions/90. Subsets II/90.cpp | 23 + solutions/90. Subsets II/90.java | 20 + solutions/90. Subsets II/90.py | 17 + solutions/900. RLE Iterator/900.cpp | 21 + solutions/900. RLE Iterator/900.java | 21 + solutions/900. RLE Iterator/900.py | 15 + solutions/901. Online Stock Span/901.cpp | 13 + solutions/901. Online Stock Span/901.java | 12 + solutions/901. Online Stock Span/901.py | 10 + .../902.cpp | 24 + .../902.java | 23 + .../902.py | 19 + .../903-2.cpp | 34 ++ .../903-2.java | 33 ++ .../903.cpp | 33 ++ .../903.java | 32 ++ solutions/904. Fruit Into Baskets/904.cpp | 19 + solutions/904. Fruit Into Baskets/904.java | 18 + solutions/904. Fruit Into Baskets/904.py | 16 + solutions/905. Sort Array By Parity/905.cpp | 18 + solutions/905. Sort Array By Parity/905.java | 20 + solutions/905. Sort Array By Parity/905.py | 14 + solutions/906. Super Palindromes/906.cpp | 46 ++ solutions/906. Super Palindromes/906.java | 44 ++ solutions/906. Super Palindromes/906.py | 42 ++ .../907. Sum of Subarray Minimums/907.cpp | 31 ++ .../907. Sum of Subarray Minimums/907.java | 32 ++ .../907. Sum of Subarray Minimums/907.py | 24 + solutions/908. Smallest Range I/908.cpp | 8 + solutions/908. Smallest Range I/908.java | 7 + solutions/908. Smallest Range I/908.py | 3 + solutions/909. Snakes and Ladders/909.cpp | 33 ++ solutions/909. Snakes and Ladders/909.java | 31 ++ solutions/909. Snakes and Ladders/909.py | 26 + solutions/91. Decode Ways/91.cpp | 28 + solutions/91. Decode Ways/91.java | 26 + solutions/91. Decode Ways/91.py | 21 + solutions/910. Smallest Range II/910.cpp | 18 + solutions/910. Smallest Range II/910.java | 17 + solutions/910. Smallest Range II/910.py | 14 + solutions/911. Online Election/911.cpp | 22 + solutions/911. Online Election/911.java | 21 + solutions/911. Online Election/911.py | 16 + solutions/912. Sort an Array/912-2.cpp | 37 ++ solutions/912. Sort an Array/912-2.java | 41 ++ solutions/912. Sort an Array/912-2.py | 28 + solutions/912. Sort an Array/912-3.cpp | 29 + solutions/912. Sort an Array/912-3.java | 33 ++ solutions/912. Sort an Array/912-3.py | 24 + solutions/912. Sort an Array/912.cpp | 41 ++ solutions/912. Sort an Array/912.java | 39 ++ solutions/912. Sort an Array/912.py | 43 ++ solutions/913. Cat and Mouse/913.cpp | 58 ++ solutions/913. Cat and Mouse/913.java | 57 ++ solutions/913. Cat and Mouse/913.py | 57 ++ .../914.cpp | 15 + .../914.java | 18 + .../914.py | 4 + .../915.cpp | 20 + .../915.java | 19 + .../915.py | 13 + solutions/916. Word Subsets/916.cpp | 34 ++ solutions/916. Word Subsets/916.java | 32 ++ solutions/916. Word Subsets/916.py | 8 + solutions/917. Reverse Only Letters/917.cpp | 13 + solutions/917. Reverse Only Letters/917.java | 16 + solutions/917. Reverse Only Letters/917.py | 16 + .../918.cpp | 20 + .../918.java | 19 + .../918. Maximum Sum Circular Subarray/918.py | 16 + .../919.cpp | 31 ++ .../919.java | 30 + .../919. Complete Binary Tree Inserter/919.py | 21 + solutions/92. Reverse Linked List II/92-2.cpp | 25 + .../92. Reverse Linked List II/92-2.java | 24 + solutions/92. Reverse Linked List II/92-2.py | 21 + solutions/92. Reverse Linked List II/92.cpp | 24 + solutions/92. Reverse Linked List II/92.java | 22 + solutions/92. Reverse Linked List II/92.py | 17 + .../920. Number of Music Playlists/920-2.cpp | 18 + .../920. Number of Music Playlists/920-2.java | 17 + .../920. Number of Music Playlists/920.cpp | 27 + .../920. Number of Music Playlists/920.java | 25 + .../921.cpp | 19 + .../921.java | 18 + .../921.py | 15 + .../922. Sort Array By Parity II/922.cpp | 17 + .../922. Sort Array By Parity II/922.java | 19 + solutions/922. Sort Array By Parity II/922.py | 15 + solutions/923. 3Sum With Multiplicity/923.cpp | 27 + .../923. 3Sum With Multiplicity/923.java | 30 + solutions/923. 3Sum With Multiplicity/923.py | 19 + .../924. Minimize Malware Spread/924.cpp | 66 +++ .../924. Minimize Malware Spread/924.java | 66 +++ solutions/925. Long Pressed Name/925.cpp | 14 + solutions/925. Long Pressed Name/925.java | 13 + solutions/925. Long Pressed Name/925.py | 11 + .../926.cpp | 19 + .../926.java | 18 + .../926.py | 16 + solutions/927. Three Equal Parts/927.cpp | 51 ++ solutions/927. Three Equal Parts/927.java | 53 ++ solutions/927. Three Equal Parts/927.py | 43 ++ .../928. Minimize Malware Spread II/928.cpp | 50 ++ .../928. Minimize Malware Spread II/928.java | 47 ++ solutions/929. Unique Email Addresses/929.cpp | 21 + .../929. Unique Email Addresses/929.java | 13 + solutions/929. Unique Email Addresses/929.py | 10 + solutions/93. Restore IP Addresses/93.cpp | 32 ++ solutions/93. Restore IP Addresses/93.java | 29 + solutions/93. Restore IP Addresses/93.py | 23 + .../930. Binary Subarrays With Sum/930-2.cpp | 21 + .../930. Binary Subarrays With Sum/930-2.java | 18 + .../930. Binary Subarrays With Sum/930-2.py | 20 + .../930. Binary Subarrays With Sum/930.cpp | 18 + .../930. Binary Subarrays With Sum/930.java | 19 + .../930. Binary Subarrays With Sum/930.py | 13 + .../931. Minimum Falling Path Sum/931.cpp | 16 + .../931. Minimum Falling Path Sum/931.java | 15 + .../931. Minimum Falling Path Sum/931.py | 12 + solutions/932. Beautiful Array/932.cpp | 26 + solutions/932. Beautiful Array/932.java | 31 ++ solutions/932. Beautiful Array/932.py | 21 + solutions/933. Number of Recent Calls/933.cpp | 12 + .../933. Number of Recent Calls/933.java | 10 + solutions/933. Number of Recent Calls/933.py | 9 + solutions/934. Shortest Bridge/934-2.cpp | 56 ++ solutions/934. Shortest Bridge/934-2.java | 53 ++ solutions/934. Shortest Bridge/934.cpp | 48 ++ solutions/934. Shortest Bridge/934.java | 44 ++ solutions/935. Knight Dialer/935.cpp | 44 ++ solutions/935. Knight Dialer/935.java | 41 ++ solutions/935. Knight Dialer/935.py | 27 + solutions/936. Stamping The Sequence/936.cpp | 50 ++ solutions/936. Stamping The Sequence/936.java | 48 ++ solutions/936. Stamping The Sequence/936.py | 45 ++ .../937. Reorder Data in Log Files/937.cpp | 29 + .../937. Reorder Data in Log Files/937.java | 30 + .../937. Reorder Data in Log Files/937.py | 15 + solutions/938. Range Sum of BST/938.cpp | 13 + solutions/938. Range Sum of BST/938.java | 11 + solutions/939. Minimum Area Rectangle/939.cpp | 22 + .../939. Minimum Area Rectangle/939.java | 23 + solutions/939. Minimum Area Rectangle/939.py | 18 + .../94. Binary Tree Inorder Traversal/94.cpp | 19 + .../94. Binary Tree Inorder Traversal/94.java | 18 + .../94. Binary Tree Inorder Traversal/94.py | 14 + .../940. Distinct Subsequences II/940.cpp | 13 + .../940. Distinct Subsequences II/940.java | 12 + .../940. Distinct Subsequences II/940.py | 10 + solutions/941. Valid Mountain Array/941.cpp | 17 + solutions/941. Valid Mountain Array/941.java | 16 + solutions/941. Valid Mountain Array/941.py | 14 + solutions/942. DI String Match/942.cpp | 14 + solutions/942. DI String Match/942.java | 14 + solutions/942. DI String Match/942.py | 15 + .../943-2.cpp | 64 +++ .../943-2.java | 71 +++ .../943.cpp | 65 +++ .../943.java | 67 +++ .../944.cpp | 15 + .../944.java | 14 + .../944. Delete Columns to Make Sorted/944.py | 11 + .../945.cpp | 16 + .../945.java | 15 + .../945.py | 10 + .../946. Validate Stack Sequences/946.cpp | 17 + .../946. Validate Stack Sequences/946.java | 16 + .../946. Validate Stack Sequences/946.py | 12 + .../947.cpp | 30 + .../947.java | 31 ++ solutions/948. Bag of Tokens/948.cpp | 27 + solutions/948. Bag of Tokens/948.java | 26 + solutions/948. Bag of Tokens/948.py | 18 + .../949.cpp | 20 + .../949.java | 19 + .../949. Largest Time for Given Digits/949.py | 6 + .../95. Unique Binary Search Trees II/95.cpp | 26 + .../95. Unique Binary Search Trees II/95.java | 24 + .../95. Unique Binary Search Trees II/95.py | 21 + .../950.cpp | 16 + .../950.java | 21 + .../950.py | 9 + .../951. Flip Equivalent Binary Trees/951.cpp | 15 + .../951.java | 13 + .../951. Flip Equivalent Binary Trees/951.py | 11 + .../952.cpp | 51 ++ .../952.java | 51 ++ .../952.py | 42 ++ .../953.cpp | 15 + .../953.java | 21 + .../953. Verifying an Alien Dictionary/953.py | 5 + solutions/954. Array of Doubled Pairs/954.cpp | 22 + .../954. Array of Doubled Pairs/954.java | 25 + solutions/954. Array of Doubled Pairs/954.py | 10 + .../955.cpp | 24 + .../955.java | 23 + solutions/956. Tallest Billboard/956-2.cpp | 26 + solutions/956. Tallest Billboard/956-2.java | 26 + solutions/956. Tallest Billboard/956.cpp | 27 + solutions/956. Tallest Billboard/956.java | 27 + .../957. Prison Cells After N Days/957.cpp | 18 + .../957. Prison Cells After N Days/957.java | 17 + .../957. Prison Cells After N Days/957.py | 17 + .../958-2.cpp | 24 + .../958-2.java | 21 + .../958.cpp | 21 + .../958.java | 19 + solutions/959. Regions Cut By Slashes/959.cpp | 45 ++ .../959. Regions Cut By Slashes/959.java | 43 ++ .../96. Unique Binary Search Trees/96.cpp | 15 + .../96. Unique Binary Search Trees/96.java | 14 + .../96. Unique Binary Search Trees/96.py | 10 + .../960.cpp | 15 + .../960.java | 22 + .../961.cpp | 9 + .../961.java | 8 + .../961.py | 6 + solutions/962. Maximum Width Ramp/962.cpp | 17 + solutions/962. Maximum Width Ramp/962.java | 16 + solutions/962. Maximum Width Ramp/962.py | 14 + .../963. Minimum Area Rectangle II/963.cpp | 38 ++ .../963. Minimum Area Rectangle II/963.java | 41 ++ .../963. Minimum Area Rectangle II/963.py | 26 + .../964.cpp | 30 + .../964.java | 33 ++ .../964.py | 23 + solutions/965. Univalued Binary Tree/965.cpp | 12 + solutions/965. Univalued Binary Tree/965.java | 11 + solutions/965. Univalued Binary Tree/965.py | 9 + solutions/966. Vowel Spellchecker/966.cpp | 46 ++ solutions/966. Vowel Spellchecker/966.java | 39 ++ solutions/966. Vowel Spellchecker/966.py | 27 + .../967.cpp | 34 ++ .../967.java | 34 ++ solutions/968. Binary Tree Cameras/968.cpp | 26 + solutions/968. Binary Tree Cameras/968.java | 25 + solutions/969. Pancake Sorting/969.cpp | 24 + solutions/969. Pancake Sorting/969.java | 33 ++ solutions/969. Pancake Sorting/969.py | 12 + solutions/97. Interleaving String/97-2.cpp | 25 + solutions/97. Interleaving String/97-2.java | 24 + solutions/97. Interleaving String/97-2.py | 22 + solutions/97. Interleaving String/97.cpp | 27 + solutions/97. Interleaving String/97.java | 26 + solutions/97. Interleaving String/97.py | 24 + solutions/970. Powerful Integers/970.cpp | 18 + solutions/970. Powerful Integers/970.java | 17 + solutions/970. Powerful Integers/970.py | 5 + .../971.cpp | 30 + .../971.java | 31 ++ solutions/972. Equal Rational Numbers/972.cpp | 29 + .../972. Equal Rational Numbers/972.java | 26 + solutions/972. Equal Rational Numbers/972.py | 23 + .../973. K Closest Points to Origin/973-2.cpp | 30 + .../973-2.java | 34 ++ .../973. K Closest Points to Origin/973-2.py | 25 + .../973. K Closest Points to Origin/973-3.cpp | 32 ++ .../973-3.java | 36 ++ .../973. K Closest Points to Origin/973-3.py | 54 ++ .../973. K Closest Points to Origin/973.cpp | 27 + .../973. K Closest Points to Origin/973.java | 22 + .../973. K Closest Points to Origin/973.py | 10 + .../974. Subarray Sums Divisible by K/974.cpp | 17 + .../974.java | 16 + .../974. Subarray Sums Divisible by K/974.py | 13 + solutions/975. Odd Even Jump/975.cpp | 27 + solutions/975. Odd Even Jump/975.java | 28 + .../976. Largest Perimeter Triangle/976.cpp | 12 + .../976. Largest Perimeter Triangle/976.java | 11 + .../976. Largest Perimeter Triangle/976.py | 9 + .../977. Squares of a Sorted Array/977.cpp | 16 + .../977. Squares of a Sorted Array/977.java | 15 + .../977. Squares of a Sorted Array/977.py | 17 + .../978. Longest Turbulent Subarray/978.cpp | 24 + .../978. Longest Turbulent Subarray/978.java | 23 + .../978. Longest Turbulent Subarray/978.py | 19 + .../979.cpp | 20 + .../979.java | 20 + .../98. Validate Binary Search Tree/98-2.cpp | 21 + .../98. Validate Binary Search Tree/98-2.java | 20 + .../98. Validate Binary Search Tree/98-2.py | 16 + .../98. Validate Binary Search Tree/98.cpp | 19 + .../98. Validate Binary Search Tree/98.java | 18 + .../98. Validate Binary Search Tree/98.py | 15 + solutions/980. Unique Paths III/980.cpp | 48 ++ solutions/980. Unique Paths III/980.java | 46 ++ .../981. Time Based Key-Value Store/981.cpp | 34 ++ .../981. Time Based Key-Value Store/981.java | 36 ++ .../981. Time Based Key-Value Store/981.py | 14 + .../982.cpp | 19 + .../982.java | 18 + .../982.py | 16 + .../983. Minimum Cost For Tickets/983.cpp | 20 + .../983. Minimum Cost For Tickets/983.java | 19 + .../983. Minimum Cost For Tickets/983.py | 16 + .../984. String Without AAA or BBB/984.cpp | 14 + .../985.cpp | 24 + .../985.java | 22 + .../985.py | 14 + .../986. Interval List Intersections/986.cpp | 21 + .../986. Interval List Intersections/986.java | 22 + .../986. Interval List Intersections/986.py | 19 + .../987.cpp | 28 + .../987.java | 27 + .../987.py | 18 + .../988.cpp | 27 + .../988.java | 26 + .../989. Add to Array-Form of Integer/989.cpp | 17 + .../989.java | 17 + .../989. Add to Array-Form of Integer/989.py | 10 + .../99. Recover Binary Search Tree/99-2.cpp | 33 ++ .../99. Recover Binary Search Tree/99-2.java | 32 ++ .../99. Recover Binary Search Tree/99-2.py | 25 + .../99. Recover Binary Search Tree/99-3.cpp | 51 ++ .../99. Recover Binary Search Tree/99-3.java | 54 ++ .../99. Recover Binary Search Tree/99-3.py | 45 ++ .../99. Recover Binary Search Tree/99.cpp | 36 ++ .../99. Recover Binary Search Tree/99.java | 34 ++ .../99. Recover Binary Search Tree/99.py | 29 + .../990.cpp | 41 ++ .../990.java | 53 ++ .../990.py | 24 + solutions/991. Broken Calculator/991.cpp | 16 + solutions/991. Broken Calculator/991.java | 15 + solutions/991. Broken Calculator/991.py | 12 + .../992.cpp | 24 + .../992.java | 21 + .../992.py | 21 + solutions/993. Cousins in Binary Tree/993.cpp | 37 ++ solutions/994. Rotting Oranges/994-2.cpp | 42 ++ solutions/994. Rotting Oranges/994.cpp | 49 ++ .../995.cpp | 21 + .../995.java | 20 + .../995.py | 16 + .../996. Number of Squareful Arrays/996.cpp | 37 ++ .../996. Number of Squareful Arrays/996.java | 36 ++ .../996. Number of Squareful Arrays/996.py | 29 + solutions/997. Find the Town Judge/997.cpp | 17 + solutions/997. Find the Town Judge/997.java | 16 + solutions/997. Find the Town Judge/997.py | 13 + .../998. Maximum Binary Tree II/998-2.cpp | 13 + .../998. Maximum Binary Tree II/998-2.java | 12 + .../998. Maximum Binary Tree II/998-2.py | 10 + solutions/998. Maximum Binary Tree II/998.cpp | 11 + .../998. Maximum Binary Tree II/998.java | 10 + solutions/998. Maximum Binary Tree II/998.py | 8 + .../999. Available Captures for Rook/999.cpp | 27 + .../999. Available Captures for Rook/999.java | 25 + .../999. Available Captures for Rook/999.py | 22 + 9437 files changed, 226612 insertions(+) create mode 100644 .clang-format create mode 100644 .github/workflows/main.yaml create mode 100644 .prettierrc create mode 100644 LICENSE create mode 100644 README.md create mode 100644 STYLEGUIDE.md create mode 100644 solutions/1. Two Sum/1.cpp create mode 100644 solutions/1. Two Sum/1.java create mode 100644 solutions/1. Two Sum/1.py create mode 100644 solutions/10. Regular Expression Matching/10.cpp create mode 100644 solutions/10. Regular Expression Matching/10.java create mode 100644 solutions/10. Regular Expression Matching/10.py create mode 100644 solutions/100. Same Tree/100.cpp create mode 100644 solutions/100. Same Tree/100.java create mode 100644 solutions/100. Same Tree/100.py create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000-2.cpp create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000-2.java create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000-3.cpp create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000-3.java create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000-4.cpp create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000-4.java create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000.cpp create mode 100644 solutions/1000. Minimum Cost to Merge Stones/1000.java create mode 100644 solutions/1001. Grid Illumination/1001.cpp create mode 100644 solutions/1001. Grid Illumination/1001.java create mode 100644 solutions/1001. Grid Illumination/1001.py create mode 100644 solutions/1002. Find Common Characters/1002.cpp create mode 100644 solutions/1002. Find Common Characters/1002.java create mode 100644 solutions/1002. Find Common Characters/1002.py create mode 100644 solutions/1003. Check If Word Is Valid After Substitutions/1003.cpp create mode 100644 solutions/1003. Check If Word Is Valid After Substitutions/1003.java create mode 100644 solutions/1003. Check If Word Is Valid After Substitutions/1003.py create mode 100644 solutions/1004. Max Consecutive Ones III/1004.cpp create mode 100644 solutions/1004. Max Consecutive Ones III/1004.java create mode 100644 solutions/1004. Max Consecutive Ones III/1004.py create mode 100644 solutions/1005. Maximize Sum Of Array After K Negations/1005.cpp create mode 100644 solutions/1005. Maximize Sum Of Array After K Negations/1005.java create mode 100644 solutions/1005. Maximize Sum Of Array After K Negations/1005.py create mode 100644 solutions/1006. Clumsy Factorial/1006.cpp create mode 100644 solutions/1006. Clumsy Factorial/1006.java create mode 100644 solutions/1006. Clumsy Factorial/1006.py create mode 100644 solutions/1007. Minimum Domino Rotations For Equal Row/1007.cpp create mode 100644 solutions/1007. Minimum Domino Rotations For Equal Row/1007.java create mode 100644 solutions/1007. Minimum Domino Rotations For Equal Row/1007.py create mode 100644 solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.cpp create mode 100644 solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.java create mode 100644 solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.py create mode 100644 solutions/1009. Complement of Base 10 Integer/1009.cpp create mode 100644 solutions/1009. Complement of Base 10 Integer/1009.java create mode 100644 solutions/1009. Complement of Base 10 Integer/1009.py create mode 100644 solutions/101. Symmetric Tree/101.cpp create mode 100644 solutions/101. Symmetric Tree/101.java create mode 100644 solutions/101. Symmetric Tree/101.py create mode 100644 solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.cpp create mode 100644 solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.java create mode 100644 solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.py create mode 100644 solutions/1011. Capacity To Ship Packages Within D Days/1011.cpp create mode 100644 solutions/1011. Capacity To Ship Packages Within D Days/1011.java create mode 100644 solutions/1011. Capacity To Ship Packages Within D Days/1011.py create mode 100644 solutions/1012. Numbers With Repeated Digits/1012.cpp create mode 100644 solutions/1012. Numbers With Repeated Digits/1012.java create mode 100644 solutions/1012. Numbers With Repeated Digits/1012.py create mode 100644 solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.cpp create mode 100644 solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.java create mode 100644 solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.py create mode 100644 solutions/1014. Best Sightseeing Pair/1014.cpp create mode 100644 solutions/1014. Best Sightseeing Pair/1014.java create mode 100644 solutions/1014. Best Sightseeing Pair/1014.py create mode 100644 solutions/1015. Smallest Integer Divisible by K/1015.cpp create mode 100644 solutions/1015. Smallest Integer Divisible by K/1015.java create mode 100644 solutions/1015. Smallest Integer Divisible by K/1015.py create mode 100644 solutions/1016. Binary String With Substrings Representing 1 To N/1016.cpp create mode 100644 solutions/1016. Binary String With Substrings Representing 1 To N/1016.java create mode 100644 solutions/1016. Binary String With Substrings Representing 1 To N/1016.py create mode 100644 solutions/1017. Convert to Base -2/1017.cpp create mode 100644 solutions/1017. Convert to Base -2/1017.java create mode 100644 solutions/1017. Convert to Base -2/1017.py create mode 100644 solutions/1018. Binary Prefix Divisible By 5/1018.cpp create mode 100644 solutions/1018. Binary Prefix Divisible By 5/1018.java create mode 100644 solutions/1018. Binary Prefix Divisible By 5/1018.py create mode 100644 solutions/1019. Next Greater Node In Linked List/1019.cpp create mode 100644 solutions/1019. Next Greater Node In Linked List/1019.java create mode 100644 solutions/1019. Next Greater Node In Linked List/1019.py create mode 100644 solutions/102. Binary Tree Level Order Traversal/102.cpp create mode 100644 solutions/102. Binary Tree Level Order Traversal/102.java create mode 100644 solutions/102. Binary Tree Level Order Traversal/102.py create mode 100644 solutions/1020. Number of Enclaves/1020.cpp create mode 100644 solutions/1020. Number of Enclaves/1020.java create mode 100644 solutions/1021. Remove Outermost Parentheses/1021.cpp create mode 100644 solutions/1021. Remove Outermost Parentheses/1021.java create mode 100644 solutions/1021. Remove Outermost Parentheses/1021.py create mode 100644 solutions/1022. Sum of Root To Leaf Binary Numbers/1022.cpp create mode 100644 solutions/1022. Sum of Root To Leaf Binary Numbers/1022.java create mode 100644 solutions/1022. Sum of Root To Leaf Binary Numbers/1022.py create mode 100644 solutions/1023. Camelcase Matching/1023.cpp create mode 100644 solutions/1023. Camelcase Matching/1023.java create mode 100644 solutions/1023. Camelcase Matching/1023.py create mode 100644 solutions/1024. Video Stitching/1024.cpp create mode 100644 solutions/1024. Video Stitching/1024.java create mode 100644 solutions/1024. Video Stitching/1024.py create mode 100644 solutions/1025. Divisor Game/1025.cpp create mode 100644 solutions/1025. Divisor Game/1025.java create mode 100644 solutions/1025. Divisor Game/1025.py create mode 100644 solutions/1026. Maximum Difference Between Node and Ancestor/1026.cpp create mode 100644 solutions/1026. Maximum Difference Between Node and Ancestor/1026.java create mode 100644 solutions/1027. Longest Arithmetic Subsequence/1027.cpp create mode 100644 solutions/1027. Longest Arithmetic Subsequence/1027.java create mode 100644 solutions/1027. Longest Arithmetic Subsequence/1027.py create mode 100644 solutions/1028. Recover a Tree From Preorder Traversal/1028.cpp create mode 100644 solutions/1028. Recover a Tree From Preorder Traversal/1028.java create mode 100644 solutions/1028. Recover a Tree From Preorder Traversal/1028.py create mode 100644 solutions/1029. Two City Scheduling/1029.cpp create mode 100644 solutions/1029. Two City Scheduling/1029.java create mode 100644 solutions/1029. Two City Scheduling/1029.py create mode 100644 solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.cpp create mode 100644 solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.java create mode 100644 solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.py create mode 100644 solutions/103. Binary Tree Zigzag Level Order Traversal/103.cpp create mode 100644 solutions/103. Binary Tree Zigzag Level Order Traversal/103.java create mode 100644 solutions/103. Binary Tree Zigzag Level Order Traversal/103.py create mode 100644 solutions/1030. Matrix Cells in Distance Order/1030.cpp create mode 100644 solutions/1030. Matrix Cells in Distance Order/1030.java create mode 100644 solutions/1030. Matrix Cells in Distance Order/1030.py create mode 100644 solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.cpp create mode 100644 solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.java create mode 100644 solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.py create mode 100644 solutions/1032. Stream of Characters/1032.cpp create mode 100644 solutions/1032. Stream of Characters/1032.java create mode 100644 solutions/1032. Stream of Characters/1032.py create mode 100644 solutions/1033. Moving Stones Until Consecutive/1033.cpp create mode 100644 solutions/1033. Moving Stones Until Consecutive/1033.java create mode 100644 solutions/1033. Moving Stones Until Consecutive/1033.py create mode 100644 solutions/1034. Coloring A Border/1034.cpp create mode 100644 solutions/1034. Coloring A Border/1034.java create mode 100644 solutions/1034. Coloring A Border/1034.py create mode 100644 solutions/1035. Uncrossed Lines/1035.cpp create mode 100644 solutions/1035. Uncrossed Lines/1035.java create mode 100644 solutions/1035. Uncrossed Lines/1035.py create mode 100644 solutions/1036. Escape a Large Maze/1036.cpp create mode 100644 solutions/1036. Escape a Large Maze/1036.java create mode 100644 solutions/1036. Escape a Large Maze/1036.py create mode 100644 solutions/1037. Valid Boomerang/1037.cpp create mode 100644 solutions/1037. Valid Boomerang/1037.java create mode 100644 solutions/1037. Valid Boomerang/1037.py create mode 100644 solutions/1038. Binary Search Tree to Greater Sum Tree/1038.cpp create mode 100644 solutions/1039. Minimum Score Triangulation of Polygon/1039.cpp create mode 100644 solutions/1039. Minimum Score Triangulation of Polygon/1039.java create mode 100644 solutions/1039. Minimum Score Triangulation of Polygon/1039.py create mode 100644 solutions/104. Maximum Depth of Binary Tree/104.cpp create mode 100644 solutions/104. Maximum Depth of Binary Tree/104.java create mode 100644 solutions/104. Maximum Depth of Binary Tree/104.py create mode 100644 solutions/1040. Moving Stones Until Consecutive II/1040.cpp create mode 100644 solutions/1040. Moving Stones Until Consecutive II/1040.java create mode 100644 solutions/1040. Moving Stones Until Consecutive II/1040.py create mode 100644 solutions/1041. Robot Bounded In Circle/1041.cpp create mode 100644 solutions/1041. Robot Bounded In Circle/1041.java create mode 100644 solutions/1041. Robot Bounded In Circle/1041.py create mode 100644 solutions/1042. Flower Planting With No Adjacent/1042.cpp create mode 100644 solutions/1042. Flower Planting With No Adjacent/1042.java create mode 100644 solutions/1042. Flower Planting With No Adjacent/1042.py create mode 100644 solutions/1043. Partition Array for Maximum Sum/1043.cpp create mode 100644 solutions/1043. Partition Array for Maximum Sum/1043.java create mode 100644 solutions/1043. Partition Array for Maximum Sum/1043.py create mode 100644 solutions/1044. Longest Duplicate Substring/1044.cpp create mode 100644 solutions/1044. Longest Duplicate Substring/1044.java create mode 100644 solutions/1044. Longest Duplicate Substring/1044.py create mode 100644 solutions/1045. Customers Who Bought All Products/1045.sql create mode 100644 solutions/1046. Last Stone Weight/1046.cpp create mode 100644 solutions/1046. Last Stone Weight/1046.java create mode 100644 solutions/1046. Last Stone Weight/1046.py create mode 100644 solutions/1047. Remove All Adjacent Duplicates In String/1047.cpp create mode 100644 solutions/1047. Remove All Adjacent Duplicates In String/1047.java create mode 100644 solutions/1048. Longest String Chain/1048-2.cpp create mode 100644 solutions/1048. Longest String Chain/1048-2.java create mode 100644 solutions/1048. Longest String Chain/1048-2.py create mode 100644 solutions/1048. Longest String Chain/1048.cpp create mode 100644 solutions/1048. Longest String Chain/1048.java create mode 100644 solutions/1048. Longest String Chain/1048.py create mode 100644 solutions/1049. Last Stone Weight II/1049.cpp create mode 100644 solutions/1049. Last Stone Weight II/1049.java create mode 100644 solutions/1049. Last Stone Weight II/1049.py create mode 100644 solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.cpp create mode 100644 solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.java create mode 100644 solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.py create mode 100644 solutions/1050. Actors and Directors Who Cooperated At Least Three Times/1050.sql create mode 100644 solutions/1051. Height Checker/1051.cpp create mode 100644 solutions/1051. Height Checker/1051.java create mode 100644 solutions/1051. Height Checker/1051.py create mode 100644 solutions/1052. Grumpy Bookstore Owner/1052.cpp create mode 100644 solutions/1052. Grumpy Bookstore Owner/1052.java create mode 100644 solutions/1052. Grumpy Bookstore Owner/1052.py create mode 100644 solutions/1053. Previous Permutation With One Swap/1053.cpp create mode 100644 solutions/1053. Previous Permutation With One Swap/1053.java create mode 100644 solutions/1053. Previous Permutation With One Swap/1053.py create mode 100644 solutions/1054. Distant Barcodes/1054.cpp create mode 100644 solutions/1054. Distant Barcodes/1054.java create mode 100644 solutions/1054. Distant Barcodes/1054.py create mode 100644 solutions/1055. Shortest Way to Form String/1055-2.cpp create mode 100644 solutions/1055. Shortest Way to Form String/1055-2.java create mode 100644 solutions/1055. Shortest Way to Form String/1055.cpp create mode 100644 solutions/1055. Shortest Way to Form String/1055.java create mode 100644 solutions/1056. Confusing Number/1056.cpp create mode 100644 solutions/1056. Confusing Number/1056.java create mode 100644 solutions/1056. Confusing Number/1056.py create mode 100644 solutions/1057. Campus Bikes/1057.cpp create mode 100644 solutions/1057. Campus Bikes/1057.java create mode 100644 solutions/1057. Campus Bikes/1057.py create mode 100644 solutions/1058. Minimize Rounding Error to Meet Target/1058.cpp create mode 100644 solutions/1058. Minimize Rounding Error to Meet Target/1058.java create mode 100644 solutions/1058. Minimize Rounding Error to Meet Target/1058.py create mode 100644 solutions/1059. All Paths from Source Lead to Destination/1059.cpp create mode 100644 solutions/1059. All Paths from Source Lead to Destination/1059.java create mode 100644 solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.cpp create mode 100644 solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.java create mode 100644 solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.py create mode 100644 solutions/1060. Missing Element in Sorted Array/1060.cpp create mode 100644 solutions/1060. Missing Element in Sorted Array/1060.java create mode 100644 solutions/1061. Lexicographically Smallest Equivalent String/1061.cpp create mode 100644 solutions/1061. Lexicographically Smallest Equivalent String/1061.java create mode 100644 solutions/1062. Longest Repeating Substring/1062.cpp create mode 100644 solutions/1062. Longest Repeating Substring/1062.java create mode 100644 solutions/1062. Longest Repeating Substring/1062.py create mode 100644 solutions/1063. Number of Valid Subarrays/1063.cpp create mode 100644 solutions/1063. Number of Valid Subarrays/1063.java create mode 100644 solutions/1063. Number of Valid Subarrays/1063.py create mode 100644 solutions/1064. Fixed Point/1064.cpp create mode 100644 solutions/1064. Fixed Point/1064.java create mode 100644 solutions/1064. Fixed Point/1064.py create mode 100644 solutions/1065. Index Pairs of a String/1065.cpp create mode 100644 solutions/1065. Index Pairs of a String/1065.java create mode 100644 solutions/1065. Index Pairs of a String/1065.py create mode 100644 solutions/1066. Campus Bikes II/1066.cpp create mode 100644 solutions/1066. Campus Bikes II/1066.java create mode 100644 solutions/1066. Campus Bikes II/1066.py create mode 100644 solutions/1067. Digit Count in Range/1067.cpp create mode 100644 solutions/1067. Digit Count in Range/1067.java create mode 100644 solutions/1068. Product Sales Analysis I/1068.sql create mode 100644 solutions/1069. Product Sales Analysis II/1069.sql create mode 100644 solutions/107. Binary Tree Level Order Traversal II/107.cpp create mode 100644 solutions/107. Binary Tree Level Order Traversal II/107.java create mode 100644 solutions/107. Binary Tree Level Order Traversal II/107.py create mode 100644 solutions/1070. Product Sales Analysis III/1070.sql create mode 100644 solutions/1071. Greatest Common Divisor of Strings/1071.cpp create mode 100644 solutions/1071. Greatest Common Divisor of Strings/1071.java create mode 100644 solutions/1071. Greatest Common Divisor of Strings/1071.py create mode 100644 solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.cpp create mode 100644 solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.java create mode 100644 solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.py create mode 100644 solutions/1073. Adding Two Negabinary Numbers/1073.cpp create mode 100644 solutions/1073. Adding Two Negabinary Numbers/1073.java create mode 100644 solutions/1073. Adding Two Negabinary Numbers/1073.py create mode 100644 solutions/1074. Number of Submatrices That Sum to Target/1074.cpp create mode 100644 solutions/1074. Number of Submatrices That Sum to Target/1074.java create mode 100644 solutions/1074. Number of Submatrices That Sum to Target/1074.py create mode 100644 solutions/1075. Project Employees I/1075.sql create mode 100644 solutions/1076. Project Employees II/1076.sql create mode 100644 solutions/1077. Project Employees III/1077.sql create mode 100644 solutions/1078. Occurrences After Bigram/1078.cpp create mode 100644 solutions/1078. Occurrences After Bigram/1078.java create mode 100644 solutions/1078. Occurrences After Bigram/1078.py create mode 100644 solutions/1079. Letter Tile Possibilities/1079.cpp create mode 100644 solutions/1079. Letter Tile Possibilities/1079.java create mode 100644 solutions/1079. Letter Tile Possibilities/1079.py create mode 100644 solutions/108. Convert Sorted Array to Binary Search Tree/108.cpp create mode 100644 solutions/108. Convert Sorted Array to Binary Search Tree/108.java create mode 100644 solutions/108. Convert Sorted Array to Binary Search Tree/108.py create mode 100644 solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.cpp create mode 100644 solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.java create mode 100644 solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.py create mode 100644 solutions/1081. Smallest Subsequence of Distinct Characters/1081.cpp create mode 100644 solutions/1081. Smallest Subsequence of Distinct Characters/1081.java create mode 100644 solutions/1081. Smallest Subsequence of Distinct Characters/1081.py create mode 100644 solutions/1082. Sales Analysis I/1082.sql create mode 100644 solutions/1083. Sales Analysis II/1083.sql create mode 100644 solutions/1084. Sales Analysis III/1084.sql create mode 100644 solutions/1085. Sum of Digits in the Minimum Number/1085.cpp create mode 100644 solutions/1085. Sum of Digits in the Minimum Number/1085.java create mode 100644 solutions/1085. Sum of Digits in the Minimum Number/1085.py create mode 100644 solutions/1086. High Five/1086.cpp create mode 100644 solutions/1086. High Five/1086.java create mode 100644 solutions/1086. High Five/1086.py create mode 100644 solutions/1087. Brace Expansion/1087.cpp create mode 100644 solutions/1087. Brace Expansion/1087.java create mode 100644 solutions/1087. Brace Expansion/1087.py create mode 100644 solutions/1088. Confusing Number II/1088.cpp create mode 100644 solutions/1088. Confusing Number II/1088.java create mode 100644 solutions/1088. Confusing Number II/1088.py create mode 100644 solutions/1089. Duplicate Zeros/1089.cpp create mode 100644 solutions/1089. Duplicate Zeros/1089.java create mode 100644 solutions/1089. Duplicate Zeros/1089.py create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109-2.cpp create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109-2.java create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109-2.py create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109-3.cpp create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109-3.java create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109-3.py create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109.cpp create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109.java create mode 100644 solutions/109. Convert Sorted List to Binary Search Tree/109.py create mode 100644 solutions/1090. Largest Values From Labels/1090.cpp create mode 100644 solutions/1091. Shortest Path in Binary Matrix/1091.cpp create mode 100644 solutions/1091. Shortest Path in Binary Matrix/1091.java create mode 100644 solutions/1092. Shortest Common Supersequence/1092.cpp create mode 100644 solutions/1092. Shortest Common Supersequence/1092.java create mode 100644 solutions/1093. Statistics from a Large Sample/1093.cpp create mode 100644 solutions/1093. Statistics from a Large Sample/1093.java create mode 100644 solutions/1093. Statistics from a Large Sample/1093.py create mode 100644 solutions/1094. Car Pooling/1094-2.cpp create mode 100644 solutions/1094. Car Pooling/1094-2.java create mode 100644 solutions/1094. Car Pooling/1094.cpp create mode 100644 solutions/1094. Car Pooling/1094.java create mode 100644 solutions/1095. Find in Mountain Array/1095.cpp create mode 100644 solutions/1095. Find in Mountain Array/1095.java create mode 100644 solutions/1095. Find in Mountain Array/1095.py create mode 100644 solutions/1096. Brace Expansion II/1096.cpp create mode 100644 solutions/1096. Brace Expansion II/1096.java create mode 100644 solutions/1096. Brace Expansion II/1096.py create mode 100644 solutions/1097. Game Play Analysis V/1097.sql create mode 100644 solutions/1098. Unpopular Books/1098.sql create mode 100644 solutions/1099. Two Sum Less Than K/1099.cpp create mode 100644 solutions/1099. Two Sum Less Than K/1099.java create mode 100644 solutions/1099. Two Sum Less Than K/1099.py create mode 100644 solutions/11. Container With Most Water/11.cpp create mode 100644 solutions/11. Container With Most Water/11.java create mode 100644 solutions/11. Container With Most Water/11.py create mode 100644 solutions/110. Balanced Binary Tree/110-2.cpp create mode 100644 solutions/110. Balanced Binary Tree/110-2.java create mode 100644 solutions/110. Balanced Binary Tree/110-2.py create mode 100644 solutions/110. Balanced Binary Tree/110-3.cpp create mode 100644 solutions/110. Balanced Binary Tree/110-3.java create mode 100644 solutions/110. Balanced Binary Tree/110-3.py create mode 100644 solutions/110. Balanced Binary Tree/110.cpp create mode 100644 solutions/110. Balanced Binary Tree/110.java create mode 100644 solutions/110. Balanced Binary Tree/110.py create mode 100644 solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.cpp create mode 100644 solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.java create mode 100644 solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.py create mode 100644 solutions/1101. The Earliest Moment When Everyone Become Friends/1101.cpp create mode 100644 solutions/1101. The Earliest Moment When Everyone Become Friends/1101.java create mode 100644 solutions/1101. The Earliest Moment When Everyone Become Friends/1101.py create mode 100644 solutions/1102. Path With Maximum Minimum Value/1102.cpp create mode 100644 solutions/1102. Path With Maximum Minimum Value/1102.java create mode 100644 solutions/1103. Distribute Candies to People/1103.cpp create mode 100644 solutions/1103. Distribute Candies to People/1103.java create mode 100644 solutions/1103. Distribute Candies to People/1103.py create mode 100644 solutions/1104. Path In Zigzag Labelled Binary Tree/1104.cpp create mode 100644 solutions/1104. Path In Zigzag Labelled Binary Tree/1104.java create mode 100644 solutions/1104. Path In Zigzag Labelled Binary Tree/1104.py create mode 100644 solutions/1105. Filling Bookcase Shelves/1105.cpp create mode 100644 solutions/1105. Filling Bookcase Shelves/1105.java create mode 100644 solutions/1105. Filling Bookcase Shelves/1105.py create mode 100644 solutions/1106. Parsing A Boolean Expression/1106.cpp create mode 100644 solutions/1106. Parsing A Boolean Expression/1106.java create mode 100644 solutions/1106. Parsing A Boolean Expression/1106.py create mode 100644 solutions/1107. New Users Daily Count/1107.sql create mode 100644 solutions/1108. Defanging an IP Address/1108.cpp create mode 100644 solutions/1108. Defanging an IP Address/1108.java create mode 100644 solutions/1108. Defanging an IP Address/1108.py create mode 100644 solutions/1109. Corporate Flight Bookings/1109.cpp create mode 100644 solutions/1109. Corporate Flight Bookings/1109.java create mode 100644 solutions/1109. Corporate Flight Bookings/1109.py create mode 100644 solutions/111. Minimum Depth of Binary Tree/111-2.cpp create mode 100644 solutions/111. Minimum Depth of Binary Tree/111-2.java create mode 100644 solutions/111. Minimum Depth of Binary Tree/111-2.py create mode 100644 solutions/111. Minimum Depth of Binary Tree/111.cpp create mode 100644 solutions/111. Minimum Depth of Binary Tree/111.java create mode 100644 solutions/111. Minimum Depth of Binary Tree/111.py create mode 100644 solutions/1110. Delete Nodes And Return Forest/1110.cpp create mode 100644 solutions/1110. Delete Nodes And Return Forest/1110.java create mode 100644 solutions/1110. Delete Nodes And Return Forest/1110.py create mode 100644 solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.cpp create mode 100644 solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.java create mode 100644 solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.py create mode 100644 solutions/1112. Highest Grade For Each Student/1112.sql create mode 100644 solutions/1113. Reported Posts/1113.sql create mode 100644 solutions/1114. Print in Order/1114.cpp create mode 100644 solutions/1114. Print in Order/1114.java create mode 100644 solutions/1114. Print in Order/1114.py create mode 100644 solutions/1115. Print FooBar Alternately/1115.cpp create mode 100644 solutions/1115. Print FooBar Alternately/1115.java create mode 100644 solutions/1115. Print FooBar Alternately/1115.py create mode 100644 solutions/1116. Print Zero Even Odd/1116.cpp create mode 100644 solutions/1116. Print Zero Even Odd/1116.java create mode 100644 solutions/1116. Print Zero Even Odd/1116.py create mode 100644 solutions/1117. Building H2O/1117.cpp create mode 100644 solutions/1118. Number of Days in a Month/1118.cpp create mode 100644 solutions/1118. Number of Days in a Month/1118.java create mode 100644 solutions/1118. Number of Days in a Month/1118.py create mode 100644 solutions/1119. Remove Vowels from a String/1119.cpp create mode 100644 solutions/1119. Remove Vowels from a String/1119.java create mode 100644 solutions/1119. Remove Vowels from a String/1119.py create mode 100644 solutions/112. Path Sum/112.cpp create mode 100644 solutions/112. Path Sum/112.java create mode 100644 solutions/112. Path Sum/112.py create mode 100644 solutions/1120. Maximum Average Subtree/1120.cpp create mode 100644 solutions/1120. Maximum Average Subtree/1120.java create mode 100644 solutions/1120. Maximum Average Subtree/1120.py create mode 100644 solutions/1121. Divide Array Into Increasing Sequences/1121.cpp create mode 100644 solutions/1121. Divide Array Into Increasing Sequences/1121.java create mode 100644 solutions/1121. Divide Array Into Increasing Sequences/1121.py create mode 100644 solutions/1122. Relative Sort Array/1122.cpp create mode 100644 solutions/1122. Relative Sort Array/1122.java create mode 100644 solutions/1122. Relative Sort Array/1122.py create mode 100644 solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.cpp create mode 100644 solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.java create mode 100644 solutions/1124. Longest Well-Performing Interval/1124.cpp create mode 100644 solutions/1124. Longest Well-Performing Interval/1124.py create mode 100644 solutions/1125. Smallest Sufficient Team/1125.cpp create mode 100644 solutions/1125. Smallest Sufficient Team/1125.java create mode 100644 solutions/1126. Active Businesses/1126.sql create mode 100644 solutions/1127. User Purchase Platform/1127.sql create mode 100644 solutions/1128. Number of Equivalent Domino Pairs/1128.cpp create mode 100644 solutions/1128. Number of Equivalent Domino Pairs/1128.java create mode 100644 solutions/1128. Number of Equivalent Domino Pairs/1128.py create mode 100644 solutions/1129. Shortest Path with Alternating Colors/1129.cpp create mode 100644 solutions/1129. Shortest Path with Alternating Colors/1129.java create mode 100644 solutions/1129. Shortest Path with Alternating Colors/1129.py create mode 100644 solutions/113. Path Sum II/113.cpp create mode 100644 solutions/113. Path Sum II/113.java create mode 100644 solutions/113. Path Sum II/113.py create mode 100644 solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.cpp create mode 100644 solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.java create mode 100644 solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.py create mode 100644 solutions/1130. Minimum Cost Tree From Leaf Values/1130-3.py create mode 100644 solutions/1130. Minimum Cost Tree From Leaf Values/1130.cpp create mode 100644 solutions/1130. Minimum Cost Tree From Leaf Values/1130.java create mode 100644 solutions/1130. Minimum Cost Tree From Leaf Values/1130.py create mode 100644 solutions/1131. Maximum of Absolute Value Expression/1131.cpp create mode 100644 solutions/1131. Maximum of Absolute Value Expression/1131.java create mode 100644 solutions/1131. Maximum of Absolute Value Expression/1131.py create mode 100644 solutions/1132. Reported Posts II/1132.sql create mode 100644 solutions/1133. Largest Unique Number/1133.cpp create mode 100644 solutions/1133. Largest Unique Number/1133.java create mode 100644 solutions/1133. Largest Unique Number/1133.py create mode 100644 solutions/1134. Armstrong Number/1134.cpp create mode 100644 solutions/1134. Armstrong Number/1134.java create mode 100644 solutions/1134. Armstrong Number/1134.py create mode 100644 solutions/1135. Connecting Cities With Minimum Cost/1135.cpp create mode 100644 solutions/1135. Connecting Cities With Minimum Cost/1135.java create mode 100644 solutions/1135. Connecting Cities With Minimum Cost/1135.py create mode 100644 solutions/1136. Parallel Courses/1136-2.cpp create mode 100644 solutions/1136. Parallel Courses/1136-2.java create mode 100644 solutions/1136. Parallel Courses/1136-2.py create mode 100644 solutions/1136. Parallel Courses/1136.cpp create mode 100644 solutions/1136. Parallel Courses/1136.java create mode 100644 solutions/1136. Parallel Courses/1136.py create mode 100644 solutions/1137. N-th Tribonacci Number/1137-2.cpp create mode 100644 solutions/1137. N-th Tribonacci Number/1137-2.java create mode 100644 solutions/1137. N-th Tribonacci Number/1137-2.py create mode 100644 solutions/1137. N-th Tribonacci Number/1137.cpp create mode 100644 solutions/1137. N-th Tribonacci Number/1137.java create mode 100644 solutions/1137. N-th Tribonacci Number/1137.py create mode 100644 solutions/1138. Alphabet Board Path/1138.cpp create mode 100644 solutions/1139. Largest 1-Bordered Square/1139.cpp create mode 100644 solutions/1139. Largest 1-Bordered Square/1139.java create mode 100644 solutions/1139. Largest 1-Bordered Square/1139.py create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114-2.cpp create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114-2.java create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114-2.py create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114-3.cpp create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114-3.java create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114-3.py create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114.cpp create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114.java create mode 100644 solutions/114. Flatten Binary Tree to Linked List/114.py create mode 100644 solutions/1140. Stone Game II/1140.cpp create mode 100644 solutions/1140. Stone Game II/1140.java create mode 100644 solutions/1141. User Activity for the Past 30 Days I/1141.sql create mode 100644 solutions/1142. User Activity for the Past 30 Days II/1142.sql create mode 100644 solutions/1143. Longest Common Subsequence/1143.cpp create mode 100644 solutions/1143. Longest Common Subsequence/1143.java create mode 100644 solutions/1143. Longest Common Subsequence/1143.py create mode 100644 solutions/1144. Decrease Elements To Make Array Zigzag/1144.cpp create mode 100644 solutions/1144. Decrease Elements To Make Array Zigzag/1144.java create mode 100644 solutions/1144. Decrease Elements To Make Array Zigzag/1144.py create mode 100644 solutions/1145. Binary Tree Coloring Game/1145.cpp create mode 100644 solutions/1145. Binary Tree Coloring Game/1145.java create mode 100644 solutions/1146. Snapshot Array/1146.cpp create mode 100644 solutions/1146. Snapshot Array/1146.java create mode 100644 solutions/1146. Snapshot Array/1146.py create mode 100644 solutions/1147. Longest Chunked Palindrome Decomposition/1147.cpp create mode 100644 solutions/1147. Longest Chunked Palindrome Decomposition/1147.java create mode 100644 solutions/1148. Article Views I/1148.sql create mode 100644 solutions/1149. Article Views II/1149.sql create mode 100644 solutions/115. Distinct Subsequences/115-2.cpp create mode 100644 solutions/115. Distinct Subsequences/115-2.java create mode 100644 solutions/115. Distinct Subsequences/115-2.py create mode 100644 solutions/115. Distinct Subsequences/115.cpp create mode 100644 solutions/115. Distinct Subsequences/115.java create mode 100644 solutions/115. Distinct Subsequences/115.py create mode 100644 solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.cpp create mode 100644 solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.java create mode 100644 solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.py create mode 100644 solutions/1151. Minimum Swaps to Group All 1's Together/1151.cpp create mode 100644 solutions/1151. Minimum Swaps to Group All 1's Together/1151.java create mode 100644 solutions/1151. Minimum Swaps to Group All 1's Together/1151.py create mode 100644 solutions/1152. Analyze User Website Visit Pattern/1152.py create mode 100644 solutions/1153. String Transforms Into Another String/1153.cpp create mode 100644 solutions/1153. String Transforms Into Another String/1153.java create mode 100644 solutions/1153. String Transforms Into Another String/1153.py create mode 100644 solutions/1154. Day of the Year/1154.cpp create mode 100644 solutions/1154. Day of the Year/1154.java create mode 100644 solutions/1154. Day of the Year/1154.py create mode 100644 solutions/1155. Number of Dice Rolls With Target Sum/1155.cpp create mode 100644 solutions/1155. Number of Dice Rolls With Target Sum/1155.java create mode 100644 solutions/1155. Number of Dice Rolls With Target Sum/1155.py create mode 100644 solutions/1156. Swap For Longest Repeated Character Substring/1156.cpp create mode 100644 solutions/1156. Swap For Longest Repeated Character Substring/1156.java create mode 100644 solutions/1156. Swap For Longest Repeated Character Substring/1156.py create mode 100644 solutions/1157. Online Majority Element In Subarray/1157.cpp create mode 100644 solutions/1157. Online Majority Element In Subarray/1157.java create mode 100644 solutions/1157. Online Majority Element In Subarray/1157.py create mode 100644 solutions/1158. Market Analysis I/1158.sql create mode 100644 solutions/1159. Market Analysis II/1159.sql create mode 100644 solutions/116. Populating Next Right Pointers in Each Node/116-2.cpp create mode 100644 solutions/116. Populating Next Right Pointers in Each Node/116-2.java create mode 100644 solutions/116. Populating Next Right Pointers in Each Node/116-2.py create mode 100644 solutions/116. Populating Next Right Pointers in Each Node/116.cpp create mode 100644 solutions/116. Populating Next Right Pointers in Each Node/116.java create mode 100644 solutions/116. Populating Next Right Pointers in Each Node/116.py create mode 100644 solutions/1160. Find Words That Can Be Formed by Characters/1160.cpp create mode 100644 solutions/1160. Find Words That Can Be Formed by Characters/1160.java create mode 100644 solutions/1160. Find Words That Can Be Formed by Characters/1160.py create mode 100644 solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.cpp create mode 100644 solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.java create mode 100644 solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.py create mode 100644 solutions/1161. Maximum Level Sum of a Binary Tree/1161.cpp create mode 100644 solutions/1161. Maximum Level Sum of a Binary Tree/1161.java create mode 100644 solutions/1161. Maximum Level Sum of a Binary Tree/1161.py create mode 100644 solutions/1162. As Far from Land as Possible/1162.cpp create mode 100644 solutions/1162. As Far from Land as Possible/1162.java create mode 100644 solutions/1162. As Far from Land as Possible/1162.py create mode 100644 solutions/1163. Last Substring in Lexicographical Order/1163.cpp create mode 100644 solutions/1163. Last Substring in Lexicographical Order/1163.java create mode 100644 solutions/1163. Last Substring in Lexicographical Order/1163.py create mode 100644 solutions/1164. Product Price at a Given Date/1164.sql create mode 100644 solutions/1165. Single-Row Keyboard/1165.cpp create mode 100644 solutions/1165. Single-Row Keyboard/1165.java create mode 100644 solutions/1165. Single-Row Keyboard/1165.py create mode 100644 solutions/1166. Design File System/1166.cpp create mode 100644 solutions/1166. Design File System/1166.java create mode 100644 solutions/1166. Design File System/1166.py create mode 100644 solutions/1167. Minimum Cost to Connect Sticks/1167.cpp create mode 100644 solutions/1167. Minimum Cost to Connect Sticks/1167.java create mode 100644 solutions/1167. Minimum Cost to Connect Sticks/1167.py create mode 100644 solutions/1168. Optimize Water Distribution in a Village/1168.cpp create mode 100644 solutions/1168. Optimize Water Distribution in a Village/1168.java create mode 100644 solutions/1168. Optimize Water Distribution in a Village/1168.py create mode 100644 solutions/1169. Invalid Transactions/1169.cpp create mode 100644 solutions/1169. Invalid Transactions/1169.java create mode 100644 solutions/1169. Invalid Transactions/1169.py create mode 100644 solutions/117. Populating Next Right Pointers in Each Node II/117.cpp create mode 100644 solutions/117. Populating Next Right Pointers in Each Node II/117.java create mode 100644 solutions/117. Populating Next Right Pointers in Each Node II/117.py create mode 100644 solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.cpp create mode 100644 solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.java create mode 100644 solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.py create mode 100644 solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.cpp create mode 100644 solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.java create mode 100644 solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.py create mode 100644 solutions/1172. Dinner Plate Stacks/1172.cpp create mode 100644 solutions/1172. Dinner Plate Stacks/1172.java create mode 100644 solutions/1172. Dinner Plate Stacks/1172.py create mode 100644 solutions/1173. Immediate Food Delivery I/1173.sql create mode 100644 solutions/1174. Immediate Food Delivery II/1174.sql create mode 100644 solutions/1175. Prime Arrangements/1175.cpp create mode 100644 solutions/1175. Prime Arrangements/1175.java create mode 100644 solutions/1175. Prime Arrangements/1175.py create mode 100644 solutions/1176. Diet Plan Performance/1176.cpp create mode 100644 solutions/1176. Diet Plan Performance/1176.java create mode 100644 solutions/1176. Diet Plan Performance/1176.py create mode 100644 solutions/1177. Can Make Palindrome from Substring/1177.cpp create mode 100644 solutions/1177. Can Make Palindrome from Substring/1177.java create mode 100644 solutions/1177. Can Make Palindrome from Substring/1177.py create mode 100644 solutions/1178. Number of Valid Words for Each Puzzle/1178.cpp create mode 100644 solutions/1178. Number of Valid Words for Each Puzzle/1178.java create mode 100644 solutions/1178. Number of Valid Words for Each Puzzle/1178.py create mode 100644 solutions/1179. Reformat Department Table/1179.sql create mode 100644 solutions/118. Pascal's Triangle/118.cpp create mode 100644 solutions/118. Pascal's Triangle/118.java create mode 100644 solutions/118. Pascal's Triangle/118.py create mode 100644 solutions/1180. Count Substrings with Only One Distinct Letter/1180.cpp create mode 100644 solutions/1180. Count Substrings with Only One Distinct Letter/1180.java create mode 100644 solutions/1180. Count Substrings with Only One Distinct Letter/1180.py create mode 100644 solutions/1181. Before and After Puzzle/1181.cpp create mode 100644 solutions/1182. Shortest Distance to Target Color/1182.cpp create mode 100644 solutions/1182. Shortest Distance to Target Color/1182.java create mode 100644 solutions/1182. Shortest Distance to Target Color/1182.py create mode 100644 solutions/1183. Maximum Number of Ones/1183-2.cpp create mode 100644 solutions/1183. Maximum Number of Ones/1183-2.java create mode 100644 solutions/1183. Maximum Number of Ones/1183-2.py create mode 100644 solutions/1183. Maximum Number of Ones/1183.cpp create mode 100644 solutions/1183. Maximum Number of Ones/1183.java create mode 100644 solutions/1183. Maximum Number of Ones/1183.py create mode 100644 solutions/1184. Distance Between Bus Stops/1184.cpp create mode 100644 solutions/1184. Distance Between Bus Stops/1184.java create mode 100644 solutions/1184. Distance Between Bus Stops/1184.py create mode 100644 solutions/1185. Day of the Week/1185.cpp create mode 100644 solutions/1185. Day of the Week/1185.java create mode 100644 solutions/1185. Day of the Week/1185.py create mode 100644 solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.cpp create mode 100644 solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.java create mode 100644 solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.py create mode 100644 solutions/1186. Maximum Subarray Sum with One Deletion/1186.cpp create mode 100644 solutions/1186. Maximum Subarray Sum with One Deletion/1186.java create mode 100644 solutions/1186. Maximum Subarray Sum with One Deletion/1186.py create mode 100644 solutions/1187. Make Array Strictly Increasing/1187.cpp create mode 100644 solutions/1187. Make Array Strictly Increasing/1187.java create mode 100644 solutions/1187. Make Array Strictly Increasing/1187.py create mode 100644 solutions/1188. Design Bounded Blocking Queue/1188.cpp create mode 100644 solutions/1188. Design Bounded Blocking Queue/1188.java create mode 100644 solutions/1188. Design Bounded Blocking Queue/1188.py create mode 100644 solutions/1189. Maximum Number of Balloons/1189.cpp create mode 100644 solutions/1189. Maximum Number of Balloons/1189.java create mode 100644 solutions/1189. Maximum Number of Balloons/1189.py create mode 100644 solutions/119. Pascal's Triangle II/119.cpp create mode 100644 solutions/119. Pascal's Triangle II/119.java create mode 100644 solutions/119. Pascal's Triangle II/119.py create mode 100644 solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.cpp create mode 100644 solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.java create mode 100644 solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.py create mode 100644 solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.cpp create mode 100644 solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.java create mode 100644 solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.py create mode 100644 solutions/1191. K-Concatenation Maximum Sum/1191.cpp create mode 100644 solutions/1191. K-Concatenation Maximum Sum/1191.java create mode 100644 solutions/1191. K-Concatenation Maximum Sum/1191.py create mode 100644 solutions/1192. Critical Connections in a Network/1192.cpp create mode 100644 solutions/1192. Critical Connections in a Network/1192.java create mode 100644 solutions/1193. Monthly Transactions I/1193.sql create mode 100644 solutions/1194. Tournament Winners/1194.sql create mode 100644 solutions/1195. Fizz Buzz Multithreaded/1195.cpp create mode 100644 solutions/1195. Fizz Buzz Multithreaded/1195.java create mode 100644 solutions/1195. Fizz Buzz Multithreaded/1195.py create mode 100644 solutions/1196. How Many Apples Can You Put into the Basket/1196.cpp create mode 100644 solutions/1196. How Many Apples Can You Put into the Basket/1196.java create mode 100644 solutions/1196. How Many Apples Can You Put into the Basket/1196.py create mode 100644 solutions/1197. Minimum Knight Moves/1197.cpp create mode 100644 solutions/1197. Minimum Knight Moves/1197.java create mode 100644 solutions/1198. Find Smallest Common Element in All Rows/1198.cpp create mode 100644 solutions/1198. Find Smallest Common Element in All Rows/1198.java create mode 100644 solutions/1198. Find Smallest Common Element in All Rows/1198.py create mode 100644 solutions/1199. Minimum Time to Build Blocks/1199.cpp create mode 100644 solutions/1199. Minimum Time to Build Blocks/1199.java create mode 100644 solutions/1199. Minimum Time to Build Blocks/1199.py create mode 100644 solutions/12. Integer to Roman/12-2.cpp create mode 100644 solutions/12. Integer to Roman/12-2.java create mode 100644 solutions/12. Integer to Roman/12-2.py create mode 100644 solutions/12. Integer to Roman/12.cpp create mode 100644 solutions/12. Integer to Roman/12.java create mode 100644 solutions/12. Integer to Roman/12.py create mode 100644 solutions/120. Triangle/120.cpp create mode 100644 solutions/120. Triangle/120.java create mode 100644 solutions/120. Triangle/120.py create mode 100644 solutions/1200. Minimum Absolute Difference/1200.cpp create mode 100644 solutions/1200. Minimum Absolute Difference/1200.java create mode 100644 solutions/1200. Minimum Absolute Difference/1200.py create mode 100644 solutions/1201. Ugly Number III/1201.cpp create mode 100644 solutions/1201. Ugly Number III/1201.java create mode 100644 solutions/1201. Ugly Number III/1201.py create mode 100644 solutions/1202. Smallest String With Swaps/1202.cpp create mode 100644 solutions/1202. Smallest String With Swaps/1202.java create mode 100644 solutions/1202. Smallest String With Swaps/1202.py create mode 100644 solutions/1203. Sort Items by Groups Respecting Dependencies/1203.cpp create mode 100644 solutions/1203. Sort Items by Groups Respecting Dependencies/1203.java create mode 100644 solutions/1204. Last Person to Fit in the Bus/1204.sql create mode 100644 solutions/1205. Monthly Transactions II/1205.sql create mode 100644 solutions/1206. Design Skiplist/1206.cpp create mode 100644 solutions/1206. Design Skiplist/1206.java create mode 100644 solutions/1206. Design Skiplist/1206.py create mode 100644 solutions/1207. Unique Number of Occurrences/1207.cpp create mode 100644 solutions/1207. Unique Number of Occurrences/1207.java create mode 100644 solutions/1207. Unique Number of Occurrences/1207.py create mode 100644 solutions/1208. Get Equal Substrings Within Budget/1208.cpp create mode 100644 solutions/1208. Get Equal Substrings Within Budget/1208.java create mode 100644 solutions/1208. Get Equal Substrings Within Budget/1208.py create mode 100644 solutions/1209. Remove All Adjacent Duplicates in String II/1209.cpp create mode 100644 solutions/1209. Remove All Adjacent Duplicates in String II/1209.java create mode 100644 solutions/1209. Remove All Adjacent Duplicates in String II/1209.py create mode 100644 solutions/121. Best Time to Buy and Sell Stock/121.cpp create mode 100644 solutions/121. Best Time to Buy and Sell Stock/121.java create mode 100644 solutions/121. Best Time to Buy and Sell Stock/121.py create mode 100644 solutions/1210. Minimum Moves to Reach Target with Rotations/1210.cpp create mode 100644 solutions/1210. Minimum Moves to Reach Target with Rotations/1210.java create mode 100644 solutions/1210. Minimum Moves to Reach Target with Rotations/1210.py create mode 100644 solutions/1211. Queries Quality and Percentage/1211.sql create mode 100644 solutions/1212. Team Scores in Football Tournament/1212.sql create mode 100644 solutions/1213. Intersection of Three Sorted Arrays/1213.cpp create mode 100644 solutions/1213. Intersection of Three Sorted Arrays/1213.java create mode 100644 solutions/1214. Two Sum BSTs/1214.cpp create mode 100644 solutions/1214. Two Sum BSTs/1214.java create mode 100644 solutions/1214. Two Sum BSTs/1214.py create mode 100644 solutions/1215. Stepping Numbers/1215-2.cpp create mode 100644 solutions/1215. Stepping Numbers/1215-2.java create mode 100644 solutions/1215. Stepping Numbers/1215-2.py create mode 100644 solutions/1215. Stepping Numbers/1215.cpp create mode 100644 solutions/1215. Stepping Numbers/1215.java create mode 100644 solutions/1215. Stepping Numbers/1215.py create mode 100644 solutions/1216. Valid Palindrome III/1216.cpp create mode 100644 solutions/1216. Valid Palindrome III/1216.java create mode 100644 solutions/1216. Valid Palindrome III/1216.py create mode 100644 solutions/1217. Play with Chips/1217.cpp create mode 100644 solutions/1217. Play with Chips/1217.java create mode 100644 solutions/1217. Play with Chips/1217.py create mode 100644 solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.cpp create mode 100644 solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.java create mode 100644 solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.py create mode 100644 solutions/1219. Path with Maximum Gold/1219.cpp create mode 100644 solutions/1219. Path with Maximum Gold/1219.java create mode 100644 solutions/1219. Path with Maximum Gold/1219.py create mode 100644 solutions/122. Best Time to Buy and Sell Stock II/122.cpp create mode 100644 solutions/122. Best Time to Buy and Sell Stock II/122.java create mode 100644 solutions/122. Best Time to Buy and Sell Stock II/122.py create mode 100644 solutions/1220. Count Vowels Permutation/1220.py create mode 100644 solutions/1221. Split a String in Balanced Strings/1221.cpp create mode 100644 solutions/1222. Queens That Can Attack the King/1222.cpp create mode 100644 solutions/1222. Queens That Can Attack the King/1222.java create mode 100644 solutions/1222. Queens That Can Attack the King/1222.py create mode 100644 solutions/1223. Dice Roll Simulation/1223.py create mode 100644 solutions/1224. Maximum Equal Frequency/1224.cpp create mode 100644 solutions/1224. Maximum Equal Frequency/1224.java create mode 100644 solutions/1224. Maximum Equal Frequency/1224.py create mode 100644 solutions/1225. Report Contiguous Dates/1225.sql create mode 100644 solutions/1226. The Dining Philosophers/1226.cpp create mode 100644 solutions/1227. Airplane Seat Assignment Probability/1227.cpp create mode 100644 solutions/1227. Airplane Seat Assignment Probability/1227.java create mode 100644 solutions/1227. Airplane Seat Assignment Probability/1227.py create mode 100644 solutions/1228. Missing Number In Arithmetic Progression/1228.cpp create mode 100644 solutions/1228. Missing Number In Arithmetic Progression/1228.java create mode 100644 solutions/1228. Missing Number In Arithmetic Progression/1228.py create mode 100644 solutions/1229. Meeting Scheduler/1229.cpp create mode 100644 solutions/1229. Meeting Scheduler/1229.java create mode 100644 solutions/1229. Meeting Scheduler/1229.py create mode 100644 solutions/123. Best Time to Buy and Sell Stock III/123.cpp create mode 100644 solutions/123. Best Time to Buy and Sell Stock III/123.java create mode 100644 solutions/123. Best Time to Buy and Sell Stock III/123.py create mode 100644 solutions/1230. Toss Strange Coins/1230-2.cpp create mode 100644 solutions/1230. Toss Strange Coins/1230-2.java create mode 100644 solutions/1230. Toss Strange Coins/1230-2.py create mode 100644 solutions/1230. Toss Strange Coins/1230.cpp create mode 100644 solutions/1230. Toss Strange Coins/1230.java create mode 100644 solutions/1230. Toss Strange Coins/1230.py create mode 100644 solutions/1231. Divide Chocolate/1231.cpp create mode 100644 solutions/1231. Divide Chocolate/1231.java create mode 100644 solutions/1231. Divide Chocolate/1231.py create mode 100644 solutions/1232. Check If It Is a Straight Line/1232.cpp create mode 100644 solutions/1232. Check If It Is a Straight Line/1232.java create mode 100644 solutions/1232. Check If It Is a Straight Line/1232.py create mode 100644 solutions/1233. Remove Sub-Folders from the Filesystem/1233.cpp create mode 100644 solutions/1233. Remove Sub-Folders from the Filesystem/1233.java create mode 100644 solutions/1233. Remove Sub-Folders from the Filesystem/1233.py create mode 100644 solutions/1234. Replace the Substring for Balanced String/1234.cpp create mode 100644 solutions/1234. Replace the Substring for Balanced String/1234.java create mode 100644 solutions/1234. Replace the Substring for Balanced String/1234.py create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235-2.cpp create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235-2.java create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235-2.py create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235-3.cpp create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235-3.java create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235-3.py create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235.cpp create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235.java create mode 100644 solutions/1235. Maximum Profit in Job Scheduling/1235.py create mode 100644 solutions/1236. Web Crawler/1236.cpp create mode 100644 solutions/1236. Web Crawler/1236.java create mode 100644 solutions/1236. Web Crawler/1236.py create mode 100644 solutions/1237. Find Positive Integer Solution for a Given Equation/1237.cpp create mode 100644 solutions/1237. Find Positive Integer Solution for a Given Equation/1237.java create mode 100644 solutions/1237. Find Positive Integer Solution for a Given Equation/1237.py create mode 100644 solutions/1238. Circular Permutation in Binary Representation/1238.cpp create mode 100644 solutions/1238. Circular Permutation in Binary Representation/1238.java create mode 100644 solutions/1238. Circular Permutation in Binary Representation/1238.py create mode 100644 solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-2.cpp create mode 100644 solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-3.cpp create mode 100644 solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239.cpp create mode 100644 solutions/124. Binary Tree Maximum Path Sum/124.cpp create mode 100644 solutions/124. Binary Tree Maximum Path Sum/124.java create mode 100644 solutions/124. Binary Tree Maximum Path Sum/124.py create mode 100644 solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.cpp create mode 100644 solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.java create mode 100644 solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.py create mode 100644 solutions/1241. Number of Comments per Post/1241.sql create mode 100644 solutions/1242. Web Crawler Multithreaded/1242.cpp create mode 100644 solutions/1243. Array Transformation/1243.cpp create mode 100644 solutions/1243. Array Transformation/1243.java create mode 100644 solutions/1243. Array Transformation/1243.py create mode 100644 solutions/1244. Design A Leaderboard/1244.cpp create mode 100644 solutions/1244. Design A Leaderboard/1244.java create mode 100644 solutions/1244. Design A Leaderboard/1244.py create mode 100644 solutions/1245. Tree Diameter/1245.cpp create mode 100644 solutions/1245. Tree Diameter/1245.java create mode 100644 solutions/1246. Palindrome Removal/1246.cpp create mode 100644 solutions/1246. Palindrome Removal/1246.java create mode 100644 solutions/1246. Palindrome Removal/1246.py create mode 100644 solutions/1247. Minimum Swaps to Make Strings Equal/1247.cpp create mode 100644 solutions/1247. Minimum Swaps to Make Strings Equal/1247.java create mode 100644 solutions/1247. Minimum Swaps to Make Strings Equal/1247.py create mode 100644 solutions/1248. Count Number of Nice Subarrays/1248.cpp create mode 100644 solutions/1248. Count Number of Nice Subarrays/1248.java create mode 100644 solutions/1248. Count Number of Nice Subarrays/1248.py create mode 100644 solutions/1249. Minimum Remove to Make Valid Parentheses/1249.cpp create mode 100644 solutions/1249. Minimum Remove to Make Valid Parentheses/1249.java create mode 100644 solutions/1249. Minimum Remove to Make Valid Parentheses/1249.py create mode 100644 solutions/125. Valid Palindrome/125.cpp create mode 100644 solutions/125. Valid Palindrome/125.java create mode 100644 solutions/125. Valid Palindrome/125.py create mode 100644 solutions/1250. Check If It Is a Good Array/1250.cpp create mode 100644 solutions/1251. Average Selling Price/1251.sql create mode 100644 solutions/1252. Cells with Odd Values in a Matrix/1252-2.cpp create mode 100644 solutions/1252. Cells with Odd Values in a Matrix/1252-2.java create mode 100644 solutions/1252. Cells with Odd Values in a Matrix/1252-2.py create mode 100644 solutions/1252. Cells with Odd Values in a Matrix/1252-3.cpp create mode 100644 solutions/1252. Cells with Odd Values in a Matrix/1252.cpp create mode 100644 solutions/1252. Cells with Odd Values in a Matrix/1252.java create mode 100644 solutions/1252. Cells with Odd Values in a Matrix/1252.py create mode 100644 solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.cpp create mode 100644 solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.java create mode 100644 solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.py create mode 100644 solutions/1254. Number of Closed Islands/1254.cpp create mode 100644 solutions/1254. Number of Closed Islands/1254.java create mode 100644 solutions/1254. Number of Closed Islands/1254.py create mode 100644 solutions/1255. Maximum Score Words Formed by Letters/1255.cpp create mode 100644 solutions/1255. Maximum Score Words Formed by Letters/1255.java create mode 100644 solutions/1255. Maximum Score Words Formed by Letters/1255.py create mode 100644 solutions/1256. Encode Number/1256.cpp create mode 100644 solutions/1256. Encode Number/1256.java create mode 100644 solutions/1256. Encode Number/1256.py create mode 100644 solutions/1257. Smallest Common Region/1257.cpp create mode 100644 solutions/1257. Smallest Common Region/1257.java create mode 100644 solutions/1258. Synonymous Sentences/1258.cpp create mode 100644 solutions/1258. Synonymous Sentences/1258.java create mode 100644 solutions/1258. Synonymous Sentences/1258.py create mode 100644 solutions/1259. Handshakes That Don't Cross/1259.cpp create mode 100644 solutions/1259. Handshakes That Don't Cross/1259.java create mode 100644 solutions/1259. Handshakes That Don't Cross/1259.py create mode 100644 solutions/126. Word Ladder II/126-2.cpp create mode 100644 solutions/126. Word Ladder II/126-3.cpp create mode 100644 solutions/126. Word Ladder II/126-4.cpp create mode 100644 solutions/126. Word Ladder II/126-5.cpp create mode 100644 solutions/126. Word Ladder II/126.cpp create mode 100644 solutions/126. Word Ladder II/126.java create mode 100644 solutions/126. Word Ladder II/126.py create mode 100644 solutions/126. Word Ladder II/127-2.py create mode 100644 solutions/1260. Shift 2D Grid/1260.cpp create mode 100644 solutions/1260. Shift 2D Grid/1260.java create mode 100644 solutions/1260. Shift 2D Grid/1260.py create mode 100644 solutions/1261. Find Elements in a Contaminated Binary Tree/1261.cpp create mode 100644 solutions/1261. Find Elements in a Contaminated Binary Tree/1261.java create mode 100644 solutions/1261. Find Elements in a Contaminated Binary Tree/1261.py create mode 100644 solutions/1262. Greatest Sum Divisible by Three/1262.cpp create mode 100644 solutions/1262. Greatest Sum Divisible by Three/1262.java create mode 100644 solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.cpp create mode 100644 solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.java create mode 100644 solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.py create mode 100644 solutions/1264. Page Recommendations/1264.sql create mode 100644 solutions/1265. Print Immutable Linked List in Reverse/1265-2.cpp create mode 100644 solutions/1265. Print Immutable Linked List in Reverse/1265.cpp create mode 100644 solutions/1266. Minimum Time Visiting All Points/1266.cpp create mode 100644 solutions/1266. Minimum Time Visiting All Points/1266.java create mode 100644 solutions/1266. Minimum Time Visiting All Points/1266.py create mode 100644 solutions/1267. Count Servers that Communicate/1267.cpp create mode 100644 solutions/1267. Count Servers that Communicate/1267.java create mode 100644 solutions/1267. Count Servers that Communicate/1267.py create mode 100644 solutions/1268. Search Suggestions System/1268.cpp create mode 100644 solutions/1268. Search Suggestions System/1268.java create mode 100644 solutions/1268. Search Suggestions System/1268.py create mode 100644 solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.cpp create mode 100644 solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.java create mode 100644 solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.py create mode 100644 solutions/127. Word Ladder/127.cpp create mode 100644 solutions/127. Word Ladder/127.java create mode 100644 solutions/127. Word Ladder/127.py create mode 100644 solutions/1270. All People Report to the Given Manager/1270.sql create mode 100644 solutions/1271. Hexspeak/1271.cpp create mode 100644 solutions/1271. Hexspeak/1271.java create mode 100644 solutions/1271. Hexspeak/1271.py create mode 100644 solutions/1272. Remove Interval/1272.cpp create mode 100644 solutions/1272. Remove Interval/1272.java create mode 100644 solutions/1272. Remove Interval/1272.py create mode 100644 solutions/1273. Delete Tree Nodes/1273.cpp create mode 100644 solutions/1273. Delete Tree Nodes/1273.java create mode 100644 solutions/1274. Number of Ships in a Rectangle/1274.cpp create mode 100644 solutions/1274. Number of Ships in a Rectangle/1274.java create mode 100644 solutions/1274. Number of Ships in a Rectangle/1274.py create mode 100644 solutions/1275. Find Winner on a Tic Tac Toe Game/1275.cpp create mode 100644 solutions/1275. Find Winner on a Tic Tac Toe Game/1275.java create mode 100644 solutions/1275. Find Winner on a Tic Tac Toe Game/1275.py create mode 100644 solutions/1276. Number of Burgers with No Waste of Ingredients/1276.cpp create mode 100644 solutions/1276. Number of Burgers with No Waste of Ingredients/1276.java create mode 100644 solutions/1276. Number of Burgers with No Waste of Ingredients/1276.py create mode 100644 solutions/1277. Count Square Submatrices with All Ones/1277.cpp create mode 100644 solutions/1277. Count Square Submatrices with All Ones/1277.java create mode 100644 solutions/1277. Count Square Submatrices with All Ones/1277.py create mode 100644 solutions/1278. Palindrome Partitioning III/1278-2.cpp create mode 100644 solutions/1278. Palindrome Partitioning III/1278-2.java create mode 100644 solutions/1278. Palindrome Partitioning III/1278.cpp create mode 100644 solutions/1278. Palindrome Partitioning III/1278.java create mode 100644 solutions/1279. Traffic Light Controlled Intersection/1279.cpp create mode 100644 solutions/1279. Traffic Light Controlled Intersection/1279.java create mode 100644 solutions/1279. Traffic Light Controlled Intersection/1279.py create mode 100644 solutions/128. Longest Consecutive Sequence/128.cpp create mode 100644 solutions/128. Longest Consecutive Sequence/128.java create mode 100644 solutions/128. Longest Consecutive Sequence/128.py create mode 100644 solutions/1280. Students and Examinations/1280.sql create mode 100644 solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.cpp create mode 100644 solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.java create mode 100644 solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.py create mode 100644 solutions/1282. Group the People Given the Group Size They Belong To/1282.cpp create mode 100644 solutions/1282. Group the People Given the Group Size They Belong To/1282.java create mode 100644 solutions/1282. Group the People Given the Group Size They Belong To/1282.py create mode 100644 solutions/1283. Find the Smallest Divisor Given a Threshold/1283.cpp create mode 100644 solutions/1283. Find the Smallest Divisor Given a Threshold/1283.java create mode 100644 solutions/1283. Find the Smallest Divisor Given a Threshold/1283.py create mode 100644 solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.cpp create mode 100644 solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.java create mode 100644 solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.py create mode 100644 solutions/1285. Find the Start and End Number of Continuous Ranges/1285.sql create mode 100644 solutions/1286. Iterator for Combination/1286.java create mode 100644 solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.cpp create mode 100644 solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.java create mode 100644 solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.py create mode 100644 solutions/1288. Remove Covered Intervals/1288.cpp create mode 100644 solutions/1288. Remove Covered Intervals/1288.java create mode 100644 solutions/1288. Remove Covered Intervals/1288.py create mode 100644 solutions/1289. Minimum Falling Path Sum II/1289.cpp create mode 100644 solutions/1289. Minimum Falling Path Sum II/1289.java create mode 100644 solutions/1289. Minimum Falling Path Sum II/1289.py create mode 100644 solutions/129. Sum Root to Leaf Numbers/129.cpp create mode 100644 solutions/129. Sum Root to Leaf Numbers/129.java create mode 100644 solutions/129. Sum Root to Leaf Numbers/129.py create mode 100644 solutions/1290. Convert Binary Number in a Linked List to Integer/1290.cpp create mode 100644 solutions/1290. Convert Binary Number in a Linked List to Integer/1290.java create mode 100644 solutions/1290. Convert Binary Number in a Linked List to Integer/1290.py create mode 100644 solutions/1291. Sequential Digits/1291.cpp create mode 100644 solutions/1291. Sequential Digits/1291.java create mode 100644 solutions/1291. Sequential Digits/1291.py create mode 100644 solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.cpp create mode 100644 solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.java create mode 100644 solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.py create mode 100644 solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.cpp create mode 100644 solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.java create mode 100644 solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.py create mode 100644 solutions/1294. Weather Type in Each Country/1294.sql create mode 100644 solutions/1295. Find Numbers with Even Number of Digits/1295.cpp create mode 100644 solutions/1295. Find Numbers with Even Number of Digits/1295.java create mode 100644 solutions/1295. Find Numbers with Even Number of Digits/1295.py create mode 100644 solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.cpp create mode 100644 solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.java create mode 100644 solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.py create mode 100644 solutions/1297. Maximum Number of Occurrences of a Substring/1297.cpp create mode 100644 solutions/1297. Maximum Number of Occurrences of a Substring/1297.java create mode 100644 solutions/1297. Maximum Number of Occurrences of a Substring/1297.py create mode 100644 solutions/1298. Maximum Candies You Can Get from Boxes/1298.cpp create mode 100644 solutions/1298. Maximum Candies You Can Get from Boxes/1298.java create mode 100644 solutions/1298. Maximum Candies You Can Get from Boxes/1298.py create mode 100644 solutions/1299. Replace Elements with Greatest Element on Right Side/1299.cpp create mode 100644 solutions/1299. Replace Elements with Greatest Element on Right Side/1299.java create mode 100644 solutions/1299. Replace Elements with Greatest Element on Right Side/1299.py create mode 100644 solutions/13. Roman to Integer/13.cpp create mode 100644 solutions/13. Roman to Integer/13.java create mode 100644 solutions/13. Roman to Integer/13.py create mode 100644 solutions/130. Surrounded Regions/130-2.cpp create mode 100644 solutions/130. Surrounded Regions/130-2.java create mode 100644 solutions/130. Surrounded Regions/130-2.py create mode 100644 solutions/130. Surrounded Regions/130.cpp create mode 100644 solutions/130. Surrounded Regions/130.java create mode 100644 solutions/130. Surrounded Regions/130.py create mode 100644 solutions/1300. Sum of Mutated Array Closest to Target/1300.cpp create mode 100644 solutions/1300. Sum of Mutated Array Closest to Target/1300.java create mode 100644 solutions/1300. Sum of Mutated Array Closest to Target/1300.py create mode 100644 solutions/1301. Number of Paths with Max Score/1301.cpp create mode 100644 solutions/1301. Number of Paths with Max Score/1301.java create mode 100644 solutions/1301. Number of Paths with Max Score/1301.py create mode 100644 solutions/1302. Deepest Leaves Sum/1302.cpp create mode 100644 solutions/1302. Deepest Leaves Sum/1302.java create mode 100644 solutions/1303. Find the Team Size/1303.sql create mode 100644 solutions/1304. Find N Unique Integers Sum up to Zero/1304.cpp create mode 100644 solutions/1304. Find N Unique Integers Sum up to Zero/1304.java create mode 100644 solutions/1304. Find N Unique Integers Sum up to Zero/1304.py create mode 100644 solutions/1305. All Elements in Two Binary Search Trees/1305.cpp create mode 100644 solutions/1305. All Elements in Two Binary Search Trees/1305.java create mode 100644 solutions/1306. Jump Game III/1306-2.cpp create mode 100644 solutions/1306. Jump Game III/1306-2.java create mode 100644 solutions/1306. Jump Game III/1306.cpp create mode 100644 solutions/1306. Jump Game III/1306.java create mode 100644 solutions/1307. Verbal Arithmetic Puzzle/1307.cpp create mode 100644 solutions/1307. Verbal Arithmetic Puzzle/1307.java create mode 100644 solutions/1307. Verbal Arithmetic Puzzle/1307.py create mode 100644 solutions/1308. Running Total for Different Genders/1308.sql create mode 100644 solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.cpp create mode 100644 solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.java create mode 100644 solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.py create mode 100644 solutions/131. Palindrome Partitioning/131.cpp create mode 100644 solutions/131. Palindrome Partitioning/131.java create mode 100644 solutions/131. Palindrome Partitioning/131.py create mode 100644 solutions/1310. XOR Queries of a Subarray/1310.cpp create mode 100644 solutions/1310. XOR Queries of a Subarray/1310.java create mode 100644 solutions/1310. XOR Queries of a Subarray/1310.py create mode 100644 solutions/1311. Get Watched Videos by Your Friends/1311.cpp create mode 100644 solutions/1311. Get Watched Videos by Your Friends/1311.java create mode 100644 solutions/1311. Get Watched Videos by Your Friends/1311.py create mode 100644 solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.cpp create mode 100644 solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.java create mode 100644 solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.py create mode 100644 solutions/1313. Decompress Run-Length Encoded List/1313.cpp create mode 100644 solutions/1313. Decompress Run-Length Encoded List/1313.java create mode 100644 solutions/1313. Decompress Run-Length Encoded List/1313.py create mode 100644 solutions/1314. Matrix Block Sum/1314.cpp create mode 100644 solutions/1314. Matrix Block Sum/1314.java create mode 100644 solutions/1314. Matrix Block Sum/1314.py create mode 100644 solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.cpp create mode 100644 solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.java create mode 100644 solutions/1316. Distinct Echo Substrings/1316.cpp create mode 100644 solutions/1316. Distinct Echo Substrings/1316.java create mode 100644 solutions/1316. Distinct Echo Substrings/1316.py create mode 100644 solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.cpp create mode 100644 solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.java create mode 100644 solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.py create mode 100644 solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.cpp create mode 100644 solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.java create mode 100644 solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.py create mode 100644 solutions/1319. Number of Operations to Make Network Connected/1319.cpp create mode 100644 solutions/1319. Number of Operations to Make Network Connected/1319.java create mode 100644 solutions/132. Palindrome Partitioning II/132.cpp create mode 100644 solutions/132. Palindrome Partitioning II/132.java create mode 100644 solutions/132. Palindrome Partitioning II/132.py create mode 100644 solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.cpp create mode 100644 solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.java create mode 100644 solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.py create mode 100644 solutions/1321. Restaurant Growth/1321.sql create mode 100644 solutions/1322. Ads Performance/1322.sql create mode 100644 solutions/1323. Maximum 69 Number/1323.cpp create mode 100644 solutions/1323. Maximum 69 Number/1323.java create mode 100644 solutions/1323. Maximum 69 Number/1323.py create mode 100644 solutions/1324. Print Words Vertically/1324.cpp create mode 100644 solutions/1324. Print Words Vertically/1324.java create mode 100644 solutions/1324. Print Words Vertically/1324.py create mode 100644 solutions/1325. Delete Leaves With a Given Value/1325.cpp create mode 100644 solutions/1325. Delete Leaves With a Given Value/1325.java create mode 100644 solutions/1325. Delete Leaves With a Given Value/1325.py create mode 100644 solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.cpp create mode 100644 solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.java create mode 100644 solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.py create mode 100644 solutions/1327. List the Products Ordered in a Period/1327.sql create mode 100644 solutions/1328. Break a Palindrome/1328.cpp create mode 100644 solutions/1328. Break a Palindrome/1328.java create mode 100644 solutions/1328. Break a Palindrome/1328.py create mode 100644 solutions/1329. Sort the Matrix Diagonally/1329.cpp create mode 100644 solutions/1329. Sort the Matrix Diagonally/1329.java create mode 100644 solutions/1329. Sort the Matrix Diagonally/1329.py create mode 100644 solutions/133. Clone Graph/133-2.cpp create mode 100644 solutions/133. Clone Graph/133-2.java create mode 100644 solutions/133. Clone Graph/133-2.py create mode 100644 solutions/133. Clone Graph/133.cpp create mode 100644 solutions/133. Clone Graph/133.java create mode 100644 solutions/133. Clone Graph/133.py create mode 100644 solutions/1330. Reverse Subarray To Maximize Array Value/1330.cpp create mode 100644 solutions/1330. Reverse Subarray To Maximize Array Value/1330.java create mode 100644 solutions/1330. Reverse Subarray To Maximize Array Value/1330.py create mode 100644 solutions/1331. Rank Transform of an Array/1331.cpp create mode 100644 solutions/1331. Rank Transform of an Array/1331.java create mode 100644 solutions/1331. Rank Transform of an Array/1331.py create mode 100644 solutions/1332. Remove Palindromic Subsequences/1332.cpp create mode 100644 solutions/1332. Remove Palindromic Subsequences/1332.java create mode 100644 solutions/1332. Remove Palindromic Subsequences/1332.py create mode 100644 solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.cpp create mode 100644 solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.java create mode 100644 solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.py create mode 100644 solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.cpp create mode 100644 solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.java create mode 100644 solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.py create mode 100644 solutions/1335. Minimum Difficulty of a Job Schedule/1335.cpp create mode 100644 solutions/1335. Minimum Difficulty of a Job Schedule/1335.java create mode 100644 solutions/1335. Minimum Difficulty of a Job Schedule/1335.py create mode 100644 solutions/1336. Number of Transactions per Visit/1336.sql create mode 100644 solutions/1337. The K Weakest Rows in a Matrix/1337.cpp create mode 100644 solutions/1337. The K Weakest Rows in a Matrix/1337.java create mode 100644 solutions/1337. The K Weakest Rows in a Matrix/1337.py create mode 100644 solutions/1338. Reduce Array Size to The Half/1338.cpp create mode 100644 solutions/1338. Reduce Array Size to The Half/1338.java create mode 100644 solutions/1338. Reduce Array Size to The Half/1338.py create mode 100644 solutions/1339. Maximum Product of Splitted Binary Tree/1339.cpp create mode 100644 solutions/1339. Maximum Product of Splitted Binary Tree/1339.java create mode 100644 solutions/134. Gas Station/134.cpp create mode 100644 solutions/134. Gas Station/134.java create mode 100644 solutions/134. Gas Station/134.py create mode 100644 solutions/1340. Jump Game V/1340.cpp create mode 100644 solutions/1340. Jump Game V/1340.java create mode 100644 solutions/1340. Jump Game V/1340.py create mode 100644 solutions/1341. Movie Rating/1341.sql create mode 100644 solutions/1342. Number of Steps to Reduce a Number to Zero/1342.cpp create mode 100644 solutions/1342. Number of Steps to Reduce a Number to Zero/1342.java create mode 100644 solutions/1342. Number of Steps to Reduce a Number to Zero/1342.py create mode 100644 solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.cpp create mode 100644 solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.java create mode 100644 solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.py create mode 100644 solutions/1344. Angle Between Hands of a Clock/1344.cpp create mode 100644 solutions/1344. Angle Between Hands of a Clock/1344.java create mode 100644 solutions/1344. Angle Between Hands of a Clock/1344.py create mode 100644 solutions/1345. Jump Game IV/1345.cpp create mode 100644 solutions/1345. Jump Game IV/1345.java create mode 100644 solutions/1345. Jump Game IV/1345.py create mode 100644 solutions/1346. Check If N and Its Double Exist/1346.cpp create mode 100644 solutions/1346. Check If N and Its Double Exist/1346.java create mode 100644 solutions/1346. Check If N and Its Double Exist/1346.py create mode 100644 solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.cpp create mode 100644 solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.java create mode 100644 solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.py create mode 100644 solutions/1348. Tweet Counts Per Frequency/1348.cpp create mode 100644 solutions/1348. Tweet Counts Per Frequency/1348.java create mode 100644 solutions/1348. Tweet Counts Per Frequency/1348.py create mode 100644 solutions/1349. Maximum Students Taking Exam/1349.cpp create mode 100644 solutions/1349. Maximum Students Taking Exam/1349.java create mode 100644 solutions/1349. Maximum Students Taking Exam/1349.py create mode 100644 solutions/135. Candy/135.cpp create mode 100644 solutions/135. Candy/135.java create mode 100644 solutions/135. Candy/135.py create mode 100644 solutions/1350. Students With Invalid Departments/1350.sql create mode 100644 solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.cpp create mode 100644 solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.java create mode 100644 solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.py create mode 100644 solutions/1352. Product of the Last K Numbers/1352.cpp create mode 100644 solutions/1352. Product of the Last K Numbers/1352.java create mode 100644 solutions/1352. Product of the Last K Numbers/1352.py create mode 100644 solutions/1353. Maximum Number of Events That Can Be Attended/1353.cpp create mode 100644 solutions/1353. Maximum Number of Events That Can Be Attended/1353.java create mode 100644 solutions/1353. Maximum Number of Events That Can Be Attended/1353.py create mode 100644 solutions/1354. Construct Target Array With Multiple Sums/1354.cpp create mode 100644 solutions/1354. Construct Target Array With Multiple Sums/1354.java create mode 100644 solutions/1354. Construct Target Array With Multiple Sums/1354.py create mode 100644 solutions/1355. Activity Participants/1355.sql create mode 100644 solutions/1356. Sort Integers by The Number of 1 Bits/1356.cpp create mode 100644 solutions/1356. Sort Integers by The Number of 1 Bits/1356.java create mode 100644 solutions/1357. Apply Discount Every n Orders/1357.cpp create mode 100644 solutions/1357. Apply Discount Every n Orders/1357.java create mode 100644 solutions/1357. Apply Discount Every n Orders/1357.py create mode 100644 solutions/1358. Number of Substrings Containing All Three Characters/1358-2.cpp create mode 100644 solutions/1358. Number of Substrings Containing All Three Characters/1358-2.java create mode 100644 solutions/1358. Number of Substrings Containing All Three Characters/1358-2.py create mode 100644 solutions/1358. Number of Substrings Containing All Three Characters/1358.cpp create mode 100644 solutions/1358. Number of Substrings Containing All Three Characters/1358.java create mode 100644 solutions/1358. Number of Substrings Containing All Three Characters/1358.py create mode 100644 solutions/1359. Count All Valid Pickup and Delivery Options/1359.cpp create mode 100644 solutions/1359. Count All Valid Pickup and Delivery Options/1359.java create mode 100644 solutions/1359. Count All Valid Pickup and Delivery Options/1359.py create mode 100644 solutions/136. Single Number/136.cpp create mode 100644 solutions/136. Single Number/136.java create mode 100644 solutions/136. Single Number/136.py create mode 100644 solutions/1360. Number of Days Between Two Dates/1360.cpp create mode 100644 solutions/1360. Number of Days Between Two Dates/1360.java create mode 100644 solutions/1360. Number of Days Between Two Dates/1360.py create mode 100644 solutions/1361. Validate Binary Tree Nodes/1361.cpp create mode 100644 solutions/1361. Validate Binary Tree Nodes/1361.java create mode 100644 solutions/1362. Closest Divisors/1362.cpp create mode 100644 solutions/1362. Closest Divisors/1362.java create mode 100644 solutions/1362. Closest Divisors/1362.py create mode 100644 solutions/1363. Largest Multiple of Three/1363.cpp create mode 100644 solutions/1363. Largest Multiple of Three/1363.java create mode 100644 solutions/1363. Largest Multiple of Three/1363.py create mode 100644 solutions/1364. Number of Trusted Contacts of a Customer/1364.sql create mode 100644 solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.cpp create mode 100644 solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.java create mode 100644 solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.py create mode 100644 solutions/1366. Rank Teams by Votes/1366.cpp create mode 100644 solutions/1366. Rank Teams by Votes/1366.java create mode 100644 solutions/1366. Rank Teams by Votes/1366.py create mode 100644 solutions/1367. Linked List in Binary Tree/1367.cpp create mode 100644 solutions/1367. Linked List in Binary Tree/1367.java create mode 100644 solutions/1367. Linked List in Binary Tree/1367.py create mode 100644 solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.cpp create mode 100644 solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.java create mode 100644 solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.py create mode 100644 solutions/1369. Get the Second Most Recent Activity/1369.sql create mode 100644 solutions/137. Single Number II/137-2.cpp create mode 100644 solutions/137. Single Number II/137-2.java create mode 100644 solutions/137. Single Number II/137-2.py create mode 100644 solutions/137. Single Number II/137.cpp create mode 100644 solutions/137. Single Number II/137.java create mode 100644 solutions/137. Single Number II/137.py create mode 100644 solutions/1370. Increasing Decreasing String/1370.cpp create mode 100644 solutions/1370. Increasing Decreasing String/1370.java create mode 100644 solutions/1370. Increasing Decreasing String/1370.py create mode 100644 solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.cpp create mode 100644 solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.java create mode 100644 solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.py create mode 100644 solutions/1372. Longest ZigZag Path in a Binary Tree/1372.cpp create mode 100644 solutions/1372. Longest ZigZag Path in a Binary Tree/1372.java create mode 100644 solutions/1372. Longest ZigZag Path in a Binary Tree/1372.py create mode 100644 solutions/1373. Maximum Sum BST in Binary Tree/1373.cpp create mode 100644 solutions/1373. Maximum Sum BST in Binary Tree/1373.java create mode 100644 solutions/1373. Maximum Sum BST in Binary Tree/1373.py create mode 100644 solutions/1374. Generate a String With Characters That Have Odd Counts/1374.cpp create mode 100644 solutions/1374. Generate a String With Characters That Have Odd Counts/1374.java create mode 100644 solutions/1374. Generate a String With Characters That Have Odd Counts/1374.py create mode 100644 solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.cpp create mode 100644 solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.java create mode 100644 solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.py create mode 100644 solutions/1376. Time Needed to Inform All Employees/1376.cpp create mode 100644 solutions/1376. Time Needed to Inform All Employees/1376.java create mode 100644 solutions/1377. Frog Position After T Seconds/1377.cpp create mode 100644 solutions/1377. Frog Position After T Seconds/1377.java create mode 100644 solutions/1377. Frog Position After T Seconds/1377.py create mode 100644 solutions/1378. Replace Employee ID With The Unique Identifier/1378.sql create mode 100644 solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.cpp create mode 100644 solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.java create mode 100644 solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.py create mode 100644 solutions/138. Copy List with Random Pointer/138.cpp create mode 100644 solutions/138. Copy List with Random Pointer/138.java create mode 100644 solutions/138. Copy List with Random Pointer/138.py create mode 100644 solutions/1380. Lucky Numbers in a Matrix/1380.cpp create mode 100644 solutions/1380. Lucky Numbers in a Matrix/1380.java create mode 100644 solutions/1380. Lucky Numbers in a Matrix/1380.py create mode 100644 solutions/1381. Design a Stack With Increment Operation/1381.cpp create mode 100644 solutions/1381. Design a Stack With Increment Operation/1381.java create mode 100644 solutions/1381. Design a Stack With Increment Operation/1381.py create mode 100644 solutions/1382. Balance a Binary Search Tree/1382.cpp create mode 100644 solutions/1382. Balance a Binary Search Tree/1382.java create mode 100644 solutions/1382. Balance a Binary Search Tree/1382.py create mode 100644 solutions/1383. Maximum Performance of a Team/1383.cpp create mode 100644 solutions/1383. Maximum Performance of a Team/1383.java create mode 100644 solutions/1383. Maximum Performance of a Team/1383.py create mode 100644 solutions/1384. Total Sales Amount by Year/1384.sql create mode 100644 solutions/1385. Find the Distance Value Between Two Arrays/1385-2.cpp create mode 100644 solutions/1385. Find the Distance Value Between Two Arrays/1385.cpp create mode 100644 solutions/1385. Find the Distance Value Between Two Arrays/1385.java create mode 100644 solutions/1385. Find the Distance Value Between Two Arrays/1385.py create mode 100644 solutions/1386. Cinema Seat Allocation/1386.cpp create mode 100644 solutions/1386. Cinema Seat Allocation/1386.java create mode 100644 solutions/1386. Cinema Seat Allocation/1386.py create mode 100644 solutions/1387. Sort Integers by The Power Value/1387.cpp create mode 100644 solutions/1387. Sort Integers by The Power Value/1387.java create mode 100644 solutions/1387. Sort Integers by The Power Value/1387.py create mode 100644 solutions/1388. Pizza With 3n Slices/1388.py create mode 100644 solutions/1389. Create Target Array in the Given Order/1389.cpp create mode 100644 solutions/1389. Create Target Array in the Given Order/1389.java create mode 100644 solutions/1389. Create Target Array in the Given Order/1389.py create mode 100644 solutions/139. Word Break/139-2.cpp create mode 100644 solutions/139. Word Break/139-2.java create mode 100644 solutions/139. Word Break/139-2.py create mode 100644 solutions/139. Word Break/139-3.cpp create mode 100644 solutions/139. Word Break/139-3.java create mode 100644 solutions/139. Word Break/139-3.py create mode 100644 solutions/139. Word Break/139-4.cpp create mode 100644 solutions/139. Word Break/139-4.java create mode 100644 solutions/139. Word Break/139-4.py create mode 100644 solutions/139. Word Break/139.cpp create mode 100644 solutions/139. Word Break/139.java create mode 100644 solutions/139. Word Break/139.py create mode 100644 solutions/1390. Four Divisors/1390.cpp create mode 100644 solutions/1390. Four Divisors/1390.java create mode 100644 solutions/1390. Four Divisors/1390.py create mode 100644 solutions/1391. Check if There is a Valid Path in a Grid/1391.cpp create mode 100644 solutions/1391. Check if There is a Valid Path in a Grid/1391.java create mode 100644 solutions/1392. Longest Happy Prefix/1392.cpp create mode 100644 solutions/1392. Longest Happy Prefix/1392.java create mode 100644 solutions/1392. Longest Happy Prefix/1392.py create mode 100644 "solutions/1393. Capital Gain\357\274\217Loss/1393.sql" create mode 100644 solutions/1394. Find Lucky Integer in an Array/1394.cpp create mode 100644 solutions/1394. Find Lucky Integer in an Array/1394.java create mode 100644 solutions/1394. Find Lucky Integer in an Array/1394.py create mode 100644 solutions/1395. Count Number of Teams/1395.cpp create mode 100644 solutions/1395. Count Number of Teams/1395.java create mode 100644 solutions/1395. Count Number of Teams/1395.py create mode 100644 solutions/1396. Design Underground System/1396.cpp create mode 100644 solutions/1396. Design Underground System/1396.java create mode 100644 solutions/1396. Design Underground System/1396.py create mode 100644 solutions/1397. Find All Good Strings/1397.cpp create mode 100644 solutions/1397. Find All Good Strings/1397.java create mode 100644 solutions/1397. Find All Good Strings/1397.py create mode 100644 solutions/1398. Customers Who Bought Products A and B but Not C/1398.sql create mode 100644 solutions/1399. Count Largest Group/1399.cpp create mode 100644 solutions/1399. Count Largest Group/1399.java create mode 100644 solutions/1399. Count Largest Group/1399.py create mode 100644 solutions/14. Longest Common Prefix/14.cpp create mode 100644 solutions/14. Longest Common Prefix/14.java create mode 100644 solutions/14. Longest Common Prefix/14.py create mode 100644 solutions/140. Word Break II/140.cpp create mode 100644 solutions/140. Word Break II/140.java create mode 100644 solutions/140. Word Break II/140.py create mode 100644 solutions/1400. Construct K Palindrome Strings/1400.cpp create mode 100644 solutions/1400. Construct K Palindrome Strings/1400.java create mode 100644 solutions/1400. Construct K Palindrome Strings/1400.py create mode 100644 solutions/1401. Circle and Rectangle Overlapping/1401.cpp create mode 100644 solutions/1402. Reducing Dishes/1402.cpp create mode 100644 solutions/1402. Reducing Dishes/1402.java create mode 100644 solutions/1402. Reducing Dishes/1402.py create mode 100644 solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.cpp create mode 100644 solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.java create mode 100644 solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.py create mode 100644 solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.cpp create mode 100644 solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.java create mode 100644 solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.py create mode 100644 solutions/1405. Longest Happy String/1405.cpp create mode 100644 solutions/1406. Stone Game III/1406-2.cpp create mode 100644 solutions/1406. Stone Game III/1406-2.java create mode 100644 solutions/1406. Stone Game III/1406-2.py create mode 100644 solutions/1406. Stone Game III/1406.cpp create mode 100644 solutions/1406. Stone Game III/1406.java create mode 100644 solutions/1406. Stone Game III/1406.py create mode 100644 solutions/1407. Top Travellers/1407.sql create mode 100644 solutions/1408. String Matching in an Array/1408-2.cpp create mode 100644 solutions/1408. String Matching in an Array/1408-2.java create mode 100644 solutions/1408. String Matching in an Array/1408-2.py create mode 100644 solutions/1408. String Matching in an Array/1408-3.cpp create mode 100644 solutions/1408. String Matching in an Array/1408-3.java create mode 100644 solutions/1408. String Matching in an Array/1408-3.py create mode 100644 solutions/1408. String Matching in an Array/1408.cpp create mode 100644 solutions/1408. String Matching in an Array/1408.java create mode 100644 solutions/1408. String Matching in an Array/1408.py create mode 100644 solutions/1409. Queries on a Permutation With Key/1409.cpp create mode 100644 solutions/1409. Queries on a Permutation With Key/1409.java create mode 100644 solutions/1409. Queries on a Permutation With Key/1409.py create mode 100644 solutions/141. Linked List Cycle/141.cpp create mode 100644 solutions/141. Linked List Cycle/141.java create mode 100644 solutions/141. Linked List Cycle/141.py create mode 100644 solutions/1410. HTML Entity Parser/1410.cpp create mode 100644 solutions/1410. HTML Entity Parser/1410.java create mode 100644 solutions/1410. HTML Entity Parser/1410.py create mode 100644 "solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.cpp" create mode 100644 "solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.java" create mode 100644 solutions/1412. Find the Quiet Students in All Exams/1412.sql create mode 100644 solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.cpp create mode 100644 solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.java create mode 100644 solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.py create mode 100644 solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.cpp create mode 100644 solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.java create mode 100644 solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.py create mode 100644 solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.cpp create mode 100644 solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.java create mode 100644 solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.py create mode 100644 solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.cpp create mode 100644 solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.java create mode 100644 solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.py create mode 100644 solutions/1416. Restore The Array/1416-2.cpp create mode 100644 solutions/1416. Restore The Array/1416.cpp create mode 100644 solutions/1417. Reformat The String/1417-2.cpp create mode 100644 solutions/1417. Reformat The String/1417.cpp create mode 100644 solutions/1417. Reformat The String/1417.java create mode 100644 solutions/1417. Reformat The String/1417.py create mode 100644 solutions/1418. Display Table of Food Orders in a Restaurant/1418.cpp create mode 100644 solutions/1419. Minimum Number of Frogs Croaking/1419.cpp create mode 100644 solutions/1419. Minimum Number of Frogs Croaking/1419.java create mode 100644 solutions/1419. Minimum Number of Frogs Croaking/1419.py create mode 100644 solutions/142. Linked List Cycle II/142.cpp create mode 100644 solutions/142. Linked List Cycle II/142.java create mode 100644 solutions/142. Linked List Cycle II/142.py create mode 100644 solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.cpp create mode 100644 solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.java create mode 100644 solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.py create mode 100644 solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.cpp create mode 100644 solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.java create mode 100644 solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.py create mode 100644 solutions/1421. NPV Queries/1421.sql create mode 100644 solutions/1422. Maximum Score After Splitting a String/1422.cpp create mode 100644 solutions/1422. Maximum Score After Splitting a String/1422.java create mode 100644 solutions/1422. Maximum Score After Splitting a String/1422.py create mode 100644 solutions/1423. Maximum Points You Can Obtain from Cards/1423.cpp create mode 100644 solutions/1423. Maximum Points You Can Obtain from Cards/1423.java create mode 100644 solutions/1423. Maximum Points You Can Obtain from Cards/1423.py create mode 100644 solutions/1424. Diagonal Traverse II/1424.cpp create mode 100644 solutions/1424. Diagonal Traverse II/1424.java create mode 100644 solutions/1425. Constrained Subsequence Sum/1425.cpp create mode 100644 solutions/1425. Constrained Subsequence Sum/1425.java create mode 100644 solutions/1425. Constrained Subsequence Sum/1425.py create mode 100644 solutions/1426. Counting Elements/1426.cpp create mode 100644 solutions/1426. Counting Elements/1426.java create mode 100644 solutions/1426. Counting Elements/1426.py create mode 100644 solutions/1427. Perform String Shifts/1427.cpp create mode 100644 solutions/1427. Perform String Shifts/1427.java create mode 100644 solutions/1427. Perform String Shifts/1427.py create mode 100644 solutions/1428. Leftmost Column with at Least a One/1428-2.cpp create mode 100644 solutions/1428. Leftmost Column with at Least a One/1428-2.java create mode 100644 solutions/1428. Leftmost Column with at Least a One/1428-2.py create mode 100644 solutions/1428. Leftmost Column with at Least a One/1428.cpp create mode 100644 solutions/1428. Leftmost Column with at Least a One/1428.java create mode 100644 solutions/1428. Leftmost Column with at Least a One/1428.py create mode 100644 solutions/1429. First Unique Number/1429.cpp create mode 100644 solutions/1429. First Unique Number/1429.java create mode 100644 solutions/1429. First Unique Number/1429.py create mode 100644 solutions/143. Reorder List/143.cpp create mode 100644 solutions/143. Reorder List/143.java create mode 100644 solutions/143. Reorder List/143.py create mode 100644 solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.cpp create mode 100644 solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.java create mode 100644 solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.py create mode 100644 solutions/1431. Kids With the Greatest Number of Candies/1431.cpp create mode 100644 solutions/1431. Kids With the Greatest Number of Candies/1431.java create mode 100644 solutions/1431. Kids With the Greatest Number of Candies/1431.py create mode 100644 solutions/1432. Max Difference You Can Get From Changing an Integer/1432.cpp create mode 100644 solutions/1432. Max Difference You Can Get From Changing an Integer/1432.java create mode 100644 solutions/1432. Max Difference You Can Get From Changing an Integer/1432.py create mode 100644 solutions/1433. Check If a String Can Break Another String/1433-2.cpp create mode 100644 solutions/1433. Check If a String Can Break Another String/1433-2.java create mode 100644 solutions/1433. Check If a String Can Break Another String/1433-2.py create mode 100644 solutions/1433. Check If a String Can Break Another String/1433.cpp create mode 100644 solutions/1433. Check If a String Can Break Another String/1433.java create mode 100644 solutions/1433. Check If a String Can Break Another String/1433.py create mode 100644 solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.cpp create mode 100644 solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.java create mode 100644 solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.cpp create mode 100644 solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.java create mode 100644 solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.cpp create mode 100644 solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.java create mode 100644 solutions/1435. Create a Session Bar Chart/1435.sql create mode 100644 solutions/1436. Destination City/1436.py create mode 100644 solutions/1437. Check If All 1's Are at Least Length K Places Away/1437.py create mode 100644 solutions/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/1438.cpp create mode 100644 solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.cpp create mode 100644 solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.java create mode 100644 solutions/144. Binary Tree Preorder Traversal/144-2.cpp create mode 100644 solutions/144. Binary Tree Preorder Traversal/144-2.java create mode 100644 solutions/144. Binary Tree Preorder Traversal/144-2.py create mode 100644 solutions/144. Binary Tree Preorder Traversal/144.cpp create mode 100644 solutions/144. Binary Tree Preorder Traversal/144.java create mode 100644 solutions/144. Binary Tree Preorder Traversal/144.py create mode 100644 solutions/1440. Evaluate Boolean Expression/1440.sql create mode 100644 solutions/1441. Build an Array With Stack Operations/1441.py create mode 100644 solutions/1442. Count Triplets That Can Form Two Arrays of Equal XOR/1442.py create mode 100644 solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.cpp create mode 100644 solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.java create mode 100644 solutions/1444. Number of Ways of Cutting a Pizza/1444.cpp create mode 100644 solutions/1444. Number of Ways of Cutting a Pizza/1444.java create mode 100644 solutions/1444. Number of Ways of Cutting a Pizza/1444.py create mode 100644 solutions/1445. Apples & Oranges/1445.sql create mode 100644 solutions/1446. Consecutive Characters/1446.cpp create mode 100644 solutions/1446. Consecutive Characters/1446.java create mode 100644 solutions/1446. Consecutive Characters/1446.py create mode 100644 solutions/1447. Simplified Fractions/1447.cpp create mode 100644 solutions/1447. Simplified Fractions/1447.java create mode 100644 solutions/1447. Simplified Fractions/1447.py create mode 100644 solutions/1448. Count Good Nodes in Binary Tree/1448.cpp create mode 100644 solutions/1448. Count Good Nodes in Binary Tree/1448.java create mode 100644 solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.cpp create mode 100644 solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.java create mode 100644 solutions/145. Binary Tree Postorder Traversal/145-2.cpp create mode 100644 solutions/145. Binary Tree Postorder Traversal/145-2.java create mode 100644 solutions/145. Binary Tree Postorder Traversal/145-2.py create mode 100644 solutions/145. Binary Tree Postorder Traversal/145.cpp create mode 100644 solutions/145. Binary Tree Postorder Traversal/145.java create mode 100644 solutions/145. Binary Tree Postorder Traversal/145.py create mode 100644 solutions/1450. Number of Students Doing Homework at a Given Time/1450.cpp create mode 100644 solutions/1451. Rearrange Words in a Sentence/1451.py create mode 100644 solutions/1452. People Whose List of Favorite Companies Is Not a Subset of Another List/1452.py create mode 100644 solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.cpp create mode 100644 solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.java create mode 100644 solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.py create mode 100644 solutions/1454. Active Users/1454.sql create mode 100644 solutions/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence/1455.py create mode 100644 solutions/1456. Maximum Number of Vowels in a Substring of Given Length/1456.py create mode 100644 solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.cpp create mode 100644 solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.java create mode 100644 solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.py create mode 100644 solutions/1458. Max Dot Product of Two Subsequences/1458.cpp create mode 100644 solutions/1458. Max Dot Product of Two Subsequences/1458.java create mode 100644 solutions/1458. Max Dot Product of Two Subsequences/1458.py create mode 100644 solutions/1459. Rectangles Area/1459.sql create mode 100644 solutions/146. LRU Cache/146-2.cpp create mode 100644 solutions/146. LRU Cache/146.cpp create mode 100644 solutions/146. LRU Cache/146.java create mode 100644 solutions/146. LRU Cache/146.py create mode 100644 solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.cpp create mode 100644 solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.java create mode 100644 solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.py create mode 100644 solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.cpp create mode 100644 solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.java create mode 100644 solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.py create mode 100644 solutions/1462. Course Schedule IV/1462-2.cpp create mode 100644 solutions/1462. Course Schedule IV/1462-2.java create mode 100644 solutions/1462. Course Schedule IV/1462-2.py create mode 100644 solutions/1462. Course Schedule IV/1462.cpp create mode 100644 solutions/1462. Course Schedule IV/1462.java create mode 100644 solutions/1462. Course Schedule IV/1462.py create mode 100644 solutions/1463. Cherry Pickup II/1463-2.cpp create mode 100644 solutions/1463. Cherry Pickup II/1463-2.java create mode 100644 solutions/1463. Cherry Pickup II/1463.cpp create mode 100644 solutions/1463. Cherry Pickup II/1463.java create mode 100644 solutions/1464. Maximum Product of Two Elements in an Array/1464-2.cpp create mode 100644 solutions/1464. Maximum Product of Two Elements in an Array/1464.cpp create mode 100644 solutions/1464. Maximum Product of Two Elements in an Array/1464.java create mode 100644 solutions/1464. Maximum Product of Two Elements in an Array/1464.py create mode 100644 solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.cpp create mode 100644 solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.java create mode 100644 solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.py create mode 100644 solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.cpp create mode 100644 solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.java create mode 100644 solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.cpp create mode 100644 solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.java create mode 100644 solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.py create mode 100644 solutions/1468. Calculate Salaries/1468.sql create mode 100644 solutions/1469. Find All The Lonely Nodes/1469.cpp create mode 100644 solutions/1469. Find All The Lonely Nodes/1469.java create mode 100644 solutions/147. Insertion Sort List/147.cpp create mode 100644 solutions/147. Insertion Sort List/147.java create mode 100644 solutions/147. Insertion Sort List/147.py create mode 100644 solutions/1470. Shuffle the Array/1470.cpp create mode 100644 solutions/1470. Shuffle the Array/1470.java create mode 100644 solutions/1470. Shuffle the Array/1470.py create mode 100644 solutions/1471. The k Strongest Values in an Array/1471-2.cpp create mode 100644 solutions/1471. The k Strongest Values in an Array/1471.cpp create mode 100644 solutions/1471. The k Strongest Values in an Array/1471.java create mode 100644 solutions/1471. The k Strongest Values in an Array/1471.py create mode 100644 solutions/1472. Design Browser History/1472-2.cpp create mode 100644 solutions/1472. Design Browser History/1472-2.java create mode 100644 solutions/1472. Design Browser History/1472-2.py create mode 100644 solutions/1472. Design Browser History/1472-3.cpp create mode 100644 solutions/1472. Design Browser History/1472-3.java create mode 100644 solutions/1472. Design Browser History/1472-3.py create mode 100644 solutions/1472. Design Browser History/1472.cpp create mode 100644 solutions/1472. Design Browser History/1472.java create mode 100644 solutions/1472. Design Browser History/1472.py create mode 100644 solutions/1473. Paint House III/1473.cpp create mode 100644 solutions/1473. Paint House III/1473.java create mode 100644 solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.cpp create mode 100644 solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.java create mode 100644 solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.py create mode 100644 solutions/1475. Final Prices With a Special Discount in a Shop/1475.cpp create mode 100644 solutions/1475. Final Prices With a Special Discount in a Shop/1475.java create mode 100644 solutions/1475. Final Prices With a Special Discount in a Shop/1475.py create mode 100644 solutions/1476. Subrectangle Queries/1476.cpp create mode 100644 solutions/1476. Subrectangle Queries/1476.java create mode 100644 solutions/1476. Subrectangle Queries/1476.py create mode 100644 solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.cpp create mode 100644 solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.java create mode 100644 solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.cpp create mode 100644 solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.java create mode 100644 solutions/1478. Allocate Mailboxes/1478.cpp create mode 100644 solutions/1478. Allocate Mailboxes/1478.java create mode 100644 solutions/1479. Sales by Day of the Week/1479.sql create mode 100644 solutions/148. Sort List/148.cpp create mode 100644 solutions/148. Sort List/148.java create mode 100644 solutions/148. Sort List/148.py create mode 100644 solutions/1480. Running Sum of 1d Array/1480.cpp create mode 100644 solutions/1480. Running Sum of 1d Array/1480.java create mode 100644 solutions/1480. Running Sum of 1d Array/1480.py create mode 100644 solutions/1481. Least Number of Unique Integers after K Removals/1481.cpp create mode 100644 solutions/1481. Least Number of Unique Integers after K Removals/1481.java create mode 100644 solutions/1481. Least Number of Unique Integers after K Removals/1481.py create mode 100644 solutions/1482. Minimum Number of Days to Make m Bouquets/1482.cpp create mode 100644 solutions/1482. Minimum Number of Days to Make m Bouquets/1482.java create mode 100644 solutions/1482. Minimum Number of Days to Make m Bouquets/1482.py create mode 100644 solutions/1483. Kth Ancestor of a Tree Node/1483.cpp create mode 100644 solutions/1483. Kth Ancestor of a Tree Node/1483.java create mode 100644 solutions/1483. Kth Ancestor of a Tree Node/1483.py create mode 100644 solutions/1484. Group Sold Products By The Date/1484.sql create mode 100644 solutions/1485. Clone Binary Tree With Random Pointer/1485.cpp create mode 100644 solutions/1485. Clone Binary Tree With Random Pointer/1485.java create mode 100644 solutions/1486. XOR Operation in an Array/1486.cpp create mode 100644 solutions/1486. XOR Operation in an Array/1486.java create mode 100644 solutions/1486. XOR Operation in an Array/1486.py create mode 100644 solutions/1487. Making File Names Unique/1487.cpp create mode 100644 solutions/1487. Making File Names Unique/1487.java create mode 100644 solutions/1487. Making File Names Unique/1487.py create mode 100644 solutions/1488. Avoid Flood in The City/1488.cpp create mode 100644 solutions/1488. Avoid Flood in The City/1488.java create mode 100644 solutions/1488. Avoid Flood in The City/1488.py create mode 100644 solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.cpp create mode 100644 solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.java create mode 100644 solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.py create mode 100644 solutions/149. Max Points on a Line/149.cpp create mode 100644 solutions/149. Max Points on a Line/149.java create mode 100644 solutions/149. Max Points on a Line/149.py create mode 100644 solutions/1490. Clone N-ary Tree/1490.cpp create mode 100644 solutions/1490. Clone N-ary Tree/1490.java create mode 100644 solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.cpp create mode 100644 solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.java create mode 100644 solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.py create mode 100644 solutions/1492. The kth Factor of n/1492.cpp create mode 100644 solutions/1492. The kth Factor of n/1492.java create mode 100644 solutions/1492. The kth Factor of n/1492.py create mode 100644 solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.cpp create mode 100644 solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.java create mode 100644 solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.py create mode 100644 solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.cpp create mode 100644 solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.java create mode 100644 solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.py create mode 100644 solutions/1494. Parallel Courses II/1494.cpp create mode 100644 solutions/1494. Parallel Courses II/1494.java create mode 100644 solutions/1494. Parallel Courses II/1494.py create mode 100644 solutions/1495. Friendly Movies Streamed Last Month/1495.sql create mode 100644 solutions/1496. Path Crossing/1496.cpp create mode 100644 solutions/1497. Check If Array Pairs Are Divisible by k/1497.cpp create mode 100644 solutions/1497. Check If Array Pairs Are Divisible by k/1497.java create mode 100644 solutions/1497. Check If Array Pairs Are Divisible by k/1497.py create mode 100644 solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.cpp create mode 100644 solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.java create mode 100644 solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.py create mode 100644 solutions/1499. Max Value of Equation/1499-2.cpp create mode 100644 solutions/1499. Max Value of Equation/1499-2.java create mode 100644 solutions/1499. Max Value of Equation/1499-2.py create mode 100644 solutions/1499. Max Value of Equation/1499.cpp create mode 100644 solutions/1499. Max Value of Equation/1499.java create mode 100644 solutions/1499. Max Value of Equation/1499.py create mode 100644 solutions/15. 3Sum/15.cpp create mode 100644 solutions/15. 3Sum/15.java create mode 100644 solutions/15. 3Sum/15.py create mode 100644 solutions/150. Evaluate Reverse Polish Notation/150.cpp create mode 100644 solutions/150. Evaluate Reverse Polish Notation/150.java create mode 100644 solutions/150. Evaluate Reverse Polish Notation/150.py create mode 100644 solutions/1500. Design a File Sharing System/1500.cpp create mode 100644 solutions/1500. Design a File Sharing System/1500.java create mode 100644 solutions/1500. Design a File Sharing System/1500.py create mode 100644 solutions/1501. Countries You Can Safely Invest In/1501.sql create mode 100644 solutions/1502. Can Make Arithmetic Progression From Sequence/1502-2.cpp create mode 100644 solutions/1502. Can Make Arithmetic Progression From Sequence/1502.cpp create mode 100644 solutions/1503. Last Moment Before All Ants Fall Out of a Plank/1503.cpp create mode 100644 solutions/1504. Count Submatrices With All Ones/1504-2.cpp create mode 100644 solutions/1504. Count Submatrices With All Ones/1504-2.java create mode 100644 solutions/1504. Count Submatrices With All Ones/1504.cpp create mode 100644 solutions/1504. Count Submatrices With All Ones/1504.java create mode 100644 solutions/1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits/1505.cpp create mode 100644 solutions/1506. Find Root of N-Ary Tree/1506.cpp create mode 100644 solutions/1506. Find Root of N-Ary Tree/1506.java create mode 100644 solutions/1506. Find Root of N-Ary Tree/1506.py create mode 100644 solutions/1507. Reformat Date/1507.cpp create mode 100644 solutions/1507. Reformat Date/1507.java create mode 100644 solutions/1507. Reformat Date/1507.py create mode 100644 solutions/1508. Range Sum of Sorted Subarray Sums/1508.cpp create mode 100644 solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.cpp create mode 100644 solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.java create mode 100644 solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.py create mode 100644 solutions/151. Reverse Words in a String/151.cpp create mode 100644 solutions/151. Reverse Words in a String/151.java create mode 100644 solutions/151. Reverse Words in a String/151.py create mode 100644 solutions/1510. Stone Game IV/1510.cpp create mode 100644 solutions/1510. Stone Game IV/1510.java create mode 100644 solutions/1511. Customer Order Frequency/1511.sql create mode 100644 solutions/1512. Number of Good Pairs/1512.cpp create mode 100644 solutions/1513. Number of Substrings With Only 1s/1513.cpp create mode 100644 solutions/1514. Path with Maximum Probability/1514.cpp create mode 100644 solutions/1514. Path with Maximum Probability/1514.java create mode 100644 solutions/1514. Path with Maximum Probability/1514.py create mode 100644 solutions/1515. Best Position for a Service Centre/1515.cpp create mode 100644 solutions/1515. Best Position for a Service Centre/1515.java create mode 100644 solutions/1515. Best Position for a Service Centre/1515.py create mode 100644 solutions/1516. Move Sub-Tree of N-Ary Tree/1516.cpp create mode 100644 solutions/1516. Move Sub-Tree of N-Ary Tree/1516.py create mode 100644 solutions/1517. Find Users With Valid E-Mails/1517.sql create mode 100644 solutions/1518. Water Bottles/1518-2.cpp create mode 100644 solutions/1518. Water Bottles/1518.cpp create mode 100644 solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.cpp create mode 100644 solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.java create mode 100644 solutions/152. Maximum Product Subarray/152.cpp create mode 100644 solutions/152. Maximum Product Subarray/152.java create mode 100644 solutions/152. Maximum Product Subarray/152.py create mode 100644 solutions/1520. Maximum Number of Non-Overlapping Substrings/1520.cpp create mode 100644 solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.cpp create mode 100644 solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.java create mode 100644 solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.py create mode 100644 solutions/1522. Diameter of N-Ary Tree/1522.cpp create mode 100644 solutions/1522. Diameter of N-Ary Tree/1522.java create mode 100644 solutions/1522. Diameter of N-Ary Tree/1522.py create mode 100644 solutions/1523. Count Odd Numbers in an Interval Range/1523.cpp create mode 100644 solutions/1524. Number of Sub-arrays With Odd Sum/1524-2.cpp create mode 100644 solutions/1524. Number of Sub-arrays With Odd Sum/1524.cpp create mode 100644 solutions/1525. Number of Good Ways to Split a String/1525.cpp create mode 100644 solutions/1525. Number of Good Ways to Split a String/1525.java create mode 100644 solutions/1525. Number of Good Ways to Split a String/1525.py create mode 100644 solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.cpp create mode 100644 solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.java create mode 100644 solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.py create mode 100644 solutions/1527. Patients With a Condition/1527.sql create mode 100644 solutions/1528. Shuffle String/1528.cpp create mode 100644 solutions/1529. Minimum Suffix Flips/1529.cpp create mode 100644 solutions/1529. Minimum Suffix Flips/1529.java create mode 100644 solutions/153. Find Minimum in Rotated Sorted Array/153.cpp create mode 100644 solutions/153. Find Minimum in Rotated Sorted Array/153.java create mode 100644 solutions/153. Find Minimum in Rotated Sorted Array/153.py create mode 100644 solutions/1530. Number of Good Leaf Nodes Pairs/1530.cpp create mode 100644 solutions/1530. Number of Good Leaf Nodes Pairs/1530.java create mode 100644 solutions/1531. String Compression II/1531.cpp create mode 100644 solutions/1531. String Compression II/1531.java create mode 100644 solutions/1531. String Compression II/1531.py create mode 100644 solutions/1532. The Most Recent Three Orders/1532.sql create mode 100644 solutions/1533. Find the Index of the Large Integer/1533-2.cpp create mode 100644 solutions/1533. Find the Index of the Large Integer/1533-2.java create mode 100644 solutions/1533. Find the Index of the Large Integer/1533-2.py create mode 100644 solutions/1533. Find the Index of the Large Integer/1533.cpp create mode 100644 solutions/1533. Find the Index of the Large Integer/1533.java create mode 100644 solutions/1533. Find the Index of the Large Integer/1533.py create mode 100644 solutions/1534. Count Good Triplets/1534.cpp create mode 100644 solutions/1534. Count Good Triplets/1534.java create mode 100644 solutions/1534. Count Good Triplets/1534.py create mode 100644 solutions/1535. Find the Winner of an Array Game/1535.cpp create mode 100644 solutions/1535. Find the Winner of an Array Game/1535.java create mode 100644 solutions/1535. Find the Winner of an Array Game/1535.py create mode 100644 solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.cpp create mode 100644 solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.java create mode 100644 solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.py create mode 100644 solutions/1537. Get the Maximum Score/1537.cpp create mode 100644 solutions/1537. Get the Maximum Score/1537.java create mode 100644 solutions/1537. Get the Maximum Score/1537.py create mode 100644 solutions/1538. Guess the Majority in a Hidden Array/1538.cpp create mode 100644 solutions/1538. Guess the Majority in a Hidden Array/1538.java create mode 100644 solutions/1538. Guess the Majority in a Hidden Array/1538.py create mode 100644 solutions/1539. Kth Missing Positive Number/1539.cpp create mode 100644 solutions/1539. Kth Missing Positive Number/1539.java create mode 100644 solutions/154. Find Minimum in Rotated Sorted Array II/154.cpp create mode 100644 solutions/154. Find Minimum in Rotated Sorted Array II/154.java create mode 100644 solutions/154. Find Minimum in Rotated Sorted Array II/154.py create mode 100644 solutions/1540. Can Convert String in K Moves/1540-2.cpp create mode 100644 solutions/1540. Can Convert String in K Moves/1540-2.java create mode 100644 solutions/1540. Can Convert String in K Moves/1540-2.py create mode 100644 solutions/1540. Can Convert String in K Moves/1540.cpp create mode 100644 solutions/1540. Can Convert String in K Moves/1540.java create mode 100644 solutions/1540. Can Convert String in K Moves/1540.py create mode 100644 solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.cpp create mode 100644 solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.java create mode 100644 solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.py create mode 100644 solutions/1542. Find Longest Awesome Substring/1542.cpp create mode 100644 solutions/1542. Find Longest Awesome Substring/1542.java create mode 100644 solutions/1542. Find Longest Awesome Substring/1542.py create mode 100644 solutions/1543. Fix Product Name Format/1543.sql create mode 100644 solutions/1544. Make The String Great/1544.cpp create mode 100644 solutions/1544. Make The String Great/1544.java create mode 100644 solutions/1544. Make The String Great/1544.py create mode 100644 solutions/1545. Find Kth Bit in Nth Binary String/1545.cpp create mode 100644 solutions/1545. Find Kth Bit in Nth Binary String/1545.java create mode 100644 solutions/1545. Find Kth Bit in Nth Binary String/1545.py create mode 100644 solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.cpp create mode 100644 solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.java create mode 100644 solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.py create mode 100644 solutions/1547. Minimum Cost to Cut a Stick/1547-2.cpp create mode 100644 solutions/1547. Minimum Cost to Cut a Stick/1547-2.java create mode 100644 solutions/1547. Minimum Cost to Cut a Stick/1547-2.py create mode 100644 solutions/1547. Minimum Cost to Cut a Stick/1547.cpp create mode 100644 solutions/1547. Minimum Cost to Cut a Stick/1547.java create mode 100644 solutions/1547. Minimum Cost to Cut a Stick/1547.py create mode 100644 solutions/1548. The Most Similar Path in a Graph/1548.cpp create mode 100644 solutions/1548. The Most Similar Path in a Graph/1548.java create mode 100644 solutions/1548. The Most Similar Path in a Graph/1548.py create mode 100644 solutions/1549. The Most Recent Orders for Each Product/1549.sql create mode 100644 solutions/155. Min Stack/155.cpp create mode 100644 solutions/155. Min Stack/155.java create mode 100644 solutions/155. Min Stack/155.py create mode 100644 solutions/1550. Three Consecutive Odds/1550.cpp create mode 100644 solutions/1550. Three Consecutive Odds/1550.java create mode 100644 solutions/1550. Three Consecutive Odds/1550.py create mode 100644 solutions/1551. Minimum Operations to Make Array Equal/1551.cpp create mode 100644 solutions/1551. Minimum Operations to Make Array Equal/1551.java create mode 100644 solutions/1551. Minimum Operations to Make Array Equal/1551.py create mode 100644 solutions/1552. Magnetic Force Between Two Balls/1552.cpp create mode 100644 solutions/1552. Magnetic Force Between Two Balls/1552.java create mode 100644 solutions/1552. Magnetic Force Between Two Balls/1552.py create mode 100644 solutions/1553. Minimum Number of Days to Eat N Oranges/1553.cpp create mode 100644 solutions/1553. Minimum Number of Days to Eat N Oranges/1553.java create mode 100644 solutions/1553. Minimum Number of Days to Eat N Oranges/1553.py create mode 100644 solutions/1554. Strings Differ by One Character/1554-2.cpp create mode 100644 solutions/1554. Strings Differ by One Character/1554-2.java create mode 100644 solutions/1554. Strings Differ by One Character/1554-2.py create mode 100644 solutions/1554. Strings Differ by One Character/1554.cpp create mode 100644 solutions/1555. Bank Account Summary/1555.sql create mode 100644 solutions/1556. Thousand Separator/1556.cpp create mode 100644 solutions/1556. Thousand Separator/1556.java create mode 100644 solutions/1556. Thousand Separator/1556.py create mode 100644 solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.cpp create mode 100644 solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.java create mode 100644 solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.py create mode 100644 solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.cpp create mode 100644 solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.java create mode 100644 solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.py create mode 100644 solutions/1559. Detect Cycles in 2D Grid/1559.cpp create mode 100644 solutions/1559. Detect Cycles in 2D Grid/1559.java create mode 100644 solutions/156. Binary Tree Upside Down/156-2.cpp create mode 100644 solutions/156. Binary Tree Upside Down/156-2.java create mode 100644 solutions/156. Binary Tree Upside Down/156-2.py create mode 100644 solutions/156. Binary Tree Upside Down/156.cpp create mode 100644 solutions/156. Binary Tree Upside Down/156.java create mode 100644 solutions/156. Binary Tree Upside Down/156.py create mode 100644 solutions/1560. Most Visited Sector in a Circular Track/1560.cpp create mode 100644 solutions/1560. Most Visited Sector in a Circular Track/1560.java create mode 100644 solutions/1560. Most Visited Sector in a Circular Track/1560.py create mode 100644 solutions/1561. Maximum Number of Coins You Can Get/1561.cpp create mode 100644 solutions/1561. Maximum Number of Coins You Can Get/1561.java create mode 100644 solutions/1561. Maximum Number of Coins You Can Get/1561.py create mode 100644 solutions/1562. Find Latest Group of Size M/1562.cpp create mode 100644 solutions/1562. Find Latest Group of Size M/1562.java create mode 100644 solutions/1562. Find Latest Group of Size M/1562.py create mode 100644 solutions/1563. Stone Game V/1563.cpp create mode 100644 solutions/1563. Stone Game V/1563.java create mode 100644 solutions/1564. Put Boxes Into the Warehouse I/1564-2.cpp create mode 100644 solutions/1564. Put Boxes Into the Warehouse I/1564-2.java create mode 100644 solutions/1564. Put Boxes Into the Warehouse I/1564-2.py create mode 100644 solutions/1564. Put Boxes Into the Warehouse I/1564.cpp create mode 100644 solutions/1564. Put Boxes Into the Warehouse I/1564.java create mode 100644 solutions/1564. Put Boxes Into the Warehouse I/1564.py create mode 100644 solutions/1565. Unique Orders and Customers Per Month/1565.sql create mode 100644 solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.cpp create mode 100644 solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.java create mode 100644 solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.py create mode 100644 solutions/1567. Maximum Length of Subarray With Positive Product/1567.cpp create mode 100644 solutions/1567. Maximum Length of Subarray With Positive Product/1567.java create mode 100644 solutions/1567. Maximum Length of Subarray With Positive Product/1567.py create mode 100644 solutions/1568. Minimum Number of Days to Disconnect Island/1568.cpp create mode 100644 solutions/1568. Minimum Number of Days to Disconnect Island/1568.java create mode 100644 solutions/1568. Minimum Number of Days to Disconnect Island/1568.py create mode 100644 solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.cpp create mode 100644 solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.java create mode 100644 solutions/157. Read N Characters Given Read4/157-2.cpp create mode 100644 solutions/157. Read N Characters Given Read4/157.cpp create mode 100644 solutions/157. Read N Characters Given Read4/157.java create mode 100644 solutions/157. Read N Characters Given Read4/157.py create mode 100644 solutions/1570. Dot Product of Two Sparse Vectors/1570-2.cpp create mode 100644 solutions/1570. Dot Product of Two Sparse Vectors/1570-2.java create mode 100644 solutions/1570. Dot Product of Two Sparse Vectors/1570.cpp create mode 100644 solutions/1570. Dot Product of Two Sparse Vectors/1570.java create mode 100644 solutions/1571. Warehouse Manager/1571.sql create mode 100644 solutions/1572. Matrix Diagonal Sum/1572.cpp create mode 100644 solutions/1572. Matrix Diagonal Sum/1572.java create mode 100644 solutions/1572. Matrix Diagonal Sum/1572.py create mode 100644 solutions/1573. Number of Ways to Split a String/1573.cpp create mode 100644 solutions/1573. Number of Ways to Split a String/1573.java create mode 100644 solutions/1573. Number of Ways to Split a String/1573.py create mode 100644 solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.cpp create mode 100644 solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.java create mode 100644 solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.py create mode 100644 solutions/1575. Count All Possible Routes/1575-2.cpp create mode 100644 solutions/1575. Count All Possible Routes/1575-2.java create mode 100644 solutions/1575. Count All Possible Routes/1575-2.py create mode 100644 solutions/1575. Count All Possible Routes/1575.cpp create mode 100644 solutions/1575. Count All Possible Routes/1575.java create mode 100644 solutions/1575. Count All Possible Routes/1575.py create mode 100644 solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.cpp create mode 100644 solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.java create mode 100644 solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.py create mode 100644 solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.cpp create mode 100644 solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.java create mode 100644 solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.py create mode 100644 solutions/1578. Minimum Time to Make Rope Colorful/1578.cpp create mode 100644 solutions/1578. Minimum Time to Make Rope Colorful/1578.java create mode 100644 solutions/1578. Minimum Time to Make Rope Colorful/1578.py create mode 100644 solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.cpp create mode 100644 solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.java create mode 100644 solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.py create mode 100644 solutions/158. Read N Characters Given Read4 II - Call multiple times/158-2.cpp create mode 100644 solutions/158. Read N Characters Given Read4 II - Call multiple times/158.cpp create mode 100644 solutions/158. Read N Characters Given Read4 II - Call multiple times/158.java create mode 100644 solutions/158. Read N Characters Given Read4 II - Call multiple times/158.py create mode 100644 solutions/1580. Put Boxes Into the Warehouse II/1580.cpp create mode 100644 solutions/1580. Put Boxes Into the Warehouse II/1580.java create mode 100644 solutions/1580. Put Boxes Into the Warehouse II/1580.py create mode 100644 solutions/1581. Customer Who Visited but Did Not Make Any Transactions/1581.sql create mode 100644 solutions/1582. Special Positions in a Binary Matrix/1582.cpp create mode 100644 solutions/1582. Special Positions in a Binary Matrix/1582.java create mode 100644 solutions/1582. Special Positions in a Binary Matrix/1582.py create mode 100644 solutions/1583. Count Unhappy Friends/1583.cpp create mode 100644 solutions/1583. Count Unhappy Friends/1583.java create mode 100644 solutions/1583. Count Unhappy Friends/1583.py create mode 100644 solutions/1584. Min Cost to Connect All Points/1584.cpp create mode 100644 solutions/1584. Min Cost to Connect All Points/1584.java create mode 100644 solutions/1584. Min Cost to Connect All Points/1584.py create mode 100644 solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.cpp create mode 100644 solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.java create mode 100644 solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.py create mode 100644 solutions/1586. Binary Search Tree Iterator II/1586.cpp create mode 100644 solutions/1586. Binary Search Tree Iterator II/1586.java create mode 100644 solutions/1586. Binary Search Tree Iterator II/1586.py create mode 100644 solutions/1587. Bank Account Summary II/1587.sql create mode 100644 solutions/1588. Sum of All Odd Length Subarrays/1588.cpp create mode 100644 solutions/1588. Sum of All Odd Length Subarrays/1588.java create mode 100644 solutions/1588. Sum of All Odd Length Subarrays/1588.py create mode 100644 solutions/1589. Maximum Sum Obtained of Any Permutation/1589.cpp create mode 100644 solutions/1589. Maximum Sum Obtained of Any Permutation/1589.java create mode 100644 solutions/1589. Maximum Sum Obtained of Any Permutation/1589.py create mode 100644 solutions/159. Longest Substring with At Most Two Distinct Characters/159.cpp create mode 100644 solutions/159. Longest Substring with At Most Two Distinct Characters/159.java create mode 100644 solutions/159. Longest Substring with At Most Two Distinct Characters/159.py create mode 100644 solutions/1590. Make Sum Divisible by P/1590.cpp create mode 100644 solutions/1590. Make Sum Divisible by P/1590.java create mode 100644 solutions/1590. Make Sum Divisible by P/1590.py create mode 100644 solutions/1591. Strange Printer II/1591.cpp create mode 100644 solutions/1591. Strange Printer II/1591.java create mode 100644 solutions/1591. Strange Printer II/1591.py create mode 100644 solutions/1592. Rearrange Spaces Between Words/1592.cpp create mode 100644 solutions/1592. Rearrange Spaces Between Words/1592.java create mode 100644 solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.cpp create mode 100644 solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.java create mode 100644 solutions/1594. Maximum Non Negative Product in a Matrix/1594.cpp create mode 100644 solutions/1594. Maximum Non Negative Product in a Matrix/1594.java create mode 100644 solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.cpp create mode 100644 solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.java create mode 100644 solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.py create mode 100644 solutions/1596. The Most Frequently Ordered Products for Each Customer/1596.sql create mode 100644 solutions/1597. Build Binary Expression Tree From Infix Expression/1597.cpp create mode 100644 solutions/1597. Build Binary Expression Tree From Infix Expression/1597.java create mode 100644 solutions/1598. Crawler Log Folder/1598.cpp create mode 100644 solutions/1598. Crawler Log Folder/1598.java create mode 100644 solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.cpp create mode 100644 solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.java create mode 100644 solutions/16. 3Sum Closest/16.cpp create mode 100644 solutions/16. 3Sum Closest/16.java create mode 100644 solutions/16. 3Sum Closest/16.py create mode 100644 solutions/160. Intersection of Two Linked Lists/160.cpp create mode 100644 solutions/160. Intersection of Two Linked Lists/160.java create mode 100644 solutions/160. Intersection of Two Linked Lists/160.py create mode 100644 solutions/1600. Throne Inheritance/1600.cpp create mode 100644 solutions/1600. Throne Inheritance/1600.java create mode 100644 solutions/1601. Maximum Number of Achievable Transfer Requests/1601.cpp create mode 100644 solutions/1601. Maximum Number of Achievable Transfer Requests/1601.java create mode 100644 solutions/1602. Find Nearest Right Node in Binary Tree/1602.cpp create mode 100644 solutions/1602. Find Nearest Right Node in Binary Tree/1602.java create mode 100644 solutions/1602. Find Nearest Right Node in Binary Tree/1602.py create mode 100644 solutions/1603. Design Parking System/1603.cpp create mode 100644 solutions/1603. Design Parking System/1603.java create mode 100644 solutions/1603. Design Parking System/1603.py create mode 100644 solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.cpp create mode 100644 solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.java create mode 100644 solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.py create mode 100644 solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.cpp create mode 100644 solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.java create mode 100644 solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.py create mode 100644 solutions/1606. Find Servers That Handled Most Number of Requests/1606.cpp create mode 100644 solutions/1606. Find Servers That Handled Most Number of Requests/1606.java create mode 100644 solutions/1607. Sellers With No Sales/1607.sql create mode 100644 solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.cpp create mode 100644 solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.java create mode 100644 solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.py create mode 100644 solutions/1609. Even Odd Tree/1609.cpp create mode 100644 solutions/1609. Even Odd Tree/1609.java create mode 100644 solutions/1609. Even Odd Tree/1609.py create mode 100644 solutions/161. One Edit Distance/161.cpp create mode 100644 solutions/161. One Edit Distance/161.java create mode 100644 solutions/161. One Edit Distance/161.py create mode 100644 solutions/1610. Maximum Number of Visible Points/1610.cpp create mode 100644 solutions/1610. Maximum Number of Visible Points/1610.java create mode 100644 solutions/1610. Maximum Number of Visible Points/1610.py create mode 100644 solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.cpp create mode 100644 solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.java create mode 100644 solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.py create mode 100644 solutions/1612. Check If Two Expression Trees are Equivalent/1612.cpp create mode 100644 solutions/1612. Check If Two Expression Trees are Equivalent/1612.java create mode 100644 solutions/1612. Check If Two Expression Trees are Equivalent/1612.py create mode 100644 solutions/1613. Find the Missing IDs/1613.sql create mode 100644 solutions/1614. Maximum Nesting Depth of the Parentheses/1614.cpp create mode 100644 solutions/1614. Maximum Nesting Depth of the Parentheses/1614.java create mode 100644 solutions/1614. Maximum Nesting Depth of the Parentheses/1614.py create mode 100644 solutions/1615. Maximal Network Rank/1615.cpp create mode 100644 solutions/1615. Maximal Network Rank/1615.java create mode 100644 solutions/1615. Maximal Network Rank/1615.py create mode 100644 solutions/1616. Split Two Strings to Make Palindrome/1616.cpp create mode 100644 solutions/1616. Split Two Strings to Make Palindrome/1616.java create mode 100644 solutions/1616. Split Two Strings to Make Palindrome/1616.py create mode 100644 solutions/1617. Count Subtrees With Max Distance Between Cities/1617.cpp create mode 100644 solutions/1617. Count Subtrees With Max Distance Between Cities/1617.java create mode 100644 solutions/1617. Count Subtrees With Max Distance Between Cities/1617.py create mode 100644 solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.cpp create mode 100644 solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.java create mode 100644 solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.py create mode 100644 solutions/1619. Mean of Array After Removing Some Elements/1619.cpp create mode 100644 solutions/1619. Mean of Array After Removing Some Elements/1619.java create mode 100644 solutions/1619. Mean of Array After Removing Some Elements/1619.py create mode 100644 solutions/162. Find Peak Element/162.cpp create mode 100644 solutions/162. Find Peak Element/162.java create mode 100644 solutions/162. Find Peak Element/162.py create mode 100644 solutions/1620. Coordinate With Maximum Network Quality/1620.cpp create mode 100644 solutions/1620. Coordinate With Maximum Network Quality/1620.java create mode 100644 solutions/1620. Coordinate With Maximum Network Quality/1620.py create mode 100644 solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.cpp create mode 100644 solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.java create mode 100644 solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.py create mode 100644 solutions/1622. Fancy Sequence/1622.cpp create mode 100644 solutions/1622. Fancy Sequence/1622.java create mode 100644 solutions/1622. Fancy Sequence/1622.py create mode 100644 solutions/1623. All Valid Triplets That Can Represent a Country/1623.sql create mode 100644 solutions/1624. Largest Substring Between Two Equal Characters/1624.cpp create mode 100644 solutions/1624. Largest Substring Between Two Equal Characters/1624.java create mode 100644 solutions/1624. Largest Substring Between Two Equal Characters/1624.py create mode 100644 solutions/1625. Lexicographically Smallest String After Applying Operations/1625.cpp create mode 100644 solutions/1625. Lexicographically Smallest String After Applying Operations/1625.java create mode 100644 solutions/1626. Best Team With No Conflicts/1626.cpp create mode 100644 solutions/1626. Best Team With No Conflicts/1626.java create mode 100644 solutions/1627. Graph Connectivity With Threshold/1627.cpp create mode 100644 solutions/1627. Graph Connectivity With Threshold/1627.java create mode 100644 solutions/1627. Graph Connectivity With Threshold/1627.py create mode 100644 solutions/1628. Design an Expression Tree With Evaluate Function/1628.cpp create mode 100644 solutions/1628. Design an Expression Tree With Evaluate Function/1628.java create mode 100644 solutions/1628. Design an Expression Tree With Evaluate Function/1628.py create mode 100644 solutions/1629. Slowest Key/1629.cpp create mode 100644 solutions/1629. Slowest Key/1629.java create mode 100644 solutions/1629. Slowest Key/1629.py create mode 100644 solutions/163. Missing Ranges/163.cpp create mode 100644 solutions/163. Missing Ranges/163.java create mode 100644 solutions/163. Missing Ranges/163.py create mode 100644 solutions/1630. Arithmetic Subarrays/1630.cpp create mode 100644 solutions/1630. Arithmetic Subarrays/1630.java create mode 100644 solutions/1630. Arithmetic Subarrays/1630.py create mode 100644 solutions/1631. Path With Minimum Effort/1631.cpp create mode 100644 solutions/1631. Path With Minimum Effort/1631.java create mode 100644 solutions/1631. Path With Minimum Effort/1631.py create mode 100644 solutions/1632. Rank Transform of a Matrix/1632.cpp create mode 100644 solutions/1632. Rank Transform of a Matrix/1632.java create mode 100644 solutions/1632. Rank Transform of a Matrix/1632.py create mode 100644 solutions/1633. Percentage of Users Attended a Contest/1633.sql create mode 100644 solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.cpp create mode 100644 solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.java create mode 100644 solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.py create mode 100644 solutions/1635. Hopper Company Queries I/1635.sql create mode 100644 solutions/1636. Sort Array by Increasing Frequency/1636.cpp create mode 100644 solutions/1636. Sort Array by Increasing Frequency/1636.java create mode 100644 solutions/1636. Sort Array by Increasing Frequency/1636.py create mode 100644 solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.cpp create mode 100644 solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.java create mode 100644 solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.py create mode 100644 solutions/1638. Count Substrings That Differ by One Character/1638.cpp create mode 100644 solutions/1638. Count Substrings That Differ by One Character/1638.java create mode 100644 solutions/1638. Count Substrings That Differ by One Character/1638.py create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.cpp create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.java create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.py create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.cpp create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.java create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.py create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.cpp create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.java create mode 100644 solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.py create mode 100644 solutions/164. Maximum Gap/164.cpp create mode 100644 solutions/164. Maximum Gap/164.java create mode 100644 solutions/164. Maximum Gap/164.py create mode 100644 solutions/1640. Check Array Formation Through Concatenation/1640.cpp create mode 100644 solutions/1640. Check Array Formation Through Concatenation/1640.java create mode 100644 solutions/1640. Check Array Formation Through Concatenation/1640.py create mode 100644 solutions/1641. Count Sorted Vowel Strings/1641-2.cpp create mode 100644 solutions/1641. Count Sorted Vowel Strings/1641-2.java create mode 100644 solutions/1641. Count Sorted Vowel Strings/1641.cpp create mode 100644 solutions/1641. Count Sorted Vowel Strings/1641.java create mode 100644 solutions/1642. Furthest Building You Can Reach/1642.cpp create mode 100644 solutions/1642. Furthest Building You Can Reach/1642.java create mode 100644 solutions/1642. Furthest Building You Can Reach/1642.py create mode 100644 solutions/1643. Kth Smallest Instructions/1643.cpp create mode 100644 solutions/1643. Kth Smallest Instructions/1643.java create mode 100644 solutions/1643. Kth Smallest Instructions/1643.py create mode 100644 solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.cpp create mode 100644 solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.java create mode 100644 solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.py create mode 100644 solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.cpp create mode 100644 solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.java create mode 100644 solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.py create mode 100644 solutions/1645. Hopper Company Queries II/1645.sql create mode 100644 solutions/1646. Get Maximum in Generated Array/1646.cpp create mode 100644 solutions/1646. Get Maximum in Generated Array/1646.java create mode 100644 solutions/1646. Get Maximum in Generated Array/1646.py create mode 100644 solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.cpp create mode 100644 solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.java create mode 100644 solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.py create mode 100644 solutions/1648. Sell Diminishing-Valued Colored Balls/1648.cpp create mode 100644 solutions/1648. Sell Diminishing-Valued Colored Balls/1648.java create mode 100644 solutions/1648. Sell Diminishing-Valued Colored Balls/1648.py create mode 100644 solutions/1649. Create Sorted Array through Instructions/1649-2.cpp create mode 100644 solutions/1649. Create Sorted Array through Instructions/1649-3.cpp create mode 100644 solutions/1649. Create Sorted Array through Instructions/1649.cpp create mode 100644 solutions/165. Compare Version Numbers/165.cpp create mode 100644 solutions/165. Compare Version Numbers/165.java create mode 100644 solutions/165. Compare Version Numbers/165.py create mode 100644 solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.cpp create mode 100644 solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.java create mode 100644 solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.py create mode 100644 solutions/1651. Hopper Company Queries III/1651.sql create mode 100644 solutions/1652. Defuse the Bomb/1652.cpp create mode 100644 solutions/1652. Defuse the Bomb/1652.java create mode 100644 solutions/1652. Defuse the Bomb/1652.py create mode 100644 solutions/1653. Minimum Deletions to Make String Balanced/1653.cpp create mode 100644 solutions/1653. Minimum Deletions to Make String Balanced/1653.java create mode 100644 solutions/1653. Minimum Deletions to Make String Balanced/1653.py create mode 100644 solutions/1654. Minimum Jumps to Reach Home/1654.cpp create mode 100644 solutions/1654. Minimum Jumps to Reach Home/1654.java create mode 100644 solutions/1654. Minimum Jumps to Reach Home/1654.py create mode 100644 solutions/1655. Distribute Repeating Integers/1655.cpp create mode 100644 solutions/1655. Distribute Repeating Integers/1655.java create mode 100644 solutions/1655. Distribute Repeating Integers/1655.py create mode 100644 solutions/1656. Design an Ordered Stream/1656.cpp create mode 100644 solutions/1656. Design an Ordered Stream/1656.java create mode 100644 solutions/1656. Design an Ordered Stream/1656.py create mode 100644 solutions/1657. Determine if Two Strings Are Close/1657.cpp create mode 100644 solutions/1657. Determine if Two Strings Are Close/1657.java create mode 100644 solutions/1657. Determine if Two Strings Are Close/1657.py create mode 100644 solutions/1658. Minimum Operations to Reduce X to Zero/1658.cpp create mode 100644 solutions/1658. Minimum Operations to Reduce X to Zero/1658.java create mode 100644 solutions/1658. Minimum Operations to Reduce X to Zero/1658.py create mode 100644 solutions/1659. Maximize Grid Happiness/1659.cpp create mode 100644 solutions/1659. Maximize Grid Happiness/1659.java create mode 100644 solutions/1659. Maximize Grid Happiness/1659.py create mode 100644 solutions/166. Fraction to Recurring Decimal/166.cpp create mode 100644 solutions/166. Fraction to Recurring Decimal/166.java create mode 100644 solutions/166. Fraction to Recurring Decimal/166.py create mode 100644 solutions/1660. Correct a Binary Tree/1660.cpp create mode 100644 solutions/1660. Correct a Binary Tree/1660.java create mode 100644 solutions/1660. Correct a Binary Tree/1660.py create mode 100644 solutions/1661. Average Time of Process per Machine/1661.sql create mode 100644 solutions/1662. Check If Two String Arrays are Equivalent/1662.cpp create mode 100644 solutions/1662. Check If Two String Arrays are Equivalent/1662.java create mode 100644 solutions/1662. Check If Two String Arrays are Equivalent/1662.py create mode 100644 solutions/1663. Smallest String With A Given Numeric Value/1663.cpp create mode 100644 solutions/1663. Smallest String With A Given Numeric Value/1663.java create mode 100644 solutions/1663. Smallest String With A Given Numeric Value/1663.py create mode 100644 solutions/1664. Ways to Make a Fair Array/1664-2.cpp create mode 100644 solutions/1664. Ways to Make a Fair Array/1664-2.java create mode 100644 solutions/1664. Ways to Make a Fair Array/1664.cpp create mode 100644 solutions/1664. Ways to Make a Fair Array/1664.java create mode 100644 solutions/1665. Minimum Initial Energy to Finish Tasks/1665.cpp create mode 100644 solutions/1665. Minimum Initial Energy to Finish Tasks/1665.java create mode 100644 solutions/1665. Minimum Initial Energy to Finish Tasks/1665.py create mode 100644 solutions/1666. Change the Root of a Binary Tree/1666.cpp create mode 100644 solutions/1666. Change the Root of a Binary Tree/1666.java create mode 100644 solutions/1667. Fix Names in a Table/1667.sql create mode 100644 solutions/1668. Maximum Repeating Substring/1668.cpp create mode 100644 solutions/1668. Maximum Repeating Substring/1668.java create mode 100644 solutions/1668. Maximum Repeating Substring/1668.py create mode 100644 solutions/1669. Merge In Between Linked Lists/1669.cpp create mode 100644 solutions/1669. Merge In Between Linked Lists/1669.java create mode 100644 solutions/1669. Merge In Between Linked Lists/1669.py create mode 100644 solutions/167. Two Sum II - Input array is sorted/167.cpp create mode 100644 solutions/167. Two Sum II - Input array is sorted/167.java create mode 100644 solutions/167. Two Sum II - Input array is sorted/167.py create mode 100644 solutions/1670. Design Front Middle Back Queue/1670.cpp create mode 100644 solutions/1670. Design Front Middle Back Queue/1670.java create mode 100644 solutions/1670. Design Front Middle Back Queue/1670.py create mode 100644 solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.cpp create mode 100644 solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.java create mode 100644 solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.py create mode 100644 solutions/1672. Richest Customer Wealth/1672.cpp create mode 100644 solutions/1672. Richest Customer Wealth/1672.java create mode 100644 solutions/1672. Richest Customer Wealth/1672.py create mode 100644 solutions/1673. Find the Most Competitive Subsequence/1673.cpp create mode 100644 solutions/1673. Find the Most Competitive Subsequence/1673.java create mode 100644 solutions/1673. Find the Most Competitive Subsequence/1673.py create mode 100644 solutions/1674. Minimum Moves to Make Array Complementary/1674.cpp create mode 100644 solutions/1674. Minimum Moves to Make Array Complementary/1674.java create mode 100644 solutions/1674. Minimum Moves to Make Array Complementary/1674.py create mode 100644 solutions/1675. Minimize Deviation in Array/1675.cpp create mode 100644 solutions/1675. Minimize Deviation in Array/1675.java create mode 100644 solutions/1675. Minimize Deviation in Array/1675.py create mode 100644 solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.cpp create mode 100644 solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.java create mode 100644 solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.py create mode 100644 solutions/1677. Product's Worth Over Invoices/1677.sql create mode 100644 solutions/1678. Goal Parser Interpretation/1678.cpp create mode 100644 solutions/1678. Goal Parser Interpretation/1678.java create mode 100644 solutions/1678. Goal Parser Interpretation/1678.py create mode 100644 solutions/1679. Max Number of K-Sum Pairs/1679.cpp create mode 100644 solutions/1679. Max Number of K-Sum Pairs/1679.java create mode 100644 solutions/1679. Max Number of K-Sum Pairs/1679.py create mode 100644 solutions/168. Excel Sheet Column Title/168.cpp create mode 100644 solutions/168. Excel Sheet Column Title/168.java create mode 100644 solutions/168. Excel Sheet Column Title/168.py create mode 100644 solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.cpp create mode 100644 solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.java create mode 100644 solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.py create mode 100644 solutions/1680. Concatenation of Consecutive Binary Numbers/1680.cpp create mode 100644 solutions/1680. Concatenation of Consecutive Binary Numbers/1680.java create mode 100644 solutions/1680. Concatenation of Consecutive Binary Numbers/1680.py create mode 100644 solutions/1681. Minimum Incompatibility/1681.cpp create mode 100644 solutions/1681. Minimum Incompatibility/1681.java create mode 100644 solutions/1681. Minimum Incompatibility/1681.py create mode 100644 solutions/1682. Longest Palindromic Subsequence II/1682-2.cpp create mode 100644 solutions/1682. Longest Palindromic Subsequence II/1682-2.java create mode 100644 solutions/1682. Longest Palindromic Subsequence II/1682-2.py create mode 100644 solutions/1682. Longest Palindromic Subsequence II/1682.cpp create mode 100644 solutions/1682. Longest Palindromic Subsequence II/1682.java create mode 100644 solutions/1682. Longest Palindromic Subsequence II/1682.py create mode 100644 solutions/1683. Invalid Tweets/1683.sql create mode 100644 solutions/1684. Count the Number of Consistent Strings/1684.cpp create mode 100644 solutions/1684. Count the Number of Consistent Strings/1684.java create mode 100644 solutions/1684. Count the Number of Consistent Strings/1684.py create mode 100644 solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.cpp create mode 100644 solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.java create mode 100644 solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.py create mode 100644 solutions/1686. Stone Game VI/1686.cpp create mode 100644 solutions/1686. Stone Game VI/1686.java create mode 100644 solutions/1687. Delivering Boxes from Storage to Ports/1687.cpp create mode 100644 solutions/1687. Delivering Boxes from Storage to Ports/1687.java create mode 100644 solutions/1687. Delivering Boxes from Storage to Ports/1687.py create mode 100644 solutions/1688. Count of Matches in Tournament/1688.cpp create mode 100644 solutions/1688. Count of Matches in Tournament/1688.java create mode 100644 solutions/1688. Count of Matches in Tournament/1688.py create mode 100644 solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.cpp create mode 100644 solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.java create mode 100644 solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.py create mode 100644 solutions/169. Majority Element/169.cpp create mode 100644 solutions/169. Majority Element/169.java create mode 100644 solutions/169. Majority Element/169.py create mode 100644 solutions/1690. Stone Game VII/1690-2.cpp create mode 100644 solutions/1690. Stone Game VII/1690-2.java create mode 100644 solutions/1690. Stone Game VII/1690.cpp create mode 100644 solutions/1690. Stone Game VII/1690.java create mode 100644 solutions/1691. Maximum Height by Stacking Cuboids/1691.cpp create mode 100644 solutions/1691. Maximum Height by Stacking Cuboids/1691.java create mode 100644 solutions/1692. Count Ways to Distribute Candies/1692-2.cpp create mode 100644 solutions/1692. Count Ways to Distribute Candies/1692-2.java create mode 100644 solutions/1692. Count Ways to Distribute Candies/1692.cpp create mode 100644 solutions/1692. Count Ways to Distribute Candies/1692.java create mode 100644 solutions/1693. Daily Leads and Partners/1693.sql create mode 100644 solutions/1694. Reformat Phone Number/1694.cpp create mode 100644 solutions/1694. Reformat Phone Number/1694.java create mode 100644 solutions/1694. Reformat Phone Number/1694.py create mode 100644 solutions/1695. Maximum Erasure Value/1695.cpp create mode 100644 solutions/1695. Maximum Erasure Value/1695.java create mode 100644 solutions/1695. Maximum Erasure Value/1695.py create mode 100644 solutions/1696. Jump Game VI/1696.cpp create mode 100644 solutions/1696. Jump Game VI/1696.java create mode 100644 solutions/1696. Jump Game VI/1696.py create mode 100644 solutions/1697. Checking Existence of Edge Length Limited Paths/1697.cpp create mode 100644 solutions/1697. Checking Existence of Edge Length Limited Paths/1697.java create mode 100644 solutions/1698. Number of Distinct Substrings in a String/1698.cpp create mode 100644 solutions/1698. Number of Distinct Substrings in a String/1698.java create mode 100644 solutions/1698. Number of Distinct Substrings in a String/1698.py create mode 100644 solutions/1699. Number of Calls Between Two Persons/1699.sql create mode 100644 solutions/17. Letter Combinations of a Phone Number/17-2.cpp create mode 100644 solutions/17. Letter Combinations of a Phone Number/17-2.java create mode 100644 solutions/17. Letter Combinations of a Phone Number/17-2.py create mode 100644 solutions/17. Letter Combinations of a Phone Number/17.cpp create mode 100644 solutions/17. Letter Combinations of a Phone Number/17.java create mode 100644 solutions/17. Letter Combinations of a Phone Number/17.py create mode 100644 solutions/170. Two Sum III - Data structure design/170.cpp create mode 100644 solutions/170. Two Sum III - Data structure design/170.java create mode 100644 solutions/170. Two Sum III - Data structure design/170.py create mode 100644 solutions/1700. Number of Students Unable to Eat Lunch/1700.cpp create mode 100644 solutions/1700. Number of Students Unable to Eat Lunch/1700.java create mode 100644 solutions/1700. Number of Students Unable to Eat Lunch/1700.py create mode 100644 solutions/1701. Average Waiting Time/1701.cpp create mode 100644 solutions/1701. Average Waiting Time/1701.java create mode 100644 solutions/1702. Maximum Binary String After Change/1702.cpp create mode 100644 solutions/1702. Maximum Binary String After Change/1702.java create mode 100644 solutions/1702. Maximum Binary String After Change/1702.py create mode 100644 solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.cpp create mode 100644 solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.java create mode 100644 solutions/1704. Determine if String Halves Are Alike/1704.cpp create mode 100644 solutions/1704. Determine if String Halves Are Alike/1704.java create mode 100644 solutions/1704. Determine if String Halves Are Alike/1704.py create mode 100644 solutions/1705. Maximum Number of Eaten Apples/1705.cpp create mode 100644 solutions/1705. Maximum Number of Eaten Apples/1705.java create mode 100644 solutions/1705. Maximum Number of Eaten Apples/1705.py create mode 100644 solutions/1706. Where Will the Ball Fall/1706.cpp create mode 100644 solutions/1706. Where Will the Ball Fall/1706.java create mode 100644 solutions/1706. Where Will the Ball Fall/1706.py create mode 100644 solutions/1707. Maximum XOR With an Element From Array/1707.cpp create mode 100644 solutions/1707. Maximum XOR With an Element From Array/1707.java create mode 100644 solutions/1707. Maximum XOR With an Element From Array/1707.py create mode 100644 solutions/1708. Largest Subarray Length K/1708.cpp create mode 100644 solutions/1708. Largest Subarray Length K/1708.java create mode 100644 solutions/1708. Largest Subarray Length K/1708.py create mode 100644 solutions/1709. Biggest Window Between Visits/1709.sql create mode 100644 solutions/171. Excel Sheet Column Number/171.cpp create mode 100644 solutions/171. Excel Sheet Column Number/171.java create mode 100644 solutions/171. Excel Sheet Column Number/171.py create mode 100644 solutions/1710. Maximum Units on a Truck/1710.cpp create mode 100644 solutions/1710. Maximum Units on a Truck/1710.java create mode 100644 solutions/1710. Maximum Units on a Truck/1710.py create mode 100644 solutions/1711. Count Good Meals/1711.cpp create mode 100644 solutions/1711. Count Good Meals/1711.java create mode 100644 solutions/1711. Count Good Meals/1711.py create mode 100644 solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.cpp create mode 100644 solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.java create mode 100644 solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.py create mode 100644 solutions/1712. Ways to Split Array Into Three Subarrays/1712.cpp create mode 100644 solutions/1712. Ways to Split Array Into Three Subarrays/1712.java create mode 100644 solutions/1712. Ways to Split Array Into Three Subarrays/1712.py create mode 100644 solutions/1713. Minimum Operations to Make a Subsequence/1713.cpp create mode 100644 solutions/1713. Minimum Operations to Make a Subsequence/1713.java create mode 100644 solutions/1713. Minimum Operations to Make a Subsequence/1713.py create mode 100644 solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.cpp create mode 100644 solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.java create mode 100644 solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.py create mode 100644 solutions/1715. Count Apples and Oranges/1715.sql create mode 100644 solutions/1716. Calculate Money in Leetcode Bank/1716.cpp create mode 100644 solutions/1716. Calculate Money in Leetcode Bank/1716.java create mode 100644 solutions/1716. Calculate Money in Leetcode Bank/1716.py create mode 100644 solutions/1717. Maximum Score From Removing Substrings/1717.cpp create mode 100644 solutions/1717. Maximum Score From Removing Substrings/1717.java create mode 100644 solutions/1717. Maximum Score From Removing Substrings/1717.py create mode 100644 solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.cpp create mode 100644 solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.java create mode 100644 solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.py create mode 100644 solutions/1719. Number Of Ways To Reconstruct A Tree/1719.cpp create mode 100644 solutions/1719. Number Of Ways To Reconstruct A Tree/1719.java create mode 100644 solutions/1719. Number Of Ways To Reconstruct A Tree/1719.py create mode 100644 solutions/172. Factorial Trailing Zeroes/172.cpp create mode 100644 solutions/172. Factorial Trailing Zeroes/172.java create mode 100644 solutions/172. Factorial Trailing Zeroes/172.py create mode 100644 solutions/1720. Decode XORed Array/1720.cpp create mode 100644 solutions/1720. Decode XORed Array/1720.java create mode 100644 solutions/1720. Decode XORed Array/1720.py create mode 100644 solutions/1721. Swapping Nodes in a Linked List/1721.cpp create mode 100644 solutions/1721. Swapping Nodes in a Linked List/1721.java create mode 100644 solutions/1721. Swapping Nodes in a Linked List/1721.py create mode 100644 solutions/1722. Minimize Hamming Distance After Swap Operations/1722.cpp create mode 100644 solutions/1722. Minimize Hamming Distance After Swap Operations/1722.java create mode 100644 solutions/1722. Minimize Hamming Distance After Swap Operations/1722.py create mode 100644 solutions/1723. Find Minimum Time to Finish All Jobs/1723.cpp create mode 100644 solutions/1723. Find Minimum Time to Finish All Jobs/1723.java create mode 100644 solutions/1723. Find Minimum Time to Finish All Jobs/1723.py create mode 100644 solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.cpp create mode 100644 solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.java create mode 100644 solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.cpp create mode 100644 solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.java create mode 100644 solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.py create mode 100644 solutions/1726. Tuple with Same Product/1726.cpp create mode 100644 solutions/1726. Tuple with Same Product/1726.java create mode 100644 solutions/1726. Tuple with Same Product/1726.py create mode 100644 solutions/1727. Largest Submatrix With Rearrangements/1727.cpp create mode 100644 solutions/1727. Largest Submatrix With Rearrangements/1727.java create mode 100644 solutions/1727. Largest Submatrix With Rearrangements/1727.py create mode 100644 solutions/1728. Cat and Mouse II/1728.cpp create mode 100644 solutions/1728. Cat and Mouse II/1728.java create mode 100644 solutions/1728. Cat and Mouse II/1728.py create mode 100644 solutions/1729. Find Followers Count/1729.sql create mode 100644 solutions/173. Binary Search Tree Iterator/173-2.cpp create mode 100644 solutions/173. Binary Search Tree Iterator/173-2.java create mode 100644 solutions/173. Binary Search Tree Iterator/173-2.py create mode 100644 solutions/173. Binary Search Tree Iterator/173.cpp create mode 100644 solutions/173. Binary Search Tree Iterator/173.java create mode 100644 solutions/173. Binary Search Tree Iterator/173.py create mode 100644 solutions/1730. Shortest Path to Get Food/1730.cpp create mode 100644 solutions/1730. Shortest Path to Get Food/1730.java create mode 100644 solutions/1730. Shortest Path to Get Food/1730.py create mode 100644 solutions/1731. The Number of Employees Which Report to Each Employee/1731.sql create mode 100644 solutions/1732. Find the Highest Altitude/1732.cpp create mode 100644 solutions/1732. Find the Highest Altitude/1732.java create mode 100644 solutions/1732. Find the Highest Altitude/1732.py create mode 100644 solutions/1733. Minimum Number of People to Teach/1733.cpp create mode 100644 solutions/1733. Minimum Number of People to Teach/1733.java create mode 100644 solutions/1733. Minimum Number of People to Teach/1733.py create mode 100644 solutions/1734. Decode XORed Permutation/1734.cpp create mode 100644 solutions/1734. Decode XORed Permutation/1734.java create mode 100644 solutions/1734. Decode XORed Permutation/1734.py create mode 100644 solutions/1735. Count Ways to Make Array With Product/1735.cpp create mode 100644 solutions/1735. Count Ways to Make Array With Product/1735.java create mode 100644 solutions/1735. Count Ways to Make Array With Product/1735.py create mode 100644 solutions/1736. Latest Time by Replacing Hidden Digits/1736.cpp create mode 100644 solutions/1736. Latest Time by Replacing Hidden Digits/1736.java create mode 100644 solutions/1736. Latest Time by Replacing Hidden Digits/1736.py create mode 100644 solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.cpp create mode 100644 solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.java create mode 100644 solutions/1738. Find Kth Largest XOR Coordinate Value/1738.cpp create mode 100644 solutions/1738. Find Kth Largest XOR Coordinate Value/1738.java create mode 100644 solutions/1739. Building Boxes/1739.cpp create mode 100644 solutions/1739. Building Boxes/1739.java create mode 100644 solutions/1739. Building Boxes/1739.py create mode 100644 solutions/174. Dungeon Game/174.cpp create mode 100644 solutions/174. Dungeon Game/174.java create mode 100644 solutions/174. Dungeon Game/174.py create mode 100644 solutions/1740. Find Distance in a Binary Tree/1740.cpp create mode 100644 solutions/1740. Find Distance in a Binary Tree/1740.java create mode 100644 solutions/1740. Find Distance in a Binary Tree/1740.py create mode 100644 solutions/1741. Find Total Time Spent by Each Employee/1741.sql create mode 100644 solutions/1742. Maximum Number of Balls in a Box/1742.cpp create mode 100644 solutions/1742. Maximum Number of Balls in a Box/1742.java create mode 100644 solutions/1742. Maximum Number of Balls in a Box/1742.py create mode 100644 solutions/1743. Restore the Array From Adjacent Pairs/1743.cpp create mode 100644 solutions/1743. Restore the Array From Adjacent Pairs/1743.java create mode 100644 solutions/1743. Restore the Array From Adjacent Pairs/1743.py create mode 100644 solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.cpp create mode 100644 solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.java create mode 100644 solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.py create mode 100644 solutions/1745. Palindrome Partitioning IV/1745-2.cpp create mode 100644 solutions/1745. Palindrome Partitioning IV/1745-2.java create mode 100644 solutions/1745. Palindrome Partitioning IV/1745-2.py create mode 100644 solutions/1745. Palindrome Partitioning IV/1745.cpp create mode 100644 solutions/1745. Palindrome Partitioning IV/1745.java create mode 100644 solutions/1745. Palindrome Partitioning IV/1745.py create mode 100644 solutions/1746. Maximum Subarray Sum After One Operation/1746.cpp create mode 100644 solutions/1746. Maximum Subarray Sum After One Operation/1746.java create mode 100644 solutions/1746. Maximum Subarray Sum After One Operation/1746.py create mode 100644 solutions/1747. Leetflex Banned Accounts/1747.sql create mode 100644 solutions/1748. Sum of Unique Elements/1748.cpp create mode 100644 solutions/1748. Sum of Unique Elements/1748.java create mode 100644 solutions/1748. Sum of Unique Elements/1748.py create mode 100644 solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.cpp create mode 100644 solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.java create mode 100644 solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.py create mode 100644 solutions/1749. Maximum Absolute Sum of Any Subarray/1749.cpp create mode 100644 solutions/1749. Maximum Absolute Sum of Any Subarray/1749.java create mode 100644 solutions/1749. Maximum Absolute Sum of Any Subarray/1749.py create mode 100644 solutions/175. Combine Two Tables/175.sql create mode 100644 solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.cpp create mode 100644 solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.java create mode 100644 solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.py create mode 100644 solutions/1751. Maximum Number of Events That Can Be Attended II/1751.cpp create mode 100644 solutions/1751. Maximum Number of Events That Can Be Attended II/1751.java create mode 100644 solutions/1751. Maximum Number of Events That Can Be Attended II/1751.py create mode 100644 solutions/1752. Check if Array Is Sorted and Rotated/1752.cpp create mode 100644 solutions/1752. Check if Array Is Sorted and Rotated/1752.java create mode 100644 solutions/1753. Maximum Score From Removing Stones/1753.cpp create mode 100644 solutions/1753. Maximum Score From Removing Stones/1753.java create mode 100644 solutions/1754. Largest Merge Of Two Strings/1754.cpp create mode 100644 solutions/1754. Largest Merge Of Two Strings/1754.java create mode 100644 solutions/1754. Largest Merge Of Two Strings/1754.py create mode 100644 solutions/1755. Closest Subsequence Sum/1755.cpp create mode 100644 solutions/1755. Closest Subsequence Sum/1755.java create mode 100644 solutions/1755. Closest Subsequence Sum/1755.py create mode 100644 solutions/1756. Design Most Recently Used Queue/1756.py create mode 100644 solutions/1757. Recyclable and Low Fat Products/1757.sql create mode 100644 solutions/1758. Minimum Changes To Make Alternating Binary String/1758.cpp create mode 100644 solutions/1758. Minimum Changes To Make Alternating Binary String/1758.java create mode 100644 solutions/1758. Minimum Changes To Make Alternating Binary String/1758.py create mode 100644 solutions/1759. Count Number of Homogenous Substrings/1759.cpp create mode 100644 solutions/1759. Count Number of Homogenous Substrings/1759.java create mode 100644 solutions/1759. Count Number of Homogenous Substrings/1759.py create mode 100644 solutions/176. Second Highest Salary/176.sql create mode 100644 solutions/1760. Minimum Limit of Balls in a Bag/1760.cpp create mode 100644 solutions/1760. Minimum Limit of Balls in a Bag/1760.java create mode 100644 solutions/1760. Minimum Limit of Balls in a Bag/1760.py create mode 100644 solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.cpp create mode 100644 solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.java create mode 100644 solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.py create mode 100644 solutions/1762. Buildings With an Ocean View/1762.cpp create mode 100644 solutions/1762. Buildings With an Ocean View/1762.java create mode 100644 solutions/1762. Buildings With an Ocean View/1762.py create mode 100644 solutions/1763. Longest Nice Substring/1763.cpp create mode 100644 solutions/1763. Longest Nice Substring/1763.java create mode 100644 solutions/1763. Longest Nice Substring/1763.py create mode 100644 solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.cpp create mode 100644 solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.java create mode 100644 solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.py create mode 100644 solutions/1765. Map of Highest Peak/1765.cpp create mode 100644 solutions/1765. Map of Highest Peak/1765.java create mode 100644 solutions/1765. Map of Highest Peak/1765.py create mode 100644 solutions/1766. Tree of Coprimes/1766.cpp create mode 100644 solutions/1766. Tree of Coprimes/1766.java create mode 100644 solutions/1766. Tree of Coprimes/1766.py create mode 100644 solutions/1767. Find the Subtasks That Did Not Execute/1767.sql create mode 100644 solutions/1768. Merge Strings Alternately/1768.cpp create mode 100644 solutions/1768. Merge Strings Alternately/1768.java create mode 100644 solutions/1768. Merge Strings Alternately/1768.py create mode 100644 solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.cpp create mode 100644 solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.java create mode 100644 solutions/177. Nth Highest Salary/177.sql create mode 100644 solutions/1770. Maximum Score from Performing Multiplication Operations/1770.cpp create mode 100644 solutions/1770. Maximum Score from Performing Multiplication Operations/1770.java create mode 100644 solutions/1770. Maximum Score from Performing Multiplication Operations/1770.py create mode 100644 solutions/1771. Maximize Palindrome Length From Subsequences/1771.cpp create mode 100644 solutions/1771. Maximize Palindrome Length From Subsequences/1771.java create mode 100644 solutions/1772. Sort Features by Popularity/1772.cpp create mode 100644 solutions/1772. Sort Features by Popularity/1772.java create mode 100644 solutions/1773. Count Items Matching a Rule/1773.cpp create mode 100644 solutions/1773. Count Items Matching a Rule/1773.java create mode 100644 solutions/1774. Closest Dessert Cost/1774.cpp create mode 100644 solutions/1774. Closest Dessert Cost/1774.java create mode 100644 solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.cpp create mode 100644 solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.java create mode 100644 solutions/1776. Car Fleet II/1776.cpp create mode 100644 solutions/1776. Car Fleet II/1776.java create mode 100644 solutions/1776. Car Fleet II/1776.py create mode 100644 solutions/1777. Product's Price for Each Store/1777.sql create mode 100644 solutions/1778. Shortest Path in a Hidden Grid/1778.cpp create mode 100644 solutions/1778. Shortest Path in a Hidden Grid/1778.java create mode 100644 solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.cpp create mode 100644 solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.java create mode 100644 solutions/178. Rank Scores/178.sql create mode 100644 solutions/1780. Check if Number is a Sum of Powers of Three/1780.cpp create mode 100644 solutions/1780. Check if Number is a Sum of Powers of Three/1780.java create mode 100644 solutions/1780. Check if Number is a Sum of Powers of Three/1780.py create mode 100644 solutions/1781. Sum of Beauty of All Substrings/1781.cpp create mode 100644 solutions/1781. Sum of Beauty of All Substrings/1781.java create mode 100644 solutions/1781. Sum of Beauty of All Substrings/1781.py create mode 100644 solutions/1782. Count Pairs Of Nodes/1782.cpp create mode 100644 solutions/1782. Count Pairs Of Nodes/1782.java create mode 100644 solutions/1782. Count Pairs Of Nodes/1782.py create mode 100644 solutions/1783. Grand Slam Titles/1783.sql create mode 100644 solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.cpp create mode 100644 solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.java create mode 100644 solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.py create mode 100644 solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.cpp create mode 100644 solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.java create mode 100644 solutions/1786. Number of Restricted Paths From First to Last Node/1786.cpp create mode 100644 solutions/1786. Number of Restricted Paths From First to Last Node/1786.java create mode 100644 solutions/1786. Number of Restricted Paths From First to Last Node/1786.py create mode 100644 solutions/1787. Make the XOR of All Segments Equal to Zero/1787.cpp create mode 100644 solutions/1787. Make the XOR of All Segments Equal to Zero/1787.java create mode 100644 solutions/1787. Make the XOR of All Segments Equal to Zero/1787.py create mode 100644 solutions/1788. Maximize the Beauty of the Garden/1788.cpp create mode 100644 solutions/1788. Maximize the Beauty of the Garden/1788.java create mode 100644 solutions/1788. Maximize the Beauty of the Garden/1788.py create mode 100644 solutions/1789. Primary Department for Each Employee/1789.sql create mode 100644 solutions/179. Largest Number/179.cpp create mode 100644 solutions/179. Largest Number/179.java create mode 100644 solutions/179. Largest Number/179.py create mode 100644 solutions/1790. Check if One String Swap Can Make Strings Equal/1790.cpp create mode 100644 solutions/1790. Check if One String Swap Can Make Strings Equal/1790.java create mode 100644 solutions/1790. Check if One String Swap Can Make Strings Equal/1790.py create mode 100644 solutions/1791. Find Center of Star Graph/1791.cpp create mode 100644 solutions/1791. Find Center of Star Graph/1791.java create mode 100644 solutions/1791. Find Center of Star Graph/1791.py create mode 100644 solutions/1792. Maximum Average Pass Ratio/1792.cpp create mode 100644 solutions/1792. Maximum Average Pass Ratio/1792.java create mode 100644 solutions/1792. Maximum Average Pass Ratio/1792.py create mode 100644 solutions/1793. Maximum Score of a Good Subarray/1793-2.cpp create mode 100644 solutions/1793. Maximum Score of a Good Subarray/1793-2.java create mode 100644 solutions/1793. Maximum Score of a Good Subarray/1793-2.py create mode 100644 solutions/1793. Maximum Score of a Good Subarray/1793.cpp create mode 100644 solutions/1793. Maximum Score of a Good Subarray/1793.java create mode 100644 solutions/1793. Maximum Score of a Good Subarray/1793.py create mode 100644 solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.cpp create mode 100644 solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.java create mode 100644 solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.py create mode 100644 solutions/1795. Rearrange Products Table/1795.sql create mode 100644 solutions/1796. Second Largest Digit in a String/1796.cpp create mode 100644 solutions/1796. Second Largest Digit in a String/1796.java create mode 100644 solutions/1796. Second Largest Digit in a String/1796.py create mode 100644 solutions/1797. Design Authentication Manager/1797.cpp create mode 100644 solutions/1797. Design Authentication Manager/1797.java create mode 100644 solutions/1797. Design Authentication Manager/1797.py create mode 100644 solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.cpp create mode 100644 solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.java create mode 100644 solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.py create mode 100644 solutions/1799. Maximize Score After N Operations/1799.cpp create mode 100644 solutions/1799. Maximize Score After N Operations/1799.java create mode 100644 solutions/1799. Maximize Score After N Operations/1799.py create mode 100644 solutions/18. 4Sum/18.cpp create mode 100644 solutions/18. 4Sum/18.java create mode 100644 solutions/18. 4Sum/18.py create mode 100644 solutions/180. Consecutive Numbers/180.sql create mode 100644 solutions/1800. Maximum Ascending Subarray Sum/1800.cpp create mode 100644 solutions/1800. Maximum Ascending Subarray Sum/1800.java create mode 100644 solutions/1800. Maximum Ascending Subarray Sum/1800.py create mode 100644 solutions/1801. Number of Orders in the Backlog/1801.cpp create mode 100644 solutions/1801. Number of Orders in the Backlog/1801.java create mode 100644 solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.cpp create mode 100644 solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.java create mode 100644 solutions/1803. Count Pairs With XOR in a Range/1803.cpp create mode 100644 solutions/1803. Count Pairs With XOR in a Range/1803.java create mode 100644 solutions/1804. Implement Trie II (Prefix Tree)/1804.cpp create mode 100644 solutions/1804. Implement Trie II (Prefix Tree)/1804.java create mode 100644 solutions/1805. Number of Different Integers in a String/1805-2.py create mode 100644 solutions/1805. Number of Different Integers in a String/1805.cpp create mode 100644 solutions/1805. Number of Different Integers in a String/1805.java create mode 100644 solutions/1805. Number of Different Integers in a String/1805.py create mode 100644 solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.cpp create mode 100644 solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.java create mode 100644 solutions/1807. Evaluate the Bracket Pairs of a String/1807.cpp create mode 100644 solutions/1807. Evaluate the Bracket Pairs of a String/1807.java create mode 100644 solutions/1808. Maximize Number of Nice Divisors/1808.cpp create mode 100644 solutions/1808. Maximize Number of Nice Divisors/1808.java create mode 100644 solutions/1809. Ad-Free Sessions/1809.sql create mode 100644 solutions/181. Employees Earning More Than Their Managers/181.sql create mode 100644 solutions/1810. Minimum Path Cost in a Hidden Grid/1810.cpp create mode 100644 solutions/1810. Minimum Path Cost in a Hidden Grid/1810.java create mode 100644 solutions/1811. Find Interview Candidates/1811.sql create mode 100644 solutions/1812. Determine Color of a Chessboard Square/1812.cpp create mode 100644 solutions/1812. Determine Color of a Chessboard Square/1812.java create mode 100644 solutions/1812. Determine Color of a Chessboard Square/1812.py create mode 100644 solutions/1813. Sentence Similarity III/1813.cpp create mode 100644 solutions/1813. Sentence Similarity III/1813.java create mode 100644 solutions/1813. Sentence Similarity III/1813.py create mode 100644 solutions/1814. Count Nice Pairs in an Array/1814.cpp create mode 100644 solutions/1814. Count Nice Pairs in an Array/1814.java create mode 100644 solutions/1814. Count Nice Pairs in an Array/1814.py create mode 100644 solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.cpp create mode 100644 solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.java create mode 100644 solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.py create mode 100644 solutions/1816. Truncate Sentence/1816.cpp create mode 100644 solutions/1816. Truncate Sentence/1816.java create mode 100644 solutions/1816. Truncate Sentence/1816.py create mode 100644 solutions/1817. Finding the Users Active Minutes/1817.cpp create mode 100644 solutions/1817. Finding the Users Active Minutes/1817.java create mode 100644 solutions/1817. Finding the Users Active Minutes/1817.py create mode 100644 solutions/1818. Minimum Absolute Sum Difference/1818.cpp create mode 100644 solutions/1818. Minimum Absolute Sum Difference/1818.java create mode 100644 solutions/1818. Minimum Absolute Sum Difference/1818.py create mode 100644 solutions/1819. Number of Different Subsequences GCDs/1819.cpp create mode 100644 solutions/1819. Number of Different Subsequences GCDs/1819.java create mode 100644 solutions/182. Duplicate Emails/182.sql create mode 100644 solutions/1820. Maximum Number of Accepted Invitations/1820.cpp create mode 100644 solutions/1820. Maximum Number of Accepted Invitations/1820.java create mode 100644 solutions/1820. Maximum Number of Accepted Invitations/1820.py create mode 100644 solutions/1821. Find Customers With Positive Revenue this Year/1821.sql create mode 100644 solutions/1822. Sign of the Product of an Array/1822.cpp create mode 100644 solutions/1822. Sign of the Product of an Array/1822.java create mode 100644 solutions/1822. Sign of the Product of an Array/1822.py create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823-2.cpp create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823-2.java create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823-2.py create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823-3.cpp create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823-3.java create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823-3.py create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823.cpp create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823.java create mode 100644 solutions/1823. Find the Winner of the Circular Game/1823.py create mode 100644 solutions/1824. Minimum Sideway Jumps/1824.cpp create mode 100644 solutions/1824. Minimum Sideway Jumps/1824.java create mode 100644 solutions/1824. Minimum Sideway Jumps/1824.py create mode 100644 solutions/1825. Finding MK Average/1825-2.cpp create mode 100644 solutions/1825. Finding MK Average/1825-2.java create mode 100644 solutions/1825. Finding MK Average/1825.cpp create mode 100644 solutions/1825. Finding MK Average/1825.java create mode 100644 solutions/1826. Faulty Sensor/1826.cpp create mode 100644 solutions/1826. Faulty Sensor/1826.java create mode 100644 solutions/1826. Faulty Sensor/1826.py create mode 100644 solutions/1827. Minimum Operations to Make the Array Increasing/1827.cpp create mode 100644 solutions/1827. Minimum Operations to Make the Array Increasing/1827.java create mode 100644 solutions/1827. Minimum Operations to Make the Array Increasing/1827.py create mode 100644 solutions/1828. Queries on Number of Points Inside a Circle/1828.cpp create mode 100644 solutions/1828. Queries on Number of Points Inside a Circle/1828.java create mode 100644 solutions/1828. Queries on Number of Points Inside a Circle/1828.py create mode 100644 solutions/1829. Maximum XOR for Each Query/1829.cpp create mode 100644 solutions/1829. Maximum XOR for Each Query/1829.java create mode 100644 solutions/1829. Maximum XOR for Each Query/1829.py create mode 100644 solutions/183. Customers Who Never Order/183.sql create mode 100644 solutions/1830. Minimum Number of Operations to Make String Sorted/1830.cpp create mode 100644 solutions/1830. Minimum Number of Operations to Make String Sorted/1830.java create mode 100644 solutions/1830. Minimum Number of Operations to Make String Sorted/1830.py create mode 100644 solutions/1831. Maximum Transaction Each Day/1831.sql create mode 100644 solutions/1832. Check if the Sentence Is Pangram/1832-2.cpp create mode 100644 solutions/1832. Check if the Sentence Is Pangram/1832-2.java create mode 100644 solutions/1832. Check if the Sentence Is Pangram/1832-2.py create mode 100644 solutions/1832. Check if the Sentence Is Pangram/1832.cpp create mode 100644 solutions/1832. Check if the Sentence Is Pangram/1832.java create mode 100644 solutions/1832. Check if the Sentence Is Pangram/1832.py create mode 100644 solutions/1833. Maximum Ice Cream Bars/1833.cpp create mode 100644 solutions/1833. Maximum Ice Cream Bars/1833.java create mode 100644 solutions/1833. Maximum Ice Cream Bars/1833.py create mode 100644 solutions/1834. Single-Threaded CPU/1834.cpp create mode 100644 solutions/1834. Single-Threaded CPU/1834.java create mode 100644 solutions/1834. Single-Threaded CPU/1834.py create mode 100644 solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.cpp create mode 100644 solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.java create mode 100644 solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.py create mode 100644 solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.cpp create mode 100644 solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.java create mode 100644 solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.py create mode 100644 solutions/1837. Sum of Digits in Base K/1837.cpp create mode 100644 solutions/1837. Sum of Digits in Base K/1837.java create mode 100644 solutions/1837. Sum of Digits in Base K/1837.py create mode 100644 solutions/1838. Frequency of the Most Frequent Element/1838.cpp create mode 100644 solutions/1838. Frequency of the Most Frequent Element/1838.java create mode 100644 solutions/1838. Frequency of the Most Frequent Element/1838.py create mode 100644 solutions/1839. Longest Substring Of All Vowels in Order/1839.cpp create mode 100644 solutions/1839. Longest Substring Of All Vowels in Order/1839.java create mode 100644 solutions/1839. Longest Substring Of All Vowels in Order/1839.py create mode 100644 solutions/184. Department Highest Salary/184.sql create mode 100644 solutions/1840. Maximum Building Height/1840.cpp create mode 100644 solutions/1840. Maximum Building Height/1840.java create mode 100644 solutions/1840. Maximum Building Height/1840.py create mode 100644 solutions/1841. League Statistics/1841.sql create mode 100644 solutions/1842. Next Palindrome Using Same Digits/1842.cpp create mode 100644 solutions/1842. Next Palindrome Using Same Digits/1842.java create mode 100644 solutions/1842. Next Palindrome Using Same Digits/1842.py create mode 100644 solutions/1843. Suspicious Bank Accounts/1843.sql create mode 100644 solutions/1844. Replace All Digits with Characters/1844.cpp create mode 100644 solutions/1844. Replace All Digits with Characters/1844.java create mode 100644 solutions/1844. Replace All Digits with Characters/1844.py create mode 100644 solutions/1845. Seat Reservation Manager/1845.cpp create mode 100644 solutions/1845. Seat Reservation Manager/1845.java create mode 100644 solutions/1845. Seat Reservation Manager/1845.py create mode 100644 solutions/1846. Maximum Element After Decreasing and Rearranging/1846.cpp create mode 100644 solutions/1846. Maximum Element After Decreasing and Rearranging/1846.java create mode 100644 solutions/1846. Maximum Element After Decreasing and Rearranging/1846.py create mode 100644 solutions/1847. Closest Room/1847.cpp create mode 100644 solutions/1847. Closest Room/1847.java create mode 100644 solutions/1847. Closest Room/1847.py create mode 100644 solutions/1848. Minimum Distance to the Target Element/1848.cpp create mode 100644 solutions/1848. Minimum Distance to the Target Element/1848.java create mode 100644 solutions/1848. Minimum Distance to the Target Element/1848.py create mode 100644 solutions/1849. Splitting a String Into Descending Consecutive Values/1849.cpp create mode 100644 solutions/1849. Splitting a String Into Descending Consecutive Values/1849.java create mode 100644 solutions/1849. Splitting a String Into Descending Consecutive Values/1849.py create mode 100644 solutions/185. Department Top Three Salaries/185.sql create mode 100644 solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.cpp create mode 100644 solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.java create mode 100644 solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.py create mode 100644 solutions/1851. Minimum Interval to Include Each Query/1851.cpp create mode 100644 solutions/1851. Minimum Interval to Include Each Query/1851.java create mode 100644 solutions/1852. Distinct Numbers in Each Subarray/1852.cpp create mode 100644 solutions/1852. Distinct Numbers in Each Subarray/1852.java create mode 100644 solutions/1852. Distinct Numbers in Each Subarray/1852.py create mode 100644 solutions/1853. Convert Date Format/1853.sql create mode 100644 solutions/1854. Maximum Population Year/1854.cpp create mode 100644 solutions/1854. Maximum Population Year/1854.java create mode 100644 solutions/1854. Maximum Population Year/1854.py create mode 100644 solutions/1855. Maximum Distance Between a Pair of Values/1855-2.cpp create mode 100644 solutions/1855. Maximum Distance Between a Pair of Values/1855-2.java create mode 100644 solutions/1855. Maximum Distance Between a Pair of Values/1855-2.py create mode 100644 solutions/1855. Maximum Distance Between a Pair of Values/1855.cpp create mode 100644 solutions/1855. Maximum Distance Between a Pair of Values/1855.java create mode 100644 solutions/1855. Maximum Distance Between a Pair of Values/1855.py create mode 100644 solutions/1856. Maximum Subarray Min-Product/1856.cpp create mode 100644 solutions/1856. Maximum Subarray Min-Product/1856.java create mode 100644 solutions/1856. Maximum Subarray Min-Product/1856.py create mode 100644 solutions/1857. Largest Color Value in a Directed Graph/1857.cpp create mode 100644 solutions/1857. Largest Color Value in a Directed Graph/1857.java create mode 100644 solutions/1857. Largest Color Value in a Directed Graph/1857.py create mode 100644 solutions/1858. Longest Word With All Prefixes/1858.cpp create mode 100644 solutions/1858. Longest Word With All Prefixes/1858.java create mode 100644 solutions/1858. Longest Word With All Prefixes/1858.py create mode 100644 solutions/1859. Sorting the Sentence/1859.cpp create mode 100644 solutions/1859. Sorting the Sentence/1859.java create mode 100644 solutions/1859. Sorting the Sentence/1859.py create mode 100644 solutions/186. Reverse Words in a String II/186.cpp create mode 100644 solutions/186. Reverse Words in a String II/186.java create mode 100644 solutions/186. Reverse Words in a String II/186.py create mode 100644 solutions/1860. Incremental Memory Leak/1860.cpp create mode 100644 solutions/1860. Incremental Memory Leak/1860.java create mode 100644 solutions/1860. Incremental Memory Leak/1860.py create mode 100644 solutions/1861. Rotating the Box/1861.cpp create mode 100644 solutions/1861. Rotating the Box/1861.java create mode 100644 solutions/1861. Rotating the Box/1861.py create mode 100644 solutions/1862. Sum of Floored Pairs/1862.cpp create mode 100644 solutions/1862. Sum of Floored Pairs/1862.java create mode 100644 solutions/1862. Sum of Floored Pairs/1862.py create mode 100644 solutions/1863. Sum of All Subset XOR Totals/1863-2.cpp create mode 100644 solutions/1863. Sum of All Subset XOR Totals/1863-2.java create mode 100644 solutions/1863. Sum of All Subset XOR Totals/1863-2.py create mode 100644 solutions/1863. Sum of All Subset XOR Totals/1863.cpp create mode 100644 solutions/1863. Sum of All Subset XOR Totals/1863.java create mode 100644 solutions/1863. Sum of All Subset XOR Totals/1863.py create mode 100644 solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.cpp create mode 100644 solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.java create mode 100644 solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.py create mode 100644 solutions/1865. Finding Pairs With a Certain Sum/1865.cpp create mode 100644 solutions/1865. Finding Pairs With a Certain Sum/1865.java create mode 100644 solutions/1865. Finding Pairs With a Certain Sum/1865.py create mode 100644 solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.cpp create mode 100644 solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.java create mode 100644 solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.py create mode 100644 solutions/1867. Orders With Maximum Quantity Above Average/1867.sql create mode 100644 solutions/1868. Product of Two Run-Length Encoded Arrays/1868.cpp create mode 100644 solutions/1868. Product of Two Run-Length Encoded Arrays/1868.java create mode 100644 solutions/1868. Product of Two Run-Length Encoded Arrays/1868.py create mode 100644 solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.cpp create mode 100644 solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.java create mode 100644 solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.py create mode 100644 solutions/187. Repeated DNA Sequences/187.cpp create mode 100644 solutions/187. Repeated DNA Sequences/187.java create mode 100644 solutions/187. Repeated DNA Sequences/187.py create mode 100644 solutions/1870. Minimum Speed to Arrive on Time/1870.cpp create mode 100644 solutions/1870. Minimum Speed to Arrive on Time/1870.java create mode 100644 solutions/1870. Minimum Speed to Arrive on Time/1870.py create mode 100644 solutions/1871. Jump Game VII/1871.cpp create mode 100644 solutions/1871. Jump Game VII/1871.java create mode 100644 solutions/1871. Jump Game VII/1871.py create mode 100644 solutions/1872. Stone Game VIII/1872.cpp create mode 100644 solutions/1872. Stone Game VIII/1872.java create mode 100644 solutions/1872. Stone Game VIII/1872.py create mode 100644 solutions/1873. Calculate Special Bonus/1873.sql create mode 100644 solutions/1874. Minimize Product Sum of Two Arrays/1874.cpp create mode 100644 solutions/1874. Minimize Product Sum of Two Arrays/1874.java create mode 100644 solutions/1874. Minimize Product Sum of Two Arrays/1874.py create mode 100644 solutions/1875. Group Employees of the Same Salary/1875.sql create mode 100644 solutions/1876. Substrings of Size Three with Distinct Characters/1876.cpp create mode 100644 solutions/1876. Substrings of Size Three with Distinct Characters/1876.java create mode 100644 solutions/1876. Substrings of Size Three with Distinct Characters/1876.py create mode 100644 solutions/1877. Minimize Maximum Pair Sum in Array/1877.cpp create mode 100644 solutions/1877. Minimize Maximum Pair Sum in Array/1877.java create mode 100644 solutions/1877. Minimize Maximum Pair Sum in Array/1877.py create mode 100644 solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.cpp create mode 100644 solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.java create mode 100644 solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.py create mode 100644 solutions/1879. Minimum XOR Sum of Two Arrays/1879.cpp create mode 100644 solutions/1879. Minimum XOR Sum of Two Arrays/1879.java create mode 100644 solutions/1879. Minimum XOR Sum of Two Arrays/1879.py create mode 100644 solutions/188. Best Time to Buy and Sell Stock IV/188.cpp create mode 100644 solutions/188. Best Time to Buy and Sell Stock IV/188.java create mode 100644 solutions/188. Best Time to Buy and Sell Stock IV/188.py create mode 100644 solutions/1880. Check if Word Equals Summation of Two Words/1880.cpp create mode 100644 solutions/1880. Check if Word Equals Summation of Two Words/1880.java create mode 100644 solutions/1880. Check if Word Equals Summation of Two Words/1880.py create mode 100644 solutions/1881. Maximum Value after Insertion/1881.cpp create mode 100644 solutions/1881. Maximum Value after Insertion/1881.java create mode 100644 solutions/1881. Maximum Value after Insertion/1881.py create mode 100644 solutions/1882. Process Tasks Using Servers/1882.cpp create mode 100644 solutions/1882. Process Tasks Using Servers/1882.java create mode 100644 solutions/1882. Process Tasks Using Servers/1882.py create mode 100644 solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.cpp create mode 100644 solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.java create mode 100644 solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.py create mode 100644 solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.cpp create mode 100644 solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.java create mode 100644 solutions/1885. Count Pairs in Two Arrays/1885.cpp create mode 100644 solutions/1885. Count Pairs in Two Arrays/1885.java create mode 100644 solutions/1885. Count Pairs in Two Arrays/1885.py create mode 100644 solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.cpp create mode 100644 solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.java create mode 100644 solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.py create mode 100644 solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.cpp create mode 100644 solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.java create mode 100644 solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.py create mode 100644 solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.cpp create mode 100644 solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.java create mode 100644 solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.py create mode 100644 solutions/1889. Minimum Space Wasted From Packaging/1889.cpp create mode 100644 solutions/1889. Minimum Space Wasted From Packaging/1889.java create mode 100644 solutions/1889. Minimum Space Wasted From Packaging/1889.py create mode 100644 solutions/189. Rotate Array/189.cpp create mode 100644 solutions/189. Rotate Array/189.java create mode 100644 solutions/189. Rotate Array/189.py create mode 100644 solutions/1890. The Latest Login in 2020/1890.sql create mode 100644 solutions/1891. Cutting Ribbons/1891.cpp create mode 100644 solutions/1891. Cutting Ribbons/1891.java create mode 100644 solutions/1891. Cutting Ribbons/1891.py create mode 100644 solutions/1892. Page Recommendations II/1892.sql create mode 100644 solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.cpp create mode 100644 solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.java create mode 100644 solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.py create mode 100644 solutions/1893. Check if All the Integers in a Range Are Covered/1893.cpp create mode 100644 solutions/1893. Check if All the Integers in a Range Are Covered/1893.java create mode 100644 solutions/1893. Check if All the Integers in a Range Are Covered/1893.py create mode 100644 solutions/1894. Find the Student that Will Replace the Chalk/1894.cpp create mode 100644 solutions/1894. Find the Student that Will Replace the Chalk/1894.java create mode 100644 solutions/1894. Find the Student that Will Replace the Chalk/1894.py create mode 100644 solutions/1895. Largest Magic Square/1895.cpp create mode 100644 solutions/1895. Largest Magic Square/1895.java create mode 100644 solutions/1895. Largest Magic Square/1895.py create mode 100644 solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.cpp create mode 100644 solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.java create mode 100644 solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.py create mode 100644 solutions/1897. Redistribute Characters to Make All Strings Equal/1897.cpp create mode 100644 solutions/1897. Redistribute Characters to Make All Strings Equal/1897.java create mode 100644 solutions/1897. Redistribute Characters to Make All Strings Equal/1897.py create mode 100644 solutions/1898. Maximum Number of Removable Characters/1898.cpp create mode 100644 solutions/1898. Maximum Number of Removable Characters/1898.java create mode 100644 solutions/1898. Maximum Number of Removable Characters/1898.py create mode 100644 solutions/1899. Merge Triplets to Form Target Triplet/1899.cpp create mode 100644 solutions/1899. Merge Triplets to Form Target Triplet/1899.java create mode 100644 solutions/1899. Merge Triplets to Form Target Triplet/1899.py create mode 100644 solutions/19. Remove Nth Node From End of List/19.cpp create mode 100644 solutions/19. Remove Nth Node From End of List/19.java create mode 100644 solutions/19. Remove Nth Node From End of List/19.py create mode 100644 solutions/190. Reverse Bits/190.cpp create mode 100644 solutions/190. Reverse Bits/190.java create mode 100644 solutions/190. Reverse Bits/190.py create mode 100644 solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.cpp create mode 100644 solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.java create mode 100644 solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.py create mode 100644 solutions/1901. Find a Peak Element II/1901.cpp create mode 100644 solutions/1901. Find a Peak Element II/1901.java create mode 100644 solutions/1901. Find a Peak Element II/1901.py create mode 100644 solutions/1902. Depth of BST Given Insertion Order/1902.cpp create mode 100644 solutions/1902. Depth of BST Given Insertion Order/1902.java create mode 100644 solutions/1903. Largest Odd Number in String/1903.cpp create mode 100644 solutions/1903. Largest Odd Number in String/1903.java create mode 100644 solutions/1903. Largest Odd Number in String/1903.py create mode 100644 solutions/1904. The Number of Full Rounds You Have Played/1904.cpp create mode 100644 solutions/1904. The Number of Full Rounds You Have Played/1904.java create mode 100644 solutions/1904. The Number of Full Rounds You Have Played/1904.py create mode 100644 solutions/1905. Count Sub Islands/1905.cpp create mode 100644 solutions/1905. Count Sub Islands/1905.java create mode 100644 solutions/1905. Count Sub Islands/1905.py create mode 100644 solutions/1906. Minimum Absolute Difference Queries/1906.cpp create mode 100644 solutions/1906. Minimum Absolute Difference Queries/1906.java create mode 100644 solutions/1906. Minimum Absolute Difference Queries/1906.py create mode 100644 solutions/1907. Count Salary Categories/1907.sql create mode 100644 solutions/1908. Game of Nim/1908.cpp create mode 100644 solutions/1908. Game of Nim/1908.java create mode 100644 solutions/1908. Game of Nim/1908.py create mode 100644 solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.cpp create mode 100644 solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.java create mode 100644 solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.py create mode 100644 solutions/191. Number of 1 Bits/191-2.cpp create mode 100644 solutions/191. Number of 1 Bits/191-2.java create mode 100644 solutions/191. Number of 1 Bits/191-2.py create mode 100644 solutions/191. Number of 1 Bits/191.cpp create mode 100644 solutions/191. Number of 1 Bits/191.java create mode 100644 solutions/191. Number of 1 Bits/191.py create mode 100644 solutions/1910. Remove All Occurrences of a Substring/1910.cpp create mode 100644 solutions/1910. Remove All Occurrences of a Substring/1910.java create mode 100644 solutions/1910. Remove All Occurrences of a Substring/1910.py create mode 100644 solutions/1911. Maximum Alternating Subsequence Sum/1911.cpp create mode 100644 solutions/1911. Maximum Alternating Subsequence Sum/1911.java create mode 100644 solutions/1911. Maximum Alternating Subsequence Sum/1911.py create mode 100644 solutions/1912. Design Movie Rental System/1912.cpp create mode 100644 solutions/1912. Design Movie Rental System/1912.java create mode 100644 solutions/1912. Design Movie Rental System/1912.py create mode 100644 solutions/1913. Maximum Product Difference Between Two Pairs/1913.cpp create mode 100644 solutions/1913. Maximum Product Difference Between Two Pairs/1913.java create mode 100644 solutions/1913. Maximum Product Difference Between Two Pairs/1913.py create mode 100644 solutions/1914. Cyclically Rotating a Grid/1914.cpp create mode 100644 solutions/1914. Cyclically Rotating a Grid/1914.java create mode 100644 solutions/1914. Cyclically Rotating a Grid/1914.py create mode 100644 solutions/1915. Number of Wonderful Substrings/1915.cpp create mode 100644 solutions/1915. Number of Wonderful Substrings/1915.java create mode 100644 solutions/1915. Number of Wonderful Substrings/1915.py create mode 100644 solutions/1916. Count Ways to Build Rooms in an Ant Colony/1916.py create mode 100644 solutions/1917. Leetcodify Friends Recommendations/1917.sql create mode 100644 solutions/1918. Kth Smallest Subarray Sum/1918.cpp create mode 100644 solutions/1918. Kth Smallest Subarray Sum/1918.java create mode 100644 solutions/1918. Kth Smallest Subarray Sum/1918.py create mode 100644 solutions/1919. Leetcodify Similar Friends/1919.sql create mode 100644 solutions/192. Word Frequency/192.sh create mode 100644 solutions/1920. Build Array from Permutation/1920.cpp create mode 100644 solutions/1920. Build Array from Permutation/1920.java create mode 100644 solutions/1920. Build Array from Permutation/1920.py create mode 100644 solutions/1921. Eliminate Maximum Number of Monsters/1921.cpp create mode 100644 solutions/1921. Eliminate Maximum Number of Monsters/1921.java create mode 100644 solutions/1921. Eliminate Maximum Number of Monsters/1921.py create mode 100644 solutions/1922. Count Good Numbers/1922.cpp create mode 100644 solutions/1922. Count Good Numbers/1922.java create mode 100644 solutions/1922. Count Good Numbers/1922.py create mode 100644 solutions/1923. Longest Common Subpath/1923.cpp create mode 100644 solutions/1923. Longest Common Subpath/1923.java create mode 100644 solutions/1923. Longest Common Subpath/1923.py create mode 100644 solutions/1924. Erect the Fence II/1924.cpp create mode 100644 solutions/1924. Erect the Fence II/1924.java create mode 100644 solutions/1924. Erect the Fence II/1924.py create mode 100644 solutions/1925. Count Square Sum Triples/1925.cpp create mode 100644 solutions/1925. Count Square Sum Triples/1925.java create mode 100644 solutions/1925. Count Square Sum Triples/1925.py create mode 100644 solutions/1926. Nearest Exit from Entrance in Maze/1926.cpp create mode 100644 solutions/1926. Nearest Exit from Entrance in Maze/1926.java create mode 100644 solutions/1926. Nearest Exit from Entrance in Maze/1926.py create mode 100644 solutions/1927. Sum Game/1927.cpp create mode 100644 solutions/1927. Sum Game/1927.java create mode 100644 solutions/1927. Sum Game/1927.py create mode 100644 solutions/1928. Minimum Cost to Reach Destination in Time/1928.cpp create mode 100644 solutions/1928. Minimum Cost to Reach Destination in Time/1928.java create mode 100644 solutions/1928. Minimum Cost to Reach Destination in Time/1928.py create mode 100644 solutions/1929. Concatenation of Array/1929.cpp create mode 100644 solutions/1929. Concatenation of Array/1929.java create mode 100644 solutions/1929. Concatenation of Array/1929.py create mode 100644 solutions/193. Valid Phone Numbers/193.sh create mode 100644 solutions/1930. Unique Length-3 Palindromic Subsequences/1930.cpp create mode 100644 solutions/1930. Unique Length-3 Palindromic Subsequences/1930.java create mode 100644 solutions/1930. Unique Length-3 Palindromic Subsequences/1930.py create mode 100644 solutions/1931. Painting a Grid With Three Different Colors/1931.cpp create mode 100644 solutions/1931. Painting a Grid With Three Different Colors/1931.java create mode 100644 solutions/1931. Painting a Grid With Three Different Colors/1931.py create mode 100644 solutions/1932. Merge BSTs to Create Single BST/1932.cpp create mode 100644 solutions/1932. Merge BSTs to Create Single BST/1932.java create mode 100644 solutions/1932. Merge BSTs to Create Single BST/1932.py create mode 100644 solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.cpp create mode 100644 solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.java create mode 100644 solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.py create mode 100644 solutions/1934. Confirmation Rate/1934.sql create mode 100644 solutions/1935. Maximum Number of Words You Can Type/1935.cpp create mode 100644 solutions/1935. Maximum Number of Words You Can Type/1935.java create mode 100644 solutions/1935. Maximum Number of Words You Can Type/1935.py create mode 100644 solutions/1936. Add Minimum Number of Rungs/1936.cpp create mode 100644 solutions/1936. Add Minimum Number of Rungs/1936.java create mode 100644 solutions/1936. Add Minimum Number of Rungs/1936.py create mode 100644 solutions/1937. Maximum Number of Points with Cost/1937.cpp create mode 100644 solutions/1937. Maximum Number of Points with Cost/1937.java create mode 100644 solutions/1937. Maximum Number of Points with Cost/1937.py create mode 100644 solutions/1938. Maximum Genetic Difference Query/1938.cpp create mode 100644 solutions/1938. Maximum Genetic Difference Query/1938.java create mode 100644 solutions/1938. Maximum Genetic Difference Query/1938.py create mode 100644 solutions/1939. Users That Actively Request Confirmation Messages/1939.sql create mode 100644 solutions/194. Transpose File/194.sh create mode 100644 solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940-2.py create mode 100644 solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.cpp create mode 100644 solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.java create mode 100644 solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.py create mode 100644 solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.cpp create mode 100644 solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.java create mode 100644 solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.py create mode 100644 solutions/1942. The Number of the Smallest Unoccupied Chair/1942.cpp create mode 100644 solutions/1942. The Number of the Smallest Unoccupied Chair/1942.java create mode 100644 solutions/1942. The Number of the Smallest Unoccupied Chair/1942.py create mode 100644 solutions/1943. Describe the Painting/1943.cpp create mode 100644 solutions/1943. Describe the Painting/1943.java create mode 100644 solutions/1943. Describe the Painting/1943.py create mode 100644 solutions/1944. Number of Visible People in a Queue/1944.cpp create mode 100644 solutions/1944. Number of Visible People in a Queue/1944.java create mode 100644 solutions/1944. Number of Visible People in a Queue/1944.py create mode 100644 solutions/1945. Sum of Digits of String After Convert/1945.cpp create mode 100644 solutions/1945. Sum of Digits of String After Convert/1945.java create mode 100644 solutions/1945. Sum of Digits of String After Convert/1945.py create mode 100644 solutions/1946. Largest Number After Mutating Substring/1946.cpp create mode 100644 solutions/1946. Largest Number After Mutating Substring/1946.java create mode 100644 solutions/1946. Largest Number After Mutating Substring/1946.py create mode 100644 solutions/1947. Maximum Compatibility Score Sum/1947.cpp create mode 100644 solutions/1947. Maximum Compatibility Score Sum/1947.java create mode 100644 solutions/1947. Maximum Compatibility Score Sum/1947.py create mode 100644 solutions/1948. Delete Duplicate Folders in System/1948.cpp create mode 100644 solutions/1948. Delete Duplicate Folders in System/1948.java create mode 100644 solutions/1948. Delete Duplicate Folders in System/1948.py create mode 100644 solutions/1949. Strong Friendship/1949.sql create mode 100644 solutions/195. Tenth Line/195.sh create mode 100644 solutions/1950. Maximum of Minimum Values in All Subarrays/1950.cpp create mode 100644 solutions/1950. Maximum of Minimum Values in All Subarrays/1950.java create mode 100644 solutions/1950. Maximum of Minimum Values in All Subarrays/1950.py create mode 100644 solutions/1951. All the Pairs With the Maximum Number of Common Followers/1951.sql create mode 100644 solutions/1952. Three Divisors/1952.cpp create mode 100644 solutions/1952. Three Divisors/1952.java create mode 100644 solutions/1952. Three Divisors/1952.py create mode 100644 solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.cpp create mode 100644 solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.java create mode 100644 solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.py create mode 100644 solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.cpp create mode 100644 solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.java create mode 100644 solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.py create mode 100644 solutions/1955. Count Number of Special Subsequences/1955-2.cpp create mode 100644 solutions/1955. Count Number of Special Subsequences/1955-2.java create mode 100644 solutions/1955. Count Number of Special Subsequences/1955-2.py create mode 100644 solutions/1955. Count Number of Special Subsequences/1955-3.cpp create mode 100644 solutions/1955. Count Number of Special Subsequences/1955-3.java create mode 100644 solutions/1955. Count Number of Special Subsequences/1955-3.py create mode 100644 solutions/1955. Count Number of Special Subsequences/1955.cpp create mode 100644 solutions/1955. Count Number of Special Subsequences/1955.java create mode 100644 solutions/1955. Count Number of Special Subsequences/1955.py create mode 100644 solutions/1956. Minimum Time For K Virus Variants to Spread/1956.cpp create mode 100644 solutions/1956. Minimum Time For K Virus Variants to Spread/1956.java create mode 100644 solutions/1956. Minimum Time For K Virus Variants to Spread/1956.py create mode 100644 solutions/1957. Delete Characters to Make Fancy String/1957.cpp create mode 100644 solutions/1957. Delete Characters to Make Fancy String/1957.java create mode 100644 solutions/1957. Delete Characters to Make Fancy String/1957.py create mode 100644 solutions/1958. Check if Move is Legal/1958.cpp create mode 100644 solutions/1958. Check if Move is Legal/1958.java create mode 100644 solutions/1958. Check if Move is Legal/1958.py create mode 100644 solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.cpp create mode 100644 solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.java create mode 100644 solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.py create mode 100644 solutions/196. Delete Duplicate Emails/196.sql create mode 100644 solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.cpp create mode 100644 solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.java create mode 100644 solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.py create mode 100644 solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.cpp create mode 100644 solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.java create mode 100644 solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.py create mode 100644 solutions/1961. Check If String Is a Prefix of Array/1961.cpp create mode 100644 solutions/1961. Check If String Is a Prefix of Array/1961.java create mode 100644 solutions/1961. Check If String Is a Prefix of Array/1961.py create mode 100644 solutions/1962. Remove Stones to Minimize the Total/1962.cpp create mode 100644 solutions/1962. Remove Stones to Minimize the Total/1962.java create mode 100644 solutions/1962. Remove Stones to Minimize the Total/1962.py create mode 100644 solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.cpp create mode 100644 solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.java create mode 100644 solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.py create mode 100644 solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.cpp create mode 100644 solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.java create mode 100644 solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.py create mode 100644 solutions/1965. Employees With Missing Information/1965.sql create mode 100644 solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.cpp create mode 100644 solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.java create mode 100644 solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.py create mode 100644 solutions/1967. Number of Strings That Appear as Substrings in Word/1967.cpp create mode 100644 solutions/1967. Number of Strings That Appear as Substrings in Word/1967.java create mode 100644 solutions/1967. Number of Strings That Appear as Substrings in Word/1967.py create mode 100644 solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.cpp create mode 100644 solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.java create mode 100644 solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.py create mode 100644 solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.cpp create mode 100644 solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.java create mode 100644 solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.py create mode 100644 solutions/197. Rising Temperature/197.sql create mode 100644 solutions/1970. Last Day Where You Can Still Cross/1970.cpp create mode 100644 solutions/1970. Last Day Where You Can Still Cross/1970.java create mode 100644 solutions/1970. Last Day Where You Can Still Cross/1970.py create mode 100644 solutions/1971. Find if Path Exists in Graph/1971.cpp create mode 100644 solutions/1971. Find if Path Exists in Graph/1971.java create mode 100644 solutions/1971. Find if Path Exists in Graph/1971.py create mode 100644 solutions/1972. First and Last Call On the Same Day/1972.sql create mode 100644 solutions/1973. Count Nodes Equal to Sum of Descendants/1973.cpp create mode 100644 solutions/1973. Count Nodes Equal to Sum of Descendants/1973.java create mode 100644 solutions/1973. Count Nodes Equal to Sum of Descendants/1973.py create mode 100644 solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.cpp create mode 100644 solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.java create mode 100644 solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.py create mode 100644 solutions/1975. Maximum Matrix Sum/1975.cpp create mode 100644 solutions/1975. Maximum Matrix Sum/1975.java create mode 100644 solutions/1975. Maximum Matrix Sum/1975.py create mode 100644 solutions/1976. Number of Ways to Arrive at Destination/1976.cpp create mode 100644 solutions/1976. Number of Ways to Arrive at Destination/1976.java create mode 100644 solutions/1976. Number of Ways to Arrive at Destination/1976.py create mode 100644 solutions/1977. Number of Ways to Separate Numbers/1977.cpp create mode 100644 solutions/1977. Number of Ways to Separate Numbers/1977.java create mode 100644 solutions/1977. Number of Ways to Separate Numbers/1977.py create mode 100644 solutions/1978. Employees Whose Manager Left the Company/1978.sql create mode 100644 solutions/1979. Find Greatest Common Divisor of Array/1979.cpp create mode 100644 solutions/1979. Find Greatest Common Divisor of Array/1979.java create mode 100644 solutions/1979. Find Greatest Common Divisor of Array/1979.py create mode 100644 solutions/198. House Robber/198-2.cpp create mode 100644 solutions/198. House Robber/198-2.java create mode 100644 solutions/198. House Robber/198-2.py create mode 100644 solutions/198. House Robber/198.cpp create mode 100644 solutions/198. House Robber/198.java create mode 100644 solutions/198. House Robber/198.py create mode 100644 solutions/1980. Find Unique Binary String/1980-2.cpp create mode 100644 solutions/1980. Find Unique Binary String/1980-2.java create mode 100644 solutions/1980. Find Unique Binary String/1980-2.py create mode 100644 solutions/1980. Find Unique Binary String/1980.cpp create mode 100644 solutions/1980. Find Unique Binary String/1980.java create mode 100644 solutions/1980. Find Unique Binary String/1980.py create mode 100644 solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.cpp create mode 100644 solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.java create mode 100644 solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.py create mode 100644 solutions/1982. Find Array Given Subset Sums/1982.cpp create mode 100644 solutions/1982. Find Array Given Subset Sums/1982.java create mode 100644 solutions/1982. Find Array Given Subset Sums/1982.py create mode 100644 solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.cpp create mode 100644 solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.java create mode 100644 solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.py create mode 100644 solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.cpp create mode 100644 solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.java create mode 100644 solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.py create mode 100644 solutions/1985. Find the Kth Largest Integer in the Array/1985.cpp create mode 100644 solutions/1985. Find the Kth Largest Integer in the Array/1985.java create mode 100644 solutions/1985. Find the Kth Largest Integer in the Array/1985.py create mode 100644 solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.cpp create mode 100644 solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.java create mode 100644 solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.py create mode 100644 solutions/1987. Number of Unique Good Subsequences/1987.cpp create mode 100644 solutions/1987. Number of Unique Good Subsequences/1987.java create mode 100644 solutions/1987. Number of Unique Good Subsequences/1987.py create mode 100644 solutions/1988. Find Cutoff Score for Each School/1988.sql create mode 100644 solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.cpp create mode 100644 solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.java create mode 100644 solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.py create mode 100644 solutions/199. Binary Tree Right Side View/199-2.cpp create mode 100644 solutions/199. Binary Tree Right Side View/199-2.java create mode 100644 solutions/199. Binary Tree Right Side View/199-2.py create mode 100644 solutions/199. Binary Tree Right Side View/199.cpp create mode 100644 solutions/199. Binary Tree Right Side View/199.java create mode 100644 solutions/199. Binary Tree Right Side View/199.py create mode 100644 solutions/1990. Count the Number of Experiments/1990.sql create mode 100644 solutions/1991. Find the Middle Index in Array/1991.cpp create mode 100644 solutions/1991. Find the Middle Index in Array/1991.java create mode 100644 solutions/1991. Find the Middle Index in Array/1991.py create mode 100644 solutions/1992. Find All Groups of Farmland/1992.cpp create mode 100644 solutions/1992. Find All Groups of Farmland/1992.java create mode 100644 solutions/1992. Find All Groups of Farmland/1992.py create mode 100644 solutions/1993. Operations on Tree/1993.cpp create mode 100644 solutions/1993. Operations on Tree/1993.java create mode 100644 solutions/1993. Operations on Tree/1993.py create mode 100644 solutions/1994. The Number of Good Subsets/1994.cpp create mode 100644 solutions/1994. The Number of Good Subsets/1994.java create mode 100644 solutions/1994. The Number of Good Subsets/1994.py create mode 100644 solutions/1995. Count Special Quadruplets/1995-2.cpp create mode 100644 solutions/1995. Count Special Quadruplets/1995-2.java create mode 100644 solutions/1995. Count Special Quadruplets/1995-2.py create mode 100644 solutions/1995. Count Special Quadruplets/1995-3.cpp create mode 100644 solutions/1995. Count Special Quadruplets/1995-3.java create mode 100644 solutions/1995. Count Special Quadruplets/1995-3.py create mode 100644 solutions/1995. Count Special Quadruplets/1995.cpp create mode 100644 solutions/1995. Count Special Quadruplets/1995.java create mode 100644 solutions/1995. Count Special Quadruplets/1995.py create mode 100644 solutions/1996. The Number of Weak Characters in the Game/1996-2.cpp create mode 100644 solutions/1996. The Number of Weak Characters in the Game/1996-2.java create mode 100644 solutions/1996. The Number of Weak Characters in the Game/1996-2.py create mode 100644 solutions/1996. The Number of Weak Characters in the Game/1996.cpp create mode 100644 solutions/1996. The Number of Weak Characters in the Game/1996.java create mode 100644 solutions/1996. The Number of Weak Characters in the Game/1996.py create mode 100644 solutions/1997. First Day Where You Have Been in All the Rooms/1997.cpp create mode 100644 solutions/1997. First Day Where You Have Been in All the Rooms/1997.java create mode 100644 solutions/1997. First Day Where You Have Been in All the Rooms/1997.py create mode 100644 solutions/1998. GCD Sort of an Array/1998.cpp create mode 100644 solutions/1998. GCD Sort of an Array/1998.java create mode 100644 solutions/1998. GCD Sort of an Array/1998.py create mode 100644 solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.cpp create mode 100644 solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.java create mode 100644 solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.py create mode 100644 solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.cpp create mode 100644 solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.java create mode 100644 solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.py create mode 100644 solutions/2. Add Two Numbers/2.cpp create mode 100644 solutions/2. Add Two Numbers/2.java create mode 100644 solutions/2. Add Two Numbers/2.py create mode 100644 solutions/20. Valid Parentheses/20.cpp create mode 100644 solutions/20. Valid Parentheses/20.java create mode 100644 solutions/20. Valid Parentheses/20.py create mode 100644 solutions/200. Number of Islands/200-2.cpp create mode 100644 solutions/200. Number of Islands/200-2.java create mode 100644 solutions/200. Number of Islands/200-2.py create mode 100644 solutions/200. Number of Islands/200.cpp create mode 100644 solutions/200. Number of Islands/200.java create mode 100644 solutions/200. Number of Islands/200.py create mode 100644 solutions/2000. Reverse Prefix of Word/2000.cpp create mode 100644 solutions/2000. Reverse Prefix of Word/2000.java create mode 100644 solutions/2000. Reverse Prefix of Word/2000.py create mode 100644 solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.cpp create mode 100644 solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.java create mode 100644 solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.py create mode 100644 solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.cpp create mode 100644 solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.java create mode 100644 solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.py create mode 100644 solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.cpp create mode 100644 solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.java create mode 100644 solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.py create mode 100644 solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.cpp create mode 100644 solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.java create mode 100644 solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.py create mode 100644 solutions/2004. The Number of Seniors and Juniors to Join the Company/2004.sql create mode 100644 solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.cpp create mode 100644 solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.java create mode 100644 solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.py create mode 100644 solutions/2006. Count Number of Pairs With Absolute Difference K/2006.cpp create mode 100644 solutions/2006. Count Number of Pairs With Absolute Difference K/2006.java create mode 100644 solutions/2006. Count Number of Pairs With Absolute Difference K/2006.py create mode 100644 solutions/2007. Find Original Array From Doubled Array/2007.cpp create mode 100644 solutions/2007. Find Original Array From Doubled Array/2007.java create mode 100644 solutions/2007. Find Original Array From Doubled Array/2007.py create mode 100644 solutions/2008. Maximum Earnings From Taxi/2008-2.cpp create mode 100644 solutions/2008. Maximum Earnings From Taxi/2008-2.java create mode 100644 solutions/2008. Maximum Earnings From Taxi/2008-2.py create mode 100644 solutions/2008. Maximum Earnings From Taxi/2008.cpp create mode 100644 solutions/2008. Maximum Earnings From Taxi/2008.java create mode 100644 solutions/2008. Maximum Earnings From Taxi/2008.py create mode 100644 solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.cpp create mode 100644 solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.java create mode 100644 solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.py create mode 100644 solutions/201. Bitwise AND of Numbers Range/201.cpp create mode 100644 solutions/201. Bitwise AND of Numbers Range/201.java create mode 100644 solutions/201. Bitwise AND of Numbers Range/201.py create mode 100644 solutions/2010. The Number of Seniors and Juniors to Join the Company II/2010.sql create mode 100644 solutions/2011. Final Value of Variable After Performing Operations/2011.cpp create mode 100644 solutions/2011. Final Value of Variable After Performing Operations/2011.java create mode 100644 solutions/2011. Final Value of Variable After Performing Operations/2011.py create mode 100644 solutions/2012. Sum of Beauty in the Array/2012.cpp create mode 100644 solutions/2012. Sum of Beauty in the Array/2012.java create mode 100644 solutions/2012. Sum of Beauty in the Array/2012.py create mode 100644 solutions/2013. Detect Squares/2013.cpp create mode 100644 solutions/2013. Detect Squares/2013.java create mode 100644 solutions/2013. Detect Squares/2013.py create mode 100644 solutions/2014. Longest Subsequence Repeated k Times/2014.cpp create mode 100644 solutions/2014. Longest Subsequence Repeated k Times/2014.java create mode 100644 solutions/2014. Longest Subsequence Repeated k Times/2014.py create mode 100644 solutions/2015. Average Height of Buildings in Each Segment/2015.cpp create mode 100644 solutions/2015. Average Height of Buildings in Each Segment/2015.java create mode 100644 solutions/2015. Average Height of Buildings in Each Segment/2015.py create mode 100644 solutions/2016. Maximum Difference Between Increasing Elements/2016.cpp create mode 100644 solutions/2016. Maximum Difference Between Increasing Elements/2016.java create mode 100644 solutions/2016. Maximum Difference Between Increasing Elements/2016.py create mode 100644 solutions/2017. Grid Game/2017.cpp create mode 100644 solutions/2017. Grid Game/2017.java create mode 100644 solutions/2017. Grid Game/2017.py create mode 100644 solutions/2018. Check if Word Can Be Placed In Crossword/2018.cpp create mode 100644 solutions/2018. Check if Word Can Be Placed In Crossword/2018.java create mode 100644 solutions/2018. Check if Word Can Be Placed In Crossword/2018.py create mode 100644 solutions/2019. The Score of Students Solving Math Expression/2019.cpp create mode 100644 solutions/2019. The Score of Students Solving Math Expression/2019.java create mode 100644 solutions/2019. The Score of Students Solving Math Expression/2019.py create mode 100644 solutions/202. Happy Number/202.cpp create mode 100644 solutions/202. Happy Number/202.java create mode 100644 solutions/202. Happy Number/202.py create mode 100644 solutions/2020. Number of Accounts That Did Not Stream/2020.sql create mode 100644 solutions/2021. Brightest Position on Street/2021.cpp create mode 100644 solutions/2021. Brightest Position on Street/2021.java create mode 100644 solutions/2021. Brightest Position on Street/2021.py create mode 100644 solutions/2022. Convert 1D Array Into 2D Array/2022.cpp create mode 100644 solutions/2022. Convert 1D Array Into 2D Array/2022.java create mode 100644 solutions/2022. Convert 1D Array Into 2D Array/2022.py create mode 100644 solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.cpp create mode 100644 solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.java create mode 100644 solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.py create mode 100644 solutions/2024. Maximize the Confusion of an Exam/2024.cpp create mode 100644 solutions/2024. Maximize the Confusion of an Exam/2024.java create mode 100644 solutions/2024. Maximize the Confusion of an Exam/2024.py create mode 100644 solutions/2025. Maximum Number of Ways to Partition an Array/2025.cpp create mode 100644 solutions/2025. Maximum Number of Ways to Partition an Array/2025.java create mode 100644 solutions/2025. Maximum Number of Ways to Partition an Array/2025.py create mode 100644 solutions/2026. Low-Quality Problems/2026.sql create mode 100644 solutions/2027. Minimum Moves to Convert String/2027.cpp create mode 100644 solutions/2027. Minimum Moves to Convert String/2027.java create mode 100644 solutions/2027. Minimum Moves to Convert String/2027.py create mode 100644 solutions/2028. Find Missing Observations/2028.cpp create mode 100644 solutions/2028. Find Missing Observations/2028.java create mode 100644 solutions/2028. Find Missing Observations/2028.py create mode 100644 solutions/2029. Stone Game IX/2029.cpp create mode 100644 solutions/2029. Stone Game IX/2029.java create mode 100644 solutions/2029. Stone Game IX/2029.py create mode 100644 solutions/203. Remove Linked List Elements/203.cpp create mode 100644 solutions/203. Remove Linked List Elements/203.java create mode 100644 solutions/203. Remove Linked List Elements/203.py create mode 100644 solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.cpp create mode 100644 solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.java create mode 100644 solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.py create mode 100644 solutions/2031. Count Subarrays With More Ones Than Zeros/2031.cpp create mode 100644 solutions/2031. Count Subarrays With More Ones Than Zeros/2031.java create mode 100644 solutions/2031. Count Subarrays With More Ones Than Zeros/2031.py create mode 100644 solutions/2032. Two Out of Three/2032.cpp create mode 100644 solutions/2032. Two Out of Three/2032.java create mode 100644 solutions/2032. Two Out of Three/2032.py create mode 100644 solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.cpp create mode 100644 solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.java create mode 100644 solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.py create mode 100644 solutions/2034. Stock Price Fluctuation/2034-2.cpp create mode 100644 solutions/2034. Stock Price Fluctuation/2034.cpp create mode 100644 solutions/2034. Stock Price Fluctuation/2034.java create mode 100644 solutions/2034. Stock Price Fluctuation/2034.py create mode 100644 solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.cpp create mode 100644 solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.java create mode 100644 solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.py create mode 100644 solutions/2036. Maximum Alternating Subarray Sum/2036.cpp create mode 100644 solutions/2036. Maximum Alternating Subarray Sum/2036.java create mode 100644 solutions/2036. Maximum Alternating Subarray Sum/2036.py create mode 100644 solutions/2037. Minimum Number of Moves to Seat Everyone/2037.cpp create mode 100644 solutions/2037. Minimum Number of Moves to Seat Everyone/2037.java create mode 100644 solutions/2037. Minimum Number of Moves to Seat Everyone/2037.py create mode 100644 solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.cpp create mode 100644 solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.java create mode 100644 solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.py create mode 100644 solutions/2039. The Time When the Network Becomes Idle/2039.cpp create mode 100644 solutions/2039. The Time When the Network Becomes Idle/2039.java create mode 100644 solutions/2039. The Time When the Network Becomes Idle/2039.py create mode 100644 solutions/204. Count Primes/204.cpp create mode 100644 solutions/204. Count Primes/204.java create mode 100644 solutions/204. Count Primes/204.py create mode 100644 solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.cpp create mode 100644 solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.java create mode 100644 solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.py create mode 100644 solutions/2041. Accepted Candidates From the Interviews/2041.sql create mode 100644 solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.cpp create mode 100644 solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.java create mode 100644 solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.py create mode 100644 solutions/2043. Simple Bank System/2043.cpp create mode 100644 solutions/2043. Simple Bank System/2043.java create mode 100644 solutions/2043. Simple Bank System/2043.py create mode 100644 solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.cpp create mode 100644 solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.java create mode 100644 solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.py create mode 100644 solutions/2045. Second Minimum Time to Reach Destination/2045.cpp create mode 100644 solutions/2045. Second Minimum Time to Reach Destination/2045.java create mode 100644 solutions/2045. Second Minimum Time to Reach Destination/2045.py create mode 100644 solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.cpp create mode 100644 solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.java create mode 100644 solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.py create mode 100644 solutions/2047. Number of Valid Words in a Sentence/2047-2.cpp create mode 100644 solutions/2047. Number of Valid Words in a Sentence/2047-2.java create mode 100644 solutions/2047. Number of Valid Words in a Sentence/2047-2.py create mode 100644 solutions/2047. Number of Valid Words in a Sentence/2047.cpp create mode 100644 solutions/2047. Number of Valid Words in a Sentence/2047.java create mode 100644 solutions/2047. Number of Valid Words in a Sentence/2047.py create mode 100644 solutions/2048. Next Greater Numerically Balanced Number/2048.cpp create mode 100644 solutions/2048. Next Greater Numerically Balanced Number/2048.java create mode 100644 solutions/2048. Next Greater Numerically Balanced Number/2048.py create mode 100644 solutions/2049. Count Nodes With the Highest Score/2049.cpp create mode 100644 solutions/2049. Count Nodes With the Highest Score/2049.java create mode 100644 solutions/2049. Count Nodes With the Highest Score/2049.py create mode 100644 solutions/205. Isomorphic Strings/205.cpp create mode 100644 solutions/205. Isomorphic Strings/205.java create mode 100644 solutions/205. Isomorphic Strings/205.py create mode 100644 solutions/2050. Parallel Courses III/2050.cpp create mode 100644 solutions/2050. Parallel Courses III/2050.java create mode 100644 solutions/2050. Parallel Courses III/2050.py create mode 100644 solutions/2051. The Category of Each Member in the Store/2051.sql create mode 100644 solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.cpp create mode 100644 solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.java create mode 100644 solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.py create mode 100644 solutions/2053. Kth Distinct String in an Array/2053.cpp create mode 100644 solutions/2053. Kth Distinct String in an Array/2053.java create mode 100644 solutions/2053. Kth Distinct String in an Array/2053.py create mode 100644 solutions/2054. Two Best Non-Overlapping Events/2054.cpp create mode 100644 solutions/2054. Two Best Non-Overlapping Events/2054.java create mode 100644 solutions/2054. Two Best Non-Overlapping Events/2054.py create mode 100644 solutions/2055. Plates Between Candles/2055-2.cpp create mode 100644 solutions/2055. Plates Between Candles/2055-2.java create mode 100644 solutions/2055. Plates Between Candles/2055-2.py create mode 100644 solutions/2055. Plates Between Candles/2055.cpp create mode 100644 solutions/2055. Plates Between Candles/2055.java create mode 100644 solutions/2055. Plates Between Candles/2055.py create mode 100644 solutions/2056. Number of Valid Move Combinations On Chessboard/2056.cpp create mode 100644 solutions/2056. Number of Valid Move Combinations On Chessboard/2056.java create mode 100644 solutions/2056. Number of Valid Move Combinations On Chessboard/2056.py create mode 100644 solutions/2057. Smallest Index With Equal Value/2057.cpp create mode 100644 solutions/2057. Smallest Index With Equal Value/2057.java create mode 100644 solutions/2057. Smallest Index With Equal Value/2057.py create mode 100644 solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.cpp create mode 100644 solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.java create mode 100644 solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.py create mode 100644 solutions/2059. Minimum Operations to Convert Number/2059.cpp create mode 100644 solutions/2059. Minimum Operations to Convert Number/2059.java create mode 100644 solutions/2059. Minimum Operations to Convert Number/2059.py create mode 100644 solutions/206. Reverse Linked List/206-2.cpp create mode 100644 solutions/206. Reverse Linked List/206-2.java create mode 100644 solutions/206. Reverse Linked List/206-2.py create mode 100644 solutions/206. Reverse Linked List/206.cpp create mode 100644 solutions/206. Reverse Linked List/206.java create mode 100644 solutions/206. Reverse Linked List/206.py create mode 100644 solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.cpp create mode 100644 solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.java create mode 100644 solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.py create mode 100644 solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.cpp create mode 100644 solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.java create mode 100644 solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.py create mode 100644 solutions/2062. Count Vowel Substrings of a String/2062.cpp create mode 100644 solutions/2062. Count Vowel Substrings of a String/2062.java create mode 100644 solutions/2062. Count Vowel Substrings of a String/2062.py create mode 100644 solutions/2063. Vowels of All Substrings/2063-2.cpp create mode 100644 solutions/2063. Vowels of All Substrings/2063-2.java create mode 100644 solutions/2063. Vowels of All Substrings/2063-2.py create mode 100644 solutions/2063. Vowels of All Substrings/2063.cpp create mode 100644 solutions/2063. Vowels of All Substrings/2063.java create mode 100644 solutions/2063. Vowels of All Substrings/2063.py create mode 100644 solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.cpp create mode 100644 solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.java create mode 100644 solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.py create mode 100644 solutions/2065. Maximum Path Quality of a Graph/2065-2.py create mode 100644 solutions/2065. Maximum Path Quality of a Graph/2065.cpp create mode 100644 solutions/2065. Maximum Path Quality of a Graph/2065.java create mode 100644 solutions/2065. Maximum Path Quality of a Graph/2065.py create mode 100644 solutions/2066. Account Balance/2066.sql create mode 100644 solutions/2067. Number of Equal Count Substrings/2067.cpp create mode 100644 solutions/2067. Number of Equal Count Substrings/2067.java create mode 100644 solutions/2067. Number of Equal Count Substrings/2067.py create mode 100644 solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.cpp create mode 100644 solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.java create mode 100644 solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.py create mode 100644 solutions/2069. Walking Robot Simulation II/2069.cpp create mode 100644 solutions/2069. Walking Robot Simulation II/2069.java create mode 100644 solutions/2069. Walking Robot Simulation II/2069.py create mode 100644 solutions/207. Course Schedule/207.cpp create mode 100644 solutions/207. Course Schedule/207.java create mode 100644 solutions/207. Course Schedule/207.py create mode 100644 solutions/2070. Most Beautiful Item for Each Query/2070.cpp create mode 100644 solutions/2070. Most Beautiful Item for Each Query/2070.java create mode 100644 solutions/2070. Most Beautiful Item for Each Query/2070.py create mode 100644 solutions/2071. Maximum Number of Tasks You Can Assign/2071.cpp create mode 100644 solutions/2071. Maximum Number of Tasks You Can Assign/2071.java create mode 100644 solutions/2071. Maximum Number of Tasks You Can Assign/2071.py create mode 100644 solutions/2072. The Winner University/2072.sql create mode 100644 solutions/2073. Time Needed to Buy Tickets/2073.cpp create mode 100644 solutions/2073. Time Needed to Buy Tickets/2073.java create mode 100644 solutions/2073. Time Needed to Buy Tickets/2073.py create mode 100644 solutions/2074. Reverse Nodes in Even Length Groups/2074.cpp create mode 100644 solutions/2074. Reverse Nodes in Even Length Groups/2074.java create mode 100644 solutions/2074. Reverse Nodes in Even Length Groups/2074.py create mode 100644 solutions/2075. Decode the Slanted Ciphertext/2075-2.py create mode 100644 solutions/2075. Decode the Slanted Ciphertext/2075.py create mode 100644 solutions/2076. Process Restricted Friend Requests/2076.cpp create mode 100644 solutions/2076. Process Restricted Friend Requests/2076.java create mode 100644 solutions/2076. Process Restricted Friend Requests/2076.py create mode 100644 solutions/2077. Paths in Maze That Lead to Same Room/2077.py create mode 100644 solutions/2078. Two Furthest Houses With Different Colors/2078.cpp create mode 100644 solutions/2078. Two Furthest Houses With Different Colors/2078.java create mode 100644 solutions/2078. Two Furthest Houses With Different Colors/2078.py create mode 100644 solutions/2079. Watering Plants/2079.py create mode 100644 solutions/208. Implement Trie (Prefix Tree)/208.cpp create mode 100644 solutions/208. Implement Trie (Prefix Tree)/208.java create mode 100644 solutions/208. Implement Trie (Prefix Tree)/208.py create mode 100644 solutions/2080. Range Frequency Queries/2080.py create mode 100644 solutions/2081. Sum of k-Mirror Numbers/2081.py create mode 100644 solutions/2082. The Number of Rich Customers/2082.sql create mode 100644 solutions/2083. Substrings That Begin and End With the Same Letter/2083.cpp create mode 100644 solutions/2083. Substrings That Begin and End With the Same Letter/2083.java create mode 100644 solutions/2083. Substrings That Begin and End With the Same Letter/2083.py create mode 100644 solutions/2084. Drop Type 1 Orders for Customers With Type 0 Orders/2084.sql create mode 100644 solutions/2085. Count Common Words With One Occurrence/2085.cpp create mode 100644 solutions/2085. Count Common Words With One Occurrence/2085.java create mode 100644 solutions/2085. Count Common Words With One Occurrence/2085.py create mode 100644 solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.cpp create mode 100644 solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.java create mode 100644 solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.py create mode 100644 solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.cpp create mode 100644 solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.java create mode 100644 solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.py create mode 100644 solutions/2088. Count Fertile Pyramids in a Land/2088.cpp create mode 100644 solutions/2088. Count Fertile Pyramids in a Land/2088.java create mode 100644 solutions/2088. Count Fertile Pyramids in a Land/2088.py create mode 100644 solutions/2089. Find Target Indices After Sorting Array/2089.cpp create mode 100644 solutions/2089. Find Target Indices After Sorting Array/2089.java create mode 100644 solutions/2089. Find Target Indices After Sorting Array/2089.py create mode 100644 solutions/209. Minimum Size Subarray Sum/209.cpp create mode 100644 solutions/209. Minimum Size Subarray Sum/209.java create mode 100644 solutions/209. Minimum Size Subarray Sum/209.py create mode 100644 solutions/2090. K Radius Subarray Averages/2090.cpp create mode 100644 solutions/2090. K Radius Subarray Averages/2090.java create mode 100644 solutions/2090. K Radius Subarray Averages/2090.py create mode 100644 solutions/2091. Removing Minimum and Maximum From Array/2091.cpp create mode 100644 solutions/2091. Removing Minimum and Maximum From Array/2091.java create mode 100644 solutions/2091. Removing Minimum and Maximum From Array/2091.py create mode 100644 solutions/2092. Find All People With Secret/2092.cpp create mode 100644 solutions/2092. Find All People With Secret/2092.java create mode 100644 solutions/2092. Find All People With Secret/2092.py create mode 100644 solutions/2093. Minimum Cost to Reach City With Discounts/2093.cpp create mode 100644 solutions/2093. Minimum Cost to Reach City With Discounts/2093.java create mode 100644 solutions/2093. Minimum Cost to Reach City With Discounts/2093.py create mode 100644 solutions/2094. Finding 3-Digit Even Numbers/2094.cpp create mode 100644 solutions/2094. Finding 3-Digit Even Numbers/2094.java create mode 100644 solutions/2094. Finding 3-Digit Even Numbers/2094.py create mode 100644 solutions/2095. Delete the Middle Node of a Linked List/2095.cpp create mode 100644 solutions/2095. Delete the Middle Node of a Linked List/2095.java create mode 100644 solutions/2095. Delete the Middle Node of a Linked List/2095.py create mode 100644 solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.cpp create mode 100644 solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.java create mode 100644 solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.py create mode 100644 solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.cpp create mode 100644 solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.java create mode 100644 solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.py create mode 100644 solutions/2097. Valid Arrangement of Pairs/2097.cpp create mode 100644 solutions/2097. Valid Arrangement of Pairs/2097.java create mode 100644 solutions/2097. Valid Arrangement of Pairs/2097.py create mode 100644 solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.cpp create mode 100644 solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.java create mode 100644 solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.py create mode 100644 solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.cpp create mode 100644 solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.java create mode 100644 solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.py create mode 100644 solutions/21. Merge Two Sorted Lists/21.cpp create mode 100644 solutions/21. Merge Two Sorted Lists/21.java create mode 100644 solutions/21. Merge Two Sorted Lists/21.py create mode 100644 solutions/210. Course Schedule II/210-2.cpp create mode 100644 solutions/210. Course Schedule II/210-2.java create mode 100644 solutions/210. Course Schedule II/210-2.py create mode 100644 solutions/210. Course Schedule II/210.cpp create mode 100644 solutions/210. Course Schedule II/210.java create mode 100644 solutions/210. Course Schedule II/210.py create mode 100644 solutions/2100. Find Good Days to Rob the Bank/2100.cpp create mode 100644 solutions/2100. Find Good Days to Rob the Bank/2100.java create mode 100644 solutions/2100. Find Good Days to Rob the Bank/2100.py create mode 100644 solutions/2101. Detonate the Maximum Bombs/2101.cpp create mode 100644 solutions/2101. Detonate the Maximum Bombs/2101.java create mode 100644 solutions/2101. Detonate the Maximum Bombs/2101.py create mode 100644 solutions/2102. Sequentially Ordinal Rank Tracker/2102.cpp create mode 100644 solutions/2102. Sequentially Ordinal Rank Tracker/2102.java create mode 100644 solutions/2102. Sequentially Ordinal Rank Tracker/2102.py create mode 100644 solutions/2103. Rings and Rods/2103.cpp create mode 100644 solutions/2103. Rings and Rods/2103.java create mode 100644 solutions/2103. Rings and Rods/2103.py create mode 100644 solutions/2104. Sum of Subarray Ranges/2104.cpp create mode 100644 solutions/2104. Sum of Subarray Ranges/2104.java create mode 100644 solutions/2104. Sum of Subarray Ranges/2104.py create mode 100644 solutions/2105. Watering Plants II/2105.cpp create mode 100644 solutions/2105. Watering Plants II/2105.java create mode 100644 solutions/2105. Watering Plants II/2105.py create mode 100644 solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.cpp create mode 100644 solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.java create mode 100644 solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.py create mode 100644 solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.cpp create mode 100644 solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.java create mode 100644 solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.py create mode 100644 solutions/2108. Find First Palindromic String in the Array/2108.cpp create mode 100644 solutions/2108. Find First Palindromic String in the Array/2108.java create mode 100644 solutions/2108. Find First Palindromic String in the Array/2108.py create mode 100644 solutions/2109. Adding Spaces to a String/2109.cpp create mode 100644 solutions/2109. Adding Spaces to a String/2109.java create mode 100644 solutions/2109. Adding Spaces to a String/2109.py create mode 100644 solutions/211. Add and Search Word - Data structure design/211.cpp create mode 100644 solutions/211. Add and Search Word - Data structure design/211.java create mode 100644 solutions/211. Add and Search Word - Data structure design/211.py create mode 100644 solutions/2110. Number of Smooth Descent Periods of a Stock/2110.cpp create mode 100644 solutions/2110. Number of Smooth Descent Periods of a Stock/2110.java create mode 100644 solutions/2110. Number of Smooth Descent Periods of a Stock/2110.py create mode 100644 solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.cpp create mode 100644 solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.java create mode 100644 solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.py create mode 100644 solutions/2112. The Airport With the Most Traffic/2112.sql create mode 100644 solutions/2113. Elements in Array After Removing and Replacing Elements/2113.cpp create mode 100644 solutions/2113. Elements in Array After Removing and Replacing Elements/2113.java create mode 100644 solutions/2113. Elements in Array After Removing and Replacing Elements/2113.py create mode 100644 solutions/2114. Maximum Number of Words Found in Sentences/2114.cpp create mode 100644 solutions/2114. Maximum Number of Words Found in Sentences/2114.java create mode 100644 solutions/2114. Maximum Number of Words Found in Sentences/2114.py create mode 100644 solutions/2115. Find All Possible Recipes from Given Supplies/2115.cpp create mode 100644 solutions/2115. Find All Possible Recipes from Given Supplies/2115.java create mode 100644 solutions/2115. Find All Possible Recipes from Given Supplies/2115.py create mode 100644 solutions/2116. Check if a Parentheses String Can Be Valid/2116.cpp create mode 100644 solutions/2116. Check if a Parentheses String Can Be Valid/2116.java create mode 100644 solutions/2116. Check if a Parentheses String Can Be Valid/2116.py create mode 100644 solutions/2117. Abbreviating the Product of a Range/2117.cpp create mode 100644 solutions/2117. Abbreviating the Product of a Range/2117.java create mode 100644 solutions/2117. Abbreviating the Product of a Range/2117.py create mode 100644 solutions/2118. Build the Equation/2118.sql create mode 100644 solutions/2119. A Number After a Double Reversal/2119-2.cpp create mode 100644 solutions/2119. A Number After a Double Reversal/2119-2.java create mode 100644 solutions/2119. A Number After a Double Reversal/2119-2.py create mode 100644 solutions/2119. A Number After a Double Reversal/2119.cpp create mode 100644 solutions/2119. A Number After a Double Reversal/2119.java create mode 100644 solutions/2119. A Number After a Double Reversal/2119.py create mode 100644 solutions/212. Word Search II/212.cpp create mode 100644 solutions/212. Word Search II/212.java create mode 100644 solutions/212. Word Search II/212.py create mode 100644 solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.cpp create mode 100644 solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.java create mode 100644 solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.py create mode 100644 solutions/2121. Intervals Between Identical Elements/2121.cpp create mode 100644 solutions/2121. Intervals Between Identical Elements/2121.java create mode 100644 solutions/2121. Intervals Between Identical Elements/2121.py create mode 100644 solutions/2122. Recover the Original Array/2122.cpp create mode 100644 solutions/2122. Recover the Original Array/2122.java create mode 100644 solutions/2122. Recover the Original Array/2122.py create mode 100644 solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.cpp create mode 100644 solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.java create mode 100644 solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.py create mode 100644 solutions/2124. Check if All A's Appears Before All B's/2124.cpp create mode 100644 solutions/2124. Check if All A's Appears Before All B's/2124.java create mode 100644 solutions/2124. Check if All A's Appears Before All B's/2124.py create mode 100644 solutions/2125. Number of Laser Beams in a Bank/2125.cpp create mode 100644 solutions/2125. Number of Laser Beams in a Bank/2125.java create mode 100644 solutions/2125. Number of Laser Beams in a Bank/2125.py create mode 100644 solutions/2126. Destroying Asteroids/2126.cpp create mode 100644 solutions/2126. Destroying Asteroids/2126.java create mode 100644 solutions/2126. Destroying Asteroids/2126.py create mode 100644 solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.cpp create mode 100644 solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.java create mode 100644 solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.py create mode 100644 solutions/2128. Remove All Ones With Row and Column Flips/2128.cpp create mode 100644 solutions/2128. Remove All Ones With Row and Column Flips/2128.java create mode 100644 solutions/2128. Remove All Ones With Row and Column Flips/2128.py create mode 100644 solutions/2129. Capitalize the Title/2129.cpp create mode 100644 solutions/2129. Capitalize the Title/2129.java create mode 100644 solutions/2129. Capitalize the Title/2129.py create mode 100644 solutions/213. House Robber II/213.cpp create mode 100644 solutions/213. House Robber II/213.java create mode 100644 solutions/213. House Robber II/213.py create mode 100644 solutions/2130. Maximum Twin Sum of a Linked List/2130.cpp create mode 100644 solutions/2130. Maximum Twin Sum of a Linked List/2130.java create mode 100644 solutions/2130. Maximum Twin Sum of a Linked List/2130.py create mode 100644 solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.cpp create mode 100644 solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.java create mode 100644 solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.py create mode 100644 solutions/2132. Stamping the Grid/2132.cpp create mode 100644 solutions/2132. Stamping the Grid/2132.java create mode 100644 solutions/2132. Stamping the Grid/2132.py create mode 100644 solutions/2133. Check if Every Row and Column Contains All Numbers/2133.cpp create mode 100644 solutions/2133. Check if Every Row and Column Contains All Numbers/2133.java create mode 100644 solutions/2133. Check if Every Row and Column Contains All Numbers/2133.py create mode 100644 solutions/2134. Minimum Swaps to Group All 1's Together II/2134.cpp create mode 100644 solutions/2134. Minimum Swaps to Group All 1's Together II/2134.java create mode 100644 solutions/2134. Minimum Swaps to Group All 1's Together II/2134.py create mode 100644 solutions/2135. Count Words Obtained After Adding a Letter/2135.cpp create mode 100644 solutions/2135. Count Words Obtained After Adding a Letter/2135.java create mode 100644 solutions/2135. Count Words Obtained After Adding a Letter/2135.py create mode 100644 solutions/2136. Earliest Possible Day of Full Bloom/2136.cpp create mode 100644 solutions/2136. Earliest Possible Day of Full Bloom/2136.java create mode 100644 solutions/2136. Earliest Possible Day of Full Bloom/2136.py create mode 100644 solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.cpp create mode 100644 solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.java create mode 100644 solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.py create mode 100644 solutions/2138. Divide a String Into Groups of Size k/2138.cpp create mode 100644 solutions/2138. Divide a String Into Groups of Size k/2138.java create mode 100644 solutions/2138. Divide a String Into Groups of Size k/2138.py create mode 100644 solutions/2139. Minimum Moves to Reach Target Score/2139.cpp create mode 100644 solutions/2139. Minimum Moves to Reach Target Score/2139.java create mode 100644 solutions/2139. Minimum Moves to Reach Target Score/2139.py create mode 100644 solutions/214. Shortest Palindrome/214.cpp create mode 100644 solutions/214. Shortest Palindrome/214.java create mode 100644 solutions/214. Shortest Palindrome/214.py create mode 100644 solutions/2140. Solving Questions With Brainpower/2140.cpp create mode 100644 solutions/2140. Solving Questions With Brainpower/2140.java create mode 100644 solutions/2140. Solving Questions With Brainpower/2140.py create mode 100644 solutions/2141. Maximum Running Time of N Computers/2141.cpp create mode 100644 solutions/2141. Maximum Running Time of N Computers/2141.java create mode 100644 solutions/2141. Maximum Running Time of N Computers/2141.py create mode 100644 solutions/2142. The Number of Passengers in Each Bus I/2142.sql create mode 100644 solutions/2143. Choose Numbers From Two Arrays in Range/2143.cpp create mode 100644 solutions/2143. Choose Numbers From Two Arrays in Range/2143.java create mode 100644 solutions/2143. Choose Numbers From Two Arrays in Range/2143.py create mode 100644 solutions/2144. Minimum Cost of Buying Candies With Discount/2144.cpp create mode 100644 solutions/2144. Minimum Cost of Buying Candies With Discount/2144.java create mode 100644 solutions/2144. Minimum Cost of Buying Candies With Discount/2144.py create mode 100644 solutions/2145. Count the Hidden Sequences/2145-2.cpp create mode 100644 solutions/2145. Count the Hidden Sequences/2145-2.java create mode 100644 solutions/2145. Count the Hidden Sequences/2145-2.py create mode 100644 solutions/2145. Count the Hidden Sequences/2145.cpp create mode 100644 solutions/2145. Count the Hidden Sequences/2145.java create mode 100644 solutions/2145. Count the Hidden Sequences/2145.py create mode 100644 solutions/2146. K Highest Ranked Items Within a Price Range/2146.cpp create mode 100644 solutions/2146. K Highest Ranked Items Within a Price Range/2146.java create mode 100644 solutions/2146. K Highest Ranked Items Within a Price Range/2146.py create mode 100644 solutions/2147. Number of Ways to Divide a Long Corridor/2147.cpp create mode 100644 solutions/2147. Number of Ways to Divide a Long Corridor/2147.java create mode 100644 solutions/2147. Number of Ways to Divide a Long Corridor/2147.py create mode 100644 solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.cpp create mode 100644 solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.java create mode 100644 solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.py create mode 100644 solutions/2149. Rearrange Array Elements by Sign/2149.cpp create mode 100644 solutions/2149. Rearrange Array Elements by Sign/2149.java create mode 100644 solutions/2149. Rearrange Array Elements by Sign/2149.py create mode 100644 solutions/215. Kth Largest Element in an Array/215-2.cpp create mode 100644 solutions/215. Kth Largest Element in an Array/215-2.java create mode 100644 solutions/215. Kth Largest Element in an Array/215-2.py create mode 100644 solutions/215. Kth Largest Element in an Array/215-3.cpp create mode 100644 solutions/215. Kth Largest Element in an Array/215-3.java create mode 100644 solutions/215. Kth Largest Element in an Array/215-3.py create mode 100644 solutions/215. Kth Largest Element in an Array/215.cpp create mode 100644 solutions/215. Kth Largest Element in an Array/215.java create mode 100644 solutions/215. Kth Largest Element in an Array/215.py create mode 100644 solutions/2150. Find All Lonely Numbers in the Array/2150.cpp create mode 100644 solutions/2150. Find All Lonely Numbers in the Array/2150.java create mode 100644 solutions/2150. Find All Lonely Numbers in the Array/2150.py create mode 100644 solutions/2151. Maximum Good People Based on Statements/2151-2.cpp create mode 100644 solutions/2151. Maximum Good People Based on Statements/2151-2.java create mode 100644 solutions/2151. Maximum Good People Based on Statements/2151-2.py create mode 100644 solutions/2151. Maximum Good People Based on Statements/2151.cpp create mode 100644 solutions/2151. Maximum Good People Based on Statements/2151.java create mode 100644 solutions/2151. Maximum Good People Based on Statements/2151.py create mode 100644 solutions/2152. Minimum Number of Lines to Cover Points/2152.cpp create mode 100644 solutions/2152. Minimum Number of Lines to Cover Points/2152.java create mode 100644 solutions/2152. Minimum Number of Lines to Cover Points/2152.py create mode 100644 solutions/2153. The Number of Passengers in Each Bus II/2153.sql create mode 100644 solutions/2154. Keep Multiplying Found Values by Two/2155-2.cpp create mode 100644 solutions/2154. Keep Multiplying Found Values by Two/2155-2.java create mode 100644 solutions/2154. Keep Multiplying Found Values by Two/2155-2.py create mode 100644 solutions/2154. Keep Multiplying Found Values by Two/2155.cpp create mode 100644 solutions/2154. Keep Multiplying Found Values by Two/2155.java create mode 100644 solutions/2154. Keep Multiplying Found Values by Two/2155.py create mode 100644 solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.cpp create mode 100644 solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.java create mode 100644 solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.py create mode 100644 solutions/2156. Find Substring With Given Hash Value/2156.cpp create mode 100644 solutions/2156. Find Substring With Given Hash Value/2156.java create mode 100644 solutions/2156. Find Substring With Given Hash Value/2156.py create mode 100644 solutions/2157. Groups of Strings/2157.cpp create mode 100644 solutions/2157. Groups of Strings/2157.java create mode 100644 solutions/2157. Groups of Strings/2157.py create mode 100644 solutions/2158. Amount of New Area Painted Each Day/2158-2.cpp create mode 100644 solutions/2158. Amount of New Area Painted Each Day/2158.cpp create mode 100644 solutions/2158. Amount of New Area Painted Each Day/2158.java create mode 100644 solutions/2158. Amount of New Area Painted Each Day/2158.py create mode 100644 solutions/2159. Order Two Columns Independently/2159.sql create mode 100644 solutions/216. Combination Sum III/216.cpp create mode 100644 solutions/216. Combination Sum III/216.java create mode 100644 solutions/216. Combination Sum III/216.py create mode 100644 solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.cpp create mode 100644 solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.java create mode 100644 solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.py create mode 100644 solutions/2161. Partition Array According to Given Pivot/2161.cpp create mode 100644 solutions/2161. Partition Array According to Given Pivot/2161.java create mode 100644 solutions/2161. Partition Array According to Given Pivot/2161.py create mode 100644 solutions/2162. Minimum Cost to Set Cooking Time/2162.cpp create mode 100644 solutions/2162. Minimum Cost to Set Cooking Time/2162.java create mode 100644 solutions/2162. Minimum Cost to Set Cooking Time/2162.py create mode 100644 solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.cpp create mode 100644 solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.java create mode 100644 solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.py create mode 100644 solutions/2164. Sort Even and Odd Indices Independently/2164-2.py create mode 100644 solutions/2164. Sort Even and Odd Indices Independently/2164.cpp create mode 100644 solutions/2164. Sort Even and Odd Indices Independently/2164.java create mode 100644 solutions/2164. Sort Even and Odd Indices Independently/2164.py create mode 100644 solutions/2165. Smallest Value of the Rearranged Number/2165.cpp create mode 100644 solutions/2165. Smallest Value of the Rearranged Number/2165.java create mode 100644 solutions/2165. Smallest Value of the Rearranged Number/2165.py create mode 100644 solutions/2166. Design Bitset/2166.cpp create mode 100644 solutions/2166. Design Bitset/2166.java create mode 100644 solutions/2166. Design Bitset/2166.py create mode 100644 solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.cpp create mode 100644 solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.java create mode 100644 solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.py create mode 100644 solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.cpp create mode 100644 solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.java create mode 100644 solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.py create mode 100644 solutions/2168. Unique Substrings With Equal Digit Frequency/2168.cpp create mode 100644 solutions/2168. Unique Substrings With Equal Digit Frequency/2168.java create mode 100644 solutions/2168. Unique Substrings With Equal Digit Frequency/2168.py create mode 100644 solutions/2169. Count Operations to Obtain Zero/2169.cpp create mode 100644 solutions/2169. Count Operations to Obtain Zero/2169.java create mode 100644 solutions/2169. Count Operations to Obtain Zero/2169.py create mode 100644 solutions/217. Contains Duplicate/217.cpp create mode 100644 solutions/217. Contains Duplicate/217.java create mode 100644 solutions/217. Contains Duplicate/217.py create mode 100644 solutions/2170. Minimum Operations to Make the Array Alternating/2170.cpp create mode 100644 solutions/2170. Minimum Operations to Make the Array Alternating/2170.java create mode 100644 solutions/2170. Minimum Operations to Make the Array Alternating/2170.py create mode 100644 solutions/2171. Removing Minimum Number of Magic Beans/2171.cpp create mode 100644 solutions/2171. Removing Minimum Number of Magic Beans/2171.java create mode 100644 solutions/2171. Removing Minimum Number of Magic Beans/2171.py create mode 100644 solutions/2172. Maximum AND Sum of Array/2172.cpp create mode 100644 solutions/2172. Maximum AND Sum of Array/2172.java create mode 100644 solutions/2172. Maximum AND Sum of Array/2172.py create mode 100644 solutions/2173. Longest Winning Streak/2173.sql create mode 100644 solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.cpp create mode 100644 solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.java create mode 100644 solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.py create mode 100644 solutions/2174. Remove All Ones With Row and Column Flips II/2174.cpp create mode 100644 solutions/2174. Remove All Ones With Row and Column Flips II/2174.java create mode 100644 solutions/2174. Remove All Ones With Row and Column Flips II/2174.py create mode 100644 solutions/2175. The Change in Global Rankings/2175.sql create mode 100644 solutions/2176. Count Equal and Divisible Pairs in an Array/2176.cpp create mode 100644 solutions/2176. Count Equal and Divisible Pairs in an Array/2176.java create mode 100644 solutions/2176. Count Equal and Divisible Pairs in an Array/2176.py create mode 100644 solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.cpp create mode 100644 solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.java create mode 100644 solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.py create mode 100644 solutions/2178. Maximum Split of Positive Even Integers/2178.cpp create mode 100644 solutions/2178. Maximum Split of Positive Even Integers/2178.java create mode 100644 solutions/2178. Maximum Split of Positive Even Integers/2178.py create mode 100644 solutions/2179. Count Good Triplets in an Array/2179.cpp create mode 100644 solutions/2179. Count Good Triplets in an Array/2179.java create mode 100644 solutions/2179. Count Good Triplets in an Array/2179.py create mode 100644 solutions/218. The Skyline Problem/218-2.cpp create mode 100644 solutions/218. The Skyline Problem/218.cpp create mode 100644 solutions/218. The Skyline Problem/218.java create mode 100644 solutions/218. The Skyline Problem/218.py create mode 100644 solutions/2180. Count Integers With Even Digit Sum/2180.cpp create mode 100644 solutions/2180. Count Integers With Even Digit Sum/2180.java create mode 100644 solutions/2180. Count Integers With Even Digit Sum/2180.py create mode 100644 solutions/2181. Merge Nodes in Between Zeros/2181-2.cpp create mode 100644 solutions/2181. Merge Nodes in Between Zeros/2181-2.java create mode 100644 solutions/2181. Merge Nodes in Between Zeros/2181-2.py create mode 100644 solutions/2181. Merge Nodes in Between Zeros/2181.cpp create mode 100644 solutions/2181. Merge Nodes in Between Zeros/2181.java create mode 100644 solutions/2181. Merge Nodes in Between Zeros/2181.py create mode 100644 solutions/2182. Construct String With Repeat Limit/2182.cpp create mode 100644 solutions/2182. Construct String With Repeat Limit/2182.java create mode 100644 solutions/2182. Construct String With Repeat Limit/2182.py create mode 100644 solutions/2183. Count Array Pairs Divisible by K/2183.cpp create mode 100644 solutions/2183. Count Array Pairs Divisible by K/2183.java create mode 100644 solutions/2183. Count Array Pairs Divisible by K/2183.py create mode 100644 solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.cpp create mode 100644 solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.java create mode 100644 solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.py create mode 100644 solutions/2185. Counting Words With a Given Prefix/2185.cpp create mode 100644 solutions/2185. Counting Words With a Given Prefix/2185.java create mode 100644 solutions/2185. Counting Words With a Given Prefix/2185.py create mode 100644 solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.cpp create mode 100644 solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.java create mode 100644 solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.py create mode 100644 solutions/2187. Minimum Time to Complete Trips/2187.cpp create mode 100644 solutions/2187. Minimum Time to Complete Trips/2187.java create mode 100644 solutions/2187. Minimum Time to Complete Trips/2187.py create mode 100644 solutions/2188. Minimum Time to Finish the Race/2188-2.cpp create mode 100644 solutions/2188. Minimum Time to Finish the Race/2188.cpp create mode 100644 solutions/2188. Minimum Time to Finish the Race/2188.java create mode 100644 solutions/2188. Minimum Time to Finish the Race/2188.py create mode 100644 solutions/2189. Number of Ways to Build House of Cards/2189.cpp create mode 100644 solutions/2189. Number of Ways to Build House of Cards/2189.java create mode 100644 solutions/2189. Number of Ways to Build House of Cards/2189.py create mode 100644 solutions/219. Contains Duplicate II/219.cpp create mode 100644 solutions/219. Contains Duplicate II/219.java create mode 100644 solutions/219. Contains Duplicate II/219.py create mode 100644 solutions/2190. Most Frequent Number Following Key In an Array/2190.cpp create mode 100644 solutions/2190. Most Frequent Number Following Key In an Array/2190.java create mode 100644 solutions/2190. Most Frequent Number Following Key In an Array/2190.py create mode 100644 solutions/2191. Sort the Jumbled Numbers/2191-2.cpp create mode 100644 solutions/2191. Sort the Jumbled Numbers/2191-2.java create mode 100644 solutions/2191. Sort the Jumbled Numbers/2191.cpp create mode 100644 solutions/2191. Sort the Jumbled Numbers/2191.java create mode 100644 solutions/2191. Sort the Jumbled Numbers/2191.py create mode 100644 solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.cpp create mode 100644 solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.java create mode 100644 solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.py create mode 100644 solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.cpp create mode 100644 solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.java create mode 100644 solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.py create mode 100644 solutions/2193. Minimum Number of Moves to Make Palindrome/2193.cpp create mode 100644 solutions/2193. Minimum Number of Moves to Make Palindrome/2193.java create mode 100644 solutions/2193. Minimum Number of Moves to Make Palindrome/2193.py create mode 100644 solutions/2194. Cells in a Range on an Excel Sheet/2194.cpp create mode 100644 solutions/2194. Cells in a Range on an Excel Sheet/2194.java create mode 100644 solutions/2194. Cells in a Range on an Excel Sheet/2194.py create mode 100644 solutions/2195. Append K Integers With Minimal Sum/2195.cpp create mode 100644 solutions/2195. Append K Integers With Minimal Sum/2195.java create mode 100644 solutions/2195. Append K Integers With Minimal Sum/2195.py create mode 100644 solutions/2196. Create Binary Tree From Descriptions/2196.cpp create mode 100644 solutions/2196. Create Binary Tree From Descriptions/2196.java create mode 100644 solutions/2196. Create Binary Tree From Descriptions/2196.py create mode 100644 solutions/2197. Replace Non-Coprime Numbers in Array/2197.cpp create mode 100644 solutions/2197. Replace Non-Coprime Numbers in Array/2197.java create mode 100644 solutions/2197. Replace Non-Coprime Numbers in Array/2197.py create mode 100644 solutions/2198. Number of Single Divisor Triplets/2198.cpp create mode 100644 solutions/2198. Number of Single Divisor Triplets/2198.java create mode 100644 solutions/2198. Number of Single Divisor Triplets/2198.py create mode 100644 solutions/2199. Finding the Topic of Each Post/2199.sql create mode 100644 solutions/22. Generate Parentheses/22.cpp create mode 100644 solutions/22. Generate Parentheses/22.java create mode 100644 solutions/22. Generate Parentheses/22.py create mode 100644 solutions/220. Contains Duplicate III/220-2.cpp create mode 100644 solutions/220. Contains Duplicate III/220-2.java create mode 100644 solutions/220. Contains Duplicate III/220-2.py create mode 100644 solutions/220. Contains Duplicate III/220.cpp create mode 100644 solutions/220. Contains Duplicate III/220.java create mode 100644 solutions/2200. Find All K-Distant Indices in an Array/2200.cpp create mode 100644 solutions/2200. Find All K-Distant Indices in an Array/2200.java create mode 100644 solutions/2200. Find All K-Distant Indices in an Array/2200.py create mode 100644 solutions/2201. Count Artifacts That Can Be Extracted/2201.cpp create mode 100644 solutions/2201. Count Artifacts That Can Be Extracted/2201.java create mode 100644 solutions/2201. Count Artifacts That Can Be Extracted/2201.py create mode 100644 solutions/2202. Maximize the Topmost Element After K Moves/2202.cpp create mode 100644 solutions/2202. Maximize the Topmost Element After K Moves/2202.java create mode 100644 solutions/2202. Maximize the Topmost Element After K Moves/2202.py create mode 100644 solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.cpp create mode 100644 solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.java create mode 100644 solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.py create mode 100644 solutions/2204. Distance to a Cycle in Undirected Graph/2204.cpp create mode 100644 solutions/2204. Distance to a Cycle in Undirected Graph/2204.java create mode 100644 solutions/2204. Distance to a Cycle in Undirected Graph/2204.py create mode 100644 solutions/2205. The Number of Users That Are Eligible for Discount/2205.sql create mode 100644 solutions/2206. Divide Array Into Equal Pairs/2206.cpp create mode 100644 solutions/2206. Divide Array Into Equal Pairs/2206.java create mode 100644 solutions/2206. Divide Array Into Equal Pairs/2206.py create mode 100644 solutions/2207. Maximize Number of Subsequences in a String/2207.cpp create mode 100644 solutions/2207. Maximize Number of Subsequences in a String/2207.java create mode 100644 solutions/2207. Maximize Number of Subsequences in a String/2207.py create mode 100644 solutions/2208. Minimum Operations to Halve Array Sum/2208.cpp create mode 100644 solutions/2208. Minimum Operations to Halve Array Sum/2208.java create mode 100644 solutions/2208. Minimum Operations to Halve Array Sum/2208.py create mode 100644 solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.cpp create mode 100644 solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.java create mode 100644 solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.py create mode 100644 solutions/2209. Minimum White Tiles After Covering With Carpets/2209.cpp create mode 100644 solutions/2209. Minimum White Tiles After Covering With Carpets/2209.java create mode 100644 solutions/2209. Minimum White Tiles After Covering With Carpets/2209.py create mode 100644 solutions/221. Maximal Square/221-2.cpp create mode 100644 solutions/221. Maximal Square/221-2.java create mode 100644 solutions/221. Maximal Square/221-2.py create mode 100644 solutions/221. Maximal Square/221.cpp create mode 100644 solutions/221. Maximal Square/221.java create mode 100644 solutions/221. Maximal Square/221.py create mode 100644 solutions/2210. Count Hills and Valleys in an Array/2210.cpp create mode 100644 solutions/2210. Count Hills and Valleys in an Array/2210.java create mode 100644 solutions/2210. Count Hills and Valleys in an Array/2210.py create mode 100644 solutions/2211. Count Collisions on a Road/2211.cpp create mode 100644 solutions/2211. Count Collisions on a Road/2211.java create mode 100644 solutions/2211. Count Collisions on a Road/2211.py create mode 100644 solutions/2212. Maximum Points in an Archery Competition/2212.cpp create mode 100644 solutions/2212. Maximum Points in an Archery Competition/2212.java create mode 100644 solutions/2212. Maximum Points in an Archery Competition/2212.py create mode 100644 solutions/2213. Longest Substring of One Repeating Character/2213.cpp create mode 100644 solutions/2214. Minimum Health to Beat Game/2214.cpp create mode 100644 solutions/2214. Minimum Health to Beat Game/2214.java create mode 100644 solutions/2214. Minimum Health to Beat Game/2214.py create mode 100644 solutions/2215. Find the Difference of Two Arrays/2215.cpp create mode 100644 solutions/2215. Find the Difference of Two Arrays/2215.java create mode 100644 solutions/2215. Find the Difference of Two Arrays/2215.py create mode 100644 solutions/2216. Minimum Deletions to Make Array Beautiful/2216.cpp create mode 100644 solutions/2216. Minimum Deletions to Make Array Beautiful/2216.java create mode 100644 solutions/2216. Minimum Deletions to Make Array Beautiful/2216.py create mode 100644 solutions/2217. Find Palindrome With Fixed Length/2217.cpp create mode 100644 solutions/2217. Find Palindrome With Fixed Length/2217.java create mode 100644 solutions/2217. Find Palindrome With Fixed Length/2217.py create mode 100644 solutions/2218. Maximum Value of K Coins From Piles/2218.cpp create mode 100644 solutions/2218. Maximum Value of K Coins From Piles/2218.java create mode 100644 solutions/2218. Maximum Value of K Coins From Piles/2218.py create mode 100644 solutions/2219. Maximum Sum Score of Array/2219.cpp create mode 100644 solutions/2219. Maximum Sum Score of Array/2219.java create mode 100644 solutions/2219. Maximum Sum Score of Array/2219.py create mode 100644 solutions/222. Count Complete Tree Nodes/222-2.cpp create mode 100644 solutions/222. Count Complete Tree Nodes/222-2.java create mode 100644 solutions/222. Count Complete Tree Nodes/222-2.py create mode 100644 solutions/222. Count Complete Tree Nodes/222.cpp create mode 100644 solutions/222. Count Complete Tree Nodes/222.java create mode 100644 solutions/222. Count Complete Tree Nodes/222.py create mode 100644 solutions/2220. Minimum Bit Flips to Convert Number/2220.cpp create mode 100644 solutions/2220. Minimum Bit Flips to Convert Number/2220.java create mode 100644 solutions/2220. Minimum Bit Flips to Convert Number/2220.py create mode 100644 solutions/2221. Find Triangular Sum of an Array/2221.cpp create mode 100644 solutions/2221. Find Triangular Sum of an Array/2221.java create mode 100644 solutions/2221. Find Triangular Sum of an Array/2221.py create mode 100644 solutions/2222. Number of Ways to Select Buildings/2222.cpp create mode 100644 solutions/2222. Number of Ways to Select Buildings/2222.java create mode 100644 solutions/2222. Number of Ways to Select Buildings/2222.py create mode 100644 solutions/2223. Sum of Scores of Built Strings/2223.cpp create mode 100644 solutions/2223. Sum of Scores of Built Strings/2223.java create mode 100644 solutions/2223. Sum of Scores of Built Strings/2223.py create mode 100644 solutions/2224. Minimum Number of Operations to Convert Time/2224.cpp create mode 100644 solutions/2224. Minimum Number of Operations to Convert Time/2224.java create mode 100644 solutions/2224. Minimum Number of Operations to Convert Time/2224.py create mode 100644 solutions/2225. Find Players With Zero or One Losses/2225.cpp create mode 100644 solutions/2225. Find Players With Zero or One Losses/2225.java create mode 100644 solutions/2225. Find Players With Zero or One Losses/2225.py create mode 100644 solutions/2226. Maximum Candies Allocated to K Children/2226.cpp create mode 100644 solutions/2226. Maximum Candies Allocated to K Children/2226.java create mode 100644 solutions/2226. Maximum Candies Allocated to K Children/2226.py create mode 100644 solutions/2227. Encrypt and Decrypt Strings/2227-2.cpp create mode 100644 solutions/2227. Encrypt and Decrypt Strings/2227-2.java create mode 100644 solutions/2227. Encrypt and Decrypt Strings/2227-2.py create mode 100644 solutions/2227. Encrypt and Decrypt Strings/2227.cpp create mode 100644 solutions/2227. Encrypt and Decrypt Strings/2227.java create mode 100644 solutions/2227. Encrypt and Decrypt Strings/2227.py create mode 100644 solutions/2228. Users With Two Purchases Within Seven Days/2228.sql create mode 100644 solutions/2229. Check if an Array Is Consecutive/2229.cpp create mode 100644 solutions/2229. Check if an Array Is Consecutive/2229.java create mode 100644 solutions/2229. Check if an Array Is Consecutive/2229.py create mode 100644 solutions/223. Rectangle Area/223.cpp create mode 100644 solutions/223. Rectangle Area/223.java create mode 100644 solutions/223. Rectangle Area/223.py create mode 100644 solutions/2230. The Users That Are Eligible for Discount/2230.sql create mode 100644 solutions/2231. Largest Number After Digit Swaps by Parity/2231.cpp create mode 100644 solutions/2231. Largest Number After Digit Swaps by Parity/2231.java create mode 100644 solutions/2231. Largest Number After Digit Swaps by Parity/2231.py create mode 100644 solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.cpp create mode 100644 solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.java create mode 100644 solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.py create mode 100644 solutions/2233. Maximum Product After K Increments/2233.cpp create mode 100644 solutions/2233. Maximum Product After K Increments/2233.java create mode 100644 solutions/2233. Maximum Product After K Increments/2233.py create mode 100644 solutions/2234. Maximum Total Beauty of the Gardens/2234.cpp create mode 100644 solutions/2234. Maximum Total Beauty of the Gardens/2234.java create mode 100644 solutions/2234. Maximum Total Beauty of the Gardens/2234.py create mode 100644 solutions/2235. Add Two Integers/2235.cpp create mode 100644 solutions/2235. Add Two Integers/2235.java create mode 100644 solutions/2235. Add Two Integers/2235.py create mode 100644 solutions/2236. Root Equals Sum of Children/2236.cpp create mode 100644 solutions/2236. Root Equals Sum of Children/2236.java create mode 100644 solutions/2236. Root Equals Sum of Children/2236.py create mode 100644 solutions/2237. Count Positions on Street With Required Brightness/2237.cpp create mode 100644 solutions/2237. Count Positions on Street With Required Brightness/2237.java create mode 100644 solutions/2237. Count Positions on Street With Required Brightness/2237.py create mode 100644 solutions/2238. Number of Times a Driver Was a Passenger/2238.sql create mode 100644 solutions/2239. Find Closest Number to Zero/2239.cpp create mode 100644 solutions/2239. Find Closest Number to Zero/2239.java create mode 100644 solutions/2239. Find Closest Number to Zero/2239.py create mode 100644 solutions/224. Basic Calculator/224.cpp create mode 100644 solutions/224. Basic Calculator/224.java create mode 100644 solutions/224. Basic Calculator/224.py create mode 100644 solutions/2240. Number of Ways to Buy Pens and Pencils/2240.cpp create mode 100644 solutions/2240. Number of Ways to Buy Pens and Pencils/2240.java create mode 100644 solutions/2240. Number of Ways to Buy Pens and Pencils/2240.py create mode 100644 solutions/2241. Design an ATM Machine/2241.cpp create mode 100644 solutions/2241. Design an ATM Machine/2241.java create mode 100644 solutions/2241. Design an ATM Machine/2241.py create mode 100644 solutions/2242. Maximum Score of a Node Sequence/2242.cpp create mode 100644 solutions/2242. Maximum Score of a Node Sequence/2242.java create mode 100644 solutions/2242. Maximum Score of a Node Sequence/2242.py create mode 100644 solutions/2243. Calculate Digit Sum of a String/2243.cpp create mode 100644 solutions/2243. Calculate Digit Sum of a String/2243.java create mode 100644 solutions/2243. Calculate Digit Sum of a String/2243.py create mode 100644 solutions/2244. Minimum Rounds to Complete All Tasks/2244.cpp create mode 100644 solutions/2244. Minimum Rounds to Complete All Tasks/2244.java create mode 100644 solutions/2244. Minimum Rounds to Complete All Tasks/2244.py create mode 100644 solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.cpp create mode 100644 solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.java create mode 100644 solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.py create mode 100644 solutions/2246. Longest Path With Different Adjacent Characters/2246.cpp create mode 100644 solutions/2246. Longest Path With Different Adjacent Characters/2246.java create mode 100644 solutions/2246. Longest Path With Different Adjacent Characters/2246.py create mode 100644 solutions/2247. Maximum Cost of Trip With K Highways/2247.cpp create mode 100644 solutions/2247. Maximum Cost of Trip With K Highways/2247.java create mode 100644 solutions/2247. Maximum Cost of Trip With K Highways/2247.py create mode 100644 solutions/2248. Intersection of Multiple Arrays/2248.cpp create mode 100644 solutions/2248. Intersection of Multiple Arrays/2248.java create mode 100644 solutions/2248. Intersection of Multiple Arrays/2248.py create mode 100644 solutions/2249. Count Lattice Points Inside a Circle/2249-2.cpp create mode 100644 solutions/2249. Count Lattice Points Inside a Circle/2249-2.java create mode 100644 solutions/2249. Count Lattice Points Inside a Circle/2249-2.py create mode 100644 solutions/2249. Count Lattice Points Inside a Circle/2249.cpp create mode 100644 solutions/2249. Count Lattice Points Inside a Circle/2249.java create mode 100644 solutions/2249. Count Lattice Points Inside a Circle/2249.py create mode 100644 solutions/225. Implement Stack using Queues/225.cpp create mode 100644 solutions/225. Implement Stack using Queues/225.java create mode 100644 solutions/225. Implement Stack using Queues/225.py create mode 100644 solutions/2250. Count Number of Rectangles Containing Each Point/2250.cpp create mode 100644 solutions/2250. Count Number of Rectangles Containing Each Point/2250.java create mode 100644 solutions/2250. Count Number of Rectangles Containing Each Point/2250.py create mode 100644 solutions/2251. Number of Flowers in Full Bloom/2251.cpp create mode 100644 solutions/2251. Number of Flowers in Full Bloom/2251.java create mode 100644 solutions/2251. Number of Flowers in Full Bloom/2251.py create mode 100644 solutions/2252. Dynamic Pivoting of a Table/2252.sql create mode 100644 solutions/2253. Dynamic Unpivoting of a Table/2253.sql create mode 100644 solutions/2254. Design Video Sharing Platform/2254.cpp create mode 100644 solutions/2254. Design Video Sharing Platform/2254.java create mode 100644 solutions/2254. Design Video Sharing Platform/2254.py create mode 100644 solutions/2255. Count Prefixes of a Given String/2255.cpp create mode 100644 solutions/2255. Count Prefixes of a Given String/2255.java create mode 100644 solutions/2255. Count Prefixes of a Given String/2255.py create mode 100644 solutions/2256. Minimum Average Difference/2256.cpp create mode 100644 solutions/2256. Minimum Average Difference/2256.java create mode 100644 solutions/2256. Minimum Average Difference/2256.py create mode 100644 solutions/2257. Count Unguarded Cells in the Grid/2257.cpp create mode 100644 solutions/2257. Count Unguarded Cells in the Grid/2257.java create mode 100644 solutions/2257. Count Unguarded Cells in the Grid/2257.py create mode 100644 solutions/2258. Escape the Spreading Fire/2258.cpp create mode 100644 solutions/2258. Escape the Spreading Fire/2258.java create mode 100644 solutions/2258. Escape the Spreading Fire/2258.py create mode 100644 solutions/2259. Remove Digit From Number to Maximize Result/2259.cpp create mode 100644 solutions/2259. Remove Digit From Number to Maximize Result/2259.java create mode 100644 solutions/2259. Remove Digit From Number to Maximize Result/2259.py create mode 100644 solutions/226. Invert Binary Tree/226.cpp create mode 100644 solutions/226. Invert Binary Tree/226.java create mode 100644 solutions/226. Invert Binary Tree/226.py create mode 100644 solutions/2260. Minimum Consecutive Cards to Pick Up/2260.cpp create mode 100644 solutions/2260. Minimum Consecutive Cards to Pick Up/2260.java create mode 100644 solutions/2260. Minimum Consecutive Cards to Pick Up/2260.py create mode 100644 solutions/2261. K Divisible Elements Subarrays/2261.cpp create mode 100644 solutions/2261. K Divisible Elements Subarrays/2261.java create mode 100644 solutions/2261. K Divisible Elements Subarrays/2261.py create mode 100644 solutions/2262. Total Appeal of A String/2262-2.cpp create mode 100644 solutions/2262. Total Appeal of A String/2262-2.java create mode 100644 solutions/2262. Total Appeal of A String/2262-2.py create mode 100644 solutions/2262. Total Appeal of A String/2262.cpp create mode 100644 solutions/2262. Total Appeal of A String/2262.java create mode 100644 solutions/2262. Total Appeal of A String/2262.py create mode 100644 solutions/2263. Make Array Non-decreasing or Non-increasing/2263.cpp create mode 100644 solutions/2263. Make Array Non-decreasing or Non-increasing/2263.java create mode 100644 solutions/2263. Make Array Non-decreasing or Non-increasing/2263.py create mode 100644 solutions/2264. Largest 3-Same-Digit Number in String/2264.cpp create mode 100644 solutions/2264. Largest 3-Same-Digit Number in String/2264.java create mode 100644 solutions/2264. Largest 3-Same-Digit Number in String/2264.py create mode 100644 solutions/2265. Count Nodes Equal to Average of Subtree/2265.cpp create mode 100644 solutions/2265. Count Nodes Equal to Average of Subtree/2265.java create mode 100644 solutions/2265. Count Nodes Equal to Average of Subtree/2265.py create mode 100644 solutions/2266. Count Number of Texts/2266.cpp create mode 100644 solutions/2266. Count Number of Texts/2266.java create mode 100644 solutions/2266. Count Number of Texts/2266.py create mode 100644 solutions/2267. Check if There Is a Valid Parentheses String Path/2267.cpp create mode 100644 solutions/2267. Check if There Is a Valid Parentheses String Path/2267.java create mode 100644 solutions/2267. Check if There Is a Valid Parentheses String Path/2267.py create mode 100644 solutions/2268. Minimum Number of Keypresses/2268.cpp create mode 100644 solutions/2268. Minimum Number of Keypresses/2268.java create mode 100644 solutions/2268. Minimum Number of Keypresses/2268.py create mode 100644 solutions/2269. Find the K-Beauty of a Number/2269.cpp create mode 100644 solutions/2269. Find the K-Beauty of a Number/2269.java create mode 100644 solutions/2269. Find the K-Beauty of a Number/2269.py create mode 100644 solutions/227. Basic Calculator II/227-2.cpp create mode 100644 solutions/227. Basic Calculator II/227-2.java create mode 100644 solutions/227. Basic Calculator II/227-2.py create mode 100644 solutions/227. Basic Calculator II/227.cpp create mode 100644 solutions/227. Basic Calculator II/227.java create mode 100644 solutions/227. Basic Calculator II/227.py create mode 100644 solutions/2270. Number of Ways to Split Array/2270.cpp create mode 100644 solutions/2270. Number of Ways to Split Array/2270.java create mode 100644 solutions/2270. Number of Ways to Split Array/2270.py create mode 100644 solutions/2271. Maximum White Tiles Covered by a Carpet/2271.cpp create mode 100644 solutions/2271. Maximum White Tiles Covered by a Carpet/2271.java create mode 100644 solutions/2271. Maximum White Tiles Covered by a Carpet/2271.py create mode 100644 solutions/2272. Substring With Largest Variance/2272.cpp create mode 100644 solutions/2272. Substring With Largest Variance/2272.java create mode 100644 solutions/2272. Substring With Largest Variance/2272.py create mode 100644 solutions/2273. Find Resultant Array After Removing Anagrams/2273.cpp create mode 100644 solutions/2273. Find Resultant Array After Removing Anagrams/2273.java create mode 100644 solutions/2273. Find Resultant Array After Removing Anagrams/2273.py create mode 100644 solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.cpp create mode 100644 solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.java create mode 100644 solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.py create mode 100644 solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.cpp create mode 100644 solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.java create mode 100644 solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.py create mode 100644 solutions/2276. Count Integers in Intervals/2276.cpp create mode 100644 solutions/2276. Count Integers in Intervals/2276.java create mode 100644 solutions/2276. Count Integers in Intervals/2276.py create mode 100644 solutions/2277. Closest Node to Path in Tree/2277.cpp create mode 100644 solutions/2277. Closest Node to Path in Tree/2277.java create mode 100644 solutions/2277. Closest Node to Path in Tree/2277.py create mode 100644 solutions/2278. Percentage of Letter in String/2278.cpp create mode 100644 solutions/2278. Percentage of Letter in String/2278.java create mode 100644 solutions/2278. Percentage of Letter in String/2278.py create mode 100644 solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.cpp create mode 100644 solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.java create mode 100644 solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.py create mode 100644 solutions/228. Summary Ranges/228.cpp create mode 100644 solutions/228. Summary Ranges/228.java create mode 100644 solutions/228. Summary Ranges/228.py create mode 100644 solutions/2280. Minimum Lines to Represent a Line Chart/2280.cpp create mode 100644 solutions/2280. Minimum Lines to Represent a Line Chart/2280.java create mode 100644 solutions/2280. Minimum Lines to Represent a Line Chart/2280.py create mode 100644 solutions/2281. Sum of Total Strength of Wizards/2281.cpp create mode 100644 solutions/2281. Sum of Total Strength of Wizards/2281.java create mode 100644 solutions/2281. Sum of Total Strength of Wizards/2281.py create mode 100644 solutions/2282. Number of People That Can Be Seen in a Grid/2282.cpp create mode 100644 solutions/2282. Number of People That Can Be Seen in a Grid/2282.java create mode 100644 solutions/2282. Number of People That Can Be Seen in a Grid/2282.py create mode 100644 solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.cpp create mode 100644 solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.java create mode 100644 solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.py create mode 100644 solutions/2284. Sender With Largest Word Count/2284.cpp create mode 100644 solutions/2284. Sender With Largest Word Count/2284.java create mode 100644 solutions/2284. Sender With Largest Word Count/2284.py create mode 100644 solutions/2285. Maximum Total Importance of Roads/2285.cpp create mode 100644 solutions/2285. Maximum Total Importance of Roads/2285.java create mode 100644 solutions/2285. Maximum Total Importance of Roads/2285.py create mode 100644 solutions/2286. Booking Concert Tickets in Groups/2286.cpp create mode 100644 solutions/2287. Rearrange Characters to Make Target String/2287.cpp create mode 100644 solutions/2287. Rearrange Characters to Make Target String/2287.java create mode 100644 solutions/2287. Rearrange Characters to Make Target String/2287.py create mode 100644 solutions/2288. Apply Discount to Prices/2288.cpp create mode 100644 solutions/2288. Apply Discount to Prices/2288.java create mode 100644 solutions/2288. Apply Discount to Prices/2288.py create mode 100644 solutions/2289. Steps to Make Array Non-decreasing/2289.cpp create mode 100644 solutions/2289. Steps to Make Array Non-decreasing/2289.java create mode 100644 solutions/2289. Steps to Make Array Non-decreasing/2289.py create mode 100644 solutions/229. Majority Element II/229.cpp create mode 100644 solutions/229. Majority Element II/229.java create mode 100644 solutions/229. Majority Element II/229.py create mode 100644 solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.cpp create mode 100644 solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.java create mode 100644 solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.py create mode 100644 solutions/2291. Maximum Profit From Trading Stocks/2291-2.cpp create mode 100644 solutions/2291. Maximum Profit From Trading Stocks/2291-2.java create mode 100644 solutions/2291. Maximum Profit From Trading Stocks/2291-2.py create mode 100644 solutions/2291. Maximum Profit From Trading Stocks/2291.cpp create mode 100644 solutions/2291. Maximum Profit From Trading Stocks/2291.java create mode 100644 solutions/2291. Maximum Profit From Trading Stocks/2291.py create mode 100644 solutions/2292. Products With Three or More Orders in Two Consecutive Years/2292.sql create mode 100644 solutions/2293. Min Max Game/2293.cpp create mode 100644 solutions/2293. Min Max Game/2293.java create mode 100644 solutions/2293. Min Max Game/2293.py create mode 100644 solutions/2294. Partition Array Such That Maximum Difference Is K/2294.cpp create mode 100644 solutions/2294. Partition Array Such That Maximum Difference Is K/2294.java create mode 100644 solutions/2294. Partition Array Such That Maximum Difference Is K/2294.py create mode 100644 solutions/2295. Replace Elements in an Array/2295.cpp create mode 100644 solutions/2295. Replace Elements in an Array/2295.java create mode 100644 solutions/2295. Replace Elements in an Array/2295.py create mode 100644 solutions/2296. Design a Text Editor/2296.cpp create mode 100644 solutions/2296. Design a Text Editor/2296.java create mode 100644 solutions/2296. Design a Text Editor/2296.py create mode 100644 solutions/2297. Jump Game IX/2297.cpp create mode 100644 solutions/2297. Jump Game IX/2297.java create mode 100644 solutions/2297. Jump Game IX/2297.py create mode 100644 solutions/2298. Tasks Count in the Weekend/2298.sql create mode 100644 solutions/2299. Strong Password Checker II/2299.cpp create mode 100644 solutions/2299. Strong Password Checker II/2299.java create mode 100644 solutions/2299. Strong Password Checker II/2299.py create mode 100644 solutions/23. Merge k Sorted Lists/23.cpp create mode 100644 solutions/23. Merge k Sorted Lists/23.java create mode 100644 solutions/23. Merge k Sorted Lists/23.py create mode 100644 solutions/230. Kth Smallest Element in a BST/230-2.cpp create mode 100644 solutions/230. Kth Smallest Element in a BST/230-2.java create mode 100644 solutions/230. Kth Smallest Element in a BST/230-2.py create mode 100644 solutions/230. Kth Smallest Element in a BST/230-3.cpp create mode 100644 solutions/230. Kth Smallest Element in a BST/230-3.java create mode 100644 solutions/230. Kth Smallest Element in a BST/230-3.py create mode 100644 solutions/230. Kth Smallest Element in a BST/230.cpp create mode 100644 solutions/230. Kth Smallest Element in a BST/230.java create mode 100644 solutions/230. Kth Smallest Element in a BST/230.py create mode 100644 solutions/2300. Successful Pairs of Spells and Potions/2300.cpp create mode 100644 solutions/2300. Successful Pairs of Spells and Potions/2300.java create mode 100644 solutions/2300. Successful Pairs of Spells and Potions/2300.py create mode 100644 solutions/2301. Match Substring After Replacement/2301.cpp create mode 100644 solutions/2301. Match Substring After Replacement/2301.java create mode 100644 solutions/2301. Match Substring After Replacement/2301.py create mode 100644 solutions/2302. Count Subarrays With Score Less Than K/2302.cpp create mode 100644 solutions/2302. Count Subarrays With Score Less Than K/2302.java create mode 100644 solutions/2302. Count Subarrays With Score Less Than K/2302.py create mode 100644 solutions/2303. Calculate Amount Paid in Taxes/2303.cpp create mode 100644 solutions/2303. Calculate Amount Paid in Taxes/2303.java create mode 100644 solutions/2303. Calculate Amount Paid in Taxes/2303.py create mode 100644 solutions/2304. Minimum Path Cost in a Grid/2304.cpp create mode 100644 solutions/2304. Minimum Path Cost in a Grid/2304.java create mode 100644 solutions/2304. Minimum Path Cost in a Grid/2304.py create mode 100644 solutions/2305. Fair Distribution of Cookies/2305.cpp create mode 100644 solutions/2305. Fair Distribution of Cookies/2305.java create mode 100644 solutions/2305. Fair Distribution of Cookies/2305.py create mode 100644 solutions/2306. Naming a Company/2306.cpp create mode 100644 solutions/2306. Naming a Company/2306.java create mode 100644 solutions/2306. Naming a Company/2306.py create mode 100644 solutions/2307. Check for Contradictions in Equations/2307.cpp create mode 100644 solutions/2307. Check for Contradictions in Equations/2307.java create mode 100644 solutions/2307. Check for Contradictions in Equations/2307.py create mode 100644 solutions/2308. Arrange Table by Gender/2308.sql create mode 100644 solutions/2309. Greatest English Letter in Upper and Lower Case/2309.cpp create mode 100644 solutions/2309. Greatest English Letter in Upper and Lower Case/2309.java create mode 100644 solutions/2309. Greatest English Letter in Upper and Lower Case/2309.py create mode 100644 solutions/231. Power of Two/231.cpp create mode 100644 solutions/231. Power of Two/231.java create mode 100644 solutions/231. Power of Two/231.py create mode 100644 solutions/2310. Sum of Numbers With Units Digit K/2310.cpp create mode 100644 solutions/2310. Sum of Numbers With Units Digit K/2310.java create mode 100644 solutions/2310. Sum of Numbers With Units Digit K/2310.py create mode 100644 solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.cpp create mode 100644 solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.java create mode 100644 solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.py create mode 100644 solutions/2312. Selling Pieces of Wood/2312.cpp create mode 100644 solutions/2312. Selling Pieces of Wood/2312.java create mode 100644 solutions/2312. Selling Pieces of Wood/2312.py create mode 100644 solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.cpp create mode 100644 solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.py create mode 100644 solutions/2314. The First Day of the Maximum Recorded Degree in Each City/2314.sql create mode 100644 solutions/2315. Count Asterisks/2315.cpp create mode 100644 solutions/2315. Count Asterisks/2315.java create mode 100644 solutions/2315. Count Asterisks/2315.py create mode 100644 solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.cpp create mode 100644 solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.java create mode 100644 solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.py create mode 100644 solutions/2317. Maximum XOR After Operations/2317.cpp create mode 100644 solutions/2317. Maximum XOR After Operations/2317.java create mode 100644 solutions/2317. Maximum XOR After Operations/2317.py create mode 100644 solutions/2318. Number of Distinct Roll Sequences/2318.cpp create mode 100644 solutions/2318. Number of Distinct Roll Sequences/2318.java create mode 100644 solutions/2318. Number of Distinct Roll Sequences/2318.py create mode 100644 solutions/2319. Check if Matrix Is X-Matrix/2319.cpp create mode 100644 solutions/2319. Check if Matrix Is X-Matrix/2319.java create mode 100644 solutions/2319. Check if Matrix Is X-Matrix/2319.py create mode 100644 solutions/232. Implement Queue using Stacks/232.cpp create mode 100644 solutions/232. Implement Queue using Stacks/232.java create mode 100644 solutions/232. Implement Queue using Stacks/232.py create mode 100644 solutions/2320. Count Number of Ways to Place Houses/2320.cpp create mode 100644 solutions/2320. Count Number of Ways to Place Houses/2320.java create mode 100644 solutions/2320. Count Number of Ways to Place Houses/2320.py create mode 100644 solutions/2321. Maximum Score Of Spliced Array/2321.cpp create mode 100644 solutions/2321. Maximum Score Of Spliced Array/2321.java create mode 100644 solutions/2321. Maximum Score Of Spliced Array/2321.py create mode 100644 solutions/2322. Minimum Score After Removals on a Tree/2322.cpp create mode 100644 solutions/2322. Minimum Score After Removals on a Tree/2322.java create mode 100644 solutions/2322. Minimum Score After Removals on a Tree/2322.py create mode 100644 solutions/2323. Find Minimum Time to Finish All Jobs II/2323.cpp create mode 100644 solutions/2323. Find Minimum Time to Finish All Jobs II/2323.java create mode 100644 solutions/2323. Find Minimum Time to Finish All Jobs II/2323.py create mode 100644 solutions/2324. Product Sales Analysis IV/2324.sql create mode 100644 solutions/2325. Decode the Message/2325.cpp create mode 100644 solutions/2325. Decode the Message/2325.java create mode 100644 solutions/2325. Decode the Message/2325.py create mode 100644 solutions/2326. Spiral Matrix IV/2326.cpp create mode 100644 solutions/2326. Spiral Matrix IV/2326.java create mode 100644 solutions/2326. Spiral Matrix IV/2326.py create mode 100644 solutions/2327. Number of People Aware of a Secret/2327.cpp create mode 100644 solutions/2327. Number of People Aware of a Secret/2327.java create mode 100644 solutions/2327. Number of People Aware of a Secret/2327.py create mode 100644 solutions/2328. Number of Increasing Paths in a Grid/2328.cpp create mode 100644 solutions/2328. Number of Increasing Paths in a Grid/2328.java create mode 100644 solutions/2328. Number of Increasing Paths in a Grid/2328.py create mode 100644 solutions/2329. Product Sales Analysis V/2329.sql create mode 100644 solutions/233. Number of Digit One/233.cpp create mode 100644 solutions/233. Number of Digit One/233.java create mode 100644 solutions/233. Number of Digit One/233.py create mode 100644 solutions/2330. Valid Palindrome IV/2330.cpp create mode 100644 solutions/2330. Valid Palindrome IV/2330.java create mode 100644 solutions/2330. Valid Palindrome IV/2330.py create mode 100644 solutions/2331. Evaluate Boolean Binary Tree/2331.cpp create mode 100644 solutions/2331. Evaluate Boolean Binary Tree/2331.java create mode 100644 solutions/2331. Evaluate Boolean Binary Tree/2331.py create mode 100644 solutions/2332. The Latest Time to Catch a Bus/2332.cpp create mode 100644 solutions/2332. The Latest Time to Catch a Bus/2332.java create mode 100644 solutions/2332. The Latest Time to Catch a Bus/2332.py create mode 100644 solutions/2333. Minimum Sum of Squared Difference/2333.cpp create mode 100644 solutions/2333. Minimum Sum of Squared Difference/2333.java create mode 100644 solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.cpp create mode 100644 solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.java create mode 100644 solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.py create mode 100644 solutions/2335. Minimum Amount of Time to Fill Cups/2335.cpp create mode 100644 solutions/2335. Minimum Amount of Time to Fill Cups/2335.java create mode 100644 solutions/2335. Minimum Amount of Time to Fill Cups/2335.py create mode 100644 solutions/2336. Smallest Number in Infinite Set/2336.cpp create mode 100644 solutions/2336. Smallest Number in Infinite Set/2336.java create mode 100644 solutions/2337. Move Pieces to Obtain a String/2337.cpp create mode 100644 solutions/2337. Move Pieces to Obtain a String/2337.java create mode 100644 solutions/2337. Move Pieces to Obtain a String/2337.py create mode 100644 solutions/2338. Count the Number of Ideal Arrays/2338.cpp create mode 100644 solutions/2339. All the Matches of the League/2339.sql create mode 100644 solutions/234. Palindrome Linked List/234.cpp create mode 100644 solutions/234. Palindrome Linked List/234.java create mode 100644 solutions/234. Palindrome Linked List/234.py create mode 100644 solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.cpp create mode 100644 solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.java create mode 100644 solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.py create mode 100644 solutions/2341. Maximum Number of Pairs in Array/2341.cpp create mode 100644 solutions/2341. Maximum Number of Pairs in Array/2341.java create mode 100644 solutions/2341. Maximum Number of Pairs in Array/2341.py create mode 100644 solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.cpp create mode 100644 solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.java create mode 100644 solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.py create mode 100644 solutions/2343. Query Kth Smallest Trimmed Number/2343.cpp create mode 100644 solutions/2344. Minimum Deletions to Make Array Divisible/2344.cpp create mode 100644 solutions/2344. Minimum Deletions to Make Array Divisible/2344.java create mode 100644 solutions/2344. Minimum Deletions to Make Array Divisible/2344.py create mode 100644 solutions/2345. Finding the Number of Visible Mountains/2345-2.cpp create mode 100644 solutions/2345. Finding the Number of Visible Mountains/2345.cpp create mode 100644 solutions/2345. Finding the Number of Visible Mountains/2345.java create mode 100644 solutions/2345. Finding the Number of Visible Mountains/2345.py create mode 100644 solutions/2346. Compute the Rank as a Percentage/2346.sql create mode 100644 solutions/2347. Best Poker Hand/2347.cpp create mode 100644 solutions/2347. Best Poker Hand/2347.java create mode 100644 solutions/2347. Best Poker Hand/2347.py create mode 100644 solutions/2348. Number of Zero-Filled Subarrays/2348.cpp create mode 100644 solutions/2348. Number of Zero-Filled Subarrays/2348.java create mode 100644 solutions/2348. Number of Zero-Filled Subarrays/2348.py create mode 100644 solutions/2349. Design a Number Container System/2349.cpp create mode 100644 solutions/2349. Design a Number Container System/2349.java create mode 100644 solutions/2349. Design a Number Container System/2349.py create mode 100644 solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.cpp create mode 100644 solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.java create mode 100644 solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.py create mode 100644 solutions/2350. Shortest Impossible Sequence of Rolls/2350.cpp create mode 100644 solutions/2350. Shortest Impossible Sequence of Rolls/2350.java create mode 100644 solutions/2350. Shortest Impossible Sequence of Rolls/2350.py create mode 100644 solutions/2351. First Letter to Appear Twice/2351.cpp create mode 100644 solutions/2351. First Letter to Appear Twice/2351.java create mode 100644 solutions/2351. First Letter to Appear Twice/2351.py create mode 100644 solutions/2352. Equal Row and Column Pairs/2352.cpp create mode 100644 solutions/2352. Equal Row and Column Pairs/2352.java create mode 100644 solutions/2352. Equal Row and Column Pairs/2352.py create mode 100644 solutions/2353. Design a Food Rating System/2353.cpp create mode 100644 solutions/2353. Design a Food Rating System/2353.java create mode 100644 solutions/2353. Design a Food Rating System/2353.py create mode 100644 solutions/2354. Number of Excellent Pairs/2354.cpp create mode 100644 solutions/2354. Number of Excellent Pairs/2354.java create mode 100644 solutions/2354. Number of Excellent Pairs/2354.py create mode 100644 solutions/2355. Maximum Number of Books You Can Take/2355.cpp create mode 100644 solutions/2355. Maximum Number of Books You Can Take/2355.java create mode 100644 solutions/2355. Maximum Number of Books You Can Take/2355.py create mode 100644 solutions/2356. Number of Unique Subjects Taught by Each Teacher/2356.sql create mode 100644 solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.cpp create mode 100644 solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.java create mode 100644 solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.py create mode 100644 solutions/2358. Maximum Number of Groups Entering a Competition/2358.cpp create mode 100644 solutions/2358. Maximum Number of Groups Entering a Competition/2358.java create mode 100644 solutions/2358. Maximum Number of Groups Entering a Competition/2358.py create mode 100644 solutions/2359. Find Closest Node to Given Two Nodes/2359.cpp create mode 100644 solutions/2359. Find Closest Node to Given Two Nodes/2359.java create mode 100644 solutions/2359. Find Closest Node to Given Two Nodes/2359.py create mode 100644 solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.cpp create mode 100644 solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.java create mode 100644 solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.py create mode 100644 solutions/236. Lowest Common Ancestor of a Binary Tree/236.cpp create mode 100644 solutions/236. Lowest Common Ancestor of a Binary Tree/236.java create mode 100644 solutions/236. Lowest Common Ancestor of a Binary Tree/236.py create mode 100644 solutions/2360. Longest Cycle in a Graph/2360.cpp create mode 100644 solutions/2360. Longest Cycle in a Graph/2360.java create mode 100644 solutions/2360. Longest Cycle in a Graph/2360.py create mode 100644 solutions/2361. Minimum Costs Using the Train Line/2361.cpp create mode 100644 solutions/2361. Minimum Costs Using the Train Line/2361.java create mode 100644 solutions/2361. Minimum Costs Using the Train Line/2361.py create mode 100644 solutions/2362. Generate the Invoice/2362.sql create mode 100644 solutions/2363. Merge Similar Items/2363.cpp create mode 100644 solutions/2363. Merge Similar Items/2363.java create mode 100644 solutions/2363. Merge Similar Items/2363.py create mode 100644 solutions/2364. Count Number of Bad Pairs/2364.cpp create mode 100644 solutions/2364. Count Number of Bad Pairs/2364.java create mode 100644 solutions/2364. Count Number of Bad Pairs/2364.py create mode 100644 solutions/2365. Task Scheduler II/2365.cpp create mode 100644 solutions/2365. Task Scheduler II/2365.java create mode 100644 solutions/2365. Task Scheduler II/2365.py create mode 100644 solutions/2366. Minimum Replacements to Sort the Array/2366.cpp create mode 100644 solutions/2366. Minimum Replacements to Sort the Array/2366.java create mode 100644 solutions/2366. Minimum Replacements to Sort the Array/2366.py create mode 100644 solutions/2367. Number of Arithmetic Triplets/2367.cpp create mode 100644 solutions/2367. Number of Arithmetic Triplets/2367.java create mode 100644 solutions/2367. Number of Arithmetic Triplets/2367.py create mode 100644 solutions/2368. Reachable Nodes With Restrictions/2368.cpp create mode 100644 solutions/2368. Reachable Nodes With Restrictions/2368.java create mode 100644 solutions/2368. Reachable Nodes With Restrictions/2368.py create mode 100644 solutions/2369. Check if There is a Valid Partition For The Array/2369.cpp create mode 100644 solutions/2369. Check if There is a Valid Partition For The Array/2369.java create mode 100644 solutions/2369. Check if There is a Valid Partition For The Array/2369.py create mode 100644 solutions/237. Delete Node in a Linked List/237.cpp create mode 100644 solutions/237. Delete Node in a Linked List/237.java create mode 100644 solutions/237. Delete Node in a Linked List/237.py create mode 100644 solutions/2370. Longest Ideal Subsequence/2370.cpp create mode 100644 solutions/2370. Longest Ideal Subsequence/2370.java create mode 100644 solutions/2370. Longest Ideal Subsequence/2370.py create mode 100644 solutions/2371. Minimize Maximum Value in a Grid/2371.cpp create mode 100644 solutions/2371. Minimize Maximum Value in a Grid/2371.java create mode 100644 solutions/2371. Minimize Maximum Value in a Grid/2371.py create mode 100644 solutions/2372. Calculate the Influence of Each Salesperson/2372.sql create mode 100644 solutions/2373. Largest Local Values in a Matrix/2373.cpp create mode 100644 solutions/2373. Largest Local Values in a Matrix/2373.java create mode 100644 solutions/2373. Largest Local Values in a Matrix/2373.py create mode 100644 solutions/2374. Node With Highest Edge Score/2374.cpp create mode 100644 solutions/2374. Node With Highest Edge Score/2374.java create mode 100644 solutions/2374. Node With Highest Edge Score/2374.py create mode 100644 solutions/2375. Construct Smallest Number From DI String/2375.cpp create mode 100644 solutions/2375. Construct Smallest Number From DI String/2375.java create mode 100644 solutions/2375. Construct Smallest Number From DI String/2375.py create mode 100644 solutions/2376. Count Special Integers/2376.cpp create mode 100644 solutions/2376. Count Special Integers/2376.java create mode 100644 solutions/2376. Count Special Integers/2376.py create mode 100644 solutions/2377. Sort the Olympic Table/2377.sql create mode 100644 solutions/2378. Choose Edges to Maximize Score in a Tree/2378.cpp create mode 100644 solutions/2378. Choose Edges to Maximize Score in a Tree/2378.java create mode 100644 solutions/2378. Choose Edges to Maximize Score in a Tree/2378.py create mode 100644 solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.cpp create mode 100644 solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.java create mode 100644 solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.py create mode 100644 solutions/238. Product of Array Except Self/238-2.cpp create mode 100644 solutions/238. Product of Array Except Self/238-2.java create mode 100644 solutions/238. Product of Array Except Self/238-2.py create mode 100644 solutions/238. Product of Array Except Self/238.cpp create mode 100644 solutions/238. Product of Array Except Self/238.java create mode 100644 solutions/238. Product of Array Except Self/238.py create mode 100644 solutions/2380. Time Needed to Rearrange a Binary String/2380.cpp create mode 100644 solutions/2380. Time Needed to Rearrange a Binary String/2380.java create mode 100644 solutions/2380. Time Needed to Rearrange a Binary String/2380.py create mode 100644 solutions/2381. Shifting Letters II/2381.cpp create mode 100644 solutions/2381. Shifting Letters II/2381.java create mode 100644 solutions/2381. Shifting Letters II/2381.py create mode 100644 solutions/2382. Maximum Segment Sum After Removals/2382.cpp create mode 100644 solutions/2382. Maximum Segment Sum After Removals/2382.java create mode 100644 solutions/2382. Maximum Segment Sum After Removals/2382.py create mode 100644 solutions/2383. Minimum Hours of Training to Win a Competition/2383.cpp create mode 100644 solutions/2383. Minimum Hours of Training to Win a Competition/2383.java create mode 100644 solutions/2383. Minimum Hours of Training to Win a Competition/2383.py create mode 100644 solutions/2384. Largest Palindromic Number/2384.cpp create mode 100644 solutions/2384. Largest Palindromic Number/2384.java create mode 100644 solutions/2384. Largest Palindromic Number/2384.py create mode 100644 solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.cpp create mode 100644 solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.java create mode 100644 solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.py create mode 100644 solutions/2386. Find the K-Sum of an Array/2386.cpp create mode 100644 solutions/2386. Find the K-Sum of an Array/2386.java create mode 100644 solutions/2386. Find the K-Sum of an Array/2386.py create mode 100644 solutions/2387. Median of a Row Wise Sorted Matrix/2387.cpp create mode 100644 solutions/2387. Median of a Row Wise Sorted Matrix/2387.java create mode 100644 solutions/2387. Median of a Row Wise Sorted Matrix/2387.py create mode 100644 solutions/2388. Change Null Values in a Table to the Previous Value/2388.sql create mode 100644 solutions/2389. Longest Subsequence With Limited Sum/2389.cpp create mode 100644 solutions/2389. Longest Subsequence With Limited Sum/2389.java create mode 100644 solutions/2389. Longest Subsequence With Limited Sum/2389.py create mode 100644 solutions/239. Sliding Window Maximum/239.cpp create mode 100644 solutions/239. Sliding Window Maximum/239.java create mode 100644 solutions/239. Sliding Window Maximum/239.py create mode 100644 solutions/2390. Removing Stars From a String/2390.cpp create mode 100644 solutions/2390. Removing Stars From a String/2390.java create mode 100644 solutions/2390. Removing Stars From a String/2390.py create mode 100644 solutions/2391. Minimum Amount of Time to Collect Garbage/2391.cpp create mode 100644 solutions/2391. Minimum Amount of Time to Collect Garbage/2391.java create mode 100644 solutions/2391. Minimum Amount of Time to Collect Garbage/2391.py create mode 100644 solutions/2392. Build a Matrix With Conditions/2392.cpp create mode 100644 solutions/2392. Build a Matrix With Conditions/2392.java create mode 100644 solutions/2392. Build a Matrix With Conditions/2392.py create mode 100644 solutions/2393. Count Strictly Increasing Subarrays/2393.cpp create mode 100644 solutions/2393. Count Strictly Increasing Subarrays/2393.java create mode 100644 solutions/2393. Count Strictly Increasing Subarrays/2393.py create mode 100644 solutions/2394. Employees With Deductions/2394.sql create mode 100644 solutions/2395. Find Subarrays With Equal Sum/2395.cpp create mode 100644 solutions/2395. Find Subarrays With Equal Sum/2395.java create mode 100644 solutions/2395. Find Subarrays With Equal Sum/2395.py create mode 100644 solutions/2396. Strictly Palindromic Number/2396.cpp create mode 100644 solutions/2396. Strictly Palindromic Number/2396.java create mode 100644 solutions/2396. Strictly Palindromic Number/2396.py create mode 100644 solutions/2397. Maximum Rows Covered by Columns/2397.cpp create mode 100644 solutions/2397. Maximum Rows Covered by Columns/2397.java create mode 100644 solutions/2397. Maximum Rows Covered by Columns/2397.py create mode 100644 solutions/2398. Maximum Number of Robots Within Budget/2398.cpp create mode 100644 solutions/2398. Maximum Number of Robots Within Budget/2398.java create mode 100644 solutions/2398. Maximum Number of Robots Within Budget/2398.py create mode 100644 solutions/2399. Check Distances Between Same Letters/2399.cpp create mode 100644 solutions/2399. Check Distances Between Same Letters/2399.java create mode 100644 solutions/2399. Check Distances Between Same Letters/2399.py create mode 100644 solutions/24. Swap Nodes in Pairs/24.cpp create mode 100644 solutions/24. Swap Nodes in Pairs/24.java create mode 100644 solutions/24. Swap Nodes in Pairs/24.py create mode 100644 solutions/240. Search a 2D Matrix II/240.cpp create mode 100644 solutions/240. Search a 2D Matrix II/240.java create mode 100644 solutions/240. Search a 2D Matrix II/240.py create mode 100644 solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.cpp create mode 100644 solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.java create mode 100644 solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.py create mode 100644 solutions/2401. Longest Nice Subarray/2401.cpp create mode 100644 solutions/2401. Longest Nice Subarray/2401.java create mode 100644 solutions/2401. Longest Nice Subarray/2401.py create mode 100644 solutions/2402. Meeting Rooms III/2402.cpp create mode 100644 solutions/2402. Meeting Rooms III/2402.java create mode 100644 solutions/2402. Meeting Rooms III/2402.py create mode 100644 solutions/2403. Minimum Time to Kill All Monsters/2403.cpp create mode 100644 solutions/2403. Minimum Time to Kill All Monsters/2403.java create mode 100644 solutions/2403. Minimum Time to Kill All Monsters/2403.py create mode 100644 solutions/2404. Most Frequent Even Element/2404.cpp create mode 100644 solutions/2404. Most Frequent Even Element/2404.java create mode 100644 solutions/2404. Most Frequent Even Element/2404.py create mode 100644 solutions/2405. Optimal Partition of String/2405.cpp create mode 100644 solutions/2405. Optimal Partition of String/2405.java create mode 100644 solutions/2405. Optimal Partition of String/2405.py create mode 100644 solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.cpp create mode 100644 solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.java create mode 100644 solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.py create mode 100644 solutions/2407. Longest Increasing Subsequence II/2407.cpp create mode 100644 solutions/2408. Design SQL/2408.cpp create mode 100644 solutions/2408. Design SQL/2408.java create mode 100644 solutions/2408. Design SQL/2408.py create mode 100644 solutions/2409. Count Days Spent Together/2409.cpp create mode 100644 solutions/2409. Count Days Spent Together/2409.java create mode 100644 solutions/2409. Count Days Spent Together/2409.py create mode 100644 solutions/241. Different Ways to Add Parentheses/241.cpp create mode 100644 solutions/241. Different Ways to Add Parentheses/241.java create mode 100644 solutions/241. Different Ways to Add Parentheses/241.py create mode 100644 solutions/2410. Maximum Matching of Players With Trainers/2410.cpp create mode 100644 solutions/2410. Maximum Matching of Players With Trainers/2410.java create mode 100644 solutions/2410. Maximum Matching of Players With Trainers/2410.py create mode 100644 solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.cpp create mode 100644 solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.java create mode 100644 solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.py create mode 100644 solutions/2412. Minimum Money Required Before Transactions/2412.cpp create mode 100644 solutions/2412. Minimum Money Required Before Transactions/2412.java create mode 100644 solutions/2412. Minimum Money Required Before Transactions/2412.py create mode 100644 solutions/2413. Smallest Even Multiple/2413.cpp create mode 100644 solutions/2413. Smallest Even Multiple/2413.java create mode 100644 solutions/2413. Smallest Even Multiple/2413.py create mode 100644 solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.cpp create mode 100644 solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.java create mode 100644 solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.py create mode 100644 solutions/2415. Reverse Odd Levels of Binary Tree/2415.cpp create mode 100644 solutions/2415. Reverse Odd Levels of Binary Tree/2415.java create mode 100644 solutions/2415. Reverse Odd Levels of Binary Tree/2415.py create mode 100644 solutions/2416. Sum of Prefix Scores of Strings/2416.cpp create mode 100644 solutions/2416. Sum of Prefix Scores of Strings/2416.java create mode 100644 solutions/2416. Sum of Prefix Scores of Strings/2416.py create mode 100644 solutions/2417. Closest Fair Integer/2417.cpp create mode 100644 solutions/2417. Closest Fair Integer/2417.java create mode 100644 solutions/2417. Closest Fair Integer/2417.py create mode 100644 solutions/2418. Sort the People/2418.cpp create mode 100644 solutions/2418. Sort the People/2418.java create mode 100644 solutions/2418. Sort the People/2418.py create mode 100644 solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.cpp create mode 100644 solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.java create mode 100644 solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.py create mode 100644 solutions/242. Valid Anagram/242.cpp create mode 100644 solutions/242. Valid Anagram/242.java create mode 100644 solutions/242. Valid Anagram/242.py create mode 100644 solutions/2420. Find All Good Indices/2420.cpp create mode 100644 solutions/2420. Find All Good Indices/2420.java create mode 100644 solutions/2420. Find All Good Indices/2420.py create mode 100644 solutions/2421. Number of Good Paths/2421.cpp create mode 100644 solutions/2421. Number of Good Paths/2421.java create mode 100644 solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.cpp create mode 100644 solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.java create mode 100644 solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.py create mode 100644 solutions/2423. Remove Letter To Equalize Frequency/2423.cpp create mode 100644 solutions/2423. Remove Letter To Equalize Frequency/2423.java create mode 100644 solutions/2423. Remove Letter To Equalize Frequency/2423.py create mode 100644 solutions/2424. Longest Uploaded Prefix/2424.cpp create mode 100644 solutions/2424. Longest Uploaded Prefix/2424.java create mode 100644 solutions/2424. Longest Uploaded Prefix/2424.py create mode 100644 solutions/2425. Bitwise XOR of All Pairings/2425.cpp create mode 100644 solutions/2425. Bitwise XOR of All Pairings/2425.java create mode 100644 solutions/2425. Bitwise XOR of All Pairings/2425.py create mode 100644 solutions/2426. Number of Pairs Satisfying Inequality/2426.cpp create mode 100644 solutions/2427. Number of Common Factors/2427.cpp create mode 100644 solutions/2427. Number of Common Factors/2427.java create mode 100644 solutions/2427. Number of Common Factors/2427.py create mode 100644 solutions/2428. Maximum Sum of an Hourglass/2428.cpp create mode 100644 solutions/2428. Maximum Sum of an Hourglass/2428.java create mode 100644 solutions/2428. Maximum Sum of an Hourglass/2428.py create mode 100644 solutions/2429. Minimize XOR/2429.cpp create mode 100644 solutions/2429. Minimize XOR/2429.java create mode 100644 solutions/2429. Minimize XOR/2429.py create mode 100644 solutions/243. Shortest Word Distance/243.cpp create mode 100644 solutions/243. Shortest Word Distance/243.java create mode 100644 solutions/243. Shortest Word Distance/243.py create mode 100644 solutions/2430. Maximum Deletions on a String/2430.cpp create mode 100644 solutions/2430. Maximum Deletions on a String/2430.java create mode 100644 solutions/2430. Maximum Deletions on a String/2430.py create mode 100644 solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.cpp create mode 100644 solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.java create mode 100644 solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.py create mode 100644 solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.cpp create mode 100644 solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.java create mode 100644 solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.py create mode 100644 solutions/2432. The Employee That Worked on the Longest Task/2432.cpp create mode 100644 solutions/2432. The Employee That Worked on the Longest Task/2432.java create mode 100644 solutions/2432. The Employee That Worked on the Longest Task/2432.py create mode 100644 solutions/2433. Find The Original Array of Prefix Xor/2433.cpp create mode 100644 solutions/2433. Find The Original Array of Prefix Xor/2433.java create mode 100644 solutions/2433. Find The Original Array of Prefix Xor/2433.py create mode 100644 solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.cpp create mode 100644 solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.java create mode 100644 solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.py create mode 100644 solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.cpp create mode 100644 solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.java create mode 100644 solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.py create mode 100644 solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.cpp create mode 100644 solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.java create mode 100644 solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.py create mode 100644 solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.cpp create mode 100644 solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.java create mode 100644 solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.py create mode 100644 solutions/2437. Number of Valid Clock Times/2437.cpp create mode 100644 solutions/2437. Number of Valid Clock Times/2437.java create mode 100644 solutions/2437. Number of Valid Clock Times/2437.py create mode 100644 solutions/2438. Range Product Queries of Powers/2438.cpp create mode 100644 solutions/2438. Range Product Queries of Powers/2438.java create mode 100644 solutions/2438. Range Product Queries of Powers/2438.py create mode 100644 solutions/2439. Minimize Maximum of Array/2439.cpp create mode 100644 solutions/2439. Minimize Maximum of Array/2439.java create mode 100644 solutions/2439. Minimize Maximum of Array/2439.py create mode 100644 solutions/244. Shortest Word Distance II/244.cpp create mode 100644 solutions/244. Shortest Word Distance II/244.java create mode 100644 solutions/244. Shortest Word Distance II/244.py create mode 100644 solutions/2440. Create Components With Same Value/2440.cpp create mode 100644 solutions/2440. Create Components With Same Value/2440.java create mode 100644 solutions/2440. Create Components With Same Value/2440.py create mode 100644 solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.cpp create mode 100644 solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.java create mode 100644 solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.py create mode 100644 solutions/2442. Count Number of Distinct Integers After Reverse Operations/2442.cpp create mode 100644 solutions/2443. Sum of Number and Its Reverse/2443.cpp create mode 100644 solutions/2444. Count Subarrays With Fixed Bounds/2444.cpp create mode 100644 solutions/2444. Count Subarrays With Fixed Bounds/2444.java create mode 100644 solutions/2444. Count Subarrays With Fixed Bounds/2444.py create mode 100644 solutions/2445. Number of Nodes With Value One/2445.cpp create mode 100644 solutions/2445. Number of Nodes With Value One/2445.java create mode 100644 solutions/2445. Number of Nodes With Value One/2445.py create mode 100644 solutions/2446. Determine if Two Events Have Conflict/2446.cpp create mode 100644 solutions/2446. Determine if Two Events Have Conflict/2446.java create mode 100644 solutions/2446. Determine if Two Events Have Conflict/2446.py create mode 100644 solutions/2447. Number of Subarrays With GCD Equal to K/2447.cpp create mode 100644 solutions/2447. Number of Subarrays With GCD Equal to K/2447.java create mode 100644 solutions/2447. Number of Subarrays With GCD Equal to K/2447.py create mode 100644 solutions/2448. Minimum Cost to Make Array Equal/2448.cpp create mode 100644 solutions/2448. Minimum Cost to Make Array Equal/2448.java create mode 100644 solutions/2448. Minimum Cost to Make Array Equal/2448.py create mode 100644 solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.cpp create mode 100644 solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.java create mode 100644 solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.py create mode 100644 solutions/245. Shortest Word Distance III/245.cpp create mode 100644 solutions/245. Shortest Word Distance III/245.java create mode 100644 solutions/245. Shortest Word Distance III/245.py create mode 100644 solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.cpp create mode 100644 solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.java create mode 100644 solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.py create mode 100644 solutions/2451. Odd String Difference/2451.cpp create mode 100644 solutions/2451. Odd String Difference/2451.java create mode 100644 solutions/2451. Odd String Difference/2451.py create mode 100644 solutions/2452. Words Within Two Edits of Dictionary/2452.cpp create mode 100644 solutions/2452. Words Within Two Edits of Dictionary/2452.java create mode 100644 solutions/2452. Words Within Two Edits of Dictionary/2452.py create mode 100644 solutions/2453. Destroy Sequential Targets/2453-2.cpp create mode 100644 solutions/2453. Destroy Sequential Targets/2453.cpp create mode 100644 solutions/2453. Destroy Sequential Targets/2453.java create mode 100644 solutions/2453. Destroy Sequential Targets/2453.py create mode 100644 solutions/2454. Next Greater Element IV/2454.cpp create mode 100644 solutions/2454. Next Greater Element IV/2454.java create mode 100644 solutions/2454. Next Greater Element IV/2454.py create mode 100644 solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.cpp create mode 100644 solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.java create mode 100644 solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.py create mode 100644 solutions/2456. Most Popular Video Creator/2456.cpp create mode 100644 solutions/2456. Most Popular Video Creator/2456.java create mode 100644 solutions/2456. Most Popular Video Creator/2456.py create mode 100644 solutions/2457. Minimum Addition to Make Integer Beautiful/2457.cpp create mode 100644 solutions/2457. Minimum Addition to Make Integer Beautiful/2457.java create mode 100644 solutions/2457. Minimum Addition to Make Integer Beautiful/2457.py create mode 100644 solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.cpp create mode 100644 solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.java create mode 100644 solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.py create mode 100644 solutions/2459. Sort Array by Moving Items to Empty Space/2459.py create mode 100644 solutions/246. Strobogrammatic Number/246.cpp create mode 100644 solutions/246. Strobogrammatic Number/246.java create mode 100644 solutions/246. Strobogrammatic Number/246.py create mode 100644 solutions/2460. Apply Operations to an Array/2460-2.cpp create mode 100644 solutions/2460. Apply Operations to an Array/2460-2.java create mode 100644 solutions/2460. Apply Operations to an Array/2460-2.py create mode 100644 solutions/2460. Apply Operations to an Array/2460.cpp create mode 100644 solutions/2460. Apply Operations to an Array/2460.java create mode 100644 solutions/2460. Apply Operations to an Array/2460.py create mode 100644 solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.cpp create mode 100644 solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.java create mode 100644 solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.py create mode 100644 solutions/2462. Total Cost to Hire K Workers/2462.cpp create mode 100644 solutions/2462. Total Cost to Hire K Workers/2462.java create mode 100644 solutions/2462. Total Cost to Hire K Workers/2462.py create mode 100644 solutions/2463. Minimum Total Distance Traveled/2463.cpp create mode 100644 solutions/2463. Minimum Total Distance Traveled/2463.java create mode 100644 solutions/2463. Minimum Total Distance Traveled/2463.py create mode 100644 solutions/2464. Minimum Subarrays in a Valid Split/2464.cpp create mode 100644 solutions/2464. Minimum Subarrays in a Valid Split/2464.java create mode 100644 solutions/2464. Minimum Subarrays in a Valid Split/2464.py create mode 100644 solutions/2465. Number of Distinct Averages/2465.cpp create mode 100644 solutions/2465. Number of Distinct Averages/2465.java create mode 100644 solutions/2465. Number of Distinct Averages/2465.py create mode 100644 solutions/2466. Count Ways To Build Good Strings/2466.cpp create mode 100644 solutions/2466. Count Ways To Build Good Strings/2466.java create mode 100644 solutions/2466. Count Ways To Build Good Strings/2466.py create mode 100644 solutions/2467. Most Profitable Path in a Tree/2467.cpp create mode 100644 solutions/2467. Most Profitable Path in a Tree/2467.java create mode 100644 solutions/2467. Most Profitable Path in a Tree/2467.py create mode 100644 solutions/2468. Split Message Based on Limit/2468.cpp create mode 100644 solutions/2468. Split Message Based on Limit/2468.java create mode 100644 solutions/2468. Split Message Based on Limit/2468.py create mode 100644 solutions/2469. Convert the Temperature/2469.cpp create mode 100644 solutions/2469. Convert the Temperature/2469.java create mode 100644 solutions/2469. Convert the Temperature/2469.py create mode 100644 solutions/247. Strobogrammatic Number II/247.cpp create mode 100644 solutions/247. Strobogrammatic Number II/247.java create mode 100644 solutions/247. Strobogrammatic Number II/247.py create mode 100644 solutions/2470. Number of Subarrays With LCM Equal to K/2470.cpp create mode 100644 solutions/2470. Number of Subarrays With LCM Equal to K/2470.java create mode 100644 solutions/2470. Number of Subarrays With LCM Equal to K/2470.py create mode 100644 solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.cpp create mode 100644 solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.java create mode 100644 solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.py create mode 100644 solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.cpp create mode 100644 solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.java create mode 100644 solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.py create mode 100644 solutions/2473. Minimum Cost to Buy Apples/2473.cpp create mode 100644 solutions/2473. Minimum Cost to Buy Apples/2473.java create mode 100644 solutions/2473. Minimum Cost to Buy Apples/2473.py create mode 100644 solutions/2474. Customers With Strictly Increasing Purchases/2474.sql create mode 100644 solutions/2475. Number of Unequal Triplets in Array/2475.cpp create mode 100644 solutions/2475. Number of Unequal Triplets in Array/2475.java create mode 100644 solutions/2475. Number of Unequal Triplets in Array/2475.py create mode 100644 solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.cpp create mode 100644 solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.java create mode 100644 solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.py create mode 100644 solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.cpp create mode 100644 solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.java create mode 100644 solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.py create mode 100644 solutions/2478. Number of Beautiful Partitions/2478.cpp create mode 100644 solutions/2478. Number of Beautiful Partitions/2478.java create mode 100644 solutions/2478. Number of Beautiful Partitions/2478.py create mode 100644 solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.cpp create mode 100644 solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.java create mode 100644 solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.py create mode 100644 solutions/248. Strobogrammatic Number III/248.cpp create mode 100644 solutions/248. Strobogrammatic Number III/248.java create mode 100644 solutions/248. Strobogrammatic Number III/248.py create mode 100644 solutions/2480. Form a Chemical Bond/2480.sql create mode 100644 solutions/2481. Minimum Cuts to Divide a Circle/2481.cpp create mode 100644 solutions/2481. Minimum Cuts to Divide a Circle/2481.java create mode 100644 solutions/2481. Minimum Cuts to Divide a Circle/2481.py create mode 100644 solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.cpp create mode 100644 solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.java create mode 100644 solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.py create mode 100644 solutions/2483. Minimum Penalty for a Shop/2483.cpp create mode 100644 solutions/2483. Minimum Penalty for a Shop/2483.java create mode 100644 solutions/2483. Minimum Penalty for a Shop/2483.py create mode 100644 solutions/2484. Count Palindromic Subsequences/2484.cpp create mode 100644 solutions/2484. Count Palindromic Subsequences/2484.java create mode 100644 solutions/2484. Count Palindromic Subsequences/2484.py create mode 100644 solutions/2485. Find the Pivot Integer/2485.cpp create mode 100644 solutions/2485. Find the Pivot Integer/2485.java create mode 100644 solutions/2485. Find the Pivot Integer/2485.py create mode 100644 solutions/2486. Append Characters to String to Make Subsequence/2486.cpp create mode 100644 solutions/2486. Append Characters to String to Make Subsequence/2486.java create mode 100644 solutions/2486. Append Characters to String to Make Subsequence/2486.py create mode 100644 solutions/2487. Remove Nodes From Linked List/2487.cpp create mode 100644 solutions/2487. Remove Nodes From Linked List/2487.java create mode 100644 solutions/2487. Remove Nodes From Linked List/2487.py create mode 100644 solutions/2488. Count Subarrays With Median K/2488.cpp create mode 100644 solutions/2488. Count Subarrays With Median K/2488.java create mode 100644 solutions/2488. Count Subarrays With Median K/2488.py create mode 100644 solutions/2489. Number of Substrings With Fixed Ratio/2489.cpp create mode 100644 solutions/2489. Number of Substrings With Fixed Ratio/2489.java create mode 100644 solutions/2489. Number of Substrings With Fixed Ratio/2489.py create mode 100644 solutions/249. Group Shifted Strings/249.cpp create mode 100644 solutions/249. Group Shifted Strings/249.java create mode 100644 solutions/249. Group Shifted Strings/249.py create mode 100644 solutions/2490. Circular Sentence/2490.cpp create mode 100644 solutions/2490. Circular Sentence/2490.java create mode 100644 solutions/2490. Circular Sentence/2490.py create mode 100644 solutions/2491. Divide Players Into Teams of Equal Skill/2491.cpp create mode 100644 solutions/2491. Divide Players Into Teams of Equal Skill/2491.java create mode 100644 solutions/2491. Divide Players Into Teams of Equal Skill/2491.py create mode 100644 solutions/2492. Minimum Score of a Path Between Two Cities/2492.cpp create mode 100644 solutions/2492. Minimum Score of a Path Between Two Cities/2492.java create mode 100644 solutions/2492. Minimum Score of a Path Between Two Cities/2492.py create mode 100644 solutions/2493. Divide Nodes Into the Maximum Number of Groups/2493.cpp create mode 100644 solutions/2494. Merge Overlapping Events in the Same Hall/2494.sql create mode 100644 solutions/2495. Number of Subarrays Having Even Product/2495.cpp create mode 100644 solutions/2495. Number of Subarrays Having Even Product/2495.java create mode 100644 solutions/2495. Number of Subarrays Having Even Product/2495.py create mode 100644 solutions/2496. Maximum Value of a String in an Array/2496.cpp create mode 100644 solutions/2496. Maximum Value of a String in an Array/2496.java create mode 100644 solutions/2496. Maximum Value of a String in an Array/2496.py create mode 100644 solutions/2497. Maximum Star Sum of a Graph/2497.cpp create mode 100644 solutions/2497. Maximum Star Sum of a Graph/2497.java create mode 100644 solutions/2497. Maximum Star Sum of a Graph/2497.py create mode 100644 solutions/2498. Frog Jump II/2498.cpp create mode 100644 solutions/2498. Frog Jump II/2498.java create mode 100644 solutions/2498. Frog Jump II/2498.py create mode 100644 solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.cpp create mode 100644 solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.java create mode 100644 solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.py create mode 100644 solutions/25. Reverse Nodes in k-Group/25-2.cpp create mode 100644 solutions/25. Reverse Nodes in k-Group/25-2.java create mode 100644 solutions/25. Reverse Nodes in k-Group/25-2.py create mode 100644 solutions/25. Reverse Nodes in k-Group/25.cpp create mode 100644 solutions/25. Reverse Nodes in k-Group/25.java create mode 100644 solutions/25. Reverse Nodes in k-Group/25.py create mode 100644 solutions/250. Count Univalue Subtrees/250.cpp create mode 100644 solutions/250. Count Univalue Subtrees/250.java create mode 100644 solutions/250. Count Univalue Subtrees/250.py create mode 100644 solutions/2500. Delete Greatest Value in Each Row/2500.cpp create mode 100644 solutions/2500. Delete Greatest Value in Each Row/2500.java create mode 100644 solutions/2500. Delete Greatest Value in Each Row/2500.py create mode 100644 solutions/2501. Longest Square Streak in an Array/2501.cpp create mode 100644 solutions/2502. Design Memory Allocator/2502.cpp create mode 100644 solutions/2502. Design Memory Allocator/2502.java create mode 100644 solutions/2502. Design Memory Allocator/2502.py create mode 100644 solutions/2503. Maximum Number of Points From Grid Queries/2503.cpp create mode 100644 solutions/2503. Maximum Number of Points From Grid Queries/2503.java create mode 100644 solutions/2503. Maximum Number of Points From Grid Queries/2503.py create mode 100644 solutions/2504. Concatenate the Name and the Profession/2504.sql create mode 100644 solutions/2505. Bitwise OR of All Subsequence Sums/2505.cpp create mode 100644 solutions/2505. Bitwise OR of All Subsequence Sums/2505.java create mode 100644 solutions/2505. Bitwise OR of All Subsequence Sums/2505.py create mode 100644 solutions/2506. Count Pairs Of Similar Strings/2506-2.py create mode 100644 solutions/2506. Count Pairs Of Similar Strings/2506.cpp create mode 100644 solutions/2506. Count Pairs Of Similar Strings/2506.java create mode 100644 solutions/2506. Count Pairs Of Similar Strings/2506.py create mode 100644 solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.cpp create mode 100644 solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.java create mode 100644 solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.py create mode 100644 solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.cpp create mode 100644 solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.java create mode 100644 solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.py create mode 100644 solutions/2509. Cycle Length Queries in a Tree/2509.cpp create mode 100644 solutions/2509. Cycle Length Queries in a Tree/2509.java create mode 100644 solutions/2509. Cycle Length Queries in a Tree/2509.py create mode 100644 solutions/251. Flatten 2D Vector/251-2.cpp create mode 100644 solutions/251. Flatten 2D Vector/251.cpp create mode 100644 solutions/251. Flatten 2D Vector/251.java create mode 100644 solutions/251. Flatten 2D Vector/251.py create mode 100644 solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.cpp create mode 100644 solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.java create mode 100644 solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.py create mode 100644 solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.cpp create mode 100644 solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.java create mode 100644 solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.py create mode 100644 solutions/2512. Reward Top K Students/2512.cpp create mode 100644 solutions/2512. Reward Top K Students/2512.java create mode 100644 solutions/2512. Reward Top K Students/2512.py create mode 100644 solutions/2513. Minimize the Maximum of Two Arrays/2513.cpp create mode 100644 solutions/2513. Minimize the Maximum of Two Arrays/2513.java create mode 100644 solutions/2513. Minimize the Maximum of Two Arrays/2513.py create mode 100644 solutions/2514. Count Anagrams/2514.cpp create mode 100644 solutions/2514. Count Anagrams/2514.java create mode 100644 solutions/2514. Count Anagrams/2514.py create mode 100644 solutions/2515. Shortest Distance to Target String in a Circular Array/2515.cpp create mode 100644 solutions/2515. Shortest Distance to Target String in a Circular Array/2515.java create mode 100644 solutions/2515. Shortest Distance to Target String in a Circular Array/2515.py create mode 100644 solutions/2516. Take K of Each Character From Left and Right/2516.cpp create mode 100644 solutions/2516. Take K of Each Character From Left and Right/2516.java create mode 100644 solutions/2516. Take K of Each Character From Left and Right/2516.py create mode 100644 solutions/2517. Maximum Tastiness of Candy Basket/2517.cpp create mode 100644 solutions/2517. Maximum Tastiness of Candy Basket/2517.java create mode 100644 solutions/2517. Maximum Tastiness of Candy Basket/2517.py create mode 100644 solutions/2518. Number of Great Partitions/2518.cpp create mode 100644 solutions/2518. Number of Great Partitions/2518.java create mode 100644 solutions/2518. Number of Great Partitions/2518.py create mode 100644 solutions/2519. Count the Number of K-Big Indices/2519.cpp create mode 100644 solutions/2519. Count the Number of K-Big Indices/2519.java create mode 100644 solutions/2519. Count the Number of K-Big Indices/2519.py create mode 100644 solutions/252. Meeting Rooms/252.cpp create mode 100644 solutions/252. Meeting Rooms/252.java create mode 100644 solutions/252. Meeting Rooms/252.py create mode 100644 solutions/2520. Count the Digits That Divide a Number/2520.cpp create mode 100644 solutions/2520. Count the Digits That Divide a Number/2520.java create mode 100644 solutions/2520. Count the Digits That Divide a Number/2520.py create mode 100644 solutions/2521. Distinct Prime Factors of Product of Array/2521.cpp create mode 100644 solutions/2521. Distinct Prime Factors of Product of Array/2521.java create mode 100644 solutions/2521. Distinct Prime Factors of Product of Array/2521.py create mode 100644 solutions/2522. Partition String Into Substrings With Values at Most K/2522.cpp create mode 100644 solutions/2522. Partition String Into Substrings With Values at Most K/2522.java create mode 100644 solutions/2522. Partition String Into Substrings With Values at Most K/2522.py create mode 100644 solutions/2523. Closest Prime Numbers in Range/2523.cpp create mode 100644 solutions/2523. Closest Prime Numbers in Range/2523.java create mode 100644 solutions/2523. Closest Prime Numbers in Range/2523.py create mode 100644 solutions/2524. Maximum Frequency Score of a Subarray/2524.cpp create mode 100644 solutions/2524. Maximum Frequency Score of a Subarray/2524.java create mode 100644 solutions/2524. Maximum Frequency Score of a Subarray/2524.py create mode 100644 solutions/2525. Categorize Box According to Criteria/2525.cpp create mode 100644 solutions/2525. Categorize Box According to Criteria/2525.java create mode 100644 solutions/2525. Categorize Box According to Criteria/2525.py create mode 100644 solutions/2526. Find Consecutive Integers from a Data Stream/2526.cpp create mode 100644 solutions/2526. Find Consecutive Integers from a Data Stream/2526.java create mode 100644 solutions/2526. Find Consecutive Integers from a Data Stream/2526.py create mode 100644 solutions/2527. Find Xor-Beauty of Array/2527.cpp create mode 100644 solutions/2527. Find Xor-Beauty of Array/2527.java create mode 100644 solutions/2527. Find Xor-Beauty of Array/2527.py create mode 100644 solutions/2528. Maximize the Minimum Powered City/2528.cpp create mode 100644 solutions/2528. Maximize the Minimum Powered City/2528.java create mode 100644 solutions/2528. Maximize the Minimum Powered City/2528.py create mode 100644 solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.cpp create mode 100644 solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.java create mode 100644 solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.py create mode 100644 solutions/253. Meeting Rooms II/253-2.cpp create mode 100644 solutions/253. Meeting Rooms II/253-2.java create mode 100644 solutions/253. Meeting Rooms II/253-2.py create mode 100644 solutions/253. Meeting Rooms II/253.cpp create mode 100644 solutions/253. Meeting Rooms II/253.java create mode 100644 solutions/253. Meeting Rooms II/253.py create mode 100644 solutions/2530. Maximal Score After Applying K Operations/2530.cpp create mode 100644 solutions/2530. Maximal Score After Applying K Operations/2530.java create mode 100644 solutions/2530. Maximal Score After Applying K Operations/2530.py create mode 100644 solutions/2531. Make Number of Distinct Characters Equal/2531.cpp create mode 100644 solutions/2531. Make Number of Distinct Characters Equal/2531.java create mode 100644 solutions/2531. Make Number of Distinct Characters Equal/2531.py create mode 100644 solutions/2532. Time to Cross a Bridge/2532.cpp create mode 100644 solutions/2532. Time to Cross a Bridge/2532.java create mode 100644 solutions/2532. Time to Cross a Bridge/2532.py create mode 100644 solutions/2533. Number of Good Binary Strings/2533.cpp create mode 100644 solutions/2533. Number of Good Binary Strings/2533.java create mode 100644 solutions/2533. Number of Good Binary Strings/2533.py create mode 100644 solutions/2534. Time Taken to Cross the Door/2534.cpp create mode 100644 solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.cpp create mode 100644 solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.java create mode 100644 solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.py create mode 100644 solutions/2536. Increment Submatrices by One/2536.cpp create mode 100644 solutions/2537. Count the Number of Good Subarrays/2537.cpp create mode 100644 solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.cpp create mode 100644 solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.java create mode 100644 solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.py create mode 100644 solutions/2539. Count the Number of Good Subsequences/2539.cpp create mode 100644 solutions/2539. Count the Number of Good Subsequences/2539.java create mode 100644 solutions/2539. Count the Number of Good Subsequences/2539.py create mode 100644 solutions/254. Factor Combinations/254.cpp create mode 100644 solutions/254. Factor Combinations/254.java create mode 100644 solutions/254. Factor Combinations/254.py create mode 100644 solutions/2540. Minimum Common Value/2540.cpp create mode 100644 solutions/2540. Minimum Common Value/2540.java create mode 100644 solutions/2540. Minimum Common Value/2540.py create mode 100644 solutions/2541. Minimum Operations to Make Array Equal II/2541.cpp create mode 100644 solutions/2541. Minimum Operations to Make Array Equal II/2541.java create mode 100644 solutions/2541. Minimum Operations to Make Array Equal II/2541.py create mode 100644 solutions/2542. Maximum Subsequence Score/2542.cpp create mode 100644 solutions/2542. Maximum Subsequence Score/2542.java create mode 100644 solutions/2542. Maximum Subsequence Score/2542.py create mode 100644 solutions/2543. Check if Point Is Reachable/2543.cpp create mode 100644 solutions/2543. Check if Point Is Reachable/2543.java create mode 100644 solutions/2543. Check if Point Is Reachable/2543.py create mode 100644 solutions/2544. Alternating Digit Sum/2544.cpp create mode 100644 solutions/2544. Alternating Digit Sum/2544.java create mode 100644 solutions/2544. Alternating Digit Sum/2544.py create mode 100644 solutions/2545. Sort the Students by Their Kth Score/2545.cpp create mode 100644 solutions/2545. Sort the Students by Their Kth Score/2545.java create mode 100644 solutions/2545. Sort the Students by Their Kth Score/2545.py create mode 100644 solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.cpp create mode 100644 solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.java create mode 100644 solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.py create mode 100644 solutions/2547. Minimum Cost to Split an Array/2547.cpp create mode 100644 solutions/2547. Minimum Cost to Split an Array/2547.java create mode 100644 solutions/2547. Minimum Cost to Split an Array/2547.py create mode 100644 solutions/2548. Maximum Price to Fill a Bag/2548.cpp create mode 100644 solutions/2548. Maximum Price to Fill a Bag/2548.java create mode 100644 solutions/2548. Maximum Price to Fill a Bag/2548.py create mode 100644 solutions/2549. Count Distinct Numbers on Board/2549.cpp create mode 100644 solutions/2549. Count Distinct Numbers on Board/2549.java create mode 100644 solutions/2549. Count Distinct Numbers on Board/2549.py create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.cpp create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.java create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.py create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.cpp create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.java create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.py create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255.cpp create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255.java create mode 100644 solutions/255. Verify Preorder Sequence in Binary Search Tree/255.py create mode 100644 solutions/2550. Count Collisions of Monkeys on a Polygon/2550.cpp create mode 100644 solutions/2550. Count Collisions of Monkeys on a Polygon/2550.java create mode 100644 solutions/2550. Count Collisions of Monkeys on a Polygon/2550.py create mode 100644 solutions/2551. Put Marbles in Bags/2551.cpp create mode 100644 solutions/2551. Put Marbles in Bags/2551.java create mode 100644 solutions/2551. Put Marbles in Bags/2551.py create mode 100644 solutions/2552. Count Increasing Quadruplets/2552.cpp create mode 100644 solutions/2552. Count Increasing Quadruplets/2552.java create mode 100644 solutions/2552. Count Increasing Quadruplets/2552.py create mode 100644 solutions/2553. Separate the Digits in an Array/2553.cpp create mode 100644 solutions/2553. Separate the Digits in an Array/2553.java create mode 100644 solutions/2553. Separate the Digits in an Array/2553.py create mode 100644 solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.cpp create mode 100644 solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.java create mode 100644 solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.py create mode 100644 solutions/2555. Maximize Win From Two Segments/2555.cpp create mode 100644 solutions/2555. Maximize Win From Two Segments/2555.java create mode 100644 solutions/2555. Maximize Win From Two Segments/2555.py create mode 100644 solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.cpp create mode 100644 solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.java create mode 100644 solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.py create mode 100644 solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.cpp create mode 100644 solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.java create mode 100644 solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.py create mode 100644 solutions/2558. Take Gifts From the Richest Pile/2558.cpp create mode 100644 solutions/2558. Take Gifts From the Richest Pile/2558.java create mode 100644 solutions/2558. Take Gifts From the Richest Pile/2558.py create mode 100644 solutions/2559. Count Vowel Strings in Ranges/2559.cpp create mode 100644 solutions/2559. Count Vowel Strings in Ranges/2559.java create mode 100644 solutions/2559. Count Vowel Strings in Ranges/2559.py create mode 100644 solutions/256. Paint House/256.cpp create mode 100644 solutions/256. Paint House/256.java create mode 100644 solutions/256. Paint House/256.py create mode 100644 solutions/2560. House Robber IV/2560.cpp create mode 100644 solutions/2560. House Robber IV/2560.java create mode 100644 solutions/2560. House Robber IV/2560.py create mode 100644 solutions/2561. Rearranging Fruits/2561.cpp create mode 100644 solutions/2561. Rearranging Fruits/2561.java create mode 100644 solutions/2561. Rearranging Fruits/2561.py create mode 100644 solutions/2562. Find the Array Concatenation Value/2562.cpp create mode 100644 solutions/2563. Count the Number of Fair Pairs/2563.cpp create mode 100644 solutions/2563. Count the Number of Fair Pairs/2563.java create mode 100644 solutions/2563. Count the Number of Fair Pairs/2563.py create mode 100644 solutions/2564. Substring XOR Queries/2564.cpp create mode 100644 solutions/2564. Substring XOR Queries/2564.java create mode 100644 solutions/2564. Substring XOR Queries/2564.py create mode 100644 solutions/2565. Subsequence With the Minimum Score/2565.py create mode 100644 solutions/2566. Maximum Difference by Remapping a Digit/2566.cpp create mode 100644 solutions/2566. Maximum Difference by Remapping a Digit/2566.java create mode 100644 solutions/2566. Maximum Difference by Remapping a Digit/2566.py create mode 100644 solutions/2567. Minimum Score by Changing Two Elements/2567.cpp create mode 100644 solutions/2567. Minimum Score by Changing Two Elements/2567.java create mode 100644 solutions/2567. Minimum Score by Changing Two Elements/2567.py create mode 100644 solutions/2568. Minimum Impossible OR/2568.cpp create mode 100644 solutions/2568. Minimum Impossible OR/2568.java create mode 100644 solutions/2568. Minimum Impossible OR/2568.py create mode 100644 solutions/2569. Handling Sum Queries After Update/2569.cpp create mode 100644 solutions/257. Binary Tree Paths/257.cpp create mode 100644 solutions/257. Binary Tree Paths/257.java create mode 100644 solutions/257. Binary Tree Paths/257.py create mode 100644 solutions/2570. Merge Two 2D Arrays by Summing Values/2570.cpp create mode 100644 solutions/2570. Merge Two 2D Arrays by Summing Values/2570.java create mode 100644 solutions/2570. Merge Two 2D Arrays by Summing Values/2570.py create mode 100644 solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.cpp create mode 100644 solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.java create mode 100644 solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.py create mode 100644 solutions/2572. Count the Number of Square-Free Subsets/2572.cpp create mode 100644 solutions/2572. Count the Number of Square-Free Subsets/2572.java create mode 100644 solutions/2572. Count the Number of Square-Free Subsets/2572.py create mode 100644 solutions/2573. Find the String with LCP/2573.cpp create mode 100644 solutions/2574. Left and Right Sum Differences/2574-2.cpp create mode 100644 solutions/2574. Left and Right Sum Differences/2574-2.java create mode 100644 solutions/2574. Left and Right Sum Differences/2574-2.py create mode 100644 solutions/2574. Left and Right Sum Differences/2574.cpp create mode 100644 solutions/2574. Left and Right Sum Differences/2574.java create mode 100644 solutions/2574. Left and Right Sum Differences/2574.py create mode 100644 solutions/2575. Find the Divisibility Array of a String/2575.cpp create mode 100644 solutions/2575. Find the Divisibility Array of a String/2575.java create mode 100644 solutions/2575. Find the Divisibility Array of a String/2575.py create mode 100644 solutions/2576. Find the Maximum Number of Marked Indices/2576-2.cpp create mode 100644 solutions/2576. Find the Maximum Number of Marked Indices/2576-2.java create mode 100644 solutions/2576. Find the Maximum Number of Marked Indices/2576-2.py create mode 100644 solutions/2576. Find the Maximum Number of Marked Indices/2576.cpp create mode 100644 solutions/2576. Find the Maximum Number of Marked Indices/2576.java create mode 100644 solutions/2576. Find the Maximum Number of Marked Indices/2576.py create mode 100644 solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.cpp create mode 100644 solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.java create mode 100644 solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.py create mode 100644 solutions/2578. Split With Minimum Sum/2578.cpp create mode 100644 solutions/2578. Split With Minimum Sum/2578.java create mode 100644 solutions/2578. Split With Minimum Sum/2578.py create mode 100644 solutions/2579. Count Total Number of Colored Cells/2579.cpp create mode 100644 solutions/2579. Count Total Number of Colored Cells/2579.java create mode 100644 solutions/2579. Count Total Number of Colored Cells/2579.py create mode 100644 solutions/258. Add Digits/258.cpp create mode 100644 solutions/258. Add Digits/258.java create mode 100644 solutions/258. Add Digits/258.py create mode 100644 solutions/2580. Count Ways to Group Overlapping Ranges/2580.cpp create mode 100644 solutions/2580. Count Ways to Group Overlapping Ranges/2580.java create mode 100644 solutions/2580. Count Ways to Group Overlapping Ranges/2580.py create mode 100644 solutions/2581. Count Number of Possible Root Nodes/2581.cpp create mode 100644 solutions/2581. Count Number of Possible Root Nodes/2581.java create mode 100644 solutions/2581. Count Number of Possible Root Nodes/2581.py create mode 100644 solutions/2582. Pass the Pillow/2582.cpp create mode 100644 solutions/2582. Pass the Pillow/2582.java create mode 100644 solutions/2582. Pass the Pillow/2582.py create mode 100644 solutions/2583. Kth Largest Sum in a Binary Tree/2583.cpp create mode 100644 solutions/2583. Kth Largest Sum in a Binary Tree/2583.java create mode 100644 solutions/2583. Kth Largest Sum in a Binary Tree/2583.py create mode 100644 solutions/2584. Split the Array to Make Coprime Products/2584.cpp create mode 100644 solutions/2584. Split the Array to Make Coprime Products/2584.java create mode 100644 solutions/2584. Split the Array to Make Coprime Products/2584.py create mode 100644 solutions/2585. Number of Ways to Earn Points/2585-2.cpp create mode 100644 solutions/2585. Number of Ways to Earn Points/2585-2.java create mode 100644 solutions/2585. Number of Ways to Earn Points/2585-2.py create mode 100644 solutions/2585. Number of Ways to Earn Points/2585.cpp create mode 100644 solutions/2585. Number of Ways to Earn Points/2585.java create mode 100644 solutions/2585. Number of Ways to Earn Points/2585.py create mode 100644 solutions/2586. Count the Number of Vowel Strings in Range/2586.cpp create mode 100644 solutions/2586. Count the Number of Vowel Strings in Range/2586.java create mode 100644 solutions/2586. Count the Number of Vowel Strings in Range/2586.py create mode 100644 solutions/2587. Rearrange Array to Maximize Prefix Score/2587.cpp create mode 100644 solutions/2587. Rearrange Array to Maximize Prefix Score/2587.java create mode 100644 solutions/2587. Rearrange Array to Maximize Prefix Score/2587.py create mode 100644 solutions/2588. Count the Number of Beautiful Subarrays/2588.cpp create mode 100644 solutions/2588. Count the Number of Beautiful Subarrays/2588.java create mode 100644 solutions/2588. Count the Number of Beautiful Subarrays/2588.py create mode 100644 solutions/2589. Minimum Time to Complete All Tasks/2589.cpp create mode 100644 solutions/2589. Minimum Time to Complete All Tasks/2589.java create mode 100644 solutions/2589. Minimum Time to Complete All Tasks/2589.py create mode 100644 solutions/259. 3Sum Smaller/259.cpp create mode 100644 solutions/259. 3Sum Smaller/259.java create mode 100644 solutions/259. 3Sum Smaller/259.py create mode 100644 solutions/2590. Design a Todo List/2590.cpp create mode 100644 solutions/2590. Design a Todo List/2590.java create mode 100644 solutions/2590. Design a Todo List/2590.py create mode 100644 solutions/2591. Distribute Money to Maximum Children/2591.cpp create mode 100644 solutions/2591. Distribute Money to Maximum Children/2591.java create mode 100644 solutions/2591. Distribute Money to Maximum Children/2591.py create mode 100644 solutions/2592. Maximize Greatness of an Array/2592.cpp create mode 100644 solutions/2592. Maximize Greatness of an Array/2592.java create mode 100644 solutions/2592. Maximize Greatness of an Array/2592.py create mode 100644 solutions/2593. Find Score of an Array After Marking All Elements/2593.cpp create mode 100644 solutions/2593. Find Score of an Array After Marking All Elements/2593.java create mode 100644 solutions/2593. Find Score of an Array After Marking All Elements/2593.py create mode 100644 solutions/2594. Minimum Time to Repair Cars/2594.cpp create mode 100644 solutions/2594. Minimum Time to Repair Cars/2594.java create mode 100644 solutions/2594. Minimum Time to Repair Cars/2594.py create mode 100644 solutions/2595. Number of Even and Odd Bits/2595.cpp create mode 100644 solutions/2595. Number of Even and Odd Bits/2595.java create mode 100644 solutions/2595. Number of Even and Odd Bits/2595.py create mode 100644 solutions/2596. Check Knight Tour Configuration/2596.cpp create mode 100644 solutions/2596. Check Knight Tour Configuration/2596.java create mode 100644 solutions/2596. Check Knight Tour Configuration/2596.py create mode 100644 solutions/2597. The Number of Beautiful Subsets/2597.cpp create mode 100644 solutions/2597. The Number of Beautiful Subsets/2597.java create mode 100644 solutions/2597. The Number of Beautiful Subsets/2597.py create mode 100644 solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.cpp create mode 100644 solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.java create mode 100644 solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.py create mode 100644 solutions/2599. Make the Prefix Sum Non-negative/2599.cpp create mode 100644 solutions/2599. Make the Prefix Sum Non-negative/2599.java create mode 100644 solutions/2599. Make the Prefix Sum Non-negative/2599.py create mode 100644 solutions/26. Remove Duplicates from Sorted Array/26.cpp create mode 100644 solutions/26. Remove Duplicates from Sorted Array/26.java create mode 100644 solutions/26. Remove Duplicates from Sorted Array/26.py create mode 100644 solutions/260. Single Number III/260.cpp create mode 100644 solutions/260. Single Number III/260.java create mode 100644 solutions/260. Single Number III/260.py create mode 100644 solutions/2600. K Items With the Maximum Sum/2600.cpp create mode 100644 solutions/2600. K Items With the Maximum Sum/2600.java create mode 100644 solutions/2600. K Items With the Maximum Sum/2600.py create mode 100644 solutions/2601. Prime Subtraction Operation/2601.cpp create mode 100644 solutions/2601. Prime Subtraction Operation/2601.java create mode 100644 solutions/2601. Prime Subtraction Operation/2601.py create mode 100644 solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.cpp create mode 100644 solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.java create mode 100644 solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.py create mode 100644 solutions/2603. Collect Coins in a Tree/2603.cpp create mode 100644 solutions/2603. Collect Coins in a Tree/2603.java create mode 100644 solutions/2603. Collect Coins in a Tree/2603.py create mode 100644 solutions/2604. Minimum Time to Eat All Grains/2604.cpp create mode 100644 solutions/2604. Minimum Time to Eat All Grains/2604.java create mode 100644 solutions/2604. Minimum Time to Eat All Grains/2604.py create mode 100644 solutions/2605. Form Smallest Number From Two Digit Arrays/2605.cpp create mode 100644 solutions/2605. Form Smallest Number From Two Digit Arrays/2605.java create mode 100644 solutions/2605. Form Smallest Number From Two Digit Arrays/2605.py create mode 100644 solutions/2606. Find the Substring With Maximum Cost/2606.cpp create mode 100644 solutions/2606. Find the Substring With Maximum Cost/2606.java create mode 100644 solutions/2606. Find the Substring With Maximum Cost/2606.py create mode 100644 solutions/2607. Make K-Subarray Sums Equal/2607.cpp create mode 100644 solutions/2607. Make K-Subarray Sums Equal/2607.java create mode 100644 solutions/2607. Make K-Subarray Sums Equal/2607.py create mode 100644 solutions/2608. Shortest Cycle in a Graph/2608.cpp create mode 100644 solutions/2608. Shortest Cycle in a Graph/2608.java create mode 100644 solutions/2608. Shortest Cycle in a Graph/2608.py create mode 100644 solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.cpp create mode 100644 solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.java create mode 100644 solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.py create mode 100644 solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.cpp create mode 100644 solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.java create mode 100644 solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.py create mode 100644 solutions/261. Graph Valid Tree/261-2.cpp create mode 100644 solutions/261. Graph Valid Tree/261-2.java create mode 100644 solutions/261. Graph Valid Tree/261-2.py create mode 100644 solutions/261. Graph Valid Tree/261.cpp create mode 100644 solutions/261. Graph Valid Tree/261.java create mode 100644 solutions/261. Graph Valid Tree/261.py create mode 100644 solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.cpp create mode 100644 solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.java create mode 100644 solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.py create mode 100644 solutions/2611. Mice and Cheese/2611.cpp create mode 100644 solutions/2611. Mice and Cheese/2611.java create mode 100644 solutions/2611. Mice and Cheese/2611.py create mode 100644 solutions/2612. Minimum Reverse Operations/2612.cpp create mode 100644 solutions/2612. Minimum Reverse Operations/2612.java create mode 100644 solutions/2612. Minimum Reverse Operations/2612.py create mode 100644 solutions/2613. Beautiful Pairs/2613.cpp create mode 100644 solutions/2614. Prime In Diagonal/2614.cpp create mode 100644 solutions/2614. Prime In Diagonal/2614.java create mode 100644 solutions/2614. Prime In Diagonal/2614.py create mode 100644 solutions/2615. Sum of Distances/2615.cpp create mode 100644 solutions/2615. Sum of Distances/2615.java create mode 100644 solutions/2615. Sum of Distances/2615.py create mode 100644 solutions/2616. Minimize the Maximum Difference of Pairs/2616.cpp create mode 100644 solutions/2616. Minimize the Maximum Difference of Pairs/2616.java create mode 100644 solutions/2616. Minimize the Maximum Difference of Pairs/2616.py create mode 100644 solutions/2617. Minimum Number of Visited Cells in a Grid/2617.cpp create mode 100644 solutions/2618. Check if Object Instance of Class/2618.ts create mode 100644 solutions/2619. Array Prototype Last/2619.ts create mode 100644 solutions/262. Trips and Users/262.sql create mode 100644 solutions/2620. Counter/2620.ts create mode 100644 solutions/2621. Sleep/2621.ts create mode 100644 solutions/2622. Cache With Time Limit/2622-2.ts create mode 100644 solutions/2622. Cache With Time Limit/2622.ts create mode 100644 solutions/2623. Memoize/2623.ts create mode 100644 solutions/2624. Snail Traversal/2624.ts create mode 100644 solutions/2625. Flatten Deeply Nested Array/2625.ts create mode 100644 solutions/2626. Array Reduce Transformation/2626.ts create mode 100644 solutions/2627. Debounce/2627.ts create mode 100644 solutions/2628. JSON Deep Equal/2628.ts create mode 100644 solutions/2629. Function Composition/2629.ts create mode 100644 solutions/263. Ugly Number/263.cpp create mode 100644 solutions/263. Ugly Number/263.java create mode 100644 solutions/263. Ugly Number/263.py create mode 100644 solutions/2630. Memoize II/2630.ts create mode 100644 solutions/2631. Group By/2631.ts create mode 100644 solutions/2632. Curry/2632.ts create mode 100644 solutions/2633. Convert Object to JSON String/2633.ts create mode 100644 solutions/2634. Filter Elements from Array/2634.ts create mode 100644 solutions/2635. Apply Transform Over Each Element in Array/2635.ts create mode 100644 solutions/2636. Promise Pool/2636.ts create mode 100644 solutions/2637. Promise Time Limit/2637.ts create mode 100644 solutions/2638. Count the Number of K-Free Subsets/2638.cpp create mode 100644 solutions/2638. Count the Number of K-Free Subsets/2638.java create mode 100644 solutions/2638. Count the Number of K-Free Subsets/2638.py create mode 100644 solutions/2639. Find the Width of Columns of a Grid/2639.cpp create mode 100644 solutions/2639. Find the Width of Columns of a Grid/2639.java create mode 100644 solutions/2639. Find the Width of Columns of a Grid/2639.py create mode 100644 solutions/264. Ugly Number II/264.cpp create mode 100644 solutions/264. Ugly Number II/264.java create mode 100644 solutions/264. Ugly Number II/264.py create mode 100644 solutions/2640. Find the Score of All Prefixes of an Array/2640.cpp create mode 100644 solutions/2640. Find the Score of All Prefixes of an Array/2640.java create mode 100644 solutions/2640. Find the Score of All Prefixes of an Array/2640.py create mode 100644 solutions/2641. Cousins in Binary Tree II/2641.cpp create mode 100644 solutions/2641. Cousins in Binary Tree II/2641.java create mode 100644 solutions/2641. Cousins in Binary Tree II/2641.py create mode 100644 solutions/2642. Design Graph With Shortest Path Calculator/2642.cpp create mode 100644 solutions/2642. Design Graph With Shortest Path Calculator/2642.java create mode 100644 solutions/2642. Design Graph With Shortest Path Calculator/2642.py create mode 100644 solutions/2643. Row With Maximum Ones/2643.cpp create mode 100644 solutions/2643. Row With Maximum Ones/2643.java create mode 100644 solutions/2643. Row With Maximum Ones/2643.py create mode 100644 solutions/2644. Find the Maximum Divisibility Score/2644.cpp create mode 100644 solutions/2644. Find the Maximum Divisibility Score/2644.java create mode 100644 solutions/2644. Find the Maximum Divisibility Score/2644.py create mode 100644 solutions/2645. Minimum Additions to Make Valid String/2645.cpp create mode 100644 solutions/2645. Minimum Additions to Make Valid String/2645.java create mode 100644 solutions/2645. Minimum Additions to Make Valid String/2645.py create mode 100644 solutions/2646. Minimize the Total Price of the Trips/2646.cpp create mode 100644 solutions/2646. Minimize the Total Price of the Trips/2646.java create mode 100644 solutions/2646. Minimize the Total Price of the Trips/2646.py create mode 100644 solutions/2647. Color the Triangle Red/2647.cpp create mode 100644 solutions/2647. Color the Triangle Red/2647.java create mode 100644 solutions/2647. Color the Triangle Red/2647.py create mode 100644 solutions/2648. Generate Fibonacci Sequence/2648.ts create mode 100644 solutions/2649. Nested Array Generator/2649.ts create mode 100644 solutions/265. Paint House II/265.cpp create mode 100644 solutions/265. Paint House II/265.java create mode 100644 solutions/265. Paint House II/265.py create mode 100644 solutions/2650. Design Cancellable Function/2650.ts create mode 100644 solutions/2651. Calculate Delayed Arrival Time/2651.cpp create mode 100644 solutions/2651. Calculate Delayed Arrival Time/2651.java create mode 100644 solutions/2651. Calculate Delayed Arrival Time/2651.py create mode 100644 solutions/2652. Sum Multiples/2652-2.cpp create mode 100644 solutions/2652. Sum Multiples/2652-2.java create mode 100644 solutions/2652. Sum Multiples/2652-2.py create mode 100644 solutions/2652. Sum Multiples/2652.cpp create mode 100644 solutions/2652. Sum Multiples/2652.java create mode 100644 solutions/2652. Sum Multiples/2652.py create mode 100644 solutions/2653. Sliding Subarray Beauty/2653.cpp create mode 100644 solutions/2653. Sliding Subarray Beauty/2653.java create mode 100644 solutions/2653. Sliding Subarray Beauty/2653.py create mode 100644 solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.cpp create mode 100644 solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.java create mode 100644 solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.py create mode 100644 solutions/2655. Find Maximal Uncovered Ranges/2655.cpp create mode 100644 solutions/2655. Find Maximal Uncovered Ranges/2655.java create mode 100644 solutions/2655. Find Maximal Uncovered Ranges/2655.py create mode 100644 solutions/2656. Maximum Sum With Exactly K Elements/2656.cpp create mode 100644 solutions/2656. Maximum Sum With Exactly K Elements/2656.java create mode 100644 solutions/2656. Maximum Sum With Exactly K Elements/2656.py create mode 100644 solutions/2657. Find the Prefix Common Array of Two Arrays/2657.cpp create mode 100644 solutions/2657. Find the Prefix Common Array of Two Arrays/2657.java create mode 100644 solutions/2657. Find the Prefix Common Array of Two Arrays/2657.py create mode 100644 solutions/2658. Maximum Number of Fish in a Grid/2658.cpp create mode 100644 solutions/2658. Maximum Number of Fish in a Grid/2658.java create mode 100644 solutions/2658. Maximum Number of Fish in a Grid/2658.py create mode 100644 solutions/2659. Make Array Empty/2659.cpp create mode 100644 solutions/2659. Make Array Empty/2659.java create mode 100644 solutions/2659. Make Array Empty/2659.py create mode 100644 solutions/266. Palindrome Permutation/266.cpp create mode 100644 solutions/266. Palindrome Permutation/266.java create mode 100644 solutions/266. Palindrome Permutation/266.py create mode 100644 solutions/2660. Determine the Winner of a Bowling Game/2660.cpp create mode 100644 solutions/2660. Determine the Winner of a Bowling Game/2660.java create mode 100644 solutions/2660. Determine the Winner of a Bowling Game/2660.py create mode 100644 solutions/2661. First Completely Painted Row or Column/2661.cpp create mode 100644 solutions/2661. First Completely Painted Row or Column/2661.java create mode 100644 solutions/2661. First Completely Painted Row or Column/2661.py create mode 100644 solutions/2662. Minimum Cost of a Path With Special Roads/2662.cpp create mode 100644 solutions/2662. Minimum Cost of a Path With Special Roads/2662.java create mode 100644 solutions/2662. Minimum Cost of a Path With Special Roads/2662.py create mode 100644 solutions/2663. Lexicographically Smallest Beautiful String/2663.cpp create mode 100644 solutions/2663. Lexicographically Smallest Beautiful String/2663.java create mode 100644 solutions/2663. Lexicographically Smallest Beautiful String/2663.py create mode 100644 "solutions/2664. The Knight\342\200\231s Tour/2664.cpp" create mode 100644 "solutions/2664. The Knight\342\200\231s Tour/2664.java" create mode 100644 "solutions/2664. The Knight\342\200\231s Tour/2664.py" create mode 100644 solutions/2665. Counter II/2665.ts create mode 100644 solutions/2666. Allow One Function Call/2666.ts create mode 100644 solutions/2667. Create Hello World Function/2667.ts create mode 100644 solutions/2668. Find Latest Salaries/2668.sql create mode 100644 solutions/2669. Count Artist Occurrences On Spotify Ranking List/2669.sql create mode 100644 solutions/267. Palindrome Permutation II/267.cpp create mode 100644 solutions/267. Palindrome Permutation II/267.java create mode 100644 solutions/267. Palindrome Permutation II/267.py create mode 100644 solutions/2670. Find the Distinct Difference Array/2670.cpp create mode 100644 solutions/2670. Find the Distinct Difference Array/2670.java create mode 100644 solutions/2670. Find the Distinct Difference Array/2670.py create mode 100644 solutions/2671. Frequency Tracker/2671.cpp create mode 100644 solutions/2671. Frequency Tracker/2671.java create mode 100644 solutions/2671. Frequency Tracker/2671.py create mode 100644 solutions/2672. Number of Adjacent Elements With the Same Color/2672.cpp create mode 100644 solutions/2672. Number of Adjacent Elements With the Same Color/2672.java create mode 100644 solutions/2672. Number of Adjacent Elements With the Same Color/2672.py create mode 100644 solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.cpp create mode 100644 solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.java create mode 100644 solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.py create mode 100644 solutions/2674. Split a Circular Linked List/2674.cpp create mode 100644 solutions/2674. Split a Circular Linked List/2674.java create mode 100644 solutions/2674. Split a Circular Linked List/2674.py create mode 100644 solutions/2675. Array of Objects to Matrix/2675.ts create mode 100644 solutions/2676. Throttle/2676.ts create mode 100644 solutions/2677. Chunk Array/2677.ts create mode 100644 solutions/2678. Number of Senior Citizens/2678.cpp create mode 100644 solutions/2678. Number of Senior Citizens/2678.java create mode 100644 solutions/2678. Number of Senior Citizens/2678.py create mode 100644 solutions/2679. Sum in a Matrix/2679.cpp create mode 100644 solutions/2679. Sum in a Matrix/2679.java create mode 100644 solutions/2679. Sum in a Matrix/2679.py create mode 100644 solutions/268. Missing Number/268.cpp create mode 100644 solutions/268. Missing Number/268.java create mode 100644 solutions/268. Missing Number/268.py create mode 100644 solutions/2680. Maximum OR/2680.cpp create mode 100644 solutions/2680. Maximum OR/2680.java create mode 100644 solutions/2680. Maximum OR/2680.py create mode 100644 solutions/2681. Power of Heroes/2681.cpp create mode 100644 solutions/2681. Power of Heroes/2681.java create mode 100644 solutions/2681. Power of Heroes/2681.py create mode 100644 solutions/2682. Find the Losers of the Circular Game/2682.cpp create mode 100644 solutions/2682. Find the Losers of the Circular Game/2682.java create mode 100644 solutions/2682. Find the Losers of the Circular Game/2682.py create mode 100644 solutions/2683. Neighboring Bitwise XOR/2683.cpp create mode 100644 solutions/2683. Neighboring Bitwise XOR/2683.java create mode 100644 solutions/2683. Neighboring Bitwise XOR/2683.py create mode 100644 solutions/2684. Maximum Number of Moves in a Grid/2684.cpp create mode 100644 solutions/2684. Maximum Number of Moves in a Grid/2684.java create mode 100644 solutions/2684. Maximum Number of Moves in a Grid/2684.py create mode 100644 solutions/2685. Count the Number of Complete Components/2685.cpp create mode 100644 solutions/2685. Count the Number of Complete Components/2685.java create mode 100644 solutions/2685. Count the Number of Complete Components/2685.py create mode 100644 solutions/2686. Immediate Food Delivery III/2686.sql create mode 100644 solutions/2687. Bikes Last Time Used/2687.sql create mode 100644 solutions/2688. Find Active Users/2688.sql create mode 100644 solutions/2689. Extract Kth Character From The Rope Tree/2589-2.py create mode 100644 solutions/2689. Extract Kth Character From The Rope Tree/2689-2.cpp create mode 100644 solutions/2689. Extract Kth Character From The Rope Tree/2689-2.java create mode 100644 solutions/2689. Extract Kth Character From The Rope Tree/2689.cpp create mode 100644 solutions/2689. Extract Kth Character From The Rope Tree/2689.java create mode 100644 solutions/2689. Extract Kth Character From The Rope Tree/2689.py create mode 100644 solutions/269. Alien Dictionary/269.cpp create mode 100644 solutions/269. Alien Dictionary/269.java create mode 100644 solutions/269. Alien Dictionary/269.py create mode 100644 solutions/2690. Infinite Method Object/2690.ts create mode 100644 solutions/2691. Immutability Helper/2691.ts create mode 100644 solutions/2692. Make Object Immutable/2692.ts create mode 100644 solutions/2693. Call Function with Custom Context/2693.ts create mode 100644 solutions/2694. Event Emitter/2694.ts create mode 100644 solutions/2695. Array Wrapper/2695.ts create mode 100644 solutions/2696. Minimum String Length After Removing Substrings/2696.cpp create mode 100644 solutions/2696. Minimum String Length After Removing Substrings/2696.java create mode 100644 solutions/2696. Minimum String Length After Removing Substrings/2696.py create mode 100644 solutions/2697. Lexicographically Smallest Palindrome/2697.cpp create mode 100644 solutions/2697. Lexicographically Smallest Palindrome/2697.java create mode 100644 solutions/2697. Lexicographically Smallest Palindrome/2697.py create mode 100644 solutions/2698. Find the Punishment Number of an Integer/2698.cpp create mode 100644 solutions/2698. Find the Punishment Number of an Integer/2698.java create mode 100644 solutions/2698. Find the Punishment Number of an Integer/2698.py create mode 100644 solutions/2699. Modify Graph Edge Weights/2699.cpp create mode 100644 solutions/2699. Modify Graph Edge Weights/2699.java create mode 100644 solutions/2699. Modify Graph Edge Weights/2699.py create mode 100644 solutions/27. Remove Element/27.cpp create mode 100644 solutions/27. Remove Element/27.java create mode 100644 solutions/27. Remove Element/27.py create mode 100644 solutions/270. Closest Binary Search Tree Value/270.cpp create mode 100644 solutions/270. Closest Binary Search Tree Value/270.java create mode 100644 solutions/270. Closest Binary Search Tree Value/270.py create mode 100644 solutions/2700. Differences Between Two Objects/2700.ts create mode 100644 solutions/2701. Consecutive Transactions with Increasing Amounts/2701.sql create mode 100644 solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.cpp create mode 100644 solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.java create mode 100644 solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.py create mode 100644 solutions/2703. Return Length of Arguments Passed/2703.ts create mode 100644 solutions/2704. To Be Or Not To Be/2704.ts create mode 100644 solutions/2705. Compact Object/2705.ts create mode 100644 solutions/2706. Buy Two Chocolates/2706.cpp create mode 100644 solutions/2706. Buy Two Chocolates/2706.java create mode 100644 solutions/2706. Buy Two Chocolates/2706.py create mode 100644 solutions/2707. Extra Characters in a String/2707.cpp create mode 100644 solutions/2707. Extra Characters in a String/2707.java create mode 100644 solutions/2707. Extra Characters in a String/2707.py create mode 100644 solutions/2708. Maximum Strength of a Group/2708.cpp create mode 100644 solutions/2708. Maximum Strength of a Group/2708.java create mode 100644 solutions/2708. Maximum Strength of a Group/2708.py create mode 100644 solutions/2709. Greatest Common Divisor Traversal/2709.cpp create mode 100644 solutions/2709. Greatest Common Divisor Traversal/2709.java create mode 100644 solutions/2709. Greatest Common Divisor Traversal/2709.py create mode 100644 solutions/271. Encode and Decode Strings/271.cpp create mode 100644 solutions/271. Encode and Decode Strings/271.java create mode 100644 solutions/271. Encode and Decode Strings/271.py create mode 100644 solutions/2710. Remove Trailing Zeros From a String/2710.cpp create mode 100644 solutions/2710. Remove Trailing Zeros From a String/2710.java create mode 100644 solutions/2710. Remove Trailing Zeros From a String/2710.py create mode 100644 solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.cpp create mode 100644 solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.java create mode 100644 solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.py create mode 100644 solutions/2712. Minimum Cost to Make All Characters Equal/2712.cpp create mode 100644 solutions/2712. Minimum Cost to Make All Characters Equal/2712.java create mode 100644 solutions/2712. Minimum Cost to Make All Characters Equal/2712.py create mode 100644 solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.cpp create mode 100644 solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.java create mode 100644 solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.py create mode 100644 solutions/2714. Find Shortest Path with K Hops/2714.cpp create mode 100644 solutions/2714. Find Shortest Path with K Hops/2714.java create mode 100644 solutions/2714. Find Shortest Path with K Hops/2714.py create mode 100644 solutions/2715. Timeout Cancellation/2715.ts create mode 100644 solutions/2716. Minimize String Length/2716.cpp create mode 100644 solutions/2716. Minimize String Length/2716.java create mode 100644 solutions/2716. Minimize String Length/2716.py create mode 100644 solutions/2717. Semi-Ordered Permutation/2717.cpp create mode 100644 solutions/2717. Semi-Ordered Permutation/2717.java create mode 100644 solutions/2717. Semi-Ordered Permutation/2717.py create mode 100644 solutions/2718. Sum of Matrix After Queries/2718.cpp create mode 100644 solutions/2718. Sum of Matrix After Queries/2718.java create mode 100644 solutions/2718. Sum of Matrix After Queries/2718.py create mode 100644 solutions/2719. Count of Integers/2719.cpp create mode 100644 solutions/272. Closest Binary Search Tree Value II/272.cpp create mode 100644 solutions/272. Closest Binary Search Tree Value II/272.java create mode 100644 solutions/272. Closest Binary Search Tree Value II/272.py create mode 100644 solutions/2720. Popularity Percentage/2720.sql create mode 100644 solutions/2721. Execute Asynchronous Functions in Parallel/2721.ts create mode 100644 solutions/2722. Join Two Arrays by ID/2722.ts create mode 100644 solutions/2723. Add Two Promises/2723.ts create mode 100644 solutions/2724. Sort By/2724.ts create mode 100644 solutions/2725. Interval Cancellation/2725.ts create mode 100644 solutions/2726. Calculator with Method Chaining/2726.ts create mode 100644 solutions/2727. Is Object Empty/2727.ts create mode 100644 solutions/2728. Count Houses in a Circular Street/2728.cpp create mode 100644 solutions/2728. Count Houses in a Circular Street/2728.java create mode 100644 solutions/2728. Count Houses in a Circular Street/2728.py create mode 100644 solutions/2729. Check if The Number is Fascinating/2729.cpp create mode 100644 solutions/2729. Check if The Number is Fascinating/2729.java create mode 100644 solutions/2729. Check if The Number is Fascinating/2729.py create mode 100644 solutions/273. Integer to English Words/273.cpp create mode 100644 solutions/273. Integer to English Words/273.java create mode 100644 solutions/273. Integer to English Words/273.py create mode 100644 solutions/2730. Find the Longest Semi-Repetitive Substring/2730.cpp create mode 100644 solutions/2730. Find the Longest Semi-Repetitive Substring/2730.java create mode 100644 solutions/2730. Find the Longest Semi-Repetitive Substring/2730.py create mode 100644 solutions/2731. Movement of Robots/2731.cpp create mode 100644 solutions/2731. Movement of Robots/2731.java create mode 100644 solutions/2731. Movement of Robots/2731.py create mode 100644 solutions/2732. Find a Good Subset of the Matrix/2732.cpp create mode 100644 solutions/2732. Find a Good Subset of the Matrix/2732.java create mode 100644 solutions/2732. Find a Good Subset of the Matrix/2732.py create mode 100644 solutions/2733. Neither Minimum nor Maximum/2733.cpp create mode 100644 solutions/2733. Neither Minimum nor Maximum/2733.java create mode 100644 solutions/2733. Neither Minimum nor Maximum/2733.py create mode 100644 solutions/2734. Lexicographically Smallest String After Substring Operation/2734.cpp create mode 100644 solutions/2734. Lexicographically Smallest String After Substring Operation/2734.java create mode 100644 solutions/2734. Lexicographically Smallest String After Substring Operation/2734.py create mode 100644 solutions/2735. Collecting Chocolates/2735.cpp create mode 100644 solutions/2735. Collecting Chocolates/2735.java create mode 100644 solutions/2735. Collecting Chocolates/2735.py create mode 100644 solutions/2736. Maximum Sum Queries/2736.cpp create mode 100644 solutions/2736. Maximum Sum Queries/2736.java create mode 100644 solutions/2736. Maximum Sum Queries/2736.py create mode 100644 solutions/2737. Find the Closest Marked Node/2737.cpp create mode 100644 solutions/2737. Find the Closest Marked Node/2737.java create mode 100644 solutions/2737. Find the Closest Marked Node/2737.py create mode 100644 solutions/2738. Count Occurrences in Text/2738.sql create mode 100644 solutions/2739. Total Distance Traveled/2739.cpp create mode 100644 solutions/2739. Total Distance Traveled/2739.java create mode 100644 solutions/2739. Total Distance Traveled/2739.py create mode 100644 solutions/274. H-Index/274-2.cpp create mode 100644 solutions/274. H-Index/274-2.java create mode 100644 solutions/274. H-Index/274-2.py create mode 100644 solutions/274. H-Index/274.cpp create mode 100644 solutions/274. H-Index/274.java create mode 100644 solutions/274. H-Index/274.py create mode 100644 solutions/2740. Find the Value of the Partition/2740.cpp create mode 100644 solutions/2740. Find the Value of the Partition/2740.java create mode 100644 solutions/2740. Find the Value of the Partition/2740.py create mode 100644 solutions/2741. Special Permutations/2741.cpp create mode 100644 solutions/2741. Special Permutations/2741.java create mode 100644 solutions/2741. Special Permutations/2741.py create mode 100644 solutions/2742. Painting the Walls/2742-2.cpp create mode 100644 solutions/2742. Painting the Walls/2742-2.java create mode 100644 solutions/2742. Painting the Walls/2742-2.py create mode 100644 solutions/2742. Painting the Walls/2742.cpp create mode 100644 solutions/2742. Painting the Walls/2742.java create mode 100644 solutions/2742. Painting the Walls/2742.py create mode 100644 solutions/2743. Count Substrings Without Repeating Character/2743.cpp create mode 100644 solutions/2743. Count Substrings Without Repeating Character/2743.java create mode 100644 solutions/2743. Count Substrings Without Repeating Character/2743.py create mode 100644 solutions/2744. Find Maximum Number of String Pairs/2744.cpp create mode 100644 solutions/2744. Find Maximum Number of String Pairs/2744.java create mode 100644 solutions/2744. Find Maximum Number of String Pairs/2744.py create mode 100644 solutions/2745. Construct the Longest New String/2745.cpp create mode 100644 solutions/2745. Construct the Longest New String/2745.java create mode 100644 solutions/2745. Construct the Longest New String/2745.py create mode 100644 solutions/2746. Decremental String Concatenation/2746.cpp create mode 100644 solutions/2746. Decremental String Concatenation/2746.java create mode 100644 solutions/2746. Decremental String Concatenation/2746.py create mode 100644 solutions/2747. Count Zero Request Servers/2747.cpp create mode 100644 solutions/2747. Count Zero Request Servers/2747.java create mode 100644 solutions/2747. Count Zero Request Servers/2747.py create mode 100644 solutions/2748. Number of Beautiful Pairs/2748.cpp create mode 100644 solutions/2748. Number of Beautiful Pairs/2748.java create mode 100644 solutions/2748. Number of Beautiful Pairs/2748.py create mode 100644 solutions/2749. Minimum Operations to Make the Integer Zero/2749.cpp create mode 100644 solutions/2749. Minimum Operations to Make the Integer Zero/2749.java create mode 100644 solutions/2749. Minimum Operations to Make the Integer Zero/2749.py create mode 100644 solutions/275. H-Index II/275.cpp create mode 100644 solutions/275. H-Index II/275.java create mode 100644 solutions/275. H-Index II/275.py create mode 100644 solutions/2750. Ways to Split Array Into Good Subarrays/2750.cpp create mode 100644 solutions/2750. Ways to Split Array Into Good Subarrays/2750.java create mode 100644 solutions/2750. Ways to Split Array Into Good Subarrays/2750.py create mode 100644 solutions/2751. Robot Collisions/2751.cpp create mode 100644 solutions/2751. Robot Collisions/2751.java create mode 100644 solutions/2751. Robot Collisions/2751.py create mode 100644 solutions/2752. Customers with Maximum Number of Transactions on Consecutive Days/2752.sql create mode 100644 solutions/2753. Count Houses in a Circular Street II/2753.cpp create mode 100644 solutions/2753. Count Houses in a Circular Street II/2753.java create mode 100644 solutions/2753. Count Houses in a Circular Street II/2753.py create mode 100644 solutions/2754. Bind Function to Context/2754.ts create mode 100644 solutions/2755. Deep Merge of Two Objects/2755.ts create mode 100644 solutions/2756. Query Batching/2756.ts create mode 100644 solutions/2757. Generate Circular Array Values/2757.ts create mode 100644 solutions/2758. Next Day/2758.ts create mode 100644 solutions/2759. Convert JSON String to Object/2759.ts create mode 100644 solutions/276. Paint Fence/276.cpp create mode 100644 solutions/276. Paint Fence/276.java create mode 100644 solutions/276. Paint Fence/276.py create mode 100644 solutions/2760. Longest Even Odd Subarray With Threshold/2760.cpp create mode 100644 solutions/2760. Longest Even Odd Subarray With Threshold/2760.java create mode 100644 solutions/2760. Longest Even Odd Subarray With Threshold/2760.py create mode 100644 solutions/2761. Prime Pairs With Target Sum/2761.cpp create mode 100644 solutions/2761. Prime Pairs With Target Sum/2761.java create mode 100644 solutions/2761. Prime Pairs With Target Sum/2761.py create mode 100644 solutions/2762. Continuous Subarrays/2762.cpp create mode 100644 solutions/2762. Continuous Subarrays/2762.java create mode 100644 solutions/2762. Continuous Subarrays/2762.py create mode 100644 solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.cpp create mode 100644 solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.java create mode 100644 solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.py create mode 100644 "solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.cpp" create mode 100644 "solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.java" create mode 100644 "solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.py" create mode 100644 solutions/2765. Longest Alternating Subarray/2765.cpp create mode 100644 solutions/2765. Longest Alternating Subarray/2765.java create mode 100644 solutions/2765. Longest Alternating Subarray/2765.py create mode 100644 solutions/2766. Relocate Marbles/2766.cpp create mode 100644 solutions/2766. Relocate Marbles/2766.java create mode 100644 solutions/2766. Relocate Marbles/2766.py create mode 100644 solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.cpp create mode 100644 solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.java create mode 100644 solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.py create mode 100644 solutions/2768. Number of Black Blocks/2768.cpp create mode 100644 solutions/2768. Number of Black Blocks/2768.java create mode 100644 solutions/2768. Number of Black Blocks/2768.py create mode 100644 solutions/2769. Find the Maximum Achievable Number/2769.cpp create mode 100644 solutions/2769. Find the Maximum Achievable Number/2769.java create mode 100644 solutions/2769. Find the Maximum Achievable Number/2769.py create mode 100644 solutions/277. Find the Celebrity/277.cpp create mode 100644 solutions/277. Find the Celebrity/277.java create mode 100644 solutions/277. Find the Celebrity/277.py create mode 100644 solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.cpp create mode 100644 solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.java create mode 100644 solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.py create mode 100644 solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.cpp create mode 100644 solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.java create mode 100644 solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.py create mode 100644 solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.cpp create mode 100644 solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.java create mode 100644 solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.py create mode 100644 solutions/2773. Height of Special Binary Tree/2773.cpp create mode 100644 solutions/2773. Height of Special Binary Tree/2773.java create mode 100644 solutions/2773. Height of Special Binary Tree/2773.py create mode 100644 solutions/2774. Array Upper Bound/2774.ts create mode 100644 solutions/2775. Undefined to Null/2775-2.ts create mode 100644 solutions/2775. Undefined to Null/2775.ts create mode 100644 solutions/2776. Convert Callback Based Function to Promise Based Function/2776.ts create mode 100644 solutions/2777. Date Range Generator/2777.ts create mode 100644 solutions/2778. Sum of Squares of Special Elements/2778.cpp create mode 100644 solutions/2778. Sum of Squares of Special Elements/2778.java create mode 100644 solutions/2778. Sum of Squares of Special Elements/2778.py create mode 100644 solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.cpp create mode 100644 solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.java create mode 100644 solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.py create mode 100644 solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.cpp create mode 100644 solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.java create mode 100644 solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.py create mode 100644 solutions/278. First Bad Version/278.cpp create mode 100644 solutions/278. First Bad Version/278.java create mode 100644 solutions/278. First Bad Version/278.py create mode 100644 solutions/2780. Minimum Index of a Valid Split/2780.cpp create mode 100644 solutions/2780. Minimum Index of a Valid Split/2780.java create mode 100644 solutions/2780. Minimum Index of a Valid Split/2780.py create mode 100644 solutions/2781. Length of the Longest Valid Substring/2781-2.cpp create mode 100644 solutions/2781. Length of the Longest Valid Substring/2781-2.java create mode 100644 solutions/2781. Length of the Longest Valid Substring/2781-2.py create mode 100644 solutions/2781. Length of the Longest Valid Substring/2781.cpp create mode 100644 solutions/2781. Length of the Longest Valid Substring/2781.java create mode 100644 solutions/2781. Length of the Longest Valid Substring/2781.py create mode 100644 solutions/2782. Number of Unique Categories/2782.cpp create mode 100644 solutions/2782. Number of Unique Categories/2782.java create mode 100644 solutions/2782. Number of Unique Categories/2782.py create mode 100644 solutions/2783. Flight Occupancy and Waitlist Analysis/2783.sql create mode 100644 solutions/2784. Check if Array is Good/2784.cpp create mode 100644 solutions/2784. Check if Array is Good/2784.java create mode 100644 solutions/2784. Check if Array is Good/2784.py create mode 100644 solutions/2785. Sort Vowels in a String/2785.cpp create mode 100644 solutions/2785. Sort Vowels in a String/2785.java create mode 100644 solutions/2785. Sort Vowels in a String/2785.py create mode 100644 solutions/2786. Visit Array Positions to Maximize Score/2786.cpp create mode 100644 solutions/2786. Visit Array Positions to Maximize Score/2786.java create mode 100644 solutions/2786. Visit Array Positions to Maximize Score/2786.py create mode 100644 solutions/2787. Ways to Express an Integer as Sum of Powers/2787.cpp create mode 100644 solutions/2787. Ways to Express an Integer as Sum of Powers/2787.java create mode 100644 solutions/2787. Ways to Express an Integer as Sum of Powers/2787.py create mode 100644 solutions/2788. Split Strings by Separator/2788.cpp create mode 100644 solutions/2788. Split Strings by Separator/2788.java create mode 100644 solutions/2788. Split Strings by Separator/2788.py create mode 100644 solutions/2789. Largest Element in an Array after Merge Operations/2789.cpp create mode 100644 solutions/2789. Largest Element in an Array after Merge Operations/2789.java create mode 100644 solutions/2789. Largest Element in an Array after Merge Operations/2789.py create mode 100644 solutions/279. Perfect Squares/279.cpp create mode 100644 solutions/279. Perfect Squares/279.java create mode 100644 solutions/279. Perfect Squares/279.py create mode 100644 solutions/2790. Maximum Number of Groups With Increasing Length/2790.cpp create mode 100644 solutions/2790. Maximum Number of Groups With Increasing Length/2790.java create mode 100644 solutions/2790. Maximum Number of Groups With Increasing Length/2790.py create mode 100644 solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.cpp create mode 100644 solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.java create mode 100644 solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.py create mode 100644 solutions/2792. Count Nodes That Are Great Enough/2792.cpp create mode 100644 solutions/2792. Count Nodes That Are Great Enough/2792.java create mode 100644 solutions/2792. Count Nodes That Are Great Enough/2792.py create mode 100644 solutions/2793. Status of Flight Tickets/2793.sql create mode 100644 solutions/2794. Create Object from Two Arrays/2794.ts create mode 100644 solutions/2795. Parallel Execution of Promises for Individual Results Retrieval/2795.ts create mode 100644 solutions/2796. Repeat String/2796.ts create mode 100644 solutions/2797. Partial Function with Placeholders/2797.ts create mode 100644 solutions/2798. Number of Employees Who Met the Target/2798.cpp create mode 100644 solutions/2798. Number of Employees Who Met the Target/2798.java create mode 100644 solutions/2798. Number of Employees Who Met the Target/2798.py create mode 100644 solutions/2799. Count Complete Subarrays in an Array/2799.cpp create mode 100644 solutions/2799. Count Complete Subarrays in an Array/2799.java create mode 100644 solutions/2799. Count Complete Subarrays in an Array/2799.py create mode 100644 solutions/28. Implement strStr()/28.cpp create mode 100644 solutions/28. Implement strStr()/28.java create mode 100644 solutions/28. Implement strStr()/28.py create mode 100644 solutions/280. Wiggle Sort/280.cpp create mode 100644 solutions/280. Wiggle Sort/280.java create mode 100644 solutions/280. Wiggle Sort/280.py create mode 100644 solutions/2800. Shortest String That Contains Three Strings/2800.cpp create mode 100644 solutions/2800. Shortest String That Contains Three Strings/2800.java create mode 100644 solutions/2800. Shortest String That Contains Three Strings/2800.py create mode 100644 solutions/2801. Count Stepping Numbers in Range/2801.cpp create mode 100644 solutions/2801. Count Stepping Numbers in Range/2801.java create mode 100644 solutions/2801. Count Stepping Numbers in Range/2801.py create mode 100644 solutions/2802. Find The K-th Lucky Number/2802.cpp create mode 100644 solutions/2802. Find The K-th Lucky Number/2802.java create mode 100644 solutions/2802. Find The K-th Lucky Number/2802.py create mode 100644 solutions/2803. Factorial Generator/2803.ts create mode 100644 solutions/2804. Array Prototype ForEach/2804.ts create mode 100644 solutions/2805. Custom Interval/2805.ts create mode 100644 solutions/2806. Account Balance After Rounded Purchase/2806.cpp create mode 100644 solutions/2806. Account Balance After Rounded Purchase/2806.java create mode 100644 solutions/2806. Account Balance After Rounded Purchase/2806.py create mode 100644 solutions/2807. Insert Greatest Common Divisors in Linked List/2807.cpp create mode 100644 solutions/2807. Insert Greatest Common Divisors in Linked List/2807.java create mode 100644 solutions/2807. Insert Greatest Common Divisors in Linked List/2807.py create mode 100644 solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.cpp create mode 100644 solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.java create mode 100644 solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.py create mode 100644 solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.cpp create mode 100644 solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.java create mode 100644 solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.py create mode 100644 solutions/2809. Minimum Time to Make Array Sum At Most x/2809.cpp create mode 100644 solutions/2809. Minimum Time to Make Array Sum At Most x/2809.java create mode 100644 solutions/2809. Minimum Time to Make Array Sum At Most x/2809.py create mode 100644 solutions/281. Zigzag Iterator/281.cpp create mode 100644 solutions/281. Zigzag Iterator/281.java create mode 100644 solutions/281. Zigzag Iterator/281.py create mode 100644 solutions/2810. Faulty Keyboard/2810.cpp create mode 100644 solutions/2810. Faulty Keyboard/2810.java create mode 100644 solutions/2810. Faulty Keyboard/2810.py create mode 100644 solutions/2811. Check if it is Possible to Split Array/2811.cpp create mode 100644 solutions/2811. Check if it is Possible to Split Array/2811.java create mode 100644 solutions/2811. Check if it is Possible to Split Array/2811.py create mode 100644 solutions/2812. Find the Safest Path in a Grid/2812.cpp create mode 100644 solutions/2812. Find the Safest Path in a Grid/2812.java create mode 100644 solutions/2812. Find the Safest Path in a Grid/2812.py create mode 100644 solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.cpp create mode 100644 solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.java create mode 100644 solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.py create mode 100644 solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.cpp create mode 100644 solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.java create mode 100644 solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.py create mode 100644 solutions/2815. Max Pair Sum in an Array/2815.cpp create mode 100644 solutions/2815. Max Pair Sum in an Array/2815.java create mode 100644 solutions/2815. Max Pair Sum in an Array/2815.py create mode 100644 solutions/2816. Double a Number Represented as a Linked List/2816-2.cpp create mode 100644 solutions/2816. Double a Number Represented as a Linked List/2816-2.java create mode 100644 solutions/2816. Double a Number Represented as a Linked List/2816-2.py create mode 100644 solutions/2816. Double a Number Represented as a Linked List/2816.cpp create mode 100644 solutions/2816. Double a Number Represented as a Linked List/2816.java create mode 100644 solutions/2816. Double a Number Represented as a Linked List/2816.py create mode 100644 solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.cpp create mode 100644 solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.java create mode 100644 solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.py create mode 100644 solutions/2818. Apply Operations to Maximize Score/2818.cpp create mode 100644 solutions/2818. Apply Operations to Maximize Score/2818.java create mode 100644 solutions/2818. Apply Operations to Maximize Score/2818.py create mode 100644 solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.cpp create mode 100644 solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.java create mode 100644 solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.py create mode 100644 solutions/282. Expression Add Operators/282.cpp create mode 100644 solutions/282. Expression Add Operators/282.java create mode 100644 solutions/282. Expression Add Operators/282.py create mode 100644 solutions/2820. Election Results/2820.sql create mode 100644 solutions/2821. Delay the Resolution of Each Promise/2821.ts create mode 100644 solutions/2822. Inversion of Object/2822.ts create mode 100644 solutions/2823. Deep Object Filter/2823.ts create mode 100644 solutions/2824. Count Pairs Whose Sum is Less than Target/2824.cpp create mode 100644 solutions/2824. Count Pairs Whose Sum is Less than Target/2824.java create mode 100644 solutions/2824. Count Pairs Whose Sum is Less than Target/2824.py create mode 100644 solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.cpp create mode 100644 solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.java create mode 100644 solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.py create mode 100644 solutions/2826. Sorting Three Groups/2826.cpp create mode 100644 solutions/2826. Sorting Three Groups/2826.java create mode 100644 solutions/2826. Sorting Three Groups/2826.py create mode 100644 solutions/2827. Number of Beautiful Integers in the Range/2827.cpp create mode 100644 solutions/2828. Check if a String Is an Acronym of Words/2828.cpp create mode 100644 solutions/2828. Check if a String Is an Acronym of Words/2828.java create mode 100644 solutions/2828. Check if a String Is an Acronym of Words/2828.py create mode 100644 solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.cpp create mode 100644 solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.java create mode 100644 solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.py create mode 100644 solutions/283. Move Zeroes/283.cpp create mode 100644 solutions/283. Move Zeroes/283.java create mode 100644 solutions/283. Move Zeroes/283.py create mode 100644 solutions/2830. Maximize the Profit as the Salesman/2830.cpp create mode 100644 solutions/2830. Maximize the Profit as the Salesman/2830.java create mode 100644 solutions/2830. Maximize the Profit as the Salesman/2830.py create mode 100644 solutions/2831. Find the Longest Equal Subarray/2831-2.cpp create mode 100644 solutions/2831. Find the Longest Equal Subarray/2831-2.java create mode 100644 solutions/2831. Find the Longest Equal Subarray/2831-2.py create mode 100644 solutions/2831. Find the Longest Equal Subarray/2831.cpp create mode 100644 solutions/2831. Find the Longest Equal Subarray/2831.java create mode 100644 solutions/2831. Find the Longest Equal Subarray/2831.py create mode 100644 solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.cpp create mode 100644 solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.java create mode 100644 solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.py create mode 100644 solutions/2833. Furthest Point From Origin/2833.cpp create mode 100644 solutions/2833. Furthest Point From Origin/2833.java create mode 100644 solutions/2833. Furthest Point From Origin/2833.py create mode 100644 solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.cpp create mode 100644 solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.java create mode 100644 solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.py create mode 100644 solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.cpp create mode 100644 solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.java create mode 100644 solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.py create mode 100644 solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.cpp create mode 100644 solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.java create mode 100644 solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.py create mode 100644 solutions/2837. Total Traveled Distance/2837.sql create mode 100644 solutions/2838. Maximum Coins Heroes Can Collect/2838.cpp create mode 100644 solutions/2838. Maximum Coins Heroes Can Collect/2838.java create mode 100644 solutions/2838. Maximum Coins Heroes Can Collect/2838.py create mode 100644 solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.cpp create mode 100644 solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.java create mode 100644 solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.py create mode 100644 solutions/284. Peeking Iterator/284.cpp create mode 100644 solutions/284. Peeking Iterator/284.java create mode 100644 solutions/284. Peeking Iterator/284.py create mode 100644 solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.cpp create mode 100644 solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.java create mode 100644 solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.py create mode 100644 solutions/2841. Maximum Sum of Almost Unique Subarray/2841.cpp create mode 100644 solutions/2841. Maximum Sum of Almost Unique Subarray/2841.java create mode 100644 solutions/2841. Maximum Sum of Almost Unique Subarray/2841.py create mode 100644 solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.cpp create mode 100644 solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.java create mode 100644 solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.py create mode 100644 solutions/2843. Count Symmetric Integers/2843.cpp create mode 100644 solutions/2843. Count Symmetric Integers/2843.java create mode 100644 solutions/2843. Count Symmetric Integers/2843.py create mode 100644 solutions/2844. Minimum Operations to Make a Special Number/2844.cpp create mode 100644 solutions/2844. Minimum Operations to Make a Special Number/2844.java create mode 100644 solutions/2844. Minimum Operations to Make a Special Number/2844.py create mode 100644 solutions/2845. Count of Interesting Subarrays/2845.cpp create mode 100644 solutions/2845. Count of Interesting Subarrays/2845.java create mode 100644 solutions/2845. Count of Interesting Subarrays/2845.py create mode 100644 solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.cpp create mode 100644 solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.java create mode 100644 solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.py create mode 100644 solutions/2847. Smallest Number With Given Digit Product/2847.cpp create mode 100644 solutions/2847. Smallest Number With Given Digit Product/2847.java create mode 100644 solutions/2847. Smallest Number With Given Digit Product/2847.py create mode 100644 solutions/2848. Points That Intersect With Cars/2848.cpp create mode 100644 solutions/2848. Points That Intersect With Cars/2848.java create mode 100644 solutions/2848. Points That Intersect With Cars/2848.py create mode 100644 solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.cpp create mode 100644 solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.java create mode 100644 solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.py create mode 100644 solutions/285. Inorder Successor in BST/285.cpp create mode 100644 solutions/285. Inorder Successor in BST/285.java create mode 100644 solutions/285. Inorder Successor in BST/285.py create mode 100644 solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.cpp create mode 100644 solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.java create mode 100644 solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.py create mode 100644 solutions/2851. String Transformation/2851.cpp create mode 100644 solutions/2851. String Transformation/2851.java create mode 100644 solutions/2851. String Transformation/2851.py create mode 100644 solutions/2852. Sum of Remoteness of All Cells/2852.cpp create mode 100644 solutions/2852. Sum of Remoteness of All Cells/2852.java create mode 100644 solutions/2852. Sum of Remoteness of All Cells/2852.py create mode 100644 solutions/2853. Highest Salaries Difference/2853.sql create mode 100644 solutions/2854. Rolling Average Steps/2854.sql create mode 100644 solutions/2855. Minimum Right Shifts to Sort the Array/2855.cpp create mode 100644 solutions/2855. Minimum Right Shifts to Sort the Array/2855.java create mode 100644 solutions/2855. Minimum Right Shifts to Sort the Array/2855.py create mode 100644 solutions/2856. Minimum Array Length After Pair Removals/2856.cpp create mode 100644 solutions/2856. Minimum Array Length After Pair Removals/2856.java create mode 100644 solutions/2856. Minimum Array Length After Pair Removals/2856.py create mode 100644 solutions/2857. Count Pairs of Points With Distance k/2857.cpp create mode 100644 solutions/2857. Count Pairs of Points With Distance k/2857.java create mode 100644 solutions/2857. Count Pairs of Points With Distance k/2857.py create mode 100644 solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.cpp create mode 100644 solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.java create mode 100644 solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.py create mode 100644 solutions/2859. Sum of Values at Indices With K Set Bits/2859.cpp create mode 100644 solutions/2859. Sum of Values at Indices With K Set Bits/2859.java create mode 100644 solutions/2859. Sum of Values at Indices With K Set Bits/2859.py create mode 100644 solutions/286. Walls and Gates/286.cpp create mode 100644 solutions/286. Walls and Gates/286.java create mode 100644 solutions/286. Walls and Gates/286.py create mode 100644 solutions/2860. Happy Students/2860.cpp create mode 100644 solutions/2860. Happy Students/2860.java create mode 100644 solutions/2860. Happy Students/2860.py create mode 100644 solutions/2861. Maximum Number of Alloys/2861.cpp create mode 100644 solutions/2861. Maximum Number of Alloys/2861.java create mode 100644 solutions/2861. Maximum Number of Alloys/2861.py create mode 100644 solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.cpp create mode 100644 solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.java create mode 100644 solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.py create mode 100644 solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.cpp create mode 100644 solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.java create mode 100644 solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.py create mode 100644 solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.cpp create mode 100644 solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.java create mode 100644 solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.py create mode 100644 solutions/2864. Maximum Odd Binary Number/2864.cpp create mode 100644 solutions/2864. Maximum Odd Binary Number/2864.java create mode 100644 solutions/2864. Maximum Odd Binary Number/2864.py create mode 100644 solutions/2865. Beautiful Towers I/2865.cpp create mode 100644 solutions/2865. Beautiful Towers I/2865.java create mode 100644 solutions/2865. Beautiful Towers I/2865.py create mode 100644 solutions/2866. Beautiful Towers II/2866.cpp create mode 100644 solutions/2866. Beautiful Towers II/2866.java create mode 100644 solutions/2866. Beautiful Towers II/2866.py create mode 100644 solutions/2867. Count Valid Paths in a Tree/2867.cpp create mode 100644 solutions/2867. Count Valid Paths in a Tree/2867.java create mode 100644 solutions/2867. Count Valid Paths in a Tree/2867.py create mode 100644 solutions/2868. The Wording Game/2868.cpp create mode 100644 solutions/2868. The Wording Game/2868.java create mode 100644 solutions/2868. The Wording Game/2868.py create mode 100644 solutions/2869. Minimum Operations to Collect Elements/2869.cpp create mode 100644 solutions/2869. Minimum Operations to Collect Elements/2869.java create mode 100644 solutions/2869. Minimum Operations to Collect Elements/2869.py create mode 100644 solutions/287. Find the Duplicate Number/287.cpp create mode 100644 solutions/287. Find the Duplicate Number/287.java create mode 100644 solutions/287. Find the Duplicate Number/287.py create mode 100644 solutions/2870. Minimum Number of Operations to Make Array Empty/2870.cpp create mode 100644 solutions/2870. Minimum Number of Operations to Make Array Empty/2870.java create mode 100644 solutions/2870. Minimum Number of Operations to Make Array Empty/2870.py create mode 100644 solutions/2871. Split Array Into Maximum Number of Subarrays/2871.cpp create mode 100644 solutions/2871. Split Array Into Maximum Number of Subarrays/2871.java create mode 100644 solutions/2871. Split Array Into Maximum Number of Subarrays/2871.py create mode 100644 solutions/2872. Maximum Number of K-Divisible Components/2872.cpp create mode 100644 solutions/2872. Maximum Number of K-Divisible Components/2872.java create mode 100644 solutions/2872. Maximum Number of K-Divisible Components/2872.py create mode 100644 solutions/2873. Maximum Value of an Ordered Triplet I/2873.cpp create mode 100644 solutions/2873. Maximum Value of an Ordered Triplet I/2873.java create mode 100644 solutions/2873. Maximum Value of an Ordered Triplet I/2873.py create mode 100644 solutions/2874. Maximum Value of an Ordered Triplet II/2874.cpp create mode 100644 solutions/2874. Maximum Value of an Ordered Triplet II/2874.java create mode 100644 solutions/2874. Maximum Value of an Ordered Triplet II/2874.py create mode 100644 solutions/2875. Minimum Size Subarray in Infinite Array/2875.cpp create mode 100644 solutions/2875. Minimum Size Subarray in Infinite Array/2875.java create mode 100644 solutions/2875. Minimum Size Subarray in Infinite Array/2875.py create mode 100644 solutions/2876. Count Visited Nodes in a Directed Graph/2876.cpp create mode 100644 solutions/2876. Count Visited Nodes in a Directed Graph/2876.java create mode 100644 solutions/2876. Count Visited Nodes in a Directed Graph/2876.py create mode 100644 solutions/2877. Create a DataFrame from List/2877.py create mode 100644 solutions/2878. Get the Size of a DataFrame/2878.py create mode 100644 solutions/2879. Display the First Three Rows/2879.py create mode 100644 solutions/288. Unique Word Abbreviation/288.cpp create mode 100644 solutions/288. Unique Word Abbreviation/288.java create mode 100644 solutions/288. Unique Word Abbreviation/288.py create mode 100644 solutions/2880. Select Data/2880.py create mode 100644 solutions/2881. Create a New Column/2881.py create mode 100644 solutions/2882. Drop Duplicate Rows/2882.py create mode 100644 solutions/2883. Drop Missing Data/2883.py create mode 100644 solutions/2884. Modify Columns/2884.py create mode 100644 solutions/2885. Rename Columns/2885.py create mode 100644 solutions/2886. Change Data Type/2886.py create mode 100644 solutions/2887. Fill Missing Data/2887.py create mode 100644 solutions/2888. Reshape Data: Concatenate/2888.py create mode 100644 solutions/2889. Reshape Data: Pivot/2889.py create mode 100644 solutions/289. Game of Life/289.cpp create mode 100644 solutions/289. Game of Life/289.java create mode 100644 solutions/289. Game of Life/289.py create mode 100644 solutions/2890. Reshape Data: Melt/2890.py create mode 100644 solutions/2891. Method Chaining/2891.py create mode 100644 solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.cpp create mode 100644 solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.java create mode 100644 solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.py create mode 100644 solutions/2893. Calculate Orders Within Each Interval/2893.sql create mode 100644 solutions/2894. Divisible and Non-divisible Sums Difference/2894.cpp create mode 100644 solutions/2894. Divisible and Non-divisible Sums Difference/2894.java create mode 100644 solutions/2894. Divisible and Non-divisible Sums Difference/2894.py create mode 100644 solutions/2895. Minimum Processing Time/2895.cpp create mode 100644 solutions/2895. Minimum Processing Time/2895.java create mode 100644 solutions/2895. Minimum Processing Time/2895.py create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.cpp create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.java create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.py create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.cpp create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.java create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.py create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896.cpp create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896.java create mode 100644 solutions/2896. Apply Operations to Make Two Strings Equal/2896.py create mode 100644 solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.cpp create mode 100644 solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.java create mode 100644 solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.py create mode 100644 solutions/2898. Maximum Linear Stock Score/2898.cpp create mode 100644 solutions/2898. Maximum Linear Stock Score/2898.java create mode 100644 solutions/2898. Maximum Linear Stock Score/2898.py create mode 100644 solutions/2899. Last Visited Integers/2899.cpp create mode 100644 solutions/2899. Last Visited Integers/2899.java create mode 100644 solutions/2899. Last Visited Integers/2899.py create mode 100644 solutions/29. Divide Two Integers/29.cpp create mode 100644 solutions/29. Divide Two Integers/29.java create mode 100644 solutions/29. Divide Two Integers/29.py create mode 100644 solutions/290. Word Pattern/290.cpp create mode 100644 solutions/290. Word Pattern/290.java create mode 100644 solutions/290. Word Pattern/290.py create mode 100644 solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.cpp create mode 100644 solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.java create mode 100644 solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.py create mode 100644 solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.cpp create mode 100644 solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.java create mode 100644 solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.py create mode 100644 solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.cpp create mode 100644 solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.java create mode 100644 solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.py create mode 100644 solutions/2903. Find Indices With Index and Value Difference I/2903.cpp create mode 100644 solutions/2903. Find Indices With Index and Value Difference I/2903.java create mode 100644 solutions/2903. Find Indices With Index and Value Difference I/2903.py create mode 100644 solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.cpp create mode 100644 solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.java create mode 100644 solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.py create mode 100644 solutions/2905. Find Indices With Index and Value Difference II/2905.cpp create mode 100644 solutions/2905. Find Indices With Index and Value Difference II/2905.java create mode 100644 solutions/2905. Find Indices With Index and Value Difference II/2905.py create mode 100644 solutions/2906. Construct Product Matrix/2906.cpp create mode 100644 solutions/2906. Construct Product Matrix/2906.java create mode 100644 solutions/2906. Construct Product Matrix/2906.py create mode 100644 solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.cpp create mode 100644 solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.java create mode 100644 solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.py create mode 100644 solutions/2908. Minimum Sum of Mountain Triplets I/2908.cpp create mode 100644 solutions/2908. Minimum Sum of Mountain Triplets I/2908.java create mode 100644 solutions/2908. Minimum Sum of Mountain Triplets I/2908.py create mode 100644 solutions/2909. Minimum Sum of Mountain Triplets II/2909.cpp create mode 100644 solutions/2909. Minimum Sum of Mountain Triplets II/2909.java create mode 100644 solutions/2909. Minimum Sum of Mountain Triplets II/2909.py create mode 100644 solutions/291. Word Pattern II/291.cpp create mode 100644 solutions/291. Word Pattern II/291.java create mode 100644 solutions/291. Word Pattern II/291.py create mode 100644 solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.cpp create mode 100644 solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.java create mode 100644 solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.py create mode 100644 solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.cpp create mode 100644 solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.java create mode 100644 solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.py create mode 100644 solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.cpp create mode 100644 solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.java create mode 100644 solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.py create mode 100644 solutions/2912. Number of Ways to Reach Destination in the Grid/2912.cpp create mode 100644 solutions/2912. Number of Ways to Reach Destination in the Grid/2912.java create mode 100644 solutions/2912. Number of Ways to Reach Destination in the Grid/2912.py create mode 100644 solutions/2913. Subarrays Distinct Element Sum of Squares I/2913.cpp create mode 100644 solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.cpp create mode 100644 solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.java create mode 100644 solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.py create mode 100644 solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.cpp create mode 100644 solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.java create mode 100644 solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.py create mode 100644 solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.cpp create mode 100644 solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.java create mode 100644 solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.py create mode 100644 solutions/2916. Subarrays Distinct Element Sum of Squares II/2916.cpp create mode 100644 solutions/2917. Find the K-or of an Array/2917.cpp create mode 100644 solutions/2917. Find the K-or of an Array/2917.java create mode 100644 solutions/2917. Find the K-or of an Array/2917.py create mode 100644 solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.cpp create mode 100644 solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.java create mode 100644 solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.py create mode 100644 solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.cpp create mode 100644 solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.java create mode 100644 solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.py create mode 100644 solutions/292. Nim Game/292.cpp create mode 100644 solutions/292. Nim Game/292.java create mode 100644 solutions/292. Nim Game/292.py create mode 100644 solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.cpp create mode 100644 solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.java create mode 100644 solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.py create mode 100644 solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.cpp create mode 100644 solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.java create mode 100644 solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.py create mode 100644 solutions/2922. Market Analysis III/2922.sql create mode 100644 solutions/2923. Find Champion I/2923-2.cpp create mode 100644 solutions/2923. Find Champion I/2923-2.java create mode 100644 solutions/2923. Find Champion I/2923-2.py create mode 100644 solutions/2923. Find Champion I/2923.cpp create mode 100644 solutions/2923. Find Champion I/2923.java create mode 100644 solutions/2923. Find Champion I/2923.py create mode 100644 solutions/2924. Find Champion II/2924.cpp create mode 100644 solutions/2924. Find Champion II/2924.java create mode 100644 solutions/2924. Find Champion II/2924.py create mode 100644 solutions/2925. Maximum Score After Applying Operations on a Tree/2925.cpp create mode 100644 solutions/2925. Maximum Score After Applying Operations on a Tree/2925.java create mode 100644 solutions/2925. Maximum Score After Applying Operations on a Tree/2925.py create mode 100644 solutions/2926. Maximum Balanced Subsequence Sum/2926.cpp create mode 100644 solutions/2926. Maximum Balanced Subsequence Sum/2926.java create mode 100644 solutions/2926. Maximum Balanced Subsequence Sum/2926.py create mode 100644 solutions/2927. Distribute Candies Among Children III/2927.cpp create mode 100644 solutions/2927. Distribute Candies Among Children III/2927.java create mode 100644 solutions/2927. Distribute Candies Among Children III/2927.py create mode 100644 solutions/2928. Distribute Candies Among Children I/2928.cpp create mode 100644 solutions/2928. Distribute Candies Among Children I/2928.java create mode 100644 solutions/2928. Distribute Candies Among Children I/2928.py create mode 100644 solutions/2929. Distribute Candies Among Children II/2929.cpp create mode 100644 solutions/2929. Distribute Candies Among Children II/2929.java create mode 100644 solutions/2929. Distribute Candies Among Children II/2929.py create mode 100644 solutions/293. Flip Game/293.cpp create mode 100644 solutions/293. Flip Game/293.java create mode 100644 solutions/293. Flip Game/293.py create mode 100644 solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.cpp create mode 100644 solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.java create mode 100644 solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.py create mode 100644 solutions/2931. Maximum Spending After Buying Items/2931.cpp create mode 100644 solutions/2931. Maximum Spending After Buying Items/2931.java create mode 100644 solutions/2931. Maximum Spending After Buying Items/2931.py create mode 100644 solutions/2932. Maximum Strong Pair XOR I/2932.cpp create mode 100644 solutions/2932. Maximum Strong Pair XOR I/2932.java create mode 100644 solutions/2932. Maximum Strong Pair XOR I/2932.py create mode 100644 solutions/2933. High-Access Employees/2933.cpp create mode 100644 solutions/2933. High-Access Employees/2933.java create mode 100644 solutions/2933. High-Access Employees/2933.py create mode 100644 solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.cpp create mode 100644 solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.java create mode 100644 solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.py create mode 100644 solutions/2935. Maximum Strong Pair XOR II/2935.cpp create mode 100644 solutions/2935. Maximum Strong Pair XOR II/2935.java create mode 100644 solutions/2935. Maximum Strong Pair XOR II/2935.py create mode 100644 solutions/2936. Number of Equal Numbers Blocks/2936.cpp create mode 100644 solutions/2936. Number of Equal Numbers Blocks/2936.java create mode 100644 solutions/2936. Number of Equal Numbers Blocks/2936.py create mode 100644 solutions/2937. Make Three Strings Equal/2937.cpp create mode 100644 solutions/2937. Make Three Strings Equal/2937.java create mode 100644 solutions/2937. Make Three Strings Equal/2937.py create mode 100644 solutions/2938. Separate Black and White Balls/2938.cpp create mode 100644 solutions/2938. Separate Black and White Balls/2938.java create mode 100644 solutions/2938. Separate Black and White Balls/2938.py create mode 100644 solutions/2939. Maximum Xor Product/2939.cpp create mode 100644 solutions/2939. Maximum Xor Product/2939.java create mode 100644 solutions/2939. Maximum Xor Product/2939.py create mode 100644 solutions/294. Flip Game II/294.cpp create mode 100644 solutions/294. Flip Game II/294.java create mode 100644 solutions/294. Flip Game II/294.py create mode 100644 solutions/2940. Find Building Where Alice and Bob Can Meet/2940.cpp create mode 100644 solutions/2940. Find Building Where Alice and Bob Can Meet/2940.java create mode 100644 solutions/2940. Find Building Where Alice and Bob Can Meet/2940.py create mode 100644 solutions/2941. Maximum GCD-Sum of a Subarray/2941.cpp create mode 100644 solutions/2941. Maximum GCD-Sum of a Subarray/2941.java create mode 100644 solutions/2941. Maximum GCD-Sum of a Subarray/2941.py create mode 100644 solutions/2942. Find Words Containing Character/2942.cpp create mode 100644 solutions/2943. Maximize Area of Square Hole in Grid Solved Medium/2943.cpp create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944-2.cpp create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944-2.java create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944-2.py create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944-3.cpp create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944-3.java create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944-3.py create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944.cpp create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944.java create mode 100644 solutions/2944. Minimum Number of Coins for Fruits/2944.py create mode 100644 solutions/2945. Find Maximum Non-decreasing Array Length/2945-2.py create mode 100644 solutions/2945. Find Maximum Non-decreasing Array Length/2945.py create mode 100644 solutions/2946. Matrix Similarity After Cyclic Shifts/2946.cpp create mode 100644 solutions/2946. Matrix Similarity After Cyclic Shifts/2946.java create mode 100644 solutions/2946. Matrix Similarity After Cyclic Shifts/2946.py create mode 100644 solutions/2947. Count Beautiful Substrings I/2947.cpp create mode 100644 solutions/2947. Count Beautiful Substrings I/2947.java create mode 100644 solutions/2947. Count Beautiful Substrings I/2947.py create mode 100644 solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.cpp create mode 100644 solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.java create mode 100644 solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.py create mode 100644 solutions/2949. Count Beautiful Substrings II/2949.cpp create mode 100644 solutions/2949. Count Beautiful Substrings II/2949.java create mode 100644 solutions/2949. Count Beautiful Substrings II/2949.py create mode 100644 solutions/295. Find Median from Data Stream/295.cpp create mode 100644 solutions/295. Find Median from Data Stream/295.java create mode 100644 solutions/295. Find Median from Data Stream/295.py create mode 100644 solutions/2950. Number of Divisible Substrings/2950.cpp create mode 100644 solutions/2950. Number of Divisible Substrings/2950.java create mode 100644 solutions/2950. Number of Divisible Substrings/2950.py create mode 100644 solutions/2951. Find the Peaks/2951.cpp create mode 100644 solutions/2951. Find the Peaks/2951.java create mode 100644 solutions/2951. Find the Peaks/2951.py create mode 100644 solutions/2952. Minimum Number of Coins to be Added/2952.cpp create mode 100644 solutions/2952. Minimum Number of Coins to be Added/2952.java create mode 100644 solutions/2952. Minimum Number of Coins to be Added/2952.py create mode 100644 solutions/2953. Count Complete Substrings/2953.cpp create mode 100644 solutions/2953. Count Complete Substrings/2953.java create mode 100644 solutions/2953. Count Complete Substrings/2953.py create mode 100644 solutions/2954. Count the Number of Infection Sequences/2954.cpp create mode 100644 solutions/2954. Count the Number of Infection Sequences/2954.java create mode 100644 solutions/2954. Count the Number of Infection Sequences/2954.py create mode 100644 solutions/2955. Number of Same-End Substrings/2955.cpp create mode 100644 solutions/2955. Number of Same-End Substrings/2955.java create mode 100644 solutions/2955. Number of Same-End Substrings/2955.py create mode 100644 solutions/2956. Find Common Elements Between Two Arrays/2956.cpp create mode 100644 solutions/2956. Find Common Elements Between Two Arrays/2956.java create mode 100644 solutions/2956. Find Common Elements Between Two Arrays/2956.py create mode 100644 solutions/2957. Remove Adjacent Almost-Equal Characters/2957.cpp create mode 100644 solutions/2957. Remove Adjacent Almost-Equal Characters/2957.java create mode 100644 solutions/2957. Remove Adjacent Almost-Equal Characters/2957.py create mode 100644 solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.cpp create mode 100644 solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.java create mode 100644 solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.py create mode 100644 solutions/2959. Number of Possible Sets of Closing Branches/2959.cpp create mode 100644 solutions/2959. Number of Possible Sets of Closing Branches/2959.java create mode 100644 solutions/2959. Number of Possible Sets of Closing Branches/2959.py create mode 100644 solutions/296. Best Meeting Point/296.cpp create mode 100644 solutions/296. Best Meeting Point/296.java create mode 100644 solutions/296. Best Meeting Point/296.py create mode 100644 solutions/2960. Count Tested Devices After Test Operations/2960.cpp create mode 100644 solutions/2960. Count Tested Devices After Test Operations/2960.java create mode 100644 solutions/2960. Count Tested Devices After Test Operations/2960.py create mode 100644 solutions/2961. Double Modular Exponentiation/2961.cpp create mode 100644 solutions/2961. Double Modular Exponentiation/2961.java create mode 100644 solutions/2961. Double Modular Exponentiation/2961.py create mode 100644 solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.cpp create mode 100644 solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.java create mode 100644 solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.py create mode 100644 solutions/2963. Count the Number of Good Partitions/2963.cpp create mode 100644 solutions/2963. Count the Number of Good Partitions/2963.java create mode 100644 solutions/2963. Count the Number of Good Partitions/2963.py create mode 100644 solutions/2964. Number of Divisible Triplet Sums/2964.cpp create mode 100644 solutions/2964. Number of Divisible Triplet Sums/2964.java create mode 100644 solutions/2964. Number of Divisible Triplet Sums/2964.py create mode 100644 solutions/2965. Find Missing and Repeated Values/2965.cpp create mode 100644 solutions/2965. Find Missing and Repeated Values/2965.java create mode 100644 solutions/2965. Find Missing and Repeated Values/2965.py create mode 100644 solutions/2966. Divide Array Into Arrays With Max Difference/2966.cpp create mode 100644 solutions/2966. Divide Array Into Arrays With Max Difference/2966.java create mode 100644 solutions/2966. Divide Array Into Arrays With Max Difference/2966.py create mode 100644 solutions/2967. Minimum Cost to Make Array Equalindromic/2967.cpp create mode 100644 solutions/2967. Minimum Cost to Make Array Equalindromic/2967.java create mode 100644 solutions/2967. Minimum Cost to Make Array Equalindromic/2967.py create mode 100644 solutions/2968. Apply Operations to Maximize Frequency Score/2968.cpp create mode 100644 solutions/2968. Apply Operations to Maximize Frequency Score/2968.java create mode 100644 solutions/2968. Apply Operations to Maximize Frequency Score/2968.py create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969-2.cpp create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969-2.java create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969-2.py create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969-3.cpp create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969-3.java create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969-3.py create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969.cpp create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969.java create mode 100644 solutions/2969. Minimum Number of Coins for Fruits II/2969.py create mode 100644 solutions/297. Serialize and Deserialize Binary Tree/297-2.cpp create mode 100644 solutions/297. Serialize and Deserialize Binary Tree/297-2.java create mode 100644 solutions/297. Serialize and Deserialize Binary Tree/297-2.py create mode 100644 solutions/297. Serialize and Deserialize Binary Tree/297.cpp create mode 100644 solutions/297. Serialize and Deserialize Binary Tree/297.java create mode 100644 solutions/297. Serialize and Deserialize Binary Tree/297.py create mode 100644 solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.cpp create mode 100644 solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.java create mode 100644 solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.py create mode 100644 solutions/2970. Count the Number of Incremovable Subarrays I/2970.cpp create mode 100644 solutions/2970. Count the Number of Incremovable Subarrays I/2970.java create mode 100644 solutions/2970. Count the Number of Incremovable Subarrays I/2970.py create mode 100644 solutions/2971. Find Polygon With the Largest Perimeter/2971.cpp create mode 100644 solutions/2971. Find Polygon With the Largest Perimeter/2971.java create mode 100644 solutions/2971. Find Polygon With the Largest Perimeter/2971.py create mode 100644 solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.cpp create mode 100644 solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.java create mode 100644 solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.py create mode 100644 solutions/2972. Count the Number of Incremovable Subarrays II/2972.cpp create mode 100644 solutions/2972. Count the Number of Incremovable Subarrays II/2972.java create mode 100644 solutions/2972. Count the Number of Incremovable Subarrays II/2972.py create mode 100644 solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.cpp create mode 100644 solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.java create mode 100644 solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.py create mode 100644 solutions/2974. Minimum Number Game/2974.cpp create mode 100644 solutions/2974. Minimum Number Game/2974.java create mode 100644 solutions/2974. Minimum Number Game/2974.py create mode 100644 solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.cpp create mode 100644 solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.java create mode 100644 solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.py create mode 100644 solutions/2976. Minimum Cost to Convert String I/2976.cpp create mode 100644 solutions/2976. Minimum Cost to Convert String I/2976.java create mode 100644 solutions/2976. Minimum Cost to Convert String I/2976.py create mode 100644 solutions/2977. Minimum Cost to Convert String II/2977.cpp create mode 100644 solutions/2977. Minimum Cost to Convert String II/2977.java create mode 100644 solutions/2977. Minimum Cost to Convert String II/2977.py create mode 100644 solutions/2978. Symmetric Coordinates/2978.sql create mode 100644 solutions/2979. Most Expensive Item That Can Not Be Bought/2979.cpp create mode 100644 solutions/2979. Most Expensive Item That Can Not Be Bought/2979.java create mode 100644 solutions/2979. Most Expensive Item That Can Not Be Bought/2979.py create mode 100644 solutions/298. Binary Tree Longest Consecutive Sequence/298.cpp create mode 100644 solutions/298. Binary Tree Longest Consecutive Sequence/298.java create mode 100644 solutions/298. Binary Tree Longest Consecutive Sequence/298.py create mode 100644 solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.cpp create mode 100644 solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.java create mode 100644 solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.py create mode 100644 solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.cpp create mode 100644 solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.java create mode 100644 solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.py create mode 100644 solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.cpp create mode 100644 solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.java create mode 100644 solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.py create mode 100644 solutions/2983. Palindrome Rearrangement Queries/2983.cpp create mode 100644 solutions/2983. Palindrome Rearrangement Queries/2983.java create mode 100644 solutions/2983. Palindrome Rearrangement Queries/2983.py create mode 100644 solutions/2984. Find Peak Calling Hours for Each City/2984.sql create mode 100644 solutions/2985. Calculate Compressed Mean/2985.sql create mode 100644 solutions/2986. Find Third Transaction/2986.sql create mode 100644 solutions/2987. Find Expensive Cities/2987.sql create mode 100644 solutions/2988. Manager of the Largest Department/2988.sql create mode 100644 solutions/2989. Class Performance/2989.sql create mode 100644 solutions/299. Bulls and Cows/299.cpp create mode 100644 solutions/299. Bulls and Cows/299.java create mode 100644 solutions/299. Bulls and Cows/299.py create mode 100644 solutions/2990. Loan Types/2990.sql create mode 100644 solutions/2991. Top Three Wineries/2991.sql create mode 100644 solutions/2992. Number of Self-Divisible Permutations/2992.cpp create mode 100644 solutions/2992. Number of Self-Divisible Permutations/2992.java create mode 100644 solutions/2992. Number of Self-Divisible Permutations/2992.py create mode 100644 solutions/2993. Friday Purchases I/2993.sql create mode 100644 solutions/2994. Friday Purchases II/2994.sql create mode 100644 solutions/2995. Viewers Turned Streamers/2995.sql create mode 100644 solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.cpp create mode 100644 solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.java create mode 100644 solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.py create mode 100644 solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.cpp create mode 100644 solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.java create mode 100644 solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.py create mode 100644 solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.cpp create mode 100644 solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.java create mode 100644 solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.py create mode 100644 solutions/2999. Count the Number of Powerful Integers/2999.cpp create mode 100644 solutions/3. Longest Substring Without Repeating Characters/3-2.cpp create mode 100644 solutions/3. Longest Substring Without Repeating Characters/3-2.java create mode 100644 solutions/3. Longest Substring Without Repeating Characters/3-2.py create mode 100644 solutions/3. Longest Substring Without Repeating Characters/3.cpp create mode 100644 solutions/3. Longest Substring Without Repeating Characters/3.java create mode 100644 solutions/3. Longest Substring Without Repeating Characters/3.py create mode 100644 solutions/30. Substring with Concatenation of All Words/30.cpp create mode 100644 solutions/30. Substring with Concatenation of All Words/30.java create mode 100644 solutions/30. Substring with Concatenation of All Words/30.py create mode 100644 solutions/300. Longest Increasing Subsequence/300-2.cpp create mode 100644 solutions/300. Longest Increasing Subsequence/300-2.java create mode 100644 solutions/300. Longest Increasing Subsequence/300-2.py create mode 100644 solutions/300. Longest Increasing Subsequence/300.cpp create mode 100644 solutions/300. Longest Increasing Subsequence/300.java create mode 100644 solutions/300. Longest Increasing Subsequence/300.py create mode 100644 solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.cpp create mode 100644 solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.java create mode 100644 solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.py create mode 100644 solutions/3001. Minimum Moves to Capture The Queen/3001.cpp create mode 100644 solutions/3001. Minimum Moves to Capture The Queen/3001.java create mode 100644 solutions/3001. Minimum Moves to Capture The Queen/3001.py create mode 100644 solutions/3002. Maximum Size of a Set After Removals/3002.cpp create mode 100644 solutions/3002. Maximum Size of a Set After Removals/3002.java create mode 100644 solutions/3002. Maximum Size of a Set After Removals/3002.py create mode 100644 solutions/3003. Maximize the Number of Partitions After Operations/3003.cpp create mode 100644 solutions/3003. Maximize the Number of Partitions After Operations/3003.java create mode 100644 solutions/3003. Maximize the Number of Partitions After Operations/3003.py create mode 100644 solutions/3004. Maximum Subtree of the Same Color/3004.cpp create mode 100644 solutions/3004. Maximum Subtree of the Same Color/3004.java create mode 100644 solutions/3004. Maximum Subtree of the Same Color/3004.py create mode 100644 solutions/3005. Count Elements With Maximum Frequency/3005.cpp create mode 100644 solutions/3005. Count Elements With Maximum Frequency/3005.java create mode 100644 solutions/3005. Count Elements With Maximum Frequency/3005.py create mode 100644 solutions/3006. Find Beautiful Indices in the Given Array I/3006.cpp create mode 100644 solutions/3006. Find Beautiful Indices in the Given Array I/3006.java create mode 100644 solutions/3006. Find Beautiful Indices in the Given Array I/3006.py create mode 100644 solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.cpp create mode 100644 solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.java create mode 100644 solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.py create mode 100644 solutions/3008. Find Beautiful Indices in the Given Array II/3008.cpp create mode 100644 solutions/3008. Find Beautiful Indices in the Given Array II/3008.java create mode 100644 solutions/3008. Find Beautiful Indices in the Given Array II/3008.py create mode 100644 solutions/3009. Maximum Number of Intersections on the Chart/3009.cpp create mode 100644 solutions/3009. Maximum Number of Intersections on the Chart/3009.java create mode 100644 solutions/3009. Maximum Number of Intersections on the Chart/3009.py create mode 100644 solutions/301. Remove Invalid Parentheses/301.cpp create mode 100644 solutions/301. Remove Invalid Parentheses/301.java create mode 100644 solutions/301. Remove Invalid Parentheses/301.py create mode 100644 solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.cpp create mode 100644 solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.java create mode 100644 solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.py create mode 100644 solutions/3011. Find if Array Can Be Sorted/3011.cpp create mode 100644 solutions/3011. Find if Array Can Be Sorted/3011.java create mode 100644 solutions/3011. Find if Array Can Be Sorted/3011.py create mode 100644 solutions/3012. Minimize Length of Array Using Operations/3012.cpp create mode 100644 solutions/3012. Minimize Length of Array Using Operations/3012.java create mode 100644 solutions/3012. Minimize Length of Array Using Operations/3012.py create mode 100644 solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.cpp create mode 100644 solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.java create mode 100644 solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.py create mode 100644 solutions/3014. Minimum Number of Pushes to Type Word I/3014.cpp create mode 100644 solutions/3014. Minimum Number of Pushes to Type Word I/3014.java create mode 100644 solutions/3014. Minimum Number of Pushes to Type Word I/3014.py create mode 100644 solutions/3015. Count the Number of Houses at a Certain Distance I/3015.cpp create mode 100644 solutions/3015. Count the Number of Houses at a Certain Distance I/3015.java create mode 100644 solutions/3015. Count the Number of Houses at a Certain Distance I/3015.py create mode 100644 solutions/3016. Minimum Number of Pushes to Type Word II/3016.cpp create mode 100644 solutions/3016. Minimum Number of Pushes to Type Word II/3016.java create mode 100644 solutions/3016. Minimum Number of Pushes to Type Word II/3016.py create mode 100644 solutions/3017. Count the Number of Houses at a Certain Distance II/3017.cpp create mode 100644 solutions/3017. Count the Number of Houses at a Certain Distance II/3017.java create mode 100644 solutions/3017. Count the Number of Houses at a Certain Distance II/3017.py create mode 100644 solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.cpp create mode 100644 solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.java create mode 100644 solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.py create mode 100644 solutions/3019. Number of Changing Keys/3019.cpp create mode 100644 solutions/3019. Number of Changing Keys/3019.java create mode 100644 solutions/3019. Number of Changing Keys/3019.py create mode 100644 solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.cpp create mode 100644 solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.java create mode 100644 solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.py create mode 100644 solutions/302. Smallest Rectangle Enclosing Black Pixels/302.cpp create mode 100644 solutions/302. Smallest Rectangle Enclosing Black Pixels/302.java create mode 100644 solutions/302. Smallest Rectangle Enclosing Black Pixels/302.py create mode 100644 solutions/3020. Find the Maximum Number of Elements in Subset/3020.cpp create mode 100644 solutions/3020. Find the Maximum Number of Elements in Subset/3020.java create mode 100644 solutions/3020. Find the Maximum Number of Elements in Subset/3020.py create mode 100644 solutions/3021. Alice and Bob Playing Flower Game/3021.cpp create mode 100644 solutions/3021. Alice and Bob Playing Flower Game/3021.java create mode 100644 solutions/3021. Alice and Bob Playing Flower Game/3021.py create mode 100644 solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.cpp create mode 100644 solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.java create mode 100644 solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.py create mode 100644 solutions/3023. Find Pattern in Infinite Stream I/3023.cpp create mode 100644 solutions/3023. Find Pattern in Infinite Stream I/3023.java create mode 100644 solutions/3023. Find Pattern in Infinite Stream I/3023.py create mode 100644 solutions/3024. Type of Triangle II Easy/3024.cpp create mode 100644 solutions/3024. Type of Triangle II Easy/3024.java create mode 100644 solutions/3024. Type of Triangle II Easy/3024.py create mode 100644 solutions/3025. Find the Number of Ways to Place People I/3025.cpp create mode 100644 solutions/3025. Find the Number of Ways to Place People I/3025.java create mode 100644 solutions/3025. Find the Number of Ways to Place People I/3025.py create mode 100644 solutions/3026. Maximum Good Subarray Sum/3026.cpp create mode 100644 solutions/3026. Maximum Good Subarray Sum/3026.java create mode 100644 solutions/3026. Maximum Good Subarray Sum/3026.py create mode 100644 solutions/3027. Find the Number of Ways to Place People II/3027.cpp create mode 100644 solutions/3027. Find the Number of Ways to Place People II/3027.java create mode 100644 solutions/3027. Find the Number of Ways to Place People II/3027.py create mode 100644 solutions/3028. Ant on the Boundary/3028.cpp create mode 100644 solutions/3028. Ant on the Boundary/3028.java create mode 100644 solutions/3028. Ant on the Boundary/3028.py create mode 100644 solutions/3029. Minimum Time to Revert Word to Initial State I/3029.cpp create mode 100644 solutions/3029. Minimum Time to Revert Word to Initial State I/3029.java create mode 100644 solutions/3029. Minimum Time to Revert Word to Initial State I/3029.py create mode 100644 solutions/303. Range Sum Query - Immutable/303.cpp create mode 100644 solutions/303. Range Sum Query - Immutable/303.java create mode 100644 solutions/303. Range Sum Query - Immutable/303.py create mode 100644 solutions/3030. Find the Grid of Region Average/3030.cpp create mode 100644 solutions/3030. Find the Grid of Region Average/3030.java create mode 100644 solutions/3030. Find the Grid of Region Average/3030.py create mode 100644 solutions/3031. Minimum Time to Revert Word to Initial State II/3031.cpp create mode 100644 solutions/3031. Minimum Time to Revert Word to Initial State II/3031.java create mode 100644 solutions/3031. Minimum Time to Revert Word to Initial State II/3031.py create mode 100644 solutions/3032. Count Numbers With Unique Digits II/3032.cpp create mode 100644 solutions/3032. Count Numbers With Unique Digits II/3032.java create mode 100644 solutions/3032. Count Numbers With Unique Digits II/3032.py create mode 100644 solutions/3033. Modify the Matrix/3033.cpp create mode 100644 solutions/3033. Modify the Matrix/3033.java create mode 100644 solutions/3033. Modify the Matrix/3033.py create mode 100644 solutions/3034. Number of Subarrays That Match a Pattern I/3034.cpp create mode 100644 solutions/3034. Number of Subarrays That Match a Pattern I/3034.java create mode 100644 solutions/3034. Number of Subarrays That Match a Pattern I/3034.py create mode 100644 solutions/3035. Maximum Palindromes After Operations/3035.cpp create mode 100644 solutions/3035. Maximum Palindromes After Operations/3035.java create mode 100644 solutions/3035. Maximum Palindromes After Operations/3035.py create mode 100644 solutions/3036. Number of Subarrays That Match a Pattern II/3036.cpp create mode 100644 solutions/3036. Number of Subarrays That Match a Pattern II/3036.java create mode 100644 solutions/3036. Number of Subarrays That Match a Pattern II/3036.py create mode 100644 solutions/3037. Find Pattern in Infinite Stream II/3037.cpp create mode 100644 solutions/3037. Find Pattern in Infinite Stream II/3037.java create mode 100644 solutions/3037. Find Pattern in Infinite Stream II/3037.py create mode 100644 solutions/3038. Maximum Number of Operations With the Same Score I/3038.cpp create mode 100644 solutions/3038. Maximum Number of Operations With the Same Score I/3038.java create mode 100644 solutions/3038. Maximum Number of Operations With the Same Score I/3038.py create mode 100644 solutions/3039. Apply Operations to Make String Empty/3039.cpp create mode 100644 solutions/3039. Apply Operations to Make String Empty/3039.java create mode 100644 solutions/3039. Apply Operations to Make String Empty/3039.py create mode 100644 solutions/304. Range Sum Query 2D - Immutable/304.cpp create mode 100644 solutions/304. Range Sum Query 2D - Immutable/304.java create mode 100644 solutions/304. Range Sum Query 2D - Immutable/304.py create mode 100644 solutions/3040. Maximum Number of Operations With the Same Score II/3040.cpp create mode 100644 solutions/3040. Maximum Number of Operations With the Same Score II/3040.java create mode 100644 solutions/3040. Maximum Number of Operations With the Same Score II/3040.py create mode 100644 solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.cpp create mode 100644 solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.java create mode 100644 solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.py create mode 100644 solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.cpp create mode 100644 solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.java create mode 100644 solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.py create mode 100644 solutions/3042. Count Prefix and Suffix Pairs I/3042.cpp create mode 100644 solutions/3042. Count Prefix and Suffix Pairs I/3042.java create mode 100644 solutions/3042. Count Prefix and Suffix Pairs I/3042.py create mode 100644 solutions/3043. Find the Length of the Longest Common Prefix/3043.cpp create mode 100644 solutions/3043. Find the Length of the Longest Common Prefix/3043.java create mode 100644 solutions/3043. Find the Length of the Longest Common Prefix/3043.py create mode 100644 solutions/3044. Most Frequent Prime/3044.cpp create mode 100644 solutions/3044. Most Frequent Prime/3044.java create mode 100644 solutions/3044. Most Frequent Prime/3044.py create mode 100644 solutions/3045. Count Prefix and Suffix Pairs II/3045.cpp create mode 100644 solutions/3045. Count Prefix and Suffix Pairs II/3045.java create mode 100644 solutions/3045. Count Prefix and Suffix Pairs II/3045.py create mode 100644 solutions/3046. Split the Array/3046.cpp create mode 100644 solutions/3046. Split the Array/3046.java create mode 100644 solutions/3046. Split the Array/3046.py create mode 100644 solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.cpp create mode 100644 solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.java create mode 100644 solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.py create mode 100644 solutions/3048. Earliest Second to Mark Indices I/3048.cpp create mode 100644 solutions/3048. Earliest Second to Mark Indices I/3048.java create mode 100644 solutions/3048. Earliest Second to Mark Indices I/3048.py create mode 100644 solutions/3049. Earliest Second to Mark Indices II/3049.cpp create mode 100644 solutions/3049. Earliest Second to Mark Indices II/3049.java create mode 100644 solutions/3049. Earliest Second to Mark Indices II/3049.py create mode 100644 solutions/305. Number of Islands II/305.cpp create mode 100644 solutions/305. Number of Islands II/305.java create mode 100644 solutions/305. Number of Islands II/305.py create mode 100644 solutions/3050. Pizza Toppings Cost Analysis/3050.sql create mode 100644 solutions/3051. Find Candidates for Data Scientist Position/3051.sql create mode 100644 solutions/3052. Maximize Items/3052.sql create mode 100644 solutions/3053. Classifying Triangles by Lengths/3053.sql create mode 100644 solutions/3054. Binary Tree Nodes/3054.sql create mode 100644 solutions/3055. Top Percentile Fraud/3055.sql create mode 100644 solutions/3056. Snaps Analysis/3056.sql create mode 100644 solutions/3057. Employees Project Allocation/3057.sql create mode 100644 solutions/3058. Friends With No Mutual Friends/3058.sql create mode 100644 solutions/3059. Find All Unique Email Domains/3059.sql create mode 100644 solutions/306. Additive Number/306.cpp create mode 100644 solutions/306. Additive Number/306.java create mode 100644 solutions/306. Additive Number/306.py create mode 100644 solutions/3060. User Activities within Time Bounds/3060.sql create mode 100644 solutions/3061. Calculate Trapping Rain Water/3061.sql create mode 100644 solutions/3062. Winner of the Linked List Game/3062.cpp create mode 100644 solutions/3062. Winner of the Linked List Game/3062.java create mode 100644 solutions/3062. Winner of the Linked List Game/3062.py create mode 100644 solutions/3063. Linked List Frequency/3063.cpp create mode 100644 solutions/3063. Linked List Frequency/3063.java create mode 100644 solutions/3063. Linked List Frequency/3063.py create mode 100644 solutions/3064. Guess the Number Using Bitwise Questions I/3064.cpp create mode 100644 solutions/3064. Guess the Number Using Bitwise Questions I/3064.java create mode 100644 solutions/3064. Guess the Number Using Bitwise Questions I/3064.py create mode 100644 solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.cpp create mode 100644 solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.java create mode 100644 solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.py create mode 100644 solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.cpp create mode 100644 solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.java create mode 100644 solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.py create mode 100644 solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.cpp create mode 100644 solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.java create mode 100644 solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.py create mode 100644 solutions/3068. Find the Maximum Sum of Node Values/3068.cpp create mode 100644 solutions/3068. Find the Maximum Sum of Node Values/3068.java create mode 100644 solutions/3068. Find the Maximum Sum of Node Values/3068.py create mode 100644 solutions/3069. Distribute Elements Into Two Arrays I/3069.cpp create mode 100644 solutions/3069. Distribute Elements Into Two Arrays I/3069.java create mode 100644 solutions/3069. Distribute Elements Into Two Arrays I/3069.py create mode 100644 solutions/307. Range Sum Query - Mutable/307-2.cpp create mode 100644 solutions/307. Range Sum Query - Mutable/307-3.cpp create mode 100644 solutions/307. Range Sum Query - Mutable/307.cpp create mode 100644 solutions/307. Range Sum Query - Mutable/307.java create mode 100644 solutions/307. Range Sum Query - Mutable/307.py create mode 100644 solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.cpp create mode 100644 solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.java create mode 100644 solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.py create mode 100644 solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.cpp create mode 100644 solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.java create mode 100644 solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.py create mode 100644 solutions/3072. Distribute Elements Into Two Arrays II/3072.cpp create mode 100644 solutions/3072. Distribute Elements Into Two Arrays II/3072.java create mode 100644 solutions/3072. Distribute Elements Into Two Arrays II/3072.py create mode 100644 solutions/3073. Maximum Increasing Triplet Value/3073.cpp create mode 100644 solutions/3073. Maximum Increasing Triplet Value/3073.java create mode 100644 solutions/3073. Maximum Increasing Triplet Value/3073.py create mode 100644 solutions/3074. Apple Redistribution into Boxes/3074.cpp create mode 100644 solutions/3074. Apple Redistribution into Boxes/3074.java create mode 100644 solutions/3074. Apple Redistribution into Boxes/3074.py create mode 100644 solutions/3075. Maximize Happiness of Selected Children/3075.cpp create mode 100644 solutions/3075. Maximize Happiness of Selected Children/3075.java create mode 100644 solutions/3075. Maximize Happiness of Selected Children/3075.py create mode 100644 solutions/3076. Shortest Uncommon Substring in an Array/3076.cpp create mode 100644 solutions/3076. Shortest Uncommon Substring in an Array/3076.java create mode 100644 solutions/3076. Shortest Uncommon Substring in an Array/3076.py create mode 100644 solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.cpp create mode 100644 solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.java create mode 100644 solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.py create mode 100644 solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.cpp create mode 100644 solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.java create mode 100644 solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.py create mode 100644 solutions/3079. Find the Sum of Encrypted Integers/3079.cpp create mode 100644 solutions/3079. Find the Sum of Encrypted Integers/3079.java create mode 100644 solutions/3079. Find the Sum of Encrypted Integers/3079.py create mode 100644 solutions/308. Range Sum Query 2D - Mutable/308.cpp create mode 100644 solutions/308. Range Sum Query 2D - Mutable/308.java create mode 100644 solutions/308. Range Sum Query 2D - Mutable/308.py create mode 100644 solutions/3080. Mark Elements on Array by Performing Queries/3080.cpp create mode 100644 solutions/3080. Mark Elements on Array by Performing Queries/3080.java create mode 100644 solutions/3080. Mark Elements on Array by Performing Queries/3080.py create mode 100644 solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.cpp create mode 100644 solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.java create mode 100644 solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.py create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.cpp create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.java create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.py create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.cpp create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.java create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.py create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082.cpp create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082.java create mode 100644 solutions/3082. Find the Sum of the Power of All Subsequences/3082.py create mode 100644 solutions/3083. Existence of a Substring in a String and Its Reverse/3083.cpp create mode 100644 solutions/3083. Existence of a Substring in a String and Its Reverse/3083.java create mode 100644 solutions/3083. Existence of a Substring in a String and Its Reverse/3083.py create mode 100644 solutions/3084. Count Substrings Starting and Ending with Given Character/3084.cpp create mode 100644 solutions/3084. Count Substrings Starting and Ending with Given Character/3084.java create mode 100644 solutions/3084. Count Substrings Starting and Ending with Given Character/3084.py create mode 100644 solutions/3085. Minimum Deletions to Make String K-Special/3085.cpp create mode 100644 solutions/3085. Minimum Deletions to Make String K-Special/3085.java create mode 100644 solutions/3085. Minimum Deletions to Make String K-Special/3085.py create mode 100644 solutions/3086. Minimum Moves to Pick K Ones/3086.cpp create mode 100644 solutions/3086. Minimum Moves to Pick K Ones/3086.java create mode 100644 solutions/3086. Minimum Moves to Pick K Ones/3086.py create mode 100644 solutions/3087. Find Trending Hashtags/3087.sql create mode 100644 solutions/3088. Make String Anti-palindrome/3088.cpp create mode 100644 solutions/3088. Make String Anti-palindrome/3088.java create mode 100644 solutions/3088. Make String Anti-palindrome/3088.py create mode 100644 solutions/3089. Find Bursty Behavior/3089.sql create mode 100644 solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.cpp create mode 100644 solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.java create mode 100644 solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.py create mode 100644 solutions/3090. Maximum Length Substring With Two Occurrences/3090.cpp create mode 100644 solutions/3090. Maximum Length Substring With Two Occurrences/3090.java create mode 100644 solutions/3090. Maximum Length Substring With Two Occurrences/3090.py create mode 100644 solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.cpp create mode 100644 solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.java create mode 100644 solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.py create mode 100644 solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.cpp create mode 100644 solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.java create mode 100644 solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.py create mode 100644 solutions/3092. Most Frequent IDs/3092.cpp create mode 100644 solutions/3092. Most Frequent IDs/3092.java create mode 100644 solutions/3092. Most Frequent IDs/3092.py create mode 100644 solutions/3093. Longest Common Suffix Queries/3093.cpp create mode 100644 solutions/3093. Longest Common Suffix Queries/3093.java create mode 100644 solutions/3093. Longest Common Suffix Queries/3093.py create mode 100644 solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.cpp create mode 100644 solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.java create mode 100644 solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.py create mode 100644 solutions/3094. Guess the Number Using Bitwise Questions II/3094.cpp create mode 100644 solutions/3094. Guess the Number Using Bitwise Questions II/3094.java create mode 100644 solutions/3094. Guess the Number Using Bitwise Questions II/3094.py create mode 100644 solutions/3095. Shortest Subarray With OR at Least K I/3095.cpp create mode 100644 solutions/3095. Shortest Subarray With OR at Least K I/3095.java create mode 100644 solutions/3095. Shortest Subarray With OR at Least K I/3095.py create mode 100644 solutions/3096. Minimum Levels to Gain More Points/3096.cpp create mode 100644 solutions/3096. Minimum Levels to Gain More Points/3096.java create mode 100644 solutions/3096. Minimum Levels to Gain More Points/3096.py create mode 100644 solutions/3097. Shortest Subarray With OR at Least K II/3097.cpp create mode 100644 solutions/3097. Shortest Subarray With OR at Least K II/3097.java create mode 100644 solutions/3097. Shortest Subarray With OR at Least K II/3097.py create mode 100644 solutions/3098. Find the Sum of Subsequence Powers/3098-2.py create mode 100644 solutions/3098. Find the Sum of Subsequence Powers/3098.cpp create mode 100644 solutions/3098. Find the Sum of Subsequence Powers/3098.java create mode 100644 solutions/3098. Find the Sum of Subsequence Powers/3098.py create mode 100644 solutions/3099. Harshad Number/3099.cpp create mode 100644 solutions/3099. Harshad Number/3099.java create mode 100644 solutions/3099. Harshad Number/3099.py create mode 100644 solutions/31. Next Permutation/31.cpp create mode 100644 solutions/31. Next Permutation/31.java create mode 100644 solutions/31. Next Permutation/31.py create mode 100644 solutions/310. Minimum Height Trees/310.cpp create mode 100644 solutions/310. Minimum Height Trees/310.java create mode 100644 solutions/310. Minimum Height Trees/310.py create mode 100644 solutions/3100. Water Bottles II/3100.cpp create mode 100644 solutions/3100. Water Bottles II/3100.java create mode 100644 solutions/3100. Water Bottles II/3100.py create mode 100644 solutions/3101. Count Alternating Subarrays/3101.cpp create mode 100644 solutions/3101. Count Alternating Subarrays/3101.java create mode 100644 solutions/3101. Count Alternating Subarrays/3101.py create mode 100644 solutions/3102. Minimize Manhattan Distances/3102.cpp create mode 100644 solutions/3102. Minimize Manhattan Distances/3102.java create mode 100644 solutions/3102. Minimize Manhattan Distances/3102.py create mode 100644 solutions/3103. Find Trending Hashtags II/3103.sql create mode 100644 solutions/3104. Find Longest Self-Contained Substring/3104.cpp create mode 100644 solutions/3104. Find Longest Self-Contained Substring/3104.java create mode 100644 solutions/3104. Find Longest Self-Contained Substring/3104.py create mode 100644 solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.cpp create mode 100644 solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.java create mode 100644 solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.py create mode 100644 solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.cpp create mode 100644 solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.java create mode 100644 solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.py create mode 100644 solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.cpp create mode 100644 solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.java create mode 100644 solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.py create mode 100644 solutions/3108. Minimum Cost Walk in Weighted Graph/3108.cpp create mode 100644 solutions/3108. Minimum Cost Walk in Weighted Graph/3108.java create mode 100644 solutions/3108. Minimum Cost Walk in Weighted Graph/3108.py create mode 100644 solutions/3109. Find the Index of Permutation/3109.cpp create mode 100644 solutions/3109. Find the Index of Permutation/3109.java create mode 100644 solutions/3109. Find the Index of Permutation/3109.py create mode 100644 solutions/311. Sparse Matrix Multiplication/311-2.cpp create mode 100644 solutions/311. Sparse Matrix Multiplication/311-2.java create mode 100644 solutions/311. Sparse Matrix Multiplication/311-2.py create mode 100644 solutions/311. Sparse Matrix Multiplication/311.cpp create mode 100644 solutions/311. Sparse Matrix Multiplication/311.java create mode 100644 solutions/311. Sparse Matrix Multiplication/311.py create mode 100644 solutions/3110. Score of a String/3110.cpp create mode 100644 solutions/3110. Score of a String/3110.java create mode 100644 solutions/3110. Score of a String/3110.py create mode 100644 solutions/3111. Minimum Rectangles to Cover Points/3111.cpp create mode 100644 solutions/3111. Minimum Rectangles to Cover Points/3111.java create mode 100644 solutions/3111. Minimum Rectangles to Cover Points/3111.py create mode 100644 solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.cpp create mode 100644 solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.java create mode 100644 solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.py create mode 100644 solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.cpp create mode 100644 solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.java create mode 100644 solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.py create mode 100644 solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.cpp create mode 100644 solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.java create mode 100644 solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.py create mode 100644 solutions/3115. Maximum Prime Difference/3115.cpp create mode 100644 solutions/3115. Maximum Prime Difference/3115.java create mode 100644 solutions/3115. Maximum Prime Difference/3115.py create mode 100644 solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.cpp create mode 100644 solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.java create mode 100644 solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.py create mode 100644 solutions/3117. Minimum Sum of Values by Dividing Array/3117.cpp create mode 100644 solutions/3117. Minimum Sum of Values by Dividing Array/3117.java create mode 100644 solutions/3117. Minimum Sum of Values by Dividing Array/3117.py create mode 100644 solutions/3118. Friday Purchase III/3118.sql create mode 100644 solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.cpp create mode 100644 solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.java create mode 100644 solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.py create mode 100644 solutions/312. Burst Balloons/312-2.cpp create mode 100644 solutions/312. Burst Balloons/312-2.java create mode 100644 solutions/312. Burst Balloons/312-2.py create mode 100644 solutions/312. Burst Balloons/312.cpp create mode 100644 solutions/312. Burst Balloons/312.java create mode 100644 solutions/312. Burst Balloons/312.py create mode 100644 solutions/3120. Count the Number of Special Characters I/3120.cpp create mode 100644 solutions/3120. Count the Number of Special Characters I/3120.java create mode 100644 solutions/3120. Count the Number of Special Characters I/3120.py create mode 100644 solutions/3121. Count the Number of Special Characters II/3121.cpp create mode 100644 solutions/3121. Count the Number of Special Characters II/3121.java create mode 100644 solutions/3121. Count the Number of Special Characters II/3121.py create mode 100644 solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.cpp create mode 100644 solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.java create mode 100644 solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.py create mode 100644 solutions/3123. Find Edges in Shortest Paths/3123.cpp create mode 100644 solutions/3123. Find Edges in Shortest Paths/3123.java create mode 100644 solutions/3123. Find Edges in Shortest Paths/3123.py create mode 100644 solutions/3124. Find Longest Calls/3124.sql create mode 100644 solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.cpp create mode 100644 solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.java create mode 100644 solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.py create mode 100644 solutions/3126. Server Utilization Time/3126.sql create mode 100644 solutions/3127. Make a Square with the Same Color/3127.cpp create mode 100644 solutions/3127. Make a Square with the Same Color/3127.java create mode 100644 solutions/3127. Make a Square with the Same Color/3127.py create mode 100644 solutions/3128. Right Triangles/3128.cpp create mode 100644 solutions/3128. Right Triangles/3128.java create mode 100644 solutions/3128. Right Triangles/3128.py create mode 100644 solutions/3129. Find All Possible Stable Binary Arrays I/3129.cpp create mode 100644 solutions/3129. Find All Possible Stable Binary Arrays I/3129.java create mode 100644 solutions/3129. Find All Possible Stable Binary Arrays I/3129.py create mode 100644 solutions/313. Super Ugly Number/313-2.cpp create mode 100644 solutions/313. Super Ugly Number/313-2.java create mode 100644 solutions/313. Super Ugly Number/313-2.py create mode 100644 solutions/313. Super Ugly Number/313.cpp create mode 100644 solutions/313. Super Ugly Number/313.java create mode 100644 solutions/313. Super Ugly Number/313.py create mode 100644 solutions/3130. Find All Possible Stable Binary Arrays II/3130.cpp create mode 100644 solutions/3130. Find All Possible Stable Binary Arrays II/3130.java create mode 100644 solutions/3130. Find All Possible Stable Binary Arrays II/3130.py create mode 100644 solutions/3131. Find the Integer Added to Array I/3131.cpp create mode 100644 solutions/3131. Find the Integer Added to Array I/3131.java create mode 100644 solutions/3131. Find the Integer Added to Array I/3131.py create mode 100644 solutions/3132. Find the Integer Added to Array II/3132.cpp create mode 100644 solutions/3132. Find the Integer Added to Array II/3132.java create mode 100644 solutions/3132. Find the Integer Added to Array II/3132.py create mode 100644 solutions/3133. Minimum Array End/3133.cpp create mode 100644 solutions/3133. Minimum Array End/3133.java create mode 100644 solutions/3133. Minimum Array End/3133.py create mode 100644 solutions/3134. Find the Median of the Uniqueness Array/3134.cpp create mode 100644 solutions/3134. Find the Median of the Uniqueness Array/3134.java create mode 100644 solutions/3134. Find the Median of the Uniqueness Array/3134.py create mode 100644 solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.cpp create mode 100644 solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.java create mode 100644 solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.py create mode 100644 solutions/3136. Valid Word/3136.cpp create mode 100644 solutions/3136. Valid Word/3136.java create mode 100644 solutions/3136. Valid Word/3136.py create mode 100644 solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.cpp create mode 100644 solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.java create mode 100644 solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.py create mode 100644 solutions/3138. Minimum Length of Anagram Concatenation/3138.cpp create mode 100644 solutions/3138. Minimum Length of Anagram Concatenation/3138.java create mode 100644 solutions/3138. Minimum Length of Anagram Concatenation/3138.py create mode 100644 solutions/3139. Minimum Cost to Equalize Array/3139.cpp create mode 100644 solutions/3139. Minimum Cost to Equalize Array/3139.java create mode 100644 solutions/3139. Minimum Cost to Equalize Array/3139.py create mode 100644 solutions/314. Binary Tree Vertical Order Traversal/314.cpp create mode 100644 solutions/314. Binary Tree Vertical Order Traversal/314.java create mode 100644 solutions/314. Binary Tree Vertical Order Traversal/314.py create mode 100644 solutions/3140. Consecutive Available Seats II/3140.sql create mode 100644 solutions/3141. Maximum Hamming Distances/3141.cpp create mode 100644 solutions/3141. Maximum Hamming Distances/3141.java create mode 100644 solutions/3141. Maximum Hamming Distances/3141.py create mode 100644 solutions/3142. Check if Grid Satisfies Conditions/3142.cpp create mode 100644 solutions/3142. Check if Grid Satisfies Conditions/3142.java create mode 100644 solutions/3142. Check if Grid Satisfies Conditions/3142.py create mode 100644 solutions/3143. Maximum Points Inside the Square/3143.cpp create mode 100644 solutions/3143. Maximum Points Inside the Square/3143.java create mode 100644 solutions/3143. Maximum Points Inside the Square/3143.py create mode 100644 solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.cpp create mode 100644 solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.java create mode 100644 solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.py create mode 100644 solutions/3145. Find Products of Elements of Big Array/3145.cpp create mode 100644 solutions/3145. Find Products of Elements of Big Array/3145.java create mode 100644 solutions/3145. Find Products of Elements of Big Array/3145.py create mode 100644 solutions/3146. Permutation Difference between Two Strings/3146.cpp create mode 100644 solutions/3146. Permutation Difference between Two Strings/3146.java create mode 100644 solutions/3146. Permutation Difference between Two Strings/3146.py create mode 100644 solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.cpp create mode 100644 solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.java create mode 100644 solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.py create mode 100644 solutions/3148. Maximum Difference Score in a Grid/3148.cpp create mode 100644 solutions/3148. Maximum Difference Score in a Grid/3148.java create mode 100644 solutions/3148. Maximum Difference Score in a Grid/3148.py create mode 100644 solutions/3149. Find the Minimum Cost Array Permutation/3149.cpp create mode 100644 solutions/3149. Find the Minimum Cost Array Permutation/3149.java create mode 100644 solutions/3149. Find the Minimum Cost Array Permutation/3149.py create mode 100644 solutions/315. Count of Smaller Numbers After Self/315-2.cpp create mode 100644 solutions/315. Count of Smaller Numbers After Self/315-3.cpp create mode 100644 solutions/315. Count of Smaller Numbers After Self/315-4.cpp create mode 100644 solutions/315. Count of Smaller Numbers After Self/315-4.java create mode 100644 solutions/315. Count of Smaller Numbers After Self/315-4.py create mode 100644 solutions/315. Count of Smaller Numbers After Self/315.cpp create mode 100644 solutions/315. Count of Smaller Numbers After Self/315.java create mode 100644 solutions/315. Count of Smaller Numbers After Self/315.py create mode 100644 solutions/3150. Invalid Tweets II/3150.sql create mode 100644 solutions/3151. Special Array I/3151.cpp create mode 100644 solutions/3151. Special Array I/3151.java create mode 100644 solutions/3151. Special Array I/3151.py create mode 100644 solutions/3152. Special Array II/3152.cpp create mode 100644 solutions/3152. Special Array II/3152.java create mode 100644 solutions/3152. Special Array II/3152.py create mode 100644 solutions/3153. Sum of Digit Differences of All Pairs/3153.cpp create mode 100644 solutions/3153. Sum of Digit Differences of All Pairs/3153.java create mode 100644 solutions/3153. Sum of Digit Differences of All Pairs/3153.py create mode 100644 solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.cpp create mode 100644 solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.java create mode 100644 solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.py create mode 100644 solutions/3155. Maximum Number of Upgradable Servers/3155.cpp create mode 100644 solutions/3155. Maximum Number of Upgradable Servers/3155.java create mode 100644 solutions/3155. Maximum Number of Upgradable Servers/3155.py create mode 100644 solutions/3156. Employee Task Duration and Concurrent Tasks/3156.sql create mode 100644 solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.cpp create mode 100644 solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.java create mode 100644 solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.py create mode 100644 solutions/3157. Find the Level of Tree with Minimum Sum/3157.cpp create mode 100644 solutions/3157. Find the Level of Tree with Minimum Sum/3157.java create mode 100644 solutions/3157. Find the Level of Tree with Minimum Sum/3157.py create mode 100644 solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.cpp create mode 100644 solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.java create mode 100644 solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.py create mode 100644 solutions/3159. Find Occurrences of an Element in an Array/3159.cpp create mode 100644 solutions/3159. Find Occurrences of an Element in an Array/3159.java create mode 100644 solutions/3159. Find Occurrences of an Element in an Array/3159.py create mode 100644 solutions/316. Remove Duplicate Letters/316.cpp create mode 100644 solutions/316. Remove Duplicate Letters/316.java create mode 100644 solutions/316. Remove Duplicate Letters/316.py create mode 100644 solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.cpp create mode 100644 solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.java create mode 100644 solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.py create mode 100644 solutions/3161. Block Placement Queries/3161.cpp create mode 100644 solutions/3161. Block Placement Queries/3161.java create mode 100644 solutions/3161. Block Placement Queries/3161.py create mode 100644 solutions/3162. Find the Number of Good Pairs I/3162.cpp create mode 100644 solutions/3162. Find the Number of Good Pairs I/3162.java create mode 100644 solutions/3162. Find the Number of Good Pairs I/3162.py create mode 100644 solutions/3163. String Compression III/3163.cpp create mode 100644 solutions/3163. String Compression III/3163.java create mode 100644 solutions/3163. String Compression III/3163.py create mode 100644 solutions/3164. Find the Number of Good Pairs II/3164.cpp create mode 100644 solutions/3164. Find the Number of Good Pairs II/3164.java create mode 100644 solutions/3164. Find the Number of Good Pairs II/3164.py create mode 100644 solutions/3165. Maximum Sum of Subsequence With Non-adjacent Elements/3165.cpp create mode 100644 solutions/3166. Calculate Parking Fees and Duration/3166.sql create mode 100644 solutions/3167. Better Compression of String/3167.cpp create mode 100644 solutions/3167. Better Compression of String/3167.java create mode 100644 solutions/3167. Better Compression of String/3167.py create mode 100644 solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.cpp create mode 100644 solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.java create mode 100644 solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.py create mode 100644 solutions/3169. Count Days Without Meetings/3169.cpp create mode 100644 solutions/3169. Count Days Without Meetings/3169.java create mode 100644 solutions/3169. Count Days Without Meetings/3169.py create mode 100644 solutions/317. Shortest Distance from All Buildings/317.cpp create mode 100644 solutions/317. Shortest Distance from All Buildings/317.java create mode 100644 solutions/317. Shortest Distance from All Buildings/317.py create mode 100644 solutions/3170. Lexicographically Minimum String After Removing Stars/3170.cpp create mode 100644 solutions/3170. Lexicographically Minimum String After Removing Stars/3170.java create mode 100644 solutions/3170. Lexicographically Minimum String After Removing Stars/3170.py create mode 100644 solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.cpp create mode 100644 solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.java create mode 100644 solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.py create mode 100644 solutions/3172. Second Day Verification/3172.sql create mode 100644 solutions/3173. Bitwise OR of Adjacent Elements/3173.cpp create mode 100644 solutions/3173. Bitwise OR of Adjacent Elements/3173.java create mode 100644 solutions/3173. Bitwise OR of Adjacent Elements/3173.py create mode 100644 solutions/3174. Clear Digits/3174.cpp create mode 100644 solutions/3174. Clear Digits/3174.java create mode 100644 solutions/3174. Clear Digits/3174.py create mode 100644 solutions/3175. Find The First Player to win K Games in a Row/3175.cpp create mode 100644 solutions/3175. Find The First Player to win K Games in a Row/3175.java create mode 100644 solutions/3175. Find The First Player to win K Games in a Row/3175.py create mode 100644 solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.cpp create mode 100644 solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.java create mode 100644 solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.py create mode 100644 solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.cpp create mode 100644 solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.java create mode 100644 solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.py create mode 100644 solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.cpp create mode 100644 solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.java create mode 100644 solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.py create mode 100644 solutions/3179. Find the N-th Value After K Seconds/3179.cpp create mode 100644 solutions/3179. Find the N-th Value After K Seconds/3179.java create mode 100644 solutions/3179. Find the N-th Value After K Seconds/3179.py create mode 100644 solutions/318. Maximum Product of Word Lengths/318.cpp create mode 100644 solutions/318. Maximum Product of Word Lengths/318.java create mode 100644 solutions/318. Maximum Product of Word Lengths/318.py create mode 100644 solutions/3180. Maximum Total Reward Using Operations I/3180.cpp create mode 100644 solutions/3180. Maximum Total Reward Using Operations I/3180.java create mode 100644 solutions/3180. Maximum Total Reward Using Operations I/3180.py create mode 100644 solutions/3181. Maximum Total Reward Using Operations II/3181.cpp create mode 100644 solutions/3181. Maximum Total Reward Using Operations II/3181.java create mode 100644 solutions/3181. Maximum Total Reward Using Operations II/3181.py create mode 100644 solutions/3182. Find Top Scoring Students/3182.sql create mode 100644 solutions/3183. The Number of Ways to Make the Sum/3183.cpp create mode 100644 solutions/3183. The Number of Ways to Make the Sum/3183.java create mode 100644 solutions/3183. The Number of Ways to Make the Sum/3183.py create mode 100644 solutions/3184. Count Pairs That Form a Complete Day I/3184.cpp create mode 100644 solutions/3184. Count Pairs That Form a Complete Day I/3184.java create mode 100644 solutions/3184. Count Pairs That Form a Complete Day I/3184.py create mode 100644 solutions/3185. Count Pairs That Form a Complete Day II/3185.cpp create mode 100644 solutions/3185. Count Pairs That Form a Complete Day II/3185.java create mode 100644 solutions/3185. Count Pairs That Form a Complete Day II/3185.py create mode 100644 solutions/3186. Maximum Total Damage With Spell Casting/3186.cpp create mode 100644 solutions/3186. Maximum Total Damage With Spell Casting/3186.java create mode 100644 solutions/3186. Maximum Total Damage With Spell Casting/3186.py create mode 100644 solutions/3187. Peaks in Array/3187-2.cpp create mode 100644 solutions/3187. Peaks in Array/3187.cpp create mode 100644 solutions/3187. Peaks in Array/3187.java create mode 100644 solutions/3187. Peaks in Array/3187.py create mode 100644 solutions/3188. Find Top Scoring Students II/3188.sql create mode 100644 solutions/3189. Minimum Moves to Get a Peaceful Board/3189.cpp create mode 100644 solutions/3189. Minimum Moves to Get a Peaceful Board/3189.java create mode 100644 solutions/3189. Minimum Moves to Get a Peaceful Board/3189.py create mode 100644 solutions/319. Bulb Switcher/319.cpp create mode 100644 solutions/319. Bulb Switcher/319.java create mode 100644 solutions/319. Bulb Switcher/319.py create mode 100644 solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.cpp create mode 100644 solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.java create mode 100644 solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.py create mode 100644 solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.cpp create mode 100644 solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.java create mode 100644 solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.py create mode 100644 solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.cpp create mode 100644 solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.java create mode 100644 solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.py create mode 100644 solutions/3193. Count the Number of Inversions/3193.cpp create mode 100644 solutions/3193. Count the Number of Inversions/3193.java create mode 100644 solutions/3193. Count the Number of Inversions/3193.py create mode 100644 solutions/3194. Minimum Average of Smallest and Largest Elements/3194.cpp create mode 100644 solutions/3194. Minimum Average of Smallest and Largest Elements/3194.java create mode 100644 solutions/3194. Minimum Average of Smallest and Largest Elements/3194.py create mode 100644 solutions/3195. Find the Minimum Area to Cover All Ones I/3195.cpp create mode 100644 solutions/3195. Find the Minimum Area to Cover All Ones I/3195.java create mode 100644 solutions/3195. Find the Minimum Area to Cover All Ones I/3195.py create mode 100644 solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.cpp create mode 100644 solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.java create mode 100644 solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.py create mode 100644 solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.cpp create mode 100644 solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.java create mode 100644 solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.py create mode 100644 solutions/3197. Find the Minimum Area to Cover All Ones II/3197.cpp create mode 100644 solutions/3197. Find the Minimum Area to Cover All Ones II/3197.java create mode 100644 solutions/3197. Find the Minimum Area to Cover All Ones II/3197.py create mode 100644 solutions/3198. Find Cities in Each State/3198.sql create mode 100644 solutions/3199. Count Triplets with Even XOR Set Bits I/3199.cpp create mode 100644 solutions/3199. Count Triplets with Even XOR Set Bits I/3199.java create mode 100644 solutions/3199. Count Triplets with Even XOR Set Bits I/3199.py create mode 100644 solutions/32. Longest Valid Parentheses/32.cpp create mode 100644 solutions/32. Longest Valid Parentheses/32.java create mode 100644 solutions/32. Longest Valid Parentheses/32.py create mode 100644 solutions/320. Generalized Abbreviation/320.cpp create mode 100644 solutions/320. Generalized Abbreviation/320.java create mode 100644 solutions/320. Generalized Abbreviation/320.py create mode 100644 solutions/3200. Maximum Height of a Triangle/3200.cpp create mode 100644 solutions/3200. Maximum Height of a Triangle/3200.java create mode 100644 solutions/3200. Maximum Height of a Triangle/3200.py create mode 100644 solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.cpp create mode 100644 solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.java create mode 100644 solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.py create mode 100644 solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.cpp create mode 100644 solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.java create mode 100644 solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.py create mode 100644 solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.cpp create mode 100644 solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.java create mode 100644 solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.py create mode 100644 solutions/3204. Bitwise User Permissions Analysis/3204.sql create mode 100644 solutions/3205. Maximum Array Hopping Score I/3205-2.cpp create mode 100644 solutions/3205. Maximum Array Hopping Score I/3205-2.java create mode 100644 solutions/3205. Maximum Array Hopping Score I/3205-2.py create mode 100644 solutions/3205. Maximum Array Hopping Score I/3205.cpp create mode 100644 solutions/3205. Maximum Array Hopping Score I/3205.java create mode 100644 solutions/3205. Maximum Array Hopping Score I/3205.py create mode 100644 solutions/3206. Alternating Groups I/3206.cpp create mode 100644 solutions/3206. Alternating Groups I/3206.java create mode 100644 solutions/3206. Alternating Groups I/3206.py create mode 100644 solutions/3207. Maximum Points After Enemy Battles/3207.cpp create mode 100644 solutions/3207. Maximum Points After Enemy Battles/3207.java create mode 100644 solutions/3207. Maximum Points After Enemy Battles/3207.py create mode 100644 solutions/3208. Alternating Groups II/3208.cpp create mode 100644 solutions/3208. Alternating Groups II/3208.java create mode 100644 solutions/3208. Alternating Groups II/3208.py create mode 100644 solutions/3209. Number of Subarrays With AND Value of K/3209.cpp create mode 100644 solutions/3209. Number of Subarrays With AND Value of K/3209.java create mode 100644 solutions/3209. Number of Subarrays With AND Value of K/3209.py create mode 100644 solutions/321. Create Maximum Number/321.cpp create mode 100644 solutions/321. Create Maximum Number/321.java create mode 100644 solutions/321. Create Maximum Number/321.py create mode 100644 solutions/3210. Find the Encrypted String/3210.cpp create mode 100644 solutions/3210. Find the Encrypted String/3210.java create mode 100644 solutions/3210. Find the Encrypted String/3210.py create mode 100644 solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.cpp create mode 100644 solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.java create mode 100644 solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.py create mode 100644 solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.cpp create mode 100644 solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.java create mode 100644 solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.py create mode 100644 solutions/3213. Construct String with Minimum Cost/3213.cpp create mode 100644 solutions/3213. Construct String with Minimum Cost/3213.java create mode 100644 solutions/3213. Construct String with Minimum Cost/3213.py create mode 100644 solutions/3214. Year on Year Growth Rate/3214.sql create mode 100644 solutions/3215. Count Triplets with Even XOR Set Bits II/3215.cpp create mode 100644 solutions/3215. Count Triplets with Even XOR Set Bits II/3215.java create mode 100644 solutions/3215. Count Triplets with Even XOR Set Bits II/3215.py create mode 100644 solutions/3216. Lexicographically Smallest String After a Swap/3216.cpp create mode 100644 solutions/3216. Lexicographically Smallest String After a Swap/3216.java create mode 100644 solutions/3216. Lexicographically Smallest String After a Swap/3216.py create mode 100644 solutions/3217. Delete Nodes From Linked List Present in Array/3217.cpp create mode 100644 solutions/3217. Delete Nodes From Linked List Present in Array/3217.java create mode 100644 solutions/3217. Delete Nodes From Linked List Present in Array/3217.py create mode 100644 solutions/3218. Minimum Cost for Cutting Cake I/3218.cpp create mode 100644 solutions/3218. Minimum Cost for Cutting Cake I/3218.java create mode 100644 solutions/3218. Minimum Cost for Cutting Cake I/3218.py create mode 100644 solutions/3219. Minimum Cost for Cutting Cake II/3219.cpp create mode 100644 solutions/3219. Minimum Cost for Cutting Cake II/3219.java create mode 100644 solutions/3219. Minimum Cost for Cutting Cake II/3219.py create mode 100644 solutions/322. Coin Change/322-2.cpp create mode 100644 solutions/322. Coin Change/322-2.java create mode 100644 solutions/322. Coin Change/322.cpp create mode 100644 solutions/322. Coin Change/322.java create mode 100644 solutions/322. Coin Change/322.py create mode 100644 solutions/3220. Odd and Even Transactions/3220.sql create mode 100644 solutions/3221. Maximum Array Hopping Score II/3221.cpp create mode 100644 solutions/3221. Maximum Array Hopping Score II/3221.java create mode 100644 solutions/3221. Maximum Array Hopping Score II/3221.py create mode 100644 solutions/3222. Find the Winning Player in Coin Game/3222.cpp create mode 100644 solutions/3222. Find the Winning Player in Coin Game/3222.java create mode 100644 solutions/3222. Find the Winning Player in Coin Game/3222.py create mode 100644 solutions/3223. Minimum Length of String After Operations/3223.cpp create mode 100644 solutions/3223. Minimum Length of String After Operations/3223.java create mode 100644 solutions/3223. Minimum Length of String After Operations/3223.py create mode 100644 solutions/3224. Minimum Array Changes to Make Differences Equal/3224.cpp create mode 100644 solutions/3224. Minimum Array Changes to Make Differences Equal/3224.java create mode 100644 solutions/3224. Minimum Array Changes to Make Differences Equal/3224.py create mode 100644 solutions/3225. Maximum Score From Grid Operations/3225.cpp create mode 100644 solutions/3225. Maximum Score From Grid Operations/3225.java create mode 100644 solutions/3225. Maximum Score From Grid Operations/3225.py create mode 100644 solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.cpp create mode 100644 solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.java create mode 100644 solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.py create mode 100644 solutions/3227. Vowels Game in a String/3227.cpp create mode 100644 solutions/3227. Vowels Game in a String/3227.java create mode 100644 solutions/3227. Vowels Game in a String/3227.py create mode 100644 solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.cpp create mode 100644 solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.java create mode 100644 solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.py create mode 100644 solutions/3229. Minimum Operations to Make Array Equal to Target/3229.cpp create mode 100644 solutions/3229. Minimum Operations to Make Array Equal to Target/3229.java create mode 100644 solutions/3229. Minimum Operations to Make Array Equal to Target/3229.py create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323-2.cpp create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323-2.java create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323-2.py create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323-3.cpp create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323-3.java create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323-3.py create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323.cpp create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323.java create mode 100644 solutions/323. Number of Connected Components in an Undirected Graph/323.py create mode 100644 solutions/3230. Customer Purchasing Behavior Analysis/3230.sql create mode 100644 solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.cpp create mode 100644 solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.java create mode 100644 solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.py create mode 100644 solutions/3232. Find if Digit Game Can Be Won/3232.cpp create mode 100644 solutions/3232. Find if Digit Game Can Be Won/3232.java create mode 100644 solutions/3232. Find if Digit Game Can Be Won/3232.py create mode 100644 solutions/3233. Find the Count of Numbers Which Are Not Special/3233.cpp create mode 100644 solutions/3233. Find the Count of Numbers Which Are Not Special/3233.java create mode 100644 solutions/3233. Find the Count of Numbers Which Are Not Special/3233.py create mode 100644 solutions/3234. Count the Number of Substrings With Dominant Ones/3234.cpp create mode 100644 solutions/3234. Count the Number of Substrings With Dominant Ones/3234.java create mode 100644 solutions/3234. Count the Number of Substrings With Dominant Ones/3234.py create mode 100644 solutions/3235. Check if the Rectangle Corner Is Reachable/3235.cpp create mode 100644 solutions/3235. Check if the Rectangle Corner Is Reachable/3235.java create mode 100644 solutions/3235. Check if the Rectangle Corner Is Reachable/3235.py create mode 100644 solutions/3236. CEO Subordinate Hierarchy/3236.sql create mode 100644 solutions/3237. Alt and Tab Simulation/3237.cpp create mode 100644 solutions/3237. Alt and Tab Simulation/3237.java create mode 100644 solutions/3237. Alt and Tab Simulation/3237.py create mode 100644 solutions/324. Wiggle Sort II/324.cpp create mode 100644 solutions/324. Wiggle Sort II/324.java create mode 100644 solutions/324. Wiggle Sort II/324.py create mode 100644 solutions/3241. Time Taken to Mark All Nodes/3241.py create mode 100644 solutions/325. Maximum Size Subarray Sum Equals k/325.cpp create mode 100644 solutions/325. Maximum Size Subarray Sum Equals k/325.java create mode 100644 solutions/325. Maximum Size Subarray Sum Equals k/325.py create mode 100644 solutions/326. Power of Three/326.cpp create mode 100644 solutions/326. Power of Three/326.java create mode 100644 solutions/326. Power of Three/326.py create mode 100644 solutions/327. Count of Range Sum/327.cpp create mode 100644 solutions/327. Count of Range Sum/327.java create mode 100644 solutions/327. Count of Range Sum/327.py create mode 100644 solutions/328. Odd Even Linked List/328.cpp create mode 100644 solutions/328. Odd Even Linked List/328.java create mode 100644 solutions/328. Odd Even Linked List/328.py create mode 100644 solutions/329. Longest Increasing Path in a Matrix/329.cpp create mode 100644 solutions/329. Longest Increasing Path in a Matrix/329.java create mode 100644 solutions/329. Longest Increasing Path in a Matrix/329.py create mode 100644 solutions/33. Search in Rotated Sorted Array/33.cpp create mode 100644 solutions/33. Search in Rotated Sorted Array/33.java create mode 100644 solutions/33. Search in Rotated Sorted Array/33.py create mode 100644 solutions/330. Patching Array/330.cpp create mode 100644 solutions/330. Patching Array/330.java create mode 100644 solutions/330. Patching Array/330.py create mode 100644 solutions/331. Verify Preorder Serialization of a Binary Tree/331.cpp create mode 100644 solutions/331. Verify Preorder Serialization of a Binary Tree/331.java create mode 100644 solutions/331. Verify Preorder Serialization of a Binary Tree/331.py create mode 100644 solutions/332. Reconstruct Itinerary/332.cpp create mode 100644 solutions/332. Reconstruct Itinerary/332.java create mode 100644 solutions/332. Reconstruct Itinerary/332.py create mode 100644 solutions/333. Largest BST Subtree/333.cpp create mode 100644 solutions/333. Largest BST Subtree/333.java create mode 100644 solutions/333. Largest BST Subtree/333.py create mode 100644 solutions/334. Increasing Triplet Subsequence/334.cpp create mode 100644 solutions/334. Increasing Triplet Subsequence/334.java create mode 100644 solutions/334. Increasing Triplet Subsequence/334.py create mode 100644 solutions/335. Self Crossing/335.cpp create mode 100644 solutions/335. Self Crossing/335.java create mode 100644 solutions/335. Self Crossing/335.py create mode 100644 solutions/336. Palindrome Pairs/336.cpp create mode 100644 solutions/336. Palindrome Pairs/336.java create mode 100644 solutions/336. Palindrome Pairs/336.py create mode 100644 solutions/337. House Robber III/337.cpp create mode 100644 solutions/337. House Robber III/337.java create mode 100644 solutions/337. House Robber III/337.py create mode 100644 solutions/338. Counting Bits/338.cpp create mode 100644 solutions/338. Counting Bits/338.java create mode 100644 solutions/338. Counting Bits/338.py create mode 100644 solutions/339. Nested List Weight Sum/339-2.cpp create mode 100644 solutions/339. Nested List Weight Sum/339-2.java create mode 100644 solutions/339. Nested List Weight Sum/339-2.py create mode 100644 solutions/339. Nested List Weight Sum/339.cpp create mode 100644 solutions/339. Nested List Weight Sum/339.java create mode 100644 solutions/339. Nested List Weight Sum/339.py create mode 100644 solutions/34. Find First and Last Position of Element in Sorted Array/34.cpp create mode 100644 solutions/34. Find First and Last Position of Element in Sorted Array/34.java create mode 100644 solutions/34. Find First and Last Position of Element in Sorted Array/34.py create mode 100644 solutions/340. Longest Substring with At Most K Distinct Characters/340-2.cpp create mode 100644 solutions/340. Longest Substring with At Most K Distinct Characters/340.cpp create mode 100644 solutions/340. Longest Substring with At Most K Distinct Characters/340.java create mode 100644 solutions/340. Longest Substring with At Most K Distinct Characters/340.py create mode 100644 solutions/341. Flatten Nested List Iterator/341-2.cpp create mode 100644 solutions/341. Flatten Nested List Iterator/341-2.java create mode 100644 solutions/341. Flatten Nested List Iterator/341-2.py create mode 100644 solutions/341. Flatten Nested List Iterator/341.cpp create mode 100644 solutions/341. Flatten Nested List Iterator/341.java create mode 100644 solutions/341. Flatten Nested List Iterator/341.py create mode 100644 solutions/342. Power of Four/342.cpp create mode 100644 solutions/342. Power of Four/342.java create mode 100644 solutions/342. Power of Four/342.py create mode 100644 solutions/343. Integer Break/343.cpp create mode 100644 solutions/343. Integer Break/343.java create mode 100644 solutions/343. Integer Break/343.py create mode 100644 solutions/344. Reverse String/344.cpp create mode 100644 solutions/344. Reverse String/344.java create mode 100644 solutions/344. Reverse String/344.py create mode 100644 solutions/345. Reverse Vowels of a String/345.cpp create mode 100644 solutions/345. Reverse Vowels of a String/345.java create mode 100644 solutions/345. Reverse Vowels of a String/345.py create mode 100644 solutions/346. Moving Average from Data Stream/346.cpp create mode 100644 solutions/346. Moving Average from Data Stream/346.java create mode 100644 solutions/346. Moving Average from Data Stream/346.py create mode 100644 solutions/347. Top K Frequent Elements/347-2.cpp create mode 100644 solutions/347. Top K Frequent Elements/347-2.java create mode 100644 solutions/347. Top K Frequent Elements/347-2.py create mode 100644 solutions/347. Top K Frequent Elements/347.cpp create mode 100644 solutions/347. Top K Frequent Elements/347.java create mode 100644 solutions/348. Design Tic-Tac-Toe/348.cpp create mode 100644 solutions/348. Design Tic-Tac-Toe/348.java create mode 100644 solutions/348. Design Tic-Tac-Toe/348.py create mode 100644 solutions/349. Intersection of Two Arrays/349.cpp create mode 100644 solutions/349. Intersection of Two Arrays/349.java create mode 100644 solutions/349. Intersection of Two Arrays/349.py create mode 100644 solutions/35. Search Insert Position/35.cpp create mode 100644 solutions/35. Search Insert Position/35.java create mode 100644 solutions/35. Search Insert Position/35.py create mode 100644 solutions/350. Intersection of Two Arrays II/350-2.cpp create mode 100644 solutions/350. Intersection of Two Arrays II/350-3.cpp create mode 100644 solutions/350. Intersection of Two Arrays II/350.cpp create mode 100644 solutions/350. Intersection of Two Arrays II/350.java create mode 100644 solutions/350. Intersection of Two Arrays II/350.py create mode 100644 solutions/351. Android Unlock Patterns/351.cpp create mode 100644 solutions/351. Android Unlock Patterns/351.java create mode 100644 solutions/351. Android Unlock Patterns/351.py create mode 100644 solutions/352. Data Stream as Disjoint Intervals/352.cpp create mode 100644 solutions/352. Data Stream as Disjoint Intervals/352.java create mode 100644 solutions/352. Data Stream as Disjoint Intervals/352.py create mode 100644 solutions/353. Design Snake Game/353.cpp create mode 100644 solutions/353. Design Snake Game/353.java create mode 100644 solutions/353. Design Snake Game/353.py create mode 100644 solutions/354. Russian Doll Envelopes/354.cpp create mode 100644 solutions/354. Russian Doll Envelopes/354.java create mode 100644 solutions/354. Russian Doll Envelopes/354.py create mode 100644 solutions/355. Design Twitter/355.cpp create mode 100644 solutions/355. Design Twitter/355.java create mode 100644 solutions/355. Design Twitter/355.py create mode 100644 solutions/356. Line Reflection/356.cpp create mode 100644 solutions/356. Line Reflection/356.java create mode 100644 solutions/356. Line Reflection/356.py create mode 100644 solutions/357. Count Numbers with Unique Digits/357.cpp create mode 100644 solutions/357. Count Numbers with Unique Digits/357.java create mode 100644 solutions/357. Count Numbers with Unique Digits/357.py create mode 100644 solutions/358. Rearrange String k Distance Apart/358.cpp create mode 100644 solutions/358. Rearrange String k Distance Apart/358.java create mode 100644 solutions/358. Rearrange String k Distance Apart/358.py create mode 100644 solutions/359. Logger Rate Limiter/359-2.cpp create mode 100644 solutions/359. Logger Rate Limiter/359-2.java create mode 100644 solutions/359. Logger Rate Limiter/359-2.py create mode 100644 solutions/359. Logger Rate Limiter/359.cpp create mode 100644 solutions/359. Logger Rate Limiter/359.java create mode 100644 solutions/359. Logger Rate Limiter/359.py create mode 100644 solutions/36. Valid Sudoku/36.cpp create mode 100644 solutions/36. Valid Sudoku/36.java create mode 100644 solutions/36. Valid Sudoku/36.py create mode 100644 solutions/360. Sort Transformed Array/360.cpp create mode 100644 solutions/360. Sort Transformed Array/360.java create mode 100644 solutions/360. Sort Transformed Array/360.py create mode 100644 solutions/361. Bomb Enemy/361.cpp create mode 100644 solutions/361. Bomb Enemy/361.java create mode 100644 solutions/361. Bomb Enemy/361.py create mode 100644 solutions/362. Design Hit Counter/362.cpp create mode 100644 solutions/362. Design Hit Counter/362.java create mode 100644 solutions/362. Design Hit Counter/362.py create mode 100644 solutions/363. Max Sum of Rectangle No Larger Than K/363.cpp create mode 100644 solutions/363. Max Sum of Rectangle No Larger Than K/363.java create mode 100644 solutions/363. Max Sum of Rectangle No Larger Than K/363.py create mode 100644 solutions/364. Nested List Weight Sum II/364.cpp create mode 100644 solutions/364. Nested List Weight Sum II/364.java create mode 100644 solutions/364. Nested List Weight Sum II/364.py create mode 100644 solutions/365. Water and Jug Problem/365.cpp create mode 100644 solutions/365. Water and Jug Problem/365.java create mode 100644 solutions/365. Water and Jug Problem/365.py create mode 100644 solutions/366. Find Leaves of Binary Tree/366.cpp create mode 100644 solutions/366. Find Leaves of Binary Tree/366.java create mode 100644 solutions/366. Find Leaves of Binary Tree/366.py create mode 100644 solutions/367. Valid Perfect Square/367.cpp create mode 100644 solutions/367. Valid Perfect Square/367.java create mode 100644 solutions/367. Valid Perfect Square/367.py create mode 100644 solutions/368. Largest Divisible Subset/368.cpp create mode 100644 solutions/368. Largest Divisible Subset/368.java create mode 100644 solutions/368. Largest Divisible Subset/368.py create mode 100644 solutions/369. Plus One Linked List/369-2.cpp create mode 100644 solutions/369. Plus One Linked List/369-2.java create mode 100644 solutions/369. Plus One Linked List/369-2.py create mode 100644 solutions/369. Plus One Linked List/369.cpp create mode 100644 solutions/369. Plus One Linked List/369.java create mode 100644 solutions/369. Plus One Linked List/369.py create mode 100644 solutions/37. Sudoku Solver/37.cpp create mode 100644 solutions/37. Sudoku Solver/37.java create mode 100644 solutions/37. Sudoku Solver/37.py create mode 100644 solutions/370. Range Addition/370.cpp create mode 100644 solutions/370. Range Addition/370.java create mode 100644 solutions/370. Range Addition/370.py create mode 100644 solutions/371. Sum of Two Integers/371.cpp create mode 100644 solutions/371. Sum of Two Integers/371.java create mode 100644 solutions/371. Sum of Two Integers/371.py create mode 100644 solutions/372. Super Pow/372.cpp create mode 100644 solutions/372. Super Pow/372.java create mode 100644 solutions/372. Super Pow/372.py create mode 100644 solutions/373. Find K Pairs with Smallest Sums/373.cpp create mode 100644 solutions/373. Find K Pairs with Smallest Sums/373.java create mode 100644 solutions/373. Find K Pairs with Smallest Sums/373.py create mode 100644 solutions/374. Guess Number Higher or Lower/374.cpp create mode 100644 solutions/374. Guess Number Higher or Lower/374.java create mode 100644 solutions/374. Guess Number Higher or Lower/374.py create mode 100644 solutions/375. Guess Number Higher or Lower II/375-2.cpp create mode 100644 solutions/375. Guess Number Higher or Lower II/375-2.java create mode 100644 solutions/375. Guess Number Higher or Lower II/375-2.py create mode 100644 solutions/375. Guess Number Higher or Lower II/375.cpp create mode 100644 solutions/375. Guess Number Higher or Lower II/375.java create mode 100644 solutions/375. Guess Number Higher or Lower II/375.py create mode 100644 solutions/376. Wiggle Subsequence/376.cpp create mode 100644 solutions/376. Wiggle Subsequence/376.java create mode 100644 solutions/376. Wiggle Subsequence/376.py create mode 100644 solutions/377. Combination Sum IV/377.cpp create mode 100644 solutions/377. Combination Sum IV/377.java create mode 100644 solutions/377. Combination Sum IV/377.py create mode 100644 solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.cpp create mode 100644 solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.java create mode 100644 solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.py create mode 100644 solutions/378. Kth Smallest Element in a Sorted Matrix/378.cpp create mode 100644 solutions/378. Kth Smallest Element in a Sorted Matrix/378.java create mode 100644 solutions/378. Kth Smallest Element in a Sorted Matrix/378.py create mode 100644 solutions/379. Design Phone Directory/379.cpp create mode 100644 solutions/379. Design Phone Directory/379.java create mode 100644 solutions/379. Design Phone Directory/379.py create mode 100644 solutions/38. Count and Say/38.cpp create mode 100644 solutions/38. Count and Say/38.java create mode 100644 solutions/38. Count and Say/38.py create mode 100644 solutions/380. Insert Delete GetRandom O(1)/380.cpp create mode 100644 solutions/380. Insert Delete GetRandom O(1)/380.java create mode 100644 solutions/380. Insert Delete GetRandom O(1)/380.py create mode 100644 solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.cpp create mode 100644 solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.java create mode 100644 solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.py create mode 100644 solutions/382. Linked List Random Node/382.cpp create mode 100644 solutions/382. Linked List Random Node/382.java create mode 100644 solutions/382. Linked List Random Node/382.py create mode 100644 solutions/383. Ransom Note/383.cpp create mode 100644 solutions/383. Ransom Note/383.java create mode 100644 solutions/383. Ransom Note/383.py create mode 100644 solutions/384. Shuffle an Array/384.cpp create mode 100644 solutions/384. Shuffle an Array/384.java create mode 100644 solutions/384. Shuffle an Array/384.py create mode 100644 solutions/385. Mini Parser/385.cpp create mode 100644 solutions/385. Mini Parser/385.java create mode 100644 solutions/385. Mini Parser/385.py create mode 100644 solutions/386. Lexicographical Numbers/386.cpp create mode 100644 solutions/386. Lexicographical Numbers/386.java create mode 100644 solutions/386. Lexicographical Numbers/386.py create mode 100644 solutions/387. First Unique Character in a String/387.cpp create mode 100644 solutions/387. First Unique Character in a String/387.java create mode 100644 solutions/387. First Unique Character in a String/387.py create mode 100644 solutions/388. Longest Absolute File Path/388.cpp create mode 100644 solutions/388. Longest Absolute File Path/388.java create mode 100644 solutions/388. Longest Absolute File Path/388.py create mode 100644 solutions/389. Find the Difference/389-2.cpp create mode 100644 solutions/389. Find the Difference/389-2.java create mode 100644 solutions/389. Find the Difference/389-2.py create mode 100644 solutions/389. Find the Difference/389.cpp create mode 100644 solutions/389. Find the Difference/389.java create mode 100644 solutions/389. Find the Difference/389.py create mode 100644 solutions/39. Combination Sum/39.cpp create mode 100644 solutions/39. Combination Sum/39.java create mode 100644 solutions/39. Combination Sum/39.py create mode 100644 solutions/390. Elimination Game/390.cpp create mode 100644 solutions/390. Elimination Game/390.java create mode 100644 solutions/390. Elimination Game/390.py create mode 100644 solutions/391. Perfect Rectangle/391.cpp create mode 100644 solutions/391. Perfect Rectangle/391.java create mode 100644 solutions/391. Perfect Rectangle/391.py create mode 100644 solutions/392. Is Subsequence/392.cpp create mode 100644 solutions/392. Is Subsequence/392.java create mode 100644 solutions/392. Is Subsequence/392.py create mode 100644 solutions/393. UTF-8 Validation/393.cpp create mode 100644 solutions/393. UTF-8 Validation/393.java create mode 100644 solutions/393. UTF-8 Validation/393.py create mode 100644 solutions/394. Decode String/394-2.cpp create mode 100644 solutions/394. Decode String/394-2.java create mode 100644 solutions/394. Decode String/394-2.py create mode 100644 solutions/394. Decode String/394.cpp create mode 100644 solutions/394. Decode String/394.java create mode 100644 solutions/394. Decode String/394.py create mode 100644 solutions/395. Longest Substring with At Least K Repeating Characters/395.cpp create mode 100644 solutions/395. Longest Substring with At Least K Repeating Characters/395.java create mode 100644 solutions/395. Longest Substring with At Least K Repeating Characters/395.py create mode 100644 solutions/396. Rotate Function/396.cpp create mode 100644 solutions/396. Rotate Function/396.java create mode 100644 solutions/396. Rotate Function/396.py create mode 100644 solutions/397. Integer Replacement/397.cpp create mode 100644 solutions/397. Integer Replacement/397.java create mode 100644 solutions/397. Integer Replacement/397.py create mode 100644 solutions/398. Random Pick Index/398.cpp create mode 100644 solutions/398. Random Pick Index/398.java create mode 100644 solutions/398. Random Pick Index/398.py create mode 100644 solutions/399. Evaluate Division/399.cpp create mode 100644 solutions/399. Evaluate Division/399.java create mode 100644 solutions/399. Evaluate Division/399.py create mode 100644 solutions/4. Median of Two Sorted Arrays/4.cpp create mode 100644 solutions/4. Median of Two Sorted Arrays/4.java create mode 100644 solutions/4. Median of Two Sorted Arrays/4.py create mode 100644 solutions/40. Combination Sum II/40.cpp create mode 100644 solutions/40. Combination Sum II/40.java create mode 100644 solutions/40. Combination Sum II/40.py create mode 100644 solutions/400. Nth Digit/400.cpp create mode 100644 solutions/400. Nth Digit/400.java create mode 100644 solutions/400. Nth Digit/400.py create mode 100644 solutions/401. Binary Watch/401-2.cpp create mode 100644 solutions/401. Binary Watch/401-2.java create mode 100644 solutions/401. Binary Watch/401-2.py create mode 100644 solutions/401. Binary Watch/401.cpp create mode 100644 solutions/401. Binary Watch/401.java create mode 100644 solutions/401. Binary Watch/401.py create mode 100644 solutions/402. Remove K Digits/402.cpp create mode 100644 solutions/402. Remove K Digits/402.java create mode 100644 solutions/402. Remove K Digits/402.py create mode 100644 solutions/403. Frog Jump/403-2.cpp create mode 100644 solutions/403. Frog Jump/403-2.java create mode 100644 solutions/403. Frog Jump/403-2.py create mode 100644 solutions/403. Frog Jump/403.cpp create mode 100644 solutions/403. Frog Jump/403.java create mode 100644 solutions/403. Frog Jump/403.py create mode 100644 solutions/404. Sum of Left Leaves/404-2.cpp create mode 100644 solutions/404. Sum of Left Leaves/404-2.java create mode 100644 solutions/404. Sum of Left Leaves/404-2.py create mode 100644 solutions/404. Sum of Left Leaves/404.cpp create mode 100644 solutions/404. Sum of Left Leaves/404.java create mode 100644 solutions/404. Sum of Left Leaves/404.py create mode 100644 solutions/405. Convert a Number to Hexadecimal/405.cpp create mode 100644 solutions/405. Convert a Number to Hexadecimal/405.java create mode 100644 solutions/405. Convert a Number to Hexadecimal/405.py create mode 100644 solutions/406. Queue Reconstruction by Height/406.cpp create mode 100644 solutions/406. Queue Reconstruction by Height/406.java create mode 100644 solutions/406. Queue Reconstruction by Height/406.py create mode 100644 solutions/407. Trapping Rain Water II/407.cpp create mode 100644 solutions/407. Trapping Rain Water II/407.java create mode 100644 solutions/407. Trapping Rain Water II/407.py create mode 100644 solutions/408. Valid Word Abbreviation/408.cpp create mode 100644 solutions/408. Valid Word Abbreviation/408.java create mode 100644 solutions/408. Valid Word Abbreviation/408.py create mode 100644 solutions/409. Longest Palindrome/409.cpp create mode 100644 solutions/409. Longest Palindrome/409.java create mode 100644 solutions/409. Longest Palindrome/409.py create mode 100644 solutions/41. First Missing Positive/41.cpp create mode 100644 solutions/41. First Missing Positive/41.java create mode 100644 solutions/41. First Missing Positive/41.py create mode 100644 solutions/410. Split Array Largest Sum/410-2.cpp create mode 100644 solutions/410. Split Array Largest Sum/410-2.java create mode 100644 solutions/410. Split Array Largest Sum/410-2.py create mode 100644 solutions/410. Split Array Largest Sum/410-3.cpp create mode 100644 solutions/410. Split Array Largest Sum/410-3.java create mode 100644 solutions/410. Split Array Largest Sum/410-3.py create mode 100644 solutions/410. Split Array Largest Sum/410.cpp create mode 100644 solutions/410. Split Array Largest Sum/410.java create mode 100644 solutions/410. Split Array Largest Sum/410.py create mode 100644 solutions/411. Minimum Unique Word Abbreviation/411.cpp create mode 100644 solutions/411. Minimum Unique Word Abbreviation/411.java create mode 100644 solutions/411. Minimum Unique Word Abbreviation/411.py create mode 100644 solutions/412. Fizz Buzz/412.cpp create mode 100644 solutions/412. Fizz Buzz/412.java create mode 100644 solutions/412. Fizz Buzz/412.py create mode 100644 solutions/413. Arithmetic Slices/413-2.cpp create mode 100644 solutions/413. Arithmetic Slices/413-2.java create mode 100644 solutions/413. Arithmetic Slices/413-2.py create mode 100644 solutions/413. Arithmetic Slices/413.cpp create mode 100644 solutions/413. Arithmetic Slices/413.java create mode 100644 solutions/413. Arithmetic Slices/413.py create mode 100644 solutions/414. Third Maximum Number/414-2.cpp create mode 100644 solutions/414. Third Maximum Number/414-2.java create mode 100644 solutions/414. Third Maximum Number/414-2.py create mode 100644 solutions/414. Third Maximum Number/414.cpp create mode 100644 solutions/414. Third Maximum Number/414.java create mode 100644 solutions/414. Third Maximum Number/414.py create mode 100644 solutions/415. Add Strings/415.cpp create mode 100644 solutions/415. Add Strings/415.java create mode 100644 solutions/415. Add Strings/415.py create mode 100644 solutions/416. Partition Equal Subset Sum/416-2.cpp create mode 100644 solutions/416. Partition Equal Subset Sum/416-2.java create mode 100644 solutions/416. Partition Equal Subset Sum/416-2.py create mode 100644 solutions/416. Partition Equal Subset Sum/416.cpp create mode 100644 solutions/416. Partition Equal Subset Sum/416.java create mode 100644 solutions/416. Partition Equal Subset Sum/416.py create mode 100644 solutions/417. Pacific Atlantic Water Flow/417-2.cpp create mode 100644 solutions/417. Pacific Atlantic Water Flow/417-2.java create mode 100644 solutions/417. Pacific Atlantic Water Flow/417-2.py create mode 100644 solutions/417. Pacific Atlantic Water Flow/417.cpp create mode 100644 solutions/417. Pacific Atlantic Water Flow/417.java create mode 100644 solutions/417. Pacific Atlantic Water Flow/417.py create mode 100644 solutions/418. Sentence Screen Fitting/418.cpp create mode 100644 solutions/418. Sentence Screen Fitting/418.java create mode 100644 solutions/418. Sentence Screen Fitting/418.py create mode 100644 solutions/419. Battleships in a Board/419.cpp create mode 100644 solutions/419. Battleships in a Board/419.java create mode 100644 solutions/419. Battleships in a Board/419.py create mode 100644 solutions/42. Trapping Rain Water/42-2.cpp create mode 100644 solutions/42. Trapping Rain Water/42-2.java create mode 100644 solutions/42. Trapping Rain Water/42-2.py create mode 100644 solutions/42. Trapping Rain Water/42.cpp create mode 100644 solutions/42. Trapping Rain Water/42.java create mode 100644 solutions/42. Trapping Rain Water/42.py create mode 100644 solutions/420. Strong Password Checker/420.cpp create mode 100644 solutions/420. Strong Password Checker/420.java create mode 100644 solutions/420. Strong Password Checker/420.py create mode 100644 solutions/421. Maximum XOR of Two Numbers in an Array/421-2.cpp create mode 100644 solutions/421. Maximum XOR of Two Numbers in an Array/421-2.java create mode 100644 solutions/421. Maximum XOR of Two Numbers in an Array/421-2.py create mode 100644 solutions/421. Maximum XOR of Two Numbers in an Array/421.cpp create mode 100644 solutions/421. Maximum XOR of Two Numbers in an Array/421.java create mode 100644 solutions/421. Maximum XOR of Two Numbers in an Array/421.py create mode 100644 solutions/422. Valid Word Square/422.cpp create mode 100644 solutions/422. Valid Word Square/422.java create mode 100644 solutions/422. Valid Word Square/422.py create mode 100644 solutions/423. Reconstruct Original Digits from English/423.cpp create mode 100644 solutions/423. Reconstruct Original Digits from English/423.java create mode 100644 solutions/423. Reconstruct Original Digits from English/423.py create mode 100644 solutions/424. Longest Repeating Character Replacement/424-2.cpp create mode 100644 solutions/424. Longest Repeating Character Replacement/424-2.java create mode 100644 solutions/424. Longest Repeating Character Replacement/424-2.py create mode 100644 solutions/424. Longest Repeating Character Replacement/424.cpp create mode 100644 solutions/424. Longest Repeating Character Replacement/424.java create mode 100644 solutions/424. Longest Repeating Character Replacement/424.py create mode 100644 solutions/425. Word Squares/425.cpp create mode 100644 solutions/425. Word Squares/425.java create mode 100644 solutions/425. Word Squares/425.py create mode 100644 solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.cpp create mode 100644 solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.java create mode 100644 solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.py create mode 100644 solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.cpp create mode 100644 solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.java create mode 100644 solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.py create mode 100644 solutions/427. Construct Quad Tree/427.cpp create mode 100644 solutions/427. Construct Quad Tree/427.java create mode 100644 solutions/428. Serialize and Deserialize N-ary Tree/428.cpp create mode 100644 solutions/428. Serialize and Deserialize N-ary Tree/428.java create mode 100644 solutions/429. N-ary Tree Level Order Traversal/429.cpp create mode 100644 solutions/429. N-ary Tree Level Order Traversal/429.java create mode 100644 solutions/43. Multiply Strings/43.cpp create mode 100644 solutions/43. Multiply Strings/43.java create mode 100644 solutions/43. Multiply Strings/43.py create mode 100644 solutions/430. Flatten a Multilevel Doubly Linked List/430-2.cpp create mode 100644 solutions/430. Flatten a Multilevel Doubly Linked List/430-2.java create mode 100644 solutions/430. Flatten a Multilevel Doubly Linked List/430-2.py create mode 100644 solutions/430. Flatten a Multilevel Doubly Linked List/430.cpp create mode 100644 solutions/430. Flatten a Multilevel Doubly Linked List/430.java create mode 100644 solutions/430. Flatten a Multilevel Doubly Linked List/430.py create mode 100644 solutions/431. Encode N-ary Tree to Binary Tree/431-2.cpp create mode 100644 solutions/431. Encode N-ary Tree to Binary Tree/431-2.java create mode 100644 solutions/431. Encode N-ary Tree to Binary Tree/431-2.py create mode 100644 solutions/431. Encode N-ary Tree to Binary Tree/431.cpp create mode 100644 solutions/431. Encode N-ary Tree to Binary Tree/431.java create mode 100644 solutions/431. Encode N-ary Tree to Binary Tree/431.py create mode 100644 solutions/432. All O`one Data Structure/432.cpp create mode 100644 solutions/433. Minimum Genetic Mutation/433.cpp create mode 100644 solutions/433. Minimum Genetic Mutation/433.java create mode 100644 solutions/434. Number of Segments in a String/434.cpp create mode 100644 solutions/434. Number of Segments in a String/434.java create mode 100644 solutions/434. Number of Segments in a String/434.py create mode 100644 solutions/435. Non-overlapping Intervals/435.cpp create mode 100644 solutions/435. Non-overlapping Intervals/435.java create mode 100644 solutions/435. Non-overlapping Intervals/435.py create mode 100644 solutions/436. Find Right Interval/436.cpp create mode 100644 solutions/436. Find Right Interval/436.java create mode 100644 solutions/437. Path Sum III/437.cpp create mode 100644 solutions/437. Path Sum III/437.java create mode 100644 solutions/437. Path Sum III/437.py create mode 100644 solutions/438. Find All Anagrams in a String/438.cpp create mode 100644 solutions/438. Find All Anagrams in a String/438.java create mode 100644 solutions/438. Find All Anagrams in a String/438.py create mode 100644 solutions/439. Ternary Expression Parser/439.cpp create mode 100644 solutions/439. Ternary Expression Parser/439.java create mode 100644 solutions/439. Ternary Expression Parser/439.py create mode 100644 solutions/44. Wildcard Matching/44.cpp create mode 100644 solutions/44. Wildcard Matching/44.java create mode 100644 solutions/44. Wildcard Matching/44.py create mode 100644 solutions/440. K-th Smallest in Lexicographical Order/440.cpp create mode 100644 solutions/440. K-th Smallest in Lexicographical Order/440.java create mode 100644 solutions/441. Arranging Coins/441.cpp create mode 100644 solutions/441. Arranging Coins/441.java create mode 100644 solutions/441. Arranging Coins/441.py create mode 100644 solutions/442. Find All Duplicates in an Array/442.cpp create mode 100644 solutions/442. Find All Duplicates in an Array/442.java create mode 100644 solutions/442. Find All Duplicates in an Array/442.py create mode 100644 solutions/443. String Compression/443.cpp create mode 100644 solutions/443. String Compression/443.java create mode 100644 solutions/443. String Compression/443.py create mode 100644 solutions/444. Sequence Reconstruction/444.cpp create mode 100644 solutions/444. Sequence Reconstruction/444.java create mode 100644 solutions/444. Sequence Reconstruction/444.py create mode 100644 solutions/445. Add Two Numbers II/445.cpp create mode 100644 solutions/445. Add Two Numbers II/445.java create mode 100644 solutions/445. Add Two Numbers II/445.py create mode 100644 solutions/446. Arithmetic Slices II - Subsequence/446.cpp create mode 100644 solutions/446. Arithmetic Slices II - Subsequence/446.java create mode 100644 solutions/447. Number of Boomerangs/447.cpp create mode 100644 solutions/447. Number of Boomerangs/447.java create mode 100644 solutions/447. Number of Boomerangs/447.py create mode 100644 solutions/448. Find All Numbers Disappeared in an Array/448.cpp create mode 100644 solutions/448. Find All Numbers Disappeared in an Array/448.java create mode 100644 solutions/448. Find All Numbers Disappeared in an Array/448.py create mode 100644 solutions/449. Serialize and Deserialize BST/449.cpp create mode 100644 solutions/449. Serialize and Deserialize BST/449.java create mode 100644 solutions/45. Jump Game II/45.cpp create mode 100644 solutions/45. Jump Game II/45.java create mode 100644 solutions/45. Jump Game II/45.py create mode 100644 solutions/450. Delete Node in a BST/450.cpp create mode 100644 solutions/450. Delete Node in a BST/450.java create mode 100644 solutions/450. Delete Node in a BST/450.py create mode 100644 solutions/451. Sort Characters By Frequency/451.cpp create mode 100644 solutions/451. Sort Characters By Frequency/451.java create mode 100644 solutions/451. Sort Characters By Frequency/451.py create mode 100644 solutions/452. Minimum Number of Arrows to Burst Balloons/452.cpp create mode 100644 solutions/452. Minimum Number of Arrows to Burst Balloons/452.java create mode 100644 solutions/452. Minimum Number of Arrows to Burst Balloons/452.py create mode 100644 solutions/453. Minimum Moves to Equal Array Elements/453.cpp create mode 100644 solutions/453. Minimum Moves to Equal Array Elements/453.java create mode 100644 solutions/453. Minimum Moves to Equal Array Elements/453.py create mode 100644 solutions/454. 4Sum II/454.cpp create mode 100644 solutions/454. 4Sum II/454.java create mode 100644 solutions/454. 4Sum II/454.py create mode 100644 solutions/455. Assign Cookies/455.cpp create mode 100644 solutions/455. Assign Cookies/455.java create mode 100644 solutions/456. 132 Pattern/456.cpp create mode 100644 solutions/456. 132 Pattern/456.java create mode 100644 solutions/457. Circular Array Loop/457.cpp create mode 100644 solutions/457. Circular Array Loop/457.java create mode 100644 solutions/457. Circular Array Loop/457.py create mode 100644 solutions/458. Poor Pigs/458.cpp create mode 100644 solutions/458. Poor Pigs/458.java create mode 100644 solutions/458. Poor Pigs/458.py create mode 100644 solutions/459. Repeated Substring Pattern/459.cpp create mode 100644 solutions/459. Repeated Substring Pattern/459.java create mode 100644 solutions/459. Repeated Substring Pattern/459.py create mode 100644 solutions/46. Permutations/46.cpp create mode 100644 solutions/46. Permutations/46.java create mode 100644 solutions/46. Permutations/46.py create mode 100644 solutions/460. LFU Cache/460.cpp create mode 100644 solutions/460. LFU Cache/460.java create mode 100644 solutions/461. Hamming Distance/461.cpp create mode 100644 solutions/461. Hamming Distance/461.java create mode 100644 solutions/462. Minimum Moves to Equal Array Elements II/462.cpp create mode 100644 solutions/462. Minimum Moves to Equal Array Elements II/462.java create mode 100644 solutions/462. Minimum Moves to Equal Array Elements II/462.py create mode 100644 solutions/463. Island Perimeter/463.cpp create mode 100644 solutions/463. Island Perimeter/463.java create mode 100644 solutions/463. Island Perimeter/463.py create mode 100644 solutions/464. Can I Win/464.cpp create mode 100644 solutions/464. Can I Win/464.java create mode 100644 solutions/465. Optimal Account Balancing/465.cpp create mode 100644 solutions/465. Optimal Account Balancing/465.java create mode 100644 solutions/465. Optimal Account Balancing/465.py create mode 100644 solutions/466. Count The Repetitions/466.cpp create mode 100644 solutions/466. Count The Repetitions/466.java create mode 100644 solutions/467. Unique Substrings in Wraparound String/467.cpp create mode 100644 solutions/467. Unique Substrings in Wraparound String/467.java create mode 100644 solutions/468. Validate IP Address/468.cpp create mode 100644 solutions/468. Validate IP Address/468.java create mode 100644 solutions/469. Convex Polygon/469.cpp create mode 100644 solutions/469. Convex Polygon/469.java create mode 100644 solutions/469. Convex Polygon/469.py create mode 100644 solutions/47. Permutations II/47.cpp create mode 100644 solutions/47. Permutations II/47.java create mode 100644 solutions/47. Permutations II/47.py create mode 100644 solutions/470. Implement Rand10() Using Rand7()/470.cpp create mode 100644 solutions/470. Implement Rand10() Using Rand7()/470.java create mode 100644 solutions/471. Encode String with Shortest Length/471-2.cpp create mode 100644 solutions/471. Encode String with Shortest Length/471-2.java create mode 100644 solutions/471. Encode String with Shortest Length/471.cpp create mode 100644 solutions/471. Encode String with Shortest Length/471.java create mode 100644 solutions/472. Concatenated Words/472.cpp create mode 100644 solutions/472. Concatenated Words/472.java create mode 100644 solutions/472. Concatenated Words/472.py create mode 100644 solutions/473. Matchsticks to Square/473.cpp create mode 100644 solutions/473. Matchsticks to Square/473.java create mode 100644 solutions/473. Matchsticks to Square/473.py create mode 100644 solutions/474. Ones and Zeroes/474.cpp create mode 100644 solutions/474. Ones and Zeroes/474.java create mode 100644 solutions/474. Ones and Zeroes/474.py create mode 100644 solutions/475. Heaters/475.cpp create mode 100644 solutions/475. Heaters/475.java create mode 100644 solutions/476. Number Complement/476.cpp create mode 100644 solutions/476. Number Complement/476.java create mode 100644 solutions/477. Total Hamming Distance/477.cpp create mode 100644 solutions/477. Total Hamming Distance/477.java create mode 100644 solutions/477. Total Hamming Distance/477.py create mode 100644 solutions/478. Generate Random Point in a Circle/478.cpp create mode 100644 solutions/478. Generate Random Point in a Circle/478.java create mode 100644 solutions/478. Generate Random Point in a Circle/478.py create mode 100644 solutions/479. Largest Palindrome Product/479.cpp create mode 100644 solutions/479. Largest Palindrome Product/479.java create mode 100644 solutions/479. Largest Palindrome Product/479.py create mode 100644 solutions/48. Rotate Image/48-2.cpp create mode 100644 solutions/48. Rotate Image/48-2.java create mode 100644 solutions/48. Rotate Image/48-2.py create mode 100644 solutions/48. Rotate Image/48.cpp create mode 100644 solutions/48. Rotate Image/48.java create mode 100644 solutions/48. Rotate Image/48.py create mode 100644 solutions/480. Sliding Window Median/480.cpp create mode 100644 solutions/481. Magical String/481.cpp create mode 100644 solutions/482. License Key Formatting/482.cpp create mode 100644 solutions/482. License Key Formatting/482.java create mode 100644 solutions/482. License Key Formatting/482.py create mode 100644 solutions/483. Smallest Good Base/483.cpp create mode 100644 solutions/483. Smallest Good Base/483.java create mode 100644 solutions/483. Smallest Good Base/483.py create mode 100644 solutions/484. Find Permutation/484-2.cpp create mode 100644 solutions/484. Find Permutation/484-2.java create mode 100644 solutions/484. Find Permutation/484-2.py create mode 100644 solutions/484. Find Permutation/484.cpp create mode 100644 solutions/484. Find Permutation/484.java create mode 100644 solutions/484. Find Permutation/484.py create mode 100644 solutions/485. Max Consecutive Ones/485.cpp create mode 100644 solutions/485. Max Consecutive Ones/485.java create mode 100644 solutions/485. Max Consecutive Ones/485.py create mode 100644 solutions/486. Predict the Winner/486-2.cpp create mode 100644 solutions/486. Predict the Winner/486-2.java create mode 100644 solutions/486. Predict the Winner/486.cpp create mode 100644 solutions/486. Predict the Winner/486.java create mode 100644 solutions/487. Max Consecutive Ones II/487-2.cpp create mode 100644 solutions/487. Max Consecutive Ones II/487-2.java create mode 100644 solutions/487. Max Consecutive Ones II/487-2.py create mode 100644 solutions/487. Max Consecutive Ones II/487-3.cpp create mode 100644 solutions/487. Max Consecutive Ones II/487-3.java create mode 100644 solutions/487. Max Consecutive Ones II/487-3.py create mode 100644 solutions/487. Max Consecutive Ones II/487.cpp create mode 100644 solutions/487. Max Consecutive Ones II/487.java create mode 100644 solutions/487. Max Consecutive Ones II/487.py create mode 100644 solutions/488. Zuma Game/488.cpp create mode 100644 solutions/488. Zuma Game/488.java create mode 100644 solutions/488. Zuma Game/488.py create mode 100644 solutions/489. Robot Room Cleaner/489.cpp create mode 100644 solutions/489. Robot Room Cleaner/489.java create mode 100644 solutions/49. Group Anagrams/49.cpp create mode 100644 solutions/49. Group Anagrams/49.java create mode 100644 solutions/49. Group Anagrams/49.py create mode 100644 solutions/490. The Maze/490-2.cpp create mode 100644 solutions/490. The Maze/490-2.java create mode 100644 solutions/490. The Maze/490-2.py create mode 100644 solutions/490. The Maze/490.cpp create mode 100644 solutions/490. The Maze/490.java create mode 100644 solutions/490. The Maze/490.py create mode 100644 solutions/491. Increasing Subsequences/491.cpp create mode 100644 solutions/491. Increasing Subsequences/491.java create mode 100644 solutions/491. Increasing Subsequences/491.py create mode 100644 solutions/492. Construct the Rectangle/492.cpp create mode 100644 solutions/492. Construct the Rectangle/492.java create mode 100644 solutions/493. Reverse Pairs/493-2.cpp create mode 100644 solutions/493. Reverse Pairs/493-3.cpp create mode 100644 solutions/493. Reverse Pairs/493-4.cpp create mode 100644 solutions/493. Reverse Pairs/493.cpp create mode 100644 solutions/494. Target Sum/494-2.cpp create mode 100644 solutions/494. Target Sum/494-2.java create mode 100644 solutions/494. Target Sum/494-2.py create mode 100644 solutions/494. Target Sum/494.cpp create mode 100644 solutions/494. Target Sum/494.java create mode 100644 solutions/494. Target Sum/494.py create mode 100644 solutions/495. Teemo Attacking/495.cpp create mode 100644 solutions/495. Teemo Attacking/495.java create mode 100644 solutions/495. Teemo Attacking/495.py create mode 100644 solutions/496. Next Greater Element I/496.cpp create mode 100644 solutions/496. Next Greater Element I/496.java create mode 100644 solutions/496. Next Greater Element I/496.py create mode 100644 solutions/497. Random Point in Non-overlapping Rectangles/497.cpp create mode 100644 solutions/497. Random Point in Non-overlapping Rectangles/497.java create mode 100644 solutions/497. Random Point in Non-overlapping Rectangles/497.py create mode 100644 solutions/498. Diagonal Traverse/498.cpp create mode 100644 solutions/498. Diagonal Traverse/498.java create mode 100644 solutions/499. The Maze III/499.cpp create mode 100644 solutions/499. The Maze III/499.java create mode 100644 solutions/499. The Maze III/499.py create mode 100644 solutions/5. Longest Palindromic Substring/5-2.cpp create mode 100644 solutions/5. Longest Palindromic Substring/5-2.java create mode 100644 solutions/5. Longest Palindromic Substring/5-2.py create mode 100644 solutions/5. Longest Palindromic Substring/5.cpp create mode 100644 solutions/5. Longest Palindromic Substring/5.java create mode 100644 solutions/5. Longest Palindromic Substring/5.py create mode 100644 solutions/50. Pow(x, n)/50.cpp create mode 100644 solutions/50. Pow(x, n)/50.java create mode 100644 solutions/50. Pow(x, n)/50.py create mode 100644 solutions/500. Keyboard Row/500.cpp create mode 100644 solutions/500. Keyboard Row/500.java create mode 100644 solutions/500. Keyboard Row/500.py create mode 100644 solutions/501. Find Mode in Binary Search Tree/501.cpp create mode 100644 solutions/501. Find Mode in Binary Search Tree/501.java create mode 100644 solutions/501. Find Mode in Binary Search Tree/501.py create mode 100644 solutions/502. IPO/502.cpp create mode 100644 solutions/502. IPO/502.java create mode 100644 solutions/503. Next Greater Element II/503.cpp create mode 100644 solutions/503. Next Greater Element II/503.java create mode 100644 solutions/503. Next Greater Element II/503.py create mode 100644 solutions/504. Base 7/504.cpp create mode 100644 solutions/504. Base 7/504.java create mode 100644 solutions/505. The Maze II/505-2.cpp create mode 100644 solutions/505. The Maze II/505-2.java create mode 100644 solutions/505. The Maze II/505.cpp create mode 100644 solutions/505. The Maze II/505.java create mode 100644 solutions/506. Relative Ranks/506.cpp create mode 100644 solutions/506. Relative Ranks/506.java create mode 100644 solutions/507. Perfect Number/507.cpp create mode 100644 solutions/507. Perfect Number/507.java create mode 100644 solutions/507. Perfect Number/507.py create mode 100644 solutions/508. Most Frequent Subtree Sum/508.cpp create mode 100644 solutions/508. Most Frequent Subtree Sum/508.java create mode 100644 solutions/508. Most Frequent Subtree Sum/508.py create mode 100644 solutions/509. Fibonacci Number/509.cpp create mode 100644 solutions/509. Fibonacci Number/509.java create mode 100644 solutions/509. Fibonacci Number/509.py create mode 100644 solutions/51. N-Queens/51.cpp create mode 100644 solutions/51. N-Queens/51.java create mode 100644 solutions/51. N-Queens/51.py create mode 100644 solutions/510. Inorder Successor in BST II/510.cpp create mode 100644 solutions/510. Inorder Successor in BST II/510.java create mode 100644 solutions/511. Game Play Analysis I/511.sql create mode 100644 solutions/512. Game Play Analysis II/512.sql create mode 100644 solutions/513. Find Bottom Left Tree Value/513-2.cpp create mode 100644 solutions/513. Find Bottom Left Tree Value/513-2.java create mode 100644 solutions/513. Find Bottom Left Tree Value/513-2.py create mode 100644 solutions/513. Find Bottom Left Tree Value/513.cpp create mode 100644 solutions/513. Find Bottom Left Tree Value/513.java create mode 100644 solutions/513. Find Bottom Left Tree Value/513.py create mode 100644 solutions/514. Freedom Trail/514.cpp create mode 100644 solutions/514. Freedom Trail/514.java create mode 100644 solutions/514. Freedom Trail/514.py create mode 100644 solutions/515. Find Largest Value in Each Tree Row/515-2.cpp create mode 100644 solutions/515. Find Largest Value in Each Tree Row/515-2.java create mode 100644 solutions/515. Find Largest Value in Each Tree Row/515-2.py create mode 100644 solutions/515. Find Largest Value in Each Tree Row/515.cpp create mode 100644 solutions/515. Find Largest Value in Each Tree Row/515.java create mode 100644 solutions/515. Find Largest Value in Each Tree Row/515.py create mode 100644 solutions/516. Longest Palindromic Subsequence/516-2.cpp create mode 100644 solutions/516. Longest Palindromic Subsequence/516-2.java create mode 100644 solutions/516. Longest Palindromic Subsequence/516-2.py create mode 100644 solutions/516. Longest Palindromic Subsequence/516.cpp create mode 100644 solutions/516. Longest Palindromic Subsequence/516.java create mode 100644 solutions/516. Longest Palindromic Subsequence/516.py create mode 100644 solutions/517. Super Washing Machines/517.cpp create mode 100644 solutions/517. Super Washing Machines/517.java create mode 100644 solutions/517. Super Washing Machines/517.py create mode 100644 solutions/518. Coin Change 2/518.cpp create mode 100644 solutions/518. Coin Change 2/518.java create mode 100644 solutions/518. Coin Change 2/518.py create mode 100644 solutions/519. Random Flip Matrix/519.cpp create mode 100644 solutions/519. Random Flip Matrix/519.java create mode 100644 solutions/52. N-Queens II/52.cpp create mode 100644 solutions/52. N-Queens II/52.java create mode 100644 solutions/52. N-Queens II/52.py create mode 100644 solutions/520. Detect Capital/520.cpp create mode 100644 solutions/520. Detect Capital/520.java create mode 100644 solutions/520. Detect Capital/520.py create mode 100644 solutions/521. Longest Uncommon Subsequence I/521.cpp create mode 100644 solutions/521. Longest Uncommon Subsequence I/521.java create mode 100644 solutions/521. Longest Uncommon Subsequence I/521.py create mode 100644 solutions/522. Longest Uncommon Subsequence II/522.cpp create mode 100644 solutions/522. Longest Uncommon Subsequence II/522.java create mode 100644 solutions/522. Longest Uncommon Subsequence II/522.py create mode 100644 solutions/523. Continuous Subarray Sum/523.cpp create mode 100644 solutions/523. Continuous Subarray Sum/523.java create mode 100644 solutions/523. Continuous Subarray Sum/523.py create mode 100644 solutions/524. Longest Word in Dictionary through Deleting/524.cpp create mode 100644 solutions/524. Longest Word in Dictionary through Deleting/524.java create mode 100644 solutions/524. Longest Word in Dictionary through Deleting/524.py create mode 100644 solutions/525. Contiguous Array/525.cpp create mode 100644 solutions/525. Contiguous Array/525.java create mode 100644 solutions/525. Contiguous Array/525.py create mode 100644 solutions/526. Beautiful Arrangement/526.cpp create mode 100644 solutions/526. Beautiful Arrangement/526.java create mode 100644 solutions/527. Word Abbreviation/527-2.cpp create mode 100644 solutions/527. Word Abbreviation/527-2.java create mode 100644 solutions/527. Word Abbreviation/527-2.py create mode 100644 solutions/527. Word Abbreviation/527-3.cpp create mode 100644 solutions/527. Word Abbreviation/527-3.java create mode 100644 solutions/527. Word Abbreviation/527-3.py create mode 100644 solutions/527. Word Abbreviation/527.cpp create mode 100644 solutions/527. Word Abbreviation/527.java create mode 100644 solutions/527. Word Abbreviation/527.py create mode 100644 solutions/528. Random Pick with Weight/528-2.cpp create mode 100644 solutions/528. Random Pick with Weight/528-2.py create mode 100644 solutions/528. Random Pick with Weight/528.cpp create mode 100644 solutions/528. Random Pick with Weight/528.java create mode 100644 solutions/528. Random Pick with Weight/528.py create mode 100644 solutions/529. Minesweeper/529.cpp create mode 100644 solutions/529. Minesweeper/529.java create mode 100644 solutions/529. Minesweeper/529.py create mode 100644 solutions/53. Maximum Subarray/53-2.cpp create mode 100644 solutions/53. Maximum Subarray/53-2.java create mode 100644 solutions/53. Maximum Subarray/53-2.py create mode 100644 solutions/53. Maximum Subarray/53-3.cpp create mode 100644 solutions/53. Maximum Subarray/53-3.java create mode 100644 solutions/53. Maximum Subarray/53-3.py create mode 100644 solutions/53. Maximum Subarray/53.cpp create mode 100644 solutions/53. Maximum Subarray/53.java create mode 100644 solutions/53. Maximum Subarray/53.py create mode 100644 solutions/530. Minimum Absolute Difference in BST/530.cpp create mode 100644 solutions/530. Minimum Absolute Difference in BST/530.java create mode 100644 solutions/531. Lonely Pixel I/531.cpp create mode 100644 solutions/531. Lonely Pixel I/531.java create mode 100644 solutions/531. Lonely Pixel I/531.py create mode 100644 solutions/532. K-diff Pairs in an Array/532.cpp create mode 100644 solutions/532. K-diff Pairs in an Array/532.java create mode 100644 solutions/532. K-diff Pairs in an Array/532.py create mode 100644 solutions/533. Lonely Pixel II/533.cpp create mode 100644 solutions/533. Lonely Pixel II/533.java create mode 100644 solutions/533. Lonely Pixel II/533.py create mode 100644 solutions/534. Game Play Analysis III/534.sql create mode 100644 solutions/535. Encode and Decode TinyURL/535.cpp create mode 100644 solutions/535. Encode and Decode TinyURL/535.java create mode 100644 solutions/535. Encode and Decode TinyURL/535.py create mode 100644 solutions/536. Construct Binary Tree from String/536-2.cpp create mode 100644 solutions/536. Construct Binary Tree from String/536-2.java create mode 100644 solutions/536. Construct Binary Tree from String/536.cpp create mode 100644 solutions/536. Construct Binary Tree from String/536.java create mode 100644 solutions/537. Complex Number Multiplication/537.cpp create mode 100644 solutions/537. Complex Number Multiplication/537.java create mode 100644 solutions/537. Complex Number Multiplication/537.py create mode 100644 solutions/538. Convert BST to Greater Tree/538.cpp create mode 100644 solutions/538. Convert BST to Greater Tree/538.java create mode 100644 solutions/538. Convert BST to Greater Tree/538.py create mode 100644 solutions/539. Minimum Time Difference/539.cpp create mode 100644 solutions/539. Minimum Time Difference/539.java create mode 100644 solutions/539. Minimum Time Difference/539.py create mode 100644 solutions/54. Spiral Matrix/54.cpp create mode 100644 solutions/54. Spiral Matrix/54.java create mode 100644 solutions/54. Spiral Matrix/54.py create mode 100644 solutions/540. Single Element in a Sorted Array/540.cpp create mode 100644 solutions/540. Single Element in a Sorted Array/540.java create mode 100644 solutions/540. Single Element in a Sorted Array/540.py create mode 100644 solutions/541. Reverse String II/541.cpp create mode 100644 solutions/541. Reverse String II/541.java create mode 100644 solutions/541. Reverse String II/541.py create mode 100644 solutions/542. 01 Matrix/542-2.cpp create mode 100644 solutions/542. 01 Matrix/542-2.java create mode 100644 solutions/542. 01 Matrix/542-2.py create mode 100644 solutions/542. 01 Matrix/542.cpp create mode 100644 solutions/542. 01 Matrix/542.java create mode 100644 solutions/542. 01 Matrix/542.py create mode 100644 solutions/543. Diameter of Binary Tree/543.cpp create mode 100644 solutions/543. Diameter of Binary Tree/543.java create mode 100644 solutions/543. Diameter of Binary Tree/543.py create mode 100644 solutions/544. Output Contest Matches/544-2.cpp create mode 100644 solutions/544. Output Contest Matches/544-2.java create mode 100644 solutions/544. Output Contest Matches/544-2.py create mode 100644 solutions/544. Output Contest Matches/544.cpp create mode 100644 solutions/544. Output Contest Matches/544.java create mode 100644 solutions/544. Output Contest Matches/544.py create mode 100644 solutions/545. Boundary of Binary Tree/545.cpp create mode 100644 solutions/545. Boundary of Binary Tree/545.java create mode 100644 solutions/545. Boundary of Binary Tree/545.py create mode 100644 solutions/546. Remove Boxes/546.cpp create mode 100644 solutions/546. Remove Boxes/546.java create mode 100644 solutions/546. Remove Boxes/546.py create mode 100644 solutions/547. Friend Circles/547.cpp create mode 100644 solutions/547. Friend Circles/547.java create mode 100644 solutions/547. Friend Circles/547.py create mode 100644 solutions/548. Split Array with Equal Sum/548.cpp create mode 100644 solutions/548. Split Array with Equal Sum/548.java create mode 100644 solutions/549. Binary Tree Longest Consecutive Sequence II/549.cpp create mode 100644 solutions/549. Binary Tree Longest Consecutive Sequence II/549.java create mode 100644 solutions/55. Jump Game/55.cpp create mode 100644 solutions/55. Jump Game/55.java create mode 100644 solutions/55. Jump Game/55.py create mode 100644 solutions/550. Game Play Analysis IV/550.sql create mode 100644 solutions/551. Student Attendance Record I/551.cpp create mode 100644 solutions/551. Student Attendance Record I/551.java create mode 100644 solutions/551. Student Attendance Record I/551.py create mode 100644 solutions/552. Student Attendance Record II/552.cpp create mode 100644 solutions/552. Student Attendance Record II/552.java create mode 100644 solutions/552. Student Attendance Record II/552.py create mode 100644 solutions/553. Optimal Division/553.cpp create mode 100644 solutions/553. Optimal Division/553.java create mode 100644 solutions/553. Optimal Division/553.py create mode 100644 solutions/554. Brick Wall/554.cpp create mode 100644 solutions/554. Brick Wall/554.java create mode 100644 solutions/554. Brick Wall/554.py create mode 100644 solutions/555. Split Concatenated Strings/555.cpp create mode 100644 solutions/555. Split Concatenated Strings/555.java create mode 100644 solutions/555. Split Concatenated Strings/555.py create mode 100644 solutions/556. Next Greater Element III/556.cpp create mode 100644 solutions/556. Next Greater Element III/556.java create mode 100644 solutions/556. Next Greater Element III/556.py create mode 100644 solutions/557. Reverse Words in a String III/557.cpp create mode 100644 solutions/557. Reverse Words in a String III/557.java create mode 100644 solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.cpp create mode 100644 solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.java create mode 100644 solutions/559. Maximum Depth of N-ary Tree/559.cpp create mode 100644 solutions/559. Maximum Depth of N-ary Tree/559.java create mode 100644 solutions/559. Maximum Depth of N-ary Tree/559.py create mode 100644 solutions/56. Merge Intervals/56.cpp create mode 100644 solutions/56. Merge Intervals/56.java create mode 100644 solutions/56. Merge Intervals/56.py create mode 100644 solutions/560. Subarray Sum Equals K/560.cpp create mode 100644 solutions/560. Subarray Sum Equals K/560.java create mode 100644 solutions/560. Subarray Sum Equals K/560.py create mode 100644 solutions/561. Array Partition I/561.cpp create mode 100644 solutions/561. Array Partition I/561.java create mode 100644 solutions/561. Array Partition I/561.py create mode 100644 solutions/562. Longest Line of Consecutive One in Matrix/562.cpp create mode 100644 solutions/562. Longest Line of Consecutive One in Matrix/562.java create mode 100644 solutions/562. Longest Line of Consecutive One in Matrix/562.py create mode 100644 solutions/563. Binary Tree Tilt/563.cpp create mode 100644 solutions/563. Binary Tree Tilt/563.java create mode 100644 solutions/563. Binary Tree Tilt/563.py create mode 100644 solutions/564. Find the Closest Palindrome/564.cpp create mode 100644 solutions/564. Find the Closest Palindrome/564.java create mode 100644 solutions/564. Find the Closest Palindrome/564.py create mode 100644 solutions/565. Array Nesting/565.cpp create mode 100644 solutions/565. Array Nesting/565.java create mode 100644 solutions/565. Array Nesting/565.py create mode 100644 solutions/566. Reshape the Matrix/566.cpp create mode 100644 solutions/566. Reshape the Matrix/566.java create mode 100644 solutions/566. Reshape the Matrix/566.py create mode 100644 solutions/567. Permutation in String/567-2.cpp create mode 100644 solutions/567. Permutation in String/567-2.java create mode 100644 solutions/567. Permutation in String/567-2.py create mode 100644 solutions/567. Permutation in String/567.cpp create mode 100644 solutions/567. Permutation in String/567.java create mode 100644 solutions/568. Maximum Vacation Days/568-2.cpp create mode 100644 solutions/568. Maximum Vacation Days/568-2.java create mode 100644 solutions/568. Maximum Vacation Days/568-3.cpp create mode 100644 solutions/568. Maximum Vacation Days/568-3.java create mode 100644 solutions/568. Maximum Vacation Days/568.cpp create mode 100644 solutions/568. Maximum Vacation Days/568.java create mode 100644 solutions/569. Median Employee Salary/569.sql create mode 100644 solutions/57. Insert Interval/57.cpp create mode 100644 solutions/57. Insert Interval/57.java create mode 100644 solutions/57. Insert Interval/57.py create mode 100644 solutions/570. Managers with at Least 5 Direct Reports/570.sql create mode 100644 solutions/571. Find Median Given Frequency of Numbers/571.sql create mode 100644 solutions/572. Subtree of Another Tree/572.cpp create mode 100644 solutions/572. Subtree of Another Tree/572.java create mode 100644 solutions/573. Squirrel Simulation/573.cpp create mode 100644 solutions/573. Squirrel Simulation/573.java create mode 100644 solutions/573. Squirrel Simulation/573.py create mode 100644 solutions/574. Winning Candidate/574.sql create mode 100644 solutions/575. Distribute Candies/575.cpp create mode 100644 solutions/575. Distribute Candies/575.java create mode 100644 solutions/575. Distribute Candies/575.py create mode 100644 solutions/576. Out of Boundary Paths/576-2.cpp create mode 100644 solutions/576. Out of Boundary Paths/576-2.java create mode 100644 solutions/576. Out of Boundary Paths/576-2.py create mode 100644 solutions/576. Out of Boundary Paths/576.cpp create mode 100644 solutions/576. Out of Boundary Paths/576.java create mode 100644 solutions/576. Out of Boundary Paths/576.py create mode 100644 solutions/577. Employee Bonus/577.sql create mode 100644 solutions/578. Get Highest Answer Rate Question/578.sql create mode 100644 solutions/579. Find Cumulative Salary of an Employee/579.sql create mode 100644 solutions/58. Length of Last Word/58.cpp create mode 100644 solutions/58. Length of Last Word/58.java create mode 100644 solutions/58. Length of Last Word/58.py create mode 100644 solutions/580. Count Student Number in Departments/580.sql create mode 100644 solutions/581. Shortest Unsorted Continuous Subarray/581.cpp create mode 100644 solutions/581. Shortest Unsorted Continuous Subarray/581.java create mode 100644 solutions/581. Shortest Unsorted Continuous Subarray/581.py create mode 100644 solutions/582. Kill Process/582.cpp create mode 100644 solutions/582. Kill Process/582.java create mode 100644 solutions/582. Kill Process/582.py create mode 100644 solutions/583. Delete Operation for Two Strings/583.cpp create mode 100644 solutions/583. Delete Operation for Two Strings/583.java create mode 100644 solutions/583. Delete Operation for Two Strings/583.py create mode 100644 solutions/584. Find Customer Referee/584.sql create mode 100644 solutions/585. Investments in 2016/585.sql create mode 100644 solutions/586. Customer Placing the Largest Number of Orders/586.sql create mode 100644 solutions/587. Erect the Fence/587.cpp create mode 100644 solutions/587. Erect the Fence/587.java create mode 100644 solutions/587. Erect the Fence/587.py create mode 100644 solutions/588. Design In-Memory File System/588.cpp create mode 100644 solutions/589. N-ary Tree Preorder Traversal/589.cpp create mode 100644 solutions/589. N-ary Tree Preorder Traversal/589.java create mode 100644 solutions/59. Spiral Matrix II/59.cpp create mode 100644 solutions/59. Spiral Matrix II/59.java create mode 100644 solutions/59. Spiral Matrix II/59.py create mode 100644 solutions/590. N-ary Tree Postorder Traversal/590.cpp create mode 100644 solutions/590. N-ary Tree Postorder Traversal/590.java create mode 100644 solutions/591. Tag Validator/591.cpp create mode 100644 solutions/591. Tag Validator/591.java create mode 100644 solutions/591. Tag Validator/591.py create mode 100644 solutions/592. Fraction Addition and Subtraction/592.cpp create mode 100644 solutions/592. Fraction Addition and Subtraction/592.java create mode 100644 solutions/592. Fraction Addition and Subtraction/592.py create mode 100644 solutions/593. Valid Square/593.cpp create mode 100644 solutions/593. Valid Square/593.java create mode 100644 solutions/593. Valid Square/593.py create mode 100644 solutions/594. Longest Harmonious Subsequence/594.cpp create mode 100644 solutions/594. Longest Harmonious Subsequence/594.java create mode 100644 solutions/594. Longest Harmonious Subsequence/594.py create mode 100644 solutions/595. Big Countries/595.sql create mode 100644 solutions/596. Classes More Than 5 Students/596.sql create mode 100644 solutions/597. Friend Requests I: Overall Acceptance Rate/597.sql create mode 100644 solutions/598. Range Addition II/598.cpp create mode 100644 solutions/598. Range Addition II/598.java create mode 100644 solutions/598. Range Addition II/598.py create mode 100644 solutions/599. Minimum Index Sum of Two Lists/599.cpp create mode 100644 solutions/599. Minimum Index Sum of Two Lists/599.java create mode 100644 solutions/599. Minimum Index Sum of Two Lists/599.py create mode 100644 solutions/6. ZigZag Conversion/6.cpp create mode 100644 solutions/6. ZigZag Conversion/6.java create mode 100644 solutions/6. ZigZag Conversion/6.py create mode 100644 solutions/60. Permutation Sequence/60.cpp create mode 100644 solutions/60. Permutation Sequence/60.java create mode 100644 solutions/60. Permutation Sequence/60.py create mode 100644 solutions/600. Non-negative Integers without Consecutive Ones/600.cpp create mode 100644 solutions/600. Non-negative Integers without Consecutive Ones/600.java create mode 100644 solutions/601. Human Traffic of Stadium/601-2.sql create mode 100644 solutions/601. Human Traffic of Stadium/601.sql create mode 100644 solutions/602. Friend Requests II: Who Has the Most Friends/602.sql create mode 100644 solutions/603. Consecutive Available Seats/603.sql create mode 100644 solutions/604. Design Compressed String Iterator/604-2.cpp create mode 100644 solutions/604. Design Compressed String Iterator/604-2.java create mode 100644 solutions/604. Design Compressed String Iterator/604-2.py create mode 100644 solutions/604. Design Compressed String Iterator/604.cpp create mode 100644 solutions/604. Design Compressed String Iterator/604.java create mode 100644 solutions/604. Design Compressed String Iterator/604.py create mode 100644 solutions/605. Can Place Flowers/605.cpp create mode 100644 solutions/605. Can Place Flowers/605.java create mode 100644 solutions/605. Can Place Flowers/605.py create mode 100644 solutions/606. Construct String from Binary Tree/606.cpp create mode 100644 solutions/606. Construct String from Binary Tree/606.java create mode 100644 solutions/606. Construct String from Binary Tree/606.py create mode 100644 solutions/607. Sales Person/607.sql create mode 100644 solutions/608. Tree Node/608.sql create mode 100644 solutions/609. Find Duplicate File in System/609.cpp create mode 100644 solutions/609. Find Duplicate File in System/609.java create mode 100644 solutions/609. Find Duplicate File in System/609.py create mode 100644 solutions/61. Rotate List/61.cpp create mode 100644 solutions/61. Rotate List/61.java create mode 100644 solutions/61. Rotate List/61.py create mode 100644 solutions/610. Triangle Judgement/610.sql create mode 100644 solutions/611. Valid Triangle Number/611.cpp create mode 100644 solutions/611. Valid Triangle Number/611.java create mode 100644 solutions/611. Valid Triangle Number/611.py create mode 100644 solutions/612. Shortest Distance in a Plane/612.sql create mode 100644 solutions/613. Shortest Distance in a Line/613.sql create mode 100644 solutions/614. Second Degree Follower/614.sql create mode 100644 solutions/615. Average Salary: Departments VS Company/615.sql create mode 100644 solutions/616. Add Bold Tag in String/616-2.cpp create mode 100644 solutions/616. Add Bold Tag in String/616-2.java create mode 100644 solutions/616. Add Bold Tag in String/616-2.py create mode 100644 solutions/616. Add Bold Tag in String/616-3.cpp create mode 100644 solutions/616. Add Bold Tag in String/616.cpp create mode 100644 solutions/616. Add Bold Tag in String/616.java create mode 100644 solutions/616. Add Bold Tag in String/616.py create mode 100644 solutions/617. Merge Two Binary Trees/617.cpp create mode 100644 solutions/617. Merge Two Binary Trees/617.java create mode 100644 solutions/617. Merge Two Binary Trees/617.py create mode 100644 solutions/618. Students Report By Geography/618.sql create mode 100644 solutions/619. Biggest Single Number/619.sql create mode 100644 solutions/62. Unique Paths/62-2.cpp create mode 100644 solutions/62. Unique Paths/62-2.java create mode 100644 solutions/62. Unique Paths/62-2.py create mode 100644 solutions/62. Unique Paths/62.cpp create mode 100644 solutions/62. Unique Paths/62.java create mode 100644 solutions/62. Unique Paths/62.py create mode 100644 solutions/620. Not Boring Movies/620.sql create mode 100644 solutions/621. Task Scheduler/621.cpp create mode 100644 solutions/621. Task Scheduler/621.java create mode 100644 solutions/621. Task Scheduler/621.py create mode 100644 solutions/622. Design Circular Queue/622.cpp create mode 100644 solutions/622. Design Circular Queue/622.java create mode 100644 solutions/623. Add One Row to Tree/623.cpp create mode 100644 solutions/623. Add One Row to Tree/623.java create mode 100644 solutions/624. Maximum Distance in Arrays/624-2.py create mode 100644 solutions/624. Maximum Distance in Arrays/624.cpp create mode 100644 solutions/624. Maximum Distance in Arrays/624.java create mode 100644 solutions/624. Maximum Distance in Arrays/624.py create mode 100644 solutions/625. Minimum Factorization/625.cpp create mode 100644 solutions/625. Minimum Factorization/625.java create mode 100644 solutions/625. Minimum Factorization/625.py create mode 100644 solutions/626. Exchange Seats/626.sql create mode 100644 solutions/627. Swap Salary/627.sql create mode 100644 solutions/628. Maximum Product of Three Numbers/628-2.cpp create mode 100644 solutions/628. Maximum Product of Three Numbers/628-2.java create mode 100644 solutions/628. Maximum Product of Three Numbers/628-2.py create mode 100644 solutions/628. Maximum Product of Three Numbers/628.cpp create mode 100644 solutions/628. Maximum Product of Three Numbers/628.java create mode 100644 solutions/628. Maximum Product of Three Numbers/628.py create mode 100644 solutions/629. K Inverse Pairs Array/629.cpp create mode 100644 solutions/629. K Inverse Pairs Array/629.java create mode 100644 solutions/629. K Inverse Pairs Array/629.py create mode 100644 solutions/63. Unique Paths II/63-2.cpp create mode 100644 solutions/63. Unique Paths II/63-2.java create mode 100644 solutions/63. Unique Paths II/63-2.py create mode 100644 solutions/63. Unique Paths II/63.cpp create mode 100644 solutions/63. Unique Paths II/63.java create mode 100644 solutions/63. Unique Paths II/63.py create mode 100644 solutions/630. Course Schedule III/630.cpp create mode 100644 solutions/630. Course Schedule III/630.java create mode 100644 solutions/630. Course Schedule III/630.py create mode 100644 solutions/631. Design Excel Sum Formula/631.cpp create mode 100644 solutions/631. Design Excel Sum Formula/631.java create mode 100644 solutions/631. Design Excel Sum Formula/631.py create mode 100644 solutions/632. Smallest Range Covering Elements from K Lists/632.cpp create mode 100644 solutions/632. Smallest Range Covering Elements from K Lists/632.java create mode 100644 solutions/632. Smallest Range Covering Elements from K Lists/632.py create mode 100644 solutions/633. Sum of Square Numbers/633.cpp create mode 100644 solutions/633. Sum of Square Numbers/633.java create mode 100644 solutions/633. Sum of Square Numbers/633.py create mode 100644 solutions/634. Find the Derangement of An Array/634-2.cpp create mode 100644 solutions/634. Find the Derangement of An Array/634-2.java create mode 100644 solutions/634. Find the Derangement of An Array/634-2.py create mode 100644 solutions/634. Find the Derangement of An Array/634.cpp create mode 100644 solutions/634. Find the Derangement of An Array/634.java create mode 100644 solutions/634. Find the Derangement of An Array/634.py create mode 100644 solutions/635. Design Log Storage System/635.cpp create mode 100644 solutions/635. Design Log Storage System/635.java create mode 100644 solutions/635. Design Log Storage System/635.py create mode 100644 solutions/636. Exclusive Time of Functions/636.cpp create mode 100644 solutions/636. Exclusive Time of Functions/636.java create mode 100644 solutions/637. Average of Levels in Binary Tree/637.cpp create mode 100644 solutions/637. Average of Levels in Binary Tree/637.java create mode 100644 solutions/638. Shopping Offers/638.cpp create mode 100644 solutions/638. Shopping Offers/638.java create mode 100644 solutions/638. Shopping Offers/638.py create mode 100644 solutions/639. Decode Ways II/639-2.cpp create mode 100644 solutions/639. Decode Ways II/639-2.java create mode 100644 solutions/639. Decode Ways II/639.cpp create mode 100644 solutions/639. Decode Ways II/639.java create mode 100644 solutions/64. Minimum Path Sum/64.cpp create mode 100644 solutions/64. Minimum Path Sum/64.java create mode 100644 solutions/64. Minimum Path Sum/64.py create mode 100644 solutions/640. Solve the Equation/640.cpp create mode 100644 solutions/640. Solve the Equation/640.java create mode 100644 solutions/640. Solve the Equation/640.py create mode 100644 solutions/641. Design Circular Deque/641.cpp create mode 100644 solutions/641. Design Circular Deque/641.java create mode 100644 solutions/642. Design Search Autocomplete System/642.java create mode 100644 solutions/642. Design Search Autocomplete System/642.py create mode 100644 solutions/643. Maximum Average Subarray I/643.cpp create mode 100644 solutions/643. Maximum Average Subarray I/643.java create mode 100644 solutions/643. Maximum Average Subarray I/643.py create mode 100644 solutions/644. Maximum Average Subarray II/644.cpp create mode 100644 solutions/644. Maximum Average Subarray II/644.java create mode 100644 solutions/644. Maximum Average Subarray II/644.py create mode 100644 solutions/645. Set Mismatch/645.cpp create mode 100644 solutions/645. Set Mismatch/645.java create mode 100644 solutions/645. Set Mismatch/645.py create mode 100644 solutions/646. Maximum Length of Pair Chain/646.cpp create mode 100644 solutions/646. Maximum Length of Pair Chain/646.java create mode 100644 solutions/646. Maximum Length of Pair Chain/646.py create mode 100644 solutions/647. Palindromic Substrings/647.cpp create mode 100644 solutions/647. Palindromic Substrings/647.java create mode 100644 solutions/647. Palindromic Substrings/647.py create mode 100644 solutions/648. Replace Words/648.cpp create mode 100644 solutions/648. Replace Words/648.java create mode 100644 solutions/648. Replace Words/648.py create mode 100644 solutions/649. Dota2 Senate/649.cpp create mode 100644 solutions/65. Valid Number/65.cpp create mode 100644 solutions/65. Valid Number/65.java create mode 100644 solutions/65. Valid Number/65.py create mode 100644 solutions/650. 2 Keys Keyboard/650.cpp create mode 100644 solutions/650. 2 Keys Keyboard/650.java create mode 100644 solutions/650. 2 Keys Keyboard/650.py create mode 100644 solutions/651. 4 Keys Keyboard/651-2.cpp create mode 100644 solutions/651. 4 Keys Keyboard/651-2.java create mode 100644 solutions/651. 4 Keys Keyboard/651.cpp create mode 100644 solutions/651. 4 Keys Keyboard/651.java create mode 100644 solutions/652. Find Duplicate Subtrees/652.cpp create mode 100644 solutions/652. Find Duplicate Subtrees/652.java create mode 100644 solutions/652. Find Duplicate Subtrees/652.py create mode 100644 solutions/653. Two Sum IV - Input is a BST/653.cpp create mode 100644 solutions/653. Two Sum IV - Input is a BST/653.java create mode 100644 solutions/653. Two Sum IV - Input is a BST/653.py create mode 100644 solutions/654. Maximum Binary Tree/654.cpp create mode 100644 solutions/654. Maximum Binary Tree/654.java create mode 100644 solutions/654. Maximum Binary Tree/654.py create mode 100644 solutions/655. Print Binary Tree/655.cpp create mode 100644 solutions/655. Print Binary Tree/655.java create mode 100644 solutions/655. Print Binary Tree/655.py create mode 100644 solutions/656. Coin Path/656-2.cpp create mode 100644 solutions/656. Coin Path/656-2.java create mode 100644 solutions/656. Coin Path/656-2.py create mode 100644 solutions/656. Coin Path/656.cpp create mode 100644 solutions/656. Coin Path/656.java create mode 100644 solutions/656. Coin Path/656.py create mode 100644 solutions/657. Robot Return to Origin/657.cpp create mode 100644 solutions/657. Robot Return to Origin/657.java create mode 100644 solutions/657. Robot Return to Origin/657.py create mode 100644 solutions/658. Find K Closest Elements/658.cpp create mode 100644 solutions/658. Find K Closest Elements/658.java create mode 100644 solutions/658. Find K Closest Elements/658.py create mode 100644 solutions/659. Split Array into Consecutive Subsequences/659.cpp create mode 100644 solutions/659. Split Array into Consecutive Subsequences/659.java create mode 100644 solutions/66. Plus One/66.cpp create mode 100644 solutions/66. Plus One/66.java create mode 100644 solutions/66. Plus One/66.py create mode 100644 solutions/660. Remove 9/660.cpp create mode 100644 solutions/660. Remove 9/660.java create mode 100644 solutions/660. Remove 9/660.py create mode 100644 solutions/661. Image Smoother/661.cpp create mode 100644 solutions/661. Image Smoother/661.java create mode 100644 solutions/661. Image Smoother/661.py create mode 100644 solutions/662. Maximum Width of Binary Tree/662-2.cpp create mode 100644 solutions/662. Maximum Width of Binary Tree/662.cpp create mode 100644 solutions/662. Maximum Width of Binary Tree/662.java create mode 100644 solutions/663. Equal Tree Partition/663.cpp create mode 100644 solutions/663. Equal Tree Partition/663.java create mode 100644 solutions/663. Equal Tree Partition/663.py create mode 100644 solutions/664. Strange Printer/664-2.cpp create mode 100644 solutions/664. Strange Printer/664-2.java create mode 100644 solutions/664. Strange Printer/664.cpp create mode 100644 solutions/664. Strange Printer/664.java create mode 100644 solutions/665. Non-decreasing Array/665.cpp create mode 100644 solutions/665. Non-decreasing Array/665.java create mode 100644 solutions/665. Non-decreasing Array/665.py create mode 100644 solutions/666. Path Sum IV/666.cpp create mode 100644 solutions/666. Path Sum IV/666.java create mode 100644 solutions/666. Path Sum IV/666.py create mode 100644 solutions/667. Beautiful Arrangement II/667.cpp create mode 100644 solutions/667. Beautiful Arrangement II/667.java create mode 100644 solutions/667. Beautiful Arrangement II/667.py create mode 100644 solutions/668. Kth Smallest Number in Multiplication Table/668.cpp create mode 100644 solutions/668. Kth Smallest Number in Multiplication Table/668.java create mode 100644 solutions/669. Trim a Binary Search Tree/669.cpp create mode 100644 solutions/669. Trim a Binary Search Tree/669.java create mode 100644 solutions/67. Add Binary/67.cpp create mode 100644 solutions/67. Add Binary/67.java create mode 100644 solutions/67. Add Binary/67.py create mode 100644 solutions/670. Maximum Swap/670.cpp create mode 100644 solutions/670. Maximum Swap/670.java create mode 100644 solutions/670. Maximum Swap/670.py create mode 100644 solutions/671. Second Minimum Node In a Binary Tree/671.cpp create mode 100644 solutions/671. Second Minimum Node In a Binary Tree/671.java create mode 100644 solutions/672. Bulb Switcher II/672.cpp create mode 100644 solutions/672. Bulb Switcher II/672.java create mode 100644 solutions/672. Bulb Switcher II/672.py create mode 100644 solutions/673. Number of Longest Increasing Subsequence/673.cpp create mode 100644 solutions/673. Number of Longest Increasing Subsequence/673.java create mode 100644 solutions/673. Number of Longest Increasing Subsequence/673.py create mode 100644 solutions/674. Longest Continuous Increasing Subsequence/674.cpp create mode 100644 solutions/674. Longest Continuous Increasing Subsequence/674.java create mode 100644 solutions/674. Longest Continuous Increasing Subsequence/674.py create mode 100644 solutions/675. Cut Off Trees for Golf Event/675.cpp create mode 100644 solutions/675. Cut Off Trees for Golf Event/675.java create mode 100644 solutions/676. Implement Magic Dictionary/676-2.cpp create mode 100644 solutions/676. Implement Magic Dictionary/676-2.java create mode 100644 solutions/676. Implement Magic Dictionary/676-2.py create mode 100644 solutions/676. Implement Magic Dictionary/676.cpp create mode 100644 solutions/676. Implement Magic Dictionary/676.java create mode 100644 solutions/676. Implement Magic Dictionary/676.py create mode 100644 solutions/677. Map Sum Pairs/677.cpp create mode 100644 solutions/677. Map Sum Pairs/677.java create mode 100644 solutions/677. Map Sum Pairs/677.py create mode 100644 solutions/678. Valid Parenthesis String/678.cpp create mode 100644 solutions/678. Valid Parenthesis String/678.java create mode 100644 solutions/678. Valid Parenthesis String/678.py create mode 100644 solutions/679. 24 Game/679.cpp create mode 100644 solutions/679. 24 Game/679.java create mode 100644 solutions/679. 24 Game/679.py create mode 100644 solutions/68. Text Justification/68.cpp create mode 100644 solutions/68. Text Justification/68.java create mode 100644 solutions/68. Text Justification/68.py create mode 100644 solutions/680. Valid Palindrome II/680.cpp create mode 100644 solutions/680. Valid Palindrome II/680.java create mode 100644 solutions/680. Valid Palindrome II/680.py create mode 100644 solutions/681. Next Closest Time/681.cpp create mode 100644 solutions/681. Next Closest Time/681.java create mode 100644 solutions/681. Next Closest Time/681.py create mode 100644 solutions/682. Baseball Game/682.cpp create mode 100644 solutions/682. Baseball Game/682.java create mode 100644 solutions/682. Baseball Game/682.py create mode 100644 solutions/683. K Empty Slots/683.cpp create mode 100644 solutions/683. K Empty Slots/683.java create mode 100644 solutions/683. K Empty Slots/683.py create mode 100644 solutions/684. Redundant Connection/684.cpp create mode 100644 solutions/684. Redundant Connection/684.java create mode 100644 solutions/684. Redundant Connection/684.py create mode 100644 solutions/685. Redundant Connection II/685.cpp create mode 100644 solutions/685. Redundant Connection II/685.java create mode 100644 solutions/685. Redundant Connection II/685.py create mode 100644 solutions/686. Repeated String Match/686.cpp create mode 100644 solutions/686. Repeated String Match/686.java create mode 100644 solutions/686. Repeated String Match/686.py create mode 100644 solutions/687. Longest Univalue Path/687.cpp create mode 100644 solutions/687. Longest Univalue Path/687.java create mode 100644 solutions/687. Longest Univalue Path/687.py create mode 100644 solutions/688. Knight Probability in Chessboard/688.cpp create mode 100644 solutions/688. Knight Probability in Chessboard/688.java create mode 100644 solutions/688. Knight Probability in Chessboard/688.py create mode 100644 solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.cpp create mode 100644 solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.java create mode 100644 solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.py create mode 100644 solutions/69. Sqrt(x)/69.cpp create mode 100644 solutions/69. Sqrt(x)/69.java create mode 100644 solutions/69. Sqrt(x)/69.py create mode 100644 solutions/690. Employee Importance/690.cpp create mode 100644 solutions/690. Employee Importance/690.java create mode 100644 solutions/690. Employee Importance/690.py create mode 100644 solutions/691. Stickers to Spell Word/691.cpp create mode 100644 solutions/691. Stickers to Spell Word/691.java create mode 100644 solutions/691. Stickers to Spell Word/691.py create mode 100644 solutions/692. Top K Frequent Words/692-2.cpp create mode 100644 solutions/692. Top K Frequent Words/692-2.java create mode 100644 solutions/692. Top K Frequent Words/692-2.py create mode 100644 solutions/692. Top K Frequent Words/692.cpp create mode 100644 solutions/692. Top K Frequent Words/692.java create mode 100644 solutions/692. Top K Frequent Words/692.py create mode 100644 solutions/693. Binary Number with Alternating Bits/693.cpp create mode 100644 solutions/693. Binary Number with Alternating Bits/693.java create mode 100644 solutions/693. Binary Number with Alternating Bits/693.py create mode 100644 solutions/694. Number of Distinct Islands/694.cpp create mode 100644 solutions/694. Number of Distinct Islands/694.java create mode 100644 solutions/694. Number of Distinct Islands/694.py create mode 100644 solutions/695. Max Area of Island/695.cpp create mode 100644 solutions/695. Max Area of Island/695.java create mode 100644 solutions/695. Max Area of Island/695.py create mode 100644 solutions/696. Count Binary Substrings/696.cpp create mode 100644 solutions/696. Count Binary Substrings/696.java create mode 100644 solutions/696. Count Binary Substrings/696.py create mode 100644 solutions/697. Degree of an Array/697.cpp create mode 100644 solutions/697. Degree of an Array/697.java create mode 100644 solutions/697. Degree of an Array/697.py create mode 100644 solutions/698. Partition to K Equal Sum Subsets/698.cpp create mode 100644 solutions/698. Partition to K Equal Sum Subsets/698.java create mode 100644 solutions/698. Partition to K Equal Sum Subsets/698.py create mode 100644 solutions/699. Falling Squares/699.cpp create mode 100644 solutions/7. Reverse Integer/7.cpp create mode 100644 solutions/7. Reverse Integer/7.java create mode 100644 solutions/7. Reverse Integer/7.py create mode 100644 solutions/70. Climbing Stairs/70-2.cpp create mode 100644 solutions/70. Climbing Stairs/70-2.java create mode 100644 solutions/70. Climbing Stairs/70-2.py create mode 100644 solutions/70. Climbing Stairs/70.cpp create mode 100644 solutions/70. Climbing Stairs/70.java create mode 100644 solutions/70. Climbing Stairs/70.py create mode 100644 solutions/700. Search in a Binary Search Tree/700.cpp create mode 100644 solutions/700. Search in a Binary Search Tree/700.java create mode 100644 solutions/700. Search in a Binary Search Tree/700.py create mode 100644 solutions/701. Insert into a Binary Search Tree/701.cpp create mode 100644 solutions/701. Insert into a Binary Search Tree/701.java create mode 100644 solutions/701. Insert into a Binary Search Tree/701.py create mode 100644 solutions/702. Search in a Sorted Array of Unknown Size/702.cpp create mode 100644 solutions/702. Search in a Sorted Array of Unknown Size/702.java create mode 100644 solutions/702. Search in a Sorted Array of Unknown Size/702.py create mode 100644 solutions/703. Kth Largest Element in a Stream/703.cpp create mode 100644 solutions/703. Kth Largest Element in a Stream/703.java create mode 100644 solutions/704. Binary Search/704.cpp create mode 100644 solutions/704. Binary Search/704.java create mode 100644 solutions/704. Binary Search/704.py create mode 100644 solutions/705. Design HashSet/705.cpp create mode 100644 solutions/705. Design HashSet/705.java create mode 100644 solutions/705. Design HashSet/705.py create mode 100644 solutions/706. Design HashMap/706.cpp create mode 100644 solutions/706. Design HashMap/706.java create mode 100644 solutions/707. Design Linked List/707.cpp create mode 100644 solutions/707. Design Linked List/707.java create mode 100644 solutions/707. Design Linked List/707.py create mode 100644 solutions/708. Insert into a Sorted Circular Linked List/708.cpp create mode 100644 solutions/708. Insert into a Sorted Circular Linked List/708.java create mode 100644 solutions/709. To Lower Case/709.cpp create mode 100644 solutions/709. To Lower Case/709.java create mode 100644 solutions/709. To Lower Case/709.py create mode 100644 solutions/71. Simplify Path/71.cpp create mode 100644 solutions/71. Simplify Path/71.java create mode 100644 solutions/71. Simplify Path/71.py create mode 100644 solutions/710. Random Pick with Blacklist/710.cpp create mode 100644 solutions/710. Random Pick with Blacklist/710.java create mode 100644 solutions/710. Random Pick with Blacklist/710.py create mode 100644 solutions/711. Number of Distinct Islands II/711.cpp create mode 100644 solutions/711. Number of Distinct Islands II/711.java create mode 100644 solutions/711. Number of Distinct Islands II/711.py create mode 100644 solutions/712. Minimum ASCII Delete Sum for Two Strings/712.cpp create mode 100644 solutions/712. Minimum ASCII Delete Sum for Two Strings/712.java create mode 100644 solutions/713. Subarray Product Less Than K/713.cpp create mode 100644 solutions/713. Subarray Product Less Than K/713.java create mode 100644 solutions/713. Subarray Product Less Than K/713.py create mode 100644 solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.cpp create mode 100644 solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.java create mode 100644 solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.py create mode 100644 solutions/715. Range Module/715-2.cpp create mode 100644 solutions/715. Range Module/715-2.java create mode 100644 solutions/715. Range Module/715-3.py create mode 100644 solutions/715. Range Module/715.cpp create mode 100644 solutions/716. Max Stack/716.cpp create mode 100644 solutions/717. 1-bit and 2-bit Characters/717.cpp create mode 100644 solutions/717. 1-bit and 2-bit Characters/717.java create mode 100644 solutions/717. 1-bit and 2-bit Characters/717.py create mode 100644 solutions/718. Maximum Length of Repeated Subarray/718-2.cpp create mode 100644 solutions/718. Maximum Length of Repeated Subarray/718-2.java create mode 100644 solutions/718. Maximum Length of Repeated Subarray/718-2.py create mode 100644 solutions/718. Maximum Length of Repeated Subarray/718.cpp create mode 100644 solutions/718. Maximum Length of Repeated Subarray/718.java create mode 100644 solutions/718. Maximum Length of Repeated Subarray/718.py create mode 100644 solutions/719. Find K-th Smallest Pair Distance/719.cpp create mode 100644 solutions/719. Find K-th Smallest Pair Distance/719.java create mode 100644 solutions/719. Find K-th Smallest Pair Distance/719.py create mode 100644 solutions/72. Edit Distance/72.cpp create mode 100644 solutions/72. Edit Distance/72.java create mode 100644 solutions/72. Edit Distance/72.py create mode 100644 solutions/720. Longest Word in Dictionary/720.cpp create mode 100644 solutions/720. Longest Word in Dictionary/720.java create mode 100644 solutions/720. Longest Word in Dictionary/720.py create mode 100644 solutions/721. Accounts Merge/721.cpp create mode 100644 solutions/721. Accounts Merge/721.java create mode 100644 solutions/722. Remove Comments/722.cpp create mode 100644 solutions/722. Remove Comments/722.java create mode 100644 solutions/722. Remove Comments/722.py create mode 100644 solutions/723. Candy Crush/723.cpp create mode 100644 solutions/723. Candy Crush/723.java create mode 100644 solutions/724. Find Pivot Index/724.cpp create mode 100644 solutions/724. Find Pivot Index/724.java create mode 100644 solutions/724. Find Pivot Index/724.py create mode 100644 solutions/725. Split Linked List in Parts/725.cpp create mode 100644 solutions/725. Split Linked List in Parts/725.java create mode 100644 solutions/725. Split Linked List in Parts/725.py create mode 100644 solutions/726. Number of Atoms/726.cpp create mode 100644 solutions/726. Number of Atoms/726.java create mode 100644 solutions/726. Number of Atoms/726.py create mode 100644 solutions/727. Minimum Window Subsequence/727.cpp create mode 100644 solutions/727. Minimum Window Subsequence/727.java create mode 100644 solutions/728. Self Dividing Numbers/728.cpp create mode 100644 solutions/728. Self Dividing Numbers/728.java create mode 100644 solutions/728. Self Dividing Numbers/728.py create mode 100644 solutions/729. My Calendar I/729-2.cpp create mode 100644 solutions/729. My Calendar I/729-2.java create mode 100644 solutions/729. My Calendar I/729-3.py create mode 100644 solutions/729. My Calendar I/729.cpp create mode 100644 solutions/729. My Calendar I/729.java create mode 100644 solutions/729. My Calendar I/729.py create mode 100644 solutions/73. Set Matrix Zeroes/73.cpp create mode 100644 solutions/73. Set Matrix Zeroes/73.java create mode 100644 solutions/73. Set Matrix Zeroes/73.py create mode 100644 solutions/730. Count Different Palindromic Subsequences/730.cpp create mode 100644 solutions/730. Count Different Palindromic Subsequences/730.java create mode 100644 solutions/730. Count Different Palindromic Subsequences/730.py create mode 100644 solutions/731. My Calendar II/731-2.cpp create mode 100644 solutions/731. My Calendar II/731-2.java create mode 100644 solutions/731. My Calendar II/731.cpp create mode 100644 solutions/731. My Calendar II/731.java create mode 100644 solutions/732. My Calendar III/732.cpp create mode 100644 solutions/732. My Calendar III/732.java create mode 100644 solutions/732. My Calendar III/732.py create mode 100644 solutions/733. Flood Fill/733.cpp create mode 100644 solutions/733. Flood Fill/733.java create mode 100644 solutions/733. Flood Fill/733.py create mode 100644 solutions/734. Sentence Similarity/734.cpp create mode 100644 solutions/734. Sentence Similarity/734.java create mode 100644 solutions/734. Sentence Similarity/734.py create mode 100644 solutions/735. Asteroid Collision/735.cpp create mode 100644 solutions/735. Asteroid Collision/735.java create mode 100644 solutions/735. Asteroid Collision/735.py create mode 100644 solutions/736. Parse Lisp Expression/736.cpp create mode 100644 solutions/736. Parse Lisp Expression/736.java create mode 100644 solutions/736. Parse Lisp Expression/736.py create mode 100644 solutions/737. Sentence Similarity II/737.cpp create mode 100644 solutions/737. Sentence Similarity II/737.java create mode 100644 solutions/737. Sentence Similarity II/737.py create mode 100644 solutions/738. Monotone Increasing Digits/738.cpp create mode 100644 solutions/738. Monotone Increasing Digits/738.java create mode 100644 solutions/739. Daily Temperatures/739.cpp create mode 100644 solutions/739. Daily Temperatures/739.java create mode 100644 solutions/739. Daily Temperatures/739.py create mode 100644 solutions/74. Search a 2D Matrix/74.cpp create mode 100644 solutions/74. Search a 2D Matrix/74.java create mode 100644 solutions/74. Search a 2D Matrix/74.py create mode 100644 solutions/740. Delete and Earn/740.cpp create mode 100644 solutions/740. Delete and Earn/740.java create mode 100644 solutions/741. Cherry Pickup/741-2.cpp create mode 100644 solutions/741. Cherry Pickup/741-2.java create mode 100644 solutions/741. Cherry Pickup/741.cpp create mode 100644 solutions/741. Cherry Pickup/741.java create mode 100644 solutions/742. Closest Leaf in a Binary Tree/742.cpp create mode 100644 solutions/742. Closest Leaf in a Binary Tree/742.java create mode 100644 solutions/743. Network Delay Time/743.cpp create mode 100644 solutions/743. Network Delay Time/743.java create mode 100644 solutions/743. Network Delay Time/743.py create mode 100644 solutions/744. Find Smallest Letter Greater Than Target/744.cpp create mode 100644 solutions/744. Find Smallest Letter Greater Than Target/744.java create mode 100644 solutions/744. Find Smallest Letter Greater Than Target/744.py create mode 100644 solutions/745. Prefix and Suffix Search/745-2.cpp create mode 100644 solutions/745. Prefix and Suffix Search/745.cpp create mode 100644 solutions/745. Prefix and Suffix Search/745.java create mode 100644 solutions/746. Min Cost Climbing Stairs/746.cpp create mode 100644 solutions/746. Min Cost Climbing Stairs/746.java create mode 100644 solutions/746. Min Cost Climbing Stairs/746.py create mode 100644 solutions/747. Largest Number At Least Twice of Others/747.cpp create mode 100644 solutions/747. Largest Number At Least Twice of Others/747.java create mode 100644 solutions/747. Largest Number At Least Twice of Others/747.py create mode 100644 solutions/748. Shortest Completing Word/748.cpp create mode 100644 solutions/748. Shortest Completing Word/748.java create mode 100644 solutions/748. Shortest Completing Word/748.py create mode 100644 solutions/749. Contain Virus/749.cpp create mode 100644 solutions/749. Contain Virus/749.java create mode 100644 solutions/75. Sort Colors/75-2.cpp create mode 100644 solutions/75. Sort Colors/75-2.java create mode 100644 solutions/75. Sort Colors/75-2.py create mode 100644 solutions/75. Sort Colors/75.cpp create mode 100644 solutions/75. Sort Colors/75.java create mode 100644 solutions/75. Sort Colors/75.py create mode 100644 solutions/750. Number Of Corner Rectangles/750.cpp create mode 100644 solutions/750. Number Of Corner Rectangles/750.java create mode 100644 solutions/751. IP to CIDR/751.cpp create mode 100644 solutions/751. IP to CIDR/751.java create mode 100644 solutions/751. IP to CIDR/751.py create mode 100644 solutions/752. Open the Lock/752.cpp create mode 100644 solutions/752. Open the Lock/752.java create mode 100644 solutions/753. Cracking the Safe/753.cpp create mode 100644 solutions/753. Cracking the Safe/753.java create mode 100644 solutions/753. Cracking the Safe/753.py create mode 100644 solutions/754. Reach a Number/754.cpp create mode 100644 solutions/754. Reach a Number/754.java create mode 100644 solutions/754. Reach a Number/754.py create mode 100644 solutions/755. Pour Water/755.cpp create mode 100644 solutions/755. Pour Water/755.java create mode 100644 solutions/755. Pour Water/755.py create mode 100644 solutions/756. Pyramid Transition Matrix/756.cpp create mode 100644 solutions/756. Pyramid Transition Matrix/756.java create mode 100644 solutions/756. Pyramid Transition Matrix/756.py create mode 100644 solutions/757. Set Intersection Size At Least Two/757.cpp create mode 100644 solutions/757. Set Intersection Size At Least Two/757.java create mode 100644 solutions/758. Bold Words in String/758-2.cpp create mode 100644 solutions/758. Bold Words in String/758-2.java create mode 100644 solutions/758. Bold Words in String/758-2.py create mode 100644 solutions/758. Bold Words in String/758-3.cpp create mode 100644 solutions/758. Bold Words in String/758.cpp create mode 100644 solutions/758. Bold Words in String/758.java create mode 100644 solutions/758. Bold Words in String/758.py create mode 100644 solutions/759. Employee Free Time/759.cpp create mode 100644 solutions/759. Employee Free Time/759.java create mode 100644 solutions/759. Employee Free Time/759.py create mode 100644 solutions/76. Minimum Window Substring/76.cpp create mode 100644 solutions/76. Minimum Window Substring/76.java create mode 100644 solutions/76. Minimum Window Substring/76.py create mode 100644 solutions/760. Find Anagram Mappings/760.cpp create mode 100644 solutions/760. Find Anagram Mappings/760.java create mode 100644 solutions/760. Find Anagram Mappings/760.py create mode 100644 solutions/761. Special Binary String/761.cpp create mode 100644 solutions/761. Special Binary String/761.java create mode 100644 solutions/761. Special Binary String/761.py create mode 100644 solutions/762. Prime Number of Set Bits in Binary Representation/762.cpp create mode 100644 solutions/762. Prime Number of Set Bits in Binary Representation/762.java create mode 100644 solutions/763. Partition Labels/763.cpp create mode 100644 solutions/763. Partition Labels/763.java create mode 100644 solutions/763. Partition Labels/763.py create mode 100644 solutions/764. Largest Plus Sign/764.cpp create mode 100644 solutions/764. Largest Plus Sign/764.java create mode 100644 solutions/765. Couples Holding Hands/765.cpp create mode 100644 solutions/765. Couples Holding Hands/765.java create mode 100644 solutions/766. Toeplitz Matrix/766-2.cpp create mode 100644 solutions/766. Toeplitz Matrix/766-2.java create mode 100644 solutions/766. Toeplitz Matrix/766.cpp create mode 100644 solutions/766. Toeplitz Matrix/766.java create mode 100644 solutions/766. Toeplitz Matrix/766.py create mode 100644 solutions/767. Reorganize String/767-2.cpp create mode 100644 solutions/767. Reorganize String/767-2.java create mode 100644 solutions/767. Reorganize String/767-2.py create mode 100644 solutions/767. Reorganize String/767.cpp create mode 100644 solutions/767. Reorganize String/767.java create mode 100644 solutions/767. Reorganize String/767.py create mode 100644 solutions/768. Max Chunks To Make Sorted II/768.cpp create mode 100644 solutions/768. Max Chunks To Make Sorted II/768.java create mode 100644 solutions/768. Max Chunks To Make Sorted II/768.py create mode 100644 solutions/769. Max Chunks To Make Sorted/769.cpp create mode 100644 solutions/769. Max Chunks To Make Sorted/769.java create mode 100644 solutions/769. Max Chunks To Make Sorted/769.py create mode 100644 solutions/77. Combinations/77.cpp create mode 100644 solutions/77. Combinations/77.java create mode 100644 solutions/77. Combinations/77.py create mode 100644 solutions/770. Basic Calculator IV/770.cpp create mode 100644 solutions/770. Basic Calculator IV/770.java create mode 100644 solutions/770. Basic Calculator IV/770.py create mode 100644 solutions/771. Jewels and Stones/771.cpp create mode 100644 solutions/771. Jewels and Stones/771.java create mode 100644 solutions/771. Jewels and Stones/771.py create mode 100644 solutions/772. Basic Calculator III/772.cpp create mode 100644 solutions/772. Basic Calculator III/772.java create mode 100644 solutions/772. Basic Calculator III/772.py create mode 100644 solutions/773. Sliding Puzzle/773.cpp create mode 100644 solutions/773. Sliding Puzzle/773.java create mode 100644 solutions/774. Minimize Max Distance to Gas Station/774.cpp create mode 100644 solutions/774. Minimize Max Distance to Gas Station/774.java create mode 100644 solutions/774. Minimize Max Distance to Gas Station/774.py create mode 100644 solutions/775. Global and Local Inversions/775-2.cpp create mode 100644 solutions/775. Global and Local Inversions/775-2.java create mode 100644 solutions/775. Global and Local Inversions/775-2.py create mode 100644 solutions/775. Global and Local Inversions/775.cpp create mode 100644 solutions/775. Global and Local Inversions/775.java create mode 100644 solutions/775. Global and Local Inversions/775.py create mode 100644 solutions/776. Split BST/776.cpp create mode 100644 solutions/776. Split BST/776.java create mode 100644 solutions/776. Split BST/776.py create mode 100644 solutions/777. Swap Adjacent in LR String/777.cpp create mode 100644 solutions/777. Swap Adjacent in LR String/777.java create mode 100644 solutions/777. Swap Adjacent in LR String/777.py create mode 100644 solutions/778. Swim in Rising Water/778.cpp create mode 100644 solutions/778. Swim in Rising Water/778.java create mode 100644 solutions/779. K-th Symbol in Grammar/779.cpp create mode 100644 solutions/779. K-th Symbol in Grammar/779.java create mode 100644 solutions/78. Subsets/78.cpp create mode 100644 solutions/78. Subsets/78.java create mode 100644 solutions/78. Subsets/78.py create mode 100644 solutions/780. Reaching Points/780.cpp create mode 100644 solutions/780. Reaching Points/780.java create mode 100644 solutions/780. Reaching Points/780.py create mode 100644 solutions/781. Rabbits in Forest/781.cpp create mode 100644 solutions/781. Rabbits in Forest/781.java create mode 100644 solutions/781. Rabbits in Forest/781.py create mode 100644 solutions/782. Transform to Chessboard/782.cpp create mode 100644 solutions/782. Transform to Chessboard/782.java create mode 100644 solutions/782. Transform to Chessboard/782.py create mode 100644 solutions/783. Minimum Distance Between BST Nodes/783.cpp create mode 100644 solutions/783. Minimum Distance Between BST Nodes/783.java create mode 100644 solutions/784. Letter Case Permutation/784.cpp create mode 100644 solutions/784. Letter Case Permutation/784.java create mode 100644 solutions/785. Is Graph Bipartite?/785-2.cpp create mode 100644 solutions/785. Is Graph Bipartite?/785-2.java create mode 100644 solutions/785. Is Graph Bipartite?/785-2.py create mode 100644 solutions/785. Is Graph Bipartite?/785.cpp create mode 100644 solutions/785. Is Graph Bipartite?/785.java create mode 100644 solutions/785. Is Graph Bipartite?/785.py create mode 100644 solutions/786. K-th Smallest Prime Fraction/786.cpp create mode 100644 solutions/786. K-th Smallest Prime Fraction/786.java create mode 100644 solutions/786. K-th Smallest Prime Fraction/786.py create mode 100644 solutions/787. Cheapest Flights Within K Stops/787.cpp create mode 100644 solutions/787. Cheapest Flights Within K Stops/787.java create mode 100644 solutions/787. Cheapest Flights Within K Stops/787.py create mode 100644 solutions/788. Rotated Digits/788.cpp create mode 100644 solutions/788. Rotated Digits/788.java create mode 100644 solutions/788. Rotated Digits/788.py create mode 100644 solutions/789. Escape The Ghosts/789.cpp create mode 100644 solutions/789. Escape The Ghosts/789.java create mode 100644 solutions/789. Escape The Ghosts/789.py create mode 100644 solutions/79. Word Search/79.cpp create mode 100644 solutions/79. Word Search/79.java create mode 100644 solutions/79. Word Search/79.py create mode 100644 solutions/790. Domino and Tromino Tiling/790.cpp create mode 100644 solutions/790. Domino and Tromino Tiling/790.java create mode 100644 solutions/790. Domino and Tromino Tiling/790.py create mode 100644 solutions/791. Custom Sort String/791.cpp create mode 100644 solutions/791. Custom Sort String/791.java create mode 100644 solutions/791. Custom Sort String/791.py create mode 100644 solutions/792. Number of Matching Subsequences/792-2.cpp create mode 100644 solutions/792. Number of Matching Subsequences/792-2.java create mode 100644 solutions/792. Number of Matching Subsequences/792-2.py create mode 100644 solutions/792. Number of Matching Subsequences/792.cpp create mode 100644 solutions/792. Number of Matching Subsequences/792.java create mode 100644 solutions/792. Number of Matching Subsequences/792.py create mode 100644 solutions/793. Preimage Size of Factorial Zeroes Function/793.cpp create mode 100644 solutions/793. Preimage Size of Factorial Zeroes Function/793.java create mode 100644 solutions/794. Valid Tic-Tac-Toe State/794.cpp create mode 100644 solutions/794. Valid Tic-Tac-Toe State/794.java create mode 100644 solutions/794. Valid Tic-Tac-Toe State/794.py create mode 100644 solutions/795. Number of Subarrays with Bounded Maximum/795.cpp create mode 100644 solutions/795. Number of Subarrays with Bounded Maximum/795.java create mode 100644 solutions/795. Number of Subarrays with Bounded Maximum/795.py create mode 100644 solutions/796. Rotate String/796.cpp create mode 100644 solutions/796. Rotate String/796.java create mode 100644 solutions/796. Rotate String/796.py create mode 100644 solutions/797. All Paths From Source to Target/797.cpp create mode 100644 solutions/797. All Paths From Source to Target/797.java create mode 100644 solutions/797. All Paths From Source to Target/797.py create mode 100644 solutions/798. Smallest Rotation with Highest Score/798.cpp create mode 100644 solutions/798. Smallest Rotation with Highest Score/798.java create mode 100644 solutions/799. Champagne Tower/799-2.cpp create mode 100644 solutions/799. Champagne Tower/799-2.java create mode 100644 solutions/799. Champagne Tower/799.cpp create mode 100644 solutions/799. Champagne Tower/799.java create mode 100644 solutions/8. String to Integer (atoi)/8.cpp create mode 100644 solutions/8. String to Integer (atoi)/8.java create mode 100644 solutions/8. String to Integer (atoi)/8.py create mode 100644 solutions/80. Remove Duplicates from Sorted Array II/80.cpp create mode 100644 solutions/80. Remove Duplicates from Sorted Array II/80.java create mode 100644 solutions/80. Remove Duplicates from Sorted Array II/80.py create mode 100644 solutions/800. Similar RGB Color/800.cpp create mode 100644 solutions/800. Similar RGB Color/800.java create mode 100644 solutions/800. Similar RGB Color/800.py create mode 100644 solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.cpp create mode 100644 solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.java create mode 100644 solutions/801. Minimum Swaps To Make Sequences Increasing/801.cpp create mode 100644 solutions/801. Minimum Swaps To Make Sequences Increasing/801.java create mode 100644 solutions/801. Minimum Swaps To Make Sequences Increasing/801.py create mode 100644 solutions/802. Find Eventual Safe States/802.cpp create mode 100644 solutions/802. Find Eventual Safe States/802.java create mode 100644 solutions/802. Find Eventual Safe States/802.py create mode 100644 solutions/803. Bricks Falling When Hit/803.cpp create mode 100644 solutions/803. Bricks Falling When Hit/803.java create mode 100644 solutions/804. Unique Morse Code Words/804.cpp create mode 100644 solutions/804. Unique Morse Code Words/804.java create mode 100644 solutions/804. Unique Morse Code Words/804.py create mode 100644 solutions/805. Split Array With Same Average/805.cpp create mode 100644 solutions/805. Split Array With Same Average/805.java create mode 100644 solutions/805. Split Array With Same Average/805.py create mode 100644 solutions/806. Number of Lines To Write String/806.cpp create mode 100644 solutions/806. Number of Lines To Write String/806.java create mode 100644 solutions/806. Number of Lines To Write String/806.py create mode 100644 solutions/807. Max Increase to Keep City Skyline/807.cpp create mode 100644 solutions/807. Max Increase to Keep City Skyline/807.java create mode 100644 solutions/807. Max Increase to Keep City Skyline/807.py create mode 100644 solutions/808. Soup Servings/808.cpp create mode 100644 solutions/808. Soup Servings/808.java create mode 100644 solutions/808. Soup Servings/808.py create mode 100644 solutions/809. Expressive Words/809.cpp create mode 100644 solutions/809. Expressive Words/809.java create mode 100644 solutions/809. Expressive Words/809.py create mode 100644 solutions/81. Search in Rotated Sorted Array II/81.cpp create mode 100644 solutions/81. Search in Rotated Sorted Array II/81.java create mode 100644 solutions/81. Search in Rotated Sorted Array II/81.py create mode 100644 solutions/810. Chalkboard XOR Game/810.cpp create mode 100644 solutions/810. Chalkboard XOR Game/810.java create mode 100644 solutions/810. Chalkboard XOR Game/810.py create mode 100644 solutions/811. Subdomain Visit Count/811.cpp create mode 100644 solutions/811. Subdomain Visit Count/811.java create mode 100644 solutions/811. Subdomain Visit Count/811.py create mode 100644 solutions/812. Largest Triangle Area/812.cpp create mode 100644 solutions/812. Largest Triangle Area/812.java create mode 100644 solutions/812. Largest Triangle Area/812.py create mode 100644 solutions/813. Largest Sum of Averages/813-2.cpp create mode 100644 solutions/813. Largest Sum of Averages/813-2.java create mode 100644 solutions/813. Largest Sum of Averages/813.cpp create mode 100644 solutions/813. Largest Sum of Averages/813.java create mode 100644 solutions/814. Binary Tree Pruning/814.cpp create mode 100644 solutions/814. Binary Tree Pruning/814.java create mode 100644 solutions/814. Binary Tree Pruning/814.py create mode 100644 solutions/815. Bus Routes/815.cpp create mode 100644 solutions/815. Bus Routes/815.java create mode 100644 solutions/815. Bus Routes/815.py create mode 100644 solutions/816. Ambiguous Coordinates/816.cpp create mode 100644 solutions/816. Ambiguous Coordinates/816.java create mode 100644 solutions/816. Ambiguous Coordinates/816.py create mode 100644 solutions/817. Linked List Components/817.cpp create mode 100644 solutions/817. Linked List Components/817.java create mode 100644 solutions/817. Linked List Components/817.py create mode 100644 solutions/818. Race Car/818.cpp create mode 100644 solutions/818. Race Car/818.java create mode 100644 solutions/819. Most Common Word/819.cpp create mode 100644 solutions/819. Most Common Word/819.java create mode 100644 solutions/819. Most Common Word/819.py create mode 100644 solutions/82. Remove Duplicates from Sorted List II/82.cpp create mode 100644 solutions/82. Remove Duplicates from Sorted List II/82.java create mode 100644 solutions/82. Remove Duplicates from Sorted List II/82.py create mode 100644 solutions/820. Short Encoding of Words/820-2.cpp create mode 100644 solutions/820. Short Encoding of Words/820.cpp create mode 100644 solutions/820. Short Encoding of Words/820.java create mode 100644 solutions/820. Short Encoding of Words/820.py create mode 100644 solutions/821. Shortest Distance to a Character/821.cpp create mode 100644 solutions/821. Shortest Distance to a Character/821.java create mode 100644 solutions/821. Shortest Distance to a Character/821.py create mode 100644 solutions/822. Card Flipping Game/822.cpp create mode 100644 solutions/822. Card Flipping Game/822.java create mode 100644 solutions/822. Card Flipping Game/822.py create mode 100644 solutions/823. Binary Trees With Factors/823.cpp create mode 100644 solutions/823. Binary Trees With Factors/823.java create mode 100644 solutions/823. Binary Trees With Factors/823.py create mode 100644 solutions/824. Goat Latin/824.cpp create mode 100644 solutions/824. Goat Latin/824.java create mode 100644 solutions/824. Goat Latin/824.py create mode 100644 solutions/825. Friends Of Appropriate Ages/825.cpp create mode 100644 solutions/825. Friends Of Appropriate Ages/825.java create mode 100644 solutions/825. Friends Of Appropriate Ages/825.py create mode 100644 solutions/826. Most Profit Assigning Work/826.cpp create mode 100644 solutions/826. Most Profit Assigning Work/826.java create mode 100644 solutions/826. Most Profit Assigning Work/826.py create mode 100644 solutions/827. Making A Large Island/827.cpp create mode 100644 solutions/827. Making A Large Island/827.java create mode 100644 solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.cpp create mode 100644 solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.java create mode 100644 solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.py create mode 100644 solutions/828. Count Unique Characters of All Substrings of a Given String/828.cpp create mode 100644 solutions/828. Count Unique Characters of All Substrings of a Given String/828.java create mode 100644 solutions/828. Count Unique Characters of All Substrings of a Given String/828.py create mode 100644 solutions/829. Consecutive Numbers Sum/829.cpp create mode 100644 solutions/829. Consecutive Numbers Sum/829.java create mode 100644 solutions/829. Consecutive Numbers Sum/829.py create mode 100644 solutions/83. Remove Duplicates from Sorted List/83.cpp create mode 100644 solutions/83. Remove Duplicates from Sorted List/83.java create mode 100644 solutions/83. Remove Duplicates from Sorted List/83.py create mode 100644 solutions/830. Positions of Large Groups/830.cpp create mode 100644 solutions/830. Positions of Large Groups/830.java create mode 100644 solutions/830. Positions of Large Groups/830.py create mode 100644 solutions/831. Masking Personal Information/831.cpp create mode 100644 solutions/831. Masking Personal Information/831.java create mode 100644 solutions/831. Masking Personal Information/831.py create mode 100644 solutions/832. Flipping an Image/832.cpp create mode 100644 solutions/832. Flipping an Image/832.java create mode 100644 solutions/832. Flipping an Image/832.py create mode 100644 solutions/833. Find And Replace in String/833.cpp create mode 100644 solutions/833. Find And Replace in String/833.java create mode 100644 solutions/833. Find And Replace in String/833.py create mode 100644 solutions/834. Sum of Distances in Tree/834.cpp create mode 100644 solutions/834. Sum of Distances in Tree/834.java create mode 100644 solutions/834. Sum of Distances in Tree/834.py create mode 100644 solutions/835. Image Overlap/835.cpp create mode 100644 solutions/835. Image Overlap/835.java create mode 100644 solutions/835. Image Overlap/835.py create mode 100644 solutions/836. Rectangle Overlap/836.cpp create mode 100644 solutions/836. Rectangle Overlap/836.java create mode 100644 solutions/836. Rectangle Overlap/836.py create mode 100644 solutions/837. New 21 Game/837.cpp create mode 100644 solutions/837. New 21 Game/837.java create mode 100644 solutions/837. New 21 Game/837.py create mode 100644 solutions/838. Push Dominoes/838.cpp create mode 100644 solutions/838. Push Dominoes/838.java create mode 100644 solutions/838. Push Dominoes/838.py create mode 100644 solutions/839. Similar String Groups/839-2.cpp create mode 100644 solutions/839. Similar String Groups/839-2.java create mode 100644 solutions/839. Similar String Groups/839.cpp create mode 100644 solutions/839. Similar String Groups/839.java create mode 100644 solutions/84. Largest Rectangle in Histogram/84.cpp create mode 100644 solutions/84. Largest Rectangle in Histogram/84.java create mode 100644 solutions/84. Largest Rectangle in Histogram/84.py create mode 100644 solutions/840. Magic Squares In Grid/840.cpp create mode 100644 solutions/840. Magic Squares In Grid/840.java create mode 100644 solutions/840. Magic Squares In Grid/840.py create mode 100644 solutions/841. Keys and Rooms/841.cpp create mode 100644 solutions/841. Keys and Rooms/841.java create mode 100644 solutions/841. Keys and Rooms/841.py create mode 100644 solutions/842. Split Array into Fibonacci Sequence/842.cpp create mode 100644 solutions/842. Split Array into Fibonacci Sequence/842.java create mode 100644 solutions/843. Guess the Word/843.cpp create mode 100644 solutions/843. Guess the Word/843.java create mode 100644 solutions/843. Guess the Word/843.py create mode 100644 solutions/844. Backspace String Compare/844-2.cpp create mode 100644 solutions/844. Backspace String Compare/844-2.java create mode 100644 solutions/844. Backspace String Compare/844-2.py create mode 100644 solutions/844. Backspace String Compare/844.cpp create mode 100644 solutions/844. Backspace String Compare/844.java create mode 100644 solutions/844. Backspace String Compare/844.py create mode 100644 solutions/845. Longest Mountain in Array/845.cpp create mode 100644 solutions/845. Longest Mountain in Array/845.java create mode 100644 solutions/845. Longest Mountain in Array/845.py create mode 100644 solutions/846. Hand of Straights/846.cpp create mode 100644 solutions/846. Hand of Straights/846.java create mode 100644 solutions/846. Hand of Straights/846.py create mode 100644 solutions/847. Shortest Path Visiting All Nodes/847.cpp create mode 100644 solutions/847. Shortest Path Visiting All Nodes/847.java create mode 100644 solutions/847. Shortest Path Visiting All Nodes/847.py create mode 100644 solutions/848. Shifting Letters/848.cpp create mode 100644 solutions/848. Shifting Letters/848.java create mode 100644 solutions/848. Shifting Letters/848.py create mode 100644 solutions/849. Maximize Distance to Closest Person/849.cpp create mode 100644 solutions/849. Maximize Distance to Closest Person/849.java create mode 100644 solutions/849. Maximize Distance to Closest Person/849.py create mode 100644 solutions/85. Maximal Rectangle/85.cpp create mode 100644 solutions/85. Maximal Rectangle/85.java create mode 100644 solutions/85. Maximal Rectangle/85.py create mode 100644 solutions/850. Rectangle Area II/850.cpp create mode 100644 solutions/850. Rectangle Area II/850.java create mode 100644 solutions/850. Rectangle Area II/850.py create mode 100644 solutions/851. Loud and Rich/851.cpp create mode 100644 solutions/851. Loud and Rich/851.java create mode 100644 solutions/851. Loud and Rich/851.py create mode 100644 solutions/852. Peak Index in a Mountain Array/852.cpp create mode 100644 solutions/852. Peak Index in a Mountain Array/852.java create mode 100644 solutions/852. Peak Index in a Mountain Array/852.py create mode 100644 solutions/853. Car Fleet/853.cpp create mode 100644 solutions/853. Car Fleet/853.java create mode 100644 solutions/853. Car Fleet/853.py create mode 100644 solutions/854. K-Similar Strings/854.cpp create mode 100644 solutions/854. K-Similar Strings/854.java create mode 100644 solutions/854. K-Similar Strings/854.py create mode 100644 solutions/855. Exam Room/855.cpp create mode 100644 solutions/855. Exam Room/855.java create mode 100644 solutions/856. Score of Parentheses/856.cpp create mode 100644 solutions/856. Score of Parentheses/856.java create mode 100644 solutions/856. Score of Parentheses/856.py create mode 100644 solutions/857. Minimum Cost to Hire K Workers/857.cpp create mode 100644 solutions/857. Minimum Cost to Hire K Workers/857.java create mode 100644 solutions/857. Minimum Cost to Hire K Workers/857.py create mode 100644 solutions/858. Mirror Reflection/858.cpp create mode 100644 solutions/858. Mirror Reflection/858.java create mode 100644 solutions/858. Mirror Reflection/858.py create mode 100644 solutions/859. Buddy Strings/859.cpp create mode 100644 solutions/859. Buddy Strings/859.java create mode 100644 solutions/859. Buddy Strings/859.py create mode 100644 solutions/86. Partition List/86.cpp create mode 100644 solutions/86. Partition List/86.java create mode 100644 solutions/86. Partition List/86.py create mode 100644 solutions/860. Lemonade Change/860.cpp create mode 100644 solutions/860. Lemonade Change/860.java create mode 100644 solutions/860. Lemonade Change/860.py create mode 100644 solutions/861. Score After Flipping Matrix/861-2.cpp create mode 100644 solutions/861. Score After Flipping Matrix/861-2.java create mode 100644 solutions/861. Score After Flipping Matrix/861-2.py create mode 100644 solutions/861. Score After Flipping Matrix/861.cpp create mode 100644 solutions/861. Score After Flipping Matrix/861.java create mode 100644 solutions/861. Score After Flipping Matrix/861.py create mode 100644 solutions/862. Shortest Subarray with Sum at Least K/862.cpp create mode 100644 solutions/862. Shortest Subarray with Sum at Least K/862.java create mode 100644 solutions/862. Shortest Subarray with Sum at Least K/862.py create mode 100644 solutions/863. All Nodes Distance K in Binary Tree/863.cpp create mode 100644 solutions/863. All Nodes Distance K in Binary Tree/863.java create mode 100644 solutions/864. Shortest Path to Get All Keys/864.cpp create mode 100644 solutions/864. Shortest Path to Get All Keys/864.java create mode 100644 solutions/865. Smallest Subtree with all the Deepest Nodes/865.cpp create mode 100644 solutions/865. Smallest Subtree with all the Deepest Nodes/865.java create mode 100644 solutions/866. Prime Palindrome/866.cpp create mode 100644 solutions/866. Prime Palindrome/866.java create mode 100644 solutions/866. Prime Palindrome/866.py create mode 100644 solutions/867. Transpose Matrix/867.cpp create mode 100644 solutions/867. Transpose Matrix/867.java create mode 100644 solutions/867. Transpose Matrix/867.py create mode 100644 solutions/868. Binary Gap/868.cpp create mode 100644 solutions/868. Binary Gap/868.java create mode 100644 solutions/868. Binary Gap/868.py create mode 100644 solutions/869. Reordered Power of 2/869.cpp create mode 100644 solutions/869. Reordered Power of 2/869.java create mode 100644 solutions/869. Reordered Power of 2/869.py create mode 100644 solutions/87. Scramble String/87.cpp create mode 100644 solutions/87. Scramble String/87.java create mode 100644 solutions/87. Scramble String/87.py create mode 100644 solutions/870. Advantage Shuffle/870.cpp create mode 100644 solutions/870. Advantage Shuffle/870.java create mode 100644 solutions/870. Advantage Shuffle/870.py create mode 100644 solutions/871. Minimum Number of Refueling Stops/871-2.cpp create mode 100644 solutions/871. Minimum Number of Refueling Stops/871-2.java create mode 100644 solutions/871. Minimum Number of Refueling Stops/871-2.py create mode 100644 solutions/871. Minimum Number of Refueling Stops/871.cpp create mode 100644 solutions/871. Minimum Number of Refueling Stops/871.java create mode 100644 solutions/871. Minimum Number of Refueling Stops/871.py create mode 100644 solutions/872. Leaf-Similar Trees/872.cpp create mode 100644 solutions/872. Leaf-Similar Trees/872.java create mode 100644 solutions/872. Leaf-Similar Trees/872.py create mode 100644 solutions/873. Length of Longest Fibonacci Subsequence/873.cpp create mode 100644 solutions/873. Length of Longest Fibonacci Subsequence/873.java create mode 100644 solutions/873. Length of Longest Fibonacci Subsequence/873.py create mode 100644 solutions/874. Walking Robot Simulation/874.cpp create mode 100644 solutions/874. Walking Robot Simulation/874.java create mode 100644 solutions/874. Walking Robot Simulation/874.py create mode 100644 solutions/875. Koko Eating Bananas/875.cpp create mode 100644 solutions/875. Koko Eating Bananas/875.java create mode 100644 solutions/875. Koko Eating Bananas/875.py create mode 100644 solutions/876. Middle of the Linked List/876.cpp create mode 100644 solutions/876. Middle of the Linked List/876.java create mode 100644 solutions/876. Middle of the Linked List/876.py create mode 100644 solutions/877. Stone Game/877-2.cpp create mode 100644 solutions/877. Stone Game/877-2.java create mode 100644 solutions/877. Stone Game/877-2.py create mode 100644 solutions/877. Stone Game/877.cpp create mode 100644 solutions/877. Stone Game/877.java create mode 100644 solutions/877. Stone Game/877.py create mode 100644 solutions/878. Nth Magical Number/878.cpp create mode 100644 solutions/878. Nth Magical Number/878.java create mode 100644 solutions/878. Nth Magical Number/878.py create mode 100644 solutions/879. Profitable Schemes/879-2.cpp create mode 100644 solutions/879. Profitable Schemes/879-2.java create mode 100644 solutions/879. Profitable Schemes/879.cpp create mode 100644 solutions/879. Profitable Schemes/879.java create mode 100644 solutions/88. Merge Sorted Array/88.cpp create mode 100644 solutions/88. Merge Sorted Array/88.java create mode 100644 solutions/88. Merge Sorted Array/88.py create mode 100644 solutions/880. Decoded String at Index/880.cpp create mode 100644 solutions/880. Decoded String at Index/880.java create mode 100644 solutions/880. Decoded String at Index/880.py create mode 100644 solutions/881. Boats to Save People/881.cpp create mode 100644 solutions/881. Boats to Save People/881.java create mode 100644 solutions/881. Boats to Save People/881.py create mode 100644 solutions/882. Reachable Nodes In Subdivided Graph/882.cpp create mode 100644 solutions/882. Reachable Nodes In Subdivided Graph/882.java create mode 100644 solutions/882. Reachable Nodes In Subdivided Graph/882.py create mode 100644 solutions/883. Projection Area of 3D Shapes/883.cpp create mode 100644 solutions/883. Projection Area of 3D Shapes/883.java create mode 100644 solutions/883. Projection Area of 3D Shapes/883.py create mode 100644 solutions/884. Uncommon Words from Two Sentences/884.cpp create mode 100644 solutions/884. Uncommon Words from Two Sentences/884.java create mode 100644 solutions/884. Uncommon Words from Two Sentences/884.py create mode 100644 solutions/885. Spiral Matrix III/885.cpp create mode 100644 solutions/885. Spiral Matrix III/885.java create mode 100644 solutions/885. Spiral Matrix III/885.py create mode 100644 solutions/886. Possible Bipartition/886.cpp create mode 100644 solutions/886. Possible Bipartition/886.java create mode 100644 solutions/886. Possible Bipartition/886.py create mode 100644 solutions/887. Super Egg Drop/887-2.cpp create mode 100644 solutions/887. Super Egg Drop/887-2.java create mode 100644 solutions/887. Super Egg Drop/887-3.cpp create mode 100644 solutions/887. Super Egg Drop/887-3.java create mode 100644 solutions/887. Super Egg Drop/887-3.py create mode 100644 solutions/887. Super Egg Drop/887.cpp create mode 100644 solutions/887. Super Egg Drop/887.java create mode 100644 solutions/888. Fair Candy Swap/888.cpp create mode 100644 solutions/888. Fair Candy Swap/888.java create mode 100644 solutions/888. Fair Candy Swap/888.py create mode 100644 solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.cpp create mode 100644 solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.java create mode 100644 solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.py create mode 100644 solutions/89. Gray Code/89.cpp create mode 100644 solutions/89. Gray Code/89.java create mode 100644 solutions/89. Gray Code/89.py create mode 100644 solutions/890. Find and Replace Pattern/890.cpp create mode 100644 solutions/890. Find and Replace Pattern/890.java create mode 100644 solutions/890. Find and Replace Pattern/890.py create mode 100644 solutions/891. Sum of Subsequence Widths/891.cpp create mode 100644 solutions/891. Sum of Subsequence Widths/891.java create mode 100644 solutions/891. Sum of Subsequence Widths/891.py create mode 100644 solutions/892. Surface Area of 3D Shapes/892.cpp create mode 100644 solutions/892. Surface Area of 3D Shapes/892.java create mode 100644 solutions/892. Surface Area of 3D Shapes/892.py create mode 100644 solutions/893. Groups of Special-Equivalent Strings/893.cpp create mode 100644 solutions/893. Groups of Special-Equivalent Strings/893.java create mode 100644 solutions/893. Groups of Special-Equivalent Strings/893.py create mode 100644 solutions/894. All Possible Full Binary Trees/894.cpp create mode 100644 solutions/894. All Possible Full Binary Trees/894.java create mode 100644 solutions/894. All Possible Full Binary Trees/894.py create mode 100644 solutions/895. Maximum Frequency Stack/895.cpp create mode 100644 solutions/895. Maximum Frequency Stack/895.java create mode 100644 solutions/895. Maximum Frequency Stack/895.py create mode 100644 solutions/896. Monotonic Array/896.cpp create mode 100644 solutions/896. Monotonic Array/896.java create mode 100644 solutions/896. Monotonic Array/896.py create mode 100644 solutions/897. Increasing Order Search Tree/897.cpp create mode 100644 solutions/897. Increasing Order Search Tree/897.java create mode 100644 solutions/897. Increasing Order Search Tree/897.py create mode 100644 solutions/898. Bitwise ORs of Subarrays/898.cpp create mode 100644 solutions/898. Bitwise ORs of Subarrays/898.java create mode 100644 solutions/899. Orderly Queue/899.cpp create mode 100644 solutions/899. Orderly Queue/899.java create mode 100644 solutions/899. Orderly Queue/899.py create mode 100644 solutions/9. Palindrome Number/9.cpp create mode 100644 solutions/9. Palindrome Number/9.java create mode 100644 solutions/9. Palindrome Number/9.py create mode 100644 solutions/90. Subsets II/90.cpp create mode 100644 solutions/90. Subsets II/90.java create mode 100644 solutions/90. Subsets II/90.py create mode 100644 solutions/900. RLE Iterator/900.cpp create mode 100644 solutions/900. RLE Iterator/900.java create mode 100644 solutions/900. RLE Iterator/900.py create mode 100644 solutions/901. Online Stock Span/901.cpp create mode 100644 solutions/901. Online Stock Span/901.java create mode 100644 solutions/901. Online Stock Span/901.py create mode 100644 solutions/902. Numbers At Most N Given Digit Set/902.cpp create mode 100644 solutions/902. Numbers At Most N Given Digit Set/902.java create mode 100644 solutions/902. Numbers At Most N Given Digit Set/902.py create mode 100644 solutions/903. Valid Permutations for DI Sequence/903-2.cpp create mode 100644 solutions/903. Valid Permutations for DI Sequence/903-2.java create mode 100644 solutions/903. Valid Permutations for DI Sequence/903.cpp create mode 100644 solutions/903. Valid Permutations for DI Sequence/903.java create mode 100644 solutions/904. Fruit Into Baskets/904.cpp create mode 100644 solutions/904. Fruit Into Baskets/904.java create mode 100644 solutions/904. Fruit Into Baskets/904.py create mode 100644 solutions/905. Sort Array By Parity/905.cpp create mode 100644 solutions/905. Sort Array By Parity/905.java create mode 100644 solutions/905. Sort Array By Parity/905.py create mode 100644 solutions/906. Super Palindromes/906.cpp create mode 100644 solutions/906. Super Palindromes/906.java create mode 100644 solutions/906. Super Palindromes/906.py create mode 100644 solutions/907. Sum of Subarray Minimums/907.cpp create mode 100644 solutions/907. Sum of Subarray Minimums/907.java create mode 100644 solutions/907. Sum of Subarray Minimums/907.py create mode 100644 solutions/908. Smallest Range I/908.cpp create mode 100644 solutions/908. Smallest Range I/908.java create mode 100644 solutions/908. Smallest Range I/908.py create mode 100644 solutions/909. Snakes and Ladders/909.cpp create mode 100644 solutions/909. Snakes and Ladders/909.java create mode 100644 solutions/909. Snakes and Ladders/909.py create mode 100644 solutions/91. Decode Ways/91.cpp create mode 100644 solutions/91. Decode Ways/91.java create mode 100644 solutions/91. Decode Ways/91.py create mode 100644 solutions/910. Smallest Range II/910.cpp create mode 100644 solutions/910. Smallest Range II/910.java create mode 100644 solutions/910. Smallest Range II/910.py create mode 100644 solutions/911. Online Election/911.cpp create mode 100644 solutions/911. Online Election/911.java create mode 100644 solutions/911. Online Election/911.py create mode 100644 solutions/912. Sort an Array/912-2.cpp create mode 100644 solutions/912. Sort an Array/912-2.java create mode 100644 solutions/912. Sort an Array/912-2.py create mode 100644 solutions/912. Sort an Array/912-3.cpp create mode 100644 solutions/912. Sort an Array/912-3.java create mode 100644 solutions/912. Sort an Array/912-3.py create mode 100644 solutions/912. Sort an Array/912.cpp create mode 100644 solutions/912. Sort an Array/912.java create mode 100644 solutions/912. Sort an Array/912.py create mode 100644 solutions/913. Cat and Mouse/913.cpp create mode 100644 solutions/913. Cat and Mouse/913.java create mode 100644 solutions/913. Cat and Mouse/913.py create mode 100644 solutions/914. X of a Kind in a Deck of Cards/914.cpp create mode 100644 solutions/914. X of a Kind in a Deck of Cards/914.java create mode 100644 solutions/914. X of a Kind in a Deck of Cards/914.py create mode 100644 solutions/915. Partition Array into Disjoint Intervals/915.cpp create mode 100644 solutions/915. Partition Array into Disjoint Intervals/915.java create mode 100644 solutions/915. Partition Array into Disjoint Intervals/915.py create mode 100644 solutions/916. Word Subsets/916.cpp create mode 100644 solutions/916. Word Subsets/916.java create mode 100644 solutions/916. Word Subsets/916.py create mode 100644 solutions/917. Reverse Only Letters/917.cpp create mode 100644 solutions/917. Reverse Only Letters/917.java create mode 100644 solutions/917. Reverse Only Letters/917.py create mode 100644 solutions/918. Maximum Sum Circular Subarray/918.cpp create mode 100644 solutions/918. Maximum Sum Circular Subarray/918.java create mode 100644 solutions/918. Maximum Sum Circular Subarray/918.py create mode 100644 solutions/919. Complete Binary Tree Inserter/919.cpp create mode 100644 solutions/919. Complete Binary Tree Inserter/919.java create mode 100644 solutions/919. Complete Binary Tree Inserter/919.py create mode 100644 solutions/92. Reverse Linked List II/92-2.cpp create mode 100644 solutions/92. Reverse Linked List II/92-2.java create mode 100644 solutions/92. Reverse Linked List II/92-2.py create mode 100644 solutions/92. Reverse Linked List II/92.cpp create mode 100644 solutions/92. Reverse Linked List II/92.java create mode 100644 solutions/92. Reverse Linked List II/92.py create mode 100644 solutions/920. Number of Music Playlists/920-2.cpp create mode 100644 solutions/920. Number of Music Playlists/920-2.java create mode 100644 solutions/920. Number of Music Playlists/920.cpp create mode 100644 solutions/920. Number of Music Playlists/920.java create mode 100644 solutions/921. Minimum Add to Make Parentheses Valid/921.cpp create mode 100644 solutions/921. Minimum Add to Make Parentheses Valid/921.java create mode 100644 solutions/921. Minimum Add to Make Parentheses Valid/921.py create mode 100644 solutions/922. Sort Array By Parity II/922.cpp create mode 100644 solutions/922. Sort Array By Parity II/922.java create mode 100644 solutions/922. Sort Array By Parity II/922.py create mode 100644 solutions/923. 3Sum With Multiplicity/923.cpp create mode 100644 solutions/923. 3Sum With Multiplicity/923.java create mode 100644 solutions/923. 3Sum With Multiplicity/923.py create mode 100644 solutions/924. Minimize Malware Spread/924.cpp create mode 100644 solutions/924. Minimize Malware Spread/924.java create mode 100644 solutions/925. Long Pressed Name/925.cpp create mode 100644 solutions/925. Long Pressed Name/925.java create mode 100644 solutions/925. Long Pressed Name/925.py create mode 100644 solutions/926. Flip String to Monotone Increasing/926.cpp create mode 100644 solutions/926. Flip String to Monotone Increasing/926.java create mode 100644 solutions/926. Flip String to Monotone Increasing/926.py create mode 100644 solutions/927. Three Equal Parts/927.cpp create mode 100644 solutions/927. Three Equal Parts/927.java create mode 100644 solutions/927. Three Equal Parts/927.py create mode 100644 solutions/928. Minimize Malware Spread II/928.cpp create mode 100644 solutions/928. Minimize Malware Spread II/928.java create mode 100644 solutions/929. Unique Email Addresses/929.cpp create mode 100644 solutions/929. Unique Email Addresses/929.java create mode 100644 solutions/929. Unique Email Addresses/929.py create mode 100644 solutions/93. Restore IP Addresses/93.cpp create mode 100644 solutions/93. Restore IP Addresses/93.java create mode 100644 solutions/93. Restore IP Addresses/93.py create mode 100644 solutions/930. Binary Subarrays With Sum/930-2.cpp create mode 100644 solutions/930. Binary Subarrays With Sum/930-2.java create mode 100644 solutions/930. Binary Subarrays With Sum/930-2.py create mode 100644 solutions/930. Binary Subarrays With Sum/930.cpp create mode 100644 solutions/930. Binary Subarrays With Sum/930.java create mode 100644 solutions/930. Binary Subarrays With Sum/930.py create mode 100644 solutions/931. Minimum Falling Path Sum/931.cpp create mode 100644 solutions/931. Minimum Falling Path Sum/931.java create mode 100644 solutions/931. Minimum Falling Path Sum/931.py create mode 100644 solutions/932. Beautiful Array/932.cpp create mode 100644 solutions/932. Beautiful Array/932.java create mode 100644 solutions/932. Beautiful Array/932.py create mode 100644 solutions/933. Number of Recent Calls/933.cpp create mode 100644 solutions/933. Number of Recent Calls/933.java create mode 100644 solutions/933. Number of Recent Calls/933.py create mode 100644 solutions/934. Shortest Bridge/934-2.cpp create mode 100644 solutions/934. Shortest Bridge/934-2.java create mode 100644 solutions/934. Shortest Bridge/934.cpp create mode 100644 solutions/934. Shortest Bridge/934.java create mode 100644 solutions/935. Knight Dialer/935.cpp create mode 100644 solutions/935. Knight Dialer/935.java create mode 100644 solutions/935. Knight Dialer/935.py create mode 100644 solutions/936. Stamping The Sequence/936.cpp create mode 100644 solutions/936. Stamping The Sequence/936.java create mode 100644 solutions/936. Stamping The Sequence/936.py create mode 100644 solutions/937. Reorder Data in Log Files/937.cpp create mode 100644 solutions/937. Reorder Data in Log Files/937.java create mode 100644 solutions/937. Reorder Data in Log Files/937.py create mode 100644 solutions/938. Range Sum of BST/938.cpp create mode 100644 solutions/938. Range Sum of BST/938.java create mode 100644 solutions/939. Minimum Area Rectangle/939.cpp create mode 100644 solutions/939. Minimum Area Rectangle/939.java create mode 100644 solutions/939. Minimum Area Rectangle/939.py create mode 100644 solutions/94. Binary Tree Inorder Traversal/94.cpp create mode 100644 solutions/94. Binary Tree Inorder Traversal/94.java create mode 100644 solutions/94. Binary Tree Inorder Traversal/94.py create mode 100644 solutions/940. Distinct Subsequences II/940.cpp create mode 100644 solutions/940. Distinct Subsequences II/940.java create mode 100644 solutions/940. Distinct Subsequences II/940.py create mode 100644 solutions/941. Valid Mountain Array/941.cpp create mode 100644 solutions/941. Valid Mountain Array/941.java create mode 100644 solutions/941. Valid Mountain Array/941.py create mode 100644 solutions/942. DI String Match/942.cpp create mode 100644 solutions/942. DI String Match/942.java create mode 100644 solutions/942. DI String Match/942.py create mode 100644 solutions/943. Find the Shortest Superstring/943-2.cpp create mode 100644 solutions/943. Find the Shortest Superstring/943-2.java create mode 100644 solutions/943. Find the Shortest Superstring/943.cpp create mode 100644 solutions/943. Find the Shortest Superstring/943.java create mode 100644 solutions/944. Delete Columns to Make Sorted/944.cpp create mode 100644 solutions/944. Delete Columns to Make Sorted/944.java create mode 100644 solutions/944. Delete Columns to Make Sorted/944.py create mode 100644 solutions/945. Minimum Increment to Make Array Unique/945.cpp create mode 100644 solutions/945. Minimum Increment to Make Array Unique/945.java create mode 100644 solutions/945. Minimum Increment to Make Array Unique/945.py create mode 100644 solutions/946. Validate Stack Sequences/946.cpp create mode 100644 solutions/946. Validate Stack Sequences/946.java create mode 100644 solutions/946. Validate Stack Sequences/946.py create mode 100644 solutions/947. Most Stones Removed with Same Row or Column/947.cpp create mode 100644 solutions/947. Most Stones Removed with Same Row or Column/947.java create mode 100644 solutions/948. Bag of Tokens/948.cpp create mode 100644 solutions/948. Bag of Tokens/948.java create mode 100644 solutions/948. Bag of Tokens/948.py create mode 100644 solutions/949. Largest Time for Given Digits/949.cpp create mode 100644 solutions/949. Largest Time for Given Digits/949.java create mode 100644 solutions/949. Largest Time for Given Digits/949.py create mode 100644 solutions/95. Unique Binary Search Trees II/95.cpp create mode 100644 solutions/95. Unique Binary Search Trees II/95.java create mode 100644 solutions/95. Unique Binary Search Trees II/95.py create mode 100644 solutions/950. Reveal Cards In Increasing Order/950.cpp create mode 100644 solutions/950. Reveal Cards In Increasing Order/950.java create mode 100644 solutions/950. Reveal Cards In Increasing Order/950.py create mode 100644 solutions/951. Flip Equivalent Binary Trees/951.cpp create mode 100644 solutions/951. Flip Equivalent Binary Trees/951.java create mode 100644 solutions/951. Flip Equivalent Binary Trees/951.py create mode 100644 solutions/952. Largest Component Size by Common Factor/952.cpp create mode 100644 solutions/952. Largest Component Size by Common Factor/952.java create mode 100644 solutions/952. Largest Component Size by Common Factor/952.py create mode 100644 solutions/953. Verifying an Alien Dictionary/953.cpp create mode 100644 solutions/953. Verifying an Alien Dictionary/953.java create mode 100644 solutions/953. Verifying an Alien Dictionary/953.py create mode 100644 solutions/954. Array of Doubled Pairs/954.cpp create mode 100644 solutions/954. Array of Doubled Pairs/954.java create mode 100644 solutions/954. Array of Doubled Pairs/954.py create mode 100644 solutions/955. Delete Columns to Make Sorted II/955.cpp create mode 100644 solutions/955. Delete Columns to Make Sorted II/955.java create mode 100644 solutions/956. Tallest Billboard/956-2.cpp create mode 100644 solutions/956. Tallest Billboard/956-2.java create mode 100644 solutions/956. Tallest Billboard/956.cpp create mode 100644 solutions/956. Tallest Billboard/956.java create mode 100644 solutions/957. Prison Cells After N Days/957.cpp create mode 100644 solutions/957. Prison Cells After N Days/957.java create mode 100644 solutions/957. Prison Cells After N Days/957.py create mode 100644 solutions/958. Check Completeness of a Binary Tree/958-2.cpp create mode 100644 solutions/958. Check Completeness of a Binary Tree/958-2.java create mode 100644 solutions/958. Check Completeness of a Binary Tree/958.cpp create mode 100644 solutions/958. Check Completeness of a Binary Tree/958.java create mode 100644 solutions/959. Regions Cut By Slashes/959.cpp create mode 100644 solutions/959. Regions Cut By Slashes/959.java create mode 100644 solutions/96. Unique Binary Search Trees/96.cpp create mode 100644 solutions/96. Unique Binary Search Trees/96.java create mode 100644 solutions/96. Unique Binary Search Trees/96.py create mode 100644 solutions/960. Delete Columns to Make Sorted III/960.cpp create mode 100644 solutions/960. Delete Columns to Make Sorted III/960.java create mode 100644 solutions/961. N-Repeated Element in Size 2N Array/961.cpp create mode 100644 solutions/961. N-Repeated Element in Size 2N Array/961.java create mode 100644 solutions/961. N-Repeated Element in Size 2N Array/961.py create mode 100644 solutions/962. Maximum Width Ramp/962.cpp create mode 100644 solutions/962. Maximum Width Ramp/962.java create mode 100644 solutions/962. Maximum Width Ramp/962.py create mode 100644 solutions/963. Minimum Area Rectangle II/963.cpp create mode 100644 solutions/963. Minimum Area Rectangle II/963.java create mode 100644 solutions/963. Minimum Area Rectangle II/963.py create mode 100644 solutions/964. Least Operators to Express Number/964.cpp create mode 100644 solutions/964. Least Operators to Express Number/964.java create mode 100644 solutions/964. Least Operators to Express Number/964.py create mode 100644 solutions/965. Univalued Binary Tree/965.cpp create mode 100644 solutions/965. Univalued Binary Tree/965.java create mode 100644 solutions/965. Univalued Binary Tree/965.py create mode 100644 solutions/966. Vowel Spellchecker/966.cpp create mode 100644 solutions/966. Vowel Spellchecker/966.java create mode 100644 solutions/966. Vowel Spellchecker/966.py create mode 100644 solutions/967. Numbers With Same Consecutive Differences/967.cpp create mode 100644 solutions/967. Numbers With Same Consecutive Differences/967.java create mode 100644 solutions/968. Binary Tree Cameras/968.cpp create mode 100644 solutions/968. Binary Tree Cameras/968.java create mode 100644 solutions/969. Pancake Sorting/969.cpp create mode 100644 solutions/969. Pancake Sorting/969.java create mode 100644 solutions/969. Pancake Sorting/969.py create mode 100644 solutions/97. Interleaving String/97-2.cpp create mode 100644 solutions/97. Interleaving String/97-2.java create mode 100644 solutions/97. Interleaving String/97-2.py create mode 100644 solutions/97. Interleaving String/97.cpp create mode 100644 solutions/97. Interleaving String/97.java create mode 100644 solutions/97. Interleaving String/97.py create mode 100644 solutions/970. Powerful Integers/970.cpp create mode 100644 solutions/970. Powerful Integers/970.java create mode 100644 solutions/970. Powerful Integers/970.py create mode 100644 solutions/971. Flip Binary Tree To Match Preorder Traversal/971.cpp create mode 100644 solutions/971. Flip Binary Tree To Match Preorder Traversal/971.java create mode 100644 solutions/972. Equal Rational Numbers/972.cpp create mode 100644 solutions/972. Equal Rational Numbers/972.java create mode 100644 solutions/972. Equal Rational Numbers/972.py create mode 100644 solutions/973. K Closest Points to Origin/973-2.cpp create mode 100644 solutions/973. K Closest Points to Origin/973-2.java create mode 100644 solutions/973. K Closest Points to Origin/973-2.py create mode 100644 solutions/973. K Closest Points to Origin/973-3.cpp create mode 100644 solutions/973. K Closest Points to Origin/973-3.java create mode 100644 solutions/973. K Closest Points to Origin/973-3.py create mode 100644 solutions/973. K Closest Points to Origin/973.cpp create mode 100644 solutions/973. K Closest Points to Origin/973.java create mode 100644 solutions/973. K Closest Points to Origin/973.py create mode 100644 solutions/974. Subarray Sums Divisible by K/974.cpp create mode 100644 solutions/974. Subarray Sums Divisible by K/974.java create mode 100644 solutions/974. Subarray Sums Divisible by K/974.py create mode 100644 solutions/975. Odd Even Jump/975.cpp create mode 100644 solutions/975. Odd Even Jump/975.java create mode 100644 solutions/976. Largest Perimeter Triangle/976.cpp create mode 100644 solutions/976. Largest Perimeter Triangle/976.java create mode 100644 solutions/976. Largest Perimeter Triangle/976.py create mode 100644 solutions/977. Squares of a Sorted Array/977.cpp create mode 100644 solutions/977. Squares of a Sorted Array/977.java create mode 100644 solutions/977. Squares of a Sorted Array/977.py create mode 100644 solutions/978. Longest Turbulent Subarray/978.cpp create mode 100644 solutions/978. Longest Turbulent Subarray/978.java create mode 100644 solutions/978. Longest Turbulent Subarray/978.py create mode 100644 solutions/979. Distribute Coins in Binary Tree/979.cpp create mode 100644 solutions/979. Distribute Coins in Binary Tree/979.java create mode 100644 solutions/98. Validate Binary Search Tree/98-2.cpp create mode 100644 solutions/98. Validate Binary Search Tree/98-2.java create mode 100644 solutions/98. Validate Binary Search Tree/98-2.py create mode 100644 solutions/98. Validate Binary Search Tree/98.cpp create mode 100644 solutions/98. Validate Binary Search Tree/98.java create mode 100644 solutions/98. Validate Binary Search Tree/98.py create mode 100644 solutions/980. Unique Paths III/980.cpp create mode 100644 solutions/980. Unique Paths III/980.java create mode 100644 solutions/981. Time Based Key-Value Store/981.cpp create mode 100644 solutions/981. Time Based Key-Value Store/981.java create mode 100644 solutions/981. Time Based Key-Value Store/981.py create mode 100644 solutions/982. Triples with Bitwise AND Equal To Zero/982.cpp create mode 100644 solutions/982. Triples with Bitwise AND Equal To Zero/982.java create mode 100644 solutions/982. Triples with Bitwise AND Equal To Zero/982.py create mode 100644 solutions/983. Minimum Cost For Tickets/983.cpp create mode 100644 solutions/983. Minimum Cost For Tickets/983.java create mode 100644 solutions/983. Minimum Cost For Tickets/983.py create mode 100644 solutions/984. String Without AAA or BBB/984.cpp create mode 100644 solutions/985. Sum of Even Numbers After Queries/985.cpp create mode 100644 solutions/985. Sum of Even Numbers After Queries/985.java create mode 100644 solutions/985. Sum of Even Numbers After Queries/985.py create mode 100644 solutions/986. Interval List Intersections/986.cpp create mode 100644 solutions/986. Interval List Intersections/986.java create mode 100644 solutions/986. Interval List Intersections/986.py create mode 100644 solutions/987. Vertical Order Traversal of a Binary Tree/987.cpp create mode 100644 solutions/987. Vertical Order Traversal of a Binary Tree/987.java create mode 100644 solutions/987. Vertical Order Traversal of a Binary Tree/987.py create mode 100644 solutions/988. Smallest String Starting From Leaf/988.cpp create mode 100644 solutions/988. Smallest String Starting From Leaf/988.java create mode 100644 solutions/989. Add to Array-Form of Integer/989.cpp create mode 100644 solutions/989. Add to Array-Form of Integer/989.java create mode 100644 solutions/989. Add to Array-Form of Integer/989.py create mode 100644 solutions/99. Recover Binary Search Tree/99-2.cpp create mode 100644 solutions/99. Recover Binary Search Tree/99-2.java create mode 100644 solutions/99. Recover Binary Search Tree/99-2.py create mode 100644 solutions/99. Recover Binary Search Tree/99-3.cpp create mode 100644 solutions/99. Recover Binary Search Tree/99-3.java create mode 100644 solutions/99. Recover Binary Search Tree/99-3.py create mode 100644 solutions/99. Recover Binary Search Tree/99.cpp create mode 100644 solutions/99. Recover Binary Search Tree/99.java create mode 100644 solutions/99. Recover Binary Search Tree/99.py create mode 100644 solutions/990. Satisfiability of Equality Equations/990.cpp create mode 100644 solutions/990. Satisfiability of Equality Equations/990.java create mode 100644 solutions/990. Satisfiability of Equality Equations/990.py create mode 100644 solutions/991. Broken Calculator/991.cpp create mode 100644 solutions/991. Broken Calculator/991.java create mode 100644 solutions/991. Broken Calculator/991.py create mode 100644 solutions/992. Subarrays with K Different Integers/992.cpp create mode 100644 solutions/992. Subarrays with K Different Integers/992.java create mode 100644 solutions/992. Subarrays with K Different Integers/992.py create mode 100644 solutions/993. Cousins in Binary Tree/993.cpp create mode 100644 solutions/994. Rotting Oranges/994-2.cpp create mode 100644 solutions/994. Rotting Oranges/994.cpp create mode 100644 solutions/995. Minimum Number of K Consecutive Bit Flips/995.cpp create mode 100644 solutions/995. Minimum Number of K Consecutive Bit Flips/995.java create mode 100644 solutions/995. Minimum Number of K Consecutive Bit Flips/995.py create mode 100644 solutions/996. Number of Squareful Arrays/996.cpp create mode 100644 solutions/996. Number of Squareful Arrays/996.java create mode 100644 solutions/996. Number of Squareful Arrays/996.py create mode 100644 solutions/997. Find the Town Judge/997.cpp create mode 100644 solutions/997. Find the Town Judge/997.java create mode 100644 solutions/997. Find the Town Judge/997.py create mode 100644 solutions/998. Maximum Binary Tree II/998-2.cpp create mode 100644 solutions/998. Maximum Binary Tree II/998-2.java create mode 100644 solutions/998. Maximum Binary Tree II/998-2.py create mode 100644 solutions/998. Maximum Binary Tree II/998.cpp create mode 100644 solutions/998. Maximum Binary Tree II/998.java create mode 100644 solutions/998. Maximum Binary Tree II/998.py create mode 100644 solutions/999. Available Captures for Rook/999.cpp create mode 100644 solutions/999. Available Captures for Rook/999.java create mode 100644 solutions/999. Available Captures for Rook/999.py diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000..d97df5f8a9b --- /dev/null +++ b/.clang-format @@ -0,0 +1,21 @@ +--- +Language: Cpp +BasedOnStyle: Google +AllowShortBlocksOnASingleLine: Empty +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlignTrailingComments: true +ColumnLimit: 80 +DerivePointerAlignment: false +LambdaBodyIndentation: OuterScope +--- +Language: Java +AllowShortBlocksOnASingleLine: Empty +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlignTrailingComments: true +ColumnLimit: 100 +IndentCaseLabels: true +SpaceAfterCStyleCast: true diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml new file mode 100644 index 00000000000..03c8f701ce0 --- /dev/null +++ b/.github/workflows/main.yaml @@ -0,0 +1,92 @@ +name: LeetCode Workflow + +# This workflow does the following: +# 1. Update the README with the latest progress. +# 2. Reset the commit history. +# 3. Build the *.md files by the code files and deploy with Mkdocs. + +on: + push: + branches: [main] + +jobs: + LeetFlow: + runs-on: ubuntu-latest + steps: + - name: Checkout LeetCode + uses: actions/checkout@v4 + with: + repository: walkccc/LeetCode + path: LeetCode + ref: main + + - name: Checkout LeetFlow + uses: actions/checkout@v4 + with: + repository: walkccc/LeetFlow + path: LeetFlow + ref: main + token: ${{ secrets.ACCESS_TOKEN }} + + - name: Run FlareSolverr Docker container + run: | + docker run -d \ + --name=flaresolverr \ + -p 8191:8191 \ + -e LOG_LEVEL=info \ + --restart unless-stopped \ + ghcr.io/flaresolverr/flaresolverr:latest + + - name: Set up Node v20 + uses: actions/setup-node@v4 + with: + node-version: 20.11.0 + + - name: Write README.md and Mkdocs *.md files + run: | + cd LeetFlow + npm install + npm run build -- --topic all + env: + CLIENT_EMAIL: ${{ secrets.CLIENT_EMAIL }} + PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }} + + - name: Reset the commit history + run: | + cd LeetCode + git checkout --orphan orphan + git add --all + git config user.name "Peng-Yu Chen" + git config user.email $EMAIL + git commit -m 'LeetCode' + git branch -D main + git branch -m main + git push origin main -f + env: + EMAIL: ${{ secrets.EMAIL }} + ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} + + - name: Set up Python 3.12 + uses: actions/setup-python@v4 + with: + python-version: '3.12' + architecture: 'x64' + cache: 'pip' + + - name: Install Python dependencies + run: | + python3 -m pip install --upgrade pip + python3 -m pip install -r LeetFlow/requirements.txt + + - name: Build LeetFlow/mkdocs to LeetFlow/site + run: mkdocs build -f LeetFlow/mkdocs/mkdocs.yml + + - name: Deploy with Mkdocs + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: LeetFlow/mkdocs/site + publish_branch: gh-pages + force_orphan: true + user_name: 'github-actions[bot]' + user_email: 'github-actions[bot]@users.noreply.github.com' diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000000..d43f2f48746 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,13 @@ +{ + "printWidth": 80, + "proseWrap": "always", + "singleQuote": true, + "overrides": [ + { + "files": "*.md", + "options": { + "parser": "markdown" + } + } + ] +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000000..58a67a6d0a4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Peng-Yu Chen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 00000000000..ff297d74ef6 --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +
+LeetCode +

LeetCode Solutions

+💡 Solutions to LeetCode in C++20, Java, Python, MySQL, and TypeScript. This repository aims to provide code with good readability and consistent style over various topics and embraces new standards. +
+
+Solved Percentage +
+Easy AC Count +Medium AC Count +Hard AC Count +
+ +## Getting Started + +See the built page here: [LeetCode Solutions](https://walkccc.me/LeetCode/). + +## Coding Style and Naming + +Please see the [style guide](https://walkccc.me/LeetCode/styleguide/). + +## Formatting + +| Language | Formatter | Style Guide | Configuration | +| ---------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| C++ | [ClangFormat](https://clang.llvm.org/docs/ClangFormat.html) | [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) | [`.clang-format`](https://github.com/walkccc/LeetCode/blob/main/.clang-format) | +| Java | [ClangFormat](https://clang.llvm.org/docs/ClangFormat.html) | [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html) | [`.clang-format`](https://github.com/walkccc/LeetCode/blob/main/.clang-format) | +| Python | [`autopep8`](https://pypi.org/project/autopep8) | [PEP 8 – Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) | Passing `--indent-size=2` for a better viewing experience in mobile devices. | +| TypeScript | [Prettier](https://prettier.io) | [Google TypeScript Style Guide](https://google.github.io/styleguide/tsguide.html) | [`.prettierrc`](https://github.com/walkccc/LeetCode/blob/main/.prettierrc) | +| MySQL | N/A | N/A | N/A | + +## Fun Facts + +This website went live on February 23, 2019. + +## License + +Licensed under the MIT License, Copyright © 2019-2024 +[P.-Y. Chen](https://github.com/walkccc). + +
+ Assembled with ❤️ in New York. +
diff --git a/STYLEGUIDE.md b/STYLEGUIDE.md new file mode 100644 index 00000000000..f018354bbcb --- /dev/null +++ b/STYLEGUIDE.md @@ -0,0 +1,517 @@ +# Style Guide + +> This document has been reviewed and discussed with +> [@hsins](https://github.com/hsins). +> +> For further reading, please see the definition of +> [Convention over configuration in Wikipedia](https://en.wikipedia.org/wiki/Convention_over_configuration). + +## Disclaimer + +### General + +- In our coding convention, we use `lowerCamelCase` for both functions and + variables. While this may deviate from the rules laid out in the + [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#General_Naming_Rules) + and + [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#naming-conventions), + it is done to maintain consistency with the LeetCode OJ system, which employs + `lowerCamelCase` for over 99% of the time. Remember, the most important thing + is to be consistent at all times. +- In code snippets, import statements and brackets may be omitted for brevity + (arguably), but they should be retained in real-world coding situations for + clarity and maintainability. + +### C++ + +- The code is only for demonstration and cannot be compiled. +- Explicitly declaring types such as `int`, `char`, and `string` is often + preferable over using the `auto` keyword introduced in C++ 11. +- `#include` statements are omitted in code snippets for brevity. +- Understanding the difference between `size_t` and `int` is crucial when + traversing arrays in practical applications, as it can affect the outcome. +- Qualifying with `std::` prefix when accessing standard libraries is + recommended for readability and maintainability in real-world coding + situations, as it clearly indicates the source of the identifier being used. + +### Java + +- The code is only for demonstration and cannot be compiled. +- Explicitly declaring types such as `int`, `char`, and `String` is often + preferable over using the `var` keyword introduced Java 10. +- `import` statements are omitted in code snippets for brevity. + +### Python + +- Private functions are prefixed with `_`, which may seem tedious. However, in + the real world, we use tools like [Mypy](https://github.com/python/mypy), + [Pytype](https://github.com/google/pytype), and + [Pyre](https://github.com/facebook/pyre-check) for static type checking. +- We pass the argument `--indent-size=2` to + [autopep8](https://pypi.org/project/autopep8/) for a better viewing + experience. +- `import` statements are omitted in code snippets for brevity. + +### SQL + +- The naming of LeetCode is quite a mess and inconsistently uses plurals and + singulars together. I'll use my best judgment to name tables in + `UpperCamelCase` in the plural form and fields in `lower_snake_case`. +- Proper indentation will be taken care of and treated seriously. +- No puzzling table abbreviation. + +## Naming Cases + +### Rules + +- **Class**: `UpperCamelCase` +- **Function**: `lowerCamelCase` +- **Variable**: `lowerCamelCase` +- **Constant**: `kUpperCamelCase` + +### Examples in C++ + +```cpp +// Class +class MyClass { ... } + +// Function +function myFunction() { ... } + +// Variable +int myVariable; + +// Constant +constexpr int kMod = 1'000'000'007; +``` + +## Template + +> We use C++ to demonstrate the idea, and the same concepts apply to Java and +> Python. + +### Rules + +- Declare the variables in the proper scope as slow as possible. + + - Declare `constexprt` as soon as possible. + - Declare `const` variables as soon as possible. + - Declare `ans` as soon as possible. + - Since LeetCode is just an online judge system rather than a big project, we + don't scatter all variables in different sections. However, we still sort + the variables based on the time we first use each of them. + +- Code section (there should be one blank line between each sections.) + + - `public` + + 1. boundary conditions + 1. initial variables + 1. There may be many kernels separated with one blank line, but there + shouldn't be any blank line in each kernel. + 1. return + + - `private` + + 1. private variables + 1. private functions + +## Schematic Template + +> We use C++ to demonstrate the idea, and the same concepts apply to Java and +> Python. + +- No blank lines between variables initialization. +- Blank one single line between each section. **However, if there's no sec 12**, + no blank line between **sec 11** and **sec 13**. +- If the last statement is not a paragraph (`for` loop most of the case), then + no blank lines between it and the `return` statement. + +```cpp +class Solution { + public: + func() { + // (sec 0) boundary conditions + + // (sec 1) initial variables + // (sec 10) constexpr/const (size/length) + // (sec 11) ans + // (sec 12) declaration & operation + // (sec 13) purely declaration + + // (sec 2) kernels + + // (sec 3) modify original initial variables + + // (sec 4) kernels + + // (sec n) return + } + + private: + // private variables + + // private functions + helper() { ... } + + anotherHelper() { ... } +}; +``` + +Example +([873. Length of Longest Fibonacci Subsequence](https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/)): + +- code: + + ```cpp + class Solution { + public: + int lenLongestFibSubseq(vector& arr) { + const int n = arr.size(); + int ans = 0; + vector> dp(n, vector(n, 2)); + unordered_map numToIndex; + + for (int i = 0; i < n; ++i) + numToIndex[arr[i]] = i; + + for (int j = 0; j < n; ++j) + for (int k = j + 1; k < n; ++k) { + const int ai = arr[k] - arr[j]; + if (ai < arr[j] && numToIndex.contains(ai)) { + const int i = numToIndex[ai]; + dp[j][k] = dp[i][j] + 1; + ans = max(ans, dp[j][k]); + } + } + + return ans; + } + }; + ``` + +- code (explanation): + + ```cpp + class Solution { + public: + int lenLongestFibSubseq(vector& arr) { + // Only get the value of size() or length() when we use it twice or more times. + // Remember to add `const` whenever possible. + const int n = arr.size(); + int ans = 0; + vector> dp(n, vector(n, 2)); + unordered_map numToIndex; + + for (int i = 0; i < n; ++i) + numToIndex[arr[i]] = i; + + for (int j = 0; j < n; ++j) + for (int k = j + 1; k < n; ++k) { + const int ai = arr[k] - arr[j]; // Add `const`. + if (ai < arr[j] && numToIndex.contains(ai)) { + const int i = numToIndex[ai]; // Add `const`. + dp[j][k] = dp[i][j] + 1; + ans = max(ans, dp[j][k]); + } + } + + return ans; + } + }; + ``` + +## Boundary Conditions + +```cpp +// Linked-List +if (l1 == nullptr && l2 == nullptr) { ... } +if (l1 != nullptr || l2 != nullptr) { ... } + +// String +if (str.empty()) { ... } +if (str.length() <= 2) { ... } + +// Vector +if (vec.size() <= 2) { ... } +``` + +## Return Value + +```cpp +return ans; +return {}; +``` + +## Data Structures + +```cpp +// C++ +unordered_set seen; +unordered_map count; +vector count; +stack stack; +queue q; +deque minQ; +auto compare = [](const ListNode* a, const ListNode* b) { + return a->val > b->val; +}; +priority_queue, decltype(compare)> minHeap(compare); +``` + +```java +// Java +Set seen = new HashSet<>(); +Map count = new HashMap<>(); +int[] count = new int[n]; +Deque stack = new ArrayDeque<>(); // Do not use `Stack`. +Queue q = new LinkedList<>(); +Deque minQ = new ArrayDeque<>(); +Queue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val); +``` + +```python +# Python +seen = set() +count = {} +count = collections.defaultdict(int) +count = collections.defaultdict(list) +count = collections.Counter() +minQ = collections.deque([root]) +stack = [] +minHeap = [] +``` + +## Two Pointers / Sliding Windows + +1. Always prefer to _one_ character to represent index variables. +1. Use `i`, `j`, `k` in the loop, in that order. + +```cpp +int i = 0; +for (const int num : nums) { ... } +``` + +```cpp +for (int i = 0, j = 0; i < n; ++i) { ... } +``` + +```cpp +int k = 0; +for (int i = 0; i < n; ++i) + for (int j = i; j < n; ++j) { ... } +``` + +```cpp +int l = 0; +int r = nums.size() - 1; +``` + +## Union Find + +```cpp +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(begin(id), end(id), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = id[j]; + } else if (rank[i] > rank[j]) { + id[j] = id[i]; + } else { + id[i] = id[j]; + ++rank[j]; + } + --count; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; +``` + +## Graph / Tree + +- If a graph has a clear tree structure, we name it a `tree`. Otherwise, we name + it a `graph`. +- Always use `(u, v)` to represent an edge regardless what is stated in the + problem. + +```cpp +vector> graph(n); + +for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); +} +``` + +## Dijkstra + +```cpp +void dijkstra(const vector>>& graph, int src) { + vector dist(graph.size(), INT_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(0, src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + } +} +``` + +## Binary Search + +1. Always prefer to _one_ character to represent index variables. +2. Always prefer to use `[l, r)` pattern. + +```cpp +int l = 0; +int r = nums.size(); + +while (l < r) { + const int m = l + (r - l) / 2; + if (f(m)) + l = m + 1; // new range [m + 1, r) + else + r = m; // new range [l, m) +} + +return l; +``` + +## ListNode + +```cpp +// Allocate the memory on the stack instead of the heap. +ListNode dummy(0); + +ListNode* curr; +ListNode* prev; +ListNode* next; + +ListNode* slow; +ListNode* fast; + +ListNode* head; +ListNode* tail; + +ListNode* l1; +ListNode* l2; +``` + +## 2D Vector / 2 Strings + +```cpp +// 2D Vector +const int m = matrix.size(); +const int n = matrix[0].size(); + +// If there're two strings. +const int m = str1.length(); +const int n = str2.length(); + +// If there's only a string. +const int n = str.length(); +``` + +## Traversing + +```cpp +// vector nums; +for (int i = 0; i < nums.size(); ++i) { ... } +for (const int num : nums) { ... } + +// vector words; +for (const string& word : words) { ... } + +// string str; +for (int i = 0; i < str.length(); ++i) { ... } +for (const char c : str) { ... } + +// unordered_set numsSet; +for (const int num : numsSet) { ... } + +// structured binding in C++17 +// unordered_map map; +for (const auto& [key, value] : map) { ... } + +// ListNode* head; +for (ListNode* curr = head; curr; curr = curr->next) { ... } +``` + +## Miscellaneous + +1. Always prefer to use `str.length()` over `str.size()`. +1. Always use _camelCase_ nomenclature when not listed above. + + ```cpp + // C++ + int currNum; + int maxProfit; + TreeNode* currNode; + ``` + +1. When there's confliction in expression and function or reserved key word: + + ```cpp + // C++ + mn, std::min() + mx, std::max() + ``` + + ```python + # Python + mn, min + mx, max + summ, sum + ``` + +1. When there are two maps/stacks, use meaningful names. + + ```cpp + // C++ + unordered_map countA; + unordered_map countB; + ``` + +1. When we need to count something, use `sum`, `count` and `total`, in that + order. +1. Initialize vector with `0` or `false` **implicitly**. +1. `constexpr` is used if possible. +1. `const` is used if possible. +1. `const auto` is used when we iterate through a `unordered_map` or `map`. +1. Use `&` whenever possible except `int` and `char` because reference typically + takes 4 bytes, while `int` takes 2/4 bytes and `char` takes 1 byte. +1. Prefer to name variables in a "adjective + noun" order. For example, + `maxLeft` is better than `leftMax`. +1. If a block is really small, for example, before a `bfs()` call, sometimes we + don't add extra blank lines. This is not a hard rule. diff --git a/solutions/1. Two Sum/1.cpp b/solutions/1. Two Sum/1.cpp new file mode 100644 index 00000000000..4e4a974cab8 --- /dev/null +++ b/solutions/1. Two Sum/1.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector twoSum(vector& nums, int target) { + unordered_map numToIndex; + + for (int i = 0; i < nums.size(); ++i) { + if (const auto it = numToIndex.find(target - nums[i]); + it != numToIndex.cend()) + return {it->second, i}; + numToIndex[nums[i]] = i; + } + + throw; + } +}; diff --git a/solutions/1. Two Sum/1.java b/solutions/1. Two Sum/1.java new file mode 100644 index 00000000000..e814c7e0057 --- /dev/null +++ b/solutions/1. Two Sum/1.java @@ -0,0 +1,13 @@ +class Solution { + public int[] twoSum(int[] nums, int target) { + Map numToIndex = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + if (numToIndex.containsKey(target - nums[i])) + return new int[] {numToIndex.get(target - nums[i]), i}; + numToIndex.put(nums[i], i); + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1. Two Sum/1.py b/solutions/1. Two Sum/1.py new file mode 100644 index 00000000000..4544ba0753a --- /dev/null +++ b/solutions/1. Two Sum/1.py @@ -0,0 +1,8 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + numToIndex = {} + + for i, num in enumerate(nums): + if target - num in numToIndex: + return numToIndex[target - num], i + numToIndex[num] = i diff --git a/solutions/10. Regular Expression Matching/10.cpp b/solutions/10. Regular Expression Matching/10.cpp new file mode 100644 index 00000000000..dd0c863fc84 --- /dev/null +++ b/solutions/10. Regular Expression Matching/10.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + bool isMatch(string s, string p) { + const int m = s.length(); + const int n = p.length(); + // dp[i][j] := true if s[0..i) matches p[0..j) + vector> dp(m + 1, vector(n + 1)); + dp[0][0] = true; + + auto isMatch = [&](int i, int j) -> bool { + return j >= 0 && p[j] == '.' || s[i] == p[j]; + }; + + for (int j = 0; j < p.length(); ++j) + if (p[j] == '*' && dp[0][j - 1]) + dp[0][j + 1] = true; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (p[j] == '*') { + // The minimum index of '*' is 1. + const bool noRepeat = dp[i + 1][j - 1]; + const bool doRepeat = isMatch(i, j - 1) && dp[i][j + 1]; + dp[i + 1][j + 1] = noRepeat || doRepeat; + } else if (isMatch(i, j)) { + dp[i + 1][j + 1] = dp[i][j]; + } + + return dp[m][n]; + } +}; diff --git a/solutions/10. Regular Expression Matching/10.java b/solutions/10. Regular Expression Matching/10.java new file mode 100644 index 00000000000..a02d6d09569 --- /dev/null +++ b/solutions/10. Regular Expression Matching/10.java @@ -0,0 +1,30 @@ +class Solution { + public boolean isMatch(String s, String p) { + final int m = s.length(); + final int n = p.length(); + // dp[i][j] := true if s[0..i) matches p[0..j) + boolean[][] dp = new boolean[m + 1][n + 1]; + dp[0][0] = true; + + for (int j = 0; j < p.length(); ++j) + if (p.charAt(j) == '*' && dp[0][j - 1]) + dp[0][j + 1] = true; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (p.charAt(j) == '*') { + // The minimum index of '*' is 1. + final boolean noRepeat = dp[i + 1][j - 1]; + final boolean doRepeat = isMatch(s, i, p, j - 1) && dp[i][j + 1]; + dp[i + 1][j + 1] = noRepeat || doRepeat; + } else if (isMatch(s, i, p, j)) { + dp[i + 1][j + 1] = dp[i][j]; + } + + return dp[m][n]; + } + + private boolean isMatch(final String s, int i, final String p, int j) { + return j >= 0 && p.charAt(j) == '.' || s.charAt(i) == p.charAt(j); + } +} diff --git a/solutions/10. Regular Expression Matching/10.py b/solutions/10. Regular Expression Matching/10.py new file mode 100644 index 00000000000..244096b89ff --- /dev/null +++ b/solutions/10. Regular Expression Matching/10.py @@ -0,0 +1,26 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + m = len(s) + n = len(p) + # dp[i][j] := True if s[0..i) matches p[0..j) + dp = [[False] * (n + 1) for _ in range(m + 1)] + dp[0][0] = True + + def isMatch(i: int, j: int) -> bool: + return j >= 0 and p[j] == '.' or s[i] == p[j] + + for j, c in enumerate(p): + if c == '*' and dp[0][j - 1]: + dp[0][j + 1] = True + + for i in range(m): + for j in range(n): + if p[j] == '*': + # The minimum index of '*' is 1. + noRepeat = dp[i + 1][j - 1] + doRepeat = isMatch(i, j - 1) and dp[i][j + 1] + dp[i + 1][j + 1] = noRepeat or doRepeat + elif isMatch(i, j): + dp[i + 1][j + 1] = dp[i][j] + + return dp[m][n] diff --git a/solutions/100. Same Tree/100.cpp b/solutions/100. Same Tree/100.cpp new file mode 100644 index 00000000000..27f9ed528f2 --- /dev/null +++ b/solutions/100. Same Tree/100.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (!p || !q) + return p == q; + return p->val == q->val && // + isSameTree(p->left, q->left) && // + isSameTree(p->right, q->right); + } +}; diff --git a/solutions/100. Same Tree/100.java b/solutions/100. Same Tree/100.java new file mode 100644 index 00000000000..b7187299ee2 --- /dev/null +++ b/solutions/100. Same Tree/100.java @@ -0,0 +1,9 @@ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null || q == null) + return p == q; + return p.val == q.val && // + isSameTree(p.left, q.left) && // + isSameTree(p.right, q.right); + } +} diff --git a/solutions/100. Same Tree/100.py b/solutions/100. Same Tree/100.py new file mode 100644 index 00000000000..157630466bb --- /dev/null +++ b/solutions/100. Same Tree/100.py @@ -0,0 +1,7 @@ +class Solution: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + if not p or not q: + return p == q + return p.val == q.val and \ + self.isSameTree(p.left, q.left) and \ + self.isSameTree(p.right, q.right) diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000-2.cpp b/solutions/1000. Minimum Cost to Merge Stones/1000-2.cpp new file mode 100644 index 00000000000..00da48b22da --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int mergeStones(vector& stones, int K) { + const int n = stones.size(); + if ((n - 1) % (K - 1)) + return -1; + + constexpr int kMax = 1'000'000'000; + // dp[i][j][k] := the minimum cost to merge stones[i..j] into k piles + vector>> dp( + n, vector>(n, vector(K + 1, kMax))); + vector prefix(n + 1); + + for (int i = 0; i < n; ++i) + dp[i][i][1] = 0; + + partial_sum(stones.begin(), stones.end(), prefix.begin() + 1); + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + for (int k = 2; k <= K; ++k) + for (int m = i; m < j; m += K - 1) + dp[i][j][k] = min(dp[i][j][k], dp[i][m][1] + dp[m + 1][j][k - 1]); + dp[i][j][1] = dp[i][j][K] + prefix[j + 1] - prefix[i]; + } + + return dp[0][n - 1][1]; + } +}; diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000-2.java b/solutions/1000. Minimum Cost to Merge Stones/1000-2.java new file mode 100644 index 00000000000..4b772c120bf --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000-2.java @@ -0,0 +1,31 @@ +class Solution { + public int mergeStones(int[] stones, int K) { + final int n = stones.length; + if ((n - 1) % (K - 1) != 0) + return -1; + + final int kMax = 1_000_000_000; + // dp[i][j][k] := the minimum cost to merge stones[i..j] into k piles + int[][][] dp = new int[n][n][K + 1]; + for (int[][] A : dp) + Arrays.stream(A).forEach(a -> Arrays.fill(a, kMax)); + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; ++i) + dp[i][i][1] = 0; + + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + stones[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + for (int k = 2; k <= K; ++k) + for (int m = i; m < j; m += K - 1) + dp[i][j][k] = Math.min(dp[i][j][k], dp[i][m][1] + dp[m + 1][j][k - 1]); + dp[i][j][1] = dp[i][j][K] + prefix[j + 1] - prefix[i]; + } + + return dp[0][n - 1][1]; + } +} diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000-3.cpp b/solutions/1000. Minimum Cost to Merge Stones/1000-3.cpp new file mode 100644 index 00000000000..299cc28754f --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000-3.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int mergeStones(vector& stones, int k) { + const int n = stones.size(); + if ((n - 1) % (k - 1)) + return -1; + + vector> mem(n, vector(n, kMax)); + vector prefix(n + 1); + + partial_sum(stones.begin(), stones.end(), prefix.begin() + 1); + const int cost = mergeStones(stones, 0, n - 1, k, prefix, mem); + return cost == kMax ? -1 : cost; + } + + private: + static constexpr int kMax = 1'000'000'000; + + // Returns the minimum cost to merge stones[i..j]. + int mergeStones(const vector& stones, int i, int j, int k, + const vector& prefix, vector>& mem) { + if (j - i + 1 < k) + return 0; + if (mem[i][j] != kMax) + return mem[i][j]; + + for (int m = i; m < j; m += k - 1) + mem[i][j] = + min(mem[i][j], mergeStones(stones, i, m, k, prefix, mem) + + mergeStones(stones, m + 1, j, k, prefix, mem)); + if ((j - i) % (k - 1) == 0) + mem[i][j] += prefix[j + 1] - prefix[i]; + + return mem[i][j]; + } +}; diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000-3.java b/solutions/1000. Minimum Cost to Merge Stones/1000-3.java new file mode 100644 index 00000000000..7c8d2e003e4 --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000-3.java @@ -0,0 +1,36 @@ +class Solution { + public int mergeStones(int[] stones, int k) { + final int n = stones.length; + if ((n - 1) % (k - 1) != 0) + return -1; + + int[][] mem = new int[n][n]; + int[] prefix = new int[n + 1]; + + Arrays.stream(mem).forEach(A -> Arrays.fill(A, kMax)); + + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + stones[i]; + + final int cost = mergeStones(stones, 0, n - 1, k, prefix, mem); + return cost == kMax ? -1 : cost; + } + + private static final int kMax = 1_000_000_000; + + // Returns the minimum cost to merge stones[i..j]. + private int mergeStones(final int[] stones, int i, int j, int k, int[] prefix, int[][] mem) { + if (j - i + 1 < k) + return 0; + if (mem[i][j] != kMax) + return mem[i][j]; + + for (int m = i; m < j; m += k - 1) + mem[i][j] = Math.min(mem[i][j], mergeStones(stones, i, m, k, prefix, mem) + + mergeStones(stones, m + 1, j, k, prefix, mem)); + if ((j - i) % (k - 1) == 0) + mem[i][j] += prefix[j + 1] - prefix[i]; + + return mem[i][j]; + } +} diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000-4.cpp b/solutions/1000. Minimum Cost to Merge Stones/1000-4.cpp new file mode 100644 index 00000000000..5bd8ae35788 --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000-4.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int mergeStones(vector& stones, int K) { + const int n = stones.size(); + if ((n - 1) % (K - 1)) + return -1; + + constexpr int kMax = 1'000'000'000; + + // dp[i][j] := the minimum cost to merge stones[i..j] + vector> dp(n, vector(n, kMax)); + vector prefix(n + 1); + + for (int i = 0; i < n; ++i) + dp[i][i] = 0; + + partial_sum(stones.begin(), stones.end(), prefix.begin() + 1); + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + for (int m = i; m < j; m += K - 1) + dp[i][j] = min(dp[i][j], dp[i][m] + dp[m + 1][j]); + if (d % (K - 1) == 0) + dp[i][j] += prefix[j + 1] - prefix[i]; + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000-4.java b/solutions/1000. Minimum Cost to Merge Stones/1000-4.java new file mode 100644 index 00000000000..8561fc4bff9 --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000-4.java @@ -0,0 +1,31 @@ +class Solution { + public int mergeStones(int[] stones, int K) { + final int n = stones.length; + if ((n - 1) % (K - 1) != 0) + return -1; + + final int kMax = 1_000_000_000; + + // dp[i][j] := the minimum cost to merge stones[i..j] + int[][] dp = new int[n][n]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, kMax)); + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; ++i) + dp[i][i] = 0; + + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + stones[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + for (int m = i; m < j; m += K - 1) + dp[i][j] = Math.min(dp[i][j], dp[i][m] + dp[m + 1][j]); + if (d % (K - 1) == 0) + dp[i][j] += prefix[j + 1] - prefix[i]; + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000.cpp b/solutions/1000. Minimum Cost to Merge Stones/1000.cpp new file mode 100644 index 00000000000..a39c18a7d1e --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int mergeStones(vector& stones, int K) { + const int n = stones.size(); + vector>> mem( + n, vector>(n, vector(K + 1, kMax))); + vector prefix(n + 1); + partial_sum(stones.begin(), stones.end(), prefix.begin() + 1); + const int cost = mergeStones(stones, 0, n - 1, 1, K, prefix, mem); + return cost == kMax ? -1 : cost; + } + + private: + static constexpr int kMax = 1'000'000'000; + + // Returns the minimum cost to merge stones[i..j] into k piles. + int mergeStones(const vector& stones, int i, int j, int k, int K, + const vector& prefix, vector>>& mem) { + if ((j - i + 1 - k) % (K - 1)) + return kMax; + if (i == j) + return k == 1 ? 0 : kMax; + if (mem[i][j][k] != kMax) + return mem[i][j][k]; + if (k == 1) + return mem[i][j][k] = mergeStones(stones, i, j, K, K, prefix, mem) + + prefix[j + 1] - prefix[i]; + + for (int m = i; m < j; m += K - 1) + mem[i][j][k] = + min(mem[i][j][k], + mergeStones(stones, i, m, 1, K, prefix, mem) + + mergeStones(stones, m + 1, j, k - 1, K, prefix, mem)); + + return mem[i][j][k]; + } +}; diff --git a/solutions/1000. Minimum Cost to Merge Stones/1000.java b/solutions/1000. Minimum Cost to Merge Stones/1000.java new file mode 100644 index 00000000000..d3e559d0305 --- /dev/null +++ b/solutions/1000. Minimum Cost to Merge Stones/1000.java @@ -0,0 +1,39 @@ +class Solution { + public int mergeStones(int[] stones, int K) { + final int n = stones.length; + int[][][] mem = new int[n][n][K + 1]; + int[] prefix = new int[n + 1]; + + for (int[][] A : mem) + Arrays.stream(A).forEach(a -> Arrays.fill(a, kMax)); + + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + stones[i]; + + final int cost = mergeStones(stones, 0, n - 1, 1, K, prefix, mem); + return cost == kMax ? -1 : cost; + } + + private static final int kMax = 1_000_000_000; + + // Returns the minimum cost to merge stones[i..j] into k piles. + private int mergeStones(final int[] stones, int i, int j, int k, int K, int[] prefix, + int[][][] mem) { + if ((j - i + 1 - k) % (K - 1) != 0) + return kMax; + if (i == j) + return k == 1 ? 0 : kMax; + if (mem[i][j][k] != kMax) + return mem[i][j][k]; + if (k == 1) + return mem[i][j][k] = + mergeStones(stones, i, j, K, K, prefix, mem) + prefix[j + 1] - prefix[i]; + + for (int m = i; m < j; m += K - 1) + mem[i][j][k] = + Math.min(mem[i][j][k], mergeStones(stones, i, m, 1, K, prefix, mem) + + mergeStones(stones, m + 1, j, k - 1, K, prefix, mem)); + + return mem[i][j][k]; + } +} diff --git a/solutions/1001. Grid Illumination/1001.cpp b/solutions/1001. Grid Illumination/1001.cpp new file mode 100644 index 00000000000..3a66c1ec833 --- /dev/null +++ b/solutions/1001. Grid Illumination/1001.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + vector gridIllumination(int n, vector>& lamps, + vector>& queries) { + vector ans; + unordered_map rows; + unordered_map cols; + unordered_map diag1; + unordered_map diag2; + unordered_set, PairHash> lampsSet; + + for (vector& lamp : lamps) { + int i = lamp[0]; + int j = lamp[1]; + if (lampsSet.insert({i, j}).second) { + ++rows[i]; + ++cols[j]; + ++diag1[i + j]; + ++diag2[i - j]; + } + } + + for (const vector& query : queries) { + int i = query[0]; + int j = query[1]; + if (rows[i] || cols[j] || diag1[i + j] || diag2[i - j]) { + ans.push_back(1); + for (int y = max(0, i - 1); y < min(n, i + 2); ++y) + for (int x = max(0, j - 1); x < min(n, j + 2); ++x) + if (lampsSet.erase({y, x})) { + --rows[y]; + --cols[x]; + --diag1[y + x]; + --diag2[y - x]; + } + } else { + ans.push_back(0); + } + } + + return ans; + } + + private: + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/1001. Grid Illumination/1001.java b/solutions/1001. Grid Illumination/1001.java new file mode 100644 index 00000000000..5071c2b6cc9 --- /dev/null +++ b/solutions/1001. Grid Illumination/1001.java @@ -0,0 +1,46 @@ +class Solution { + public int[] gridIllumination(int n, int[][] lamps, int[][] queries) { + List ans = new ArrayList<>(); + Map rows = new HashMap<>(); + Map cols = new HashMap<>(); + Map diag1 = new HashMap<>(); + Map diag2 = new HashMap<>(); + Set lampsSet = new HashSet<>(); + + for (int[] lamp : lamps) { + final int i = lamp[0]; + final int j = lamp[1]; + if (lampsSet.add(hash(i, j))) { + rows.merge(i, 1, Integer::sum); + cols.merge(j, 1, Integer::sum); + diag1.merge(i + j, 1, Integer::sum); + diag2.merge(i - j, 1, Integer::sum); + } + } + + for (int[] query : queries) { + final int i = query[0]; + final int j = query[1]; + if (rows.getOrDefault(i, 0) > 0 || cols.getOrDefault(j, 0) > 0 || + diag1.getOrDefault(i + j, 0) > 0 || diag2.getOrDefault(i - j, 0) > 0) { + ans.add(1); + for (int y = Math.max(0, i - 1); y < Math.min(n, i + 2); ++y) + for (int x = Math.max(0, j - 1); x < Math.min(n, j + 2); ++x) + if (lampsSet.remove(hash(y, x))) { + rows.merge(y, 1, Integer::sum); + cols.merge(x, 1, Integer::sum); + diag1.merge(y + x, 1, Integer::sum); + diag2.merge(y - x, 1, Integer::sum); + } + } else { + ans.add(0); + } + } + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private long hash(int i, int j) { + return ((long) i << 32) + j; + } +} diff --git a/solutions/1001. Grid Illumination/1001.py b/solutions/1001. Grid Illumination/1001.py new file mode 100644 index 00000000000..fbfe26ccaac --- /dev/null +++ b/solutions/1001. Grid Illumination/1001.py @@ -0,0 +1,32 @@ +class Solution: + def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]: + ans = [] + rows = collections.Counter() + cols = collections.Counter() + diag1 = collections.Counter() + diag2 = collections.Counter() + lampsSet = set() + + for i, j in lamps: + if (i, j) not in lampsSet: + lampsSet.add((i, j)) + rows[i] += 1 + cols[j] += 1 + diag1[i + j] += 1 + diag2[i - j] += 1 + + for i, j in queries: + if rows[i] or cols[j] or diag1[i + j] or diag2[i - j]: + ans.append(1) + for y in range(max(0, i - 1), min(n, i + 2)): + for x in range(max(0, j - 1), min(n, j + 2)): + if (y, x) in lampsSet: + lampsSet.remove((y, x)) + rows[y] -= 1 + cols[x] -= 1 + diag1[y + x] -= 1 + diag2[y - x] -= 1 + else: + ans.append(0) + + return ans diff --git a/solutions/1002. Find Common Characters/1002.cpp b/solutions/1002. Find Common Characters/1002.cpp new file mode 100644 index 00000000000..687f01cb53b --- /dev/null +++ b/solutions/1002. Find Common Characters/1002.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector commonChars(vector& words) { + vector ans; + vector commonCount(26, INT_MAX); + + for (const string& word : words) { + vector count(26); + for (const char c : word) + ++count[c - 'a']; + for (int i = 0; i < 26; ++i) + commonCount[i] = min(commonCount[i], count[i]); + } + + for (char c = 'a'; c <= 'z'; ++c) + for (int i = 0; i < commonCount[c - 'a']; ++i) + ans.push_back(string(1, c)); + + return ans; + } +}; diff --git a/solutions/1002. Find Common Characters/1002.java b/solutions/1002. Find Common Characters/1002.java new file mode 100644 index 00000000000..7164a5df817 --- /dev/null +++ b/solutions/1002. Find Common Characters/1002.java @@ -0,0 +1,21 @@ +class Solution { + public List commonChars(String[] words) { + List ans = new ArrayList<>(); + int[] commonCount = new int[26]; + Arrays.fill(commonCount, Integer.MAX_VALUE); + + for (final String word : words) { + int[] count = new int[26]; + for (final char c : word.toCharArray()) + ++count[c - 'a']; + for (int i = 0; i < 26; ++i) + commonCount[i] = Math.min(commonCount[i], count[i]); + } + + for (char c = 'a'; c <= 'z'; ++c) + for (int i = 0; i < commonCount[c - 'a']; ++i) + ans.add(String.valueOf(c)); + + return ans; + } +} diff --git a/solutions/1002. Find Common Characters/1002.py b/solutions/1002. Find Common Characters/1002.py new file mode 100644 index 00000000000..3f9c549a874 --- /dev/null +++ b/solutions/1002. Find Common Characters/1002.py @@ -0,0 +1,4 @@ +class Solution: + def commonChars(self, words: List[str]) -> List[str]: + return functools.reduce(lambda a, b: a & b, + map(collections.Counter, words)).elements() diff --git a/solutions/1003. Check If Word Is Valid After Substitutions/1003.cpp b/solutions/1003. Check If Word Is Valid After Substitutions/1003.cpp new file mode 100644 index 00000000000..49600d12a61 --- /dev/null +++ b/solutions/1003. Check If Word Is Valid After Substitutions/1003.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool isValid(string s) { + stack stack; + + for (const char c : s) + if (c == 'c') { + if (stack.size() < 2) + return false; + if (stack.top() != 'b') + return false; + stack.pop(); + if (stack.top() != 'a') + return false; + stack.pop(); + } else { + stack.push(c); + } + + return stack.empty(); + } +}; diff --git a/solutions/1003. Check If Word Is Valid After Substitutions/1003.java b/solutions/1003. Check If Word Is Valid After Substitutions/1003.java new file mode 100644 index 00000000000..4812286ad31 --- /dev/null +++ b/solutions/1003. Check If Word Is Valid After Substitutions/1003.java @@ -0,0 +1,21 @@ +class Solution { + public boolean isValid(String s) { + Deque stack = new ArrayDeque<>(); + + for (final char c : s.toCharArray()) + if (c == 'c') { + if (stack.size() < 2) + return false; + if (stack.peek() != 'b') + return false; + stack.pop(); + if (stack.peek() != 'a') + return false; + stack.pop(); + } else { + stack.push(c); + } + + return stack.isEmpty(); + } +} diff --git a/solutions/1003. Check If Word Is Valid After Substitutions/1003.py b/solutions/1003. Check If Word Is Valid After Substitutions/1003.py new file mode 100644 index 00000000000..1b33c2a28c4 --- /dev/null +++ b/solutions/1003. Check If Word Is Valid After Substitutions/1003.py @@ -0,0 +1,14 @@ +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + + for c in s: + if c == 'c': + if len(stack) < 2 or stack[-2] != 'a' or stack[-1] != 'b': + return False + stack.pop() + stack.pop() + else: + stack.append(c) + + return not stack diff --git a/solutions/1004. Max Consecutive Ones III/1004.cpp b/solutions/1004. Max Consecutive Ones III/1004.cpp new file mode 100644 index 00000000000..ab147df3d06 --- /dev/null +++ b/solutions/1004. Max Consecutive Ones III/1004.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int longestOnes(vector& nums, int k) { + int ans = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (nums[r] == 0) + --k; + while (k < 0) + if (nums[l++] == 0) + ++k; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/1004. Max Consecutive Ones III/1004.java b/solutions/1004. Max Consecutive Ones III/1004.java new file mode 100644 index 00000000000..39ad595146e --- /dev/null +++ b/solutions/1004. Max Consecutive Ones III/1004.java @@ -0,0 +1,16 @@ +class Solution { + public int longestOnes(int[] nums, int k) { + int ans = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (nums[r] == 0) + --k; + while (k < 0) + if (nums[l++] == 0) + ++k; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/1004. Max Consecutive Ones III/1004.py b/solutions/1004. Max Consecutive Ones III/1004.py new file mode 100644 index 00000000000..3aa427dc212 --- /dev/null +++ b/solutions/1004. Max Consecutive Ones III/1004.py @@ -0,0 +1,15 @@ +class Solution: + def longestOnes(self, nums: List[int], k: int) -> int: + ans = 0 + + l = 0 + for r, num in enumerate(nums): + if num == 0: + k -= 1 + while k < 0: + if nums[l] == 0: + k += 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/1005. Maximize Sum Of Array After K Negations/1005.cpp b/solutions/1005. Maximize Sum Of Array After K Negations/1005.cpp new file mode 100644 index 00000000000..74a22f19cf2 --- /dev/null +++ b/solutions/1005. Maximize Sum Of Array After K Negations/1005.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int largestSumAfterKNegations(vector& nums, int k) { + ranges::sort(nums); + + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] > 0 || k == 0) + break; + nums[i] = -nums[i]; + --k; + } + + return accumulate(nums.begin(), nums.end(), 0) - + (k % 2) * ranges::min(nums) * 2; + } +}; diff --git a/solutions/1005. Maximize Sum Of Array After K Negations/1005.java b/solutions/1005. Maximize Sum Of Array After K Negations/1005.java new file mode 100644 index 00000000000..8b28a5b854d --- /dev/null +++ b/solutions/1005. Maximize Sum Of Array After K Negations/1005.java @@ -0,0 +1,14 @@ +class Solution { + public int largestSumAfterKNegations(int[] nums, int k) { + Arrays.sort(nums); + + for (int i = 0; i < nums.length; ++i) { + if (nums[i] > 0 || k == 0) + break; + nums[i] = -nums[i]; + --k; + } + + return Arrays.stream(nums).sum() - (k % 2) * Arrays.stream(nums).min().getAsInt() * 2; + } +} diff --git a/solutions/1005. Maximize Sum Of Array After K Negations/1005.py b/solutions/1005. Maximize Sum Of Array After K Negations/1005.py new file mode 100644 index 00000000000..b9d740d444a --- /dev/null +++ b/solutions/1005. Maximize Sum Of Array After K Negations/1005.py @@ -0,0 +1,11 @@ +class Solution: + def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: + nums.sort() + + for i, num in enumerate(nums): + if num > 0 or k == 0: + break + nums[i] = -num + k -= 1 + + return sum(nums) - (k % 2) * min(nums) * 2 diff --git a/solutions/1006. Clumsy Factorial/1006.cpp b/solutions/1006. Clumsy Factorial/1006.cpp new file mode 100644 index 00000000000..fd612dcc228 --- /dev/null +++ b/solutions/1006. Clumsy Factorial/1006.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int clumsy(int n) { + if (n == 1) + return 1; + if (n == 2) + return 2; + if (n == 3) + return 6; + if (n == 4) + return 7; + if (n % 4 == 1) + return n + 2; + if (n % 4 == 2) + return n + 2; + if (n % 4 == 3) + return n - 1; + return n + 1; + } +}; diff --git a/solutions/1006. Clumsy Factorial/1006.java b/solutions/1006. Clumsy Factorial/1006.java new file mode 100644 index 00000000000..a8451d99dd6 --- /dev/null +++ b/solutions/1006. Clumsy Factorial/1006.java @@ -0,0 +1,19 @@ +class Solution { + public int clumsy(int n) { + if (n == 1) + return 1; + if (n == 2) + return 2; + if (n == 3) + return 6; + if (n == 4) + return 7; + if (n % 4 == 1) + return n + 2; + if (n % 4 == 2) + return n + 2; + if (n % 4 == 3) + return n - 1; + return n + 1; + } +} diff --git a/solutions/1006. Clumsy Factorial/1006.py b/solutions/1006. Clumsy Factorial/1006.py new file mode 100644 index 00000000000..032e467171d --- /dev/null +++ b/solutions/1006. Clumsy Factorial/1006.py @@ -0,0 +1,17 @@ +class Solution: + def clumsy(self, n: int) -> int: + if n == 1: + return 1 + if n == 2: + return 2 + if n == 3: + return 6 + if n == 4: + return 7 + if n % 4 == 1: + return n + 2 + if n % 4 == 2: + return n + 2 + if n % 4 == 3: + return n - 1 + return n + 1 diff --git a/solutions/1007. Minimum Domino Rotations For Equal Row/1007.cpp b/solutions/1007. Minimum Domino Rotations For Equal Row/1007.cpp new file mode 100644 index 00000000000..adb69e698df --- /dev/null +++ b/solutions/1007. Minimum Domino Rotations For Equal Row/1007.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minDominoRotations(vector& tops, vector& bottoms) { + const int n = tops.size(); + vector countTops(7); + vector countBottoms(7); + vector countBoth(7); + + for (int i = 0; i < n; ++i) { + ++countTops[tops[i]]; + ++countBottoms[bottoms[i]]; + if (tops[i] == bottoms[i]) + ++countBoth[tops[i]]; + } + + for (int i = 1; i <= 6; ++i) + if (countTops[i] + countBottoms[i] - countBoth[i] == n) + return n - max(countTops[i], countBottoms[i]); + + return -1; + } +}; diff --git a/solutions/1007. Minimum Domino Rotations For Equal Row/1007.java b/solutions/1007. Minimum Domino Rotations For Equal Row/1007.java new file mode 100644 index 00000000000..432935924f7 --- /dev/null +++ b/solutions/1007. Minimum Domino Rotations For Equal Row/1007.java @@ -0,0 +1,21 @@ +class Solution { + public int minDominoRotations(int[] tops, int[] bottoms) { + final int n = tops.length; + int[] countTops = new int[7]; + int[] countBottoms = new int[7]; + int[] countBoth = new int[7]; + + for (int i = 0; i < n; ++i) { + ++countTops[tops[i]]; + ++countBottoms[bottoms[i]]; + if (tops[i] == bottoms[i]) + ++countBoth[tops[i]]; + } + + for (int i = 1; i <= 6; ++i) + if (countTops[i] + countBottoms[i] - countBoth[i] == n) + return n - Math.max(countTops[i], countBottoms[i]); + + return -1; + } +} diff --git a/solutions/1007. Minimum Domino Rotations For Equal Row/1007.py b/solutions/1007. Minimum Domino Rotations For Equal Row/1007.py new file mode 100644 index 00000000000..4b44b265450 --- /dev/null +++ b/solutions/1007. Minimum Domino Rotations For Equal Row/1007.py @@ -0,0 +1,6 @@ +class Solution: + def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: + for num in range(1, 7): + if all(num in pair for pair in zip(tops, bottoms)): + return len(tops) - max(tops.count(num), bottoms.count(num)) + return -1 diff --git a/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.cpp b/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.cpp new file mode 100644 index 00000000000..9d675407ec5 --- /dev/null +++ b/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + TreeNode* bstFromPreorder(vector& preorder) { + TreeNode* root = new TreeNode(preorder[0]); + stack stack{{root}}; + + for (int i = 1; i < preorder.size(); ++i) { + TreeNode* parent = stack.top(); + TreeNode* child = new TreeNode(preorder[i]); + // Adjust the parent. + while (!stack.empty() && stack.top()->val < child->val) + parent = stack.top(), stack.pop(); + // Create parent-child link according to BST property. + if (parent->val > child->val) + parent->left = child; + else + parent->right = child; + stack.push(child); + } + + return root; + } +}; diff --git a/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.java b/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.java new file mode 100644 index 00000000000..50c6972d3dd --- /dev/null +++ b/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.java @@ -0,0 +1,22 @@ +class Solution { + public TreeNode bstFromPreorder(int[] preorder) { + TreeNode root = new TreeNode(preorder[0]); + Deque stack = new ArrayDeque<>(Arrays.asList(root)); + + for (int i = 1; i < preorder.length; ++i) { + TreeNode parent = stack.peek(); + TreeNode child = new TreeNode(preorder[i]); + // Adjust the parent. + while (!stack.isEmpty() && stack.peek().val < child.val) + parent = stack.pop(); + // Create parent-child link according to BST property. + if (parent.val > child.val) + parent.left = child; + else + parent.right = child; + stack.push(child); + } + + return root; + } +} diff --git a/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.py b/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.py new file mode 100644 index 00000000000..766437a3806 --- /dev/null +++ b/solutions/1008. Construct Binary Search Tree from Preorder Traversal/1008.py @@ -0,0 +1,19 @@ +class Solution: + def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: + root = TreeNode(preorder[0]) + stack = [root] + + for i in range(1, len(preorder)): + parent = stack[-1] + child = TreeNode(preorder[i]) + # Adjust the parent. + while stack and stack[-1].val < child.val: + parent = stack.pop() + # Create parent-child link according to BST property. + if parent.val > child.val: + parent.left = child + else: + parent.right = child + stack.append(child) + + return root diff --git a/solutions/1009. Complement of Base 10 Integer/1009.cpp b/solutions/1009. Complement of Base 10 Integer/1009.cpp new file mode 100644 index 00000000000..02bdc5bb6db --- /dev/null +++ b/solutions/1009. Complement of Base 10 Integer/1009.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int bitwiseComplement(int n) { + int mask = 1; + while (mask < n) + mask = (mask << 1) + 1; + return mask ^ n; + } +}; diff --git a/solutions/1009. Complement of Base 10 Integer/1009.java b/solutions/1009. Complement of Base 10 Integer/1009.java new file mode 100644 index 00000000000..5adcb9790a3 --- /dev/null +++ b/solutions/1009. Complement of Base 10 Integer/1009.java @@ -0,0 +1,8 @@ +class Solution { + public int bitwiseComplement(int n) { + int mask = 1; + while (mask < n) + mask = (mask << 1) + 1; + return mask ^ n; + } +} diff --git a/solutions/1009. Complement of Base 10 Integer/1009.py b/solutions/1009. Complement of Base 10 Integer/1009.py new file mode 100644 index 00000000000..6d23e92aeb9 --- /dev/null +++ b/solutions/1009. Complement of Base 10 Integer/1009.py @@ -0,0 +1,6 @@ +class Solution: + def bitwiseComplement(self, n: int) -> int: + mask = 1 + while mask < n: + mask = (mask << 1) + 1 + return mask ^ n diff --git a/solutions/101. Symmetric Tree/101.cpp b/solutions/101. Symmetric Tree/101.cpp new file mode 100644 index 00000000000..3178bf75185 --- /dev/null +++ b/solutions/101. Symmetric Tree/101.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool isSymmetric(TreeNode* root) { + return isSymmetric(root, root); + } + + private: + bool isSymmetric(TreeNode* p, TreeNode* q) { + if (!p || !q) + return p == q; + + return p->val == q->val && // + isSymmetric(p->left, q->right) && // + isSymmetric(p->right, q->left); + } +}; diff --git a/solutions/101. Symmetric Tree/101.java b/solutions/101. Symmetric Tree/101.java new file mode 100644 index 00000000000..a55b36022a3 --- /dev/null +++ b/solutions/101. Symmetric Tree/101.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isSymmetric(TreeNode root) { + return isSymmetric(root, root); + } + + private boolean isSymmetric(TreeNode p, TreeNode q) { + if (p == null || q == null) + return p == q; + + return p.val == q.val && isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left); + } +} diff --git a/solutions/101. Symmetric Tree/101.py b/solutions/101. Symmetric Tree/101.py new file mode 100644 index 00000000000..9d92fa66278 --- /dev/null +++ b/solutions/101. Symmetric Tree/101.py @@ -0,0 +1,11 @@ +class Solution: + def isSymmetric(self, root: Optional[TreeNode]) -> bool: + def isSymmetric(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + if not p or not q: + return p == q + + return p.val == q.val and \ + isSymmetric(p.left, q.right) and \ + isSymmetric(p.right, q.left) + + return isSymmetric(root, root) diff --git a/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.cpp b/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.cpp new file mode 100644 index 00000000000..5441db7393a --- /dev/null +++ b/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int numPairsDivisibleBy60(vector& time) { + int ans = 0; + vector count(60); + + for (int t : time) { + t %= 60; + ans += count[(60 - t) % 60]; + ++count[t]; + } + + return ans; + } +}; diff --git a/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.java b/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.java new file mode 100644 index 00000000000..500d795aff6 --- /dev/null +++ b/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.java @@ -0,0 +1,14 @@ +class Solution { + public int numPairsDivisibleBy60(int[] time) { + int ans = 0; + int[] count = new int[60]; + + for (int t : time) { + t %= 60; + ans += count[(60 - t) % 60]; + ++count[t]; + } + + return ans; + } +} diff --git a/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.py b/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.py new file mode 100644 index 00000000000..b53c41434ff --- /dev/null +++ b/solutions/1010. Pairs of Songs With Total Durations Divisible by 60/1010.py @@ -0,0 +1,11 @@ +class Solution: + def numPairsDivisibleBy60(self, time: List[int]) -> int: + ans = 0 + count = [0] * 60 + + for t in time: + t %= 60 + ans += count[(60 - t) % 60] + count[t] += 1 + + return ans diff --git a/solutions/1011. Capacity To Ship Packages Within D Days/1011.cpp b/solutions/1011. Capacity To Ship Packages Within D Days/1011.cpp new file mode 100644 index 00000000000..b536d77901b --- /dev/null +++ b/solutions/1011. Capacity To Ship Packages Within D Days/1011.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int shipWithinDays(vector& weights, int days) { + int l = ranges::max(weights); + int r = accumulate(weights.begin(), weights.end(), 0); + + while (l < r) { + const int m = (l + r) / 2; + if (shipDays(weights, m) <= days) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int shipDays(const vector& weights, int shipCapacity) { + int days = 1; + int capacity = 0; + for (const int weight : weights) + if (capacity + weight > shipCapacity) { + ++days; + capacity = weight; + } else { + capacity += weight; + } + return days; + }; +}; diff --git a/solutions/1011. Capacity To Ship Packages Within D Days/1011.java b/solutions/1011. Capacity To Ship Packages Within D Days/1011.java new file mode 100644 index 00000000000..71e6a4df62a --- /dev/null +++ b/solutions/1011. Capacity To Ship Packages Within D Days/1011.java @@ -0,0 +1,29 @@ +class Solution { + public int shipWithinDays(int[] weights, int days) { + int l = Arrays.stream(weights).max().getAsInt(); + int r = Arrays.stream(weights).sum(); + + while (l < r) { + final int m = (l + r) / 2; + if (shipDays(weights, m) <= days) + r = m; + else + l = m + 1; + } + + return l; + } + + private int shipDays(int[] weights, int shipCapacity) { + int days = 1; + int capacity = 0; + for (final int weight : weights) + if (capacity + weight > shipCapacity) { + ++days; + capacity = weight; + } else { + capacity += weight; + } + return days; + } +} diff --git a/solutions/1011. Capacity To Ship Packages Within D Days/1011.py b/solutions/1011. Capacity To Ship Packages Within D Days/1011.py new file mode 100644 index 00000000000..c14932dd758 --- /dev/null +++ b/solutions/1011. Capacity To Ship Packages Within D Days/1011.py @@ -0,0 +1,17 @@ +class Solution: + def shipWithinDays(self, weights: List[int], days: int) -> int: + def canShip(shipCapacity: int) -> bool: + shipDays = 1 + capacity = 0 + for weight in weights: + if capacity + weight > shipCapacity: + shipDays += 1 + capacity = weight + else: + capacity += weight + return shipDays <= days + + l = max(weights) + r = sum(weights) + return bisect.bisect_left(range(l, r), True, + key=lambda m: canShip(m)) + l diff --git a/solutions/1012. Numbers With Repeated Digits/1012.cpp b/solutions/1012. Numbers With Repeated Digits/1012.cpp new file mode 100644 index 00000000000..b7dc0860bcc --- /dev/null +++ b/solutions/1012. Numbers With Repeated Digits/1012.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + int numDupDigitsAtMostN(int n) { + return n - countSpecialNumbers(n); + } + + private: + // Same as 2376. Count Special Integers + int countSpecialNumbers(int n) { + const int digitSize = log10(n) + 1; + vector>> mem( + digitSize + 1, vector>(1 << 10, vector(2, -1))); + return count(to_string(n), 0, 0, true, mem) - 1; // - 0; + } + + private: + // Returns the number of special integers, considering the i-th digit, where + // `used` is the bitmask of the used digits, and `isTight` indicates if the + // current digit is tightly bound. + int count(const string& s, int i, int used, bool isTight, + vector>>& mem) { + if (i == s.length()) + return 1; + if (mem[i][used][isTight] != -1) + return mem[i][used][isTight]; + + int res = 0; + + const int maxDigit = isTight ? s[i] - '0' : 9; + for (int d = 0; d <= maxDigit; ++d) { + // `d` is used. + if (used >> d & 1) + continue; + // Use `d` now. + const bool nextIsTight = isTight && (d == maxDigit); + if (used == 0 && d == 0) // Don't count leading 0s as used. + res += count(s, i + 1, used, nextIsTight, mem); + else + res += count(s, i + 1, used | 1 << d, nextIsTight, mem); + } + + return mem[i][used][isTight] = res; + } +}; diff --git a/solutions/1012. Numbers With Repeated Digits/1012.java b/solutions/1012. Numbers With Repeated Digits/1012.java new file mode 100644 index 00000000000..0877b2b9839 --- /dev/null +++ b/solutions/1012. Numbers With Repeated Digits/1012.java @@ -0,0 +1,39 @@ +class Solution { + public int numDupDigitsAtMostN(int n) { + return n - countSpecialNumbers(n); + } + + // Same as 2376. Count Special Integers + private int countSpecialNumbers(int n) { + final int digitSize = (int) Math.log10(n) + 1; + Integer[][][] mem = new Integer[digitSize + 1][1 << 10][2]; + return count(String.valueOf(n), 0, 0, true, mem) - 1; // - 0; + } + + // Returns the number of special integers, considering the i-th digit, where + // `used` is the bitmask of the used digits, and `isTight` indicates if the + // current digit is tightly bound. + private int count(final String s, int i, int used, boolean isTight, Integer[][][] mem) { + if (i == s.length()) + return 1; + if (mem[i][used][isTight ? 1 : 0] != null) + return mem[i][used][isTight ? 1 : 0]; + + int res = 0; + + final int maxDigit = isTight ? s.charAt(i) - '0' : 9; + for (int d = 0; d <= maxDigit; ++d) { + // `d` is used. + if ((used >> d & 1) == 1) + continue; + // Use `d` now. + final boolean nextIsTight = isTight && (d == maxDigit); + if (used == 0 && d == 0) // Don't count leading 0s as used. + res += count(s, i + 1, used, nextIsTight, mem); + else + res += count(s, i + 1, used | 1 << d, nextIsTight, mem); + } + + return mem[i][used][isTight ? 1 : 0] = res; + } +} diff --git a/solutions/1012. Numbers With Repeated Digits/1012.py b/solutions/1012. Numbers With Repeated Digits/1012.py new file mode 100644 index 00000000000..70717a5d3df --- /dev/null +++ b/solutions/1012. Numbers With Repeated Digits/1012.py @@ -0,0 +1,35 @@ +class Solution: + def numDupDigitsAtMostN(self, n: int) -> int: + return n - self._countSpecialNumbers(n) + + # Same as 2376. Count Special Integers + def _countSpecialNumbers(self, n: int) -> int: + s = str(n) + + @functools.lru_cache(None) + def dp(i: int, used: int, isTight: bool) -> int: + """ + Returns the number of special integers, considering the i-th digit, where + `used` is the bitmask of the used digits, and `isTight` indicates if the + current digit is tightly bound. + """ + if i == len(s): + return 1 + + res = 0 + + maxDigit = int(s[i]) if isTight else 9 + for d in range(maxDigit + 1): + # `d` is used. + if used >> d & 1: + continue + # Use `d` now. + nextIsTight = isTight and (d == maxDigit) + if used == 0 and d == 0: # Don't count leading 0s as used. + res += dp(i + 1, used, nextIsTight) + else: + res += dp(i + 1, used | 1 << d, nextIsTight) + + return res + + return dp(0, 0, True) - 1 # - 0 diff --git a/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.cpp b/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.cpp new file mode 100644 index 00000000000..86aa10ce5ff --- /dev/null +++ b/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool canThreePartsEqualSum(vector& arr) { + const int sum = accumulate(arr.begin(), arr.end(), 0); + if (sum % 3 != 0) + return false; + + const int average = sum / 3; + int partCount = 0; + int partSum = 0; + + for (const int a : arr) { + partSum += a; + if (partSum == average) { + ++partCount; + partSum = 0; + } + } + + // edge case: arr = [0, 0, 0, 0] -> partCount = 4. + return partCount >= 3; + } +}; diff --git a/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.java b/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.java new file mode 100644 index 00000000000..040d32e0630 --- /dev/null +++ b/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.java @@ -0,0 +1,22 @@ +class Solution { + public boolean canThreePartsEqualSum(int[] arr) { + final int sum = Arrays.stream(arr).sum(); + if (sum % 3 != 0) + return false; + + final int average = sum / 3; + int partCount = 0; + int partSum = 0; + + for (final int a : arr) { + partSum += a; + if (partSum == average) { + ++partCount; + partSum = 0; + } + } + + // edge case: arr = [0, 0, 0, 0] -> partCount = 4. + return partCount >= 3; + } +} diff --git a/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.py b/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.py new file mode 100644 index 00000000000..97136ec0a4b --- /dev/null +++ b/solutions/1013. Partition Array Into Three Parts With Equal Sum/1013.py @@ -0,0 +1,18 @@ +class Solution: + def canThreePartsEqualSum(self, arr: List[int]) -> bool: + summ = sum(arr) + if summ % 3 != 0: + return False + + average = summ // 3 + partCount = 0 + partSum = 0 + + for a in arr: + partSum += a + if partSum == average: + partCount += 1 + partSum = 0 + + # edge case: arr = [0, 0, 0, 0] . partCount = 4. + return partCount >= 3 diff --git a/solutions/1014. Best Sightseeing Pair/1014.cpp b/solutions/1014. Best Sightseeing Pair/1014.cpp new file mode 100644 index 00000000000..b4120e76d5f --- /dev/null +++ b/solutions/1014. Best Sightseeing Pair/1014.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxScoreSightseeingPair(vector& values) { + int ans = 0; + int bestPrev = 0; + + for (const int value : values) { + ans = max(ans, value + bestPrev); + bestPrev = max(bestPrev, value) - 1; + } + + return ans; + } +}; diff --git a/solutions/1014. Best Sightseeing Pair/1014.java b/solutions/1014. Best Sightseeing Pair/1014.java new file mode 100644 index 00000000000..2f298ea4420 --- /dev/null +++ b/solutions/1014. Best Sightseeing Pair/1014.java @@ -0,0 +1,13 @@ +class Solution { + public int maxScoreSightseeingPair(int[] values) { + int ans = 0; + int bestPrev = 0; + + for (final int value : values) { + ans = Math.max(ans, value + bestPrev); + bestPrev = Math.max(bestPrev, value) - 1; + } + + return ans; + } +} diff --git a/solutions/1014. Best Sightseeing Pair/1014.py b/solutions/1014. Best Sightseeing Pair/1014.py new file mode 100644 index 00000000000..5e94ad14073 --- /dev/null +++ b/solutions/1014. Best Sightseeing Pair/1014.py @@ -0,0 +1,10 @@ +class Solution: + def maxScoreSightseeingPair(self, values: List[int]) -> int: + ans = 0 + bestPrev = 0 + + for value in values: + ans = max(ans, value + bestPrev) + bestPrev = max(bestPrev, value) - 1 + + return ans diff --git a/solutions/1015. Smallest Integer Divisible by K/1015.cpp b/solutions/1015. Smallest Integer Divisible by K/1015.cpp new file mode 100644 index 00000000000..a4055b30233 --- /dev/null +++ b/solutions/1015. Smallest Integer Divisible by K/1015.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int smallestRepunitDivByK(int k) { + if (k % 10 != 1 && k % 10 != 3 && k % 10 != 7 && k % 10 != 9) + return -1; + + unordered_set seen; + int n = 0; + + for (int length = 1; length <= k; ++length) { + n = (n * 10 + 1) % k; + if (n == 0) + return length; + if (seen.contains(n)) + return -1; + seen.insert(n); + } + + return -1; + } +}; diff --git a/solutions/1015. Smallest Integer Divisible by K/1015.java b/solutions/1015. Smallest Integer Divisible by K/1015.java new file mode 100644 index 00000000000..0be41c17900 --- /dev/null +++ b/solutions/1015. Smallest Integer Divisible by K/1015.java @@ -0,0 +1,20 @@ +class Solution { + public int smallestRepunitDivByK(int k) { + if (k % 10 != 1 && k % 10 != 3 && k % 10 != 7 && k % 10 != 9) + return -1; + + Set seen = new HashSet<>(); + int n = 0; + + for (int length = 1; length <= k; ++length) { + n = (n * 10 + 1) % k; + if (n == 0) + return length; + if (seen.contains(n)) + return -1; + seen.add(n); + } + + return -1; + } +} diff --git a/solutions/1015. Smallest Integer Divisible by K/1015.py b/solutions/1015. Smallest Integer Divisible by K/1015.py new file mode 100644 index 00000000000..80e9da2e014 --- /dev/null +++ b/solutions/1015. Smallest Integer Divisible by K/1015.py @@ -0,0 +1,17 @@ +class Solution: + def smallestRepunitDivByK(self, k: int) -> int: + if k % 10 not in {1, 3, 7, 9}: + return -1 + + seen = set() + n = 0 + + for length in range(1, k + 1): + n = (n * 10 + 1) % k + if n == 0: + return length + if n in seen: + return -1 + seen.add(n) + + return -1 diff --git a/solutions/1016. Binary String With Substrings Representing 1 To N/1016.cpp b/solutions/1016. Binary String With Substrings Representing 1 To N/1016.cpp new file mode 100644 index 00000000000..99f22be6ca9 --- /dev/null +++ b/solutions/1016. Binary String With Substrings Representing 1 To N/1016.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool queryString(string s, int n) { + if (n > 1511) + return false; + + for (int i = n; i > n / 2; --i) { + string binary = bitset<32>(i).to_string(); + binary = binary.substr(binary.find("1")); + if (s.find(binary) == string::npos) + return false; + } + + return true; + } +}; diff --git a/solutions/1016. Binary String With Substrings Representing 1 To N/1016.java b/solutions/1016. Binary String With Substrings Representing 1 To N/1016.java new file mode 100644 index 00000000000..38ea1689ff7 --- /dev/null +++ b/solutions/1016. Binary String With Substrings Representing 1 To N/1016.java @@ -0,0 +1,12 @@ +class Solution { + public boolean queryString(String s, int n) { + if (n > 1511) + return false; + + for (int i = n; i > n / 2; --i) + if (!s.contains(Integer.toBinaryString(i))) + return false; + + return true; + } +} diff --git a/solutions/1016. Binary String With Substrings Representing 1 To N/1016.py b/solutions/1016. Binary String With Substrings Representing 1 To N/1016.py new file mode 100644 index 00000000000..9e825d1f386 --- /dev/null +++ b/solutions/1016. Binary String With Substrings Representing 1 To N/1016.py @@ -0,0 +1,10 @@ +class Solution: + def queryString(self, s: str, n: int) -> bool: + if n > 1511: + return False + + for i in range(n, n // 2, -1): + if format(i, 'b') not in s: + return False + + return True diff --git a/solutions/1017. Convert to Base -2/1017.cpp b/solutions/1017. Convert to Base -2/1017.cpp new file mode 100644 index 00000000000..713f064022a --- /dev/null +++ b/solutions/1017. Convert to Base -2/1017.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + string baseNeg2(int n) { + string ans; + + while (n != 0) { + ans += to_string(n % 2); + n = -(n >> 1); + } + + return ans.empty() ? "0" : string{ans.rbegin(), ans.rend()}; + } +}; diff --git a/solutions/1017. Convert to Base -2/1017.java b/solutions/1017. Convert to Base -2/1017.java new file mode 100644 index 00000000000..b96d9c4ee7e --- /dev/null +++ b/solutions/1017. Convert to Base -2/1017.java @@ -0,0 +1,12 @@ +class Solution { + public String baseNeg2(int n) { + StringBuilder sb = new StringBuilder(); + + while (n != 0) { + sb.append(n % 2); + n = -(n >> 1); + } + + return sb.length() > 0 ? sb.reverse().toString() : "0"; + } +} diff --git a/solutions/1017. Convert to Base -2/1017.py b/solutions/1017. Convert to Base -2/1017.py new file mode 100644 index 00000000000..eb3b3e61400 --- /dev/null +++ b/solutions/1017. Convert to Base -2/1017.py @@ -0,0 +1,9 @@ +class Solution: + def baseNeg2(self, n: int) -> str: + ans = [] + + while n != 0: + ans.append(str(n % 2)) + n = -(n >> 1) + + return ''.join(reversed(ans)) if ans else '0' diff --git a/solutions/1018. Binary Prefix Divisible By 5/1018.cpp b/solutions/1018. Binary Prefix Divisible By 5/1018.cpp new file mode 100644 index 00000000000..48d1beeef76 --- /dev/null +++ b/solutions/1018. Binary Prefix Divisible By 5/1018.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector prefixesDivBy5(vector& nums) { + vector ans; + int curr = 0; + + for (const int num : nums) { + curr = (curr * 2 + num) % 5; + ans.push_back(curr % 5 == 0); + } + + return ans; + } +}; diff --git a/solutions/1018. Binary Prefix Divisible By 5/1018.java b/solutions/1018. Binary Prefix Divisible By 5/1018.java new file mode 100644 index 00000000000..3e3c7093256 --- /dev/null +++ b/solutions/1018. Binary Prefix Divisible By 5/1018.java @@ -0,0 +1,13 @@ +class Solution { + public List prefixesDivBy5(int[] nums) { + List ans = new ArrayList<>(); + int curr = 0; + + for (final int num : nums) { + curr = (curr * 2 + num) % 5; + ans.add(curr % 5 == 0); + } + + return ans; + } +} diff --git a/solutions/1018. Binary Prefix Divisible By 5/1018.py b/solutions/1018. Binary Prefix Divisible By 5/1018.py new file mode 100644 index 00000000000..e7af7ea538b --- /dev/null +++ b/solutions/1018. Binary Prefix Divisible By 5/1018.py @@ -0,0 +1,10 @@ +class Solution: + def prefixesDivBy5(self, nums: List[int]) -> List[bool]: + ans = [] + curr = 0 + + for num in nums: + curr = (curr * 2 + num) % 5 + ans.append(curr % 5 == 0) + + return ans diff --git a/solutions/1019. Next Greater Node In Linked List/1019.cpp b/solutions/1019. Next Greater Node In Linked List/1019.cpp new file mode 100644 index 00000000000..1904a8765fd --- /dev/null +++ b/solutions/1019. Next Greater Node In Linked List/1019.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector nextLargerNodes(ListNode* head) { + vector ans; + stack stack; + + for (; head; head = head->next) { + while (!stack.empty() && head->val > ans[stack.top()]) { + int index = stack.top(); + stack.pop(); + ans[index] = head->val; + } + stack.push(ans.size()); + ans.push_back(head->val); + } + + for (; !stack.empty(); stack.pop()) + ans[stack.top()] = 0; + + return ans; + } +}; diff --git a/solutions/1019. Next Greater Node In Linked List/1019.java b/solutions/1019. Next Greater Node In Linked List/1019.java new file mode 100644 index 00000000000..c13e18280a2 --- /dev/null +++ b/solutions/1019. Next Greater Node In Linked List/1019.java @@ -0,0 +1,20 @@ +class Solution { + public int[] nextLargerNodes(ListNode head) { + List ans = new ArrayList<>(); + Deque stack = new ArrayDeque<>(); + + for (; head != null; head = head.next) { + while (!stack.isEmpty() && head.val > ans.get(stack.peek())) { + int index = stack.pop(); + ans.set(index, head.val); + } + stack.push(ans.size()); + ans.add(head.val); + } + + while (!stack.isEmpty()) + ans.set(stack.pop(), 0); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/1019. Next Greater Node In Linked List/1019.py b/solutions/1019. Next Greater Node In Linked List/1019.py new file mode 100644 index 00000000000..2b2a9fb0fc6 --- /dev/null +++ b/solutions/1019. Next Greater Node In Linked List/1019.py @@ -0,0 +1,17 @@ +class Solution: + def nextLargerNodes(self, head: ListNode) -> List[int]: + ans = [] + stack = [] + + while head: + while stack and head.val > ans[stack[-1]]: + index = stack.pop() + ans[index] = head.val + stack.append(len(ans)) + ans.append(head.val) + head = head.next + + for i in stack: + ans[i] = 0 + + return ans diff --git a/solutions/102. Binary Tree Level Order Traversal/102.cpp b/solutions/102. Binary Tree Level Order Traversal/102.cpp new file mode 100644 index 00000000000..322fab08fd7 --- /dev/null +++ b/solutions/102. Binary Tree Level Order Traversal/102.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> levelOrder(TreeNode* root) { + if (root == nullptr) + return {}; + + vector> ans; + queue q{{root}}; + + while (!q.empty()) { + vector currLevel; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + currLevel.push_back(node->val); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + ans.push_back(currLevel); + } + + return ans; + } +}; diff --git a/solutions/102. Binary Tree Level Order Traversal/102.java b/solutions/102. Binary Tree Level Order Traversal/102.java new file mode 100644 index 00000000000..08903d5ca84 --- /dev/null +++ b/solutions/102. Binary Tree Level Order Traversal/102.java @@ -0,0 +1,24 @@ +class Solution { + public List> levelOrder(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + List currLevel = new ArrayList<>(); + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + currLevel.add(node.val); + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + ans.add(currLevel); + } + + return ans; + } +} diff --git a/solutions/102. Binary Tree Level Order Traversal/102.py b/solutions/102. Binary Tree Level Order Traversal/102.py new file mode 100644 index 00000000000..e7efbc0b093 --- /dev/null +++ b/solutions/102. Binary Tree Level Order Traversal/102.py @@ -0,0 +1,20 @@ +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: + return [] + + ans = [] + q = collections.deque([root]) + + while q: + currLevel = [] + for _ in range(len(q)): + node = q.popleft() + currLevel.append(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + ans.append(currLevel) + + return ans diff --git a/solutions/1020. Number of Enclaves/1020.cpp b/solutions/1020. Number of Enclaves/1020.cpp new file mode 100644 index 00000000000..c823a370532 --- /dev/null +++ b/solutions/1020. Number of Enclaves/1020.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int numEnclaves(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + + // Remove the lands connected to the edge. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + if (grid[i][j] == 1) + dfs(grid, i, j); + + return accumulate(grid.begin(), grid.end(), 0, + [](int subtotal, vector& row) { + return subtotal + accumulate(row.begin(), row.end(), 0); + }); + } + + private: + void dfs(vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] == 0) + return; + grid[i][j] = 0; + dfs(grid, i + 1, j); + dfs(grid, i - 1, j); + dfs(grid, i, j + 1); + dfs(grid, i, j - 1); + }; +}; diff --git a/solutions/1020. Number of Enclaves/1020.java b/solutions/1020. Number of Enclaves/1020.java new file mode 100644 index 00000000000..44053100711 --- /dev/null +++ b/solutions/1020. Number of Enclaves/1020.java @@ -0,0 +1,27 @@ +class Solution { + public int numEnclaves(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + + // Remove the lands connected to the edge. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + if (grid[i][j] == 1) + dfs(grid, i, j); + + return Arrays.stream(grid).flatMapToInt(Arrays::stream).sum(); + } + + private void dfs(int[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] == 0) + return; + grid[i][j] = 0; + dfs(grid, i + 1, j); + dfs(grid, i - 1, j); + dfs(grid, i, j + 1); + dfs(grid, i, j - 1); + } +} diff --git a/solutions/1021. Remove Outermost Parentheses/1021.cpp b/solutions/1021. Remove Outermost Parentheses/1021.cpp new file mode 100644 index 00000000000..b1c90c3af59 --- /dev/null +++ b/solutions/1021. Remove Outermost Parentheses/1021.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string removeOuterParentheses(string s) { + string ans; + int opened = 0; + + for (const char c : s) + if (c == '(') { + if (++opened > 1) + ans += c; + } else if (--opened > 0) { // c == ')' + ans += c; + } + + return ans; + } +}; diff --git a/solutions/1021. Remove Outermost Parentheses/1021.java b/solutions/1021. Remove Outermost Parentheses/1021.java new file mode 100644 index 00000000000..aaf3ec82c8f --- /dev/null +++ b/solutions/1021. Remove Outermost Parentheses/1021.java @@ -0,0 +1,16 @@ +class Solution { + public String removeOuterParentheses(String s) { + StringBuilder sb = new StringBuilder(); + int opened = 0; + + for (final char c : s.toCharArray()) + if (c == '(') { + if (++opened > 1) + sb.append(c); + } else if (--opened > 0) { // c == ')' + sb.append(c); + } + + return sb.toString(); + } +} diff --git a/solutions/1021. Remove Outermost Parentheses/1021.py b/solutions/1021. Remove Outermost Parentheses/1021.py new file mode 100644 index 00000000000..dc95b53914a --- /dev/null +++ b/solutions/1021. Remove Outermost Parentheses/1021.py @@ -0,0 +1,16 @@ +class Solution: + def removeOuterParentheses(self, s: str) -> str: + ans = [] + opened = 0 + + for c in s: + if c == '(': + opened += 1 + if opened > 1: + ans.append(c) + else: # c == ')' + opened -= 1 + if opened > 0: + ans.append(c) + + return ''.join(ans) diff --git a/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.cpp b/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.cpp new file mode 100644 index 00000000000..bbe578c326e --- /dev/null +++ b/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int sumRootToLeaf(TreeNode* root) { + int ans = 0; + dfs(root, 0, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int val, int& ans) { + if (root == nullptr) + return; + val = val * 2 + root->val; + if (root->left == nullptr && root->right == nullptr) + ans += val; + dfs(root->left, val, ans); + dfs(root->right, val, ans); + } +}; diff --git a/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.java b/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.java new file mode 100644 index 00000000000..be55d75bba5 --- /dev/null +++ b/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.java @@ -0,0 +1,18 @@ +class Solution { + public int sumRootToLeaf(TreeNode root) { + dfs(root, 0); + return ans; + } + + private int ans = 0; + + private void dfs(TreeNode root, int val) { + if (root == null) + return; + val = val * 2 + root.val; + if (root.left == null && root.right == null) + ans += val; + dfs(root.left, val); + dfs(root.right, val); + } +} diff --git a/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.py b/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.py new file mode 100644 index 00000000000..25d34027885 --- /dev/null +++ b/solutions/1022. Sum of Root To Leaf Binary Numbers/1022.py @@ -0,0 +1,16 @@ +class Solution: + def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def dfs(root: Optional[TreeNode], val: int) -> None: + nonlocal ans + if not root: + return + val = val * 2 + root.val + if not root.left and not root.right: + ans += val + dfs(root.left, val) + dfs(root.right, val) + + dfs(root, 0) + return ans diff --git a/solutions/1023. Camelcase Matching/1023.cpp b/solutions/1023. Camelcase Matching/1023.cpp new file mode 100644 index 00000000000..d89222be369 --- /dev/null +++ b/solutions/1023. Camelcase Matching/1023.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector camelMatch(vector& queries, string pattern) { + vector ans; + for (const string& query : queries) + ans.push_back(isMatch(query, pattern)); + return ans; + } + + private: + bool isMatch(const string& query, const string& pattern) { + int j = 0; + for (const char c : query) + if (j < pattern.length() && c == pattern[j]) + ++j; + else if (isupper(c)) + return false; + return j == pattern.length(); + } +}; diff --git a/solutions/1023. Camelcase Matching/1023.java b/solutions/1023. Camelcase Matching/1023.java new file mode 100644 index 00000000000..896007bdfb8 --- /dev/null +++ b/solutions/1023. Camelcase Matching/1023.java @@ -0,0 +1,18 @@ +class Solution { + public List camelMatch(String[] queries, String pattern) { + List ans = new ArrayList<>(); + for (final String q : queries) + ans.add(isMatch(q, pattern)); + return ans; + } + + private boolean isMatch(final String query, final String pattern) { + int j = 0; + for (final char c : query.toCharArray()) + if (j < pattern.length() && c == pattern.charAt(j)) + ++j; + else if (Character.isUpperCase(c)) + return false; + return j == pattern.length(); + } +} diff --git a/solutions/1023. Camelcase Matching/1023.py b/solutions/1023. Camelcase Matching/1023.py new file mode 100644 index 00000000000..d30fc5273d6 --- /dev/null +++ b/solutions/1023. Camelcase Matching/1023.py @@ -0,0 +1,12 @@ +class Solution: + def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: + def isMatch(query: str) -> bool: + j = 0 + for c in query: + if j < len(pattern) and c == pattern[j]: + j += 1 + elif c.isupper(): + return False + return j == len(pattern) + + return [isMatch(query) for query in queries] diff --git a/solutions/1024. Video Stitching/1024.cpp b/solutions/1024. Video Stitching/1024.cpp new file mode 100644 index 00000000000..3f0fa40418a --- /dev/null +++ b/solutions/1024. Video Stitching/1024.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int videoStitching(vector>& clips, int time) { + int ans = 0; + int end = 0; + int farthest = 0; + + sort(std::clips.begin(), std::end(clips)); + + int i = 0; + while (farthest < time) { + while (i < clips.size() && clips[i][0] <= end) + farthest = max(farthest, clips[i++][1]); + if (end == farthest) + return -1; + ++ans; + end = farthest; + } + + return ans; + } +}; diff --git a/solutions/1024. Video Stitching/1024.java b/solutions/1024. Video Stitching/1024.java new file mode 100644 index 00000000000..833c49d8e32 --- /dev/null +++ b/solutions/1024. Video Stitching/1024.java @@ -0,0 +1,21 @@ +class Solution { + public int videoStitching(int[][] clips, int time) { + int ans = 0; + int end = 0; + int farthest = 0; + + Arrays.sort(clips, (a, b) -> a[0] - b[0]); + + int i = 0; + while (farthest < time) { + while (i < clips.length && clips[i][0] <= end) + farthest = Math.max(farthest, clips[i++][1]); + if (end == farthest) + return -1; + ++ans; + end = farthest; + } + + return ans; + } +} diff --git a/solutions/1024. Video Stitching/1024.py b/solutions/1024. Video Stitching/1024.py new file mode 100644 index 00000000000..36393638541 --- /dev/null +++ b/solutions/1024. Video Stitching/1024.py @@ -0,0 +1,19 @@ +class Solution: + def videoStitching(self, clips: List[List[int]], time: int) -> int: + ans = 0 + end = 0 + farthest = 0 + + clips.sort() + + i = 0 + while farthest < time: + while i < len(clips) and clips[i][0] <= end: + farthest = max(farthest, clips[i][1]) + i += 1 + if end == farthest: + return -1 + ans += 1 + end = farthest + + return ans diff --git a/solutions/1025. Divisor Game/1025.cpp b/solutions/1025. Divisor Game/1025.cpp new file mode 100644 index 00000000000..3e2468e33bc --- /dev/null +++ b/solutions/1025. Divisor Game/1025.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool divisorGame(int n) { + return n % 2 == 0; + } +}; diff --git a/solutions/1025. Divisor Game/1025.java b/solutions/1025. Divisor Game/1025.java new file mode 100644 index 00000000000..1f6ae9a1aa8 --- /dev/null +++ b/solutions/1025. Divisor Game/1025.java @@ -0,0 +1,5 @@ +class Solution { + public boolean divisorGame(int n) { + return n % 2 == 0; + } +} diff --git a/solutions/1025. Divisor Game/1025.py b/solutions/1025. Divisor Game/1025.py new file mode 100644 index 00000000000..c698bfb3317 --- /dev/null +++ b/solutions/1025. Divisor Game/1025.py @@ -0,0 +1,3 @@ +class Solution: + def divisorGame(self, n: int) -> bool: + return n % 2 == 0 diff --git a/solutions/1026. Maximum Difference Between Node and Ancestor/1026.cpp b/solutions/1026. Maximum Difference Between Node and Ancestor/1026.cpp new file mode 100644 index 00000000000..4ac294394d7 --- /dev/null +++ b/solutions/1026. Maximum Difference Between Node and Ancestor/1026.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxAncestorDiff(TreeNode* root) { + return maxAncestorDiff(root, root->val, root->val); + } + + private: + // Returns |the maximum - the minimum| of the tree. + int maxAncestorDiff(TreeNode* root, int mn, int mx) { + if (root == nullptr) + return 0; + mn = min(mn, root->val); + mx = max(mx, root->val); + const int l = maxAncestorDiff(root->left, mn, mx); + const int r = maxAncestorDiff(root->right, mn, mx); + return max({mx - mn, l, r}); + } +}; diff --git a/solutions/1026. Maximum Difference Between Node and Ancestor/1026.java b/solutions/1026. Maximum Difference Between Node and Ancestor/1026.java new file mode 100644 index 00000000000..0543a4b04b2 --- /dev/null +++ b/solutions/1026. Maximum Difference Between Node and Ancestor/1026.java @@ -0,0 +1,16 @@ +class Solution { + public int maxAncestorDiff(TreeNode root) { + return maxAncestorDiff(root, root.val, root.val); + } + + // Returns |the maximum - the minimum| of the tree. + private int maxAncestorDiff(TreeNode root, int mn, int mx) { + if (root == null) + return 0; + mn = Math.min(mn, root.val); + mx = Math.max(mx, root.val); + final int l = maxAncestorDiff(root.left, mn, mx); + final int r = maxAncestorDiff(root.right, mn, mx); + return Math.max(mx - mn, Math.max(l, r)); + } +} diff --git a/solutions/1027. Longest Arithmetic Subsequence/1027.cpp b/solutions/1027. Longest Arithmetic Subsequence/1027.cpp new file mode 100644 index 00000000000..51aed8c1e02 --- /dev/null +++ b/solutions/1027. Longest Arithmetic Subsequence/1027.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int longestArithSeqLength(vector& nums) { + const int n = nums.size(); + int ans = 0; + // dp[i][k] := the length of the longest arithmetic subsequence of + // nums[0..i] with k = diff + 500 + vector> dp(n, vector(1001)); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < i; ++j) { + const int k = nums[i] - nums[j] + 500; + dp[i][k] = max(2, dp[j][k] + 1); + ans = max(ans, dp[i][k]); + } + + return ans; + } +}; diff --git a/solutions/1027. Longest Arithmetic Subsequence/1027.java b/solutions/1027. Longest Arithmetic Subsequence/1027.java new file mode 100644 index 00000000000..5c3fc1f0256 --- /dev/null +++ b/solutions/1027. Longest Arithmetic Subsequence/1027.java @@ -0,0 +1,18 @@ +class Solution { + public int longestArithSeqLength(int[] nums) { + final int n = nums.length; + int ans = 0; + // dp[i][k] := the length of the longest arithmetic subsequence of nums[0..i] + // with k = diff + 500 + int[][] dp = new int[n][1001]; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < i; ++j) { + final int k = nums[i] - nums[j] + 500; + dp[i][k] = Math.max(2, dp[j][k] + 1); + ans = Math.max(ans, dp[i][k]); + } + + return ans; + } +} diff --git a/solutions/1027. Longest Arithmetic Subsequence/1027.py b/solutions/1027. Longest Arithmetic Subsequence/1027.py new file mode 100644 index 00000000000..4ea42217d1d --- /dev/null +++ b/solutions/1027. Longest Arithmetic Subsequence/1027.py @@ -0,0 +1,15 @@ +class Solution: + def longestArithSeqLength(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + # dp[i][k] := the length of the longest arithmetic subsequence of nums[0..i] + # with k = diff + 500 + dp = [[0] * 1001 for _ in range(n)] + + for i in range(n): + for j in range(i): + k = nums[i] - nums[j] + 500 + dp[i][k] = max(2, dp[j][k] + 1) + ans = max(ans, dp[i][k]) + + return ans diff --git a/solutions/1028. Recover a Tree From Preorder Traversal/1028.cpp b/solutions/1028. Recover a Tree From Preorder Traversal/1028.cpp new file mode 100644 index 00000000000..e1f358402d1 --- /dev/null +++ b/solutions/1028. Recover a Tree From Preorder Traversal/1028.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + TreeNode* recoverFromPreorder(string traversal) { + int i = 0; + return recoverFromPreorder(traversal, 0, i); + } + + private: + TreeNode* recoverFromPreorder(const string& traversal, int depth, int& i) { + int nDashes = 0; + while (i + nDashes < traversal.length() && traversal[i + nDashes] == '-') + ++nDashes; + if (nDashes != depth) + return nullptr; + + i += depth; + const int start = i; + while (i < traversal.length() && isdigit(traversal[i])) + ++i; + + return new TreeNode(stoi(traversal.substr(start, i - start)), + recoverFromPreorder(traversal, depth + 1, i), + recoverFromPreorder(traversal, depth + 1, i)); + } +}; diff --git a/solutions/1028. Recover a Tree From Preorder Traversal/1028.java b/solutions/1028. Recover a Tree From Preorder Traversal/1028.java new file mode 100644 index 00000000000..42b1cc72ccc --- /dev/null +++ b/solutions/1028. Recover a Tree From Preorder Traversal/1028.java @@ -0,0 +1,24 @@ +class Solution { + public TreeNode recoverFromPreorder(String traversal) { + return recoverFromPreorder(traversal, 0); + } + + private int i = 0; + + private TreeNode recoverFromPreorder(final String traversal, int depth) { + int nDashes = 0; + while (i + nDashes < traversal.length() && traversal.charAt(i + nDashes) == '-') + ++nDashes; + if (nDashes != depth) + return null; + + i += depth; + final int start = i; + while (i < traversal.length() && Character.isDigit(traversal.charAt(i))) + ++i; + + return new TreeNode(Integer.valueOf(traversal.substring(start, i)), + recoverFromPreorder(traversal, depth + 1), + recoverFromPreorder(traversal, depth + 1)); + } +} diff --git a/solutions/1028. Recover a Tree From Preorder Traversal/1028.py b/solutions/1028. Recover a Tree From Preorder Traversal/1028.py new file mode 100644 index 00000000000..17623fff395 --- /dev/null +++ b/solutions/1028. Recover a Tree From Preorder Traversal/1028.py @@ -0,0 +1,22 @@ +class Solution: + def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]: + i = 0 + + def recoverFromPreorder(depth: int) -> Optional[TreeNode]: + nonlocal i + nDashes = 0 + while i + nDashes < len(traversal) and traversal[i + nDashes] == '-': + nDashes += 1 + if nDashes != depth: + return None + + i += depth + start = i + while i < len(traversal) and traversal[i].isdigit(): + i += 1 + + return TreeNode(int(traversal[start:i]), + recoverFromPreorder(depth + 1), + recoverFromPreorder(depth + 1)) + + return recoverFromPreorder(0) diff --git a/solutions/1029. Two City Scheduling/1029.cpp b/solutions/1029. Two City Scheduling/1029.cpp new file mode 100644 index 00000000000..32b05626d24 --- /dev/null +++ b/solutions/1029. Two City Scheduling/1029.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int twoCitySchedCost(vector>& costs) { + const int n = costs.size() / 2; + int ans = 0; + + // How much money can we save if we fly a person to A instead of B? + // To save money, we should + // 1. Fly the person with the maximum saving to A. + // 2. Fly the person with the minimum saving to B. + ranges::sort(costs, [](const vector& a, const vector& b) { + // Sort `costs` in descending order by the money saved if we fly a person + // to A instead of B. + return a[1] - a[0] > b[1] - b[0]; + }); + + for (int i = 0; i < n; ++i) + ans += costs[i][0] + costs[i + n][1]; + + return ans; + } +}; diff --git a/solutions/1029. Two City Scheduling/1029.java b/solutions/1029. Two City Scheduling/1029.java new file mode 100644 index 00000000000..99634dab9af --- /dev/null +++ b/solutions/1029. Two City Scheduling/1029.java @@ -0,0 +1,20 @@ +class Solution { + public int twoCitySchedCost(int[][] costs) { + final int n = costs.length / 2; + int ans = 0; + + // How much money can we save if we fly a person to A instead of B? + // To save money, we should + // 1. Fly the person with the maximum saving to A. + // 2. Fly the person with the minimum saving to B. + + // Sort `costs` in descending order by the money saved if we fly a person to + // A instead of B. + Arrays.sort(costs, (a, b) -> (b[1] - b[0]) - (a[1] - a[0])); + + for (int i = 0; i < n; ++i) + ans += costs[i][0] + costs[i + n][1]; + + return ans; + } +} diff --git a/solutions/1029. Two City Scheduling/1029.py b/solutions/1029. Two City Scheduling/1029.py new file mode 100644 index 00000000000..7e313555b1e --- /dev/null +++ b/solutions/1029. Two City Scheduling/1029.py @@ -0,0 +1,13 @@ +class Solution: + def twoCitySchedCost(self, costs: List[List[int]]) -> int: + n = len(costs) // 2 + + # How much money can we save if we fly a person to A instead of B? + # To save money, we should + # 1. Fly the person with the maximum saving to A. + # 2. Fly the person with the minimum saving to B. + + # Sort `costs` in descending order by the money saved if we fly a person + # to A instead of B. + costs.sort(key=lambda x: x[0] - x[1]) + return sum(costs[i][0] + costs[i + n][1] for i in range(n)) diff --git a/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.cpp b/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.cpp new file mode 100644 index 00000000000..171c7146f83 --- /dev/null +++ b/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector> zigzagLevelOrder(TreeNode* root) { + if (root == nullptr) + return {}; + + vector> ans; + queue q{{root}}; + bool isLeftToRight = true; + + while (!q.empty()) { + const int size = q.size(); + vector currLevel(size); + for (int i = 0; i < size; ++i) { + TreeNode* node = q.front(); + q.pop(); + const int index = isLeftToRight ? i : size - i - 1; + currLevel[index] = node->val; + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + ans.push_back(currLevel); + isLeftToRight = !isLeftToRight; + } + + return ans; + } +}; diff --git a/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.java b/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.java new file mode 100644 index 00000000000..87c39bfe609 --- /dev/null +++ b/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.java @@ -0,0 +1,29 @@ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + Deque q = new ArrayDeque<>(Arrays.asList(root)); + boolean isLeftToRight = true; + + while (!q.isEmpty()) { + List currLevel = new ArrayList<>(); + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + if (isLeftToRight) + currLevel.add(node.val); + else + currLevel.add(0, node.val); + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + ans.add(currLevel); + isLeftToRight = !isLeftToRight; + } + + return ans; + } +} diff --git a/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.py b/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.py new file mode 100644 index 00000000000..6ff7f47248d --- /dev/null +++ b/solutions/103. Binary Tree Zigzag Level Order Traversal/103-2.py @@ -0,0 +1,24 @@ +class Solution: + def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: + return [] + + ans = [] + q = collections.deque([root]) + isLeftToRight = True + + while q: + size = len(q) + currLevel = [0] * size + for i in range(size): + node = q.popleft() + index = i if isLeftToRight else size - i - 1 + currLevel[index] = node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + ans.append(currLevel) + isLeftToRight = not isLeftToRight + + return ans diff --git a/solutions/103. Binary Tree Zigzag Level Order Traversal/103.cpp b/solutions/103. Binary Tree Zigzag Level Order Traversal/103.cpp new file mode 100644 index 00000000000..9c09c1a3c49 --- /dev/null +++ b/solutions/103. Binary Tree Zigzag Level Order Traversal/103.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + vector> zigzagLevelOrder(TreeNode* root) { + if (root == nullptr) + return {}; + + vector> ans; + deque dq{{root}}; + bool isLeftToRight = true; + + while (!dq.empty()) { + vector currLevel; + for (int sz = dq.size(); sz > 0; --sz) + if (isLeftToRight) { + TreeNode* node = dq.front(); + dq.pop_front(); + currLevel.push_back(node->val); + if (node->left) + dq.push_back(node->left); + if (node->right) + dq.push_back(node->right); + } else { + TreeNode* node = dq.back(); + dq.pop_back(); + currLevel.push_back(node->val); + if (node->right) + dq.push_front(node->right); + if (node->left) + dq.push_front(node->left); + } + ans.push_back(currLevel); + isLeftToRight = !isLeftToRight; + } + + return ans; + } +}; diff --git a/solutions/103. Binary Tree Zigzag Level Order Traversal/103.java b/solutions/103. Binary Tree Zigzag Level Order Traversal/103.java new file mode 100644 index 00000000000..ac25ae136f4 --- /dev/null +++ b/solutions/103. Binary Tree Zigzag Level Order Traversal/103.java @@ -0,0 +1,34 @@ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + Deque dq = new ArrayDeque<>(Arrays.asList(root)); + boolean isLeftToRight = true; + + while (!dq.isEmpty()) { + List currLevel = new ArrayList<>(); + for (int sz = dq.size(); sz > 0; --sz) + if (isLeftToRight) { + TreeNode node = dq.pollFirst(); + currLevel.add(node.val); + if (node.left != null) + dq.addLast(node.left); + if (node.right != null) + dq.addLast(node.right); + } else { + TreeNode node = dq.pollLast(); + currLevel.add(node.val); + if (node.right != null) + dq.addFirst(node.right); + if (node.left != null) + dq.addFirst(node.left); + } + ans.add(currLevel); + isLeftToRight = !isLeftToRight; + } + + return ans; + } +} diff --git a/solutions/103. Binary Tree Zigzag Level Order Traversal/103.py b/solutions/103. Binary Tree Zigzag Level Order Traversal/103.py new file mode 100644 index 00000000000..0a3cf3e4fb5 --- /dev/null +++ b/solutions/103. Binary Tree Zigzag Level Order Traversal/103.py @@ -0,0 +1,30 @@ +class Solution: + def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: + return [] + + ans = [] + dq = collections.deque([root]) + isLeftToRight = True + + while dq: + currLevel = [] + for _ in range(len(dq)): + if isLeftToRight: + node = dq.popleft() + currLevel.append(node.val) + if node.left: + dq.append(node.left) + if node.right: + dq.append(node.right) + else: + node = dq.pop() + currLevel.append(node.val) + if node.right: + dq.appendleft(node.right) + if node.left: + dq.appendleft(node.left) + ans.append(currLevel) + isLeftToRight = not isLeftToRight + + return ans diff --git a/solutions/1030. Matrix Cells in Distance Order/1030.cpp b/solutions/1030. Matrix Cells in Distance Order/1030.cpp new file mode 100644 index 00000000000..b8cefed67cf --- /dev/null +++ b/solutions/1030. Matrix Cells in Distance Order/1030.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector> allCellsDistOrder(int rows, int cols, int rCenter, + int cCenter) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + vector> ans; + vector> seen(rows, vector(cols)); + queue> q{{{rCenter, cCenter}}}; + seen[rCenter][cCenter] = true; + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + ans.push_back({i, j}); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == rows || y < 0 || y == cols) + continue; + if (seen[x][y]) + continue; + seen[x][y] = true; + q.emplace(x, y); + } + } + + return ans; + } +}; diff --git a/solutions/1030. Matrix Cells in Distance Order/1030.java b/solutions/1030. Matrix Cells in Distance Order/1030.java new file mode 100644 index 00000000000..3b7585e0dc7 --- /dev/null +++ b/solutions/1030. Matrix Cells in Distance Order/1030.java @@ -0,0 +1,27 @@ +class Solution { + public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + List ans = new ArrayList<>(); + boolean[][] seen = new boolean[rows][cols]; + Queue> q = new LinkedList<>(Arrays.asList(new Pair<>(rCenter, cCenter))); + seen[rCenter][cCenter] = true; + + while (!q.isEmpty()) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + ans.add(new int[] {i, j}); + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == rows || y < 0 || y == cols) + continue; + if (seen[x][y]) + continue; + seen[x][y] = true; + q.offer(new Pair<>(x, y)); + } + } + + return ans.toArray(int[][] ::new); + } +} diff --git a/solutions/1030. Matrix Cells in Distance Order/1030.py b/solutions/1030. Matrix Cells in Distance Order/1030.py new file mode 100644 index 00000000000..184392ef3a7 --- /dev/null +++ b/solutions/1030. Matrix Cells in Distance Order/1030.py @@ -0,0 +1,21 @@ +class Solution: + def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + ans = [] + q = collections.deque([(rCenter, cCenter)]) + seen = {(rCenter, cCenter)} + + while q: + i, j = q.popleft() + ans.append([i, j]) + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == rows or y < 0 or y == cols: + continue + if (x, y) in seen: + continue + seen.add((x, y)) + q.append((x, y)) + + return ans diff --git a/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.cpp b/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.cpp new file mode 100644 index 00000000000..e385c61e9e8 --- /dev/null +++ b/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int maxSumTwoNoOverlap(vector& nums, int firstLen, int secondLen) { + return max(helper(nums, firstLen, secondLen), + helper(nums, secondLen, firstLen)); + } + + private: + int helper(vector& A, int l, int r) { + const int n = A.size(); + vector left(n); + int sum = 0; + + for (int i = 0; i < n; ++i) { + sum += A[i]; + if (i >= l) + sum -= A[i - l]; + if (i >= l - 1) + left[i] = i > 0 ? max(left[i - 1], sum) : sum; + } + + vector right(n); + sum = 0; + + for (int i = n - 1; i >= 0; --i) { + sum += A[i]; + if (i <= n - r - 1) + sum -= A[i + r]; + if (i <= n - r) + right[i] = i < n - 1 ? max(right[i + 1], sum) : sum; + } + + int ans = 0; + + for (int i = 0; i < n - 1; ++i) + ans = max(ans, left[i] + right[i + 1]); + + return ans; + } +}; diff --git a/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.java b/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.java new file mode 100644 index 00000000000..a24082facfb --- /dev/null +++ b/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.java @@ -0,0 +1,37 @@ +class Solution { + public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) { + return Math.max(helper(nums, firstLen, secondLen), helper(nums, secondLen, firstLen)); + } + + private int helper(int[] A, int l, int r) { + final int n = A.length; + int[] left = new int[n]; + int sum = 0; + + for (int i = 0; i < n; ++i) { + sum += A[i]; + if (i >= l) + sum -= A[i - l]; + if (i >= l - 1) + left[i] = i > 0 ? Math.max(left[i - 1], sum) : sum; + } + + int[] right = new int[n]; + sum = 0; + + for (int i = n - 1; i >= 0; --i) { + sum += A[i]; + if (i <= n - r - 1) + sum -= A[i + r]; + if (i <= n - r) + right[i] = i < n - 1 ? Math.max(right[i + 1], sum) : sum; + } + + int ans = 0; + + for (int i = 0; i < n - 1; ++i) + ans = Math.max(ans, left[i] + right[i + 1]); + + return ans; + } +} diff --git a/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.py b/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.py new file mode 100644 index 00000000000..fa5ea1a7103 --- /dev/null +++ b/solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.py @@ -0,0 +1,27 @@ +class Solution: + def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int: + def helper(l: int, r: int) -> int: + n = len(nums) + left = [0] * n + summ = 0 + + for i in range(n): + summ += nums[i] + if i >= l: + summ -= nums[i - l] + if i >= l - 1: + left[i] = max(left[i - 1], summ) if i > 0 else summ + + right = [0] * n + summ = 0 + + for i in reversed(range(n)): + summ += nums[i] + if i <= n - r - 1: + summ -= nums[i + r] + if i <= n - r: + right[i] = max(right[i + 1], summ) if i < n - 1 else summ + + return max(left[i] + right[i + 1] for i in range(n - 1)) + + return max(helper(firstLen, secondLen), helper(secondLen, firstLen)) diff --git a/solutions/1032. Stream of Characters/1032.cpp b/solutions/1032. Stream of Characters/1032.cpp new file mode 100644 index 00000000000..9bc78cab4a9 --- /dev/null +++ b/solutions/1032. Stream of Characters/1032.cpp @@ -0,0 +1,44 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class StreamChecker { + public: + StreamChecker(vector& words) { + for (const string& word : words) + insert(word); + } + + bool query(char letter) { + letters += letter; + shared_ptr node = root; + + for (int i = letters.length() - 1; i >= 0; --i) { + const int index = letters[i] - 'a'; + if (node->children[index] == nullptr) + return false; + node = node->children[index]; + if (node->isWord) + return true; + } + + return false; + } + + private: + shared_ptr root = make_shared(); + string letters; + + void insert(const string& word) { + shared_ptr node = root; + for (int i = word.length() - 1; i >= 0; --i) { + const int index = word[i] - 'a'; + if (node->children[index] == nullptr) + node->children[index] = make_shared(); + node = node->children[index]; + } + node->isWord = true; + } +}; diff --git a/solutions/1032. Stream of Characters/1032.java b/solutions/1032. Stream of Characters/1032.java new file mode 100644 index 00000000000..fd7b15d87f7 --- /dev/null +++ b/solutions/1032. Stream of Characters/1032.java @@ -0,0 +1,41 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class StreamChecker { + public StreamChecker(String[] words) { + for (final String word : words) + insert(word); + } + + public boolean query(char letter) { + letters.append(letter); + TrieNode node = root; + + for (int i = letters.length() - 1; i >= 0; --i) { + final int index = letters.charAt(i) - 'a'; + if (node.children[index] == null) + return false; + node = node.children[index]; + if (node.isWord) + return true; + } + + return false; + } + + private TrieNode root = new TrieNode(); + private StringBuilder letters = new StringBuilder(); + + private void insert(final String word) { + TrieNode node = root; + for (int i = word.length() - 1; i >= 0; --i) { + final int index = word.charAt(i) - 'a'; + if (node.children[index] == null) + node.children[index] = new TrieNode(); + node = node.children[index]; + } + node.isWord = true; + } +} diff --git a/solutions/1032. Stream of Characters/1032.py b/solutions/1032. Stream of Characters/1032.py new file mode 100644 index 00000000000..ac85e2f3394 --- /dev/null +++ b/solutions/1032. Stream of Characters/1032.py @@ -0,0 +1,30 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.isWord = False + + +class StreamChecker: + def __init__(self, words: List[str]): + self.root = TrieNode() + self.letters = [] + + for word in words: + self._insert(word) + + def query(self, letter: str) -> bool: + self.letters.append(letter) + node = self.root + for c in reversed(self.letters): + if c not in node.children: + return False + node = node.children[c] + if node.isWord: + return True + return False + + def _insert(self, word: str) -> None: + node = self.root + for c in reversed(word): + node = node.children.setdefault(c, TrieNode()) + node.isWord = True diff --git a/solutions/1033. Moving Stones Until Consecutive/1033.cpp b/solutions/1033. Moving Stones Until Consecutive/1033.cpp new file mode 100644 index 00000000000..6bc291f88a7 --- /dev/null +++ b/solutions/1033. Moving Stones Until Consecutive/1033.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector numMovesStones(int a, int b, int c) { + vector nums = {a, b, c}; + + ranges::sort(nums); + + if (nums[2] - nums[0] == 2) + return {0, 0}; + return {min(nums[1] - nums[0], nums[2] - nums[1]) <= 2 ? 1 : 2, + nums[2] - nums[0] - 2}; + } +}; diff --git a/solutions/1033. Moving Stones Until Consecutive/1033.java b/solutions/1033. Moving Stones Until Consecutive/1033.java new file mode 100644 index 00000000000..ec01a19d847 --- /dev/null +++ b/solutions/1033. Moving Stones Until Consecutive/1033.java @@ -0,0 +1,12 @@ +class Solution { + public int[] numMovesStones(int a, int b, int c) { + int[] nums = new int[] {a, b, c}; + + Arrays.sort(nums); + + if (nums[2] - nums[0] == 2) + return new int[] {0, 0}; + return new int[] {Math.min(nums[1] - nums[0], nums[2] - nums[1]) <= 2 ? 1 : 2, + nums[2] - nums[0] - 2}; + } +} diff --git a/solutions/1033. Moving Stones Until Consecutive/1033.py b/solutions/1033. Moving Stones Until Consecutive/1033.py new file mode 100644 index 00000000000..7a13f75e200 --- /dev/null +++ b/solutions/1033. Moving Stones Until Consecutive/1033.py @@ -0,0 +1,8 @@ +class Solution: + def numMovesStones(self, a: int, b: int, c: int) -> List[int]: + nums = sorted([a, b, c]) + + if nums[2] - nums[0] == 2: + return [0, 0] + return [1 if min(nums[1] - nums[0], nums[2] - nums[1]) <= 2 else 2, + nums[2] - nums[0] - 2] diff --git a/solutions/1034. Coloring A Border/1034.cpp b/solutions/1034. Coloring A Border/1034.cpp new file mode 100644 index 00000000000..6aebd047d04 --- /dev/null +++ b/solutions/1034. Coloring A Border/1034.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector> colorBorder(vector>& grid, int r0, int c0, + int color) { + dfs(grid, r0, c0, grid[r0][c0]); + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] < 0) + grid[i][j] = color; + + return grid; + } + + private: + void dfs(vector>& grid, int i, int j, int startColor) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] != startColor) + return; + + grid[i][j] = -startColor; + dfs(grid, i + 1, j, startColor); + dfs(grid, i - 1, j, startColor); + dfs(grid, i, j + 1, startColor); + dfs(grid, i, j - 1, startColor); + + // If this cell is already on the boarder, it must be painted later. + if (i == 0 || i == grid.size() - 1 || j == 0 || j == grid[0].size() - 1) + return; + + if (abs(grid[i + 1][j]) == startColor && // + abs(grid[i - 1][j]) == startColor && // + abs(grid[i][j + 1]) == startColor && // + abs(grid[i][j - 1]) == startColor) + grid[i][j] = startColor; + } +}; diff --git a/solutions/1034. Coloring A Border/1034.java b/solutions/1034. Coloring A Border/1034.java new file mode 100644 index 00000000000..6267e6f7d37 --- /dev/null +++ b/solutions/1034. Coloring A Border/1034.java @@ -0,0 +1,35 @@ +class Solution { + public int[][] colorBorder(int[][] grid, int r0, int c0, int color) { + dfs(grid, r0, c0, grid[r0][c0]); + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] < 0) + grid[i][j] = color; + + return grid; + } + + private void dfs(int[][] grid, int i, int j, int startColor) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] != startColor) + return; + + grid[i][j] = -startColor; + dfs(grid, i + 1, j, startColor); + dfs(grid, i - 1, j, startColor); + dfs(grid, i, j + 1, startColor); + dfs(grid, i, j - 1, startColor); + + // If this cell is already on the boarder, it must be painted later. + if (i == 0 || i == grid.length - 1 || j == 0 || j == grid[0].length - 1) + return; + + if (Math.abs(grid[i + 1][j]) == startColor && // + Math.abs(grid[i - 1][j]) == startColor && // + Math.abs(grid[i][j + 1]) == startColor && // + Math.abs(grid[i][j - 1]) == startColor) + grid[i][j] = startColor; + } +} diff --git a/solutions/1034. Coloring A Border/1034.py b/solutions/1034. Coloring A Border/1034.py new file mode 100644 index 00000000000..921ce37e229 --- /dev/null +++ b/solutions/1034. Coloring A Border/1034.py @@ -0,0 +1,27 @@ +class Solution: + def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]: + def dfs(i: int, j: int, originalColor: int) -> None: + if not 0 <= i < len(grid) or not 0 <= j < len(grid[0]) or grid[i][j] != originalColor: + return + + grid[i][j] = -originalColor + dfs(i + 1, j, originalColor) + dfs(i - 1, j, originalColor) + dfs(i, j + 1, originalColor) + dfs(i, j - 1, originalColor) + + if 0 < i < len(grid) - 1 and 0 < j < len(grid[0]) - 1 and \ + abs(grid[i + 1][j]) == originalColor and \ + abs(grid[i - 1][j]) == originalColor and \ + abs(grid[i][j + 1]) == originalColor and \ + abs(grid[i][j - 1]) == originalColor: + grid[i][j] = originalColor + + dfs(r0, c0, grid[r0][c0]) + + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] < 0: + grid[i][j] = color + + return grid diff --git a/solutions/1035. Uncrossed Lines/1035.cpp b/solutions/1035. Uncrossed Lines/1035.cpp new file mode 100644 index 00000000000..7354a69b325 --- /dev/null +++ b/solutions/1035. Uncrossed Lines/1035.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxUncrossedLines(vector& nums1, vector& nums2) { + const int m = nums1.size(); + const int n = nums2.size(); + vector> dp(m + 1, vector(n + 1)); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + dp[i][j] = nums1[i - 1] == nums2[j - 1] + ? dp[i - 1][j - 1] + 1 + : max(dp[i - 1][j], dp[i][j - 1]); + + return dp[m][n]; + } +}; diff --git a/solutions/1035. Uncrossed Lines/1035.java b/solutions/1035. Uncrossed Lines/1035.java new file mode 100644 index 00000000000..e19569eb888 --- /dev/null +++ b/solutions/1035. Uncrossed Lines/1035.java @@ -0,0 +1,14 @@ +class Solution { + public int maxUncrossedLines(int[] nums1, int[] nums2) { + final int m = nums1.length; + final int n = nums2.length; + int[][] dp = new int[m + 1][n + 1]; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + dp[i][j] = nums1[i - 1] == nums2[j - 1] ? dp[i - 1][j - 1] + 1 + : Math.max(dp[i - 1][j], dp[i][j - 1]); + + return dp[m][n]; + } +} diff --git a/solutions/1035. Uncrossed Lines/1035.py b/solutions/1035. Uncrossed Lines/1035.py new file mode 100644 index 00000000000..37cf775c4db --- /dev/null +++ b/solutions/1035. Uncrossed Lines/1035.py @@ -0,0 +1,13 @@ +class Solution: + def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: + m = len(nums1) + n = len(nums2) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(1, m + 1): + for j in range(1, n + 1): + dp[i][j] = dp[i - 1][j - 1] + 1 \ + if nums1[i - 1] == nums2[j - 1] \ + else max(dp[i - 1][j], dp[i][j - 1]) + + return dp[m][n] diff --git a/solutions/1036. Escape a Large Maze/1036.cpp b/solutions/1036. Escape a Large Maze/1036.cpp new file mode 100644 index 00000000000..284cd9fd8c8 --- /dev/null +++ b/solutions/1036. Escape a Large Maze/1036.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + bool isEscapePossible(vector>& blocked, vector& source, + vector& target) { + unordered_set blockedSet; + for (const vector& b : blocked) + blockedSet.insert(hash(b[0], b[1])); + + return dfs(blockedSet, source[0], source[1], hash(target[0], target[1]), + {}) && + dfs(blockedSet, target[0], target[1], hash(source[0], source[1]), + {}); + } + + private: + bool dfs(unordered_set& blockedSet, int i, int j, long target, + unordered_set&& visited) { + if (i < 0 || i >= 1e6 || j < 0 || j >= 1e6 || + blockedSet.contains(hash(i, j)) || visited.contains(hash(i, j))) + return false; + + visited.insert(hash(i, j)); + if (visited.size() > (1 + 199) * 199 / 2 || hash(i, j) == target) + return true; + return dfs(blockedSet, i + 1, j, target, move(visited)) || + dfs(blockedSet, i - 1, j, target, move(visited)) || + dfs(blockedSet, i, j + 1, target, move(visited)) || + dfs(blockedSet, i, j - 1, target, move(visited)); + } + + long hash(int i, int j) { + return (static_cast(i) << 16) + j; + } +}; diff --git a/solutions/1036. Escape a Large Maze/1036.java b/solutions/1036. Escape a Large Maze/1036.java new file mode 100644 index 00000000000..c01b2ae3ed3 --- /dev/null +++ b/solutions/1036. Escape a Large Maze/1036.java @@ -0,0 +1,30 @@ +class Solution { + public boolean isEscapePossible(int[][] blocked, int[] source, int[] target) { + Set blockedSet = new HashSet<>(); + for (int[] b : blocked) + blockedSet.add(hash(b[0], b[1])); + + return dfs(blockedSet, source[0], source[1], hash(target[0], target[1]), new HashSet<>()) && + dfs(blockedSet, target[0], target[1], hash(source[0], source[1]), new HashSet<>()); + } + + private boolean dfs(Set blockedSet, int i, int j, long target, Set visited) { + if (i < 0 || i >= 1e6 || j < 0 || j >= 1e6 || blockedSet.contains(hash(i, j)) || + visited.contains(hash(i, j))) + return false; + + visited.add(hash(i, j)); + if (visited.size() > (1 + 199) * 199 / 2 || hash(i, j) == target) + return true; + + return // + dfs(blockedSet, i + 1, j, target, visited) || // + dfs(blockedSet, i - 1, j, target, visited) || // + dfs(blockedSet, i, j + 1, target, visited) || // + dfs(blockedSet, i, j - 1, target, visited); + } + + private long hash(int i, int j) { + return ((long) i << 16) + j; + } +} diff --git a/solutions/1036. Escape a Large Maze/1036.py b/solutions/1036. Escape a Large Maze/1036.py new file mode 100644 index 00000000000..1243bc4fd9b --- /dev/null +++ b/solutions/1036. Escape a Large Maze/1036.py @@ -0,0 +1,16 @@ +class Solution: + def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool: + def dfs(i: int, j: int, target: List[int], visited: set) -> bool: + if not 0 <= i < 10**6 or not 0 <= j < 10**6 or (i, j) in blocked or (i, j) in visited: + return False + + visited.add((i, j)) + if len(visited) > (1 + 199) * 199 // 2 or [i, j] == target: + return True + return dfs(i + 1, j, target, visited) or \ + dfs(i - 1, j, target, visited) or \ + dfs(i, j + 1, target, visited) or \ + dfs(i, j - 1, target, visited) + + blocked = set(tuple(b) for b in blocked) + return dfs(source[0], source[1], target, set()) and dfs(target[0], target[1], source, set()) diff --git a/solutions/1037. Valid Boomerang/1037.cpp b/solutions/1037. Valid Boomerang/1037.cpp new file mode 100644 index 00000000000..93ce31c886b --- /dev/null +++ b/solutions/1037. Valid Boomerang/1037.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + bool isBoomerang(vector>& points) { + return (points[1][0] - points[0][0]) * (points[2][1] - points[1][1]) != + (points[1][1] - points[0][1]) * (points[2][0] - points[1][0]); + } +}; diff --git a/solutions/1037. Valid Boomerang/1037.java b/solutions/1037. Valid Boomerang/1037.java new file mode 100644 index 00000000000..a6760b4ea49 --- /dev/null +++ b/solutions/1037. Valid Boomerang/1037.java @@ -0,0 +1,7 @@ +class Solution { + public boolean isBoomerang(int[][] points) { + return // + (points[1][0] - points[0][0]) * (points[2][1] - points[1][1]) != // + (points[1][1] - points[0][1]) * (points[2][0] - points[1][0]); + } +} diff --git a/solutions/1037. Valid Boomerang/1037.py b/solutions/1037. Valid Boomerang/1037.py new file mode 100644 index 00000000000..04545149387 --- /dev/null +++ b/solutions/1037. Valid Boomerang/1037.py @@ -0,0 +1,4 @@ +class Solution: + def isBoomerang(self, points: List[List[int]]) -> bool: + return (points[1][0] - points[0][0]) * (points[2][1] - points[1][1]) != \ + (points[1][1] - points[0][1]) * (points[2][0] - points[1][0]) diff --git a/solutions/1038. Binary Search Tree to Greater Sum Tree/1038.cpp b/solutions/1038. Binary Search Tree to Greater Sum Tree/1038.cpp new file mode 100644 index 00000000000..174be4b3a83 --- /dev/null +++ b/solutions/1038. Binary Search Tree to Greater Sum Tree/1038.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + TreeNode* bstToGst(TreeNode* root) { + int prefix = 0; + + function reversedInorder = [&](TreeNode* root) { + if (root == nullptr) + return; + + reversedInorder(root->right); + + root->val += prefix; + prefix = root->val; + + reversedInorder(root->left); + }; + + reversedInorder(root); + return root; + } +}; diff --git a/solutions/1039. Minimum Score Triangulation of Polygon/1039.cpp b/solutions/1039. Minimum Score Triangulation of Polygon/1039.cpp new file mode 100644 index 00000000000..0f1a741af9a --- /dev/null +++ b/solutions/1039. Minimum Score Triangulation of Polygon/1039.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minScoreTriangulation(vector& values) { + const int n = values.size(); + vector> dp(n, vector(n)); + + for (int j = 2; j < n; ++j) + for (int i = j - 2; i >= 0; --i) { + dp[i][j] = INT_MAX; + for (int k = i + 1; k < j; ++k) + dp[i][j] = + min(dp[i][j], + dp[i][k] + values[i] * values[k] * values[j] + dp[k][j]); + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/1039. Minimum Score Triangulation of Polygon/1039.java b/solutions/1039. Minimum Score Triangulation of Polygon/1039.java new file mode 100644 index 00000000000..ce7580c72b1 --- /dev/null +++ b/solutions/1039. Minimum Score Triangulation of Polygon/1039.java @@ -0,0 +1,15 @@ +class Solution { + public int minScoreTriangulation(int[] values) { + final int n = values.length; + int[][] dp = new int[n][n]; + + for (int j = 2; j < n; ++j) + for (int i = j - 2; i >= 0; --i) { + dp[i][j] = Integer.MAX_VALUE; + for (int k = i + 1; k < j; ++k) + dp[i][j] = Math.min(dp[i][j], dp[i][k] + values[i] * values[k] * values[j] + dp[k][j]); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/1039. Minimum Score Triangulation of Polygon/1039.py b/solutions/1039. Minimum Score Triangulation of Polygon/1039.py new file mode 100644 index 00000000000..0e96217226f --- /dev/null +++ b/solutions/1039. Minimum Score Triangulation of Polygon/1039.py @@ -0,0 +1,13 @@ +class Solution: + def minScoreTriangulation(self, values: List[int]) -> int: + n = len(values) + dp = [[0] * n for _ in range(n)] + + for j in range(2, n): + for i in range(j - 2, -1, -1): + dp[i][j] = math.inf + for k in range(i + 1, j): + dp[i][j] = min(dp[i][j], + dp[i][k] + values[i] * values[k] * values[j] + dp[k][j]) + + return dp[0][n - 1] diff --git a/solutions/104. Maximum Depth of Binary Tree/104.cpp b/solutions/104. Maximum Depth of Binary Tree/104.cpp new file mode 100644 index 00000000000..c1e44c29c1f --- /dev/null +++ b/solutions/104. Maximum Depth of Binary Tree/104.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int maxDepth(TreeNode* root) { + if (root == nullptr) + return 0; + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; diff --git a/solutions/104. Maximum Depth of Binary Tree/104.java b/solutions/104. Maximum Depth of Binary Tree/104.java new file mode 100644 index 00000000000..7acc621406a --- /dev/null +++ b/solutions/104. Maximum Depth of Binary Tree/104.java @@ -0,0 +1,7 @@ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) + return 0; + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } +} diff --git a/solutions/104. Maximum Depth of Binary Tree/104.py b/solutions/104. Maximum Depth of Binary Tree/104.py new file mode 100644 index 00000000000..811c922b64f --- /dev/null +++ b/solutions/104. Maximum Depth of Binary Tree/104.py @@ -0,0 +1,5 @@ +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) diff --git a/solutions/1040. Moving Stones Until Consecutive II/1040.cpp b/solutions/1040. Moving Stones Until Consecutive II/1040.cpp new file mode 100644 index 00000000000..a8d3b9b5da8 --- /dev/null +++ b/solutions/1040. Moving Stones Until Consecutive II/1040.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector numMovesStonesII(vector& stones) { + const int n = stones.size(); + int minMoves = n; + + ranges::sort(stones); + + for (int l = 0, r = 0; r < n; ++r) { + while (stones[r] - stones[l] + 1 > n) + ++l; + int alreadyStored = r - l + 1; + if (alreadyStored == n - 1 && stones[r] - stones[l] + 1 == n - 1) + minMoves = min(minMoves, 2); + else + minMoves = min(minMoves, n - alreadyStored); + } + + return {minMoves, max(stones[n - 1] - stones[1] - n + 2, + stones[n - 2] - stones[0] - n + 2)}; + } +}; diff --git a/solutions/1040. Moving Stones Until Consecutive II/1040.java b/solutions/1040. Moving Stones Until Consecutive II/1040.java new file mode 100644 index 00000000000..31821db4ea6 --- /dev/null +++ b/solutions/1040. Moving Stones Until Consecutive II/1040.java @@ -0,0 +1,21 @@ +class Solution { + public int[] numMovesStonesII(int[] stones) { + final int n = stones.length; + int minMoves = n; + + Arrays.sort(stones); + + for (int l = 0, r = 0; r < n; ++r) { + while (stones[r] - stones[l] + 1 > n) + ++l; + int alreadyStored = r - l + 1; + if (alreadyStored == n - 1 && stones[r] - stones[l] + 1 == n - 1) + minMoves = Math.min(minMoves, 2); + else + minMoves = Math.min(minMoves, n - alreadyStored); + } + + return new int[] { + minMoves, Math.max(stones[n - 1] - stones[1] - n + 2, stones[n - 2] - stones[0] - n + 2)}; + } +} diff --git a/solutions/1040. Moving Stones Until Consecutive II/1040.py b/solutions/1040. Moving Stones Until Consecutive II/1040.py new file mode 100644 index 00000000000..1388c6806a1 --- /dev/null +++ b/solutions/1040. Moving Stones Until Consecutive II/1040.py @@ -0,0 +1,18 @@ +class Solution: + def numMovesStonesII(self, stones: List[int]) -> List[int]: + n = len(stones) + minMoves = n + + stones.sort() + + l = 0 + for r, stone in enumerate(stones): + while stone - stones[l] + 1 > n: + l += 1 + alreadyStored = r - l + 1 + if alreadyStored == n - 1 and stone - stones[l] + 1 == n - 1: + minMoves = 2 + else: + minMoves = min(minMoves, n - alreadyStored) + + return [minMoves, max(stones[n - 1] - stones[1] - n + 2, stones[n - 2] - stones[0] - n + 2)] diff --git a/solutions/1041. Robot Bounded In Circle/1041.cpp b/solutions/1041. Robot Bounded In Circle/1041.cpp new file mode 100644 index 00000000000..beaa9b43f74 --- /dev/null +++ b/solutions/1041. Robot Bounded In Circle/1041.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool isRobotBounded(string instructions) { + int x = 0; + int y = 0; + int d = 0; + vector> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + for (char instruction : instructions) { + if (instruction == 'G') { + x += directions[d][0]; + y += directions[d][1]; + } else if (instruction == 'L') + d = (d + 3) % 4; + else + d = (d + 1) % 4; + } + + return x == 0 && y == 0 || d > 0; + } +}; diff --git a/solutions/1041. Robot Bounded In Circle/1041.java b/solutions/1041. Robot Bounded In Circle/1041.java new file mode 100644 index 00000000000..c51dc1a1a21 --- /dev/null +++ b/solutions/1041. Robot Bounded In Circle/1041.java @@ -0,0 +1,20 @@ +class Solution { + public boolean isRobotBounded(String instructions) { + int x = 0; + int y = 0; + int d = 0; + int[][] directions = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + for (char instruction : instructions.toCharArray()) { + if (instruction == 'G') { + x += directions[d][0]; + y += directions[d][1]; + } else if (instruction == 'L') + d = (d + 3) % 4; + else + d = (d + 1) % 4; + } + + return x == 0 && y == 0 || d > 0; + } +} diff --git a/solutions/1041. Robot Bounded In Circle/1041.py b/solutions/1041. Robot Bounded In Circle/1041.py new file mode 100644 index 00000000000..96d3c9ec166 --- /dev/null +++ b/solutions/1041. Robot Bounded In Circle/1041.py @@ -0,0 +1,17 @@ +class Solution: + def isRobotBounded(self, instructions: str) -> bool: + x = 0 + y = 0 + d = 0 + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] + + for instruction in instructions: + if instruction == 'G': + x += directions[d][0] + y += directions[d][1] + elif instruction == 'L': + d = (d + 3) % 4 + else: + d = (d + 1) % 4 + + return (x, y) == (0, 0) or d > 0 diff --git a/solutions/1042. Flower Planting With No Adjacent/1042.cpp b/solutions/1042. Flower Planting With No Adjacent/1042.cpp new file mode 100644 index 00000000000..210eeb777f7 --- /dev/null +++ b/solutions/1042. Flower Planting With No Adjacent/1042.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector gardenNoAdj(int n, vector>& paths) { + vector ans(n); // ans[i] := 1, 2, 3, or 4 + vector> graph(n); + + for (const vector& p : paths) { + const int u = p[0] - 1; + const int v = p[1] - 1; + graph[u].push_back(v); + graph[v].push_back(u); + } + + for (int i = 0; i < n; ++i) { + vector used(5); + for (const int v : graph[i]) + used[ans[v]] = true; + for (int type = 1; type < 5; ++type) + if (!used[type]) { + ans[i] = type; + break; + } + } + + return ans; + } +}; diff --git a/solutions/1042. Flower Planting With No Adjacent/1042.java b/solutions/1042. Flower Planting With No Adjacent/1042.java new file mode 100644 index 00000000000..12f5e2d7104 --- /dev/null +++ b/solutions/1042. Flower Planting With No Adjacent/1042.java @@ -0,0 +1,29 @@ +class Solution { + public int[] gardenNoAdj(int n, int[][] paths) { + int[] ans = new int[n]; // ans[i] := 1, 2, 3, or 4 + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] p : paths) { + final int u = p[0] - 1; + final int v = p[1] - 1; + graph[u].add(v); + graph[v].add(u); + } + + for (int i = 0; i < n; ++i) { + boolean[] used = new boolean[5]; + for (final int v : graph[i]) + used[ans[v]] = true; + for (int type = 1; type < 5; ++type) + if (!used[type]) { + ans[i] = type; + break; + } + } + + return ans; + } +} diff --git a/solutions/1042. Flower Planting With No Adjacent/1042.py b/solutions/1042. Flower Planting With No Adjacent/1042.py new file mode 100644 index 00000000000..5b179e494b1 --- /dev/null +++ b/solutions/1042. Flower Planting With No Adjacent/1042.py @@ -0,0 +1,21 @@ +class Solution: + def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]: + ans = [0] * n # ans[i] := 1, 2, 3, or 4 + graph = [[] for _ in range(n)] + + for a, b in paths: + u = a - 1 + v = b - 1 + graph[u].append(v) + graph[v].append(u) + + for i in range(n): + used = [False] * 5 + for v in graph[i]: + used[ans[v]] = True + for type in range(1, 5): + if not used[type]: + ans[i] = type + break + + return ans diff --git a/solutions/1043. Partition Array for Maximum Sum/1043.cpp b/solutions/1043. Partition Array for Maximum Sum/1043.cpp new file mode 100644 index 00000000000..4431894470b --- /dev/null +++ b/solutions/1043. Partition Array for Maximum Sum/1043.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxSumAfterPartitioning(vector& arr, int k) { + const int n = arr.size(); + vector dp(n + 1); + + for (int i = 1; i <= n; ++i) { + int mx = INT_MIN; + for (int j = 1; j <= min(i, k); ++j) { + mx = max(mx, arr[i - j]); + dp[i] = max(dp[i], dp[i - j] + mx * j); + } + } + + return dp[n]; + } +}; diff --git a/solutions/1043. Partition Array for Maximum Sum/1043.java b/solutions/1043. Partition Array for Maximum Sum/1043.java new file mode 100644 index 00000000000..fa691dd2c1a --- /dev/null +++ b/solutions/1043. Partition Array for Maximum Sum/1043.java @@ -0,0 +1,16 @@ +class Solution { + public int maxSumAfterPartitioning(int[] arr, int k) { + final int n = arr.length; + int[] dp = new int[n + 1]; + + for (int i = 1; i <= n; ++i) { + int mx = Integer.MIN_VALUE; + for (int j = 1; j <= Math.max(i, k); ++j) { + mx = Math.max(mx, arr[i - j]); + dp[i] = Math.max(dp[i], dp[i - j] + mx * j); + } + } + + return dp[n]; + } +} diff --git a/solutions/1043. Partition Array for Maximum Sum/1043.py b/solutions/1043. Partition Array for Maximum Sum/1043.py new file mode 100644 index 00000000000..59c1f83147f --- /dev/null +++ b/solutions/1043. Partition Array for Maximum Sum/1043.py @@ -0,0 +1,12 @@ +class Solution: + def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int: + n = len(arr) + dp = [0] * (n + 1) + + for i in range(1, n + 1): + mx = -math.inf + for j in range(1, min(i, k) + 1): + mx = max(mx, arr[i - j]) + dp[i] = max(dp[i], dp[i - j] + mx * j) + + return dp[n] diff --git a/solutions/1044. Longest Duplicate Substring/1044.cpp b/solutions/1044. Longest Duplicate Substring/1044.cpp new file mode 100644 index 00000000000..f7f35ae2f3f --- /dev/null +++ b/solutions/1044. Longest Duplicate Substring/1044.cpp @@ -0,0 +1,65 @@ +class Solution { + public: + string longestDupSubstring(string s) { + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + vector pows(n, 1); + int bestStart = -1; + int l = 1; + int r = n; + + for (int i = 1; i < n; ++i) + pows[i] = (pows[i - 1] * 26L) % kMod; + + while (l < r) { + const int m = (l + r) / 2; + const int start = getStart(s, m, pows, kMod); + if (start == -1) { + r = m; + } else { + bestStart = start; + l = m + 1; + } + } + + if (bestStart == -1) + return ""; + if (getStart(s, l, pows, kMod) == -1) + return s.substr(bestStart, l - 1); + return s.substr(bestStart, l); + } + + private: + // k := the length of the substring to be hashed + int getStart(const string& s, int k, const vector& pows, + const int& kMod) { + unordered_map> hashToStarts; + long h = 0; + + // Compute the hash value of s[:k]. + for (int i = 0; i < k; ++i) + h = ((h * 26) % kMod + val(s[i])) % kMod; + hashToStarts[h].push_back(0); + + // Compute the rolling hash by Rabin Karp. + for (int i = k; i < s.length(); ++i) { + const int startIndex = i - k + 1; + h = ((h - static_cast(pows[k - 1]) * val(s[i - k])) % kMod + kMod) % + kMod; + h = (h * 26 + val(s[i])) % kMod; + if (const auto it = hashToStarts.find(h); it != hashToStarts.cend()) { + const string currSub = s.substr(startIndex, k); + for (const int start : it->second) + if (s.substr(start, k) == currSub) + return startIndex; + } + hashToStarts[h].push_back(startIndex); + } + + return -1; + } + + constexpr int val(char c) { + return c - 'a'; + } +}; diff --git a/solutions/1044. Longest Duplicate Substring/1044.java b/solutions/1044. Longest Duplicate Substring/1044.java new file mode 100644 index 00000000000..7cbe005bd59 --- /dev/null +++ b/solutions/1044. Longest Duplicate Substring/1044.java @@ -0,0 +1,64 @@ +class Solution { + public String longestDupSubstring(String s) { + final int kMod = 1_000_000_007; + final int n = s.length(); + int[] pows = new int[n]; + int bestStart = -1; + int l = 1; + int r = n; + + pows[0] = 1; + for (int i = 1; i < n; ++i) + pows[i] = (int) ((pows[i - 1] * 26L) % (long) kMod); + + while (l < r) { + final int m = (l + r) / 2; + final int start = getStart(s, m, pows, kMod); + if (start == -1) { + r = m; + } else { + bestStart = start; + l = m + 1; + } + } + + if (bestStart == -1) + return ""; + if (getStart(s, l, pows, kMod) == -1) + return s.substring(bestStart, bestStart + l - 1); + return s.substring(bestStart, bestStart + l); + } + + // k := the length of the substring to be hashed + private int getStart(final String s, int k, int[] pows, int kMod) { + Map> hashToStarts = new HashMap<>(); + long h = 0; + + // Compute the hash value of s[:k]. + for (int i = 0; i < k; ++i) + h = ((h * 26) % kMod + val(s.charAt(i))) % kMod; + hashToStarts.put(h, new ArrayList<>()); + hashToStarts.get(h).add(0); + + // Compute the rolling hash by Rabin Karp. + for (int i = k; i < s.length(); ++i) { + final int startIndex = i - k + 1; + h = ((h - (long) (pows[k - 1]) * val(s.charAt(i - k))) % kMod + kMod) % kMod; + h = (h * 26 + val(s.charAt(i))) % kMod; + if (hashToStarts.containsKey(h)) { + final String currSub = s.substring(startIndex, startIndex + k); + for (final int start : hashToStarts.get(h)) + if (s.substring(start, start + k).equals(currSub)) + return startIndex; + } + hashToStarts.put(h, new ArrayList<>()); + hashToStarts.get(h).add(startIndex); + } + + return -1; + } + + private int val(char c) { + return c - 'a'; + } +} diff --git a/solutions/1044. Longest Duplicate Substring/1044.py b/solutions/1044. Longest Duplicate Substring/1044.py new file mode 100644 index 00000000000..ec45f22de10 --- /dev/null +++ b/solutions/1044. Longest Duplicate Substring/1044.py @@ -0,0 +1,47 @@ +class Solution: + def longestDupSubstring(self, s: str) -> str: + kMod = 1_000_000_007 + bestStart = -1 + l = 1 + r = len(s) + + def val(c: str) -> int: + return ord(c) - ord('a') + + # k := the length of the substring to be hashed + def getStart(k: int) -> Optional[int]: + maxPow = pow(26, k - 1, kMod) + hashToStart = collections.defaultdict(list) + h = 0 + + # Compute the hash value of s[:k]. + for i in range(k): + h = (h * 26 + val(s[i])) % kMod + hashToStart[h].append(0) + + # Compute the rolling hash by Rabin Karp. + for i in range(k, len(s)): + startIndex = i - k + 1 + h = (h - maxPow * val(s[i - k])) % kMod + h = (h * 26 + val(s[i])) % kMod + if h in hashToStart: + currSub = s[startIndex:startIndex + k] + for start in hashToStart[h]: + if s[start:start + k] == currSub: + return startIndex + hashToStart[h].append(startIndex) + + while l < r: + m = (l + r) // 2 + start: Optional[int] = getStart(m) + if start: + bestStart = start + l = m + 1 + else: + r = m + + if bestStart == -1: + return '' + if getStart(l): + return s[bestStart:bestStart + l] + return s[bestStart:bestStart + l - 1] diff --git a/solutions/1045. Customers Who Bought All Products/1045.sql b/solutions/1045. Customers Who Bought All Products/1045.sql new file mode 100644 index 00000000000..6f3601deea9 --- /dev/null +++ b/solutions/1045. Customers Who Bought All Products/1045.sql @@ -0,0 +1,6 @@ +SELECT customer_id +FROM Customer +GROUP BY 1 +HAVING COUNT(DISTINCT product_key) = ( + SELECT COUNT(*) FROM Product + ); diff --git a/solutions/1046. Last Stone Weight/1046.cpp b/solutions/1046. Last Stone Weight/1046.cpp new file mode 100644 index 00000000000..b183a8c94d9 --- /dev/null +++ b/solutions/1046. Last Stone Weight/1046.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int lastStoneWeight(vector& stones) { + priority_queue pq{stones.begin(), stones.end()}; + + while (pq.size() >= 2) { + const int n1 = pq.top(); + pq.pop(); + const int n2 = pq.top(); + pq.pop(); + if (n1 != n2) + pq.push(n1 - n2); + } + + return pq.empty() ? 0 : pq.top(); + } +}; diff --git a/solutions/1046. Last Stone Weight/1046.java b/solutions/1046. Last Stone Weight/1046.java new file mode 100644 index 00000000000..470d90b2b7f --- /dev/null +++ b/solutions/1046. Last Stone Weight/1046.java @@ -0,0 +1,17 @@ +class Solution { + public int lastStoneWeight(int[] stones) { + Queue pq = new PriorityQueue<>(Collections.reverseOrder()); + + for (final int stone : stones) + pq.offer(stone); + + while (pq.size() >= 2) { + final int n1 = pq.poll(); + final int n2 = pq.poll(); + if (n1 != n2) + pq.offer(n1 - n2); + } + + return pq.isEmpty() ? 0 : pq.peek(); + } +} diff --git a/solutions/1046. Last Stone Weight/1046.py b/solutions/1046. Last Stone Weight/1046.py new file mode 100644 index 00000000000..687ca4532ef --- /dev/null +++ b/solutions/1046. Last Stone Weight/1046.py @@ -0,0 +1,12 @@ +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + pq = [-stone for stone in stones] + heapq.heapify(pq) + + while len(pq) >= 2: + n1 = -heapq.heappop(pq) + n2 = -heapq.heappop(pq) + if n1 != n2: + heapq.heappush(pq, -(n1 - n2)) + + return 0 if not pq else -pq[0] diff --git a/solutions/1047. Remove All Adjacent Duplicates In String/1047.cpp b/solutions/1047. Remove All Adjacent Duplicates In String/1047.cpp new file mode 100644 index 00000000000..f13f2d6e477 --- /dev/null +++ b/solutions/1047. Remove All Adjacent Duplicates In String/1047.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string removeDuplicates(const string& S) { + string ans; + + for (const char c : S) + if (!ans.empty() && ans.back() == c) + ans.pop_back(); + else + ans.push_back(c); + + return ans; + } +}; diff --git a/solutions/1047. Remove All Adjacent Duplicates In String/1047.java b/solutions/1047. Remove All Adjacent Duplicates In String/1047.java new file mode 100644 index 00000000000..69a55a7f937 --- /dev/null +++ b/solutions/1047. Remove All Adjacent Duplicates In String/1047.java @@ -0,0 +1,15 @@ +class Solution { + public String removeDuplicates(final String S) { + StringBuilder sb = new StringBuilder(); + + for (final char c : S.toCharArray()) { + final int n = sb.length(); + if (n > 0 && sb.charAt(n - 1) == c) + sb.deleteCharAt(n - 1); + else + sb.append(c); + } + + return sb.toString(); + } +} diff --git a/solutions/1048. Longest String Chain/1048-2.cpp b/solutions/1048. Longest String Chain/1048-2.cpp new file mode 100644 index 00000000000..41b15e7ac7d --- /dev/null +++ b/solutions/1048. Longest String Chain/1048-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int longestStrChain(vector& words) { + int ans = 0; + // dp[s] := the longest string chain, where s is the last word + unordered_map dp; + + ranges::sort(words, [](const string& a, const string& b) { + return a.length() < b.length(); + }); + + for (const string& word : words) { + for (int i = 0; i < word.length(); ++i) { + const string pred = word.substr(0, i) + word.substr(i + 1); + dp[word] = max(dp[word], (dp.contains(pred) ? dp[pred] : 0) + 1); + } + ans = max(ans, dp[word]); + } + + return ans; + } +}; diff --git a/solutions/1048. Longest String Chain/1048-2.java b/solutions/1048. Longest String Chain/1048-2.java new file mode 100644 index 00000000000..bbd2bad1ca7 --- /dev/null +++ b/solutions/1048. Longest String Chain/1048-2.java @@ -0,0 +1,20 @@ +class Solution { + public int longestStrChain(String[] words) { + int ans = 0; + Map dp = new HashMap<>(); + + Arrays.sort(words, (a, b) -> a.length() - b.length()); + + for (final String word : words) { + int bestLength = 0; + for (int i = 0; i < word.length(); ++i) { + final String pred = word.substring(0, i) + word.substring(i + 1); + bestLength = Math.max(bestLength, dp.getOrDefault(pred, 0) + 1); + } + dp.put(word, bestLength); + ans = Math.max(ans, bestLength); + } + + return ans; + } +} diff --git a/solutions/1048. Longest String Chain/1048-2.py b/solutions/1048. Longest String Chain/1048-2.py new file mode 100644 index 00000000000..3dbcbbab0f1 --- /dev/null +++ b/solutions/1048. Longest String Chain/1048-2.py @@ -0,0 +1,9 @@ +class Solution: + def longestStrChain(self, words: List[str]) -> int: + dp = {} + + for word in sorted(words, key=len): + dp[word] = max(dp.get(word[:i] + word[i + 1:], 0) + + 1 for i in range(len(word))) + + return max(dp.values()) diff --git a/solutions/1048. Longest String Chain/1048.cpp b/solutions/1048. Longest String Chain/1048.cpp new file mode 100644 index 00000000000..a579ac47c30 --- /dev/null +++ b/solutions/1048. Longest String Chain/1048.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int longestStrChain(vector& words) { + const unordered_set wordsSet{words.begin(), words.end()}; + unordered_map mem; + return accumulate(words.begin(), words.end(), 0, + [&](int acc, const string& word) { + return max(acc, longestStrChain(word, wordsSet, mem)); + }); + } + + private: + // Returns the longest string chain, where s is the last word. + int longestStrChain(const string& s, const unordered_set& wordsSet, + unordered_map& mem) { + if (const auto it = mem.find(s); it != mem.cend()) + return it->second; + + int res = 1; + + for (int i = 0; i < s.length(); ++i) { + const string pred = s.substr(0, i) + s.substr(i + 1); + if (wordsSet.contains(pred)) + res = max(res, longestStrChain(pred, wordsSet, mem) + 1); + } + + return mem[s] = res; + } +}; diff --git a/solutions/1048. Longest String Chain/1048.java b/solutions/1048. Longest String Chain/1048.java new file mode 100644 index 00000000000..c97c9d3dd5f --- /dev/null +++ b/solutions/1048. Longest String Chain/1048.java @@ -0,0 +1,29 @@ +class Solution { + public int longestStrChain(String[] words) { + Set wordsSet = new HashSet<>(Arrays.asList(words)); + int ans = 0; + + for (final String word : words) + ans = Math.max(ans, longestStrChain(word, wordsSet)); + + return ans; + } + // dp[s] := the longest string chain, where s is the last word + private Map dp = new HashMap<>(); + + private int longestStrChain(final String s, Set wordsSet) { + if (dp.containsKey(s)) + return dp.get(s); + + int ans = 1; + + for (int i = 0; i < s.length(); ++i) { + final String pred = s.substring(0, i) + s.substring(i + 1); + if (wordsSet.contains(pred)) + ans = Math.max(ans, longestStrChain(pred, wordsSet) + 1); + } + + dp.put(s, ans); + return ans; + } +} diff --git a/solutions/1048. Longest String Chain/1048.py b/solutions/1048. Longest String Chain/1048.py new file mode 100644 index 00000000000..971e83cfdde --- /dev/null +++ b/solutions/1048. Longest String Chain/1048.py @@ -0,0 +1,15 @@ +class Solution: + def longestStrChain(self, words: List[str]) -> int: + wordsSet = set(words) + + @functools.lru_cache(None) + def dp(s: str) -> int: + """Returns the longest chain where s is the last word.""" + ans = 1 + for i in range(len(s)): + pred = s[:i] + s[i + 1:] + if pred in wordsSet: + ans = max(ans, dp(pred) + 1) + return ans + + return max(dp(word) for word in words) diff --git a/solutions/1049. Last Stone Weight II/1049.cpp b/solutions/1049. Last Stone Weight II/1049.cpp new file mode 100644 index 00000000000..69de46b668f --- /dev/null +++ b/solutions/1049. Last Stone Weight II/1049.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int lastStoneWeightII(vector& stones) { + const int sum = accumulate(stones.begin(), stones.end(), 0); + vector dp(sum + 1); + dp[0] = true; + int s = 0; + + for (int stone : stones) + for (int w = sum / 2; w > 0; --w) { + if (w >= stone) + dp[w] = dp[w] || dp[w - stone]; + if (dp[w]) + s = max(s, w); + } + + return sum - 2 * s; + } +}; diff --git a/solutions/1049. Last Stone Weight II/1049.java b/solutions/1049. Last Stone Weight II/1049.java new file mode 100644 index 00000000000..04e66f7c704 --- /dev/null +++ b/solutions/1049. Last Stone Weight II/1049.java @@ -0,0 +1,18 @@ +class Solution { + public int lastStoneWeightII(int[] stones) { + final int sum = Arrays.stream(stones).sum(); + boolean[] dp = new boolean[sum + 1]; + dp[0] = true; + int s = 0; + + for (int stone : stones) + for (int w = sum / 2; w > 0; --w) { + if (w >= stone) + dp[w] = dp[w] || dp[w - stone]; + if (dp[w]) + s = Math.max(s, w); + } + + return sum - 2 * s; + } +} diff --git a/solutions/1049. Last Stone Weight II/1049.py b/solutions/1049. Last Stone Weight II/1049.py new file mode 100644 index 00000000000..c98bee7c197 --- /dev/null +++ b/solutions/1049. Last Stone Weight II/1049.py @@ -0,0 +1,14 @@ +class Solution: + def lastStoneWeightII(self, stones: List[int]) -> int: + summ = sum(stones) + s = 0 + dp = [True] + [False] * summ + + for stone in stones: + for w in range(summ // 2 + 1)[::-1]: + if w >= stone: + dp[w] = dp[w] or dp[w - stone] + if dp[w]: + s = max(s, w) + + return summ - 2 * s diff --git a/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.cpp b/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.cpp new file mode 100644 index 00000000000..423eb048af8 --- /dev/null +++ b/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + unordered_map inToIndex; + + for (int i = 0; i < inorder.size(); ++i) + inToIndex[inorder[i]] = i; + + return build(preorder, 0, preorder.size() - 1, inorder, 0, + inorder.size() - 1, inToIndex); + } + + private: + TreeNode* build(const vector& preorder, int preStart, int preEnd, + const vector& inorder, int inStart, int inEnd, + const unordered_map& inToIndex) { + if (preStart > preEnd) + return nullptr; + + const int rootVal = preorder[preStart]; + const int rootInIndex = inToIndex.at(rootVal); + const int leftSize = rootInIndex - inStart; + + TreeNode* root = new TreeNode(rootVal); + root->left = build(preorder, preStart + 1, preStart + leftSize, inorder, + inStart, rootInIndex - 1, inToIndex); + root->right = build(preorder, preStart + leftSize + 1, preEnd, inorder, + rootInIndex + 1, inEnd, inToIndex); + return root; + } +}; diff --git a/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.java b/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.java new file mode 100644 index 00000000000..5360949755e --- /dev/null +++ b/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.java @@ -0,0 +1,28 @@ +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + Map inToIndex = new HashMap<>(); + + for (int i = 0; i < inorder.length; ++i) + inToIndex.put(inorder[i], i); + + return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, inToIndex); + } + + private TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, + int inEnd, Map inToIndex) { + if (preStart > preEnd) + return null; + + final int rootVal = preorder[preStart]; + final int rootInIndex = inToIndex.get(rootVal); + final int leftSize = rootInIndex - inStart; + + TreeNode root = new TreeNode(rootVal); + root.left = build(preorder, preStart + 1, preStart + leftSize, inorder, inStart, + rootInIndex - 1, inToIndex); + root.right = build(preorder, preStart + leftSize + 1, preEnd, inorder, rootInIndex + 1, inEnd, + inToIndex); + + return root; + } +} diff --git a/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.py b/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.py new file mode 100644 index 00000000000..05ac355377c --- /dev/null +++ b/solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.py @@ -0,0 +1,20 @@ +class Solution: + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: + inToIndex = {num: i for i, num in enumerate(inorder)} + + def build(preStart: int, preEnd: int, inStart: int, inEnd: int) -> Optional[TreeNode]: + if preStart > preEnd: + return None + + rootVal = preorder[preStart] + rootInIndex = inToIndex[rootVal] + leftSize = rootInIndex - inStart + + root = TreeNode(rootVal) + root.left = build(preStart + 1, preStart + leftSize, + inStart, rootInIndex - 1) + root.right = build(preStart + leftSize + 1, + preEnd, rootInIndex + 1, inEnd) + return root + + return build(0, len(preorder) - 1, 0, len(inorder) - 1) diff --git a/solutions/1050. Actors and Directors Who Cooperated At Least Three Times/1050.sql b/solutions/1050. Actors and Directors Who Cooperated At Least Three Times/1050.sql new file mode 100644 index 00000000000..cd3ef8fd04b --- /dev/null +++ b/solutions/1050. Actors and Directors Who Cooperated At Least Three Times/1050.sql @@ -0,0 +1,4 @@ +SELECT actor_id, director_id +FROM ActorDirector +GROUP BY 1, 2 +HAVING COUNT(*) >= 3; diff --git a/solutions/1051. Height Checker/1051.cpp b/solutions/1051. Height Checker/1051.cpp new file mode 100644 index 00000000000..9b8535cca3e --- /dev/null +++ b/solutions/1051. Height Checker/1051.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int heightChecker(vector& heights) { + int ans = 0; + int currentHeight = 1; + vector count(101); + + for (int height : heights) + ++count[height]; + + for (int height : heights) { + while (count[currentHeight] == 0) + ++currentHeight; + if (height != currentHeight) + ++ans; + --count[currentHeight]; + } + + return ans; + } +}; diff --git a/solutions/1051. Height Checker/1051.java b/solutions/1051. Height Checker/1051.java new file mode 100644 index 00000000000..7dcf378ebf4 --- /dev/null +++ b/solutions/1051. Height Checker/1051.java @@ -0,0 +1,20 @@ +class Solution { + public int heightChecker(int[] heights) { + int ans = 0; + int currentHeight = 1; + int[] count = new int[101]; + + for (int height : heights) + ++count[height]; + + for (int height : heights) { + while (count[currentHeight] == 0) + ++currentHeight; + if (height != currentHeight) + ++ans; + --count[currentHeight]; + } + + return ans; + } +} diff --git a/solutions/1051. Height Checker/1051.py b/solutions/1051. Height Checker/1051.py new file mode 100644 index 00000000000..c4aad17a37d --- /dev/null +++ b/solutions/1051. Height Checker/1051.py @@ -0,0 +1,17 @@ +class Solution: + def heightChecker(self, heights: List[int]) -> int: + ans = 0 + currentHeight = 1 + count = [0] * 101 + + for height in heights: + count[height] += 1 + + for height in heights: + while count[currentHeight] == 0: + currentHeight += 1 + if height != currentHeight: + ans += 1 + count[currentHeight] -= 1 + + return ans diff --git a/solutions/1052. Grumpy Bookstore Owner/1052.cpp b/solutions/1052. Grumpy Bookstore Owner/1052.cpp new file mode 100644 index 00000000000..f35aad4ec42 --- /dev/null +++ b/solutions/1052. Grumpy Bookstore Owner/1052.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxSatisfied(vector& customers, vector& grumpy, int X) { + int satisfied = 0; + int madeSatisfied = 0; + int windowSatisfied = 0; + + for (int i = 0; i < customers.size(); ++i) { + if (grumpy[i] == 0) + satisfied += customers[i]; + else + windowSatisfied += customers[i]; + if (i >= X && grumpy[i - X] == 1) + windowSatisfied -= customers[i - X]; + madeSatisfied = max(madeSatisfied, windowSatisfied); + } + + return satisfied + madeSatisfied; + } +}; diff --git a/solutions/1052. Grumpy Bookstore Owner/1052.java b/solutions/1052. Grumpy Bookstore Owner/1052.java new file mode 100644 index 00000000000..f64e9a632b3 --- /dev/null +++ b/solutions/1052. Grumpy Bookstore Owner/1052.java @@ -0,0 +1,19 @@ +class Solution { + public int maxSatisfied(int[] customers, int[] grumpy, int X) { + int satisfied = 0; + int madeSatisfied = 0; + int windowSatisfied = 0; + + for (int i = 0; i < customers.length; ++i) { + if (grumpy[i] == 0) + satisfied += customers[i]; + else + windowSatisfied += customers[i]; + if (i >= X && grumpy[i - X] == 1) + windowSatisfied -= customers[i - X]; + madeSatisfied = Math.max(madeSatisfied, windowSatisfied); + } + + return satisfied + madeSatisfied; + } +} diff --git a/solutions/1052. Grumpy Bookstore Owner/1052.py b/solutions/1052. Grumpy Bookstore Owner/1052.py new file mode 100644 index 00000000000..d7a25881b22 --- /dev/null +++ b/solutions/1052. Grumpy Bookstore Owner/1052.py @@ -0,0 +1,14 @@ +class Solution: + def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int: + satisfied = sum(c for i, c in enumerate(customers) if grumpy[i] == 0) + madeSatisfied = 0 + windowSatisfied = 0 + + for i, customer in enumerate(customers): + if grumpy[i] == 1: + windowSatisfied += customer + if i >= X and grumpy[i - X] == 1: + windowSatisfied -= customers[i - X] + madeSatisfied = max(madeSatisfied, windowSatisfied) + + return satisfied + madeSatisfied diff --git a/solutions/1053. Previous Permutation With One Swap/1053.cpp b/solutions/1053. Previous Permutation With One Swap/1053.cpp new file mode 100644 index 00000000000..027758a80db --- /dev/null +++ b/solutions/1053. Previous Permutation With One Swap/1053.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector prevPermOpt1(vector& arr) { + const int n = arr.size(); + int l = n - 2; + int r = n - 1; + + while (l >= 0 && arr[l] <= arr[l + 1]) + l--; + if (l < 0) + return arr; + while (arr[r] >= arr[l] || arr[r] == arr[r - 1]) + r--; + swap(arr[l], arr[r]); + + return arr; + } +}; diff --git a/solutions/1053. Previous Permutation With One Swap/1053.java b/solutions/1053. Previous Permutation With One Swap/1053.java new file mode 100644 index 00000000000..33637d88daa --- /dev/null +++ b/solutions/1053. Previous Permutation With One Swap/1053.java @@ -0,0 +1,23 @@ +class Solution { + public int[] prevPermOpt1(int[] arr) { + final int n = arr.length; + int l = n - 2; + int r = n - 1; + + while (l >= 0 && arr[l] <= arr[l + 1]) + l--; + if (l < 0) + return arr; + while (arr[r] >= arr[l] || arr[r] == arr[r - 1]) + r--; + swap(arr, l, r); + + return arr; + } + + private void swap(int[] arr, int l, int r) { + int temp = arr[l]; + arr[l] = arr[r]; + arr[r] = temp; + } +} diff --git a/solutions/1053. Previous Permutation With One Swap/1053.py b/solutions/1053. Previous Permutation With One Swap/1053.py new file mode 100644 index 00000000000..30040585b73 --- /dev/null +++ b/solutions/1053. Previous Permutation With One Swap/1053.py @@ -0,0 +1,15 @@ +class Solution: + def prevPermOpt1(self, arr: List[int]) -> List[int]: + n = len(arr) + l = n - 2 + r = n - 1 + + while l >= 0 and arr[l] <= arr[l + 1]: + l -= 1 + if l < 0: + return arr + while arr[r] >= arr[l] or arr[r] == arr[r - 1]: + r -= 1 + arr[l], arr[r] = arr[r], arr[l] + + return arr diff --git a/solutions/1054. Distant Barcodes/1054.cpp b/solutions/1054. Distant Barcodes/1054.cpp new file mode 100644 index 00000000000..16cc2736539 --- /dev/null +++ b/solutions/1054. Distant Barcodes/1054.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector rearrangeBarcodes(vector& barcodes) { + vector ans(barcodes.size()); + vector count(10001); + int i = 0; // ans' index + + for (const int b : barcodes) + ++count[b]; + + const auto maxIt = ranges::max_element(count); + const int maxNum = maxIt - count.begin(); + + auto fillAns = [&](int num) { + while (count[num]-- > 0) { + ans[i] = num; + i = i + 2 < barcodes.size() ? i + 2 : 1; + } + }; + + fillAns(maxNum); + for (int num = 1; num < 10001; ++num) + fillAns(num); + + return ans; + } +}; diff --git a/solutions/1054. Distant Barcodes/1054.java b/solutions/1054. Distant Barcodes/1054.java new file mode 100644 index 00000000000..dedd4fba264 --- /dev/null +++ b/solutions/1054. Distant Barcodes/1054.java @@ -0,0 +1,32 @@ +class Solution { + public int[] rearrangeBarcodes(int[] barcodes) { + int[] ans = new int[barcodes.length]; + int[] count = new int[10001]; + int maxCount = 0; + int maxNum = 0; + + for (final int b : barcodes) + ++count[b]; + + for (int i = 1; i < 10001; ++i) + if (count[i] > maxCount) { + maxCount = count[i]; + maxNum = i; + } + + fillAns(ans, count, maxNum, barcodes.length); + for (int num = 1; num < 10001; ++num) + fillAns(ans, count, num, barcodes.length); + + return ans; + } + + private int i = 0; // ans' index + + private void fillAns(int[] ans, int[] count, int num, int n) { + while (count[num]-- > 0) { + ans[i] = num; + i = i + 2 < n ? i + 2 : 1; + } + } +} diff --git a/solutions/1054. Distant Barcodes/1054.py b/solutions/1054. Distant Barcodes/1054.py new file mode 100644 index 00000000000..6d4d4be61bd --- /dev/null +++ b/solutions/1054. Distant Barcodes/1054.py @@ -0,0 +1,19 @@ +class Solution: + def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]: + ans = [0] * len(barcodes) + count = collections.Counter(barcodes) + i = 0 # ans' index + maxNum = max(count, key=count.get) + + def fillAns(num: int) -> None: + nonlocal i + while count[num]: + ans[i] = num + i = i + 2 if i + 2 < len(barcodes) else 1 + count[num] -= 1 + + fillAns(maxNum) + for num in count.keys(): + fillAns(num) + + return ans diff --git a/solutions/1055. Shortest Way to Form String/1055-2.cpp b/solutions/1055. Shortest Way to Form String/1055-2.cpp new file mode 100644 index 00000000000..1fe8fb345e7 --- /dev/null +++ b/solutions/1055. Shortest Way to Form String/1055-2.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int shortestWay(string source, string target) { + const int m = source.length(); + const int n = target.length(); + // dp[i][c] := the earliest index >= i s.t. source[index] = c + // dp[i][c] := -1 if c isn't in the source + vector> dp(m, vector(26, -1)); + + dp[m - 1][source[m - 1] - 'a'] = m - 1; + for (int i = m - 2; i >= 0; --i) { + dp[i] = dp[i + 1]; + dp[i][source[i] - 'a'] = i; + } + + int ans = 0; + int i = 0; // source's index + + for (const char c : target) { + if (dp[0][c - 'a'] == -1) + return -1; + // If there are no c's left in source that occur more than i times but + // there are c's from earlier in the subsequence, add 1 to subsequence + // count and reset source's index to 0. + if (dp[i][c - 'a'] == -1) { + ++ans; + i = 0; + } + // Continue taking letters from the subsequence. + i = dp[i][c - 'a'] + 1; + if (i == m) { + ++ans; + i = 0; + } + } + + return ans + (i == 0 ? 0 : 1); + } +}; diff --git a/solutions/1055. Shortest Way to Form String/1055-2.java b/solutions/1055. Shortest Way to Form String/1055-2.java new file mode 100644 index 00000000000..583ae9c8e33 --- /dev/null +++ b/solutions/1055. Shortest Way to Form String/1055-2.java @@ -0,0 +1,40 @@ +class Solution { + public int shortestWay(String source, String target) { + final int m = source.length(); + final int n = target.length(); + // dp[i][c] := the earliest index >= i s.t. source[index] = c + // dp[i][c] := -1 if c isn't in the source + int[][] dp = new int[m][26]; + + Arrays.stream(dp).forEach(A -> Arrays.fill(A, -1)); + + dp[m - 1][source.charAt(m - 1) - 'a'] = m - 1; + for (int i = m - 2; i >= 0; --i) { + dp[i] = dp[i + 1].clone(); + dp[i][source.charAt(i) - 'a'] = i; + } + + int ans = 0; + int i = 0; // source's index + + for (final char c : target.toCharArray()) { + if (dp[0][c - 'a'] == -1) + return -1; + // If there are no c's left in source that occur more than i times but + // there are c's from earlier in the subsequence, add 1 to subsequence + // count and reset source's index to 0. + if (dp[i][c - 'a'] == -1) { + ++ans; + i = 0; + } + // Continue taking letters from the subsequence. + i = dp[i][c - 'a'] + 1; + if (i == m) { + ++ans; + i = 0; + } + } + + return ans + (i == 0 ? 0 : 1); + } +} diff --git a/solutions/1055. Shortest Way to Form String/1055.cpp b/solutions/1055. Shortest Way to Form String/1055.cpp new file mode 100644 index 00000000000..1ece99ef1f9 --- /dev/null +++ b/solutions/1055. Shortest Way to Form String/1055.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int shortestWay(string source, string target) { + int ans = 0; + + for (int i = 0; i < target.length();) { + const int prevIndex = i; + for (int j = 0; j < source.length(); ++j) + if (i < target.length() && source[j] == target[i]) + ++i; + // All chars in source didn't match target[i] + if (i == prevIndex) + return -1; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1055. Shortest Way to Form String/1055.java b/solutions/1055. Shortest Way to Form String/1055.java new file mode 100644 index 00000000000..5be57d567c0 --- /dev/null +++ b/solutions/1055. Shortest Way to Form String/1055.java @@ -0,0 +1,18 @@ +class Solution { + public int shortestWay(String source, String target) { + int ans = 0; + + for (int i = 0; i < target.length();) { + final int prevIndex = i; + for (int j = 0; j < source.length(); ++j) + if (i < target.length() && source.charAt(j) == target.charAt(i)) + ++i; + // All chars in source didn't match target[i] + if (i == prevIndex) + return -1; + ++ans; + } + + return ans; + } +} diff --git a/solutions/1056. Confusing Number/1056.cpp b/solutions/1056. Confusing Number/1056.cpp new file mode 100644 index 00000000000..0e73e483a39 --- /dev/null +++ b/solutions/1056. Confusing Number/1056.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool confusingNumber(int n) { + const string s = to_string(n); + const vector rotated{'0', '1', 'x', 'x', 'x', + 'x', '9', 'x', '8', '6'}; + string rotatedNum; + + for (int i = s.length() - 1; i >= 0; --i) { + if (rotated[s[i] - '0'] == 'x') + return false; + rotatedNum += rotated[s[i] - '0']; + } + + return rotatedNum != s; + } +}; diff --git a/solutions/1056. Confusing Number/1056.java b/solutions/1056. Confusing Number/1056.java new file mode 100644 index 00000000000..28a2c0c6d88 --- /dev/null +++ b/solutions/1056. Confusing Number/1056.java @@ -0,0 +1,15 @@ +class Solution { + public boolean confusingNumber(int n) { + final String s = String.valueOf(n); + final char[] rotated = {'0', '1', 'x', 'x', 'x', 'x', '9', 'x', '8', '6'}; + StringBuilder sb = new StringBuilder(); + + for (int i = s.length() - 1; i >= 0; --i) { + if (rotated[s.charAt(i) - '0'] == 'x') + return false; + sb.append(rotated[s.charAt(i) - '0']); + } + + return !sb.toString().equals(s); + } +} diff --git a/solutions/1056. Confusing Number/1056.py b/solutions/1056. Confusing Number/1056.py new file mode 100644 index 00000000000..841f42a8650 --- /dev/null +++ b/solutions/1056. Confusing Number/1056.py @@ -0,0 +1,12 @@ +class Solution: + def confusingNumber(self, n: int) -> bool: + s = str(n) + rotated = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'} + rotatedNum = [] + + for c in s[::-1]: + if c not in rotated: + return False + rotatedNum.append(rotated[c]) + + return ''.join(rotatedNum) != s diff --git a/solutions/1057. Campus Bikes/1057.cpp b/solutions/1057. Campus Bikes/1057.cpp new file mode 100644 index 00000000000..7a2530fcabc --- /dev/null +++ b/solutions/1057. Campus Bikes/1057.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector assignBikes(vector>& workers, + vector>& bikes) { + const int n = workers.size(); + const int m = bikes.size(); + vector ans(n, -1); + vector usedBikes(m); + // buckets[k] := (i, j), where k = dist(workers[i], bikes[j]) + vector>> buckets(2001); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < m; ++j) + buckets[dist(workers[i], bikes[j])].emplace_back(i, j); + + for (int k = 0; k < 2001; ++k) + for (const auto& [i, j] : buckets[k]) + if (ans[i] == -1 && !usedBikes[j]) { + ans[i] = j; + usedBikes[j] = true; + } + + return ans; + } + + private: + int dist(const vector& p1, const vector& p2) { + return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]); + } +}; diff --git a/solutions/1057. Campus Bikes/1057.java b/solutions/1057. Campus Bikes/1057.java new file mode 100644 index 00000000000..1809ef9edf7 --- /dev/null +++ b/solutions/1057. Campus Bikes/1057.java @@ -0,0 +1,35 @@ +class Solution { + public int[] assignBikes(int[][] workers, int[][] bikes) { + final int n = workers.length; + final int m = bikes.length; + int[] ans = new int[n]; + boolean[] usedBikes = new boolean[m]; + // buckets[k] := (i, j), where k = dist(workers[i], bikes[j]) + List>[] buckets = new List[2001]; + + for (int i = 0; i < 2001; ++i) + buckets[i] = new ArrayList<>(); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < m; ++j) + buckets[dist(workers[i], bikes[j])].add(new Pair<>(i, j)); + + Arrays.fill(ans, -1); + + for (int k = 0; k < 2001; ++k) + for (Pair pair : buckets[k]) { + final int i = pair.getKey(); + final int j = pair.getValue(); + if (ans[i] == -1 && !usedBikes[j]) { + ans[i] = j; + usedBikes[j] = true; + } + } + + return ans; + } + + private int dist(int[] p1, int[] p2) { + return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]); + } +} diff --git a/solutions/1057. Campus Bikes/1057.py b/solutions/1057. Campus Bikes/1057.py new file mode 100644 index 00000000000..4a07222a3e2 --- /dev/null +++ b/solutions/1057. Campus Bikes/1057.py @@ -0,0 +1,21 @@ +class Solution: + def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]: + ans = [-1] * len(workers) + usedBikes = [False] * len(bikes) + # buckets[k] := (i, j), where k = dist(workers[i], bikes[j]) + buckets = [[] for _ in range(2001)] + + def dist(p1: List[int], p2: List[int]) -> int: + return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) + + for i, worker in enumerate(workers): + for j, bike in enumerate(bikes): + buckets[dist(worker, bike)].append((i, j)) + + for k in range(2001): + for i, j in buckets[k]: + if ans[i] == -1 and not usedBikes[j]: + ans[i] = j + usedBikes[j] = True + + return ans diff --git a/solutions/1058. Minimize Rounding Error to Meet Target/1058.cpp b/solutions/1058. Minimize Rounding Error to Meet Target/1058.cpp new file mode 100644 index 00000000000..b07c782b78c --- /dev/null +++ b/solutions/1058. Minimize Rounding Error to Meet Target/1058.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + string minimizeError(vector& prices, int target) { + // A[i] := (costCeil - costFloor, costCeil, costFloor) + // The lower the costCeil - costFloor is, the cheaper to ceil it. + vector> A; + int sumFloored = 0; + int sumCeiled = 0; + + for (const string& p : prices) { + const double price = stod(p); + const int floored = floor(price); + const int ceiled = ceil(price); + sumFloored += floored; + sumCeiled += ceiled; + const double costFloor = price - static_cast(floored); + const double costCeil = static_cast(ceiled) - price; + A.emplace_back(costCeil - costFloor, costCeil, costFloor); + } + + if (sumFloored > target || sumCeiled < target) + return "-1"; + + ranges::sort(A); + + double sumError = 0.0; + const int nCeiled = target - sumFloored; + for (int i = 0; i < nCeiled; ++i) + sumError += get<1>(A[i]); + for (int i = nCeiled; i < A.size(); ++i) + sumError += get<2>(A[i]); + + stringstream ss; + ss << std::fixed << std::setprecision(3) << sumError; + return ss.str(); + } +}; diff --git a/solutions/1058. Minimize Rounding Error to Meet Target/1058.java b/solutions/1058. Minimize Rounding Error to Meet Target/1058.java new file mode 100644 index 00000000000..d9bdb4a0615 --- /dev/null +++ b/solutions/1058. Minimize Rounding Error to Meet Target/1058.java @@ -0,0 +1,39 @@ +class Solution { + public String minimizeError(String[] prices, int target) { + // A[i] := (costCeil - costFloor, costCeil, costFloor) + // The lower the costCeil - costFloor is, the cheaper to ceil it. + List A = new ArrayList<>(); + int sumFloored = 0; + int sumCeiled = 0; + + for (final String p : prices) { + final double price = Double.parseDouble(p); + final int floored = (int) Math.floor(price); + final int ceiled = (int) Math.ceil(price); + sumFloored += floored; + sumCeiled += ceiled; + final double costFloor = price - (double) floored; + final double costCeil = (double) ceiled - price; + A.add(new double[] {costCeil - costFloor, costCeil, costFloor}); + } + + if (sumFloored > target || sumCeiled < target) + return "-1"; + + Collections.sort(A, new Comparator() { + @Override + public int compare(double[] a, double[] b) { + return Double.compare(a[0], b[0]); + } + }); + + double sumError = 0.0; + final int nCeiled = target - sumFloored; + for (int i = 0; i < nCeiled; ++i) + sumError += A.get(i)[1]; + for (int i = nCeiled; i < A.size(); ++i) + sumError += A.get(i)[2]; + + return String.format("%.3f", sumError); + } +} diff --git a/solutions/1058. Minimize Rounding Error to Meet Target/1058.py b/solutions/1058. Minimize Rounding Error to Meet Target/1058.py new file mode 100644 index 00000000000..00725e8aeb3 --- /dev/null +++ b/solutions/1058. Minimize Rounding Error to Meet Target/1058.py @@ -0,0 +1,24 @@ +class Solution: + def minimizeError(self, prices: List[str], target: int) -> str: + # A[i] := (costCeil - costFloor, costCeil, costFloor) + # The lower the costCeil - costFloor is, the cheaper to ceil it. + A = [] + sumFloored = 0 + sumCeiled = 0 + + for price in map(float, prices): + floored = math.floor(price) + ceiled = math.ceil(price) + sumFloored += floored + sumCeiled += ceiled + costFloor = price - floored + costCeil = ceiled - price + A.append((costCeil - costFloor, costCeil, costFloor)) + + if not sumFloored <= target <= sumCeiled: + return '-1' + + A.sort() + nCeiled = target - sumFloored + return '{:.3f}'.format(sum(a[1] for a in A[:nCeiled]) + + sum(a[2] for a in A[nCeiled:])) diff --git a/solutions/1059. All Paths from Source Lead to Destination/1059.cpp b/solutions/1059. All Paths from Source Lead to Destination/1059.cpp new file mode 100644 index 00000000000..0c2bb4f5c1f --- /dev/null +++ b/solutions/1059. All Paths from Source Lead to Destination/1059.cpp @@ -0,0 +1,34 @@ +enum class State { kInit, kVisiting, kVisited }; + +class Solution { + public: + bool leadsToDestination(int n, vector>& edges, int source, + int destination) { + vector> graph(n); + vector states(n); + + for (const vector& edge : edges) + graph[e[0]].push_back(e[1]); + + return acyclic(graph, source, destination, states); + } + + private: + bool acyclic(const vector>& graph, int u, int dest, + vector& states) { + if (graph[u].empty()) + return u == dest; + if (states[u] == State::kVisiting) + return false; + if (states[u] == State::kVisited) + return true; + + states[u] = State::kVisiting; + for (const int v : graph[u]) + if (!acyclic(graph, v, dest, states)) + return false; + states[u] = State::kVisited; + + return true; + } +}; diff --git a/solutions/1059. All Paths from Source Lead to Destination/1059.java b/solutions/1059. All Paths from Source Lead to Destination/1059.java new file mode 100644 index 00000000000..2a94aa5130c --- /dev/null +++ b/solutions/1059. All Paths from Source Lead to Destination/1059.java @@ -0,0 +1,33 @@ +enum State { kInit, kVisiting, kVisited } + +class Solution { + public boolean leadsToDestination(int n, int[][] edges, int source, int destination) { + List[] graph = new List[n]; + State[] states = new State[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) + graph[e[0]].add(e[1]); + + return acyclic(graph, source, destination, states); + } + + private boolean acyclic(List[] graph, int u, int dest, State[] states) { + if (graph[u].isEmpty()) + return u == dest; + if (states[u] == State.kVisiting) + return false; + if (states[u] == State.kVisited) + return true; + + states[u] = State.kVisiting; + for (final int v : graph[u]) + if (!acyclic(graph, v, dest, states)) + return false; + states[u] = State.kVisited; + + return true; + } +} diff --git a/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.cpp b/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.cpp new file mode 100644 index 00000000000..44af5c9d971 --- /dev/null +++ b/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + TreeNode* buildTree(vector& inorder, vector& postorder) { + unordered_map inToIndex; + + for (int i = 0; i < inorder.size(); ++i) + inToIndex[inorder[i]] = i; + + return build(inorder, 0, inorder.size() - 1, postorder, 0, + postorder.size() - 1, inToIndex); + } + + private: + TreeNode* build(const vector& inorder, int inStart, int inEnd, + const vector& postorder, int postStart, int postEnd, + const unordered_map& inToIndex) { + if (inStart > inEnd) + return nullptr; + + const int rootVal = postorder[postEnd]; + const int rootInIndex = inToIndex.at(rootVal); + const int leftSize = rootInIndex - inStart; + + TreeNode* root = new TreeNode(rootVal); + root->left = build(inorder, inStart, rootInIndex - 1, postorder, postStart, + postStart + leftSize - 1, inToIndex); + root->right = build(inorder, rootInIndex + 1, inEnd, postorder, + postStart + leftSize, postEnd - 1, inToIndex); + return root; + } +}; diff --git a/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.java b/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.java new file mode 100644 index 00000000000..aa98d07ff87 --- /dev/null +++ b/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.java @@ -0,0 +1,27 @@ +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + Map inToIndex = new HashMap<>(); + + for (int i = 0; i < inorder.length; ++i) + inToIndex.put(inorder[i], i); + + return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, inToIndex); + } + + TreeNode build(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd, + Map inToIndex) { + if (inStart > inEnd) + return null; + + final int rootVal = postorder[postEnd]; + final int rootInIndex = inToIndex.get(rootVal); + final int leftSize = rootInIndex - inStart; + + TreeNode root = new TreeNode(rootVal); + root.left = build(inorder, inStart, rootInIndex - 1, postorder, postStart, + postStart + leftSize - 1, inToIndex); + root.right = build(inorder, rootInIndex + 1, inEnd, postorder, postStart + leftSize, + postEnd - 1, inToIndex); + return root; + } +} diff --git a/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.py b/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.py new file mode 100644 index 00000000000..fe647cbc246 --- /dev/null +++ b/solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.py @@ -0,0 +1,20 @@ +class Solution: + def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: + inToIndex = {num: i for i, num in enumerate(inorder)} + + def build(inStart: int, inEnd: int, postStart: int, postEnd: int) -> Optional[TreeNode]: + if inStart > inEnd: + return None + + rootVal = postorder[postEnd] + rootInIndex = inToIndex[rootVal] + leftSize = rootInIndex - inStart + + root = TreeNode(rootVal) + root.left = build(inStart, rootInIndex - 1, postStart, + postStart + leftSize - 1) + root.right = build(rootInIndex + 1, inEnd, postStart + leftSize, + postEnd - 1) + return root + + return build(0, len(inorder) - 1, 0, len(postorder) - 1) diff --git a/solutions/1060. Missing Element in Sorted Array/1060.cpp b/solutions/1060. Missing Element in Sorted Array/1060.cpp new file mode 100644 index 00000000000..c14910da45e --- /dev/null +++ b/solutions/1060. Missing Element in Sorted Array/1060.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int missingElement(vector& nums, int k) { + int l = 0; + int r = nums.size(); + + // the number of missing numbers in [nums[0], nums[i]] + auto nMissing = [&](int i) { return nums[i] - nums[0] - i; }; + + // Find the first index l s.t. nMissing(l) >= k + while (l < r) { + const int m = (l + r) / 2; + if (nMissing(m) >= k) + r = m; + else + l = m + 1; + } + + return nums[l - 1] + (k - nMissing(l - 1)); + } +}; diff --git a/solutions/1060. Missing Element in Sorted Array/1060.java b/solutions/1060. Missing Element in Sorted Array/1060.java new file mode 100644 index 00000000000..547afff146f --- /dev/null +++ b/solutions/1060. Missing Element in Sorted Array/1060.java @@ -0,0 +1,22 @@ +class Solution { + public int missingElement(int[] nums, int k) { + int l = 0; + int r = nums.length; + + // Find the first index l s.t. nMissing(l) >= k + while (l < r) { + final int m = (l + r) / 2; + if (nMissing(nums, m) >= k) + r = m; + else + l = m + 1; + } + + return nums[l - 1] + (k - nMissing(nums, l - 1)); + } + + // the number of missing numbers in [nums[0], nums[i]] + private int nMissing(int[] nums, int i) { + return nums[i] - nums[0] - i; + } +} diff --git a/solutions/1061. Lexicographically Smallest Equivalent String/1061.cpp b/solutions/1061. Lexicographically Smallest Equivalent String/1061.cpp new file mode 100644 index 00000000000..7742823c514 --- /dev/null +++ b/solutions/1061. Lexicographically Smallest Equivalent String/1061.cpp @@ -0,0 +1,38 @@ +class UnionFind { + public: + UnionFind(int n) : id(n) { + iota(id.begin(), id.end(), 0); + } + + void union_(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i > j) + id[i] = j; + else + id[j] = i; + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; +}; + +class Solution { + public: + string smallestEquivalentString(string s1, string s2, string baseStr) { + string ans; + UnionFind uf(26); + + for (int i = 0; i < s1.length(); ++i) + uf.union_(s1[i] - 'a', s2[i] - 'a'); + + for (const char c : baseStr) + ans += 'a' + uf.find(c - 'a'); + + return ans; + } +}; diff --git a/solutions/1061. Lexicographically Smallest Equivalent String/1061.java b/solutions/1061. Lexicographically Smallest Equivalent String/1061.java new file mode 100644 index 00000000000..764f86c0389 --- /dev/null +++ b/solutions/1061. Lexicographically Smallest Equivalent String/1061.java @@ -0,0 +1,37 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void union(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i > j) + id[i] = j; + else + id[j] = i; + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; +} + +class Solution { + public String smallestEquivalentString(String s1, String s2, String baseStr) { + StringBuilder sb = new StringBuilder(); + UnionFind uf = new UnionFind(26); + + for (int i = 0; i < s1.length(); ++i) + uf.union(s1.charAt(i) - 'a', s2.charAt(i) - 'a'); + + for (final char c : baseStr.toCharArray()) + sb.append((char) ('a' + uf.find(c - 'a'))); + + return sb.toString(); + } +} diff --git a/solutions/1062. Longest Repeating Substring/1062.cpp b/solutions/1062. Longest Repeating Substring/1062.cpp new file mode 100644 index 00000000000..7a1ea630732 --- /dev/null +++ b/solutions/1062. Longest Repeating Substring/1062.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int longestRepeatingSubstring(string s) { + const int n = s.length(); + int ans = 0; + // dp[i][j] := the number of repeating characters of s[0..i) and s[0..j) + vector> dp(n + 1, vector(n + 1)); + + for (int i = 1; i <= n; ++i) + for (int j = i + 1; j <= n; ++j) + if (s[i - 1] == s[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + ans = max(ans, dp[i][j]); + } + + return ans; + } +}; diff --git a/solutions/1062. Longest Repeating Substring/1062.java b/solutions/1062. Longest Repeating Substring/1062.java new file mode 100644 index 00000000000..094fcc25283 --- /dev/null +++ b/solutions/1062. Longest Repeating Substring/1062.java @@ -0,0 +1,17 @@ +class Solution { + public int longestRepeatingSubstring(String s) { + final int n = s.length(); + int ans = 0; + // dp[i][j] := the number of repeating characters of s[0..i) and s[0..j) + int[][] dp = new int[n + 1][n + 1]; + + for (int i = 1; i <= n; ++i) + for (int j = i + 1; j <= n; ++j) + if (S.charAt(i - 1) == s.charAt(j - 1)) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + ans = Math.max(ans, dp[i][j]); + } + + return ans; + } +} diff --git a/solutions/1062. Longest Repeating Substring/1062.py b/solutions/1062. Longest Repeating Substring/1062.py new file mode 100644 index 00000000000..3aaa8e6d2d2 --- /dev/null +++ b/solutions/1062. Longest Repeating Substring/1062.py @@ -0,0 +1,14 @@ +class Solution: + def longestRepeatingSubstring(self, s: str) -> int: + n = len(s) + ans = 0 + # dp[i][j] := the number of repeating characters of s[0..i) and s[0..j) + dp = [[0] * (n + 1) for _ in range(n + 1)] + + for i in range(1, n + 1): + for j in range(i + 1, n + 1): + if s[i - 1] == s[j - 1]: + dp[i][j] = 1 + dp[i - 1][j - 1] + ans = max(ans, dp[i][j]) + + return ans diff --git a/solutions/1063. Number of Valid Subarrays/1063.cpp b/solutions/1063. Number of Valid Subarrays/1063.cpp new file mode 100644 index 00000000000..89e16273deb --- /dev/null +++ b/solutions/1063. Number of Valid Subarrays/1063.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int validSubarrays(vector& nums) { + // For each `num` in `nums`, each element x in the stack can be the leftmost + // element s.t. [x, num] forms a valid subarray, so the size of the stack is + // the number of valid subarrays ending in the current number. + // + // e.g. nums = [1, 3, 2] + // num = 1, stack = [1] -> valid subarray is [1] + // num = 3, stack = [1, 3] -> valid subarrays are [1, 3], [3] + // num = 2, stack = [1, 2] -> valid subarrays are [1, 3, 2], [2] + int ans = 0; + stack stack; + + for (const int num : nums) { + while (!stack.empty() && stack.top() > num) + stack.pop(); + stack.push(num); + ans += stack.size(); + } + + return ans; + } +}; diff --git a/solutions/1063. Number of Valid Subarrays/1063.java b/solutions/1063. Number of Valid Subarrays/1063.java new file mode 100644 index 00000000000..24719568638 --- /dev/null +++ b/solutions/1063. Number of Valid Subarrays/1063.java @@ -0,0 +1,23 @@ +class Solution { + public int validSubarrays(int[] nums) { + // For each `num` in `nums`, each element x in the stack can be the leftmost + // element s.t. [x, num] forms a valid subarray, so the size of the stack is + // the number of valid subarrays ending in the current number. + // + // e.g. nums = [1, 3, 2] + // num = 1, stack = [1] -> valid subarray is [1] + // num = 3, stack = [1, 3] -> valid subarrays are [1, 3], [3] + // num = 2, stack = [1, 2] -> valid subarrays are [1, 3, 2], [2] + int ans = 0; + Deque stack = new ArrayDeque<>(); + + for (final int num : nums) { + while (!stack.isEmpty() && stack.peek() > num) + stack.pop(); + stack.push(num); + ans += stack.size(); + } + + return ans; + } +} diff --git a/solutions/1063. Number of Valid Subarrays/1063.py b/solutions/1063. Number of Valid Subarrays/1063.py new file mode 100644 index 00000000000..ce7222d6f36 --- /dev/null +++ b/solutions/1063. Number of Valid Subarrays/1063.py @@ -0,0 +1,20 @@ +class Solution: + def validSubarrays(self, nums: List[int]) -> int: + # For each `num` in `nums`, each element x in the stack can be the leftmost + # element s.t. [x, num] forms a valid subarray, so the size of the stack is + # the number of valid subarrays ending in the current number. + # + # e.g. nums = [1, 3, 2] + # num = 1, stack = [1] -> valid subarray is [1] + # num = 3, stack = [1, 3] -> valid subarrays are [1, 3], [3] + # num = 2, stack = [1, 2] -> valid subarrays are [1, 3, 2], [2] + ans = 0 + stack = [] + + for num in nums: + while stack and stack[-1] > num: + stack.pop() + stack.append(num) + ans += len(stack) + + return ans diff --git a/solutions/1064. Fixed Point/1064.cpp b/solutions/1064. Fixed Point/1064.cpp new file mode 100644 index 00000000000..c2ebe40aba5 --- /dev/null +++ b/solutions/1064. Fixed Point/1064.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int fixedPoint(vector& arr) { + int l = 0; + int r = arr.size() - 1; + + // Since arr[i] is strictly increasing, arr[i] - i will also be increasing. + // Therefore, binary search `arr` for the first arr[i] - i = 0. + while (l < r) { + const int m = (l + r) / 2; + if (arr[m] - m >= 0) + r = m; + else + l = m + 1; + } + + return arr[l] == l ? l : -1; + } +}; diff --git a/solutions/1064. Fixed Point/1064.java b/solutions/1064. Fixed Point/1064.java new file mode 100644 index 00000000000..c0bba9eaeeb --- /dev/null +++ b/solutions/1064. Fixed Point/1064.java @@ -0,0 +1,18 @@ +class Solution { + public int fixedPoint(int[] arr) { + int l = 0; + int r = arr.length - 1; + + // Since arr[i] is strictly increasing, arr[i] - i will also be increasing. + // Therefore, binary search `arr` for the first arr[i] - i = 0. + while (l < r) { + final int m = (l + r) / 2; + if (arr[m] - m >= 0) + r = m; + else + l = m + 1; + } + + return arr[l] == l ? l : -1; + } +} diff --git a/solutions/1064. Fixed Point/1064.py b/solutions/1064. Fixed Point/1064.py new file mode 100644 index 00000000000..4b48613e5f6 --- /dev/null +++ b/solutions/1064. Fixed Point/1064.py @@ -0,0 +1,15 @@ +class Solution: + def fixedPoint(self, arr: List[int]) -> int: + l = 0 + r = len(arr) - 1 + + # Since arr[i] is strictly increasing, arr[i] - i will also be increasing. + # Therefore, binary search `arr` for the first arr[i] - i = 0. + while l < r: + m = (l + r) // 2 + if arr[m] - m >= 0: + r = m + else: + l = m + 1 + + return l if arr[l] == l else -1 diff --git a/solutions/1065. Index Pairs of a String/1065.cpp b/solutions/1065. Index Pairs of a String/1065.cpp new file mode 100644 index 00000000000..82348403149 --- /dev/null +++ b/solutions/1065. Index Pairs of a String/1065.cpp @@ -0,0 +1,38 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class Solution { + public: + vector> indexPairs(string text, vector& words) { + vector> ans; + shared_ptr root = make_shared(); + + for (const string& word : words) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->isWord = true; + } + + for (int i = 0; i < text.length(); ++i) { + shared_ptr node = root; + for (int j = i; j < text.length(); j++) { + const int index = text[j] - 'a'; + if (node->children[index] == nullptr) + break; + node = node->children[index]; + if (node->isWord) + ans.push_back({i, j}); + } + } + + return ans; + } +}; diff --git a/solutions/1065. Index Pairs of a String/1065.java b/solutions/1065. Index Pairs of a String/1065.java new file mode 100644 index 00000000000..083721e724a --- /dev/null +++ b/solutions/1065. Index Pairs of a String/1065.java @@ -0,0 +1,36 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class Solution { + public int[][] indexPairs(String text, String[] words) { + List ans = new ArrayList<>(); + TrieNode root = new TrieNode(); + + for (final String word : words) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + for (int i = 0; i < text.length(); ++i) { + TrieNode node = root; + for (int j = i; j < text.length(); ++j) { + final int index = text.charAt(j) - 'a'; + if (node.children[index] == null) + break; + node = node.children[index]; + if (node.isWord) + ans.add(new int[] {i, j}); + } + } + + return ans.toArray(int[][] ::new); + } +} diff --git a/solutions/1065. Index Pairs of a String/1065.py b/solutions/1065. Index Pairs of a String/1065.py new file mode 100644 index 00000000000..6aa141ce954 --- /dev/null +++ b/solutions/1065. Index Pairs of a String/1065.py @@ -0,0 +1,29 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode) + self.isWord = False + + +class Solution: + def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: + ans = [] + root = TrieNode() + + for word in words: + node: TrieNode = root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + # Scan each text[i..j]. + for i in range(len(text)): + node: TrieNode = root + for j in range(i, len(text)): + c = text[j] + if c not in node.children: + break + node = node.children[c] + if node.isWord: + ans.append([i, j]) + + return ans diff --git a/solutions/1066. Campus Bikes II/1066.cpp b/solutions/1066. Campus Bikes II/1066.cpp new file mode 100644 index 00000000000..7ea10b2c4aa --- /dev/null +++ b/solutions/1066. Campus Bikes II/1066.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int assignBikes(vector>& workers, vector>& bikes) { + vector mem(1 << bikes.size(), INT_MAX); + return assignBikes(workers, bikes, 0, 0, mem); + } + + private: + // Returns the minimum Manhattan distances to assign bikes to + // workers[workerIndex..n), where `used` is the bitmask of the used bikes. + int assignBikes(const vector>& workers, + const vector>& bikes, int workerIndex, int used, + vector& mem) { + if (workerIndex == workers.size()) + return 0; + if (mem[used] != INT_MAX) + return mem[used]; + + for (int bikeIndex = 0; bikeIndex < bikes.size(); ++bikeIndex) + if ((used >> bikeIndex & 1) == 0) + mem[used] = + min(mem[used], dist(workers[workerIndex], bikes[bikeIndex]) + + assignBikes(workers, bikes, workerIndex + 1, + used | 1 << bikeIndex, mem)); + + return mem[used]; + } + + int dist(const vector& p1, const vector& p2) { + return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]); + } +}; diff --git a/solutions/1066. Campus Bikes II/1066.java b/solutions/1066. Campus Bikes II/1066.java new file mode 100644 index 00000000000..c222de3cf11 --- /dev/null +++ b/solutions/1066. Campus Bikes II/1066.java @@ -0,0 +1,28 @@ +class Solution { + public int assignBikes(int[][] workers, int[][] bikes) { + int[] mem = new int[1 << bikes.length]; + Arrays.fill(mem, Integer.MAX_VALUE); + return assignBikes(workers, bikes, 0, 0, mem); + } + + // Returns the minimum Manhattan distances to assign bikes to + // workers[workerIndex..n), where `used` is the bitmask of the used bikes. + private int assignBikes(int[][] workers, int[][] bikes, int workerIndex, int used, int[] mem) { + if (workerIndex == workers.length) + return 0; + if (mem[used] != Integer.MAX_VALUE) + return mem[used]; + + for (int bikeIndex = 0; bikeIndex < bikes.length; bikeIndex++) + if ((used >> bikeIndex & 1) == 0) + mem[used] = Math.min(mem[used], dist(workers[workerIndex], bikes[bikeIndex]) + + assignBikes(workers, bikes, workerIndex + 1, + used | (1 << bikeIndex), mem)); + + return mem[used]; + } + + private int dist(int[] p1, int[] p2) { + return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]); + } +} diff --git a/solutions/1066. Campus Bikes II/1066.py b/solutions/1066. Campus Bikes II/1066.py new file mode 100644 index 00000000000..9a17633029e --- /dev/null +++ b/solutions/1066. Campus Bikes II/1066.py @@ -0,0 +1,18 @@ +class Solution: + def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int: + def dist(p1: List[int], p2: List[int]) -> int: + return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) + + @functools.lru_cache(None) + def dp(workerIndex: int, used: int) -> int: + """ + Returns the minimum Manhattan distances to assign bikes to + workers[workerIndex..n), where `used` is the bitmask of the used bikes. + """ + if workerIndex == len(workers): + return 0 + return min((dist(workers[workerIndex], bike) + dp(workerIndex + 1, used | 1 << i) + for i, bike in enumerate(bikes) + if not used >> i & 1), default=math.inf) + + return dp(0, 0) diff --git a/solutions/1067. Digit Count in Range/1067.cpp b/solutions/1067. Digit Count in Range/1067.cpp new file mode 100644 index 00000000000..593125ab965 --- /dev/null +++ b/solutions/1067. Digit Count in Range/1067.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int digitsCount(int d, int low, int high) { + return countDigit(high, d) - countDigit(low - 1, d); + } + + private: + int countDigit(int n, int d) { + int count = 0; + + for (int pow10 = 1; pow10 <= n; pow10 *= 10) { + const int divisor = pow10 * 10; + const int quotient = n / divisor; + const int remainder = n % divisor; + if (quotient > 0) + count += quotient * pow10; + if (d == 0) + count -= pow10; + if (remainder >= d * pow10) + count += min(remainder - d * pow10 + 1, pow10); + } + + return count; + } +}; diff --git a/solutions/1067. Digit Count in Range/1067.java b/solutions/1067. Digit Count in Range/1067.java new file mode 100644 index 00000000000..e13c51e4c35 --- /dev/null +++ b/solutions/1067. Digit Count in Range/1067.java @@ -0,0 +1,23 @@ +class Solution { + public int digitsCount(int d, int low, int high) { + return countDigit(high, d) - countDigit(low - 1, d); + } + + private int countDigit(int n, int d) { + int count = 0; + + for (int pow10 = 1; pow10 <= n; pow10 *= 10) { + final int divisor = pow10 * 10; + final int quotient = n / divisor; + final int remainder = n % divisor; + if (quotient > 0) + count += quotient * pow10; + if (d == 0) + count -= pow10; + if (remainder >= d * pow10) + count += Math.min(remainder - d * pow10 + 1, pow10); + } + + return count; + } +} diff --git a/solutions/1068. Product Sales Analysis I/1068.sql b/solutions/1068. Product Sales Analysis I/1068.sql new file mode 100644 index 00000000000..a7cf55a3ae1 --- /dev/null +++ b/solutions/1068. Product Sales Analysis I/1068.sql @@ -0,0 +1,7 @@ +SELECT + Product.product_name, + Sales.year, + Sales.price +FROM Sales +INNER JOIN Product + USING (product_id); diff --git a/solutions/1069. Product Sales Analysis II/1069.sql b/solutions/1069. Product Sales Analysis II/1069.sql new file mode 100644 index 00000000000..686ee0ce7ca --- /dev/null +++ b/solutions/1069. Product Sales Analysis II/1069.sql @@ -0,0 +1,3 @@ +SELECT product_id, SUM(quantity) AS total_quantity +FROM Sales +GROUP BY 1; diff --git a/solutions/107. Binary Tree Level Order Traversal II/107.cpp b/solutions/107. Binary Tree Level Order Traversal II/107.cpp new file mode 100644 index 00000000000..344ad4fad16 --- /dev/null +++ b/solutions/107. Binary Tree Level Order Traversal II/107.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector> levelOrderBottom(TreeNode* root) { + if (root == nullptr) + return {}; + + vector> ans; + queue q{{root}}; + + while (!q.empty()) { + vector currLevel; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + currLevel.push_back(node->val); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + ans.push_back(currLevel); + } + + reverse(ans.begin(), ans.end()); + return ans; + } +}; diff --git a/solutions/107. Binary Tree Level Order Traversal II/107.java b/solutions/107. Binary Tree Level Order Traversal II/107.java new file mode 100644 index 00000000000..1c3f3ebe1a7 --- /dev/null +++ b/solutions/107. Binary Tree Level Order Traversal II/107.java @@ -0,0 +1,25 @@ +class Solution { + public List> levelOrderBottom(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + List currLevel = new ArrayList<>(); + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + currLevel.add(node.val); + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + ans.add(currLevel); + } + + Collections.reverse(ans); + return ans; + } +} diff --git a/solutions/107. Binary Tree Level Order Traversal II/107.py b/solutions/107. Binary Tree Level Order Traversal II/107.py new file mode 100644 index 00000000000..57842296a16 --- /dev/null +++ b/solutions/107. Binary Tree Level Order Traversal II/107.py @@ -0,0 +1,20 @@ +class Solution: + def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: + return [] + + ans = [] + q = collections.deque([root]) + + while q: + currLevel = [] + for _ in range(len(q)): + node = q.popleft() + currLevel.append(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + ans.append(currLevel) + + return ans[::-1] diff --git a/solutions/1070. Product Sales Analysis III/1070.sql b/solutions/1070. Product Sales Analysis III/1070.sql new file mode 100644 index 00000000000..9ffcc4af355 --- /dev/null +++ b/solutions/1070. Product Sales Analysis III/1070.sql @@ -0,0 +1,14 @@ +WITH + ProductToYear AS ( + SELECT product_id, MIN(year) AS year + FROM Sales + GROUP BY 1 + ) +SELECT + Sales.product_id, + ProductToYear.year AS first_year, + Sales.quantity, + Sales.price +FROM Sales +INNER JOIN ProductToYear + USING (product_id, year); diff --git a/solutions/1071. Greatest Common Divisor of Strings/1071.cpp b/solutions/1071. Greatest Common Divisor of Strings/1071.cpp new file mode 100644 index 00000000000..b3a9decd887 --- /dev/null +++ b/solutions/1071. Greatest Common Divisor of Strings/1071.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + string gcdOfStrings(string str1, string str2) { + if (str1.length() < str2.length()) + return gcdOfStrings(str2, str1); + if (str1.find(str2) == string::npos) + return ""; + if (str2.empty()) + return str1; + return gcdOfStrings(str2, mod(str1, str2)); + } + + private: + string mod(string& s1, const string& s2) { + while (s1.find(s2) == 0) + s1 = s1.substr(s2.length()); + return s1; + } +}; diff --git a/solutions/1071. Greatest Common Divisor of Strings/1071.java b/solutions/1071. Greatest Common Divisor of Strings/1071.java new file mode 100644 index 00000000000..1a1814638ae --- /dev/null +++ b/solutions/1071. Greatest Common Divisor of Strings/1071.java @@ -0,0 +1,17 @@ +class Solution { + public String gcdOfStrings(String str1, String str2) { + if (str1.length() < str2.length()) + return gcdOfStrings(str2, str1); + if (!str1.startsWith(str2)) + return ""; + if (str2.isEmpty()) + return str1; + return gcdOfStrings(str2, mod(str1, str2)); + } + + private String mod(String s1, final String s2) { + while (s1.startsWith(s2)) + s1 = s1.substring(s2.length()); + return s1; + } +} diff --git a/solutions/1071. Greatest Common Divisor of Strings/1071.py b/solutions/1071. Greatest Common Divisor of Strings/1071.py new file mode 100644 index 00000000000..9a3314f5ef4 --- /dev/null +++ b/solutions/1071. Greatest Common Divisor of Strings/1071.py @@ -0,0 +1,14 @@ +class Solution: + def gcdOfStrings(self, str1: str, str2: str) -> str: + def mod(s1: str, s2: str) -> str: + while s1.startswith(s2): + s1 = s1[len(s2):] + return s1 + + if len(str1) < len(str2): + return self.gcdOfStrings(str2, str1) + if not str1.startswith(str2): + return '' + if not str2: + return str1 + return self.gcdOfStrings(str2, mod(str1, str2)) diff --git a/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.cpp b/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.cpp new file mode 100644 index 00000000000..ca65bc7bf9a --- /dev/null +++ b/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maxEqualRowsAfterFlips(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + int ans = 0; + vector flip(n); + unordered_set seen; + + for (int i = 0; i < m; ++i) { + if (seen.contains(i)) + continue; + int count = 0; + for (int j = 0; j < n; ++j) + flip[j] = 1 ^ matrix[i][j]; + for (int k = 0; k < m; ++k) + if (matrix[k] == matrix[i] || matrix[k] == flip) { + seen.insert(k); + ++count; + } + ans = max(ans, count); + } + + return ans; + } +}; diff --git a/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.java b/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.java new file mode 100644 index 00000000000..97043ff7392 --- /dev/null +++ b/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.java @@ -0,0 +1,25 @@ +class Solution { + public int maxEqualRowsAfterFlips(int[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + int ans = 0; + int[] flip = new int[n]; + Set seen = new HashSet<>(); + + for (int i = 0; i < m; ++i) { + if (seen.contains(i)) + continue; + int count = 0; + for (int j = 0; j < n; ++j) + flip[j] = 1 ^ matrix[i][j]; + for (int k = 0; k < m; ++k) + if (Arrays.equals(matrix[k], matrix[i]) || Arrays.equals(matrix[k], flip)) { + seen.add(k); + ++count; + } + ans = Math.max(ans, count); + } + + return ans; + } +} diff --git a/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.py b/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.py new file mode 100644 index 00000000000..d43a58f61a4 --- /dev/null +++ b/solutions/1072. Flip Columns For Maximum Number of Equal Rows/1072.py @@ -0,0 +1,4 @@ +class Solution: + def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int: + patterns = [tuple(a ^ row[0] for a in row) for row in matrix] + return max(Counter(patterns).values()) diff --git a/solutions/1073. Adding Two Negabinary Numbers/1073.cpp b/solutions/1073. Adding Two Negabinary Numbers/1073.cpp new file mode 100644 index 00000000000..e8d8b6caaa1 --- /dev/null +++ b/solutions/1073. Adding Two Negabinary Numbers/1073.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector addNegabinary(vector& arr1, vector& arr2) { + deque ans; + int carry = 0; + int i = arr1.size() - 1; + int j = arr2.size() - 1; + + while (carry != 0 || i >= 0 || j >= 0) { + if (i >= 0) + carry += arr1[i--]; + if (j >= 0) + carry += arr2[j--]; + ans.push_front(carry & 1); + carry = -(carry >> 1); + } + + while (ans.size() > 1 && ans.front() == 0) + ans.pop_front(); + + return {ans.begin(), ans.end()}; + } +}; diff --git a/solutions/1073. Adding Two Negabinary Numbers/1073.java b/solutions/1073. Adding Two Negabinary Numbers/1073.java new file mode 100644 index 00000000000..c0d1c151aa0 --- /dev/null +++ b/solutions/1073. Adding Two Negabinary Numbers/1073.java @@ -0,0 +1,22 @@ +class Solution { + public int[] addNegabinary(int[] arr1, int[] arr2) { + Deque ans = new ArrayDeque<>(); + int carry = 0; + int i = arr1.length - 1; + int j = arr2.length - 1; + + while (carry != 0 || i >= 0 || j >= 0) { + if (i >= 0) + carry += arr1[i--]; + if (j >= 0) + carry += arr2[j--]; + ans.addFirst(carry & 1); + carry = -(carry >> 1); + } + + while (ans.size() > 1 && ans.getFirst() == 0) + ans.pollFirst(); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/1073. Adding Two Negabinary Numbers/1073.py b/solutions/1073. Adding Two Negabinary Numbers/1073.py new file mode 100644 index 00000000000..a6c83ff0c8b --- /dev/null +++ b/solutions/1073. Adding Two Negabinary Numbers/1073.py @@ -0,0 +1,17 @@ +class Solution: + def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]: + ans = [] + carry = 0 + + while carry != 0 or arr1 or arr2: + if arr1: + carry += arr1.pop() + if arr2: + carry += arr2.pop() + ans.append(carry & 1) + carry = -(carry >> 1) + + while len(ans) > 1 and ans[-1] == 0: + ans.pop() + + return ans[::-1] diff --git a/solutions/1074. Number of Submatrices That Sum to Target/1074.cpp b/solutions/1074. Number of Submatrices That Sum to Target/1074.cpp new file mode 100644 index 00000000000..09f977330ab --- /dev/null +++ b/solutions/1074. Number of Submatrices That Sum to Target/1074.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int numSubmatrixSumTarget(vector>& matrix, int target) { + const int m = matrix.size(); + const int n = matrix[0].size(); + int ans = 0; + + // Transfer each row in the matrix to the prefix sum. + for (auto& row : matrix) + for (int i = 1; i < n; ++i) + row[i] += row[i - 1]; + + for (int baseCol = 0; baseCol < n; ++baseCol) + for (int j = baseCol; j < n; ++j) { + unordered_map prefixCount{{0, 1}}; + int sum = 0; + for (int i = 0; i < m; ++i) { + if (baseCol > 0) + sum -= matrix[i][baseCol - 1]; + sum += matrix[i][j]; + if (const auto it = prefixCount.find(sum - target); + it != prefixCount.cend()) + ans += it->second; + ++prefixCount[sum]; + } + } + + return ans; + } +}; diff --git a/solutions/1074. Number of Submatrices That Sum to Target/1074.java b/solutions/1074. Number of Submatrices That Sum to Target/1074.java new file mode 100644 index 00000000000..46ef48084f7 --- /dev/null +++ b/solutions/1074. Number of Submatrices That Sum to Target/1074.java @@ -0,0 +1,28 @@ +class Solution { + public int numSubmatrixSumTarget(int[][] matrix, int target) { + final int m = matrix.length; + final int n = matrix[0].length; + int ans = 0; + + // Transfer each row in the matrix to the prefix sum. + for (int[] row : matrix) + for (int i = 1; i < n; ++i) + row[i] += row[i - 1]; + + for (int baseCol = 0; baseCol < n; ++baseCol) + for (int j = baseCol; j < n; ++j) { + Map prefixCount = new HashMap<>(); + prefixCount.put(0, 1); + int sum = 0; + for (int i = 0; i < m; ++i) { + if (baseCol > 0) + sum -= matrix[i][baseCol - 1]; + sum += matrix[i][j]; + ans += prefixCount.getOrDefault(sum - target, 0); + prefixCount.merge(sum, 1, Integer::sum); + } + } + + return ans; + } +} diff --git a/solutions/1074. Number of Submatrices That Sum to Target/1074.py b/solutions/1074. Number of Submatrices That Sum to Target/1074.py new file mode 100644 index 00000000000..56b619ce305 --- /dev/null +++ b/solutions/1074. Number of Submatrices That Sum to Target/1074.py @@ -0,0 +1,23 @@ +class Solution: + def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: + m = len(matrix) + n = len(matrix[0]) + ans = 0 + + # Transfer each row in the matrix to the prefix sum. + for row in matrix: + for i in range(1, n): + row[i] += row[i - 1] + + for baseCol in range(n): + for j in range(baseCol, n): + prefixCount = collections.Counter({0: 1}) + summ = 0 + for i in range(m): + if baseCol > 0: + summ -= matrix[i][baseCol - 1] + summ += matrix[i][j] + ans += prefixCount[summ - target] + prefixCount[summ] += 1 + + return ans diff --git a/solutions/1075. Project Employees I/1075.sql b/solutions/1075. Project Employees I/1075.sql new file mode 100644 index 00000000000..53768a4bd9c --- /dev/null +++ b/solutions/1075. Project Employees I/1075.sql @@ -0,0 +1,7 @@ +SELECT + Project.project_id, + ROUND(AVG(Employee.experience_years), 2) AS average_years +FROM Project +INNER JOIN Employee + USING (employee_id) +GROUP BY 1; diff --git a/solutions/1076. Project Employees II/1076.sql b/solutions/1076. Project Employees II/1076.sql new file mode 100644 index 00000000000..0588c25a170 --- /dev/null +++ b/solutions/1076. Project Employees II/1076.sql @@ -0,0 +1,9 @@ +WITH + RankedProjects AS ( + SELECT project_id, RANK() OVER(ORDER BY COUNT(*) DESC) AS `rank` + FROM Project + GROUP BY 1 + ) +SELECT project_id +FROM RankedProjects +WHERE `rank` = 1; diff --git a/solutions/1077. Project Employees III/1077.sql b/solutions/1077. Project Employees III/1077.sql new file mode 100644 index 00000000000..08894c92fed --- /dev/null +++ b/solutions/1077. Project Employees III/1077.sql @@ -0,0 +1,16 @@ +WITH + RankedProjectToEmployee AS ( + SELECT + Project.project_id, + Project.employee_id, + RANK() OVER( + PARTITION BY Project.project_id + ORDER BY Employee.experience_years DESC + ) AS `rank` + FROM Project + INNER JOIN Employee + USING (employee_id) + ) +SELECT project_id, employee_id +FROM RankedProjectToEmployee +WHERE `rank` = 1; diff --git a/solutions/1078. Occurrences After Bigram/1078.cpp b/solutions/1078. Occurrences After Bigram/1078.cpp new file mode 100644 index 00000000000..e05e02f0db5 --- /dev/null +++ b/solutions/1078. Occurrences After Bigram/1078.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector findOcurrences(string text, string first, string second) { + vector ans; + stringstream ss(text); + + for (string prev2, prev, word; ss >> word;) { + if (prev2 == first && prev == second) + ans.push_back(word); + prev2 = prev; + prev = word; + } + + return ans; + } +}; diff --git a/solutions/1078. Occurrences After Bigram/1078.java b/solutions/1078. Occurrences After Bigram/1078.java new file mode 100644 index 00000000000..e94f1308e29 --- /dev/null +++ b/solutions/1078. Occurrences After Bigram/1078.java @@ -0,0 +1,12 @@ +class Solution { + public String[] findOcurrences(String text, String first, String second) { + List ans = new ArrayList<>(); + String[] words = text.split(" "); + + for (int i = 0; i + 2 < words.length; ++i) + if (first.equals(words[i]) && second.equals(words[i + 1])) + ans.add(words[i + 2]); + + return ans.toArray(new String[0]); + } +} diff --git a/solutions/1078. Occurrences After Bigram/1078.py b/solutions/1078. Occurrences After Bigram/1078.py new file mode 100644 index 00000000000..0eb5502a90d --- /dev/null +++ b/solutions/1078. Occurrences After Bigram/1078.py @@ -0,0 +1,4 @@ +class Solution: + def findOcurrences(self, text: str, first: str, second: str) -> List[str]: + words = text.split() + return [c for a, b, c in zip(words, words[1:], words[2:]) if a == first and b == second] diff --git a/solutions/1079. Letter Tile Possibilities/1079.cpp b/solutions/1079. Letter Tile Possibilities/1079.cpp new file mode 100644 index 00000000000..45efd00c936 --- /dev/null +++ b/solutions/1079. Letter Tile Possibilities/1079.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int numTilePossibilities(string tiles) { + vector count(26); + + for (const char t : tiles) + ++count[t - 'A']; + + return dfs(count); + } + + private: + int dfs(vector& count) { + int possibleSequences = 0; + + for (int& c : count) { + if (c == 0) + continue; + // Put c in the current position. We only care about the number of + // possible sequences of letters but don't care about the actual + // combination. + --c; + possibleSequences += 1 + dfs(count); + ++c; + } + + return possibleSequences; + } +}; diff --git a/solutions/1079. Letter Tile Possibilities/1079.java b/solutions/1079. Letter Tile Possibilities/1079.java new file mode 100644 index 00000000000..1fc4e39da13 --- /dev/null +++ b/solutions/1079. Letter Tile Possibilities/1079.java @@ -0,0 +1,26 @@ +class Solution { + public int numTilePossibilities(String tiles) { + int[] count = new int[26]; + + for (final char t : tiles.toCharArray()) + ++count[t - 'A']; + + return dfs(count); + } + + private int dfs(int[] count) { + int possibleSequences = 0; + + for (int i = 0; i < 26; ++i) { + if (count[i] == 0) + continue; + // Put c in the current position. We only care about the number of possible + // sequences of letters but don't care about the actual combination. + --count[i]; + possibleSequences += 1 + dfs(count); + ++count[i]; + } + + return possibleSequences; + } +} diff --git a/solutions/1079. Letter Tile Possibilities/1079.py b/solutions/1079. Letter Tile Possibilities/1079.py new file mode 100644 index 00000000000..b103df464c2 --- /dev/null +++ b/solutions/1079. Letter Tile Possibilities/1079.py @@ -0,0 +1,19 @@ +class Solution: + def numTilePossibilities(self, tiles: str) -> int: + count = collections.Counter(tiles) + + def dfs(count: Dict[int, int]) -> int: + possibleSequences = 0 + + for k, v in count.items(): + if v == 0: + continue + # Put c in the current position. We only care about the number of possible + # sequences of letters but don't care about the actual combination. + count[k] -= 1 + possibleSequences += 1 + dfs(count) + count[k] += 1 + + return possibleSequences + + return dfs(count) diff --git a/solutions/108. Convert Sorted Array to Binary Search Tree/108.cpp b/solutions/108. Convert Sorted Array to Binary Search Tree/108.cpp new file mode 100644 index 00000000000..116ed1faa88 --- /dev/null +++ b/solutions/108. Convert Sorted Array to Binary Search Tree/108.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + TreeNode* sortedArrayToBST(vector& nums) { + return build(nums, 0, nums.size() - 1); + } + + private: + TreeNode* build(const vector& nums, int l, int r) { + if (l > r) + return nullptr; + const int m = (l + r) / 2; + return new TreeNode(nums[m], build(nums, l, m - 1), build(nums, m + 1, r)); + } +}; diff --git a/solutions/108. Convert Sorted Array to Binary Search Tree/108.java b/solutions/108. Convert Sorted Array to Binary Search Tree/108.java new file mode 100644 index 00000000000..a5b12ddc8a2 --- /dev/null +++ b/solutions/108. Convert Sorted Array to Binary Search Tree/108.java @@ -0,0 +1,12 @@ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + return build(nums, 0, nums.length - 1); + } + + private TreeNode build(int[] nums, int l, int r) { + if (l > r) + return null; + final int m = (l + r) / 2; + return new TreeNode(nums[m], build(nums, l, m - 1), build(nums, m + 1, r)); + } +} diff --git a/solutions/108. Convert Sorted Array to Binary Search Tree/108.py b/solutions/108. Convert Sorted Array to Binary Search Tree/108.py new file mode 100644 index 00000000000..49923961e60 --- /dev/null +++ b/solutions/108. Convert Sorted Array to Binary Search Tree/108.py @@ -0,0 +1,11 @@ +class Solution: + def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: + def build(l: int, r: int) -> Optional[TreeNode]: + if l > r: + return None + m = (l + r) // 2 + return TreeNode(nums[m], + build(l, m - 1), + build(m + 1, r)) + + return build(0, len(nums) - 1) diff --git a/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.cpp b/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.cpp new file mode 100644 index 00000000000..739360cf09e --- /dev/null +++ b/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + TreeNode* sufficientSubset(TreeNode* root, int limit) { + if (root == nullptr) + return nullptr; + if (root->left == nullptr && root->right == nullptr) + return root->val < limit ? nullptr : root; + root->left = sufficientSubset(root->left, limit - root->val); + root->right = sufficientSubset(root->right, limit - root->val); + return root->left == nullptr && root->right == nullptr ? nullptr : root; + } +}; diff --git a/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.java b/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.java new file mode 100644 index 00000000000..1d3c211ccd3 --- /dev/null +++ b/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.java @@ -0,0 +1,11 @@ +class Solution { + public TreeNode sufficientSubset(TreeNode root, int limit) { + if (root == null) + return null; + if (root.left == null && root.right == null) + return root.val < limit ? null : root; + root.left = sufficientSubset(root.left, limit - root.val); + root.right = sufficientSubset(root.right, limit - root.val); + return root.left == null && root.right == null ? null : root; + } +} diff --git a/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.py b/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.py new file mode 100644 index 00000000000..e65b027fcbe --- /dev/null +++ b/solutions/1080. Insufficient Nodes in Root to Leaf Paths/1080.py @@ -0,0 +1,9 @@ +class Solution: + def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]: + if not root: + return None + if not root.left and not root.right: + return None if root.val < limit else root + root.left = self.sufficientSubset(root.left, limit - root.val) + root.right = self.sufficientSubset(root.right, limit - root.val) + return None if not root.left and not root.right else root diff --git a/solutions/1081. Smallest Subsequence of Distinct Characters/1081.cpp b/solutions/1081. Smallest Subsequence of Distinct Characters/1081.cpp new file mode 100644 index 00000000000..f2457ae61d9 --- /dev/null +++ b/solutions/1081. Smallest Subsequence of Distinct Characters/1081.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string smallestSubsequence(string text) { + string ans; + vector count(128); + vector used(128); + + for (const char c : text) + ++count[c]; + + for (const char c : text) { + --count[c]; + if (used[c]) + continue; + while (!ans.empty() && ans.back() > c && count[ans.back()] > 0) { + used[ans.back()] = false; + ans.pop_back(); + } + used[c] = true; + ans.push_back(c); + } + + return ans; + } +}; diff --git a/solutions/1081. Smallest Subsequence of Distinct Characters/1081.java b/solutions/1081. Smallest Subsequence of Distinct Characters/1081.java new file mode 100644 index 00000000000..4ce3a9b9b6b --- /dev/null +++ b/solutions/1081. Smallest Subsequence of Distinct Characters/1081.java @@ -0,0 +1,28 @@ +class Solution { + public String smallestSubsequence(String text) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[128]; + boolean[] used = new boolean[128]; + + for (final char c : text.toCharArray()) + ++count[c]; + + for (final char c : text.toCharArray()) { + --count[c]; + if (used[c]) + continue; + while (sb.length() > 0 && last(sb) > c && count[last(sb)] > 0) { + used[last(sb)] = false; + sb.setLength(sb.length() - 1); + } + used[c] = true; + sb.append(c); + } + + return sb.toString(); + } + + private char last(StringBuilder sb) { + return sb.charAt(sb.length() - 1); + } +} diff --git a/solutions/1081. Smallest Subsequence of Distinct Characters/1081.py b/solutions/1081. Smallest Subsequence of Distinct Characters/1081.py new file mode 100644 index 00000000000..ea15d43bc9b --- /dev/null +++ b/solutions/1081. Smallest Subsequence of Distinct Characters/1081.py @@ -0,0 +1,17 @@ +class Solution: + def smallestSubsequence(self, text: str) -> str: + ans = [] + count = collections.Counter(text) + used = [False] * 26 + + for c in text: + count[c] -= 1 + if used[ord(c) - ord('a')]: + continue + while ans and ans[-1] > c and count[ans[-1]] > 0: + used[ord(ans[-1]) - ord('a')] = False + ans.pop() + ans.append(c) + used[ord(ans[-1]) - ord('a')] = True + + return ''.join(ans) diff --git a/solutions/1082. Sales Analysis I/1082.sql b/solutions/1082. Sales Analysis I/1082.sql new file mode 100644 index 00000000000..159e467f8c5 --- /dev/null +++ b/solutions/1082. Sales Analysis I/1082.sql @@ -0,0 +1,12 @@ +WITH + SellerToPrice AS ( + SELECT seller_id, SUM(price) AS price + FROM Sales + GROUP BY 1 + ) +SELECT seller_id +FROM SellerToPrice +WHERE price = ( + SELECT MAX(price) + FROM SellerToPrice + ); diff --git a/solutions/1083. Sales Analysis II/1083.sql b/solutions/1083. Sales Analysis II/1083.sql new file mode 100644 index 00000000000..677ca98c9ef --- /dev/null +++ b/solutions/1083. Sales Analysis II/1083.sql @@ -0,0 +1,8 @@ +SELECT Sales.buyer_id +FROM Sales +INNER JOIN Product + USING (product_id) +GROUP BY 1 +HAVING + SUM(Product.product_name = 'S8') > 0 + AND SUM(Product.product_name = 'iPhone') = 0; diff --git a/solutions/1084. Sales Analysis III/1084.sql b/solutions/1084. Sales Analysis III/1084.sql new file mode 100644 index 00000000000..d2f201e18b3 --- /dev/null +++ b/solutions/1084. Sales Analysis III/1084.sql @@ -0,0 +1,11 @@ +SELECT + Product.product_id, + Product.product_name +FROM Product +INNER JOIN Sales + USING (product_id) +GROUP BY 1, 2 +HAVING SUM( + Sales.sale_date < '2019-01-01' + OR Sales.sale_date > '2019-03-31' + ) = 0; diff --git a/solutions/1085. Sum of Digits in the Minimum Number/1085.cpp b/solutions/1085. Sum of Digits in the Minimum Number/1085.cpp new file mode 100644 index 00000000000..65bcf98cc89 --- /dev/null +++ b/solutions/1085. Sum of Digits in the Minimum Number/1085.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int sumOfDigits(vector& nums) { + int mn = ranges::min(nums); + int sum = 0; + + while (mn > 0) { + sum += mn % 10; + mn /= 10; + } + + return sum & 1 ^ 1; + } +}; diff --git a/solutions/1085. Sum of Digits in the Minimum Number/1085.java b/solutions/1085. Sum of Digits in the Minimum Number/1085.java new file mode 100644 index 00000000000..ee375088e1e --- /dev/null +++ b/solutions/1085. Sum of Digits in the Minimum Number/1085.java @@ -0,0 +1,13 @@ +class Solution { + public int sumOfDigits(int[] nums) { + int mn = Arrays.stream(nums).min().getAsInt(); + int sum = 0; + + while (mn > 0) { + sum += mn % 10; + mn /= 10; + } + + return sum & 1 ^ 1; + } +} diff --git a/solutions/1085. Sum of Digits in the Minimum Number/1085.py b/solutions/1085. Sum of Digits in the Minimum Number/1085.py new file mode 100644 index 00000000000..88d4b80e278 --- /dev/null +++ b/solutions/1085. Sum of Digits in the Minimum Number/1085.py @@ -0,0 +1,3 @@ +class Solution: + def sumOfDigits(self, nums: List[int]) -> int: + return sum(int(d) for d in str(min(nums))) & 1 ^ 1 diff --git a/solutions/1086. High Five/1086.cpp b/solutions/1086. High Five/1086.cpp new file mode 100644 index 00000000000..996a4bc7d36 --- /dev/null +++ b/solutions/1086. High Five/1086.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector> highFive(vector>& items) { + vector> ans; + map, greater>> idToScores; + + for (const vector& item : items) { + const int id = item[0]; + const int score = item[1]; + auto& scores = idToScores[id]; + scores.push(score); + if (scores.size() > 5) + scores.pop(); + } + + for (auto& [id, scores] : idToScores) { + int sum = 0; + while (!scores.empty()) + sum += scores.top(), scores.pop(); + ans.push_back({id, sum / 5}); + } + + return ans; + } +}; diff --git a/solutions/1086. High Five/1086.java b/solutions/1086. High Five/1086.java new file mode 100644 index 00000000000..2bf246ea114 --- /dev/null +++ b/solutions/1086. High Five/1086.java @@ -0,0 +1,27 @@ +class Solution { + public int[][] highFive(int[][] items) { + List ans = new ArrayList<>(); + Map> idToScores = new TreeMap<>(); + + for (int[] item : items) { + final int id = item[0]; + final int score = item[1]; + idToScores.putIfAbsent(id, new PriorityQueue<>()); + PriorityQueue scores = idToScores.get(id); + scores.add(score); + if (scores.size() > 5) + scores.poll(); + } + + for (Map.Entry> entry : idToScores.entrySet()) { + final int id = entry.getKey(); + PriorityQueue scores = entry.getValue(); + int sum = 0; + while (!scores.isEmpty()) + sum += scores.poll(); + ans.add(new int[] {id, sum / 5}); + } + + return ans.toArray(int[][] ::new); + } +} diff --git a/solutions/1086. High Five/1086.py b/solutions/1086. High Five/1086.py new file mode 100644 index 00000000000..074d553ec2b --- /dev/null +++ b/solutions/1086. High Five/1086.py @@ -0,0 +1,10 @@ +class Solution: + def highFive(self, items: List[List[int]]) -> List[List[int]]: + idToScores = collections.defaultdict(list) + + for id, score in items: + heapq.heappush(idToScores[id], score) + if len(idToScores[id]) > 5: + heapq.heappop(idToScores[id]) + + return [[id, sum(scores) // 5] for id, scores in sorted(idToScores.items())] diff --git a/solutions/1087. Brace Expansion/1087.cpp b/solutions/1087. Brace Expansion/1087.cpp new file mode 100644 index 00000000000..dea63731421 --- /dev/null +++ b/solutions/1087. Brace Expansion/1087.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector expand(string s) { + vector ans; + string path; + dfs(s, 0, path, ans); + return ans; + } + + private: + void dfs(const string& s, int i, string& path, vector& ans) { + if (i == s.length()) { + ans.push_back(path); + return; + } + if (s[i] == '{') { + const int nextRightBraceIndex = s.find_first_of('}', i); + for (const char c : + split(s.substr(i + 1, nextRightBraceIndex - i - 1), ',')) { + path.push_back(c); + dfs(s, nextRightBraceIndex + 1, path, ans); + path.pop_back(); + } + } else { // s[i] != '{' + path.push_back(s[i]); + dfs(s, i + 1, path, ans); + path.pop_back(); + } + } + + vector split(const string& s, char delimiter) { + vector splitted; + for (const char c : s) + if (c != delimiter) + splitted.push_back(c); + return splitted; + } +}; diff --git a/solutions/1087. Brace Expansion/1087.java b/solutions/1087. Brace Expansion/1087.java new file mode 100644 index 00000000000..e2bf93b5dd8 --- /dev/null +++ b/solutions/1087. Brace Expansion/1087.java @@ -0,0 +1,28 @@ +class Solution { + public String[] expand(String s) { + List ans = new ArrayList<>(); + + dfs(s, 0, new StringBuilder(), ans); + Collections.sort(ans); + return ans.toArray(new String[0]); + } + + private void dfs(final String s, int i, StringBuilder sb, List ans) { + if (i == s.length()) { + ans.add(sb.toString()); + return; + } + if (s.charAt(i) == '{') { + final int nextRightBraceIndex = s.indexOf("}", i); + for (final String c : s.substring(i + 1, nextRightBraceIndex).split(",")) { + sb.append(c); + dfs(s, nextRightBraceIndex + 1, sb, ans); + sb.deleteCharAt(sb.length() - 1); + } + } else { // s[i] != '{' + sb.append(s.charAt(i)); + dfs(s, i + 1, sb, ans); + sb.deleteCharAt(sb.length() - 1); + } + } +} diff --git a/solutions/1087. Brace Expansion/1087.py b/solutions/1087. Brace Expansion/1087.py new file mode 100644 index 00000000000..2870a70fa58 --- /dev/null +++ b/solutions/1087. Brace Expansion/1087.py @@ -0,0 +1,21 @@ +class Solution: + def expand(self, s: str) -> List[str]: + ans = [] + + def dfs(i: int, path: List[str]) -> None: + if i == len(s): + ans.append(''.join(path)) + return + if s[i] == '{': + nextRightBraceIndex = s.find('}', i) + for c in s[i + 1:nextRightBraceIndex].split(','): + path.append(c) + dfs(nextRightBraceIndex + 1, path) + path.pop() + else: # s[i] != '{' + path.append(s[i]) + dfs(i + 1, path) + path.pop() + + dfs(0, []) + return sorted(ans) diff --git a/solutions/1088. Confusing Number II/1088.cpp b/solutions/1088. Confusing Number II/1088.cpp new file mode 100644 index 00000000000..70719d706b6 --- /dev/null +++ b/solutions/1088. Confusing Number II/1088.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int confusingNumberII(int n) { + return dfs(n, 0, 0, 1); + } + + private: + vector> digitToRotated{{0, 0}, {1, 1}, {6, 9}, {8, 8}, {9, 6}}; + + int dfs(int n, long num, long rotatedNum, long unit) { + int ans = num != rotatedNum; + // Add one more digit + for (const auto& [digit, rotated] : digitToRotated) { + if (digit == 0 && num == 0) + continue; + const long nextNum = num * 10 + digit; + if (nextNum > n) + break; + ans += dfs(n, nextNum, rotated * unit + rotatedNum, unit * 10); + } + return ans; + } +}; diff --git a/solutions/1088. Confusing Number II/1088.java b/solutions/1088. Confusing Number II/1088.java new file mode 100644 index 00000000000..66ecf659ee8 --- /dev/null +++ b/solutions/1088. Confusing Number II/1088.java @@ -0,0 +1,23 @@ +class Solution { + public int confusingNumberII(int n) { + return dfs(n, 0, 0, 1); + } + + private int[][] digitToRotated = {{0, 0}, {1, 1}, {6, 9}, {8, 8}, {9, 6}}; + + int dfs(int n, long num, long rotatedNum, long unit) { + int ans = num == rotatedNum ? 0 : 1; + // Add one more digit + for (int[] pair : digitToRotated) { + final int digit = pair[0]; + final int rotated = pair[1]; + if (digit == 0 && num == 0) + continue; + final long nextNum = num * 10 + digit; + if (nextNum > n) + break; + ans += dfs(n, nextNum, rotated * unit + rotatedNum, unit * 10); + } + return ans; + } +} diff --git a/solutions/1088. Confusing Number II/1088.py b/solutions/1088. Confusing Number II/1088.py new file mode 100644 index 00000000000..d3ce079f471 --- /dev/null +++ b/solutions/1088. Confusing Number II/1088.py @@ -0,0 +1,17 @@ +class Solution: + def confusingNumberII(self, n: int) -> int: + digitToRotated = [(0, 0), (1, 1), (6, 9), (8, 8), (9, 6)] + + def dfs(num: int, rotatedNum: int, unit: int) -> int: + ans = 0 if num == rotatedNum else 1 + # Add one more digit + for digit, rotated in digitToRotated: + if digit == 0 and num == 0: + continue + nextNum = num * 10 + digit + if nextNum > n: + break + ans += dfs(nextNum, rotated * unit + rotatedNum, unit * 10) + return ans + + return dfs(0, 0, 1) diff --git a/solutions/1089. Duplicate Zeros/1089.cpp b/solutions/1089. Duplicate Zeros/1089.cpp new file mode 100644 index 00000000000..d1602a135dd --- /dev/null +++ b/solutions/1089. Duplicate Zeros/1089.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + void duplicateZeros(vector& arr) { + int zeros = ranges::count_if(arr, [](int a) { return a == 0; }); + + for (int i = arr.size() - 1, j = arr.size() + zeros - 1; i < j; --i, --j) { + if (j < arr.size()) + arr[j] = arr[i]; + if (arr[i] == 0) + if (--j < arr.size()) + arr[j] = arr[i]; + } + } +}; diff --git a/solutions/1089. Duplicate Zeros/1089.java b/solutions/1089. Duplicate Zeros/1089.java new file mode 100644 index 00000000000..97c6eac1deb --- /dev/null +++ b/solutions/1089. Duplicate Zeros/1089.java @@ -0,0 +1,17 @@ +class Solution { + public void duplicateZeros(int[] arr) { + int zeros = 0; + + for (int a : arr) + if (a == 0) + ++zeros; + + for (int i = arr.length - 1, j = arr.length + zeros - 1; i < j; --i, --j) { + if (j < arr.length) + arr[j] = arr[i]; + if (arr[i] == 0) + if (--j < arr.length) + arr[j] = arr[i]; + } + } +} diff --git a/solutions/1089. Duplicate Zeros/1089.py b/solutions/1089. Duplicate Zeros/1089.py new file mode 100644 index 00000000000..1294ace2e0b --- /dev/null +++ b/solutions/1089. Duplicate Zeros/1089.py @@ -0,0 +1,15 @@ +class Solution: + def duplicateZeros(self, arr: List[int]) -> None: + zeros = arr.count(0) + i = len(arr) - 1 + j = len(arr) + zeros - 1 + + while i < j: + if j < len(arr): + arr[j] = arr[i] + if arr[i] == 0: + j -= 1 + if j < len(arr): + arr[j] = arr[i] + i -= 1 + j -= 1 diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109-2.cpp b/solutions/109. Convert Sorted List to Binary Search Tree/109-2.cpp new file mode 100644 index 00000000000..14236bda325 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + TreeNode* sortedListToBST(ListNode* head) { + vector A; + + // Construct the array. + for (ListNode* curr = head; curr; curr = curr->next) + A.push_back(curr->val); + + return helper(A, 0, A.size() - 1); + } + + private: + TreeNode* helper(const vector& A, int l, int r) { + if (l > r) + return nullptr; + + const int m = (l + r) / 2; + TreeNode* root = new TreeNode(A[m]); + root->left = helper(A, l, m - 1); + root->right = helper(A, m + 1, r); + return root; + } +}; diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109-2.java b/solutions/109. Convert Sorted List to Binary Search Tree/109-2.java new file mode 100644 index 00000000000..d0213610bd6 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109-2.java @@ -0,0 +1,22 @@ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + List A = new ArrayList<>(); + + // Construct the array. + for (ListNode curr = head; curr != null; curr = curr.next) + A.add(curr.val); + + return helper(A, 0, A.size() - 1); + } + + private TreeNode helper(List A, int l, int r) { + if (l > r) + return null; + + final int m = (l + r) / 2; + TreeNode root = new TreeNode(A.get(m)); + root.left = helper(A, l, m - 1); + root.right = helper(A, m + 1, r); + return root; + } +} diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109-2.py b/solutions/109. Convert Sorted List to Binary Search Tree/109-2.py new file mode 100644 index 00000000000..05ce272278c --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109-2.py @@ -0,0 +1,21 @@ +class Solution: + def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: + A = [] + + # Construct the array. + curr = head + while curr: + A.append(curr.val) + curr = curr.next + + def helper(l: int, r: int) -> Optional[TreeNode]: + if l > r: + return None + + m = (l + r) // 2 + root = TreeNode(A[m]) + root.left = helper(l, m - 1) + root.right = helper(m + 1, r) + return root + + return helper(0, len(A) - 1) diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109-3.cpp b/solutions/109. Convert Sorted List to Binary Search Tree/109-3.cpp new file mode 100644 index 00000000000..70deee062d8 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109-3.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + TreeNode* sortedListToBST(ListNode* head) { + this->head = head; + return helper(0, getLength(head) - 1); + } + + private: + ListNode* head; + + TreeNode* helper(int l, int r) { + if (l > r) + return nullptr; + + const int m = (l + r) / 2; + + // Simulate inorder traversal: recursively form the left half. + TreeNode* left = helper(l, m - 1); + + // Once the left half is traversed, process the current node. + TreeNode* root = new TreeNode(head->val); + root->left = left; + + // Maintain the invariance. + head = head->next; + + // Simulate inorder traversal: recursively form the right half. + root->right = helper(m + 1, r); + return root; + } + + int getLength(ListNode* head) { + int length = 0; + for (ListNode* curr = head; curr; curr = curr->next) + ++length; + return length; + } +}; diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109-3.java b/solutions/109. Convert Sorted List to Binary Search Tree/109-3.java new file mode 100644 index 00000000000..2b26d293ca8 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109-3.java @@ -0,0 +1,36 @@ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + this.head = head; + return helper(0, getLength(head) - 1); + } + + private ListNode head; + + private TreeNode helper(int l, int r) { + if (l > r) + return null; + + final int m = (l + r) / 2; + + // Simulate inorder traversal: recursively form the left half. + TreeNode left = helper(l, m - 1); + + // Once the left half is traversed, process the current node. + TreeNode root = new TreeNode(head.val); + root.left = left; + + // Maintain the invariance. + head = head.next; + + // Simulate inorder traversal: recursively form the right half. + root.right = helper(m + 1, r); + return root; + } + + private int getLength(ListNode head) { + int length = 0; + for (ListNode curr = head; curr != null; curr = curr.next) + ++length; + return length; + } +} diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109-3.py b/solutions/109. Convert Sorted List to Binary Search Tree/109-3.py new file mode 100644 index 00000000000..03cd2f4bec8 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109-3.py @@ -0,0 +1,32 @@ +class Solution: + def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: + def helper(l: int, r: int) -> Optional[TreeNode]: + nonlocal head + if l > r: + return None + + m = (l + r) // 2 + + # Simulate inorder traversal: recursively form the left half. + left = helper(l, m - 1) + + # Once the left half is traversed, process the current node. + root = TreeNode(head.val) + root.left = left + + # Maintain the invariance. + head = head.next + + # Simulate inorder traversal: recursively form the right half. + root.right = helper(m + 1, r) + return root + + return helper(0, self._getLength(head) - 1) + + def _getLength(self, head: Optional[ListNode]) -> int: + length = 0 + curr = head + while curr: + length += 1 + curr = curr.next + return length diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109.cpp b/solutions/109. Convert Sorted List to Binary Search Tree/109.cpp new file mode 100644 index 00000000000..2ebcada53e1 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + TreeNode* sortedListToBST(ListNode* head) { + if (head == nullptr) + return nullptr; + if (!head->next) + return new TreeNode(head->val); + + ListNode* mid = findMid(head); + TreeNode* root = new TreeNode(mid->val); + root->left = sortedListToBST(head); + root->right = sortedListToBST(mid->next); + + return root; + } + + private: + ListNode* findMid(ListNode* head) { + ListNode* prev = nullptr; + ListNode* slow = head; + ListNode* fast = head; + + while (fast != nullptr && fast->next != nullptr) { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + prev->next = nullptr; + + return slow; + } +}; diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109.java b/solutions/109. Convert Sorted List to Binary Search Tree/109.java new file mode 100644 index 00000000000..a4fc009de05 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109.java @@ -0,0 +1,30 @@ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + if (head == null) + return null; + if (head.next == null) + return new TreeNode(head.val); + + ListNode mid = findMid(head); + TreeNode root = new TreeNode(mid.val); + root.left = sortedListToBST(head); + root.right = sortedListToBST(mid.next); + + return root; + } + + private ListNode findMid(ListNode head) { + ListNode prev = null; + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) { + prev = slow; + slow = slow.next; + fast = fast.next.next; + } + prev.next = null; + + return slow; + } +} diff --git a/solutions/109. Convert Sorted List to Binary Search Tree/109.py b/solutions/109. Convert Sorted List to Binary Search Tree/109.py new file mode 100644 index 00000000000..40bbdf9b971 --- /dev/null +++ b/solutions/109. Convert Sorted List to Binary Search Tree/109.py @@ -0,0 +1,26 @@ +class Solution: + def sortedListToBST(self, head: ListNode) -> TreeNode: + def findMid(head: ListNode) -> ListNode: + prev = None + slow = head + fast = head + + while fast and fast.next: + prev = slow + slow = slow.next + fast = fast.next.next + prev.next = None + + return slow + + if not head: + return None + if not head.next: + return TreeNode(head.val) + + mid = findMid(head) + root = TreeNode(mid.val) + root.left = self.sortedListToBST(head) + root.right = self.sortedListToBST(mid.next) + + return root diff --git a/solutions/1090. Largest Values From Labels/1090.cpp b/solutions/1090. Largest Values From Labels/1090.cpp new file mode 100644 index 00000000000..8e8b8ddbad1 --- /dev/null +++ b/solutions/1090. Largest Values From Labels/1090.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int largestValsFromLabels(vector& values, vector& labels, + int num_wanted, int use_limit) { + const int n = values.size(); + int ans = 0; + vector> items; + unordered_map labelsUsed; + + for (int i = 0; i < n; ++i) + items.emplace_back(values[i], labels[i]); + + ranges::sort( + items, [](const auto& a, const auto& b) { return a.first > b.first; }); + + for (const auto& [value, label] : items) { + if (labelsUsed[label] < use_limit) { + ans += value; + ++labelsUsed[label]; + if (--num_wanted == 0) + break; + } + } + + return ans; + } +}; diff --git a/solutions/1091. Shortest Path in Binary Matrix/1091.cpp b/solutions/1091. Shortest Path in Binary Matrix/1091.cpp new file mode 100644 index 00000000000..b8fb99934e5 --- /dev/null +++ b/solutions/1091. Shortest Path in Binary Matrix/1091.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int shortestPathBinaryMatrix(vector>& grid) { + const int n = grid.size(); + if (grid[0][0] == 0 && n == 1) + return 1; + if (grid[0][0] == 1 || grid.back().back() == 1) + return -1; + + const vector> dirs{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, + {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + + int ans = 0; + queue> q{{{0, 0}}}; + vector> seen(n, vector(n)); + seen[0][0] = true; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (grid[x][y] != 0 || seen[x][y]) + continue; + if (x == n - 1 && y == n - 1) + return ans + 1; + q.emplace(x, y); + seen[x][y] = true; + } + } + } + + return -1; + } +}; diff --git a/solutions/1091. Shortest Path in Binary Matrix/1091.java b/solutions/1091. Shortest Path in Binary Matrix/1091.java new file mode 100644 index 00000000000..0fa871a2dc0 --- /dev/null +++ b/solutions/1091. Shortest Path in Binary Matrix/1091.java @@ -0,0 +1,39 @@ +class Solution { + public int shortestPathBinaryMatrix(int[][] grid) { + final int n = grid.length; + if (grid[0][0] == 0 && n == 1) + return 1; + if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) + return -1; + + final int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + + int ans = 0; + Queue q = new ArrayDeque<>(); + q.offer(new int[] {0, 0}); + boolean[][] seen = new boolean[n][n]; + seen[0][0] = true; + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (grid[x][y] != 0 || seen[x][y]) + continue; + if (x == n - 1 && y == n - 1) + return ans + 1; + q.offer(new int[] {x, y}); + seen[x][y] = true; + } + } + } + + return -1; + } +} diff --git a/solutions/1092. Shortest Common Supersequence/1092.cpp b/solutions/1092. Shortest Common Supersequence/1092.cpp new file mode 100644 index 00000000000..bdb894fa7fc --- /dev/null +++ b/solutions/1092. Shortest Common Supersequence/1092.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + string shortestCommonSupersequence(string str1, string str2) { + string ans; + int i = 0; // str1's index + int j = 0; // str2's index + + for (const char c : lcs(str1, str2)) { + // Append the letters that are not part of the LCS. + while (str1[i] != c) + ans += str1[i++]; + while (str2[j] != c) + ans += str2[j++]; + // Append the letter of the LCS and match it with str1 and str2. + ans += c; + ++i; + ++j; + } + + // Append the remaining letters. + return ans + str1.substr(i) + str2.substr(j); + } + + private: + string lcs(const string& a, const string& b) { + const int m = a.length(); + const int n = b.length(); + // dp[i][j] := the length of LCS(a[0..i), b[0..j)) + vector> dp(m + 1, vector(n + 1)); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (a[i - 1] == b[j - 1]) + dp[i][j] = dp[i - 1][j - 1] + a[i - 1]; + else + dp[i][j] = dp[i - 1][j].length() > dp[i][j - 1].length() + ? dp[i - 1][j] + : dp[i][j - 1]; + + return dp[m][n]; + } +}; diff --git a/solutions/1092. Shortest Common Supersequence/1092.java b/solutions/1092. Shortest Common Supersequence/1092.java new file mode 100644 index 00000000000..523a4b9fa67 --- /dev/null +++ b/solutions/1092. Shortest Common Supersequence/1092.java @@ -0,0 +1,42 @@ +class Solution { + public String shortestCommonSupersequence(String str1, String str2) { + StringBuilder sb = new StringBuilder(); + int i = 0; // str1's index + int j = 0; // str2's index + + for (final char c : lcs(str1, str2).toCharArray()) { + // Append the letters that are not part of the LCS. + while (str1.charAt(i) != c) + sb.append(str1.charAt(i++)); + while (str2.charAt(j) != c) + sb.append(str2.charAt(j++)); + // Append the letter of the LCS and match it with str1 and str2. + sb.append(c); + ++i; + ++j; + } + + // Append the remaining letters. + return sb.toString() + str1.substring(i) + str2.substring(j); + } + + private String lcs(final String a, final String b) { + final int m = a.length(); + final int n = b.length(); + // dp[i][j] := the length of LCS(a[0..i), b[0..j)) + StringBuilder[][] dp = new StringBuilder[m + 1][n + 1]; + + for (final StringBuilder[] row : dp) + for (int i = 0; i < row.length; ++i) + row[i] = new StringBuilder(); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (a.charAt(i - 1) == b.charAt(j - 1)) + dp[i][j].append(dp[i - 1][j - 1]).append(a.charAt(i - 1)); + else + dp[i][j] = dp[i - 1][j].length() > dp[i][j - 1].length() ? dp[i - 1][j] : dp[i][j - 1]; + + return dp[m][n].toString(); + } +} diff --git a/solutions/1093. Statistics from a Large Sample/1093.cpp b/solutions/1093. Statistics from a Large Sample/1093.cpp new file mode 100644 index 00000000000..8f86ea2e055 --- /dev/null +++ b/solutions/1093. Statistics from a Large Sample/1093.cpp @@ -0,0 +1,56 @@ +class Solution { + public: + vector sampleStats(vector& count) { + const int n = accumulate(count.begin(), count.end(), 0); + const double mode = ranges::max_element(count) - count.begin(); + return { + getMinimum(count), + getMaximum(count), + getMean(count, n), + (getLeftMedian(count, n) + getRightMedian(count, n)) / 2.0, + mode, + }; + } + + private: + double getMinimum(const vector& count) { + for (int i = 0; i < count.size(); ++i) + if (count[i]) + return i; + return -1; + } + + double getMaximum(const vector& count) { + for (int i = count.size() - 1; i >= 0; --i) + if (count[i]) + return i; + return -1; + } + + double getMean(const vector& count, double n) { + double mean = 0; + for (long i = 0; i < count.size(); ++i) + mean += (i * count[i]) / n; + return mean; + } + + double getLeftMedian(const vector& count, double n) { + int numCount = 0; + for (int i = 0; i < count.size(); ++i) { + numCount += count[i]; + if (numCount >= n / 2) + return i; + } + return -1; + } + + double getRightMedian(const vector& count, double n) { + int numCount = 0; + for (int i = count.size() - 1; i >= 0; --i) { + numCount += count[i]; + if (numCount >= n / 2) + return i; + } + return -1; + } +}; diff --git a/solutions/1093. Statistics from a Large Sample/1093.java b/solutions/1093. Statistics from a Large Sample/1093.java new file mode 100644 index 00000000000..fe8db5e1850 --- /dev/null +++ b/solutions/1093. Statistics from a Large Sample/1093.java @@ -0,0 +1,64 @@ +class Solution { + public double[] sampleStats(int[] count) { + final int n = Arrays.stream(count).sum(); + return new double[] { + getMinimum(count), // + getMaximum(count), // + getMean(count, n), // + (getLeftMedian(count, n) + getRightMedian(count, n)) / 2.0, // + getMode(count), + }; + } + + private double getMinimum(int[] count) { + for (int i = 0; i < count.length; ++i) + if (count[i] > 0) + return i; + return -1; + } + + private double getMaximum(int[] count) { + for (int i = count.length - 1; i >= 0; --i) + if (count[i] > 0) + return i; + return -1; + } + + private double getMean(int[] count, double n) { + double mean = 0; + for (int i = 0; i < count.length; ++i) + mean += ((long) i * (long) count[i]) / n; + return mean; + } + + private double getLeftMedian(int[] count, double n) { + int numCount = 0; + for (int i = 0; i < count.length; ++i) { + numCount += count[i]; + if (numCount >= n / 2) + return i; + } + return -1; + } + + private double getRightMedian(int[] count, double n) { + int numCount = 0; + for (int i = count.length - 1; i >= 0; --i) { + numCount += count[i]; + if (numCount >= n / 2) + return i; + } + return -1; + } + + private double getMode(int[] count) { + int mode = -1; + int maxCount = 0; + for (int i = 0; i < count.length; ++i) + if (count[i] > maxCount) { + maxCount = count[i]; + mode = i; + } + return mode; + } +} diff --git a/solutions/1093. Statistics from a Large Sample/1093.py b/solutions/1093. Statistics from a Large Sample/1093.py new file mode 100644 index 00000000000..7ee3123099e --- /dev/null +++ b/solutions/1093. Statistics from a Large Sample/1093.py @@ -0,0 +1,26 @@ +class Solution: + def sampleStats(self, count: List[int]) -> List[float]: + minimum = next((i for i, num in enumerate(count) if num), None) + maximum = next((i for i, num in reversed( + list(enumerate(count))) if num), None) + n = sum(count) + mean = sum(i * c / n for i, c in enumerate(count)) + mode = count.index(max(count)) + + numCount = 0 + leftMedian = 0 + for i, c in enumerate(count): + numCount += c + if numCount >= n / 2: + leftMedian = i + break + + numCount = 0 + rightMedian = 0 + for i, c in reversed(list(enumerate(count))): + numCount += c + if numCount >= n / 2: + rightMedian = i + break + + return [minimum, maximum, mean, (leftMedian + rightMedian) / 2, mode] diff --git a/solutions/1094. Car Pooling/1094-2.cpp b/solutions/1094. Car Pooling/1094-2.cpp new file mode 100644 index 00000000000..ef8eed13992 --- /dev/null +++ b/solutions/1094. Car Pooling/1094-2.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool carPooling(vector>& trips, int capacity) { + int currentPassengers = 0; + vector line(1001); + + for (const vector& trip : trips) { + const int nPassengers = trip[0]; + const int start = trip[1]; + const int end = trip[2]; + line[start] += nPassengers; + line[end] -= nPassengers; + } + + for (const int passengerChange : line) { + currentPassengers += passengerChange; + if (currentPassengers > capacity) + return false; + } + + return true; + } +}; diff --git a/solutions/1094. Car Pooling/1094-2.java b/solutions/1094. Car Pooling/1094-2.java new file mode 100644 index 00000000000..1ebeb9822e8 --- /dev/null +++ b/solutions/1094. Car Pooling/1094-2.java @@ -0,0 +1,22 @@ +class Solution { + public boolean carPooling(int[][] trips, int capacity) { + int currentPassengers = 0; + int[] line = new int[1001]; + + for (int[] trip : trips) { + final int nPassengers = trip[0]; + final int start = trip[1]; + final int end = trip[2]; + line[start] += nPassengers; + line[end] -= nPassengers; + } + + for (final int passengerChange : line) { + currentPassengers += passengerChange; + if (currentPassengers > capacity) + return false; + } + + return true; + } +} diff --git a/solutions/1094. Car Pooling/1094.cpp b/solutions/1094. Car Pooling/1094.cpp new file mode 100644 index 00000000000..9b7ba5ab271 --- /dev/null +++ b/solutions/1094. Car Pooling/1094.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool carPooling(vector>& trips, int capacity) { + int currentPassengers = 0; + map line; + + for (const vector& trip : trips) { + const int nPassengers = trip[0]; + const int start = trip[1]; + const int end = trip[2]; + line[start] += nPassengers; + line[end] -= nPassengers; + } + + for (const auto [_, passengerChange] : line) { + currentPassengers += passengerChange; + if (currentPassengers > capacity) + return false; + } + + return true; + } +}; diff --git a/solutions/1094. Car Pooling/1094.java b/solutions/1094. Car Pooling/1094.java new file mode 100644 index 00000000000..2f8938e6782 --- /dev/null +++ b/solutions/1094. Car Pooling/1094.java @@ -0,0 +1,22 @@ +class Solution { + public boolean carPooling(int[][] trips, int capacity) { + int currentPassengers = 0; + Map line = new TreeMap<>(); + + for (int[] trip : trips) { + final int nPassengers = trip[0]; + final int start = trip[1]; + final int end = trip[2]; + line.merge(start, nPassengers, Integer::sum); + line.merge(end, -nPassengers, Integer::sum); + } + + for (final int passengerChange : line.values()) { + currentPassengers += passengerChange; + if (currentPassengers > capacity) + return false; + } + + return true; + } +} diff --git a/solutions/1095. Find in Mountain Array/1095.cpp b/solutions/1095. Find in Mountain Array/1095.cpp new file mode 100644 index 00000000000..e36c516b38e --- /dev/null +++ b/solutions/1095. Find in Mountain Array/1095.cpp @@ -0,0 +1,63 @@ +/** + * // This is the MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * class MountainArray { + * public: + * int get(int index); + * int length(); + * }; + */ + +class Solution { + public: + int findInMountainArray(int target, MountainArray& mountainArr) { + const int n = mountainArr.length(); + const int peakIndex = peakIndexInMountainArray(mountainArr, 0, n - 1); + + const int leftIndex = searchLeft(mountainArr, target, 0, peakIndex); + if (mountainArr.get(leftIndex) == target) + return leftIndex; + + const int rightIndex = + searchRight(mountainArr, target, peakIndex + 1, n - 1); + if (mountainArr.get(rightIndex) == target) + return rightIndex; + + return -1; + } + + private: + // 852. Peak Index in a Mountain Array + int peakIndexInMountainArray(MountainArray& A, int l, int r) { + while (l < r) { + const int m = (l + r) / 2; + if (A.get(m) < A.get(m + 1)) + l = m + 1; + else + r = m; + } + return l; + } + + int searchLeft(MountainArray& A, int target, int l, int r) { + while (l < r) { + const int m = (l + r) / 2; + if (A.get(m) < target) + l = m + 1; + else + r = m; + } + return l; + } + + int searchRight(MountainArray& A, int target, int l, int r) { + while (l < r) { + const int m = (l + r) / 2; + if (A.get(m) > target) + l = m + 1; + else + r = m; + } + return l; + } +}; diff --git a/solutions/1095. Find in Mountain Array/1095.java b/solutions/1095. Find in Mountain Array/1095.java new file mode 100644 index 00000000000..7d7ca16e1c9 --- /dev/null +++ b/solutions/1095. Find in Mountain Array/1095.java @@ -0,0 +1,59 @@ +/** + * // This is MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * interface MountainArray { + * public int get(int index) {} + * public int length() {} + * } + */ + +class Solution { + public int findInMountainArray(int target, MountainArray mountainArr) { + final int n = mountainArr.length(); + final int peakIndex = peakIndexInMountainArray(mountainArr, 0, n - 1); + + final int leftIndex = searchLeft(mountainArr, target, 0, peakIndex); + if (mountainArr.get(leftIndex) == target) + return leftIndex; + + final int rightIndex = searchRight(mountainArr, target, peakIndex + 1, n - 1); + if (mountainArr.get(rightIndex) == target) + return rightIndex; + + return -1; + } + + // 852. Peak Index in a Mountain Array + private int peakIndexInMountainArray(MountainArray A, int l, int r) { + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m) < A.get(m + 1)) + l = m + 1; + else + r = m; + } + return l; + } + + private int searchLeft(MountainArray A, int target, int l, int r) { + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m) < target) + l = m + 1; + else + r = m; + } + return l; + } + + private int searchRight(MountainArray A, int target, int l, int r) { + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m) > target) + l = m + 1; + else + r = m; + } + return l; + } +} diff --git a/solutions/1095. Find in Mountain Array/1095.py b/solutions/1095. Find in Mountain Array/1095.py new file mode 100644 index 00000000000..9dddd864fe0 --- /dev/null +++ b/solutions/1095. Find in Mountain Array/1095.py @@ -0,0 +1,50 @@ +# """ +# This is MountainArray's API interface. +# You should not implement it, or speculate about its implementation +# """ +# Class MountainArray: +# def get(self, index: int) -> int: +# def length(self) -> int: + +class Solution: + def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int: + n = mountain_arr.length() + peakIndex = self.peakIndexInMountainArray(mountain_arr, 0, n - 1) + + leftIndex = self.searchLeft(mountain_arr, target, 0, peakIndex) + if mountain_arr.get(leftIndex) == target: + return leftIndex + + rightIndex = self.searchRight(mountain_arr, target, peakIndex + 1, n - 1) + if mountain_arr.get(rightIndex) == target: + return rightIndex + + return -1 + + # 852. Peak Index in a Mountain Array + def peakIndexInMountainArray(self, A: 'MountainArray', l: int, r: int) -> int: + while l < r: + m = (l + r) // 2 + if A.get(m) < A.get(m + 1): + l = m + 1 + else: + r = m + return l + + def searchLeft(self, A: 'MountainArray', target: int, l: int, r: int) -> int: + while l < r: + m = (l + r) // 2 + if A.get(m) < target: + l = m + 1 + else: + r = m + return l + + def searchRight(self, A: 'MountainArray', target: int, l: int, r: int) -> int: + while l < r: + m = (l + r) // 2 + if A.get(m) > target: + l = m + 1 + else: + r = m + return l diff --git a/solutions/1096. Brace Expansion II/1096.cpp b/solutions/1096. Brace Expansion II/1096.cpp new file mode 100644 index 00000000000..f9273eee50f --- /dev/null +++ b/solutions/1096. Brace Expansion II/1096.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + vector braceExpansionII(string expression) { + return dfs(expression, 0, expression.length() - 1); + } + + private: + vector dfs(const string& expression, int s, int e) { + set ans; + vector> groups{{}}; + int layer = 0; + int left = 0; + + for (int i = s; i <= e; ++i) + if (expression[i] == '{' && ++layer == 1) + left = i + 1; + else if (expression[i] == '}' && --layer == 0) + merge(groups, dfs(expression, left, i - 1)); + else if (expression[i] == ',' && layer == 0) + groups.push_back({}); + else if (layer == 0) + merge(groups, {string(1, expression[i])}); + + for (const vector& group : groups) + for (const string& word : group) + ans.insert(word); + + return {ans.begin(), ans.end()}; + } + + void merge(vector>& groups, const vector group) { + if (groups.back().empty()) { + groups[groups.size() - 1] = group; + return; + } + + vector mergedGroup; + + for (auto& word1 : groups.back()) + for (auto& word2 : group) + mergedGroup.push_back(word1 + word2); + + groups[groups.size() - 1] = mergedGroup; + } +}; diff --git a/solutions/1096. Brace Expansion II/1096.java b/solutions/1096. Brace Expansion II/1096.java new file mode 100644 index 00000000000..983e58d3fc9 --- /dev/null +++ b/solutions/1096. Brace Expansion II/1096.java @@ -0,0 +1,44 @@ +class Solution { + public List braceExpansionII(String expression) { + return dfs(expression, 0, expression.length() - 1); + } + + private List dfs(final String expression, int s, int e) { + TreeSet ans = new TreeSet<>(); + List> groups = new ArrayList<>(); + groups.add(new ArrayList<>()); + int layer = 0; + int left = 0; + + for (int i = s; i <= e; ++i) + if (expression.charAt(i) == '{' && ++layer == 1) + left = i + 1; + else if (expression.charAt(i) == '}' && --layer == 0) + merge(groups, dfs(expression, left, i - 1)); + else if (expression.charAt(i) == ',' && layer == 0) + groups.add(new ArrayList<>()); + else if (layer == 0) + merge(groups, new ArrayList<>(Arrays.asList(String.valueOf(expression.charAt(i))))); + + for (final List group : groups) + for (final String word : group) + ans.add(word); + + return new ArrayList<>(ans); + } + + void merge(List> groups, List group) { + if (groups.get(groups.size() - 1).isEmpty()) { + groups.set(groups.size() - 1, group); + return; + } + + List mergedGroup = new ArrayList<>(); + + for (final String word1 : groups.get(groups.size() - 1)) + for (final String word2 : group) + mergedGroup.add(word1 + word2); + + groups.set(groups.size() - 1, mergedGroup); + } +} diff --git a/solutions/1096. Brace Expansion II/1096.py b/solutions/1096. Brace Expansion II/1096.py new file mode 100644 index 00000000000..38a9bd00c60 --- /dev/null +++ b/solutions/1096. Brace Expansion II/1096.py @@ -0,0 +1,33 @@ +class Solution: + def braceExpansionII(self, expression: str) -> List[str]: + def merge(groups: List[List[str]], group: List[str]) -> None: + if not groups[-1]: + groups[-1] = group + return + + groups[-1] = [word1 + word2 for word1 in groups[-1] + for word2 in group] + + def dfs(s: int, e: int) -> List[str]: + groups = [[]] + layer = 0 + + for i in range(s, e + 1): + c = expression[i] + if c == '{': + layer += 1 + if layer == 1: + left = i + 1 + elif c == '}': + layer -= 1 + if layer == 0: + group = dfs(left, i - 1) + merge(groups, group) + elif c == ',' and layer == 0: + groups.append([]) + elif layer == 0: + merge(groups, [c]) + + return sorted(list({word for group in groups for word in group})) + + return dfs(0, len(expression) - 1) diff --git a/solutions/1097. Game Play Analysis V/1097.sql b/solutions/1097. Game Play Analysis V/1097.sql new file mode 100644 index 00000000000..bff188e8052 --- /dev/null +++ b/solutions/1097. Game Play Analysis V/1097.sql @@ -0,0 +1,18 @@ +WITH + PlayerToInstallDate AS ( + SELECT player_id, MIN(event_date) AS install_dt + FROM Activity + GROUP BY 1 + ) +SELECT PlayerToInstallDate.install_dt, + COUNT(*) AS installs, + ROUND( + SUM(IF(Activity.event_date, 1, 0)) / COUNT(PlayerToInstallDate.install_dt), + 2 + ) AS Day1_retention +FROM PlayerToInstallDate +LEFT JOIN Activity + ON ( + PlayerToInstallDate.player_id = Activity.player_id + AND DATEDIFF(Activity.event_date, PlayerToInstallDate.install_dt) = 1) +GROUP BY 1; diff --git a/solutions/1098. Unpopular Books/1098.sql b/solutions/1098. Unpopular Books/1098.sql new file mode 100644 index 00000000000..8d5352008b7 --- /dev/null +++ b/solutions/1098. Unpopular Books/1098.sql @@ -0,0 +1,11 @@ +SELECT + Books.book_id, + ANY_VALUE(Books.name) AS name +FROM Books +LEFT JOIN Orders + ON ( + Books.book_id = Orders.book_id + AND Orders.dispatch_date BETWEEN '2018-06-23' AND '2019-06-23') +WHERE DATEDIFF('2019-06-23', Books.available_from) > 30 +GROUP BY 1 +HAVING IFNULL(SUM(Orders.quantity), 0) < 10; diff --git a/solutions/1099. Two Sum Less Than K/1099.cpp b/solutions/1099. Two Sum Less Than K/1099.cpp new file mode 100644 index 00000000000..5585222ac30 --- /dev/null +++ b/solutions/1099. Two Sum Less Than K/1099.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int twoSumLessThanK(vector& nums, int k) { + if (nums.size() < 2) + return -1; + + int ans = -1; // Note the constraint that nums[i] > 0. + int l = 0; + int r = nums.size() - 1; + + ranges::sort(nums); + + while (l < r) + if (nums[l] + nums[r] < k) { + ans = max(ans, nums[l] + nums[r]); + ++l; + } else { + --r; + } + + return ans; + } +}; diff --git a/solutions/1099. Two Sum Less Than K/1099.java b/solutions/1099. Two Sum Less Than K/1099.java new file mode 100644 index 00000000000..b7ceaf724c2 --- /dev/null +++ b/solutions/1099. Two Sum Less Than K/1099.java @@ -0,0 +1,22 @@ +class Solution { + public int twoSumLessThanK(int[] nums, int k) { + if (nums.length < 2) + return -1; + + int ans = -1; // Note the constraint that nums[i] > 0. + int l = 0; + int r = nums.length - 1; + + numsrrays.sort(nums); + + while (l < r) + if (nums[l] + nums[r] < k) { + ans = Math.max(ans, nums[l] + nums[r]); + ++l; + } else { + --r; + } + + return ans; + } +} diff --git a/solutions/1099. Two Sum Less Than K/1099.py b/solutions/1099. Two Sum Less Than K/1099.py new file mode 100644 index 00000000000..c0dc1b3cf91 --- /dev/null +++ b/solutions/1099. Two Sum Less Than K/1099.py @@ -0,0 +1,19 @@ +class Solution: + def twoSumLessThanK(self, nums: List[int], k: int) -> int: + if len(nums) < 2: + return -1 + + ans = -1 # Note the constrathat nums[i] > 0. + l = 0 + r = len(nums) - 1 + + nums.sort() + + while l < r: + if nums[l] + nums[r] < k: + ans = max(ans, nums[l] + nums[r]) + l += 1 + else: + r -= 1 + + return ans diff --git a/solutions/11. Container With Most Water/11.cpp b/solutions/11. Container With Most Water/11.cpp new file mode 100644 index 00000000000..53b52c6c396 --- /dev/null +++ b/solutions/11. Container With Most Water/11.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maxArea(vector& height) { + int ans = 0; + int l = 0; + int r = height.size() - 1; + + while (l < r) { + const int minHeight = min(height[l], height[r]); + ans = max(ans, minHeight * (r - l)); + if (height[l] < height[r]) + ++l; + else + --r; + } + + return ans; + } +}; diff --git a/solutions/11. Container With Most Water/11.java b/solutions/11. Container With Most Water/11.java new file mode 100644 index 00000000000..720da671e90 --- /dev/null +++ b/solutions/11. Container With Most Water/11.java @@ -0,0 +1,18 @@ +class Solution { + public int maxArea(int[] height) { + int ans = 0; + int l = 0; + int r = height.length - 1; + + while (l < r) { + final int minHeight = Math.min(height[l], height[r]); + ans = Math.max(ans, minHeight * (r - l)); + if (height[l] < height[r]) + ++l; + else + --r; + } + + return ans; + } +} diff --git a/solutions/11. Container With Most Water/11.py b/solutions/11. Container With Most Water/11.py new file mode 100644 index 00000000000..201f1941fb5 --- /dev/null +++ b/solutions/11. Container With Most Water/11.py @@ -0,0 +1,15 @@ +class Solution: + def maxArea(self, height: List[int]) -> int: + ans = 0 + l = 0 + r = len(height) - 1 + + while l < r: + minHeight = min(height[l], height[r]) + ans = max(ans, minHeight * (r - l)) + if height[l] < height[r]: + l += 1 + else: + r -= 1 + + return ans diff --git a/solutions/110. Balanced Binary Tree/110-2.cpp b/solutions/110. Balanced Binary Tree/110-2.cpp new file mode 100644 index 00000000000..3c282180b87 --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110-2.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool isBalanced(TreeNode* root) { + bool ans = true; + maxDepth(root, ans); + return ans; + } + + // Returns the height of root and sets ans to false if root unbalanced. + int maxDepth(TreeNode* root, bool& ans) { + if (root == nullptr || !ans) + return 0; + const int left = maxDepth(root->left, ans); + const int right = maxDepth(root->right, ans); + if (abs(left - right) > 1) + ans = false; + return max(left, right) + 1; + } +}; diff --git a/solutions/110. Balanced Binary Tree/110-2.java b/solutions/110. Balanced Binary Tree/110-2.java new file mode 100644 index 00000000000..a5705a284be --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110-2.java @@ -0,0 +1,19 @@ +class Solution { + public boolean isBalanced(TreeNode root) { + maxDepth(root); + return ans; + } + + private boolean ans = true; + + // Returns the height of root and sets ans to false if root unbalanced. + public int maxDepth(TreeNode root) { + if (root == null || !ans) + return 0; + final int left = maxDepth(root.left); + final int right = maxDepth(root.right); + if (Math.abs(left - right) > 1) + ans = false; + return Math.max(left, right) + 1; + } +} diff --git a/solutions/110. Balanced Binary Tree/110-2.py b/solutions/110. Balanced Binary Tree/110-2.py new file mode 100644 index 00000000000..06f0dbe6b53 --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110-2.py @@ -0,0 +1,17 @@ +class Solution: + def isBalanced(self, root: Optional[TreeNode]) -> bool: + ans = True + + def maxDepth(root: Optional[TreeNode]) -> int: + """Returns the height of root and sets ans to false if root unbalanced.""" + nonlocal ans + if not root or not ans: + return 0 + left = maxDepth(root.left) + right = maxDepth(root.right) + if abs(left - right) > 1: + ans = False + return max(left, right) + 1 + + maxDepth(root) + return ans diff --git a/solutions/110. Balanced Binary Tree/110-3.cpp b/solutions/110. Balanced Binary Tree/110-3.cpp new file mode 100644 index 00000000000..2fb7f1aa5d8 --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110-3.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + bool isBalanced(TreeNode* root) { + return maxDepth(root) != -1; + } + + private: + // Returns the height of root if root is balanced; otherwise, returns -1. + int maxDepth(TreeNode* root) { + if (root == nullptr) + return 0; + + const int left = maxDepth(root->left); + if (left == -1) + return -1; + const int right = maxDepth(root->right); + if (right == -1) + return -1; + if (abs(left - right) > 1) + return -1; + + return 1 + max(left, right); + } +}; diff --git a/solutions/110. Balanced Binary Tree/110-3.java b/solutions/110. Balanced Binary Tree/110-3.java new file mode 100644 index 00000000000..7c9a76a813b --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110-3.java @@ -0,0 +1,22 @@ +class Solution { + public boolean isBalanced(TreeNode root) { + return maxDepth(root) != -1; + } + + // Returns the height of root if root is balanced; otherwise, returns -1. + private int maxDepth(TreeNode root) { + if (root == null) + return 0; + + final int left = maxDepth(root.left); + if (left == -1) + return -1; + final int right = maxDepth(root.right); + if (right == -1) + return -1; + if (Math.abs(left - right) > 1) + return -1; + + return 1 + Math.max(left, right); + } +} diff --git a/solutions/110. Balanced Binary Tree/110-3.py b/solutions/110. Balanced Binary Tree/110-3.py new file mode 100644 index 00000000000..946b1c588b6 --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110-3.py @@ -0,0 +1,19 @@ +class Solution: + def isBalanced(self, root: Optional[TreeNode]) -> bool: + def maxDepth(root: Optional[TreeNode]) -> int: + """Returns the height of root if root is balanced; otherwise, returns -1.""" + if not root: + return 0 + + left = maxDepth(root.left) + if left == -1: + return -1 + right = maxDepth(root.right) + if right == -1: + return -1 + if abs(left - right) > 1: + return -1 + + return 1 + max(maxDepth(root.left), maxDepth(root.right)) + + return maxDepth(root) != -1 diff --git a/solutions/110. Balanced Binary Tree/110.cpp b/solutions/110. Balanced Binary Tree/110.cpp new file mode 100644 index 00000000000..2ed35ff0c24 --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool isBalanced(TreeNode* root) { + if (root == nullptr) + return true; + return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 && + isBalanced(root->left) && isBalanced(root->right); + } + + private: + int maxDepth(TreeNode* root) { + if (root == nullptr) + return 0; + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; diff --git a/solutions/110. Balanced Binary Tree/110.java b/solutions/110. Balanced Binary Tree/110.java new file mode 100644 index 00000000000..61405c7ee98 --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isBalanced(TreeNode root) { + if (root == null) + return true; + return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 && // + isBalanced(root.left) && // + isBalanced(root.right); + } + + private int maxDepth(TreeNode root) { + if (root == null) + return 0; + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } +} diff --git a/solutions/110. Balanced Binary Tree/110.py b/solutions/110. Balanced Binary Tree/110.py new file mode 100644 index 00000000000..e9b36f5af0a --- /dev/null +++ b/solutions/110. Balanced Binary Tree/110.py @@ -0,0 +1,12 @@ +class Solution: + def isBalanced(self, root: Optional[TreeNode]) -> bool: + if not root: + return True + + def maxDepth(root: Optional[TreeNode]) -> int: + if not root: + return 0 + return 1 + max(maxDepth(root.left), maxDepth(root.right)) + + return abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 and \ + self.isBalanced(root.left) and self.isBalanced(root.right) diff --git a/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.cpp b/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.cpp new file mode 100644 index 00000000000..939ebba9493 --- /dev/null +++ b/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int numKLenSubstrNoRepeats(string s, int k) { + int ans = 0; + int unique = 0; + vector count(26); + + for (int i = 0; i < s.length(); ++i) { + if (++count[s[i] - 'a'] == 1) + ++unique; + if (i >= k && --count[s[i - k] - 'a'] == 0) + --unique; + if (unique == k) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.java b/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.java new file mode 100644 index 00000000000..bb512883136 --- /dev/null +++ b/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.java @@ -0,0 +1,18 @@ +class Solution { + public int numKLenSubstrNoRepeats(String s, int k) { + int ans = 0; + int unique = 0; + int[] count = new int[26]; + + for (int i = 0; i < s.length(); ++i) { + if (++count[s.charAt(i) - 'a'] == 1) + ++unique; + if (i >= k && --count[s.charAt(i - k) - 'a'] == 0) + --unique; + if (unique == k) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.py b/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.py new file mode 100644 index 00000000000..875bce2fcd1 --- /dev/null +++ b/solutions/1100. Find K-Length Substrings With No Repeated Characters/1100.py @@ -0,0 +1,18 @@ +class Solution: + def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: + ans = 0 + unique = 0 + count = collections.Counter() + + for i, c in enumerate(s): + count[c] += 1 + if count[c] == 1: + unique += 1 + if i >= k: + count[s[i - k]] -= 1 + if count[s[i - k]] == 0: + unique -= 1 + if unique == k: + ans += 1 + + return ans diff --git a/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.cpp b/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.cpp new file mode 100644 index 00000000000..e09a5e848e6 --- /dev/null +++ b/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.cpp @@ -0,0 +1,58 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + int earliestAcq(vector>& logs, int n) { + UnionFind uf(n); + + // Sort `logs` by timestamp. + sort( + logs.begin(), logs.end(), + [](const vector& a, const vector& b) { return a[0] < b[0]; }); + + for (const vector& log : logs) { + const int timestamp = log[0]; + const int x = log[1]; + const int y = log[2]; + uf.unionByRank(x, y); + if (uf.getCount() == 1) + return timestamp; + } + + return -1; + } +}; diff --git a/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.java b/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.java new file mode 100644 index 00000000000..bc75a0eb510 --- /dev/null +++ b/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.java @@ -0,0 +1,57 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + public int getCount() { + return count; + } + + private int count; + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int earliestAcq(int[][] logs, int n) { + UnionFind uf = new UnionFind(n); + + // Sort `logs` by timestamp. + Arrays.sort(logs, (a, b) -> a[0] - b[0]); + + for (int[] log : logs) { + final int timestamp = log[0]; + final int x = log[1]; + final int y = log[2]; + uf.unionByRank(x, y); + if (uf.getCount() == 1) + return timestamp; + } + + return -1; + } +} diff --git a/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.py b/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.py new file mode 100644 index 00000000000..bd1bb6f4716 --- /dev/null +++ b/solutions/1101. The Earliest Moment When Everyone Become Friends/1101.py @@ -0,0 +1,42 @@ +class UnionFind: + def __init__(self, n: int): + self.count = n + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self._find(u) + j = self._find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + self.count -= 1 + + def getCount(self) -> int: + return self.count + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def earliestAcq(self, logs: List[List[int]], n: int) -> int: + uf = UnionFind(n) + + logs.sort(key=lambda x: x[0]) + + # Sort `logs` by timestamp. + for timestamp, x, y in logs: + uf.unionByRank(x, y) + if uf.getCount() == 1: + return timestamp + + return -1 diff --git a/solutions/1102. Path With Maximum Minimum Value/1102.cpp b/solutions/1102. Path With Maximum Minimum Value/1102.cpp new file mode 100644 index 00000000000..ff8a5ac48bf --- /dev/null +++ b/solutions/1102. Path With Maximum Minimum Value/1102.cpp @@ -0,0 +1,41 @@ +struct T { + int i; + int j; + int val; + T(int i, int j, int val) : i(i), j(j), val(val) {} +}; + +class Solution { + public: + int maximumMinimumPath(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + int ans = grid[0][0]; + vector> seen(m, vector(n)); + auto compare = [](const T& a, const T& b) { return a.val < b.val; }; + priority_queue, decltype(compare)> maxHeap(compare); + + maxHeap.emplace(0, 0, grid[0][0]); + + while (!maxHeap.empty()) { + const auto [i, j, val] = maxHeap.top(); + maxHeap.pop(); + ans = min(ans, val); + if (i == m - 1 && j == n - 1) + return ans; + seen[i][j] = true; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + maxHeap.emplace(x, y, grid[x][y]); + } + } + + throw; + } +}; diff --git a/solutions/1102. Path With Maximum Minimum Value/1102.java b/solutions/1102. Path With Maximum Minimum Value/1102.java new file mode 100644 index 00000000000..26f4f1dcc09 --- /dev/null +++ b/solutions/1102. Path With Maximum Minimum Value/1102.java @@ -0,0 +1,44 @@ +class T { + public int i; + public int j; + public int val; + public T(int i, int j, int val) { + this.i = i; + this.j = j; + this.val = val; + } +} + +class Solution { + public int maximumMinimumPath(int[][] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length; + int ans = grid[0][0]; + boolean[][] seen = new boolean[m][n]; + Queue maxHeap = new PriorityQueue<>((a, b) -> b.val - a.val); + + maxHeap.offer(new T(0, 0, grid[0][0])); + + while (!maxHeap.isEmpty()) { + final int i = maxHeap.peek().i; + final int j = maxHeap.peek().j; + final int val = maxHeap.poll().val; + ans = Math.min(ans, val); + if (i == m - 1 && j == n - 1) + return ans; + seen[i][j] = true; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + maxHeap.offer(new T(x, y, grid[x][y])); + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1103. Distribute Candies to People/1103.cpp b/solutions/1103. Distribute Candies to People/1103.cpp new file mode 100644 index 00000000000..17eee153137 --- /dev/null +++ b/solutions/1103. Distribute Candies to People/1103.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector distributeCandies(int candies, long n) { + vector ans(n); + int rows = (-n + sqrt(n * n + 8 * n * n * candies)) / (2 * n * n); + int accumN = rows * (rows - 1) * n / 2; + + for (int i = 0; i < n; ++i) + ans[i] = accumN + rows * (i + 1); + + int givenCandies = (n * n * rows * rows + n * rows) / 2; + candies -= givenCandies; + + for (int i = 0, lastGiven = rows * n + 1; candies > 0; ++i, ++lastGiven) { + int actualGiven = min(lastGiven, candies); + candies -= actualGiven; + ans[i] += actualGiven; + } + + return ans; + } +}; diff --git a/solutions/1103. Distribute Candies to People/1103.java b/solutions/1103. Distribute Candies to People/1103.java new file mode 100644 index 00000000000..6593978d341 --- /dev/null +++ b/solutions/1103. Distribute Candies to People/1103.java @@ -0,0 +1,23 @@ +class Solution { + public int[] distributeCandies(int candies, int num_people) { + int[] ans = new int[num_people]; + long c = (long) candies; + long n = (long) num_people; + int rows = (int) (-n + Math.sqrt(n * n + 8 * n * n * c)) / (int) (2 * n * n); + int accumN = rows * (rows - 1) * num_people / 2; + + for (int i = 0; i < n; ++i) + ans[i] = accumN + rows * (i + 1); + + int givenCandies = (num_people * num_people * rows * rows + num_people * rows) / 2; + candies -= givenCandies; + + for (int i = 0, lastGiven = rows * num_people + 1; candies > 0; ++i, ++lastGiven) { + int actualGiven = Math.min(lastGiven, candies); + candies -= actualGiven; + ans[i] += actualGiven; + } + + return ans; + } +} diff --git a/solutions/1103. Distribute Candies to People/1103.py b/solutions/1103. Distribute Candies to People/1103.py new file mode 100644 index 00000000000..af808a47b33 --- /dev/null +++ b/solutions/1103. Distribute Candies to People/1103.py @@ -0,0 +1,22 @@ +class Solution: + def distributeCandies(self, candies: int, n: int) -> List[int]: + ans = [0] * n + rows = int((-n + (n**2 + 8 * n**2 * candies)**0.5) / (2 * n**2)) + accumN = rows * (rows - 1) * n // 2 + + for i in range(n): + ans[i] = accumN + rows * (i + 1) + + givenCandies = (n**2 * rows**2 + n * rows) // 2 + candies -= givenCandies + lastGiven = rows * n + i = 0 + + while candies > 0: + lastGiven += 1 + actualGiven = min(lastGiven, candies) + candies -= actualGiven + ans[i] += actualGiven + i += 1 + + return ans diff --git a/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.cpp b/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.cpp new file mode 100644 index 00000000000..f1dee396a57 --- /dev/null +++ b/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector pathInZigZagTree(int label) { + deque ans; + int level; + + for (int l = 0; l < 21; ++l) + if (pow(2, l) > label) { + level = l - 1; + break; + } + + if (level % 2 == 1) + label = boundarySum(level) - label; + + for (int l = level; l >= 0; --l) { + ans.push_front(l % 2 == 0 ? label : boundarySum(l) - label); + label /= 2; + } + + return {ans.begin(), ans.end()}; + } + + private: + int boundarySum(int level) { + return pow(2, level) + pow(2, level + 1) - 1; + } +}; diff --git a/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.java b/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.java new file mode 100644 index 00000000000..0394e558a40 --- /dev/null +++ b/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.java @@ -0,0 +1,26 @@ +class Solution { + public List pathInZigZagTree(int label) { + LinkedList ans = new LinkedList<>(); + int level = 0; + + for (int l = 0; l < 21; ++l) + if (Math.pow(2, l) > label) { + level = l - 1; + break; + } + + if (level % 2 == 1) + label = boundarySum(level) - label; + + for (int l = level; l >= 0; --l) { + ans.addFirst(l % 2 == 0 ? label : boundarySum(l) - label); + label /= 2; + } + + return new ArrayList<>(ans); + } + + private int boundarySum(int level) { + return (int) Math.pow(2, level) + (int) Math.pow(2, level + 1) - 1; + } +} diff --git a/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.py b/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.py new file mode 100644 index 00000000000..a9fc5560639 --- /dev/null +++ b/solutions/1104. Path In Zigzag Labelled Binary Tree/1104.py @@ -0,0 +1,20 @@ +class Solution: + def pathInZigZagTree(self, label: int) -> List[int]: + def boundarySum(level: int): + return 2**level + 2**(level + 1) - 1 + + ans = [] + + for l in range(21): + if 2**l > label: + level = l - 1 + break + + if level % 2 == 1: + label = boundarySum(level) - label + + for l in reversed(range(level + 1)): + ans.append(label if l % 2 == 0 else boundarySum(l) - label) + label //= 2 + + return ans[::-1] diff --git a/solutions/1105. Filling Bookcase Shelves/1105.cpp b/solutions/1105. Filling Bookcase Shelves/1105.cpp new file mode 100644 index 00000000000..5b27cf63f2a --- /dev/null +++ b/solutions/1105. Filling Bookcase Shelves/1105.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minHeightShelves(vector>& books, int shelfWidth) { + // dp[i] := the minimum height to place the first i books + vector dp(books.size() + 1, INT_MAX); + dp[0] = 0; + + for (int i = 0; i < books.size(); ++i) { + int sumThickness = 0; + int maxHeight = 0; + // Place books[j..i] on a new shelf. + for (int j = i; j >= 0; --j) { + const int thickness = books[j][0]; + const int height = books[j][1]; + sumThickness += thickness; + if (sumThickness > shelfWidth) + break; + maxHeight = max(maxHeight, height); + dp[i + 1] = min(dp[i + 1], dp[j] + maxHeight); + } + } + + return dp.back(); + } +}; diff --git a/solutions/1105. Filling Bookcase Shelves/1105.java b/solutions/1105. Filling Bookcase Shelves/1105.java new file mode 100644 index 00000000000..d253572c14e --- /dev/null +++ b/solutions/1105. Filling Bookcase Shelves/1105.java @@ -0,0 +1,26 @@ +class Solution { + public int minHeightShelves(int[][] books, int shelfWidth) { + final int n = books.length; + // dp[i] := the minimum height to place the first i books + int[] dp = new int[n + 1]; + Arrays.fill(dp, Integer.MAX_VALUE); + dp[0] = 0; + + for (int i = 0; i < books.length; ++i) { + int sumThickness = 0; + int maxHeight = 0; + // Place books[j..i] on a new shelf. + for (int j = i; j >= 0; --j) { + final int thickness = books[j][0]; + final int height = books[j][1]; + sumThickness += thickness; + if (sumThickness > shelfWidth) + break; + maxHeight = Math.max(maxHeight, height); + dp[i + 1] = Math.min(dp[i + 1], dp[j] + maxHeight); + } + } + + return dp[n]; + } +} diff --git a/solutions/1105. Filling Bookcase Shelves/1105.py b/solutions/1105. Filling Bookcase Shelves/1105.py new file mode 100644 index 00000000000..0cb3838a675 --- /dev/null +++ b/solutions/1105. Filling Bookcase Shelves/1105.py @@ -0,0 +1,18 @@ +class Solution: + def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: + # dp[i] := the minimum height to place the first i books + dp = [0] + [math.inf] * len(books) + + for i in range(len(books)): + sumThickness = 0 + maxHeight = 0 + # Place books[j..i] on a new shelf. + for j in range(i, -1, -1): + thickness, height = books[j] + sumThickness += thickness + if sumThickness > shelfWidth: + break + maxHeight = max(maxHeight, height) + dp[i + 1] = min(dp[i + 1], dp[j] + maxHeight) + + return dp[-1] diff --git a/solutions/1106. Parsing A Boolean Expression/1106.cpp b/solutions/1106. Parsing A Boolean Expression/1106.cpp new file mode 100644 index 00000000000..16bf4befe22 --- /dev/null +++ b/solutions/1106. Parsing A Boolean Expression/1106.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + bool parseBoolExpr(string expression) { + int i = 0; + return parse(expression, i); + } + + private: + bool parse(const string& exp, int& i) { + if (exp[i] == 't') { + ++i; + return true; + } + if (exp[i] == 'f') { + ++i; + return false; + } + if (exp[i] == '!') { + i += 2; + bool ans = !parse(exp, i); + ++i; + return ans; + } + + bool isAnd = exp[i] == '&'; + bool ans = isAnd; + i += 2; + while (exp[i] != ')') { + bool parsed = parse(exp, i); + if (isAnd) + ans &= parsed; + else + ans |= parsed; + if (exp[i] == ',') + ++i; + } + ++i; + return ans; + } +}; diff --git a/solutions/1106. Parsing A Boolean Expression/1106.java b/solutions/1106. Parsing A Boolean Expression/1106.java new file mode 100644 index 00000000000..397003a4851 --- /dev/null +++ b/solutions/1106. Parsing A Boolean Expression/1106.java @@ -0,0 +1,45 @@ +class Solution { + public boolean parseBoolExpr(String expression) { + return dfs(expression, 0, expression.length() - 1); + } + + private boolean dfs(final String expression, int s, int e) { + if (s == e) + return expression.charAt(s) == 't'; + + List exps = new ArrayList<>(); + int layer = 0; + int left = 0; + char op = ' '; + + for (int i = s; i <= e; ++i) { + char c = expression.charAt(i); + if (layer == 0 && (c == '!' || c == '&' || c == '|')) + op = c; + else if (c == '(' && ++layer == 1) + left = i + 1; + else if (c == ')' && --layer == 0) + exps.add(dfs(expression, left, i - 1)); + else if (c == ',' && layer == 1) { + exps.add(dfs(expression, left, i - 1)); + left = i + 1; + } + } + + if (op == '&') { + boolean ans = true; + for (boolean exp : exps) + ans &= exp; + return ans; + } + + if (op == '|') { + boolean ans = false; + for (boolean exp : exps) + ans |= exp; + return ans; + } + + return !exps.get(0); + } +} diff --git a/solutions/1106. Parsing A Boolean Expression/1106.py b/solutions/1106. Parsing A Boolean Expression/1106.py new file mode 100644 index 00000000000..c0e5c198129 --- /dev/null +++ b/solutions/1106. Parsing A Boolean Expression/1106.py @@ -0,0 +1,33 @@ +class Solution: + def parseBoolExpr(self, expression: str) -> bool: + def dfs(s: int, e: int) -> List[str]: + if s == e: + return True if expression[s] == 't' else False + + exps = [] + layer = 0 + + for i in range(s, e + 1): + c = expression[i] + if layer == 0 and c in '!&|': + op = c + elif c == '(': + layer += 1 + if layer == 1: + left = i + 1 + elif c == ')': + layer -= 1 + if layer == 0: + exps.append(dfs(left, i - 1)) + elif c == ',' and layer == 1: + exps.append(dfs(left, i - 1)) + left = i + 1 + + if op == '|': + return functools.reduce(operator.or_, exps) + if op == '&': + return functools.reduce(operator.and_, exps) + if op == '!': + return not exps[0] + + return dfs(0, len(expression) - 1) diff --git a/solutions/1107. New Users Daily Count/1107.sql b/solutions/1107. New Users Daily Count/1107.sql new file mode 100644 index 00000000000..61e3b8d8492 --- /dev/null +++ b/solutions/1107. New Users Daily Count/1107.sql @@ -0,0 +1,15 @@ +WITH + UserToLoginDate AS ( + SELECT + user_id, + MIN(activity_date) AS login_date + FROM Traffic + WHERE activity = 'login' + GROUP BY 1 + ) +SELECT + login_date, + COUNT(*) AS user_count +FROM UserToLoginDate +WHERE DATEDIFF('2019-06-30', login_date) <= 90 +GROUP BY 1; diff --git a/solutions/1108. Defanging an IP Address/1108.cpp b/solutions/1108. Defanging an IP Address/1108.cpp new file mode 100644 index 00000000000..b01a162dc5a --- /dev/null +++ b/solutions/1108. Defanging an IP Address/1108.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + string defangIPaddr(string address) { + return regex_replace(address, regex("[.]"), "[.]"); + } +}; diff --git a/solutions/1108. Defanging an IP Address/1108.java b/solutions/1108. Defanging an IP Address/1108.java new file mode 100644 index 00000000000..91bc8ee6867 --- /dev/null +++ b/solutions/1108. Defanging an IP Address/1108.java @@ -0,0 +1,5 @@ +class Solution { + public String defangIPaddr(String address) { + return address.replace(".", "[.]"); + } +} diff --git a/solutions/1108. Defanging an IP Address/1108.py b/solutions/1108. Defanging an IP Address/1108.py new file mode 100644 index 00000000000..ade19352b7f --- /dev/null +++ b/solutions/1108. Defanging an IP Address/1108.py @@ -0,0 +1,3 @@ +class Solution: + def defangIPaddr(self, address: str) -> str: + return address.replace('.', '[.]') diff --git a/solutions/1109. Corporate Flight Bookings/1109.cpp b/solutions/1109. Corporate Flight Bookings/1109.cpp new file mode 100644 index 00000000000..50e5748990b --- /dev/null +++ b/solutions/1109. Corporate Flight Bookings/1109.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector corpFlightBookings(vector>& bookings, int n) { + vector ans(n); + + for (vector& booking : bookings) { + ans[booking[0] - 1] += booking[2]; + if (booking[1] < n) + ans[booking[1]] -= booking[2]; + } + + for (int i = 1; i < n; ++i) + ans[i] += ans[i - 1]; + + return ans; + } +}; diff --git a/solutions/1109. Corporate Flight Bookings/1109.java b/solutions/1109. Corporate Flight Bookings/1109.java new file mode 100644 index 00000000000..b26fa830563 --- /dev/null +++ b/solutions/1109. Corporate Flight Bookings/1109.java @@ -0,0 +1,16 @@ +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + int[] ans = new int[n]; + + for (int[] booking : bookings) { + ans[booking[0] - 1] += booking[2]; + if (booking[1] < n) + ans[booking[1]] -= booking[2]; + } + + for (int i = 1; i < n; ++i) + ans[i] += ans[i - 1]; + + return ans; + } +} diff --git a/solutions/1109. Corporate Flight Bookings/1109.py b/solutions/1109. Corporate Flight Bookings/1109.py new file mode 100644 index 00000000000..62d09fa469f --- /dev/null +++ b/solutions/1109. Corporate Flight Bookings/1109.py @@ -0,0 +1,13 @@ +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + ans = [0] * n + + for booking in bookings: + ans[booking[0] - 1] += booking[2] + if booking[1] < n: + ans[booking[1]] -= booking[2] + + for i in range(1, n): + ans[i] += ans[i - 1] + + return ans diff --git a/solutions/111. Minimum Depth of Binary Tree/111-2.cpp b/solutions/111. Minimum Depth of Binary Tree/111-2.cpp new file mode 100644 index 00000000000..a0f9af879fd --- /dev/null +++ b/solutions/111. Minimum Depth of Binary Tree/111-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minDepth(TreeNode* root) { + if (root == nullptr) + return 0; + + int ans = 0; + queue q{{root}}; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + if (node->left == nullptr && node->right == nullptr) + return ans; + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + } + + throw; + } +}; diff --git a/solutions/111. Minimum Depth of Binary Tree/111-2.java b/solutions/111. Minimum Depth of Binary Tree/111-2.java new file mode 100644 index 00000000000..e7da421c7b7 --- /dev/null +++ b/solutions/111. Minimum Depth of Binary Tree/111-2.java @@ -0,0 +1,24 @@ +class Solution { + public int minDepth(TreeNode root) { + if (root == null) + return 0; + + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + if (node.left == null && node.right == null) + return ans; + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/111. Minimum Depth of Binary Tree/111-2.py b/solutions/111. Minimum Depth of Binary Tree/111-2.py new file mode 100644 index 00000000000..805d04d28f2 --- /dev/null +++ b/solutions/111. Minimum Depth of Binary Tree/111-2.py @@ -0,0 +1,18 @@ +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + ans = 0 + q = collections.deque([root]) + + while q: + ans += 1 + for _ in range(len(q)): + node = q.popleft() + if not node.left and not node.right: + return ans + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) diff --git a/solutions/111. Minimum Depth of Binary Tree/111.cpp b/solutions/111. Minimum Depth of Binary Tree/111.cpp new file mode 100644 index 00000000000..a8b06258a7c --- /dev/null +++ b/solutions/111. Minimum Depth of Binary Tree/111.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int minDepth(TreeNode* root) { + if (root == nullptr) + return 0; + if (root->left == nullptr) + return minDepth(root->right) + 1; + if (root->right == nullptr) + return minDepth(root->left) + 1; + return min(minDepth(root->left), minDepth(root->right)) + 1; + } +}; diff --git a/solutions/111. Minimum Depth of Binary Tree/111.java b/solutions/111. Minimum Depth of Binary Tree/111.java new file mode 100644 index 00000000000..bdf0f99a20c --- /dev/null +++ b/solutions/111. Minimum Depth of Binary Tree/111.java @@ -0,0 +1,11 @@ +class Solution { + public int minDepth(TreeNode root) { + if (root == null) + return 0; + if (root.left == null) + return minDepth(root.right) + 1; + if (root.right == null) + return minDepth(root.left) + 1; + return Math.min(minDepth(root.left), minDepth(root.right)) + 1; + } +} diff --git a/solutions/111. Minimum Depth of Binary Tree/111.py b/solutions/111. Minimum Depth of Binary Tree/111.py new file mode 100644 index 00000000000..8af7f5f8320 --- /dev/null +++ b/solutions/111. Minimum Depth of Binary Tree/111.py @@ -0,0 +1,9 @@ +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + if not root.left: + return self.minDepth(root.right) + 1 + if not root.right: + return self.minDepth(root.left) + 1 + return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 diff --git a/solutions/1110. Delete Nodes And Return Forest/1110.cpp b/solutions/1110. Delete Nodes And Return Forest/1110.cpp new file mode 100644 index 00000000000..78805e956ff --- /dev/null +++ b/solutions/1110. Delete Nodes And Return Forest/1110.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector delNodes(TreeNode* root, vector& to_delete) { + vector ans; + dfs(root, {to_delete.begin(), to_delete.end()}, true, ans); + return ans; + } + + private: + TreeNode* dfs(TreeNode*& root, const unordered_set&& toDeleteSet, + bool isRoot, vector& ans) { + if (root == nullptr) + return nullptr; + + const bool deleted = toDeleteSet.contains(root->val); + if (isRoot && !deleted) + ans.push_back(root); + + // If root is deleted, both children have the possibility to be a new root + root->left = dfs(root->left, move(toDeleteSet), deleted, ans); + root->right = dfs(root->right, move(toDeleteSet), deleted, ans); + return deleted ? nullptr : root; + } +}; diff --git a/solutions/1110. Delete Nodes And Return Forest/1110.java b/solutions/1110. Delete Nodes And Return Forest/1110.java new file mode 100644 index 00000000000..1e1858ab20c --- /dev/null +++ b/solutions/1110. Delete Nodes And Return Forest/1110.java @@ -0,0 +1,23 @@ +class Solution { + public List delNodes(TreeNode root, int[] to_delete) { + List ans = new ArrayList<>(); + Set toDeleteSet = Arrays.stream(to_delete).boxed().collect(Collectors.toSet()); + dfs(root, toDeleteSet, true, ans); + return ans; + } + + private TreeNode dfs(TreeNode root, Set toDeleteSet, boolean isRoot, + List ans) { + if (root == null) + return null; + + final boolean deleted = toDeleteSet.contains(root.val); + if (isRoot && !deleted) + ans.add(root); + + // If root is deleted, both children have the possibility to be a new root + root.left = dfs(root.left, toDeleteSet, deleted, ans); + root.right = dfs(root.right, toDeleteSet, deleted, ans); + return deleted ? null : root; + } +} diff --git a/solutions/1110. Delete Nodes And Return Forest/1110.py b/solutions/1110. Delete Nodes And Return Forest/1110.py new file mode 100644 index 00000000000..95147ee761c --- /dev/null +++ b/solutions/1110. Delete Nodes And Return Forest/1110.py @@ -0,0 +1,20 @@ +class Solution: + def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]: + ans = [] + toDeleteSet = set(to_delete) + + def dfs(root: TreeNode, isRoot: bool) -> TreeNode: + if not root: + return None + + deleted = root.val in toDeleteSet + if isRoot and not deleted: + ans.append(root) + + # If root is deleted, both children have the possibility to be a new root + root.left = dfs(root.left, deleted) + root.right = dfs(root.right, deleted) + return None if deleted else root + + dfs(root, True) + return ans diff --git a/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.cpp b/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.cpp new file mode 100644 index 00000000000..76e1a7e6a79 --- /dev/null +++ b/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector maxDepthAfterSplit(string seq) { + vector ans; + int depth = 1; + + // Put all odd-depth parentheses in one group and even-depth parentheses in + // the other group. + for (const char c : seq) + if (c == '(') + ans.push_back(++depth % 2); + else + ans.push_back(depth-- % 2); + + return ans; + } +}; diff --git a/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.java b/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.java new file mode 100644 index 00000000000..632a7147f1f --- /dev/null +++ b/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.java @@ -0,0 +1,16 @@ +class Solution { + public int[] maxDepthAfterSplit(String seq) { + int[] ans = new int[seq.length()]; + int depth = 1; + + // Put all odd-depth parentheses in one group and even-depth parentheses in + // the other group. + for (int i = 0; i < seq.length(); ++i) + if (seq.charAt(i) == '(') + ans[i] = ++depth % 2; + else + ans[i] = depth-- % 2; + + return ans; + } +} diff --git a/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.py b/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.py new file mode 100644 index 00000000000..aa360f7b598 --- /dev/null +++ b/solutions/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111.py @@ -0,0 +1,15 @@ +class Solution: + def maxDepthAfterSplit(self, seq: str) -> List[int]: + ans = [] + depth = 1 + + # Put all odd-depth parentheses in one group and even-depth parentheses in the other group. + for c in seq: + if c == '(': + depth += 1 + ans.append(depth % 2) + else: + ans.append(depth % 2) + depth -= 1 + + return ans diff --git a/solutions/1112. Highest Grade For Each Student/1112.sql b/solutions/1112. Highest Grade For Each Student/1112.sql new file mode 100644 index 00000000000..7602df2de73 --- /dev/null +++ b/solutions/1112. Highest Grade For Each Student/1112.sql @@ -0,0 +1,18 @@ +WITH + RankedEnrollments AS ( + SELECT + student_id, + course_id, + grade, + RANK() OVER( + PARTITION BY student_id + ORDER BY grade DESC, course_id + ) AS `rank` + FROM Enrollments + ) +SELECT + student_id, + course_id, + grade +FROM RankedEnrollments +WHERE `rank` = 1; diff --git a/solutions/1113. Reported Posts/1113.sql b/solutions/1113. Reported Posts/1113.sql new file mode 100644 index 00000000000..719b99b66a0 --- /dev/null +++ b/solutions/1113. Reported Posts/1113.sql @@ -0,0 +1,8 @@ +SELECT + extra AS report_reason, + COUNT(DISTINCT post_id) AS report_count +FROM Actions +WHERE + ACTION = 'report' + AND DATEDIFF('2019-07-05', action_date) = 1 +GROUP BY 1; diff --git a/solutions/1114. Print in Order/1114.cpp b/solutions/1114. Print in Order/1114.cpp new file mode 100644 index 00000000000..366d3da4882 --- /dev/null +++ b/solutions/1114. Print in Order/1114.cpp @@ -0,0 +1,27 @@ +class Foo { + public: + Foo() { + firstDone.lock(); + secondDone.lock(); + } + + void first(function printFirst) { + printFirst(); + firstDone.unlock(); + } + + void second(function printSecond) { + firstDone.lock(); + printSecond(); + secondDone.unlock(); + } + + void third(function printThird) { + secondDone.lock(); + printThird(); + } + + private: + mutex firstDone; + mutex secondDone; +}; diff --git a/solutions/1114. Print in Order/1114.java b/solutions/1114. Print in Order/1114.java new file mode 100644 index 00000000000..dc860e5283d --- /dev/null +++ b/solutions/1114. Print in Order/1114.java @@ -0,0 +1,22 @@ +class Foo { + public void first(Runnable printFirst) throws InterruptedException { + printFirst.run(); + firstDone.incrementAndGet(); + } + + public void second(Runnable printSecond) throws InterruptedException { + while (firstDone.get() != 1) + ; + printSecond.run(); + secondDone.incrementAndGet(); + } + + public void third(Runnable printThird) throws InterruptedException { + while (secondDone.get() != 1) + ; + printThird.run(); + } + + private AtomicInteger firstDone = new AtomicInteger(); + private AtomicInteger secondDone = new AtomicInteger(); +} diff --git a/solutions/1114. Print in Order/1114.py b/solutions/1114. Print in Order/1114.py new file mode 100644 index 00000000000..2e86b004eed --- /dev/null +++ b/solutions/1114. Print in Order/1114.py @@ -0,0 +1,22 @@ +from threading import Lock + + +class Foo: + def __init__(self): + self.firstDone = Lock() + self.secondDone = Lock() + self.firstDone.acquire() + self.secondDone.acquire() + + def first(self, printFirst: 'Callable[[], None]') -> None: + printFirst() + self.firstDone.release() + + def second(self, printSecond: 'Callable[[], None]') -> None: + self.firstDone.acquire() + printSecond() + self.secondDone.release() + + def third(self, printThird: 'Callable[[], None]') -> None: + self.secondDone.acquire() + printThird() diff --git a/solutions/1115. Print FooBar Alternately/1115.cpp b/solutions/1115. Print FooBar Alternately/1115.cpp new file mode 100644 index 00000000000..b6c83e072f7 --- /dev/null +++ b/solutions/1115. Print FooBar Alternately/1115.cpp @@ -0,0 +1,37 @@ +// LeetCode doesn't support C++20 yet, so we don't have std::counting_semaphore +// or binary_semaphore. +#include + +class FooBar { + public: + FooBar(int n) : n(n) { + sem_init(&fooSemaphore, /*pshared=*/0, /*value=*/1); + sem_init(&barSemaphore, /*pshared=*/0, /*value=*/0); + } + + ~FooBar() { + sem_destroy(&fooSemaphore); + sem_destroy(&barSemaphore); + } + + void foo(function printFoo) { + for (int i = 0; i < n; ++i) { + sem_wait(&fooSemaphore); + printFoo(); + sem_post(&barSemaphore); + } + } + + void bar(function printBar) { + for (int i = 0; i < n; ++i) { + sem_wait(&barSemaphore); + printBar(); + sem_post(&fooSemaphore); + } + } + + private: + const int n; + sem_t fooSemaphore; + sem_t barSemaphore; +}; diff --git a/solutions/1115. Print FooBar Alternately/1115.java b/solutions/1115. Print FooBar Alternately/1115.java new file mode 100644 index 00000000000..397e5c3705f --- /dev/null +++ b/solutions/1115. Print FooBar Alternately/1115.java @@ -0,0 +1,25 @@ +class FooBar { + public FooBar(int n) { + this.n = n; + } + + public void foo(Runnable printFoo) throws InterruptedException { + for (int i = 0; i < n; ++i) { + fooSemaphore.acquire(); + printFoo.run(); + barSemaphore.release(); + } + } + + public void bar(Runnable printBar) throws InterruptedException { + for (int i = 0; i < n; ++i) { + barSemaphore.acquire(); + printBar.run(); + fooSemaphore.release(); + } + } + + private int n; + private Semaphore fooSemaphore = new Semaphore(1); + private Semaphore barSemaphore = new Semaphore(0); +} diff --git a/solutions/1115. Print FooBar Alternately/1115.py b/solutions/1115. Print FooBar Alternately/1115.py new file mode 100644 index 00000000000..fe1c45143cb --- /dev/null +++ b/solutions/1115. Print FooBar Alternately/1115.py @@ -0,0 +1,20 @@ +from threading import Semaphore + + +class FooBar: + def __init__(self, n): + self.n = n + self.fooSemaphore = Semaphore(1) + self.barSemaphore = Semaphore(0) + + def foo(self, printFoo: 'Callable[[], None]') -> None: + for _ in range(self.n): + self.fooSemaphore.acquire() + printFoo() + self.barSemaphore.release() + + def bar(self, printBar: 'Callable[[], None]') -> None: + for _ in range(self.n): + self.barSemaphore.acquire() + printBar() + self.fooSemaphore.release() diff --git a/solutions/1116. Print Zero Even Odd/1116.cpp b/solutions/1116. Print Zero Even Odd/1116.cpp new file mode 100644 index 00000000000..dac74d1a395 --- /dev/null +++ b/solutions/1116. Print Zero Even Odd/1116.cpp @@ -0,0 +1,49 @@ +// LeetCode doesn't support C++20 yet, so we don't have std::counting_semaphore +// or binary_semaphore. +#include + +class ZeroEvenOdd { + public: + ZeroEvenOdd(int n) : n(n) { + sem_init(&zeroSemaphore, /*pshared=*/0, /*value=*/1); + sem_init(&evenSemaphore, /*pshared=*/0, /*value=*/0); + sem_init(&oddSemaphore, /*pshared=*/0, /*value=*/0); + } + + ~ZeroEvenOdd() { + sem_destroy(&zeroSemaphore); + sem_destroy(&evenSemaphore); + sem_destroy(&oddSemaphore); + } + + // printNumber(x) outputs "x", where x is an integer. + void zero(function printNumber) { + for (int i = 0; i < n; ++i) { + sem_wait(&zeroSemaphore); + printNumber(0); + sem_post(&(i % 2 == 0 ? oddSemaphore : evenSemaphore)); + } + } + + void even(function printNumber) { + for (int i = 2; i <= n; i += 2) { + sem_wait(&evenSemaphore); + printNumber(i); + sem_post(&zeroSemaphore); + } + } + + void odd(function printNumber) { + for (int i = 1; i <= n; i += 2) { + sem_wait(&oddSemaphore); + printNumber(i); + sem_post(&zeroSemaphore); + } + } + + private: + const int n; + sem_t zeroSemaphore; + sem_t evenSemaphore; + sem_t oddSemaphore; +}; diff --git a/solutions/1116. Print Zero Even Odd/1116.java b/solutions/1116. Print Zero Even Odd/1116.java new file mode 100644 index 00000000000..5de91682b0d --- /dev/null +++ b/solutions/1116. Print Zero Even Odd/1116.java @@ -0,0 +1,35 @@ +class ZeroEvenOdd { + public ZeroEvenOdd(int n) { + this.n = n; + } + + // printNumber.accept(x) outputs "x", where x is an integer. + public void zero(IntConsumer printNumber) throws InterruptedException { + for (int i = 0; i < n; ++i) { + zeroSemaphore.acquire(); + printNumber.accept(0); + (i % 2 == 0 ? oddSemaphore : evenSemaphore).release(); + } + } + + public void even(IntConsumer printNumber) throws InterruptedException { + for (int i = 2; i <= n; i += 2) { + evenSemaphore.acquire(); + printNumber.accept(i); + zeroSemaphore.release(); + } + } + + public void odd(IntConsumer printNumber) throws InterruptedException { + for (int i = 1; i <= n; i += 2) { + oddSemaphore.acquire(); + printNumber.accept(i); + zeroSemaphore.release(); + } + } + + private int n; + private Semaphore zeroSemaphore = new Semaphore(1); + private Semaphore evenSemaphore = new Semaphore(0); + private Semaphore oddSemaphore = new Semaphore(0); +} diff --git a/solutions/1116. Print Zero Even Odd/1116.py b/solutions/1116. Print Zero Even Odd/1116.py new file mode 100644 index 00000000000..8b49dc9b0a2 --- /dev/null +++ b/solutions/1116. Print Zero Even Odd/1116.py @@ -0,0 +1,28 @@ +from threading import Semaphore + + +class ZeroEvenOdd: + def __init__(self, n): + self.n = n + self.zeroSemaphore = Semaphore(1) + self.evenSemaphore = Semaphore(0) + self.oddSemaphore = Semaphore(0) + + # printNumber(x) outputs "x", where x is an integer. + def zero(self, printNumber: 'Callable[[int], None]') -> None: + for i in range(self.n): + self.zeroSemaphore.acquire() + printNumber(0) + (self.oddSemaphore if i & 2 == 0 else self.evenSemaphore).release() + + def even(self, printNumber: 'Callable[[int], None]') -> None: + for i in range(2, self.n + 1, 2): + self.evenSemaphore.acquire() + printNumber(i) + self.zeroSemaphore.release() + + def odd(self, printNumber: 'Callable[[int], None]') -> None: + for i in range(1, self.n + 1, 2): + self.oddSemaphore.acquire() + printNumber(i) + self.zeroSemaphore.release() diff --git a/solutions/1117. Building H2O/1117.cpp b/solutions/1117. Building H2O/1117.cpp new file mode 100644 index 00000000000..08548e25eb3 --- /dev/null +++ b/solutions/1117. Building H2O/1117.cpp @@ -0,0 +1,39 @@ +// LeetCode doesn't support C++20 yet, so we don't have std::counting_semaphore +// or binary_semaphore. +#include + +class H2O { + public: + H2O() { + sem_init(&hSemaphore, /*pshared=*/0, /*value=*/1); + sem_init(&oSemaphore, /*pshared=*/0, /*value=*/0); + } + + ~H2O() { + sem_destroy(&hSemaphore); + sem_destroy(&oSemaphore); + } + + void hydrogen(function releaseHydrogen) { + sem_wait(&hSemaphore); + ++h; + // releaseHydrogen() outputs "H". Do not change or remove this line. + releaseHydrogen(); + if (h % 2 == 0) + sem_post(&oSemaphore); + else + sem_post(&hSemaphore); + } + + void oxygen(function releaseOxygen) { + sem_wait(&oSemaphore); + // releaseOxygen() outputs "O". Do not change or remove this line. + releaseOxygen(); + sem_post(&hSemaphore); + } + + private: + sem_t hSemaphore; + sem_t oSemaphore; + int h = 0; +}; diff --git a/solutions/1118. Number of Days in a Month/1118.cpp b/solutions/1118. Number of Days in a Month/1118.cpp new file mode 100644 index 00000000000..de7cc0b613f --- /dev/null +++ b/solutions/1118. Number of Days in a Month/1118.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int numberOfDays(int year, int month) { + const vector days = {0, 31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; + return month == 2 && isLeapYear(year) ? 29 : days[month]; + } + + private: + bool isLeapYear(int year) { + return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; + }; +}; diff --git a/solutions/1118. Number of Days in a Month/1118.java b/solutions/1118. Number of Days in a Month/1118.java new file mode 100644 index 00000000000..9d6f95f3a6d --- /dev/null +++ b/solutions/1118. Number of Days in a Month/1118.java @@ -0,0 +1,10 @@ +class Solution { + public int numberOfDays(int year, int month) { + final int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + return month == 2 && isLeapYear(year) ? 29 : days[month]; + } + + private boolean isLeapYear(int year) { + return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; + } +} diff --git a/solutions/1118. Number of Days in a Month/1118.py b/solutions/1118. Number of Days in a Month/1118.py new file mode 100644 index 00000000000..5458b4bec24 --- /dev/null +++ b/solutions/1118. Number of Days in a Month/1118.py @@ -0,0 +1,6 @@ +class Solution: + def numberOfDays(self, year: int, month: int) -> int: + days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + def isLeapYear(year: int) -> bool: + return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 + return 29 if month == 2 and isLeapYear(year) else days[month] diff --git a/solutions/1119. Remove Vowels from a String/1119.cpp b/solutions/1119. Remove Vowels from a String/1119.cpp new file mode 100644 index 00000000000..627991881ee --- /dev/null +++ b/solutions/1119. Remove Vowels from a String/1119.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string removeVowels(string s) { + s.erase(remove_if(s.begin(), s.end(), [&](char c) { return isVowel(c); }), + s.end()); + return s; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiou"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/1119. Remove Vowels from a String/1119.java b/solutions/1119. Remove Vowels from a String/1119.java new file mode 100644 index 00000000000..5601f19a24a --- /dev/null +++ b/solutions/1119. Remove Vowels from a String/1119.java @@ -0,0 +1,5 @@ +class Solution { + public String removeVowels(String s) { + return s.replaceAll("[aeiou]", ""); + } +} diff --git a/solutions/1119. Remove Vowels from a String/1119.py b/solutions/1119. Remove Vowels from a String/1119.py new file mode 100644 index 00000000000..c1e0676a225 --- /dev/null +++ b/solutions/1119. Remove Vowels from a String/1119.py @@ -0,0 +1,3 @@ +class Solution: + def removeVowels(self, s: str) -> str: + return re.sub('a|e|i|o|u', '', s) diff --git a/solutions/112. Path Sum/112.cpp b/solutions/112. Path Sum/112.cpp new file mode 100644 index 00000000000..1379b92836f --- /dev/null +++ b/solutions/112. Path Sum/112.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool hasPathSum(TreeNode* root, int sum) { + if (root == nullptr) + return false; + if (root->val == sum && root->left == nullptr && root->right == nullptr) + return true; + return hasPathSum(root->left, sum - root->val) || + hasPathSum(root->right, sum - root->val); + } +}; diff --git a/solutions/112. Path Sum/112.java b/solutions/112. Path Sum/112.java new file mode 100644 index 00000000000..756749f4aae --- /dev/null +++ b/solutions/112. Path Sum/112.java @@ -0,0 +1,11 @@ +class Solution { + public boolean hasPathSum(TreeNode root, int sum) { + if (root == null) + return false; + if (root.val == sum && root.left == null && root.right == null) + return true; + return // + hasPathSum(root.left, sum - root.val) || // + hasPathSum(root.right, sum - root.val); + } +} diff --git a/solutions/112. Path Sum/112.py b/solutions/112. Path Sum/112.py new file mode 100644 index 00000000000..9daea69c67f --- /dev/null +++ b/solutions/112. Path Sum/112.py @@ -0,0 +1,8 @@ +class Solution: + def hasPathSum(self, root: TreeNode, summ: int) -> bool: + if not root: + return False + if root.val == summ and not root.left and not root.right: + return True + return self.hasPathSum(root.left, summ - root.val) or \ + self.hasPathSum(root.right, summ - root.val) diff --git a/solutions/1120. Maximum Average Subtree/1120.cpp b/solutions/1120. Maximum Average Subtree/1120.cpp new file mode 100644 index 00000000000..f589a478d61 --- /dev/null +++ b/solutions/1120. Maximum Average Subtree/1120.cpp @@ -0,0 +1,27 @@ +struct T { + int sum; + int count; + double maxAverage; +}; + +class Solution { + public: + double maximumAverageSubtree(TreeNode* root) { + return maximumAverage(root).maxAverage; + } + + private: + T maximumAverage(TreeNode* root) { + if (root == nullptr) + return {0, 0, 0.0}; + + const T left = maximumAverage(root->left); + const T right = maximumAverage(root->right); + + const int sum = root->val + left.sum + right.sum; + const int count = 1 + left.count + right.count; + const double maxAverage = + max({sum / (double)count, left.maxAverage, right.maxAverage}); + return {sum, count, maxAverage}; + } +}; diff --git a/solutions/1120. Maximum Average Subtree/1120.java b/solutions/1120. Maximum Average Subtree/1120.java new file mode 100644 index 00000000000..ff219891c42 --- /dev/null +++ b/solutions/1120. Maximum Average Subtree/1120.java @@ -0,0 +1,30 @@ +class T { + public int sum; + public int count; + public double maxAverage; + public T(int sum, int count, double maxAverage) { + this.sum = sum; + this.count = count; + this.maxAverage = maxAverage; + } +} + +class Solution { + public double maximumAverageSubtree(TreeNode root) { + return maximumAverage(root).maxAverage; + } + + private T maximumAverage(TreeNode root) { + if (root == null) + return new T(0, 0, 0.0); + + T left = maximumAverage(root.left); + T right = maximumAverage(root.right); + + final int sum = root.val + left.sum + right.sum; + final int count = 1 + left.count + right.count; + final double maxAverage = + Math.max(sum / (double) count, Math.max(left.maxAverage, right.maxAverage)); + return new T(sum, count, maxAverage); + } +} diff --git a/solutions/1120. Maximum Average Subtree/1120.py b/solutions/1120. Maximum Average Subtree/1120.py new file mode 100644 index 00000000000..20739ba768f --- /dev/null +++ b/solutions/1120. Maximum Average Subtree/1120.py @@ -0,0 +1,22 @@ +class T: + def __init__(self, summ: int, count: int, maxAverage: float): + self.summ = summ + self.count = count + self.maxAverage = maxAverage + + +class Solution: + def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float: + def maximumAverage(root: Optional[TreeNode]) -> T: + if not root: + return T(0, 0, 0) + + left = maximumAverage(root.left) + right = maximumAverage(root.right) + + summ = root.val + left.summ + right.summ + count = 1 + left.count + right.count + maxAverage = max(summ / count, left.maxAverage, right.maxAverage) + return T(summ, count, maxAverage) + + return maximumAverage(root).maxAverage diff --git a/solutions/1121. Divide Array Into Increasing Sequences/1121.cpp b/solutions/1121. Divide Array Into Increasing Sequences/1121.cpp new file mode 100644 index 00000000000..c3f322bb86d --- /dev/null +++ b/solutions/1121. Divide Array Into Increasing Sequences/1121.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool canDivideIntoSubsequences(vector& nums, int k) { + // Find the number with the maxFreq, we need at least maxFreq * k elements + // e.g. nums = [1, 2, 2, 3, 4], we have maxFreq = 2 (two 2s), so we have to + // Split nums into two subsequences say k = 3, the minimum length of nums is + // 2 x 3 = 6, which is impossible if nums.size() = 5 + const int n = nums.size(); + int freq = 1; + int maxFreq = 1; + + for (int i = 1; i < n; ++i) { + freq = nums[i - 1] < nums[i] ? 1 : ++freq; + maxFreq = max(maxFreq, freq); + } + + return n >= maxFreq * k; + } +}; diff --git a/solutions/1121. Divide Array Into Increasing Sequences/1121.java b/solutions/1121. Divide Array Into Increasing Sequences/1121.java new file mode 100644 index 00000000000..eb5f2c869be --- /dev/null +++ b/solutions/1121. Divide Array Into Increasing Sequences/1121.java @@ -0,0 +1,18 @@ +class Solution { + public boolean canDivideIntoSubsequences(int[] nums, int k) { + // Find the number with the maxFreq, we need at least maxFreq * k elements + // e.g. nums = [1, 2, 2, 3, 4], we have maxFreq = 2 (two 2s), so we have to + // Split nums into two subsequences say k = 3, the minimum length of nums is 2 x + // 3 = 6, which is impossible if nums.size() = 5 + final int n = nums.length; + int freq = 1; + int maxFreq = 1; + + for (int i = 1; i < n; ++i) { + freq = nums[i - 1] < nums[i] ? 1 : ++freq; + maxFreq = Math.max(maxFreq, freq); + } + + return n >= maxFreq * k; + } +} diff --git a/solutions/1121. Divide Array Into Increasing Sequences/1121.py b/solutions/1121. Divide Array Into Increasing Sequences/1121.py new file mode 100644 index 00000000000..a92d4e86ff1 --- /dev/null +++ b/solutions/1121. Divide Array Into Increasing Sequences/1121.py @@ -0,0 +1,7 @@ +class Solution: + def canDivideIntoSubsequences(self, nums: List[int], k: int) -> bool: + # Find the number with the maxFreq, we need at least maxFreq * k elements + # e.g. nums = [1, 2, 2, 3, 4], we have maxFreq = 2 (two 2s), so we have to + # Split nums into two subsequences say k = 3, the minimum length of nums is 2 x + # 3 = 6, which is impossible if len(nums) = 5 + return len(nums) >= k * max(Counter(nums).values()) diff --git a/solutions/1122. Relative Sort Array/1122.cpp b/solutions/1122. Relative Sort Array/1122.cpp new file mode 100644 index 00000000000..3f6ab88a54e --- /dev/null +++ b/solutions/1122. Relative Sort Array/1122.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector relativeSortArray(vector& arr1, vector& arr2) { + vector ans; + vector count(1001); + + for (int a : arr1) + ++count[a]; + + for (int a : arr2) + while (count[a]-- > 0) + ans.push_back(a); + + for (int num = 0; num < 1001; ++num) + while (count[num]-- > 0) + ans.push_back(num); + + return ans; + } +}; diff --git a/solutions/1122. Relative Sort Array/1122.java b/solutions/1122. Relative Sort Array/1122.java new file mode 100644 index 00000000000..cec9eadccc1 --- /dev/null +++ b/solutions/1122. Relative Sort Array/1122.java @@ -0,0 +1,20 @@ +class Solution { + public int[] relativeSortArray(int[] arr1, int[] arr2) { + int[] ans = new int[arr1.length]; + int[] count = new int[1001]; + int i = 0; + + for (int a : arr1) + ++count[a]; + + for (int a : arr2) + while (count[a]-- > 0) + ans[i++] = a; + + for (int num = 0; num < 1001; ++num) + while (count[num]-- > 0) + ans[i++] = num; + + return ans; + } +} diff --git a/solutions/1122. Relative Sort Array/1122.py b/solutions/1122. Relative Sort Array/1122.py new file mode 100644 index 00000000000..ce356631f98 --- /dev/null +++ b/solutions/1122. Relative Sort Array/1122.py @@ -0,0 +1,18 @@ +class Solution: + def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: + ans = [] + count = [0] * 1001 + + for a in arr1: + count[a] += 1 + + for a in arr2: + while count[a] > 0: + ans.append(a) + count[a] -= 1 + + for num in range(1001): + for _ in range(count[num]): + ans.append(num) + + return ans diff --git a/solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.cpp b/solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.cpp new file mode 100644 index 00000000000..30d3523200c --- /dev/null +++ b/solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.cpp @@ -0,0 +1,24 @@ +struct T { + TreeNode* lca; + int depth; +}; + +class Solution { + public: + TreeNode* lcaDeepestLeaves(TreeNode* root) { + return dfs(root).lca; + } + + private: + T dfs(TreeNode* root) { + if (root == nullptr) + return {nullptr, 0}; + const T left = dfs(root->left); + const T right = dfs(root->right); + if (left.depth > right.depth) + return {left.lca, left.depth + 1}; + if (left.depth < right.depth) + return {right.lca, right.depth + 1}; + return {root, left.depth + 1}; + } +}; diff --git a/solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.java b/solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.java new file mode 100644 index 00000000000..e29ae6d8a57 --- /dev/null +++ b/solutions/1123. Lowest Common Ancestor of Deepest Leaves/1123.java @@ -0,0 +1,26 @@ +class T { + public TreeNode lca; + public int depth; + public T(TreeNode lca, int depth) { + this.lca = lca; + this.depth = depth; + } +}; + +class Solution { + public TreeNode lcaDeepestLeaves(TreeNode root) { + return dfs(root).lca; + } + + private T dfs(TreeNode root) { + if (root == null) + return new T(null, 0); + const T left = dfs(root.left); + const T right = dfs(root.right); + if (left.depth > right.depth) + return new T(left.lca, left.depth + 1); + if (left.depth < right.depth) + return new T(right.lca, right.depth + 1); + return new T(root, left.depth + 1); + } +} diff --git a/solutions/1124. Longest Well-Performing Interval/1124.cpp b/solutions/1124. Longest Well-Performing Interval/1124.cpp new file mode 100644 index 00000000000..1cb9cb7dbbe --- /dev/null +++ b/solutions/1124. Longest Well-Performing Interval/1124.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int longestWPI(vector& hours) { + int ans = 0; + int prefix = 0; + unordered_map map; + + for (int i = 0; i < hours.size(); ++i) { + prefix += hours[i] > 8 ? 1 : -1; + if (prefix > 0) { + ans = i + 1; + } else { + if (!map.contains(prefix)) + map[prefix] = i; + if (const auto it = map.find(prefix - 1); it != map.cend()) + ans = max(ans, i - it->second); + } + } + + return ans; + } +}; diff --git a/solutions/1124. Longest Well-Performing Interval/1124.py b/solutions/1124. Longest Well-Performing Interval/1124.py new file mode 100644 index 00000000000..1693410185e --- /dev/null +++ b/solutions/1124. Longest Well-Performing Interval/1124.py @@ -0,0 +1,17 @@ +class Solution: + def longestWPI(self, hours: List[int]) -> int: + ans = 0 + prefix = 0 + dict = {} + + for i in range(len(hours)): + prefix += 1 if hours[i] > 8 else -1 + if prefix > 0: + ans = i + 1 + else: + if prefix not in dict: + dict[prefix] = i + if prefix - 1 in dict: + ans = max(ans, i - dict[prefix - 1]) + + return ans diff --git a/solutions/1125. Smallest Sufficient Team/1125.cpp b/solutions/1125. Smallest Sufficient Team/1125.cpp new file mode 100644 index 00000000000..0a0edeaf553 --- /dev/null +++ b/solutions/1125. Smallest Sufficient Team/1125.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + vector smallestSufficientTeam(vector& req_skills, + vector>& people) { + const int n = req_skills.size(); + const int nSkills = 1 << n; + unordered_map skillToId; + // dp[i] := the minimum people's indices to cover skillset of mask i + unordered_map> dp; + dp.reserve(nSkills); // Avoid rehash. + dp[0] = {}; + + for (int i = 0; i < n; ++i) + skillToId[req_skills[i]] = i; + + auto getSkill = [&](const vector& person) { + int mask = 0; + for (const string& skill : person) + if (const auto it = skillToId.find(skill); it != skillToId.cend()) + mask |= 1 << it->second; + return mask; + }; + + for (int i = 0; i < people.size(); ++i) { + const int currSkill = getSkill(people[i]); + for (const auto& [mask, indices] : dp) { + const int newSkillSet = mask | currSkill; + if (newSkillSet == mask) // Adding people[i] doesn't increase skill set + continue; + if (!dp.contains(newSkillSet) || + dp[newSkillSet].size() > indices.size() + 1) { + dp[newSkillSet] = indices; + dp[newSkillSet].push_back(i); + } + } + } + + return dp[nSkills - 1]; + } +}; diff --git a/solutions/1125. Smallest Sufficient Team/1125.java b/solutions/1125. Smallest Sufficient Team/1125.java new file mode 100644 index 00000000000..60a7177c864 --- /dev/null +++ b/solutions/1125. Smallest Sufficient Team/1125.java @@ -0,0 +1,38 @@ +class Solution { + public int[] smallestSufficientTeam(String[] req_skills, List> people) { + final int n = req_skills.length; + final int nSkills = 1 << n; + Map skillToId = new HashMap(); + // dp[i] := the minimum people's indices to cover skillset of mask i + List[] dp = new List[nSkills]; + dp[0] = new ArrayList<>(); + + for (int i = 0; i < req_skills.length; ++i) + skillToId.put(req_skills[i], i); + + for (int i = 0; i < people.size(); ++i) { + final int currSkill = getSkill(people.get(i), skillToId); + for (int j = 0; j < nSkills; ++j) { + if (dp[j] == null) + continue; + final int newSkillSet = currSkill | j; + if (newSkillSet == j) // Adding people[i] doesn't increase skill set + continue; + if (dp[newSkillSet] == null || dp[newSkillSet].size() > dp[j].size() + 1) { + dp[newSkillSet] = new ArrayList<>(dp[j]); + dp[newSkillSet].add(i); + } + } + } + + return dp[nSkills - 1].stream().mapToInt(Integer::intValue).toArray(); + } + + private int getSkill(List person, Map skillToId) { + int mask = 0; + for (final String skill : person) + if (skillToId.containsKey(skill)) + mask |= 1 << skillToId.get(skill); + return mask; + } +} diff --git a/solutions/1126. Active Businesses/1126.sql b/solutions/1126. Active Businesses/1126.sql new file mode 100644 index 00000000000..9ebafb0cdde --- /dev/null +++ b/solutions/1126. Active Businesses/1126.sql @@ -0,0 +1,12 @@ +WITH + AvgEvents AS ( + SELECT + business_id, + AVG(occurences) OVER(PARTITION BY event_type) AS event_avg_occurences, + occurences + FROM Events + ) +SELECT business_id +FROM AvgEvents +GROUP BY 1 +HAVING SUM(IF(occurences > event_avg_occurences, 1, 0)) > 1; diff --git a/solutions/1127. User Purchase Platform/1127.sql b/solutions/1127. User Purchase Platform/1127.sql new file mode 100644 index 00000000000..7469e6f577c --- /dev/null +++ b/solutions/1127. User Purchase Platform/1127.sql @@ -0,0 +1,32 @@ +WITH + UserToAmount AS ( + SELECT + user_id, + spend_date, + CASE + WHEN COUNT(DISTINCT platform) = 2 THEN 'both' + ELSE platform + END AS platform, + SUM(amount) AS amount + FROM Spending + GROUP BY 1, 2 + ), + DateAndPlatforms AS ( + SELECT DISTINCT(spend_date), 'desktop' AS platform + FROM Spending + UNION ALL + SELECT DISTINCT(spend_date), 'mobile' AS platform + FROM Spending + UNION ALL + SELECT DISTINCT(spend_date), 'both' AS platform + FROM Spending + ) +SELECT + DateAndPlatforms.spend_date, + DateAndPlatforms.platform, + IFNULL(SUM(UserToAmount.amount), 0) AS total_amount, + COUNT(DISTINCT UserToAmount.user_id) AS total_users +FROM DateAndPlatforms +LEFT JOIN UserToAmount + USING (spend_date, platform) +GROUP BY 1, 2; diff --git a/solutions/1128. Number of Equivalent Domino Pairs/1128.cpp b/solutions/1128. Number of Equivalent Domino Pairs/1128.cpp new file mode 100644 index 00000000000..104820182f3 --- /dev/null +++ b/solutions/1128. Number of Equivalent Domino Pairs/1128.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int numEquivDominoPairs(vector>& dominoes) { + int ans = 0; + unordered_map count; + + for (vector& domino : dominoes) { + int key = min(domino[0], domino[1]) * 10 + max(domino[0], domino[1]); + ans += count[key]; + ++count[key]; + } + + return ans; + } +}; diff --git a/solutions/1128. Number of Equivalent Domino Pairs/1128.java b/solutions/1128. Number of Equivalent Domino Pairs/1128.java new file mode 100644 index 00000000000..899ff8e2ad8 --- /dev/null +++ b/solutions/1128. Number of Equivalent Domino Pairs/1128.java @@ -0,0 +1,14 @@ +class Solution { + public int numEquivDominoPairs(int[][] dominoes) { + int ans = 0; + Map count = new HashMap<>(); + + for (int[] domino : dominoes) { + int key = Math.min(domino[0], domino[1]) * 10 + Math.max(domino[0], domino[1]); + ans += count.getOrDefault(key, 0); + count.merge(key, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/1128. Number of Equivalent Domino Pairs/1128.py b/solutions/1128. Number of Equivalent Domino Pairs/1128.py new file mode 100644 index 00000000000..475a7346e89 --- /dev/null +++ b/solutions/1128. Number of Equivalent Domino Pairs/1128.py @@ -0,0 +1,11 @@ +class Solution: + def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: + ans = 0 + count = collections.Counter() + + for domino in dominoes: + key = min(domino[0], domino[1]) * 10 + max(domino[0], domino[1]) + ans += count[key] + count[key] += 1 + + return ans diff --git a/solutions/1129. Shortest Path with Alternating Colors/1129.cpp b/solutions/1129. Shortest Path with Alternating Colors/1129.cpp new file mode 100644 index 00000000000..4e2c860093a --- /dev/null +++ b/solutions/1129. Shortest Path with Alternating Colors/1129.cpp @@ -0,0 +1,38 @@ +enum class Color { kInit, kRed, kBlue }; + +class Solution { + public: + vector shortestAlternatingPaths(int n, vector>& redEdges, + vector>& blueEdges) { + vector ans(n, -1); + vector>> graph(n); // graph[u] := [(v, edgeColor)] + queue> q{{{0, Color::kInit}}}; // [(u, prevColor)] + + for (const vector& edge : redEdges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].emplace_back(v, Color::kRed); + } + + for (const vector& edge : blueEdges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].emplace_back(v, Color::kBlue); + } + + for (int step = 0; !q.empty(); ++step) + for (int sz = q.size(); sz > 0; --sz) { + const auto [u, prevColor] = q.front(); + q.pop(); + ans[u] = ans[u] == -1 ? step : ans[u]; + for (auto& [v, edgeColor] : graph[u]) { + if (v == -1 || edgeColor == prevColor) + continue; + q.emplace(v, edgeColor); + v = -1; // Mark (u, v) as used. + } + } + + return ans; + } +}; diff --git a/solutions/1129. Shortest Path with Alternating Colors/1129.java b/solutions/1129. Shortest Path with Alternating Colors/1129.java new file mode 100644 index 00000000000..0ecb56fe187 --- /dev/null +++ b/solutions/1129. Shortest Path with Alternating Colors/1129.java @@ -0,0 +1,46 @@ +enum Color { kInit, kRed, kBlue } + +class Solution { + public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { + int[] ans = new int[n]; + Arrays.fill(ans, -1); + // graph[u] := [(v, edgeColor)] + List>[] graph = new List[n]; + // [(u, prevColor)] + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(0, Color.kInit))); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : redEdges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(new Pair<>(v, Color.kRed)); + } + + for (int[] edge : blueEdges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(new Pair<>(v, Color.kBlue)); + } + + for (int step = 0; !q.isEmpty(); ++step) + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.peek().getKey(); + Color prevColor = q.poll().getValue(); + ans[u] = ans[u] == -1 ? step : ans[u]; + for (int i = 0; i < graph[u].size(); ++i) { + Pair node = graph[u].get(i); + final int v = node.getKey(); + Color edgeColor = node.getValue(); + if (v == -1 || edgeColor == prevColor) + continue; + q.add(new Pair<>(v, edgeColor)); + // Mark (u, v) as used. + graph[u].set(i, new Pair<>(-1, edgeColor)); + } + } + + return ans; + } +} diff --git a/solutions/1129. Shortest Path with Alternating Colors/1129.py b/solutions/1129. Shortest Path with Alternating Colors/1129.py new file mode 100644 index 00000000000..b2ddf64f644 --- /dev/null +++ b/solutions/1129. Shortest Path with Alternating Colors/1129.py @@ -0,0 +1,35 @@ +from enum import Enum + + +class Color(Enum): + kInit = 0 + kRed = 1 + kBlue = 2 + + +class Solution: + def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]: + ans = [-1] * n + graph = [[] for _ in range(n)] # graph[u] := [(v, edgeColor)] + q = collections.deque([(0, Color.kInit)]) # [(u, prevColor)] + + for u, v in redEdges: + graph[u].append((v, Color.kRed)) + + for u, v in blueEdges: + graph[u].append((v, Color.kBlue)) + + step = 0 + while q: + for _ in range(len(q)): + u, prevColor = q.popleft() + if ans[u] == -1: + ans[u] = step + for i, (v, edgeColor) in enumerate(graph[u]): + if v == -1 or edgeColor == prevColor: + continue + q.append((v, edgeColor)) + graph[u][i] = (-1, edgeColor) # Mark (u, v) as used. + step += 1 + + return ans diff --git a/solutions/113. Path Sum II/113.cpp b/solutions/113. Path Sum II/113.cpp new file mode 100644 index 00000000000..60ca8ad9ff9 --- /dev/null +++ b/solutions/113. Path Sum II/113.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> pathSum(TreeNode* root, int sum) { + vector> ans; + dfs(root, sum, {}, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int sum, vector&& path, + vector>& ans) { + if (root == nullptr) + return; + if (root->val == sum && root->left == nullptr && root->right == nullptr) { + path.push_back(root->val); + ans.push_back(path); + path.pop_back(); + return; + } + + path.push_back(root->val); + dfs(root->left, sum - root->val, move(path), ans); + dfs(root->right, sum - root->val, move(path), ans); + path.pop_back(); + } +}; diff --git a/solutions/113. Path Sum II/113.java b/solutions/113. Path Sum II/113.java new file mode 100644 index 00000000000..62cc7e163f1 --- /dev/null +++ b/solutions/113. Path Sum II/113.java @@ -0,0 +1,23 @@ +class Solution { + public List> pathSum(TreeNode root, int sum) { + List> ans = new ArrayList<>(); + dfs(root, sum, new ArrayList<>(), ans); + return ans; + } + + private void dfs(TreeNode root, int sum, List path, List> ans) { + if (root == null) + return; + if (root.val == sum && root.left == null && root.right == null) { + path.add(root.val); + ans.add(new ArrayList<>(path)); + path.remove(path.size() - 1); + return; + } + + path.add(root.val); + dfs(root.left, sum - root.val, path, ans); + dfs(root.right, sum - root.val, path, ans); + path.remove(path.size() - 1); + } +} diff --git a/solutions/113. Path Sum II/113.py b/solutions/113. Path Sum II/113.py new file mode 100644 index 00000000000..1040842ef5b --- /dev/null +++ b/solutions/113. Path Sum II/113.py @@ -0,0 +1,16 @@ +class Solution: + def pathSum(self, root: TreeNode, summ: int) -> List[List[int]]: + ans = [] + + def dfs(root: TreeNode, summ: int, path: List[int]) -> None: + if not root: + return + if root.val == summ and not root.left and not root.right: + ans.append(path + [root.val]) + return + + dfs(root.left, summ - root.val, path + [root.val]) + dfs(root.right, summ - root.val, path + [root.val]) + + dfs(root, summ, []) + return ans diff --git a/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.cpp b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.cpp new file mode 100644 index 00000000000..1326ae62114 --- /dev/null +++ b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int mctFromLeafValues(vector& arr) { + int ans = 0; + vector stack{INT_MAX}; + + for (const int a : arr) { + while (stack.back() <= a) { + const int mid = stack.back(); + stack.pop_back(); + // Multiply mid with next greater element in the array, + // On the left (stack[-1]) or on the right (current number a) + ans += min(stack.back(), a) * mid; + } + stack.push_back(a); + } + + for (int i = 2; i < stack.size(); ++i) + ans += stack[i] * stack[i - 1]; + + return ans; + } +}; diff --git a/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.java b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.java new file mode 100644 index 00000000000..67ddcf61203 --- /dev/null +++ b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.java @@ -0,0 +1,22 @@ +class Solution { + public int mctFromLeafValues(int[] arr) { + int ans = 0; + Deque stack = new ArrayDeque<>(); + stack.push(Integer.MAX_VALUE); + + for (final int a : arr) { + while (stack.peek() <= a) { + final int mid = stack.pop(); + // Multiply mid with next greater element in the array, + // On the left (stack[-1]) or on the right (current number a) + ans += Math.min(stack.peek(), a) * mid; + } + stack.push(a); + } + + while (stack.size() > 2) + ans += stack.pop() * stack.peek(); + + return ans; + } +} diff --git a/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.py b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.py new file mode 100644 index 00000000000..f6762c6008f --- /dev/null +++ b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-2.py @@ -0,0 +1,14 @@ +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + ans = 0 + stack = [math.inf] + + for a in arr: + while stack and stack[-1] <= a: + mid = stack.pop() + # Multiply mid with next greater element in the array, + # On the left (stack[-1]) or on the right (current number a) + ans += min(stack[-1], a) * mid + stack.append(a) + + return ans + sum(a * b for a, b in zip(stack[1:], stack[2:])) diff --git a/solutions/1130. Minimum Cost Tree From Leaf Values/1130-3.py b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-3.py new file mode 100644 index 00000000000..65e569558e9 --- /dev/null +++ b/solutions/1130. Minimum Cost Tree From Leaf Values/1130-3.py @@ -0,0 +1,9 @@ +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + ans = 0 + + while len(arr) > 1: + i = arr.index(min(arr)) + ans += min(arr[i - 1:i] + arr[i + 1:i + 2]) * arr.pop(i) + + return ans diff --git a/solutions/1130. Minimum Cost Tree From Leaf Values/1130.cpp b/solutions/1130. Minimum Cost Tree From Leaf Values/1130.cpp new file mode 100644 index 00000000000..fcfe2338697 --- /dev/null +++ b/solutions/1130. Minimum Cost Tree From Leaf Values/1130.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int mctFromLeafValues(vector& arr) { + const int n = arr.size(); + // dp[i][j] := the minimum cost of arr[i..j] + vector> dp(n, vector(n)); + // maxVal[i][j] := the maximum value of arr[i..j] + vector> maxVal(n, vector(n)); + + for (int i = 0; i < n; ++i) + maxVal[i][i] = arr[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + maxVal[i][j] = max(maxVal[i][j - 1], maxVal[i + 1][j]); + } + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + dp[i][j] = INT_MAX; + for (int k = i; k < j; ++k) + dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + + maxVal[i][k] * maxVal[k + 1][j]); + } + + return dp[0].back(); + } +}; diff --git a/solutions/1130. Minimum Cost Tree From Leaf Values/1130.java b/solutions/1130. Minimum Cost Tree From Leaf Values/1130.java new file mode 100644 index 00000000000..1ae5cbcf11b --- /dev/null +++ b/solutions/1130. Minimum Cost Tree From Leaf Values/1130.java @@ -0,0 +1,28 @@ +class Solution { + public int mctFromLeafValues(int[] arr) { + final int n = arr.length; + // dp[i][j] := the minimum cost of arr[i..j] + int[][] dp = new int[n][n]; + // maxVal[i][j] := the maximum value of arr[i..j] + int[][] maxVal = new int[n][n]; + + for (int i = 0; i < n; ++i) + maxVal[i][i] = arr[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + maxVal[i][j] = Math.max(maxVal[i][j - 1], maxVal[i + 1][j]); + } + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + dp[i][j] = Integer.MAX_VALUE; + for (int k = i; k < j; ++k) + dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + maxVal[i][k] * maxVal[k + 1][j]); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/1130. Minimum Cost Tree From Leaf Values/1130.py b/solutions/1130. Minimum Cost Tree From Leaf Values/1130.py new file mode 100644 index 00000000000..56fd7cde2cb --- /dev/null +++ b/solutions/1130. Minimum Cost Tree From Leaf Values/1130.py @@ -0,0 +1,25 @@ +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + n = len(arr) + # dp[i][j] := the minimum cost of arr[i..j] + dp = [[0] * n for _ in range(n)] + # maxVal[i][j] := the maximum value of arr[i..j] + maxVal = [[0] * n for _ in range(n)] + + for i in range(n): + maxVal[i][i] = arr[i] + + for d in range(1, n): + for i in range(n - d): + j = i + d + maxVal[i][j] = max(maxVal[i][j - 1], maxVal[i + 1][j]) + + for d in range(1, n): + for i in range(n - d): + j = i + d + dp[i][j] = math.inf + for k in range(i, j): + dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + + maxVal[i][k] * maxVal[k + 1][j]) + + return dp[0][-1] diff --git a/solutions/1131. Maximum of Absolute Value Expression/1131.cpp b/solutions/1131. Maximum of Absolute Value Expression/1131.cpp new file mode 100644 index 00000000000..633baeed495 --- /dev/null +++ b/solutions/1131. Maximum of Absolute Value Expression/1131.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int maxAbsValExpr(vector& arr1, vector& arr2) { + const int n = arr1.size(); + vector a(n); + vector b(n); + vector c(n); + vector d(n); + + for (int i = 0; i < n; ++i) { + a[i] = arr1[i] + arr2[i] + i; + b[i] = arr1[i] + arr2[i] - i; + c[i] = arr1[i] - arr2[i] + i; + d[i] = arr1[i] - arr2[i] - i; + } + + return max(max(diff(a), diff(b)), max(diff(c), diff(d))); + } + + private: + int diff(vector& nums) { + return ranges::max(nums) - ranges::min(nums); + } +}; diff --git a/solutions/1131. Maximum of Absolute Value Expression/1131.java b/solutions/1131. Maximum of Absolute Value Expression/1131.java new file mode 100644 index 00000000000..d252dfd479a --- /dev/null +++ b/solutions/1131. Maximum of Absolute Value Expression/1131.java @@ -0,0 +1,24 @@ +class Solution { + public int maxAbsValExpr(int[] arr1, int[] arr2) { + final int n = arr1.length; + int[] a = new int[n]; + int[] b = new int[n]; + int[] c = new int[n]; + int[] d = new int[n]; + + for (int i = 0; i < n; ++i) { + a[i] = arr1[i] + arr2[i] + i; + b[i] = arr1[i] + arr2[i] - i; + c[i] = arr1[i] - arr2[i] + i; + d[i] = arr1[i] - arr2[i] - i; + } + + return Math.max(Math.max(diff(a), diff(b)), Math.max(diff(c), diff(d))); + } + + private int diff(int[] nums) { + final int mn = Arrays.stream(nums).min().getAsInt(); + final int mx = Arrays.stream(nums).max().getAsInt(); + return mx - mn; + } +} diff --git a/solutions/1131. Maximum of Absolute Value Expression/1131.py b/solutions/1131. Maximum of Absolute Value Expression/1131.py new file mode 100644 index 00000000000..ebab5c48ab6 --- /dev/null +++ b/solutions/1131. Maximum of Absolute Value Expression/1131.py @@ -0,0 +1,8 @@ +class Solution: + def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: + n = len(arr1) + a = [arr1[i] + arr2[i] + i for i in range(n)] + b = [arr1[i] + arr2[i] - i for i in range(n)] + c = [arr1[i] - arr2[i] + i for i in range(n)] + d = [arr1[i] - arr2[i] - i for i in range(n)] + return max(map(lambda x: max(x) - min(x), (a, b, c, d))) diff --git a/solutions/1132. Reported Posts II/1132.sql b/solutions/1132. Reported Posts II/1132.sql new file mode 100644 index 00000000000..553f2b2ff2d --- /dev/null +++ b/solutions/1132. Reported Posts II/1132.sql @@ -0,0 +1,13 @@ +WITH + DailyPercents AS ( + SELECT ( + COUNT(DISTINCT Removals.post_id) / COUNT(DISTINCT Actions.post_id) + ) * 100 AS percent + FROM Actions + LEFT JOIN Removals + USING (post_id) + WHERE Actions.extra = 'spam' + GROUP BY Actions.action_date + ) +SELECT ROUND(AVG(percent), 2) AS average_daily_percent +FROM DailyPercents; diff --git a/solutions/1133. Largest Unique Number/1133.cpp b/solutions/1133. Largest Unique Number/1133.cpp new file mode 100644 index 00000000000..705e4a689c2 --- /dev/null +++ b/solutions/1133. Largest Unique Number/1133.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int largestUniqueNumber(vector& nums) { + constexpr int kMax = 1000; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int num = kMax; num >= 0; --num) + if (count[num] == 1) + return num; + + return -1; + } +}; diff --git a/solutions/1133. Largest Unique Number/1133.java b/solutions/1133. Largest Unique Number/1133.java new file mode 100644 index 00000000000..0e2149ac5c9 --- /dev/null +++ b/solutions/1133. Largest Unique Number/1133.java @@ -0,0 +1,15 @@ +class Solution { + public int largestUniqueNumber(int[] nums) { + final int kMax = 1000; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int num = kMax; num >= 0; --num) + if (count[num] == 1) + return num; + + return -1; + } +} diff --git a/solutions/1133. Largest Unique Number/1133.py b/solutions/1133. Largest Unique Number/1133.py new file mode 100644 index 00000000000..0203c6e007a --- /dev/null +++ b/solutions/1133. Largest Unique Number/1133.py @@ -0,0 +1,4 @@ +class Solution: + def largestUniqueNumber(self, nums: List[int]) -> int: + return max([num for num, freq in collections.Counter(nums).items() + if freq == 1], default=-1) diff --git a/solutions/1134. Armstrong Number/1134.cpp b/solutions/1134. Armstrong Number/1134.cpp new file mode 100644 index 00000000000..82fe1c6c820 --- /dev/null +++ b/solutions/1134. Armstrong Number/1134.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + bool isArmstrong(int n) { + const string s = to_string(n); + const int k = s.length(); + for (const char c : s) + n -= pow(c - '0', k); + return n == 0; + } +}; diff --git a/solutions/1134. Armstrong Number/1134.java b/solutions/1134. Armstrong Number/1134.java new file mode 100644 index 00000000000..a1b253c57b4 --- /dev/null +++ b/solutions/1134. Armstrong Number/1134.java @@ -0,0 +1,9 @@ +class Solution { + public boolean isArmstrong(int n) { + final String s = String.valueOf(n); + final int k = s.length(); + for (final char c : s.toCharArray()) + n -= Math.pow(c - '0', k); + return n == 0; + } +} diff --git a/solutions/1134. Armstrong Number/1134.py b/solutions/1134. Armstrong Number/1134.py new file mode 100644 index 00000000000..22c420f8c2e --- /dev/null +++ b/solutions/1134. Armstrong Number/1134.py @@ -0,0 +1,5 @@ +class Solution: + def isArmstrong(self, n: int) -> bool: + s = str(n) + k = len(s) + return sum(pow(int(c), k) for c in s) == n diff --git a/solutions/1135. Connecting Cities With Minimum Cost/1135.cpp b/solutions/1135. Connecting Cities With Minimum Cost/1135.cpp new file mode 100644 index 00000000000..bea058bc012 --- /dev/null +++ b/solutions/1135. Connecting Cities With Minimum Cost/1135.cpp @@ -0,0 +1,59 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + int minimumCost(int n, vector>& connections) { + int ans = 0; + UnionFind uf(n + 1); + + // Sort by cost. + sort( + connections.begin(), connections.end(), + [](const vector& a, const vector& b) { return a[2] < b[2]; }); + + for (const vector& c : connections) { + const int u = c[0]; + const int v = c[1]; + const int cost = c[2]; + if (uf.find(u) == uf.find(v)) + continue; + uf.unionByRank(u, v); + ans += cost; + } + + const int root = uf.find(1); + for (int i = 1; i <= n; ++i) + if (uf.find(i) != root) + return -1; + + return ans; + } +}; diff --git a/solutions/1135. Connecting Cities With Minimum Cost/1135.java b/solutions/1135. Connecting Cities With Minimum Cost/1135.java new file mode 100644 index 00000000000..adadf0a302d --- /dev/null +++ b/solutions/1135. Connecting Cities With Minimum Cost/1135.java @@ -0,0 +1,57 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public int minimumCost(int n, int[][] connections) { + int ans = 0; + UnionFind uf = new UnionFind(n + 1); + + // Sort by cost. + Arrays.sort(connections, (a, b) -> a[2] - b[2]); + + for (int[] c : connections) { + final int u = c[0]; + final int v = c[1]; + final int cost = c[2]; + if (uf.find(u) == uf.find(v)) + continue; + uf.unionByRank(u, v); + ans += cost; + } + + final int root = uf.find(1); + for (int i = 1; i <= n; ++i) + if (uf.find(i) != root) + return -1; + + return ans; + } +} diff --git a/solutions/1135. Connecting Cities With Minimum Cost/1135.py b/solutions/1135. Connecting Cities With Minimum Cost/1135.py new file mode 100644 index 00000000000..3db4eaad18e --- /dev/null +++ b/solutions/1135. Connecting Cities With Minimum Cost/1135.py @@ -0,0 +1,43 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def minimumCost(self, n: int, connections: List[List[int]]) -> int: + ans = 0 + uf = UnionFind(n + 1) + + # Sort by cost. + connections.sort(key=lambda x: x[2]) + + for u, v, cost in connections: + if uf.find(u) == uf.find(v): + continue + uf.unionByRank(u, v) + ans += cost + + root = uf.find(1) + if any(uf.find(i) != root for i in range(1, n + 1)): + return -1 + + return ans diff --git a/solutions/1136. Parallel Courses/1136-2.cpp b/solutions/1136. Parallel Courses/1136-2.cpp new file mode 100644 index 00000000000..e93e5a8cebd --- /dev/null +++ b/solutions/1136. Parallel Courses/1136-2.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int minimumSemesters(int n, vector>& relations) { + int ans = 0; + vector> graph(n); + vector inDegrees(n); + queue q; + + // Build the graph. + for (const vector& relation : relations) { + const int u = relation[0] - 1; + const int v = relation[1] - 1; + graph[u].push_back(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const int u = q.front(); + q.pop(); + --n; + for (const int v : graph[u]) + if (--inDegrees[v] == 0) + q.push(v); + } + ++ans; + } + + return n == 0 ? ans : -1; + } +}; diff --git a/solutions/1136. Parallel Courses/1136-2.java b/solutions/1136. Parallel Courses/1136-2.java new file mode 100644 index 00000000000..c9cb1dd3c7d --- /dev/null +++ b/solutions/1136. Parallel Courses/1136-2.java @@ -0,0 +1,37 @@ +class Solution { + public int minimumSemesters(int n, int[][] relations) { + int ans = 0; + List[] graph = new List[n]; + int[] inDegrees = new int[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph. + for (int[] relation : relations) { + final int u = relation[0] - 1; + final int v = relation[1] - 1; + graph[u].add(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + Queue q = IntStream.range(0, n) + .filter(i -> inDegrees[i] == 0) + .boxed() + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.poll(); + --n; + for (final int v : graph[u]) + if (--inDegrees[v] == 0) + q.offer(v); + } + ++ans; + } + + return n == 0 ? ans : -1; + } +} diff --git a/solutions/1136. Parallel Courses/1136-2.py b/solutions/1136. Parallel Courses/1136-2.py new file mode 100644 index 00000000000..87c68f5d0b1 --- /dev/null +++ b/solutions/1136. Parallel Courses/1136-2.py @@ -0,0 +1,25 @@ +class Solution: + def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: + ans = 0 + graph = [[] for _ in range(n)] + inDegrees = [0] * n + + # Build the graph. + for u, v in relations: + graph[u - 1].append(v - 1) + inDegrees[v - 1] += 1 + + # Perform topological sorting. + q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) + + while q: + for _ in range(len(q)): + u = q.popleft() + n -= 1 + for v in graph[u]: + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + ans += 1 + + return ans if n == 0 else -1 diff --git a/solutions/1136. Parallel Courses/1136.cpp b/solutions/1136. Parallel Courses/1136.cpp new file mode 100644 index 00000000000..a5da7d5ca0c --- /dev/null +++ b/solutions/1136. Parallel Courses/1136.cpp @@ -0,0 +1,41 @@ +enum class State { kInit, kVisiting, kVisited }; + +class Solution { + public: + int minimumSemesters(int n, vector>& relations) { + vector> graph(n); + vector states(n); + vector depth(n, 1); + + for (const vector& relation : relations) { + const int u = relation[0] - 1; + const int v = relation[1] - 1; + graph[u].push_back(v); + } + + for (int i = 0; i < n; ++i) + if (hasCycle(graph, i, states, depth)) + return -1; + + return ranges::max(depth); + } + + private: + bool hasCycle(const vector>& graph, int u, vector& states, + vector& depth) { + if (states[u] == State::kVisiting) + return true; + if (states[u] == State::kVisited) + return false; + + states[u] = State::kVisiting; + for (const int v : graph[u]) { + if (hasCycle(graph, v, states, depth)) + return true; + depth[u] = max(depth[u], 1 + depth[v]); + } + states[u] = State::kVisited; + + return false; + } +}; diff --git a/solutions/1136. Parallel Courses/1136.java b/solutions/1136. Parallel Courses/1136.java new file mode 100644 index 00000000000..9b321e70cfa --- /dev/null +++ b/solutions/1136. Parallel Courses/1136.java @@ -0,0 +1,42 @@ +enum State { kInit, kVisiting, kVisited } + +class Solution { + public int minimumSemesters(int n, int[][] relations) { + List[] graph = new List[n]; + State[] states = new State[n]; + int[] depth = new int[n]; + Arrays.fill(depth, 1); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] relation : relations) { + final int u = relation[0] - 1; + final int v = relation[1] - 1; + graph[u].add(v); + } + + for (int i = 0; i < n; ++i) + if (hasCycle(graph, i, states, depth)) + return -1; + + return Arrays.stream(depth).max().getAsInt(); + } + + private boolean hasCycle(List[] graph, int u, State[] states, int[] depth) { + if (states[u] == State.kVisiting) + return true; + if (states[u] == State.kVisited) + return false; + + states[u] = State.kVisiting; + for (final int v : graph[u]) { + if (hasCycle(graph, v, states, depth)) + return true; + depth[u] = Math.max(depth[u], 1 + depth[v]); + } + states[u] = State.kVisited; + + return false; + } +} diff --git a/solutions/1136. Parallel Courses/1136.py b/solutions/1136. Parallel Courses/1136.py new file mode 100644 index 00000000000..f37e5b5d35f --- /dev/null +++ b/solutions/1136. Parallel Courses/1136.py @@ -0,0 +1,36 @@ +from enum import Enum + + +class State(Enum): + kInit = 0 + kVisiting = 1 + kVisited = 2 + + +class Solution: + def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: + graph = [[] for _ in range(n)] + states = [State.kInit] * n + depth = [1] * n + + for u, v in relations: + graph[u - 1].append(v - 1) + + def hasCycle(u: int) -> bool: + if states[u] == State.kVisiting: + return True + if states[u] == State.kVisited: + return False + + states[u] = State.kVisiting + for v in graph[u]: + if hasCycle(v): + return True + depth[u] = max(depth[u], 1 + depth[v]) + states[u] = State.kVisited + + return False + + if any(hasCycle(i) for i in range(n)): + return -1 + return max(depth) diff --git a/solutions/1137. N-th Tribonacci Number/1137-2.cpp b/solutions/1137. N-th Tribonacci Number/1137-2.cpp new file mode 100644 index 00000000000..609e53e7c5e --- /dev/null +++ b/solutions/1137. N-th Tribonacci Number/1137-2.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int tribonacci(int n) { + vector dp{0, 1, 1}; + + for (int i = 3; i <= n; ++i) + dp[i % 3] = dp[0] + dp[1] + dp[2]; + + return dp[n % 3]; + } +}; diff --git a/solutions/1137. N-th Tribonacci Number/1137-2.java b/solutions/1137. N-th Tribonacci Number/1137-2.java new file mode 100644 index 00000000000..3e13900f79e --- /dev/null +++ b/solutions/1137. N-th Tribonacci Number/1137-2.java @@ -0,0 +1,10 @@ +class Solution { + public int tribonacci(int n) { + int[] dp = {0, 1, 1}; + + for (int i = 3; i <= n; ++i) + dp[i % 3] = dp[0] + dp[1] + dp[2]; + + return dp[n % 3]; + } +} diff --git a/solutions/1137. N-th Tribonacci Number/1137-2.py b/solutions/1137. N-th Tribonacci Number/1137-2.py new file mode 100644 index 00000000000..c5a499d3a18 --- /dev/null +++ b/solutions/1137. N-th Tribonacci Number/1137-2.py @@ -0,0 +1,8 @@ +class Solution: + def tribonacci(self, n: int) -> int: + dp = [0, 1, 1] + + for i in range(3, n + 1): + dp[i % 3] = sum(dp) + + return dp[n % 3] diff --git a/solutions/1137. N-th Tribonacci Number/1137.cpp b/solutions/1137. N-th Tribonacci Number/1137.cpp new file mode 100644 index 00000000000..f82391cfea5 --- /dev/null +++ b/solutions/1137. N-th Tribonacci Number/1137.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int tribonacci(int n) { + if (n < 2) + return n; + + vector dp{0, 1, 1}; + + for (int i = 3; i <= n; ++i) { + const int next = dp[0] + dp[1] + dp[2]; + dp[0] = dp[1]; + dp[1] = dp[2]; + dp[2] = next; + } + + return dp[2]; + } +}; diff --git a/solutions/1137. N-th Tribonacci Number/1137.java b/solutions/1137. N-th Tribonacci Number/1137.java new file mode 100644 index 00000000000..c7821122764 --- /dev/null +++ b/solutions/1137. N-th Tribonacci Number/1137.java @@ -0,0 +1,17 @@ +class Solution { + public int tribonacci(int n) { + if (n < 2) + return n; + + int[] dp = {0, 1, 1}; + + for (int i = 3; i <= n; ++i) { + final int next = dp[0] + dp[1] + dp[2]; + dp[0] = dp[1]; + dp[1] = dp[2]; + dp[2] = next; + } + + return dp[2]; + } +} diff --git a/solutions/1137. N-th Tribonacci Number/1137.py b/solutions/1137. N-th Tribonacci Number/1137.py new file mode 100644 index 00000000000..48511210802 --- /dev/null +++ b/solutions/1137. N-th Tribonacci Number/1137.py @@ -0,0 +1,11 @@ +class Solution: + def tribonacci(self, n: int) -> int: + if n < 2: + return n + + dp = [0, 1, 1] + + for _ in range(3, n + 1): + dp[0], dp[1], dp[2] = dp[1], dp[2], sum(dp) + + return dp[2] diff --git a/solutions/1138. Alphabet Board Path/1138.cpp b/solutions/1138. Alphabet Board Path/1138.cpp new file mode 100644 index 00000000000..361773ca758 --- /dev/null +++ b/solutions/1138. Alphabet Board Path/1138.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string alphabetBoardPath(string target) { + string ans; + int x = 0; + int y = 0; + + for (char c : target) { + int newX = (c - 'a') % 5; + int newY = (c - 'a') / 5; + ans += string(max(0, y - newY), 'U') + string(max(0, newX - x), 'R') + + string(max(0, x - newX), 'L') + string(max(0, newY - y), 'D') + + '!'; + x = newX; + y = newY; + } + + return ans; + } +}; diff --git a/solutions/1139. Largest 1-Bordered Square/1139.cpp b/solutions/1139. Largest 1-Bordered Square/1139.cpp new file mode 100644 index 00000000000..73882dcb1b9 --- /dev/null +++ b/solutions/1139. Largest 1-Bordered Square/1139.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int largest1BorderedSquare(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + + // leftOnes[i][j] := consecutive 1s in the left of grid[i][j] + vector> leftOnes(m, vector(n)); + // topOnes[i][j] := consecutive 1s in the top of grid[i][j] + vector> topOnes(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + leftOnes[i][j] = j == 0 ? 1 : 1 + leftOnes[i][j - 1]; + topOnes[i][j] = i == 0 ? 1 : 1 + topOnes[i - 1][j]; + } + + for (int sz = min(m, n); sz > 0; --sz) + for (int i = 0; i + sz - 1 < m; ++i) + for (int j = 0; j + sz - 1 < n; ++j) { + const int x = i + sz - 1; + const int y = j + sz - 1; + // If grid[i..x][j..y] has all 1s on its border. + if (min(leftOnes[i][y], leftOnes[x][y]) >= sz && + min(topOnes[x][j], topOnes[x][y]) >= sz) + return sz * sz; + } + + return 0; + } +}; diff --git a/solutions/1139. Largest 1-Bordered Square/1139.java b/solutions/1139. Largest 1-Bordered Square/1139.java new file mode 100644 index 00000000000..2c51e9a01c1 --- /dev/null +++ b/solutions/1139. Largest 1-Bordered Square/1139.java @@ -0,0 +1,31 @@ +class Solution { + public int largest1BorderedSquare(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + + // leftOnes[i][j] := consecutive 1s in the left of grid[i][j] + int[][] leftOnes = new int[m][n]; + // topOnes[i][j] := consecutive 1s in the top of grid[i][j] + int[][] topOnes = new int[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + leftOnes[i][j] = j == 0 ? 1 : 1 + leftOnes[i][j - 1]; + topOnes[i][j] = i == 0 ? 1 : 1 + topOnes[i - 1][j]; + } + + for (int sz = Math.min(m, n); sz > 0; --sz) + for (int i = 0; i + sz - 1 < m; ++i) + for (int j = 0; j + sz - 1 < n; ++j) { + final int x = i + sz - 1; + final int y = j + sz - 1; + // If grid[i..x][j..y] has all 1s on its border. + if (Math.min(leftOnes[i][y], leftOnes[x][y]) >= sz && + Math.min(topOnes[x][j], topOnes[x][y]) >= sz) + return sz * sz; + } + + return 0; + } +}; diff --git a/solutions/1139. Largest 1-Bordered Square/1139.py b/solutions/1139. Largest 1-Bordered Square/1139.py new file mode 100644 index 00000000000..ff8afedaaa2 --- /dev/null +++ b/solutions/1139. Largest 1-Bordered Square/1139.py @@ -0,0 +1,26 @@ +class Solution: + def largest1BorderedSquare(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + + # leftOnes[i][j] := consecutive 1s in the left of grid[i][j] + leftOnes = [[0] * n for _ in range(m)] + # topOnes[i][j] := consecutive 1s in the top of grid[i][j] + topOnes = [[0] * n for _ in range(m)] + + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + leftOnes[i][j] = 1 if j == 0 else 1 + leftOnes[i][j - 1] + topOnes[i][j] = 1 if i == 0 else 1 + topOnes[i - 1][j] + + for sz in range(min(m, n), 0, -1): + for i in range(m - sz + 1): + for j in range(n - sz + 1): + x = i + sz - 1 + y = j + sz - 1 + # If grid[i..x][j..y] has all 1s on its border. + if min(leftOnes[i][y], leftOnes[x][y], topOnes[x][j], topOnes[x][y]) >= sz: + return sz * sz + + return 0 diff --git a/solutions/114. Flatten Binary Tree to Linked List/114-2.cpp b/solutions/114. Flatten Binary Tree to Linked List/114-2.cpp new file mode 100644 index 00000000000..e76d849ac07 --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + void flatten(TreeNode* root) { + if (root == nullptr) + return; + + stack stack{{root}}; + + while (!stack.empty()) { + root = stack.top(), stack.pop(); + if (root->right) + stack.push(root->right); + if (root->left) + stack.push(root->left); + if (!stack.empty()) + root->right = stack.top(); + root->left = nullptr; + } + } +}; diff --git a/solutions/114. Flatten Binary Tree to Linked List/114-2.java b/solutions/114. Flatten Binary Tree to Linked List/114-2.java new file mode 100644 index 00000000000..84e74e67ceb --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114-2.java @@ -0,0 +1,20 @@ +class Solution { + public void flatten(TreeNode root) { + if (root == null) + return; + + Deque stack = new ArrayDeque<>(); + stack.push(root); + + while (!stack.isEmpty()) { + root = stack.pop(); + if (root.right != null) + stack.push(root.right); + if (root.left != null) + stack.push(root.left); + if (!stack.isEmpty()) + root.right = stack.peek(); + root.left = null; + } + } +} diff --git a/solutions/114. Flatten Binary Tree to Linked List/114-2.py b/solutions/114. Flatten Binary Tree to Linked List/114-2.py new file mode 100644 index 00000000000..384f9c0ef64 --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114-2.py @@ -0,0 +1,16 @@ +class Solution: + def flatten(self, root: Optional[TreeNode]) -> None: + if not root: + return + + stack = [root] + + while stack: + root = stack.pop() + if root.right: + stack.append(root.right) + if root.left: + stack.append(root.left) + if stack: + root.right = stack[-1] + root.left = None diff --git a/solutions/114. Flatten Binary Tree to Linked List/114-3.cpp b/solutions/114. Flatten Binary Tree to Linked List/114-3.cpp new file mode 100644 index 00000000000..6c3fc1b6ee9 --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114-3.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + void flatten(TreeNode* root) { + if (root == nullptr) + return; + + while (root) { + if (root->left) { + // Find the rightmost root. + TreeNode* rightmost = root->left; + while (rightmost->right) + rightmost = rightmost->right; + // Rewire the connections. + rightmost->right = root->right; + root->right = root->left; + root->left = nullptr; + } + // Move on to the right side of the tree. + root = root->right; + } + } +}; diff --git a/solutions/114. Flatten Binary Tree to Linked List/114-3.java b/solutions/114. Flatten Binary Tree to Linked List/114-3.java new file mode 100644 index 00000000000..2f6a519313b --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114-3.java @@ -0,0 +1,21 @@ +class Solution { + public void flatten(TreeNode root) { + if (root == null) + return; + + while (root != null) { + if (root.left != null) { + // Find the rightmost root. + TreeNode rightmost = root.left; + while (rightmost.right != null) + rightmost = rightmost.right; + // Rewire the connections. + rightmost.right = root.right; + root.right = root.left; + root.left = null; + } + // Move on to the right side of the tree. + root = root.right; + } + } +} diff --git a/solutions/114. Flatten Binary Tree to Linked List/114-3.py b/solutions/114. Flatten Binary Tree to Linked List/114-3.py new file mode 100644 index 00000000000..765817547a9 --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114-3.py @@ -0,0 +1,17 @@ +class Solution: + def flatten(self, root: Optional[TreeNode]) -> None: + if not root: + return + + while root: + if root.left: + # Find the rightmost root + rightmost = root.left + while rightmost.right: + rightmost = rightmost.right + # Rewire the connections + rightmost.right = root.right + root.right = root.left + root.left = None + # Move on to the right side of the tree + root = root.right diff --git a/solutions/114. Flatten Binary Tree to Linked List/114.cpp b/solutions/114. Flatten Binary Tree to Linked List/114.cpp new file mode 100644 index 00000000000..d439c52f50f --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + void flatten(TreeNode* root) { + if (root == nullptr) + return; + + flatten(root->left); + flatten(root->right); + + TreeNode* const left = root->left; // flattened left + TreeNode* const right = root->right; // flattened right + + root->left = nullptr; + root->right = left; + + // Connect the original right subtree to the end of the new right subtree. + TreeNode* rightmost = root; + while (rightmost->right) + rightmost = rightmost->right; + rightmost->right = right; + } +}; diff --git a/solutions/114. Flatten Binary Tree to Linked List/114.java b/solutions/114. Flatten Binary Tree to Linked List/114.java new file mode 100644 index 00000000000..e78e21f8537 --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114.java @@ -0,0 +1,21 @@ +class Solution { + public void flatten(TreeNode root) { + if (root == null) + return; + + flatten(root.left); + flatten(root.right); + + TreeNode left = root.left; // flattened left + TreeNode right = root.right; // flattened right + + root.left = null; + root.right = left; + + // Connect the original right subtree to the end of the new right subtree. + TreeNode rightmost = root; + while (rightmost.right != null) + rightmost = rightmost.right; + rightmost.right = right; + } +} diff --git a/solutions/114. Flatten Binary Tree to Linked List/114.py b/solutions/114. Flatten Binary Tree to Linked List/114.py new file mode 100644 index 00000000000..f2dc9c822b6 --- /dev/null +++ b/solutions/114. Flatten Binary Tree to Linked List/114.py @@ -0,0 +1,19 @@ +class Solution: + def flatten(self, root: Optional[TreeNode]) -> None: + if not root: + return + + self.flatten(root.left) + self.flatten(root.right) + + left = root.left # flattened left + right = root.right # flattened right + + root.left = None + root.right = left + + # Connect the original right subtree to the end of the new right subtree. + rightmost = root + while rightmost.right: + rightmost = rightmost.right + rightmost.right = right diff --git a/solutions/1140. Stone Game II/1140.cpp b/solutions/1140. Stone Game II/1140.cpp new file mode 100644 index 00000000000..4537f66a6f6 --- /dev/null +++ b/solutions/1140. Stone Game II/1140.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int stoneGameII(vector& piles) { + const int n = piles.size(); + vector> mem(n, vector(n)); + vector suffix = piles; // suffix[i] := sum(piles[i..n)) + for (int i = n - 2; i >= 0; --i) + suffix[i] += suffix[i + 1]; + return stoneGameII(suffix, 0, 1, mem); + } + + private: + // Returns the maximum number of stones Alice can get from piles[i..n) with M. + int stoneGameII(const vector& suffix, int i, int M, + vector>& mem) { + if (i + 2 * M >= mem.size()) + return suffix[i]; + if (mem[i][M] > 0) + return mem[i][M]; + + int opponent = suffix[i]; + + for (int X = 1; X <= 2 * M; ++X) + opponent = min(opponent, stoneGameII(suffix, i + X, max(M, X), mem)); + + return mem[i][M] = suffix[i] - opponent; + } +}; diff --git a/solutions/1140. Stone Game II/1140.java b/solutions/1140. Stone Game II/1140.java new file mode 100644 index 00000000000..112422ec5f9 --- /dev/null +++ b/solutions/1140. Stone Game II/1140.java @@ -0,0 +1,27 @@ +class Solution { + public int stoneGameII(int[] piles) { + final int n = piles.length; + int[][] mem = new int[n][n]; + int[] suffix = new int[n]; // suffix[i] := sum(piles[i..n)) + Arrays.stream(mem).forEach(A -> Arrays.fill(A, -1)); + suffix[n - 1] = piles[n - 1]; + for (int i = n - 2; i >= 0; --i) + suffix[i] = suffix[i + 1] + piles[i]; + return stoneGameII(suffix, 0, 1, mem); + } + + // Returns the maximum number of stones Alice can get from piles[i..n) with M. + private int stoneGameII(int[] suffix, int i, int M, int[][] mem) { + if (i + 2 * M >= suffix.length) + return suffix[i]; + if (mem[i][M] != -1) + return mem[i][M]; + + int opponent = suffix[i]; + + for (int X = 1; X <= 2 * M; ++X) + opponent = Math.min(opponent, stoneGameII(suffix, i + X, Math.max(M, X), mem)); + + return mem[i][M] = suffix[i] - opponent; + } +} diff --git a/solutions/1141. User Activity for the Past 30 Days I/1141.sql b/solutions/1141. User Activity for the Past 30 Days I/1141.sql new file mode 100644 index 00000000000..78c1e7bc50a --- /dev/null +++ b/solutions/1141. User Activity for the Past 30 Days I/1141.sql @@ -0,0 +1,6 @@ +SELECT + activity_date AS day, + COUNT(DISTINCT user_id) AS active_users +FROM Activity +WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27' +GROUP BY 1; diff --git a/solutions/1142. User Activity for the Past 30 Days II/1142.sql b/solutions/1142. User Activity for the Past 30 Days II/1142.sql new file mode 100644 index 00000000000..8065dd9750c --- /dev/null +++ b/solutions/1142. User Activity for the Past 30 Days II/1142.sql @@ -0,0 +1,10 @@ +SELECT + IFNULL( + ROUND( + COUNT(DISTINCT session_id) / COUNT(DISTINCT user_id), + 2 + ), + 0.00 + ) AS average_sessions_per_user +FROM Activity +WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27'; diff --git a/solutions/1143. Longest Common Subsequence/1143.cpp b/solutions/1143. Longest Common Subsequence/1143.cpp new file mode 100644 index 00000000000..3964f10ae07 --- /dev/null +++ b/solutions/1143. Longest Common Subsequence/1143.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int longestCommonSubsequence(string text1, string text2) { + const int m = text1.length(); + const int n = text2.length(); + // dp[i][j] := the length of LCS(text1[0..i), text2[0..j)) + vector> dp(m + 1, vector(n + 1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + dp[i + 1][j + 1] = text1[i] == text2[j] + ? 1 + dp[i][j] + : max(dp[i][j + 1], dp[i + 1][j]); + + return dp[m][n]; + } +}; diff --git a/solutions/1143. Longest Common Subsequence/1143.java b/solutions/1143. Longest Common Subsequence/1143.java new file mode 100644 index 00000000000..ac40cd31451 --- /dev/null +++ b/solutions/1143. Longest Common Subsequence/1143.java @@ -0,0 +1,16 @@ +class Solution { + public int longestCommonSubsequence(String text1, String text2) { + final int m = text1.length(); + final int n = text2.length(); + // dp[i][j] := the length of LCS(text1[0..i), text2[0..j)) + int[][] dp = new int[m + 1][n + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + dp[i + 1][j + 1] = text1.charAt(i) == text2.charAt(j) + ? 1 + dp[i][j] + : Math.max(dp[i][j + 1], dp[i + 1][j]); + + return dp[m][n]; + } +} diff --git a/solutions/1143. Longest Common Subsequence/1143.py b/solutions/1143. Longest Common Subsequence/1143.py new file mode 100644 index 00000000000..9892c48f0b7 --- /dev/null +++ b/solutions/1143. Longest Common Subsequence/1143.py @@ -0,0 +1,14 @@ +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + m = len(text1) + n = len(text2) + # dp[i][j] := the length of LCS(text1[0..i), text2[0..j)) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(m): + for j in range(n): + dp[i + 1][j + 1] = \ + 1 + dp[i][j] if text1[i] == text2[j] \ + else max(dp[i][j + 1], dp[i + 1][j]) + + return dp[m][n] diff --git a/solutions/1144. Decrease Elements To Make Array Zigzag/1144.cpp b/solutions/1144. Decrease Elements To Make Array Zigzag/1144.cpp new file mode 100644 index 00000000000..8489b449a7c --- /dev/null +++ b/solutions/1144. Decrease Elements To Make Array Zigzag/1144.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int movesToMakeZigzag(vector& nums) { + vector decreasing(2); + + for (int i = 0; i < nums.size(); ++i) { + int l = i > 0 ? nums[i - 1] : 1001; + int r = i + 1 < nums.size() ? nums[i + 1] : 1001; + decreasing[i % 2] += max(0, nums[i] - min(l, r) + 1); + } + + return min(decreasing[0], decreasing[1]); + } +}; diff --git a/solutions/1144. Decrease Elements To Make Array Zigzag/1144.java b/solutions/1144. Decrease Elements To Make Array Zigzag/1144.java new file mode 100644 index 00000000000..7f02e5a3016 --- /dev/null +++ b/solutions/1144. Decrease Elements To Make Array Zigzag/1144.java @@ -0,0 +1,13 @@ +class Solution { + public int movesToMakeZigzag(int[] nums) { + int[] decreasing = new int[2]; + + for (int i = 0; i < nums.length; ++i) { + int l = i > 0 ? nums[i - 1] : 1001; + int r = i + 1 < nums.length ? nums[i + 1] : 1001; + decreasing[i % 2] += Math.max(0, nums[i] - Math.min(l, r) + 1); + } + + return Math.min(decreasing[0], decreasing[1]); + } +} diff --git a/solutions/1144. Decrease Elements To Make Array Zigzag/1144.py b/solutions/1144. Decrease Elements To Make Array Zigzag/1144.py new file mode 100644 index 00000000000..685b67c1d84 --- /dev/null +++ b/solutions/1144. Decrease Elements To Make Array Zigzag/1144.py @@ -0,0 +1,10 @@ +class Solution: + def movesToMakeZigzag(self, nums: List[int]) -> int: + decreasing = [0] * 2 + + for i, num in enumerate(nums): + l = nums[i - 1] if i > 0 else 1001 + r = nums[i + 1] if i + 1 < len(nums) else 1001 + decreasing[i % 2] += max(0, num - min(l, r) + 1) + + return min(decreasing[0], decreasing[1]) diff --git a/solutions/1145. Binary Tree Coloring Game/1145.cpp b/solutions/1145. Binary Tree Coloring Game/1145.cpp new file mode 100644 index 00000000000..ac280691058 --- /dev/null +++ b/solutions/1145. Binary Tree Coloring Game/1145.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool btreeGameWinningMove(TreeNode* root, int n, int x) { + count(root, x); + return max({leftCount, rightCount, n - leftCount - rightCount - 1}) > n / 2; + } + + private: + int leftCount; // the number of nodes of n's left + int rightCount; // the number of nodes of n's right + + int count(TreeNode* root, int x) { + if (root == nullptr) + return 0; + const int l = count(root->left, x); + const int r = count(root->right, x); + if (root->val == x) { + leftCount = l; + rightCount = r; + } + return 1 + l + r; + } +}; diff --git a/solutions/1145. Binary Tree Coloring Game/1145.java b/solutions/1145. Binary Tree Coloring Game/1145.java new file mode 100644 index 00000000000..a4481537134 --- /dev/null +++ b/solutions/1145. Binary Tree Coloring Game/1145.java @@ -0,0 +1,21 @@ +class Solution { + public boolean btreeGameWinningMove(TreeNode root, int n, int x) { + count(root, x); + return Math.max(Math.max(leftCount, rightCount), n - leftCount - rightCount - 1) > n / 2; + } + + private int leftCount; // the number of nodes of n's left + private int rightCount; // the number of nodes of n's right + + private int count(TreeNode root, int x) { + if (root == null) + return 0; + final int l = count(root.left, x); + final int r = count(root.right, x); + if (root.val == x) { + leftCount = l; + rightCount = r; + } + return 1 + l + r; + } +} diff --git a/solutions/1146. Snapshot Array/1146.cpp b/solutions/1146. Snapshot Array/1146.cpp new file mode 100644 index 00000000000..a0e298d1dda --- /dev/null +++ b/solutions/1146. Snapshot Array/1146.cpp @@ -0,0 +1,30 @@ +class SnapshotArray { + public: + SnapshotArray(int length) : snaps(length) { + for (auto& snap : snaps) + snap.emplace_back(0, 0); + } + + void set(int index, int val) { + auto& [lastSnapId, lastVal] = snaps[index].back(); + if (lastSnapId == snap_id) + lastVal = val; + else + snaps[index].emplace_back(snap_id, val); + } + + int snap() { + return snap_id++; + } + + int get(int index, int snap_id) { + const vector>& snap = snaps[index]; + auto it = ranges::lower_bound(snap, make_pair(snap_id + 1, 0)); + return prev(it)->second; + } + + private: + // snaps[i] := [(snap_id, val)] + vector>> snaps; + int snap_id = 0; +}; diff --git a/solutions/1146. Snapshot Array/1146.java b/solutions/1146. Snapshot Array/1146.java new file mode 100644 index 00000000000..d7370abb40f --- /dev/null +++ b/solutions/1146. Snapshot Array/1146.java @@ -0,0 +1,32 @@ +class SnapshotArray { + public SnapshotArray(int length) { + snaps = new List[length]; + for (int i = 0; i < length; ++i) { + snaps[i] = new ArrayList<>(); + snaps[i].add(new int[] {0, 0}); + } + } + + public void set(int index, int val) { + int[] snap = snaps[index].get(snaps[index].size() - 1); + if (snap[0] == snap_id) + snap[1] = val; + else + snaps[index].add(new int[] {snap_id, val}); + } + + public int snap() { + return snap_id++; + } + + public int get(int index, int snap_id) { + int i = Collections.binarySearch(snaps[index], new int[] {snap_id, 0}, + (a, b) -> Integer.compare(a[0], b[0])); + if (i < 0) + i = -i - 2; + return snaps[index].get(i)[1]; + } + + private List[] snaps; + private int snap_id = 0; +} diff --git a/solutions/1146. Snapshot Array/1146.py b/solutions/1146. Snapshot Array/1146.py new file mode 100644 index 00000000000..68ff3d0b548 --- /dev/null +++ b/solutions/1146. Snapshot Array/1146.py @@ -0,0 +1,19 @@ +class SnapshotArray: + def __init__(self, length: int): + self.snaps = [[[0, 0]] for _ in range(length)] + self.snap_id = 0 + + def set(self, index: int, val: int) -> None: + snap = self.snaps[index][-1] + if snap[0] == self.snap_id: + snap[1] = val + else: + self.snaps[index].append([self.snap_id, val]) + + def snap(self) -> int: + self.snap_id += 1 + return self.snap_id - 1 + + def get(self, index: int, snap_id: int) -> int: + i = bisect_left(self.snaps[index], [snap_id + 1]) - 1 + return self.snaps[index][i][1] diff --git a/solutions/1147. Longest Chunked Palindrome Decomposition/1147.cpp b/solutions/1147. Longest Chunked Palindrome Decomposition/1147.cpp new file mode 100644 index 00000000000..88d77bfe1b6 --- /dev/null +++ b/solutions/1147. Longest Chunked Palindrome Decomposition/1147.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int longestDecomposition(string text) { + int count = 0; + int l = 0; + + for (int r = 1; 2 * r <= text.length(); ++r) + if (equal(text.begin() + l, text.begin() + r, text.end() - r)) { + count += 2; + l = r; + } + + return count + (2 * l < text.length()); + } +}; diff --git a/solutions/1147. Longest Chunked Palindrome Decomposition/1147.java b/solutions/1147. Longest Chunked Palindrome Decomposition/1147.java new file mode 100644 index 00000000000..f942590965c --- /dev/null +++ b/solutions/1147. Longest Chunked Palindrome Decomposition/1147.java @@ -0,0 +1,16 @@ +class Solution { + public int longestDecomposition(String text) { + final int n = text.length(); + + int count = 0; + int l = 0; + + for (int r = 1; 2 * r <= n; ++r) + if (text.substring(n - r).startsWith(text.substring(l, r))) { + count += 2; + l = r; + } + + return count + (2 * l < n ? 1 : 0); + } +} diff --git a/solutions/1148. Article Views I/1148.sql b/solutions/1148. Article Views I/1148.sql new file mode 100644 index 00000000000..66cba172c93 --- /dev/null +++ b/solutions/1148. Article Views I/1148.sql @@ -0,0 +1,4 @@ +SELECT DISTINCT author_id AS id +FROM Views +WHERE author_id = viewer_id +ORDER BY 1; diff --git a/solutions/1149. Article Views II/1149.sql b/solutions/1149. Article Views II/1149.sql new file mode 100644 index 00000000000..81a9caf0f30 --- /dev/null +++ b/solutions/1149. Article Views II/1149.sql @@ -0,0 +1,5 @@ +SELECT DISTINCT viewer_id AS id +FROM Views +GROUP BY viewer_id, view_date +HAVING COUNT(DISTINCT article_id) > 1 +ORDER BY 1; diff --git a/solutions/115. Distinct Subsequences/115-2.cpp b/solutions/115. Distinct Subsequences/115-2.cpp new file mode 100644 index 00000000000..f57cf5658a4 --- /dev/null +++ b/solutions/115. Distinct Subsequences/115-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int numDistinct(string s, string t) { + const int m = s.length(); + const int n = t.length(); + vector dp(n + 1); + dp[0] = 1; + + for (int i = 1; i <= m; ++i) + for (int j = n; j >= 1; --j) + if (s[i - 1] == t[j - 1]) + dp[j] += dp[j - 1]; + + return dp[n]; + } +}; diff --git a/solutions/115. Distinct Subsequences/115-2.java b/solutions/115. Distinct Subsequences/115-2.java new file mode 100644 index 00000000000..1b1720d650c --- /dev/null +++ b/solutions/115. Distinct Subsequences/115-2.java @@ -0,0 +1,15 @@ +class Solution { + public int numDistinct(String s, String t) { + final int m = s.length(); + final int n = t.length(); + long[] dp = new long[n + 1]; + dp[0] = 1; + + for (int i = 1; i <= m; ++i) + for (int j = n; j >= 1; --j) + if (s.charAt(i - 1) == t.charAt(j - 1)) + dp[j] += dp[j - 1]; + + return (int) dp[n]; + } +} diff --git a/solutions/115. Distinct Subsequences/115-2.py b/solutions/115. Distinct Subsequences/115-2.py new file mode 100644 index 00000000000..71eb0d98766 --- /dev/null +++ b/solutions/115. Distinct Subsequences/115-2.py @@ -0,0 +1,12 @@ +class Solution: + def numDistinct(self, s: str, t: str) -> int: + m = len(s) + n = len(t) + dp = [1] + [0] * n + + for i in range(1, m + 1): + for j in range(n, 1 - 1, -1): + if s[i - 1] == t[j - 1]: + dp[j] += dp[j - 1] + + return dp[n] diff --git a/solutions/115. Distinct Subsequences/115.cpp b/solutions/115. Distinct Subsequences/115.cpp new file mode 100644 index 00000000000..c387c74f1d8 --- /dev/null +++ b/solutions/115. Distinct Subsequences/115.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int numDistinct(string s, string t) { + const int m = s.length(); + const int n = t.length(); + vector> dp(m + 1, vector(n + 1)); + + for (int i = 0; i <= m; ++i) + dp[i][0] = 1; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (s[i - 1] == t[j - 1]) + dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; + else + dp[i][j] = dp[i - 1][j]; + + return dp[m][n]; + } +}; diff --git a/solutions/115. Distinct Subsequences/115.java b/solutions/115. Distinct Subsequences/115.java new file mode 100644 index 00000000000..49a7da7015a --- /dev/null +++ b/solutions/115. Distinct Subsequences/115.java @@ -0,0 +1,19 @@ +class Solution { + public int numDistinct(String s, String t) { + final int m = s.length(); + final int n = t.length(); + long[][] dp = new long[m + 1][n + 1]; + + for (int i = 0; i <= m; ++i) + dp[i][0] = 1; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (s.charAt(i - 1) == t.charAt(j - 1)) + dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; + else + dp[i][j] = dp[i - 1][j]; + + return (int) dp[m][n]; + } +} diff --git a/solutions/115. Distinct Subsequences/115.py b/solutions/115. Distinct Subsequences/115.py new file mode 100644 index 00000000000..229d55ab915 --- /dev/null +++ b/solutions/115. Distinct Subsequences/115.py @@ -0,0 +1,17 @@ +class Solution: + def numDistinct(self, s: str, t: str) -> int: + m = len(s) + n = len(t) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(m + 1): + dp[i][0] = 1 + + for i in range(1, m + 1): + for j in range(1, n + 1): + if s[i - 1] == t[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] + else: + dp[i][j] = dp[i - 1][j] + + return dp[m][n] diff --git a/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.cpp b/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.cpp new file mode 100644 index 00000000000..34e2b488864 --- /dev/null +++ b/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + bool isMajorityElement(vector& nums, int target) { + const int n = nums.size(); + const int i = ranges::lower_bound(nums, target) - nums.begin(); + return i + n / 2 < n && nums[i + n / 2] == target; + } +}; diff --git a/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.java b/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.java new file mode 100644 index 00000000000..12322141084 --- /dev/null +++ b/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.java @@ -0,0 +1,20 @@ +class Solution { + public boolean isMajorityElement(int[] nums, int target) { + final int n = nums.length; + final int i = firstGreaterEqual(nums, target); + return i + n / 2 < n && nums[i + n / 2] == target; + } + + private int firstGreaterEqual(int[] A, int target) { + int l = 0; + int r = A.length; + while (l < r) { + final int m = (l + r) / 2; + if (A[m] >= target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.py b/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.py new file mode 100644 index 00000000000..ffd7c97bff9 --- /dev/null +++ b/solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.py @@ -0,0 +1,5 @@ +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + n = len(nums) + i = bisect.bisect_left(nums, target) + return i + n // 2 < n and nums[i + n // 2] == target diff --git a/solutions/1151. Minimum Swaps to Group All 1's Together/1151.cpp b/solutions/1151. Minimum Swaps to Group All 1's Together/1151.cpp new file mode 100644 index 00000000000..a3dd37e6a6c --- /dev/null +++ b/solutions/1151. Minimum Swaps to Group All 1's Together/1151.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minSwaps(vector& data) { + const int k = ranges::count(data, 1); + int ones = 0; // the number of ones in the window + int maxOnes = 0; // the maximum number of ones in the window + + for (int i = 0; i < data.size(); ++i) { + if (i >= k && data[i - k]) + --ones; + if (data[i]) + ++ones; + maxOnes = max(maxOnes, ones); + } + + return k - maxOnes; + } +}; diff --git a/solutions/1151. Minimum Swaps to Group All 1's Together/1151.java b/solutions/1151. Minimum Swaps to Group All 1's Together/1151.java new file mode 100644 index 00000000000..6a6b9406a41 --- /dev/null +++ b/solutions/1151. Minimum Swaps to Group All 1's Together/1151.java @@ -0,0 +1,17 @@ +class Solution { + public int minSwaps(int[] data) { + final int k = (int) Arrays.stream(data).filter(a -> a == 1).count(); + int ones = 1; // the number of ones in the window + int maxOnes = 0; // the maximum number of ones in the window + + for (int i = 0; i < data.length; ++i) { + if (i >= k && data[i - k] == 1) + --ones; + if (data[i] == 1) + ++ones; + maxOnes = Math.max(maxOnes, ones); + } + + return k - maxOnes; + } +} diff --git a/solutions/1151. Minimum Swaps to Group All 1's Together/1151.py b/solutions/1151. Minimum Swaps to Group All 1's Together/1151.py new file mode 100644 index 00000000000..9c371acd1cb --- /dev/null +++ b/solutions/1151. Minimum Swaps to Group All 1's Together/1151.py @@ -0,0 +1,14 @@ +class Solution: + def minSwaps(self, data: List[int]) -> int: + k = data.count(1) + ones = 0 # the number of ones in the window + maxOnes = 0 # the maximum number of ones in the window + + for i, num in enumerate(data): + if i >= k and data[i - k]: + ones -= 1 + if num: + ones += 1 + maxOnes = max(maxOnes, ones) + + return k - maxOnes diff --git a/solutions/1152. Analyze User Website Visit Pattern/1152.py b/solutions/1152. Analyze User Website Visit Pattern/1152.py new file mode 100644 index 00000000000..4263edb22f9 --- /dev/null +++ b/solutions/1152. Analyze User Website Visit Pattern/1152.py @@ -0,0 +1,15 @@ +class Solution: + def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]: + userToSites = collections.defaultdict(list) + + # Sort websites of each user by timestamp. + for user, _, site in sorted(zip(username, timestamp, website), key=lambda x: (x[1])): + userToSites[user].append(site) + + # For each of three websites, count its frequency. + patternCount = collections.Counter() + + for user, sites in userToSites.items(): + patternCount.update(Counter(set(itertools.combinations(sites, 3)))) + + return max(sorted(patternCount), key=patternCount.get) diff --git a/solutions/1153. String Transforms Into Another String/1153.cpp b/solutions/1153. String Transforms Into Another String/1153.cpp new file mode 100644 index 00000000000..960bbb3beb2 --- /dev/null +++ b/solutions/1153. String Transforms Into Another String/1153.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool canConvert(string str1, string str2) { + if (str1 == str2) + return true; + + vector mappings(128); + + for (int i = 0; i < str1.length(); ++i) { + const int a = str1[i]; + const int b = str2[i]; + if (mappings[a] != 0 && mappings[a] != b) + return false; + mappings[a] = b; + } + + // No letter in the str1 maps to > 1 letter in the str2 and there is at + // lest one temporary letter can break any loops. + return unordered_set(str2.begin(), str2.end()).size() < 26; + } +}; diff --git a/solutions/1153. String Transforms Into Another String/1153.java b/solutions/1153. String Transforms Into Another String/1153.java new file mode 100644 index 00000000000..e4e7fb23f1e --- /dev/null +++ b/solutions/1153. String Transforms Into Another String/1153.java @@ -0,0 +1,20 @@ +class Solution { + public boolean canConvert(String str1, String str2) { + if (str1.equals(str2)) + return true; + + Map mappings = new HashMap<>(); + + for (int i = 0; i < str1.length(); ++i) { + final char a = str1.charAt(i); + final char b = str2.charAt(i); + if (mappings.getOrDefault(a, b) != b) + return false; + mappings.put(a, b); + } + + // No letter in the str1 maps to > 1 letter in the str2 and there is at + // lest one temporary letter can break any loops. + return new HashSet<>(mappings.values()).size() < 26; + } +} diff --git a/solutions/1153. String Transforms Into Another String/1153.py b/solutions/1153. String Transforms Into Another String/1153.py new file mode 100644 index 00000000000..13bfb0c9a8e --- /dev/null +++ b/solutions/1153. String Transforms Into Another String/1153.py @@ -0,0 +1,15 @@ +class Solution: + def canConvert(self, str1: str, str2: str) -> bool: + if str1 == str2: + return True + + mappings = {} + + for a, b in zip(str1, str2): + if mappings.get(a, b) != b: + return False + mappings[a] = b + + # No letter in the str1 maps to > 1 letter in the str2 and there is at + # lest one temporary letter can break any loops. + return len(set(str2)) < 26 diff --git a/solutions/1154. Day of the Year/1154.cpp b/solutions/1154. Day of the Year/1154.cpp new file mode 100644 index 00000000000..a41343d66a2 --- /dev/null +++ b/solutions/1154. Day of the Year/1154.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int dayOfYear(string date) { + int year = stoi(date.substr(0, 4)); + int month = stoi(date.substr(5, 2)); + int day = stoi(date.substr(8)); + vector days = { + 31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + return accumulate(days.begin(), days.begin() + month - 1, 0) + day; + } + + private: + bool isLeapYear(int year) { + return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + } +}; diff --git a/solutions/1154. Day of the Year/1154.java b/solutions/1154. Day of the Year/1154.java new file mode 100644 index 00000000000..baab1d680fc --- /dev/null +++ b/solutions/1154. Day of the Year/1154.java @@ -0,0 +1,18 @@ +class Solution { + public int dayOfYear(String date) { + int ans = 0; + int year = Integer.valueOf(date.substring(0, 4)); + int month = Integer.valueOf(date.substring(5, 7)); + int day = Integer.valueOf(date.substring(8)); + int[] days = new int[] {31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + for (int i = 0; i < month - 1; ++i) + ans += days[i]; + + return ans + day; + } + + private boolean isLeapYear(int year) { + return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + } +} diff --git a/solutions/1154. Day of the Year/1154.py b/solutions/1154. Day of the Year/1154.py new file mode 100644 index 00000000000..6e4c4277a18 --- /dev/null +++ b/solutions/1154. Day of the Year/1154.py @@ -0,0 +1,12 @@ +class Solution: + def dayOfYear(self, date: str) -> int: + def isLeapYear(year: int) -> bool: + return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 + + year = int(date[:4]) + month = int(date[5:7]) + day = int(date[8:]) + days = [31, 29 if isLeapYear( + year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + return sum(days[:month - 1]) + day diff --git a/solutions/1155. Number of Dice Rolls With Target Sum/1155.cpp b/solutions/1155. Number of Dice Rolls With Target Sum/1155.cpp new file mode 100644 index 00000000000..061dea3b6a0 --- /dev/null +++ b/solutions/1155. Number of Dice Rolls With Target Sum/1155.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int numRollsToTarget(int n, int k, int target) { + constexpr int kMod = 1'000'000'007; + vector dp(target + 1); + dp[0] = 1; + + while (n-- > 0) { // n dices + vector newDp(target + 1); + for (int i = 1; i <= k; ++i) // numbers 1, 2, ..., f + for (int t = i; t <= target; ++t) { // all the possible targets + newDp[t] += dp[t - i]; + newDp[t] %= kMod; + } + dp = move(newDp); + } + + return dp[target]; + } +}; diff --git a/solutions/1155. Number of Dice Rolls With Target Sum/1155.java b/solutions/1155. Number of Dice Rolls With Target Sum/1155.java new file mode 100644 index 00000000000..258cc519bfb --- /dev/null +++ b/solutions/1155. Number of Dice Rolls With Target Sum/1155.java @@ -0,0 +1,19 @@ +class Solution { + public int numRollsToTarget(int n, int k, int target) { + final int kMod = 1_000_000_007; + int[] dp = new int[target + 1]; + dp[0] = 1; + + while (n-- > 0) { // n dices + int[] newDp = new int[target + 1]; + for (int i = 1; i <= k; ++i) // numbers 1, 2, ..., f + for (int t = i; t <= target; ++t) { // all the possible targets + newDp[t] += dp[t - i]; + newDp[t] %= kMod; + } + dp = newDp; + } + + return dp[target]; + } +} diff --git a/solutions/1155. Number of Dice Rolls With Target Sum/1155.py b/solutions/1155. Number of Dice Rolls With Target Sum/1155.py new file mode 100644 index 00000000000..77aaad4d25b --- /dev/null +++ b/solutions/1155. Number of Dice Rolls With Target Sum/1155.py @@ -0,0 +1,14 @@ +class Solution: + def numRollsToTarget(self, n: int, k: int, target: int) -> int: + kMod = 1_000_000_007 + dp = [1] + [0] * target + + for _ in range(n): # n dices + newDp = [0] * (target + 1) + for i in range(1, k + 1): # numbers 1, 2, ..., f + for t in range(i, target + 1): # all the possible targets + newDp[t] += dp[t - i] + newDp[t] %= kMod + dp = newDp + + return dp[target] diff --git a/solutions/1156. Swap For Longest Repeated Character Substring/1156.cpp b/solutions/1156. Swap For Longest Repeated Character Substring/1156.cpp new file mode 100644 index 00000000000..51b7fc169dd --- /dev/null +++ b/solutions/1156. Swap For Longest Repeated Character Substring/1156.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxRepOpt1(string text) { + int ans = 0; + vector count(26); + vector> groups{{text[0], 1}}; + + for (char c : text) + ++count[c - 'a']; + + for (int i = 1; i < text.length(); ++i) + if (text[i] == text[i - 1]) + ++groups[groups.size() - 1].second; + else + groups.emplace_back(text[i], 1); + + for (const auto& [c, length] : groups) + ans = max(ans, min(length + 1, count[c - 'a'])); + + for (int i = 1; i + 1 < groups.size(); ++i) + if (groups[i - 1].first == groups[i + 1].first && groups[i].second == 1) + ans = max(ans, min(groups[i - 1].second + groups[i + 1].second + 1, + count[groups[i - 1].first - 'a'])); + + return ans; + } +}; diff --git a/solutions/1156. Swap For Longest Repeated Character Substring/1156.java b/solutions/1156. Swap For Longest Repeated Character Substring/1156.java new file mode 100644 index 00000000000..bcf0a017747 --- /dev/null +++ b/solutions/1156. Swap For Longest Repeated Character Substring/1156.java @@ -0,0 +1,28 @@ +class Solution { + public int maxRepOpt1(String text) { + int ans = 0; + int[] count = new int[26]; + List groups = new ArrayList<>(); + + for (char c : text.toCharArray()) + ++count[c - 'a']; + + groups.add(new int[] {text.charAt(0), 1}); + + for (int i = 1; i < text.length(); ++i) + if (text.charAt(i) == text.charAt(i - 1)) + ++groups.get(groups.size() - 1)[1]; + else + groups.add(new int[] {text.charAt(i), 1}); + + for (int[] group : groups) + ans = Math.max(ans, Math.min(group[1] + 1, count[group[0] - 'a'])); + + for (int i = 1; i + 1 < groups.size(); ++i) + if (groups.get(i - 1)[0] == groups.get(i + 1)[0] && groups.get(i)[1] == 1) + ans = Math.max(ans, Math.min(groups.get(i - 1)[1] + groups.get(i + 1)[1] + 1, + count[groups.get(i - 1)[0] - 'a'])); + + return ans; + } +} diff --git a/solutions/1156. Swap For Longest Repeated Character Substring/1156.py b/solutions/1156. Swap For Longest Repeated Character Substring/1156.py new file mode 100644 index 00000000000..03782c65440 --- /dev/null +++ b/solutions/1156. Swap For Longest Repeated Character Substring/1156.py @@ -0,0 +1,13 @@ +class Solution: + def maxRepOpt1(self, text: str) -> int: + count = collections.Counter(text) + groups = [[c, len(list(group))] + for c, group in itertools.groupby(text)] + ans = max(min(length + 1, count[c]) for c, length in groups) + + for i in range(1, len(groups) - 1): + if groups[i - 1][0] == groups[i + 1][0] and groups[i][1] == 1: + ans = max( + ans, min(groups[i - 1][1] + groups[i + 1][1] + 1, count[groups[i - 1][0]])) + + return ans diff --git a/solutions/1157. Online Majority Element In Subarray/1157.cpp b/solutions/1157. Online Majority Element In Subarray/1157.cpp new file mode 100644 index 00000000000..8d8e45f5868 --- /dev/null +++ b/solutions/1157. Online Majority Element In Subarray/1157.cpp @@ -0,0 +1,26 @@ +class MajorityChecker { + public: + MajorityChecker(vector& arr) : arr(arr) { + for (int i = 0; i < arr.size(); ++i) + numToIndices[arr[i]].push_back(i); + } + + int query(int left, int right, int threshold) { + for (int i = 0; i < kTimes; ++i) { + const int randIndex = rand() % (right - left + 1) + left; + const int num = arr[randIndex]; + const vector& indices = numToIndices[num]; + const auto lit = ranges::lower_bound(indices, left); + const auto rit = ranges::upper_bound(indices, right); + if (rit - lit >= threshold) + return num; + } + + return -1; + } + + private: + const vector arr; + static constexpr int kTimes = 20; // 2^kTimes >> |arr| = n + unordered_map> numToIndices; +}; diff --git a/solutions/1157. Online Majority Element In Subarray/1157.java b/solutions/1157. Online Majority Element In Subarray/1157.java new file mode 100644 index 00000000000..259d29112d0 --- /dev/null +++ b/solutions/1157. Online Majority Element In Subarray/1157.java @@ -0,0 +1,34 @@ +class MajorityChecker { + public MajorityChecker(int[] arr) { + this.arr = arr; + for (int i = 0; i < arr.length; ++i) { + if (!numToIndices.containsKey(arr[i])) + numToIndices.put(arr[i], new ArrayList<>()); + numToIndices.get(arr[i]).add(i); + } + } + + public int query(int left, int right, int threshold) { + for (int i = 0; i < kTimes; ++i) { + final int randIndex = rand.nextInt(right - left + 1) + left; + final int num = arr[randIndex]; + List indices = numToIndices.get(num); + final int l = firstGreaterEqual(indices, left); + final int r = firstGreaterEqual(indices, right + 1); + if (r - l >= threshold) + return num; + } + + return -1; + } + + private static final int kTimes = 20; // 2^kTimes >> |arr| + private int[] arr; + private Map> numToIndices = new HashMap<>(); + private Random rand = new Random(); + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/1157. Online Majority Element In Subarray/1157.py b/solutions/1157. Online Majority Element In Subarray/1157.py new file mode 100644 index 00000000000..fcaac8c74a0 --- /dev/null +++ b/solutions/1157. Online Majority Element In Subarray/1157.py @@ -0,0 +1,20 @@ +class MajorityChecker: + def __init__(self, arr: List[int]): + self.arr = arr + self.kTimes = 20 # 2^kTimes >> |arr| + self.numToIndices = collections.defaultdict(list) + + for i, a in enumerate(self.arr): + self.numToIndices[a].append(i) + + def query(self, left: int, right: int, threshold: int) -> int: + for _ in range(self.kTimes): + randIndex = random.randint(left, right) + num = self.arr[randIndex] + indices = self.numToIndices[num] + l = bisect.bisect_left(indices, left) + r = bisect.bisect_right(indices, right) + if r - l >= threshold: + return num + + return -1 diff --git a/solutions/1158. Market Analysis I/1158.sql b/solutions/1158. Market Analysis I/1158.sql new file mode 100644 index 00000000000..3936f6c207c --- /dev/null +++ b/solutions/1158. Market Analysis I/1158.sql @@ -0,0 +1,8 @@ +SELECT + Users.user_id AS buyer_id, + Users.join_date, + COUNT(Orders.order_id) AS orders_in_2019 +FROM Users +LEFT JOIN Orders + ON (Users.user_id = Orders.buyer_id AND YEAR(order_date) = '2019') +GROUP BY 1; diff --git a/solutions/1159. Market Analysis II/1159.sql b/solutions/1159. Market Analysis II/1159.sql new file mode 100644 index 00000000000..71592f356d9 --- /dev/null +++ b/solutions/1159. Market Analysis II/1159.sql @@ -0,0 +1,22 @@ +WITH + RankedOrders AS ( + SELECT + Orders.seller_id, + RANK() OVER( + PARTITION BY Orders.seller_id + ORDER BY Orders.order_date + ) AS `rank`, + Items.item_brand + FROM Orders + INNER JOIN Items + USING (item_id) + ) +SELECT + user_id AS seller_id, + CASE + WHEN Users.favorite_brand = RankedOrders.item_brand THEN 'yes' + ELSE 'no' + END AS 2nd_item_fav_brand +FROM Users +LEFT JOIN RankedOrders + ON (Users.user_id = RankedOrders.seller_id AND RankedOrders.`rank` = 2); diff --git a/solutions/116. Populating Next Right Pointers in Each Node/116-2.cpp b/solutions/116. Populating Next Right Pointers in Each Node/116-2.cpp new file mode 100644 index 00000000000..5d8e8413058 --- /dev/null +++ b/solutions/116. Populating Next Right Pointers in Each Node/116-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + Node* connect(Node* root) { + Node* node = root; // the node that is above the current needling + + while (node && node->left) { + Node dummy(0); // the dummy node before needling + // Needle the children of the node. + for (Node* needle = &dummy; node; node = node->next) { + needle->next = node->left; + needle = needle->next; + needle->next = node->right; + needle = needle->next; + } + node = dummy.next; // Move the node to the next level. + } + + return root; + } +}; diff --git a/solutions/116. Populating Next Right Pointers in Each Node/116-2.java b/solutions/116. Populating Next Right Pointers in Each Node/116-2.java new file mode 100644 index 00000000000..776d10e8200 --- /dev/null +++ b/solutions/116. Populating Next Right Pointers in Each Node/116-2.java @@ -0,0 +1,19 @@ +class Solution { + public Node connect(Node root) { + Node node = root; // the node that is above the current needling + + while (node != null && node.left != null) { + Node dummy = new Node(); // a dummy node before needling + // Needle the children of the node. + for (Node needle = dummy; node != null; node = node.next) { + needle.next = node.left; + needle = needle.next; + needle.next = node.right; + needle = needle.next; + } + node = dummy.next; // Move the node to the next level. + } + + return root; + } +} diff --git a/solutions/116. Populating Next Right Pointers in Each Node/116-2.py b/solutions/116. Populating Next Right Pointers in Each Node/116-2.py new file mode 100644 index 00000000000..725613e2c99 --- /dev/null +++ b/solutions/116. Populating Next Right Pointers in Each Node/116-2.py @@ -0,0 +1,17 @@ +class Solution: + def connect(self, root: 'Node') -> 'Node': + node = root # the node that is above the current needling + + while node and node.left: + dummy = Node(0) # a dummy node before needling + # Needle the children of the node. + needle = dummy + while node: + needle.next = node.left + needle = needle.next + needle.next = node.right + needle = needle.next + node = node.next + node = dummy.next # Move the node to the next level. + + return root diff --git a/solutions/116. Populating Next Right Pointers in Each Node/116.cpp b/solutions/116. Populating Next Right Pointers in Each Node/116.cpp new file mode 100644 index 00000000000..1fa5454ebd8 --- /dev/null +++ b/solutions/116. Populating Next Right Pointers in Each Node/116.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + Node* connect(Node* root) { + if (root == nullptr) + return nullptr; + connectTwoNodes(root->left, root->right); + return root; + } + + private: + void connectTwoNodes(Node* p, Node* q) { + if (p == nullptr) + return; + p->next = q; + connectTwoNodes(p->left, p->right); + connectTwoNodes(q->left, q->right); + connectTwoNodes(p->right, q->left); + } +}; diff --git a/solutions/116. Populating Next Right Pointers in Each Node/116.java b/solutions/116. Populating Next Right Pointers in Each Node/116.java new file mode 100644 index 00000000000..2f1c0104a85 --- /dev/null +++ b/solutions/116. Populating Next Right Pointers in Each Node/116.java @@ -0,0 +1,17 @@ +class Solution { + public Node connect(Node root) { + if (root == null) + return null; + connectTwoNodes(root.left, root.right); + return root; + } + + private void connectTwoNodes(Node p, Node q) { + if (p == null) + return; + p.next = q; + connectTwoNodes(p.left, p.right); + connectTwoNodes(q.left, q.right); + connectTwoNodes(p.right, q.left); + } +} diff --git a/solutions/116. Populating Next Right Pointers in Each Node/116.py b/solutions/116. Populating Next Right Pointers in Each Node/116.py new file mode 100644 index 00000000000..c47bb914ec6 --- /dev/null +++ b/solutions/116. Populating Next Right Pointers in Each Node/116.py @@ -0,0 +1,15 @@ +class Solution: + def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': + if not root: + return None + + def connectTwoNodes(p, q) -> None: + if not p: + return + p.next = q + connectTwoNodes(p.left, p.right) + connectTwoNodes(q.left, q.right) + connectTwoNodes(p.right, q.left) + + connectTwoNodes(root.left, root.right) + return root diff --git a/solutions/1160. Find Words That Can Be Formed by Characters/1160.cpp b/solutions/1160. Find Words That Can Be Formed by Characters/1160.cpp new file mode 100644 index 00000000000..66ef953cf58 --- /dev/null +++ b/solutions/1160. Find Words That Can Be Formed by Characters/1160.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int countCharacters(vector& words, string chars) { + int ans = 0; + vector count(26); + + for (const char c : chars) + ++count[c - 'a']; + + for (const string& word : words) { + vector tempCount(count); + for (const char c : word) + if (--tempCount[c - 'a'] < 0) { + ans -= word.length(); + break; + } + ans += word.length(); + } + + return ans; + } +}; diff --git a/solutions/1160. Find Words That Can Be Formed by Characters/1160.java b/solutions/1160. Find Words That Can Be Formed by Characters/1160.java new file mode 100644 index 00000000000..02f282d9f3b --- /dev/null +++ b/solutions/1160. Find Words That Can Be Formed by Characters/1160.java @@ -0,0 +1,21 @@ +class Solution { + public int countCharacters(String[] words, String chars) { + int ans = 0; + int[] count = new int[26]; + + for (final char c : chars.toCharArray()) + ++count[c - 'a']; + + for (final String word : words) { + int[] tempCount = count.clone(); + for (final char c : word.toCharArray()) + if (--tempCount[c - 'a'] < 0) { + ans -= word.length(); + break; + } + ans += word.length(); + } + + return ans; + } +} diff --git a/solutions/1160. Find Words That Can Be Formed by Characters/1160.py b/solutions/1160. Find Words That Can Be Formed by Characters/1160.py new file mode 100644 index 00000000000..f96053addc2 --- /dev/null +++ b/solutions/1160. Find Words That Can Be Formed by Characters/1160.py @@ -0,0 +1,15 @@ +class Solution: + def countCharacters(self, words: List[str], chars: str) -> int: + ans = 0 + count = collections.Counter(chars) + + for word in words: + tempCount = count.copy() + for c in word: + tempCount[c] -= 1 + if tempCount[c] < 0: + ans -= len(word) + break + ans += len(word) + + return ans diff --git a/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.cpp b/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.cpp new file mode 100644 index 00000000000..ceee91270d7 --- /dev/null +++ b/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxLevelSum(TreeNode* root) { + // levelSums[i] := the sum of level (i + 1) (1-indexed) + vector levelSums; + dfs(root, 0, levelSums); + return 1 + ranges::max_element(levelSums) - levelSums.begin(); + } + + private: + void dfs(TreeNode* root, int level, vector& levelSums) { + if (root == nullptr) + return; + if (levelSums.size() == level) + levelSums.push_back(0); + levelSums[level] += root->val; + dfs(root->left, level + 1, levelSums); + dfs(root->right, level + 1, levelSums); + } +}; diff --git a/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.java b/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.java new file mode 100644 index 00000000000..c5ed557804a --- /dev/null +++ b/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.java @@ -0,0 +1,19 @@ +class Solution { + public int maxLevelSum(TreeNode root) { + // levelSums[i] := the sum of level (i + 1) (1-indexed) + List levelSums = new ArrayList<>(); + dfs(root, 0, levelSums); + return 1 + IntStream.range(0, levelSums.size()) + .reduce(0, (a, b) -> levelSums.get(a) < levelSums.get(b) ? b : a); + } + + private void dfs(TreeNode root, int level, List levelSums) { + if (root == null) + return; + if (levelSums.size() == level) + levelSums.add(0); + levelSums.set(level, levelSums.get(level) + root.val); + dfs(root.left, level + 1, levelSums); + dfs(root.right, level + 1, levelSums); + } +} diff --git a/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.py b/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.py new file mode 100644 index 00000000000..de8ae47646a --- /dev/null +++ b/solutions/1161. Maximum Level Sum of a Binary Tree/1161-2.py @@ -0,0 +1,16 @@ +class Solution: + def maxLevelSum(self, root: Optional[TreeNode]) -> int: + # levelSums[i] := the sum of level (i + 1) (1-indexed) + levelSums = [] + + def dfs(root: Optional[TreeNode], level: int) -> None: + if not root: + return + if len(levelSums) == level: + levelSums.append(0) + levelSums[level] += root.val + dfs(root.left, level + 1) + dfs(root.right, level + 1) + + dfs(root, 0) + return 1 + levelSums.index(max(levelSums)) diff --git a/solutions/1161. Maximum Level Sum of a Binary Tree/1161.cpp b/solutions/1161. Maximum Level Sum of a Binary Tree/1161.cpp new file mode 100644 index 00000000000..e8404b03412 --- /dev/null +++ b/solutions/1161. Maximum Level Sum of a Binary Tree/1161.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxLevelSum(TreeNode* root) { + int ans = 0; + int maxLevelSum = INT_MIN; + queue q{{root}}; + + for (int level = 1; !q.empty(); ++level) { + int levelSum = 0; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + levelSum += node->val; + if (node->left != nullptr) + q.push(node->left); + if (node->right != nullptr) + q.push(node->right); + } + if (levelSum > maxLevelSum) { + maxLevelSum = levelSum; + ans = level; + } + } + + return ans; + } +}; diff --git a/solutions/1161. Maximum Level Sum of a Binary Tree/1161.java b/solutions/1161. Maximum Level Sum of a Binary Tree/1161.java new file mode 100644 index 00000000000..d2ff770d16c --- /dev/null +++ b/solutions/1161. Maximum Level Sum of a Binary Tree/1161.java @@ -0,0 +1,25 @@ +class Solution { + public int maxLevelSum(TreeNode root) { + int ans = 0; + int maxLevelSum = Integer.MIN_VALUE; + Queue q = new LinkedList<>(Arrays.asList(root)); + + for (int level = 1; !q.isEmpty(); ++level) { + int levelSum = 0; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + levelSum += node.val; + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + if (levelSum > maxLevelSum) { + maxLevelSum = levelSum; + ans = level; + } + } + + return ans; + } +} diff --git a/solutions/1161. Maximum Level Sum of a Binary Tree/1161.py b/solutions/1161. Maximum Level Sum of a Binary Tree/1161.py new file mode 100644 index 00000000000..f7e02b6b7ff --- /dev/null +++ b/solutions/1161. Maximum Level Sum of a Binary Tree/1161.py @@ -0,0 +1,22 @@ +class Solution: + def maxLevelSum(self, root: Optional[TreeNode]) -> int: + ans = 0 + maxLevelSum = -math.inf + q = collections.deque([root]) + + level = 1 + while q: + levelSum = 0 + for _ in range(len(q)): + node = q.popleft() + levelSum += node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if levelSum > maxLevelSum: + maxLevelSum = levelSum + ans = level + level += 1 + + return ans diff --git a/solutions/1162. As Far from Land as Possible/1162.cpp b/solutions/1162. As Far from Land as Possible/1162.cpp new file mode 100644 index 00000000000..137629d8951 --- /dev/null +++ b/solutions/1162. As Far from Land as Possible/1162.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int maxDistance(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + queue> q; + int water = 0; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0) + ++water; + else + q.emplace(i, j); + + if (water == 0 || water == m * n) + return -1; + + int ans = 0; + + for (int d = 0; !q.empty(); ++d) + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + ans = d; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] > 0) + continue; + q.emplace(x, y); + grid[x][y] = 2; // Mark as visited. + } + } + + return ans; + } +}; diff --git a/solutions/1162. As Far from Land as Possible/1162.java b/solutions/1162. As Far from Land as Possible/1162.java new file mode 100644 index 00000000000..dafadc80db3 --- /dev/null +++ b/solutions/1162. As Far from Land as Possible/1162.java @@ -0,0 +1,41 @@ +class Solution { + public int maxDistance(int[][] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length; + Queue> q = new ArrayDeque<>(); + int water = 0; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0) + ++water; + else + q.offer(new Pair<>(i, j)); + + if (water == 0 || water == m * n) + return -1; + + int ans = 0; + + for (int d = 0; !q.isEmpty(); ++d) + for (int sz = q.size(); sz > 0; --sz) { + Pair pair = q.poll(); + final int i = pair.getKey(); + final int j = pair.getValue(); + ans = d; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] > 0) + continue; + q.offer(new Pair<>(x, y)); + grid[x][y] = 2; // Mark as visited. + } + } + + return ans; + } +} diff --git a/solutions/1162. As Far from Land as Possible/1162.py b/solutions/1162. As Far from Land as Possible/1162.py new file mode 100644 index 00000000000..91d8a0fec6a --- /dev/null +++ b/solutions/1162. As Far from Land as Possible/1162.py @@ -0,0 +1,37 @@ +class Solution: + def maxDistance(self, grid: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + q = collections.deque() + water = 0 + + for i in range(m): + for j in range(n): + if grid[i][j] == 0: + water += 1 + else: + q.append((i, j)) + + if water == 0 or water == m * n: + return -1 + + ans = 0 + d = 0 + + while q: + for _ in range(len(q)): + i, j = q.popleft() + ans = d + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if grid[x][y] > 0: + continue + q.append((x, y)) + grid[x][y] = 2 # Mark as visited. + d += 1 + + return ans diff --git a/solutions/1163. Last Substring in Lexicographical Order/1163.cpp b/solutions/1163. Last Substring in Lexicographical Order/1163.cpp new file mode 100644 index 00000000000..09edfe36f80 --- /dev/null +++ b/solutions/1163. Last Substring in Lexicographical Order/1163.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string lastSubstring(string s) { + int i = 0; + int j = 1; + int k = 0; // the number of the same letters of s[i..n) and s[j..n) + + while (j + k < s.length()) { + if (s[i + k] == s[j + k]) { + ++k; + } else if (s[i + k] > s[j + k]) { + // s[i..i + k] == s[j..j + k] and s[i + k] > s[j + k] means that we + // should start from s[j + k] to find a possible larger substring. + j += k + 1; + k = 0; + } else { + // s[i..i + k] == s[j..j + k] and s[i + k] < s[j + k] means that either + // starting from s[i + k + 1] or s[j] has a larger substring. + i = max(i + k + 1, j); + j = i + 1; + k = 0; + } + } + + return s.substr(i); + } +}; diff --git a/solutions/1163. Last Substring in Lexicographical Order/1163.java b/solutions/1163. Last Substring in Lexicographical Order/1163.java new file mode 100644 index 00000000000..72d10bd6217 --- /dev/null +++ b/solutions/1163. Last Substring in Lexicographical Order/1163.java @@ -0,0 +1,26 @@ +class Solution { + public String lastSubstring(String s) { + int i = 0; + int j = 1; + int k = 0; // the number of the same letters of s[i..n) and s[j..n) + + while (j + k < s.length()) { + if (s.charAt(i + k) == s.charAt(j + k)) { + ++k; + } else if (s.charAt(i + k) > s.charAt(j + k)) { + // s[i..i + k] == s[j..j + k] and s[i + k] > s[j + k] means that we + // should start from s[j + k] to find a possible larger substring. + j += k + 1; + k = 0; + } else { + // s[i..i + k] == s[j..j + k] and s[i + k] < s[j + k] means that either + // starting from s[i + k + 1] or s[j] has a larger substring. + i = Math.max(i + k + 1, j); + j = i + 1; + k = 0; + } + } + + return s.substring(i); + } +} diff --git a/solutions/1163. Last Substring in Lexicographical Order/1163.py b/solutions/1163. Last Substring in Lexicographical Order/1163.py new file mode 100644 index 00000000000..2ef73f4b430 --- /dev/null +++ b/solutions/1163. Last Substring in Lexicographical Order/1163.py @@ -0,0 +1,22 @@ +class Solution: + def lastSubstring(self, s: str) -> str: + i = 0 + j = 1 + k = 0 # the number of the same letters of s[i..n) and s[j..n) + + while j + k < len(s): + if s[i + k] == s[j + k]: + k += 1 + elif s[i + k] > s[j + k]: + # s[i..i + k] == s[j..j + k] and s[i + k] > s[j + k] means that we + # should start from s[j + k] to find a possible larger substring. + j += k + 1 + k = 0 + else: + # s[i..i + k] == s[j..j + k] and s[i + k] < s[j + k] means that either + # starting from s[i + k + 1] or s[j] has a larger substring + i = max(i + k + 1, j) + j = i + 1 + k = 0 + + return s[i:] diff --git a/solutions/1164. Product Price at a Given Date/1164.sql b/solutions/1164. Product Price at a Given Date/1164.sql new file mode 100644 index 00000000000..182c8bce740 --- /dev/null +++ b/solutions/1164. Product Price at a Given Date/1164.sql @@ -0,0 +1,24 @@ +WITH + RankedProducts AS ( + SELECT + product_id, + new_price, + RANK() OVER( + PARTITION BY product_id + ORDER BY change_date DESC + ) AS `rank` + FROM Products + WHERE change_date <= '2019-08-16' + ), + ProductToLatestPrice AS ( + SELECT product_id, new_price + FROM RankedProducts + WHERE `rank` = 1 + ) +SELECT + Products.product_id, + IFNULL(ProductToLatestPrice.new_price, 10) AS price +FROM Products +LEFT JOIN ProductToLatestPrice + USING (product_id) +GROUP BY 1; diff --git a/solutions/1165. Single-Row Keyboard/1165.cpp b/solutions/1165. Single-Row Keyboard/1165.cpp new file mode 100644 index 00000000000..9725cc8c302 --- /dev/null +++ b/solutions/1165. Single-Row Keyboard/1165.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int calculateTime(string keyboard, string word) { + int ans = 0; + int prevIndex = 0; + vector letterToIndex(26); + + for (int i = 0; i < keyboard.length(); ++i) + letterToIndex[keyboard[i] - 'a'] = i; + + for (const char c : word) { + const int currIndex = letterToIndex[c - 'a']; + ans += abs(currIndex - prevIndex); + prevIndex = currIndex; + } + + return ans; + } +}; diff --git a/solutions/1165. Single-Row Keyboard/1165.java b/solutions/1165. Single-Row Keyboard/1165.java new file mode 100644 index 00000000000..56be5cbd27f --- /dev/null +++ b/solutions/1165. Single-Row Keyboard/1165.java @@ -0,0 +1,18 @@ +class Solution { + public int calculateTime(String keyboard, String word) { + int ans = 0; + int prevIndex = 0; + int[] letterToIndex = new int[26]; + + for (int i = 0; i < keyboard.length(); ++i) + letterToIndex[keyboard.charAt(i) - 'a'] = i; + + for (final char c : word.toCharArray()) { + final int currIndex = letterToIndex[c - 'a']; + ans += Math.abs(currIndex - prevIndex); + prevIndex = currIndex; + } + + return ans; + } +} diff --git a/solutions/1165. Single-Row Keyboard/1165.py b/solutions/1165. Single-Row Keyboard/1165.py new file mode 100644 index 00000000000..b7a9953d99c --- /dev/null +++ b/solutions/1165. Single-Row Keyboard/1165.py @@ -0,0 +1,6 @@ +class Solution: + def calculateTime(self, keyboard: str, word: str) -> int: + letterToIndex = {c: i for i, c in enumerate(keyboard)} + return letterToIndex[word[0]] + \ + sum(abs(letterToIndex[a] - letterToIndex[b]) + for a, b in itertools.pairwise(word)) diff --git a/solutions/1166. Design File System/1166.cpp b/solutions/1166. Design File System/1166.cpp new file mode 100644 index 00000000000..55b55f2a689 --- /dev/null +++ b/solutions/1166. Design File System/1166.cpp @@ -0,0 +1,51 @@ +struct TrieNode { + unordered_map> children; + int value; + TrieNode(int value) : value(value) {} +}; + +class FileSystem { + public: + bool createPath(string path, int value) { + const vector subpaths = getSubpaths(path); + shared_ptr node = root; + + for (int i = 0; i < subpaths.size() - 1; ++i) { + auto it = node->children.find(subpaths[i]); + if (it == node->children.end()) + return false; + node = it->second; + } + + if (node->children.contains(subpaths.back())) + return false; + node->children[subpaths.back()] = make_shared(value); + return true; + } + + int get(string path) { + const vector subpaths = getSubpaths(path); + shared_ptr node = root; + + for (const string& subpath : getSubpaths(path)) { + auto it = node->children.find(subpath); + if (it == node->children.end()) + return -1; + node = it->second; + } + + return node->value; + } + + private: + shared_ptr root = make_shared(0); + + vector getSubpaths(const string& path) { + vector subpaths; + istringstream iss(path); + for (string subpath; getline(iss, subpath, '/');) + if (!subpath.empty()) + subpaths.push_back(subpath); + return subpaths; + } +}; diff --git a/solutions/1166. Design File System/1166.java b/solutions/1166. Design File System/1166.java new file mode 100644 index 00000000000..bb70ee97720 --- /dev/null +++ b/solutions/1166. Design File System/1166.java @@ -0,0 +1,41 @@ +class TrieNode { + public Map children = new HashMap<>(); + public int value; + public TrieNode(int value) { + this.value = value; + } +} + +class FileSystem { + public boolean createPath(String path, int value) { + final String[] subpaths = path.split("/"); + TrieNode node = root; + + for (int i = 1; i < subpaths.length - 1; ++i) { + if (!node.children.containsKey(subpaths[i])) + return false; + node = node.children.get(subpaths[i]); + } + + final String lastSubpath = subpaths[subpaths.length - 1]; + if (node.children.containsKey(lastSubpath)) + return false; + node.children.put(lastSubpath, new TrieNode(value)); + return true; + } + + public int get(String path) { + final String[] subpaths = path.split("/"); + TrieNode node = root; + + for (int i = 1; i < subpaths.length; ++i) { + if (!node.children.containsKey(subpaths[i])) + return -1; + node = node.children.get(subpaths[i]); + } + + return node.value; + } + + private TrieNode root = new TrieNode(0); +} diff --git a/solutions/1166. Design File System/1166.py b/solutions/1166. Design File System/1166.py new file mode 100644 index 00000000000..3fdc6c85528 --- /dev/null +++ b/solutions/1166. Design File System/1166.py @@ -0,0 +1,33 @@ +class TrieNode: + def __init__(self, value: int = 0): + self.children: Dict[str, TrieNode] = {} + self.value = value + + +class FileSystem: + def __init__(self): + self.root = TrieNode() + + def createPath(self, path: str, value: int) -> bool: + node: TrieNode = self.root + subpaths = path.split('/') + + for i in range(1, len(subpaths) - 1): + if subpaths[i] not in node.children: + return False + node = node.children[subpaths[i]] + + if subpaths[-1] in node.children: + return False + node.children[subpaths[-1]] = TrieNode(value) + return True + + def get(self, path: str) -> int: + node: TrieNode = self.root + + for subpath in path.split('/')[1:]: + if subpath not in node.children: + return -1 + node = node.children[subpath] + + return node.value diff --git a/solutions/1167. Minimum Cost to Connect Sticks/1167.cpp b/solutions/1167. Minimum Cost to Connect Sticks/1167.cpp new file mode 100644 index 00000000000..4677f131af8 --- /dev/null +++ b/solutions/1167. Minimum Cost to Connect Sticks/1167.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int connectSticks(vector& sticks) { + int ans = 0; + priority_queue, greater<>> minHeap; + + for (const int stick : sticks) + minHeap.push(stick); + + while (minHeap.size() > 1) { + const int x = minHeap.top(); + minHeap.pop(); + const int y = minHeap.top(); + minHeap.pop(); + ans += x + y; + minHeap.push(x + y); + } + + return ans; + } +}; diff --git a/solutions/1167. Minimum Cost to Connect Sticks/1167.java b/solutions/1167. Minimum Cost to Connect Sticks/1167.java new file mode 100644 index 00000000000..6c82c433c1d --- /dev/null +++ b/solutions/1167. Minimum Cost to Connect Sticks/1167.java @@ -0,0 +1,18 @@ +class Solution { + public int connectSticks(int[] sticks) { + int ans = 0; + Queue minHeap = new PriorityQueue<>(); + + for (final int stick : sticks) + minHeap.offer(stick); + + while (minHeap.size() > 1) { + final int x = minHeap.poll(); + final int y = minHeap.poll(); + ans += x + y; + minHeap.offer(x + y); + } + + return ans; + } +} diff --git a/solutions/1167. Minimum Cost to Connect Sticks/1167.py b/solutions/1167. Minimum Cost to Connect Sticks/1167.py new file mode 100644 index 00000000000..c34a2e7589b --- /dev/null +++ b/solutions/1167. Minimum Cost to Connect Sticks/1167.py @@ -0,0 +1,12 @@ +class Solution: + def connectSticks(self, sticks: List[int]) -> int: + ans = 0 + heapq.heapify(sticks) + + while len(sticks) > 1: + x = heapq.heappop(sticks) + y = heapq.heappop(sticks) + ans += x + y + heapq.heappush(sticks, x + y) + + return ans diff --git a/solutions/1168. Optimize Water Distribution in a Village/1168.cpp b/solutions/1168. Optimize Water Distribution in a Village/1168.cpp new file mode 100644 index 00000000000..fd7b38eede6 --- /dev/null +++ b/solutions/1168. Optimize Water Distribution in a Village/1168.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int minCostToSupplyWater(int n, vector& wells, + vector>& pipes) { + int ans = 0; + using P = pair; + vector> graph(n + 1); + priority_queue, greater<>> minHeap; // (d, u) + + for (const vector& pipe : pipes) { + const int u = pipe[0]; + const int v = pipe[1]; + const int w = pipe[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + // Connect virtual 0 with nodes 1 to n. + for (int i = 0; i < n; ++i) { + graph[0].emplace_back(i + 1, wells[i]); + minHeap.emplace(wells[i], i + 1); + } + + unordered_set mst{{0}}; + + while (mst.size() < n + 1) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (mst.contains(u)) + continue; + // Add the new vertex. + mst.insert(u); + ans += d; + // Expand if possible. + for (const auto [v, w] : graph[u]) + if (!mst.contains(v)) + minHeap.emplace(w, v); + } + + return ans; + } +}; diff --git a/solutions/1168. Optimize Water Distribution in a Village/1168.java b/solutions/1168. Optimize Water Distribution in a Village/1168.java new file mode 100644 index 00000000000..6b6c40d2efd --- /dev/null +++ b/solutions/1168. Optimize Water Distribution in a Village/1168.java @@ -0,0 +1,47 @@ +class Solution { + public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + int ans = 0; + List>[] graph = new List[n + 1]; + Queue> minHeap = + new PriorityQueue<>(Comparator.comparing(Pair::getKey)); // (d, u) + + for (int i = 0; i <= n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] pipe : pipes) { + final int u = pipe[0]; + final int v = pipe[1]; + final int w = pipe[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + // Connect virtual 0 with nodes 1 to n. + for (int i = 0; i < n; ++i) { + graph[0].add(new Pair<>(i + 1, wells[i])); + minHeap.offer(new Pair<>(wells[i], i + 1)); + } + + Set mst = new HashSet<>(Arrays.asList(0)); + + while (mst.size() < n + 1) { + Pair pair = minHeap.poll(); + final int d = pair.getKey(); + final int u = pair.getValue(); + if (mst.contains(u)) + continue; + // Add the new vertex. + mst.add(u); + ans += d; + // Expand if possible. + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (!mst.contains(v)) + minHeap.offer(new Pair<>(w, v)); + } + } + + return ans; + } +} diff --git a/solutions/1168. Optimize Water Distribution in a Village/1168.py b/solutions/1168. Optimize Water Distribution in a Village/1168.py new file mode 100644 index 00000000000..373ac8f40c3 --- /dev/null +++ b/solutions/1168. Optimize Water Distribution in a Village/1168.py @@ -0,0 +1,30 @@ +class Solution: + def minCostToSupplyWater(self, n: int, wells: List[int], pipes: List[List[int]]) -> int: + ans = 0 + graph = [[] for _ in range(n + 1)] + minHeap = [] # (d, u) + + for u, v, w in pipes: + graph[u].append((v, w)) + graph[v].append((u, w)) + + # Connect virtual 0 with nodes 1 to n. + for i, well in enumerate(wells): + graph[0].append((i + 1, well)) + heapq.heappush(minHeap, (well, i + 1)) + + mst = {0} + + while len(mst) < n + 1: + d, u = heapq.heappop(minHeap) + if u in mst: + continue + # Add the new vertex. + mst.add(u) + ans += d + # Expand if possible. + for v, w in graph[u]: + if v not in mst: + heapq.heappush(minHeap, (w, v)) + + return ans diff --git a/solutions/1169. Invalid Transactions/1169.cpp b/solutions/1169. Invalid Transactions/1169.cpp new file mode 100644 index 00000000000..b82b4cf1d47 --- /dev/null +++ b/solutions/1169. Invalid Transactions/1169.cpp @@ -0,0 +1,47 @@ +struct Trans { + string name; + int time; + int amount; + string city; +}; + +class Solution { + public: + vector invalidTransactions(vector& transactions) { + vector ans; + unordered_map> nameToTranses; + + for (const string& t : transactions) { + const Trans trans = getTrans(t); + nameToTranses[trans.name].push_back(trans); + } + + for (const string& t : transactions) { + const Trans currTrans = getTrans(t); + if (currTrans.amount > 1000) { + ans.push_back(t); + } else if (const auto it = nameToTranses.find(currTrans.name); + it != nameToTranses.cend()) { + // Iterate through all the transactions with the same name, check if + // they're within 60 minutes in a different city. + for (Trans trans : it->second) + if (abs(trans.time - currTrans.time) <= 60 && + trans.city != currTrans.city) { + ans.push_back(t); + break; + } + } + } + + return ans; + } + + private: + Trans getTrans(const string& t) { + istringstream iss(t); + vector s(4, ""); + for (int i = 0; getline(iss, s[i++], ',');) + ; + return {s[0], stoi(s[1]), stoi(s[2]), s[3]}; + } +}; diff --git a/solutions/1169. Invalid Transactions/1169.java b/solutions/1169. Invalid Transactions/1169.java new file mode 100644 index 00000000000..d5f6d2fbe86 --- /dev/null +++ b/solutions/1169. Invalid Transactions/1169.java @@ -0,0 +1,47 @@ +class Trans { + public String name; + public int time; + public int amount; + public String city; + public Trans(String name, int time, int amount, String city) { + this.name = name; + this.time = time; + this.amount = amount; + this.city = city; + } +} + +class Solution { + public List invalidTransactions(String[] transactions) { + List ans = new ArrayList<>(); + Map> nameToTranses = new HashMap<>(); + + for (final String t : transactions) { + Trans trans = getTrans(t); + nameToTranses.putIfAbsent(trans.name, new ArrayList<>()); + nameToTranses.get(trans.name).add(trans); + } + + for (final String t : transactions) { + Trans currTrans = getTrans(t); + if (currTrans.amount > 1000) { + ans.add(t); + } else if (nameToTranses.containsKey(currTrans.name)) { + // Iterate through all the transactions with the same name, check if + // they're within 60 minutes in a different city. + for (Trans trans : nameToTranses.get(currTrans.name)) + if (Math.abs(trans.time - currTrans.time) <= 60 && !trans.city.equals(currTrans.city)) { + ans.add(t); + break; + } + } + } + + return ans; + } + + private Trans getTrans(final String t) { + String[] s = t.split(","); // [name, time, amount, city] + return new Trans(s[0], Integer.parseInt(s[1]), Integer.parseInt(s[2]), s[3]); + } +} diff --git a/solutions/1169. Invalid Transactions/1169.py b/solutions/1169. Invalid Transactions/1169.py new file mode 100644 index 00000000000..076c2dc009f --- /dev/null +++ b/solutions/1169. Invalid Transactions/1169.py @@ -0,0 +1,22 @@ +class Solution: + def invalidTransactions(self, transactions: List[str]) -> List[str]: + ans = [] + nameToTranses = collections.defaultdict(list) + + for t in transactions: + name, time, amount, city = t.split(',') + time, amount = int(time), int(amount) + nameToTranses[name].append({'time': time, 'city': city}) + + for t in transactions: + name, time, amount, city = t.split(',') + time, amount = int(time), int(amount) + if amount > 1000: + ans.append(t) + elif name in nameToTranses: + for sameName in nameToTranses[name]: + if abs(sameName['time'] - time) <= 60 and sameName['city'] != city: + ans.append(t) + break + + return ans diff --git a/solutions/117. Populating Next Right Pointers in Each Node II/117.cpp b/solutions/117. Populating Next Right Pointers in Each Node II/117.cpp new file mode 100644 index 00000000000..aed2bf3a0d0 --- /dev/null +++ b/solutions/117. Populating Next Right Pointers in Each Node II/117.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + Node* connect(Node* root) { + Node* node = root; // the node that is above the current needling + + while (node) { + Node dummy(0); // the dummy node before needling + // Needle the children of the node. + for (Node* needle = &dummy; node; node = node->next) { + if (node->left) { // Needle the left child. + needle->next = node->left; + needle = needle->next; + } + if (node->right) { // Needle the right child. + needle->next = node->right; + needle = needle->next; + } + } + node = dummy.next; // Move the node to the next level. + } + + return root; + } +}; diff --git a/solutions/117. Populating Next Right Pointers in Each Node II/117.java b/solutions/117. Populating Next Right Pointers in Each Node II/117.java new file mode 100644 index 00000000000..05d4fe0b021 --- /dev/null +++ b/solutions/117. Populating Next Right Pointers in Each Node II/117.java @@ -0,0 +1,23 @@ +class Solution { + public Node connect(Node root) { + Node node = root; // the node that is above the current needling + + while (node != null) { + Node dummy = new Node(); // a dummy node before needling + // Needle the children of the node. + for (Node needle = dummy; node != null; node = node.next) { + if (node.left != null) { // Needle the left child. + needle.next = node.left; + needle = needle.next; + } + if (node.right != null) { // Needle the right child. + needle.next = node.right; + needle = needle.next; + } + } + node = dummy.next; // Move the node to the next level. + } + + return root; + } +} diff --git a/solutions/117. Populating Next Right Pointers in Each Node II/117.py b/solutions/117. Populating Next Right Pointers in Each Node II/117.py new file mode 100644 index 00000000000..b36d8635fb4 --- /dev/null +++ b/solutions/117. Populating Next Right Pointers in Each Node II/117.py @@ -0,0 +1,19 @@ +class Solution: + def connect(self, root: 'Node') -> 'Node': + node = root # the node that is above the current needling + + while node: + dummy = Node(0) # a dummy node before needling + # Needle the children of the node. + needle = dummy + while node: + if node.left: # Needle the left child. + needle.next = node.left + needle = needle.next + if node.right: # Needle the right child. + needle.next = node.right + needle = needle.next + node = node.next + node = dummy.next # Move the node to the next level. + + return root diff --git a/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.cpp b/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.cpp new file mode 100644 index 00000000000..e2f744731f3 --- /dev/null +++ b/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector numSmallerByFrequency(vector& queries, + vector& words) { + vector ans; + vector wordsFreq; + + for (const string& word : words) + wordsFreq.push_back(f(word)); + ranges::sort(wordsFreq); + + for (const string& query : queries) { + const int freq = f(query); + ans.push_back(wordsFreq.end() - ranges::upper_bound(wordsFreq, freq)); + } + + return ans; + } + + private: + int f(const string& word) { + int count = 0; + char currentChar = 'z' + 1; + + for (const char c : word) + if (c < currentChar) { + currentChar = c; + count = 1; + } else if (c == currentChar) { + ++count; + } + + return count; + } +}; diff --git a/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.java b/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.java new file mode 100644 index 00000000000..6b8d874e8e4 --- /dev/null +++ b/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.java @@ -0,0 +1,43 @@ +class Solution { + public int[] numSmallerByFrequency(String[] queries, String[] words) { + int[] ans = new int[queries.length]; + int[] wordsFreq = new int[words.length]; + + for (int i = 0; i < words.length; ++i) + wordsFreq[i] = f(words[i]); + Arrays.sort(wordsFreq); + + for (int i = 0; i < queries.length; ++i) { + final int freq = f(queries[i]); + ans[i] = words.length - firstGreater(wordsFreq, 0, wordsFreq.length, freq); + } + + return ans; + } + + private int f(final String word) { + int count = 0; + char currentChar = 'z' + 1; + + for (final char c : word.toCharArray()) + if (c < currentChar) { + currentChar = c; + count = 1; + } else if (c == currentChar) { + ++count; + } + + return count; + } + + private int firstGreater(int[] nums, int l, int r, int value) { + while (l < r) { + final int m = (l + r) / 2; + if (nums[m] > value) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.py b/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.py new file mode 100644 index 00000000000..96d05199122 --- /dev/null +++ b/solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.py @@ -0,0 +1,11 @@ +class Solution: + def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: + ans = [] + wordsFreq = sorted([word.count(min(word)) for word in words]) + + for q in queries: + count = q.count(min(q)) + index = bisect.bisect(wordsFreq, count) + ans.append(len(words) - index) + + return ans diff --git a/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.cpp b/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.cpp new file mode 100644 index 00000000000..cd50812fad4 --- /dev/null +++ b/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + ListNode* removeZeroSumSublists(ListNode* head) { + ListNode dummy(0, head); + int prefix = 0; + unordered_map prefixToNode; + prefixToNode[0] = &dummy; + + for (; head; head = head->next) { + prefix += head->val; + prefixToNode[prefix] = head; + } + + prefix = 0; + + for (head = &dummy; head; head = head->next) { + prefix += head->val; + head->next = prefixToNode[prefix]->next; + } + + return dummy.next; + } +}; diff --git a/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.java b/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.java new file mode 100644 index 00000000000..2b30c031f5b --- /dev/null +++ b/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.java @@ -0,0 +1,22 @@ +class Solution { + public ListNode removeZeroSumSublists(ListNode head) { + ListNode dummy = new ListNode(0, head); + int prefix = 0; + Map prefixToNode = new HashMap<>(); + prefixToNode.put(0, dummy); + + for (; head != null; head = head.next) { + prefix += head.val; + prefixToNode.put(prefix, head); + } + + prefix = 0; + + for (head = dummy; head != null; head = head.next) { + prefix += head.val; + head.next = prefixToNode.get(prefix).next; + } + + return dummy.next; + } +} diff --git a/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.py b/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.py new file mode 100644 index 00000000000..515fc4c5df6 --- /dev/null +++ b/solutions/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.py @@ -0,0 +1,20 @@ +class Solution: + def removeZeroSumSublists(self, head: ListNode) -> ListNode: + dummy = ListNode(0, head) + prefix = 0 + prefixToNode = {0: dummy} + + while head: + prefix += head.val + prefixToNode[prefix] = head + head = head.next + + prefix = 0 + head = dummy + + while head: + prefix += head.val + head.next = prefixToNode[prefix].next + head = head.next + + return dummy.next diff --git a/solutions/1172. Dinner Plate Stacks/1172.cpp b/solutions/1172. Dinner Plate Stacks/1172.cpp new file mode 100644 index 00000000000..cb246aa5f2f --- /dev/null +++ b/solutions/1172. Dinner Plate Stacks/1172.cpp @@ -0,0 +1,48 @@ +class DinnerPlates { + public: + DinnerPlates(int capacity) : capacity(capacity) { + minHeap.push(0); + } + + void push(int val) { + const int index = minHeap.top(); + // Add a new stack on demand. + if (index == stacks.size()) + stacks.push_back({}); + // Push the new value. + stacks[index].push(val); + // If the stack pushed is full, remove its candidacy from `minHeap`. + if (stacks[index].size() == capacity) { + minHeap.pop(); + // If `minHeap` is empty, the next available stack index is |stacks|. + if (minHeap.empty()) + minHeap.push(stacks.size()); + } + } + + int pop() { + // Remove empty stacks from the back. + while (!stacks.empty() && stacks.back().empty()) + stacks.pop_back(); + if (stacks.empty()) + return -1; + return popAtStack(stacks.size() - 1); + } + + int popAtStack(int index) { + if (index >= stacks.size() || stacks[index].empty()) + return -1; + // If the stack is going to have space, add its candiday to `minHeap`. + if (stacks[index].size() == capacity) + minHeap.push(index); + const int val = stacks[index].top(); + stacks[index].pop(); + return val; + } + + private: + const int capacity; + vector> stacks; + // the minimum indices of the stacks to push + priority_queue, greater<>> minHeap; +}; diff --git a/solutions/1172. Dinner Plate Stacks/1172.java b/solutions/1172. Dinner Plate Stacks/1172.java new file mode 100644 index 00000000000..96c758c457b --- /dev/null +++ b/solutions/1172. Dinner Plate Stacks/1172.java @@ -0,0 +1,44 @@ +class DinnerPlates { + public DinnerPlates(int capacity) { + this.capacity = capacity; + minHeap.offer(0); + } + + public void push(int val) { + final int index = minHeap.peek(); + // Add a new stack on demand. + if (index == stacks.size()) + stacks.add(new ArrayDeque<>()); + // Push the new value. + stacks.get(index).push(val); + // If the stack pushed is full, remove its candidacy from `minHeap`. + if (stacks.get(index).size() == capacity) { + minHeap.poll(); + // If `minHeap` is empty, the next available stack index is |stacks|. + if (minHeap.isEmpty()) + minHeap.offer(stacks.size()); + } + } + + public int pop() { + // Remove empty stacks from the back. + while (!stacks.isEmpty() && stacks.get(stacks.size() - 1).isEmpty()) + stacks.remove(stacks.size() - 1); + if (stacks.isEmpty()) + return -1; + return popAtStack(stacks.size() - 1); + } + + public int popAtStack(int index) { + if (index >= stacks.size() || stacks.get(index).isEmpty()) + return -1; + // If the stack is going to have space, add its candiday to `minHeap`. + if (stacks.get(index).size() == capacity) + minHeap.offer(index); + return stacks.get(index).pop(); + } + + private final int capacity; + private List> stacks = new ArrayList<>(); + private Queue minHeap = new PriorityQueue<>(); +} diff --git a/solutions/1172. Dinner Plate Stacks/1172.py b/solutions/1172. Dinner Plate Stacks/1172.py new file mode 100644 index 00000000000..daea45e167c --- /dev/null +++ b/solutions/1172. Dinner Plate Stacks/1172.py @@ -0,0 +1,35 @@ +class DinnerPlates: + def __init__(self, capacity: int): + self.capacity = capacity + self.stacks = [] + self.minHeap = [0] # the minimum indices of the stacks to push + + def push(self, val: int) -> None: + index = self.minHeap[0] + # Add a new stack on demand. + if index == len(self.stacks): + self.stacks.append([]) + # Push the new value. + self.stacks[index].append(val) + # If the stack pushed is full, remove its candidacy from `minHeap`. + if len(self.stacks[index]) == self.capacity: + heapq.heappop(self.minHeap) + # If `minHeap` is empty, the next available stack index is |stacks|. + if not self.minHeap: + heapq.heappush(self.minHeap, len(self.stacks)) + + def pop(self) -> int: + # Remove empty stacks from the back. + while self.stacks and not self.stacks[-1]: + self.stacks.pop() + if not self.stacks: + return -1 + return self.popAtStack(len(self.stacks) - 1) + + def popAtStack(self, index: int) -> int: + if index >= len(self.stacks) or not self.stacks[index]: + return -1 + # If the stack is going to have space, add its candiday to `minHeap`. + if len(self.stacks[index]) == self.capacity: + heapq.heappush(self.minHeap, index) + return self.stacks[index].pop() diff --git a/solutions/1173. Immediate Food Delivery I/1173.sql b/solutions/1173. Immediate Food Delivery I/1173.sql new file mode 100644 index 00000000000..12b6973e1b7 --- /dev/null +++ b/solutions/1173. Immediate Food Delivery I/1173.sql @@ -0,0 +1,6 @@ +SELECT + ROUND( + 100 * AVG(order_date = customer_pref_delivery_date), + 2 + ) AS immediate_percentage +FROM Delivery; diff --git a/solutions/1174. Immediate Food Delivery II/1174.sql b/solutions/1174. Immediate Food Delivery II/1174.sql new file mode 100644 index 00000000000..004fb5b63b0 --- /dev/null +++ b/solutions/1174. Immediate Food Delivery II/1174.sql @@ -0,0 +1,12 @@ +WITH + CustomerToIsImmediate AS( + SELECT + DISTINCT customer_id, + FIRST_VALUE(order_date = customer_pref_delivery_date) OVER( + PARTITION BY customer_id + ORDER BY order_date + ) is_immediate + FROM Delivery + ) +SELECT ROUND(AVG(is_immediate) * 100, 2) immediate_percentage +FROM CustomerToIsImmediate; diff --git a/solutions/1175. Prime Arrangements/1175.cpp b/solutions/1175. Prime Arrangements/1175.cpp new file mode 100644 index 00000000000..b0012b1be1a --- /dev/null +++ b/solutions/1175. Prime Arrangements/1175.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int numPrimeArrangements(int n) { + constexpr int kMod = 1'000'000'007; + const int count = countPrimes(n); + return (factorial(count, kMod) * factorial(n - count, kMod)) % kMod; + } + + private: + int countPrimes(int n) { + vector prime(n + 1, true); + prime[0] = false; + prime[1] = false; + + for (int i = 0; i <= sqrt(n); ++i) + if (prime[i]) + for (int j = i * i; j <= n; j += i) + prime[j] = false; + + return ranges::count(prime, true); + } + + long factorial(int n, const int kMod) { + long fact = 1; + for (int i = 1; i <= n; ++i) + fact = fact * i % kMod; + return fact; + } +}; diff --git a/solutions/1175. Prime Arrangements/1175.java b/solutions/1175. Prime Arrangements/1175.java new file mode 100644 index 00000000000..4e69786805c --- /dev/null +++ b/solutions/1175. Prime Arrangements/1175.java @@ -0,0 +1,32 @@ +class Solution { + public int numPrimeArrangements(int n) { + final int kMod = 1_000_000_007; + final int count = countPrimes(n); + return (int) ((factorial(count, kMod) * factorial(n - count, kMod)) % kMod); + } + + private int countPrimes(int n) { + boolean[] prime = new boolean[n + 1]; + Arrays.fill(prime, 2, n + 1, true); + + for (int i = 0; i * i <= n; ++i) + if (prime[i]) + for (int j = i * i; j <= n; j += i) + prime[j] = false; + + int count = 0; + + for (boolean p : prime) + if (p) + ++count; + + return count; + } + + long factorial(int n, final long kMod) { + long fact = 1; + for (int i = 1; i <= n; ++i) + fact = fact * i % kMod; + return fact; + } +} diff --git a/solutions/1175. Prime Arrangements/1175.py b/solutions/1175. Prime Arrangements/1175.py new file mode 100644 index 00000000000..b97d1481f52 --- /dev/null +++ b/solutions/1175. Prime Arrangements/1175.py @@ -0,0 +1,24 @@ +class Solution: + def numPrimeArrangements(self, n: int) -> int: + kMod = 1_000_000_007 + + def countPrimes(n: int) -> int: + isPrime = [False] * 2 + [True] * (n - 1) + + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n + 1, i): + isPrime[j] = False + + return sum(isPrime) + + def factorial(n: int) -> int: + fact = 1 + + for i in range(1, n + 1): + fact = fact * i % kMod + + return fact + + count = countPrimes(n) + return factorial(count) * factorial(n - count) % kMod diff --git a/solutions/1176. Diet Plan Performance/1176.cpp b/solutions/1176. Diet Plan Performance/1176.cpp new file mode 100644 index 00000000000..8bce045c91a --- /dev/null +++ b/solutions/1176. Diet Plan Performance/1176.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int dietPlanPerformance(vector& calories, int k, int lower, int upper) { + int ans = 0; + int sum = 0; + + for (int i = 0; i < calories.size(); ++i) { + sum += calories[i]; + if (i < k - 1) + continue; + if (i >= k) + sum -= calories[i - k]; + if (sum < lower) + --ans; + else if (sum > upper) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1176. Diet Plan Performance/1176.java b/solutions/1176. Diet Plan Performance/1176.java new file mode 100644 index 00000000000..0076faf7cd5 --- /dev/null +++ b/solutions/1176. Diet Plan Performance/1176.java @@ -0,0 +1,20 @@ +class Solution { + public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { + int ans = 0; + int sum = 0; + + for (int i = 0; i < calories.length; ++i) { + sum += calories[i]; + if (i < k - 1) + continue; + if (i >= k) + sum -= calories[i - k]; + if (sum < lower) + --ans; + else if (sum > upper) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1176. Diet Plan Performance/1176.py b/solutions/1176. Diet Plan Performance/1176.py new file mode 100644 index 00000000000..fb904de55a8 --- /dev/null +++ b/solutions/1176. Diet Plan Performance/1176.py @@ -0,0 +1,17 @@ +class Solution: + def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int: + ans = 0 + summ = 0 + + for i, calorie in enumerate(calories): + summ += calorie + if i < k - 1: + continue + if i >= k: + summ -= calories[i - k] + if summ < lower: + ans -= 1 + elif summ > upper: + ans += 1 + + return ans diff --git a/solutions/1177. Can Make Palindrome from Substring/1177.cpp b/solutions/1177. Can Make Palindrome from Substring/1177.cpp new file mode 100644 index 00000000000..3c64ed5e194 --- /dev/null +++ b/solutions/1177. Can Make Palindrome from Substring/1177.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector canMakePaliQueries(string s, vector>& queries) { + vector ans; + vector dp(s.length() + 1); + + for (int i = 1; i <= s.length(); ++i) + dp[i] = dp[i - 1] ^ 1 << s[i - 1] - 'a'; + + for (const vector& query : queries) { + const int odds = popcount(dp[query[1] + 1] ^ dp[query[0]]); + ans.push_back(odds / 2 <= query[2]); + } + + return ans; + } +}; diff --git a/solutions/1177. Can Make Palindrome from Substring/1177.java b/solutions/1177. Can Make Palindrome from Substring/1177.java new file mode 100644 index 00000000000..3ee496a3086 --- /dev/null +++ b/solutions/1177. Can Make Palindrome from Substring/1177.java @@ -0,0 +1,16 @@ +class Solution { + public List canMakePaliQueries(String s, int[][] queries) { + List ans = new ArrayList<>(); + int[] dp = new int[s.length() + 1]; + + for (int i = 1; i <= s.length(); ++i) + dp[i] = dp[i - 1] ^ 1 << s.charAt(i - 1) - 'a'; + + for (int[] query : queries) { + int odds = Integer.bitCount(dp[query[1] + 1] ^ dp[query[0]]); + ans.add(odds / 2 <= query[2]); + } + + return ans; + } +} diff --git a/solutions/1177. Can Make Palindrome from Substring/1177.py b/solutions/1177. Can Make Palindrome from Substring/1177.py new file mode 100644 index 00000000000..2abb5149279 --- /dev/null +++ b/solutions/1177. Can Make Palindrome from Substring/1177.py @@ -0,0 +1,11 @@ +class Solution: + def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: + dp = [0] * (len(s) + 1) + + for i in range(1, len(s) + 1): + dp[i] = dp[i - 1] ^ 1 << ord(s[i - 1]) - ord('a') + + return [ + (dp[right + 1] ^ dp[left]).bit_count() // 2 <= k + for left, right, k in queries + ] diff --git a/solutions/1178. Number of Valid Words for Each Puzzle/1178.cpp b/solutions/1178. Number of Valid Words for Each Puzzle/1178.cpp new file mode 100644 index 00000000000..93d88e663cf --- /dev/null +++ b/solutions/1178. Number of Valid Words for Each Puzzle/1178.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector findNumOfValidWords(vector& words, + vector& puzzles) { + vector ans; + unordered_map binaryCount; + + for (const string& word : words) { + int mask = 0; + for (char c : word) + mask |= 1 << c - 'a'; + ++binaryCount[mask]; + } + + for (const string& puzzle : puzzles) { + int valid = 0; + const int n = puzzle.length() - 1; + for (int i = 0; i < (1 << n); ++i) { + int mask = 1 << puzzle[0] - 'a'; + for (int j = 0; j < n; ++j) + if (i >> j & 1) + mask |= 1 << puzzle[j + 1] - 'a'; + if (const auto it = binaryCount.find(mask); it != binaryCount.cend()) + valid += it->second; + } + ans.push_back(valid); + } + + return ans; + } +}; diff --git a/solutions/1178. Number of Valid Words for Each Puzzle/1178.java b/solutions/1178. Number of Valid Words for Each Puzzle/1178.java new file mode 100644 index 00000000000..60e374292e9 --- /dev/null +++ b/solutions/1178. Number of Valid Words for Each Puzzle/1178.java @@ -0,0 +1,29 @@ +class Solution { + public List findNumOfValidWords(String[] words, String[] puzzles) { + List ans = new ArrayList<>(); + Map binaryCount = new HashMap<>(); + + for (final String word : words) { + int mask = 0; + for (char c : word.toCharArray()) + mask |= 1 << (c - 'a'); + binaryCount.merge(mask, 1, Integer::sum); + } + + for (final String puzzle : puzzles) { + int valid = 0; + final int n = puzzle.length() - 1; + for (int i = 0; i < (1 << n); ++i) { + int mask = 1 << puzzle.charAt(0) - 'a'; + for (int j = 0; j < n; ++j) + if ((i >> j & 1) == 1) + mask |= 1 << puzzle.charAt(j + 1) - 'a'; + if (binaryCount.containsKey(mask)) + valid += binaryCount.get(mask); + } + ans.add(valid); + } + + return ans; + } +} diff --git a/solutions/1178. Number of Valid Words for Each Puzzle/1178.py b/solutions/1178. Number of Valid Words for Each Puzzle/1178.py new file mode 100644 index 00000000000..36602c6febd --- /dev/null +++ b/solutions/1178. Number of Valid Words for Each Puzzle/1178.py @@ -0,0 +1,24 @@ +class Solution: + def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: + ans = [] + binaryCount = collections.Counter() + + for word in words: + mask = 0 + for c in word: + mask |= 1 << (ord(c) - ord('a')) + binaryCount[mask] += 1 + + for puzzle in puzzles: + valid = 0 + n = len(puzzle) - 1 + for i in range(1 << n): + mask = 1 << ord(puzzle[0]) - ord('a') + for j in range(n): + if i >> j & 1: + mask |= 1 << ord(puzzle[j + 1]) - ord('a') + if mask in binaryCount: + valid += binaryCount[mask] + ans.append(valid) + + return ans diff --git a/solutions/1179. Reformat Department Table/1179.sql b/solutions/1179. Reformat Department Table/1179.sql new file mode 100644 index 00000000000..6b99bab83f4 --- /dev/null +++ b/solutions/1179. Reformat Department Table/1179.sql @@ -0,0 +1,16 @@ +SELECT + id, + SUM(IF(month = 'Jan', revenue, NULL)) AS Jan_Revenue, + SUM(IF(month = 'Feb', revenue, NULL)) AS Feb_Revenue, + SUM(IF(month = 'Mar', revenue, NULL)) AS Mar_Revenue, + SUM(IF(month = 'Apr', revenue, NULL)) AS Apr_Revenue, + SUM(IF(month = 'May', revenue, NULL)) AS May_Revenue, + SUM(IF(month = 'Jun', revenue, NULL)) AS Jun_Revenue, + SUM(IF(month = 'Jul', revenue, NULL)) AS Jul_Revenue, + SUM(IF(month = 'Aug', revenue, NULL)) AS Aug_Revenue, + SUM(IF(month = 'Sep', revenue, NULL)) AS Sep_Revenue, + SUM(IF(month = 'Oct', revenue, NULL)) AS Oct_Revenue, + SUM(IF(month = 'Nov', revenue, NULL)) AS Nov_Revenue, + SUM(IF(month = 'Dec', revenue, NULL)) AS Dec_Revenue +FROM Department +GROUP BY 1; diff --git a/solutions/118. Pascal's Triangle/118.cpp b/solutions/118. Pascal's Triangle/118.cpp new file mode 100644 index 00000000000..6ec35e7d8cf --- /dev/null +++ b/solutions/118. Pascal's Triangle/118.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector> generate(int numRows) { + vector> ans; + + for (int i = 0; i < numRows; ++i) + ans.push_back(vector(i + 1, 1)); + + for (int i = 2; i < numRows; ++i) + for (int j = 1; j < ans[i].size() - 1; ++j) + ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]; + + return ans; + } +}; diff --git a/solutions/118. Pascal's Triangle/118.java b/solutions/118. Pascal's Triangle/118.java new file mode 100644 index 00000000000..a8813c9c6ed --- /dev/null +++ b/solutions/118. Pascal's Triangle/118.java @@ -0,0 +1,17 @@ +class Solution { + public List> generate(int numRows) { + List> ans = new ArrayList<>(); + + for (int i = 0; i < numRows; ++i) { + Integer[] temp = new Integer[i + 1]; + Arrays.fill(temp, 1); + ans.add(Arrays.asList(temp)); + } + + for (int i = 2; i < numRows; ++i) + for (int j = 1; j < ans.get(i).size() - 1; ++j) + ans.get(i).set(j, ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j)); + + return ans; + } +} diff --git a/solutions/118. Pascal's Triangle/118.py b/solutions/118. Pascal's Triangle/118.py new file mode 100644 index 00000000000..0504cffe2b3 --- /dev/null +++ b/solutions/118. Pascal's Triangle/118.py @@ -0,0 +1,12 @@ +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + ans = [] + + for i in range(numRows): + ans.append([1] * (i + 1)) + + for i in range(2, numRows): + for j in range(1, len(ans[i]) - 1): + ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j] + + return ans diff --git a/solutions/1180. Count Substrings with Only One Distinct Letter/1180.cpp b/solutions/1180. Count Substrings with Only One Distinct Letter/1180.cpp new file mode 100644 index 00000000000..b8a73e0fd7a --- /dev/null +++ b/solutions/1180. Count Substrings with Only One Distinct Letter/1180.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countLetters(string s) { + int ans = 0; + int dp = 0; // the length of the running letter + char letter = '@'; // the running letter + + for (const char c : s) { + if (c == letter) { + ++dp; + } else { + dp = 1; + letter = c; + } + // Add the number of substrings ending in the current letter. + ans += dp; + } + + return ans; + } +}; diff --git a/solutions/1180. Count Substrings with Only One Distinct Letter/1180.java b/solutions/1180. Count Substrings with Only One Distinct Letter/1180.java new file mode 100644 index 00000000000..28bacf6291f --- /dev/null +++ b/solutions/1180. Count Substrings with Only One Distinct Letter/1180.java @@ -0,0 +1,20 @@ +class Solution { + public int countLetters(String s) { + int ans = 0; + int dp = 0; // the length of the running letter + char letter = '@'; // the running letter + + for (final char c : s.toCharArray()) { + if (c == letter) { + ++dp; + } else { + dp = 1; + letter = c; + } + // Add the number of substrings ending in the current letter. + ans += dp; + } + + return ans; + } +} diff --git a/solutions/1180. Count Substrings with Only One Distinct Letter/1180.py b/solutions/1180. Count Substrings with Only One Distinct Letter/1180.py new file mode 100644 index 00000000000..b4d036b98a7 --- /dev/null +++ b/solutions/1180. Count Substrings with Only One Distinct Letter/1180.py @@ -0,0 +1,15 @@ +class Solution: + def countLetters(self, s: str) -> int: + ans = 0 + dp = 0 # the length of the running letter + letter = '@' # the running letter + + for c in s: + if c == letter: + dp += 1 + else: + dp = 1 + letter = c + ans += dp # Add the number of substrings ending in the current letter. + + return ans diff --git a/solutions/1181. Before and After Puzzle/1181.cpp b/solutions/1181. Before and After Puzzle/1181.cpp new file mode 100644 index 00000000000..793843dbd4d --- /dev/null +++ b/solutions/1181. Before and After Puzzle/1181.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + vector beforeAndAfterPuzzles(vector& phrases) { + set ans; + unordered_map> firstWordToLasts; + unordered_map> lastWordToFirsts; + + for (const string& phrase : phrases) { + const int firstSpaceIndex = phrase.find(' '); + const int lastSpaceIndex = phrase.rfind(' '); + // the index after the firstWord + const int i = + firstSpaceIndex == string::npos ? phrase.length() : firstSpaceIndex; + // the index of the lastWord + const int j = lastSpaceIndex == string::npos ? 0 : lastSpaceIndex + 1; + const string firstWord = phrase.substr(0, i); + const string lastWord = phrase.substr(j); + + // Concatenate `phrase` with `last` having the same `firstWord`. + if (const auto it = firstWordToLasts.find(lastWord); + it != firstWordToLasts.cend()) + for (const string& last : it->second) + ans.insert(phrase + last); + + // Concatenate `first` having the same `lastWord` with `phrase`. + if (const auto it = lastWordToFirsts.find(firstWord); + it != lastWordToFirsts.cend()) + for (const string& first : it->second) + ans.insert(first + phrase); + + // e.g. "a b c" -> {"a": " b c"} + // "a" -> {"a": ""} + firstWordToLasts[firstWord].insert(phrase.substr(i)); + + // e.g. "a b c" -> {"c": "a b "} + // "a" -> {"a": ""} + lastWordToFirsts[lastWord].insert(phrase.substr(0, j)); + } + + return {ans.begin(), ans.end()}; + } +}; diff --git a/solutions/1182. Shortest Distance to Target Color/1182.cpp b/solutions/1182. Shortest Distance to Target Color/1182.cpp new file mode 100644 index 00000000000..51c14591f07 --- /dev/null +++ b/solutions/1182. Shortest Distance to Target Color/1182.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector shortestDistanceColor(vector& colors, + vector>& queries) { + constexpr int kNumColor = 3; + const int n = colors.size(); + vector ans; + // left[i][c] := the closest index of color c in index i to the left + vector> left(n, vector(kNumColor + 1)); + // right[i][c] := the closest index of color c in index i to the right + vector> right(n, vector(kNumColor + 1)); + + vector colorToClosestIndex{0, -1, -1, -1}; // 0-indexed, -1 := N/A + for (int i = 0; i < n; ++i) { + colorToClosestIndex[colors[i]] = i; + for (int c = 1; c <= kNumColor; ++c) + left[i][c] = colorToClosestIndex[c]; + } + + colorToClosestIndex = {0, -1, -1, -1}; // Reset. + for (int i = n - 1; i >= 0; --i) { + colorToClosestIndex[colors[i]] = i; + for (int c = 1; c <= kNumColor; ++c) + right[i][c] = colorToClosestIndex[c]; + } + + for (const vector& query : queries) { + const int i = query[0]; + const int c = query[1]; + const int leftDist = left[i][c] == -1 ? INT_MAX : i - left[i][c]; + const int rightDist = right[i][c] == -1 ? INT_MAX : right[i][c] - i; + const int minDist = min(leftDist, rightDist); + ans.push_back(minDist == INT_MAX ? -1 : minDist); + } + + return ans; + } +}; diff --git a/solutions/1182. Shortest Distance to Target Color/1182.java b/solutions/1182. Shortest Distance to Target Color/1182.java new file mode 100644 index 00000000000..d0d96ddbca6 --- /dev/null +++ b/solutions/1182. Shortest Distance to Target Color/1182.java @@ -0,0 +1,36 @@ +class Solution { + public List shortestDistanceColor(int[] colors, int[][] queries) { + final int kNumColor = 3; + final int n = colors.length; + List ans = new ArrayList<>(); + // left[i][c] := the closest index of color c in index i to the left + int[][] left = new int[n][kNumColor + 1]; + // right[i][c] := the closest index of color c in index i to the right + int[][] right = new int[n][kNumColor + 1]; + + int[] colorToClosestIndex = {0, -1, -1, -1}; // 0-indexed, -1 := N/A + for (int i = 0; i < n; ++i) { + colorToClosestIndex[colors[i]] = i; + for (int c = 1; c <= kNumColor; ++c) + left[i][c] = colorToClosestIndex[c]; + } + + colorToClosestIndex = {0, -1, -1, -1}; // Reset + for (int i = n - 1; i >= 0; --i) { + colorToClosestIndex[colors[i]] = i; + for (int c = 1; c <= kNumColor; ++c) + right[i][c] = colorToClosestIndex[c]; + } + + for (int[] query : queries) { + final int i = query[0]; + final int c = query[1]; + final int leftDist = left[i][c] == -1 ? Integer.MAX_VALUE : i - left[i][c]; + final int rightDist = right[i][c] == -1 ? Integer.MAX_VALUE : right[i][c] - i; + final int minDist = Math.min(leftDist, rightDist); + ans.add(minDist == Integer.MAX_VALUE ? -1 : minDist); + } + + return ans; + } +} diff --git a/solutions/1182. Shortest Distance to Target Color/1182.py b/solutions/1182. Shortest Distance to Target Color/1182.py new file mode 100644 index 00000000000..9bd5f2a04e1 --- /dev/null +++ b/solutions/1182. Shortest Distance to Target Color/1182.py @@ -0,0 +1,29 @@ +class Solution: + def shortestDistanceColor(self, colors: List[int], queries: List[List[int]]) -> List[int]: + kNumColor = 3 + n = len(colors) + ans = [] + # left[i][c] := the closest index of color c in index i to the left + left = [[0] * (kNumColor + 1) for _ in range(n)] + # right[i][c] := the closest index of color c in index i to the right + right = [[0] * (kNumColor + 1) for _ in range(n)] + + colorToLatestIndex = [0, -1, -1, -1] # 0-indexed, -1 means N//A + for i, color in enumerate(colors): + colorToLatestIndex[color] = i + for c in range(1, kNumColor + 1): + left[i][c] = colorToLatestIndex[c] + + colorToLatestIndex = [0, -1, -1, -1] # Reset. + for i in range(n - 1, -1, -1): + colorToLatestIndex[colors[i]] = i + for c in range(1, kNumColor + 1): + right[i][c] = colorToLatestIndex[c] + + for i, c in queries: + leftDist = math.inf if left[i][c] == -1 else i - left[i][c] + rightDist = math.inf if right[i][c] == -1 else right[i][c] - i + minDist = min(leftDist, rightDist) + ans.append(-1 if minDist == math.inf else minDist) + + return ans diff --git a/solutions/1183. Maximum Number of Ones/1183-2.cpp b/solutions/1183. Maximum Number of Ones/1183-2.cpp new file mode 100644 index 00000000000..4cac519aa15 --- /dev/null +++ b/solutions/1183. Maximum Number of Ones/1183-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) { + vector subCount; + + auto getCount = [&](int length, int index) -> int { + return (length - index - 1) / sideLength + 1; + }; + + for (int i = 0; i < sideLength; ++i) + for (int j = 0; j < sideLength; ++j) + subCount.push_back(getCount(width, i) * getCount(height, j)); + + ranges::sort(subCount, greater<>()); + return accumulate(subCount.begin(), subCount.begin() + maxOnes, 0); + } +}; diff --git a/solutions/1183. Maximum Number of Ones/1183-2.java b/solutions/1183. Maximum Number of Ones/1183-2.java new file mode 100644 index 00000000000..e4d16704e99 --- /dev/null +++ b/solutions/1183. Maximum Number of Ones/1183-2.java @@ -0,0 +1,21 @@ +class Solution { + public int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) { + int ans = 0; + List subCount = new ArrayList<>(); + + for (int i = 0; i < sideLength; ++i) + for (int j = 0; j < sideLength; ++j) + subCount.add(getCount(width, i, sideLength) * getCount(height, j, sideLength)); + + Collections.sort(subCount, Collections.reverseOrder()); + + for (int i = 0; i < maxOnes; ++i) + ans += subCount.get(i); + + return ans; + } + + private int getCount(int length, int index, int sideLength) { + return (length - index - 1) / sideLength + 1; + } +} diff --git a/solutions/1183. Maximum Number of Ones/1183-2.py b/solutions/1183. Maximum Number of Ones/1183-2.py new file mode 100644 index 00000000000..04ea3edfd8b --- /dev/null +++ b/solutions/1183. Maximum Number of Ones/1183-2.py @@ -0,0 +1,12 @@ +class Solution: + def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int: + subCount = [] + + def getCount(length: int, index: int) -> int: + return (length - index - 1) // sideLength + 1 + + for i in range(sideLength): + for j in range(sideLength): + subCount.append(getCount(width, i) * getCount(height, j)) + + return sum(sorted(subCount, reverse=True)[:maxOnes]) diff --git a/solutions/1183. Maximum Number of Ones/1183.cpp b/solutions/1183. Maximum Number of Ones/1183.cpp new file mode 100644 index 00000000000..032a887cd8a --- /dev/null +++ b/solutions/1183. Maximum Number of Ones/1183.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) { + int ans = 0; + vector> submatrix(sideLength, vector(sideLength)); + priority_queue maxHeap; + + for (int i = 0; i < width; ++i) + for (int j = 0; j < height; ++j) + ++submatrix[i % sideLength][j % sideLength]; + + for (const vector& row : submatrix) + for (const int a : row) + maxHeap.push(a); + + for (int i = 0; i < maxOnes; ++i) + ans += maxHeap.top(), maxHeap.pop(); + + return ans; + } +}; diff --git a/solutions/1183. Maximum Number of Ones/1183.java b/solutions/1183. Maximum Number of Ones/1183.java new file mode 100644 index 00000000000..66ac108da51 --- /dev/null +++ b/solutions/1183. Maximum Number of Ones/1183.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) { + int ans = 0; + int[][] submatrix = new int[sideLength][sideLength]; + Queue maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); + + for (int i = 0; i < width; ++i) + for (int j = 0; j < height; ++j) + ++submatrix[i % sideLength][j % sideLength]; + + for (int[] row : submatrix) + for (final int a : row) + maxHeap.offer(a); + + for (int i = 0; i < maxOnes; ++i) + ans += maxHeap.poll(); + + return ans; + } +} diff --git a/solutions/1183. Maximum Number of Ones/1183.py b/solutions/1183. Maximum Number of Ones/1183.py new file mode 100644 index 00000000000..2b5c6bbb8c3 --- /dev/null +++ b/solutions/1183. Maximum Number of Ones/1183.py @@ -0,0 +1,9 @@ +class Solution: + def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int: + submatrix = [[0] * sideLength for _ in range(sideLength)] + + for i in range(width): + for j in range(height): + submatrix[i % sideLength][j % sideLength] += 1 + + return sum(heapq.nlargest(maxOnes, [a for row in submatrix for a in row])) diff --git a/solutions/1184. Distance Between Bus Stops/1184.cpp b/solutions/1184. Distance Between Bus Stops/1184.cpp new file mode 100644 index 00000000000..8e6e3790b15 --- /dev/null +++ b/solutions/1184. Distance Between Bus Stops/1184.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int distanceBetweenBusStops(vector& distance, int start, + int destination) { + int clockwise = 0; + int counterclockwise = 0; + + if (start > destination) + swap(start, destination); + + for (int i = 0; i < distance.size(); ++i) { + if (i >= start && i < destination) + clockwise += distance[i]; + else + counterclockwise += distance[i]; + } + + return min(clockwise, counterclockwise); + } +}; diff --git a/solutions/1184. Distance Between Bus Stops/1184.java b/solutions/1184. Distance Between Bus Stops/1184.java new file mode 100644 index 00000000000..faab71758e0 --- /dev/null +++ b/solutions/1184. Distance Between Bus Stops/1184.java @@ -0,0 +1,21 @@ +class Solution { + public int distanceBetweenBusStops(int[] distance, int start, int destination) { + int clockwise = 0; + int counterclockwise = 0; + + if (start > destination) { + int temp = start; + start = destination; + destination = temp; + } + + for (int i = 0; i < distance.length; ++i) { + if (i >= start && i < destination) + clockwise += distance[i]; + else + counterclockwise += distance[i]; + } + + return Math.min(clockwise, counterclockwise); + } +} diff --git a/solutions/1184. Distance Between Bus Stops/1184.py b/solutions/1184. Distance Between Bus Stops/1184.py new file mode 100644 index 00000000000..2b4d42a32a6 --- /dev/null +++ b/solutions/1184. Distance Between Bus Stops/1184.py @@ -0,0 +1,15 @@ +class Solution: + def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: + clockwise = 0 + counterclockwise = 0 + + if start > destination: + start, destination = destination, start + + for i, d in enumerate(distance): + if i >= start and i < destination: + clockwise += d + else: + counterclockwise += d + + return min(clockwise, counterclockwise) diff --git a/solutions/1185. Day of the Week/1185.cpp b/solutions/1185. Day of the Week/1185.cpp new file mode 100644 index 00000000000..e290135d064 --- /dev/null +++ b/solutions/1185. Day of the Week/1185.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + string dayOfTheWeek(int day, int month, int year) { + vector week = {"Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday"}; + vector days = { + 31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int count = 0; + + for (int i = 1971; i < year; ++i) + count += i % 4 == 0 ? 366 : 365; + for (int i = 0; i < month - 1; ++i) + count += days[i]; + count += day; + + return week[(count + 4) % 7]; + } + + private: + bool isLeapYear(int year) { + return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + } +}; diff --git a/solutions/1185. Day of the Week/1185.java b/solutions/1185. Day of the Week/1185.java new file mode 100644 index 00000000000..5cbec46a88b --- /dev/null +++ b/solutions/1185. Day of the Week/1185.java @@ -0,0 +1,19 @@ +class Solution { + public String dayOfTheWeek(int day, int month, int year) { + String[] week = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + int[] days = {31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int count = 0; + + for (int i = 1971; i < year; ++i) + count += i % 4 == 0 ? 366 : 365; + for (int i = 0; i < month - 1; ++i) + count += days[i]; + count += day; + + return week[(count + 4) % 7]; + } + + private boolean isLeapYear(int year) { + return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + } +} diff --git a/solutions/1185. Day of the Week/1185.py b/solutions/1185. Day of the Week/1185.py new file mode 100644 index 00000000000..e80ecbbc56d --- /dev/null +++ b/solutions/1185. Day of the Week/1185.py @@ -0,0 +1,18 @@ +class Solution: + def dayOfTheWeek(self, day: int, month: int, year: int) -> str: + def isLeapYear(year: int) -> bool: + return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 + + week = ["Sunday", "Monday", "Tuesday", + "Wednesday", "Thursday", "Friday", "Saturday"] + days = [31, 29 if isLeapYear( + year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + count = 0 + + for i in range(1971, year): + count += 366 if i % 4 == 0 else 365 + for i in range(month - 1): + count += days[i] + count += day + + return week[(count + 4) % 7] diff --git a/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.cpp b/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.cpp new file mode 100644 index 00000000000..10d30756e2e --- /dev/null +++ b/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + // Similar to 53. Maximum Subarray + int maximumSum(vector& arr) { + constexpr int kMin = INT_MIN / 2; + int ans = kMin; + int zero = kMin; // no deletion + int one = kMin; // <= 1 deletion + + for (const int a : arr) { + one = max({a, one + a, zero /*delete a*/}); + zero = max(a, zero + a); + ans = max(ans, one); + } + + return ans; + } +}; diff --git a/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.java b/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.java new file mode 100644 index 00000000000..d30f2a1a54a --- /dev/null +++ b/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.java @@ -0,0 +1,17 @@ +class Solution { + // Similar to 53. Maximum Subarray + public int maximumSum(int[] arr) { + final int kMin = Integer.MIN_VALUE / 2; + int ans = kMin; + int zero = kMin; // no deletion + int one = kMin; // <= 1 deletion + + for (final int a : arr) { + one = Math.max(a, Math.max(one + a, zero /*delete a*/)); + zero = Math.max(a, zero + a); + ans = Math.max(ans, one); + } + + return ans; + } +} diff --git a/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.py b/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.py new file mode 100644 index 00000000000..bdb7c8571cc --- /dev/null +++ b/solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.py @@ -0,0 +1,13 @@ +class Solution: + # Very similar to 53. Maximum Subarray + def maximumSum(self, arr: List[int]) -> int: + ans = -math.inf + zero = -math.inf # no deletion + one = -math.inf # <= 1 deletion + + for a in arr: + one = max(a, one + a, zero) + zero = max(a, zero + a) + ans = max(ans, one) + + return ans diff --git a/solutions/1186. Maximum Subarray Sum with One Deletion/1186.cpp b/solutions/1186. Maximum Subarray Sum with One Deletion/1186.cpp new file mode 100644 index 00000000000..a9ba0b5cb8e --- /dev/null +++ b/solutions/1186. Maximum Subarray Sum with One Deletion/1186.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + // Similar to 53. Maximum Subarray + int maximumSum(vector& arr) { + // dp[0][i] := the maximum sum subarray ending in i (no deletion) + // dp[1][i] := the maximum sum subarray ending in i (at most 1 deletion) + vector> dp(2, vector(arr.size())); + + dp[0][0] = arr[0]; + dp[1][0] = arr[0]; + for (int i = 1; i < arr.size(); ++i) { + dp[0][i] = max(arr[i], dp[0][i - 1] + arr[i]); + dp[1][i] = + max({arr[i], dp[1][i - 1] + arr[i], dp[0][i - 1] /*delete arr[i]*/}); + } + + return ranges::max(dp[1]); + } +}; diff --git a/solutions/1186. Maximum Subarray Sum with One Deletion/1186.java b/solutions/1186. Maximum Subarray Sum with One Deletion/1186.java new file mode 100644 index 00000000000..598cff12e41 --- /dev/null +++ b/solutions/1186. Maximum Subarray Sum with One Deletion/1186.java @@ -0,0 +1,17 @@ +class Solution { + // Similar to 53. Maximum Subarray + public int maximumSum(int[] arr) { + // dp[0][i] := the maximum sum subarray ending in i (no deletion) + // dp[1][i] := the maximum sum subarray ending in i (at most 1 deletion) + int[][] dp = new int[2][arr.length]; + + dp[0][0] = arr[0]; + dp[1][0] = arr[0]; + for (int i = 1; i < arr.length; ++i) { + dp[0][i] = Math.max(arr[i], dp[0][i - 1] + arr[i]); + dp[1][i] = Math.max(arr[i], Math.max(dp[1][i - 1] + arr[i], dp[0][i - 1] /*delete arr[i]*/)); + } + + return Arrays.stream(dp[1]).max().getAsInt(); + } +} diff --git a/solutions/1186. Maximum Subarray Sum with One Deletion/1186.py b/solutions/1186. Maximum Subarray Sum with One Deletion/1186.py new file mode 100644 index 00000000000..591e45e36e2 --- /dev/null +++ b/solutions/1186. Maximum Subarray Sum with One Deletion/1186.py @@ -0,0 +1,14 @@ +class Solution: + # Very similar to 53. Maximum Subarray + def maximumSum(self, arr: List[int]) -> int: + # dp[0][i] := the maximum sum subarray ending in i (no deletion) + # dp[1][i] := the maximum sum subarray ending in i (at most 1 deletion) + dp = [[0] * len(arr) for _ in range(2)] + + dp[0][0] = arr[0] + dp[1][0] = arr[0] + for i in range(1, len(arr)): + dp[0][i] = max(arr[i], dp[0][i - 1] + arr[i]) + dp[1][i] = max(arr[i], dp[1][i - 1] + arr[i], dp[0][i - 1]) + + return max(dp[1]) diff --git a/solutions/1187. Make Array Strictly Increasing/1187.cpp b/solutions/1187. Make Array Strictly Increasing/1187.cpp new file mode 100644 index 00000000000..186b34425be --- /dev/null +++ b/solutions/1187. Make Array Strictly Increasing/1187.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int makeArrayIncreasing(vector& arr1, vector& arr2) { + // dp[i] := the minimum steps to reach i at previous round + unordered_map dp{{-1, 0}}; + + ranges::sort(arr2); + + for (const int a : arr1) { + unordered_map nextDp; + for (const auto& [val, steps] : dp) { + // It's possible to use the value in the arr1. + if (a > val) + nextDp[a] = min(nextDp.contains(a) ? nextDp[a] : INT_MAX, steps); + // Also try the value in the arr2. + if (const auto it = ranges::upper_bound(arr2, val); it != arr2.cend()) + nextDp[*it] = + min(nextDp.contains(*it) ? nextDp[*it] : INT_MAX, steps + 1); + } + if (nextDp.empty()) + return -1; + dp = move(nextDp); + } + + int ans = INT_MAX; + for (const auto& [_, steps] : dp) + ans = min(ans, steps); + return ans; + } +}; diff --git a/solutions/1187. Make Array Strictly Increasing/1187.java b/solutions/1187. Make Array Strictly Increasing/1187.java new file mode 100644 index 00000000000..f729cc98742 --- /dev/null +++ b/solutions/1187. Make Array Strictly Increasing/1187.java @@ -0,0 +1,33 @@ +class Solution { + public int makeArrayIncreasing(int[] arr1, int[] arr2) { + // dp[i] := the minimum steps to reach i at previous round + Map dp = new HashMap<>(); + dp.put(-1, 0); + + Arrays.sort(arr2); + + for (final int a : arr1) { + Map nextDp = new HashMap<>(); + for (final int val : dp.keySet()) { + final int steps = dp.get(val); + // It's possible to use the value in the arr1. + if (a > val) + nextDp.put(a, Math.min(nextDp.getOrDefault(a, Integer.MAX_VALUE), steps)); + // Also try the value in the arr2. + final int i = firstGreater(arr2, val); + if (i < arr2.length) + nextDp.put(arr2[i], Math.min(nextDp.getOrDefault(arr2[i], Integer.MAX_VALUE), steps + 1)); + } + if (nextDp.isEmpty()) + return -1; + dp = nextDp; + } + + return Collections.min(dp.values()); + } + + private int firstGreater(int[] A, int target) { + final int i = Arrays.binarySearch(A, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/1187. Make Array Strictly Increasing/1187.py b/solutions/1187. Make Array Strictly Increasing/1187.py new file mode 100644 index 00000000000..e253000e894 --- /dev/null +++ b/solutions/1187. Make Array Strictly Increasing/1187.py @@ -0,0 +1,22 @@ +class Solution: + def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: + # dp[i] := the minimum steps to reach i at previous round + dp = {-1: 0} + + arr2.sort() + + for a in arr1: + nextDp = collections.defaultdict(lambda: math.inf) + for val, steps in dp.items(): + # It's possible to use the value in the arr1. + if a > val: + nextDp[a] = min(nextDp[a], steps) + # Also try the value in the arr2. + i = bisect_right(arr2, val) + if i < len(arr2): + nextDp[arr2[i]] = min(nextDp[arr2[i]], steps + 1) + if not nextDp: + return -1 + dp = nextDp + + return min(dp.values()) diff --git a/solutions/1188. Design Bounded Blocking Queue/1188.cpp b/solutions/1188. Design Bounded Blocking Queue/1188.cpp new file mode 100644 index 00000000000..17773df542b --- /dev/null +++ b/solutions/1188. Design Bounded Blocking Queue/1188.cpp @@ -0,0 +1,39 @@ +// LeetCode doesn't support C++20 yet, so we don't have std::counting_semaphore +// or binary_semaphore. +#include + +class BoundedBlockingQueue { + public: + BoundedBlockingQueue(int capacity) { + sem_init(&enqueueSemaphore, /*pshared=*/0, /*value=*/capacity); + sem_init(&dequeueSemaphore, /*pshared=*/0, /*value=*/0); + } + + ~BoundedBlockingQueue() { + sem_destroy(&enqueueSemaphore); + sem_destroy(&dequeueSemaphore); + } + + void enqueue(int element) { + sem_wait(&enqueueSemaphore); + q.push(element); + sem_post(&dequeueSemaphore); + } + + int dequeue() { + sem_wait(&dequeueSemaphore); + const int element = q.front(); + q.pop(); + sem_post(&enqueueSemaphore); + return element; + } + + int size() { + return q.size(); + } + + private: + queue q; + sem_t enqueueSemaphore; + sem_t dequeueSemaphore; +}; diff --git a/solutions/1188. Design Bounded Blocking Queue/1188.java b/solutions/1188. Design Bounded Blocking Queue/1188.java new file mode 100644 index 00000000000..15f4ed57568 --- /dev/null +++ b/solutions/1188. Design Bounded Blocking Queue/1188.java @@ -0,0 +1,26 @@ +class BoundedBlockingQueue { + public BoundedBlockingQueue(int capacity) { + this.enqueueSemaphore = new Semaphore(capacity); + } + + public void enqueue(int element) throws InterruptedException { + enqueueSemaphore.acquire(); + q.offer(element); + dequeueSemaphore.release(); + } + + public int dequeue() throws InterruptedException { + dequeueSemaphore.acquire(); + final int element = q.poll(); + enqueueSemaphore.release(); + return element; + } + + public int size() { + return q.size(); + } + + private Queue q = new ArrayDeque<>(); + private Semaphore enqueueSemaphore; + private Semaphore dequeueSemaphore = new Semaphore(0); +} diff --git a/solutions/1188. Design Bounded Blocking Queue/1188.py b/solutions/1188. Design Bounded Blocking Queue/1188.py new file mode 100644 index 00000000000..56b13a931ac --- /dev/null +++ b/solutions/1188. Design Bounded Blocking Queue/1188.py @@ -0,0 +1,22 @@ +from threading import Semaphore + + +class BoundedBlockingQueue: + def __init__(self, capacity: int): + self.q = collections.deque() + self.enqueueSemaphore = Semaphore(capacity) + self.dequeueSemaphore = Semaphore(0) + + def enqueue(self, element: int) -> None: + self.enqueueSemaphore.acquire() + self.q.append(element) + self.dequeueSemaphore.release() + + def dequeue(self) -> int: + self.dequeueSemaphore.acquire() + element = self.q.popleft() + self.enqueueSemaphore.release() + return element + + def size(self) -> int: + return len(self.q) diff --git a/solutions/1189. Maximum Number of Balloons/1189.cpp b/solutions/1189. Maximum Number of Balloons/1189.cpp new file mode 100644 index 00000000000..77a85376521 --- /dev/null +++ b/solutions/1189. Maximum Number of Balloons/1189.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxNumberOfBalloons(string text) { + int ans = INT_MAX; + vector count(26); + + for (char c : text) + ++count[c - 'a']; + + for (char c : string("ban")) + ans = min(ans, count[c - 'a']); + + for (char c : string("lo")) + ans = min(ans, count[c - 'a'] / 2); + + return ans; + } +}; diff --git a/solutions/1189. Maximum Number of Balloons/1189.java b/solutions/1189. Maximum Number of Balloons/1189.java new file mode 100644 index 00000000000..a9f491b03e9 --- /dev/null +++ b/solutions/1189. Maximum Number of Balloons/1189.java @@ -0,0 +1,17 @@ +class Solution { + public int maxNumberOfBalloons(String text) { + int ans = Integer.MAX_VALUE; + int[] count = new int[26]; + + for (char c : text.toCharArray()) + ++count[c - 'a']; + + for (char c : new char[] {'b', 'a', 'n'}) + ans = Math.min(ans, count[c - 'a']); + + for (char c : new char[] {'o', 'l'}) + ans = Math.min(ans, count[c - 'a'] / 2); + + return ans; + } +} diff --git a/solutions/1189. Maximum Number of Balloons/1189.py b/solutions/1189. Maximum Number of Balloons/1189.py new file mode 100644 index 00000000000..39973734039 --- /dev/null +++ b/solutions/1189. Maximum Number of Balloons/1189.py @@ -0,0 +1,4 @@ +class Solution: + def maxNumberOfBalloons(self, text: str) -> int: + count = collections.Counter(text) + return min(count['b'], count['a'], count['l'] // 2, count['o'] // 2, count['n']) diff --git a/solutions/119. Pascal's Triangle II/119.cpp b/solutions/119. Pascal's Triangle II/119.cpp new file mode 100644 index 00000000000..5a2ecb3dca0 --- /dev/null +++ b/solutions/119. Pascal's Triangle II/119.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector getRow(int rowIndex) { + vector ans(rowIndex + 1, 1); + + for (int i = 2; i < rowIndex + 1; ++i) + for (int j = 1; j < i; ++j) + ans[i - j] += ans[i - j - 1]; + + return ans; + } +}; diff --git a/solutions/119. Pascal's Triangle II/119.java b/solutions/119. Pascal's Triangle II/119.java new file mode 100644 index 00000000000..820698f4c19 --- /dev/null +++ b/solutions/119. Pascal's Triangle II/119.java @@ -0,0 +1,12 @@ +class Solution { + public List getRow(int rowIndex) { + Integer[] ans = new Integer[rowIndex + 1]; + Arrays.fill(ans, 1); + + for (int i = 2; i < rowIndex + 1; ++i) + for (int j = 1; j < i; ++j) + ans[i - j] += ans[i - j - 1]; + + return Arrays.asList(ans); + } +} diff --git a/solutions/119. Pascal's Triangle II/119.py b/solutions/119. Pascal's Triangle II/119.py new file mode 100644 index 00000000000..849027306aa --- /dev/null +++ b/solutions/119. Pascal's Triangle II/119.py @@ -0,0 +1,9 @@ +class Solution: + def getRow(self, rowIndex: int) -> List[int]: + ans = [1] * (rowIndex + 1) + + for i in range(2, rowIndex + 1): + for j in range(1, i): + ans[i - j] += ans[i - j - 1] + + return ans diff --git a/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.cpp b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.cpp new file mode 100644 index 00000000000..b450d7fae28 --- /dev/null +++ b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + string reverseParentheses(string s) { + string ans; + stack stack; + unordered_map pair; + + for (int i = 0; i < s.length(); ++i) + if (s[i] == '(') { + stack.push(i); + } else if (s[i] == ')') { + const int j = stack.top(); + stack.pop(); + pair[i] = j; + pair[j] = i; + } + + for (int i = 0, d = 1; i < s.length(); i += d) + if (s[i] == '(' || s[i] == ')') { + i = pair[i]; + d = -d; + } else { + ans += s[i]; + } + + return ans; + } +}; diff --git a/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.java b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.java new file mode 100644 index 00000000000..3e1f730bb48 --- /dev/null +++ b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.java @@ -0,0 +1,26 @@ +class Solution { + public String reverseParentheses(String s) { + StringBuilder sb = new StringBuilder(); + Deque stack = new ArrayDeque<>(); + Map pair = new HashMap<>(); + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) == '(') { + stack.push(i); + } else if (s.charAt(i) == ')') { + final int j = stack.pop(); + pair.put(i, j); + pair.put(j, i); + } + + for (int i = 0, d = 1; i < s.length(); i += d) + if (s.charAt(i) == '(' || s.charAt(i) == ')') { + i = pair.get(i); + d = -d; + } else { + sb.append(s.charAt(i)); + } + + return sb.toString(); + } +} diff --git a/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.py b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.py new file mode 100644 index 00000000000..fc336df5607 --- /dev/null +++ b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190-2.py @@ -0,0 +1,25 @@ +class Solution: + def reverseParentheses(self, s: str) -> str: + ans = [] + stack = [] + pair = {} + + for i, c in enumerate(s): + if c == '(': + stack.append(i) + elif c == ')': + j = stack.pop() + pair[i] = j + pair[j] = i + + i = 0 + d = 1 + while i < len(s): + if s[i] in '()': + i = pair[i] + d = -d + else: + ans.append(s[i]) + i += d + + return ''.join(ans) diff --git a/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.cpp b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.cpp new file mode 100644 index 00000000000..0f5db7ad6e2 --- /dev/null +++ b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string reverseParentheses(string s) { + stack stack; + string ans; + + for (const char c : s) + if (c == '(') { + stack.push(ans.length()); + } else if (c == ')') { + // Reverse the corresponding substring between (). + const int j = stack.top(); + stack.pop(); + reverse(ans.begin() + j, ans.end()); + } else { + ans += c; + } + + return ans; + } +}; diff --git a/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.java b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.java new file mode 100644 index 00000000000..9b6734e90bb --- /dev/null +++ b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.java @@ -0,0 +1,23 @@ +class Solution { + public String reverseParentheses(String s) { + Deque stack = new ArrayDeque<>(); + StringBuilder sb = new StringBuilder(); + + for (final char c : s.toCharArray()) + if (c == '(') { + stack.push(sb.length()); + } else if (c == ')') { + // Reverse the corresponding substring between (). + StringBuilder reversed = new StringBuilder(); + for (int sz = sb.length() - stack.pop(); sz > 0; --sz) { + reversed.append(sb.charAt(sb.length() - 1)); + sb.deleteCharAt(sb.length() - 1); + } + sb.append(reversed); + } else { + sb.append(c); + } + + return sb.toString(); + } +} diff --git a/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.py b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.py new file mode 100644 index 00000000000..59a2a2e46a2 --- /dev/null +++ b/solutions/1190. Reverse Substrings Between Each Pair of Parentheses/1190.py @@ -0,0 +1,16 @@ +class Solution: + def reverseParentheses(self, s: str) -> str: + stack = [] + ans = [] + + for c in s: + if c == '(': + stack.append(len(ans)) + elif c == ')': + # Reverse the corresponding substring between (). + j = stack.pop() + ans[j:] = ans[j:][::-1] + else: + ans.append(c) + + return ''.join(ans) diff --git a/solutions/1191. K-Concatenation Maximum Sum/1191.cpp b/solutions/1191. K-Concatenation Maximum Sum/1191.cpp new file mode 100644 index 00000000000..bfabfe97731 --- /dev/null +++ b/solutions/1191. K-Concatenation Maximum Sum/1191.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int kConcatenationMaxSum(vector& arr, int k) { + constexpr int kMod = 1'000'000'007; + const int sz = arr.size() * (k == 1 ? 1 : 2); + const int sum = accumulate(arr.begin(), arr.end(), 0); + // The concatenated array will be [arr1, arr2, ..., arrk]. + // If sum(arr) > 0 and k > 2, then arr2, ..., arr(k - 1) should be included. + // Equivalently, maxSubarraySum is from arr1 and arrk. + return (sum > 0 && k > 2 ? kadane(arr, sz) + sum * static_cast(k - 2) + : kadane(arr, sz)) % + kMod; + } + + private: + int kadane(const vector& A, int sz) { + int ans = 0; + int sum = 0; + for (int i = 0; i < sz; ++i) { + const int a = A[i % A.size()]; + sum = max(a, sum + a); + ans = max(ans, sum); + } + return ans; + } +}; diff --git a/solutions/1191. K-Concatenation Maximum Sum/1191.java b/solutions/1191. K-Concatenation Maximum Sum/1191.java new file mode 100644 index 00000000000..4fc40760ec4 --- /dev/null +++ b/solutions/1191. K-Concatenation Maximum Sum/1191.java @@ -0,0 +1,24 @@ +class Solution { + public int kConcatenationMaxSum(int[] arr, int k) { + final int kMod = 1_000_000_007; + final int sz = arr.length * (k == 1 ? 1 : 2); + final int sum = Arrays.stream(arr).sum(); + // The concatenated array will be [arr1, arr2, ..., arrk]. + // If sum(arr) > 0 and k > 2, then arr2, ..., arr(k - 1) should be included. + // Equivalently, maxSubarraySum is from arr1 and arrk. + if (sum > 0 && k > 2) + return (int) ((kadane(arr, sz) + sum * (long) (k - 2)) % kMod); + return kadane(arr, sz) % kMod; + } + + private int kadane(int[] A, int sz) { + int ans = 0; + int sum = 0; + for (int i = 0; i < sz; ++i) { + final int a = A[i % A.length]; + sum = Math.max(a, sum + a); + ans = Math.max(ans, sum); + } + return ans; + } +} diff --git a/solutions/1191. K-Concatenation Maximum Sum/1191.py b/solutions/1191. K-Concatenation Maximum Sum/1191.py new file mode 100644 index 00000000000..2e1ae6d9754 --- /dev/null +++ b/solutions/1191. K-Concatenation Maximum Sum/1191.py @@ -0,0 +1,20 @@ +class Solution: + def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: + kMod = 1_000_000_007 + sz = len(arr) * (1 if k == 1 else 2) + summ = sum(arr) + # The concatenated array will be [arr1, arr2, ..., arrk]. + # If sum(arr) > 0 and k > 2, then arr2, ..., arr(k - 1) should be included. + # Equivalently, maxSubarraySum is from arr1 and arrk. + if summ > 0 and k > 2: + return (self.kadane(arr, sz) + summ * (k - 2)) % kMod + return self.kadane(arr, sz) % kMod + + def kadane(self, A: List[int], sz: int) -> int: + ans = 0 + summ = 0 + for i in range(sz): + a = A[i % len(A)] + summ = max(a, summ + a) + ans = max(ans, summ) + return ans diff --git a/solutions/1192. Critical Connections in a Network/1192.cpp b/solutions/1192. Critical Connections in a Network/1192.cpp new file mode 100644 index 00000000000..c222c514d23 --- /dev/null +++ b/solutions/1192. Critical Connections in a Network/1192.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + vector> criticalConnections(int n, + vector>& connections) { + vector> ans; + vector> graph(n); + + for (const vector& connection : connections) { + const int u = connection[0]; + const int v = connection[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + // rank[i] := the minimum node that node i can reach with forward edges + // Initialize with NO_RANK = -2 to indicate not visited.. + getRank(graph, 0, 0, vector(n, NO_RANK), ans); + return ans; + } + + private: + static constexpr int NO_RANK = -2; + + // Gets the minimum rank that u can reach with forward edges. + int getRank(const vector>& graph, int u, int currRank, + vector&& rank, vector>& ans) { + if (rank[u] != NO_RANK) // The rank is already determined. + return rank[u]; + + rank[u] = currRank; + int minRank = currRank; + + for (const int v : graph[u]) { + // visited || parent (that's why NO_RANK = -2 instead of -1) + if (rank[u] == rank.size() || rank[v] == currRank - 1) + continue; + const int nextRank = getRank(graph, v, currRank + 1, move(rank), ans); + // (u, v) is the only way for u go to v. + if (nextRank == currRank + 1) + ans.push_back({u, v}); + minRank = min(minRank, nextRank); + } + + rank[u] = rank.size(); // Mark as visited. + return minRank; + } +}; diff --git a/solutions/1192. Critical Connections in a Network/1192.java b/solutions/1192. Critical Connections in a Network/1192.java new file mode 100644 index 00000000000..2fd0084c1e3 --- /dev/null +++ b/solutions/1192. Critical Connections in a Network/1192.java @@ -0,0 +1,49 @@ +class Solution { + public List> criticalConnections(int n, List> connections) { + List> ans = new ArrayList<>(); + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (List connection : connections) { + final int u = connection.get(0); + final int v = connection.get(1); + graph[u].add(v); + graph[v].add(u); + } + + // rank[i] := the minimum node that node i can reach with forward edges + // Initialize with NO_RANK = -2 to indicate not visited.. + int[] rank = new int[n]; + Arrays.fill(rank, NO_RANK); + getRank(graph, 0, 0, rank, ans); + return ans; + } + + private static final int NO_RANK = -2; + + // Gets the minimum rank that u can reach with forward edges. + private int getRank(List[] graph, int u, int myRank, int[] rank, + List> ans) { + if (rank[u] != NO_RANK) // The rank is already been determined. + return rank[u]; + + rank[u] = myRank; + int minRank = myRank; + + for (final int v : graph[u]) { + // visited || parent (that's why NO_RANK = -2 instead of -1) + if (rank[u] == rank.length || rank[v] == myRank - 1) + continue; + final int nextRank = getRank(graph, v, myRank + 1, rank, ans); + // (u, v) is the only way for u go to v. + if (nextRank == myRank + 1) + ans.add(Arrays.asList(u, v)); + minRank = Math.min(minRank, nextRank); + } + + rank[u] = rank.length; // Mark as visited. + return minRank; + } +} diff --git a/solutions/1193. Monthly Transactions I/1193.sql b/solutions/1193. Monthly Transactions I/1193.sql new file mode 100644 index 00000000000..452c6b4a7c6 --- /dev/null +++ b/solutions/1193. Monthly Transactions I/1193.sql @@ -0,0 +1,9 @@ +SELECT + DATE_FORMAT(trans_date, '%Y-%m') AS month, + country, + COUNT(*) AS trans_count, + SUM(state = 'approved') AS approved_count, + SUM(amount) AS trans_total_amount, + SUM(IF(state = 'approved', amount, 0)) AS approved_total_amount +FROM Transactions +GROUP BY 1, 2; diff --git a/solutions/1194. Tournament Winners/1194.sql b/solutions/1194. Tournament Winners/1194.sql new file mode 100644 index 00000000000..9a6e1815176 --- /dev/null +++ b/solutions/1194. Tournament Winners/1194.sql @@ -0,0 +1,37 @@ +WITH + PlayerToScore AS ( + ( + SELECT + Players.player_id, + Players.group_id, + Matches.first_score AS score + FROM Players + LEFT JOIN Matches + ON (Players.player_id = Matches.first_player) + ) + UNION ALL + ( + SELECT + Players.player_id, + Players.group_id, + Matches.second_score AS score + FROM Players + LEFT JOIN Matches + ON (Players.player_id = Matches.second_player) + ) + ), + RankedPlayers AS ( + SELECT + player_id, + group_id, + RANK() OVER( + PARTITION BY group_id + ORDER BY SUM(score) DESC, + player_id + ) AS `rank` + FROM PlayerToScore + GROUP BY 1 + ) +SELECT group_id, player_id +FROM RankedPlayers +WHERE `rank` = 1; diff --git a/solutions/1195. Fizz Buzz Multithreaded/1195.cpp b/solutions/1195. Fizz Buzz Multithreaded/1195.cpp new file mode 100644 index 00000000000..a65d6195a65 --- /dev/null +++ b/solutions/1195. Fizz Buzz Multithreaded/1195.cpp @@ -0,0 +1,74 @@ +// LeetCode doesn't support C++20 yet, so we don't have std::counting_semaphore +// or binary_semaphore. +#include + +class FizzBuzz { + public: + FizzBuzz(int n) : n(n) { + sem_init(&fizzSemaphore, /*pshared=*/0, /*value=*/0); + sem_init(&buzzSemaphore, /*pshared=*/0, /*value=*/0); + sem_init(&fizzbuzzSemaphore, /*pshared=*/0, /*value=*/0); + sem_init(&numberSemaphore, /*pshared=*/0, /*value=*/1); + } + + ~FizzBuzz() { + sem_destroy(&fizzSemaphore); + sem_destroy(&buzzSemaphore); + sem_destroy(&fizzbuzzSemaphore); + sem_destroy(&numberSemaphore); + } + + // printFizz() outputs "fizz". + void fizz(function printFizz) { + for (int i = 1; i <= n; ++i) + if (i % 3 == 0 && i % 15 != 0) { + sem_wait(&fizzSemaphore); + printFizz(); + sem_post(&numberSemaphore); + } + } + + // printBuzz() outputs "buzz". + void buzz(function printBuzz) { + for (int i = 1; i <= n; ++i) + if (i % 5 == 0 && i % 15 != 0) { + sem_wait(&buzzSemaphore); + printBuzz(); + sem_post(&numberSemaphore); + } + } + + // printFizzBuzz() outputs "fizzbuzz". + void fizzbuzz(function printFizzBuzz) { + for (int i = 1; i <= n; ++i) + if (i % 15 == 0) { + sem_wait(&fizzbuzzSemaphore); + printFizzBuzz(); + sem_post(&numberSemaphore); + } + } + + // printNumber(x) outputs "x", where x is an integer. + void number(function printNumber) { + for (int i = 1; i <= n; ++i) { + sem_wait(&numberSemaphore); + if (i % 15 == 0) + sem_post(&fizzbuzzSemaphore); + else if (i % 3 == 0) + sem_post(&fizzSemaphore); + else if (i % 5 == 0) + sem_post(&buzzSemaphore); + else { + printNumber(i); + sem_post(&numberSemaphore); + } + } + } + + private: + const int n; + sem_t fizzSemaphore; + sem_t buzzSemaphore; + sem_t fizzbuzzSemaphore; + sem_t numberSemaphore; +}; diff --git a/solutions/1195. Fizz Buzz Multithreaded/1195.java b/solutions/1195. Fizz Buzz Multithreaded/1195.java new file mode 100644 index 00000000000..cd21943686f --- /dev/null +++ b/solutions/1195. Fizz Buzz Multithreaded/1195.java @@ -0,0 +1,58 @@ +class FizzBuzz { + public FizzBuzz(int n) { + this.n = n; + } + + // printFizz.run() outputs "fizz". + public void fizz(Runnable printFizz) throws InterruptedException { + for (int i = 1; i <= n; ++i) + if (i % 3 == 0 && i % 15 != 0) { + fizzSemaphore.acquire(); + printFizz.run(); + numberSemaphore.release(); + } + } + + // printBuzz.run() outputs "buzz". + public void buzz(Runnable printBuzz) throws InterruptedException { + for (int i = 1; i <= n; ++i) + if (i % 5 == 0 && i % 15 != 0) { + buzzSemaphore.acquire(); + printBuzz.run(); + numberSemaphore.release(); + } + } + + // printFizzBuzz.run() outputs "fizzbuzz". + public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException { + for (int i = 1; i <= n; ++i) + if (i % 15 == 0) { + fizzbuzzSemaphore.acquire(); + printFizzBuzz.run(); + numberSemaphore.release(); + } + } + + // printNumber.accept(x) outputs "x", where x is an integer. + public void number(IntConsumer printNumber) throws InterruptedException { + for (int i = 1; i <= n; ++i) { + numberSemaphore.acquire(); + if (i % 15 == 0) + fizzbuzzSemaphore.release(); + else if (i % 3 == 0) + fizzSemaphore.release(); + else if (i % 5 == 0) + buzzSemaphore.release(); + else { + printNumber.accept(i); + numberSemaphore.release(); + } + } + } + + private int n; + private Semaphore fizzSemaphore = new Semaphore(0); + private Semaphore buzzSemaphore = new Semaphore(0); + private Semaphore fizzbuzzSemaphore = new Semaphore(0); + private Semaphore numberSemaphore = new Semaphore(1); +} diff --git a/solutions/1195. Fizz Buzz Multithreaded/1195.py b/solutions/1195. Fizz Buzz Multithreaded/1195.py new file mode 100644 index 00000000000..9a112080064 --- /dev/null +++ b/solutions/1195. Fizz Buzz Multithreaded/1195.py @@ -0,0 +1,48 @@ +from threading import Semaphore + + +class FizzBuzz: + def __init__(self, n: int): + self.n = n + self.fizzSemaphore = Semaphore(0) + self.buzzSemaphore = Semaphore(0) + self.fizzbuzzSemaphore = Semaphore(0) + self.numberSemaphore = Semaphore(1) + + # printFizz() outputs "fizz" + def fizz(self, printFizz: 'Callable[[], None]') -> None: + for i in range(1, self.n + 1): + if i % 3 == 0 and i % 15 != 0: + self.fizzSemaphore.acquire() + printFizz() + self.numberSemaphore.release() + + # printBuzz() outputs "buzz" + def buzz(self, printBuzz: 'Callable[[], None]') -> None: + for i in range(1, self.n + 1): + if i % 5 == 0 and i % 15 != 0: + self.buzzSemaphore.acquire() + printBuzz() + self.numberSemaphore.release() + + # printFizzBuzz() outputs "fizzbuzz" + def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None: + for i in range(1, self.n + 1): + if i % 15 == 0: + self.fizzbuzzSemaphore.acquire() + printFizzBuzz() + self.numberSemaphore.release() + + # printNumber(x) outputs "x", where x is an integer. + def number(self, printNumber: 'Callable[[int], None]') -> None: + for i in range(1, self.n + 1): + self.numberSemaphore.acquire() + if i % 15 == 0: + self.fizzbuzzSemaphore.release() + elif i % 3 == 0: + self.fizzSemaphore.release() + elif i % 5 == 0: + self.buzzSemaphore.release() + else: + printNumber(i) + self.numberSemaphore.release() diff --git a/solutions/1196. How Many Apples Can You Put into the Basket/1196.cpp b/solutions/1196. How Many Apples Can You Put into the Basket/1196.cpp new file mode 100644 index 00000000000..005deedb3d9 --- /dev/null +++ b/solutions/1196. How Many Apples Can You Put into the Basket/1196.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxNumberOfApples(vector& weight) { + int sum = 0; + + ranges::sort(weight); + + for (int i = 0; i < weight.size(); ++i) { + sum += weight[i]; + if (sum > 5000) + return i; + } + + return weight.size(); + } +}; diff --git a/solutions/1196. How Many Apples Can You Put into the Basket/1196.java b/solutions/1196. How Many Apples Can You Put into the Basket/1196.java new file mode 100644 index 00000000000..4cff0d2ac07 --- /dev/null +++ b/solutions/1196. How Many Apples Can You Put into the Basket/1196.java @@ -0,0 +1,15 @@ +class Solution { + public int maxNumberOfApples(int[] weight) { + int sum = 0; + + Arrays.sort(weight); + + for (int i = 0; i < weight.length; ++i) { + sum += weight[i]; + if (sum > 5000) + return i; + } + + return weight.length; + } +} diff --git a/solutions/1196. How Many Apples Can You Put into the Basket/1196.py b/solutions/1196. How Many Apples Can You Put into the Basket/1196.py new file mode 100644 index 00000000000..1bf7aae32c3 --- /dev/null +++ b/solutions/1196. How Many Apples Can You Put into the Basket/1196.py @@ -0,0 +1,10 @@ +class Solution: + def maxNumberOfApples(self, weight: List[int]) -> int: + summ = 0 + + for i, w in enumerate(sorted(weight)): + summ += w + if summ > 5000: + return i + + return len(weight) diff --git a/solutions/1197. Minimum Knight Moves/1197.cpp b/solutions/1197. Minimum Knight Moves/1197.cpp new file mode 100644 index 00000000000..f834b4a614d --- /dev/null +++ b/solutions/1197. Minimum Knight Moves/1197.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int minKnightMoves(int x, int y) { + return dp(abs(x), abs(y)); + } + + private: + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; + + unordered_map, int, PairHash> mem; + + int dp(int x, int y) { + if (x + y == 0) // (0, 0) + return 0; + if (x + y == 2) // (0, 2), (1, 1), (2, 0) + return 2; + if (const auto it = mem.find({x, y}); it != mem.cend()) + return it->second; + + return mem[{x, y}] = 1 + min(dp(abs(x - 2), abs(y - 1)), // + dp(abs(x - 1), abs(y - 2))); + } +}; diff --git a/solutions/1197. Minimum Knight Moves/1197.java b/solutions/1197. Minimum Knight Moves/1197.java new file mode 100644 index 00000000000..7421b4e375f --- /dev/null +++ b/solutions/1197. Minimum Knight Moves/1197.java @@ -0,0 +1,23 @@ +class Solution { + public int minKnightMoves(int x, int y) { + return dp(Math.abs(x), Math.abs(y)); + } + + private Map, Integer> mem = new HashMap<>(); + + private int dp(int x, int y) { + if (x + y == 0) // (0, 0) + return 0; + if (x + y == 2) // (0, 2), (1, 1), (2, 0) + return 2; + Pair key = new Pair<>(x, y); + if (mem.containsKey(key)) + return mem.get(key); + + final int minMove = 1 + Math.min( // + dp(Math.abs(x - 2), Math.abs(y - 1)), // + dp(Math.abs(x - 1), Math.abs(y - 2))); + mem.put(key, minMove); + return minMove; + } +} diff --git a/solutions/1198. Find Smallest Common Element in All Rows/1198.cpp b/solutions/1198. Find Smallest Common Element in All Rows/1198.cpp new file mode 100644 index 00000000000..e1df880a33b --- /dev/null +++ b/solutions/1198. Find Smallest Common Element in All Rows/1198.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int smallestCommonElement(vector>& mat) { + constexpr int kMax = 10000; + vector count(kMax + 1); + + for (const vector& row : mat) + for (const int a : row) + if (++count[a] == mat.size()) + return a; + + return -1; + } +}; diff --git a/solutions/1198. Find Smallest Common Element in All Rows/1198.java b/solutions/1198. Find Smallest Common Element in All Rows/1198.java new file mode 100644 index 00000000000..a15c0b1bb86 --- /dev/null +++ b/solutions/1198. Find Smallest Common Element in All Rows/1198.java @@ -0,0 +1,13 @@ +class Solution { + public int smallestCommonElement(int[][] mat) { + final int kMax = 10000; + int[] count = new int[kMax + 1]; + + for (int[] row : mat) + for (final int a : row) + if (++count[a] == mat.length) + return a; + + return -1; + } +} diff --git a/solutions/1198. Find Smallest Common Element in All Rows/1198.py b/solutions/1198. Find Smallest Common Element in All Rows/1198.py new file mode 100644 index 00000000000..660e00027aa --- /dev/null +++ b/solutions/1198. Find Smallest Common Element in All Rows/1198.py @@ -0,0 +1,12 @@ +class Solution: + def smallestCommonElement(self, mat: List[List[int]]) -> int: + kMax = 10000 + count = [0] * (kMax + 1) + + for row in mat: + for a in row: + count[a] += 1 + if count[a] == len(mat): + return a + + return -1 diff --git a/solutions/1199. Minimum Time to Build Blocks/1199.cpp b/solutions/1199. Minimum Time to Build Blocks/1199.cpp new file mode 100644 index 00000000000..95adb23585c --- /dev/null +++ b/solutions/1199. Minimum Time to Build Blocks/1199.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minBuildTime(vector& blocks, int split) { + priority_queue, greater<>> minHeap; + + for (const int block : blocks) + minHeap.push(block); + + while (minHeap.size() > 1) { + minHeap.pop(); // the minimum + const int x = minHeap.top(); // the second minimum + minHeap.pop(); + minHeap.push(x + split); + } + + return minHeap.top(); + } +}; diff --git a/solutions/1199. Minimum Time to Build Blocks/1199.java b/solutions/1199. Minimum Time to Build Blocks/1199.java new file mode 100644 index 00000000000..35475a1e711 --- /dev/null +++ b/solutions/1199. Minimum Time to Build Blocks/1199.java @@ -0,0 +1,16 @@ +class Solution { + public int minBuildTime(int[] blocks, int split) { + Queue minHeap = new PriorityQueue<>(); + + for (final int block : blocks) + minHeap.offer(block); + + while (minHeap.size() > 1) { + minHeap.poll(); // the minimum + final int x = minHeap.poll(); // the second minimum + minHeap.offer(x + split); + } + + return minHeap.poll(); + } +} diff --git a/solutions/1199. Minimum Time to Build Blocks/1199.py b/solutions/1199. Minimum Time to Build Blocks/1199.py new file mode 100644 index 00000000000..823253140ad --- /dev/null +++ b/solutions/1199. Minimum Time to Build Blocks/1199.py @@ -0,0 +1,11 @@ +class Solution: + def minBuildTime(self, blocks: List[int], split: int) -> int: + minHeap = blocks.copy() + heapify(minHeap) + + while len(minHeap) > 1: + heapq.heappop(minHeap) # the minimum + x = heapq.heappop(minHeap) # the second minimum + heapq.heappush(minHeap, x + split) + + return minHeap[0] diff --git a/solutions/12. Integer to Roman/12-2.cpp b/solutions/12. Integer to Roman/12-2.cpp new file mode 100644 index 00000000000..02f68ea759e --- /dev/null +++ b/solutions/12. Integer to Roman/12-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string intToRoman(int num) { + const vector M{"", "M", "MM", "MMM"}; + const vector C{"", "C", "CC", "CCC", "CD", + "D", "DC", "DCC", "DCCC", "CM"}; + const vector X{"", "X", "XX", "XXX", "XL", + "L", "LX", "LXX", "LXXX", "XC"}; + const vector I{"", "I", "II", "III", "IV", + "V", "VI", "VII", "VIII", "IX"}; + return M[num / 1000] + C[num % 1000 / 100] + X[num % 100 / 10] + + I[num % 10]; + } +}; diff --git a/solutions/12. Integer to Roman/12-2.java b/solutions/12. Integer to Roman/12-2.java new file mode 100644 index 00000000000..177cf182666 --- /dev/null +++ b/solutions/12. Integer to Roman/12-2.java @@ -0,0 +1,9 @@ +class Solution { + public String intToRoman(int num) { + final String[] M = {"", "M", "MM", "MMM"}; + final String[] C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + final String[] X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + final String[] I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + return M[num / 1000] + C[num % 1000 / 100] + X[num % 100 / 10] + I[num % 10]; + } +} diff --git a/solutions/12. Integer to Roman/12-2.py b/solutions/12. Integer to Roman/12-2.py new file mode 100644 index 00000000000..91db4b8bc0d --- /dev/null +++ b/solutions/12. Integer to Roman/12-2.py @@ -0,0 +1,7 @@ +class Solution: + def intToRoman(self, num: int) -> str: + M = ['', 'M', 'MM', 'MMM'] + C = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'] + X = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'] + I = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'] + return M[num // 1000] + C[num % 1000 // 100] + X[num % 100 // 10] + I[num % 10] diff --git a/solutions/12. Integer to Roman/12.cpp b/solutions/12. Integer to Roman/12.cpp new file mode 100644 index 00000000000..3e5ade6c6b7 --- /dev/null +++ b/solutions/12. Integer to Roman/12.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string intToRoman(int num) { + const vector> valueSymbols{ + {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, + {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, + {5, "V"}, {4, "IV"}, {1, "I"}}; + string ans; + + for (const auto& [value, symbol] : valueSymbols) { + if (num == 0) + break; + while (num >= value) { + num -= value; + ans += symbol; + } + } + + return ans; + } +}; diff --git a/solutions/12. Integer to Roman/12.java b/solutions/12. Integer to Roman/12.java new file mode 100644 index 00000000000..ca990b26744 --- /dev/null +++ b/solutions/12. Integer to Roman/12.java @@ -0,0 +1,19 @@ +class Solution { + public String intToRoman(int num) { + final int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + final String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", + "XL", "X", "IX", "V", "IV", "I"}; + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < values.length; ++i) { + if (num == 0) + break; + while (num >= values[i]) { + num -= values[i]; + sb.append(symbols[i]); + } + } + + return sb.toString(); + } +} diff --git a/solutions/12. Integer to Roman/12.py b/solutions/12. Integer to Roman/12.py new file mode 100644 index 00000000000..9905e2aee17 --- /dev/null +++ b/solutions/12. Integer to Roman/12.py @@ -0,0 +1,18 @@ +class Solution: + def intToRoman(self, num: int) -> str: + valueSymbols = [(1000, 'M'), (900, 'CM'), + (500, 'D'), (400, 'CD'), + (100, 'C'), (90, 'XC'), + (50, 'L'), (40, 'XL'), + (10, 'X'), (9, 'IX'), + (5, 'V'), (4, 'IV'), + (1, 'I')] + ans = [] + + for value, symbol in valueSymbols: + if num == 0: + break + count, num = divmod(num, value) + ans.append(symbol * count) + + return ''.join(ans) diff --git a/solutions/120. Triangle/120.cpp b/solutions/120. Triangle/120.cpp new file mode 100644 index 00000000000..1af2114c0e1 --- /dev/null +++ b/solutions/120. Triangle/120.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int minimumTotal(vector>& triangle) { + for (int i = triangle.size() - 2; i >= 0; --i) + for (int j = 0; j <= i; ++j) + triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); + return triangle[0][0]; + } +}; diff --git a/solutions/120. Triangle/120.java b/solutions/120. Triangle/120.java new file mode 100644 index 00000000000..d48b43315c0 --- /dev/null +++ b/solutions/120. Triangle/120.java @@ -0,0 +1,9 @@ +class Solution { + public int minimumTotal(List> triangle) { + for (int i = triangle.size() - 2; i >= 0; --i) + for (int j = 0; j <= i; ++j) + triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), + triangle.get(i + 1).get(j + 1))); + return triangle.get(0).get(0); + } +} diff --git a/solutions/120. Triangle/120.py b/solutions/120. Triangle/120.py new file mode 100644 index 00000000000..96c0773a51c --- /dev/null +++ b/solutions/120. Triangle/120.py @@ -0,0 +1,8 @@ +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + for i in reversed(range(len(triangle) - 1)): + for j in range(i + 1): + triangle[i][j] += min(triangle[i + 1][j], + triangle[i + 1][j + 1]) + + return triangle[0][0] diff --git a/solutions/1200. Minimum Absolute Difference/1200.cpp b/solutions/1200. Minimum Absolute Difference/1200.cpp new file mode 100644 index 00000000000..ed25c0e9d5a --- /dev/null +++ b/solutions/1200. Minimum Absolute Difference/1200.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector> minimumAbsDifference(vector& arr) { + vector> ans; + int mn = INT_MAX; + + ranges::sort(arr); + + for (int i = 1; i < arr.size(); ++i) { + const int diff = arr[i] - arr[i - 1]; + if (diff < mn) { + mn = diff; + ans.clear(); + } + if (diff == mn) + ans.push_back({arr[i - 1], arr[i]}); + } + + return ans; + } +}; diff --git a/solutions/1200. Minimum Absolute Difference/1200.java b/solutions/1200. Minimum Absolute Difference/1200.java new file mode 100644 index 00000000000..6cc141e46e5 --- /dev/null +++ b/solutions/1200. Minimum Absolute Difference/1200.java @@ -0,0 +1,20 @@ +class Solution { + public List> minimumAbsDifference(int[] arr) { + List> ans = new ArrayList<>(); + int mn = Integer.MAX_VALUE; + + Arrays.sort(arr); + + for (int i = 1; i < arr.length; ++i) { + final int diff = arr[i] - arr[i - 1]; + if (diff < mn) { + mn = diff; + ans.clear(); + } + if (diff == mn) + ans.add(Arrays.asList(arr[i - 1], arr[i])); + } + + return ans; + } +} diff --git a/solutions/1200. Minimum Absolute Difference/1200.py b/solutions/1200. Minimum Absolute Difference/1200.py new file mode 100644 index 00000000000..a298f4e2613 --- /dev/null +++ b/solutions/1200. Minimum Absolute Difference/1200.py @@ -0,0 +1,16 @@ +class Solution: + def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: + ans = [] + mn = math.inf + + arr.sort() + + for a, b in itertools.pairwise(arr): + diff = b - a + if diff < mn: + mn = diff + ans = [] + if diff == mn: + ans.append([a, b]) + + return ans diff --git a/solutions/1201. Ugly Number III/1201.cpp b/solutions/1201. Ugly Number III/1201.cpp new file mode 100644 index 00000000000..c96ed9942dc --- /dev/null +++ b/solutions/1201. Ugly Number III/1201.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int nthUglyNumber(int n, long a, long b, long c) { + const long ab = a * b / __gcd(a, b); + const long ac = a * c / __gcd(a, c); + const long bc = b * c / __gcd(b, c); + const long abc = a * bc / __gcd(a, bc); + int l = 1; + int r = 2'000'000'000; + + while (l < r) { + const int m = l + (r - l) / 2; + if (m / a + m / b + m / c - m / ab - m / ac - m / bc + m / abc >= n) + r = m; + else + l = m + 1; + } + + return l; + } +}; diff --git a/solutions/1201. Ugly Number III/1201.java b/solutions/1201. Ugly Number III/1201.java new file mode 100644 index 00000000000..33137484d06 --- /dev/null +++ b/solutions/1201. Ugly Number III/1201.java @@ -0,0 +1,24 @@ +class Solution { + public int nthUglyNumber(int n, long a, long b, long c) { + final long ab = a * b / gcd(a, b); + final long ac = a * c / gcd(a, c); + final long bc = b * c / gcd(b, c); + final long abc = a * bc / gcd(a, bc); + int l = 1; + int r = 2_000_000_000; + + while (l < r) { + final int m = (l + r) / 2; + if (m / a + m / b + m / c - m / ab - m / ac - m / bc + m / abc >= n) + r = m; + else + l = m + 1; + } + + return l; + } + + private long gcd(long a, long b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/1201. Ugly Number III/1201.py b/solutions/1201. Ugly Number III/1201.py new file mode 100644 index 00000000000..d3171bc1b40 --- /dev/null +++ b/solutions/1201. Ugly Number III/1201.py @@ -0,0 +1,9 @@ +class Solution: + def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: + ab = a * b // math.gcd(a, b) + ac = a * c // math.gcd(a, c) + bc = b * c // math.gcd(b, c) + abc = a * bc // math.gcd(a, bc) + return bisect.bisect_left( + range(2 * 10**9), n, + key=lambda m: m // a + m // b + m // c - m // ab - m // ac - m // bc + m // abc) diff --git a/solutions/1202. Smallest String With Swaps/1202.cpp b/solutions/1202. Smallest String With Swaps/1202.cpp new file mode 100644 index 00000000000..99222d65c72 --- /dev/null +++ b/solutions/1202. Smallest String With Swaps/1202.cpp @@ -0,0 +1,49 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + string smallestStringWithSwaps(string s, vector>& pairs) { + string ans; + UnionFind uf(s.length()); + unordered_map, greater<>>> map; + + for (const vector& pair : pairs) + uf.unionByRank(pair[0], pair[1]); + + for (int i = 0; i < s.length(); ++i) + map[uf.find(i)].push(s[i]); + + for (int i = 0; i < s.length(); ++i) + ans += map[uf.find(i)].top(), map[uf.find(i)].pop(); + + return ans; + } +}; diff --git a/solutions/1202. Smallest String With Swaps/1202.java b/solutions/1202. Smallest String With Swaps/1202.java new file mode 100644 index 00000000000..0705482b68e --- /dev/null +++ b/solutions/1202. Smallest String With Swaps/1202.java @@ -0,0 +1,49 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public String smallestStringWithSwaps(String s, List> pairs) { + StringBuilder ans = new StringBuilder(); + UnionFind uf = new UnionFind(s.length()); + Map> map = new HashMap<>(); + + for (List pair : pairs) + uf.unionByRank(pair.get(0), pair.get(1)); + + for (int i = 0; i < s.length(); ++i) + map.computeIfAbsent(uf.find(i), k -> new PriorityQueue<>()).offer(s.charAt(i)); + + for (int i = 0; i < s.length(); ++i) + ans.append(map.get(uf.find(i)).poll()); + + return ans.toString(); + } +} diff --git a/solutions/1202. Smallest String With Swaps/1202.py b/solutions/1202. Smallest String With Swaps/1202.py new file mode 100644 index 00000000000..f40a140c78b --- /dev/null +++ b/solutions/1202. Smallest String With Swaps/1202.py @@ -0,0 +1,43 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: + ans = '' + uf = UnionFind(len(s)) + map = collections.defaultdict(list) + + for a, b in pairs: + uf.unionByRank(a, b) + + for i, c in enumerate(s): + map[uf.find(i)].append(c) + + for key in map.keys(): + map[key].sort(reverse=True) + + for i in range(len(s)): + ans += map[uf.find(i)].pop() + + return ans diff --git a/solutions/1203. Sort Items by Groups Respecting Dependencies/1203.cpp b/solutions/1203. Sort Items by Groups Respecting Dependencies/1203.cpp new file mode 100644 index 00000000000..e771575aa5c --- /dev/null +++ b/solutions/1203. Sort Items by Groups Respecting Dependencies/1203.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + vector sortItems(int n, int m, vector& group, + vector>& beforeItems) { + vector> graph(n + m); + vector inDegrees(n + m); + + // Build the graph by remapping the k-th group to k + n imaginary node. + for (int i = 0; i < group.size(); ++i) { + if (group[i] == -1) + continue; + graph[group[i] + n].push_back(i); + ++inDegrees[i]; + } + + for (int i = 0; i < beforeItems.size(); ++i) + for (const int b : beforeItems[i]) { + const int u = group[b] == -1 ? b : group[b] + n; + const int v = group[i] == -1 ? i : group[i] + n; + if (u == v) { // u and v are already in the same group. + graph[b].push_back(i); + ++inDegrees[i]; + } else { + graph[u].push_back(v); + ++inDegrees[v]; + } + } + + // Perform topological sorting. + vector ans; + + for (int i = 0; i < n + m; ++i) + if (inDegrees[i] == 0) // inDegrees[i] == -1 means visited. + dfs(graph, i, inDegrees, n, ans); + + return ans.size() == n ? ans : vector(); + } + + private: + void dfs(const vector>& graph, int u, vector& inDegrees, + int n, vector& ans) { + if (u < n) + ans.push_back(u); + + inDegrees[u] = -1; // Mark as visited. + + for (const int v : graph[u]) + if (--inDegrees[v] == 0) + dfs(graph, v, inDegrees, n, ans); + } +}; diff --git a/solutions/1203. Sort Items by Groups Respecting Dependencies/1203.java b/solutions/1203. Sort Items by Groups Respecting Dependencies/1203.java new file mode 100644 index 00000000000..4a78a5e7778 --- /dev/null +++ b/solutions/1203. Sort Items by Groups Respecting Dependencies/1203.java @@ -0,0 +1,50 @@ +class Solution { + public int[] sortItems(int n, int m, int[] group, List> beforeItems) { + List[] graph = new List[n + m]; + int[] inDegrees = new int[n + m]; + + for (int i = 0; i < graph.length; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph by remapping the k-th group to k + n imaginary node. + for (int i = 0; i < group.length; ++i) { + if (group[i] == -1) + continue; + graph[group[i] + n].add(i); + ++inDegrees[i]; + } + + for (int i = 0; i < beforeItems.size(); ++i) + for (final int b : beforeItems.get(i)) { + final int u = group[b] == -1 ? b : group[b] + n; + final int v = group[i] == -1 ? i : group[i] + n; + if (u == v) { // u and v are already in the same group. + graph[b].add(i); + ++inDegrees[i]; + } else { + graph[u].add(v); + ++inDegrees[v]; + } + } + + // Perform topological sorting. + List ans = new ArrayList<>(); + + for (int i = 0; i < n + m; ++i) + if (inDegrees[i] == 0) // inDegrees[i] == -1 means visited. + dfs(graph, i, inDegrees, n, ans); + + return ans.size() == n ? ans.stream().mapToInt(Integer::intValue).toArray() : new int[] {}; + } + + private void dfs(List[] graph, int u, int[] inDegrees, int n, List ans) { + if (u < n) + ans.add(u); + + inDegrees[u] = -1; // Mark as visited. + + for (final int v : graph[u]) + if (--inDegrees[v] == 0) + dfs(graph, v, inDegrees, n, ans); + } +} diff --git a/solutions/1204. Last Person to Fit in the Bus/1204.sql b/solutions/1204. Last Person to Fit in the Bus/1204.sql new file mode 100644 index 00000000000..13eca482772 --- /dev/null +++ b/solutions/1204. Last Person to Fit in the Bus/1204.sql @@ -0,0 +1,12 @@ +WITH + AccumulatedQueue AS ( + SELECT + person_name, + SUM(weight) OVER(ORDER BY turn) AS accumulated_weight + FROM Queue + ) +SELECT person_name +FROM AccumulatedQueue +WHERE accumulated_weight <= 1000 +ORDER BY accumulated_weight DESC +LIMIT 1; diff --git a/solutions/1205. Monthly Transactions II/1205.sql b/solutions/1205. Monthly Transactions II/1205.sql new file mode 100644 index 00000000000..e79b5566691 --- /dev/null +++ b/solutions/1205. Monthly Transactions II/1205.sql @@ -0,0 +1,30 @@ +WITH + ApprovedTransactionsAndChargebacks AS ( + SELECT + id, + country, + state, + amount, + DATE_FORMAT(trans_date, '%Y-%m') AS `month` + FROM Transactions + WHERE state = 'approved' + UNION ALL + SELECT + trans_id AS id, + country, + 'chargeback' AS state, + amount, + DATE_FORMAT(Chargebacks.trans_date, '%Y-%m') AS `month` + FROM Chargebacks + LEFT JOIN Transactions + ON (Chargebacks.trans_id = Transactions.id) + ) +SELECT + `month`, + country, + SUM(state = 'approved') AS approved_count, + SUM(IF(state = 'approved', amount, 0)) AS approved_amount, + SUM(state = 'chargeback') AS chargeback_count, + SUM(IF(state = 'chargeback', amount, 0)) AS chargeback_amount +FROM ApprovedTransactionsAndChargebacks +GROUP BY 1, 2; diff --git a/solutions/1206. Design Skiplist/1206.cpp b/solutions/1206. Design Skiplist/1206.cpp new file mode 100644 index 00000000000..78c8eaa6b3c --- /dev/null +++ b/solutions/1206. Design Skiplist/1206.cpp @@ -0,0 +1,63 @@ +struct Node { + int val; + shared_ptr next; + shared_ptr down; + Node(int val = -1, shared_ptr next = nullptr, + shared_ptr down = nullptr) + : val(val), next(next), down(down) {} +}; + +class Skiplist { + public: + bool search(int target) { + for (shared_ptr node = dummy; node; node = node->down) { + advance(node, target); + if (node->next && node->next->val == target) + return true; + } + return false; + } + + void add(int num) { + // Collect nodes that are before the insertion point. + stack> nodes; + for (shared_ptr node = dummy; node; node = node->down) { + advance(node, num); + nodes.push(node); + } + + shared_ptr down; + bool shouldInsert = true; + while (shouldInsert && !nodes.empty()) { + shared_ptr prev = nodes.top(); + nodes.pop(); + prev->next = make_shared(num, prev->next, down); + down = prev->next; + shouldInsert = rand() % 2 == 1; + } + + // Create a topmost new level dummy that points to the existing dummy. + if (shouldInsert) + dummy = make_shared(-1, nullptr, dummy); + } + + bool erase(int num) { + bool found = false; + for (shared_ptr node = dummy; node; node = node->down) { + advance(node, num); + if (node->next && node->next->val == num) { + node->next = node->next->next; + found = true; + } + } + return found; + } + + private: + shared_ptr dummy = make_shared(-1); + + void advance(shared_ptr& node, int target) { + while (node->next && node->next->val < target) + node = node->next; + } +}; diff --git a/solutions/1206. Design Skiplist/1206.java b/solutions/1206. Design Skiplist/1206.java new file mode 100644 index 00000000000..f30262701d6 --- /dev/null +++ b/solutions/1206. Design Skiplist/1206.java @@ -0,0 +1,63 @@ +class Node { + public int val; + public Node next; + public Node down; + public Node(int val, Node next, Node down) { + this.val = val; + this.next = next; + this.down = down; + } +} + +class Skiplist { + public boolean search(int target) { + for (Node node = dummy; node != null; node = node.down) { + node = advance(node, target); + if (node.next != null && node.next.val == target) + return true; + } + return false; + } + + public void add(int num) { + // Collect nodes that are before the insertion point. + Deque nodes = new ArrayDeque<>(); + for (Node node = dummy; node != null; node = node.down) { + node = advance(node, num); + nodes.push(node); + } + + Node down = null; + boolean shouldInsert = true; + while (shouldInsert && !nodes.isEmpty()) { + Node prev = nodes.poll(); + prev.next = new Node(num, prev.next, down); + down = prev.next; + shouldInsert = Math.random() < 0.5; + } + + // Create a topmost new level dummy that points to the existing dummy. + if (shouldInsert) + dummy = new Node(-1, null, dummy); + } + + public boolean erase(int num) { + boolean found = false; + for (Node node = dummy; node != null; node = node.down) { + node = advance(node, num); + if (node.next != null && node.next.val == num) { + node.next = node.next.next; + found = true; + } + } + return found; + } + + private Node dummy = new Node(-1, null, null); + + private Node advance(Node node, int target) { + while (node.next != null && node.next.val < target) + node = node.next; + return node; + } +} diff --git a/solutions/1206. Design Skiplist/1206.py b/solutions/1206. Design Skiplist/1206.py new file mode 100644 index 00000000000..a46d77d9eca --- /dev/null +++ b/solutions/1206. Design Skiplist/1206.py @@ -0,0 +1,63 @@ +class Node: + def __init__(self, val=-1, next=None, down=None): + self.val = val + self.next = next + self.down = down + + +class Skiplist: + def __init__(self): + self.dummy = Node() + + def search(self, target: int) -> bool: + node = self.dummy + while node: + while node.next and node.next.val < target: + node = node.next + if node.next and node.next.val == target: + return True + # Move to the next level + node = node.down + return False + + def add(self, num: int) -> None: + # Collect nodes that are before the insertion point. + nodes = [] + node = self.dummy + while node: + while node.next and node.next.val < num: + node = node.next + nodes.append(node) + # Move to the next level + node = node.down + + shouldInsert = True + down = None + while shouldInsert and nodes: + node = nodes.pop() + node.next = Node(num, node.next, down) + down = node.next + shouldInsert = random.getrandbits(1) == 0 + + # Create a topmost new level dummy that points to the existing dummy. + if shouldInsert: + self.dummy = Node(-1, None, self.dummy) + + def erase(self, num: int) -> bool: + node = self.dummy + found = False + while node: + while node.next and node.next.val < num: + node = node.next + if node.next and node.next.val == num: + # Delete the node + node.next = node.next.next + found = True + # Move to the next level + node = node.down + return found + + # Move to the node s.t. node.next.val >= target + def _advance(self, node: Node, target: int) -> None: + while node.next and node.next.val < target: + node = node.next diff --git a/solutions/1207. Unique Number of Occurrences/1207.cpp b/solutions/1207. Unique Number of Occurrences/1207.cpp new file mode 100644 index 00000000000..355f7dcfa77 --- /dev/null +++ b/solutions/1207. Unique Number of Occurrences/1207.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool uniqueOccurrences(vector& arr) { + unordered_map count; + unordered_set occurrences; + + for (const int a : arr) + ++count[a]; + + for (const auto& [_, value] : count) + if (!occurrences.insert(value).second) + return false; + + return true; + } +}; diff --git a/solutions/1207. Unique Number of Occurrences/1207.java b/solutions/1207. Unique Number of Occurrences/1207.java new file mode 100644 index 00000000000..922377fc6ed --- /dev/null +++ b/solutions/1207. Unique Number of Occurrences/1207.java @@ -0,0 +1,15 @@ +class Solution { + public boolean uniqueOccurrences(int[] arr) { + Map count = new HashMap<>(); + Set occurrences = new HashSet<>(); + + for (final int a : arr) + count.merge(a, 1, Integer::sum); + + for (final int value : count.values()) + if (!occurrences.add(value)) + return false; + + return true; + } +} diff --git a/solutions/1207. Unique Number of Occurrences/1207.py b/solutions/1207. Unique Number of Occurrences/1207.py new file mode 100644 index 00000000000..0e95a4b5367 --- /dev/null +++ b/solutions/1207. Unique Number of Occurrences/1207.py @@ -0,0 +1,11 @@ +class Solution: + def uniqueOccurrences(self, arr: List[int]) -> bool: + count = collections.Counter(arr) + occurrences = set() + + for value in count.values(): + if value in occurrences: + return False + occurrences.add(value) + + return True diff --git a/solutions/1208. Get Equal Substrings Within Budget/1208.cpp b/solutions/1208. Get Equal Substrings Within Budget/1208.cpp new file mode 100644 index 00000000000..020372f69c4 --- /dev/null +++ b/solutions/1208. Get Equal Substrings Within Budget/1208.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int equalSubstring(string s, string t, int maxCost) { + int j = 0; + for (int i = 0; i < s.length(); ++i) { + maxCost -= abs(s[i] - t[i]); + if (maxCost < 0) + maxCost += abs(s[j] - t[j++]); + } + + return s.length() - j; + } +}; diff --git a/solutions/1208. Get Equal Substrings Within Budget/1208.java b/solutions/1208. Get Equal Substrings Within Budget/1208.java new file mode 100644 index 00000000000..47f5c0f5696 --- /dev/null +++ b/solutions/1208. Get Equal Substrings Within Budget/1208.java @@ -0,0 +1,12 @@ +class Solution { + public int equalSubstring(String s, String t, int maxCost) { + int j = 0; + for (int i = 0; i < s.length(); ++i) { + maxCost -= Math.abs(s.charAt(i) - t.charAt(i)); + if (maxCost < 0) + maxCost += Math.abs(s.charAt(j) - t.charAt(j++)); + } + + return s.length() - j; + } +} diff --git a/solutions/1208. Get Equal Substrings Within Budget/1208.py b/solutions/1208. Get Equal Substrings Within Budget/1208.py new file mode 100644 index 00000000000..a24fad17058 --- /dev/null +++ b/solutions/1208. Get Equal Substrings Within Budget/1208.py @@ -0,0 +1,10 @@ +class Solution: + def equalSubstring(self, s: str, t: str, maxCost: int) -> int: + j = 0 + for i in range(len(s)): + maxCost -= abs(ord(s[i]) - ord(t[i])) + if maxCost < 0: + maxCost += abs(ord(s[j]) - ord(t[j])) + j += 1 + + return len(s) - j diff --git a/solutions/1209. Remove All Adjacent Duplicates in String II/1209.cpp b/solutions/1209. Remove All Adjacent Duplicates in String II/1209.cpp new file mode 100644 index 00000000000..c6c941d3a70 --- /dev/null +++ b/solutions/1209. Remove All Adjacent Duplicates in String II/1209.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string removeDuplicates(const string& s, int k) { + string ans; + vector> stack; + + for (const char c : s) + if (stack.empty() || stack.back().first != c) + stack.emplace_back(c, 1); + else if (++stack.back().second == k) // stack[-1] == c + stack.pop_back(); + + for (const auto& [c, count] : stack) + ans.append(count, c); + + return ans; + } +}; diff --git a/solutions/1209. Remove All Adjacent Duplicates in String II/1209.java b/solutions/1209. Remove All Adjacent Duplicates in String II/1209.java new file mode 100644 index 00000000000..32baffbcbc7 --- /dev/null +++ b/solutions/1209. Remove All Adjacent Duplicates in String II/1209.java @@ -0,0 +1,33 @@ +class Item { + char c; + int freq; + + public Item(char c, int freq) { + this.c = c; + this.freq = freq; + } +} + +class Solution { + public String removeDuplicates(String s, int k) { + StringBuilder sb = new StringBuilder(); + LinkedList stack = new LinkedList<>(); + + for (final char c : s.toCharArray()) { + if (!stack.isEmpty() && stack.peek().c == c) + ++stack.peek().freq; + else + stack.push(new Item(c, 1)); + if (stack.peek().freq == k) + stack.pop(); + } + + while (!stack.isEmpty()) { + Item item = stack.pop(); + for (int i = 0; i < item.freq; ++i) + sb.append(item.c); + } + + return sb.reverse().toString(); + } +} diff --git a/solutions/1209. Remove All Adjacent Duplicates in String II/1209.py b/solutions/1209. Remove All Adjacent Duplicates in String II/1209.py new file mode 100644 index 00000000000..606ed706fdb --- /dev/null +++ b/solutions/1209. Remove All Adjacent Duplicates in String II/1209.py @@ -0,0 +1,13 @@ +class Solution: + def removeDuplicates(self, s: str, k: int) -> str: + stack = [] + + for c in s: + if not stack or stack[-1][0] != c: + stack.append([c, 1]) + else: # stack[-1][0] == c + stack[-1][1] += 1 + if stack[-1][1] == k: + stack.pop() + + return ''.join(c * count for c, count in stack) diff --git a/solutions/121. Best Time to Buy and Sell Stock/121.cpp b/solutions/121. Best Time to Buy and Sell Stock/121.cpp new file mode 100644 index 00000000000..ac544557f13 --- /dev/null +++ b/solutions/121. Best Time to Buy and Sell Stock/121.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxProfit(vector& prices) { + int sellOne = 0; + int holdOne = INT_MIN; + + for (const int price : prices) { + sellOne = max(sellOne, holdOne + price); + holdOne = max(holdOne, -price); + } + + return sellOne; + } +}; diff --git a/solutions/121. Best Time to Buy and Sell Stock/121.java b/solutions/121. Best Time to Buy and Sell Stock/121.java new file mode 100644 index 00000000000..c02c9956f8b --- /dev/null +++ b/solutions/121. Best Time to Buy and Sell Stock/121.java @@ -0,0 +1,13 @@ +class Solution { + public int maxProfit(int[] prices) { + int sellOne = 0; + int holdOne = Integer.MIN_VALUE; + + for (final int price : prices) { + sellOne = Math.max(sellOne, holdOne + price); + holdOne = Math.max(holdOne, -price); + } + + return sellOne; + } +} diff --git a/solutions/121. Best Time to Buy and Sell Stock/121.py b/solutions/121. Best Time to Buy and Sell Stock/121.py new file mode 100644 index 00000000000..22d80b40be1 --- /dev/null +++ b/solutions/121. Best Time to Buy and Sell Stock/121.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + sellOne = 0 + holdOne = -math.inf + + for price in prices: + sellOne = max(sellOne, holdOne + price) + holdOne = max(holdOne, -price) + + return sellOne diff --git a/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.cpp b/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.cpp new file mode 100644 index 00000000000..5f81756f1ed --- /dev/null +++ b/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.cpp @@ -0,0 +1,65 @@ +enum class Pos { kHorizontal, kVertical }; + +class Solution { + public: + int minimumMoves(vector>& grid) { + const int n = grid.size(); + int ans = 0; + // the state of (x, y, pos) + // pos := 0 (horizontal) / 1 (vertical) + queue> q{{{0, 0, Pos::kHorizontal}}}; + vector>> seen(n, + vector>(n, vector(2))); + seen[0][0][static_cast(Pos::kHorizontal)] = true; + + auto canMoveRight = [&](int x, int y, Pos pos) -> bool { + if (pos == Pos::kHorizontal) + return y + 2 < n && !grid[x][y + 2]; + return y + 1 < n && !grid[x][y + 1] && !grid[x + 1][y + 1]; + }; + + auto canMoveDown = [&](int x, int y, Pos pos) -> bool { + if (pos == Pos::kVertical) + return x + 2 < n && !grid[x + 2][y]; + return x + 1 < n && !grid[x + 1][y] && !grid[x + 1][y + 1]; + }; + + auto canRotateClockwise = [&](int x, int y, Pos pos) -> bool { + return pos == Pos::kHorizontal && x + 1 < n && !grid[x + 1][y + 1] && + !grid[x + 1][y]; + }; + + auto canRotateCounterclockwise = [&](int x, int y, Pos pos) -> bool { + return pos == Pos::kVertical && y + 1 < n && !grid[x + 1][y + 1] && + !grid[x][y + 1]; + }; + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const auto [x, y, pos] = q.front(); + q.pop(); + if (x == n - 1 && y == n - 2 && pos == Pos::kHorizontal) + return ans; + if (canMoveRight(x, y, pos) && !seen[x][y + 1][static_cast(pos)]) { + q.emplace(x, y + 1, pos); + seen[x][y + 1][static_cast(pos)] = true; + } + if (canMoveDown(x, y, pos) && !seen[x + 1][y][static_cast(pos)]) { + q.emplace(x + 1, y, pos); + seen[x + 1][y][static_cast(pos)] = true; + } + const Pos newPos = + pos == Pos::kHorizontal ? Pos::kVertical : Pos::kHorizontal; + if ((canRotateClockwise(x, y, pos) || + canRotateCounterclockwise(x, y, pos)) && + !seen[x][y][static_cast(newPos)]) { + q.emplace(x, y, newPos); + seen[x][y][static_cast(newPos)] = true; + } + } + ++ans; + } + + return -1; + } +}; diff --git a/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.java b/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.java new file mode 100644 index 00000000000..3a94c7f68c8 --- /dev/null +++ b/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.java @@ -0,0 +1,63 @@ +enum Pos { kHorizontal, kVertical } + +class Solution { + public int minimumMoves(int[][] grid) { + final int n = grid.length; + int ans = 0; + // the state of (x, y, pos) + // pos := 0 (horizontal) / 1 (vertical) + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {0, 0, Pos.kHorizontal.ordinal()})); + boolean[][][] seen = new boolean[n][n][2]; + seen[0][0][Pos.kHorizontal.ordinal()] = true; + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int x = q.peek()[0]; + final int y = q.peek()[1]; + final int pos = q.poll()[2]; + if (x == n - 1 && y == n - 2 && pos == Pos.kHorizontal.ordinal()) + return ans; + if (canMoveRight(grid, x, y, pos) && !seen[x][y + 1][pos]) { + q.offer(new int[] {x, y + 1, pos}); + seen[x][y + 1][pos] = true; + } + if (canMoveDown(grid, x, y, pos) && !seen[x + 1][y][pos]) { + q.offer(new int[] {x + 1, y, pos}); + seen[x + 1][y][pos] = true; + } + final int newPos = + pos == Pos.kHorizontal.ordinal() ? Pos.kVertical.ordinal() : Pos.kHorizontal.ordinal(); + if ((canRotateClockwise(grid, x, y, pos) || canRotateCounterclockwise(grid, x, y, pos)) && + !seen[x][y][newPos]) { + q.offer(new int[] {x, y, newPos}); + seen[x][y][newPos] = true; + } + } + ++ans; + } + + return -1; + } + + private boolean canMoveRight(int[][] grid, int x, int y, int pos) { + if (pos == Pos.kHorizontal.ordinal()) + return y + 2 < grid.length && grid[x][y + 2] == 0; + return y + 1 < grid.length && grid[x][y + 1] == 0 && grid[x + 1][y + 1] == 0; + } + + private boolean canMoveDown(int[][] grid, int x, int y, int pos) { + if (pos == Pos.kVertical.ordinal()) + return x + 2 < grid.length && grid[x + 2][y] == 0; + return x + 1 < grid.length && grid[x + 1][y] == 0 && grid[x + 1][y + 1] == 0; + }; + + private boolean canRotateClockwise(int[][] grid, int x, int y, int pos) { + return pos == Pos.kHorizontal.ordinal() && x + 1 < grid.length && grid[x + 1][y + 1] == 0 && + grid[x + 1][y] == 0; + }; + + private boolean canRotateCounterclockwise(int[][] grid, int x, int y, int pos) { + return pos == Pos.kVertical.ordinal() && y + 1 < grid.length && grid[x + 1][y + 1] == 0 && + grid[x][y + 1] == 0; + }; +} diff --git a/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.py b/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.py new file mode 100644 index 00000000000..9745ee0da71 --- /dev/null +++ b/solutions/1210. Minimum Moves to Reach Target with Rotations/1210.py @@ -0,0 +1,54 @@ +from enum import IntEnum + + +class Pos(IntEnum): + kHorizontal = 0 + kVertical = 1 + + +class Solution: + def minimumMoves(self, grid: List[List[int]]) -> int: + n = len(grid) + ans = 0 + # the state of (x, y, pos) + # pos := 0 (horizontal) / 1 (vertical) + q = collections.deque([(0, 0, Pos.kHorizontal)]) + seen = {(0, 0, Pos.kHorizontal)} + + def canMoveRight(x: int, y: int, pos: Pos) -> bool: + if pos == Pos.kHorizontal: + return y + 2 < n and not grid[x][y + 2] + return y + 1 < n and not grid[x][y + 1] and not grid[x + 1][y + 1] + + def canMoveDown(x: int, y: int, pos: Pos) -> bool: + if pos == Pos.kVertical: + return x + 2 < n and not grid[x + 2][y] + return x + 1 < n and not grid[x + 1][y] and not grid[x + 1][y + 1] + + def canRotateClockwise(x: int, y: int, pos: Pos) -> bool: + return pos == Pos.kHorizontal and x + 1 < n and \ + not grid[x + 1][y + 1] and not grid[x + 1][y] + + def canRotateCounterclockwise(x: int, y: int, pos: Pos) -> bool: + return pos == Pos.kVertical and y + 1 < n and \ + not grid[x + 1][y + 1] and not grid[x][y + 1] + + while q: + for _ in range(len(q)): + x, y, pos = q.popleft() + if x == n - 1 and y == n - 2 and pos == Pos.kHorizontal: + return ans + if canMoveRight(x, y, pos) and (x, y + 1, pos) not in seen: + q.append((x, y + 1, pos)) + seen.add((x, y + 1, pos)) + if canMoveDown(x, y, pos) and (x + 1, y, pos) not in seen: + q.append((x + 1, y, pos)) + seen.add((x + 1, y, pos)) + newPos = Pos.kVertical if pos == Pos.kHorizontal else Pos.kHorizontal + if (canRotateClockwise(x, y, pos) or canRotateCounterclockwise(x, y, pos)) and \ + (x, y, newPos) not in seen: + q.append((x, y, newPos)) + seen.add((x, y, newPos)) + ans += 1 + + return -1 diff --git a/solutions/1211. Queries Quality and Percentage/1211.sql b/solutions/1211. Queries Quality and Percentage/1211.sql new file mode 100644 index 00000000000..07ed9cbedcb --- /dev/null +++ b/solutions/1211. Queries Quality and Percentage/1211.sql @@ -0,0 +1,6 @@ +SELECT + query_name, + ROUND(AVG(rating / position), 2) AS quality, + ROUND(AVG(rating < 3) * 100, 2) AS poor_query_percentage +FROM Queries +GROUP BY 1; diff --git a/solutions/1212. Team Scores in Football Tournament/1212.sql b/solutions/1212. Team Scores in Football Tournament/1212.sql new file mode 100644 index 00000000000..33d26b9f3ca --- /dev/null +++ b/solutions/1212. Team Scores in Football Tournament/1212.sql @@ -0,0 +1,29 @@ +WITH + TwoWayMatches AS ( + SELECT + host_team AS team_id, + host_goals AS goals, + guest_goals AS opponent_goals + FROM Matches + UNION ALL + SELECT + guest_team, + guest_goals, + host_goals + FROM Matches + ) +SELECT + Teams.team_id, + Teams.team_name, + SUM( + CASE + WHEN goals > opponent_goals THEN 3 + WHEN goals = opponent_goals THEN 1 + ELSE 0 + END + ) AS num_points +FROM Teams +LEFT JOIN TwoWayMatches + USING (team_id) +GROUP BY 1 +ORDER BY num_points DESC, team_id; diff --git a/solutions/1213. Intersection of Three Sorted Arrays/1213.cpp b/solutions/1213. Intersection of Three Sorted Arrays/1213.cpp new file mode 100644 index 00000000000..e66e7f1288d --- /dev/null +++ b/solutions/1213. Intersection of Three Sorted Arrays/1213.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector arraysIntersection(vector& arr1, vector& arr2, + vector& arr3) { + vector ans; + int i = 0; + int j = 0; + int k = 0; + + while (i < arr1.size() && j < arr2.size() && k < arr3.size()) { + const int mn = min({arr1[i], arr2[j], arr3[k]}); + if (arr1[i] == mn && arr2[j] == mn && arr3[k] == mn) { + ans.push_back(mn); + ++i; + ++j; + ++k; + } else if (arr1[i] == mn) { + ++i; + } else if (arr2[j] == mn) { + ++j; + } else { + ++k; + } + } + + return ans; + } +}; diff --git a/solutions/1213. Intersection of Three Sorted Arrays/1213.java b/solutions/1213. Intersection of Three Sorted Arrays/1213.java new file mode 100644 index 00000000000..290cc14eb76 --- /dev/null +++ b/solutions/1213. Intersection of Three Sorted Arrays/1213.java @@ -0,0 +1,26 @@ +class Solution { + public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { + List ans = new ArrayList<>(); + int i = 0; + int j = 0; + int k = 0; + + while (i < arr1.length && j < arr2.length && k < arr3.length) { + final int mn = Math.min(arr1[i], Math.min(arr2[j], arr3[k])); + if (arr1[i] == mn && arr2[j] == mn && arr3[k] == mn) { + ans.add(mn); + ++i; + ++j; + ++k; + } else if (arr1[i] == mn) { + ++i; + } else if (arr2[j] == mn) { + ++j; + } else { + ++k; + } + } + + return ans; + } +} diff --git a/solutions/1214. Two Sum BSTs/1214.cpp b/solutions/1214. Two Sum BSTs/1214.cpp new file mode 100644 index 00000000000..be0e1870b35 --- /dev/null +++ b/solutions/1214. Two Sum BSTs/1214.cpp @@ -0,0 +1,51 @@ +class BSTIterator { + public: + BSTIterator(TreeNode* root, bool leftToRight) : leftToRight(leftToRight) { + pushUntilNull(root); + } + + bool hasNext() { + return !stack.empty(); + } + + int next() { + TreeNode* root = stack.top(); + stack.pop(); + pushUntilNull(leftToRight ? root->right : root->left); + return root->val; + } + + private: + stack stack; + bool leftToRight; + + void pushUntilNull(TreeNode* root) { + while (root != nullptr) { + stack.push(root); + root = leftToRight ? root->left : root->right; + } + } +}; + +class Solution { + public: + bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) { + BSTIterator bst1(root1, true); + BSTIterator bst2(root2, false); + + for (int l = bst1.next(), r = bst2.next(); true;) { + const int sum = l + r; + if (sum == target) + return true; + if (sum < target) { + if (!bst1.hasNext()) + return false; + l = bst1.next(); + } else { + if (!bst2.hasNext()) + return false; + r = bst2.next(); + } + } + } +}; diff --git a/solutions/1214. Two Sum BSTs/1214.java b/solutions/1214. Two Sum BSTs/1214.java new file mode 100644 index 00000000000..212f7fbcd68 --- /dev/null +++ b/solutions/1214. Two Sum BSTs/1214.java @@ -0,0 +1,48 @@ +class BSTIterator { + BSTIterator(TreeNode root, boolean leftToRight) { + this.leftToRight = leftToRight; + pushUntilNull(root); + } + + public boolean hasNext() { + return !stack.isEmpty(); + } + + public int next() { + TreeNode root = stack.pop(); + pushUntilNull(leftToRight ? root.right : root.left); + return root.val; + } + + private Deque stack = new ArrayDeque<>(); + private boolean leftToRight; + + private void pushUntilNull(TreeNode root) { + while (root != null) { + stack.push(root); + root = leftToRight ? root.left : root.right; + } + } +} + +class Solution { + public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) { + BSTIterator bst1 = new BSTIterator(root1, true); + BSTIterator bst2 = new BSTIterator(root2, false); + + for (int l = bst1.next(), r = bst2.next(); true;) { + final int sum = l + r; + if (sum == target) + return true; + if (sum < target) { + if (!bst1.hasNext()) + return false; + l = bst1.next(); + } else { + if (!bst2.hasNext()) + return false; + r = bst2.next(); + } + } + } +} diff --git a/solutions/1214. Two Sum BSTs/1214.py b/solutions/1214. Two Sum BSTs/1214.py new file mode 100644 index 00000000000..ba49d06958b --- /dev/null +++ b/solutions/1214. Two Sum BSTs/1214.py @@ -0,0 +1,42 @@ +class BSTIterator: + def __init__(self, root: Optional[TreeNode], leftToRight: bool): + self.stack = [] + self.leftToRight = leftToRight + self._pushUntilNone(root) + + def hasNext(self) -> bool: + return len(self.stack) > 0 + + def next(self) -> int: + node = self.stack.pop() + if self.leftToRight: + self._pushUntilNone(node.right) + else: + self._pushUntilNone(node.left) + return node.val + + def _pushUntilNone(self, root: Optional[TreeNode]): + while root: + self.stack.append(root) + root = root.left if self.leftToRight else root.right + + +class Solution: + def twoSumBSTs(self, root1: Optional[TreeNode], root2: Optional[TreeNode], target: int) -> bool: + bst1 = BSTIterator(root1, True) + bst2 = BSTIterator(root2, False) + + l = bst1.next() + r = bst2.next() + while True: + summ = l + r + if summ == target: + return True + if summ < target: + if not bst1.hasNext(): + return False + l = bst1.next() + else: + if not bst2.hasNext(): + return False + r = bst2.next() diff --git a/solutions/1215. Stepping Numbers/1215-2.cpp b/solutions/1215. Stepping Numbers/1215-2.cpp new file mode 100644 index 00000000000..fd87e0cceda --- /dev/null +++ b/solutions/1215. Stepping Numbers/1215-2.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector countSteppingNumbers(int low, int high) { + vector ans; + if (low == 0) + ans.push_back(0); + + for (int i = 1; i <= 9; ++i) + dfs(i, low, high, ans); + + ranges::sort(ans); + return ans; + } + + private: + void dfs(long curr, int low, int high, vector& ans) { + if (curr > high) + return; + if (curr >= low) + ans.push_back(curr); + + const int lastDigit = curr % 10; + if (lastDigit > 0) + dfs(curr * 10 + lastDigit - 1, low, high, ans); + if (lastDigit < 9) + dfs(curr * 10 + lastDigit + 1, low, high, ans); + } +}; diff --git a/solutions/1215. Stepping Numbers/1215-2.java b/solutions/1215. Stepping Numbers/1215-2.java new file mode 100644 index 00000000000..31a21e0e58a --- /dev/null +++ b/solutions/1215. Stepping Numbers/1215-2.java @@ -0,0 +1,26 @@ +class Solution { + public List countSteppingNumbers(int low, int high) { + List ans = new ArrayList<>(); + if (low == 0) + ans.add(0); + + for (long i = 1; i <= 9; ++i) + dfs(i, low, high, ans); + + Collections.sort(ans); + return ans; + } + + private void dfs(long curr, int low, int high, List ans) { + if (curr > high) + return; + if (curr >= low) + ans.add((int) curr); + + final long lastDigit = curr % 10; + if (lastDigit > 0) + dfs(curr * 10 + lastDigit - 1, low, high, ans); + if (lastDigit < 9) + dfs(curr * 10 + lastDigit + 1, low, high, ans); + } +} diff --git a/solutions/1215. Stepping Numbers/1215-2.py b/solutions/1215. Stepping Numbers/1215-2.py new file mode 100644 index 00000000000..d7e089fe29d --- /dev/null +++ b/solutions/1215. Stepping Numbers/1215-2.py @@ -0,0 +1,21 @@ +class Solution: + def countSteppingNumbers(self, low: int, high: int) -> List[int]: + ans = [0] if low == 0 else [] + + def dfs(curr: int) -> None: + if curr > high: + return + if curr >= low: + ans.append(curr) + + lastDigit = curr % 10 + if lastDigit > 0: + dfs(curr * 10 + lastDigit - 1) + if lastDigit < 9: + dfs(curr * 10 + lastDigit + 1) + + for i in range(1, 9 + 1): + dfs(i) + + ans.sort() + return ans diff --git a/solutions/1215. Stepping Numbers/1215.cpp b/solutions/1215. Stepping Numbers/1215.cpp new file mode 100644 index 00000000000..68e5dee39e9 --- /dev/null +++ b/solutions/1215. Stepping Numbers/1215.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector countSteppingNumbers(int low, int high) { + vector ans; + if (low == 0) + ans.push_back(0); + + queue q; + + for (int i = 1; i <= 9; ++i) + q.push(i); + + while (!q.empty()) { + const long curr = q.front(); + q.pop(); + if (curr > high) + continue; + if (curr >= low) + ans.push_back(curr); + const int lastDigit = curr % 10; + if (lastDigit > 0) + q.push(curr * 10 + lastDigit - 1); + if (lastDigit < 9) + q.push(curr * 10 + lastDigit + 1); + } + + return ans; + } +}; diff --git a/solutions/1215. Stepping Numbers/1215.java b/solutions/1215. Stepping Numbers/1215.java new file mode 100644 index 00000000000..bde8d5d5f54 --- /dev/null +++ b/solutions/1215. Stepping Numbers/1215.java @@ -0,0 +1,27 @@ +class Solution { + public List countSteppingNumbers(int low, int high) { + List ans = new ArrayList<>(); + if (low == 0) + ans.add(0); + + Queue q = new ArrayDeque<>(); + + for (long i = 1; i <= 9; ++i) + q.offer(i); + + while (!q.isEmpty()) { + final long curr = q.poll(); + if (curr > high) + continue; + if (curr >= low) + ans.add((int) curr); + final long lastDigit = curr % 10; + if (lastDigit > 0) + q.offer(curr * 10 + lastDigit - 1); + if (lastDigit < 9) + q.offer(curr * 10 + lastDigit + 1); + } + + return ans; + } +} diff --git a/solutions/1215. Stepping Numbers/1215.py b/solutions/1215. Stepping Numbers/1215.py new file mode 100644 index 00000000000..4821d1217f9 --- /dev/null +++ b/solutions/1215. Stepping Numbers/1215.py @@ -0,0 +1,18 @@ +class Solution: + def countSteppingNumbers(self, low: int, high: int) -> List[int]: + ans = [0] if low == 0 else [] + q = collections.deque(list(range(1, 10))) + + while q: + curr = q.popleft() + if curr > high: + continue + if curr >= low: + ans.append(curr) + lastDigit = curr % 10 + if lastDigit > 0: + q.append(curr * 10 + lastDigit - 1) + if lastDigit < 9: + q.append(curr * 10 + lastDigit + 1) + + return ans diff --git a/solutions/1216. Valid Palindrome III/1216.cpp b/solutions/1216. Valid Palindrome III/1216.cpp new file mode 100644 index 00000000000..25322fed0c7 --- /dev/null +++ b/solutions/1216. Valid Palindrome III/1216.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool isValidPalindrome(string s, int k) { + return s.length() - longestPalindromeSubseq(s) <= k; + } + + private: + // Same as 516. Longest Palindromic Subsequence + int longestPalindromeSubseq(const string& s) { + const int n = s.length(); + // dp[i][j] := the length of LPS(s[i..j]) + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + if (s[i] == s[j]) + dp[i][j] = 2 + dp[i + 1][j - 1]; + else + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/1216. Valid Palindrome III/1216.java b/solutions/1216. Valid Palindrome III/1216.java new file mode 100644 index 00000000000..447f6ca2f8c --- /dev/null +++ b/solutions/1216. Valid Palindrome III/1216.java @@ -0,0 +1,26 @@ +class Solution { + public boolean isValidPalindrome(String s, int k) { + return s.length() - longestPalindromeSubseq(s) <= k; + } + + // Same as 516. Longest Palindromic Subsequence + private int longestPalindromeSubseq(final String s) { + final int n = s.length(); + // dp[i][j] := the length of LPS(s[i..j]) + int[][] dp = new int[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + if (s.charAt(i) == s.charAt(j)) + dp[i][j] = 2 + dp[i + 1][j - 1]; + else + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/1216. Valid Palindrome III/1216.py b/solutions/1216. Valid Palindrome III/1216.py new file mode 100644 index 00000000000..455961ae43f --- /dev/null +++ b/solutions/1216. Valid Palindrome III/1216.py @@ -0,0 +1,22 @@ +class Solution: + def isValidPalindrome(self, s: str, k: int) -> bool: + return len(s) - self._longestPalindromeSubseq(s) <= k + + # Same as 516. Longest Palindromic Subsequence + def _longestPalindromeSubseq(self, s: str) -> int: + n = len(s) + # dp[i][j] := the length of LPS(s[i..j]) + dp = [[0] * n for _ in range(n)] + + for i in range(n): + dp[i][i] = 1 + + for d in range(1, n): + for i in range(n - d): + j = i + d + if s[i] == s[j]: + dp[i][j] = 2 + dp[i + 1][j - 1] + else: + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) + + return dp[0][n - 1] diff --git a/solutions/1217. Play with Chips/1217.cpp b/solutions/1217. Play with Chips/1217.cpp new file mode 100644 index 00000000000..a8797239cad --- /dev/null +++ b/solutions/1217. Play with Chips/1217.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int minCostToMoveChips(vector& position) { + vector count(2); + for (const int p : position) + ++count[p % 2]; + return min(count[0], count[1]); + } +}; diff --git a/solutions/1217. Play with Chips/1217.java b/solutions/1217. Play with Chips/1217.java new file mode 100644 index 00000000000..56fa540d5a4 --- /dev/null +++ b/solutions/1217. Play with Chips/1217.java @@ -0,0 +1,8 @@ +class Solution { + public int minCostToMoveChips(int[] position) { + int[] count = new int[2]; + for (final int p : position) + ++count[p % 2]; + return Math.min(count[0], count[1]); + } +} diff --git a/solutions/1217. Play with Chips/1217.py b/solutions/1217. Play with Chips/1217.py new file mode 100644 index 00000000000..91c964fc7a1 --- /dev/null +++ b/solutions/1217. Play with Chips/1217.py @@ -0,0 +1,6 @@ +class Solution: + def minCostToMoveChips(self, position: List[int]) -> int: + count = [0] * 2 + for p in position: + count[p % 2] += 1 + return min(count[0], count[1]) diff --git a/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.cpp b/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.cpp new file mode 100644 index 00000000000..5e5ad60f408 --- /dev/null +++ b/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int longestSubsequence(vector& arr, int difference) { + int ans = 0; + unordered_map lengthAt; + + for (const int a : arr) { + if (const auto it = lengthAt.find(a - difference); it != lengthAt.cend()) + lengthAt[a] = it->second + 1; + else + lengthAt[a] = 1; + ans = max(ans, lengthAt[a]); + } + + return ans; + } +}; diff --git a/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.java b/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.java new file mode 100644 index 00000000000..a26a680ecee --- /dev/null +++ b/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.java @@ -0,0 +1,13 @@ +class Solution { + public int longestSubsequence(int[] arr, int difference) { + int ans = 0; + Map lengthAt = new HashMap<>(); + + for (final int a : arr) { + lengthAt.put(a, lengthAt.getOrDefault(a - difference, 0) + 1); + ans = Math.max(ans, lengthAt.get(a)); + } + + return ans; + } +} diff --git a/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.py b/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.py new file mode 100644 index 00000000000..f311e256f33 --- /dev/null +++ b/solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.py @@ -0,0 +1,10 @@ +class Solution: + def longestSubsequence(self, arr: List[int], difference: int) -> int: + ans = 0 + lengthAt = {} + + for a in arr: + lengthAt[a] = lengthAt.get(a - difference, 0) + 1 + ans = max(ans, lengthAt[a]) + + return ans diff --git a/solutions/1219. Path with Maximum Gold/1219.cpp b/solutions/1219. Path with Maximum Gold/1219.cpp new file mode 100644 index 00000000000..4badf0d0eb7 --- /dev/null +++ b/solutions/1219. Path with Maximum Gold/1219.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int getMaximumGold(vector>& grid) { + int ans = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + ans = max(ans, dfs(grid, i, j)); + + return ans; + } + + private: + int dfs(vector>& grid, int i, int j) { + if (i < 0 || j < 0 || i == grid.size() || j == grid[0].size()) + return 0; + if (grid[i][j] == 0) + return 0; + + const int gold = grid[i][j]; + grid[i][j] = 0; // Mark as visited. + const int maxPath = max({dfs(grid, i + 1, j), dfs(grid, i - 1, j), + dfs(grid, i, j + 1), dfs(grid, i, j - 1)}); + grid[i][j] = gold; + return gold + maxPath; + } +}; diff --git a/solutions/1219. Path with Maximum Gold/1219.java b/solutions/1219. Path with Maximum Gold/1219.java new file mode 100644 index 00000000000..016ad0aec63 --- /dev/null +++ b/solutions/1219. Path with Maximum Gold/1219.java @@ -0,0 +1,25 @@ +class Solution { + public int getMaximumGold(int[][] grid) { + int ans = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + ans = Math.max(ans, dfs(grid, i, j)); + + return ans; + } + + private int dfs(int[][] grid, int i, int j) { + if (i < 0 || j < 0 || i == grid.length || j == grid[0].length) + return 0; + if (grid[i][j] == 0) + return 0; + + final int gold = grid[i][j]; + grid[i][j] = 0; // Mark as visited. + final int maxPath = Math.max(Math.max(dfs(grid, i + 1, j), dfs(grid, i - 1, j)), + Math.max(dfs(grid, i, j + 1), dfs(grid, i, j - 1))); + grid[i][j] = gold; + return gold + maxPath; + } +} diff --git a/solutions/1219. Path with Maximum Gold/1219.py b/solutions/1219. Path with Maximum Gold/1219.py new file mode 100644 index 00000000000..b3301b8d8c7 --- /dev/null +++ b/solutions/1219. Path with Maximum Gold/1219.py @@ -0,0 +1,18 @@ +class Solution: + def getMaximumGold(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + if i < 0 or j < 0 or i == len(grid) or j == len(grid[0]): + return 0 + if grid[i][j] == 0: + return 0 + + gold = grid[i][j] + grid[i][j] = 0 # Mark as visited. + maxPath = max(dfs(i + 1, j), dfs(i - 1, j), + dfs(i, j + 1), dfs(i, j - 1)) + grid[i][j] = gold + return gold + maxPath + + return max(dfs(i, j) + for i in range(len(grid)) + for j in range(len(grid[0]))) diff --git a/solutions/122. Best Time to Buy and Sell Stock II/122.cpp b/solutions/122. Best Time to Buy and Sell Stock II/122.cpp new file mode 100644 index 00000000000..3df267b77b3 --- /dev/null +++ b/solutions/122. Best Time to Buy and Sell Stock II/122.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxProfit(vector& prices) { + int sell = 0; + int hold = INT_MIN; + + for (const int price : prices) { + sell = max(sell, hold + price); + hold = max(hold, sell - price); + } + + return sell; + } +}; diff --git a/solutions/122. Best Time to Buy and Sell Stock II/122.java b/solutions/122. Best Time to Buy and Sell Stock II/122.java new file mode 100644 index 00000000000..6c226635bdb --- /dev/null +++ b/solutions/122. Best Time to Buy and Sell Stock II/122.java @@ -0,0 +1,13 @@ +class Solution { + public int maxProfit(int[] prices) { + int sell = 0; + int hold = Integer.MIN_VALUE; + + for (final int price : prices) { + sell = Math.max(sell, hold + price); + hold = Math.max(hold, sell - price); + } + + return sell; + } +} diff --git a/solutions/122. Best Time to Buy and Sell Stock II/122.py b/solutions/122. Best Time to Buy and Sell Stock II/122.py new file mode 100644 index 00000000000..1f18bd480ac --- /dev/null +++ b/solutions/122. Best Time to Buy and Sell Stock II/122.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + sell = 0 + hold = -math.inf + + for price in prices: + sell = max(sell, hold + price) + hold = max(hold, sell - price) + + return sell diff --git a/solutions/1220. Count Vowels Permutation/1220.py b/solutions/1220. Count Vowels Permutation/1220.py new file mode 100644 index 00000000000..15dce6769f6 --- /dev/null +++ b/solutions/1220. Count Vowels Permutation/1220.py @@ -0,0 +1,14 @@ +class Solution: + def countVowelPermutation(self, n: int) -> int: + kMod = 1_000_000_007 + dp = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1} + + for _ in range(n - 1): + newDp = {'a': dp['e'] + dp['i'] + dp['u'], + 'e': dp['a'] + dp['i'], + 'i': dp['e'] + dp['o'], + 'o': dp['i'], + 'u': dp['i'] + dp['o']} + dp = newDp + + return sum(dp.values()) % kMod diff --git a/solutions/1221. Split a String in Balanced Strings/1221.cpp b/solutions/1221. Split a String in Balanced Strings/1221.cpp new file mode 100644 index 00000000000..c3eff222238 --- /dev/null +++ b/solutions/1221. Split a String in Balanced Strings/1221.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int balancedStringSplit(string s) { + int ans = 0; + int count = 0; + + for (const char c : s) { + count += c == 'L' ? 1 : -1; + if (count == 0) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1222. Queens That Can Attack the King/1222.cpp b/solutions/1222. Queens That Can Attack the King/1222.cpp new file mode 100644 index 00000000000..1d8adca6d3b --- /dev/null +++ b/solutions/1222. Queens That Can Attack the King/1222.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector> queensAttacktheKing(vector>& queens, + vector& king) { + vector> ans; + unordered_set queensSet; + + for (vector& queen : queens) + queensSet.insert(hash(queen[0], queen[1])); + + vector> directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, + {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + for (vector d : directions) + for (int i = king[0] + d[0], j = king[1] + d[1]; + 0 <= i && i < 8 && 0 <= j && j < 8; i += d[0], j += d[1]) + if (queensSet.contains(hash(i, j))) { + ans.push_back({i, j}); + break; + } + + return ans; + } + + private: + int hash(int i, int j) { + return i * 8 + j; + } +}; diff --git a/solutions/1222. Queens That Can Attack the King/1222.java b/solutions/1222. Queens That Can Attack the King/1222.java new file mode 100644 index 00000000000..13f12f6b458 --- /dev/null +++ b/solutions/1222. Queens That Can Attack the King/1222.java @@ -0,0 +1,25 @@ +class Solution { + public List> queensAttacktheKing(int[][] queens, int[] king) { + List> ans = new ArrayList<>(); + Set queensSet = new HashSet<>(); + + for (int[] queen : queens) + queensSet.add(hash(queen[0], queen[1])); + + int[][] directions = + new int[][] {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + for (int[] d : directions) + for (int i = king[0] + d[0], j = king[1] + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8; + i += d[0], j += d[1]) + if (queensSet.contains(hash(i, j))) { + ans.add(Arrays.asList(i, j)); + break; + } + + return ans; + } + + private int hash(int i, int j) { + return i * 8 + j; + } +} diff --git a/solutions/1222. Queens That Can Attack the King/1222.py b/solutions/1222. Queens That Can Attack the King/1222.py new file mode 100644 index 00000000000..147fefbc5b3 --- /dev/null +++ b/solutions/1222. Queens That Can Attack the King/1222.py @@ -0,0 +1,16 @@ +class Solution: + def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]: + ans = [] + queens = {(i, j) for i, j in queens} + + for d in [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]: + i = king[0] + d[0] + j = king[1] + d[1] + while 0 <= i < 8 and 0 <= j < 8: + if (i, j) in queens: + ans.append([i, j]) + break + i += d[0] + j += d[1] + + return ans diff --git a/solutions/1223. Dice Roll Simulation/1223.py b/solutions/1223. Dice Roll Simulation/1223.py new file mode 100644 index 00000000000..949602a944c --- /dev/null +++ b/solutions/1223. Dice Roll Simulation/1223.py @@ -0,0 +1,27 @@ +class Solution: + def dieSimulator(self, n: int, rollMax: List[int]) -> int: + kMaxRolls = 15 + kMod = 1_000_000_007 + + dp = [[[0] * (kMaxRolls + 1) for j in range(6)] for i in range(n + 1)] + + for num in range(6): + dp[1][num][1] = 1 + + for i in range(2, n + 1): + for currNum in range(6): + for prevNum in range(6): + for k in range(1, 15 + 1): + if prevNum != currNum: + dp[i][currNum][1] = ( + dp[i][currNum][1] + dp[i - 1][prevNum][k]) % kMod + elif k < rollMax[currNum]: + dp[i][currNum][k + 1] = dp[i - 1][currNum][k] + + ans = 0 + + for num in range(6): + for k in range(1, 15 + 1): + ans += dp[n][num][k] + + return ans % kMod diff --git a/solutions/1224. Maximum Equal Frequency/1224.cpp b/solutions/1224. Maximum Equal Frequency/1224.cpp new file mode 100644 index 00000000000..1c1532fa3a9 --- /dev/null +++ b/solutions/1224. Maximum Equal Frequency/1224.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maxEqualFreq(vector& nums) { + int ans = 0; + int maxFreq = 0; + unordered_map count; + unordered_map freq; + + for (int i = 0; i < nums.size(); ++i) { + const int num = nums[i]; + --freq[count[num]]; + ++count[num]; + ++freq[count[num]]; + maxFreq = max(maxFreq, count[num]); + if (maxFreq == 1 || maxFreq * freq[maxFreq] == i || + (maxFreq - 1) * (freq[maxFreq - 1] + 1) == i) + ans = i + 1; + } + + return ans; + } +}; diff --git a/solutions/1224. Maximum Equal Frequency/1224.java b/solutions/1224. Maximum Equal Frequency/1224.java new file mode 100644 index 00000000000..c07693982b4 --- /dev/null +++ b/solutions/1224. Maximum Equal Frequency/1224.java @@ -0,0 +1,22 @@ +class Solution { + public int maxEqualFreq(int[] nums) { + int ans = 0; + int maxFreq = 0; + Map count = new HashMap<>(); + Map freq = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + final int currentFreq = count.getOrDefault(nums[i], 0); + freq.merge(currentFreq, -1, Integer::sum); + final int updatedFreq = currentFreq + 1; + count.put(nums[i], updatedFreq); + freq.merge(updatedFreq, 1, Integer::sum); + maxFreq = Math.max(maxFreq, updatedFreq); + if (maxFreq == 1 || maxFreq * freq.get(maxFreq) == i || + (maxFreq - 1) * (freq.get(maxFreq - 1) + 1) == i) + ans = i + 1; + } + + return ans; + } +} diff --git a/solutions/1224. Maximum Equal Frequency/1224.py b/solutions/1224. Maximum Equal Frequency/1224.py new file mode 100644 index 00000000000..df4de26f6ef --- /dev/null +++ b/solutions/1224. Maximum Equal Frequency/1224.py @@ -0,0 +1,16 @@ +class Solution: + def maxEqualFreq(self, nums: List[int]) -> int: + ans = 0 + maxFreq = 0 + count = collections.Counter() + freq = collections.Counter() + + for i, num in enumerate(nums): + freq[count[num]] -= 1 + count[num] += 1 + freq[count[num]] += 1 + maxFreq = max(maxFreq, count[num]) + if maxFreq == 1 or maxFreq * freq[maxFreq] == i or (maxFreq - 1) * (freq[maxFreq - 1] + 1) == i: + ans = i + 1 + + return ans diff --git a/solutions/1225. Report Contiguous Dates/1225.sql b/solutions/1225. Report Contiguous Dates/1225.sql new file mode 100644 index 00000000000..608f2624bf8 --- /dev/null +++ b/solutions/1225. Report Contiguous Dates/1225.sql @@ -0,0 +1,31 @@ +WITH + RankedDatesPerState AS ( + SELECT + 'failed' AS state, + fail_date AS `date`, + RANK() OVER(ORDER BY fail_date) AS rank_per_state + FROM Failed + WHERE fail_date BETWEEN '2019-01-01' AND '2019-12-31' + UNION ALL + SELECT + 'succeeded' AS state, + success_date AS `date`, + RANK() OVER(ORDER BY success_date) AS rank_per_state + FROM Succeeded + WHERE success_date BETWEEN '2019-01-01' AND '2019-12-31' + ), + RankedDates AS ( + SELECT + state, + `date`, + rank_per_state, + RANK() OVER(ORDER BY `date`) AS `rank` + FROM RankedDatesPerState + ) +SELECT + state AS period_state, + MIN(`date`) AS start_date, + MAX(`date`) AS end_date +FROM RankedDates +GROUP BY state, (`rank` - rank_per_state) +ORDER BY start_date diff --git a/solutions/1226. The Dining Philosophers/1226.cpp b/solutions/1226. The Dining Philosophers/1226.cpp new file mode 100644 index 00000000000..0d1497e61ed --- /dev/null +++ b/solutions/1226. The Dining Philosophers/1226.cpp @@ -0,0 +1,16 @@ +class DiningPhilosophers { + std::mutex mutex; + + public: + void wantsToEat(int philosopher, function pickLeftFork, + function pickRightFork, function eat, + function putLeftFork, function putRightFork) { + mutex.lock(); + pickLeftFork(); + pickRightFork(); + eat(); + putLeftFork(); + putRightFork(); + mutex.unlock(); + } +}; diff --git a/solutions/1227. Airplane Seat Assignment Probability/1227.cpp b/solutions/1227. Airplane Seat Assignment Probability/1227.cpp new file mode 100644 index 00000000000..667e50a85f7 --- /dev/null +++ b/solutions/1227. Airplane Seat Assignment Probability/1227.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + double nthPersonGetsNthSeat(int n) { + return n == 1 ? 1 : 0.5; + } +}; diff --git a/solutions/1227. Airplane Seat Assignment Probability/1227.java b/solutions/1227. Airplane Seat Assignment Probability/1227.java new file mode 100644 index 00000000000..c7fd1052e5a --- /dev/null +++ b/solutions/1227. Airplane Seat Assignment Probability/1227.java @@ -0,0 +1,5 @@ +class Solution { + public double nthPersonGetsNthSeat(int n) { + return n == 1 ? 1 : 0.5; + } +} diff --git a/solutions/1227. Airplane Seat Assignment Probability/1227.py b/solutions/1227. Airplane Seat Assignment Probability/1227.py new file mode 100644 index 00000000000..f2d9826a7f1 --- /dev/null +++ b/solutions/1227. Airplane Seat Assignment Probability/1227.py @@ -0,0 +1,3 @@ +class Solution: + def nthPersonGetsNthSeat(self, n: int) -> float: + return 1 if n == 1 else 0.5 diff --git a/solutions/1228. Missing Number In Arithmetic Progression/1228.cpp b/solutions/1228. Missing Number In Arithmetic Progression/1228.cpp new file mode 100644 index 00000000000..0e08fcd3e2d --- /dev/null +++ b/solutions/1228. Missing Number In Arithmetic Progression/1228.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int missingNumber(vector& arr) { + const int n = arr.size(); + const int delta = (arr.back() - arr.front()) / n; + int l = 0; + int r = n - 1; + + while (l < r) { + const int m = (l + r) / 2; + if (arr[m] == arr[0] + m * delta) + l = m + 1; + else + r = m; + } + + return arr[0] + l * delta; + } +}; diff --git a/solutions/1228. Missing Number In Arithmetic Progression/1228.java b/solutions/1228. Missing Number In Arithmetic Progression/1228.java new file mode 100644 index 00000000000..0e593c46de9 --- /dev/null +++ b/solutions/1228. Missing Number In Arithmetic Progression/1228.java @@ -0,0 +1,18 @@ +class Solution { + public int missingNumber(int[] arr) { + final int n = arr.length; + final int delta = (arr[n - 1] - arr[0]) / n; + int l = 0; + int r = n - 1; + + while (l < r) { + final int m = (l + r) / 2; + if (arr[m] == arr[0] + m * delta) + l = m + 1; + else + r = m; + } + + return arr[0] + l * delta; + } +} diff --git a/solutions/1228. Missing Number In Arithmetic Progression/1228.py b/solutions/1228. Missing Number In Arithmetic Progression/1228.py new file mode 100644 index 00000000000..19919c6528d --- /dev/null +++ b/solutions/1228. Missing Number In Arithmetic Progression/1228.py @@ -0,0 +1,15 @@ +class Solution: + def missingNumber(self, arr: List[int]) -> int: + n = len(arr) + delta = (arr[-1] - arr[0]) // n + l = 0 + r = n - 1 + + while l < r: + m = (l + r) // 2 + if arr[m] == arr[0] + m * delta: + l = m + 1 + else: + r = m + + return arr[0] + l * delta diff --git a/solutions/1229. Meeting Scheduler/1229.cpp b/solutions/1229. Meeting Scheduler/1229.cpp new file mode 100644 index 00000000000..3943cfb28dc --- /dev/null +++ b/solutions/1229. Meeting Scheduler/1229.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector minAvailableDuration(vector>& slots1, + vector>& slots2, int duration) { + ranges::sort(slots1); + ranges::sort(slots2); + + int i = 0; // slots1's index + int j = 0; // slots2's index + + while (i < slots1.size() && j < slots2.size()) { + const int start = max(slots1[i][0], slots2[j][0]); + const int end = min(slots1[i][1], slots2[j][1]); + if (start + duration <= end) + return {start, start + duration}; + if (slots1[i][1] < slots2[j][1]) + ++i; + else + ++j; + } + + return {}; + } +}; diff --git a/solutions/1229. Meeting Scheduler/1229.java b/solutions/1229. Meeting Scheduler/1229.java new file mode 100644 index 00000000000..403115b5852 --- /dev/null +++ b/solutions/1229. Meeting Scheduler/1229.java @@ -0,0 +1,22 @@ +class Solution { + public List minAvailableDuration(int[][] slots1, int[][] slots2, int duration) { + Arrays.sort(slots1, (a, b) -> a[0] - b[0]); + Arrays.sort(slots2, (a, b) -> a[0] - b[0]); + + int i = 0; // slots1's index + int j = 0; // slots2's index + + while (i < slots1.length && j < slots2.length) { + final int start = Math.max(slots1[i][0], slots2[j][0]); + final int end = Math.min(slots1[i][1], slots2[j][1]); + if (start + duration <= end) + return Arrays.asList(start, start + duration); + if (slots1[i][1] < slots2[j][1]) + ++i; + else + ++j; + } + + return new ArrayList<>(); + } +} diff --git a/solutions/1229. Meeting Scheduler/1229.py b/solutions/1229. Meeting Scheduler/1229.py new file mode 100644 index 00000000000..33cba0b5b77 --- /dev/null +++ b/solutions/1229. Meeting Scheduler/1229.py @@ -0,0 +1,19 @@ +class Solution: + def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]: + slots1.sort() + slots2.sort() + + i = 0 # slots1's index + j = 0 # slots2's index + + while i < len(slots1) and j < len(slots2): + start = max(slots1[i][0], slots2[j][0]) + end = min(slots1[i][1], slots2[j][1]) + if start + duration <= end: + return [start, start + duration] + if slots1[i][1] < slots2[j][1]: + i += 1 + else: + j += 1 + + return [] diff --git a/solutions/123. Best Time to Buy and Sell Stock III/123.cpp b/solutions/123. Best Time to Buy and Sell Stock III/123.cpp new file mode 100644 index 00000000000..0abfd2d08e1 --- /dev/null +++ b/solutions/123. Best Time to Buy and Sell Stock III/123.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxProfit(vector& prices) { + int sellTwo = 0; + int holdTwo = INT_MIN; + int sellOne = 0; + int holdOne = INT_MIN; + + for (const int price : prices) { + sellTwo = max(sellTwo, holdTwo + price); + holdTwo = max(holdTwo, sellOne - price); + sellOne = max(sellOne, holdOne + price); + holdOne = max(holdOne, -price); + } + + return sellTwo; + } +}; diff --git a/solutions/123. Best Time to Buy and Sell Stock III/123.java b/solutions/123. Best Time to Buy and Sell Stock III/123.java new file mode 100644 index 00000000000..2820e7273da --- /dev/null +++ b/solutions/123. Best Time to Buy and Sell Stock III/123.java @@ -0,0 +1,17 @@ +class Solution { + public int maxProfit(int[] prices) { + int sellTwo = 0; + int holdTwo = Integer.MIN_VALUE; + int sellOne = 0; + int holdOne = Integer.MIN_VALUE; + + for (final int price : prices) { + sellTwo = Math.max(sellTwo, holdTwo + price); + holdTwo = Math.max(holdTwo, sellOne - price); + sellOne = Math.max(sellOne, holdOne + price); + holdOne = Math.max(holdOne, -price); + } + + return sellTwo; + } +} diff --git a/solutions/123. Best Time to Buy and Sell Stock III/123.py b/solutions/123. Best Time to Buy and Sell Stock III/123.py new file mode 100644 index 00000000000..9b4c0ebd74b --- /dev/null +++ b/solutions/123. Best Time to Buy and Sell Stock III/123.py @@ -0,0 +1,14 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + sellTwo = 0 + holdTwo = -math.inf + sellOne = 0 + holdOne = -math.inf + + for price in prices: + sellTwo = max(sellTwo, holdTwo + price) + holdTwo = max(holdTwo, sellOne - price) + sellOne = max(sellOne, holdOne + price) + holdOne = max(holdOne, -price) + + return sellTwo diff --git a/solutions/1230. Toss Strange Coins/1230-2.cpp b/solutions/1230. Toss Strange Coins/1230-2.cpp new file mode 100644 index 00000000000..9c97e0e5d1a --- /dev/null +++ b/solutions/1230. Toss Strange Coins/1230-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + double probabilityOfHeads(vector& prob, int target) { + // dp[j] := the probability of tossing the coins so far with j heads + vector dp(target + 1); + dp[0] = 1.0; + + for (const double p : prob) + for (int j = target; j >= 0; --j) + dp[j] = (j > 0 ? dp[j - 1] * p : 0) + dp[j] * (1 - p); + + return dp[target]; + } +}; diff --git a/solutions/1230. Toss Strange Coins/1230-2.java b/solutions/1230. Toss Strange Coins/1230-2.java new file mode 100644 index 00000000000..57299f6d451 --- /dev/null +++ b/solutions/1230. Toss Strange Coins/1230-2.java @@ -0,0 +1,13 @@ +class Solution { + public double probabilityOfHeads(double[] prob, int target) { + // dp[j] := the probability of tossing the coins so far with j heads + double[] dp = new double[target + 1]; + dp[0] = 1.0; + + for (final double p : prob) + for (int j = target; j >= 0; --j) + dp[j] = (j > 0 ? dp[j - 1] * p : 0) + dp[j] * (1 - p); + + return dp[target]; + } +} diff --git a/solutions/1230. Toss Strange Coins/1230-2.py b/solutions/1230. Toss Strange Coins/1230-2.py new file mode 100644 index 00000000000..0688b678bd3 --- /dev/null +++ b/solutions/1230. Toss Strange Coins/1230-2.py @@ -0,0 +1,10 @@ +class Solution: + def probabilityOfHeads(self, prob: List[float], target: int) -> float: + # dp[j] := the probability of tossing the coins so far with j heads + dp = [1.0] + [0] * len(prob) + + for p in prob: + for j in range(target, -1, -1): + dp[j] = (dp[j - 1] * p if j > 0 else 0) + dp[j] * (1 - p) + + return dp[target] diff --git a/solutions/1230. Toss Strange Coins/1230.cpp b/solutions/1230. Toss Strange Coins/1230.cpp new file mode 100644 index 00000000000..b87ce0595ad --- /dev/null +++ b/solutions/1230. Toss Strange Coins/1230.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + double probabilityOfHeads(vector& prob, int target) { + // dp[i][j] := the probability of tossing the first i coins with j heads + vector> dp(prob.size() + 1, vector(target + 1)); + dp[0][0] = 1.0; + + for (int i = 1; i <= prob.size(); ++i) + for (int j = 0; j <= target; ++j) + dp[i][j] = (j > 0 ? dp[i - 1][j - 1] * prob[i - 1] : 0) + + dp[i - 1][j] * (1 - prob[i - 1]); + + return dp[prob.size()][target]; + } +}; diff --git a/solutions/1230. Toss Strange Coins/1230.java b/solutions/1230. Toss Strange Coins/1230.java new file mode 100644 index 00000000000..fb01139e6a0 --- /dev/null +++ b/solutions/1230. Toss Strange Coins/1230.java @@ -0,0 +1,13 @@ +class Solution { + public double probabilityOfHeads(double[] prob, int target) { + // dp[i][j] := the probability of tossing the first i coins with j heads + double[][] dp = new double[prob.length + 1][target + 1]; + dp[0][0] = 1.0; + + for (int i = 1; i <= prob.length; ++i) + for (int j = 0; j <= target; ++j) + dp[i][j] = (j > 0 ? dp[i - 1][j - 1] * prob[i - 1] : 0) + dp[i - 1][j] * (1 - prob[i - 1]); + + return dp[prob.length][target]; + } +} diff --git a/solutions/1230. Toss Strange Coins/1230.py b/solutions/1230. Toss Strange Coins/1230.py new file mode 100644 index 00000000000..8754de022ec --- /dev/null +++ b/solutions/1230. Toss Strange Coins/1230.py @@ -0,0 +1,12 @@ +class Solution: + def probabilityOfHeads(self, prob: List[float], target: int) -> float: + # dp[i][j] := the probability of tossing the first i coins with j heads + dp = [[0] * (target + 1) for _ in range(len(prob) + 1)] + dp[0][0] = 1.0 + + for i in range(1, len(prob) + 1): + for j in range(target + 1): + dp[i][j] = (dp[i - 1][j - 1] * prob[i - 1] if j > 0 else 0) + \ + dp[i - 1][j] * (1 - prob[i - 1]) + + return dp[len(prob)][target] diff --git a/solutions/1231. Divide Chocolate/1231.cpp b/solutions/1231. Divide Chocolate/1231.cpp new file mode 100644 index 00000000000..bb6e1cabd6e --- /dev/null +++ b/solutions/1231. Divide Chocolate/1231.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int maximizeSweetness(vector& sweetness, int k) { + int l = sweetness.size() / (k + 1); + int r = accumulate(sweetness.begin(), sweetness.end(), 0) / (k + 1); + + while (l < r) { + const int m = (l + r) / 2; + if (canEat(sweetness, k, m)) + l = m + 1; + else + r = m; + } + + return canEat(sweetness, k, l) ? l : l - 1; + } + + private: + // Returns true if can eat m sweetness (the minimum sweetness of each piece). + bool canEat(const vector& sweetness, int k, int m) { + int pieces = 0; + int sum = 0; // the running sum + + for (const int s : sweetness) { + sum += s; + if (sum >= m) { + if (++pieces > k) + return true; + sum = 0; + } + } + + return false; + }; +}; diff --git a/solutions/1231. Divide Chocolate/1231.java b/solutions/1231. Divide Chocolate/1231.java new file mode 100644 index 00000000000..5b50c689d1f --- /dev/null +++ b/solutions/1231. Divide Chocolate/1231.java @@ -0,0 +1,33 @@ +class Solution { + public int maximizeSweetness(int[] sweetness, int k) { + int l = sweetness.length / (k + 1); + int r = Arrays.stream(sweetness).sum() / (k + 1); + + while (l < r) { + final int m = (l + r) / 2; + if (canEat(sweetness, k, m)) + l = m + 1; + else + r = m; + } + + return canEat(sweetness, k, l) ? l : l - 1; + } + + // Returns true if can eat m sweetness (the minimum sweetness of each piece). + private boolean canEat(int[] sweetness, int k, int m) { + int pieces = 0; + int sum = 0; // the running sum + + for (final int s : sweetness) { + sum += s; + if (sum >= m) { + if (++pieces > k) + return true; + sum = 0; + } + } + + return false; + } +} diff --git a/solutions/1231. Divide Chocolate/1231.py b/solutions/1231. Divide Chocolate/1231.py new file mode 100644 index 00000000000..014ae4e67ae --- /dev/null +++ b/solutions/1231. Divide Chocolate/1231.py @@ -0,0 +1,26 @@ +class Solution: + def maximizeSweetness(self, sweetness: List[int], k: int) -> int: + l = len(sweetness) // (k + 1) + r = sum(sweetness) // (k + 1) + + def canEat(m: int) -> bool: + """ + Returns True if can eat m sweetness (the minimum sweetness of each piece). + """ + pieces = 0 + summ = 0 # the running sum + for s in sweetness: + summ += s + if summ >= m: + pieces += 1 + summ = 0 + return pieces > k + + while l < r: + m = (l + r) // 2 + if canEat(m): + l = m + 1 + else: + r = m + + return l if canEat(l) else l - 1 diff --git a/solutions/1232. Check If It Is a Straight Line/1232.cpp b/solutions/1232. Check If It Is a Straight Line/1232.cpp new file mode 100644 index 00000000000..87c64a959bd --- /dev/null +++ b/solutions/1232. Check If It Is a Straight Line/1232.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool checkStraightLine(vector>& coordinates) { + int x0 = coordinates[0][0]; + int y0 = coordinates[0][1]; + int x1 = coordinates[1][0]; + int y1 = coordinates[1][1]; + int dx = x1 - x0; + int dy = y1 - y0; + + for (int i = 2; i < coordinates.size(); ++i) { + int x = coordinates[i][0]; + int y = coordinates[i][1]; + if ((x - x0) * dy != (y - y0) * dx) + return false; + } + + return true; + } +}; diff --git a/solutions/1232. Check If It Is a Straight Line/1232.java b/solutions/1232. Check If It Is a Straight Line/1232.java new file mode 100644 index 00000000000..4cc098a424f --- /dev/null +++ b/solutions/1232. Check If It Is a Straight Line/1232.java @@ -0,0 +1,19 @@ +class Solution { + public boolean checkStraightLine(int[][] coordinates) { + int x0 = coordinates[0][0]; + int y0 = coordinates[0][1]; + int x1 = coordinates[1][0]; + int y1 = coordinates[1][1]; + int dx = x1 - x0; + int dy = y1 - y0; + + for (int i = 2; i < coordinates.length; ++i) { + int x = coordinates[i][0]; + int y = coordinates[i][1]; + if ((x - x0) * dy != (y - y0) * dx) + return false; + } + + return true; + } +} diff --git a/solutions/1232. Check If It Is a Straight Line/1232.py b/solutions/1232. Check If It Is a Straight Line/1232.py new file mode 100644 index 00000000000..5073014d0a4 --- /dev/null +++ b/solutions/1232. Check If It Is a Straight Line/1232.py @@ -0,0 +1,7 @@ +class Solution: + def checkStraightLine(self, coordinates: List[List[int]]) -> bool: + x0, y0, x1, y1 = *coordinates[0], *coordinates[1] + dx = x1 - x0 + dy = y1 - y0 + + return all((x - x0) * dy == (y - y0) * dx for x, y in coordinates) diff --git a/solutions/1233. Remove Sub-Folders from the Filesystem/1233.cpp b/solutions/1233. Remove Sub-Folders from the Filesystem/1233.cpp new file mode 100644 index 00000000000..15025971632 --- /dev/null +++ b/solutions/1233. Remove Sub-Folders from the Filesystem/1233.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector removeSubfolders(vector& folder) { + vector ans; + string prev; + + ranges::sort(folder); + + for (const string& f : folder) { + if (!prev.empty() && f.find(prev) == 0 && f[prev.length()] == '/') + continue; + ans.push_back(f); + prev = f; + } + + return ans; + } +}; diff --git a/solutions/1233. Remove Sub-Folders from the Filesystem/1233.java b/solutions/1233. Remove Sub-Folders from the Filesystem/1233.java new file mode 100644 index 00000000000..ecb82deac17 --- /dev/null +++ b/solutions/1233. Remove Sub-Folders from the Filesystem/1233.java @@ -0,0 +1,17 @@ +class Solution { + public List removeSubfolders(String[] folder) { + List ans = new ArrayList<>(); + String prev = ""; + + Arrays.sort(folder); + + for (final String f : folder) { + if (!prev.isEmpty() && f.startsWith(prev) && f.charAt(prev.length()) == '/') + continue; + ans.add(f); + prev = f; + } + + return ans; + } +} diff --git a/solutions/1233. Remove Sub-Folders from the Filesystem/1233.py b/solutions/1233. Remove Sub-Folders from the Filesystem/1233.py new file mode 100644 index 00000000000..97dade92835 --- /dev/null +++ b/solutions/1233. Remove Sub-Folders from the Filesystem/1233.py @@ -0,0 +1,14 @@ +class Solution: + def removeSubfolders(self, folder: List[str]) -> List[str]: + ans = [] + prev = "" + + folder.sort() + + for f in folder: + if len(prev) > 0 and f.startswith(prev) and f[len(prev)] == '/': + continue + ans.append(f) + prev = f + + return ans diff --git a/solutions/1234. Replace the Substring for Balanced String/1234.cpp b/solutions/1234. Replace the Substring for Balanced String/1234.cpp new file mode 100644 index 00000000000..9e63eca6f7b --- /dev/null +++ b/solutions/1234. Replace the Substring for Balanced String/1234.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int balancedString(string s) { + const int n = s.length(); + const int k = n / 4; + int ans = n; + vector count(128); + + for (const char c : s) + ++count[c]; + + for (int i = 0, j = 0; i < n; ++i) { + --count[s[i]]; + while (j < n && count['Q'] <= k && count['W'] <= k && count['E'] <= k && + count['R'] <= k) { + ans = min(ans, i - j + 1); + ++count[s[j]]; + ++j; + } + } + + return ans; + } +}; diff --git a/solutions/1234. Replace the Substring for Balanced String/1234.java b/solutions/1234. Replace the Substring for Balanced String/1234.java new file mode 100644 index 00000000000..59fbcd02a91 --- /dev/null +++ b/solutions/1234. Replace the Substring for Balanced String/1234.java @@ -0,0 +1,22 @@ +class Solution { + public int balancedString(String s) { + final int n = s.length(); + final int k = n / 4; + int ans = n; + int[] count = new int[128]; + + for (final char c : s.toCharArray()) + ++count[c]; + + for (int i = 0, j = 0; i < n; ++i) { + --count[s.charAt(i)]; + while (j < n && count['Q'] <= k && count['W'] <= k && count['E'] <= k && count['R'] <= k) { + ans = Math.min(ans, i - j + 1); + ++count[s.charAt(j)]; + ++j; + } + } + + return ans; + } +} diff --git a/solutions/1234. Replace the Substring for Balanced String/1234.py b/solutions/1234. Replace the Substring for Balanced String/1234.py new file mode 100644 index 00000000000..ac6c9ce1d98 --- /dev/null +++ b/solutions/1234. Replace the Substring for Balanced String/1234.py @@ -0,0 +1,14 @@ +class Solution: + def balancedString(self, s: str) -> int: + ans = len(s) + count = collections.Counter(s) + j = 0 + + for i, c in enumerate(s): + count[c] -= 1 + while j < len(s) and all(count[c] <= len(s) // 4 for c in 'QWER'): + ans = min(ans, i - j + 1) + count[s[j]] += 1 + j += 1 + + return ans diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235-2.cpp b/solutions/1235. Maximum Profit in Job Scheduling/1235-2.cpp new file mode 100644 index 00000000000..5c9672f0e14 --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235-2.cpp @@ -0,0 +1,41 @@ +struct Job { + int startTime; + int endTime; + int profit; + Job(int startTime, int endTime, int profit) + : startTime(startTime), endTime(endTime), profit(profit) {} +}; + +class Solution { + public: + int jobScheduling(vector& startTime, vector& endTime, + vector& profit) { + const int n = startTime.size(); + // dp[i] := the maximum profit to schedule jobs[i..n) + vector dp(n + 1); + vector jobs; + + for (int i = 0; i < n; ++i) + jobs.emplace_back(startTime[i], endTime[i], profit[i]); + + ranges::sort(jobs, [](const Job& a, const Job& b) { + return a.startTime < b.startTime; + }); + + for (int i = 0; i < n; ++i) + startTime[i] = jobs[i].startTime; + + for (int i = n - 1; i >= 0; --i) { + const int j = firstGreaterEqual(startTime, i + 1, jobs[i].endTime); + const int pick = jobs[i].profit + dp[j]; + const int skip = dp[i + 1]; + dp[i] = max(pick, skip); + } + + return dp[0]; + } + + int firstGreaterEqual(const vector& A, int startFrom, int target) { + return lower_bound(A.begin() + startFrom, A.end(), target) - A.begin(); + } +}; diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235-2.java b/solutions/1235. Maximum Profit in Job Scheduling/1235-2.java new file mode 100644 index 00000000000..010b389a243 --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235-2.java @@ -0,0 +1,49 @@ +class Job { + public int startTime; + public int endTime; + public int profit; + public Job(int startTime, int endTime, int profit) { + this.startTime = startTime; + this.endTime = endTime; + this.profit = profit; + } +} + +class Solution { + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + final int n = startTime.length; + // dp[i] := the maximum profit to schedule jobs[i..n) + int[] dp = new int[n + 1]; + Job[] jobs = new Job[n]; + + for (int i = 0; i < n; ++i) + jobs[i] = new Job(startTime[i], endTime[i], profit[i]); + + Arrays.sort(jobs, (a, b) -> a.startTime - b.startTime); + + for (int i = 0; i < n; ++i) + startTime[i] = jobs[i].startTime; + + for (int i = n - 1; i >= 0; --i) { + final int j = firstGreaterEqual(startTime, i + 1, jobs[i].endTime); + final int pick = jobs[i].profit + dp[j]; + final int skip = dp[i + 1]; + dp[i] = Math.max(pick, skip); + } + + return dp[0]; + } + + private int firstGreaterEqual(int[] A, int startFrom, int target) { + int l = startFrom; + int r = A.length; + while (l < r) { + final int m = (l + r) / 2; + if (A[m] >= target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235-2.py b/solutions/1235. Maximum Profit in Job Scheduling/1235-2.py new file mode 100644 index 00000000000..ac42e92481b --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235-2.py @@ -0,0 +1,14 @@ +class Solution: + def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: + # dp[i] := the maximum profit to schedule jobs[i..n) + dp = [0] * (len(startTime) + 1) + jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)]) + + for i in range(len(startTime)): + startTime[i] = jobs[i][0] + + for i in reversed(range(len(startTime))): + j = bisect.bisect_left(startTime, jobs[i][1]) + dp[i] = max(jobs[i][2] + dp[j], dp[i + 1]) + + return dp[0] diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235-3.cpp b/solutions/1235. Maximum Profit in Job Scheduling/1235-3.cpp new file mode 100644 index 00000000000..b3caa492438 --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235-3.cpp @@ -0,0 +1,44 @@ +struct Job { + int startTime; + int endTime; + int profit; + Job(int startTime, int endTime, int profit) + : startTime(startTime), endTime(endTime), profit(profit) {} +}; + +class Solution { + public: + int jobScheduling(vector& startTime, vector& endTime, + vector& profit) { + vector jobs; + + for (int i = 0; i < startTime.size(); ++i) + jobs.emplace_back(startTime[i], endTime[i], profit[i]); + + ranges::sort(jobs, [](const Job& a, const Job& b) { + return a.startTime < b.startTime; + }); + + return getMaxProfit(jobs); + } + + private: + int getMaxProfit(const vector& jobs) { + int maxProfit = 0; + auto compare = [](const Job& a, const Job& b) { + return a.endTime > b.endTime; + }; + priority_queue, decltype(compare)> minHeap(compare); + + for (const auto& [s, e, p] : jobs) { + while (!minHeap.empty() && s >= minHeap.top().endTime) + maxProfit = max(maxProfit, minHeap.top().profit), minHeap.pop(); + minHeap.emplace(s, e, p + maxProfit); + } + + while (!minHeap.empty()) + maxProfit = max(maxProfit, minHeap.top().profit), minHeap.pop(); + + return maxProfit; + } +}; diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235-3.java b/solutions/1235. Maximum Profit in Job Scheduling/1235-3.java new file mode 100644 index 00000000000..8ff84ebe1fe --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235-3.java @@ -0,0 +1,45 @@ +class Job { + public int startTime; + public int endTime; + public int profit; + public Job(int startTime, int endTime, int profit) { + this.startTime = startTime; + this.endTime = endTime; + this.profit = profit; + } +} + +class Solution { + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + final int n = startTime.length; + + Job[] jobs = new Job[n]; + + for (int i = 0; i < n; ++i) + jobs[i] = new Job(startTime[i], endTime[i], profit[i]); + + Arrays.sort(jobs, (a, b) -> a.startTime - b.startTime); + + // Will use binary search to find the first available startTime + for (int i = 0; i < n; ++i) + startTime[i] = jobs[i].startTime; + + return getMaxProfit(jobs); + } + + private int getMaxProfit(Job[] jobs) { + int maxProfit = 0; + Queue minHeap = new PriorityQueue<>((a, b) -> a.endTime - b.endTime); + + for (Job job : jobs) { + while (!minHeap.isEmpty() && job.startTime >= minHeap.peek().endTime) + maxProfit = Math.max(maxProfit, minHeap.poll().profit); + minHeap.offer(new Job(job.startTime, job.endTime, job.profit + maxProfit)); + } + + while (!minHeap.isEmpty()) + maxProfit = Math.max(maxProfit, minHeap.poll().profit); + + return maxProfit; + } +} diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235-3.py b/solutions/1235. Maximum Profit in Job Scheduling/1235-3.py new file mode 100644 index 00000000000..0b903cec241 --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235-3.py @@ -0,0 +1,16 @@ +class Solution: + def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: + maxProfit = 0 + jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)]) + minHeap = [] # (endTime, profit) + + # Will use binary search to find the first available startTime + for i in range(len(startTime)): + startTime[i] = jobs[i][0] + + for s, e, p in jobs: + while minHeap and s >= minHeap[0][0]: + maxProfit = max(maxProfit, heapq.heappop(minHeap)[1]) + heapq.heappush(minHeap, (e, p + maxProfit)) + + return max(maxProfit, max(p for _, p in minHeap)) diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235.cpp b/solutions/1235. Maximum Profit in Job Scheduling/1235.cpp new file mode 100644 index 00000000000..ca96c30347a --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235.cpp @@ -0,0 +1,49 @@ +struct Job { + int startTime; + int endTime; + int profit; + Job(int startTime, int endTime, int profit) + : startTime(startTime), endTime(endTime), profit(profit) {} +}; + +class Solution { + public: + int jobScheduling(vector& startTime, vector& endTime, + vector& profit) { + const int n = startTime.size(); + vector mem(n + 1); + vector jobs; + + for (int i = 0; i < n; ++i) + jobs.emplace_back(startTime[i], endTime[i], profit[i]); + + ranges::sort(jobs, [](const Job& a, const Job& b) { + return a.startTime < b.startTime; + }); + + // Will use binary search to find the first available start time. + for (int i = 0; i < n; ++i) + startTime[i] = jobs[i].startTime; + + return jobScheduling(jobs, startTime, 0, mem); + } + + private: + // Returns the maximum profit to schedule jobs[i..n). + int jobScheduling(const vector& jobs, const vector& startTime, + int i, vector& mem) { + if (i == jobs.size()) + return 0; + if (mem[i] > 0) + return mem[i]; + + const int j = firstGreaterEqual(startTime, i + 1, jobs[i].endTime); + const int pick = jobs[i].profit + jobScheduling(jobs, startTime, j, mem); + const int skip = jobScheduling(jobs, startTime, i + 1, mem); + return mem[i] = max(pick, skip); + } + + int firstGreaterEqual(const vector& A, int startFrom, int target) { + return lower_bound(A.begin() + startFrom, A.end(), target) - A.begin(); + } +}; diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235.java b/solutions/1235. Maximum Profit in Job Scheduling/1235.java new file mode 100644 index 00000000000..ffd28abb063 --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235.java @@ -0,0 +1,54 @@ +class Job { + public int startTime; + public int endTime; + public int profit; + public Job(int startTime, int endTime, int profit) { + this.startTime = startTime; + this.endTime = endTime; + this.profit = profit; + } +} + +class Solution { + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + final int n = startTime.length; + int[] mem = new int[n + 1]; + Job[] jobs = new Job[n]; + + for (int i = 0; i < n; ++i) + jobs[i] = new Job(startTime[i], endTime[i], profit[i]); + + Arrays.sort(jobs, (a, b) -> a.startTime - b.startTime); + + // Will use binary search to find the first available start time. + for (int i = 0; i < n; ++i) + startTime[i] = jobs[i].startTime; + + return jobScheduling(jobs, startTime, 0, mem); + } + + private int jobScheduling(Job[] jobs, int[] startTime, int i, int[] mem) { + if (i == jobs.length) + return 0; + if (mem[i] > 0) + return mem[i]; + + final int j = firstGreaterEqual(startTime, i + 1, jobs[i].endTime); + final int pick = jobs[i].profit + jobScheduling(jobs, startTime, j, mem); + final int skip = jobScheduling(jobs, startTime, i + 1, mem); + return mem[i] = Math.max(pick, skip); + } + + private int firstGreaterEqual(int[] A, int startFrom, int target) { + int l = startFrom; + int r = A.length; + while (l < r) { + final int m = (l + r) / 2; + if (A[m] >= target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1235. Maximum Profit in Job Scheduling/1235.py b/solutions/1235. Maximum Profit in Job Scheduling/1235.py new file mode 100644 index 00000000000..e27d4d84d0c --- /dev/null +++ b/solutions/1235. Maximum Profit in Job Scheduling/1235.py @@ -0,0 +1,17 @@ +class Solution: + def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: + jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)]) + + # Will use binary search to find the first available startTime + for i in range(len(startTime)): + startTime[i] = jobs[i][0] + + @functools.lru_cache(None) + def dp(i: int) -> int: + """Returns the maximum profit to schedule jobs[i..n).""" + if i == len(startTime): + return 0 + j = bisect.bisect_left(startTime, jobs[i][1]) + return max(jobs[i][2] + dp(j), dp(i + 1)) + + return dp(0) diff --git a/solutions/1236. Web Crawler/1236.cpp b/solutions/1236. Web Crawler/1236.cpp new file mode 100644 index 00000000000..c7dba6c2326 --- /dev/null +++ b/solutions/1236. Web Crawler/1236.cpp @@ -0,0 +1,39 @@ +/** + * // This is the HtmlParser's API interface. + * // You should not implement it, or speculate about its implementation + * class HtmlParser { + * public: + * vector getUrls(string url); + * }; + */ + +class Solution { + public: + vector crawl(string startUrl, HtmlParser htmlParser) { + queue q{{startUrl}}; + unordered_set seen{{startUrl}}; + const string& hostname = getHostname(startUrl); + + while (!q.empty()) { + const string currUrl = q.front(); + q.pop(); + for (const string& url : htmlParser.getUrls(currUrl)) { + if (seen.contains(url)) + continue; + if (url.find(hostname) != string::npos) { + q.push(url); + seen.insert(url); + } + } + } + + return {seen.begin(), seen.end()}; + } + + private: + string getHostname(const string& url) { + const int firstSlash = url.find_first_of('/'); + const int thirdSlash = url.find_first_of('/', firstSlash + 2); + return url.substr(firstSlash + 2, thirdSlash - firstSlash - 2); + } +}; diff --git a/solutions/1236. Web Crawler/1236.java b/solutions/1236. Web Crawler/1236.java new file mode 100644 index 00000000000..b366e9bc396 --- /dev/null +++ b/solutions/1236. Web Crawler/1236.java @@ -0,0 +1,29 @@ +/** + * // This is the HtmlParser's API interface. + * // You should not implement it, or speculate about its implementation + * interface HtmlParser { + * public List getUrls(String url) {} + * } + */ + +class Solution { + public List crawl(String startUrl, HtmlParser htmlParser) { + Queue q = new ArrayDeque<>(Arrays.asList(startUrl)); + Set seen = new HashSet<>(Arrays.asList(startUrl)); + final String hostname = startUrl.split("/")[2]; + + while (!q.isEmpty()) { + final String currUrl = q.poll(); + for (final String url : htmlParser.getUrls(currUrl)) { + if (seen.contains(url)) + continue; + if (url.contains(hostname)) { + q.offer(url); + seen.add(url); + } + } + } + + return new ArrayList<>(seen); + } +} diff --git a/solutions/1236. Web Crawler/1236.py b/solutions/1236. Web Crawler/1236.py new file mode 100644 index 00000000000..2415e867553 --- /dev/null +++ b/solutions/1236. Web Crawler/1236.py @@ -0,0 +1,23 @@ +# """ +# This is HtmlParser's API interface. +# You should not implement it, or speculate about its implementation +# """ +# Class HtmlParser(object): +# def getUrls(self, url: str) -> List[str]: + +class Solution: + def crawl(self, startUrl: str, htmlParser: 'HtmlParser') -> List[str]: + q = collections.deque([startUrl]) + seen = {startUrl} + hostname = startUrl.split('/')[2] + + while q: + currUrl = q.popleft() + for url in htmlParser.getUrls(currUrl): + if url in seen: + continue + if hostname in url: + q.append(url) + seen.add(url) + + return seen diff --git a/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.cpp b/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.cpp new file mode 100644 index 00000000000..0be8522845f --- /dev/null +++ b/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector> findSolution(CustomFunction& customfunction, int z) { + vector> ans; + int x = 1; + int y = 1000; + + while (x <= 1000 && y >= 1) { + int f = customfunction.f(x, y); + if (f < z) + ++x; + else if (f > z) + --y; + else + ans.push_back({x++, y--}); + } + + return ans; + } +}; diff --git a/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.java b/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.java new file mode 100644 index 00000000000..9c7badf4014 --- /dev/null +++ b/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.java @@ -0,0 +1,19 @@ +class Solution { + public List> findSolution(CustomFunction customfunction, int z) { + List> ans = new LinkedList<>(); + int x = 1; + int y = 1000; + + while (x <= 1000 && y >= 1) { + int f = customfunction.f(x, y); + if (f < z) + ++x; + else if (f > z) + --y; + else + ans.add(Arrays.asList(x++, y--)); + } + + return ans; + } +} diff --git a/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.py b/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.py new file mode 100644 index 00000000000..9939fc76295 --- /dev/null +++ b/solutions/1237. Find Positive Integer Solution for a Given Equation/1237.py @@ -0,0 +1,18 @@ +class Solution: + def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: + ans = [] + x = 1 + y = 1000 + + while x <= 1000 and y >= 1: + f = customfunction.f(x, y) + if f < z: + x += 1 + elif f > z: + y -= 1 + else: + ans.append([x, y]) + x += 1 + y -= 1 + + return ans diff --git a/solutions/1238. Circular Permutation in Binary Representation/1238.cpp b/solutions/1238. Circular Permutation in Binary Representation/1238.cpp new file mode 100644 index 00000000000..85162edc5cd --- /dev/null +++ b/solutions/1238. Circular Permutation in Binary Representation/1238.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector circularPermutation(int n, int start) { + vector ans; + + for (int i = 0; i < 1 << n; ++i) + ans.push_back(start ^ i ^ i >> 1); + + return ans; + } +}; diff --git a/solutions/1238. Circular Permutation in Binary Representation/1238.java b/solutions/1238. Circular Permutation in Binary Representation/1238.java new file mode 100644 index 00000000000..e54213c1919 --- /dev/null +++ b/solutions/1238. Circular Permutation in Binary Representation/1238.java @@ -0,0 +1,10 @@ +class Solution { + public List circularPermutation(int n, int start) { + List ans = new ArrayList<>(); + + for (int i = 0; i < 1 << n; ++i) + ans.add(start ^ i ^ i >> 1); + + return ans; + } +} diff --git a/solutions/1238. Circular Permutation in Binary Representation/1238.py b/solutions/1238. Circular Permutation in Binary Representation/1238.py new file mode 100644 index 00000000000..da3be8df28e --- /dev/null +++ b/solutions/1238. Circular Permutation in Binary Representation/1238.py @@ -0,0 +1,3 @@ +class Solution: + def circularPermutation(self, n: int, start: int) -> List[int]: + return [start ^ i ^ i >> 1 for i in range(1 << n)] diff --git a/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-2.cpp b/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-2.cpp new file mode 100644 index 00000000000..fcd9b1343cf --- /dev/null +++ b/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maxLength(vector& arr) { + vector> masks; + + for (const string& s : arr) { + const bitset<26> mask = getMask(s); + if (mask.contains() == s.length()) + masks.push_back(mask); + } + + return dfs(masks, 0, /*used=*/bitset<26>()); + } + + private: + int dfs(const vector>& masks, int s, bitset<26> used) { + int res = used.contains(); + for (int i = s; i < masks.size(); ++i) + if (!(used & masks[i]).any()) + res = max(res, dfs(masks, i + 1, used | masks[i])); + return res; + } + + bitset<26> getMask(const string& s) { + bitset<26> mask; + for (const char c : s) + mask.set(c - 'a'); + return mask; + } +}; diff --git a/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-3.cpp b/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-3.cpp new file mode 100644 index 00000000000..90ae7b02cd1 --- /dev/null +++ b/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239-3.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int maxLength(vector& arr) { + vector masks; + + for (const string& s : arr) { + const int mask = getMask(s); + if (mask != -1) + masks.push_back(mask); + } + + return dfs(masks, 0, /*used=*/0); + } + + private: + int dfs(const vector& masks, int i, int used) { + if (i == masks.size()) + return 0; + const int pick = + (masks[i] & used) == 0 + ? popcount(masks[i]) + dfs(masks, i + 1, used | masks[i]) + : 0; + const int skip = dfs(masks, i + 1, used); + return max(pick, skip); + } + + int getMask(const string& s) { + int mask = 0; + for (const char c : s) { + const int i = c - 'a'; + if ((mask & (1 << i)) != 0) + return -1; + mask |= 1 << i; + } + return mask; + } +}; diff --git a/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239.cpp b/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239.cpp new file mode 100644 index 00000000000..54894449e27 --- /dev/null +++ b/solutions/1239. Maximum Length of a Concatenated String with Unique Characters/1239.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int maxLength(vector& arr) { + vector masks; + + for (const string& s : arr) { + const int mask = getMask(s); + if (mask != -1) + masks.push_back(mask); + } + + return dfs(masks, 0, /*used=*/0); + } + + private: + int dfs(const vector& masks, int s, unsigned used) { + int res = popcount(used); + for (int i = s; i < masks.size(); ++i) + if ((used & masks[i]) == 0) + res = max(res, dfs(masks, i + 1, used | masks[i])); + return res; + } + + int getMask(const string& s) { + int mask = 0; + for (const char c : s) { + const int i = c - 'a'; + if ((mask & (1 << i)) != 0) + return -1; + mask |= 1 << i; + } + return mask; + } +}; diff --git a/solutions/124. Binary Tree Maximum Path Sum/124.cpp b/solutions/124. Binary Tree Maximum Path Sum/124.cpp new file mode 100644 index 00000000000..19a10c72fe9 --- /dev/null +++ b/solutions/124. Binary Tree Maximum Path Sum/124.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maxPathSum(TreeNode* root) { + int ans = INT_MIN; + maxPathSumDownFrom(root, ans); + return ans; + } + + private: + // Returns the maximum path sum starting from the current root, where + // root->val is always included. + int maxPathSumDownFrom(TreeNode* root, int& ans) { + if (root == nullptr) + return 0; + + const int l = max(0, maxPathSumDownFrom(root->left, ans)); + const int r = max(0, maxPathSumDownFrom(root->right, ans)); + ans = max(ans, root->val + l + r); + return root->val + max(l, r); + } +}; diff --git a/solutions/124. Binary Tree Maximum Path Sum/124.java b/solutions/124. Binary Tree Maximum Path Sum/124.java new file mode 100644 index 00000000000..25fa69080bb --- /dev/null +++ b/solutions/124. Binary Tree Maximum Path Sum/124.java @@ -0,0 +1,20 @@ +class Solution { + public int maxPathSum(TreeNode root) { + maxPathSumDownFrom(root); + return ans; + } + + private int ans = Integer.MIN_VALUE; + + // Returns the maximum path sum starting from the current root, where + // root.val is always included. + private int maxPathSumDownFrom(TreeNode root) { + if (root == null) + return 0; + + final int l = Math.max(maxPathSumDownFrom(root.left), 0); + final int r = Math.max(maxPathSumDownFrom(root.right), 0); + ans = Math.max(ans, root.val + l + r); + return root.val + Math.max(l, r); + } +} diff --git a/solutions/124. Binary Tree Maximum Path Sum/124.py b/solutions/124. Binary Tree Maximum Path Sum/124.py new file mode 100644 index 00000000000..ceb09132e06 --- /dev/null +++ b/solutions/124. Binary Tree Maximum Path Sum/124.py @@ -0,0 +1,20 @@ +class Solution: + def maxPathSum(self, root: Optional[TreeNode]) -> int: + ans = -math.inf + + def maxPathSumDownFrom(root: Optional[TreeNode]) -> int: + """ + Returns the maximum path sum starting from the current root, where + root.val is always included. + """ + nonlocal ans + if not root: + return 0 + + l = max(0, maxPathSumDownFrom(root.left)) + r = max(0, maxPathSumDownFrom(root.right)) + ans = max(ans, root.val + l + r) + return root.val + max(l, r) + + maxPathSumDownFrom(root) + return ans diff --git a/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.cpp b/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.cpp new file mode 100644 index 00000000000..10ce55b1a12 --- /dev/null +++ b/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int tilingRectangle(int n, int m) { + unordered_map mem; + return tilingRectangle(n, m, 0, /*heights=*/vector(m), mem); + } + + private: + static constexpr int kBase = 13; + + int tilingRectangle(int n, int m, long hashedHeights, vector&& heights, + unordered_map& mem) { + if (const auto it = mem.find(hashedHeights); it != mem.cend()) + return it->second; + + const auto it = ranges::min_element(heights); + const int minHeight = *it; + if (minHeight == n) // All filled. + return 0; + + int ans = m * n; + const int start = it - heights.begin(); + // Try to put square of different size that doesn't exceed the width/height. + for (int sz = 1; sz <= min(m - start, n - minHeight); ++sz) { + // heights[start..start + sz) must has the same height. + if (heights[start + sz - 1] != minHeight) + break; + // Put a square of size `sz` to cover heights[start..start + sz). + for (int i = start; i < start + sz; ++i) + heights[i] += sz; + ans = min(ans, tilingRectangle(n, m, hash(heights), move(heights), mem)); + for (int i = start; i < start + sz; ++i) + heights[i] -= sz; + } + + return mem[hashedHeights] = 1 + ans; + } + + long hash(const vector& heights) { + long hashed = 0; + for (int i = heights.size() - 1; i >= 0; --i) + hashed = hashed * kBase + heights[i]; + return hashed; + } +}; diff --git a/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.java b/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.java new file mode 100644 index 00000000000..2ea9c309217 --- /dev/null +++ b/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.java @@ -0,0 +1,49 @@ +class Solution { + public int tilingRectangle(int n, int m) { + return tilingRectangle(n, m, 0, new int[m]); + } + + private static final int kBase = 13; + private Map dp = new HashMap<>(); + + private int tilingRectangle(int n, int m, long hashedHeights, int[] heights) { + if (dp.containsKey(hashedHeights)) + return dp.get(hashedHeights); + + final int minHeight = Arrays.stream(heights).min().getAsInt(); + if (minHeight == n) // All filled. + return 0; + + int ans = m * n; + int start = -1; + + for (int i = 0; i < m; ++i) + if (heights[i] == minHeight) { + start = i; + break; + } + + // Try to put square of different size that doesn't exceed the width/height. + for (int sz = 1; sz <= Math.min(m - start, n - minHeight); ++sz) { + // heights[start..start + sz) must has the same height. + if (heights[start + sz - 1] != minHeight) + break; + // Put a square of size `sz` to cover heights[start..start + sz). + for (int i = start; i < start + sz; ++i) + heights[i] += sz; + ans = Math.min(ans, tilingRectangle(n, m, hash(heights), heights)); + for (int i = start; i < start + sz; ++i) + heights[i] -= sz; + } + + dp.put(hashedHeights, 1 + ans); + return 1 + ans; + } + + private long hash(int[] heights) { + long hashed = 0; + for (int i = heights.length - 1; i >= 0; --i) + hashed = hashed * kBase + heights[i]; + return hashed; + } +} diff --git a/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.py b/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.py new file mode 100644 index 00000000000..ccdde2cca48 --- /dev/null +++ b/solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.py @@ -0,0 +1,24 @@ +class Solution: + def tilingRectangle(self, n: int, m: int) -> int: + @functools.lru_cache(None) + def dp(heights: int) -> int: + minHeight = min(heights) + if minHeight == n: # All filled. + return 0 + + ans = m * n + heightsList = list(heights) + start = heightsList.index(minHeight) + + # Try to put square of different size that doesn't exceed the width/height. + for sz in range(1, min(m - start + 1, n - minHeight + 1)): + # heights[start..start + sz) must has the same height. + if heights[start + sz - 1] != minHeight: + break + # Put a square of size `sz` to cover heights[start..start + sz). + heightsList[start:start + sz] = [minHeight + sz] * sz + ans = min(ans, dp(tuple(heightsList))) + + return 1 + ans + + return dp(tuple([0] * m)) diff --git a/solutions/1241. Number of Comments per Post/1241.sql b/solutions/1241. Number of Comments per Post/1241.sql new file mode 100644 index 00000000000..18bf676e47a --- /dev/null +++ b/solutions/1241. Number of Comments per Post/1241.sql @@ -0,0 +1,13 @@ +WITH + Posts AS ( + SELECT DISTINCT sub_id AS post_id + FROM Submissions + WHERE parent_id IS NULL + ) +SELECT + Posts.post_id, + COUNT(DISTINCT Comments.sub_id) AS number_of_comments +FROM Posts +LEFT JOIN Submissions AS Comments + ON (Posts.post_id = Comments.parent_id) +GROUP BY 1; diff --git a/solutions/1242. Web Crawler Multithreaded/1242.cpp b/solutions/1242. Web Crawler Multithreaded/1242.cpp new file mode 100644 index 00000000000..b28c02fe4b2 --- /dev/null +++ b/solutions/1242. Web Crawler Multithreaded/1242.cpp @@ -0,0 +1,60 @@ +/** + * // This is the HtmlParser's API interface. + * // You should not implement it, or speculate about its implementation + * class HtmlParser { + * public: + * vector getUrls(string url); + * }; + */ + +class Solution { + public: + vector crawl(string startUrl, HtmlParser htmlParser) { + queue q{{startUrl}}; + unordered_set seen{{startUrl}}; + const string& hostname = getHostname(startUrl); + const int nThreads = std::thread::hardware_concurrency(); + vector threads; + std::mutex mtx; + std::condition_variable cv; + + auto t = [&]() { + while (true) { + unique_lock lock(mtx); + cv.wait_for(lock, 30ms, [&]() { return q.size(); }); + if (q.empty()) + return; + auto cur = q.front(); + q.pop(); + lock.unlock(); + const vector urls = htmlParser.getUrls(cur); + lock.lock(); + for (const string& url : urls) { + if (seen.contains(url)) + continue; + if (url.find(hostname) != string::npos) { + q.push(url); + seen.insert(url); + } + } + lock.unlock(); + cv.notify_all(); + } + }; + + for (int i = 0; i < nThreads; ++i) + threads.emplace_back(t); + + for (std::thread& t : threads) + t.join(); + + return {seen.begin(), seen.end()}; + } + + private: + string getHostname(const string& url) { + const int firstSlash = url.find_first_of('/'); + const int thirdSlash = url.find_first_of('/', firstSlash + 2); + return url.substr(firstSlash + 2, thirdSlash - firstSlash - 2); + } +}; diff --git a/solutions/1243. Array Transformation/1243.cpp b/solutions/1243. Array Transformation/1243.cpp new file mode 100644 index 00000000000..10954fa969e --- /dev/null +++ b/solutions/1243. Array Transformation/1243.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector transformArray(vector& arr) { + if (arr.size() < 3) + return arr; + + vector ans(arr.size()); + + while (ans != arr) { + ans = arr; + for (int i = 1; i < arr.size() - 1; ++i) { + if (ans[i - 1] > ans[i] && ans[i] < ans[i + 1]) + ++arr[i]; + else if (ans[i - 1] < ans[i] && ans[i] > ans[i + 1]) + --arr[i]; + } + } + + return ans; + } +}; diff --git a/solutions/1243. Array Transformation/1243.java b/solutions/1243. Array Transformation/1243.java new file mode 100644 index 00000000000..fabb4fe20c2 --- /dev/null +++ b/solutions/1243. Array Transformation/1243.java @@ -0,0 +1,19 @@ +class Solution { + public List transformArray(int[] arr) { + if (arr.length < 3) + return Arrays.stream(arr).boxed().toList(); + + int[] ans = new int[0]; + + while (!Arrays.equals(ans, arr)) { + ans = arr.clone(); + for (int i = 1; i < arr.length - 1; ++i) + if (ans[i - 1] > ans[i] && ans[i] < ans[i + 1]) + ++arr[i]; + else if (ans[i - 1] < ans[i] && ans[i] > ans[i + 1]) + --arr[i]; + } + + return Arrays.stream(ans).boxed().toList(); + } +} diff --git a/solutions/1243. Array Transformation/1243.py b/solutions/1243. Array Transformation/1243.py new file mode 100644 index 00000000000..7ce4a468619 --- /dev/null +++ b/solutions/1243. Array Transformation/1243.py @@ -0,0 +1,16 @@ +class Solution: + def transformArray(self, arr: List[int]) -> List[int]: + if len(arr) < 3: + return arr + + ans = [] + + while ans != arr: + ans = arr[:] + for i in range(1, len(arr) - 1): + if ans[i - 1] > ans[i] < ans[i + 1]: + arr[i] += 1 + elif ans[i - 1] < ans[i] > ans[i + 1]: + arr[i] -= 1 + + return ans diff --git a/solutions/1244. Design A Leaderboard/1244.cpp b/solutions/1244. Design A Leaderboard/1244.cpp new file mode 100644 index 00000000000..7db570a6811 --- /dev/null +++ b/solutions/1244. Design A Leaderboard/1244.cpp @@ -0,0 +1,29 @@ +class Leaderboard { + public: + void addScore(int playerId, int score) { + idToScore[playerId] += score; + } + + int top(int K) { + int ans = 0; + priority_queue, greater<>> minHeap; + + for (const auto& [id, score] : idToScore) { + minHeap.push(score); + if (minHeap.size() > K) + minHeap.pop(); + } + + while (!minHeap.empty()) + ans += minHeap.top(), minHeap.pop(); + + return ans; + } + + void reset(int playerId) { + idToScore.erase(playerId); + } + + private: + unordered_map idToScore; +}; diff --git a/solutions/1244. Design A Leaderboard/1244.java b/solutions/1244. Design A Leaderboard/1244.java new file mode 100644 index 00000000000..dfa319a34cf --- /dev/null +++ b/solutions/1244. Design A Leaderboard/1244.java @@ -0,0 +1,27 @@ +class Leaderboard { + public void addScore(int playerId, int score) { + idToScore.merge(playerId, score, Integer::sum); + } + + public int top(int K) { + int ans = 0; + Queue minHeap = new PriorityQueue<>(); + + for (final int score : idToScore.values()) { + minHeap.offer(score); + if (minHeap.size() > K) + minHeap.poll(); + } + + while (!minHeap.isEmpty()) + ans += minHeap.poll(); + + return ans; + } + + public void reset(int playerId) { + idToScore.remove(playerId); + } + + private Map idToScore = new HashMap<>(); +} diff --git a/solutions/1244. Design A Leaderboard/1244.py b/solutions/1244. Design A Leaderboard/1244.py new file mode 100644 index 00000000000..d8ab4453ae5 --- /dev/null +++ b/solutions/1244. Design A Leaderboard/1244.py @@ -0,0 +1,12 @@ +class Leaderboard: + def __init__(self): + self.idToScore = collections.Counter() + + def addScore(self, playerId: int, score: int) -> None: + self.idToScore[playerId] += score + + def top(self, K: int) -> int: + return sum(score for _, score in self.idToScore.most_common(K)) + + def reset(self, playerId: int) -> None: + del self.idToScore[playerId] diff --git a/solutions/1245. Tree Diameter/1245.cpp b/solutions/1245. Tree Diameter/1245.cpp new file mode 100644 index 00000000000..d758b3f0f99 --- /dev/null +++ b/solutions/1245. Tree Diameter/1245.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int treeDiameter(vector>& edges) { + const int n = edges.size(); + int ans = 0; + vector> tree(n + 1); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + maxDepth(tree, 0, -1, ans); + return ans; + } + + private: + int maxDepth(const vector>& tree, int u, int parent, int& ans) { + int maxDepth1 = 0; // the maximum depth + int maxDepth2 = -1; // the second maximum depth + + for (const int v : tree[u]) { + if (v == parent) + continue; + const int depth = maxDepth(tree, v, u, ans); + if (depth > maxDepth1) { + maxDepth2 = maxDepth1; + maxDepth1 = depth; + } else if (depth > maxDepth2) { + maxDepth2 = depth; + } + } + + ans = max(ans, maxDepth1 + maxDepth2); + return 1 + maxDepth1; + } +}; diff --git a/solutions/1245. Tree Diameter/1245.java b/solutions/1245. Tree Diameter/1245.java new file mode 100644 index 00000000000..06e9e2a41f6 --- /dev/null +++ b/solutions/1245. Tree Diameter/1245.java @@ -0,0 +1,41 @@ +class Solution { + public int treeDiameter(int[][] edges) { + final int n = edges.length; + List[] tree = new List[n + 1]; + + for (int i = 0; i < tree.length; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + maxDepth(tree, 0, -1); + return ans; + } + + private int ans = 0; + + private int maxDepth(List[] tree, int u, int parent) { + int maxDepth1 = 0; // the maximum depth + int maxDepth2 = -1; // the second maximum depth + + for (final int v : tree[u]) { + if (v == parent) + continue; + final int depth = maxDepth(tree, v, u); + if (depth > maxDepth1) { + maxDepth2 = maxDepth1; + maxDepth1 = depth; + } else if (depth > maxDepth2) { + maxDepth2 = depth; + } + } + + ans = Math.max(ans, maxDepth1 + maxDepth2); + return 1 + maxDepth1; + } +} diff --git a/solutions/1246. Palindrome Removal/1246.cpp b/solutions/1246. Palindrome Removal/1246.cpp new file mode 100644 index 00000000000..34feb49ca16 --- /dev/null +++ b/solutions/1246. Palindrome Removal/1246.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minimumMoves(vector& arr) { + const int n = arr.size(); + // dp[i][j] := the minimum number of moves to remove all numbers from + // arr[i..j] + vector> dp(n, vector(n, n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int i = 0; i + 1 < n; ++i) + dp[i][i + 1] = arr[i] == arr[i + 1] ? 1 : 2; + + for (int d = 2; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + // Remove arr[i] and arr[j] within the move of removing + // arr[i + 1..j - 1] + if (arr[i] == arr[j]) + dp[i][j] = dp[i + 1][j - 1]; + // Try all the possible partitions. + for (int k = i; k < j; ++k) + dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]); + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/1246. Palindrome Removal/1246.java b/solutions/1246. Palindrome Removal/1246.java new file mode 100644 index 00000000000..38df47e9dbd --- /dev/null +++ b/solutions/1246. Palindrome Removal/1246.java @@ -0,0 +1,28 @@ +class Solution { + public int minimumMoves(int[] arr) { + final int n = arr.length; + // dp[i][j] := the minimum number of moves to remove all numbers from arr[i..j] + int[][] dp = new int[n][n]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int i = 0; i + 1 < n; ++i) + dp[i][i + 1] = arr[i] == arr[i + 1] ? 1 : 2; + + for (int d = 2; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + // Remove arr[i] and arr[j] within the move of removing + // arr[i + 1..j - 1] + if (arr[i] == arr[j]) + dp[i][j] = dp[i + 1][j - 1]; + // Try all the possible partitions. + for (int k = i; k < j; ++k) + dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j]); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/1246. Palindrome Removal/1246.py b/solutions/1246. Palindrome Removal/1246.py new file mode 100644 index 00000000000..e64fa6c58cf --- /dev/null +++ b/solutions/1246. Palindrome Removal/1246.py @@ -0,0 +1,24 @@ +class Solution: + def minimumMoves(self, arr: List[int]) -> int: + n = len(arr) + # dp[i][j] := the minimum number of moves to remove all numbers from arr[i..j] + dp = [[n] * n for _ in range(n)] + + for i in range(n): + dp[i][i] = 1 + + for i in range(n - 1): + dp[i][i + 1] = 1 if arr[i] == arr[i + 1] else 2 + + for d in range(2, n): + for i in range(n - d): + j = i + d + # Remove arr[i] and arr[j] within the move of removing + # arr[i + 1..j - 1] + if arr[i] == arr[j]: + dp[i][j] = dp[i + 1][j - 1] + # Try all the possible partitions. + for k in range(i, j): + dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]) + + return dp[0][n - 1] diff --git a/solutions/1247. Minimum Swaps to Make Strings Equal/1247.cpp b/solutions/1247. Minimum Swaps to Make Strings Equal/1247.cpp new file mode 100644 index 00000000000..341d0c01624 --- /dev/null +++ b/solutions/1247. Minimum Swaps to Make Strings Equal/1247.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minimumSwap(string s1, string s2) { + // ("xx", "yy") = (2 "xy"s) -> 1 swap + // ("yy", "xx") = (2 "yx"s) -> 1 swap + // ("xy", "yx") = (1 "xy" and 1 "yx") -> 2 swaps + int xy = 0; // the number of indices i's s.t. s1[i] = 'x' and s2[i] 'y' + int yx = 0; // the number of indices i's s.t. s1[i] = 'y' and s2[i] 'x' + + for (int i = 0; i < s1.length(); ++i) { + if (s1[i] == s2[i]) + continue; + if (s1[i] == 'x') + ++xy; + else + ++yx; + } + + if ((xy + yx) % 2 == 1) + return -1; + return xy / 2 + yx / 2 + (xy % 2 == 0 ? 0 : 2); + } +}; diff --git a/solutions/1247. Minimum Swaps to Make Strings Equal/1247.java b/solutions/1247. Minimum Swaps to Make Strings Equal/1247.java new file mode 100644 index 00000000000..cc70273f3ea --- /dev/null +++ b/solutions/1247. Minimum Swaps to Make Strings Equal/1247.java @@ -0,0 +1,22 @@ +class Solution { + public int minimumSwap(String s1, String s2) { + // ("xx", "yy") = (2 "xy"s) -> 1 swap + // ("yy", "xx") = (2 "yx"s) -> 1 swap + // ("xy", "yx") = (1 "xy" and 1 "yx") -> 2 swaps + int xy = 0; // the number of indices i's s.t. s1[i] = 'x' and s2[i] 'y' + int yx = 0; // the number of indices i's s.t. s1[i] = 'y' and s2[i] 'x' + + for (int i = 0; i < s1.length(); ++i) { + if (s1.charAt(i) == s2.charAt(i)) + continue; + if (s1.charAt(i) == 'x') + ++xy; + else + ++yx; + } + + if ((xy + yx) % 2 == 1) + return -1; + return xy / 2 + yx / 2 + (xy % 2 == 0 ? 0 : 2); + } +} diff --git a/solutions/1247. Minimum Swaps to Make Strings Equal/1247.py b/solutions/1247. Minimum Swaps to Make Strings Equal/1247.py new file mode 100644 index 00000000000..1b9a8b80ac7 --- /dev/null +++ b/solutions/1247. Minimum Swaps to Make Strings Equal/1247.py @@ -0,0 +1,19 @@ +class Solution: + def minimumSwap(self, s1: str, s2: str) -> int: + # ('xx', 'yy') = (2 'xy's) . 1 swap + # ('yy', 'xx') = (2 'yx's) . 1 swap + # ('xy', 'yx') = (1 'xy' and 1 'yx') . 2 swaps + xy = 0 # the number of indices i's s.t. s1[i] = 'x' and s2[i] 'y' + yx = 0 # the number of indices i's s.t. s1[i] = 'y' and s2[i] 'x' + + for a, b in zip(s1, s2): + if a == b: + continue + if a == 'x': + xy += 1 + else: + yx += 1 + + if (xy + yx) % 2 == 1: + return -1 + return xy // 2 + yx // 2 + (0 if xy % 2 == 0 else 2) diff --git a/solutions/1248. Count Number of Nice Subarrays/1248.cpp b/solutions/1248. Count Number of Nice Subarrays/1248.cpp new file mode 100644 index 00000000000..18fcb1d0053 --- /dev/null +++ b/solutions/1248. Count Number of Nice Subarrays/1248.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int numberOfSubarrays(vector& nums, int k) { + return numberOfSubarraysAtMost(nums, k) - + numberOfSubarraysAtMost(nums, k - 1); + } + + private: + int numberOfSubarraysAtMost(vector& nums, int k) { + int ans = 0; + + for (int l = 0, r = 0; r <= nums.size();) + if (k >= 0) { + ans += r - l; + if (r == nums.size()) + break; + if (nums[r] % 2 == 1) + --k; + ++r; + } else { + if (nums[l] % 2 == 1) + ++k; + ++l; + } + + return ans; + } +}; diff --git a/solutions/1248. Count Number of Nice Subarrays/1248.java b/solutions/1248. Count Number of Nice Subarrays/1248.java new file mode 100644 index 00000000000..32efd98cc6a --- /dev/null +++ b/solutions/1248. Count Number of Nice Subarrays/1248.java @@ -0,0 +1,25 @@ +class Solution { + public int numberOfSubarrays(int[] nums, int k) { + return numberOfSubarraysAtMost(nums, k) - numberOfSubarraysAtMost(nums, k - 1); + } + + private int numberOfSubarraysAtMost(int[] nums, int k) { + int ans = 0; + + for (int l = 0, r = 0; r <= nums.length;) + if (k >= 0) { + ans += r - l; + if (r == nums.length) + break; + if (nums[r] % 2 == 1) + --k; + ++r; + } else { + if (nums[l] % 2 == 1) + ++k; + ++l; + } + + return ans; + } +} diff --git a/solutions/1248. Count Number of Nice Subarrays/1248.py b/solutions/1248. Count Number of Nice Subarrays/1248.py new file mode 100644 index 00000000000..8a55d6ecc8c --- /dev/null +++ b/solutions/1248. Count Number of Nice Subarrays/1248.py @@ -0,0 +1,22 @@ +class Solution: + def numberOfSubarrays(self, nums: List[int], k: int) -> int: + def numberOfSubarraysAtMost(k: int) -> int: + ans = 0 + l = 0 + r = 0 + + while r <= len(nums): + if k >= 0: + ans += r - l + if r == len(nums): + break + if nums[r] & 1: + k -= 1 + r += 1 + else: + if nums[l] & 1: + k += 1 + l += 1 + return ans + + return numberOfSubarraysAtMost(k) - numberOfSubarraysAtMost(k - 1) diff --git a/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.cpp b/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.cpp new file mode 100644 index 00000000000..14a5cd17a85 --- /dev/null +++ b/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + string minRemoveToMakeValid(string s) { + stack stack; // unpaired '(' indices + + for (int i = 0; i < s.length(); ++i) + if (s[i] == '(') { + stack.push(i); // Record the unpaired '(' index. + } else if (s[i] == ')') { + if (stack.empty()) + s[i] = '*'; // Mark the unpaired ')' as '*'. + else + stack.pop(); // Find a pair! + } + + // Mark the unpaired '(' as '*'. + while (!stack.empty()) + s[stack.top()] = '*', stack.pop(); + + std::erase(s, '*'); + return s; + } +}; diff --git a/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.java b/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.java new file mode 100644 index 00000000000..1360b6d3e6b --- /dev/null +++ b/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.java @@ -0,0 +1,22 @@ +class Solution { + public String minRemoveToMakeValid(String s) { + Deque stack = new ArrayDeque<>(); // unpaired '(' indices + StringBuilder sb = new StringBuilder(s); + + for (int i = 0; i < s.length(); ++i) + if (sb.charAt(i) == '(') { + stack.push(i); // Record the unpaired '(' index. + } else if (sb.charAt(i) == ')') { + if (stack.isEmpty()) + sb.setCharAt(i, '#'); // Mark the unpaired ')' as '#'. + else + stack.pop(); // Find a pair! + } + + // Mark the unpaired '(' as '#'. + while (!stack.isEmpty()) + sb.setCharAt(stack.pop(), '#'); + + return sb.toString().replaceAll("#", ""); + } +} diff --git a/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.py b/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.py new file mode 100644 index 00000000000..5130a09fc3c --- /dev/null +++ b/solutions/1249. Minimum Remove to Make Valid Parentheses/1249.py @@ -0,0 +1,19 @@ +class Solution: + def minRemoveToMakeValid(self, s: str) -> str: + stack = [] # unpaired '(' indices + chars = list(s) + + for i, c in enumerate(chars): + if c == '(': + stack.append(i) # Record the unpaired '(' index. + elif c == ')': + if stack: + stack.pop() # Find a pair + else: + chars[i] = '*' # Mark the unpaired ')' as '*'. + + # Mark the unpaired '(' as '*'. + while stack: + chars[stack.pop()] = '*' + + return ''.join(chars).replace('*', '') diff --git a/solutions/125. Valid Palindrome/125.cpp b/solutions/125. Valid Palindrome/125.cpp new file mode 100644 index 00000000000..cad57a42505 --- /dev/null +++ b/solutions/125. Valid Palindrome/125.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool isPalindrome(string s) { + int l = 0; + int r = s.length() - 1; + + while (l < r) { + while (l < r && !isalnum(s[l])) + ++l; + while (l < r && !isalnum(s[r])) + --r; + if (tolower(s[l]) != tolower(s[r])) + return false; + ++l; + --r; + } + + return true; + } +}; diff --git a/solutions/125. Valid Palindrome/125.java b/solutions/125. Valid Palindrome/125.java new file mode 100644 index 00000000000..76b96fa9030 --- /dev/null +++ b/solutions/125. Valid Palindrome/125.java @@ -0,0 +1,19 @@ +class Solution { + public boolean isPalindrome(String s) { + int l = 0; + int r = s.length() - 1; + + while (l < r) { + while (l < r && !Character.isLetterOrDigit(s.charAt(l))) + ++l; + while (l < r && !Character.isLetterOrDigit(s.charAt(r))) + --r; + if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) + return false; + ++l; + --r; + } + + return true; + } +} diff --git a/solutions/125. Valid Palindrome/125.py b/solutions/125. Valid Palindrome/125.py new file mode 100644 index 00000000000..f845ea8135b --- /dev/null +++ b/solutions/125. Valid Palindrome/125.py @@ -0,0 +1,16 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + l = 0 + r = len(s) - 1 + + while l < r: + while l < r and not s[l].isalnum(): + l += 1 + while l < r and not s[r].isalnum(): + r -= 1 + if s[l].lower() != s[r].lower(): + return False + l += 1 + r -= 1 + + return True diff --git a/solutions/1250. Check If It Is a Good Array/1250.cpp b/solutions/1250. Check If It Is a Good Array/1250.cpp new file mode 100644 index 00000000000..e70d33b8244 --- /dev/null +++ b/solutions/1250. Check If It Is a Good Array/1250.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool isGoodArray(vector& nums) { + int g = nums[0]; + + for (const int num : nums) + g = __gcd(g, num); + + return g == 1; + } +}; diff --git a/solutions/1251. Average Selling Price/1251.sql b/solutions/1251. Average Selling Price/1251.sql new file mode 100644 index 00000000000..d57f2b46e6e --- /dev/null +++ b/solutions/1251. Average Selling Price/1251.sql @@ -0,0 +1,15 @@ +SELECT + Prices.product_id, + IFNULL( + ROUND( + SUM(Prices.price * UnitsSold.units) / SUM(UnitsSold.units), + 2 + ), + 0 + ) AS average_price +FROM Prices +LEFT JOIN UnitsSold + ON ( + Prices.product_id = UnitsSold.product_id + AND UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date) +GROUP BY 1; diff --git a/solutions/1252. Cells with Odd Values in a Matrix/1252-2.cpp b/solutions/1252. Cells with Odd Values in a Matrix/1252-2.cpp new file mode 100644 index 00000000000..1fa4868fb9e --- /dev/null +++ b/solutions/1252. Cells with Odd Values in a Matrix/1252-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int oddCells(int m, int n, vector>& indices) { + // rows[i] and cols[i] := + // 1. true (flipped even times) + // 2. false (flipped odd times) + vector rows(m); + vector cols(n); + + for (const vector& index : indices) { + rows[index[0]] = rows[index[0]] ^ true; + cols[index[1]] = cols[index[1]] ^ true; + } + + const int oddRowsCount = ranges::count(rows, true); + const int oddColsCount = ranges::count(cols, true); + const int evenRowsCount = m - oddRowsCount; + const int evenColsCount = n - oddColsCount; + return oddRowsCount * evenColsCount + oddColsCount * evenRowsCount; + } +}; diff --git a/solutions/1252. Cells with Odd Values in a Matrix/1252-2.java b/solutions/1252. Cells with Odd Values in a Matrix/1252-2.java new file mode 100644 index 00000000000..5925fc44bc1 --- /dev/null +++ b/solutions/1252. Cells with Odd Values in a Matrix/1252-2.java @@ -0,0 +1,29 @@ +class Solution { + public int oddCells(int m, int n, int[][] indices) { + // rows[i] and cols[i] := + // 1. true (flipped even times) + // 2. false (flipped odd times) + boolean[] rows = new boolean[n]; + boolean[] cols = new boolean[n]; + + for (int[] index : indices) { + rows[index[0]] = rows[index[0]] ^ true; + cols[index[1]] = cols[index[1]] ^ true; + } + + int oddRowsCount = 0; + int oddColsCount = 0; + + for (boolean row : rows) + if (row) + ++oddRowsCount; + + for (boolean col : cols) + if (col) + ++oddColsCount; + + final int evenRowsCount = m - oddRowsCount; + final int evenColsCount = n - oddColsCount; + return oddRowsCount * evenColsCount + oddColsCount * evenRowsCount; + } +} diff --git a/solutions/1252. Cells with Odd Values in a Matrix/1252-2.py b/solutions/1252. Cells with Odd Values in a Matrix/1252-2.py new file mode 100644 index 00000000000..a066e0303ce --- /dev/null +++ b/solutions/1252. Cells with Odd Values in a Matrix/1252-2.py @@ -0,0 +1,17 @@ +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + # rows[i] and cols[i] := + # 1. True (flipped even times) + # 2. False (flipped odd times) + rows = [False] * m + cols = [False] * n + + for r, c in indices: + rows[r] ^= True + cols[c] ^= True + + oddRowsCount = rows.count(True) + oddColsCount = cols.count(True) + evenRowsCount = m - oddRowsCount + evenColsCount = n - oddColsCount + return oddRowsCount * evenColsCount + oddColsCount * evenRowsCount diff --git a/solutions/1252. Cells with Odd Values in a Matrix/1252-3.cpp b/solutions/1252. Cells with Odd Values in a Matrix/1252-3.cpp new file mode 100644 index 00000000000..56905dcf34b --- /dev/null +++ b/solutions/1252. Cells with Odd Values in a Matrix/1252-3.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int oddCells(int m, int n, vector>& indices) { + unordered_set oddRows; + unordered_set oddCols; + + for (const vector& index : indices) { + const int r = index[0]; + const int c = index[1]; + if (!oddRows.insert(r).second) + oddRows.erase(r); + if (!oddCols.insert(c).second) + oddCols.erase(c); + } + + return oddRows.size() * (n - oddCols.size()) + + oddCols.size() * (m - oddRows.size()); + } +}; diff --git a/solutions/1252. Cells with Odd Values in a Matrix/1252.cpp b/solutions/1252. Cells with Odd Values in a Matrix/1252.cpp new file mode 100644 index 00000000000..9686f26d29d --- /dev/null +++ b/solutions/1252. Cells with Odd Values in a Matrix/1252.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int oddCells(int m, int n, vector>& indices) { + int ans = 0; + // rows[i] and cols[i] := + // true (flipped even times) / false (flipped odd times) + vector rows(m); + vector cols(n); + + for (const vector& index : indices) { + rows[index[0]] = rows[index[0]] ^ true; + cols[index[1]] = cols[index[1]] ^ true; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + ans += rows[i] ^ cols[j]; + + return ans; + } +}; diff --git a/solutions/1252. Cells with Odd Values in a Matrix/1252.java b/solutions/1252. Cells with Odd Values in a Matrix/1252.java new file mode 100644 index 00000000000..8d2dd5c6ff1 --- /dev/null +++ b/solutions/1252. Cells with Odd Values in a Matrix/1252.java @@ -0,0 +1,21 @@ +class Solution { + public int oddCells(int m, int n, int[][] indices) { + int ans = 0; + // rows[i] and cols[i] := + // true (flipped even times) / false (flipped odd times) + boolean[] rows = new boolean[n]; + boolean[] cols = new boolean[n]; + + for (int[] index : indices) { + rows[index[0]] = rows[index[0]] ^ true; + cols[index[1]] = cols[index[1]] ^ true; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (rows[i] ^ cols[j]) + ++ans; + + return ans; + } +} diff --git a/solutions/1252. Cells with Odd Values in a Matrix/1252.py b/solutions/1252. Cells with Odd Values in a Matrix/1252.py new file mode 100644 index 00000000000..37440f444ca --- /dev/null +++ b/solutions/1252. Cells with Odd Values in a Matrix/1252.py @@ -0,0 +1,14 @@ +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + # rows[i] and cols[i] := + # true (flipped even times) / false (flipped odd times) + rows = [False] * m + cols = [False] * n + + for r, c in indices: + rows[r] ^= True + cols[c] ^= True + + return sum(rows[i] ^ cols[j] + for i in range(m) + for j in range(n)) diff --git a/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.cpp b/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.cpp new file mode 100644 index 00000000000..e698384ffd0 --- /dev/null +++ b/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector> reconstructMatrix(int upper, int lower, + vector& colsum) { + if (upper + lower != accumulate(colsum.begin(), colsum.end(), 0)) + return {}; + if (min(upper, lower) < + ranges::count_if(colsum, [](int c) { return c == 2; })) + return {}; + + vector> ans(2, vector(colsum.size())); + + for (int j = 0; j < colsum.size(); ++j) + if (colsum[j] == 2) { + ans[0][j] = 1; + ans[1][j] = 1; + --upper; + --lower; + } + + for (int j = 0; j < colsum.size(); ++j) { + if (colsum[j] == 1 && upper > 0) { + ans[0][j] = 1; + --colsum[j]; + --upper; + } + + if (colsum[j] == 1 && lower > 0) { + ans[1][j] = 1; + --lower; + } + } + + return ans; + } +}; diff --git a/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.java b/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.java new file mode 100644 index 00000000000..0aa316b5076 --- /dev/null +++ b/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.java @@ -0,0 +1,39 @@ +class Solution { + public List> reconstructMatrix(int upper, int lower, int[] colsum) { + if (upper + lower != Arrays.stream(colsum).sum()) + return new ArrayList<>(); + + int count = 0; + for (int c : colsum) + if (c == 2) + ++count; + + if (Math.min(upper, lower) < count) + return new ArrayList<>(); + + int[][] ans = new int[2][colsum.length]; + + for (int j = 0; j < colsum.length; ++j) + if (colsum[j] == 2) { + ans[0][j] = 1; + ans[1][j] = 1; + --upper; + --lower; + } + + for (int j = 0; j < colsum.length; ++j) { + if (colsum[j] == 1 && upper > 0) { + ans[0][j] = 1; + --colsum[j]; + --upper; + } + + if (colsum[j] == 1 && lower > 0) { + ans[1][j] = 1; + --lower; + } + } + + return new ArrayList(Arrays.asList(ans[0], ans[1])); + } +} diff --git a/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.py b/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.py new file mode 100644 index 00000000000..5bbaa8d1f75 --- /dev/null +++ b/solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.py @@ -0,0 +1,26 @@ +class Solution: + def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]: + if upper + lower != sum(colsum): + return [] + if min(upper, lower) < colsum.count(2): + return [] + + ans = [[0] * len(colsum) for _ in range(2)] + + for j, c in enumerate(colsum): + if c == 2: + ans[0][j] = 1 + ans[1][j] = 1 + upper -= 1 + lower -= 1 + + for j, c in enumerate(colsum): + if c == 1 and upper > 0: + ans[0][j] = 1 + c -= 1 + upper -= 1 + if c == 1 and lower > 0: + ans[1][j] = 1 + lower -= 1 + + return ans diff --git a/solutions/1254. Number of Closed Islands/1254.cpp b/solutions/1254. Number of Closed Islands/1254.cpp new file mode 100644 index 00000000000..a3fafd8c768 --- /dev/null +++ b/solutions/1254. Number of Closed Islands/1254.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int closedIsland(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + + // Remove the lands connected to the edge. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + if (grid[i][j] == 0) + dfs(grid, i, j); + + int ans = 0; + + // Reduce to 200. Number of Islands + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0) { + dfs(grid, i, j); + ++ans; + } + + return ans; + } + + private: + void dfs(vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] == 1) + return; + + grid[i][j] = 1; + dfs(grid, i + 1, j); + dfs(grid, i - 1, j); + dfs(grid, i, j + 1); + dfs(grid, i, j - 1); + }; +}; diff --git a/solutions/1254. Number of Closed Islands/1254.java b/solutions/1254. Number of Closed Islands/1254.java new file mode 100644 index 00000000000..bed40db3f93 --- /dev/null +++ b/solutions/1254. Number of Closed Islands/1254.java @@ -0,0 +1,38 @@ +class Solution { + public int closedIsland(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + + // Remove the lands connected to the edge. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + if (grid[i][j] == 0) + dfs(grid, i, j); + + int ans = 0; + + // Reduce to 200. Number of Islands + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0) { + dfs(grid, i, j); + ++ans; + } + + return ans; + } + + private void dfs(int[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] == 1) + return; + + grid[i][j] = 1; + dfs(grid, i + 1, j); + dfs(grid, i - 1, j); + dfs(grid, i, j + 1); + dfs(grid, i, j - 1); + } +} diff --git a/solutions/1254. Number of Closed Islands/1254.py b/solutions/1254. Number of Closed Islands/1254.py new file mode 100644 index 00000000000..3171c4a1fe6 --- /dev/null +++ b/solutions/1254. Number of Closed Islands/1254.py @@ -0,0 +1,34 @@ +class Solution: + def closedIsland(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + + def dfs(i: int, j: int) -> None: + if i < 0 or i == m or j < 0 or j == n: + return + if grid[i][j] == 1: + return + + grid[i][j] = 1 + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1) + + # Remove the lands connected to the edge. + for i in range(m): + for j in range(n): + if i * j == 0 or i == m - 1 or j == n - 1: + if grid[i][j] == 0: + dfs(i, j) + + ans = 0 + + # Reduce to 200. Number of Islands + for i in range(m): + for j in range(n): + if grid[i][j] == 0: + dfs(i, j) + ans += 1 + + return ans diff --git a/solutions/1255. Maximum Score Words Formed by Letters/1255.cpp b/solutions/1255. Maximum Score Words Formed by Letters/1255.cpp new file mode 100644 index 00000000000..7df2734d975 --- /dev/null +++ b/solutions/1255. Maximum Score Words Formed by Letters/1255.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int maxScoreWords(vector& words, vector& letters, + vector& score) { + vector count(26); + for (const char c : letters) + ++count[c - 'a']; + return dfs(words, 0, count, score); + } + + private: + // Returns the maximum score you can get from words[s..n). + int dfs(const vector& words, int s, vector& count, + const vector& score) { + int ans = 0; + for (int i = s; i < words.size(); ++i) { + const int earned = useWord(words, i, count, score); + if (earned > 0) + ans = max(ans, earned + dfs(words, i + 1, count, score)); + unuseWord(words, i, count); + } + return ans; + } + + int useWord(const vector& words, int i, vector& count, + const vector& score) { + bool isValid = true; + int earned = 0; + for (const char c : words[i]) { + if (--count[c - 'a'] < 0) + isValid = false; + earned += score[c - 'a']; + } + return isValid ? earned : -1; + } + + void unuseWord(const vector& words, int i, vector& count) { + for (const char c : words[i]) + ++count[c - 'a']; + } +}; diff --git a/solutions/1255. Maximum Score Words Formed by Letters/1255.java b/solutions/1255. Maximum Score Words Formed by Letters/1255.java new file mode 100644 index 00000000000..9957f3a54be --- /dev/null +++ b/solutions/1255. Maximum Score Words Formed by Letters/1255.java @@ -0,0 +1,36 @@ +class Solution { + public int maxScoreWords(String[] words, char[] letters, int[] score) { + int[] count = new int[26]; + for (final char c : letters) + ++count[c - 'a']; + return dfs(words, 0, count, score); + } + + // Returns the maximum score you can get from words[s..n). + private int dfs(String[] words, int s, int[] count, int[] score) { + int ans = 0; + for (int i = s; i < words.length; ++i) { + final int earned = useWord(words, i, count, score); + if (earned > 0) + ans = Math.max(ans, earned + dfs(words, i + 1, count, score)); + unuseWord(words, i, count); + } + return ans; + } + + int useWord(String[] words, int i, int[] count, int[] score) { + boolean isValid = true; + int earned = 0; + for (final char c : words[i].toCharArray()) { + if (--count[c - 'a'] < 0) + isValid = false; + earned += score[c - 'a']; + } + return isValid ? earned : -1; + } + + void unuseWord(String[] words, int i, int[] count) { + for (final char c : words[i].toCharArray()) + ++count[c - 'a']; + } +} diff --git a/solutions/1255. Maximum Score Words Formed by Letters/1255.py b/solutions/1255. Maximum Score Words Formed by Letters/1255.py new file mode 100644 index 00000000000..c03cc8722c0 --- /dev/null +++ b/solutions/1255. Maximum Score Words Formed by Letters/1255.py @@ -0,0 +1,29 @@ +class Solution: + def maxScoreWords(self, words: List[str], letters: List[chr], score: List[int]) -> int: + count = collections.Counter(letters) + + def useWord(i: int) -> int: + isValid = True + earned = 0 + for c in words[i]: + count[c] -= 1 + if count[c] < 0: + isValid = False + earned += score[ord(c) - ord('a')] + return earned if isValid else -1 + + def unuseWord(i: int) -> None: + for c in words[i]: + count[c] += 1 + + def dfs(s: int) -> int: + """Returns the maximum score you can get from words[s..n).""" + ans = 0 + for i in range(s, len(words)): + earned = useWord(i) + if earned > 0: + ans = max(ans, earned + dfs(i + 1)) + unuseWord(i) + return ans + + return dfs(0) diff --git a/solutions/1256. Encode Number/1256.cpp b/solutions/1256. Encode Number/1256.cpp new file mode 100644 index 00000000000..2aa02bd624c --- /dev/null +++ b/solutions/1256. Encode Number/1256.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + string encode(int num) { + string binaryStr = bitset<30>(num + 1).to_string(); + binaryStr.erase(0, binaryStr.find_first_not_of('0')); + return binaryStr.substr(1); + } +}; diff --git a/solutions/1256. Encode Number/1256.java b/solutions/1256. Encode Number/1256.java new file mode 100644 index 00000000000..0e5bb3c40f5 --- /dev/null +++ b/solutions/1256. Encode Number/1256.java @@ -0,0 +1,5 @@ +class Solution { + public String encode(int num) { + return Integer.toBinaryString(num + 1).substring(1); + } +} diff --git a/solutions/1256. Encode Number/1256.py b/solutions/1256. Encode Number/1256.py new file mode 100644 index 00000000000..d40037fddf0 --- /dev/null +++ b/solutions/1256. Encode Number/1256.py @@ -0,0 +1,3 @@ +class Solution: + def encode(self, num: int) -> str: + return bin(num + 1)[3:] diff --git a/solutions/1257. Smallest Common Region/1257.cpp b/solutions/1257. Smallest Common Region/1257.cpp new file mode 100644 index 00000000000..e4198c555ca --- /dev/null +++ b/solutions/1257. Smallest Common Region/1257.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string findSmallestRegion(vector>& regions, string region1, + string region2) { + unordered_map parent; + unordered_set ancestors; // region1's ancestors + + for (const vector& region : regions) + for (int i = 1; i < region.size(); ++i) + parent[region[i]] = region[0]; + + // Add all the region1's ancestors. + while (region1 != "") { + ancestors.insert(region1); + region1 = parent[region1]; // Region1 becomes "" in the end + } + + // Go up from region2 until meet any of region1's ancestors. + while (!ancestors.contains(region2)) + region2 = parent[region2]; + + return region2; + } +}; diff --git a/solutions/1257. Smallest Common Region/1257.java b/solutions/1257. Smallest Common Region/1257.java new file mode 100644 index 00000000000..6fa16d581e0 --- /dev/null +++ b/solutions/1257. Smallest Common Region/1257.java @@ -0,0 +1,22 @@ +class Solution { + public String findSmallestRegion(List> regions, String region1, String region2) { + Map parent = new HashMap<>(); + Set ancestors = new HashSet<>(); // region1's ancestors + + for (List region : regions) + for (int i = 1; i < region.size(); ++i) + parent.put(region.get(i), region.get(0)); + + // Add all the region1's ancestors. + while (region1 != null) { + ancestors.add(region1); + region1 = parent.get(region1); // Region1 becomes null in the end. + } + + // Go up from region2 until meet any of region1's ancestors. + while (!ancestors.contains(region2)) + region2 = parent.get(region2); + + return region2; + } +} diff --git a/solutions/1258. Synonymous Sentences/1258.cpp b/solutions/1258. Synonymous Sentences/1258.cpp new file mode 100644 index 00000000000..8c40dca7fb9 --- /dev/null +++ b/solutions/1258. Synonymous Sentences/1258.cpp @@ -0,0 +1,56 @@ +class Solution { + public: + vector generateSentences(vector>& synonyms, + string text) { + set ans; + unordered_map> graph; + queue q{{text}}; + + for (const vector& synonym : synonyms) { + const string& s = synonym[0]; + const string& t = synonym[1]; + graph[s].push_back(t); + graph[t].push_back(s); + } + + while (!q.empty()) { + const string u = q.front(); + q.pop(); + ans.insert(u); + vector words = split(u); + for (string& word : words) { + const auto it = graph.find(word); + if (it == graph.cend()) + continue; + for (const string& synonym : it->second) { + // Replace words[i] with its synonym. + word = synonym; + const string newText = join(words, ' '); + if (!ans.contains(newText)) + q.push(newText); + } + } + } + + return {ans.begin(), ans.end()}; + } + + private: + vector split(const string& s) { + vector words; + istringstream iss(s); + for (string token; iss >> token;) + words.push_back(token); + return words; + } + + string join(const vector& words, char c) { + string joined; + for (int i = 0; i < words.size(); ++i) { + joined += words[i]; + if (i != words.size() - 1) + joined += c; + } + return joined; + } +}; diff --git a/solutions/1258. Synonymous Sentences/1258.java b/solutions/1258. Synonymous Sentences/1258.java new file mode 100644 index 00000000000..14157222990 --- /dev/null +++ b/solutions/1258. Synonymous Sentences/1258.java @@ -0,0 +1,32 @@ +class Solution { + public List generateSentences(List> synonyms, String text) { + Set ans = new TreeSet<>(); + Map> graph = new HashMap<>(); + Queue q = new ArrayDeque<>(Arrays.asList(text)); + + for (List synonym : synonyms) { + final String s = synonym.get(0); + final String t = synonym.get(1); + graph.putIfAbsent(s, new ArrayList<>()); + graph.putIfAbsent(t, new ArrayList<>()); + graph.get(s).add(t); + graph.get(t).add(s); + } + + while (!q.isEmpty()) { + final String u = q.poll(); + ans.add(u); + String[] words = u.split("\\s"); + for (int i = 0; i < words.length; ++i) + for (final String synonym : graph.getOrDefault(words[i], new ArrayList<>())) { + // Replace words[i] with its synonym. + words[i] = synonym; + final String newText = String.join(" ", words); + if (!ans.contains(newText)) + q.offer(newText); + } + } + + return new ArrayList<>(ans); + } +} diff --git a/solutions/1258. Synonymous Sentences/1258.py b/solutions/1258. Synonymous Sentences/1258.py new file mode 100644 index 00000000000..3c6ce56895f --- /dev/null +++ b/solutions/1258. Synonymous Sentences/1258.py @@ -0,0 +1,26 @@ +from sortedcontainers import SortedSet + + +class Solution: + def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]: + ans = SortedSet() + graph = collections.defaultdict(list) + q = collections.deque([text]) + + for s, t in synonyms: + graph[s].append(t) + graph[t].append(s) + + while q: + u = q.popleft() + ans.add(u) + words = u.split() + for i, word in enumerate(words): + for synonym in graph[word]: + # Replace words[i] with its synonym. + words[i] = synonym + newText = ' '.join(words) + if newText not in ans: + q.append(newText) + + return list(ans) diff --git a/solutions/1259. Handshakes That Don't Cross/1259.cpp b/solutions/1259. Handshakes That Don't Cross/1259.cpp new file mode 100644 index 00000000000..25fecc8c458 --- /dev/null +++ b/solutions/1259. Handshakes That Don't Cross/1259.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int numberOfWays(int numPeople) { + constexpr int kMod = 1'000'000'007; + // dp[i] := the number of ways i handshakes could occure s.t. none of the + // handshakes cross + vector dp(numPeople / 2 + 1); + dp[0] = 1; + + for (int i = 1; i <= numPeople / 2; ++i) + for (int j = 0; j < i; ++j) { + dp[i] += dp[j] * dp[i - 1 - j]; + dp[i] %= kMod; + } + + return dp[numPeople / 2]; + } +}; diff --git a/solutions/1259. Handshakes That Don't Cross/1259.java b/solutions/1259. Handshakes That Don't Cross/1259.java new file mode 100644 index 00000000000..3ef1b833aea --- /dev/null +++ b/solutions/1259. Handshakes That Don't Cross/1259.java @@ -0,0 +1,17 @@ +class Solution { + public int numberOfWays(int numPeople) { + final long kMod = 1_000_000_007; + // dp[i] := the number of ways i handshakes could occure s.t. none of the + // handshakes cross + long[] dp = new long[numPeople / 2 + 1]; + dp[0] = 1; + + for (int i = 1; i <= numPeople / 2; ++i) + for (int j = 0; j < i; ++j) { + dp[i] += dp[j] * dp[i - 1 - j]; + dp[i] %= kMod; + } + + return (int) dp[numPeople / 2]; + } +} diff --git a/solutions/1259. Handshakes That Don't Cross/1259.py b/solutions/1259. Handshakes That Don't Cross/1259.py new file mode 100644 index 00000000000..a899c23cb18 --- /dev/null +++ b/solutions/1259. Handshakes That Don't Cross/1259.py @@ -0,0 +1,13 @@ +class Solution: + def numberOfWays(self, numPeople: int) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of ways i handshakes could occure s.t. none of the + # handshakes cross + dp = [1] + [0] * (numPeople // 2) + + for i in range(1, numPeople // 2 + 1): + for j in range(i): + dp[i] += dp[j] * dp[i - 1 - j] + dp[i] %= kMod + + return dp[numPeople // 2] diff --git a/solutions/126. Word Ladder II/126-2.cpp b/solutions/126. Word Ladder II/126-2.cpp new file mode 100644 index 00000000000..cc4283e2feb --- /dev/null +++ b/solutions/126. Word Ladder II/126-2.cpp @@ -0,0 +1,106 @@ +class Solution { + public: + vector> findLadders(string beginWord, string endWord, + vector& wordList) { + unordered_set wordSet{wordList.begin(), wordList.end()}; + if (!wordSet.contains(endWord)) + return {}; + + // {"hit": ["hot"], "hot": ["dot", "lot"], ...} + unordered_map> graph; + + // Build the graph from the beginWord to the endWord. + if (!bfs(beginWord, endWord, wordSet, graph)) + return {}; + + vector> ans; + dfs(graph, beginWord, endWord, {beginWord}, ans); + return ans; + } + + private: + bool bfs(const string& beginWord, const string& endWord, + unordered_set& wordSet, + unordered_map>& graph) { + unordered_set forwardWords{beginWord}; + unordered_set backwardWords{endWord}; + bool backward = false; + + while (!forwardWords.empty() && !backwardWords.empty()) { + for (const string& word : forwardWords) + wordSet.erase(word); + for (const string& word : backwardWords) + wordSet.erase(word); + // Always expand the smaller queue. + if (forwardWords.size() > backwardWords.size()) { + swap(forwardWords, backwardWords); + backward = !backward; + } + unordered_set nextLevelWords; + bool reachEndWord = false; + for (const string& parent : forwardWords) { + for (const string& child : + getChildren(parent, wordSet, backwardWords)) { + // Should check if `child` is in `backwardWords` since we erase them + // at the beginning of each while loop. + if (wordSet.contains(child) || backwardWords.contains(child)) { + nextLevelWords.insert(child); + if (backward) + graph[child].push_back(parent); + else + graph[parent].push_back(child); + } + // We've reached the end word since there's a word in the + // `forwardWords` connecting to a word in `backwardWords`. Note that + // we can't return here since we need to completely explore this + // level. + if (backwardWords.contains(child)) + reachEndWord = true; + } + } + if (reachEndWord) + return true; + forwardWords = move(nextLevelWords); + } + + return true; + } + + vector getChildren(const string& parent, + const unordered_set& wordSet, + const unordered_set& backwardWords) { + vector children; + string s(parent); + + for (int i = 0; i < s.length(); ++i) { + const char cache = s[i]; + for (char c = 'a'; c <= 'z'; ++c) { + if (c == cache) + continue; + s[i] = c; // Now is `child` + if (wordSet.contains(s) || backwardWords.contains(s)) + children.push_back(s); + } + s[i] = cache; + } + + return children; + } + + void dfs(const unordered_map>& graph, + const string& word, const string& endWord, vector&& path, + vector>& ans) { + if (word == endWord) { + ans.push_back(path); + return; + } + if (!graph.contains(word)) + return; + + for (const string& child : graph.at(word)) { + path.push_back(child); + dfs(graph, child, endWord, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/126. Word Ladder II/126-3.cpp b/solutions/126. Word Ladder II/126-3.cpp new file mode 100644 index 00000000000..0e1ecabd41b --- /dev/null +++ b/solutions/126. Word Ladder II/126-3.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector> findLadders(string beginWord, string endWord, + vector& wordList) { + vector> ans; + unordered_set wordSet(wordList.begin(), wordList.end()); + queue> paths{{{beginWord}}}; // {{"hit"}} + + while (!paths.empty()) { + unordered_set currentLevelVisited; + for (int sz = paths.size(); sz > 0; --sz) { + vector path = paths.front(); + paths.pop(); // {"hit"} + string lastWord = path.back(); // "hit" + for (int i = 0; i < lastWord.length(); ++i) { + char cache = lastWord[i]; // Cache = 'i' + for (char c = 'a'; c <= 'z'; ++c) { + lastWord[i] = c; // "hit" -> "hot" (temporarily) + if (wordSet.contains(lastWord)) { // Find "hot" in the wordSet. + currentLevelVisited.insert(lastWord); // Mark "hot" as visited. + vector nextPath(path); + nextPath.push_back(lastWord); // nextPath = {"hit", "hot"} + if (lastWord == endWord) + ans.push_back(nextPath); + else + paths.push(nextPath); + } + } + lastWord[i] = cache; // Convert "hot" back to "hit". + } + } + for (const string& word : currentLevelVisited) + wordSet.erase(word); + } + + return ans; + } +}; diff --git a/solutions/126. Word Ladder II/126-4.cpp b/solutions/126. Word Ladder II/126-4.cpp new file mode 100644 index 00000000000..62755e15b0e --- /dev/null +++ b/solutions/126. Word Ladder II/126-4.cpp @@ -0,0 +1,90 @@ +class Solution { + public: + vector> findLadders(string beginWord, string endWord, + vector& wordList) { + unordered_set wordSet{wordList.begin(), wordList.end()}; + if (!wordSet.contains(endWord)) + return {}; + + // Build the adjacency list. + // e.g. {"hit": ["hot"], "hot": ["dot", "lot"], ...} + if (!wordSet.contains(beginWord)) + wordList.push_back(beginWord); + unordered_map> graph = getGraph(wordList); + + // childToParents[child] := the fastest parents to reach `child` + unordered_map> childToParents; + if (!bfs(beginWord, endWord, graph, childToParents)) + return {}; + + vector> ans; + // Find the paths from the endWord to the beginWord. + dfs(childToParents, endWord, beginWord, {endWord}, ans); + return ans; + } + + private: + unordered_map> getGraph( + const vector& wordList) { + unordered_map> graph; + for (int i = 1; i < wordList.size(); ++i) + for (int j = 0; j < i; ++j) { + const string& u = wordList[i]; + const string& v = wordList[j]; + if (isConnect(u, v)) { + graph[u].push_back(v); + graph[v].push_back(u); + } + } + return graph; + } + + bool isConnect(const string& s, const string& t) { + int count = 0; + for (int i = 0; i < s.length(); ++i) + if (s[i] != t[i]) + ++count; + return count == 1; + } + + bool bfs(const string& beginWord, const string& endWord, + const unordered_map>& graph, + unordered_map>& childToParents) { + // dist[u] := the minimum distance to reach `u` + unordered_map dist{{beginWord, 0}}; + queue q{{beginWord}}; + while (!q.empty()) { + const string u = q.front(); + q.pop(); + if (u == endWord) + return true; + if (const auto it = graph.find(u); it != graph.cend()) + for (const string& v : it->second) + if (!dist.contains(v) || dist[u] + 1 < dist[v]) { + dist[v] = dist[u] + 1; + q.push(v); + // Clear childToParents[v] since they take longer to reach v. + childToParents[v] = {u}; + } else if (dist[u] + 1 == dist[v]) { + // No need to q.push(v) since v is already in the queue. + childToParents[v].push_back(u); + } + } + return false; + } + + void dfs(const unordered_map>& childToParents, + const string& word, const string& beginWord, vector&& path, + vector>& ans) { + if (word == beginWord) { + ans.push_back({path.rbegin(), path.rend()}); + return; + } + if (const auto it = childToParents.find(word); it != childToParents.cend()) + for (const string& parent : it->second) { + path.push_back(parent); + dfs(childToParents, parent, beginWord, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/126. Word Ladder II/126-5.cpp b/solutions/126. Word Ladder II/126-5.cpp new file mode 100644 index 00000000000..31de9df4aa3 --- /dev/null +++ b/solutions/126. Word Ladder II/126-5.cpp @@ -0,0 +1,81 @@ +class Solution { + public: + vector> findLadders(string beginWord, string endWord, + vector& wordList) { + unordered_set wordSet{wordList.begin(), wordList.end()}; + if (!wordSet.contains(endWord)) + return {}; + + unordered_map distFromBeginWord{{beginWord, 0}}; + if (!bfs(beginWord, endWord, wordSet, distFromBeginWord)) + return {}; + + vector> ans; + wordSet.insert(beginWord); + dfs(endWord, beginWord, distFromBeginWord, wordSet, {endWord}, ans); + return ans; + } + + private: + // Uses BFS to update the minimum steps to reach `endWord` from `beginWord` by + // using the words in `wordSet`. + bool bfs(const string& beginWord, const string& endWord, + unordered_set& wordSet, + unordered_map& distFromBeginWord) { + queue q{{beginWord}}; + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const string parent = q.front(); + q.pop(); + if (parent == endWord) + return true; + for (const string& child : getChildren(parent, wordSet)) { + if (distFromBeginWord.contains(child)) + continue; + distFromBeginWord[child] = distFromBeginWord[parent] + 1; + q.push(child); + } + } + } + return false; + } + + void dfs(const string& word, const string& beginWord, + const unordered_map& distFromBeginWord, + const unordered_set& wordSet, vector&& path, + vector>& ans) { + if (word == beginWord) { + ans.push_back({path.rbegin(), path.rend()}); + return; + } + + const int currDist = distFromBeginWord.at(word); + + for (const string& child : getChildren(word, wordSet)) { + if (const auto it = distFromBeginWord.find(child); + it != distFromBeginWord.cend() && it->second == currDist - 1) { + path.push_back(child); + dfs(child, beginWord, distFromBeginWord, wordSet, move(path), ans); + path.pop_back(); + } + } + } + + vector getChildren(const string& parent, + const unordered_set& wordSet) { + vector children; + string child(parent); + for (int i = 0; i < child.length(); ++i) { + const char cache = child[i]; + for (char c = 'a'; c <= 'z'; ++c) { + if (c == cache) + continue; + child[i] = c; + if (wordSet.contains(child)) + children.push_back(child); + } + child[i] = cache; + } + return children; + } +}; diff --git a/solutions/126. Word Ladder II/126.cpp b/solutions/126. Word Ladder II/126.cpp new file mode 100644 index 00000000000..0c2a223b452 --- /dev/null +++ b/solutions/126. Word Ladder II/126.cpp @@ -0,0 +1,85 @@ +class Solution { + public: + vector> findLadders(string beginWord, string endWord, + vector& wordList) { + unordered_set wordSet{wordList.begin(), wordList.end()}; + if (!wordSet.contains(endWord)) + return {}; + + // {"hit": ["hot"], "hot": ["dot", "lot"], ...} + unordered_map> graph; + + // Build the graph from the beginWord to the endWord. + if (!bfs(beginWord, endWord, wordSet, graph)) + return {}; + + vector> ans; + dfs(graph, beginWord, endWord, {beginWord}, ans); + return ans; + } + + private: + bool bfs(const string& beginWord, const string& endWord, + unordered_set& wordSet, + unordered_map>& graph) { + unordered_set currentLevelWords{beginWord}; + + while (!currentLevelWords.empty()) { + for (const string& word : currentLevelWords) + wordSet.erase(word); + unordered_set nextLevelWords; + bool reachEndWord = false; + for (const string& parent : currentLevelWords) { + vector children; + getChildren(parent, wordSet, children); + for (const string& child : children) { + if (wordSet.contains(child)) { + nextLevelWords.insert(child); + graph[parent].push_back(child); + } + if (child == endWord) + reachEndWord = true; + } + } + if (reachEndWord) + return true; + currentLevelWords = move(nextLevelWords); + } + + return false; + } + + void getChildren(const string& parent, const unordered_set& wordSet, + vector& children) { + string s(parent); + + for (int i = 0; i < s.length(); ++i) { + const char cache = s[i]; + for (char c = 'a'; c <= 'z'; ++c) { + if (c == cache) + continue; + s[i] = c; + if (wordSet.contains(s)) + children.push_back(s); + } + s[i] = cache; + } + } + + void dfs(const unordered_map>& graph, + const string& word, const string& endWord, vector&& path, + vector>& ans) { + if (word == endWord) { + ans.push_back(path); + return; + } + if (!graph.contains(word)) + return; + + for (const string& child : graph.at(word)) { + path.push_back(child); + dfs(graph, child, endWord, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/126. Word Ladder II/126.java b/solutions/126. Word Ladder II/126.java new file mode 100644 index 00000000000..82f7f2ee157 --- /dev/null +++ b/solutions/126. Word Ladder II/126.java @@ -0,0 +1,84 @@ +class Solution { + public List> findLadders(String beginWord, String endWord, List wordList) { + Set wordSet = new HashSet<>(wordList); + if (!wordSet.contains(endWord)) + return new ArrayList<>(); + + // {"hit": ["hot"], "hot": ["dot", "lot"], ...} + Map> graph = new HashMap<>(); + + // Build the graph from the beginWord to the endWord. + if (!bfs(beginWord, endWord, wordSet, graph)) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + List path = new ArrayList<>(Arrays.asList(beginWord)); + dfs(graph, beginWord, endWord, path, ans); + return ans; + } + + private boolean bfs(final String beginWord, final String endWord, Set wordSet, + Map> graph) { + Set currentLevelWords = new HashSet<>(); + currentLevelWords.add(beginWord); + boolean reachEndWord = false; + + while (!currentLevelWords.isEmpty()) { + for (final String word : currentLevelWords) + wordSet.remove(word); + Set nextLevelWords = new HashSet<>(); + for (final String parent : currentLevelWords) { + graph.putIfAbsent(parent, new ArrayList<>()); + for (final String child : getChildren(parent, wordSet)) { + if (wordSet.contains(child)) { + nextLevelWords.add(child); + graph.get(parent).add(child); + } + if (child.equals(endWord)) + reachEndWord = true; + } + } + if (reachEndWord) + return true; + currentLevelWords = nextLevelWords; + } + + return false; + } + + private List getChildren(final String parent, Set wordSet) { + List children = new ArrayList<>(); + StringBuilder sb = new StringBuilder(parent); + + for (int i = 0; i < sb.length(); ++i) { + final char cache = sb.charAt(i); + for (char c = 'a'; c <= 'z'; ++c) { + if (c == cache) + continue; + sb.setCharAt(i, c); + final String child = sb.toString(); + if (wordSet.contains(child)) + children.add(child); + } + sb.setCharAt(i, cache); + } + + return children; + } + + private void dfs(Map> graph, final String word, final String endWord, + List path, List> ans) { + if (word.equals(endWord)) { + ans.add(new ArrayList<>(path)); + return; + } + if (!graph.containsKey(word)) + return; + + for (final String child : graph.get(word)) { + path.add(child); + dfs(graph, child, endWord, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/126. Word Ladder II/126.py b/solutions/126. Word Ladder II/126.py new file mode 100644 index 00000000000..974015dc807 --- /dev/null +++ b/solutions/126. Word Ladder II/126.py @@ -0,0 +1,63 @@ +class Solution: + def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: + wordSet = set(wordList) + if endWord not in wordList: + return [] + + # {"hit": ["hot"], "hot": ["dot", "lot"], ...} + graph: Dict[str, List[str]] = collections.defaultdict(list) + + # Build the graph from the beginWord to the endWord. + if not self._bfs(beginWord, endWord, wordSet, graph): + return [] + + ans = [] + self._dfs(graph, beginWord, endWord, [beginWord], ans) + return ans + + def _bfs(self, beginWord: str, endWord: str, wordSet: Set[str], graph: Dict[str, List[str]]) -> bool: + currentLevelWords = {beginWord} + + while currentLevelWords: + for word in currentLevelWords: + wordSet.discard(word) + nextLevelWords = set() + reachEndWord = False + for parent in currentLevelWords: + for child in self._getChildren(parent, wordSet): + if child in wordSet: + nextLevelWords.add(child) + graph[parent].append(child) + if child == endWord: + reachEndWord = True + if reachEndWord: + return True + currentLevelWords = nextLevelWords + + return False + + def _getChildren(self, parent: str, wordSet: Set[str]) -> List[str]: + children = [] + s = list(parent) + + for i, cache in enumerate(s): + for c in string.ascii_lowercase: + if c == cache: + continue + s[i] = c + child = ''.join(s) + if child in wordSet: + children.append(child) + s[i] = cache + + return children + + def _dfs(self, graph: Dict[str, List[str]], word: str, endWord: str, path: List[str], ans: List[List[str]]) -> None: + if word == endWord: + ans.append(path.copy()) + return + + for child in graph.get(word, []): + path.append(child) + self._dfs(graph, child, endWord, path, ans) + path.pop() diff --git a/solutions/126. Word Ladder II/127-2.py b/solutions/126. Word Ladder II/127-2.py new file mode 100644 index 00000000000..744c531a5c8 --- /dev/null +++ b/solutions/126. Word Ladder II/127-2.py @@ -0,0 +1,75 @@ +class Solution: + def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: + wordSet = set(wordList) + if endWord not in wordList: + return [] + + # {"hit": ["hot"], "hot": ["dot", "lot"], ...} + graph: Dict[str, List[str]] = collections.defaultdict(list) + + # Build the graph from the beginWord to the endWord. + if not self._bfs(beginWord, endWord, wordSet, graph): + return [] + + ans = [] + + self._dfs(graph, beginWord, endWord, [beginWord], ans) + return ans + + def _bfs(self, beginWord: str, endWord: str, wordSet: Set[str], graph: Dict[str, List[str]]) -> bool: + q1 = {beginWord} + q2 = {endWord} + backward = False + + while q1 and q2: + for word in q1: + wordSet.discard(word) + for word in q2: + wordSet.discard(word) + # Always expand the smaller queue. + if len(q1) > len(q2): + q1, q2 = q2, q1 + backward = not backward + q = set() + reachEndWord = False + for parent in q1: + for child in self._getChildren(parent, wordSet, q2): + if child in wordSet or child in q2: + q.add(child) + if backward: + graph[child].append(parent) + else: + graph[parent].append(child) + if child in q2: + reachEndWord = True + if reachEndWord: + return True + q1 = q + + return False + + def _getChildren(self, parent: str, wordSet: Set[str], q2) -> List[str]: + children = [] + s = list(parent) + + for i, cache in enumerate(s): + for c in string.ascii_lowercase: + if c == cache: + continue + s[i] = c + child = ''.join(s) + if child in wordSet or child in q2: + children.append(child) + s[i] = cache + + return children + + def _dfs(self, graph: Dict[str, List[str]], word: str, endWord: str, path: List[str], ans: List[List[str]]) -> None: + if word == endWord: + ans.append(path.copy()) + return + + for child in graph.get(word, []): + path.append(child) + self._dfs(graph, child, endWord, path, ans) + path.pop() diff --git a/solutions/1260. Shift 2D Grid/1260.cpp b/solutions/1260. Shift 2D Grid/1260.cpp new file mode 100644 index 00000000000..fd95a3151f6 --- /dev/null +++ b/solutions/1260. Shift 2D Grid/1260.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector> shiftGrid(vector>& grid, int k) { + const int m = grid.size(); + const int n = grid[0].size(); + vector> ans(m, vector(n)); + + k %= m * n; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + const int index = (i * n + j + k) % (m * n); + const int x = index / n; + const int y = index % n; + ans[x][y] = grid[i][j]; + } + + return ans; + } +}; diff --git a/solutions/1260. Shift 2D Grid/1260.java b/solutions/1260. Shift 2D Grid/1260.java new file mode 100644 index 00000000000..1e491b39e5a --- /dev/null +++ b/solutions/1260. Shift 2D Grid/1260.java @@ -0,0 +1,23 @@ +class Solution { + public List> shiftGrid(int[][] grid, int k) { + final int m = grid.length; + final int n = grid[0].length; + List> ans = new ArrayList<>(); + int[][] arr = new int[m][n]; + + k %= m * n; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + final int index = (i * n + j + k) % (m * n); + final int x = index / n; + final int y = index % n; + arr[x][y] = grid[i][j]; + } + + for (int[] row : arr) + ans.add(Arrays.stream(row).boxed().collect(Collectors.toList())); + + return ans; + } +} diff --git a/solutions/1260. Shift 2D Grid/1260.py b/solutions/1260. Shift 2D Grid/1260.py new file mode 100644 index 00000000000..e9732e8ac1d --- /dev/null +++ b/solutions/1260. Shift 2D Grid/1260.py @@ -0,0 +1,16 @@ +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m = len(grid) + n = len(grid[0]) + ans = [[0] * n for _ in range(m)] + + k %= m * n + + for i in range(m): + for j in range(n): + index = (i * n + j + k) % (m * n) + x = index // n + y = index % n + ans[x][y] = grid[i][j] + + return ans diff --git a/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.cpp b/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.cpp new file mode 100644 index 00000000000..ec36a6cad0c --- /dev/null +++ b/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.cpp @@ -0,0 +1,23 @@ +class FindElements { + public: + FindElements(TreeNode* root) { + dfs(root, 0); + } + + bool find(int target) { + return vals.contains(target); + } + + private: + unordered_set vals; + + void dfs(TreeNode* root, int val) { + if (root == nullptr) + return; + + root->val = val; + vals.insert(val); + dfs(root->left, val * 2 + 1); + dfs(root->right, val * 2 + 2); + } +}; diff --git a/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.java b/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.java new file mode 100644 index 00000000000..2ad52326a1e --- /dev/null +++ b/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.java @@ -0,0 +1,21 @@ +class FindElements { + public FindElements(TreeNode root) { + dfs(root, 0); + } + + public boolean find(int target) { + return vals.contains(target); + } + + private Set vals = new HashSet<>(); + + private void dfs(TreeNode root, int val) { + if (root == null) + return; + + root.val = val; + vals.add(val); + dfs(root.left, val * 2 + 1); + dfs(root.right, val * 2 + 2); + } +} diff --git a/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.py b/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.py new file mode 100644 index 00000000000..f46d4918f98 --- /dev/null +++ b/solutions/1261. Find Elements in a Contaminated Binary Tree/1261.py @@ -0,0 +1,16 @@ +class FindElements: + def __init__(self, root: Optional[TreeNode]): + self.vals = set() + self.dfs(root, 0) + + def find(self, target: int) -> bool: + return target in self.vals + + def dfs(self, root: Optional[TreeNode], val: int) -> None: + if not root: + return + + root.val = val + self.vals.add(val) + self.dfs(root.left, val * 2 + 1) + self.dfs(root.right, val * 2 + 2) diff --git a/solutions/1262. Greatest Sum Divisible by Three/1262.cpp b/solutions/1262. Greatest Sum Divisible by Three/1262.cpp new file mode 100644 index 00000000000..a32fc97a82d --- /dev/null +++ b/solutions/1262. Greatest Sum Divisible by Three/1262.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int maxSumDivThree(vector& nums) { + vector dp(3); // dp[i] := the maximum sum so far s.t. sum % 3 == i + + for (const int num : nums) + for (const int sum : vector(dp)) + dp[(sum + num) % 3] = max(dp[(sum + num) % 3], sum + num); + + return dp[0]; + } +}; diff --git a/solutions/1262. Greatest Sum Divisible by Three/1262.java b/solutions/1262. Greatest Sum Divisible by Three/1262.java new file mode 100644 index 00000000000..02a7372c2ac --- /dev/null +++ b/solutions/1262. Greatest Sum Divisible by Three/1262.java @@ -0,0 +1,11 @@ +class Solution { + public int maxSumDivThree(int[] nums) { + int[] dp = new int[3]; // dp[i] := the maximum sum so far s.t. sum % 3 == i + + for (final int num : nums) + for (final int sum : dp.clone()) + dp[(sum + num) % 3] = Math.max(dp[(sum + num) % 3], sum + num); + + return dp[0]; + } +} diff --git a/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.cpp b/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.cpp new file mode 100644 index 00000000000..bf7ac10b006 --- /dev/null +++ b/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.cpp @@ -0,0 +1,93 @@ +class Solution { + public: + int minPushBox(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector box; + vector player; + vector target; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 'B') + box = {i, j}; + else if (grid[i][j] == 'S') + player = {i, j}; + else if (grid[i][j] == 'T') + target = {i, j}; + + int ans = 0; + // (boxX, boxY, playerX, playerY) + queue> q{ + {{box[0], box[1], player[0], player[1]}}}; + vector>>> seen( + m, vector>>( + n, vector>(m, vector(n)))); + seen[box[0]][box[1]][player[0]][player[1]] = true; + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const auto [boxX, boxY, playerX, playerY] = q.front(); + q.pop(); + if (boxX == target[0] && boxY == target[1]) + return ans; + for (const auto& [dx, dy] : dirs) { + const int nextBoxX = boxX + dx; + const int nextBoxY = boxY + dy; + if (isInvalid(grid, nextBoxX, nextBoxY)) + continue; + if (seen[nextBoxX][nextBoxY][boxX][boxY]) + continue; + const int fromX = boxX + dirs[(k + 2) % 4]; + const int fromY = boxY + dirs[(k + 3) % 4]; + if (isInvalid(grid, fromX, fromY)) + continue; + if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) { + seen[nextBoxX][nextBoxY][boxX][boxY] = true; + q.emplace(nextBoxX, nextBoxY, boxX, boxY); + } + } + } + ++ans; + } + + return -1; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns true if (playerX, playerY) can go to (fromX, fromY). + bool canGoTo(const vector>& grid, int playerX, int playerY, + int fromX, int fromY, int boxX, int boxY) { + queue> q{{{playerX, playerY}}}; + vector> seen(grid.size(), vector(grid[0].size())); + seen[playerX][playerY] = true; + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + if (i == fromX && j == fromY) + return true; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (isInvalid(grid, x, y)) + continue; + if (seen[x][y]) + continue; + if (x == boxX && y == boxY) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + + return false; + } + + bool isInvalid(const vector>& grid, int playerX, int playerY) { + return playerX < 0 || playerX == grid.size() || playerY < 0 || + playerY == grid[0].size() || grid[playerX][playerY] == '#'; + } +}; diff --git a/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.java b/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.java new file mode 100644 index 00000000000..2f8454685a7 --- /dev/null +++ b/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.java @@ -0,0 +1,91 @@ +class Solution { + public int minPushBox(char[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[] box = {-1, -1}; + int[] player = {-1, -1}; + int[] target = {-1, -1}; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 'B') + box = new int[] {i, j}; + else if (grid[i][j] == 'S') + player = new int[] {i, j}; + else if (grid[i][j] == 'T') + target = new int[] {i, j}; + + int ans = 0; + // (boxX, boxY, playerX, playerY) + Queue q = + new ArrayDeque<>(Arrays.asList(new int[] {box[0], box[1], player[0], player[1]})); + boolean[][][][] seen = new boolean[m][n][m][n]; + seen[box[0]][box[1]][player[0]][player[1]] = true; + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int boxX = q.peek()[0]; + final int boxY = q.peek()[1]; + final int playerX = q.peek()[2]; + final int playerY = q.poll()[3]; + if (boxX == target[0] && boxY == target[1]) + return ans; + for (int[] dir : dirs) { + final int nextBoxX = boxX + dir[0]; + final int nextBoxY = boxY + dir[1]; + if (isInvalid(grid, nextBoxX, nextBoxY)) + continue; + if (seen[nextBoxX][nextBoxY][boxX][boxY]) + continue; + final int fromX = boxX + dirs[(k + 2) % 4]; + final int fromY = boxY + dirs[(k + 3) % 4]; + if (isInvalid(grid, fromX, fromY)) + continue; + if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) { + seen[nextBoxX][nextBoxY][boxX][boxY] = true; + q.offer(new int[] {nextBoxX, nextBoxY, boxX, boxY}); + } + } + } + ++ans; + } + + return -1; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns true if (playerX, playerY) can go to (fromX, fromY). + private boolean canGoTo(char[][] grid, int playerX, int playerY, int fromX, int fromY, int boxX, + int boxY) { + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(playerX, playerY))); + boolean[][] seen = new boolean[grid.length][grid[0].length]; + seen[playerX][playerY] = true; + + while (!q.isEmpty()) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + if (i == fromX && j == fromY) + return true; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (isInvalid(grid, x, y)) + continue; + if (seen[x][y]) + continue; + if (x == boxX && y == boxY) + continue; + q.offer(new Pair<>(x, y)); + seen[x][y] = true; + } + } + + return false; + } + + private boolean isInvalid(char[][] grid, int playerX, int playerY) { + return playerX < 0 || playerX == grid.length || playerY < 0 || playerY == grid[0].length || + grid[playerX][playerY] == '#'; + } +} diff --git a/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.py b/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.py new file mode 100644 index 00000000000..b9fadd9c0b8 --- /dev/null +++ b/solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.py @@ -0,0 +1,69 @@ +class Solution: + def minPushBox(self, grid: List[List[chr]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + + for i in range(m): + for j in range(n): + if grid[i][j] == 'B': + box = (i, j) + elif grid[i][j] == 'S': + player = (i, j) + elif grid[i][j] == 'T': + target = (i, j) + + def isInvalid(playerX: int, playerY: int) -> bool: + return playerX < 0 or playerX == m or playerY < 0 or playerY == n \ + or grid[playerX][playerY] == '#' + + def canGoTo(playerX: int, playerY: int, fromX: int, fromY: int, boxX: int, boxY: int) -> bool: + """Returns True if (playerX, playerY) can go to (fromX, fromY).""" + q = collections.deque([(playerX, playerY)]) + seen = {(playerX, playerY)} + + while q: + i, j = q.popleft() + if i == fromX and j == fromY: + return True + for dx, dy in dirs: + x = i + dx + y = j + dy + if isInvalid(x, y): + continue + if (x, y) in seen: + continue + if x == boxX and y == boxY: + continue + q.append((x, y)) + seen.add((x, y)) + + return False + + ans = 0 + # (boxX, boxY, playerX, playerY) + q = collections.deque([(box[0], box[1], player[0], player[1])]) + seen = {(box[0], box[1], player[0], player[1])} + + while q: + for _ in range(len(q)): + boxX, boxY, playerX, playerY = q.popleft() + if boxX == target[0] and boxY == target[1]: + return ans + for dx, dy in dirs: + nextBoxX = boxX + dx + nextBoxY = boxY + dy + if isInvalid(nextBoxX, nextBoxY): + continue + if (nextBoxX, nextBoxY, boxX, boxY) in seen: + continue + fromX = boxX + dirs[(k + 2) % 4] + fromY = boxY + dirs[(k + 3) % 4] + if isInvalid(fromX, fromY): + continue + if canGoTo(playerX, playerY, fromX, fromY, boxX, boxY): + q.append((nextBoxX, nextBoxY, boxX, boxY)) + seen.add((nextBoxX, nextBoxY, boxX, boxY)) + ans += 1 + + return -1 diff --git a/solutions/1264. Page Recommendations/1264.sql b/solutions/1264. Page Recommendations/1264.sql new file mode 100644 index 00000000000..0c9ac788ca5 --- /dev/null +++ b/solutions/1264. Page Recommendations/1264.sql @@ -0,0 +1,19 @@ +WITH + UserToFriends AS ( + SELECT user1_id AS user_id, user2_id AS friend_id FROM Friendship + UNION ALL + SELECT user2_id AS user_id, user1_id AS friend_id FROM friendship + ) +SELECT FriendLikes.page_id AS recommended_page +FROM UserToFriends +LEFT JOIN Likes AS FriendLikes + ON (UserToFriends.friend_id = FriendLikes.user_id) +LEFT JOIN Likes AS UserLikes + ON ( + UserToFriends.user_id = UserLikes.user_id + AND FriendLikes.page_id = UserLikes.page_id) +WHERE + UserToFriends.user_id = 1 + AND UserLikes.page_id IS NULL + AND FriendLikes.page_id IS NOT NULL +GROUP BY 1; diff --git a/solutions/1265. Print Immutable Linked List in Reverse/1265-2.cpp b/solutions/1265. Print Immutable Linked List in Reverse/1265-2.cpp new file mode 100644 index 00000000000..90506d3d218 --- /dev/null +++ b/solutions/1265. Print Immutable Linked List in Reverse/1265-2.cpp @@ -0,0 +1,24 @@ +/** + * // This is the ImmutableListNode's API interface. + * // You should not implement it, or speculate about its implementation. + * class ImmutableListNode { + * public: + * void printValue(); // Print the value of the node. + * ImmutableListNode* getNext(); // Returns the next node. + * }; + */ + +class Solution { + public: + void printLinkedListInReverse(ImmutableListNode* head) { + stack stack; + + while (head) { + stack.push(head); + head = head->getNext(); + } + + while (!stack.empty()) + stack.top()->printValue(), stack.pop(); + } +}; diff --git a/solutions/1265. Print Immutable Linked List in Reverse/1265.cpp b/solutions/1265. Print Immutable Linked List in Reverse/1265.cpp new file mode 100644 index 00000000000..a1462dfc67f --- /dev/null +++ b/solutions/1265. Print Immutable Linked List in Reverse/1265.cpp @@ -0,0 +1,20 @@ +/** + * // This is the ImmutableListNode's API interface. + * // You should not implement it, or speculate about its implementation. + * class ImmutableListNode { + * public: + * void printValue(); // Print the value of the node. + * ImmutableListNode* getNext(); // Returns the next node. + * }; + */ + +class Solution { + public: + void printLinkedListInReverse(ImmutableListNode* head) { + if (head == nullptr) + return; + + printLinkedListInReverse(head->getNext()); + head->printValue(); + } +}; diff --git a/solutions/1266. Minimum Time Visiting All Points/1266.cpp b/solutions/1266. Minimum Time Visiting All Points/1266.cpp new file mode 100644 index 00000000000..79cbca6251b --- /dev/null +++ b/solutions/1266. Minimum Time Visiting All Points/1266.cpp @@ -0,0 +1,12 @@ +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/solutions/1266. Minimum Time Visiting All Points/1266.java b/solutions/1266. Minimum Time Visiting All Points/1266.java new file mode 100644 index 00000000000..d745cac8a84 --- /dev/null +++ b/solutions/1266. Minimum Time Visiting All Points/1266.java @@ -0,0 +1,11 @@ +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/solutions/1266. Minimum Time Visiting All Points/1266.py b/solutions/1266. Minimum Time Visiting All Points/1266.py new file mode 100644 index 00000000000..3f726dbbbf6 --- /dev/null +++ b/solutions/1266. Minimum Time Visiting All Points/1266.py @@ -0,0 +1,9 @@ +class Solution: + def minTimeToVisitAllPoints(self, points: List[List[int]]) -> 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/solutions/1267. Count Servers that Communicate/1267.cpp b/solutions/1267. Count Servers that Communicate/1267.cpp new file mode 100644 index 00000000000..242847ffafe --- /dev/null +++ b/solutions/1267. Count Servers that Communicate/1267.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int countServers(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + vector rows(m); + vector cols(n); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + ++rows[i]; + ++cols[j]; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1)) + ++ans; + + return ans; + } +}; diff --git a/solutions/1267. Count Servers that Communicate/1267.java b/solutions/1267. Count Servers that Communicate/1267.java new file mode 100644 index 00000000000..73110b00fbd --- /dev/null +++ b/solutions/1267. Count Servers that Communicate/1267.java @@ -0,0 +1,23 @@ +class Solution { + public int countServers(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + int[] rows = new int[m]; + int[] cols = new int[n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + ++rows[i]; + ++cols[j]; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1)) + ++ans; + + return ans; + } +} diff --git a/solutions/1267. Count Servers that Communicate/1267.py b/solutions/1267. Count Servers that Communicate/1267.py new file mode 100644 index 00000000000..55451c95443 --- /dev/null +++ b/solutions/1267. Count Servers that Communicate/1267.py @@ -0,0 +1,20 @@ +class Solution: + def countServers(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + ans = 0 + rows = [0] * m + cols = [0] * n + + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + rows[i] += 1 + cols[j] += 1 + + for i in range(m): + for j in range(n): + if grid[i][j] == 1 and (rows[i] > 1 or cols[j] > 1): + ans += 1 + + return ans diff --git a/solutions/1268. Search Suggestions System/1268.cpp b/solutions/1268. Search Suggestions System/1268.cpp new file mode 100644 index 00000000000..dbc0c382161 --- /dev/null +++ b/solutions/1268. Search Suggestions System/1268.cpp @@ -0,0 +1,61 @@ +struct TrieNode { + vector> children; + const string* word = nullptr; + TrieNode() : children(26) {} +}; + +class Solution { + public: + vector> suggestedProducts(vector& products, + string searchWord) { + vector> ans; + + for (const string& product : products) + insert(product); + + shared_ptr node = root; + + for (const char c : searchWord) { + if (node == nullptr || node->children[c - 'a'] == nullptr) { + node = nullptr; + ans.push_back({}); + continue; + } + node = node->children[c - 'a']; + ans.push_back(search(node)); + } + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->word = &word; + } + + vector search(shared_ptr node) { + vector res; + dfs(node, res); + return res; + } + + void dfs(shared_ptr node, vector& ans) { + if (ans.size() == 3) + return; + if (node == nullptr) + return; + if (node->word != nullptr) + ans.push_back(*node->word); + for (shared_ptr child : node->children) + dfs(child, ans); + } +}; diff --git a/solutions/1268. Search Suggestions System/1268.java b/solutions/1268. Search Suggestions System/1268.java new file mode 100644 index 00000000000..73b739b7832 --- /dev/null +++ b/solutions/1268. Search Suggestions System/1268.java @@ -0,0 +1,57 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public String word; +} + +class Solution { + public List> suggestedProducts(String[] products, String searchWord) { + List> ans = new ArrayList<>(); + + for (final String product : products) + insert(product); + + TrieNode node = root; + + for (final char c : searchWord.toCharArray()) { + if (node == null || node.children[c - 'a'] == null) { + node = null; + ans.add(new ArrayList<>()); + continue; + } + node = node.children[c - 'a']; + ans.add(search(node)); + } + + return ans; + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.word = word; + } + + private List search(TrieNode node) { + List res = new ArrayList<>(); + dfs(node, res); + return res; + } + + private void dfs(TrieNode node, List ans) { + if (ans.size() == 3) + return; + if (node == null) + return; + if (node.word != null) + ans.add(node.word); + for (TrieNode child : node.children) + dfs(child, ans); + } +} diff --git a/solutions/1268. Search Suggestions System/1268.py b/solutions/1268. Search Suggestions System/1268.py new file mode 100644 index 00000000000..fd6bac6cd4e --- /dev/null +++ b/solutions/1268. Search Suggestions System/1268.py @@ -0,0 +1,47 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.word: Optional[str] = None + + +class Solution: + def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: + ans = [] + root = TrieNode() + + def insert(word: str) -> None: + node = root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.word = word + + def search(node: Optional[TrieNode]) -> List[str]: + res: List[str] = [] + dfs(node, res) + return res + + def dfs(node: Optional[TrieNode], res: List[str]) -> None: + if len(res) == 3: + return + if not node: + return + if node.word: + res.append(node.word) + for c in string.ascii_lowercase: + if c in node.children: + dfs(node.children[c], res) + + for product in products: + insert(product) + + node = root + + for c in searchWord: + if not node or c not in node.children: + node = None + ans.append([]) + continue + node = node.children[c] + ans.append(search(node)) + + return ans diff --git a/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.cpp b/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.cpp new file mode 100644 index 00000000000..c6bf0cb4b0b --- /dev/null +++ b/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int numWays(int steps, int arrLen) { + constexpr int kMod = 1'000'000'007; + const int n = min(arrLen, steps / 2 + 1); + // dp[i] := the number of ways to stay at index i + vector dp(n); + dp[0] = 1; + + while (steps--) { + vector newDp(n); + for (int i = 0; i < n; ++i) { + newDp[i] = dp[i]; + if (i - 1 >= 0) + newDp[i] += dp[i - 1]; + if (i + 1 < n) + newDp[i] += dp[i + 1]; + newDp[i] %= kMod; + } + dp = move(newDp); + } + + return dp[0]; + } +}; diff --git a/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.java b/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.java new file mode 100644 index 00000000000..e893d055dd8 --- /dev/null +++ b/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.java @@ -0,0 +1,24 @@ +class Solution { + public int numWays(int steps, int arrLen) { + final int kMod = 1_000_000_007; + final int n = Math.min(arrLen, steps / 2 + 1); + // dp[i] := the number of ways to stay at index i + long[] dp = new long[n]; + dp[0] = 1; + + while (steps-- > 0) { + long[] newDp = new long[n]; + for (int i = 0; i < n; ++i) { + newDp[i] = dp[i]; + if (i - 1 >= 0) + newDp[i] += dp[i - 1]; + if (i + 1 < n) + newDp[i] += dp[i + 1]; + newDp[i] %= kMod; + } + dp = newDp; + } + + return (int) dp[0]; + } +} diff --git a/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.py b/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.py new file mode 100644 index 00000000000..47841c65545 --- /dev/null +++ b/solutions/1269. Number of Ways to Stay in the Same Place After Some Steps/1269.py @@ -0,0 +1,19 @@ +class Solution: + def numWays(self, steps: int, arrLen: int) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of ways to stay at index i + dp = [0] * min(steps // 2 + 1, arrLen) + dp[0] = 1 + + for _ in range(steps): + newDp = [0] * min(steps // 2 + 1, arrLen) + for i, ways in enumerate(dp): + if ways > 0: + for dx in (-1, 0, 1): + nextIndex = i + dx + if 0 <= nextIndex < len(dp): + newDp[nextIndex] += ways + newDp[nextIndex] %= kMod + dp = newDp + + return dp[0] diff --git a/solutions/127. Word Ladder/127.cpp b/solutions/127. Word Ladder/127.cpp new file mode 100644 index 00000000000..2d398428451 --- /dev/null +++ b/solutions/127. Word Ladder/127.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set wordSet(wordList.begin(), wordList.end()); + if (!wordSet.contains(endWord)) + return 0; + + int ans = 0; + queue q{{beginWord}}; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + string word = q.front(); + q.pop(); + for (int i = 0; i < word.length(); ++i) { + const char cache = word[i]; + for (char c = 'a'; c <= 'z'; ++c) { + word[i] = c; + if (word == endWord) + return ans + 1; + if (wordSet.contains(word)) { + q.push(word); + wordSet.erase(word); + } + } + word[i] = cache; + } + } + } + + return 0; + } +}; diff --git a/solutions/127. Word Ladder/127.java b/solutions/127. Word Ladder/127.java new file mode 100644 index 00000000000..f25d9ee4672 --- /dev/null +++ b/solutions/127. Word Ladder/127.java @@ -0,0 +1,33 @@ +class Solution { + public int ladderLength(String beginWord, String endWord, List wordList) { + Set wordSet = new HashSet<>(wordList); + if (!wordSet.contains(endWord)) + return 0; + + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(beginWord)); + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + StringBuilder sb = new StringBuilder(q.poll()); + for (int i = 0; i < sb.length(); ++i) { + final char cache = sb.charAt(i); + for (char c = 'a'; c <= 'z'; ++c) { + sb.setCharAt(i, c); + final String word = sb.toString(); + if (word.equals(endWord)) + return ans + 1; + if (wordSet.contains(word)) { + q.offer(word); + wordSet.remove(word); + } + } + sb.setCharAt(i, cache); + } + } + } + + return 0; + } +} diff --git a/solutions/127. Word Ladder/127.py b/solutions/127. Word Ladder/127.py new file mode 100644 index 00000000000..5bf245bd061 --- /dev/null +++ b/solutions/127. Word Ladder/127.py @@ -0,0 +1,25 @@ +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + wordSet = set(wordList) + if endWord not in wordSet: + return 0 + + ans = 0 + q = collections.deque([beginWord]) + + while q: + ans += 1 + for _ in range(len(q)): + wordList = list(q.popleft()) + for i, cache in enumerate(wordList): + for c in string.ascii_lowercase: + wordList[i] = c + word = ''.join(wordList) + if word == endWord: + return ans + 1 + if word in wordSet: + q.append(word) + wordSet.remove(word) + wordList[i] = cache + + return 0 diff --git a/solutions/1270. All People Report to the Given Manager/1270.sql b/solutions/1270. All People Report to the Given Manager/1270.sql new file mode 100644 index 00000000000..2bc9e987549 --- /dev/null +++ b/solutions/1270. All People Report to the Given Manager/1270.sql @@ -0,0 +1,9 @@ +SELECT Employee.employee_id +FROM Employees AS Employee +INNER JOIN Employees AS DirectManager + ON (Employee.manager_id = DirectManager.employee_id) +INNER JOIN Employees AS SkipManager + ON (DirectManager.manager_id = SkipManager.employee_id) +WHERE + SkipManager.manager_id = 1 + AND Employee.employee_id != 1; diff --git a/solutions/1271. Hexspeak/1271.cpp b/solutions/1271. Hexspeak/1271.cpp new file mode 100644 index 00000000000..2d7d59b6183 --- /dev/null +++ b/solutions/1271. Hexspeak/1271.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string toHexspeak(string num) { + const long n = stol(num); + stringstream ss; + ss << hex << uppercase << n; + string ans(ss.str()); + + for (char& c : ans) { + if (c > '1' && c <= '9') + return "ERROR"; + if (c == '0') + c = 'O'; + else if (c == '1') + c = 'I'; + } + + return ans; + } +}; diff --git a/solutions/1271. Hexspeak/1271.java b/solutions/1271. Hexspeak/1271.java new file mode 100644 index 00000000000..a28abd56320 --- /dev/null +++ b/solutions/1271. Hexspeak/1271.java @@ -0,0 +1,7 @@ +class Solution { + public String toHexspeak(String num) { + final long n = Long.parseLong(num); + final String ans = Long.toHexString(n).toUpperCase().replace('1', 'I').replace('0', 'O'); + return ans.chars().anyMatch(c -> Character.isDigit(c)) ? "ERROR" : ans; + } +} diff --git a/solutions/1271. Hexspeak/1271.py b/solutions/1271. Hexspeak/1271.py new file mode 100644 index 00000000000..c6b44c458b5 --- /dev/null +++ b/solutions/1271. Hexspeak/1271.py @@ -0,0 +1,4 @@ +class Solution: + def toHexspeak(self, num: str) -> str: + s = hex(int(num)).upper()[2:].translate(str.maketrans('01', 'OI')) + return 'ERROR' if any(c.isdigit() for c in s) else s diff --git a/solutions/1272. Remove Interval/1272.cpp b/solutions/1272. Remove Interval/1272.cpp new file mode 100644 index 00000000000..76750ea3c30 --- /dev/null +++ b/solutions/1272. Remove Interval/1272.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector> removeInterval(vector>& intervals, + vector& toBeRemoved) { + vector> ans; + + for (const vector& interval : intervals) { + const int a = interval[0]; + const int b = interval[1]; + if (a >= toBeRemoved[1] || b <= toBeRemoved[0]) { + ans.push_back(interval); + } else { // a < toBeRemoved[1] && b > toBeRemoved[0] + if (a < toBeRemoved[0]) + ans.push_back({a, toBeRemoved[0]}); + if (b > toBeRemoved[1]) + ans.push_back({toBeRemoved[1], b}); + } + } + + return ans; + } +}; diff --git a/solutions/1272. Remove Interval/1272.java b/solutions/1272. Remove Interval/1272.java new file mode 100644 index 00000000000..e95252a4598 --- /dev/null +++ b/solutions/1272. Remove Interval/1272.java @@ -0,0 +1,20 @@ +class Solution { + public List> removeInterval(int[][] intervals, int[] toBeRemoved) { + List> ans = new ArrayList<>(); + + for (int[] interval : intervals) { + final int a = interval[0]; + final int b = interval[1]; + if (a >= toBeRemoved[1] || b <= toBeRemoved[0]) { + ans.add(Arrays.asList(a, b)); + } else { // a < toBeRemoved[1] && b > toBeRemoved[0] + if (a < toBeRemoved[0]) + ans.add(Arrays.asList(a, toBeRemoved[0])); + if (b > toBeRemoved[1]) + ans.add(Arrays.asList(toBeRemoved[1], b)); + } + } + + return ans; + } +} diff --git a/solutions/1272. Remove Interval/1272.py b/solutions/1272. Remove Interval/1272.py new file mode 100644 index 00000000000..ccfea1f2d73 --- /dev/null +++ b/solutions/1272. Remove Interval/1272.py @@ -0,0 +1,14 @@ +class Solution: + def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: + ans = [] + + for a, b in intervals: + if a >= toBeRemoved[1] or b <= toBeRemoved[0]: + ans.append([a, b]) + else: # a < toBeRemoved[1] and b > toBeRemoved[0] + if a < toBeRemoved[0]: + ans.append([a, toBeRemoved[0]]) + if b > toBeRemoved[1]: + ans.append([toBeRemoved[1], b]) + + return ans diff --git a/solutions/1273. Delete Tree Nodes/1273.cpp b/solutions/1273. Delete Tree Nodes/1273.cpp new file mode 100644 index 00000000000..eb623893cbe --- /dev/null +++ b/solutions/1273. Delete Tree Nodes/1273.cpp @@ -0,0 +1,32 @@ +struct T { + int sum; + int count; +}; + +class Solution { + public: + int deleteTreeNodes(int nodes, vector& parent, vector& value) { + vector> tree(nodes); + + for (int i = 1; i < parent.size(); ++i) + tree[parent[i]].push_back(i); + + return dfs(tree, 0, value).count; + } + + private: + T dfs(const vector>& tree, int u, const vector& value) { + int sum = value[u]; // the root value + int count = 1; // this root + + for (const int v : tree[u]) { + const T t = dfs(tree, v, value); + sum += t.sum; + count += t.count; + } + + if (sum == 0) // Delete this root. + return {0, 0}; // So, its count = 0. + return {sum, count}; + } +}; diff --git a/solutions/1273. Delete Tree Nodes/1273.java b/solutions/1273. Delete Tree Nodes/1273.java new file mode 100644 index 00000000000..f358071ad93 --- /dev/null +++ b/solutions/1273. Delete Tree Nodes/1273.java @@ -0,0 +1,37 @@ +class T { + public int sum; + public int count; + public T(int sum, int count) { + this.sum = sum; + this.count = count; + } +} + +class Solution { + public int deleteTreeNodes(int nodes, int[] parent, int[] value) { + List[] tree = new List[nodes]; + + for (int i = 0; i < tree.length; ++i) + tree[i] = new ArrayList<>(); + + for (int i = 1; i < parent.length; ++i) + tree[parent[i]].add(i); + + return dfs(tree, 0, value).count; + } + + private T dfs(List[] tree, int u, int[] value) { + int sum = value[u]; // the root value + int count = 1; // this root + + for (final int v : tree[u]) { + final T t = dfs(tree, v, value); + sum += t.sum; + count += t.count; + } + + if (sum == 0) // Delete this root. + return new T(0, 0); // So, its count = 0. + return new T(sum, count); + } +} diff --git a/solutions/1274. Number of Ships in a Rectangle/1274.cpp b/solutions/1274. Number of Ships in a Rectangle/1274.cpp new file mode 100644 index 00000000000..8d115871015 --- /dev/null +++ b/solutions/1274. Number of Ships in a Rectangle/1274.cpp @@ -0,0 +1,35 @@ +/** + * // This is Sea's API interface. + * // You should not implement it, or speculate about its implementation + * class Sea { + * public: + * bool hasShips(vector topRight, vector bottomLeft); + * }; + */ + +class Solution { + public: + int countShips(Sea sea, vector topRight, vector bottomLeft) { + if (topRight[0] < bottomLeft[0] || topRight[1] < bottomLeft[1]) + return 0; + if (!sea.hasShips(topRight, bottomLeft)) + return 0; + + // sea.hashShips(topRight, bottomLeft) == true + if (topRight[0] == bottomLeft[0] && topRight[1] == bottomLeft[1]) + return 1; + + const int mx = (topRight[0] + bottomLeft[0]) / 2; + const int my = (topRight[1] + bottomLeft[1]) / 2; + int ans = 0; + // the top-right + ans += countShips(sea, topRight, {mx + 1, my + 1}); + // the bottom-right + ans += countShips(sea, {topRight[0], my}, {mx + 1, bottomLeft[1]}); + // the top-left + ans += countShips(sea, {mx, topRight[1]}, {bottomLeft[0], my + 1}); + // the bottom-left + ans += countShips(sea, {mx, my}, bottomLeft); + return ans; + } +}; diff --git a/solutions/1274. Number of Ships in a Rectangle/1274.java b/solutions/1274. Number of Ships in a Rectangle/1274.java new file mode 100644 index 00000000000..2450bd4f208 --- /dev/null +++ b/solutions/1274. Number of Ships in a Rectangle/1274.java @@ -0,0 +1,33 @@ +/** + * // This is Sea's API interface. + * // You should not implement it, or speculate about its implementation + * class Sea { + * public boolean hasShips(int[] topRight, int[] bottomLeft); + * } + */ + +class Solution { + public int countShips(Sea sea, int[] topRight, int[] bottomLeft) { + if (topRight[0] < bottomLeft[0] || topRight[1] < bottomLeft[1]) + return 0; + if (!sea.hasShips(topRight, bottomLeft)) + return 0; + + // sea.hashShips(topRight, bottomLeft) == true + if (topRight[0] == bottomLeft[0] && topRight[1] == bottomLeft[1]) + return 1; + + final int mx = (topRight[0] + bottomLeft[0]) / 2; + final int my = (topRight[1] + bottomLeft[1]) / 2; + int ans = 0; + // the top-right + ans += countShips(sea, topRight, new int[] {mx + 1, my + 1}); + // the bottom-right + ans += countShips(sea, new int[] {topRight[0], my}, new int[] {mx + 1, bottomLeft[1]}); + // the top-left + ans += countShips(sea, new int[] {mx, topRight[1]}, new int[] {bottomLeft[0], my + 1}); + // the bottom-left + ans += countShips(sea, new int[] {mx, my}, bottomLeft); + return ans; + } +} diff --git a/solutions/1274. Number of Ships in a Rectangle/1274.py b/solutions/1274. Number of Ships in a Rectangle/1274.py new file mode 100644 index 00000000000..5e5a2e082ca --- /dev/null +++ b/solutions/1274. Number of Ships in a Rectangle/1274.py @@ -0,0 +1,38 @@ +# """ +# This is Sea's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class Sea(object): +# def hasShips(self, topRight: 'Point', bottomLeft: 'Point') -> bool: +# pass +# +# class Point(object): +# def __init__(self, x: int, y: int): +# self.x = x +# self.y = y + +class Solution(object): + def countShips(self, sea: 'Sea', topRight: 'Point', bottomLeft: 'Point') -> int: + if topRight.x < bottomLeft.x or topRight.y < bottomLeft.y: + return 0 + if not sea.hasShips(topRight, bottomLeft): + return 0 + + # sea.hashShips(topRight, bottomLeft) == True + if topRight.x == bottomLeft.x and topRight.y == bottomLeft.y: + return 1 + + mx = (topRight.x + bottomLeft.x) // 2 + my = (topRight.y + bottomLeft.y) // 2 + ans = 0 + # the top-right + ans += self.countShips(sea, topRight, Point(mx + 1, my + 1)) + # the bottom-right + ans += self.countShips(sea, Point(topRight.x, my), + Point(mx + 1, bottomLeft.y)) + # the top-left + ans += self.countShips(sea, Point(mx, topRight.y), + Point(bottomLeft.x, my + 1)) + # the bottom-left + ans += self.countShips(sea, Point(mx, my), bottomLeft) + return ans diff --git a/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.cpp b/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.cpp new file mode 100644 index 00000000000..45a804eb294 --- /dev/null +++ b/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string tictactoe(vector>& moves) { + vector> row(2, vector(3)); + vector> col(2, vector(3)); + vector diag1(2); + vector diag2(2); + + for (int i = 0; i < moves.size(); ++i) { + const int r = moves[i][0]; + const int c = moves[i][1]; + const int j = i & 1; + if (++row[j][r] == 3 || ++col[j][c] == 3 || r == c && ++diag1[j] == 3 || + r + c == 2 && ++diag2[j] == 3) + return j == 0 ? "A" : "B"; + } + + return moves.size() == 9 ? "Draw" : "Pending"; + } +}; diff --git a/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.java b/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.java new file mode 100644 index 00000000000..c68a2308280 --- /dev/null +++ b/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.java @@ -0,0 +1,19 @@ +class Solution { + public String tictactoe(int[][] moves) { + int[][] row = new int[2][3]; + int[][] col = new int[2][3]; + int[] diag1 = new int[2]; + int[] diag2 = new int[2]; + + for (int i = 0; i < moves.length; ++i) { + final int r = moves[i][0]; + final int c = moves[i][1]; + final int j = i & 1; + if (++row[j][r] == 3 || ++col[j][c] == 3 || r == c && ++diag1[j] == 3 || + r + c == 2 && ++diag2[j] == 3) + return j == 0 ? "A" : "B"; + } + + return moves.length == 9 ? "Draw" : "Pending"; + } +} diff --git a/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.py b/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.py new file mode 100644 index 00000000000..77fc116d1c9 --- /dev/null +++ b/solutions/1275. Find Winner on a Tic Tac Toe Game/1275.py @@ -0,0 +1,18 @@ +class Solution: + def tictactoe(self, moves: List[List[int]]) -> str: + row = [[0] * 3 for _ in range(2)] + col = [[0] * 3 for _ in range(2)] + diag1 = [0] * 2 + diag2 = [0] * 2 + i = 0 + + for r, c in moves: + row[i][r] += 1 + col[i][c] += 1 + diag1[i] += r == c + diag2[i] += r + c == 2 + if 3 in (row[i][r], col[i][c], diag1[i], diag2[i]): + return 'A' if i == 0 else 'B' + i ^= 1 + + return 'Draw' if len(moves) == 9 else 'Pending' diff --git a/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.cpp b/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.cpp new file mode 100644 index 00000000000..180dd52030c --- /dev/null +++ b/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector numOfBurgers(int tomatoSlices, int cheeseSlices) { + if (tomatoSlices % 2 == 1 || tomatoSlices < 2 * cheeseSlices || + tomatoSlices > cheeseSlices * 4) + return {}; + + int jumboBurgers = (tomatoSlices - 2 * cheeseSlices) / 2; + + return {jumboBurgers, cheeseSlices - jumboBurgers}; + } +}; diff --git a/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.java b/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.java new file mode 100644 index 00000000000..178e6e1d3a6 --- /dev/null +++ b/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.java @@ -0,0 +1,10 @@ +class Solution { + public List numOfBurgers(int tomatoSlices, int cheeseSlices) { + if (tomatoSlices % 2 == 1 || tomatoSlices < 2 * cheeseSlices || tomatoSlices > cheeseSlices * 4) + return new ArrayList<>(); + + int jumboBurgers = (tomatoSlices - 2 * cheeseSlices) / 2; + + return new ArrayList<>(Arrays.asList(jumboBurgers, cheeseSlices - jumboBurgers)); + } +} diff --git a/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.py b/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.py new file mode 100644 index 00000000000..7dd4eebfba5 --- /dev/null +++ b/solutions/1276. Number of Burgers with No Waste of Ingredients/1276.py @@ -0,0 +1,8 @@ +class Solution: + def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: + if tomatoSlices % 2 == 1 or tomatoSlices < 2 * cheeseSlices or tomatoSlices > cheeseSlices * 4: + return [] + + jumboBurgers = (tomatoSlices - 2 * cheeseSlices) // 2 + + return [jumboBurgers, cheeseSlices - jumboBurgers] diff --git a/solutions/1277. Count Square Submatrices with All Ones/1277.cpp b/solutions/1277. Count Square Submatrices with All Ones/1277.cpp new file mode 100644 index 00000000000..c1a3548ba0b --- /dev/null +++ b/solutions/1277. Count Square Submatrices with All Ones/1277.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int countSquares(vector>& matrix) { + for (int i = 0; i < matrix.size(); ++i) + for (int j = 0; j < matrix[0].size(); ++j) + if (matrix[i][j] == 1 && i > 0 && j > 0) + matrix[i][j] += + min({matrix[i - 1][j - 1], matrix[i - 1][j], matrix[i][j - 1]}); + return accumulate(matrix.begin(), matrix.end(), 0, + [](int subtotal, const vector& row) { + return subtotal + accumulate(row.begin(), row.end(), 0); + }); + } +}; diff --git a/solutions/1277. Count Square Submatrices with All Ones/1277.java b/solutions/1277. Count Square Submatrices with All Ones/1277.java new file mode 100644 index 00000000000..95bd227b168 --- /dev/null +++ b/solutions/1277. Count Square Submatrices with All Ones/1277.java @@ -0,0 +1,10 @@ +class Solution { + public int countSquares(int[][] matrix) { + for (int i = 0; i < matrix.length; ++i) + for (int j = 0; j < matrix[0].length; ++j) + if (matrix[i][j] == 1 && i > 0 && j > 0) + matrix[i][j] += + Math.min(matrix[i - 1][j - 1], Math.min(matrix[i - 1][j], matrix[i][j - 1])); + return Arrays.stream(matrix).flatMapToInt(Arrays::stream).sum(); + } +} diff --git a/solutions/1277. Count Square Submatrices with All Ones/1277.py b/solutions/1277. Count Square Submatrices with All Ones/1277.py new file mode 100644 index 00000000000..ad3def85c53 --- /dev/null +++ b/solutions/1277. Count Square Submatrices with All Ones/1277.py @@ -0,0 +1,8 @@ +class Solution: + def countSquares(self, matrix: List[List[int]]) -> int: + for i in range(len(matrix)): + for j in range(len(matrix[0])): + if matrix[i][j] == 1 and i > 0 and j > 0: + matrix[i][j] += min(matrix[i - 1][j - 1], + matrix[i - 1][j], matrix[i][j - 1]) + return sum(map(sum, matrix)) diff --git a/solutions/1278. Palindrome Partitioning III/1278-2.cpp b/solutions/1278. Palindrome Partitioning III/1278-2.cpp new file mode 100644 index 00000000000..bcfef67f2f3 --- /dev/null +++ b/solutions/1278. Palindrome Partitioning III/1278-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int palindromePartition(string s, int K) { + const int n = s.length(); + // dp[i][k] := the minimum cost to make k palindromes by s[0..i) + vector> dp(n + 1, vector(K + 1, n)); + // cost[i][j] := the minimum cost to make s[i..j] palindrome + vector> cost(n, vector(n)); + + for (int d = 1; d < n; ++d) + for (int i = 0, j = d; j < n; ++i, ++j) + cost[i][j] = (s[i] != s[j]) + cost[i + 1][j - 1]; + + for (int i = 1; i <= n; ++i) + dp[i][1] = cost[0][i - 1]; + + for (int k = 2; k <= K; ++k) + for (int i = k; i <= n; ++i) + for (int j = k - 1; j < i; ++j) + dp[i][k] = min(dp[i][k], dp[j][k - 1] + cost[j][i - 1]); + + return dp[n][K]; + } +}; diff --git a/solutions/1278. Palindrome Partitioning III/1278-2.java b/solutions/1278. Palindrome Partitioning III/1278-2.java new file mode 100644 index 00000000000..e6ed35bcfa8 --- /dev/null +++ b/solutions/1278. Palindrome Partitioning III/1278-2.java @@ -0,0 +1,24 @@ +class Solution { + public int palindromePartition(String s, int K) { + final int n = s.length(); + // dp[i][k] := the minimum cost to make k palindromes by s[0..i) + int[][] dp = new int[n + 1][K + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, n)); + // cost[i][j] := the minimum cost to make s[i..j] palindrome + int[][] cost = new int[n][n]; + + for (int d = 1; d < n; ++d) + for (int i = 0, j = d; j < n; ++i, ++j) + cost[i][j] = (s.charAt(i) == s.charAt(j) ? 0 : 1) + cost[i + 1][j - 1]; + + for (int i = 1; i <= n; ++i) + dp[i][1] = cost[0][i - 1]; + + for (int k = 2; k <= K; ++k) + for (int i = k; i <= n; ++i) + for (int j = k - 1; j < i; ++j) + dp[i][k] = Math.min(dp[i][k], dp[j][k - 1] + cost[j][i - 1]); + + return dp[n][K]; + } +} diff --git a/solutions/1278. Palindrome Partitioning III/1278.cpp b/solutions/1278. Palindrome Partitioning III/1278.cpp new file mode 100644 index 00000000000..65464d80c4f --- /dev/null +++ b/solutions/1278. Palindrome Partitioning III/1278.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int palindromePartition(string s, int k) { + const int n = s.length(); + vector> mem(n + 1, vector(k + 1, n)); + // cost[i][j] := the minimum cost to make s[i..j] palindrome + vector> cost(n, vector(n)); + + for (int d = 1; d < n; ++d) + for (int i = 0, j = d; j < n; ++i, ++j) + cost[i][j] = (s[i] != s[j]) + cost[i + 1][j - 1]; + + return palindromePartition(n, k, cost, mem); + } + + private: + // Returns the minimum cost to make k palindromes by s[0..i). + int palindromePartition(int n, int k, const vector>& cost, + vector>& mem) { + if (k == 1) + return cost[0][n - 1]; + if (mem[n][k] < n) + return mem[n][k]; + + // Try all the possible partitions. + for (int i = k - 1; i < n; ++i) + mem[n][k] = min( + mem[n][k], palindromePartition(i, k - 1, cost, mem) + cost[i][n - 1]); + + return mem[n][k]; + } +}; diff --git a/solutions/1278. Palindrome Partitioning III/1278.java b/solutions/1278. Palindrome Partitioning III/1278.java new file mode 100644 index 00000000000..919a0c25b8f --- /dev/null +++ b/solutions/1278. Palindrome Partitioning III/1278.java @@ -0,0 +1,31 @@ +class Solution { + public int palindromePartition(String s, int k) { + final int n = s.length(); + int[][] mem = new int[n + 1][k + 1]; + // cost[i][j] := the minimum cost to make s[i..j] palindrome + int[][] cost = new int[n][n]; + + Arrays.stream(mem).forEach(A -> Arrays.fill(A, n)); + + for (int d = 1; d < n; ++d) + for (int i = 0, j = d; j < n; ++i, ++j) + cost[i][j] = (s.charAt(i) == s.charAt(j) ? 0 : 1) + cost[i + 1][j - 1]; + + return palindromePartition(n, k, cost, mem); + } + + // Returns the minimum cost to make k palindromes by s[0..i). + private int palindromePartition(int n, int k, int[][] cost, int[][] mem) { + if (k == 1) + return cost[0][n - 1]; + if (mem[n][k] < n) + return mem[n][k]; + + // Try all the possible partitions. + for (int i = k - 1; i < n; ++i) + mem[n][k] = Math.min(mem[n][k], // + palindromePartition(i, k - 1, cost, mem) + cost[i][n - 1]); + + return mem[n][k]; + } +} diff --git a/solutions/1279. Traffic Light Controlled Intersection/1279.cpp b/solutions/1279. Traffic Light Controlled Intersection/1279.cpp new file mode 100644 index 00000000000..559be6e8dd3 --- /dev/null +++ b/solutions/1279. Traffic Light Controlled Intersection/1279.cpp @@ -0,0 +1,27 @@ +class TrafficLight { + public: + void carArrived( + // ID of the car + int carId, + // ID of the road the car travels on. Can be 1 (road A) or 2 (road B). + int roadId, + // direction of the car + int direction, + // Use turnGreen() to turn light to green on current road. + function turnGreen, + // Use crossCar() to make car cross the intersection. + function crossCar + + ) { + std::lock_guard lock(mutex); + if (canPassRoadId != roadId) { + canPassRoadId = roadId; + turnGreen(); + } + crossCar(); + } + + private: + int canPassRoadId = 1; // 1 := road A, 2 := road B + std::mutex mutex; +}; diff --git a/solutions/1279. Traffic Light Controlled Intersection/1279.java b/solutions/1279. Traffic Light Controlled Intersection/1279.java new file mode 100644 index 00000000000..222bcd632cb --- /dev/null +++ b/solutions/1279. Traffic Light Controlled Intersection/1279.java @@ -0,0 +1,23 @@ +class TrafficLight { + public void carArrived( + // ID of the car + int carId, + // ID of the road the car travels on. Can be 1 (road A) or 2 (road B). + int roadId, + // direction of the car + int direction, + // Use turnGreen() to turn light to green on current road. + Runnable turnGreen, + // Use crossCar() to make car cross the intersection. + Runnable crossCar) { + synchronized (this) { + if (canPassRoadId != roadId) { + canPassRoadId = roadId; + turnGreen.run(); + } + crossCar.run(); + } + } + + private int canPassRoadId = 1; // 1 := road A, 2 := road B +} diff --git a/solutions/1279. Traffic Light Controlled Intersection/1279.py b/solutions/1279. Traffic Light Controlled Intersection/1279.py new file mode 100644 index 00000000000..66891357c1e --- /dev/null +++ b/solutions/1279. Traffic Light Controlled Intersection/1279.py @@ -0,0 +1,21 @@ +class TrafficLight: + def __init__(self): + self.canPassRoadId = 1 # 1 := road A, 2 := road B + + def carArrived( + self, + # ID of the car + carId: int, + # ID of the road the car travels on. Can be 1 (road A) or 2 (road B). + roadId: int, + # direction of the car + direction: int, + # Use turnGreen() to turn light to green on current road. + turnGreen: Callable[[], None], + # Use crossCar() to make car cross the intersection. + crossCar: Callable[[], None] + ) -> None: + if roadId != self.canPassRoadId: + self.canPassRoadId = roadId + turnGreen() + crossCar() diff --git a/solutions/128. Longest Consecutive Sequence/128.cpp b/solutions/128. Longest Consecutive Sequence/128.cpp new file mode 100644 index 00000000000..685d23e87c9 --- /dev/null +++ b/solutions/128. Longest Consecutive Sequence/128.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int longestConsecutive(vector& nums) { + int ans = 0; + unordered_set seen{nums.begin(), nums.end()}; + + for (int num : nums) { + // `num` is the start of a sequence. + if (seen.contains(num - 1)) + continue; + int length = 1; + while (seen.contains(++num)) + ++length; + ans = max(ans, length); + } + + return ans; + } +}; diff --git a/solutions/128. Longest Consecutive Sequence/128.java b/solutions/128. Longest Consecutive Sequence/128.java new file mode 100644 index 00000000000..adab6407d4c --- /dev/null +++ b/solutions/128. Longest Consecutive Sequence/128.java @@ -0,0 +1,18 @@ +class Solution { + public int longestConsecutive(int[] nums) { + int ans = 0; + Set seen = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + + for (int num : nums) { + // `num` is the start of a sequence. + if (seen.contains(num - 1)) + continue; + int length = 1; + while (seen.contains(++num)) + ++length; + ans = Math.max(ans, length); + } + + return ans; + } +} diff --git a/solutions/128. Longest Consecutive Sequence/128.py b/solutions/128. Longest Consecutive Sequence/128.py new file mode 100644 index 00000000000..80a134a966b --- /dev/null +++ b/solutions/128. Longest Consecutive Sequence/128.py @@ -0,0 +1,16 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + ans = 0 + seen = set(nums) + + for num in nums: + # `num` is the start of a sequence. + if num - 1 in seen: + continue + length = 0 + while num in seen: + num += 1 + length += 1 + ans = max(ans, length) + + return ans diff --git a/solutions/1280. Students and Examinations/1280.sql b/solutions/1280. Students and Examinations/1280.sql new file mode 100644 index 00000000000..e6df5aac787 --- /dev/null +++ b/solutions/1280. Students and Examinations/1280.sql @@ -0,0 +1,13 @@ +SELECT + Students.student_id, + Students.student_name, + Subjects.subject_name, + COUNT(Examinations.student_id) AS attended_exams +FROM Students +CROSS JOIN Subjects +LEFT JOIN Examinations + ON ( + Students.student_id = Examinations.student_id + AND Subjects.subject_name = Examinations.subject_name) +GROUP BY 1, 2, 3 +ORDER BY Students.student_id, Subjects.subject_name; diff --git a/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.cpp b/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.cpp new file mode 100644 index 00000000000..c435fe8780b --- /dev/null +++ b/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int subtractProductAndSum(int n) { + int prod = 1; + int summ = 0; + + for (; n > 0; n /= 10) { + prod *= n % 10; + summ += n % 10; + } + + return prod - summ; + } +}; diff --git a/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.java b/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.java new file mode 100644 index 00000000000..71006714872 --- /dev/null +++ b/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.java @@ -0,0 +1,13 @@ +class Solution { + public int subtractProductAndSum(int n) { + int prod = 1; + int summ = 0; + + for (; n > 0; n /= 10) { + prod *= n % 10; + summ += n % 10; + } + + return prod - summ; + } +} diff --git a/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.py b/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.py new file mode 100644 index 00000000000..abeecf5a4d1 --- /dev/null +++ b/solutions/1281. Subtract the Product and Sum of Digits of an Integer/1281.py @@ -0,0 +1,11 @@ +class Solution: + def subtractProductAndSum(self, n: int) -> int: + prod = 1 + summ = 0 + + while n > 0: + prod *= n % 10 + summ += n % 10 + n //= 10 + + return prod - summ diff --git a/solutions/1282. Group the People Given the Group Size They Belong To/1282.cpp b/solutions/1282. Group the People Given the Group Size They Belong To/1282.cpp new file mode 100644 index 00000000000..7b86db05e1f --- /dev/null +++ b/solutions/1282. Group the People Given the Group Size They Belong To/1282.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector> groupThePeople(vector& groupSizes) { + vector> ans; + unordered_map> groupSizeToIndices; + + for (int i = 0; i < groupSizes.size(); ++i) + groupSizeToIndices[groupSizes[i]].push_back(i); + + for (const auto& [groupSize, indices] : groupSizeToIndices) { + vector groupIndices; + for (const int index : indices) { + groupIndices.push_back(index); + if (groupIndices.size() == groupSize) { + ans.push_back(groupIndices); + groupIndices.clear(); + } + } + } + + return ans; + } +}; diff --git a/solutions/1282. Group the People Given the Group Size They Belong To/1282.java b/solutions/1282. Group the People Given the Group Size They Belong To/1282.java new file mode 100644 index 00000000000..ce1fd1108a1 --- /dev/null +++ b/solutions/1282. Group the People Given the Group Size They Belong To/1282.java @@ -0,0 +1,27 @@ +class Solution { + public List> groupThePeople(int[] groupSizes) { + List> ans = new ArrayList<>(); + Map> groupSizeToIndices = new HashMap<>(); + + for (int i = 0; i < groupSizes.length; ++i) { + final int groupSize = groupSizes[i]; + groupSizeToIndices.putIfAbsent(groupSize, new ArrayList<>()); + groupSizeToIndices.get(groupSize).add(i); + } + + for (Map.Entry> entry : groupSizeToIndices.entrySet()) { + final int groupSize = entry.getKey(); + List indices = entry.getValue(); + List groupIndices = new ArrayList<>(); + for (final int index : indices) { + groupIndices.add(index); + if (groupIndices.size() == groupSize) { + ans.add(new ArrayList<>(groupIndices)); + groupIndices.clear(); + } + } + } + + return ans; + } +} diff --git a/solutions/1282. Group the People Given the Group Size They Belong To/1282.py b/solutions/1282. Group the People Given the Group Size They Belong To/1282.py new file mode 100644 index 00000000000..a4e6b24a068 --- /dev/null +++ b/solutions/1282. Group the People Given the Group Size They Belong To/1282.py @@ -0,0 +1,17 @@ +class Solution: + def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: + ans = [] + groupSizeToIndices = defaultdict(list) + + for i, groupSize in enumerate(groupSizes): + groupSizeToIndices[groupSize].append(i) + + for groupSize, indices in groupSizeToIndices.items(): + groupIndices = [] + for index in indices: + groupIndices.append(index) + if len(groupIndices) == groupSize: + ans.append(groupIndices.copy()) + groupIndices.clear() + + return ans diff --git a/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.cpp b/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.cpp new file mode 100644 index 00000000000..82be4e05ad5 --- /dev/null +++ b/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int smallestDivisor(vector& nums, int threshold) { + int l = 1; + int r = ranges::max(nums); + + while (l < r) { + const int m = (l + r) / 2; + if (sumDivision(nums, m) <= threshold) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int sumDivision(const vector& nums, int m) { + int sum = 0; + for (const int num : nums) + sum += (num - 1) / m + 1; + return sum; + } +}; diff --git a/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.java b/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.java new file mode 100644 index 00000000000..ea1c1316a4e --- /dev/null +++ b/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.java @@ -0,0 +1,23 @@ +class Solution { + public int smallestDivisor(int[] nums, int threshold) { + int l = 1; + int r = Arrays.stream(nums).max().getAsInt(); + + while (l < r) { + final int m = (l + r) / 2; + if (sumDivision(nums, m) <= threshold) + r = m; + else + l = m + 1; + } + + return l; + } + + private int sumDivision(int[] nums, int m) { + int sum = 0; + for (final int num : nums) + sum += (num - 1) / m + 1; + return sum; + } +} diff --git a/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.py b/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.py new file mode 100644 index 00000000000..5ecb96b25cc --- /dev/null +++ b/solutions/1283. Find the Smallest Divisor Given a Threshold/1283.py @@ -0,0 +1,13 @@ +class Solution: + def smallestDivisor(self, nums: List[int], threshold: int) -> int: + l = 1 + r = max(nums) + + while l < r: + m = (l + r) // 2 + if sum((num - 1) // m + 1 for num in nums) <= threshold: + r = m + else: + l = m + 1 + + return l diff --git a/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.cpp b/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.cpp new file mode 100644 index 00000000000..44d781c44b5 --- /dev/null +++ b/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int minFlips(vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + const int hash = getHash(mat, m, n); + if (hash == 0) + return 0; + + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + queue q{{hash}}; + unordered_set seen{hash}; + + for (int step = 1; !q.empty(); ++step) { + for (int sz = q.size(); sz > 0; --sz) { + const int curr = q.front(); + q.pop(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int next = curr ^ 1 << (i * n + j); + // Flie the four neighbors. + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + next ^= 1 << (x * n + y); + } + if (next == 0) + return step; + if (seen.contains(next)) + continue; + q.push(next); + seen.insert(next); + } + } + } + } + + return -1; + } + + private: + int getHash(const vector>& mat, int m, int n) { + int hash = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j]) + hash |= 1 << (i * n + j); + return hash; + } +}; diff --git a/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.java b/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.java new file mode 100644 index 00000000000..fcdd8025835 --- /dev/null +++ b/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.java @@ -0,0 +1,49 @@ +class Solution { + public int minFlips(int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + final int hash = getHash(mat, m, n); + if (hash == 0) + return 0; + + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + Queue q = new ArrayDeque<>(Arrays.asList(hash)); + Set seen = new HashSet<>(Arrays.asList(hash)); + + for (int step = 1; !q.isEmpty(); ++step) { + for (int sz = q.size(); sz > 0; --sz) { + final int curr = q.poll(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int next = curr ^ 1 << (i * n + j); + // Flie the four neighbors. + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + next ^= 1 << (x * n + y); + } + if (next == 0) + return step; + if (seen.contains(next)) + continue; + q.offer(next); + seen.add(next); + } + } + } + } + + return -1; + } + + private int getHash(int[][] mat, int m, int n) { + int hash = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 1) + hash |= 1 << (i * n + j); + return hash; + } +} diff --git a/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.py b/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.py new file mode 100644 index 00000000000..cb87c273227 --- /dev/null +++ b/solutions/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284.py @@ -0,0 +1,43 @@ +class Solution: + def minFlips(self, mat: List[List[int]]) -> int: + m = len(mat) + n = len(mat[0]) + hash = self._getHash(mat, m, n) + if hash == 0: + return 0 + + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + step = 0 + q = collections.deque([hash]) + seen = {hash} + + while q: + step += 1 + for _ in range(len(q)): + curr = q.popleft() + for i in range(m): + for j in range(n): + next = curr ^ 1 << (i * n + j) + # Flie the four neighbors. + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + next ^= 1 << (x * n + y) + if next == 0: + return step + if next in seen: + continue + q.append(next) + seen.add(next) + + return -1 + + def _getHash(self, mat: List[List[int]], m: int, n: int) -> int: + hash = 0 + for i in range(m): + for j in range(n): + if mat[i][j]: + hash |= 1 << (i * n + j) + return hash diff --git a/solutions/1285. Find the Start and End Number of Continuous Ranges/1285.sql b/solutions/1285. Find the Start and End Number of Continuous Ranges/1285.sql new file mode 100644 index 00000000000..fb525408c7d --- /dev/null +++ b/solutions/1285. Find the Start and End Number of Continuous Ranges/1285.sql @@ -0,0 +1,12 @@ +WITH + LogToRowNumber AS ( + SELECT + log_id, + ROW_NUMBER() OVER(ORDER BY log_id) AS `row_number` + FROM Logs + ) +SELECT + MIN(log_id) AS start_id, + MAX(log_id) AS end_id +FROM LogToRowNumber +GROUP BY log_id - `row_number`; diff --git a/solutions/1286. Iterator for Combination/1286.java b/solutions/1286. Iterator for Combination/1286.java new file mode 100644 index 00000000000..2a619d11add --- /dev/null +++ b/solutions/1286. Iterator for Combination/1286.java @@ -0,0 +1,33 @@ +class CombinationIterator { + public CombinationIterator(String characters, int combinationLength) { + final int n = characters.length(); + final int k = combinationLength; + + // Generate bitmasks from 0..00 to 1..11 + for (int mask = 0; mask < 1 << n; mask++) { + // Use bitmasks with k 1-bits + if (Integer.bitCount(mask) == k) { + // Convert bitmask into combination + // 111 --> "abc", 000 --> "" + // 110 --> "ab", 101 --> "ac", 011 --> "bc" + StringBuilder curr = new StringBuilder(); + for (int j = 0; j < n; j++) { + if ((mask & (1 << n - j - 1)) != 0) { + curr.append(characters.charAt(j)); + } + } + combinations.push(curr.toString()); + } + } + } + + public String next() { + return combinations.pop(); + } + + public boolean hasNext() { + return (!combinations.isEmpty()); + } + + private Deque combinations = new ArrayDeque(); +} diff --git a/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.cpp b/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.cpp new file mode 100644 index 00000000000..7e6dcd6f8e7 --- /dev/null +++ b/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int findSpecialInteger(vector& arr) { + const int n = arr.size(); + const int quarter = n / 4; + + for (int i = 0; i < n - quarter; ++i) + if (arr[i] == arr[i + quarter]) + return arr[i]; + + throw; + } +}; diff --git a/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.java b/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.java new file mode 100644 index 00000000000..c12bfd0fe01 --- /dev/null +++ b/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.java @@ -0,0 +1,12 @@ +class Solution { + public int findSpecialInteger(int[] arr) { + final int n = arr.length; + final int quarter = n / 4; + + for (int i = 0; i < n - quarter; ++i) + if (arr[i] == arr[i + quarter]) + return arr[i]; + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.py b/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.py new file mode 100644 index 00000000000..aa5426a25a1 --- /dev/null +++ b/solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.py @@ -0,0 +1,8 @@ +class Solution: + def findSpecialInteger(self, arr: List[int]) -> int: + n = len(arr) + quarter = n // 4 + + for i in range(n - quarter): + if arr[i] == arr[i + quarter]: + return arr[i] diff --git a/solutions/1288. Remove Covered Intervals/1288.cpp b/solutions/1288. Remove Covered Intervals/1288.cpp new file mode 100644 index 00000000000..cd415b154a5 --- /dev/null +++ b/solutions/1288. Remove Covered Intervals/1288.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int removeCoveredIntervals(vector>& intervals) { + // If the two intervals have the same `start`, put the one with a larger + // `end` first. + ranges::sort(intervals, [](const vector& a, const vector& b) { + return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; + }); + + int ans = 0; + int prevEnd = 0; + + for (const vector& interval : intervals) + // Current interval is not covered by the previous one. + if (prevEnd < interval[1]) { + ++ans; + prevEnd = interval[1]; + } + + return ans; + } +}; diff --git a/solutions/1288. Remove Covered Intervals/1288.java b/solutions/1288. Remove Covered Intervals/1288.java new file mode 100644 index 00000000000..cca03079606 --- /dev/null +++ b/solutions/1288. Remove Covered Intervals/1288.java @@ -0,0 +1,19 @@ +class Solution { + public int removeCoveredIntervals(int[][] intervals) { + // If the two intervals have the same `start`, put the one with a larger + // `end` first. + Arrays.sort(intervals, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + + int ans = 0; + int prevEnd = 0; + + for (int[] interval : intervals) + // Current interval is not covered by the previous one. + if (prevEnd < interval[1]) { + ++ans; + prevEnd = interval[1]; + } + + return ans; + } +} diff --git a/solutions/1288. Remove Covered Intervals/1288.py b/solutions/1288. Remove Covered Intervals/1288.py new file mode 100644 index 00000000000..b14fa5e1357 --- /dev/null +++ b/solutions/1288. Remove Covered Intervals/1288.py @@ -0,0 +1,14 @@ +class Solution: + def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: + ans = 0 + prevEnd = 0 + + # If the two intervals have the same `start`, put the one with a larger + # `end` first. + for _, end in sorted(intervals, key=lambda x: (x[0], -x[1])): + # Current interval is not covered by the previous one. + if prevEnd < end: + ans += 1 + prevEnd = end + + return ans diff --git a/solutions/1289. Minimum Falling Path Sum II/1289.cpp b/solutions/1289. Minimum Falling Path Sum II/1289.cpp new file mode 100644 index 00000000000..1bb9f257126 --- /dev/null +++ b/solutions/1289. Minimum Falling Path Sum II/1289.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int minFallingPathSum(vector>& grid) { + const int n = grid.size(); + + for (int i = 1; i < n; ++i) { + const vector> twoMinNumAndIndexs = + getTwoMinNumAndIndexs(grid[i - 1]); + const auto& [firstMinNum, firstMinIndex] = twoMinNumAndIndexs[0]; + const auto& [secondMinNum, _] = twoMinNumAndIndexs[1]; + for (int j = 0; j < n; ++j) + if (j == firstMinIndex) + grid[i][j] += secondMinNum; + else + grid[i][j] += firstMinNum; + } + + return ranges::min(grid.back()); + } + + private: + vector> getTwoMinNumAndIndexs(const vector& A) { + vector> numAndIndexs; + + for (int i = 0; i < A.size(); ++i) + numAndIndexs.emplace_back(A[i], i); + + ranges::sort(numAndIndexs); + return {numAndIndexs[0], numAndIndexs[1]}; + } +}; diff --git a/solutions/1289. Minimum Falling Path Sum II/1289.java b/solutions/1289. Minimum Falling Path Sum II/1289.java new file mode 100644 index 00000000000..3e08a13847e --- /dev/null +++ b/solutions/1289. Minimum Falling Path Sum II/1289.java @@ -0,0 +1,29 @@ +class Solution { + public int minFallingPathSum(int[][] grid) { + final int n = grid.length; + + for (int i = 1; i < n; ++i) { + Pair[] twoMinnumAndIndexes = getTwoMinnumAndIndexes(grid[i - 1]); + final int firstMinNum = twoMinnumAndIndexes[0].getKey(); + final int firstMinIndex = twoMinnumAndIndexes[0].getValue(); + final int secondMinNum = twoMinnumAndIndexes[1].getKey(); + for (int j = 0; j < n; ++j) + if (j == firstMinIndex) + grid[i][j] += secondMinNum; + else + grid[i][j] += firstMinNum; + } + + return Arrays.stream(grid[n - 1]).min().getAsInt(); + } + + private Pair[] getTwoMinnumAndIndexes(int[] A) { + List> numAndIndexes = new ArrayList<>(); + + for (int i = 0; i < A.length; ++i) + numAndIndexes.add(new Pair<>(A[i], i)); + + Collections.sort(numAndIndexes, (a, b) -> a.getKey() - b.getKey()); + return new Pair[] {numAndIndexes.get(0), numAndIndexes.get(1)}; + } +} diff --git a/solutions/1289. Minimum Falling Path Sum II/1289.py b/solutions/1289. Minimum Falling Path Sum II/1289.py new file mode 100644 index 00000000000..14ddc6d883c --- /dev/null +++ b/solutions/1289. Minimum Falling Path Sum II/1289.py @@ -0,0 +1,14 @@ +class Solution: + def minFallingPathSum(self, grid: List[List[int]]) -> int: + n = len(grid) + + for i in range(1, n): + (firstMinNum, firstMinIndex), (secondMinNum, _) = sorted( + {(a, i) for i, a in enumerate(grid[i - 1])})[:2] + for j in range(n): + if j == firstMinIndex: + grid[i][j] += secondMinNum + else: + grid[i][j] += firstMinNum + + return min(grid[-1]) diff --git a/solutions/129. Sum Root to Leaf Numbers/129.cpp b/solutions/129. Sum Root to Leaf Numbers/129.cpp new file mode 100644 index 00000000000..9ce432f843c --- /dev/null +++ b/solutions/129. Sum Root to Leaf Numbers/129.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int sumNumbers(TreeNode* root) { + int ans = 0; + dfs(root, 0, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int path, int& ans) { + if (root == nullptr) + return; + if (root->left == nullptr && root->right == nullptr) { + ans += path * 10 + root->val; + return; + } + + dfs(root->left, path * 10 + root->val, ans); + dfs(root->right, path * 10 + root->val, ans); + } +}; diff --git a/solutions/129. Sum Root to Leaf Numbers/129.java b/solutions/129. Sum Root to Leaf Numbers/129.java new file mode 100644 index 00000000000..f3e5ecbfbbf --- /dev/null +++ b/solutions/129. Sum Root to Leaf Numbers/129.java @@ -0,0 +1,20 @@ +class Solution { + public int sumNumbers(TreeNode root) { + dfs(root, 0); + return ans; + } + + private int ans = 0; + + private void dfs(TreeNode root, int path) { + if (root == null) + return; + if (root.left == null && root.right == null) { + ans += path * 10 + root.val; + return; + } + + dfs(root.left, path * 10 + root.val); + dfs(root.right, path * 10 + root.val); + } +} diff --git a/solutions/129. Sum Root to Leaf Numbers/129.py b/solutions/129. Sum Root to Leaf Numbers/129.py new file mode 100644 index 00000000000..8f55027c42b --- /dev/null +++ b/solutions/129. Sum Root to Leaf Numbers/129.py @@ -0,0 +1,17 @@ +class Solution: + def sumNumbers(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def dfs(root: Optional[TreeNode], path: int) -> None: + nonlocal ans + if not root: + return + if not root.left and not root.right: + ans += path * 10 + root.val + return + + dfs(root.left, path * 10 + root.val) + dfs(root.right, path * 10 + root.val) + + dfs(root, 0) + return ans diff --git a/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.cpp b/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.cpp new file mode 100644 index 00000000000..27deba76135 --- /dev/null +++ b/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int getDecimalValue(ListNode* head) { + int ans = 0; + + for (; head; head = head->next) + ans = ans * 2 + head->val; + + return ans; + } +}; diff --git a/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.java b/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.java new file mode 100644 index 00000000000..3dcff2d7eca --- /dev/null +++ b/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.java @@ -0,0 +1,10 @@ +class Solution { + public int getDecimalValue(ListNode head) { + int ans = 0; + + for (; head != null; head = head.next) + ans = ans * 2 + head.val; + + return ans; + } +} diff --git a/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.py b/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.py new file mode 100644 index 00000000000..7a1a857cbda --- /dev/null +++ b/solutions/1290. Convert Binary Number in a Linked List to Integer/1290.py @@ -0,0 +1,9 @@ +class Solution: + def getDecimalValue(self, head: ListNode) -> int: + ans = 0 + + while head: + ans = ans * 2 + head.val + head = head.next + + return ans diff --git a/solutions/1291. Sequential Digits/1291.cpp b/solutions/1291. Sequential Digits/1291.cpp new file mode 100644 index 00000000000..3c3137461ff --- /dev/null +++ b/solutions/1291. Sequential Digits/1291.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector sequentialDigits(int low, int high) { + vector ans; + queue q{{1, 2, 3, 4, 5, 6, 7, 8, 9}}; + + while (!q.empty()) { + const int num = q.front(); + q.pop(); + if (num > high) + return ans; + if (low <= num && num <= high) + ans.push_back(num); + const int lastDigit = num % 10; + if (lastDigit < 9) + q.push(num * 10 + lastDigit + 1); + } + + return ans; + } +}; diff --git a/solutions/1291. Sequential Digits/1291.java b/solutions/1291. Sequential Digits/1291.java new file mode 100644 index 00000000000..eac3f00828b --- /dev/null +++ b/solutions/1291. Sequential Digits/1291.java @@ -0,0 +1,19 @@ +class Solution { + public List sequentialDigits(int low, int high) { + List ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); + + while (!q.isEmpty()) { + final int num = q.poll(); + if (num > high) + return ans; + if (low <= num && num <= high) + ans.add(num); + final int lastDigit = num % 10; + if (lastDigit < 9) + q.offer(num * 10 + lastDigit + 1); + } + + return ans; + } +} diff --git a/solutions/1291. Sequential Digits/1291.py b/solutions/1291. Sequential Digits/1291.py new file mode 100644 index 00000000000..7622d3bd3e9 --- /dev/null +++ b/solutions/1291. Sequential Digits/1291.py @@ -0,0 +1,16 @@ +class Solution: + def sequentialDigits(self, low: int, high: int) -> List[int]: + ans = [] + q = collections.deque([num for num in range(1, 10)]) + + while q: + num = q.popleft() + if num > high: + return ans + if low <= num and num <= high: + ans.append(num) + lastDigit = num % 10 + if lastDigit < 9: + q.append(num * 10 + lastDigit + 1) + + return ans diff --git a/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.cpp b/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.cpp new file mode 100644 index 00000000000..38151e9661d --- /dev/null +++ b/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maxSideLength(vector>& mat, int threshold) { + const int m = mat.size(); + const int n = mat[0].size(); + int ans = 0; + vector> prefix(m + 1, vector(n + 1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + prefix[i + 1][j + 1] = + mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int length = ans; length < min(m - i, n - j); ++length) { + if (squareSum(prefix, i, j, i + length, j + length) > threshold) + break; + ans = max(ans, length + 1); + } + + return ans; + } + + private: + int squareSum(vector>& prefix, int r1, int c1, int r2, int c2) { + return prefix[r2 + 1][c2 + 1] - prefix[r1][c2 + 1] - prefix[r2 + 1][c1] + + prefix[r1][c1]; + } +}; diff --git a/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.java b/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.java new file mode 100644 index 00000000000..80054dea25e --- /dev/null +++ b/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.java @@ -0,0 +1,26 @@ +class Solution { + public int maxSideLength(int[][] mat, int threshold) { + final int m = mat.length; + final int n = mat[0].length; + int ans = 0; + int[][] prefix = new int[m + 1][n + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + prefix[i + 1][j + 1] = mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int length = ans; length < Math.min(m - i, n - j); ++length) { + if (squareSum(prefix, i, j, i + length, j + length) > threshold) + break; + ans = Math.max(ans, length + 1); + } + + return ans; + } + + private int squareSum(int[][] prefix, int r1, int c1, int r2, int c2) { + return prefix[r2 + 1][c2 + 1] - prefix[r1][c2 + 1] - prefix[r2 + 1][c1] + prefix[r1][c1]; + } +} diff --git a/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.py b/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.py new file mode 100644 index 00000000000..228c6ce09a7 --- /dev/null +++ b/solutions/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292.py @@ -0,0 +1,23 @@ +class Solution: + def maxSideLength(self, mat: List[List[int]], threshold: int) -> int: + m = len(mat) + n = len(mat[0]) + ans = 0 + prefix = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(m): + for j in range(n): + prefix[i + 1][j + 1] = mat[i][j] + prefix[i][j + 1] + \ + prefix[i + 1][j] - prefix[i][j] + + def squareSum(r1: int, c1: int, r2: int, c2: int) -> int: + return prefix[r2 + 1][c2 + 1] - prefix[r1][c2 + 1] - prefix[r2 + 1][c1] + prefix[r1][c1] + + for i in range(m): + for j in range(n): + for length in range(ans, min(m - i, n - j)): + if squareSum(i, j, i + length, j + length) > threshold: + break + ans = max(ans, length + 1) + + return ans diff --git a/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.cpp b/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.cpp new file mode 100644 index 00000000000..1cb0ec7f2e0 --- /dev/null +++ b/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int shortestPath(vector>& grid, int k) { + const int m = grid.size(); + const int n = grid[0].size(); + if (m == 1 && n == 1) + return 0; + + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int steps = 0; + queue> q{{{0, 0, k}}}; // (i, j, eliminate) + vector>> seen( + m, vector>(n, vector(k + 1))); + seen[0][0][k] = true; + + while (!q.empty()) { + ++steps; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j, eliminate] = q.front(); + q.pop(); + for (int l = 0; l < 4; ++l) { + const int x = i + dirs[l]; + const int y = j + dirs[l + 1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (x == m - 1 && y == n - 1) + return steps; + if (grid[x][y] == 1 && eliminate == 0) + continue; + const int newEliminate = eliminate - grid[x][y]; + if (seen[x][y][newEliminate]) + continue; + q.emplace(x, y, newEliminate); + seen[x][y][newEliminate] = true; + } + } + } + + return -1; + } +}; diff --git a/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.java b/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.java new file mode 100644 index 00000000000..c196c97af7b --- /dev/null +++ b/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.java @@ -0,0 +1,52 @@ +class T { + public int i; + public int j; + public int eliminate; + public T(int i, int j, int eliminate) { + this.i = i; + this.j = j; + this.eliminate = eliminate; + } +} + +class Solution { + public int shortestPath(int[][] grid, int k) { + final int m = grid.length; + final int n = grid[0].length; + if (m == 1 && n == 1) + return 0; + + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int steps = 0; + Queue q = new ArrayDeque<>(); + q.offer(new T(0, 0, k)); + boolean[][][] seen = new boolean[m][n][k + 1]; + seen[0][0][k] = true; + + while (!q.isEmpty()) { + ++steps; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().i; + final int j = q.peek().j; + final int eliminate = q.poll().eliminate; + for (int l = 0; l < 4; ++l) { + final int x = i + dirs[l]; + final int y = j + dirs[l + 1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (x == m - 1 && y == n - 1) + return steps; + if (grid[x][y] == 1 && eliminate == 0) + continue; + final int newEliminate = eliminate - grid[x][y]; + if (seen[x][y][newEliminate]) + continue; + q.offer(new T(x, y, newEliminate)); + seen[x][y][newEliminate] = true; + } + } + } + + return -1; + } +} diff --git a/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.py b/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.py new file mode 100644 index 00000000000..62826d1c4c8 --- /dev/null +++ b/solutions/1293. Shortest Path in a Grid with Obstacles Elimination/1293.py @@ -0,0 +1,32 @@ +class Solution: + def shortestPath(self, grid: List[List[int]], k: int) -> int: + m = len(grid) + n = len(grid[0]) + if m == 1 and n == 1: + return 0 + + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + steps = 0 + q = collections.deque([(0, 0, k)]) + seen = {(0, 0, k)} + + while q: + steps += 1 + for _ in range(len(q)): + i, j, eliminate = q.popleft() + for l in range(4): + x = i + dirs[l] + y = j + dirs[l + 1] + if x < 0 or x == m or y < 0 or y == n: + continue + if x == m - 1 and y == n - 1: + return steps + if grid[x][y] == 1 and eliminate == 0: + continue + newEliminate = eliminate - grid[x][y] + if (x, y, newEliminate) in seen: + continue + q.append((x, y, newEliminate)) + seen.add((x, y, newEliminate)) + + return -1 diff --git a/solutions/1294. Weather Type in Each Country/1294.sql b/solutions/1294. Weather Type in Each Country/1294.sql new file mode 100644 index 00000000000..b522427b473 --- /dev/null +++ b/solutions/1294. Weather Type in Each Country/1294.sql @@ -0,0 +1,14 @@ +SELECT + country_name, + ( + CASE + WHEN AVG(Weather.weather_state * 1.0) <= 15.0 THEN 'Cold' + WHEN AVG(Weather.weather_state * 1.0) >= 25.0 THEN 'Hot' + ELSE 'Warm' + END + ) AS weather_type +FROM Countries +INNER JOIN Weather + USING (country_id) +WHERE day BETWEEN '2019-11-01' AND '2019-11-30' +GROUP BY 1; diff --git a/solutions/1295. Find Numbers with Even Number of Digits/1295.cpp b/solutions/1295. Find Numbers with Even Number of Digits/1295.cpp new file mode 100644 index 00000000000..59e48b85e26 --- /dev/null +++ b/solutions/1295. Find Numbers with Even Number of Digits/1295.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int findNumbers(vector& nums) { + int ans = 0; + + for (int num : nums) + if (9 < num && num < 100 || 999 < num && num < 10000 || num == 100000) + ++ans; + + return ans; + } +}; diff --git a/solutions/1295. Find Numbers with Even Number of Digits/1295.java b/solutions/1295. Find Numbers with Even Number of Digits/1295.java new file mode 100644 index 00000000000..168cfc64e46 --- /dev/null +++ b/solutions/1295. Find Numbers with Even Number of Digits/1295.java @@ -0,0 +1,11 @@ +class Solution { + public int findNumbers(int[] nums) { + int ans = 0; + + for (int num : nums) + if (9 < num && num < 100 || 999 < num && num < 10000 || num == 100000) + ++ans; + + return ans; + } +} diff --git a/solutions/1295. Find Numbers with Even Number of Digits/1295.py b/solutions/1295. Find Numbers with Even Number of Digits/1295.py new file mode 100644 index 00000000000..428cc7f7b74 --- /dev/null +++ b/solutions/1295. Find Numbers with Even Number of Digits/1295.py @@ -0,0 +1,9 @@ +class Solution: + def findNumbers(self, nums: List[int]) -> int: + ans = 0 + + for num in nums: + if 9 < num < 100 or 999 < num < 10000 or num == 100000: + ans += 1 + + return ans diff --git a/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.cpp b/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.cpp new file mode 100644 index 00000000000..a3c17038de4 --- /dev/null +++ b/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool isPossibleDivide(vector& nums, int k) { + map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [start, _] : count) { + const int value = count[start]; + if (value > 0) + for (int i = start; i < start + k; ++i) { + count[i] -= value; + if (count[i] < 0) + return false; + } + } + + return true; + } +}; diff --git a/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.java b/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.java new file mode 100644 index 00000000000..5c03e6e1df0 --- /dev/null +++ b/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isPossibleDivide(int[] nums, int k) { + TreeMap count = new TreeMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int start : count.keySet()) { + final int value = count.getOrDefault(start, 0); + if (value > 0) + for (int i = start; i < start + k; ++i) + if (count.merge(i, -value, Integer::sum) < 0) + return false; + } + + return true; + } +} diff --git a/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.py b/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.py new file mode 100644 index 00000000000..6f7c3991600 --- /dev/null +++ b/solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.py @@ -0,0 +1,13 @@ +class Solution: + def isPossibleDivide(self, nums: List[int], k: int) -> bool: + count = collections.Counter(nums) + + for start in sorted(count): + value = count[start] + if value > 0: + for i in range(start, start + k): + count[i] -= value + if count[i] < 0: + return False + + return True diff --git a/solutions/1297. Maximum Number of Occurrences of a Substring/1297.cpp b/solutions/1297. Maximum Number of Occurrences of a Substring/1297.cpp new file mode 100644 index 00000000000..810effd497c --- /dev/null +++ b/solutions/1297. Maximum Number of Occurrences of a Substring/1297.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maxFreq(string s, int maxLetters, int minSize, int maxSize) { + // Greedily consider strings with `minSize`, so ignore `maxSize`. + int ans = 0; + int letters = 0; + vector count(26); + unordered_map substringCount; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s[r] - 'a'] == 1) + ++letters; + while (letters > maxLetters || r - l + 1 > minSize) + if (--count[s[l++] - 'a'] == 0) + --letters; + if (r - l + 1 == minSize) + ans = max(ans, ++substringCount[s.substr(l, minSize)]); + } + + return ans; + } +}; diff --git a/solutions/1297. Maximum Number of Occurrences of a Substring/1297.java b/solutions/1297. Maximum Number of Occurrences of a Substring/1297.java new file mode 100644 index 00000000000..72d17382d12 --- /dev/null +++ b/solutions/1297. Maximum Number of Occurrences of a Substring/1297.java @@ -0,0 +1,21 @@ +class Solution { + public int maxFreq(String s, int maxLetters, int minSize, int maxSize) { + // Greedily consider strings with `minSize`, so ignore `maxSize`. + int ans = 0; + int letters = 0; + int[] count = new int[26]; + Map substringCount = new HashMap<>(); + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s.charAt(r) - 'a'] == 1) + ++letters; + while (letters > maxLetters || r - l + 1 > minSize) + if (--count[s.charAt(l++) - 'a'] == 0) + --letters; + if (r - l + 1 == minSize) + ans = Math.max(ans, substringCount.merge(s.substring(l, l + minSize), 1, Integer::sum)); + } + + return ans; + } +} diff --git a/solutions/1297. Maximum Number of Occurrences of a Substring/1297.py b/solutions/1297. Maximum Number of Occurrences of a Substring/1297.py new file mode 100644 index 00000000000..b918de269be --- /dev/null +++ b/solutions/1297. Maximum Number of Occurrences of a Substring/1297.py @@ -0,0 +1,24 @@ +class Solution: + def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: + # Greedily consider strings with `minSize`, so ignore `maxSize`. + ans = 0 + letters = 0 + count = collections.Counter() + substringCount = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + if count[c] == 1: + letters += 1 + while letters > maxLetters or r - l + 1 > minSize: + count[s[l]] -= 1 + if count[s[l]] == 0: + letters -= 1 + l += 1 + if r - l + 1 == minSize: + sub = s[l:l + minSize] + substringCount[sub] += 1 + ans = max(ans, substringCount[sub]) + + return ans diff --git a/solutions/1298. Maximum Candies You Can Get from Boxes/1298.cpp b/solutions/1298. Maximum Candies You Can Get from Boxes/1298.cpp new file mode 100644 index 00000000000..3fcceb2e83a --- /dev/null +++ b/solutions/1298. Maximum Candies You Can Get from Boxes/1298.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int maxCandies(vector& status, vector& candies, + vector>& keys, vector>& containedBoxes, + vector& initialBoxes) { + int ans = 0; + queue q; + vector reachedClosedBoxes(status.size()); + + auto pushBoxesIfPossible = [&status, &q, + &reachedClosedBoxes](const vector& boxes) { + for (const int box : boxes) + if (status[box]) + q.push(box); + else + reachedClosedBoxes[box] = true; + }; + + pushBoxesIfPossible(initialBoxes); + + while (!q.empty()) { + const int currBox = q.front(); + q.pop(); + + // Add the candies. + ans += candies[currBox]; + + // Push `reachedClosedBoxes` by `key` obtained in this turn and change + // their statuses. + for (const int key : keys[currBox]) { + if (!status[key] && reachedClosedBoxes[key]) + q.push(key); + status[key] = 1; // boxes[key] is now open. + } + + // Push the boxes contained in `currBox`. + pushBoxesIfPossible(containedBoxes[currBox]); + } + + return ans; + } +}; diff --git a/solutions/1298. Maximum Candies You Can Get from Boxes/1298.java b/solutions/1298. Maximum Candies You Can Get from Boxes/1298.java new file mode 100644 index 00000000000..8f30ecaad8b --- /dev/null +++ b/solutions/1298. Maximum Candies You Can Get from Boxes/1298.java @@ -0,0 +1,39 @@ +class Solution { + public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, + int[] initialBoxes) { + int ans = 0; + Queue q = new ArrayDeque<>(); + boolean[] reachedClosedBoxes = new boolean[status.length]; + + pushBoxesIfPossible(initialBoxes, status, q, reachedClosedBoxes); + + while (!q.isEmpty()) { + final int currBox = q.poll(); + + // Add the candies. + ans += candies[currBox]; + + // Push `reachedClosedBoxes` by `key` obtained in this turn and change + // their statuses. + for (final int key : keys[currBox]) { + if (status[key] == 0 && reachedClosedBoxes[key]) + q.offer(key); + status[key] = 1; // boxes[key] is now open. + } + + // Push the boxes contained in `currBox`. + pushBoxesIfPossible(containedBoxes[currBox], status, q, reachedClosedBoxes); + } + + return ans; + } + + private void pushBoxesIfPossible(int[] boxes, int[] status, Queue q, + boolean[] reachedClosedBoxes) { + for (final int box : boxes) + if (status[box] == 1) + q.offer(box); + else + reachedClosedBoxes[box] = true; + } +} diff --git a/solutions/1298. Maximum Candies You Can Get from Boxes/1298.py b/solutions/1298. Maximum Candies You Can Get from Boxes/1298.py new file mode 100644 index 00000000000..593a1e3def5 --- /dev/null +++ b/solutions/1298. Maximum Candies You Can Get from Boxes/1298.py @@ -0,0 +1,32 @@ +class Solution: + def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int: + ans = 0 + q = collections.deque() + reachedClosedBoxes = [0] * len(status) + + def pushBoxesIfPossible(boxes: List[int]) -> None: + for box in boxes: + if status[box]: + q.append(box) + else: + reachedClosedBoxes[box] = True + + pushBoxesIfPossible(initialBoxes) + + while q: + currBox = q.popleft() + + # Add the candies. + ans += candies[currBox] + + # Push `reachedClosedBoxes` by `key` obtained in this turn and change + # their statuses. + for key in keys[currBox]: + if not status[key] and reachedClosedBoxes[key]: + q.append(key) + status[key] = 1 # boxes[key] is now open + + # Push the boxes contained in `currBox`. + pushBoxesIfPossible(containedBoxes[currBox]) + + return ans diff --git a/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.cpp b/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.cpp new file mode 100644 index 00000000000..84335181744 --- /dev/null +++ b/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + vector replaceElements(vector& arr) { + int maxOfRight = -1; + for (int i = arr.size() - 1; i >= 0; --i) + maxOfRight = max(maxOfRight, exchange(arr[i], maxOfRight)); + return arr; + } +}; diff --git a/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.java b/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.java new file mode 100644 index 00000000000..4f658affb09 --- /dev/null +++ b/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.java @@ -0,0 +1,11 @@ +class Solution { + public int[] replaceElements(int[] arr) { + int maxOfRight = -1; + for (int i = arr.length - 1; i >= 0; --i) { + int a = arr[i]; + arr[i] = maxOfRight; + maxOfRight = Math.max(maxOfRight, a); + } + return arr; + } +} diff --git a/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.py b/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.py new file mode 100644 index 00000000000..e3e035dad76 --- /dev/null +++ b/solutions/1299. Replace Elements with Greatest Element on Right Side/1299.py @@ -0,0 +1,6 @@ +class Solution: + def replaceElements(self, arr: List[int]) -> List[int]: + maxOfRight = -1 + for i in reversed(range(len(arr))): + arr[i], maxOfRight = maxOfRight, max(maxOfRight, arr[i]) + return arr diff --git a/solutions/13. Roman to Integer/13.cpp b/solutions/13. Roman to Integer/13.cpp new file mode 100644 index 00000000000..8f8e0239698 --- /dev/null +++ b/solutions/13. Roman to Integer/13.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int romanToInt(string s) { + int ans = 0; + vector roman(128); + + roman['I'] = 1; + roman['V'] = 5; + roman['X'] = 10; + roman['L'] = 50; + roman['C'] = 100; + roman['D'] = 500; + roman['M'] = 1000; + + for (int i = 0; i + 1 < s.length(); ++i) + if (roman[s[i]] < roman[s[i + 1]]) + ans -= roman[s[i]]; + else + ans += roman[s[i]]; + + return ans + roman[s.back()]; + } +}; diff --git a/solutions/13. Roman to Integer/13.java b/solutions/13. Roman to Integer/13.java new file mode 100644 index 00000000000..5c0306bc196 --- /dev/null +++ b/solutions/13. Roman to Integer/13.java @@ -0,0 +1,22 @@ +class Solution { + public int romanToInt(String s) { + int ans = 0; + int[] roman = new int[128]; + + roman['I'] = 1; + roman['V'] = 5; + roman['X'] = 10; + roman['L'] = 50; + roman['C'] = 100; + roman['D'] = 500; + roman['M'] = 1000; + + for (int i = 0; i + 1 < s.length(); ++i) + if (roman[s.charAt(i)] < roman[s.charAt(i + 1)]) + ans -= roman[s.charAt(i)]; + else + ans += roman[s.charAt(i)]; + + return ans + roman[s.charAt(s.length() - 1)]; + } +} diff --git a/solutions/13. Roman to Integer/13.py b/solutions/13. Roman to Integer/13.py new file mode 100644 index 00000000000..7a086adbeae --- /dev/null +++ b/solutions/13. Roman to Integer/13.py @@ -0,0 +1,13 @@ +class Solution: + def romanToInt(self, s: str) -> int: + ans = 0 + roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, + 'C': 100, 'D': 500, 'M': 1000} + + for a, b in zip(s, s[1:]): + if roman[a] < roman[b]: + ans -= roman[a] + else: + ans += roman[a] + + return ans + roman[s[-1]] diff --git a/solutions/130. Surrounded Regions/130-2.cpp b/solutions/130. Surrounded Regions/130-2.cpp new file mode 100644 index 00000000000..3014bceb9b0 --- /dev/null +++ b/solutions/130. Surrounded Regions/130-2.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + void solve(vector>& board) { + if (board.empty()) + return; + + const int m = board.size(); + const int n = board[0].size(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + dfs(board, i, j); + + for (vector& row : board) + for (char& c : row) + if (c == '*') + c = 'O'; + else if (c == 'O') + c = 'X'; + } + + private: + // Marks the grids with 'O' that stretch from the four sides to '*'. + void dfs(vector>& board, int i, int j) { + if (i < 0 || i == board.size() || j < 0 || j == board[0].size()) + return; + if (board[i][j] != 'O') + return; + board[i][j] = '*'; + dfs(board, i + 1, j); + dfs(board, i - 1, j); + dfs(board, i, j + 1); + dfs(board, i, j - 1); + } +}; diff --git a/solutions/130. Surrounded Regions/130-2.java b/solutions/130. Surrounded Regions/130-2.java new file mode 100644 index 00000000000..11f9e2b577b --- /dev/null +++ b/solutions/130. Surrounded Regions/130-2.java @@ -0,0 +1,34 @@ +class Solution { + public void solve(char[][] board) { + if (board.length == 0) + return; + + final int m = board.length; + final int n = board[0].length; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + dfs(board, i, j); + + for (char[] row : board) + for (int i = 0; i < row.length; ++i) + if (row[i] == '*') + row[i] = 'O'; + else if (row[i] == 'O') + row[i] = 'X'; + } + + // Marks the grids with 'O' that stretch from the four sides to '*'. + private void dfs(char[][] board, int i, int j) { + if (i < 0 || i == board.length || j < 0 || j == board[0].length) + return; + if (board[i][j] != 'O') + return; + board[i][j] = '*'; + dfs(board, i + 1, j); + dfs(board, i - 1, j); + dfs(board, i, j + 1); + dfs(board, i, j - 1); + } +} diff --git a/solutions/130. Surrounded Regions/130-2.py b/solutions/130. Surrounded Regions/130-2.py new file mode 100644 index 00000000000..1ffde074cc9 --- /dev/null +++ b/solutions/130. Surrounded Regions/130-2.py @@ -0,0 +1,28 @@ +class Solution: + def solve(self, board: List[List[str]]) -> None: + if not board: + return + + m = len(board) + n = len(board[0]) + + def dfs(i: int, j: int) -> None: + """Marks the grids with 'O' that stretch from the four sides to '*'.""" + if i < 0 or i == m or j < 0 or j == n: + return + if board[i][j] != 'O': + return + board[i][j] = '*' + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1) + + for i in range(m): + for j in range(n): + if i * j == 0 or i == m - 1 or j == n - 1: + dfs(i, j) + + for row in board: + for i, c in enumerate(row): + row[i] = 'O' if c == '*' else 'X' diff --git a/solutions/130. Surrounded Regions/130.cpp b/solutions/130. Surrounded Regions/130.cpp new file mode 100644 index 00000000000..a655e8053b9 --- /dev/null +++ b/solutions/130. Surrounded Regions/130.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + void solve(vector>& board) { + if (board.empty()) + return; + + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = board.size(); + const int n = board[0].size(); + + queue> q; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + if (board[i][j] == 'O') { + q.emplace(i, j); + board[i][j] = '*'; + } + + // Mark the grids that stretch from the four sides with '*'. + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (board[x][y] != 'O') + continue; + q.emplace(x, y); + board[x][y] = '*'; + } + } + + for (vector& row : board) + for (char& c : row) + if (c == '*') + c = 'O'; + else if (c == 'O') + c = 'X'; + } +}; diff --git a/solutions/130. Surrounded Regions/130.java b/solutions/130. Surrounded Regions/130.java new file mode 100644 index 00000000000..e38e64a753f --- /dev/null +++ b/solutions/130. Surrounded Regions/130.java @@ -0,0 +1,42 @@ +class Solution { + public void solve(char[][] board) { + if (board.length == 0) + return; + + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = board.length; + final int n = board[0].length; + Queue q = new ArrayDeque<>(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i * j == 0 || i == m - 1 || j == n - 1) + if (board[i][j] == 'O') { + q.offer(new int[] {i, j}); + board[i][j] = '*'; + } + + // Mark the grids that stretch from the four sides with '*'. + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (board[x][y] != 'O') + continue; + q.offer(new int[] {x, y}); + board[x][y] = '*'; + } + } + + for (char[] row : board) + for (int i = 0; i < row.length; ++i) + if (row[i] == '*') + row[i] = 'O'; + else if (row[i] == 'O') + row[i] = 'X'; + } +} diff --git a/solutions/130. Surrounded Regions/130.py b/solutions/130. Surrounded Regions/130.py new file mode 100644 index 00000000000..152bf860089 --- /dev/null +++ b/solutions/130. Surrounded Regions/130.py @@ -0,0 +1,33 @@ +class Solution: + def solve(self, board: List[List[str]]) -> None: + if not board: + return + + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(board) + n = len(board[0]) + q = collections.deque() + + for i in range(m): + for j in range(n): + if i * j == 0 or i == m - 1 or j == n - 1: + if board[i][j] == 'O': + q.append((i, j)) + board[i][j] = '*' + + # Mark the grids that stretch from the four sides with '*'. + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if board[x][y] != 'O': + continue + q.append((x, y)) + board[x][y] = '*' + + for row in board: + for i, c in enumerate(row): + row[i] = 'O' if c == '*' else 'X' diff --git a/solutions/1300. Sum of Mutated Array Closest to Target/1300.cpp b/solutions/1300. Sum of Mutated Array Closest to Target/1300.cpp new file mode 100644 index 00000000000..6790edbb06d --- /dev/null +++ b/solutions/1300. Sum of Mutated Array Closest to Target/1300.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int findBestValue(vector& arr, int target) { + const int n = arr.size(); + const double err = 1e-9; + + int prefix = 0; + + ranges::sort(arr); + + for (int i = 0; i < n; ++i) { + int ans = round((target - prefix - err) / (double)(n - i)); + if (ans <= arr[i]) + return ans; + prefix += arr[i]; + } + + return arr.back(); + } +}; diff --git a/solutions/1300. Sum of Mutated Array Closest to Target/1300.java b/solutions/1300. Sum of Mutated Array Closest to Target/1300.java new file mode 100644 index 00000000000..fbcba03e28b --- /dev/null +++ b/solutions/1300. Sum of Mutated Array Closest to Target/1300.java @@ -0,0 +1,19 @@ +class Solution { + public int findBestValue(int[] arr, int target) { + final int n = arr.length; + final double err = 1e-9; + + int prefix = 0; + + Arrays.sort(arr); + + for (int i = 0; i < n; ++i) { + int ans = (int) Math.round(((float) target - prefix - err) / (n - i)); + if (ans <= arr[i]) + return ans; + prefix += arr[i]; + } + + return arr[n - 1]; + } +} diff --git a/solutions/1300. Sum of Mutated Array Closest to Target/1300.py b/solutions/1300. Sum of Mutated Array Closest to Target/1300.py new file mode 100644 index 00000000000..0b2fc40439e --- /dev/null +++ b/solutions/1300. Sum of Mutated Array Closest to Target/1300.py @@ -0,0 +1,13 @@ +class Solution: + def findBestValue(self, arr: List[int], target: int) -> int: + prefix = 0 + + arr.sort() + + for i, a in enumerate(arr): + ans = round((target - prefix) / (len(arr) - i)) + if ans <= a: + return ans + prefix += a + + return arr[-1] diff --git a/solutions/1301. Number of Paths with Max Score/1301.cpp b/solutions/1301. Number of Paths with Max Score/1301.cpp new file mode 100644 index 00000000000..c4067625c0b --- /dev/null +++ b/solutions/1301. Number of Paths with Max Score/1301.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + vector pathsWithMaxScore(vector& board) { + constexpr int kMod = 1'000'000'007; + const int n = board.size(); + const vector> dirs{{0, 1}, {1, 0}, {1, 1}}; + // dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j) + vector> dp(n + 1, vector(n + 1, -1)); + // count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to + // (i, j) + vector> count(n + 1, vector(n + 1)); + + dp[0][0] = 0; + dp[n - 1][n - 1] = 0; + count[n - 1][n - 1] = 1; + + for (int i = n - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) { + if (board[i][j] == 'S' || board[i][j] == 'X') + continue; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (dp[i][j] < dp[x][y]) { + dp[i][j] = dp[x][y]; + count[i][j] = count[x][y]; + } else if (dp[i][j] == dp[x][y]) { + count[i][j] += count[x][y]; + count[i][j] %= kMod; + } + } + // If there's path(s) from 'S' to (i, j) and the cell is not 'E'. + if (dp[i][j] != -1 && board[i][j] != 'E') { + dp[i][j] += board[i][j] - '0'; + dp[i][j] %= kMod; + } + } + + return {dp[0][0], count[0][0]}; + } +}; diff --git a/solutions/1301. Number of Paths with Max Score/1301.java b/solutions/1301. Number of Paths with Max Score/1301.java new file mode 100644 index 00000000000..1c05ff56e10 --- /dev/null +++ b/solutions/1301. Number of Paths with Max Score/1301.java @@ -0,0 +1,40 @@ +class Solution { + public int[] pathsWithMaxScore(List board) { + final int kMod = 1_000_000_007; + final int n = board.size(); + final int[][] dirs = {{0, 1}, {1, 0}, {1, 1}}; + // dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j) + int[][] dp = new int[n + 1][n + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, -1)); + // count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to (i, j) + int[][] count = new int[n + 1][n + 1]; + + dp[0][0] = 0; + dp[n - 1][n - 1] = 0; + count[n - 1][n - 1] = 1; + + for (int i = n - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) { + if (board.get(i).charAt(j) == 'S' || board.get(i).charAt(j) == 'X') + continue; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (dp[i][j] < dp[x][y]) { + dp[i][j] = dp[x][y]; + count[i][j] = count[x][y]; + } else if (dp[i][j] == dp[x][y]) { + count[i][j] += count[x][y]; + count[i][j] %= kMod; + } + } + // If there's path(s) from 'S' to (i, j) and the cell is not 'E'. + if (dp[i][j] != -1 && board.get(i).charAt(j) != 'E') { + dp[i][j] += board.get(i).charAt(j) - '0'; + dp[i][j] %= kMod; + } + } + + return new int[] {dp[0][0], count[0][0]}; + } +} diff --git a/solutions/1301. Number of Paths with Max Score/1301.py b/solutions/1301. Number of Paths with Max Score/1301.py new file mode 100644 index 00000000000..5ae3cc6fe0e --- /dev/null +++ b/solutions/1301. Number of Paths with Max Score/1301.py @@ -0,0 +1,35 @@ +class Solution: + def pathsWithMaxScore(self, board: List[str]) -> List[int]: + kMod = 1_000_000_007 + n = len(board) + dirs = ((0, 1), (1, 0), (1, 1)) + # dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j) + dp = [[-1] * (n + 1) for _ in range(n + 1)] + # count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to + # (i, j) + count = [[0] * (n + 1) for _ in range(n + 1)] + + dp[0][0] = 0 + dp[n - 1][n - 1] = 0 + count[n - 1][n - 1] = 1 + + for i in reversed(range(n)): + for j in reversed(range(n)): + if board[i][j] == 'S' or board[i][j] == 'X': + continue + for dx, dy in dirs: + x = i + dx + y = j + dy + if dp[i][j] < dp[x][y]: + dp[i][j] = dp[x][y] + count[i][j] = count[x][y] + elif dp[i][j] == dp[x][y]: + count[i][j] += count[x][y] + count[i][j] %= kMod + + # If there's path(s) from 'S' to (i, j) and the cell is not 'E'. + if dp[i][j] != -1 and board[i][j] != 'E': + dp[i][j] += int(board[i][j]) + dp[i][j] %= kMod + + return [dp[0][0], count[0][0]] diff --git a/solutions/1302. Deepest Leaves Sum/1302.cpp b/solutions/1302. Deepest Leaves Sum/1302.cpp new file mode 100644 index 00000000000..1e75afb981d --- /dev/null +++ b/solutions/1302. Deepest Leaves Sum/1302.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int deepestLeavesSum(TreeNode* root) { + int ans = 0; + queue q{{root}}; + + while (!q.empty()) { + ans = 0; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + ans += node->val; + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + } + + return ans; + } +}; diff --git a/solutions/1302. Deepest Leaves Sum/1302.java b/solutions/1302. Deepest Leaves Sum/1302.java new file mode 100644 index 00000000000..263b945764f --- /dev/null +++ b/solutions/1302. Deepest Leaves Sum/1302.java @@ -0,0 +1,20 @@ +class Solution { + public int deepestLeavesSum(TreeNode root) { + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + ans = 0; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + ans += node.val; + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + } + + return ans; + } +} diff --git a/solutions/1303. Find the Team Size/1303.sql b/solutions/1303. Find the Team Size/1303.sql new file mode 100644 index 00000000000..5737a859eac --- /dev/null +++ b/solutions/1303. Find the Team Size/1303.sql @@ -0,0 +1,4 @@ +SELECT + employee_id, + COUNT(*) OVER(PARTITION BY team_id) AS team_size +FROM Employee; diff --git a/solutions/1304. Find N Unique Integers Sum up to Zero/1304.cpp b/solutions/1304. Find N Unique Integers Sum up to Zero/1304.cpp new file mode 100644 index 00000000000..855bc505701 --- /dev/null +++ b/solutions/1304. Find N Unique Integers Sum up to Zero/1304.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector sumZero(int n) { + vector ans(n); + + for (int i = 0; i < n; ++i) + ans[i] = i * 2 - n + 1; + + return ans; + } +}; diff --git a/solutions/1304. Find N Unique Integers Sum up to Zero/1304.java b/solutions/1304. Find N Unique Integers Sum up to Zero/1304.java new file mode 100644 index 00000000000..82c06ad451f --- /dev/null +++ b/solutions/1304. Find N Unique Integers Sum up to Zero/1304.java @@ -0,0 +1,10 @@ +class Solution { + public int[] sumZero(int n) { + int[] ans = new int[n]; + + for (int i = 0; i < n; ++i) + ans[i] = i * 2 - n + 1; + + return ans; + } +} diff --git a/solutions/1304. Find N Unique Integers Sum up to Zero/1304.py b/solutions/1304. Find N Unique Integers Sum up to Zero/1304.py new file mode 100644 index 00000000000..38cd1c38d79 --- /dev/null +++ b/solutions/1304. Find N Unique Integers Sum up to Zero/1304.py @@ -0,0 +1,3 @@ +class Solution: + def sumZero(self, n: int) -> List[int]: + return list(range(1 - n, n, 2)) diff --git a/solutions/1305. All Elements in Two Binary Search Trees/1305.cpp b/solutions/1305. All Elements in Two Binary Search Trees/1305.cpp new file mode 100644 index 00000000000..6456efbc71a --- /dev/null +++ b/solutions/1305. All Elements in Two Binary Search Trees/1305.cpp @@ -0,0 +1,60 @@ +class BSTIterator { + public: + BSTIterator(TreeNode* root) { + pushLeftsUntilNull(root); + } + + int peek() { + return stack.top()->val; + } + + void next() { + TreeNode* node = stack.top(); + stack.pop(); + pushLeftsUntilNull(node->right); + } + + bool hasNext() { + return !stack.empty(); + } + + private: + stack stack; + + void pushLeftsUntilNull(TreeNode* node) { + while (node) { + stack.push(node); + node = node->left; + } + } +}; + +class Solution { + public: + vector getAllElements(TreeNode* root1, TreeNode* root2) { + vector ans; + BSTIterator bstIterator1(root1); + BSTIterator bstIterator2(root2); + + while (bstIterator1.hasNext() && bstIterator2.hasNext()) + if (bstIterator1.peek() < bstIterator2.peek()) { + ans.push_back(bstIterator1.peek()); + bstIterator1.next(); + } else { + ans.push_back(bstIterator2.peek()); + bstIterator2.next(); + } + + while (bstIterator1.hasNext()) { + ans.push_back(bstIterator1.peek()); + bstIterator1.next(); + } + + while (bstIterator2.hasNext()) { + ans.push_back(bstIterator2.peek()); + bstIterator2.next(); + } + + return ans; + } +}; diff --git a/solutions/1305. All Elements in Two Binary Search Trees/1305.java b/solutions/1305. All Elements in Two Binary Search Trees/1305.java new file mode 100644 index 00000000000..d6ced94b1c4 --- /dev/null +++ b/solutions/1305. All Elements in Two Binary Search Trees/1305.java @@ -0,0 +1,55 @@ +class BSTIterator { + public BSTIterator(TreeNode root) { + pushLeftsUntilNull(root); + } + + public int peek() { + return stack.peek().val; + } + + public void next() { + pushLeftsUntilNull(stack.pop().right); + } + + public boolean hasNext() { + return !stack.isEmpty(); + } + + private Deque stack = new ArrayDeque<>(); + + private void pushLeftsUntilNull(TreeNode node) { + while (node != null) { + stack.push(node); + node = node.left; + } + } +} + +class Solution { + public List getAllElements(TreeNode root1, TreeNode root2) { + List ans = new ArrayList<>(); + BSTIterator bstIterator1 = new BSTIterator(root1); + BSTIterator bstIterator2 = new BSTIterator(root2); + + while (bstIterator1.hasNext() && bstIterator2.hasNext()) + if (bstIterator1.peek() < bstIterator2.peek()) { + ans.add(bstIterator1.peek()); + bstIterator1.next(); + } else { + ans.add(bstIterator2.peek()); + bstIterator2.next(); + } + + while (bstIterator1.hasNext()) { + ans.add(bstIterator1.peek()); + bstIterator1.next(); + } + + while (bstIterator2.hasNext()) { + ans.add(bstIterator2.peek()); + bstIterator2.next(); + } + + return ans; + } +} diff --git a/solutions/1306. Jump Game III/1306-2.cpp b/solutions/1306. Jump Game III/1306-2.cpp new file mode 100644 index 00000000000..65e3159ee04 --- /dev/null +++ b/solutions/1306. Jump Game III/1306-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool canReach(vector& arr, int start) { + return canReach(arr, start, vector(arr.size())); + } + + private: + bool canReach(const vector& A, int node, vector&& seen) { + if (node < 0 || node >= A.size()) + return false; + if (seen[node]) + return false; + if (A[node] == 0) + return true; + + seen[node] = true; + return canReach(A, node + A[node], move(seen)) || + canReach(A, node - A[node], move(seen)); + } +}; diff --git a/solutions/1306. Jump Game III/1306-2.java b/solutions/1306. Jump Game III/1306-2.java new file mode 100644 index 00000000000..db7fbdc75f1 --- /dev/null +++ b/solutions/1306. Jump Game III/1306-2.java @@ -0,0 +1,17 @@ +class Solution { + public boolean canReach(int[] arr, int start) { + return canReach(arr, start, new boolean[arr.length]); + } + + private boolean canReach(int[] A, int node, boolean[] seen) { + if (node < 0 || node >= A.length) + return false; + if (seen[node]) + return false; + if (A[node] == 0) + return true; + + seen[node] = true; + return canReach(A, node + A[node], seen) || canReach(A, node - A[node], seen); + } +} diff --git a/solutions/1306. Jump Game III/1306.cpp b/solutions/1306. Jump Game III/1306.cpp new file mode 100644 index 00000000000..ee2bd2a870b --- /dev/null +++ b/solutions/1306. Jump Game III/1306.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool canReach(vector& arr, int start) { + const int n = arr.size(); + queue q{{start}}; + vector seen(n); + + while (!q.empty()) { + const int node = q.front(); + q.pop(); + + if (arr[node] == 0) + return true; + if (seen[node]) + continue; + + // Check the available next steps. + if (node - arr[node] >= 0) + q.push(node - arr[node]); + if (node + arr[node] < n) + q.push(node + arr[node]); + + seen[node] = true; + } + + return false; + } +}; diff --git a/solutions/1306. Jump Game III/1306.java b/solutions/1306. Jump Game III/1306.java new file mode 100644 index 00000000000..ac3f9a40e0a --- /dev/null +++ b/solutions/1306. Jump Game III/1306.java @@ -0,0 +1,26 @@ +class Solution { + public boolean canReach(int[] arr, int start) { + final int n = arr.length; + Queue q = new ArrayDeque<>(Arrays.asList(start)); + boolean[] seen = new boolean[n]; + + while (!q.isEmpty()) { + final int node = q.poll(); + + if (arr[node] == 0) + return true; + if (seen[node]) + continue; + + // Check the available next steps. + if (node - arr[node] >= 0) + q.offer(node - arr[node]); + if (node + arr[node] < n) + q.offer(node + arr[node]); + + seen[node] = true; + } + + return false; + } +} diff --git a/solutions/1307. Verbal Arithmetic Puzzle/1307.cpp b/solutions/1307. Verbal Arithmetic Puzzle/1307.cpp new file mode 100644 index 00000000000..5dd3855ce5c --- /dev/null +++ b/solutions/1307. Verbal Arithmetic Puzzle/1307.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + bool isSolvable(vector& words, string result) { + usedDigit = vector(10); + words.push_back(result); + rows = words.size(); + for (const string& word : words) + cols = max(cols, static_cast(word.length())); + return dfs(words, 0, 0, 0); + } + + private: + unordered_map letterToDigit; + vector usedDigit; + int rows; + int cols; + + bool dfs(vector& words, int row, int col, int sum) { + if (col == cols) + return sum == 0; + if (row == rows) + return sum % 10 == 0 && dfs(words, 0, col + 1, sum / 10); + + string word = words[row]; + if (col >= word.length()) + return dfs(words, row + 1, col, sum); + + char letter = word[word.length() - col - 1]; + int sign = row == rows - 1 ? -1 : 1; + + if (const auto it = letterToDigit.find(letter); + it != letterToDigit.cend() && + (it->second > 0 || col < word.length() - 1)) + return dfs(words, row + 1, col, sum + sign * letterToDigit[letter]); + + for (int digit = 0; digit < 10; ++digit) + if (!usedDigit[digit] && (digit > 0 || col + 1 < word.length())) { + letterToDigit[letter] = digit; + usedDigit[digit] = true; + if (dfs(words, row + 1, col, sum + sign * digit)) + return true; + usedDigit[digit] = false; + letterToDigit.erase(letter); + } + + return false; + } +}; diff --git a/solutions/1307. Verbal Arithmetic Puzzle/1307.java b/solutions/1307. Verbal Arithmetic Puzzle/1307.java new file mode 100644 index 00000000000..fbaad287cf2 --- /dev/null +++ b/solutions/1307. Verbal Arithmetic Puzzle/1307.java @@ -0,0 +1,44 @@ +class Solution { + public boolean isSolvable(String[] words, String result) { + rows = words.length + 1; + for (final String word : words) + cols = Math.max(cols, word.length()); + cols = Math.max(cols, result.length()); + return dfs(words, result, 0, 0, 0); + } + + private Map letterToDigit = new HashMap<>(); + private boolean[] usedDigit = new boolean[10]; + private int rows = 0; + private int cols = 0; + + private boolean dfs(String[] words, String result, int row, int col, int sum) { + if (col == cols) + return sum == 0; + if (row == rows) + return sum % 10 == 0 && dfs(words, result, 0, col + 1, sum / 10); + + String word = row == rows - 1 ? result : words[row]; + if (col >= word.length()) + return dfs(words, result, row + 1, col, sum); + + char letter = word.charAt(word.length() - col - 1); + int sign = row == rows - 1 ? -1 : 1; + + if (letterToDigit.containsKey(letter) && + (letterToDigit.get(letter) > 0 || col < word.length() - 1)) + return dfs(words, result, row + 1, col, sum + sign * letterToDigit.get(letter)); + + for (int digit = 0; digit < 10; ++digit) + if (!usedDigit[digit] && (digit > 0 || col < word.length() - 1)) { + letterToDigit.put(letter, digit); + usedDigit[digit] = true; + if (dfs(words, result, row + 1, col, sum + sign * letterToDigit.get(letter))) + return true; + usedDigit[digit] = false; + letterToDigit.remove(letter); + } + + return false; + } +} diff --git a/solutions/1307. Verbal Arithmetic Puzzle/1307.py b/solutions/1307. Verbal Arithmetic Puzzle/1307.py new file mode 100644 index 00000000000..9a3181ffe6c --- /dev/null +++ b/solutions/1307. Verbal Arithmetic Puzzle/1307.py @@ -0,0 +1,37 @@ +class Solution: + def isSolvable(self, words: List[str], result: str) -> bool: + words.append(result) + rows = len(words) + cols = max(map(len, words)) + letterToDigit = {} + usedDigit = [False] * 10 + + def dfs(row: int, col: int, summ: int) -> bool: + if col == cols: + return summ == 0 + if row == rows: + return summ % 10 == 0 and dfs(0, col + 1, summ // 10) + + word = words[row] + if col >= len(word): + return dfs(row + 1, col, summ) + + letter = word[~col] + sign = -1 if row == rows - 1 else 1 + + if letter in letterToDigit and (letterToDigit[letter] > 0 or col < len(word) - 1): + return dfs(row + 1, col, summ + sign * letterToDigit[letter]) + + for digit, used in enumerate(usedDigit): + if not used and (digit > 0 or col < len(word) - 1): + letterToDigit[letter] = digit + usedDigit[digit] = True + if dfs(row + 1, col, summ + sign * digit): + return True + usedDigit[digit] = False + if letter in letterToDigit: + del letterToDigit[letter] + + return False + + return dfs(0, 0, 0) diff --git a/solutions/1308. Running Total for Different Genders/1308.sql b/solutions/1308. Running Total for Different Genders/1308.sql new file mode 100644 index 00000000000..2bae7398819 --- /dev/null +++ b/solutions/1308. Running Total for Different Genders/1308.sql @@ -0,0 +1,9 @@ +SELECT + gender, + day, + SUM(score_points) OVER( + PARTITION BY gender + ORDER BY day + ) AS total +FROM Scores +ORDER BY 1, 2; diff --git a/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.cpp b/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.cpp new file mode 100644 index 00000000000..464c41f81f0 --- /dev/null +++ b/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string freqAlphabets(string s) { + string ans; + + for (int i = 0; i < s.length();) { + if (i + 2 < s.length() && s[i + 2] == '#') { + ans += stoi(s.substr(i, 2)) + 'a' - 1; + i += 3; + } else { + ans += (s[i] - '0') + 'a' - 1; + i += 1; + } + } + + return ans; + } +}; diff --git a/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.java b/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.java new file mode 100644 index 00000000000..7a80717212d --- /dev/null +++ b/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.java @@ -0,0 +1,17 @@ +class Solution { + public String freqAlphabets(String s) { + String ans = ""; + + for (int i = 0; i < s.length();) { + if (i + 2 < s.length() && s.charAt(i + 2) == '#') { + ans += (char) (Integer.valueOf(s.substring(i, i + 2)) + 'a' - 1); + i += 3; + } else { + ans += (char) ((s.charAt(i) - '0') + 'a' - 1); + i += 1; + } + } + + return ans; + } +} diff --git a/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.py b/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.py new file mode 100644 index 00000000000..cd85093bf6b --- /dev/null +++ b/solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.py @@ -0,0 +1,14 @@ +class Solution: + def freqAlphabets(self, s: str) -> str: + ans = '' + i = 0 + + while i < len(s): + if i + 2 < len(s) and s[i + 2] == '#': + ans += chr(int(s[i:i + 2]) + ord('a') - 1) + i += 3 + else: + ans += chr(int(s[i]) + ord('a') - 1) + i += 1 + + return ans diff --git a/solutions/131. Palindrome Partitioning/131.cpp b/solutions/131. Palindrome Partitioning/131.cpp new file mode 100644 index 00000000000..117efc5b75d --- /dev/null +++ b/solutions/131. Palindrome Partitioning/131.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector> partition(string s) { + vector> ans; + dfs(s, 0, {}, ans); + return ans; + } + + private: + void dfs(const string& s, int start, vector&& path, + vector>& ans) { + if (start == s.length()) { + ans.push_back(path); + return; + } + + for (int i = start; i < s.length(); ++i) + if (isPalindrome(s, start, i)) { + path.push_back(s.substr(start, i - start + 1)); + dfs(s, i + 1, move(path), ans); + path.pop_back(); + } + } + + bool isPalindrome(const string& s, int l, int r) { + while (l < r) + if (s[l++] != s[r--]) + return false; + return true; + } +}; diff --git a/solutions/131. Palindrome Partitioning/131.java b/solutions/131. Palindrome Partitioning/131.java new file mode 100644 index 00000000000..64a4b35606f --- /dev/null +++ b/solutions/131. Palindrome Partitioning/131.java @@ -0,0 +1,28 @@ +class Solution { + public List> partition(String s) { + List> ans = new ArrayList<>(); + dfs(s, 0, new ArrayList<>(), ans); + return ans; + } + + private void dfs(final String s, int start, List path, List> ans) { + if (start == s.length()) { + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = start; i < s.length(); ++i) + if (isPalindrome(s, start, i)) { + path.add(s.substring(start, i + 1)); + dfs(s, i + 1, path, ans); + path.remove(path.size() - 1); + } + } + + private boolean isPalindrome(final String s, int l, int r) { + while (l < r) + if (s.charAt(l++) != s.charAt(r--)) + return false; + return true; + } +} diff --git a/solutions/131. Palindrome Partitioning/131.py b/solutions/131. Palindrome Partitioning/131.py new file mode 100644 index 00000000000..599f8419dc1 --- /dev/null +++ b/solutions/131. Palindrome Partitioning/131.py @@ -0,0 +1,18 @@ +class Solution: + def partition(self, s: str) -> List[List[str]]: + ans = [] + + def isPalindrome(s: str) -> bool: + return s == s[::-1] + + def dfs(s: str, j: int, path: List[str], ans: List[List[str]]) -> None: + if j == len(s): + ans.append(path) + return + + for i in range(j, len(s)): + if isPalindrome(s[j: i + 1]): + dfs(s, i + 1, path + [s[j: i + 1]], ans) + + dfs(s, 0, [], ans) + return ans diff --git a/solutions/1310. XOR Queries of a Subarray/1310.cpp b/solutions/1310. XOR Queries of a Subarray/1310.cpp new file mode 100644 index 00000000000..54241bd934f --- /dev/null +++ b/solutions/1310. XOR Queries of a Subarray/1310.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector xorQueries(vector& arr, vector>& queries) { + vector ans; + vector xors(arr.size() + 1); + + for (int i = 0; i < arr.size(); ++i) + xors[i + 1] = xors[i] ^ arr[i]; + + for (const vector& query : queries) { + const int left = query[0]; + const int right = query[1]; + ans.push_back(xors[left] ^ xors[right + 1]); + } + + return ans; + } +}; diff --git a/solutions/1310. XOR Queries of a Subarray/1310.java b/solutions/1310. XOR Queries of a Subarray/1310.java new file mode 100644 index 00000000000..c45d8b4d6fc --- /dev/null +++ b/solutions/1310. XOR Queries of a Subarray/1310.java @@ -0,0 +1,18 @@ +class Solution { + public int[] xorQueries(int[] arr, int[][] queries) { + int[] ans = new int[queries.length]; + int[] xors = new int[arr.length + 1]; + + for (int i = 0; i < arr.length; ++i) + xors[i + 1] = xors[i] ^ arr[i]; + + int i = 0; + for (int[] query : queries) { + final int left = query[0]; + final int right = query[1]; + ans[i++] = xors[left] ^ xors[right + 1]; + } + + return ans; + } +} diff --git a/solutions/1310. XOR Queries of a Subarray/1310.py b/solutions/1310. XOR Queries of a Subarray/1310.py new file mode 100644 index 00000000000..fbb40f9c56f --- /dev/null +++ b/solutions/1310. XOR Queries of a Subarray/1310.py @@ -0,0 +1,12 @@ +class Solution: + def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + ans = [] + xors = [0] * (len(arr) + 1) + + for i, a in enumerate(arr): + xors[i + 1] = xors[i] ^ a + + for left, right in queries: + ans.append(xors[left] ^ xors[right + 1]) + + return ans diff --git a/solutions/1311. Get Watched Videos by Your Friends/1311.cpp b/solutions/1311. Get Watched Videos by Your Friends/1311.cpp new file mode 100644 index 00000000000..c491fe5e245 --- /dev/null +++ b/solutions/1311. Get Watched Videos by Your Friends/1311.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + vector watchedVideosByFriends(vector>& watchedVideos, + vector>& friends, int id, + int level) { + vector ans; + vector visited(friends.size()); + visited[id] = true; + queue queue{{id}}; + unordered_map count; + set> freqAndVideo; + + for (int i = 0; i < level; ++i) + for (int j = queue.size(); j > 0; --j) { + for (int f : friends[queue.front()]) + if (visited[f] == false) { + visited[f] = true; + queue.push(f); + } + queue.pop(); + } + + for (int i = queue.size(); i > 0; --i) { + for (const string& video : watchedVideos[queue.front()]) + ++count[video]; + queue.pop(); + } + + for (const auto& [video, freq] : count) + freqAndVideo.insert({freq, video}); + + for (const auto& [_, video] : freqAndVideo) + ans.push_back(video); + + return ans; + } +}; diff --git a/solutions/1311. Get Watched Videos by Your Friends/1311.java b/solutions/1311. Get Watched Videos by Your Friends/1311.java new file mode 100644 index 00000000000..7afdb7bbfc2 --- /dev/null +++ b/solutions/1311. Get Watched Videos by Your Friends/1311.java @@ -0,0 +1,29 @@ +class Solution { + public List watchedVideosByFriends(List> watchedVideos, int[][] friends, + int id, int level) { + boolean[] visited = new boolean[friends.length]; + visited[id] = true; + Queue queue = new ArrayDeque<>(Arrays.asList(id)); + Map count = new HashMap<>(); + + for (int i = 0; i < level; ++i) + for (int j = queue.size(); j > 0; --j) { + for (int friend : friends[queue.peek()]) + if (visited[friend] == false) { + visited[friend] = true; + queue.add(friend); + } + queue.poll(); + } + + for (int friend : queue) + for (final String video : watchedVideos.get(friend)) + count.merge(video, 1, Integer::sum); + + List ans = new ArrayList<>(count.keySet()); + + ans.sort((a, b) -> count.get(a) == count.get(b) ? a.compareTo(b) : count.get(a) - count.get(b)); + + return ans; + } +} diff --git a/solutions/1311. Get Watched Videos by Your Friends/1311.py b/solutions/1311. Get Watched Videos by Your Friends/1311.py new file mode 100644 index 00000000000..87a83cbc4d3 --- /dev/null +++ b/solutions/1311. Get Watched Videos by Your Friends/1311.py @@ -0,0 +1,21 @@ +class Solution: + def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], + id: int, level: int) -> List[str]: + visited = [False] * 100 + visited[id] = True + q = collections.deque([id]) + count = collections.Counter() + + for _ in range(level): + for _ in range(len(q)): + curr = q.popleft() + for friend in friends[curr]: + if not visited[friend]: + visited[friend] = True + q.append(friend) + + for friend in q: + for video in watchedVideos[friend]: + count[video] += 1 + + return sorted(count.keys(), key=lambda video: (count[video], video)) diff --git a/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.cpp b/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.cpp new file mode 100644 index 00000000000..e73e0ac7683 --- /dev/null +++ b/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int minInsertions(string s) { + return s.length() - longestPalindromeSubseq(s); + } + + private: + // Same as 516. Longest Palindromic Subsequence + int longestPalindromeSubseq(const string& s) { + const int n = s.length(); + // dp[i][j] := the length of LPS(s[i..j]) + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + if (s[i] == s[j]) + dp[i][j] = 2 + dp[i + 1][j - 1]; + else + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.java b/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.java new file mode 100644 index 00000000000..7c6c9fe4ba6 --- /dev/null +++ b/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.java @@ -0,0 +1,26 @@ +class Solution { + public int minInsertions(String s) { + return s.length() - longestPalindromeSubseq(s); + } + + // Same as 516. Longest Palindromic Subsequence + public int longestPalindromeSubseq(String s) { + final int n = s.length(); + // dp[i][j] := the length of LPS(s[i..j]) + int[][] dp = new int[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + if (s.charAt(i) == s.charAt(j)) + dp[i][j] = 2 + dp[i + 1][j - 1]; + else + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.py b/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.py new file mode 100644 index 00000000000..78c82975d62 --- /dev/null +++ b/solutions/1312. Minimum Insertion Steps to Make a String Palindrome/1312.py @@ -0,0 +1,22 @@ +class Solution: + def minInsertions(self, s: str) -> int: + return len(s) - self._longestPalindromeSubseq(s) + + # Same as 516. Longest Palindromic Subsequence + def _longestPalindromeSubseq(self, s: str) -> int: + n = len(s) + # dp[i][j] := the length of LPS(s[i..j]) + dp = [[0] * n for _ in range(n)] + + for i in range(n): + dp[i][i] = 1 + + for d in range(1, n): + for i in range(n - d): + j = i + d + if s[i] == s[j]: + dp[i][j] = 2 + dp[i + 1][j - 1] + else: + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) + + return dp[0][n - 1] diff --git a/solutions/1313. Decompress Run-Length Encoded List/1313.cpp b/solutions/1313. Decompress Run-Length Encoded List/1313.cpp new file mode 100644 index 00000000000..e69dc5bd4ac --- /dev/null +++ b/solutions/1313. Decompress Run-Length Encoded List/1313.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector decompressRLElist(vector& nums) { + vector ans; + + for (int i = 0; i < nums.size(); i += 2) + ans.insert(ans.end(), nums[i], nums[i + 1]); + + return ans; + } +}; diff --git a/solutions/1313. Decompress Run-Length Encoded List/1313.java b/solutions/1313. Decompress Run-Length Encoded List/1313.java new file mode 100644 index 00000000000..d2c759df622 --- /dev/null +++ b/solutions/1313. Decompress Run-Length Encoded List/1313.java @@ -0,0 +1,11 @@ +class Solution { + public int[] decompressRLElist(int[] nums) { + List ans = new ArrayList<>(); + + for (int i = 0; i < nums.length; i += 2) + for (int freq = 0; freq < nums[i]; ++freq) + ans.add(nums[i + 1]); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/1313. Decompress Run-Length Encoded List/1313.py b/solutions/1313. Decompress Run-Length Encoded List/1313.py new file mode 100644 index 00000000000..249eb9b0a34 --- /dev/null +++ b/solutions/1313. Decompress Run-Length Encoded List/1313.py @@ -0,0 +1,8 @@ +class Solution: + def decompressRLElist(self, nums: List[int]) -> List[int]: + ans = [] + + for i in range(0, len(nums), 2): + ans += [nums[i + 1]] * nums[i] + + return ans diff --git a/solutions/1314. Matrix Block Sum/1314.cpp b/solutions/1314. Matrix Block Sum/1314.cpp new file mode 100644 index 00000000000..421625128b2 --- /dev/null +++ b/solutions/1314. Matrix Block Sum/1314.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> matrixBlockSum(vector>& mat, int k) { + const int m = mat.size(); + const int n = mat[0].size(); + vector> ans(m, vector(n)); + vector> prefix(m + 1, vector(n + 1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + prefix[i + 1][j + 1] = + mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + const int r1 = max(0, i - k) + 1; + const int c1 = max(0, j - k) + 1; + const int r2 = min(m - 1, i + k) + 1; + const int c2 = min(n - 1, j + k) + 1; + ans[i][j] = prefix[r2][c2] - prefix[r2][c1 - 1] - prefix[r1 - 1][c2] + + prefix[r1 - 1][c1 - 1]; + } + + return ans; + } +}; diff --git a/solutions/1314. Matrix Block Sum/1314.java b/solutions/1314. Matrix Block Sum/1314.java new file mode 100644 index 00000000000..7fd5d6c2481 --- /dev/null +++ b/solutions/1314. Matrix Block Sum/1314.java @@ -0,0 +1,24 @@ +class Solution { + public int[][] matrixBlockSum(int[][] mat, int k) { + final int m = mat.length; + final int n = mat[0].length; + int[][] ans = new int[m][n]; + int[][] prefix = new int[m + 1][n + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + prefix[i + 1][j + 1] = mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + final int r1 = Math.max(0, i - k) + 1; + final int c1 = Math.max(0, j - k) + 1; + final int r2 = Math.min(m - 1, i + k) + 1; + final int c2 = Math.min(n - 1, j + k) + 1; + ans[i][j] = + prefix[r2][c2] - prefix[r2][c1 - 1] - prefix[r1 - 1][c2] + prefix[r1 - 1][c1 - 1]; + } + + return ans; + } +} diff --git a/solutions/1314. Matrix Block Sum/1314.py b/solutions/1314. Matrix Block Sum/1314.py new file mode 100644 index 00000000000..37b6af03a4a --- /dev/null +++ b/solutions/1314. Matrix Block Sum/1314.py @@ -0,0 +1,22 @@ +class Solution: + def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]: + m = len(mat) + n = len(mat[0]) + ans = [[0] * n for _ in range(m)] + prefix = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(m): + for j in range(n): + prefix[i + 1][j + 1] = mat[i][j] + \ + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j] + + for i in range(m): + for j in range(n): + r1 = max(0, i - k) + 1 + c1 = max(0, j - k) + 1 + r2 = min(m - 1, i + k) + 1 + c2 = min(n - 1, j + k) + 1 + ans[i][j] = prefix[r2][c2] - prefix[r2][c1 - 1] - \ + prefix[r1 - 1][c2] + prefix[r1 - 1][c1 - 1] + + return ans diff --git a/solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.cpp b/solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.cpp new file mode 100644 index 00000000000..c08acca2e5c --- /dev/null +++ b/solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int sumEvenGrandparent(TreeNode* root) { + return dfs(root, 1, 1); // The parent and the grandparent are odd at first. + } + + private: + int dfs(TreeNode* root, int p, int gp) { + if (root == nullptr) + return 0; + return (gp % 2 == 0 ? root->val : 0) + // + dfs(root->left, root->val, p) + // + dfs(root->right, root->val, p); + } +}; diff --git a/solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.java b/solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.java new file mode 100644 index 00000000000..5e2b3413f18 --- /dev/null +++ b/solutions/1315. Sum of Nodes with Even-Valued Grandparent/1315.java @@ -0,0 +1,13 @@ +class Solution { + public int sumEvenGrandparent(TreeNode root) { + return dfs(root, 1, 1); // The parent and the grandparent are odd at first. + } + + private int dfs(TreeNode root, int p, int gp) { + if (root == null) + return 0; + return (gp % 2 == 0 ? root.val : 0) + // + dfs(root.left, root.val, p) + // + dfs(root.right, root.val, p); + } +} diff --git a/solutions/1316. Distinct Echo Substrings/1316.cpp b/solutions/1316. Distinct Echo Substrings/1316.cpp new file mode 100644 index 00000000000..51a364de7e7 --- /dev/null +++ b/solutions/1316. Distinct Echo Substrings/1316.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int distinctEchoSubstrings(string text) { + unordered_set seen; + + for (int k = 1; k <= text.length() / 2; ++k) { // the target length + int same = 0; + for (int l = 0, r = k; r < text.length(); ++l, ++r) { + if (text[l] == text[r]) + ++same; + else + same = 0; + if (same == k) { + seen.insert(text.substr(l - k + 1, k)); + // Move the window thus leaving a letter behind, so we need to + // decrease the counter. + --same; + } + } + } + + return seen.size(); + } +}; diff --git a/solutions/1316. Distinct Echo Substrings/1316.java b/solutions/1316. Distinct Echo Substrings/1316.java new file mode 100644 index 00000000000..a69a03610e6 --- /dev/null +++ b/solutions/1316. Distinct Echo Substrings/1316.java @@ -0,0 +1,23 @@ +class Solution { + public int distinctEchoSubstrings(String text) { + Set seen = new HashSet<>(); + + for (int k = 1; k <= text.length() / 2; ++k) { // the target length + int same = 0; + for (int l = 0, r = k; r < text.length(); ++l, ++r) { + if (text.charAt(l) == text.charAt(r)) + ++same; + else + same = 0; + if (same == k) { + seen.add(text.substring(l - k + 1, l + 1)); + // Move the window thus leaving a letter behind, so we need to + // decrease the counter. + --same; + } + } + } + + return seen.size(); + } +} diff --git a/solutions/1316. Distinct Echo Substrings/1316.py b/solutions/1316. Distinct Echo Substrings/1316.py new file mode 100644 index 00000000000..31cb07a6cab --- /dev/null +++ b/solutions/1316. Distinct Echo Substrings/1316.py @@ -0,0 +1,20 @@ +class Solution: + def distinctEchoSubstrings(self, text: str) -> int: + seen = set() + + for k in range(1, len(text) // 2 + 1): # the target length + same = 0 + l = 0 + for r in range(k, len(text)): + if text[l] == text[r]: + same += 1 + else: + same = 0 + if same == k: + seen.add(text[l - k + 1:l + 1]) + # Move the window thus leaving a letter behind, so we need to + # decrease the counter. + same -= 1 + l += 1 + + return len(seen) diff --git a/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.cpp b/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.cpp new file mode 100644 index 00000000000..a381f2d2ccb --- /dev/null +++ b/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector getNoZeroIntegers(int n) { + for (int A = 1; A < n; ++A) { + int B = n - A; + if (to_string(A).find('0') == string::npos && + to_string(B).find('0') == string::npos) + return {A, B}; + } + + throw; + } +}; diff --git a/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.java b/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.java new file mode 100644 index 00000000000..ef9d9468815 --- /dev/null +++ b/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.java @@ -0,0 +1,11 @@ +class Solution { + public int[] getNoZeroIntegers(int n) { + for (int A = 1; A < n; ++A) { + int B = n - A; + if (!String.valueOf(A).contains("0") && !String.valueOf(B).contains("0")) + return new int[] {A, B}; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.py b/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.py new file mode 100644 index 00000000000..c34db81f825 --- /dev/null +++ b/solutions/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.py @@ -0,0 +1,6 @@ +class Solution: + def getNoZeroIntegers(self, n: int) -> List[int]: + for A in range(n): + B = n - A + if '0' not in str(A) and '0' not in str(B): + return A, B diff --git a/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.cpp b/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.cpp new file mode 100644 index 00000000000..423bcc49183 --- /dev/null +++ b/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minFlips(int a, int b, int c) { + constexpr int kMaxBit = 30; + int ans = 0; + + for (int i = 0; i < kMaxBit; ++i) + if (c >> i & 1) + ans += (a >> i & 1) == 0 && (b >> i & 1) == 0; + else // (c >> i & 1) == 0 + ans += (a >> i & 1) + (b >> i & 1); + + return ans; + } +}; diff --git a/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.java b/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.java new file mode 100644 index 00000000000..570f9d5749b --- /dev/null +++ b/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.java @@ -0,0 +1,14 @@ +class Solution { + public int minFlips(int a, int b, int c) { + final int kMaxBit = 30; + int ans = 0; + + for (int i = 0; i < kMaxBit; ++i) + if ((c >> i & 1) == 1) + ans += ((a >> i & 1) == 0 && (b >> i & 1) == 0) ? 1 : 0; + else // (c >> i & 1) == 0 + ans += ((a >> i & 1) == 1 ? 1 : 0) + ((b >> i & 1) == 1 ? 1 : 0); + + return ans; + } +} diff --git a/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.py b/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.py new file mode 100644 index 00000000000..df1f1084814 --- /dev/null +++ b/solutions/1318. Minimum Flips to Make a OR b Equal to c/1318.py @@ -0,0 +1,12 @@ +class Solution: + def minFlips(self, a: int, b: int, c: int) -> int: + kMaxBit = 30 + ans = 0 + + for i in range(kMaxBit): + if c >> i & 1: + ans += (a >> i & 1) == 0 and (b >> i & 1) == 0 + else: # (c >> i & 1) == 0 + ans += (a >> i & 1) + (b >> i & 1) + + return ans diff --git a/solutions/1319. Number of Operations to Make Network Connected/1319.cpp b/solutions/1319. Number of Operations to Make Network Connected/1319.cpp new file mode 100644 index 00000000000..19fc18e2e62 --- /dev/null +++ b/solutions/1319. Number of Operations to Make Network Connected/1319.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int makeConnected(int n, vector>& connections) { + // To connect n nodes, we need at least n - 1 edges + if (connections.size() < n - 1) + return -1; + + int numOfConnected = 0; + vector> graph(n); + unordered_set seen; + + for (const vector& connection : connections) { + const int u = connection[0]; + const int v = connection[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + for (int i = 0; i < n; ++i) + if (seen.insert(i).second) { + dfs(graph, i, seen); + ++numOfConnected; + } + + return numOfConnected - 1; + } + + private: + void dfs(const vector>& graph, int u, unordered_set& seen) { + for (const int v : graph[u]) + if (seen.insert(v).second) + dfs(graph, v, seen); + } +}; diff --git a/solutions/1319. Number of Operations to Make Network Connected/1319.java b/solutions/1319. Number of Operations to Make Network Connected/1319.java new file mode 100644 index 00000000000..cfd8b4da4e2 --- /dev/null +++ b/solutions/1319. Number of Operations to Make Network Connected/1319.java @@ -0,0 +1,35 @@ +class Solution { + public int makeConnected(int n, int[][] connections) { + // To connect n nodes, we need at least n - 1 edges + if (connections.length < n - 1) + return -1; + + int numOfConnected = 0; + List[] graph = new List[n]; + Set seen = new HashSet<>(); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] connection : connections) { + final int u = connection[0]; + final int v = connection[1]; + graph[u].add(v); + graph[v].add(u); + } + + for (int i = 0; i < n; ++i) + if (seen.add(i)) { + dfs(graph, i, seen); + ++numOfConnected; + } + + return numOfConnected - 1; + } + + private void dfs(List[] graph, int u, Set seen) { + for (final int v : graph[u]) + if (seen.add(v)) + dfs(graph, v, seen); + } +} diff --git a/solutions/132. Palindrome Partitioning II/132.cpp b/solutions/132. Palindrome Partitioning II/132.cpp new file mode 100644 index 00000000000..fd655c0a980 --- /dev/null +++ b/solutions/132. Palindrome Partitioning II/132.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int minCut(string s) { + const int n = s.length(); + // isPalindrome[i][j] := true if s[i..j] is a palindrome + vector> isPalindrome(n, vector(n, true)); + // dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i] + vector dp(n, n); + + for (int l = 2; l <= n; ++l) + for (int i = 0, j = l - 1; j < n; ++i, ++j) + isPalindrome[i][j] = s[i] == s[j] && isPalindrome[i + 1][j - 1]; + + for (int i = 0; i < n; ++i) { + if (isPalindrome[0][i]) { + dp[i] = 0; + continue; + } + + // Try all the possible partitions. + for (int j = 0; j < i; ++j) + if (isPalindrome[j + 1][i]) + dp[i] = min(dp[i], dp[j] + 1); + } + + return dp.back(); + } +}; diff --git a/solutions/132. Palindrome Partitioning II/132.java b/solutions/132. Palindrome Partitioning II/132.java new file mode 100644 index 00000000000..ef9705a6fc3 --- /dev/null +++ b/solutions/132. Palindrome Partitioning II/132.java @@ -0,0 +1,30 @@ +class Solution { + public int minCut(String s) { + final int n = s.length(); + // isPalindrome[i][j] := true if s[i..j] is a palindrome + boolean[][] isPalindrome = new boolean[n][n]; + for (boolean[] row : isPalindrome) + Arrays.fill(row, true); + // dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i] + int[] dp = new int[n]; + Arrays.fill(dp, n); + + for (int l = 2; l <= n; ++l) + for (int i = 0, j = l - 1; j < n; ++i, ++j) + isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && isPalindrome[i + 1][j - 1]; + + for (int i = 0; i < n; ++i) { + if (isPalindrome[0][i]) { + dp[i] = 0; + continue; + } + + // Try all the possible partitions. + for (int j = 0; j < i; ++j) + if (isPalindrome[j + 1][i]) + dp[i] = Math.min(dp[i], dp[j] + 1); + } + + return dp[n - 1]; + } +} diff --git a/solutions/132. Palindrome Partitioning II/132.py b/solutions/132. Palindrome Partitioning II/132.py new file mode 100644 index 00000000000..29d5d2ada44 --- /dev/null +++ b/solutions/132. Palindrome Partitioning II/132.py @@ -0,0 +1,25 @@ +class Solution: + def minCut(self, s: str) -> int: + n = len(s) + # isPalindrome[i][j] := True if s[i..j] is a palindrome + isPalindrome = [[True] * n for _ in range(n)] + # dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i] + dp = [n] * n + + for l in range(2, n + 1): + i = 0 + for j in range(l - 1, n): + isPalindrome[i][j] = s[i] == s[j] and isPalindrome[i + 1][j - 1] + i += 1 + + for i in range(n): + if isPalindrome[0][i]: + dp[i] = 0 + continue + + # Try all the possible partitions. + for j in range(i): + if isPalindrome[j + 1][i]: + dp[i] = min(dp[i], dp[j] + 1) + + return dp[-1] diff --git a/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.cpp b/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.cpp new file mode 100644 index 00000000000..e8a46426989 --- /dev/null +++ b/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minimumDistance(string word) { + vector>> mem( + 27, vector>(27, vector(word.length(), -1))); + return minimumDistance(word, 26, 26, 0, mem); + } + + private: + // Returns the minimum distance to type `word`, where the left finger is on + // the i-th letter, the right finger is on the j-th letter, and word[0..k) + // have been written. + int minimumDistance(const string& word, int i, int j, int k, + vector>>& mem) { + if (k == word.length()) + return 0; + if (mem[i][j][k] != -1) + return mem[i][j][k]; + const int c = word[k] - 'A'; + const int moveLeft = dist(i, c) + minimumDistance(word, c, j, k + 1, mem); + const int moveRight = dist(j, c) + minimumDistance(word, i, c, k + 1, mem); + return mem[i][j][k] = min(moveLeft, moveRight); + } + + int dist(int a, int b) { + if (a == 26) // the first hovering state + return 0; + const int x1 = a / 6; + const int y1 = a % 6; + const int x2 = b / 6; + const int y2 = b % 6; + return abs(x1 - x2) + abs(y1 - y2); + } +}; diff --git a/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.java b/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.java new file mode 100644 index 00000000000..19300e91c9a --- /dev/null +++ b/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.java @@ -0,0 +1,30 @@ +class Solution { + public int minimumDistance(String word) { + Integer[][][] mem = new Integer[27][27][word.length()]; + return minimumDistance(word, 26, 26, 0, mem); + } + + // Returns the minimum distance to type `word`, where the left finger is on + // the i-th letter, the right finger is on the j-th letter, and word[0..k) + // have been written. + private int minimumDistance(final String word, int i, int j, int k, Integer[][][] mem) { + if (k == word.length()) + return 0; + if (mem[i][j][k] != null) + return mem[i][j][k]; + final int c = word.charAt(k) - 'A'; + final int moveLeft = dist(i, c) + minimumDistance(word, c, j, k + 1, mem); + final int moveRight = dist(j, c) + minimumDistance(word, i, c, k + 1, mem); + return mem[i][j][k] = Math.min(moveLeft, moveRight); + } + + private int dist(int a, int b) { + if (a == 26) // the first hovering state + return 0; + final int x1 = a / 6; + final int y1 = a % 6; + final int x2 = b / 6; + final int y2 = b % 6; + return Math.abs(x1 - x2) + Math.abs(y1 - y2); + } +} diff --git a/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.py b/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.py new file mode 100644 index 00000000000..129fa56eb78 --- /dev/null +++ b/solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.py @@ -0,0 +1,24 @@ +class Solution: + def minimumDistance(self, word: str) -> int: + def dist(a: int, b: int) -> int: + if a == 26: # the first hovering state + return 0 + x1, y1 = a // 6, a % 6 + x2, y2 = b // 6, b % 6 + return abs(x1 - x2) + abs(y1 - y2) + + @functools.lru_cache(None) + def dp(i: int, j: int, k: int) -> int: + """ + Returns the minimum distance to type the `word`, where the left finger is + on the i-th letter, the right finger is on the j-th letter, and the + words[0..k) have been written. + """ + if k == len(word): + return 0 + nxt = ord(word[k]) - ord('A') + moveLeft = dist(i, nxt) + dp(nxt, j, k + 1) + moveRight = dist(j, nxt) + dp(i, nxt, k + 1) + return min(moveLeft, moveRight) + + return dp(26, 26, 0) diff --git a/solutions/1321. Restaurant Growth/1321.sql b/solutions/1321. Restaurant Growth/1321.sql new file mode 100644 index 00000000000..952b93e3cd3 --- /dev/null +++ b/solutions/1321. Restaurant Growth/1321.sql @@ -0,0 +1,17 @@ +WITH + Dates AS ( + SELECT DISTINCT visited_on + FROM Customer + WHERE visited_on >= ( + SELECT DATE_ADD(MIN(visited_on), INTERVAL 6 DAY) + FROM Customer + ) + ) +SELECT + Dates.visited_on, + SUM(Customer.amount) AS amount, + ROUND(SUM(Customer.amount) / 7, 2) AS average_amount +FROM Dates +LEFT JOIN Customer + ON (DATEDIFF(Dates.visited_on, Customer.visited_on) BETWEEN 0 AND 6) +GROUP BY 1; diff --git a/solutions/1322. Ads Performance/1322.sql b/solutions/1322. Ads Performance/1322.sql new file mode 100644 index 00000000000..e2f91c36232 --- /dev/null +++ b/solutions/1322. Ads Performance/1322.sql @@ -0,0 +1,12 @@ +SELECT + ad_id, + IFNULL( + ROUND( + SUM(action = 'Clicked') * 100 /(SUM(action = 'Clicked') + SUM(action = 'Viewed')), + 2 + ), + 0 + ) AS ctr +FROM Ads +GROUP BY 1 +ORDER BY ctr DESC, ad_id; diff --git a/solutions/1323. Maximum 69 Number/1323.cpp b/solutions/1323. Maximum 69 Number/1323.cpp new file mode 100644 index 00000000000..58392bab673 --- /dev/null +++ b/solutions/1323. Maximum 69 Number/1323.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maximum69Number(int num) { + string ans = to_string(num); + + for (char& c : ans) + if (c == '6') { + c = '9'; + break; + } + + return stoi(ans); + } +}; diff --git a/solutions/1323. Maximum 69 Number/1323.java b/solutions/1323. Maximum 69 Number/1323.java new file mode 100644 index 00000000000..0218c40136a --- /dev/null +++ b/solutions/1323. Maximum 69 Number/1323.java @@ -0,0 +1,13 @@ +class Solution { + public int maximum69Number(int num) { + char[] ans = String.valueOf(num).toCharArray(); + + for (int i = 0; i < ans.length; ++i) + if (ans[i] == '6') { + ans[i] = '9'; + break; + } + + return Integer.valueOf(String.valueOf(ans)); + } +} diff --git a/solutions/1323. Maximum 69 Number/1323.py b/solutions/1323. Maximum 69 Number/1323.py new file mode 100644 index 00000000000..af3e5749eaa --- /dev/null +++ b/solutions/1323. Maximum 69 Number/1323.py @@ -0,0 +1,3 @@ +class Solution: + def maximum69Number(self, num: int) -> int: + return int(str(num).replace('6', '9', 1)) diff --git a/solutions/1324. Print Words Vertically/1324.cpp b/solutions/1324. Print Words Vertically/1324.cpp new file mode 100644 index 00000000000..63b4a91051c --- /dev/null +++ b/solutions/1324. Print Words Vertically/1324.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector printVertically(string s) { + vector ans; + vector words = split(s); + size_t maxLength = 0; + + for (const string& word : words) + maxLength = max(maxLength, word.length()); + + for (size_t i = 0; i < maxLength; ++i) { + string row; + for (const string& word : words) + row += i < word.length() ? word[i] : ' '; + while (row.back() == ' ') + row.pop_back(); + ans.push_back(row); + } + + return ans; + } + + private: + vector split(const string& s) { + vector words; + istringstream iss(s); + for (string token; iss >> token;) + words.push_back(token); + return words; + } +}; diff --git a/solutions/1324. Print Words Vertically/1324.java b/solutions/1324. Print Words Vertically/1324.java new file mode 100644 index 00000000000..0eefcc17c76 --- /dev/null +++ b/solutions/1324. Print Words Vertically/1324.java @@ -0,0 +1,21 @@ +class Solution { + public List printVertically(String s) { + List ans = new ArrayList<>(); + String[] words = s.split(" "); + int maxLength = 0; + + for (final String word : words) + maxLength = Math.max(maxLength, word.length()); + + for (int i = 0; i < maxLength; ++i) { + StringBuilder sb = new StringBuilder(); + for (final String word : words) + sb.append(i < word.length() ? word.charAt(i) : ' '); + while (sb.charAt(sb.length() - 1) == ' ') + sb.deleteCharAt(sb.length() - 1); + ans.add(sb.toString()); + } + + return ans; + } +} diff --git a/solutions/1324. Print Words Vertically/1324.py b/solutions/1324. Print Words Vertically/1324.py new file mode 100644 index 00000000000..0b2d82941a0 --- /dev/null +++ b/solutions/1324. Print Words Vertically/1324.py @@ -0,0 +1,13 @@ +class Solution: + def printVertically(self, s: str) -> List[str]: + ans = [] + words = s.split() + maxLength = max(len(word) for word in words) + + for i in range(maxLength): + row = [] + for word in words: + row.append(word[i] if i < len(word) else ' ') + ans.append(''.join(row).rstrip()) + + return ans diff --git a/solutions/1325. Delete Leaves With a Given Value/1325.cpp b/solutions/1325. Delete Leaves With a Given Value/1325.cpp new file mode 100644 index 00000000000..ebc32fc4ecf --- /dev/null +++ b/solutions/1325. Delete Leaves With a Given Value/1325.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + TreeNode* removeLeafNodes(TreeNode* root, int target) { + if (root == nullptr) + return nullptr; + root->left = removeLeafNodes(root->left, target); + root->right = removeLeafNodes(root->right, target); + return isLeaf(root) && root->val == target ? nullptr : root; + } + + private: + bool isLeaf(TreeNode* root) { + return root->left == nullptr && root->right == nullptr; + } +}; diff --git a/solutions/1325. Delete Leaves With a Given Value/1325.java b/solutions/1325. Delete Leaves With a Given Value/1325.java new file mode 100644 index 00000000000..56dca85195e --- /dev/null +++ b/solutions/1325. Delete Leaves With a Given Value/1325.java @@ -0,0 +1,13 @@ +class Solution { + public TreeNode removeLeafNodes(TreeNode root, int target) { + if (root == null) + return null; + root.left = removeLeafNodes(root.left, target); + root.right = removeLeafNodes(root.right, target); + return isLeaf(root) && root.val == target ? null : root; + } + + private boolean isLeaf(TreeNode root) { + return root.left == null && root.right == null; + } +} diff --git a/solutions/1325. Delete Leaves With a Given Value/1325.py b/solutions/1325. Delete Leaves With a Given Value/1325.py new file mode 100644 index 00000000000..376fcc8c7dd --- /dev/null +++ b/solutions/1325. Delete Leaves With a Given Value/1325.py @@ -0,0 +1,10 @@ +class Solution: + def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: + if not root: + return None + root.left = self.removeLeafNodes(root.left, target) + root.right = self.removeLeafNodes(root.right, target) + return None if self._isLeaf(root) and root.val == target else root + + def _isLeaf(self, root: Optional[TreeNode]) -> bool: + return not root.left and not root.right diff --git a/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.cpp b/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.cpp new file mode 100644 index 00000000000..8c3f2d1fe27 --- /dev/null +++ b/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minTaps(int n, vector& ranges) { + vector nums(n + 1); + + for (int i = 0; i <= n; ++i) { + int l = max(0, i - ranges[i]); + int r = min(n, i + ranges[i]); + nums[l] = max(nums[l], r - l); + } + + int ans = 0; + int end = 0; + int farthest = 0; + + for (int i = 0; i < n; i++) { + farthest = max(farthest, i + nums[i]); + if (i == end) { + ++ans; + end = farthest; + } + } + + return end == n ? ans : -1; + } +}; diff --git a/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.java b/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.java new file mode 100644 index 00000000000..d1045b82cea --- /dev/null +++ b/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.java @@ -0,0 +1,25 @@ +class Solution { + public int minTaps(int n, int[] ranges) { + int[] nums = new int[n + 1]; + + for (int i = 0; i <= n; ++i) { + int l = Math.max(0, i - ranges[i]); + int r = Math.min(n, i + ranges[i]); + nums[l] = Math.max(nums[l], r - l); + } + + int ans = 0; + int end = 0; + int farthest = 0; + + for (int i = 0; i < n; i++) { + farthest = Math.max(farthest, i + nums[i]); + if (i == end) { + ++ans; + end = farthest; + } + } + + return end == n ? ans : -1; + } +} diff --git a/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.py b/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.py new file mode 100644 index 00000000000..b6cec105133 --- /dev/null +++ b/solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.py @@ -0,0 +1,20 @@ +class Solution: + def minTaps(self, n: int, ranges: List[int]) -> int: + nums = [0] * (n + 1) + + for i, range_ in enumerate(ranges): + l = max(0, i - range_) + r = min(n, range_ + i) + nums[l] = max(nums[l], r - l) + + ans = 0 + end = 0 + farthest = 0 + + for i in range(n): + farthest = max(farthest, i + nums[i]) + if i == end: + ans += 1 + end = farthest + + return ans if end == n else -1 diff --git a/solutions/1327. List the Products Ordered in a Period/1327.sql b/solutions/1327. List the Products Ordered in a Period/1327.sql new file mode 100644 index 00000000000..6765f8d9147 --- /dev/null +++ b/solutions/1327. List the Products Ordered in a Period/1327.sql @@ -0,0 +1,9 @@ +SELECT + Products.product_name, + SUM(Orders.unit) AS unit +FROM Products +INNER JOIN Orders + USING (product_id) +WHERE DATE_FORMAT(Orders.order_date, '%Y-%m') = '2020-02' +GROUP BY product_id +HAVING SUM(Orders.unit) >= 100; diff --git a/solutions/1328. Break a Palindrome/1328.cpp b/solutions/1328. Break a Palindrome/1328.cpp new file mode 100644 index 00000000000..5da30392c7f --- /dev/null +++ b/solutions/1328. Break a Palindrome/1328.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + string breakPalindrome(string palindrome) { + if (palindrome.length() == 1) + return ""; + + for (int i = 0; i < palindrome.length() / 2; ++i) + if (palindrome[i] != 'a') { + palindrome[i] = 'a'; + return palindrome; + } + + palindrome.back() = 'b'; + return palindrome; + } +}; diff --git a/solutions/1328. Break a Palindrome/1328.java b/solutions/1328. Break a Palindrome/1328.java new file mode 100644 index 00000000000..b997ec883e9 --- /dev/null +++ b/solutions/1328. Break a Palindrome/1328.java @@ -0,0 +1,17 @@ +class Solution { + public String breakPalindrome(String palindrome) { + if (palindrome.length() == 1) + return ""; + + StringBuilder sb = new StringBuilder(palindrome); + + for (int i = 0; i < palindrome.length() / 2; ++i) + if (palindrome.charAt(i) != 'a') { + sb.setCharAt(i, 'a'); + return sb.toString(); + } + + sb.setCharAt(sb.length() - 1, 'b'); + return sb.toString(); + } +} diff --git a/solutions/1328. Break a Palindrome/1328.py b/solutions/1328. Break a Palindrome/1328.py new file mode 100644 index 00000000000..3b434da5dc0 --- /dev/null +++ b/solutions/1328. Break a Palindrome/1328.py @@ -0,0 +1,14 @@ +class Solution: + def breakPalindrome(self, palindrome: str) -> str: + if len(palindrome) == 1: + return '' + + ans = list(palindrome) + + for i in range(len(palindrome) // 2): + if palindrome[i] != 'a': + ans[i] = 'a' + return ''.join(ans) + + ans[-1] = 'b' + return ''.join(ans) diff --git a/solutions/1329. Sort the Matrix Diagonally/1329.cpp b/solutions/1329. Sort the Matrix Diagonally/1329.cpp new file mode 100644 index 00000000000..f619101bb9e --- /dev/null +++ b/solutions/1329. Sort the Matrix Diagonally/1329.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector> diagonalSort(vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + + unordered_map> count; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + count[i - j].push(mat[i][j]); + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) + mat[i][j] = count[i - j].top(), count[i - j].pop(); + + return mat; + } +}; diff --git a/solutions/1329. Sort the Matrix Diagonally/1329.java b/solutions/1329. Sort the Matrix Diagonally/1329.java new file mode 100644 index 00000000000..087f8cef9df --- /dev/null +++ b/solutions/1329. Sort the Matrix Diagonally/1329.java @@ -0,0 +1,18 @@ +class Solution { + public int[][] diagonalSort(int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + + Map> count = new HashMap<>(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + count.computeIfAbsent(i - j, k -> new PriorityQueue<>()).add(mat[i][j]); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + mat[i][j] = count.get(i - j).poll(); + + return mat; + } +} diff --git a/solutions/1329. Sort the Matrix Diagonally/1329.py b/solutions/1329. Sort the Matrix Diagonally/1329.py new file mode 100644 index 00000000000..551c1a4d362 --- /dev/null +++ b/solutions/1329. Sort the Matrix Diagonally/1329.py @@ -0,0 +1,19 @@ +class Solution: + def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: + m = len(mat) + n = len(mat[0]) + + count = collections.defaultdict(list) + + for i in range(m): + for j in range(n): + count[i - j].append(mat[i][j]) + + for value in count.values(): + value.sort(reverse=1) + + for i in range(m): + for j in range(n): + mat[i][j] = count[i - j].pop() + + return mat diff --git a/solutions/133. Clone Graph/133-2.cpp b/solutions/133. Clone Graph/133-2.cpp new file mode 100644 index 00000000000..e7ed183a83d --- /dev/null +++ b/solutions/133. Clone Graph/133-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + Node* cloneGraph(Node* node) { + if (node == nullptr) + return nullptr; + if (const auto it = map.find(node); it != map.cend()) + return it->second; + + Node* newNode = new Node(node->val); + map[node] = newNode; + + for (Node* neighbor : node->neighbors) + newNode->neighbors.push_back(cloneGraph(neighbor)); + + return newNode; + } + + private: + unordered_map map; +}; diff --git a/solutions/133. Clone Graph/133-2.java b/solutions/133. Clone Graph/133-2.java new file mode 100644 index 00000000000..cfe77eccc1b --- /dev/null +++ b/solutions/133. Clone Graph/133-2.java @@ -0,0 +1,18 @@ +class Solution { + public Node cloneGraph(Node node) { + if (node == null) + return null; + if (map.containsKey(node)) + return map.get(node); + + Node newNode = new Node(node.val); + map.put(node, newNode); + + for (Node neighbor : node.neighbors) + newNode.neighbors.add(cloneGraph(neighbor)); + + return newNode; + } + + private Map map = new HashMap<>(); +} diff --git a/solutions/133. Clone Graph/133-2.py b/solutions/133. Clone Graph/133-2.py new file mode 100644 index 00000000000..a84c9e6dfd0 --- /dev/null +++ b/solutions/133. Clone Graph/133-2.py @@ -0,0 +1,16 @@ +class Solution: + def cloneGraph(self, node: 'Node') -> 'Node': + if not node: + return None + if node in self.map: + return self.map[node] + + newNode = Node(node.val, []) + self.map[node] = newNode + + for neighbor in node.neighbors: + self.map[node].neighbors.append(self.cloneGraph(neighbor)) + + return newNode + + map = {} diff --git a/solutions/133. Clone Graph/133.cpp b/solutions/133. Clone Graph/133.cpp new file mode 100644 index 00000000000..72e5f8ef565 --- /dev/null +++ b/solutions/133. Clone Graph/133.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + Node* cloneGraph(Node* node) { + if (node == nullptr) + return nullptr; + + queue q{{node}}; + unordered_map map{{node, new Node(node->val)}}; + + while (!q.empty()) { + Node* u = q.front(); + q.pop(); + for (Node* v : u->neighbors) { + if (!map.contains(v)) { + map[v] = new Node(v->val); + q.push(v); + } + map[u]->neighbors.push_back(map[v]); + } + } + + return map[node]; + } +}; diff --git a/solutions/133. Clone Graph/133.java b/solutions/133. Clone Graph/133.java new file mode 100644 index 00000000000..ddc0647ee73 --- /dev/null +++ b/solutions/133. Clone Graph/133.java @@ -0,0 +1,23 @@ +class Solution { + public Node cloneGraph(Node node) { + if (node == null) + return null; + + Queue q = new ArrayDeque<>(Arrays.asList(node)); + Map map = new HashMap<>(); + map.put(node, new Node(node.val)); + + while (!q.isEmpty()) { + Node u = q.poll(); + for (Node v : u.neighbors) { + if (!map.containsKey(v)) { + map.put(v, new Node(v.val)); + q.offer(v); + } + map.get(u).neighbors.add(map.get(v)); + } + } + + return map.get(node); + } +} diff --git a/solutions/133. Clone Graph/133.py b/solutions/133. Clone Graph/133.py new file mode 100644 index 00000000000..19d3bcafe87 --- /dev/null +++ b/solutions/133. Clone Graph/133.py @@ -0,0 +1,17 @@ +class Solution: + def cloneGraph(self, node: 'Node') -> 'Node': + if not node: + return None + + q = collections.deque([node]) + map = {node: Node(node.val)} + + while q: + u = q.popleft() + for v in u.neighbors: + if v not in map: + map[v] = Node(v.val) + q.append(v) + map[u].neighbors.append(map[v]) + + return map[node] diff --git a/solutions/1330. Reverse Subarray To Maximize Array Value/1330.cpp b/solutions/1330. Reverse Subarray To Maximize Array Value/1330.cpp new file mode 100644 index 00000000000..4775320c3e3 --- /dev/null +++ b/solutions/1330. Reverse Subarray To Maximize Array Value/1330.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxValueAfterReverse(vector& nums) { + int total = 0; + int mn = INT_MAX; + int mx = INT_MIN; + + for (int i = 0; i + 1 < nums.size(); ++i) { + const int a = nums[i]; + const int b = nums[i + 1]; + total += abs(a - b); + mn = min(mn, max(a, b)); + mx = max(mx, min(a, b)); + } + int diff = max(0, (mx - mn) * 2); + + for (int i = 0; i + 1 < nums.size(); ++i) { + const int a = nums[i]; + const int b = nums[i + 1]; + const int headDiff = -abs(a - b) + abs(nums.front() - b); + const int tailDiff = -abs(a - b) + abs(nums.back() - a); + diff = max({diff, headDiff, tailDiff}); + } + + return total + diff; + } +}; diff --git a/solutions/1330. Reverse Subarray To Maximize Array Value/1330.java b/solutions/1330. Reverse Subarray To Maximize Array Value/1330.java new file mode 100644 index 00000000000..f7250c92476 --- /dev/null +++ b/solutions/1330. Reverse Subarray To Maximize Array Value/1330.java @@ -0,0 +1,26 @@ +class Solution { + public int maxValueAfterReverse(int[] nums) { + int total = 0; + int mn = Integer.MAX_VALUE; + int mx = Integer.MIN_VALUE; + + for (int i = 0; i + 1 < nums.length; ++i) { + final int a = nums[i]; + final int b = nums[i + 1]; + total += Math.abs(a - b); + mn = Math.min(mn, Math.max(a, b)); + mx = Math.max(mx, Math.min(a, b)); + } + int diff = Math.max(0, (mx - mn) * 2); + + for (int i = 0; i + 1 < nums.length; ++i) { + final int a = nums[i]; + final int b = nums[i + 1]; + final int headDiff = -Math.abs(a - b) + Math.abs(nums[0] - b); + final int tailDiff = -Math.abs(a - b) + Math.abs(nums[nums.length - 1] - a); + diff = Math.max(diff, Math.max(headDiff, tailDiff)); + } + + return total + diff; + } +} diff --git a/solutions/1330. Reverse Subarray To Maximize Array Value/1330.py b/solutions/1330. Reverse Subarray To Maximize Array Value/1330.py new file mode 100644 index 00000000000..774ffcf0137 --- /dev/null +++ b/solutions/1330. Reverse Subarray To Maximize Array Value/1330.py @@ -0,0 +1,16 @@ +class Solution: + def maxValueAfterReverse(self, nums: List[int]) -> int: + mn = math.inf + mx = -math.inf + + for a, b in zip(nums, nums[1:]): + mn = min(mn, max(a, b)) + mx = max(mx, min(a, b)) + diff = max(0, (mx - mn) * 2) + + for a, b in zip(nums, nums[1:]): + headDiff = -abs(a - b) + abs(nums[0] - b) + tailDiff = -abs(a - b) + abs(nums[-1] - a) + diff = max(diff, headDiff, tailDiff) + + return sum(abs(a - b) for a, b in zip(nums, nums[1:])) + diff diff --git a/solutions/1331. Rank Transform of an Array/1331.cpp b/solutions/1331. Rank Transform of an Array/1331.cpp new file mode 100644 index 00000000000..c1f2f6998d2 --- /dev/null +++ b/solutions/1331. Rank Transform of an Array/1331.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector arrayRankTransform(vector& arr) { + vector sortedArr(arr); + unordered_map rank; + + ranges::sort(sortedArr); + + for (const int a : sortedArr) + if (!rank.contains(a)) + rank[a] = rank.size() + 1; + + for (int& a : arr) + a = rank[a]; + + return arr; + } +}; diff --git a/solutions/1331. Rank Transform of an Array/1331.java b/solutions/1331. Rank Transform of an Array/1331.java new file mode 100644 index 00000000000..676873bdf6d --- /dev/null +++ b/solutions/1331. Rank Transform of an Array/1331.java @@ -0,0 +1,16 @@ +class Solution { + public int[] arrayRankTransform(int[] arr) { + int[] sortedArr = arr.clone(); + Map rank = new HashMap<>(); + + Arrays.sort(sortedArr); + + for (final int a : sortedArr) + rank.putIfAbsent(a, rank.size() + 1); + + for (int i = 0; i < arr.length; ++i) + arr[i] = rank.get(arr[i]); + + return arr; + } +} diff --git a/solutions/1331. Rank Transform of an Array/1331.py b/solutions/1331. Rank Transform of an Array/1331.py new file mode 100644 index 00000000000..4d1139b7db8 --- /dev/null +++ b/solutions/1331. Rank Transform of an Array/1331.py @@ -0,0 +1,9 @@ +class Solution: + def arrayRankTransform(self, arr: List[int]) -> List[int]: + rank = {} + + for a in sorted(arr): + if a not in rank: + rank[a] = len(rank) + 1 + + return map(rank.get, arr) diff --git a/solutions/1332. Remove Palindromic Subsequences/1332.cpp b/solutions/1332. Remove Palindromic Subsequences/1332.cpp new file mode 100644 index 00000000000..966e4027df7 --- /dev/null +++ b/solutions/1332. Remove Palindromic Subsequences/1332.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int removePalindromeSub(string s) { + return equal(s.begin(), s.end(), s.rbegin()) ? 1 : 2; + } +}; diff --git a/solutions/1332. Remove Palindromic Subsequences/1332.java b/solutions/1332. Remove Palindromic Subsequences/1332.java new file mode 100644 index 00000000000..1ced1ba7462 --- /dev/null +++ b/solutions/1332. Remove Palindromic Subsequences/1332.java @@ -0,0 +1,5 @@ +class Solution { + public int removePalindromeSub(String s) { + return s.equals(new StringBuilder(s).reverse().toString()) ? 1 : 2; + } +} diff --git a/solutions/1332. Remove Palindromic Subsequences/1332.py b/solutions/1332. Remove Palindromic Subsequences/1332.py new file mode 100644 index 00000000000..4d0614e747e --- /dev/null +++ b/solutions/1332. Remove Palindromic Subsequences/1332.py @@ -0,0 +1,3 @@ +class Solution: + def removePalindromeSub(self, s: str) -> int: + return 1 if s == s[::-1] else 2 diff --git a/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.cpp b/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.cpp new file mode 100644 index 00000000000..367f77ca8a1 --- /dev/null +++ b/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector filterRestaurants(vector>& restaurants, + int veganFriendly, int maxPrice, + int maxDistance) { + vector ans; + vector> filtered; + + for (vector& restaurant : restaurants) + if (restaurant[2] >= veganFriendly && restaurant[3] <= maxPrice && + restaurant[4] <= maxDistance) + filtered.push_back(restaurant); + + ranges::sort(filtered, [](const vector& a, const vector& b) { + return a[1] == b[1] ? a[0] > b[0] : a[1] > b[1]; + }); + + for (const vector& f : filtered) + ans.push_back(f[0]); + + return ans; + } +}; diff --git a/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.java b/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.java new file mode 100644 index 00000000000..6951bb21b93 --- /dev/null +++ b/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.java @@ -0,0 +1,10 @@ +class Solution { + public List filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, + int maxDistance) { + return Arrays.stream(restaurants) + .filter(r -> r[2] >= veganFriendly && r[3] <= maxPrice && r[4] <= maxDistance) + .sorted((a, b) -> a[1] == b[1] ? b[0] - a[0] : b[1] - a[1]) + .map(i -> i[0]) + .collect(Collectors.toList()); + } +} diff --git a/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.py b/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.py new file mode 100644 index 00000000000..ca670829e4e --- /dev/null +++ b/solutions/1333. Filter Restaurants by Vegan-Friendly, Price and Distance/1333.py @@ -0,0 +1,4 @@ +class Solution: + def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]: + restaurants.sort(key=lambda r: (-r[1], -r[0])) + return [i for i, _, v, p, d in restaurants if v >= veganFriendly and p <= maxPrice and d <= maxDistance] diff --git a/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.cpp b/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.cpp new file mode 100644 index 00000000000..25baeecc136 --- /dev/null +++ b/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + int ans = -1; + int minCitiesCount = n; + const vector> dist = floydWarshall(n, edges, distanceThreshold); + + for (int i = 0; i < n; ++i) { + int citiesCount = 0; + for (int j = 0; j < n; ++j) + if (dist[i][j] <= distanceThreshold) + ++citiesCount; + if (citiesCount <= minCitiesCount) { + ans = i; + minCitiesCount = citiesCount; + } + } + + return ans; + } + + private: + vector> floydWarshall(int n, const vector>& edges, + int distanceThreshold) { + vector> dist(n, vector(n, distanceThreshold + 1)); + + for (int i = 0; i < n; ++i) + dist[i][i] = 0; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + dist[u][v] = w; + dist[v][u] = w; + } + + for (int k = 0; k < n; ++k) + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); + + return dist; + } +}; diff --git a/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.java b/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.java new file mode 100644 index 00000000000..4e752a35b88 --- /dev/null +++ b/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.java @@ -0,0 +1,43 @@ +class Solution { + public int findTheCity(int n, int[][] edges, int distanceThreshold) { + int ans = -1; + int minCitiesCount = n; + int[][] dist = floydWarshall(n, edges, distanceThreshold); + + for (int i = 0; i < n; ++i) { + int citiesCount = 0; + for (int j = 0; j < n; ++j) + if (dist[i][j] <= distanceThreshold) + ++citiesCount; + if (citiesCount <= minCitiesCount) { + ans = i; + minCitiesCount = citiesCount; + } + } + + return ans; + } + + private int[][] floydWarshall(int n, int[][] edges, int distanceThreshold) { + int[][] dist = new int[n][n]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, distanceThreshold + 1)); + + for (int i = 0; i < n; ++i) + dist[i][i] = 0; + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + dist[u][v] = w; + dist[v][u] = w; + } + + for (int k = 0; k < n; ++k) + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + + return dist; + } +} diff --git a/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.py b/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.py new file mode 100644 index 00000000000..548ad336145 --- /dev/null +++ b/solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.py @@ -0,0 +1,30 @@ +class Solution: + def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: + ans = -1 + minCitiesCount = n + dist = self._floydWarshall(n, edges, distanceThreshold) + + for i in range(n): + citiesCount = sum(dist[i][j] <= distanceThreshold for j in range(n)) + if citiesCount <= minCitiesCount: + ans = i + minCitiesCount = citiesCount + + return ans + + def _floydWarshall(self, n: int, edges: List[List[int]], distanceThreshold: int) -> List[List[int]]: + dist = [[distanceThreshold + 1] * n for _ in range(n)] + + for i in range(n): + dist[i][i] = 0 + + for u, v, w in edges: + dist[u][v] = w + dist[v][u] = w + + for k in range(n): + for i in range(n): + for j in range(n): + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + + return dist diff --git a/solutions/1335. Minimum Difficulty of a Job Schedule/1335.cpp b/solutions/1335. Minimum Difficulty of a Job Schedule/1335.cpp new file mode 100644 index 00000000000..fd804cc84e9 --- /dev/null +++ b/solutions/1335. Minimum Difficulty of a Job Schedule/1335.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minDifficulty(vector& jobDifficulty, int d) { + const int n = jobDifficulty.size(); + if (n < d) + return -1; + + // dp[i][k] := the minimum difficulty to schedule the first i jobs in k days + vector> dp(n + 1, vector(d + 1, INT_MAX / 2)); + dp[0][0] = 0; + + for (int i = 1; i <= n; ++i) + for (int k = 1; k <= d; ++k) { + int maxDifficulty = 0; // max(job[j + 1..i]) + for (int j = i - 1; j >= k - 1; --j) { // 1-based + maxDifficulty = max(maxDifficulty, jobDifficulty[j]); // 0-based + dp[i][k] = min(dp[i][k], dp[j][k - 1] + maxDifficulty); + } + } + + return dp[n][d]; + } +}; diff --git a/solutions/1335. Minimum Difficulty of a Job Schedule/1335.java b/solutions/1335. Minimum Difficulty of a Job Schedule/1335.java new file mode 100644 index 00000000000..9f3f284b9b8 --- /dev/null +++ b/solutions/1335. Minimum Difficulty of a Job Schedule/1335.java @@ -0,0 +1,24 @@ +class Solution { + public int minDifficulty(int[] jobDifficulty, int d) { + final int n = jobDifficulty.length; + if (n < d) + return -1; + + // dp[i][k] := the minimum difficulty to schedule the first i jobs in k days + int[][] dp = new int[n + 1][d + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE / 2)); + dp[0][0] = 0; + + for (int i = 1; i <= n; ++i) + for (int k = 1; k <= d; ++k) { + // max(job[j + 1..i]) + int maxDifficulty = 0; + for (int j = i - 1; j >= k - 1; --j) { // 1-based + maxDifficulty = Math.max(maxDifficulty, jobDifficulty[j]); // 0-based + dp[i][k] = Math.min(dp[i][k], dp[j][k - 1] + maxDifficulty); + } + } + + return dp[n][d]; + } +} diff --git a/solutions/1335. Minimum Difficulty of a Job Schedule/1335.py b/solutions/1335. Minimum Difficulty of a Job Schedule/1335.py new file mode 100644 index 00000000000..e59806cf767 --- /dev/null +++ b/solutions/1335. Minimum Difficulty of a Job Schedule/1335.py @@ -0,0 +1,18 @@ +class Solution: + def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: + n = len(jobDifficulty) + if d > n: + return -1 + + # dp[i][k] := the minimum difficulty to schedule the first i jobs in k days + dp = [[math.inf] * (d + 1) for _ in range(n + 1)] + dp[0][0] = 0 + + for i in range(1, n + 1): + for k in range(1, d + 1): + maxDifficulty = 0 # max(job[j + 1..i]) + for j in range(i - 1, k - 2, -1): # 1-based + maxDifficulty = max(maxDifficulty, jobDifficulty[j]) # 0-based + dp[i][k] = min(dp[i][k], dp[j][k - 1] + maxDifficulty) + + return dp[n][d] diff --git a/solutions/1336. Number of Transactions per Visit/1336.sql b/solutions/1336. Number of Transactions per Visit/1336.sql new file mode 100644 index 00000000000..b3b3849ba55 --- /dev/null +++ b/solutions/1336. Number of Transactions per Visit/1336.sql @@ -0,0 +1,30 @@ +WITH + Users AS ( + SELECT + Visits.user_id, + Visits.visit_date, + COUNT(Transactions.transaction_date) AS transaction_count + FROM Visits + LEFT JOIN Transactions + ON ( + Visits.user_id = Transactions.user_id + AND Visits.visit_date = Transactions.transaction_date) + GROUP BY 1, 2 + ), + RowNumbers AS ( + SELECT ROW_NUMBER() OVER() AS `row_number` + FROM Transactions + UNION ALL + SELECT 0 + ) +SELECT + RowNumbers.`row_number` AS transactions_count, + COUNT(Users.user_id) AS visits_count +FROM RowNumbers +LEFT JOIN Users + ON (RowNumbers.`row_number` = Users.transaction_count) +WHERE RowNumbers.`row_number` <= ( + SELECT MAX(transaction_count) FROM Users + ) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/1337. The K Weakest Rows in a Matrix/1337.cpp b/solutions/1337. The K Weakest Rows in a Matrix/1337.cpp new file mode 100644 index 00000000000..b1a69a30ca2 --- /dev/null +++ b/solutions/1337. The K Weakest Rows in a Matrix/1337.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector kWeakestRows(vector>& mat, int k) { + vector ans; + vector> rowSum; + + for (int i = 0; i < mat.size(); ++i) + rowSum.push_back({accumulate(mat[i].begin(), mat[i].end(), 0), i}); + + ranges::sort(rowSum, [](const vector& a, const vector& b) { + return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]; + }); + + for (int i = 0; i < k; ++i) + ans.push_back(rowSum[i][1]); + + return ans; + } +}; diff --git a/solutions/1337. The K Weakest Rows in a Matrix/1337.java b/solutions/1337. The K Weakest Rows in a Matrix/1337.java new file mode 100644 index 00000000000..10232ec50f4 --- /dev/null +++ b/solutions/1337. The K Weakest Rows in a Matrix/1337.java @@ -0,0 +1,18 @@ +class Solution { + public int[] kWeakestRows(int[][] mat, int k) { + int[] ans = new int[k]; + int[][] candidates = new int[mat.length][2]; + + for (int i = 0; i < mat.length; ++i) { + candidates[i][0] = IntStream.of(mat[i]).sum(); + candidates[i][1] = i; + } + + Arrays.sort(candidates, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + + for (int i = 0; i < k; ++i) + ans[i] = candidates[i][1]; + + return ans; + } +} diff --git a/solutions/1337. The K Weakest Rows in a Matrix/1337.py b/solutions/1337. The K Weakest Rows in a Matrix/1337.py new file mode 100644 index 00000000000..8e33b560c4d --- /dev/null +++ b/solutions/1337. The K Weakest Rows in a Matrix/1337.py @@ -0,0 +1,10 @@ +class Solution: + def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: + candidates = [] + + for i, row in enumerate(mat): + candidates.append([sum(row), i]) + + candidates.sort(key=lambda c: (c[0], c[1])) + + return [i for _, i in candidates[:k]] diff --git a/solutions/1338. Reduce Array Size to The Half/1338.cpp b/solutions/1338. Reduce Array Size to The Half/1338.cpp new file mode 100644 index 00000000000..70faad60fcb --- /dev/null +++ b/solutions/1338. Reduce Array Size to The Half/1338.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int minSetSize(vector& arr) { + const int n = arr.size(); + int sum = 0; + unordered_map map; + vector> count; + + for (const int a : arr) + ++map[a]; + + for (const auto& [a, freq] : map) + count.push_back(make_pair(a, freq)); + + ranges::sort(count, [](const pair& a, const pair& b) { + return a.second > b.second; + }); + + for (int i = 0; i < count.size(); ++i) { + sum += count[i].second; + if (sum >= n / 2) + return i + 1; + } + + throw; + } +}; diff --git a/solutions/1338. Reduce Array Size to The Half/1338.java b/solutions/1338. Reduce Array Size to The Half/1338.java new file mode 100644 index 00000000000..2464c1f371c --- /dev/null +++ b/solutions/1338. Reduce Array Size to The Half/1338.java @@ -0,0 +1,28 @@ +class Solution { + public int minSetSize(int[] arr) { + final int n = arr.length; + int sum = 0; + Map map = new HashMap<>(); + + for (final int a : arr) + map.merge(a, 1, Integer::sum); + + int[][] count = new int[map.size()][2]; + int i = 0; + + for (final int key : map.keySet()) { + count[i][0] = key; + count[i++][1] = map.get(key); + } + + Arrays.sort(count, (c1, c2) -> c2[1] - c1[1]); + + for (i = 0; i < count.length; ++i) { + sum += count[i][1]; + if (sum >= n / 2) + return i + 1; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1338. Reduce Array Size to The Half/1338.py b/solutions/1338. Reduce Array Size to The Half/1338.py new file mode 100644 index 00000000000..4ac2c3c22b5 --- /dev/null +++ b/solutions/1338. Reduce Array Size to The Half/1338.py @@ -0,0 +1,12 @@ +class Solution: + def minSetSize(self, arr: List[int]) -> int: + n = len(arr) + + count = collections.Counter(arr).most_common() + count.sort(key=lambda c: -c[1]) + + summ = 0 + for i, c in enumerate(count): + summ += c[1] + if summ >= n // 2: + return i + 1 diff --git a/solutions/1339. Maximum Product of Splitted Binary Tree/1339.cpp b/solutions/1339. Maximum Product of Splitted Binary Tree/1339.cpp new file mode 100644 index 00000000000..a08708dcc03 --- /dev/null +++ b/solutions/1339. Maximum Product of Splitted Binary Tree/1339.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maxProduct(TreeNode* root) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + vector allSums; + const long totalSum = treeSum(root, allSums); + + for (const long sum : allSums) + ans = max(ans, sum * (totalSum - sum)); + + return ans % kMod; + } + + private: + int treeSum(TreeNode* root, vector& allSums) { + if (root == nullptr) + return 0; + + const int leftSum = treeSum(root->left, allSums); + const int rightSum = treeSum(root->right, allSums); + const int sum = root->val + leftSum + rightSum; + allSums.push_back(sum); + return sum; + } +}; diff --git a/solutions/1339. Maximum Product of Splitted Binary Tree/1339.java b/solutions/1339. Maximum Product of Splitted Binary Tree/1339.java new file mode 100644 index 00000000000..b91bb38b9e8 --- /dev/null +++ b/solutions/1339. Maximum Product of Splitted Binary Tree/1339.java @@ -0,0 +1,24 @@ +class Solution { + public int maxProduct(TreeNode root) { + final int kMod = 1_000_000_007; + long ans = 0; + List allSums = new ArrayList<>(); + final long totalSum = treeSum(root, allSums); + + for (final long sum : allSums) + ans = Math.max(ans, sum * (totalSum - sum)); + + return (int) (ans % kMod); + } + + private int treeSum(TreeNode root, List allSums) { + if (root == null) + return 0; + + final int leftSum = treeSum(root.left, allSums); + final int rightSum = treeSum(root.right, allSums); + final int sum = root.val + leftSum + rightSum; + allSums.add(sum); + return sum; + } +} diff --git a/solutions/134. Gas Station/134.cpp b/solutions/134. Gas Station/134.cpp new file mode 100644 index 00000000000..3c17765d580 --- /dev/null +++ b/solutions/134. Gas Station/134.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int canCompleteCircuit(vector& gas, vector& cost) { + const int gasSum = accumulate(gas.begin(), gas.end(), 0); + const int costSum = accumulate(cost.begin(), cost.end(), 0); + if (gasSum - costSum < 0) + return -1; + + int ans = 0; + int sum = 0; + + // Try to start from each index. + for (int i = 0; i < gas.size(); ++i) { + sum += gas[i] - cost[i]; + if (sum < 0) { + sum = 0; + ans = i + 1; // Start from the next index. + } + } + + return ans; + } +}; diff --git a/solutions/134. Gas Station/134.java b/solutions/134. Gas Station/134.java new file mode 100644 index 00000000000..bcbe9121d7d --- /dev/null +++ b/solutions/134. Gas Station/134.java @@ -0,0 +1,22 @@ +class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + final int gasSum = Arrays.stream(gas).sum(); + final int costSum = Arrays.stream(cost).sum(); + if (gasSum - costSum < 0) + return -1; + + int ans = 0; + int sum = 0; + + // Try to start from each index. + for (int i = 0; i < gas.length; ++i) { + sum += gas[i] - cost[i]; + if (sum < 0) { + sum = 0; + ans = i + 1; // Start from the next index. + } + } + + return ans; + } +} diff --git a/solutions/134. Gas Station/134.py b/solutions/134. Gas Station/134.py new file mode 100644 index 00000000000..2b6e3edf93d --- /dev/null +++ b/solutions/134. Gas Station/134.py @@ -0,0 +1,15 @@ +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + ans = 0 + net = 0 + summ = 0 + + # Try to start from each index. + for i in range(len(gas)): + net += gas[i] - cost[i] + summ += gas[i] - cost[i] + if summ < 0: + summ = 0 + ans = i + 1 # Start from the next index. + + return -1 if net < 0 else ans diff --git a/solutions/1340. Jump Game V/1340.cpp b/solutions/1340. Jump Game V/1340.cpp new file mode 100644 index 00000000000..abefb7c4194 --- /dev/null +++ b/solutions/1340. Jump Game V/1340.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maxJumps(vector& arr, int d) { + const int n = arr.size(); + // dp[i] := the maximum jumps starting from arr[i] + vector dp(n, 1); + // a dcreasing stack that stores indices + stack stack; + + for (int i = 0; i <= n; ++i) { + while (!stack.empty() && (i == n || arr[stack.top()] < arr[i])) { + vector indices{stack.top()}; + stack.pop(); + while (!stack.empty() && arr[stack.top()] == arr[indices[0]]) + indices.push_back(stack.top()), stack.pop(); + for (const int j : indices) { + if (i < n && i - j <= d) + // Can jump from i to j. + dp[i] = max(dp[i], dp[j] + 1); + if (!stack.empty() && j - stack.top() <= d) + // Can jump from stack[-1] to j. + dp[stack.top()] = max(dp[stack.top()], dp[j] + 1); + } + } + stack.push(i); + } + + return ranges::max(dp); + } +}; diff --git a/solutions/1340. Jump Game V/1340.java b/solutions/1340. Jump Game V/1340.java new file mode 100644 index 00000000000..06bd5731f8e --- /dev/null +++ b/solutions/1340. Jump Game V/1340.java @@ -0,0 +1,28 @@ +class Solution { + public int maxJumps(int[] arr, int d) { + final int n = arr.length; + // dp[i] := the maximum jumps starting from arr[i] + int[] dp = new int[n]; + // a dcreasing stack that stores indices + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i <= n; ++i) { + while (!stack.isEmpty() && (i == n || arr[stack.peek()] < arr[i])) { + List indices = new ArrayList<>(Arrays.asList(stack.pop())); + while (!stack.isEmpty() && arr[stack.peek()] == arr[indices.get(0)]) + indices.add(stack.pop()); + for (final int j : indices) { + if (i < n && i - j <= d) + // Can jump from i to j. + dp[i] = Math.max(dp[i], dp[j] + 1); + if (!stack.isEmpty() && j - stack.peek() <= d) + // Can jump from stack.peek() to j + dp[stack.peek()] = Math.max(dp[stack.peek()], dp[j] + 1); + } + } + stack.push(i); + } + + return Arrays.stream(dp).max().getAsInt() + 1; + } +} diff --git a/solutions/1340. Jump Game V/1340.py b/solutions/1340. Jump Game V/1340.py new file mode 100644 index 00000000000..96cf02b3d12 --- /dev/null +++ b/solutions/1340. Jump Game V/1340.py @@ -0,0 +1,23 @@ +class Solution: + def maxJumps(self, arr: List[int], d: int) -> int: + n = len(arr) + # dp[i] := the maximum jumps starting from arr[i] + dp = [1] * n + # a dcreasing stack that stores indices + stack = [] + + for i in range(n + 1): + while stack and (i == n or arr[stack[-1]] < arr[i]): + indices = [stack.pop()] + while stack and arr[stack[-1]] == arr[indices[0]]: + indices.append(stack.pop()) + for j in indices: + if i < n and i - j <= d: + # Can jump from i to j. + dp[i] = max(dp[i], dp[j] + 1) + if stack and j - stack[-1] <= d: + # Can jump from stack[-1] to j + dp[stack[-1]] = max(dp[stack[-1]], dp[j] + 1) + stack.append(i) + + return max(dp) diff --git a/solutions/1341. Movie Rating/1341.sql b/solutions/1341. Movie Rating/1341.sql new file mode 100644 index 00000000000..e9fa4e8a441 --- /dev/null +++ b/solutions/1341. Movie Rating/1341.sql @@ -0,0 +1,20 @@ +( + SELECT Users.name AS results + FROM MovieRating + INNER JOIN Users + USING (user_id) + GROUP BY user_id + ORDER BY COUNT(MovieRating.movie_id) DESC, Users.name + LIMIT 1 +) +UNION ALL +( + SELECT Movies.title AS results + FROM MovieRating + INNER JOIN Movies + USING (movie_id) + WHERE DATE_FORMAT(created_at, '%Y-%m') = '2020-02' + GROUP BY movie_id + ORDER BY AVG(MovieRating.rating) DESC, Movies.title + LIMIT 1 +); diff --git a/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.cpp b/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.cpp new file mode 100644 index 00000000000..92c2b48dc73 --- /dev/null +++ b/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int numberOfSteps(unsigned num) { + if (num == 0) + return 0; + const int subtractSteps = popcount(num); + const int divideSteps = 31 - __builtin_clz(num); + return subtractSteps + divideSteps; + } +}; diff --git a/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.java b/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.java new file mode 100644 index 00000000000..86b330d18b2 --- /dev/null +++ b/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.java @@ -0,0 +1,9 @@ +public class Solution { + public int numberOfSteps(int num) { + if (num == 0) + return 0; + final int subtractSteps = Integer.bitCount(num); + final int divideSteps = 31 - Integer.numberOfLeadingZeros(num); + return subtractSteps + divideSteps; + } +} diff --git a/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.py b/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.py new file mode 100644 index 00000000000..6ca2f9eee9e --- /dev/null +++ b/solutions/1342. Number of Steps to Reduce a Number to Zero/1342.py @@ -0,0 +1,7 @@ +class Solution: + def numberOfSteps(self, num: int) -> int: + if num == 0: + return 0 + subtractSteps = num.bit_count() + divideSteps = num.bit_length() - 1 + return subtractSteps + divideSteps diff --git a/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.cpp b/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.cpp new file mode 100644 index 00000000000..c1b6a4522da --- /dev/null +++ b/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int numOfSubarrays(vector& arr, int k, int threshold) { + int ans = 0; + int windowSum = 0; + + for (int i = 0; i < arr.size(); ++i) { + windowSum += arr[i]; + if (i >= k) + windowSum -= arr[i - k]; + if (i >= k - 1 && windowSum / k >= threshold) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.java b/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.java new file mode 100644 index 00000000000..33c882eb389 --- /dev/null +++ b/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.java @@ -0,0 +1,16 @@ +class Solution { + public int numOfSubarrays(int[] arr, int k, int threshold) { + int ans = 0; + int windowSum = 0; + + for (int i = 0; i < arr.length; ++i) { + windowSum += arr[i]; + if (i >= k) + windowSum -= arr[i - k]; + if (i >= k - 1 && windowSum / k >= threshold) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.py b/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.py new file mode 100644 index 00000000000..7f508e8e27c --- /dev/null +++ b/solutions/1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/1343.py @@ -0,0 +1,13 @@ +class Solution: + def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: + ans = 0 + windowSum = 0 + + for i in range(len(arr)): + windowSum += arr[i] + if i >= k: + windowSum -= arr[i - k] + if i >= k - 1 and windowSum // k >= threshold: + ans += 1 + + return ans diff --git a/solutions/1344. Angle Between Hands of a Clock/1344.cpp b/solutions/1344. Angle Between Hands of a Clock/1344.cpp new file mode 100644 index 00000000000..9accae47991 --- /dev/null +++ b/solutions/1344. Angle Between Hands of a Clock/1344.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + double angleClock(int hour, int minutes) { + const double hourHand = (hour % 12 + minutes / 60.0) * 30; + const double minuteHand = minutes * 6; + const double diff = abs(hourHand - minuteHand); + return min(diff, 360 - diff); + } +}; diff --git a/solutions/1344. Angle Between Hands of a Clock/1344.java b/solutions/1344. Angle Between Hands of a Clock/1344.java new file mode 100644 index 00000000000..449d2a74d01 --- /dev/null +++ b/solutions/1344. Angle Between Hands of a Clock/1344.java @@ -0,0 +1,8 @@ +class Solution { + public double angleClock(int hour, int minutes) { + final double hourHand = (hour % 12 + minutes / 60.0) * 30; + final double minuteHand = minutes * 6; + final double diff = Math.abs(hourHand - minuteHand); + return Math.min(diff, 360 - diff); + } +} diff --git a/solutions/1344. Angle Between Hands of a Clock/1344.py b/solutions/1344. Angle Between Hands of a Clock/1344.py new file mode 100644 index 00000000000..6bc6fad13b5 --- /dev/null +++ b/solutions/1344. Angle Between Hands of a Clock/1344.py @@ -0,0 +1,7 @@ +class Solution: + def angleClock(self, hour: int, minutes: int) -> float: + hourAngle = (hour % 12) * 30 + minutes * 0.5 + minuteAngle = minutes * 6 + ans = abs(hourAngle - minuteAngle) + + return min(ans, 360 - ans) diff --git a/solutions/1345. Jump Game IV/1345.cpp b/solutions/1345. Jump Game IV/1345.cpp new file mode 100644 index 00000000000..ce4af1580b8 --- /dev/null +++ b/solutions/1345. Jump Game IV/1345.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int minJumps(vector& arr) { + const int n = arr.size(); + // {a: indices} + unordered_map> graph; + queue q{{0}}; + vector seen(n); + seen[0] = true; + + for (int i = 0; i < n; ++i) + graph[arr[i]].push_back(i); + + for (int step = 0; !q.empty(); ++step) { + for (int sz = q.size(); sz > 0; --sz) { + const int i = q.front(); + q.pop(); + if (i == n - 1) + return step; + seen[i] = true; + const int u = arr[i]; + if (i + 1 < n) + graph[u].push_back(i + 1); + if (i - 1 >= 0) + graph[u].push_back(i - 1); + for (const int v : graph[u]) { + if (seen[v]) + continue; + q.push(v); + } + graph[u].clear(); + } + } + + throw; + } +}; diff --git a/solutions/1345. Jump Game IV/1345.java b/solutions/1345. Jump Game IV/1345.java new file mode 100644 index 00000000000..b95218a2405 --- /dev/null +++ b/solutions/1345. Jump Game IV/1345.java @@ -0,0 +1,37 @@ +class Solution { + public int minJumps(int[] arr) { + final int n = arr.length; + // {a: indices} + Map> graph = new HashMap<>(); + Queue q = new ArrayDeque<>(Arrays.asList(0)); + boolean[] seen = new boolean[n]; + seen[0] = true; + + for (int i = 0; i < n; ++i) { + graph.putIfAbsent(arr[i], new ArrayList<>()); + graph.get(arr[i]).add(i); + } + + for (int step = 0; !q.isEmpty(); ++step) { + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.poll(); + if (i == n - 1) + return step; + seen[i] = true; + final int u = arr[i]; + if (i + 1 < n) + graph.get(u).add(i + 1); + if (i - 1 >= 0) + graph.get(u).add(i - 1); + for (final int v : graph.get(u)) { + if (seen[v]) + continue; + q.offer(v); + } + graph.get(u).clear(); + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1345. Jump Game IV/1345.py b/solutions/1345. Jump Game IV/1345.py new file mode 100644 index 00000000000..0e0ecb3b09f --- /dev/null +++ b/solutions/1345. Jump Game IV/1345.py @@ -0,0 +1,29 @@ +class Solution: + def minJumps(self, arr: List[int]) -> int: + n = len(arr) + # {num: indices} + graph = collections.defaultdict(list) + step = 0 + q = collections.deque([0]) + seen = {0} + + for i, a in enumerate(arr): + graph[a].append(i) + + while q: + for _ in range(len(q)): + i = q.popleft() + if i == n - 1: + return step + seen.add(i) + u = arr[i] + if i + 1 < n: + graph[u].append(i + 1) + if i - 1 >= 0: + graph[u].append(i - 1) + for v in graph[u]: + if v in seen: + continue + q.append(v) + graph[u].clear() + step += 1 diff --git a/solutions/1346. Check If N and Its Double Exist/1346.cpp b/solutions/1346. Check If N and Its Double Exist/1346.cpp new file mode 100644 index 00000000000..34a1ace4e8a --- /dev/null +++ b/solutions/1346. Check If N and Its Double Exist/1346.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + bool checkIfExist(vector& arr) { + unordered_set seen; + + for (const int a : arr) { + if (seen.contains(a * 2) || a % 2 == 0 && seen.contains(a / 2)) + return true; + seen.insert(a); + } + + return false; + } +}; diff --git a/solutions/1346. Check If N and Its Double Exist/1346.java b/solutions/1346. Check If N and Its Double Exist/1346.java new file mode 100644 index 00000000000..36fa18ac15a --- /dev/null +++ b/solutions/1346. Check If N and Its Double Exist/1346.java @@ -0,0 +1,13 @@ +class Solution { + public boolean checkIfExist(int[] arr) { + Set seen = new HashSet<>(); + + for (final int a : arr) { + if (seen.contains(a * 2) || a % 2 == 0 && seen.contains(a / 2)) + return true; + seen.add(a); + } + + return false; + } +} diff --git a/solutions/1346. Check If N and Its Double Exist/1346.py b/solutions/1346. Check If N and Its Double Exist/1346.py new file mode 100644 index 00000000000..c228db861c2 --- /dev/null +++ b/solutions/1346. Check If N and Its Double Exist/1346.py @@ -0,0 +1,10 @@ +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + seen = set() + + for a in arr: + if a * 2 in seen or a % 2 == 0 and a // 2 in seen: + return True + seen.add(a) + + return False diff --git a/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.cpp b/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.cpp new file mode 100644 index 00000000000..c74a87f2616 --- /dev/null +++ b/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minSteps(string s, string t) { + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + for (const char c : t) + --count[c - 'a']; + + return accumulate(count.begin(), count.end(), 0, [](int subtotal, int c) { + return subtotal + abs(c); + }) / 2; + } +}; diff --git a/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.java b/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.java new file mode 100644 index 00000000000..c19ee1bdf88 --- /dev/null +++ b/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.java @@ -0,0 +1,13 @@ +class Solution { + public int minSteps(String s, String t) { + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (final char c : t.toCharArray()) + --count[c - 'a']; + + return Arrays.stream(count).map(Math::abs).sum() / 2; + } +} diff --git a/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.py b/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.py new file mode 100644 index 00000000000..02d6e4688fd --- /dev/null +++ b/solutions/1347. Minimum Number of Steps to Make Two Strings Anagram/1347.py @@ -0,0 +1,5 @@ +class Solution: + def minSteps(self, s: str, t: str) -> int: + count = collections.Counter(s) + count.subtract(collections.Counter(t)) + return sum(abs(value) for value in count.values()) // 2 diff --git a/solutions/1348. Tweet Counts Per Frequency/1348.cpp b/solutions/1348. Tweet Counts Per Frequency/1348.cpp new file mode 100644 index 00000000000..07c53a9968a --- /dev/null +++ b/solutions/1348. Tweet Counts Per Frequency/1348.cpp @@ -0,0 +1,25 @@ +class TweetCounts { + public: + void recordTweet(string tweetName, int time) { + ++tweetNameToTimeCount[tweetName][time]; + } + + vector getTweetCountsPerFrequency(string freq, string tweetName, + int startTime, int endTime) { + const int chunkSize = freq == "minute" ? 60 : freq == "hour" ? 3600 : 86400; + vector counts((endTime - startTime) / chunkSize + 1); + const map& timeCount = tweetNameToTimeCount[tweetName]; + const auto lo = timeCount.lower_bound(startTime); + const auto hi = timeCount.upper_bound(endTime); + + for (auto it = lo; it != hi; ++it) { + const int index = (it->first - startTime) / chunkSize; + counts[index] += it->second; + } + + return counts; + } + + private: + unordered_map> tweetNameToTimeCount; +}; diff --git a/solutions/1348. Tweet Counts Per Frequency/1348.java b/solutions/1348. Tweet Counts Per Frequency/1348.java new file mode 100644 index 00000000000..363399eb32f --- /dev/null +++ b/solutions/1348. Tweet Counts Per Frequency/1348.java @@ -0,0 +1,22 @@ +class TweetCounts { + public void recordTweet(String tweetName, int time) { + tweetNameToTimeCount.putIfAbsent(tweetName, new TreeMap<>()); + tweetNameToTimeCount.get(tweetName).merge(time, 1, Integer::sum); + } + + public List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, + int endTime) { + final int chunkSize = freq.equals("minute") ? 60 : freq.equals("hour") ? 3600 : 86400; + int[] counts = new int[(endTime - startTime) / chunkSize + 1]; + TreeMap timeCount = tweetNameToTimeCount.get(tweetName); + + for (Map.Entry entry : timeCount.subMap(startTime, endTime + 1).entrySet()) { + final int index = (entry.getKey() - startTime) / chunkSize; + counts[index] += entry.getValue(); + } + + return Arrays.stream(counts).boxed().collect(Collectors.toList()); + } + + private Map> tweetNameToTimeCount = new HashMap<>(); +} diff --git a/solutions/1348. Tweet Counts Per Frequency/1348.py b/solutions/1348. Tweet Counts Per Frequency/1348.py new file mode 100644 index 00000000000..3fd9220d9db --- /dev/null +++ b/solutions/1348. Tweet Counts Per Frequency/1348.py @@ -0,0 +1,21 @@ +from sortedcontainers import SortedList + + +class TweetCounts: + def __init__(self): + self.tweetNameToTimes = collections.defaultdict(SortedList) + + def recordTweet(self, tweetName: str, time: int) -> None: + self.tweetNameToTimes[tweetName].add(time) + + def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]: + counts = [] + times = self.tweetNameToTimes[tweetName] + chunk = 60 if freq == 'minute' else 3600 if freq == 'hour' else 86400 + + # I := startTime of each chunk + for i in range(startTime, endTime + 1, chunk): + j = min(i + chunk, endTime + 1) # EndTime of each chunk + counts.append(bisect_left(times, j) - bisect_left(times, i)) + + return counts diff --git a/solutions/1349. Maximum Students Taking Exam/1349.cpp b/solutions/1349. Maximum Students Taking Exam/1349.cpp new file mode 100644 index 00000000000..7fb306002ea --- /dev/null +++ b/solutions/1349. Maximum Students Taking Exam/1349.cpp @@ -0,0 +1,55 @@ +class Solution { + public: + int maxStudents(vector>& seats) { + return accumulate(seats.begin(), seats.end(), 0, + [&](int subtotal, const auto& seat) { + return subtotal + ranges::count(seat, '.'); + }) - hungarian(seats); + } + + private: + const vector> dirs{{-1, -1}, {0, -1}, {1, -1}, + {-1, 1}, {0, 1}, {1, 1}}; + + int hungarian(const vector>& seats) { + const int m = seats.size(); + const int n = seats[0].size(); + int count = 0; + vector> seen(m, vector(n)); + vector> match(m, vector(n, -1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (seats[i][j] == '.' && match[i][j] == -1) { + const int sessionId = i * n + j; + seen[i][j] = sessionId; + count += dfs(seats, i, j, sessionId, seen, match); + } + + return count; + } + + int dfs(const vector>& seats, int i, int j, int sessionId, + vector>& seen, vector>& match) { + const int m = seats.size(); + const int n = seats[0].size(); + + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seats[x][y] != '.' || seen[x][y] == sessionId) + continue; + seen[x][y] = sessionId; + if (match[x][y] == -1 || dfs(seats, match[x][y] / n, match[x][y] % n, + sessionId, seen, match)) { + match[x][y] = i * n + j; + match[i][j] = x * n + y; + return 1; + } + } + + return 0; + } +}; diff --git a/solutions/1349. Maximum Students Taking Exam/1349.java b/solutions/1349. Maximum Students Taking Exam/1349.java new file mode 100644 index 00000000000..b9585bd2dde --- /dev/null +++ b/solutions/1349. Maximum Students Taking Exam/1349.java @@ -0,0 +1,57 @@ +class Solution { + public int maxStudents(char[][] seats) { + int studentsCount = 0; + + for (char[] seat : seats) + for (final char s : seat) + if (s == '.') + ++studentsCount; + + return studentsCount - hungarian(seats); + } + + private static final int[][] dirs = {{-1, -1}, {0, -1}, {1, -1}, {-1, 1}, {0, 1}, {1, 1}}; + + private int hungarian(char[][] seats) { + final int m = seats.length; + final int n = seats[0].length; + int count = 0; + int[][] seen = new int[m][n]; + int[][] match = new int[m][n]; + Arrays.stream(match).forEach(A -> Arrays.fill(A, -1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (seats[i][j] == '.' && match[i][j] == -1) { + final int sessionId = i * n + j; + seen[i][j] = sessionId; + if (dfs(seats, i, j, sessionId, seen, match)) + ++count; + } + + return count; + } + + private boolean dfs(char[][] seats, int i, int j, int sessionId, int[][] seen, int[][] match) { + final int m = seats.length; + final int n = seats[0].length; + + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seats[x][y] != '.' || seen[x][y] == sessionId) + continue; + seen[x][y] = sessionId; + if (match[x][y] == -1 || + dfs(seats, match[x][y] / n, match[x][y] % n, sessionId, seen, match)) { + match[x][y] = i * n + j; + match[i][j] = x * n + y; + return true; + } + } + + return false; + } +} diff --git a/solutions/1349. Maximum Students Taking Exam/1349.py b/solutions/1349. Maximum Students Taking Exam/1349.py new file mode 100644 index 00000000000..8fe950ff378 --- /dev/null +++ b/solutions/1349. Maximum Students Taking Exam/1349.py @@ -0,0 +1,36 @@ +class Solution: + def maxStudents(self, seats: List[List[str]]) -> int: + m = len(seats) + n = len(seats[0]) + dirs = ((-1, -1), (0, -1), (1, -1), (-1, 1), (0, 1), (1, 1)) + seen = [[0] * n for _ in range(m)] + match = [[-1] * n for _ in range(m)] + + def dfs(i: int, j: int, sessionId: int) -> int: + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if seats[x][y] != '.' or seen[x][y] == sessionId: + continue + seen[x][y] = sessionId + if match[x][y] == -1 or dfs(*divmod(match[x][y], n), sessionId): + match[x][y] = i * n + j + match[i][j] = x * n + y + return 1 + return 0 + + def hungarian() -> int: + count = 0 + for i in range(m): + for j in range(n): + if seats[i][j] == '.' and match[i][j] == -1: + sessionId = i * n + j + seen[i][j] = sessionId + count += dfs(i, j, sessionId) + return count + + return sum(seats[i][j] == '.' + for i in range(m) + for j in range(n)) - hungarian() diff --git a/solutions/135. Candy/135.cpp b/solutions/135. Candy/135.cpp new file mode 100644 index 00000000000..392dbbced66 --- /dev/null +++ b/solutions/135. Candy/135.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int candy(vector& ratings) { + const int n = ratings.size(); + int ans = 0; + vector l(n, 1); + vector r(n, 1); + + for (int i = 1; i < n; ++i) + if (ratings[i] > ratings[i - 1]) + l[i] = l[i - 1] + 1; + + for (int i = n - 2; i >= 0; --i) + if (ratings[i] > ratings[i + 1]) + r[i] = r[i + 1] + 1; + + for (int i = 0; i < n; ++i) + ans += max(l[i], r[i]); + + return ans; + } +}; diff --git a/solutions/135. Candy/135.java b/solutions/135. Candy/135.java new file mode 100644 index 00000000000..89331237cd1 --- /dev/null +++ b/solutions/135. Candy/135.java @@ -0,0 +1,24 @@ +class Solution { + public int candy(int[] ratings) { + final int n = ratings.length; + + int ans = 0; + int[] l = new int[n]; + int[] r = new int[n]; + Arrays.fill(l, 1); + Arrays.fill(r, 1); + + for (int i = 1; i < n; ++i) + if (ratings[i] > ratings[i - 1]) + l[i] = l[i - 1] + 1; + + for (int i = n - 2; i >= 0; --i) + if (ratings[i] > ratings[i + 1]) + r[i] = r[i + 1] + 1; + + for (int i = 0; i < n; ++i) + ans += Math.max(l[i], r[i]); + + return ans; + } +} diff --git a/solutions/135. Candy/135.py b/solutions/135. Candy/135.py new file mode 100644 index 00000000000..0b2f1485632 --- /dev/null +++ b/solutions/135. Candy/135.py @@ -0,0 +1,20 @@ +class Solution: + def candy(self, ratings: List[int]) -> int: + n = len(ratings) + + ans = 0 + l = [1] * n + r = [1] * n + + for i in range(1, n): + if ratings[i] > ratings[i - 1]: + l[i] = l[i - 1] + 1 + + for i in range(n - 2, -1, -1): + if ratings[i] > ratings[i + 1]: + r[i] = r[i + 1] + 1 + + for a, b in zip(l, r): + ans += max(a, b) + + return ans diff --git a/solutions/1350. Students With Invalid Departments/1350.sql b/solutions/1350. Students With Invalid Departments/1350.sql new file mode 100644 index 00000000000..14c1de53473 --- /dev/null +++ b/solutions/1350. Students With Invalid Departments/1350.sql @@ -0,0 +1,7 @@ +SELECT + Students.id, + Students.name +FROM Students +LEFT JOIN Departments + ON (Students.department_id = Departments.id) +WHERE Departments.id IS NULL; diff --git a/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.cpp b/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.cpp new file mode 100644 index 00000000000..1a743098bed --- /dev/null +++ b/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countNegatives(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + int i = m - 1; + int j = 0; + + while (i >= 0 && j < n) { + if (grid[i][j] < 0) { + ans += n - j; + --i; + } else { + ++j; + } + } + + return ans; + } +}; diff --git a/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.java b/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.java new file mode 100644 index 00000000000..4eb202049f9 --- /dev/null +++ b/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.java @@ -0,0 +1,20 @@ +class Solution { + public int countNegatives(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + int i = m - 1; + int j = 0; + + while (i >= 0 && j < n) { + if (grid[i][j] < 0) { + ans += n - j; + --i; + } else { + ++j; + } + } + + return ans; + } +} diff --git a/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.py b/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.py new file mode 100644 index 00000000000..910f8dd1645 --- /dev/null +++ b/solutions/1351. Count Negative Numbers in a Sorted Matrix/1351.py @@ -0,0 +1,16 @@ +class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + ans = 0 + i = m - 1 + j = 0 + + while i >= 0 and j < n: + if grid[i][j] < 0: + ans += n - j + i -= 1 + else: + j += 1 + + return ans diff --git a/solutions/1352. Product of the Last K Numbers/1352.cpp b/solutions/1352. Product of the Last K Numbers/1352.cpp new file mode 100644 index 00000000000..39ecd8651c3 --- /dev/null +++ b/solutions/1352. Product of the Last K Numbers/1352.cpp @@ -0,0 +1,19 @@ +class ProductOfNumbers { + public: + ProductOfNumbers() : prefix{1} {} + + void add(int num) { + if (num == 0) + prefix = {1}; + else + prefix.push_back(prefix.back() * num); + } + + int getProduct(int k) { + return k >= prefix.size() ? 0 + : prefix.back() / prefix[prefix.size() - k - 1]; + } + + private: + vector prefix; +}; diff --git a/solutions/1352. Product of the Last K Numbers/1352.java b/solutions/1352. Product of the Last K Numbers/1352.java new file mode 100644 index 00000000000..344b394a28c --- /dev/null +++ b/solutions/1352. Product of the Last K Numbers/1352.java @@ -0,0 +1,19 @@ +class ProductOfNumbers { + public ProductOfNumbers() { + prefix = new ArrayList<>(Arrays.asList(1)); + } + + public void add(int num) { + if (num == 0) + prefix = new ArrayList<>(Arrays.asList(1)); + else + prefix.add(prefix.get(prefix.size() - 1) * num); + } + + public int getProduct(int k) { + return k >= prefix.size() ? 0 + : prefix.get(prefix.size() - 1) / prefix.get(prefix.size() - k - 1); + } + + private List prefix = new ArrayList<>(); +} diff --git a/solutions/1352. Product of the Last K Numbers/1352.py b/solutions/1352. Product of the Last K Numbers/1352.py new file mode 100644 index 00000000000..66db23a88c5 --- /dev/null +++ b/solutions/1352. Product of the Last K Numbers/1352.py @@ -0,0 +1,12 @@ +class ProductOfNumbers: + def __init__(self): + self.prefix = [1] + + def add(self, num: int) -> None: + if num == 0: + self.prefix = [1] + else: + self.prefix.append(self.prefix[-1] * num) + + def getProduct(self, k: int) -> int: + return 0 if k >= len(self.prefix) else self.prefix[-1] // self.prefix[len(self.prefix) - k - 1] diff --git a/solutions/1353. Maximum Number of Events That Can Be Attended/1353.cpp b/solutions/1353. Maximum Number of Events That Can Be Attended/1353.cpp new file mode 100644 index 00000000000..842ede4f7f9 --- /dev/null +++ b/solutions/1353. Maximum Number of Events That Can Be Attended/1353.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int maxEvents(vector>& events) { + int ans = 0; + int d = 0; // the current day + int i = 0; // events' index + priority_queue, greater<>> minHeap; + + ranges::sort(events); + + while (!minHeap.empty() || i < events.size()) { + // If no events are available to attend today, let time flies to the next + // available event. + if (minHeap.empty()) + d = events[i][0]; + // All the events starting from today are newly available. + while (i < events.size() && events[i][0] == d) + minHeap.push(events[i++][1]); + // Greedily attend the event that'll end the earliest since it has higher + // chance can't be attended in the future. + minHeap.pop(); + ++ans; + ++d; + // Pop the events that can't be attended. + while (!minHeap.empty() && minHeap.top() < d) + minHeap.pop(); + } + + return ans; + } +}; diff --git a/solutions/1353. Maximum Number of Events That Can Be Attended/1353.java b/solutions/1353. Maximum Number of Events That Can Be Attended/1353.java new file mode 100644 index 00000000000..b20f5099d97 --- /dev/null +++ b/solutions/1353. Maximum Number of Events That Can Be Attended/1353.java @@ -0,0 +1,30 @@ +class Solution { + public int maxEvents(int[][] events) { + int ans = 0; + int d = 0; // the current day + int i = 0; // events' index + Queue minHeap = new PriorityQueue<>(); + + Arrays.sort(events, (a, b) -> a[0] - b[0]); + + while (!minHeap.isEmpty() || i < events.length) { + // If no events are available to attend today, let time flies to the next + // available event. + if (minHeap.isEmpty()) + d = events[i][0]; + // All the events starting from today are newly available. + while (i < events.length && events[i][0] == d) + minHeap.offer(events[i++][1]); + // Greedily attend the event that'll end the earliest since it has higher + // chance can't be attended in the future. + minHeap.poll(); + ++ans; + ++d; + // Pop the events that can't be attended. + while (!minHeap.isEmpty() && minHeap.peek() < d) + minHeap.poll(); + } + + return ans; + } +} diff --git a/solutions/1353. Maximum Number of Events That Can Be Attended/1353.py b/solutions/1353. Maximum Number of Events That Can Be Attended/1353.py new file mode 100644 index 00000000000..cbc2b92a2c5 --- /dev/null +++ b/solutions/1353. Maximum Number of Events That Can Be Attended/1353.py @@ -0,0 +1,27 @@ +class Solution: + def maxEvents(self, events: List[List[int]]) -> int: + ans = 0 + minHeap = [] + i = 0 # events' index + + events.sort(key=lambda x: x[0]) + + while minHeap or i < len(events): + # If no events are available to attend today, let time flies to the next + # available event. + if not minHeap: + d = events[i][0] + # All the events starting from today are newly available. + while i < len(events) and events[i][0] == d: + heapq.heappush(minHeap, events[i][1]) + i += 1 + # Greedily attend the event that'll end the earliest since it has higher + # chance can't be attended in the future. + heapq.heappop(minHeap) + ans += 1 + d += 1 + # Pop the events that can't be attended. + while minHeap and minHeap[0] < d: + heapq.heappop(minHeap) + + return ans diff --git a/solutions/1354. Construct Target Array With Multiple Sums/1354.cpp b/solutions/1354. Construct Target Array With Multiple Sums/1354.cpp new file mode 100644 index 00000000000..7f6429a1583 --- /dev/null +++ b/solutions/1354. Construct Target Array With Multiple Sums/1354.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool isPossible(vector& target) { + if (target.size() == 1) + return target[0] == 1; + + long sum = accumulate(target.begin(), target.end(), 0L); + priority_queue maxHeap; + + for (const int num : target) + maxHeap.push(num); + + while (maxHeap.top() > 1) { + const long mx = maxHeap.top(); + maxHeap.pop(); + const long restSum = sum - mx; + // Only occurs if n == 2. + if (restSum == 1) + return true; + const long updated = mx % restSum; + // updated == 0 (invalid) or didn't change. + if (updated == 0 || updated == mx) + return false; + maxHeap.push(updated); + sum = sum - mx + updated; + } + + return true; + } +}; diff --git a/solutions/1354. Construct Target Array With Multiple Sums/1354.java b/solutions/1354. Construct Target Array With Multiple Sums/1354.java new file mode 100644 index 00000000000..7448876cdd1 --- /dev/null +++ b/solutions/1354. Construct Target Array With Multiple Sums/1354.java @@ -0,0 +1,28 @@ +class Solution { + public boolean isPossible(int[] target) { + if (target.length == 1) + return target[0] == 1; + + long sum = Arrays.stream(target).asLongStream().sum(); + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + for (final int num : target) + maxHeap.offer(num); + + while (maxHeap.peek() > 1) { + final long mx = maxHeap.poll(); + final long restSum = sum - mx; + // Only occurs if n == 2. + if (restSum == 1) + return true; + final long updated = mx % restSum; + // updated == 0 (invalid) or didn't change. + if (updated == 0 || updated == mx) + return false; + maxHeap.offer((int) updated); + sum = sum - mx + updated; + } + + return true; + } +} diff --git a/solutions/1354. Construct Target Array With Multiple Sums/1354.py b/solutions/1354. Construct Target Array With Multiple Sums/1354.py new file mode 100644 index 00000000000..ca00f6b1573 --- /dev/null +++ b/solutions/1354. Construct Target Array With Multiple Sums/1354.py @@ -0,0 +1,23 @@ +class Solution: + def isPossible(self, target: List[int]) -> bool: + if len(target) == 1: + return target[0] == 1 + + summ = sum(target) + maxHeap = [-num for num in target] + heapq.heapify(maxHeap) + + while -maxHeap[0] > 1: + mx = -heapq.heappop(maxHeap) + restSum = summ - mx + # Only occurs if n == 2. + if restSum == 1: + return True + updated = mx % restSum + # updated == 0 (invalid) or didn't change. + if updated == 0 or updated == mx: + return False + heapq.heappush(maxHeap, -updated) + summ = summ - mx + updated + + return True diff --git a/solutions/1355. Activity Participants/1355.sql b/solutions/1355. Activity Participants/1355.sql new file mode 100644 index 00000000000..fd7f9269fd6 --- /dev/null +++ b/solutions/1355. Activity Participants/1355.sql @@ -0,0 +1,12 @@ +WITH + RankedFriends AS ( + SELECT + activity, + RANK() OVER(ORDER BY COUNT(id) ASC) AS rank_asc, + RANK() OVER(ORDER BY COUNT(id) DESC) AS rank_desc + FROM Friends + GROUP BY 1 + ) +SELECT activity +FROM RankedFriends +WHERE rank_asc > 1 AND rank_desc > 1; diff --git a/solutions/1356. Sort Integers by The Number of 1 Bits/1356.cpp b/solutions/1356. Sort Integers by The Number of 1 Bits/1356.cpp new file mode 100644 index 00000000000..0f18ae83b98 --- /dev/null +++ b/solutions/1356. Sort Integers by The Number of 1 Bits/1356.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector sortByBits(vector& arr) { + ranges::sort(arr, [](const int a, int b) { + const int x = bitset<32>(a).contains(); + const int y = bitset<32>(b).contains(); + return x == y ? a < b : x < y; + }); + return arr; + } +}; diff --git a/solutions/1356. Sort Integers by The Number of 1 Bits/1356.java b/solutions/1356. Sort Integers by The Number of 1 Bits/1356.java new file mode 100644 index 00000000000..c591f4160fc --- /dev/null +++ b/solutions/1356. Sort Integers by The Number of 1 Bits/1356.java @@ -0,0 +1,11 @@ +class Solution { + public int[] sortByBits(int[] arr) { + Integer[] A = Arrays.stream(arr).boxed().toArray(Integer[] ::new); + Arrays.sort(A, + (a, b) + -> Integer.bitCount(a) == Integer.bitCount(b) + ? a - b + : Integer.bitCount(a) - Integer.bitCount(b)); + return Arrays.stream(A).mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/1357. Apply Discount Every n Orders/1357.cpp b/solutions/1357. Apply Discount Every n Orders/1357.cpp new file mode 100644 index 00000000000..6b0aa536951 --- /dev/null +++ b/solutions/1357. Apply Discount Every n Orders/1357.cpp @@ -0,0 +1,22 @@ +class Cashier { + public: + Cashier(int n, int discount, vector& products, vector& prices) + : n(n), discount(discount) { + for (int i = 0; i < products.size(); ++i) + productToPrice[products[i]] = prices[i]; + } + + double getBill(vector product, vector amount) { + ++count; + int total = 0; + for (int i = 0; i < product.size(); ++i) + total += productToPrice[product[i]] * amount[i]; + return count % n == 0 ? total * (1 - discount / 100.0) : total; + } + + private: + const int n; + const int discount; + unordered_map productToPrice; + int count = 0; +}; diff --git a/solutions/1357. Apply Discount Every n Orders/1357.java b/solutions/1357. Apply Discount Every n Orders/1357.java new file mode 100644 index 00000000000..6d005a4016c --- /dev/null +++ b/solutions/1357. Apply Discount Every n Orders/1357.java @@ -0,0 +1,21 @@ +class Cashier { + public Cashier(int n, int discount, int[] products, int[] prices) { + this.n = n; + this.discount = discount; + for (int i = 0; i < products.length; ++i) + productToPrice.put(products[i], prices[i]); + } + + public double getBill(int[] product, int[] amount) { + ++count; + int total = 0; + for (int i = 0; i < product.length; ++i) + total += productToPrice.get(product[i]) * amount[i]; + return count % n == 0 ? total * (1 - discount / 100.0) : total; + } + + private int n; + private int discount; + private Map productToPrice = new HashMap<>(); + private int count = 0; +} diff --git a/solutions/1357. Apply Discount Every n Orders/1357.py b/solutions/1357. Apply Discount Every n Orders/1357.py new file mode 100644 index 00000000000..d6ba76b6161 --- /dev/null +++ b/solutions/1357. Apply Discount Every n Orders/1357.py @@ -0,0 +1,14 @@ +class Cashier: + def __init__(self, n: int, discount: int, products: List[int], prices: List[int]): + self.n = n + self.discount = discount + self.productToPrice = dict(zip(products, prices)) + self.count = 0 + + def getBill(self, product: List[int], amount: List[int]) -> float: + self.count += 1 + total = sum(self.productToPrice[p] * amount[i] + for i, p in enumerate(product)) + if self.count % self.n == 0: + return total * (1 - self.discount / 100) + return total diff --git a/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.cpp b/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.cpp new file mode 100644 index 00000000000..9741ad654af --- /dev/null +++ b/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + // Similar to 3. Longest Substring Without Repeating Characters + int numberOfSubstrings(string s) { + int ans = 0; + vector lastSeen( + 3, -1); // lastSeen[c] := the index of the last time c appeared + + for (int i = 0; i < s.length(); ++i) { + lastSeen[s[i] - 'a'] = i; + // s[0..i], s[1..i], s[min(lastSeen)..i] are satisfied strings. + ans += 1 + ranges::min(lastSeen); + } + + return ans; + } +}; diff --git a/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.java b/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.java new file mode 100644 index 00000000000..5d7155b1b4d --- /dev/null +++ b/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.java @@ -0,0 +1,16 @@ +class Solution { + // Similar to 3. Longest SubString Without Repeating Characters + public int numberOfSubstrings(String s) { + int ans = 0; + int[] lastSeen = new int[3]; // lastSeen[c] := the index of the last time c appeared + Arrays.fill(lastSeen, -1); + + for (int i = 0; i < s.length(); ++i) { + lastSeen[s.charAt(i) - 'a'] = i; + // s[0..i], s[1..i], s[Math.min(lastSeen)..i] are satisfied strings. + ans += 1 + Arrays.stream(lastSeen).min().getAsInt(); + } + + return ans; + } +} diff --git a/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.py b/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.py new file mode 100644 index 00000000000..8eabacd2d43 --- /dev/null +++ b/solutions/1358. Number of Substrings Containing All Three Characters/1358-2.py @@ -0,0 +1,13 @@ +class Solution: + # Similar to 3. Longest SubWithout Repeating Characters + def numberOfSubstrings(self, s: str) -> int: + ans = 0 + # lastSeen[c] := the index of the last time c appeared + lastSeen = {c: -1 for c in 'abc'} + + for i, c in enumerate(s): + lastSeen[c] = i + # s[0..i], s[1..i], s[min(lastSeen)..i] are satisfied strings. + ans += 1 + min(lastSeen.values()) + + return ans diff --git a/solutions/1358. Number of Substrings Containing All Three Characters/1358.cpp b/solutions/1358. Number of Substrings Containing All Three Characters/1358.cpp new file mode 100644 index 00000000000..3168d855b05 --- /dev/null +++ b/solutions/1358. Number of Substrings Containing All Three Characters/1358.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + // Similar to 3. Longest Substring Without Repeating Characters + int numberOfSubstrings(string s) { + int ans = 0; + vector count(3); + + int l = 0; + for (const char c : s) { + ++count[c - 'a']; + while (count[0] > 0 && count[1] > 0 && count[2] > 0) + --count[s[l++] - 'a']; + // s[0..r], s[1..r], ..., s[l - 1..r] are satified strings. + ans += l; + } + + return ans; + } +}; diff --git a/solutions/1358. Number of Substrings Containing All Three Characters/1358.java b/solutions/1358. Number of Substrings Containing All Three Characters/1358.java new file mode 100644 index 00000000000..78143609712 --- /dev/null +++ b/solutions/1358. Number of Substrings Containing All Three Characters/1358.java @@ -0,0 +1,18 @@ +class Solution { + // Similar to 3. Longest SubString Without Repeating Characters + public int numberOfSubstrings(String s) { + int ans = 0; + int[] count = new int[3]; + + int l = 0; + for (final char c : s.toCharArray()) { + ++count[c - 'a']; + while (count[0] > 0 && count[1] > 0 && count[2] > 0) + --count[s.charAt(l++) - 'a']; + // s[0..r], s[1..r], ..., s[l - 1..r] are satified strings. + ans += l; + } + + return ans; + } +} diff --git a/solutions/1358. Number of Substrings Containing All Three Characters/1358.py b/solutions/1358. Number of Substrings Containing All Three Characters/1358.py new file mode 100644 index 00000000000..24449503113 --- /dev/null +++ b/solutions/1358. Number of Substrings Containing All Three Characters/1358.py @@ -0,0 +1,16 @@ +class Solution: + # Similar to 3. Longest SubWithout Repeating Characters + def numberOfSubstrings(self, s: str) -> int: + ans = 0 + count = {c: 0 for c in 'abc'} + + l = 0 + for c in s: + count[c] += 1 + while min(count.values()) > 0: + count[s[l]] -= 1 + l += 1 + # s[0..r], s[1..r], ..., s[l - 1..r] are satified strings. + ans += l + + return ans diff --git a/solutions/1359. Count All Valid Pickup and Delivery Options/1359.cpp b/solutions/1359. Count All Valid Pickup and Delivery Options/1359.cpp new file mode 100644 index 00000000000..21aa059715f --- /dev/null +++ b/solutions/1359. Count All Valid Pickup and Delivery Options/1359.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int countOrders(int n) { + constexpr int kMod = 1'000'000'007; + long ans = 1; + + for (int i = 1; i <= n; ++i) + ans = ans * i * (i * 2 - 1) % kMod; + + return ans; + } +}; diff --git a/solutions/1359. Count All Valid Pickup and Delivery Options/1359.java b/solutions/1359. Count All Valid Pickup and Delivery Options/1359.java new file mode 100644 index 00000000000..330ec3c44de --- /dev/null +++ b/solutions/1359. Count All Valid Pickup and Delivery Options/1359.java @@ -0,0 +1,11 @@ +class Solution { + public int countOrders(int n) { + final int kMod = 1_000_000_007; + long ans = 1; + + for (int i = 1; i <= n; ++i) + ans = ans * i * (i * 2 - 1) % kMod; + + return (int) ans; + } +} diff --git a/solutions/1359. Count All Valid Pickup and Delivery Options/1359.py b/solutions/1359. Count All Valid Pickup and Delivery Options/1359.py new file mode 100644 index 00000000000..1901779ff83 --- /dev/null +++ b/solutions/1359. Count All Valid Pickup and Delivery Options/1359.py @@ -0,0 +1,9 @@ +class Solution: + def countOrders(self, n: int) -> int: + kMod = 1_000_000_007 + ans = 1 + + for i in range(1, n + 1): + ans = ans * i * (i * 2 - 1) % kMod + + return ans diff --git a/solutions/136. Single Number/136.cpp b/solutions/136. Single Number/136.cpp new file mode 100644 index 00000000000..494418cbc5e --- /dev/null +++ b/solutions/136. Single Number/136.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int singleNumber(vector& nums) { + int ans = 0; + + for (const int num : nums) + ans ^= num; + + return ans; + } +}; diff --git a/solutions/136. Single Number/136.java b/solutions/136. Single Number/136.java new file mode 100644 index 00000000000..98ad2c0dd27 --- /dev/null +++ b/solutions/136. Single Number/136.java @@ -0,0 +1,10 @@ +class Solution { + public int singleNumber(int[] nums) { + int ans = 0; + + for (final int num : nums) + ans ^= num; + + return ans; + } +} diff --git a/solutions/136. Single Number/136.py b/solutions/136. Single Number/136.py new file mode 100644 index 00000000000..9e7e63986f7 --- /dev/null +++ b/solutions/136. Single Number/136.py @@ -0,0 +1,3 @@ +class Solution: + def singleNumber(self, nums: List[int]) -> int: + return functools.reduce(operator.xor, nums, 0) diff --git a/solutions/1360. Number of Days Between Two Dates/1360.cpp b/solutions/1360. Number of Days Between Two Dates/1360.cpp new file mode 100644 index 00000000000..9a21000abf9 --- /dev/null +++ b/solutions/1360. Number of Days Between Two Dates/1360.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int daysBetweenDates(string date1, string date2) { + return abs(daysFrom1971(date1) - daysFrom1971(date2)); + } + + private: + const vector days{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + int daysFrom1971(const string& date) { + const int year = stoi(date1.substr(0, 4)); + const int month = stoi(date1.substr(5, 2)); + const int day = stoi(date1.substr(8, 2)); + int res = 0; + for (int i = 1971; i < year; ++i) + res += isLeapYear(i) ? 366 : 365; + for (int i = 0; i < month; ++i) + res += days[i]; + if (month > 2 && isLeapYear(year)) + ++res; + res += day; + return res; + } + + bool isLeapYear(int year) { + return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; + }; +}; diff --git a/solutions/1360. Number of Days Between Two Dates/1360.java b/solutions/1360. Number of Days Between Two Dates/1360.java new file mode 100644 index 00000000000..9ef95e4d88a --- /dev/null +++ b/solutions/1360. Number of Days Between Two Dates/1360.java @@ -0,0 +1,25 @@ +class Solution { + public int daysBetweenDates(String date1, String date2) { + return Math.abs(daysFrom1971(date1) - daysFrom1971(date2)); + } + + private static final int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + private int daysFrom1971(final String date) { + final int year = Integer.valueOf(date.substring(0, 4)); + final int month = Integer.valueOf(date.substring(5, 7)); + final int day = Integer.valueOf(date.substring(8)); + int res = 0; + for (int i = 1971; i < year; ++i) + res += isLeapYear(i) ? 366 : 365; + for (int i = 0; i < month; ++i) + res += days[i]; + if (month > 2 && isLeapYear(year)) + ++res; + return res + day; + } + + private boolean isLeapYear(int year) { + return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; + }; +} diff --git a/solutions/1360. Number of Days Between Two Dates/1360.py b/solutions/1360. Number of Days Between Two Dates/1360.py new file mode 100644 index 00000000000..71a864bdecd --- /dev/null +++ b/solutions/1360. Number of Days Between Two Dates/1360.py @@ -0,0 +1,13 @@ +class Solution: + def daysBetweenDates(self, date1: str, date2: str) -> int: + days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + def isLeapYear(year: int) -> bool: + return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 + + def daysFrom1971(date: str) -> int: + year, month, day = map(int, date.split('-')) + return 365 * (year - 1971) + sum(map(isLeapYear, range(1971, year))) + \ + sum(days[:month]) + day + (month > 2 and isLeapYear(year)) + + return abs(daysFrom1971(date1) - daysFrom1971(date2)) diff --git a/solutions/1361. Validate Binary Tree Nodes/1361.cpp b/solutions/1361. Validate Binary Tree Nodes/1361.cpp new file mode 100644 index 00000000000..d5c65859803 --- /dev/null +++ b/solutions/1361. Validate Binary Tree Nodes/1361.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + bool validateBinaryTreeNodes(int n, vector& leftChild, + vector& rightChild) { + vector inDegrees(n); + int root = -1; + + // If the in-degree of any node > 1, return false. + for (const int child : leftChild) + if (child != -1 && ++inDegrees[child] == 2) + return false; + + for (const int child : rightChild) + if (child != -1 && ++inDegrees[child] == 2) + return false; + + // Find the root (the node with in-degree == 0). + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + if (root == -1) + root = i; + else + return false; // There're multiple roots. + + // Didn't find the root. + if (root == -1) + return false; + + return countNodes(root, leftChild, rightChild) == n; + } + + private: + int countNodes(int root, const vector& leftChild, + const vector& rightChild) { + if (root == -1) + return 0; + return 1 + // + countNodes(leftChild[root], leftChild, rightChild) + + countNodes(rightChild[root], leftChild, rightChild); + } +}; diff --git a/solutions/1361. Validate Binary Tree Nodes/1361.java b/solutions/1361. Validate Binary Tree Nodes/1361.java new file mode 100644 index 00000000000..caffcda6092 --- /dev/null +++ b/solutions/1361. Validate Binary Tree Nodes/1361.java @@ -0,0 +1,37 @@ +class Solution { + public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) { + int[] inDegrees = new int[n]; + int root = -1; + + // If the in-degree of any node > 1, return false. + for (final int child : leftChild) + if (child != -1 && ++inDegrees[child] == 2) + return false; + + for (final int child : rightChild) + if (child != -1 && ++inDegrees[child] == 2) + return false; + + // Find the root (the node with in-degree == 0). + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + if (root == -1) + root = i; + else + return false; // There're multiple roots. + + // Didn't find the root. + if (root == -1) + return false; + + return countNodes(root, leftChild, rightChild) == n; + } + + private int countNodes(int root, int[] leftChild, int[] rightChild) { + if (root == -1) + return 0; + return 1 + // + countNodes(leftChild[root], leftChild, rightChild) + + countNodes(rightChild[root], leftChild, rightChild); + } +} diff --git a/solutions/1362. Closest Divisors/1362.cpp b/solutions/1362. Closest Divisors/1362.cpp new file mode 100644 index 00000000000..d557d2ac690 --- /dev/null +++ b/solutions/1362. Closest Divisors/1362.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector closestDivisors(int num) { + for (int root = sqrt(num + 2); root > 0; --root) + for (int cand : {num + 1, num + 2}) + if (cand % root == 0) + return {root, cand / root}; + + throw; + } +}; diff --git a/solutions/1362. Closest Divisors/1362.java b/solutions/1362. Closest Divisors/1362.java new file mode 100644 index 00000000000..ccee613ebc7 --- /dev/null +++ b/solutions/1362. Closest Divisors/1362.java @@ -0,0 +1,10 @@ +class Solution { + public int[] closestDivisors(int num) { + for (int root = (int) Math.sqrt(num + 2); root > 0; --root) + for (int cand : new int[] {num + 1, num + 2}) + if (cand % root == 0) + return new int[] {root, cand / root}; + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1362. Closest Divisors/1362.py b/solutions/1362. Closest Divisors/1362.py new file mode 100644 index 00000000000..16c566b6c1d --- /dev/null +++ b/solutions/1362. Closest Divisors/1362.py @@ -0,0 +1,6 @@ +class Solution: + def closestDivisors(self, num: int) -> List[int]: + for root in reversed(range(math.isqrt(num + 2) + 1)): + for cand in [num + 1, num + 2]: + if cand % root == 0: + return [root, cand // root] diff --git a/solutions/1363. Largest Multiple of Three/1363.cpp b/solutions/1363. Largest Multiple of Three/1363.cpp new file mode 100644 index 00000000000..127c5bedbb9 --- /dev/null +++ b/solutions/1363. Largest Multiple of Three/1363.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + string largestMultipleOfThree(vector& digits) { + string ans; + vector mod1{1, 4, 7, 2, 5, 8}; + vector mod2{2, 5, 8, 1, 4, 7}; + vector count(10); + int sum = accumulate(digits.begin(), digits.end(), 0); + + for (const int digit : digits) + ++count[digit]; + + while (sum % 3 != 0) + for (int i : sum % 3 == 1 ? mod1 : mod2) + if (count[i]) { + --count[i]; + sum -= i; + break; + } + + for (int digit = 9; digit >= 0; --digit) + ans += string(count[digit], '0' + digit); + + return ans.size() && ans[0] == '0' ? "0" : ans; + } +}; diff --git a/solutions/1363. Largest Multiple of Three/1363.java b/solutions/1363. Largest Multiple of Three/1363.java new file mode 100644 index 00000000000..87cd318e302 --- /dev/null +++ b/solutions/1363. Largest Multiple of Three/1363.java @@ -0,0 +1,27 @@ +class Solution { + public String largestMultipleOfThree(int[] digits) { + StringBuilder ans = new StringBuilder(); + int[] mod1 = new int[] {1, 4, 7, 2, 5, 8}; + int[] mod2 = new int[] {2, 5, 8, 1, 4, 7}; + int[] count = new int[10]; + int sum = 0; + + for (int digit : digits) { + ++count[digit]; + sum += digit; + } + + while (sum % 3 != 0) + for (int i : sum % 3 == 1 ? mod1 : mod2) + if (count[i] > 0) { + --count[i]; + sum -= i; + break; + } + + for (int digit = 9; digit >= 0; --digit) + ans.append(Character.toString('0' + digit).repeat(count[digit])); + + return ans.length() > 0 && ans.charAt(0) == '0' ? "0" : ans.toString(); + } +} diff --git a/solutions/1363. Largest Multiple of Three/1363.py b/solutions/1363. Largest Multiple of Three/1363.py new file mode 100644 index 00000000000..f308e9957df --- /dev/null +++ b/solutions/1363. Largest Multiple of Three/1363.py @@ -0,0 +1,19 @@ +class Solution: + def largestMultipleOfThree(self, digits: List[int]) -> str: + ans = '' + mod1 = [1, 4, 7, 2, 5, 8] + mod2 = [2, 5, 8, 1, 4, 7] + count = collections.Counter(digits) + summ = sum(digits) + + while summ % 3 != 0: + for digit in (mod1 if summ % 3 == 1 else mod2): + if count[digit]: + count[digit] -= 1 + summ -= digit + break + + for digit in reversed(range(10)): + ans += str(digit) * count[digit] + + return '0' if len(ans) and ans[0] == '0' else ans diff --git a/solutions/1364. Number of Trusted Contacts of a Customer/1364.sql b/solutions/1364. Number of Trusted Contacts of a Customer/1364.sql new file mode 100644 index 00000000000..a3b9e9549fd --- /dev/null +++ b/solutions/1364. Number of Trusted Contacts of a Customer/1364.sql @@ -0,0 +1,15 @@ +SELECT + Invoices.invoice_id, + Customers.customer_name, + Invoices.price, + COUNT(Contacts.user_id) AS contacts_cnt, + COUNT(CustomerEmails.email) AS trusted_contacts_cnt +FROM Invoices +INNER JOIN Customers + ON (Invoices.user_id = Customers.customer_id) +LEFT JOIN Contacts + ON (Customers.customer_id = Contacts.user_id) +LEFT JOIN Customers AS CustomerEmails + ON (Contacts.contact_email = CustomerEmails.email) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.cpp b/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.cpp new file mode 100644 index 00000000000..8492d9d5f61 --- /dev/null +++ b/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector smallerNumbersThanCurrent(vector& nums) { + constexpr int kMax = 100; + vector ans; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int i = 1; i <= kMax; ++i) + count[i] += count[i - 1]; + + for (const int num : nums) + ans.push_back(num == 0 ? 0 : count[num - 1]); + + return ans; + } +}; diff --git a/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.java b/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.java new file mode 100644 index 00000000000..1fc169aad86 --- /dev/null +++ b/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.java @@ -0,0 +1,18 @@ +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + final int kMax = 100; + int[] ans = new int[nums.length]; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int i = 1; i <= kMax; ++i) + count[i] += count[i - 1]; + + for (int i = 0; i < nums.length; ++i) + ans[i] = nums[i] == 0 ? 0 : count[nums[i] - 1]; + + return ans; + } +} diff --git a/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.py b/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.py new file mode 100644 index 00000000000..d0b5e339fc3 --- /dev/null +++ b/solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.py @@ -0,0 +1,10 @@ +class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + kMax = 100 + count = collections.Counter(nums) + + for i in range(1, kMax + 1): + count[i] += count[i - 1] + + return [0 if num == 0 else count[num - 1] + for num in nums] diff --git a/solutions/1366. Rank Teams by Votes/1366.cpp b/solutions/1366. Rank Teams by Votes/1366.cpp new file mode 100644 index 00000000000..dae16286027 --- /dev/null +++ b/solutions/1366. Rank Teams by Votes/1366.cpp @@ -0,0 +1,30 @@ +struct Team { + char name; + vector rank; + Team(char name, int teamSize) : name(name), rank(teamSize) {} +}; + +class Solution { + public: + string rankTeams(vector& votes) { + const int teamSize = votes[0].size(); + string ans; + vector teams; + + for (int i = 0; i < 26; ++i) + teams.push_back(Team('A' + i, teamSize)); + + for (const string& vote : votes) + for (int i = 0; i < teamSize; ++i) + ++teams[vote[i] - 'A'].rank[i]; + + ranges::sort(teams, [](const Team& a, const Team& b) { + return a.rank == b.rank ? a.name < b.name : a.rank > b.rank; + }); + + for (int i = 0; i < teamSize; ++i) + ans += teams[i].name; + + return ans; + } +}; diff --git a/solutions/1366. Rank Teams by Votes/1366.java b/solutions/1366. Rank Teams by Votes/1366.java new file mode 100644 index 00000000000..04067ec1f97 --- /dev/null +++ b/solutions/1366. Rank Teams by Votes/1366.java @@ -0,0 +1,40 @@ +class Team { + public char name; + public int[] rank; + public Team(char name, int teamSize) { + this.name = name; + this.rank = new int[teamSize]; + } +} + +class Solution { + public String rankTeams(String[] votes) { + final int teamSize = votes[0].length(); + StringBuilder sb = new StringBuilder(); + Team[] teams = new Team[26]; + + for (int i = 0; i < 26; ++i) + teams[i] = new Team((char) ('A' + i), teamSize); + + for (final String vote : votes) + for (int i = 0; i < teamSize; ++i) + ++teams[vote.charAt(i) - 'A'].rank[i]; + + Arrays.sort(teams, new Comparator() { + @Override + public int compare(Team a, Team b) { + for (int i = 0; i < a.rank.length; ++i) + if (a.rank[i] > b.rank[i]) + return -1; + else if (a.rank[i] < b.rank[i]) + return 1; + return a.name - b.name; + } + }); + + for (int i = 0; i < teamSize; ++i) + sb.append(teams[i].name); + + return sb.toString(); + } +} diff --git a/solutions/1366. Rank Teams by Votes/1366.py b/solutions/1366. Rank Teams by Votes/1366.py new file mode 100644 index 00000000000..338d5dfade1 --- /dev/null +++ b/solutions/1366. Rank Teams by Votes/1366.py @@ -0,0 +1,17 @@ +class Team: + def __init__(self, name: str, teamSize: int): + self.name = name + self.rank = [0] * teamSize + + +class Solution: + def rankTeams(self, votes: List[str]) -> str: + teamSize = len(votes[0]) + teams = [Team(chr(ord('A') + i), teamSize) for i in range(26)] + + for vote in votes: + for i in range(teamSize): + teams[ord(vote[i]) - ord('A')].rank[i] += 1 + + teams.sort(key=lambda x: (x.rank, -ord(x.name)), reverse=True) + return ''.join(team.name for team in teams[:teamSize]) diff --git a/solutions/1367. Linked List in Binary Tree/1367.cpp b/solutions/1367. Linked List in Binary Tree/1367.cpp new file mode 100644 index 00000000000..33fb528b8b2 --- /dev/null +++ b/solutions/1367. Linked List in Binary Tree/1367.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool isSubPath(ListNode* head, TreeNode* root) { + if (root == nullptr) + return false; + return isContinuousSubPath(head, root) || isSubPath(head, root->left) || + isSubPath(head, root->right); + } + + private: + bool isContinuousSubPath(ListNode* head, TreeNode* root) { + if (head == nullptr) + return true; + if (root == nullptr) + return false; + return head->val == root->val && + (isContinuousSubPath(head->next, root->left) || + isContinuousSubPath(head->next, root->right)); + } +}; diff --git a/solutions/1367. Linked List in Binary Tree/1367.java b/solutions/1367. Linked List in Binary Tree/1367.java new file mode 100644 index 00000000000..15a2ad0a80a --- /dev/null +++ b/solutions/1367. Linked List in Binary Tree/1367.java @@ -0,0 +1,17 @@ +class Solution { + public boolean isSubPath(ListNode head, TreeNode root) { + if (root == null) + return false; + return isContinuousSubPath(head, root) || isSubPath(head, root.left) || + isSubPath(head, root.right); + } + + private boolean isContinuousSubPath(ListNode head, TreeNode root) { + if (head == null) + return true; + if (root == null) + return false; + return head.val == root.val && + (isContinuousSubPath(head.next, root.left) || isContinuousSubPath(head.next, root.right)); + } +} diff --git a/solutions/1367. Linked List in Binary Tree/1367.py b/solutions/1367. Linked List in Binary Tree/1367.py new file mode 100644 index 00000000000..2533701aa1e --- /dev/null +++ b/solutions/1367. Linked List in Binary Tree/1367.py @@ -0,0 +1,16 @@ +class Solution: + def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool: + if not root: + return False + return self._isContinuousSubPath(head, root) or \ + self.isSubPath(head, root.left) or \ + self.isSubPath(head, root.right) + + def _isContinuousSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool: + if not head: + return True + if not root: + return False + return head.val == root.val and \ + (self._isContinuousSubPath(head.next, root.left) + or self._isContinuousSubPath(head.next, root.right)) diff --git a/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.cpp b/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.cpp new file mode 100644 index 00000000000..cf94ae8c6a7 --- /dev/null +++ b/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int minCost(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector> mem(m, vector(n, -1)); + queue> q; + + dfs(grid, 0, 0, /*cost=*/0, q, mem); + + for (int cost = 1; !q.empty(); ++cost) + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) + dfs(grid, i + dx, j + dy, cost, q, mem); + } + + return mem.back().back(); + } + + private: + const vector> dirs{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + void dfs(const vector>& grid, int i, int j, int cost, + queue>& q, vector>& mem) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (mem[i][j] != -1) + return; + + mem[i][j] = cost; + q.emplace(i, j); + const auto [dx, dy] = dirs[grid[i][j] - 1]; + dfs(grid, i + dx, j + dy, cost, q, mem); + } +}; diff --git a/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.java b/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.java new file mode 100644 index 00000000000..534643f6d5e --- /dev/null +++ b/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.java @@ -0,0 +1,37 @@ +class Solution { + public int minCost(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[][] mem = new int[m][n]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, -1)); + Queue> q = new ArrayDeque<>(); + + dfs(grid, 0, 0, /*cost=*/0, q, mem); + + for (int cost = 1; !q.isEmpty(); ++cost) + for (int sz = q.size(); sz > 0; --sz) { + Pair pair = q.poll(); + final int i = pair.getKey(); + final int j = pair.getValue(); + for (int[] dir : dirs) + dfs(grid, i + dir[0], j + dir[1], cost, q, mem); + } + + return mem[m - 1][n - 1]; + } + + private static final int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + private void dfs(int[][] grid, int i, int j, int cost, Queue> q, + int[][] mem) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (mem[i][j] != -1) + return; + + mem[i][j] = cost; + q.add(new Pair<>(i, j)); + int[] dir = dirs[grid[i][j] - 1]; + dfs(grid, i + dir[0], j + dir[1], cost, q, mem); + } +} diff --git a/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.py b/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.py new file mode 100644 index 00000000000..2b7642ae653 --- /dev/null +++ b/solutions/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368.py @@ -0,0 +1,30 @@ +class Solution: + def minCost(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + dirs = ((0, 1), (0, -1), (1, 0), (-1, 0)) + dp = [[-1] * n for _ in range(m)] + q = collections.deque() + + def dfs(i: int, j: int, cost: int) -> None: + if i < 0 or i == m or j < 0 or j == n: + return + if dp[i][j] != -1: + return + + dp[i][j] = cost + q.append((i, j)) + dx, dy = dirs[grid[i][j] - 1] + dfs(i + dx, j + dy, cost) + + dfs(0, 0, 0) + + cost = 0 + while q: + cost += 1 + for _ in range(len(q)): + i, j = q.popleft() + for dx, dy in dirs: + dfs(i + dx, j + dy, cost) + + return dp[-1][-1] diff --git a/solutions/1369. Get the Second Most Recent Activity/1369.sql b/solutions/1369. Get the Second Most Recent Activity/1369.sql new file mode 100644 index 00000000000..50baf4a0cb7 --- /dev/null +++ b/solutions/1369. Get the Second Most Recent Activity/1369.sql @@ -0,0 +1,18 @@ +WITH + RankedUserActivity AS ( + SELECT + *, + COUNT(*) OVER(PARTITION BY username) AS `count`, + RANK() OVER( + PARTITION BY username + ORDER BY endDate DESC + ) AS `rank` + FROM UserActivity + ) +SELECT + username, + activity, + startDate, + endDate +FROM RankedUserActivity +WHERE `count` = 1 OR `rank` = 2; diff --git a/solutions/137. Single Number II/137-2.cpp b/solutions/137. Single Number II/137-2.cpp new file mode 100644 index 00000000000..f389695fab5 --- /dev/null +++ b/solutions/137. Single Number II/137-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int singleNumber(vector& nums) { + int ones = 0; + int twos = 0; + + for (const int num : nums) { + ones ^= (num & ~twos); + twos ^= (num & ~ones); + } + + return ones; + } +}; diff --git a/solutions/137. Single Number II/137-2.java b/solutions/137. Single Number II/137-2.java new file mode 100644 index 00000000000..24b72fd5ad6 --- /dev/null +++ b/solutions/137. Single Number II/137-2.java @@ -0,0 +1,13 @@ +class Solution { + public int singleNumber(int[] nums) { + int ones = 0; + int twos = 0; + + for (final int num : nums) { + ones ^= (num & ~twos); + twos ^= (num & ~ones); + } + + return ones; + } +} diff --git a/solutions/137. Single Number II/137-2.py b/solutions/137. Single Number II/137-2.py new file mode 100644 index 00000000000..dbb7edf02ec --- /dev/null +++ b/solutions/137. Single Number II/137-2.py @@ -0,0 +1,10 @@ +class Solution: + def singleNumber(self, nums: List[int]) -> int: + ones = 0 + twos = 0 + + for num in nums: + ones ^= (num & ~twos) + twos ^= (num & ~ones) + + return ones diff --git a/solutions/137. Single Number II/137.cpp b/solutions/137. Single Number II/137.cpp new file mode 100644 index 00000000000..ec4046b6bfc --- /dev/null +++ b/solutions/137. Single Number II/137.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int singleNumber(vector& nums) { + int ans = 0; + + for (int i = 0; i < 32; ++i) { + int sum = 0; + for (const int num : nums) + sum += num >> i & 1; + sum %= 3; + ans |= sum << i; + } + + return ans; + } +}; diff --git a/solutions/137. Single Number II/137.java b/solutions/137. Single Number II/137.java new file mode 100644 index 00000000000..1632b972d47 --- /dev/null +++ b/solutions/137. Single Number II/137.java @@ -0,0 +1,15 @@ +class Solution { + public int singleNumber(int[] nums) { + int ans = 0; + + for (int i = 0; i < 32; ++i) { + int sum = 0; + for (final int num : nums) + sum += num >> i & 1; + sum %= 3; + ans |= sum << i; + } + + return ans; + } +} diff --git a/solutions/137. Single Number II/137.py b/solutions/137. Single Number II/137.py new file mode 100644 index 00000000000..781e69552c7 --- /dev/null +++ b/solutions/137. Single Number II/137.py @@ -0,0 +1,10 @@ +class Solution: + def singleNumber(self, nums: List[int]) -> int: + ones = 0 + twos = 0 + + for num in nums: + ones ^= num & ~twos + twos ^= num & ~ones + + return ones diff --git a/solutions/1370. Increasing Decreasing String/1370.cpp b/solutions/1370. Increasing Decreasing String/1370.cpp new file mode 100644 index 00000000000..75759c36787 --- /dev/null +++ b/solutions/1370. Increasing Decreasing String/1370.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string sortString(string s) { + string ans; + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + while (ans.length() < s.size()) { + for (int i = 0; i < 26; ++i) { + if (count[i] == 0) + continue; + ans += 'a' + i; + --count[i]; + } + for (int i = 25; i >= 0; --i) { + if (count[i] == 0) + continue; + ans += 'a' + i; + --count[i]; + } + } + + return ans; + } +}; diff --git a/solutions/1370. Increasing Decreasing String/1370.java b/solutions/1370. Increasing Decreasing String/1370.java new file mode 100644 index 00000000000..39bc2ef8108 --- /dev/null +++ b/solutions/1370. Increasing Decreasing String/1370.java @@ -0,0 +1,26 @@ +class Solution { + public String sortString(String s) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + while (sb.length() < s.length()) { + for (int i = 0; i < 26; i++) { + if (count[i] == 0) + continue; + sb.append((char) (i + 'a')); + --count[i]; + } + for (int i = 25; i >= 0; i--) { + if (count[i] == 0) + continue; + sb.append((char) (i + 'a')); + --count[i]; + } + } + + return sb.toString(); + } +} diff --git a/solutions/1370. Increasing Decreasing String/1370.py b/solutions/1370. Increasing Decreasing String/1370.py new file mode 100644 index 00000000000..786ec45cd41 --- /dev/null +++ b/solutions/1370. Increasing Decreasing String/1370.py @@ -0,0 +1,11 @@ +class Solution: + def sortString(self, s: str) -> str: + ans = [] + count = collections.Counter(s) + + while count: + for chars in string.ascii_lowercase, reversed(string.ascii_lowercase): + ans += [c for c in chars if c in count] + count -= dict.fromkeys(count, 1) + + return ''.join(ans) diff --git a/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.cpp b/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.cpp new file mode 100644 index 00000000000..bf0ed3b622b --- /dev/null +++ b/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int findTheLongestSubstring(string s) { + constexpr string_view kVowels = "aeiou"; + int ans = 0; + int prefix = 0; // the binary prefix + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < s.length(); ++i) { + const int index = kVowels.find(s[i]); + if (index != -1) + prefix ^= 1 << index; + if (!prefixToIndex.contains(prefix)) + prefixToIndex[prefix] = i; + ans = max(ans, i - prefixToIndex[prefix]); + } + + return ans; + } +}; diff --git a/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.java b/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.java new file mode 100644 index 00000000000..39fbcf78198 --- /dev/null +++ b/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.java @@ -0,0 +1,19 @@ +class Solution { + public int findTheLongestSubstring(String s) { + final String kVowels = "aeiou"; + int ans = 0; + int prefix = 0; // the binary prefix + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < s.length(); ++i) { + final int index = kVowels.indexOf(s.charAt(i)); + if (index != -1) + prefix ^= 1 << index; + prefixToIndex.putIfAbsent(prefix, i); + ans = Math.max(ans, i - prefixToIndex.get(prefix)); + } + + return ans; + } +} diff --git a/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.py b/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.py new file mode 100644 index 00000000000..2266409ddf7 --- /dev/null +++ b/solutions/1371. Find the Longest Substring Containing Vowels in Even Counts/1371.py @@ -0,0 +1,15 @@ +class Solution: + def findTheLongestSubstring(self, s: str) -> int: + kVowels = 'aeiou' + ans = 0 + prefix = 0 # the binary prefix + prefixToIndex = {0: -1} + + for i, c in enumerate(s): + index = kVowels.find(c) + if index != -1: + prefix ^= 1 << index + prefixToIndex.setdefault(prefix, i) + ans = max(ans, i - prefixToIndex[prefix]) + + return ans diff --git a/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.cpp b/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.cpp new file mode 100644 index 00000000000..220dec5d437 --- /dev/null +++ b/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.cpp @@ -0,0 +1,25 @@ +struct T { + int leftMax; + int rightMax; + int subtreeMax; +}; + +class Solution { + public: + int longestZigZag(TreeNode* root) { + return dfs(root).subtreeMax; + } + + private: + T dfs(TreeNode* root) { + if (root == nullptr) + return {-1, -1, -1}; + const T left = dfs(root->left); + const T right = dfs(root->right); + const int leftZigZag = left.rightMax + 1; + const int rightZigZag = right.leftMax + 1; + const int subtreeMax = + max({leftZigZag, rightZigZag, left.subtreeMax, right.subtreeMax}); + return {leftZigZag, rightZigZag, subtreeMax}; + } +}; diff --git a/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.java b/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.java new file mode 100644 index 00000000000..d76e170cda1 --- /dev/null +++ b/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.java @@ -0,0 +1,29 @@ +class T { + public int leftMax; + public int rightMax; + public int subtreeMax; + + public T(int leftMax, int rightMax, int subtreeMax) { + this.leftMax = leftMax; + this.rightMax = rightMax; + this.subtreeMax = subtreeMax; + } +} + +class Solution { + public int longestZigZag(TreeNode root) { + return dfs(root).subtreeMax; + } + + private T dfs(TreeNode root) { + if (root == null) + return new T(-1, -1, -1); + T left = dfs(root.left); + T right = dfs(root.right); + final int leftZigZag = left.rightMax + 1; + final int rightZigZag = right.leftMax + 1; + final int subtreeMax = + Math.max(Math.max(leftZigZag, rightZigZag), Math.max(left.subtreeMax, right.subtreeMax)); + return new T(leftZigZag, rightZigZag, subtreeMax); + } +} diff --git a/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.py b/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.py new file mode 100644 index 00000000000..28a30492fe0 --- /dev/null +++ b/solutions/1372. Longest ZigZag Path in a Binary Tree/1372.py @@ -0,0 +1,21 @@ +class T: + def __init__(self, leftMax: int, rightMax: int, subtreeMax: int): + self.leftMax = leftMax + self.rightMax = rightMax + self.subtreeMax = subtreeMax + + +class Solution: + def longestZigZag(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]) -> T: + if not root: + return T(-1, -1, -1) + left = dfs(root.left) + right = dfs(root.right) + leftZigZag = left.rightMax + 1 + rightZigZag = right.leftMax + 1 + subtreeMax = max(leftZigZag, rightZigZag, + left.subtreeMax, right.subtreeMax) + return T(leftZigZag, rightZigZag, subtreeMax) + + return dfs(root).subtreeMax diff --git a/solutions/1373. Maximum Sum BST in Binary Tree/1373.cpp b/solutions/1373. Maximum Sum BST in Binary Tree/1373.cpp new file mode 100644 index 00000000000..d18a0f79820 --- /dev/null +++ b/solutions/1373. Maximum Sum BST in Binary Tree/1373.cpp @@ -0,0 +1,37 @@ +struct T { + bool isBST; + int mx; + int mn; + int sum; + T() : isBST(false) {} + T(bool isBST, int mx, int mn, int sum) + : isBST(isBST), mx(mx), mn(mn), sum(sum) {} +}; + +class Solution { + public: + int maxSumBST(TreeNode* root) { + int ans = 0; + traverse(root, ans); + return ans; + } + + private: + T traverse(TreeNode* root, int& ans) { + if (root == nullptr) + return T(true, INT_MIN, INT_MAX, 0); + + const T left = traverse(root->left, ans); + const T right = traverse(root->right, ans); + + if (!left.isBST || !right.isBST) + return T(); + if (root->val <= left.mx || root->val >= right.mn) + return T(); + + // The `root` is a valid BST. + const int sum = root->val + left.sum + right.sum; + ans = max(ans, sum); + return T(true, max(root->val, right.mx), min(root->val, left.mn), sum); + } +}; diff --git a/solutions/1373. Maximum Sum BST in Binary Tree/1373.java b/solutions/1373. Maximum Sum BST in Binary Tree/1373.java new file mode 100644 index 00000000000..2f0e5b2be70 --- /dev/null +++ b/solutions/1373. Maximum Sum BST in Binary Tree/1373.java @@ -0,0 +1,45 @@ +class T { + public boolean isBST; + public Integer mx; + public Integer mn; + public Integer sum; + public T() { + this.isBST = false; + this.mx = null; + this.mn = null; + this.sum = null; + } + public T(boolean isBST, int mx, int mn, int sum) { + this.isBST = isBST; + this.mx = mx; + this.mn = mn; + this.sum = sum; + } +} + +class Solution { + public int maxSumBST(TreeNode root) { + traverse(root); + return ans; + } + + private int ans = 0; + + private T traverse(TreeNode root) { + if (root == null) + return new T(true, Integer.MIN_VALUE, Integer.MAX_VALUE, 0); + + T left = traverse(root.left); + T right = traverse(root.right); + + if (!left.isBST || !right.isBST) + return new T(); + if (root.val <= left.mx || root.val >= right.mn) + return new T(); + + // The `root` is a valid BST. + final int sum = root.val + left.sum + right.sum; + ans = Math.max(ans, sum); + return new T(true, Math.max(root.val, right.mx), Math.min(root.val, left.mn), sum); + } +} diff --git a/solutions/1373. Maximum Sum BST in Binary Tree/1373.py b/solutions/1373. Maximum Sum BST in Binary Tree/1373.py new file mode 100644 index 00000000000..b89a68a56f9 --- /dev/null +++ b/solutions/1373. Maximum Sum BST in Binary Tree/1373.py @@ -0,0 +1,34 @@ +class T: + def __init__(self, isBST: bool = False, + mx: Optional[int] = None, + mn: Optional[int] = None, + sum: Optional[int] = None): + self.isBST = isBST + self.mx = mx + self.mn = mn + self.sum = sum + + +class Solution: + def maxSumBST(self, root: Optional[TreeNode]) -> int: + self.ans = 0 + + def traverse(root: Optional[TreeNode]) -> T: + if not root: + return T(True, -math.inf, math.inf, 0) + + left: T = traverse(root.left) + right: T = traverse(root.right) + + if not left.isBST or not right.isBST: + return T() + if root.val <= left.mx or root.val >= right.mn: + return T() + + # The `root` is a valid BST. + summ = root.val + left.sum + right.sum + self.ans = max(self.ans, summ) + return T(True, max(root.val, right.mx), min(root.val, left.mn), summ) + + traverse(root) + return self.ans diff --git a/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.cpp b/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.cpp new file mode 100644 index 00000000000..0416798455d --- /dev/null +++ b/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + string generateTheString(int n) { + string s(n, 'a'); + if (n % 2 == 0) + s.back() = 'b'; + return s; + } +}; diff --git a/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.java b/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.java new file mode 100644 index 00000000000..8878e64c423 --- /dev/null +++ b/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.java @@ -0,0 +1,10 @@ +class Solution { + public String generateTheString(int n) { + StringBuilder sb = new StringBuilder(n); + for (int i = 0; i < n; ++i) + sb.append('a'); + if (n % 2 == 0) + sb.setCharAt(n - 1, 'b'); + return sb.toString(); + } +} diff --git a/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.py b/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.py new file mode 100644 index 00000000000..5280a5d46bf --- /dev/null +++ b/solutions/1374. Generate a String With Characters That Have Odd Counts/1374.py @@ -0,0 +1,6 @@ +class Solution: + def generateTheString(self, n: int) -> str: + s = 'a' * n + if n % 2 == 0: + s = s[:-1] + 'b' + return s diff --git a/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.cpp b/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.cpp new file mode 100644 index 00000000000..4ab0713158b --- /dev/null +++ b/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int numTimesAllBlue(vector& flips) { + int ans = 0; + int rightmost = 0; + + for (int i = 0; i < flips.size(); ++i) { + rightmost = max(rightmost, flips[i]); + // max(flips[0..i]) = rightmost = i + 1, + // so flips[0..i] is a permutation of 1, 2, ..., i + 1. + if (rightmost == i + 1) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.java b/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.java new file mode 100644 index 00000000000..3c6d5024140 --- /dev/null +++ b/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.java @@ -0,0 +1,16 @@ +class Solution { + public int numTimesAllBlue(int[] flips) { + int ans = 0; + int rightmost = 0; + + for (int i = 0; i < flips.length; ++i) { + rightmost = Math.max(rightmost, flips[i]); + // Math.max(flips[0..i]) = rightmost = i + 1, + // so flips[0..i] is a permutation of 1, 2, ..., i + 1. + if (rightmost == i + 1) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.py b/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.py new file mode 100644 index 00000000000..8e6892a1259 --- /dev/null +++ b/solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.py @@ -0,0 +1,13 @@ +class Solution: + def numTimesAllBlue(self, flips: List[int]) -> int: + ans = 0 + rightmost = 0 + + for i, flip in enumerate(flips): + rightmost = max(rightmost, flip) + # max(flips[0..i]) = rightmost = i + 1, + # so flips[0..i] is a permutation of 1, 2, ..., i + 1. + if rightmost == i + 1: + ans += 1 + + return ans diff --git a/solutions/1376. Time Needed to Inform All Employees/1376.cpp b/solutions/1376. Time Needed to Inform All Employees/1376.cpp new file mode 100644 index 00000000000..8c2e29861da --- /dev/null +++ b/solutions/1376. Time Needed to Inform All Employees/1376.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int numOfMinutes(int n, int headID, vector& manager, + vector& informTime) { + int ans = 0; + + for (int i = 0; i < n; ++i) + ans = max(ans, dfs(i, headID, manager, informTime, {})); + + return ans; + } + + private: + int dfs(int i, int headID, const vector& manager, + const vector& informTime, unordered_map&& mem) { + if (const auto it = mem.find(i); it != mem.cend()) + return it->second; + if (i == headID) + return 0; + + const int parent = manager[i]; + return mem[i] = informTime[parent] + + dfs(parent, headID, manager, informTime, move(mem)); + } +}; diff --git a/solutions/1376. Time Needed to Inform All Employees/1376.java b/solutions/1376. Time Needed to Inform All Employees/1376.java new file mode 100644 index 00000000000..5f2f0a302e7 --- /dev/null +++ b/solutions/1376. Time Needed to Inform All Employees/1376.java @@ -0,0 +1,22 @@ +class Solution { + public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) { + int ans = 0; + Map mem = new HashMap<>(); + + for (int i = 0; i < n; ++i) + ans = Math.max(ans, dfs(i, headID, manager, informTime, mem)); + + return ans; + } + + int dfs(int i, int headID, int[] manager, int[] informTime, Map mem) { + if (mem.containsKey(i)) + return mem.get(i); + if (i == headID) + return 0; + + final int parent = manager[i]; + mem.put(i, informTime[parent] + dfs(parent, headID, manager, informTime, mem)); + return mem.get(i); + } +} diff --git a/solutions/1377. Frog Position After T Seconds/1377.cpp b/solutions/1377. Frog Position After T Seconds/1377.cpp new file mode 100644 index 00000000000..92669635a80 --- /dev/null +++ b/solutions/1377. Frog Position After T Seconds/1377.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + double frogPosition(int n, vector>& edges, int t, int target) { + vector> tree(n + 1); + queue q{{1}}; + vector seen(n + 1); + vector prob(n + 1); + + seen[1] = true; + prob[1] = 1.0; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + while (!q.empty() && t-- > 0) + for (int sz = q.size(); sz > 0; --sz) { + const int a = q.front(); + q.pop(); + const int nChildren = + ranges::count_if(tree[a], [&seen](int b) { return !seen[b]; }); + for (const int b : tree[a]) { + if (seen[b]) + continue; + seen[b] = true; + prob[b] = prob[a] / nChildren; + q.push(b); + } + if (nChildren > 0) + prob[a] = 0.0; + } + + return prob[target]; + } +}; diff --git a/solutions/1377. Frog Position After T Seconds/1377.java b/solutions/1377. Frog Position After T Seconds/1377.java new file mode 100644 index 00000000000..99d93afa81d --- /dev/null +++ b/solutions/1377. Frog Position After T Seconds/1377.java @@ -0,0 +1,41 @@ +class Solution { + public double frogPosition(int n, int[][] edges, int t, int target) { + List[] tree = new List[n + 1]; + Queue q = new ArrayDeque<>(Arrays.asList(1)); + boolean[] seen = new boolean[n + 1]; + double[] prob = new double[n + 1]; + + seen[1] = true; + prob[1] = 1.0; + + for (int i = 1; i <= n; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + while (!q.isEmpty() && t-- > 0) + for (int sz = q.size(); sz > 0; --sz) { + final int a = q.poll(); + int nChildren = 0; + for (final int b : tree[a]) + if (!seen[b]) + ++nChildren; + for (final int b : tree[a]) { + if (seen[b]) + continue; + seen[b] = true; + prob[b] = prob[a] / nChildren; + q.add(b); + } + if (nChildren > 0) + prob[a] = 0.0; + } + + return prob[target]; + } +} diff --git a/solutions/1377. Frog Position After T Seconds/1377.py b/solutions/1377. Frog Position After T Seconds/1377.py new file mode 100644 index 00000000000..093cc4431b7 --- /dev/null +++ b/solutions/1377. Frog Position After T Seconds/1377.py @@ -0,0 +1,28 @@ +class Solution: + def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float: + tree = [[] for _ in range(n + 1)] + q = collections.deque([1]) + seen = [False] * (n + 1) + prob = [0] * (n + 1) + + prob[1] = 1 + seen[1] = True + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + for _ in range(t): + for _ in range(len(q)): + a = q.popleft() + nChildren = sum(not seen[b] for b in tree[a]) + for b in tree[a]: + if seen[b]: + continue + seen[b] = True + prob[b] = prob[a] / nChildren + q.append(b) + if nChildren > 0: + prob[a] = 0 + + return prob[target] diff --git a/solutions/1378. Replace Employee ID With The Unique Identifier/1378.sql b/solutions/1378. Replace Employee ID With The Unique Identifier/1378.sql new file mode 100644 index 00000000000..e5ceffe9baf --- /dev/null +++ b/solutions/1378. Replace Employee ID With The Unique Identifier/1378.sql @@ -0,0 +1,6 @@ +SELECT + EmployeeUNI.unique_id, + Employees.name +FROM Employees +LEFT JOIN EmployeeUNI + USING (id); diff --git a/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.cpp b/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.cpp new file mode 100644 index 00000000000..c0692a5913a --- /dev/null +++ b/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, + TreeNode* target) { + TreeNode* ans = nullptr; + dfs(original, cloned, target, ans); + return ans; + } + + private: + void dfs(TreeNode* original, TreeNode* cloned, TreeNode* target, + TreeNode*& ans) { + if (ans != nullptr) + return; + if (original == nullptr) + return; + if (original == target) { + ans = cloned; + return; + } + dfs(original->left, cloned->left, target, ans); + dfs(original->right, cloned->right, target, ans); + } +}; diff --git a/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.java b/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.java new file mode 100644 index 00000000000..56b1da73a85 --- /dev/null +++ b/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.java @@ -0,0 +1,22 @@ +class Solution { + public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, + final TreeNode target) { + dfs(original, cloned, target); + return ans; + } + + private TreeNode ans = null; + + private void dfs(TreeNode original, TreeNode cloned, TreeNode target) { + if (ans != null) + return; + if (original == null) + return; + if (original == target) { + ans = cloned; + return; + } + dfs(original.left, cloned.left, target); + dfs(original.right, cloned.right, target); + } +} diff --git a/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.py b/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.py new file mode 100644 index 00000000000..6abad18e063 --- /dev/null +++ b/solutions/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/1379.py @@ -0,0 +1,19 @@ +class Solution: + def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: + ans = None + + def dfs(original: TreeNode, cloned: TreeNode) -> None: + nonlocal ans + if ans: + return + if not original: + return + if original == target: + ans = cloned + return + + dfs(original.left, cloned.left) + dfs(original.right, cloned.right) + + dfs(original, cloned) + return ans diff --git a/solutions/138. Copy List with Random Pointer/138.cpp b/solutions/138. Copy List with Random Pointer/138.cpp new file mode 100644 index 00000000000..02d3b8b6cba --- /dev/null +++ b/solutions/138. Copy List with Random Pointer/138.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + Node* copyRandomList(Node* head) { + if (head == nullptr) + return nullptr; + if (const auto it = map.find(head); it != map.cend()) + return it->second; + + Node* newNode = new Node(head->val); + map[head] = newNode; + newNode->next = copyRandomList(head->next); + newNode->random = copyRandomList(head->random); + return newNode; + } + + private: + unordered_map map; +}; diff --git a/solutions/138. Copy List with Random Pointer/138.java b/solutions/138. Copy List with Random Pointer/138.java new file mode 100644 index 00000000000..3e9198807c7 --- /dev/null +++ b/solutions/138. Copy List with Random Pointer/138.java @@ -0,0 +1,16 @@ +class Solution { + public Node copyRandomList(Node head) { + if (head == null) + return null; + if (map.containsKey(head)) + return map.get(head); + + Node newNode = new Node(head.val); + map.put(head, newNode); + newNode.next = copyRandomList(head.next); + newNode.random = copyRandomList(head.random); + return newNode; + } + + private Map map = new HashMap<>(); +} diff --git a/solutions/138. Copy List with Random Pointer/138.py b/solutions/138. Copy List with Random Pointer/138.py new file mode 100644 index 00000000000..ae1f473fbc4 --- /dev/null +++ b/solutions/138. Copy List with Random Pointer/138.py @@ -0,0 +1,14 @@ +class Solution: + def copyRandomList(self, head: 'Node') -> 'Node': + if not head: + return None + if head in self.map: + return self.map[head] + + newNode = Node(head.val) + self.map[head] = newNode + newNode.next = self.copyRandomList(head.next) + newNode.random = self.copyRandomList(head.random) + return newNode + + map = {} diff --git a/solutions/1380. Lucky Numbers in a Matrix/1380.cpp b/solutions/1380. Lucky Numbers in a Matrix/1380.cpp new file mode 100644 index 00000000000..d1fb3b44849 --- /dev/null +++ b/solutions/1380. Lucky Numbers in a Matrix/1380.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector luckyNumbers(vector>& matrix) { + for (const vector& row : matrix) { + const int minIndex = distance(row.begin(), ranges::min_element(row)); + if (row[minIndex] == maxNumOfColumn(matrix, minIndex)) + return {row[minIndex]}; + } + return {}; + } + + private: + int maxNumOfColumn(const vector>& matrix, int j) { + int res = 0; + for (int i = 0; i < matrix.size(); ++i) + res = max(res, matrix[i][j]); + return res; + } +}; diff --git a/solutions/1380. Lucky Numbers in a Matrix/1380.java b/solutions/1380. Lucky Numbers in a Matrix/1380.java new file mode 100644 index 00000000000..87b278e8ca4 --- /dev/null +++ b/solutions/1380. Lucky Numbers in a Matrix/1380.java @@ -0,0 +1,25 @@ +class Solution { + public List luckyNumbers(int[][] matrix) { + for (int[] row : matrix) { + final int minIndex = getMinIndex(row); + if (row[minIndex] == maxNumOfColumn(matrix, minIndex)) + return List.of(row[minIndex]); + } + return new ArrayList<>(); + } + + private int getMinIndex(int[] row) { + int minIndex = 0; + for (int j = 0; j < row.length; ++j) + if (row[j] < row[minIndex]) + minIndex = j; + return minIndex; + } + + private int maxNumOfColumn(int[][] matrix, int j) { + int res = 0; + for (int i = 0; i < matrix.length; ++i) + res = Math.max(res, matrix[i][j]); + return res; + } +} diff --git a/solutions/1380. Lucky Numbers in a Matrix/1380.py b/solutions/1380. Lucky Numbers in a Matrix/1380.py new file mode 100644 index 00000000000..702b487e067 --- /dev/null +++ b/solutions/1380. Lucky Numbers in a Matrix/1380.py @@ -0,0 +1,7 @@ +class Solution: + def luckyNumbers(self, matrix: List[List[int]]) -> List[int]: + for row in matrix: + minIndex = row.index(min(row)) + if row[minIndex] == max(list(zip(*matrix))[minIndex]): + return [row[minIndex]] + return [] diff --git a/solutions/1381. Design a Stack With Increment Operation/1381.cpp b/solutions/1381. Design a Stack With Increment Operation/1381.cpp new file mode 100644 index 00000000000..81e8f0af41f --- /dev/null +++ b/solutions/1381. Design a Stack With Increment Operation/1381.cpp @@ -0,0 +1,36 @@ +class CustomStack { + public: + CustomStack(int maxSize) : maxSize(maxSize) {} + + void push(int x) { + if (stack.size() == maxSize) + return; + stack.push(x); + pendingIncrements.push_back(0); + } + + int pop() { + if (stack.empty()) + return -1; + const int i = stack.size() - 1; + if (i > 0) + pendingIncrements[i - 1] += pendingIncrements[i]; + const int val = stack.top() + pendingIncrements[i]; + stack.pop(); + pendingIncrements.pop_back(); + return val; + } + + void increment(int k, int val) { + if (stack.empty()) + return; + const int i = min(k - 1, static_cast(stack.size()) - 1); + pendingIncrements[i] += val; + } + + private: + const int maxSize; + stack stack; + // pendingIncrements[i] := the pending increment for stack[0..i]. + vector pendingIncrements; +}; diff --git a/solutions/1381. Design a Stack With Increment Operation/1381.java b/solutions/1381. Design a Stack With Increment Operation/1381.java new file mode 100644 index 00000000000..0d3753bdc9c --- /dev/null +++ b/solutions/1381. Design a Stack With Increment Operation/1381.java @@ -0,0 +1,35 @@ +class CustomStack { + public CustomStack(int maxSize) { + this.maxSize = maxSize; + } + + public void push(int x) { + if (stack.size() == maxSize) + return; + stack.push(x); + pendingIncrements.add(0); + } + + public int pop() { + if (stack.isEmpty()) + return -1; + final int i = stack.size() - 1; + final int pendingIncrement = pendingIncrements.get(i); + pendingIncrements.remove(i); + if (i > 0) + pendingIncrements.set(i - 1, pendingIncrements.get(i - 1) + pendingIncrement); + return stack.pop() + pendingIncrement; + } + + public void increment(int k, int val) { + if (stack.isEmpty()) + return; + final int i = Math.min(k - 1, stack.size() - 1); + pendingIncrements.set(i, pendingIncrements.get(i) + val); + } + + private int maxSize; + private Deque stack = new ArrayDeque<>(); + // pendingIncrements[i] := the pending increment for stack[0..i]. + private List pendingIncrements = new ArrayList<>(); +} diff --git a/solutions/1381. Design a Stack With Increment Operation/1381.py b/solutions/1381. Design a Stack With Increment Operation/1381.py new file mode 100644 index 00000000000..18c63373336 --- /dev/null +++ b/solutions/1381. Design a Stack With Increment Operation/1381.py @@ -0,0 +1,25 @@ +class CustomStack: + def __init__(self, maxSize: int): + self.maxSize = maxSize + self.stack = [] + # pendingIncrements[i] := the pending increment for stack[0..i]. + self.pendingIncrements = [] + + def push(self, x: int) -> None: + if len(self.stack) == self.maxSize: + return + self.stack.append(x) + self.pendingIncrements.append(0) + + def pop(self) -> int: + if not self.stack: + return -1 + if len(self.stack) > 1: + self.pendingIncrements[-2] += self.pendingIncrements[-1] + return self.stack.pop() + self.pendingIncrements.pop() + + def increment(self, k: int, val: int) -> None: + if not self.stack: + return + i = min(k - 1, len(self.stack) - 1) + self.pendingIncrements[i] += val diff --git a/solutions/1382. Balance a Binary Search Tree/1382.cpp b/solutions/1382. Balance a Binary Search Tree/1382.cpp new file mode 100644 index 00000000000..98bee53c382 --- /dev/null +++ b/solutions/1382. Balance a Binary Search Tree/1382.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + TreeNode* balanceBST(TreeNode* root) { + vector nums; + inorder(root, nums); + return build(nums, 0, nums.size() - 1); + } + + private: + void inorder(TreeNode* root, vector& nums) { + if (root == nullptr) + return; + inorder(root->left, nums); + nums.push_back(root->val); + inorder(root->right, nums); + } + + // Same as 108. Convert Sorted Array to Binary Search Tree + TreeNode* build(const vector& nums, int l, int r) { + if (l > r) + return nullptr; + const int m = (l + r) / 2; + return new TreeNode(nums[m], build(nums, l, m - 1), build(nums, m + 1, r)); + } +}; diff --git a/solutions/1382. Balance a Binary Search Tree/1382.java b/solutions/1382. Balance a Binary Search Tree/1382.java new file mode 100644 index 00000000000..72ac41677dc --- /dev/null +++ b/solutions/1382. Balance a Binary Search Tree/1382.java @@ -0,0 +1,23 @@ +class Solution { + public TreeNode balanceBST(TreeNode root) { + List nums = new ArrayList<>(); + inorder(root, nums); + return build(nums, 0, nums.size() - 1); + } + + private void inorder(TreeNode root, List nums) { + if (root == null) + return; + inorder(root.left, nums); + nums.add(root.val); + inorder(root.right, nums); + } + + // Same as 108. Convert Sorted Array to Binary Search Tree + private TreeNode build(List nums, int l, int r) { + if (l > r) + return null; + final int m = (l + r) / 2; + return new TreeNode(nums.get(m), build(nums, l, m - 1), build(nums, m + 1, r)); + } +} diff --git a/solutions/1382. Balance a Binary Search Tree/1382.py b/solutions/1382. Balance a Binary Search Tree/1382.py new file mode 100644 index 00000000000..7e37e62ea13 --- /dev/null +++ b/solutions/1382. Balance a Binary Search Tree/1382.py @@ -0,0 +1,23 @@ +class Solution: + def balanceBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + nums = [] + + def inorder(root: Optional[TreeNode]) -> None: + if not root: + return + inorder(root.left) + nums.append(root.val) + inorder(root.right) + + inorder(root) + + # Same as 108. Convert Sorted Array to Binary Search Tree + def build(l: int, r: int) -> Optional[TreeNode]: + if l > r: + return None + m = (l + r) // 2 + return TreeNode(nums[m], + build(l, m - 1), + build(m + 1, r)) + + return build(0, len(nums) - 1) diff --git a/solutions/1383. Maximum Performance of a Team/1383.cpp b/solutions/1383. Maximum Performance of a Team/1383.cpp new file mode 100644 index 00000000000..72f13100873 --- /dev/null +++ b/solutions/1383. Maximum Performance of a Team/1383.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + // Similar to 857. Minimum Cost to Hire K Workers + int maxPerformance(int n, vector& speed, vector& efficiency, + int k) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + long speedSum = 0; + // (efficiency[i], speed[i]) sorted by efficiency[i] in descending order + vector> A; + priority_queue, greater<>> minHeap; + + for (int i = 0; i < n; ++i) + A.emplace_back(efficiency[i], speed[i]); + + ranges::sort(A, greater<>()); + + for (const auto& [e, s] : A) { + minHeap.push(s); + speedSum += s; + if (minHeap.size() > k) + speedSum -= minHeap.top(), minHeap.pop(); + ans = max(ans, speedSum * e); + } + + return ans % kMod; + } +}; diff --git a/solutions/1383. Maximum Performance of a Team/1383.java b/solutions/1383. Maximum Performance of a Team/1383.java new file mode 100644 index 00000000000..ea219f7ce16 --- /dev/null +++ b/solutions/1383. Maximum Performance of a Team/1383.java @@ -0,0 +1,28 @@ +class Solution { + // Similar to 857. Minimum Cost to Hire K Workers + public int maxPerformance(int n, int[] speed, int[] efficiency, int k) { + final int kMod = 1_000_000_007; + long ans = 0; + long speedSum = 0; + // (efficiency[i], speed[i]) sorted by efficiency[i] in descending order + Pair[] A = new Pair[n]; + Queue minHeap = new PriorityQueue<>(); + + for (int i = 0; i < n; ++i) + A[i] = new Pair<>(efficiency[i], speed[i]); + + Arrays.sort(A, (a, b) -> Integer.compare(b.getKey(), a.getKey())); + + for (Pair a : A) { + final int e = a.getKey(); + final int s = a.getValue(); + minHeap.offer(s); + speedSum += s; + if (minHeap.size() > k) + speedSum -= minHeap.poll(); + ans = Math.max(ans, speedSum * e); + } + + return (int) (ans % kMod); + } +} diff --git a/solutions/1383. Maximum Performance of a Team/1383.py b/solutions/1383. Maximum Performance of a Team/1383.py new file mode 100644 index 00000000000..fb9f62b3954 --- /dev/null +++ b/solutions/1383. Maximum Performance of a Team/1383.py @@ -0,0 +1,18 @@ +class Solution: + # Similar to 857. Minimum Cost to Hire K Workers + def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: + kMod = 1_000_000_007 + ans = 0 + speedSum = 0 + # (efficiency[i], speed[i]) sorted by efficiency[i] in descending order + A = sorted([(e, s) for s, e in zip(speed, efficiency)], reverse=True) + minHeap = [] + + for e, s in A: + heapq.heappush(minHeap, s) + speedSum += s + if len(minHeap) > k: + speedSum -= heapq.heappop(minHeap) + ans = max(ans, speedSum * e) + + return ans % kMod diff --git a/solutions/1384. Total Sales Amount by Year/1384.sql b/solutions/1384. Total Sales Amount by Year/1384.sql new file mode 100644 index 00000000000..77db015f4f9 --- /dev/null +++ b/solutions/1384. Total Sales Amount by Year/1384.sql @@ -0,0 +1,26 @@ +WITH + Calendar AS ( + # We should be given a calendar in hand. Otherwise, assume we are oracle + # and already know the testcase. + SELECT '2018' AS year, '2018-01-01' AS start, '2018-12-31' AS end + UNION ALL + SELECT '2019' AS year, '2019-01-01' AS start, '2019-12-31' AS end + UNION ALL + SELECT '2020' AS year, '2020-01-01' AS start, '2020-12-31' AS end + ) +SELECT + Product.product_id, + Product.product_name, + Calendar.year AS report_year, + ( + DATEDIFF( + LEAST(Sales.period_end, Calendar.end), + GREATEST(Sales.period_start, Calendar.start) + ) + 1 + ) * Sales.average_daily_sales AS total_amount +FROM Sales +INNER JOIN Calendar + ON (Calendar.year BETWEEN YEAR(Sales.period_start) AND year(Sales.period_end)) +INNER JOIN Product + USING (product_id) +ORDER BY 1, 3; diff --git a/solutions/1385. Find the Distance Value Between Two Arrays/1385-2.cpp b/solutions/1385. Find the Distance Value Between Two Arrays/1385-2.cpp new file mode 100644 index 00000000000..c1c5111eebb --- /dev/null +++ b/solutions/1385. Find the Distance Value Between Two Arrays/1385-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int findTheDistanceValue(vector& arr1, vector& arr2, int d) { + int ans = 0; + + ranges::sort(arr2); + + for (const int a : arr1) + if (ranges::upper_bound(arr2, a + d) == ranges::lower_bound(arr2, a - d)) + ++ans; + + return ans; + } +}; diff --git a/solutions/1385. Find the Distance Value Between Two Arrays/1385.cpp b/solutions/1385. Find the Distance Value Between Two Arrays/1385.cpp new file mode 100644 index 00000000000..76365f12fd2 --- /dev/null +++ b/solutions/1385. Find the Distance Value Between Two Arrays/1385.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int findTheDistanceValue(vector& arr1, vector& arr2, int d) { + int ans = 0; + + ranges::sort(arr2); + + for (const int a : arr1) { + const auto it = lower_bound(begin(arr2), end(arr2), a); + if ((it == arr2.end() || *it - a > d) && + (it == arr2.begin() || a - *prev(it) > d)) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1385. Find the Distance Value Between Two Arrays/1385.java b/solutions/1385. Find the Distance Value Between Two Arrays/1385.java new file mode 100644 index 00000000000..0d2eaf00bd4 --- /dev/null +++ b/solutions/1385. Find the Distance Value Between Two Arrays/1385.java @@ -0,0 +1,16 @@ +class Solution { + public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { + int ans = 0; + + Arrays.sort(arr2); + + for (final int a : arr1) { + int i = Arrays.binarySearch(arr2, a); + i = i < 0 ? -i - 1 : i; + if ((i == arr2.length || arr2[i] - a > d) && (i == 0 || a - arr2[i - 1] > d)) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1385. Find the Distance Value Between Two Arrays/1385.py b/solutions/1385. Find the Distance Value Between Two Arrays/1385.py new file mode 100644 index 00000000000..6f411ba4e76 --- /dev/null +++ b/solutions/1385. Find the Distance Value Between Two Arrays/1385.py @@ -0,0 +1,12 @@ +class Solution: + def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: + ans = 0 + + arr2.sort() + + for a in arr1: + i = bisect.bisect_left(arr2, a) + if (i == len(arr2) or arr2[i] - a > d) and (i == 0 or a - arr2[i - 1] > d): + ans += 1 + + return ans diff --git a/solutions/1386. Cinema Seat Allocation/1386.cpp b/solutions/1386. Cinema Seat Allocation/1386.cpp new file mode 100644 index 00000000000..9c2f7c98910 --- /dev/null +++ b/solutions/1386. Cinema Seat Allocation/1386.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maxNumberOfFamilies(int n, vector>& reservedSeats) { + int ans = 0; + unordered_map rowToSeats; + + for (const vector& reservedSeat : reservedSeats) { + const int row = reservedSeat[0]; + const int seat = reservedSeat[1]; + rowToSeats[row] |= 1 << (seat - 1); + } + + for (const auto& [_, seats] : rowToSeats) + if ((seats & 0b0111111110) == 0) + // Can fit 2 four-person groups. + ans += 2; + else if ((seats & 0b0111100000) == 0 || // The left is not occupied. + (seats & 0b0001111000) == 0 || // The middle is not occupied. + (seats & 0b0000011110) == 0) // The right is notoccupied. + // Can fit 1 four-person group. + ans += 1; + + // Any empty row can fit 2 four-person groups. + return ans + (n - rowToSeats.size()) * 2; + } +}; diff --git a/solutions/1386. Cinema Seat Allocation/1386.java b/solutions/1386. Cinema Seat Allocation/1386.java new file mode 100644 index 00000000000..cba279428f9 --- /dev/null +++ b/solutions/1386. Cinema Seat Allocation/1386.java @@ -0,0 +1,25 @@ +class Solution { + public int maxNumberOfFamilies(int n, int[][] reservedSeats) { + int ans = 0; + Map rowToSeats = new HashMap<>(); + + for (int[] reservedSeat : reservedSeats) { + final int row = reservedSeat[0]; + final int seat = reservedSeat[1]; + rowToSeats.put(row, rowToSeats.getOrDefault(row, 0) | 1 << (seat - 1)); + } + + for (final int seats : rowToSeats.values()) + if ((seats & 0b0111111110) == 0) + // Can fit 2 four-person groups. + ans += 2; + else if ((seats & 0b0111100000) == 0 || // The left is not occupied. + (seats & 0b0001111000) == 0 || // The middle is not occupied. + (seats & 0b0000011110) == 0) // The right is notoccupied. + // Can fit 1 four-person group. + ans += 1; + + // Any empty row can fit 2 four-person groups. + return ans + (n - rowToSeats.size()) * 2; + } +} diff --git a/solutions/1386. Cinema Seat Allocation/1386.py b/solutions/1386. Cinema Seat Allocation/1386.py new file mode 100644 index 00000000000..76eb48b45a4 --- /dev/null +++ b/solutions/1386. Cinema Seat Allocation/1386.py @@ -0,0 +1,20 @@ +class Solution: + def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int: + ans = 0 + rowToSeats = collections.Counter() + + for row, seat in reservedSeats: + rowToSeats[row] |= 1 << (seat - 1) + + for seats in rowToSeats.values(): + if (seats & 0b0111111110) == 0: + # Can fit 2 four-person groups. + ans += 2 + elif (seats & 0b0111100000) == 0 \ + or (seats & 0b0001111000) == 0 \ + or (seats & 0b0000011110) == 0: + # Can fit 1 four-person group. + ans += 1 + + # Any empty row can fit 2 four-person groups. + return ans + (n - len(rowToSeats)) * 2 diff --git a/solutions/1387. Sort Integers by The Power Value/1387.cpp b/solutions/1387. Sort Integers by The Power Value/1387.cpp new file mode 100644 index 00000000000..aebbb98c5b4 --- /dev/null +++ b/solutions/1387. Sort Integers by The Power Value/1387.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int getKth(int lo, int hi, int k) { + vector> powAndVals; // (pow, val) + + for (int i = lo; i <= hi; ++i) + powAndVals.emplace_back(getPow(i), i); + + nth_element(powAndVals.begin(), powAndVals.begin() + k - 1, + powAndVals.end()); + return powAndVals[k - 1].second; + } + + private: + int getPow(int n) { + if (n == 1) + return 0; + return 1 + (n % 2 == 0 ? getPow(n / 2) : getPow(n * 3 + 1)); + } +}; diff --git a/solutions/1387. Sort Integers by The Power Value/1387.java b/solutions/1387. Sort Integers by The Power Value/1387.java new file mode 100644 index 00000000000..5ee5430ee62 --- /dev/null +++ b/solutions/1387. Sort Integers by The Power Value/1387.java @@ -0,0 +1,17 @@ +class Solution { + public int getKth(int lo, int hi, int k) { + int[][] powAndVals = new int[hi - lo + 1][2]; // (pow, val) + + for (int i = lo; i <= hi; ++i) + powAndVals[i - lo] = new int[] {getPow(i), i}; + + Arrays.sort(powAndVals, (a, b) -> a[0] - b[0]); + return powAndVals[k - 1][1]; + } + + private int getPow(int n) { + if (n == 1) + return 0; + return 1 + (n % 2 == 0 ? getPow(n / 2) : getPow(n * 3 + 1)); + } +} diff --git a/solutions/1387. Sort Integers by The Power Value/1387.py b/solutions/1387. Sort Integers by The Power Value/1387.py new file mode 100644 index 00000000000..1e60f03d83a --- /dev/null +++ b/solutions/1387. Sort Integers by The Power Value/1387.py @@ -0,0 +1,10 @@ +class Solution: + def getKth(self, lo: int, hi: int, k: int) -> int: + return sorted([(self._getPow(i), i) for i in range(lo, hi + 1)])[k - 1][1] + + def _getPow(self, n: int) -> int: + if n == 1: + return 0 + if n % 2 == 0: + return 1 + self._getPow(n // 2) + return 1 + self._getPow(n * 3 + 1) diff --git a/solutions/1388. Pizza With 3n Slices/1388.py b/solutions/1388. Pizza With 3n Slices/1388.py new file mode 100644 index 00000000000..6feda68ec5a --- /dev/null +++ b/solutions/1388. Pizza With 3n Slices/1388.py @@ -0,0 +1,24 @@ +class Solution: + def maxSizeSlices(self, slices: List[int]) -> int: + @functools.lru_cache(None) + def dp(i: int, j: int, k: int) -> int: + """ + Returns the maximum the sum of slices if you can pick k slices from + slices[i..j). + """ + if k == 1: + return max(slices[i:j]) + # Note that j - i is not the number of all the left slices. Since you + # Might have chosen not to take a slice in a previous step, there would be + # Leftovers outside [i:j]. If you take slices[i], one of the slices your + # Friends take will be outside of [i:j], so the length of [i:j] is reduced + # By 2 instead of 3. Therefore, the minimum # Is 2 * k - 1 (the last step only + # Requires one slice). + if j - i < 2 * k - 1: + return -math.inf + return max(slices[i] + dp(i + 2, j, k - 1), + dp(i + 1, j, k)) + + k = len(slices) // 3 + return max(dp(0, len(slices) - 1, k), + dp(1, len(slices), k)) diff --git a/solutions/1389. Create Target Array in the Given Order/1389.cpp b/solutions/1389. Create Target Array in the Given Order/1389.cpp new file mode 100644 index 00000000000..68f756b4c24 --- /dev/null +++ b/solutions/1389. Create Target Array in the Given Order/1389.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + vector createTargetArray(vector& nums, vector& index) { + vector ans; + for (int i = 0; i < nums.size(); ++i) + ans.insert(ans.begin() + index[i], nums[i]); + return ans; + } +}; diff --git a/solutions/1389. Create Target Array in the Given Order/1389.java b/solutions/1389. Create Target Array in the Given Order/1389.java new file mode 100644 index 00000000000..e777fd553b7 --- /dev/null +++ b/solutions/1389. Create Target Array in the Given Order/1389.java @@ -0,0 +1,8 @@ +class Solution { + public int[] createTargetArray(int[] nums, int[] index) { + List ans = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) + ans.add(index[i], nums[i]); + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/1389. Create Target Array in the Given Order/1389.py b/solutions/1389. Create Target Array in the Given Order/1389.py new file mode 100644 index 00000000000..252cc81c7a1 --- /dev/null +++ b/solutions/1389. Create Target Array in the Given Order/1389.py @@ -0,0 +1,6 @@ +class Solution: + def createTargetArray(self, nums, index): + ans = [] + for num, i in zip(nums, index): + ans.insert(i, num) + return ans diff --git a/solutions/139. Word Break/139-2.cpp b/solutions/139. Word Break/139-2.cpp new file mode 100644 index 00000000000..a80344178c3 --- /dev/null +++ b/solutions/139. Word Break/139-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + bool wordBreak(string s, vector& wordDict) { + return wordBreak(s, 0, {wordDict.begin(), wordDict.end()}, + vector(s.length(), -1)); + } + + private: + // Returns true if s[i..n) can be segmented. + bool wordBreak(const string& s, int i, const unordered_set&& wordSet, + vector&& mem) { + if (i == s.length()) + return true; + if (mem[i] != -1) + return mem[i]; + + for (int j = i + 1; j <= s.length(); ++j) + if (wordSet.contains(s.substr(i, j - i)) && + wordBreak(s, j, move(wordSet), move(mem))) + return mem[i] = 1; + + return mem[i] = 0; + } +}; diff --git a/solutions/139. Word Break/139-2.java b/solutions/139. Word Break/139-2.java new file mode 100644 index 00000000000..e307a565423 --- /dev/null +++ b/solutions/139. Word Break/139-2.java @@ -0,0 +1,19 @@ +class Solution { + public boolean wordBreak(String s, List wordDict) { + return wordBreak(s, 0, new HashSet<>(wordDict), new Boolean[s.length()]); + } + + // Returns true if s[i..n) can be segmented. + private boolean wordBreak(final String s, int i, Set wordSet, Boolean[] mem) { + if (i == s.length()) + return true; + if (mem[i] != null) + return mem[i]; + + for (int j = i + 1; j <= s.length(); ++j) + if (wordSet.contains(s.substring(i, j)) && wordBreak(s, j, wordSet, mem)) + return mem[i] = true; + + return mem[i] = false; + } +} diff --git a/solutions/139. Word Break/139-2.py b/solutions/139. Word Break/139-2.py new file mode 100644 index 00000000000..7e04410425f --- /dev/null +++ b/solutions/139. Word Break/139-2.py @@ -0,0 +1,12 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + wordSet = set(wordDict) + + @functools.lru_cache(None) + def wordBreak(i: int) -> bool: + """Returns True if s[i..n) can be segmented.""" + if i == len(s): + return True + return any(s[i:j] in wordSet and wordBreak(j) for j in range(i + 1, len(s) + 1)) + + return wordBreak(0) diff --git a/solutions/139. Word Break/139-3.cpp b/solutions/139. Word Break/139-3.cpp new file mode 100644 index 00000000000..a12abcaf23f --- /dev/null +++ b/solutions/139. Word Break/139-3.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool wordBreak(string s, vector& wordDict) { + const int n = s.length(); + const unordered_set wordSet{wordDict.begin(), wordDict.end()}; + // dp[i] := true if s[0..i) can be segmented + vector dp(n + 1); + dp[0] = true; + + for (int i = 1; i <= n; ++i) + for (int j = 0; j < i; ++j) + // s[0..j) can be segmented and s[j..i) is in `wordSet`, so s[0..i) can + // be segmented. + if (dp[j] && wordSet.contains(s.substr(j, i - j))) { + dp[i] = true; + break; + } + + return dp[n]; + } +}; diff --git a/solutions/139. Word Break/139-3.java b/solutions/139. Word Break/139-3.java new file mode 100644 index 00000000000..b8955dd7dee --- /dev/null +++ b/solutions/139. Word Break/139-3.java @@ -0,0 +1,20 @@ +class Solution { + public boolean wordBreak(String s, List wordDict) { + final int n = s.length(); + Set wordSet = new HashSet<>(wordDict); + // dp[i] := true if s[0..i) can be segmented + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + + for (int i = 1; i <= n; ++i) + for (int j = 0; j < i; ++j) + // s[0..j) can be segmented and s[j..i) is in `wordSet`, so s[0..i) can + // be segmented. + if (dp[j] && wordSet.contains(s.substring(j, i))) { + dp[i] = true; + break; + } + + return dp[n]; + } +} diff --git a/solutions/139. Word Break/139-3.py b/solutions/139. Word Break/139-3.py new file mode 100644 index 00000000000..db3afcee63c --- /dev/null +++ b/solutions/139. Word Break/139-3.py @@ -0,0 +1,16 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + n = len(s) + wordSet = set(wordDict) + # dp[i] := True if s[0..i) can be segmented + dp = [True] + [False] * n + + for i in range(1, n + 1): + for j in range(i): + # s[0..j) can be segmented and s[j..i) is in `wordSet`, so s[0..i) can + # be segmented. + if dp[j] and s[j:i] in wordSet: + dp[i] = True + break + + return dp[n] diff --git a/solutions/139. Word Break/139-4.cpp b/solutions/139. Word Break/139-4.cpp new file mode 100644 index 00000000000..1c78f3f533e --- /dev/null +++ b/solutions/139. Word Break/139-4.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + bool wordBreak(string s, vector& wordDict) { + const int n = s.length(); + const int maxLength = getMaxLength(wordDict); + const unordered_set wordSet{wordDict.begin(), wordDict.end()}; + // dp[i] := true if s[0..i) can be segmented + vector dp(n + 1); + dp[0] = true; + + for (int i = 1; i <= n; ++i) + for (int j = i - 1; j >= 0; --j) { + if (i - j > maxLength) + break; + // s[0..j) can be segmented and s[j..i) is in the wordSet, so s[0..i) + // can be segmented. + if (dp[j] && wordSet.contains(s.substr(j, i - j))) { + dp[i] = true; + break; + } + } + + return dp[n]; + } + + private: + int getMaxLength(const vector& wordDict) { + return ranges::max_element(wordDict, [](const string& a, const string& b) { + return a.length() < b.length(); + })->length(); + } +}; diff --git a/solutions/139. Word Break/139-4.java b/solutions/139. Word Break/139-4.java new file mode 100644 index 00000000000..4efc389761e --- /dev/null +++ b/solutions/139. Word Break/139-4.java @@ -0,0 +1,28 @@ +class Solution { + public boolean wordBreak(String s, List wordDict) { + final int n = s.length(); + final int maxLength = getMaxLength(wordDict); + Set wordSet = new HashSet<>(wordDict); + // dp[i] := true if s[0..i) can be segmented + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + + for (int i = 1; i <= n; ++i) + for (int j = i - 1; j >= 0; --j) { + if (i - j > maxLength) + break; + // s[0..j) can be segmented and s[j..i) is in the wordSet, so s[0..i) + // can be segmented. + if (dp[j] && wordSet.contains(s.substring(j, i))) { + dp[i] = true; + break; + } + } + + return dp[n]; + } + + private int getMaxLength(List wordDict) { + return wordDict.stream().mapToInt(String::length).max().getAsInt(); + } +} diff --git a/solutions/139. Word Break/139-4.py b/solutions/139. Word Break/139-4.py new file mode 100644 index 00000000000..9d56f8e0e6c --- /dev/null +++ b/solutions/139. Word Break/139-4.py @@ -0,0 +1,19 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + n = len(s) + maxLength = len(max(wordDict, key=len)) + wordSet = set(wordDict) + # dp[i] := True if s[0..i) can be segmented + dp = [True] + [False] * n + + for i in range(1, n + 1): + for j in reversed(range(i)): + if i - j > maxLength: + break + # s[0..j) can be segmented and s[j..i) is in the wordSet, so s[0..i) + # can be segmented. + if dp[j] and s[j:i] in wordSet: + dp[i] = True + break + + return dp[n] diff --git a/solutions/139. Word Break/139.cpp b/solutions/139. Word Break/139.cpp new file mode 100644 index 00000000000..9bf791c4a65 --- /dev/null +++ b/solutions/139. Word Break/139.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + bool wordBreak(string s, vector& wordDict) { + return wordBreak(s, {wordDict.begin(), wordDict.end()}, {}); + } + + private: + bool wordBreak(const string& s, const unordered_set&& wordSet, + unordered_map&& mem) { + if (wordSet.contains(s)) + return true; + if (const auto it = mem.find(s); it != mem.cend()) + return it->second; + + // 1 <= prefix.length() < s.length() + for (int i = 1; i < s.length(); ++i) { + const string& prefix = s.substr(0, i); + const string& suffix = s.substr(i); + if (wordSet.contains(prefix) && + wordBreak(suffix, move(wordSet), move(mem))) + return mem[s] = true; + } + + return mem[s] = false; + } +}; diff --git a/solutions/139. Word Break/139.java b/solutions/139. Word Break/139.java new file mode 100644 index 00000000000..68d94ca184b --- /dev/null +++ b/solutions/139. Word Break/139.java @@ -0,0 +1,27 @@ +class Solution { + public boolean wordBreak(String s, List wordDict) { + return wordBreak(s, new HashSet<>(wordDict), new HashMap<>()); + } + + private boolean wordBreak(final String s, Set wordSet, Map mem) { + if (mem.containsKey(s)) + return mem.get(s); + if (wordSet.contains(s)) { + mem.put(s, true); + return true; + } + + // 1 <= prefix.length() < s.length() + for (int i = 1; i < s.length(); ++i) { + final String prefix = s.substring(0, i); + final String suffix = s.substring(i); + if (wordSet.contains(prefix) && wordBreak(suffix, wordSet, mem)) { + mem.put(s, true); + return true; + } + } + + mem.put(s, false); + return false; + } +} diff --git a/solutions/139. Word Break/139.py b/solutions/139. Word Break/139.py new file mode 100644 index 00000000000..9bdf82086ba --- /dev/null +++ b/solutions/139. Word Break/139.py @@ -0,0 +1,12 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + wordSet = set(wordDict) + + @functools.lru_cache(None) + def wordBreak(s: str) -> bool: + """Returns True if s can be segmented.""" + if s in wordSet: + return True + return any(s[:i] in wordSet and wordBreak(s[i:]) for i in range(len(s))) + + return wordBreak(s) diff --git a/solutions/1390. Four Divisors/1390.cpp b/solutions/1390. Four Divisors/1390.cpp new file mode 100644 index 00000000000..a94fae9b781 --- /dev/null +++ b/solutions/1390. Four Divisors/1390.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int sumFourDivisors(vector& nums) { + int ans = 0; + + for (int num : nums) { + int divisor = 0; + for (int i = 2; i * i <= num; ++i) + if (num % i == 0) { + if (divisor == 0) + divisor = i; + else { + divisor = 0; + break; + } + } + if (divisor > 0 && divisor * divisor < num) + ans += 1 + num + divisor + num / divisor; + } + + return ans; + } +}; diff --git a/solutions/1390. Four Divisors/1390.java b/solutions/1390. Four Divisors/1390.java new file mode 100644 index 00000000000..b8d04456fb5 --- /dev/null +++ b/solutions/1390. Four Divisors/1390.java @@ -0,0 +1,22 @@ +class Solution { + public int sumFourDivisors(int[] nums) { + int ans = 0; + + for (int num : nums) { + int divisor = 0; + for (int i = 2; i * i <= num; ++i) + if (num % i == 0) { + if (divisor == 0) + divisor = i; + else { + divisor = 0; + break; + } + } + if (divisor > 0 && divisor * divisor < num) + ans += 1 + num + divisor + num / divisor; + } + + return ans; + } +} diff --git a/solutions/1390. Four Divisors/1390.py b/solutions/1390. Four Divisors/1390.py new file mode 100644 index 00000000000..8b21976fa5d --- /dev/null +++ b/solutions/1390. Four Divisors/1390.py @@ -0,0 +1,17 @@ +class Solution: + def sumFourDivisors(self, nums: List[int]) -> int: + ans = 0 + + for num in nums: + divisor = 0 + for i in range(2, math.isqrt(num) + 1): + if num % i == 0: + if divisor == 0: + divisor = i + else: + divisor = 0 + break + if divisor > 0 and divisor * divisor < num: + ans += 1 + num + divisor + num // divisor + + return ans diff --git a/solutions/1391. Check if There is a Valid Path in a Grid/1391.cpp b/solutions/1391. Check if There is a Valid Path in a Grid/1391.cpp new file mode 100644 index 00000000000..55582df6468 --- /dev/null +++ b/solutions/1391. Check if There is a Valid Path in a Grid/1391.cpp @@ -0,0 +1,60 @@ +class Solution { + public: + bool hasValidPath(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + // g := upscaled grid + vector> g(m * 3, vector(n * 3)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + switch (grid[i][j]) { + case 1: + g[i * 3 + 1][j * 3 + 0] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 2] = true; + break; + case 2: + g[i * 3 + 0][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 2][j * 3 + 1] = true; + break; + case 3: + g[i * 3 + 1][j * 3 + 0] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 2][j * 3 + 1] = true; + break; + case 4: + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 2] = true; + g[i * 3 + 2][j * 3 + 1] = true; + break; + case 5: + g[i * 3 + 0][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 0] = true; + g[i * 3 + 1][j * 3 + 1] = true; + break; + case 6: + g[i * 3 + 0][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 2] = true; + break; + } + + return dfs(g, 1, 1); + } + + private: + bool dfs(vector>& g, int i, int j) { + if (i < 0 || i == g.size() || j < 0 || j == g[0].size()) + return false; + if (!g[i][j]) // There's no path here. + return false; + if (i == g.size() - 2 && j == g[0].size() - 2) + return true; + + g[i][j] = false; // Mark as visited. + return dfs(g, i + 1, j) || dfs(g, i - 1, j) || dfs(g, i, j + 1) || + dfs(g, i, j - 1); + } +}; diff --git a/solutions/1391. Check if There is a Valid Path in a Grid/1391.java b/solutions/1391. Check if There is a Valid Path in a Grid/1391.java new file mode 100644 index 00000000000..40af1f02bb0 --- /dev/null +++ b/solutions/1391. Check if There is a Valid Path in a Grid/1391.java @@ -0,0 +1,57 @@ +class Solution { + public boolean hasValidPath(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + // g := upscaled grid + boolean[][] g = new boolean[m * 3][n * 3]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + switch (grid[i][j]) { + case 1: + g[i * 3 + 1][j * 3 + 0] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 2] = true; + break; + case 2: + g[i * 3 + 0][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 2][j * 3 + 1] = true; + break; + case 3: + g[i * 3 + 1][j * 3 + 0] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 2][j * 3 + 1] = true; + break; + case 4: + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 2] = true; + g[i * 3 + 2][j * 3 + 1] = true; + break; + case 5: + g[i * 3 + 0][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 0] = true; + g[i * 3 + 1][j * 3 + 1] = true; + break; + case 6: + g[i * 3 + 0][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 1] = true; + g[i * 3 + 1][j * 3 + 2] = true; + break; + } + + return dfs(g, 1, 1); + } + + private boolean dfs(boolean[][] g, int i, int j) { + if (i < 0 || i == g.length || j < 0 || j == g[0].length) + return false; + if (!g[i][j]) // There's no path here. + return false; + if (i == g.length - 2 && j == g[0].length - 2) + return true; + + g[i][j] = false; // Mark as visited. + return dfs(g, i + 1, j) || dfs(g, i - 1, j) || dfs(g, i, j + 1) || dfs(g, i, j - 1); + } +} diff --git a/solutions/1392. Longest Happy Prefix/1392.cpp b/solutions/1392. Longest Happy Prefix/1392.cpp new file mode 100644 index 00000000000..d6772469755 --- /dev/null +++ b/solutions/1392. Longest Happy Prefix/1392.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string longestPrefix(string s) { + constexpr int kBase = 26; + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + int maxLength = 0; + long pow = 1; + long prefixHash = 0; // the hash of s[0..i] + long suffixHash = 0; // the hash of s[j..n) + + for (int i = 0, j = n - 1; i < n - 1; ++i, --j) { + prefixHash = (prefixHash * kBase + val(s[i])) % kMod; + suffixHash = (val(s[j]) * pow + suffixHash) % kMod; + pow = pow * kBase % kMod; + if (prefixHash == suffixHash) + maxLength = i + 1; + } + + return s.substr(0, maxLength); + } + + private: + constexpr int val(char c) { + return c - 'a'; + } +}; diff --git a/solutions/1392. Longest Happy Prefix/1392.java b/solutions/1392. Longest Happy Prefix/1392.java new file mode 100644 index 00000000000..d0f2a839a61 --- /dev/null +++ b/solutions/1392. Longest Happy Prefix/1392.java @@ -0,0 +1,25 @@ +class Solution { + public String longestPrefix(String s) { + final int kBase = 26; + final int kMod = 1_000_000_007; + final int n = s.length(); + int maxLength = 0; + long pow = 1; + long prefixHash = 0; // the hash of s[0..i] + long suffixHash = 0; // the hash of s[j..n) + + for (int i = 0, j = n - 1; i < n - 1; ++i, --j) { + prefixHash = (prefixHash * kBase + val(s.charAt(i))) % kMod; + suffixHash = (val(s.charAt(j)) * pow + suffixHash) % kMod; + pow = pow * kBase % kMod; + if (prefixHash == suffixHash) + maxLength = i + 1; + } + + return s.substring(0, maxLength); + } + + private int val(char c) { + return c - 'a'; + } +} diff --git a/solutions/1392. Longest Happy Prefix/1392.py b/solutions/1392. Longest Happy Prefix/1392.py new file mode 100644 index 00000000000..4bd55c9f223 --- /dev/null +++ b/solutions/1392. Longest Happy Prefix/1392.py @@ -0,0 +1,23 @@ +class Solution: + def longestPrefix(self, s: str) -> str: + kBase = 26 + kMod = 1_000_000_007 + n = len(s) + maxLength = 0 + pow = 1 + prefixHash = 0 # the hash of s[0..i] + suffixHash = 0 # the hash of s[j..n) + + def val(c: str) -> int: + return ord(c) - ord('a') + + j = n - 1 + for i in range(n - 1): + prefixHash = (prefixHash * kBase + val(s[i])) % kMod + suffixHash = (val(s[j]) * pow + suffixHash) % kMod + pow = pow * kBase % kMod + if prefixHash == suffixHash: + maxLength = i + 1 + j -= 1 + + return s[:maxLength] diff --git "a/solutions/1393. Capital Gain\357\274\217Loss/1393.sql" "b/solutions/1393. Capital Gain\357\274\217Loss/1393.sql" new file mode 100644 index 00000000000..88f8d3da185 --- /dev/null +++ "b/solutions/1393. Capital Gain\357\274\217Loss/1393.sql" @@ -0,0 +1,5 @@ +SELECT + stock_name, + SUM(IF(operation = 'Buy', -price, price)) AS capital_gain_loss +FROM Stocks +GROUP BY 1; diff --git a/solutions/1394. Find Lucky Integer in an Array/1394.cpp b/solutions/1394. Find Lucky Integer in an Array/1394.cpp new file mode 100644 index 00000000000..2ade04f6d1e --- /dev/null +++ b/solutions/1394. Find Lucky Integer in an Array/1394.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int findLucky(vector& arr) { + vector count(arr.size() + 1); + + for (const int a : arr) + if (a <= arr.size()) + ++count[a]; + + for (int i = arr.size(); i >= 1; --i) + if (count[i] == i) + return i; + + return -1; + } +}; diff --git a/solutions/1394. Find Lucky Integer in an Array/1394.java b/solutions/1394. Find Lucky Integer in an Array/1394.java new file mode 100644 index 00000000000..d35c5cb4627 --- /dev/null +++ b/solutions/1394. Find Lucky Integer in an Array/1394.java @@ -0,0 +1,15 @@ +class Solution { + public int findLucky(int[] arr) { + int[] count = new int[arr.length + 1]; + + for (final int a : arr) + if (a <= arr.length) + ++count[a]; + + for (int i = arr.length; i >= 1; --i) + if (count[i] == i) + return i; + + return -1; + } +} diff --git a/solutions/1394. Find Lucky Integer in an Array/1394.py b/solutions/1394. Find Lucky Integer in an Array/1394.py new file mode 100644 index 00000000000..4d69cad83cc --- /dev/null +++ b/solutions/1394. Find Lucky Integer in an Array/1394.py @@ -0,0 +1,13 @@ +class Solution: + def findLucky(self, arr: List[int]) -> int: + count = [0] * (len(arr) + 1) + + for a in arr: + if a <= len(arr): + count[a] += 1 + + for i in range(len(arr), 0, -1): + if count[i] == i: + return i + + return -1 diff --git a/solutions/1395. Count Number of Teams/1395.cpp b/solutions/1395. Count Number of Teams/1395.cpp new file mode 100644 index 00000000000..d0e74419431 --- /dev/null +++ b/solutions/1395. Count Number of Teams/1395.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int numTeams(vector& rating) { + int ans = 0; + + for (int i = 1; i < rating.size() - 1; ++i) { + // Calculate soldiers on the left with less/greater ratings. + int leftLess = 0; + int leftGreater = 0; + for (int j = 0; j < i; ++j) + if (rating[j] < rating[i]) + ++leftLess; + else if (rating[j] > rating[i]) + ++leftGreater; + // Calculate soldiers on the right with less/greater ratings. + int rightLess = 0; + int rightGreater = 0; + for (int j = i + 1; j < rating.size(); ++j) + if (rating[j] < rating[i]) + ++rightLess; + else if (rating[j] > rating[i]) + ++rightGreater; + ans += leftLess * rightGreater + leftGreater * rightLess; + } + + return ans; + } +}; diff --git a/solutions/1395. Count Number of Teams/1395.java b/solutions/1395. Count Number of Teams/1395.java new file mode 100644 index 00000000000..0f1b3725a55 --- /dev/null +++ b/solutions/1395. Count Number of Teams/1395.java @@ -0,0 +1,27 @@ +class Solution { + public int numTeams(int[] rating) { + int ans = 0; + + for (int i = 1; i < rating.length - 1; ++i) { + // Calculate soldiers on the left with less/greater ratings. + int leftLess = 0; + int leftGreater = 0; + for (int j = 0; j < i; ++j) + if (rating[j] < rating[i]) + ++leftLess; + else if (rating[j] > rating[i]) + ++leftGreater; + // Calculate soldiers on the right with less/greater ratings. + int rightLess = 0; + int rightGreater = 0; + for (int j = i + 1; j < rating.length; ++j) + if (rating[j] < rating[i]) + ++rightLess; + else if (rating[j] > rating[i]) + ++rightGreater; + ans += leftLess * rightGreater + leftGreater * rightLess; + } + + return ans; + } +} diff --git a/solutions/1395. Count Number of Teams/1395.py b/solutions/1395. Count Number of Teams/1395.py new file mode 100644 index 00000000000..9f2d99a239e --- /dev/null +++ b/solutions/1395. Count Number of Teams/1395.py @@ -0,0 +1,24 @@ +class Solution: + def numTeams(self, rating: List[int]) -> int: + ans = 0 + + for i in range(1, len(rating) - 1): + # Calculate soldiers on the left with less//greater ratings. + leftLess = 0 + leftGreater = 0 + for j in range(i): + if rating[j] < rating[i]: + leftLess += 1 + elif rating[j] > rating[i]: + leftGreater += 1 + # Calculate soldiers on the right with less//greater ratings. + rightLess = 0 + rightGreater = 0 + for j in range(i + 1, len(rating)): + if rating[j] < rating[i]: + rightLess += 1 + elif rating[j] > rating[i]: + rightGreater += 1 + ans += leftLess * rightGreater + leftGreater * rightLess + + return ans diff --git a/solutions/1396. Design Underground System/1396.cpp b/solutions/1396. Design Underground System/1396.cpp new file mode 100644 index 00000000000..7b9a016fe0d --- /dev/null +++ b/solutions/1396. Design Underground System/1396.cpp @@ -0,0 +1,34 @@ +struct CheckIn { + string stationName; + int time; +}; + +struct CheckOut { + int numTrips; + int totalTime; +}; + +class UndergroundSystem { + public: + void checkIn(int id, string stationName, int t) { + checkIns[id] = {stationName, t}; + } + + void checkOut(int id, string stationName, int t) { + const auto [startStation, startTime] = checkIns[id]; + checkIns.erase(id); + const string& route = startStation + "->" + stationName; + ++checkOuts[route].numTrips; + checkOuts[route].totalTime += t - startTime; + } + + double getAverageTime(string startStation, string endStation) { + const auto& [numTrips, totalTime] = + checkOuts[startStation + "->" + endStation]; + return totalTime / (double)numTrips; + } + + private: + unordered_map checkIns; // {id: (stationName, time)} + unordered_map checkOuts; // {route: (numTrips, totalTime)} +}; diff --git a/solutions/1396. Design Underground System/1396.java b/solutions/1396. Design Underground System/1396.java new file mode 100644 index 00000000000..704d7dda8ba --- /dev/null +++ b/solutions/1396. Design Underground System/1396.java @@ -0,0 +1,40 @@ +class CheckIn { + public String stationName; + public int time; + public CheckIn(String stationName, int time) { + this.stationName = stationName; + this.time = time; + } +} + +class CheckOut { + public int numTrips; + public int totalTime; + public CheckOut(int numTrips, int totalTime) { + this.numTrips = numTrips; + this.totalTime = totalTime; + } +} + +class UndergroundSystem { + public void checkIn(int id, String stationName, int t) { + checkIns.put(id, new CheckIn(stationName, t)); + } + + public void checkOut(int id, String stationName, int t) { + final CheckIn checkIn = checkIns.get(id); + checkIns.remove(id); + final String route = checkIn.stationName + "->" + stationName; + checkOuts.putIfAbsent(route, new CheckOut(0, 0)); + ++checkOuts.get(route).numTrips; + checkOuts.get(route).totalTime += t - checkIn.time; + } + + public double getAverageTime(String startStation, String endStation) { + final CheckOut checkOut = checkOuts.get(startStation + "->" + endStation); + return checkOut.totalTime / (double) checkOut.numTrips; + } + + private Map checkIns = new HashMap<>(); // {id: (stationName, time)} + private Map checkOuts = new HashMap<>(); // {route: (numTrips, totalTime)} +} diff --git a/solutions/1396. Design Underground System/1396.py b/solutions/1396. Design Underground System/1396.py new file mode 100644 index 00000000000..e772ae99870 --- /dev/null +++ b/solutions/1396. Design Underground System/1396.py @@ -0,0 +1,19 @@ +class UndergroundSystem: + def __init__(self): + # {id: (stationName, time)} + self.checkIns = {} + # {route: (numTrips, totalTime)} + self.checkOuts = collections.defaultdict(lambda: [0, 0]) + + def checkIn(self, id: int, stationName: str, t: int) -> None: + self.checkIns[id] = (stationName, t) + + def checkOut(self, id: int, stationName: str, t: int) -> None: + startStation, startTime = self.checkIns.pop(id) + route = (startStation, stationName) + self.checkOuts[route][0] += 1 + self.checkOuts[route][1] += t - startTime + + def getAverageTime(self, startStation: str, endStation: str) -> float: + numTrips, totalTime = self.checkOuts[(startStation, endStation)] + return totalTime / numTrips diff --git a/solutions/1397. Find All Good Strings/1397.cpp b/solutions/1397. Find All Good Strings/1397.cpp new file mode 100644 index 00000000000..66066dcaf35 --- /dev/null +++ b/solutions/1397. Find All Good Strings/1397.cpp @@ -0,0 +1,72 @@ +class Solution { + public: + int findGoodStrings(int n, string s1, string s2, string evil) { + vector>>> mem( + n, vector>>( + evil.length(), vector>(2, vector(2, -1)))); + // nextMatchedCount[i][j] := the number of next matched evil count, where + // there're i matches with `evil` and the current letter is ('a' + j) + vector> nextMatchedCount(evil.length(), vector(26, -1)); + return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount, + mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of good strings for s[i..n), where there're j matches + // with `evil`, `isS1Prefix` indicates if the current letter is tightly bound + // for `s1` and `isS2Prefix` indicates if the current letter is tightly bound + // for `s2`. + int count(const string& s1, const string& s2, const string& evil, int i, + int matchedEvilCount, bool isS1Prefix, bool isS2Prefix, + const vector& evilLPS, vector>& nextMatchedCount, + vector>>>& mem) { + // s[0..i) contains `evil`, so don't consider any ongoing strings. + if (matchedEvilCount == evil.length()) + return 0; + // Run out of strings, so contribute one. + if (i == s1.length()) + return 1; + int& res = mem[i][matchedEvilCount][isS1Prefix][isS2Prefix]; + if (res != -1) + return res; + res = 0; + const char minLetter = isS1Prefix ? s1[i] : 'a'; + const char maxLetter = isS2Prefix ? s2[i] : 'z'; + for (char c = minLetter; c <= maxLetter; ++c) { + const int nextMatchedEvilCount = getNextMatchedEvilCount( + nextMatchedCount, evil, matchedEvilCount, c, evilLPS); + res += count(s1, s2, evil, i + 1, nextMatchedEvilCount, + isS1Prefix && c == s1[i], isS2Prefix && c == s2[i], evilLPS, + nextMatchedCount, mem); + res %= kMod; + } + return res; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + vector getLPS(const string& pattern) { + vector lps(pattern.length()); + for (int i = 1, j = 0; i < pattern.length(); ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } + + // j := the next index we're trying to match with `currLetter` + int getNextMatchedEvilCount(vector>& nextMatchedCount, + const string& evil, int j, char currLetter, + const vector& evilLPS) { + int& res = nextMatchedCount[j][currLetter - 'a']; + if (res != -1) + return res; + while (j > 0 && evil[j] != currLetter) + j = evilLPS[j - 1]; + return res = (evil[j] == currLetter ? j + 1 : j); + } +}; diff --git a/solutions/1397. Find All Good Strings/1397.java b/solutions/1397. Find All Good Strings/1397.java new file mode 100644 index 00000000000..780c19ede49 --- /dev/null +++ b/solutions/1397. Find All Good Strings/1397.java @@ -0,0 +1,65 @@ +class Solution { + public int findGoodStrings(int n, String s1, String s2, String evil) { + Integer[][][][] mem = new Integer[n][evil.length()][2][2]; + // nextMatchedCount[i][j] := the number of next matched evil count, where + // there're j matches with `evil` and the current letter is ('a' + j) + Integer[][] nextMatchedCount = new Integer[evil.length()][26]; + return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of good strings for s[i..n), where there're j matches + // with `evil`, `isS1Prefix` indicates if the current letter is tightly bound + // for `s1` and `isS2Prefix` indicates if the current letter is tightly bound + // for `s2`. + private int count(final String s1, final String s2, final String evil, int i, + int matchedEvilCount, boolean isS1Prefix, boolean isS2Prefix, int[] evilLPS, + Integer[][] nextMatchedCount, Integer[][][][] mem) { + // s[0..i) contains `evil`, so don't consider any ongoing strings. + if (matchedEvilCount == evil.length()) + return 0; + // Run out of strings, so contribute one. + if (i == s1.length()) + return 1; + final int k1 = isS1Prefix ? 1 : 0; + final int k2 = isS2Prefix ? 1 : 0; + if (mem[i][matchedEvilCount][k1][k2] != null) + return mem[i][matchedEvilCount][k1][k2]; + mem[i][matchedEvilCount][k1][k2] = 0; + final char minChar = isS1Prefix ? s1.charAt(i) : 'a'; + final char maxChar = isS2Prefix ? s2.charAt(i) : 'z'; + for (char c = minChar; c <= maxChar; ++c) { + final int nextMatchedEvilCount = + getNextMatchedEvilCount(nextMatchedCount, evil, matchedEvilCount, c, evilLPS); + mem[i][matchedEvilCount][k1][k2] += + count(s1, s2, evil, i + 1, nextMatchedEvilCount, isS1Prefix && c == s1.charAt(i), + isS2Prefix && c == s2.charAt(i), evilLPS, nextMatchedCount, mem); + mem[i][matchedEvilCount][k1][k2] %= kMod; + } + return mem[i][matchedEvilCount][k1][k2]; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + private int[] getLPS(final String pattern) { + int[] lps = new int[pattern.length()]; + for (int i = 1, j = 0; i < pattern.length(); ++i) { + while (j > 0 && pattern.charAt(j) != pattern.charAt(i)) + j = lps[j - 1]; + if (pattern.charAt(i) == pattern.charAt(j)) + lps[i] = ++j; + } + return lps; + } + + // j := the next index we're trying to match with `currLetter` + private int getNextMatchedEvilCount(Integer[][] nextMatchedCount, final String evil, int j, + char currChar, int[] lps) { + if (nextMatchedCount[j][currChar - 'a'] != null) + return nextMatchedCount[j][currChar - 'a']; + while (j > 0 && evil.charAt(j) != currChar) + j = lps[j - 1]; + return nextMatchedCount[j][currChar - 'a'] = (evil.charAt(j) == currChar ? j + 1 : j); + } +} diff --git a/solutions/1397. Find All Good Strings/1397.py b/solutions/1397. Find All Good Strings/1397.py new file mode 100644 index 00000000000..6da2407b5ed --- /dev/null +++ b/solutions/1397. Find All Good Strings/1397.py @@ -0,0 +1,57 @@ +class Solution: + def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int: + kMod = 1_000_000_007 + evilLPS = self._getLPS(evil) + + @functools.lru_cache(None) + def getNextMatchedEvilCount(j: int, currChar: str) -> int: + """ + Returns the number of next matched evil count, where there're j matches + with `evil` and the current letter is ('a' + j). + """ + while j > 0 and evil[j] != currChar: + j = evilLPS[j - 1] + return j + 1 if evil[j] == currChar else j + + @functools.lru_cache(None) + def dp(i: int, matchedEvilCount: int, isS1Prefix: bool, isS2Prefix: bool) -> int: + """ + Returns the number of good strings for s[i..n), where there're j matches + with `evil`, `isS1Prefix` indicates if the current letter is tightly bound + for `s1` and `isS2Prefix` indicates if the current letter is tightly bound + for `s2`. + """ + # s[0..i) contains `evil`, so don't consider any ongoing strings. + if matchedEvilCount == len(evil): + return 0 + # Run out of strings, so contribute one. + if i == n: + return 1 + ans = 0 + minCharIndex = ord(s1[i]) if isS1Prefix else ord('a') + maxCharIndex = ord(s2[i]) if isS2Prefix else ord('z') + for charIndex in range(minCharIndex, maxCharIndex + 1): + c = chr(charIndex) + nextMatchedEvilCount = getNextMatchedEvilCount(matchedEvilCount, c) + ans += dp(i + 1, nextMatchedEvilCount, + isS1Prefix and c == s1[i], + isS2Prefix and c == s2[i]) + ans %= kMod + return ans + + return dp(0, 0, True, True) + + def _getLPS(self, pattern: str) -> List[int]: + """ + Returns the lps array, where lps[i] is the length of the longest prefix of + pattern[0..i] which is also a suffix of this substring. + """ + lps = [0] * len(pattern) + j = 0 + for i in range(1, len(pattern)): + while j > 0 and pattern[j] != pattern[i]: + j = lps[j - 1] + if pattern[i] == pattern[j]: + lps[i] = j + 1 + j += 1 + return lps diff --git a/solutions/1398. Customers Who Bought Products A and B but Not C/1398.sql b/solutions/1398. Customers Who Bought Products A and B but Not C/1398.sql new file mode 100644 index 00000000000..12dfe031339 --- /dev/null +++ b/solutions/1398. Customers Who Bought Products A and B but Not C/1398.sql @@ -0,0 +1,11 @@ +SELECT + customer_id, + customer_name +FROM Customers +INNER JOIN Orders + USING (customer_id) +GROUP BY 1 +HAVING + SUM(Orders.product_name = 'A') > 0 + AND SUM(Orders.product_name = 'B') > 0 + AND SUM(Orders.product_name = 'C') = 0; diff --git a/solutions/1399. Count Largest Group/1399.cpp b/solutions/1399. Count Largest Group/1399.cpp new file mode 100644 index 00000000000..97eadeb27c1 --- /dev/null +++ b/solutions/1399. Count Largest Group/1399.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countLargestGroup(int n) { + vector count(9 * 4 + 1); + for (int i = 1; i <= n; ++i) + ++count[getDigitSum(i)]; + return ranges::count(count, ranges::max(count)); + } + + private: + int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +}; diff --git a/solutions/1399. Count Largest Group/1399.java b/solutions/1399. Count Largest Group/1399.java new file mode 100644 index 00000000000..d23d89162cf --- /dev/null +++ b/solutions/1399. Count Largest Group/1399.java @@ -0,0 +1,18 @@ +class Solution { + public int countLargestGroup(int n) { + int[] count = new int[9 * 4 + 1]; + for (int i = 1; i <= n; ++i) + ++count[getDigitSum(i)]; + final int mx = Arrays.stream(count).max().getAsInt(); + return (int) Arrays.stream(count).filter(c -> c == mx).count(); + } + + private int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +} diff --git a/solutions/1399. Count Largest Group/1399.py b/solutions/1399. Count Largest Group/1399.py new file mode 100644 index 00000000000..79c3ba1213c --- /dev/null +++ b/solutions/1399. Count Largest Group/1399.py @@ -0,0 +1,9 @@ +class Solution: + def countLargestGroup(self, n: int) -> int: + count = [0] * (9 * 4 + 1) + for i in range(1, n + 1): + count[self._getDigitSum(i)] += 1 + return count.count(max(count)) + + def _getDigitSum(self, num: int) -> int: + return sum(int(digit) for digit in str(num)) diff --git a/solutions/14. Longest Common Prefix/14.cpp b/solutions/14. Longest Common Prefix/14.cpp new file mode 100644 index 00000000000..9bde5a953cc --- /dev/null +++ b/solutions/14. Longest Common Prefix/14.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) + return ""; + + for (int i = 0; i < strs[0].length(); ++i) + for (int j = 1; j < strs.size(); ++j) + if (i == strs[j].length() || strs[j][i] != strs[0][i]) + return strs[0].substr(0, i); + + return strs[0]; + } +}; diff --git a/solutions/14. Longest Common Prefix/14.java b/solutions/14. Longest Common Prefix/14.java new file mode 100644 index 00000000000..7a87fd87369 --- /dev/null +++ b/solutions/14. Longest Common Prefix/14.java @@ -0,0 +1,13 @@ +class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs.length == 0) + return ""; + + for (int i = 0; i < strs[0].length(); ++i) + for (int j = 1; j < strs.length; ++j) + if (i == strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)) + return strs[0].substring(0, i); + + return strs[0]; + } +} diff --git a/solutions/14. Longest Common Prefix/14.py b/solutions/14. Longest Common Prefix/14.py new file mode 100644 index 00000000000..a17772d893d --- /dev/null +++ b/solutions/14. Longest Common Prefix/14.py @@ -0,0 +1,11 @@ +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + if not strs: + return '' + + for i in range(len(strs[0])): + for j in range(1, len(strs)): + if i == len(strs[j]) or strs[j][i] != strs[0][i]: + return strs[0][:i] + + return strs[0] diff --git a/solutions/140. Word Break II/140.cpp b/solutions/140. Word Break II/140.cpp new file mode 100644 index 00000000000..448aeedbe6e --- /dev/null +++ b/solutions/140. Word Break II/140.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector wordBreak(string s, vector& wordDict) { + unordered_set wordSet{wordDict.begin(), wordDict.end()}; + unordered_map> mem; + return wordBreak(s, wordSet, mem); + } + + private: + vector wordBreak(const string& s, + const unordered_set& wordSet, + unordered_map>& mem) { + if (const auto it = mem.find(s); it != mem.cend()) + return it->second; + + vector ans; + + // 1 <= prefix.length() < s.length() + for (int i = 1; i < s.length(); ++i) { + const string& prefix = s.substr(0, i); + const string& suffix = s.substr(i); + if (wordSet.contains(prefix)) + for (const string& word : wordBreak(suffix, wordSet, mem)) + ans.push_back(prefix + " " + word); + } + + // `wordSet` contains the whole string s, so don't add any space. + if (wordSet.contains(s)) + ans.push_back(s); + + return mem[s] = ans; + } +}; diff --git a/solutions/140. Word Break II/140.java b/solutions/140. Word Break II/140.java new file mode 100644 index 00000000000..4b44fde4cc8 --- /dev/null +++ b/solutions/140. Word Break II/140.java @@ -0,0 +1,31 @@ +class Solution { + public List wordBreak(String s, List wordDict) { + Set wordSet = new HashSet<>(wordDict); + Map> mem = new HashMap<>(); + return wordBreak(s, wordSet, mem); + } + + private List wordBreak(final String s, Set wordSet, + Map> mem) { + if (mem.containsKey(s)) + return mem.get(s); + + List ans = new ArrayList<>(); + + // 1 <= prefix.length() < s.length() + for (int i = 1; i < s.length(); ++i) { + final String prefix = s.substring(0, i); + final String suffix = s.substring(i); + if (wordSet.contains(prefix)) + for (final String word : wordBreak(suffix, wordSet, mem)) + ans.add(prefix + " " + word); + } + + // `wordSet` contains the whole string s, so don't add any space. + if (wordSet.contains(s)) + ans.add(s); + + mem.put(s, ans); + return ans; + } +} diff --git a/solutions/140. Word Break II/140.py b/solutions/140. Word Break II/140.py new file mode 100644 index 00000000000..ca2c2cbebae --- /dev/null +++ b/solutions/140. Word Break II/140.py @@ -0,0 +1,23 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: + wordSet = set(wordDict) + + @functools.lru_cache(None) + def wordBreak(s: str) -> List[str]: + ans = [] + + # 1 <= len(prefix) < len(s) + for i in range(1, len(s)): + prefix = s[0:i] + suffix = s[i:] + if prefix in wordSet: + for word in wordBreak(suffix): + ans.append(prefix + ' ' + word) + + # `wordSet` contains the whole string s, so don't add any space. + if s in wordSet: + ans.append(s) + + return ans + + return wordBreak(s) diff --git a/solutions/1400. Construct K Palindrome Strings/1400.cpp b/solutions/1400. Construct K Palindrome Strings/1400.cpp new file mode 100644 index 00000000000..7ba52377df6 --- /dev/null +++ b/solutions/1400. Construct K Palindrome Strings/1400.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool canConstruct(string s, int k) { + // If |s| < k, we cannot construct k strings from the s. + if (s.length() < k) + return false; + + bitset<26> odd; + + for (const char c : s) + odd.flip(c - 'a'); + + // If the number of letters that have odd counts > k, the minimum number of + // palindromic strings we can construct is > k. + return odd.contains() <= k; + } +}; diff --git a/solutions/1400. Construct K Palindrome Strings/1400.java b/solutions/1400. Construct K Palindrome Strings/1400.java new file mode 100644 index 00000000000..32e2e8314ed --- /dev/null +++ b/solutions/1400. Construct K Palindrome Strings/1400.java @@ -0,0 +1,16 @@ +class Solution { + public boolean canConstruct(String s, int k) { + // If |s| < k, we cannot construct k strings from the s. + if (s.length() < k) + return false; + + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + count[c - 'a'] ^= 1; + + // If the number of letters that have odd counts > k, the minimum number of + // palindromic strings we can construct is > k. + return Arrays.stream(count).filter(c -> c % 2 == 1).count() <= k; + } +} diff --git a/solutions/1400. Construct K Palindrome Strings/1400.py b/solutions/1400. Construct K Palindrome Strings/1400.py new file mode 100644 index 00000000000..76bb3cc6a5d --- /dev/null +++ b/solutions/1400. Construct K Palindrome Strings/1400.py @@ -0,0 +1,7 @@ +class Solution: + def canConstruct(self, s: str, k: int) -> bool: + # If |s| < k, we cannot construct k strings from the s. + # If the number of letters that have odd counts > k, the minimum number of + # palindromic strings we can construct is > k. + return sum(freq & 1 + for freq in collections.Counter(s).values()) <= k <= len(s) diff --git a/solutions/1401. Circle and Rectangle Overlapping/1401.cpp b/solutions/1401. Circle and Rectangle Overlapping/1401.cpp new file mode 100644 index 00000000000..e4fc15ce0e9 --- /dev/null +++ b/solutions/1401. Circle and Rectangle Overlapping/1401.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool checkOverlap(int radius, int x_center, int y_center, int x1, int y1, + int x2, int y2) { + auto clamp = [&](int center, int mn, int mx) { + return max(mn, min(mx, center)); + }; + + // the closest point to the circle within the rectangle + int closestX = clamp(x_center, x1, x2); + int closestY = clamp(y_center, y1, y2); + + // the distance between the circle's center and its closest point + int distanceX = x_center - closestX; + int distanceY = y_center - closestY; + + // If the distance < the circle's radius, an intersection occurs. + return (distanceX * distanceX) + (distanceY * distanceY) <= + (radius * radius); + } +}; diff --git a/solutions/1402. Reducing Dishes/1402.cpp b/solutions/1402. Reducing Dishes/1402.cpp new file mode 100644 index 00000000000..865d6bf7c2b --- /dev/null +++ b/solutions/1402. Reducing Dishes/1402.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxSatisfaction(vector& satisfaction) { + int ans = 0; + int sumSatisfaction = 0; + + ranges::sort(satisfaction, greater<>()); + + for (const int s : satisfaction) { + sumSatisfaction += s; + if (sumSatisfaction <= 0) + return ans; + ans += sumSatisfaction; + } + + return ans; + } +}; diff --git a/solutions/1402. Reducing Dishes/1402.java b/solutions/1402. Reducing Dishes/1402.java new file mode 100644 index 00000000000..6de12f89fe4 --- /dev/null +++ b/solutions/1402. Reducing Dishes/1402.java @@ -0,0 +1,21 @@ +class Solution { + public int maxSatisfaction(int[] satisfaction) { + int ans = 0; + int sumSatisfaction = 0; + + satisfaction = Arrays.stream(satisfaction) + .boxed() + .sorted(Collections.reverseOrder()) + .mapToInt(Integer::intValue) + .toArray(); + + for (final int s : satisfaction) { + sumSatisfaction += s; + if (sumSatisfaction <= 0) + return ans; + ans += sumSatisfaction; + } + + return ans; + } +} diff --git a/solutions/1402. Reducing Dishes/1402.py b/solutions/1402. Reducing Dishes/1402.py new file mode 100644 index 00000000000..3ce980bad56 --- /dev/null +++ b/solutions/1402. Reducing Dishes/1402.py @@ -0,0 +1,12 @@ +class Solution: + def maxSatisfaction(self, satisfaction: List[int]) -> int: + ans = 0 + sumSatisfaction = 0 + + for s in sorted(satisfaction, reverse=True): + sumSatisfaction += s + if sumSatisfaction <= 0: + return ans + ans += sumSatisfaction + + return ans diff --git a/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.cpp b/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.cpp new file mode 100644 index 00000000000..e791223e8b0 --- /dev/null +++ b/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector minSubsequence(vector& nums) { + vector ans; + priority_queue maxHeap(nums.begin(), nums.end()); + int half = accumulate(nums.begin(), nums.end(), 0) / 2; + + while (half >= 0) { + ans.push_back(maxHeap.top()); + half -= maxHeap.top(), maxHeap.pop(); + } + + return ans; + } +}; diff --git a/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.java b/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.java new file mode 100644 index 00000000000..b9908f05b1a --- /dev/null +++ b/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.java @@ -0,0 +1,16 @@ +class Solution { + public List minSubsequence(int[] nums) { + List ans = new ArrayList<>(); + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + for (final int num : nums) + maxHeap.offer(num); + int half = Arrays.stream(nums).sum() / 2; + + while (half >= 0) { + ans.add(maxHeap.peek()); + half -= maxHeap.poll(); + } + + return ans; + } +} diff --git a/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.py b/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.py new file mode 100644 index 00000000000..f400c68a85d --- /dev/null +++ b/solutions/1403. Minimum Subsequence in Non-Increasing Order/1403.py @@ -0,0 +1,12 @@ +class Solution: + def minSubsequence(self, nums: List[int]) -> List[int]: + ans = [] + maxHeap = [-num for num in nums] + heapq.heapify(maxHeap) + half = sum(nums) // 2 + + while half >= 0: + ans.append(-maxHeap[0]) + half += heapq.heappop(maxHeap) + + return ans diff --git a/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.cpp b/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.cpp new file mode 100644 index 00000000000..98f90571353 --- /dev/null +++ b/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int numSteps(string s) { + int ans = 0; + + // All the trailing 0s can be popped by 1 step. + while (s.back() == '0') { + s.pop_back(); + ++ans; + } + + if (s == "1") + return ans; + + // `s` is now odd, so add 1 to `s` and cost 1 step. + ++ans; + + // All the 1s will become 0s and can be popped by 1 step. + // All the 0s will become 1s and can be popped by 2 steps (adding 1 then + // dividing by 2). + for (const char c : s) + ans += c == '1' ? 1 : 2; + + return ans; + } +}; diff --git a/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.java b/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.java new file mode 100644 index 00000000000..a041ee5df0b --- /dev/null +++ b/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.java @@ -0,0 +1,26 @@ +class Solution { + public int numSteps(String s) { + int ans = 0; + StringBuilder sb = new StringBuilder(s); + + // All the trailing 0s can be popped by 1 step. + while (sb.charAt(sb.length() - 1) == '0') { + sb.deleteCharAt(sb.length() - 1); + ++ans; + } + + if (sb.toString().equals("1")) + return ans; + + // `s` is now odd, so add 1 to `s` and cost 1 step. + ++ans; + + // All the 1s will become 0s and can be popped by 1 step. + // All the 0s will become 1s and can be popped by 2 steps (adding 1 then + // dividing by 2). + for (final char c : sb.toString().toCharArray()) + ans += c == '1' ? 1 : 2; + + return ans; + } +} diff --git a/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.py b/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.py new file mode 100644 index 00000000000..70436a29b34 --- /dev/null +++ b/solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.py @@ -0,0 +1,18 @@ +class Solution: + def numSteps(self, s: str) -> int: + ans = 0 + chars = list(s) + + # All the trailing 0s can be popped by 1 step. + while chars[-1] == '0': + chars.pop() + ans += 1 + + if ''.join(chars) == '1': + return ans + + # `s` is now odd, so add 1 to `s` and cost 1 step. + # All the 1s will become 0s and can be popped by 1 step. + # All the 0s will become 1s and can be popped by 2 steps (adding 1 then + # dividing by 2). + return ans + 1 + sum(1 if c == '1' else 2 for c in chars) diff --git a/solutions/1405. Longest Happy String/1405.cpp b/solutions/1405. Longest Happy String/1405.cpp new file mode 100644 index 00000000000..6bb60162b69 --- /dev/null +++ b/solutions/1405. Longest Happy String/1405.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string longestDiverseString(int a, int b, int c, char A = 'a', char B = 'b', + char C = 'c') { + if (a < b) + return longestDiverseString(b, a, c, B, A, C); + if (b < c) + return longestDiverseString(a, c, b, A, C, B); + if (b == 0) + return string(min(a, 2), A); + + const int useA = min(a, 2); + const int useB = (a - useA >= b) ? 1 : 0; + return string(useA, A) + string(useB, B) + + longestDiverseString(a - useA, b - useB, c, A, B, C); + } +}; diff --git a/solutions/1406. Stone Game III/1406-2.cpp b/solutions/1406. Stone Game III/1406-2.cpp new file mode 100644 index 00000000000..7b6061ad414 --- /dev/null +++ b/solutions/1406. Stone Game III/1406-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string stoneGameIII(vector& stoneValue) { + const int n = stoneValue.size(); + // dp[i] := the maximum relative score Alice can make with stoneValue[i..n) + vector dp(n + 1, INT_MIN / 2); + dp.back() = 0; + + for (int i = n - 1; i >= 0; --i) { + int sum = 0; + for (int j = i; j < i + 3 && j < n; ++j) { + sum += stoneValue[j]; + dp[i] = max(dp[i], sum - dp[j + 1]); + } + } + + const int score = dp[0]; + return score > 0 ? "Alice" : score < 0 ? "Bob" : "Tie"; + } +}; diff --git a/solutions/1406. Stone Game III/1406-2.java b/solutions/1406. Stone Game III/1406-2.java new file mode 100644 index 00000000000..169f10203d1 --- /dev/null +++ b/solutions/1406. Stone Game III/1406-2.java @@ -0,0 +1,19 @@ +class Solution { + public String stoneGameIII(int[] stoneValue) { + final int n = stoneValue.length; + // dp[i] := the maximum relative score Alice can make with stoneValue[i..n) + int[] dp = new int[n + 1]; + Arrays.fill(dp, 0, n, Integer.MIN_VALUE / 2); + + for (int i = n - 1; i >= 0; --i) { + int sum = 0; + for (int j = i; j < i + 3 && j < n; ++j) { + sum += stoneValue[j]; + dp[i] = Math.max(dp[i], sum - dp[j + 1]); + } + } + + final int score = dp[0]; + return score > 0 ? "Alice" : score < 0 ? "Bob" : "Tie"; + } +} diff --git a/solutions/1406. Stone Game III/1406-2.py b/solutions/1406. Stone Game III/1406-2.py new file mode 100644 index 00000000000..6ecdc972a05 --- /dev/null +++ b/solutions/1406. Stone Game III/1406-2.py @@ -0,0 +1,18 @@ +class Solution: + def stoneGameIII(self, stoneValue: List[int]) -> str: + n = len(stoneValue) + # dp[i] := the maximum relative score Alice can make with stoneValue[i..n) + dp = [-math.inf] * n + [0] + + for i in reversed(range(n)): + summ = 0 + for j in range(i, i + 3): + if j == n: + break + summ += stoneValue[j] + dp[i] = max(dp[i], summ - dp[j + 1]) + + score = dp[0] + if score == 0: + return 'Tie' + return 'Alice' if score > 0 else 'Bob' diff --git a/solutions/1406. Stone Game III/1406.cpp b/solutions/1406. Stone Game III/1406.cpp new file mode 100644 index 00000000000..a240b026408 --- /dev/null +++ b/solutions/1406. Stone Game III/1406.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string stoneGameIII(vector& stoneValue) { + vector mem(stoneValue.size(), INT_MIN); + const int score = stoneGameIII(stoneValue, 0, mem); + return score > 0 ? "Alice" : score < 0 ? "Bob" : "Tie"; + } + + private: + // Returns the maximum relative score Alice can make from stoneValue[i..n). + int stoneGameIII(const vector& stoneValue, int i, vector& mem) { + if (i == stoneValue.size()) + return 0; + if (mem[i] > INT_MIN) + return mem[i]; + + int sum = 0; + for (int j = i; j < i + 3 && j < stoneValue.size(); ++j) { + sum += stoneValue[j]; + mem[i] = max(mem[i], sum - stoneGameIII(stoneValue, j + 1, mem)); + } + + return mem[i]; + }; +}; diff --git a/solutions/1406. Stone Game III/1406.java b/solutions/1406. Stone Game III/1406.java new file mode 100644 index 00000000000..2cabbf8a3b1 --- /dev/null +++ b/solutions/1406. Stone Game III/1406.java @@ -0,0 +1,24 @@ +class Solution { + public String stoneGameIII(int[] stoneValue) { + int[] mem = new int[stoneValue.length]; + Arrays.fill(mem, Integer.MIN_VALUE); + final int score = stoneGameIII(stoneValue, 0, mem); + return score > 0 ? "Alice" : score < 0 ? "Bob" : "Tie"; + } + + // Returns the maximum relative score Alice can make from stoneValue[i..n). + private int stoneGameIII(int[] stoneValue, int i, int[] mem) { + if (i == stoneValue.length) + return 0; + if (mem[i] > Integer.MIN_VALUE) + return mem[i]; + + int sum = 0; + for (int j = i; j < i + 3 && j < stoneValue.length; ++j) { + sum += stoneValue[j]; + mem[i] = Math.max(mem[i], sum - stoneGameIII(stoneValue, j + 1, mem)); + } + + return mem[i]; + }; +} diff --git a/solutions/1406. Stone Game III/1406.py b/solutions/1406. Stone Game III/1406.py new file mode 100644 index 00000000000..b40a55e7863 --- /dev/null +++ b/solutions/1406. Stone Game III/1406.py @@ -0,0 +1,25 @@ +class Solution: + def stoneGameIII(self, stoneValue: List[int]) -> str: + @functools.lru_cache(None) + def dp(i: int) -> int: + """ + Returns the maximum relative score Alice can make with stoneValue[i..n). + """ + if i == len(stoneValue): + return 0 + + res = -math.inf + summ = 0 + + for j in range(i, i + 3): + if j == len(stoneValue): + break + summ += stoneValue[j] + res = max(res, summ - dp(j + 1)) + + return res + + score = dp(0) + if score == 0: + return 'Tie' + return 'Alice' if score > 0 else 'Bob' diff --git a/solutions/1407. Top Travellers/1407.sql b/solutions/1407. Top Travellers/1407.sql new file mode 100644 index 00000000000..afcf193ef18 --- /dev/null +++ b/solutions/1407. Top Travellers/1407.sql @@ -0,0 +1,8 @@ +SELECT + Users.name, + IFNULL(SUM(Rides.distance), 0) AS travelled_distance +FROM Users +LEFT JOIN Rides + ON (Users.id = Rides.user_id) +GROUP BY Users.id +ORDER BY 2 DESC, 1; diff --git a/solutions/1408. String Matching in an Array/1408-2.cpp b/solutions/1408. String Matching in an Array/1408-2.cpp new file mode 100644 index 00000000000..70f9b4f11c2 --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408-2.cpp @@ -0,0 +1,52 @@ +struct TrieNode { + vector> children; + TrieNode() : children(26) {} +}; + +class Trie { + public: + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + } + + bool search(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + return false; + node = node->children[i]; + } + return true; + } + + private: + shared_ptr root = make_shared(); +}; + +class Solution { + public: + vector stringMatching(vector& words) { + vector ans; + Trie trie; + + ranges::sort(words, [](const string& a, const string& b) { + return a.length() > b.length(); + }); + + for (const string& word : words) { + if (trie.search(word)) + ans.push_back(word); + for (int i = 0; i < word.length(); ++i) + trie.insert(word.substr(i)); + } + + return ans; + } +}; diff --git a/solutions/1408. String Matching in an Array/1408-2.java b/solutions/1408. String Matching in an Array/1408-2.java new file mode 100644 index 00000000000..b456a21530d --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408-2.java @@ -0,0 +1,46 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; +} + +class Trie { + public void insert(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + } + + public boolean search(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + return false; + node = node.children[i]; + } + return true; + } + + private TrieNode root = new TrieNode(); +} + +class Solution { + public List stringMatching(String[] words) { + List ans = new ArrayList<>(); + Trie trie = new Trie(); + + Arrays.sort(words, (a, b) -> b.length() - a.length()); + + for (final String word : words) { + if (trie.search(word)) + ans.add(word); + for (int i = 0; i < word.length(); ++i) + trie.insert(word.substring(i)); + } + + return ans; + } +} diff --git a/solutions/1408. String Matching in an Array/1408-2.py b/solutions/1408. String Matching in an Array/1408-2.py new file mode 100644 index 00000000000..df6454c3a40 --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408-2.py @@ -0,0 +1,35 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> None: + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + + def search(self, word: str) -> bool: + node: TrieNode = self.root + for c in word: + if c not in node.children: + return False + node = node.children[c] + return True + + +class Solution: + def stringMatching(self, words: List[str]) -> List[str]: + ans = [] + trie = Trie() + + for word in sorted(words, key=lambda x: -len(x)): + if trie.search(word): + ans.append(word) + for i in range(len(word)): + trie.insert(word[i:]) + + return ans diff --git a/solutions/1408. String Matching in an Array/1408-3.cpp b/solutions/1408. String Matching in an Array/1408-3.cpp new file mode 100644 index 00000000000..9a4d0118f28 --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408-3.cpp @@ -0,0 +1,51 @@ +struct TrieNode { + vector> children; + int count = 0; + TrieNode() : children(26) {} +}; + +class Trie { + public: + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + ++node->count; + } + } + + bool search(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + return false; + node = node->children[i]; + } + return node->count > 1; + } + + private: + shared_ptr root = make_shared(); +}; + +class Solution { + public: + vector stringMatching(vector& words) { + vector ans; + Trie trie; + + for (const string& word : words) + for (int i = 0; i < word.length(); ++i) + trie.insert(word.substr(i)); + + for (const string& word : words) + if (trie.search(word)) + ans.push_back(word); + + return ans; + } +}; diff --git a/solutions/1408. String Matching in an Array/1408-3.java b/solutions/1408. String Matching in an Array/1408-3.java new file mode 100644 index 00000000000..22368173b9b --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408-3.java @@ -0,0 +1,47 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int count = 0; +} + +class Trie { + public void insert(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + ++node.count; + } + } + + public boolean search(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + return false; + node = node.children[i]; + } + return node.count > 1; + } + + private TrieNode root = new TrieNode(); +} + +class Solution { + public List stringMatching(String[] words) { + List ans = new ArrayList<>(); + Trie trie = new Trie(); + + for (final String word : words) + for (int i = 0; i < word.length(); ++i) + trie.insert(word.substring(i)); + + for (final String word : words) + if (trie.search(word)) + ans.add(word); + + return ans; + } +} diff --git a/solutions/1408. String Matching in an Array/1408-3.py b/solutions/1408. String Matching in an Array/1408-3.py new file mode 100644 index 00000000000..22d18afacb0 --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408-3.py @@ -0,0 +1,34 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.count = 0 + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> None: + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.count += 1 + + def search(self, word: str) -> bool: + node: TrieNode = self.root + for c in word: + if c not in node.children: + return False + node = node.children[c] + return node.count > 1 + + +class Solution: + def stringMatching(self, words: List[str]) -> List[str]: + trie = Trie() + + for word in words: + for i in range(len(word)): + trie.insert(word[i:]) + + return [word for word in words if trie.search(word)] diff --git a/solutions/1408. String Matching in an Array/1408.cpp b/solutions/1408. String Matching in an Array/1408.cpp new file mode 100644 index 00000000000..ac9b91c0a98 --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector stringMatching(vector& words) { + vector ans; + for (const string& a : words) + for (const string& b : words) + if (a.length() < b.length() && b.find(a) != string::npos) { + ans.push_back(a); + break; + } + return ans; + } +}; diff --git a/solutions/1408. String Matching in an Array/1408.java b/solutions/1408. String Matching in an Array/1408.java new file mode 100644 index 00000000000..44eb766fc91 --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408.java @@ -0,0 +1,12 @@ +class Solution { + public List stringMatching(String[] words) { + List ans = new ArrayList<>(); + for (final String a : words) + for (final String b : words) + if (a.length() < b.length() && b.indexOf(a) != -1) { + ans.add(a); + break; + } + return ans; + } +} diff --git a/solutions/1408. String Matching in an Array/1408.py b/solutions/1408. String Matching in an Array/1408.py new file mode 100644 index 00000000000..3c61029451d --- /dev/null +++ b/solutions/1408. String Matching in an Array/1408.py @@ -0,0 +1,9 @@ +class Solution: + def stringMatching(self, words: List[str]) -> List[str]: + ans = [] + for a in words: + for b in words: + if len(a) < len(b) and b.find(a) != -1: + ans.append(a) + break + return ans diff --git a/solutions/1409. Queries on a Permutation With Key/1409.cpp b/solutions/1409. Queries on a Permutation With Key/1409.cpp new file mode 100644 index 00000000000..f55be4cbbb9 --- /dev/null +++ b/solutions/1409. Queries on a Permutation With Key/1409.cpp @@ -0,0 +1,55 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + vector processQueries(vector& queries, int m) { + vector ans; + // Map [-m, m] to [0, 2 * m]. + FenwickTree tree(2 * m + 1); + unordered_map numToIndex; + + for (int num = 1; num <= m; ++num) { + numToIndex[num] = num + m; + tree.add(num + m, 1); + } + + int nextEmptyIndex = m; // Map 0 to m. + + for (const int query : queries) { + const int index = numToIndex[query]; + ans.push_back(tree.get(index - 1)); + // Move `query` from `index` to `nextEmptyIndex`. + tree.add(index, -1); + tree.add(nextEmptyIndex, 1); + numToIndex[query] = nextEmptyIndex--; + } + + return ans; + } +}; diff --git a/solutions/1409. Queries on a Permutation With Key/1409.java b/solutions/1409. Queries on a Permutation With Key/1409.java new file mode 100644 index 00000000000..ab25ea871eb --- /dev/null +++ b/solutions/1409. Queries on a Permutation With Key/1409.java @@ -0,0 +1,55 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public int[] processQueries(int[] queries, int m) { + int[] ans = new int[queries.length]; + // Map [-m, m] to [0, 2 * m]. + FenwickTree tree = new FenwickTree(2 * m + 1); + Map numToIndex = new HashMap<>(); + + for (int num = 1; num <= m; ++num) { + numToIndex.put(num, num + m); + tree.add(num + m, 1); + } + + int nextEmptyIndex = m; // Map 0 to m. + + for (int i = 0; i < queries.length; ++i) { + final int query = queries[i]; + final int index = numToIndex.get(query); + ans[i] = tree.get(index - 1); + // Move `query` from `index` to `nextEmptyIndex`. + tree.add(index, -1); + tree.add(nextEmptyIndex, 1); + numToIndex.put(query, nextEmptyIndex--); + } + + return ans; + } +} diff --git a/solutions/1409. Queries on a Permutation With Key/1409.py b/solutions/1409. Queries on a Permutation With Key/1409.py new file mode 100644 index 00000000000..8c74cc5a54a --- /dev/null +++ b/solutions/1409. Queries on a Permutation With Key/1409.py @@ -0,0 +1,43 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def processQueries(self, queries: List[int], m: int) -> List[int]: + ans = [] + # Map [-m, m] to [0, 2 * m]. + tree = FenwickTree(2 * m + 1) + numToIndex = {num: num + m for num in range(1, m + 1)} + + for num in range(1, m + 1): + tree.add(num + m, 1) + + nextEmptyIndex = m # Map 0 to m. + + for query in queries: + index = numToIndex[query] + ans.append(tree.get(index - 1)) + # Move `query` from `index` to `nextEmptyIndex`. + tree.add(index, -1) + tree.add(nextEmptyIndex, 1) + numToIndex[query] = nextEmptyIndex + nextEmptyIndex -= 1 + + return ans diff --git a/solutions/141. Linked List Cycle/141.cpp b/solutions/141. Linked List Cycle/141.cpp new file mode 100644 index 00000000000..ad8076aca0c --- /dev/null +++ b/solutions/141. Linked List Cycle/141.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool hasCycle(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head; + + while (fast != nullptr && fast->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) + return true; + } + + return false; + } +}; diff --git a/solutions/141. Linked List Cycle/141.java b/solutions/141. Linked List Cycle/141.java new file mode 100644 index 00000000000..f75d68bcf1e --- /dev/null +++ b/solutions/141. Linked List Cycle/141.java @@ -0,0 +1,15 @@ +public class Solution { + public boolean hasCycle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) + return true; + } + + return false; + } +} diff --git a/solutions/141. Linked List Cycle/141.py b/solutions/141. Linked List Cycle/141.py new file mode 100644 index 00000000000..85ce09d5de8 --- /dev/null +++ b/solutions/141. Linked List Cycle/141.py @@ -0,0 +1,12 @@ +class Solution: + def hasCycle(self, head: ListNode) -> bool: + slow = head + fast = head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + return True + + return False diff --git a/solutions/1410. HTML Entity Parser/1410.cpp b/solutions/1410. HTML Entity Parser/1410.cpp new file mode 100644 index 00000000000..115e2ef89dc --- /dev/null +++ b/solutions/1410. HTML Entity Parser/1410.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + string entityParser(string text) { + const unordered_map entityToChar{ + {""", '"'}, {"'", '\''}, {"&", '&'}, + {">", '>'}, {"<", '<'}, {"⁄", '/'}}; + string ans; + int j = 0; // text[j..ampersandIndex - 1] is the pending substring. + int ampersandIndex = -1; + + for (int i = 0; i < text.length(); ++i) + if (text[i] == '&') { + ampersandIndex = i; + } else if (text[i] == ';' && ampersandIndex >= j) { + const string sub = text.substr(ampersandIndex, i - ampersandIndex + 1); + ans += text.substr(j, ampersandIndex - j); + ans += getCharIfMatched(text, sub, entityToChar); + j = i + 1; + } + + return ans + text.substr(j); + } + + private: + string getCharIfMatched(const string& text, const string& sub, + const unordered_map& entityToChar) { + for (const auto& [entity, c] : entityToChar) + if (entity == sub) + return string(1, c); + return sub; + } +}; diff --git a/solutions/1410. HTML Entity Parser/1410.java b/solutions/1410. HTML Entity Parser/1410.java new file mode 100644 index 00000000000..8c9131367e7 --- /dev/null +++ b/solutions/1410. HTML Entity Parser/1410.java @@ -0,0 +1,15 @@ +class Solution { + public String entityParser(String text) { + Map entryToChar = + Map.of(""", "\"", "'", "'", ">", ">", "<", "<", "⁄", "/"); + + for (Map.Entry entry : entryToChar.entrySet()) { + final String entity = entry.getKey(); + final String c = entry.getValue(); + text = text.replaceAll(entity, c); + } + + // Process '&' in last. + return text.replaceAll("&", "&"); + } +} diff --git a/solutions/1410. HTML Entity Parser/1410.py b/solutions/1410. HTML Entity Parser/1410.py new file mode 100644 index 00000000000..f5c6284efc3 --- /dev/null +++ b/solutions/1410. HTML Entity Parser/1410.py @@ -0,0 +1,10 @@ +class Solution: + def entityParser(self, text: str) -> str: + entityToChar = {'"': '"', ''': '\'', + '>': '>', '<': '<', '⁄': '/'} + + for entity, c in entityToChar.items(): + text = text.replace(entity, c) + + # Process '&' in last. + return text.replace('&', '&') diff --git "a/solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.cpp" "b/solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.cpp" new file mode 100644 index 00000000000..129c16feddc --- /dev/null +++ "b/solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.cpp" @@ -0,0 +1,17 @@ +class Solution { + public: + int numOfWays(int n) { + constexpr int kMod = 1'000'000'007; + long color2 = 6; // 121, 131, 212, 232, 313, 323 + long color3 = 6; // 123, 132, 213, 231, 312, 321 + + for (int i = 1; i < n; ++i) { + const long nextColor2 = color2 * 3 + color3 * 2; + const long nextColor3 = color2 * 2 + color3 * 2; + color2 = nextColor2 % kMod; + color3 = nextColor3 % kMod; + } + + return (color2 + color3) % kMod; + } +}; diff --git "a/solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.java" "b/solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.java" new file mode 100644 index 00000000000..a6b62d4558a --- /dev/null +++ "b/solutions/1411. Number of Ways to Paint N \303\227 3 Grid/1411.java" @@ -0,0 +1,16 @@ +class Solution { + public int numOfWays(int n) { + final int kMod = 1_000_000_007; + long color2 = 6; // 121, 131, 212, 232, 313, 323 + long color3 = 6; // 123, 132, 213, 231, 312, 321 + + for (int i = 1; i < n; ++i) { + final long nextColor2 = color2 * 3 + color3 * 2; + final long nextColor3 = color2 * 2 + color3 * 2; + color2 = nextColor2 % kMod; + color3 = nextColor3 % kMod; + } + + return (int) ((color2 + color3) % kMod); + } +} diff --git a/solutions/1412. Find the Quiet Students in All Exams/1412.sql b/solutions/1412. Find the Quiet Students in All Exams/1412.sql new file mode 100644 index 00000000000..e8a3823746c --- /dev/null +++ b/solutions/1412. Find the Quiet Students in All Exams/1412.sql @@ -0,0 +1,15 @@ +WITH + RankedStudents AS ( + SELECT + student_id, + RANK() OVER(PARTITION BY exam_id ORDER BY score ASC) rank_asc, + RANK() OVER(PARTITION BY exam_id ORDER BY score DESC) rank_desc + FROM Exam + ) +SELECT * FROM Student +WHERE student_id IN ( + SELECT student_id FROM RankedStudents + GROUP BY 1 + HAVING MIN(rank_asc) > 1 AND MIN(rank_desc) > 1 +) +ORDER BY student_id; diff --git a/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.cpp b/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.cpp new file mode 100644 index 00000000000..dc298fc92b8 --- /dev/null +++ b/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int minStartValue(vector& nums) { + int sum = 0; + int minSum = 0; + + for (const int num : nums) + minSum = min(minSum, sum += num); + + return 1 - minSum; + } +}; diff --git a/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.java b/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.java new file mode 100644 index 00000000000..ddd426428cc --- /dev/null +++ b/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.java @@ -0,0 +1,11 @@ +class Solution { + public int minStartValue(int[] nums) { + int sum = 0; + int minSum = 0; + + for (final int num : nums) + minSum = Math.min(minSum, sum += num); + + return 1 - minSum; + } +} diff --git a/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.py b/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.py new file mode 100644 index 00000000000..f6880f328e9 --- /dev/null +++ b/solutions/1413. Minimum Value to Get Positive Step by Step Sum/1413.py @@ -0,0 +1,10 @@ +class Solution: + def minStartValue(self, nums: List[int]) -> int: + summ = 0 + minSum = 0 + + for num in nums: + summ += num + minSum = min(minSum, summ) + + return 1 - minSum diff --git a/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.cpp b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.cpp new file mode 100644 index 00000000000..4e6a29d3140 --- /dev/null +++ b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int findMinFibonacciNumbers(int k) { + int ans = 0; + int a = 1; // F_1 + int b = 1; // F_2 + + while (b <= k) { + // a, b = F_{i + 1}, F_{i + 2} + // -> a, b = F_{i + 2}, F_{i + 3} + const int temp = a; + a = b; + b = a + temp; + } + + while (a > 0) { + if (a <= k) { + k -= a; + ++ans; + } + // a, b = F_{i + 2}, F_{i + 3} + // -> a, b = F_{i + 1}, F_{i + 2} + const int temp = a; + a = b - a; + b = temp; + } + + return ans; + } +}; diff --git a/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.java b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.java new file mode 100644 index 00000000000..838fbb4ce2d --- /dev/null +++ b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.java @@ -0,0 +1,29 @@ +class Solution { + public int findMinFibonacciNumbers(int k) { + int ans = 0; + int a = 1; // F_1 + int b = 1; // F_2 + + while (b <= k) { + // a, b = F_{i + 1}, F_{i + 2} + // -> a, b = F_{i + 2}, F_{i + 3} + final int temp = a; + a = b; + b = a + temp; + } + + while (a > 0) { + if (a <= k) { + k -= a; + ++ans; + } + // a, b = F_{i + 2}, F_{i + 3} + // -> a, b = F_{i + 1}, F_{i + 2} + final int temp = a; + a = b - a; + b = temp; + } + + return ans; + } +} diff --git a/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.py b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.py new file mode 100644 index 00000000000..b257b0ed1d0 --- /dev/null +++ b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.py @@ -0,0 +1,20 @@ +class Solution: + def findMinFibonacciNumbers(self, k: int) -> int: + ans = 0 + a = 1 # F_1 + b = 1 # F_2 + + while b <= k: + # a, b = F_{i + 1}, F_{i + 2} + # -> a, b = F_{i + 2}, F_{i + 3} + a, b = b, a + b + + while a > 0: + if a <= k: + k -= a + ans += 1 + # a, b = F_{i + 2}, F_{i + 3} + # -> a, b = F_{i + 1}, F_{i + 2} + a, b = b - a, a + + return ans diff --git a/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.cpp b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.cpp new file mode 100644 index 00000000000..e7d27dc33b9 --- /dev/null +++ b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int findMinFibonacciNumbers(int k) { + if (k < 2) // k == 0 || k == 1 + return k; + + int a = 1; // F_1 + int b = 1; // F_2 + + while (b <= k) { + // a, b = F_{i + 1}, F_{i + 2} + // -> a, b = F_{i + 2}, F_{i + 3} + const int temp = a; + a = b; + b = a + temp; + } + + return 1 + findMinFibonacciNumbers(k - a); + } +}; diff --git a/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.java b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.java new file mode 100644 index 00000000000..b6f67de9d23 --- /dev/null +++ b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.java @@ -0,0 +1,19 @@ +class Solution { + public int findMinFibonacciNumbers(int k) { + if (k < 2) // k == 0 || k == 1 + return k; + + int a = 1; // F_1 + int b = 1; // F_2 + + while (b <= k) { + // a, b = F_{i + 1}, F_{i + 2} + // -> a, b = F_{i + 2}, F_{i + 3} + final int temp = a; + a = b; + b = a + temp; + } + + return 1 + findMinFibonacciNumbers(k - a); + } +} diff --git a/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.py b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.py new file mode 100644 index 00000000000..52766410e96 --- /dev/null +++ b/solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414.py @@ -0,0 +1,14 @@ +class Solution: + def findMinFibonacciNumbers(self, k: int) -> int: + if k < 2: # k == 0 or k == 1 + return k + + a = 1 # F_1 + b = 1 # F_2 + + while b <= k: + # a, b = F_{i + 1}, F_{i + 2} + # -> a, b = F_{i + 2}, F_{i + 3} + a, b = b, a + b + + return 1 + self.findMinFibonacciNumbers(k - a) diff --git a/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.cpp b/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.cpp new file mode 100644 index 00000000000..74693405e65 --- /dev/null +++ b/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + string getHappyString(int n, int k) { + const unordered_map nextLetters{ + {'a', "bc"}, {'b', "ac"}, {'c', "ab"}}; + queue q{{{"a", "b", "c"}}}; + + while (q.front().length() != n) { + const string u = q.front(); + q.pop(); + for (const char nextLetter : nextLetters.at(u.back())) + q.push(u + nextLetter); + } + + if (q.size() < k) + return ""; + + for (int i = 0; i < k - 1; ++i) + q.pop(); + return q.front(); + } +}; diff --git a/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.java b/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.java new file mode 100644 index 00000000000..d644b9d6bc1 --- /dev/null +++ b/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.java @@ -0,0 +1,19 @@ +class Solution { + public String getHappyString(int n, int k) { + Map nextLetters = Map.of('a', "bc", 'b', "ac", 'c', "ab"); + Queue q = new ArrayDeque<>(Arrays.asList("a", "b", "c")); + + while (q.peek().length() != n) { + final String u = q.poll(); + for (final char nextLetter : nextLetters.get(u.charAt(u.length() - 1)).toCharArray()) + q.offer(u + nextLetter); + } + + if (q.size() < k) + return ""; + + for (int i = 0; i < k - 1; ++i) + q.poll(); + return q.poll(); + } +} diff --git a/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.py b/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.py new file mode 100644 index 00000000000..ae4a38665a8 --- /dev/null +++ b/solutions/1415. The k-th Lexicographical String of All Happy Strings of Length n/1415.py @@ -0,0 +1,11 @@ +class Solution: + def getHappyString(self, n: int, k: int) -> str: + nextLetters = {'a': 'bc', 'b': 'ac', 'c': 'ab'} + q = collections.deque(['a', 'b', 'c']) + + while len(q[0]) != n: + u = q.popleft() + for nextLetter in nextLetters[u[-1]]: + q.append(u + nextLetter) + + return '' if len(q) < k else q[k - 1] diff --git a/solutions/1416. Restore The Array/1416-2.cpp b/solutions/1416. Restore The Array/1416-2.cpp new file mode 100644 index 00000000000..2a240c070a3 --- /dev/null +++ b/solutions/1416. Restore The Array/1416-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int numberOfArrays(string s, int k) { + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + // dp[i] := the number of arrays to restore s[i..n) with k + vector dp(n + 1); + dp.back() = 1; // an empty string "" + + for (int i = n - 1; i >= 0; --i) { + if (s[i] == '0') + continue; // a leading zero + long num = 0; + for (int j = i; j < n; ++j) { + num = num * 10 + (s[j] - '0'); + if (num > k) + break; + dp[i] = (dp[i] + dp[j + 1]) % kMod; + } + } + + return dp[0]; + } +}; diff --git a/solutions/1416. Restore The Array/1416.cpp b/solutions/1416. Restore The Array/1416.cpp new file mode 100644 index 00000000000..3e43d829a9c --- /dev/null +++ b/solutions/1416. Restore The Array/1416.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int numberOfArrays(string s, int k) { + vector mem(s.length(), -1); + return numberOfArrays(s, 0, k, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of arrays to restore s[i..n) with k. + int numberOfArrays(const string& s, int i, int k, vector& mem) { + if (i == s.length()) + return 1; // an empty string "" + if (s[i] == '0') + return 0; // a leading zero + if (mem[i] != -1) + return mem[i]; + + int res = 0; + long num = 0; + + for (int j = i; j < s.length(); ++j) { + num = num * 10 + (s[j] - '0'); + if (num > k) + break; + res = (res + numberOfArrays(s, j + 1, k, mem)) % kMod; + } + + return mem[i] = res; + } +}; diff --git a/solutions/1417. Reformat The String/1417-2.cpp b/solutions/1417. Reformat The String/1417-2.cpp new file mode 100644 index 00000000000..cd8421a860f --- /dev/null +++ b/solutions/1417. Reformat The String/1417-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + string reformat(string s) { + const int countAlpha = + ranges::count_if(s, [](char c) { return isalpha(c); }); + const int countDigit = s.size() - countAlpha; + if (abs(countAlpha - countDigit) >= 2) + return ""; + + // Initialize the starting index. e.g. "a0a0a" or "0a0a0". + const int alphaStartingIndex = countAlpha >= countDigit ? 0 : 1; + + // Place all alphas in the indices 0, 2, 4, 6, ... or 1, 3, 5, 7, .... + for (int i = 0, j = alphaStartingIndex; i < s.length(); ++i) { + if (i < j && i % 2 == alphaStartingIndex) + continue; // The `s[i]` has been set. + if (!isalpha(s[i])) + continue; + swap(s[i], s[j]); + j += 2; + --i; + } + + return s; + } +}; diff --git a/solutions/1417. Reformat The String/1417.cpp b/solutions/1417. Reformat The String/1417.cpp new file mode 100644 index 00000000000..d2ff3e41fb1 --- /dev/null +++ b/solutions/1417. Reformat The String/1417.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string reformat(string s) { + vector A; + vector B; + + for (const char c : s) + isalpha(c) ? A.push_back(c) : B.push_back(c); + + if (A.size() < B.size()) + swap(A, B); + if (A.size() - B.size() > 1) + return ""; + + string ans; + + for (int i = 0; i < B.size(); ++i) + ans += string{A[i], B[i]}; + + if (A.size() > B.size()) + ans += A.back(); + return ans; + } +}; diff --git a/solutions/1417. Reformat The String/1417.java b/solutions/1417. Reformat The String/1417.java new file mode 100644 index 00000000000..9b4a5091939 --- /dev/null +++ b/solutions/1417. Reformat The String/1417.java @@ -0,0 +1,31 @@ +class Solution { + public String reformat(String s) { + List A = new ArrayList<>(); + List B = new ArrayList<>(); + + for (final char c : s.toCharArray()) + if (Character.isAlphabetic(c)) + A.add(c); + else + B.add(c); + + if (A.size() < B.size()) { + List temp = A; + A = B; + B = temp; + } + if (A.size() - B.size() > 1) + return ""; + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < B.size(); ++i) { + sb.append(A.get(i)); + sb.append(B.get(i)); + } + + if (A.size() > B.size()) + sb.append(A.get(A.size() - 1)); + return sb.toString(); + } +} diff --git a/solutions/1417. Reformat The String/1417.py b/solutions/1417. Reformat The String/1417.py new file mode 100644 index 00000000000..2f285209d00 --- /dev/null +++ b/solutions/1417. Reformat The String/1417.py @@ -0,0 +1,19 @@ +class Solution: + def reformat(self, s: str) -> str: + A = [c for c in s if c.isalpha()] + B = [c for c in s if c.isdigit()] + + if len(A) < len(B): + A, B = B, A + if len(A) - len(B) > 1: + return '' + + ans = [] + + for i in range(len(B)): + ans.append(A[i]) + ans.append(B[i]) + + if len(A) == len(B) + 1: + ans.append(A[-1]) + return ''.join(ans) diff --git a/solutions/1418. Display Table of Food Orders in a Restaurant/1418.cpp b/solutions/1418. Display Table of Food Orders in a Restaurant/1418.cpp new file mode 100644 index 00000000000..f13b201c45e --- /dev/null +++ b/solutions/1418. Display Table of Food Orders in a Restaurant/1418.cpp @@ -0,0 +1,53 @@ +class Solution { + public: + vector> displayTable(vector>& orders) { + vector> ans{{"Table"}}; + unordered_map tableNumberToRowIndex; + unordered_map foodItemToColIndex; + + // Create the first row and column of ans. + for (const vector& order : orders) { + const string& tableNumber = order[1]; + const string& foodItem = order[2]; + // Initialize indices with 0s. + tableNumberToRowIndex[tableNumber] = 0; + foodItemToColIndex[foodItem] = 0; + } + for (const auto& [tableNumber, _] : tableNumberToRowIndex) + ans.push_back({tableNumber}); + for (const auto& [foodItem, _] : foodItemToColIndex) + ans[0].push_back(foodItem); + + // Sort the first row and the column, except ans[0][0]. + sort(ans[0].begin() + 1, ans[0].end()); + sort(ans.begin() + 1, ans.end(), + [](const vector& a, const vector& b) { + return stoi(a[0]) < stoi(b[0]); + }); + + // Set the indices after sorting. + for (int i = 0; i < tableNumberToRowIndex.size(); ++i) + tableNumberToRowIndex[ans[i + 1][0]] = i; + for (int i = 0; i < foodItemToColIndex.size(); ++i) + foodItemToColIndex[ans[0][i + 1]] = i; + + // Get all the counts of each food item in each table. + vector> count; + for (int i = 0; i < tableNumberToRowIndex.size(); ++i) + count.push_back(vector(foodItemToColIndex.size())); + for (const vector& order : orders) { + const string& tableNumber = order[1]; + const string& foodItem = order[2]; + const int rowIndex = tableNumberToRowIndex[tableNumber]; + const int colIndex = foodItemToColIndex[foodItem]; + ++count[rowIndex][colIndex]; + } + + // Set the counts to `ans`. + for (int i = 0; i < tableNumberToRowIndex.size(); ++i) + for (int j = 0; j < foodItemToColIndex.size(); ++j) + ans[i + 1].push_back(to_string(count[i][j])); + + return ans; + } +}; diff --git a/solutions/1419. Minimum Number of Frogs Croaking/1419.cpp b/solutions/1419. Minimum Number of Frogs Croaking/1419.cpp new file mode 100644 index 00000000000..6a9b24fe216 --- /dev/null +++ b/solutions/1419. Minimum Number of Frogs Croaking/1419.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minNumberOfFrogs(string croakOfFrogs) { + const string kCroak = "croak"; + int ans = 0; + int frogs = 0; + vector count(5); + + for (const char c : croakOfFrogs) { + ++count[kCroak.find(c)]; + for (int i = 1; i < 5; ++i) + if (count[i] > count[i - 1]) + return -1; + if (c == 'c') + ++frogs; + else if (c == 'k') + --frogs; + ans = max(ans, frogs); + } + + return frogs == 0 ? ans : -1; + } +}; diff --git a/solutions/1419. Minimum Number of Frogs Croaking/1419.java b/solutions/1419. Minimum Number of Frogs Croaking/1419.java new file mode 100644 index 00000000000..ec66b7b6a8f --- /dev/null +++ b/solutions/1419. Minimum Number of Frogs Croaking/1419.java @@ -0,0 +1,22 @@ +class Solution { + public int minNumberOfFrogs(String croakOfFrogs) { + final String kCroak = "croak"; + int ans = 0; + int frogs = 0; + int[] count = new int[5]; + + for (final char c : croakOfFrogs.toCharArray()) { + ++count[kCroak.indexOf(c)]; + for (int i = 1; i < 5; ++i) + if (count[i] > count[i - 1]) + return -1; + if (c == 'c') + ++frogs; + else if (c == 'k') + --frogs; + ans = Math.max(ans, frogs); + } + + return frogs == 0 ? ans : -1; + } +} diff --git a/solutions/1419. Minimum Number of Frogs Croaking/1419.py b/solutions/1419. Minimum Number of Frogs Croaking/1419.py new file mode 100644 index 00000000000..01864c24e8b --- /dev/null +++ b/solutions/1419. Minimum Number of Frogs Croaking/1419.py @@ -0,0 +1,18 @@ +class Solution: + def minNumberOfFrogs(self, croakOfFrogs: str) -> int: + kCroak = 'croak' + ans = 0 + frogs = 0 + count = [0] * 5 + + for c in croakOfFrogs: + count[kCroak.index(c)] += 1 + if any(count[i] > count[i - 1] for i in range(1, 5)): + return -1 + if c == 'c': + frogs += 1 + elif c == 'k': + frogs -= 1 + ans = max(ans, frogs) + + return ans if frogs == 0 else -1 diff --git a/solutions/142. Linked List Cycle II/142.cpp b/solutions/142. Linked List Cycle II/142.cpp new file mode 100644 index 00000000000..86cb29b9725 --- /dev/null +++ b/solutions/142. Linked List Cycle II/142.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + ListNode* detectCycle(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head; + + while (fast != nullptr && fast->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + slow = head; + while (slow != fast) { + slow = slow->next; + fast = fast->next; + } + return slow; + } + } + + return nullptr; + } +}; diff --git a/solutions/142. Linked List Cycle II/142.java b/solutions/142. Linked List Cycle II/142.java new file mode 100644 index 00000000000..fc6f3e830d2 --- /dev/null +++ b/solutions/142. Linked List Cycle II/142.java @@ -0,0 +1,21 @@ +public class Solution { + public ListNode detectCycle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) { + slow = head; + while (slow != fast) { + slow = slow.next; + fast = fast.next; + } + return slow; + } + } + + return null; + } +} diff --git a/solutions/142. Linked List Cycle II/142.py b/solutions/142. Linked List Cycle II/142.py new file mode 100644 index 00000000000..933f03f3041 --- /dev/null +++ b/solutions/142. Linked List Cycle II/142.py @@ -0,0 +1,16 @@ +class Solution: + def detectCycle(self, head: ListNode) -> ListNode: + slow = head + fast = head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + slow = head + while slow != fast: + slow = slow.next + fast = fast.next + return slow + + return None diff --git a/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.cpp b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.cpp new file mode 100644 index 00000000000..8750e80bccf --- /dev/null +++ b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int numOfArrays(int n, int m, int k) { + constexpr int kMod = 1'000'000'007; + // dp[i][j][k] := the number of ways to build an array of length i, where j + // is the maximum number and k is the `search_cost` + vector>> dp( + n + 1, vector>(m + 1, vector(k + 1))); + // prefix[i][j][k] := sum(dp[i][x][k]), where 1 <= x <= j + vector>> prefix( + n + 1, vector>(m + 1, vector(k + 1))); + + for (int j = 1; j <= m; ++j) { + dp[1][j][1] = 1; + prefix[1][j][1] = j; + } + + for (int i = 2; i <= n; ++i) // for each length + for (int j = 1; j <= m; ++j) // for each max value + for (int cost = 1; cost <= k; ++cost) { // for each cost + // 1. Appending any of [1, j] in the i-th position doesn't change the + // maximum and cost. + // 2. Appending j in the i-th position makes j the new max and + // cost 1. + dp[i][j][cost] = (static_cast(j) * dp[i - 1][j][cost] + + prefix[i - 1][j - 1][cost - 1]) % + kMod; + prefix[i][j][cost] = (dp[i][j][cost] + prefix[i][j - 1][cost]) % kMod; + } + + int ans = 0; + for (int j = 1; j <= m; ++j) { + ans += dp[n][j][k]; + ans %= kMod; + } + return ans; + } +}; diff --git a/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.java b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.java new file mode 100644 index 00000000000..f2e10154426 --- /dev/null +++ b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.java @@ -0,0 +1,33 @@ +class Solution { + public int numOfArrays(int n, int m, int k) { + final int kMod = 1_000_000_007; + // dp[i][j][k] := the number of ways to build an array of length i, where j + // is the maximum number and k is the `search_cost` + int[][][] dp = new int[n + 1][m + 1][k + 1]; + // prefix[i][j][k] := sum(dp[i][x][k]), where 1 <= x <= j + int[][][] prefix = new int[n + 1][m + 1][k + 1]; + + for (int j = 1; j <= m; ++j) { + dp[1][j][1] = 1; + prefix[1][j][1] = j; + } + + for (int i = 2; i <= n; ++i) // for each length + for (int j = 1; j <= m; ++j) // for each max value + for (int cost = 1; cost <= k; ++cost) { // for each cost + // 1. Appending any of [1, j] in the i-th position doesn't change the + // maximum and cost. + // 2. Appending j in the i-th position makes j the new max and cost 1. + dp[i][j][cost] = + (int) (((long) j * dp[i - 1][j][cost] + prefix[i - 1][j - 1][cost - 1]) % kMod); + prefix[i][j][cost] = (dp[i][j][cost] + prefix[i][j - 1][cost]) % kMod; + } + + int ans = 0; + for (int j = 1; j <= m; ++j) { + ans += dp[n][j][k]; + ans %= kMod; + } + return ans; + } +} diff --git a/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.py b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.py new file mode 100644 index 00000000000..4d60e724a7d --- /dev/null +++ b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420-2.py @@ -0,0 +1,24 @@ +class Solution: + def numOfArrays(self, n: int, m: int, k: int) -> int: + kMod = 1_000_000_007 + # dp[i][j][k] := the number of ways to build an array of length i, where j + # is the maximum number and k is the `search_cost` + dp = [[[0] * (k + 1) for j in range(m + 1)] for _ in range(n + 1)] + # prefix[i][j][k] := sum(dp[i][x][k]), where 1 <= x <= j + prefix = [[[0] * (k + 1) for j in range(m + 1)] for _ in range(n + 1)] + + for j in range(1, m + 1): + dp[1][j][1] = 1 + prefix[1][j][1] = j + + for i in range(2, n + 1): # for each length + for j in range(1, m + 1): # for each max value + for cost in range(1, k + 1): # for each cost + # 1. Appending any of [1, j] in the i-th position doesn't change the + # maximum and cost. + # 2. Appending j in the i-th position makes j the new max and cost 1. + dp[i][j][cost] = (j * dp[i - 1][j][cost] + + prefix[i - 1][j - 1][cost - 1]) % kMod + prefix[i][j][cost] = (dp[i][j][cost] + prefix[i][j - 1][cost]) % kMod + + return sum(dp[n][j][k] for j in range(1, m + 1)) % kMod diff --git a/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.cpp b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.cpp new file mode 100644 index 00000000000..925112406a5 --- /dev/null +++ b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int numOfArrays(int n, int m, int k) { + constexpr int kMod = 1'000'000'007; + // dp[i][j][k] := the number of ways to build an array of length i, where j + // is the maximum number and k is `search_cost` + vector>> dp( + n + 1, vector>(m + 1, vector(k + 1))); + + for (int j = 1; j <= m; ++j) + dp[1][j][1] = 1; + + for (int i = 2; i <= n; ++i) // for each length + for (int j = 1; j <= m; ++j) // for each max value + for (int cost = 1; cost <= k; ++cost) { // for each cost + // 1. Appending any of [1, j] in the i-th position doesn't change the + // maximum and cost. + dp[i][j][cost] = static_cast(j) * dp[i - 1][j][cost] % kMod; + // 2. Appending j in the i-th position makes j the new max and cost 1. + for (int prevMax = 1; prevMax < j; ++prevMax) { + dp[i][j][cost] += dp[i - 1][prevMax][cost - 1]; + dp[i][j][cost] %= kMod; + } + } + + int ans = 0; + for (int j = 1; j <= m; ++j) { + ans += dp[n][j][k]; + ans %= kMod; + } + return ans; + } +}; diff --git a/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.java b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.java new file mode 100644 index 00000000000..82adaecdadd --- /dev/null +++ b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.java @@ -0,0 +1,31 @@ +class Solution { + public int numOfArrays(int n, int m, int k) { + final int kMod = 1_000_000_007; + // dp[i][j][k] := the number of ways to build an array of length i, where j + // is the maximum number and k is `search_cost` + int[][][] dp = new int[n + 1][m + 1][k + 1]; + + for (int j = 1; j <= m; ++j) + dp[1][j][1] = 1; + + for (int i = 2; i <= n; ++i) // for each length + for (int j = 1; j <= m; ++j) // for each max value + for (int cost = 1; cost <= k; ++cost) { // for each cost + // 1. Appending any of [1, j] in the i-th position doesn't change the + // maximum and cost. + dp[i][j][cost] = (int) ((long) j * dp[i - 1][j][cost] % kMod); + // 2. Appending j in the i-th position makes j the new max and cost 1. + for (int prevMax = 1; prevMax < j; ++prevMax) { + dp[i][j][cost] += dp[i - 1][prevMax][cost - 1]; + dp[i][j][cost] %= kMod; + } + } + + int ans = 0; + for (int j = 1; j <= m; ++j) { + ans += dp[n][j][k]; + ans %= kMod; + } + return ans; + } +} diff --git a/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.py b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.py new file mode 100644 index 00000000000..42905ed816b --- /dev/null +++ b/solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.py @@ -0,0 +1,22 @@ +class Solution: + def numOfArrays(self, n: int, m: int, k: int) -> int: + kMod = 1_000_000_007 + # dp[i][j][k] := the number of ways to build an array of length i, where j + # is the maximum number and k is `search_cost` + dp = [[[0] * (k + 1) for j in range(m + 1)] for _ in range(n + 1)] + + for j in range(1, m + 1): + dp[1][j][1] = 1 + + for i in range(2, n + 1): # for each length + for j in range(1, m + 1): # for each max value + for cost in range(1, k + 1): # for each cost + # 1. Appending any of [1, j] in the i-th position doesn't change the + # maximum and cost. + dp[i][j][cost] = j * dp[i - 1][j][cost] % kMod + # 2. Appending j in the i-th position makes j the new max and cost 1. + for prevMax in range(1, j): + dp[i][j][cost] += dp[i - 1][prevMax][cost - 1] + dp[i][j][cost] %= kMod + + return sum(dp[n][j][k] for j in range(1, m + 1)) % kMod diff --git a/solutions/1421. NPV Queries/1421.sql b/solutions/1421. NPV Queries/1421.sql new file mode 100644 index 00000000000..b2285fd29ba --- /dev/null +++ b/solutions/1421. NPV Queries/1421.sql @@ -0,0 +1,7 @@ +SELECT + Queries.id, + Queries.year, + IFNULL(NPV.npv, 0) AS npv +FROM Queries +LEFT JOIN NPV + USING (id, year); diff --git a/solutions/1422. Maximum Score After Splitting a String/1422.cpp b/solutions/1422. Maximum Score After Splitting a String/1422.cpp new file mode 100644 index 00000000000..28291bafcdc --- /dev/null +++ b/solutions/1422. Maximum Score After Splitting a String/1422.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxScore(string s) { + int ans = 0; + int zeros = 0; + int ones = ranges::count(s, '1'); + + for (int i = 0; i + 1 < s.size(); ++i) { + if (s[i] == '0') + ++zeros; + else + --ones; + ans = max(ans, zeros + ones); + } + + return ans; + } +}; diff --git a/solutions/1422. Maximum Score After Splitting a String/1422.java b/solutions/1422. Maximum Score After Splitting a String/1422.java new file mode 100644 index 00000000000..861744d88d2 --- /dev/null +++ b/solutions/1422. Maximum Score After Splitting a String/1422.java @@ -0,0 +1,17 @@ +class Solution { + public int maxScore(String s) { + int ans = 0; + int zeros = 0; + int ones = (int) s.chars().filter(c -> c == '1').count(); + + for (int i = 0; i + 1 < s.length(); ++i) { + if (s.charAt(i) == '0') + ++zeros; + else + --ones; + ans = Math.max(ans, zeros + ones); + } + + return ans; + } +} diff --git a/solutions/1422. Maximum Score After Splitting a String/1422.py b/solutions/1422. Maximum Score After Splitting a String/1422.py new file mode 100644 index 00000000000..a4c1300eb4e --- /dev/null +++ b/solutions/1422. Maximum Score After Splitting a String/1422.py @@ -0,0 +1,14 @@ +class Solution: + def maxScore(self, s: str) -> int: + ans = 0 + zeros = 0 + ones = s.count('1') + + for i in range(len(s) - 1): + if s[i] == '0': + zeros += 1 + else: + ones -= 1 + ans = max(ans, zeros + ones) + + return ans diff --git a/solutions/1423. Maximum Points You Can Obtain from Cards/1423.cpp b/solutions/1423. Maximum Points You Can Obtain from Cards/1423.cpp new file mode 100644 index 00000000000..3f9eb3ffc08 --- /dev/null +++ b/solutions/1423. Maximum Points You Can Obtain from Cards/1423.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxScore(vector& cardPoints, int k) { + const int n = cardPoints.size(); + const int sum = accumulate(cardPoints.begin(), cardPoints.end(), 0); + int windowSum = + accumulate(cardPoints.begin(), cardPoints.begin() + n - k, 0); + int ans = sum - windowSum; + + for (int i = 0; i < k; ++i) { + windowSum -= cardPoints[i]; + windowSum += cardPoints[i + n - k]; + ans = max(ans, sum - windowSum); + } + + return ans; + } +}; diff --git a/solutions/1423. Maximum Points You Can Obtain from Cards/1423.java b/solutions/1423. Maximum Points You Can Obtain from Cards/1423.java new file mode 100644 index 00000000000..f2b4f86aa0d --- /dev/null +++ b/solutions/1423. Maximum Points You Can Obtain from Cards/1423.java @@ -0,0 +1,19 @@ +class Solution { + public int maxScore(int[] cardPoints, int k) { + final int n = cardPoints.length; + final int sum = Arrays.stream(cardPoints).sum(); + int windowSum = 0; + for (int i = 0; i < n - k; ++i) + windowSum += cardPoints[i]; + + int ans = sum - windowSum; + + for (int i = 0; i < k; ++i) { + windowSum -= cardPoints[i]; + windowSum += cardPoints[i + n - k]; + ans = Math.max(ans, sum - windowSum); + } + + return ans; + } +} diff --git a/solutions/1423. Maximum Points You Can Obtain from Cards/1423.py b/solutions/1423. Maximum Points You Can Obtain from Cards/1423.py new file mode 100644 index 00000000000..daa92d4ffbe --- /dev/null +++ b/solutions/1423. Maximum Points You Can Obtain from Cards/1423.py @@ -0,0 +1,13 @@ +class Solution: + def maxScore(self, cardPoints: List[int], k: int) -> int: + n = len(cardPoints) + summ = sum(cardPoints) + windowSum = sum(cardPoints[:n - k]) + ans = summ - windowSum + + for i in range(k): + windowSum -= cardPoints[i] + windowSum += cardPoints[i + n - k] + ans = max(ans, summ - windowSum) + + return ans diff --git a/solutions/1424. Diagonal Traverse II/1424.cpp b/solutions/1424. Diagonal Traverse II/1424.cpp new file mode 100644 index 00000000000..de0c6d1d749 --- /dev/null +++ b/solutions/1424. Diagonal Traverse II/1424.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector findDiagonalOrder(vector>& nums) { + vector ans; + unordered_map> keyToNums; // key := row + column + int maxKey = 0; + + for (int i = 0; i < nums.size(); ++i) + for (int j = 0; j < nums[i].size(); ++j) { + const int key = i + j; + keyToNums[key].push_back(nums[i][j]); + maxKey = max(maxKey, key); + } + + for (int i = 0; i <= maxKey; ++i) + for (auto it = keyToNums[i].rbegin(); it != keyToNums[i].rend(); ++it) + ans.push_back(*it); + + return ans; + } +}; diff --git a/solutions/1424. Diagonal Traverse II/1424.java b/solutions/1424. Diagonal Traverse II/1424.java new file mode 100644 index 00000000000..2ccbc2cf177 --- /dev/null +++ b/solutions/1424. Diagonal Traverse II/1424.java @@ -0,0 +1,21 @@ +class Solution { + public int[] findDiagonalOrder(List> nums) { + List ans = new ArrayList<>(); + Map> keyToNums = new HashMap<>(); // key := row + column + int maxKey = 0; + + for (int i = 0; i < nums.size(); ++i) + for (int j = 0; j < nums.get(i).size(); ++j) { + final int key = i + j; + keyToNums.putIfAbsent(key, new ArrayList<>()); + keyToNums.get(key).add(nums.get(i).get(j)); + maxKey = Math.max(key, maxKey); + } + + for (int i = 0; i <= maxKey; ++i) + for (int j = keyToNums.get(i).size() - 1; j >= 0; --j) + ans.add(keyToNums.get(i).get(j)); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/1425. Constrained Subsequence Sum/1425.cpp b/solutions/1425. Constrained Subsequence Sum/1425.cpp new file mode 100644 index 00000000000..50b2de34be5 --- /dev/null +++ b/solutions/1425. Constrained Subsequence Sum/1425.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int constrainedSubsetSum(vector& nums, int k) { + // dp[i] := the maximum the sum of non-empty subsequences in nums[0..i] + vector dp(nums.size()); + // dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0 + // in decreasing order. + deque dq; + + for (int i = 0; i < nums.size(); ++i) { + if (dq.empty()) + dp[i] = nums[i]; + else + dp[i] = max(dq.front(), 0) + nums[i]; + while (!dq.empty() && dq.back() < dp[i]) + dq.pop_back(); + dq.push_back(dp[i]); + if (i >= k && dp[i - k] == dq.front()) + dq.pop_front(); + } + + return ranges::max(dp); + } +}; diff --git a/solutions/1425. Constrained Subsequence Sum/1425.java b/solutions/1425. Constrained Subsequence Sum/1425.java new file mode 100644 index 00000000000..e901f3c98c8 --- /dev/null +++ b/solutions/1425. Constrained Subsequence Sum/1425.java @@ -0,0 +1,23 @@ +class Solution { + public int constrainedSubsetSum(int[] nums, int k) { + // dp[i] := the maximum the sum of non-empty subsequences in nums[0..i] + int[] dp = new int[nums.length]; + // dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0 + // in decreasing order. + Deque dq = new ArrayDeque<>(); + + for (int i = 0; i < nums.length; ++i) { + if (dq.isEmpty()) + dp[i] = nums[i]; + else + dp[i] = Math.max(dq.peekFirst(), 0) + nums[i]; + while (!dq.isEmpty() && dq.peekLast() < dp[i]) + dq.pollLast(); + dq.offerLast(dp[i]); + if (i >= k && dp[i - k] == dq.peekFirst()) + dq.pollFirst(); + } + + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/1425. Constrained Subsequence Sum/1425.py b/solutions/1425. Constrained Subsequence Sum/1425.py new file mode 100644 index 00000000000..10a630575c8 --- /dev/null +++ b/solutions/1425. Constrained Subsequence Sum/1425.py @@ -0,0 +1,20 @@ +class Solution: + def constrainedSubsetSum(self, nums: List[int], k: int) -> int: + # dp[i] := the maximum the sum of non-empty subsequences in nums[0..i] + dp = [0] * len(nums) + # dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0 + # in decreasing order. + dq = collections.deque() + + for i, num in enumerate(nums): + if dq: + dp[i] = max(dq[0], 0) + num + else: + dp[i] = num + while dq and dq[-1] < dp[i]: + dq.pop() + dq.append(dp[i]) + if i >= k and dp[i - k] == dq[0]: + dq.popleft() + + return max(dp) diff --git a/solutions/1426. Counting Elements/1426.cpp b/solutions/1426. Counting Elements/1426.cpp new file mode 100644 index 00000000000..3322b75e19a --- /dev/null +++ b/solutions/1426. Counting Elements/1426.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int countElements(vector& arr) { + unordered_set arrSet{arr.begin(), arr.end()}; + return ranges::count_if( + arr, [&arrSet](int a) { return arrSet.contains(a + 1); }); + } +}; diff --git a/solutions/1426. Counting Elements/1426.java b/solutions/1426. Counting Elements/1426.java new file mode 100644 index 00000000000..ea4001bb7bc --- /dev/null +++ b/solutions/1426. Counting Elements/1426.java @@ -0,0 +1,15 @@ +class Solution { + public int countElements(int[] arr) { + int ans = 0; + Map count = new HashMap<>(); + + for (final int a : arr) + count.merge(a, 1, Integer::sum); + + for (Map.Entry entry : count.entrySet()) + if (count.containsKey(entry.getKey() + 1)) + ans += entry.getValue(); + + return ans; + } +} diff --git a/solutions/1426. Counting Elements/1426.py b/solutions/1426. Counting Elements/1426.py new file mode 100644 index 00000000000..c7a56e40dd3 --- /dev/null +++ b/solutions/1426. Counting Elements/1426.py @@ -0,0 +1,6 @@ +class Solution: + def countElements(self, arr: List[int]) -> int: + count = collections.Counter(arr) + return sum(freq + for a, freq in count.items() + if count[a + 1] > 0) diff --git a/solutions/1427. Perform String Shifts/1427.cpp b/solutions/1427. Perform String Shifts/1427.cpp new file mode 100644 index 00000000000..92af22f424c --- /dev/null +++ b/solutions/1427. Perform String Shifts/1427.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + string stringShift(string s, vector>& shift) { + const int n = s.length(); + int move = 0; + + for (const vector& pair : shift) { + const int direction = pair[0]; + const int amount = pair[1]; + if (direction == 0) + move -= amount; + else + move += amount; + } + + move = ((move % n) + n) % n; + return s.substr(n - move) + s.substr(0, n - move); + } +}; diff --git a/solutions/1427. Perform String Shifts/1427.java b/solutions/1427. Perform String Shifts/1427.java new file mode 100644 index 00000000000..c6fb278139e --- /dev/null +++ b/solutions/1427. Perform String Shifts/1427.java @@ -0,0 +1,18 @@ +class Solution { + public String stringShift(String s, int[][] shift) { + final int n = s.length(); + int move = 0; + + for (int[] pair : shift) { + final int direction = pair[0]; + final int amount = pair[1]; + if (direction == 0) + move -= amount; + else + move += amount; + } + + move = ((move % n) + n) % n; + return s.substring(n - move) + s.substring(0, n - move); + } +} diff --git a/solutions/1427. Perform String Shifts/1427.py b/solutions/1427. Perform String Shifts/1427.py new file mode 100644 index 00000000000..b400c4899e0 --- /dev/null +++ b/solutions/1427. Perform String Shifts/1427.py @@ -0,0 +1,12 @@ +class Solution: + def stringShift(self, s: str, shift: List[List[int]]) -> str: + move = 0 + + for direction, amount in shift: + if direction == 0: + move -= amount + else: + move += amount + + move %= len(s) + return s[-move:] + s[:-move] diff --git a/solutions/1428. Leftmost Column with at Least a One/1428-2.cpp b/solutions/1428. Leftmost Column with at Least a One/1428-2.cpp new file mode 100644 index 00000000000..96c85d66a70 --- /dev/null +++ b/solutions/1428. Leftmost Column with at Least a One/1428-2.cpp @@ -0,0 +1,29 @@ +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * class BinaryMatrix { + * public: + * int get(int row, int col); + * vector dimensions(); + * }; + */ + +class Solution { + public: + int leftMostColumnWithOne(BinaryMatrix& binaryMatrix) { + const vector dimensions = binaryMatrix.dimensions(); + const int m = dimensions[0]; + const int n = dimensions[1]; + int ans = -1; + int i = 0; + int j = n - 1; + + while (i < m && j >= 0) + if (binaryMatrix.get(i, j) == 1) + ans = j--; + else + ++i; + + return ans; + } +}; diff --git a/solutions/1428. Leftmost Column with at Least a One/1428-2.java b/solutions/1428. Leftmost Column with at Least a One/1428-2.java new file mode 100644 index 00000000000..875d8a5b5ae --- /dev/null +++ b/solutions/1428. Leftmost Column with at Least a One/1428-2.java @@ -0,0 +1,27 @@ +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * interface BinaryMatrix { + * public int get(int row, int col) {} + * public List dimensions {} + * }; + */ + +class Solution { + public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { + final List dimensions = binaryMatrix.dimensions(); + final int m = dimensions.get(0); + final int n = dimensions.get(1); + int ans = -1; + int i = 0; + int j = n - 1; + + while (i < m && j >= 0) + if (binaryMatrix.get(i, j) == 1) + ans = j--; + else + ++i; + + return ans; + } +} diff --git a/solutions/1428. Leftmost Column with at Least a One/1428-2.py b/solutions/1428. Leftmost Column with at Least a One/1428-2.py new file mode 100644 index 00000000000..061a004fc2d --- /dev/null +++ b/solutions/1428. Leftmost Column with at Least a One/1428-2.py @@ -0,0 +1,23 @@ +# """ +# This is BinaryMatrix's API interface. +# You should not implement it, or speculate about its implementation +# """ +# Class BinaryMatrix(object): +# def get(self, row: int, col: int) -> int: +# def dimensions(self) -> List[int]: + +class Solution: + def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: + m, n = binaryMatrix.dimensions() + ans = -1 + i = 0 + j = n - 1 + + while i < m and j >= 0: + if binaryMatrix.get(i, j): + ans = j + j -= 1 + else: + i += 1 + + return ans diff --git a/solutions/1428. Leftmost Column with at Least a One/1428.cpp b/solutions/1428. Leftmost Column with at Least a One/1428.cpp new file mode 100644 index 00000000000..eadd7c60c04 --- /dev/null +++ b/solutions/1428. Leftmost Column with at Least a One/1428.cpp @@ -0,0 +1,41 @@ +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * class BinaryMatrix { + * public: + * int get(int row, int col); + * vector dimensions(); + * }; + */ + +class Solution { + public: + int leftMostColumnWithOne(BinaryMatrix& binaryMatrix) { + const vector dimensions = binaryMatrix.dimensions(); + const int m = dimensions[0]; + const int n = dimensions[1]; + int ans = -1; + int l = 0; + int r = n - 1; + + while (l <= r) { + const int mid = (l + r) / 2; + if (existOne(binaryMatrix, m, mid)) { + ans = mid; + r = mid - 1; + } else { + l = mid + 1; + } + } + + return ans; + } + + private: + bool existOne(BinaryMatrix& binaryMatrix, int m, int col) { + for (int i = 0; i < m; ++i) + if (binaryMatrix.get(i, col) == 1) + return true; + return false; + } +}; diff --git a/solutions/1428. Leftmost Column with at Least a One/1428.java b/solutions/1428. Leftmost Column with at Least a One/1428.java new file mode 100644 index 00000000000..4622ac0718b --- /dev/null +++ b/solutions/1428. Leftmost Column with at Least a One/1428.java @@ -0,0 +1,38 @@ +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * interface BinaryMatrix { + * public int get(int row, int col) {} + * public List dimensions {} + * }; + */ + +class Solution { + public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { + final List dimensions = binaryMatrix.dimensions(); + final int m = dimensions.get(0); + final int n = dimensions.get(1); + int ans = -1; + int l = 0; + int r = n - 1; + + while (l <= r) { + final int mid = (l + r) / 2; + if (existOne(binaryMatrix, m, mid)) { + ans = mid; + r = mid - 1; + } else { + l = mid + 1; + } + } + + return ans; + } + + private boolean existOne(BinaryMatrix binaryMatrix, int m, int col) { + for (int i = 0; i < m; ++i) + if (binaryMatrix.get(i, col) == 1) + return true; + return false; + } +} diff --git a/solutions/1428. Leftmost Column with at Least a One/1428.py b/solutions/1428. Leftmost Column with at Least a One/1428.py new file mode 100644 index 00000000000..814a99da305 --- /dev/null +++ b/solutions/1428. Leftmost Column with at Least a One/1428.py @@ -0,0 +1,24 @@ +# """ +# This is BinaryMatrix's API interface. +# You should not implement it, or speculate about its implementation +# """ +# Class BinaryMatrix(object): +# def get(self, row: int, col: int) -> int: +# def dimensions(self) -> List[int]: + +class Solution: + def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: + m, n = binaryMatrix.dimensions() + ans = -1 + l = 0 + r = n - 1 + + while l <= r: + mid = (l + r) // 2 + if any(binaryMatrix.get(i, mid) for i in range(m)): + ans = mid + r = mid - 1 + else: + l = mid + 1 + + return ans diff --git a/solutions/1429. First Unique Number/1429.cpp b/solutions/1429. First Unique Number/1429.cpp new file mode 100644 index 00000000000..b2f34070bf7 --- /dev/null +++ b/solutions/1429. First Unique Number/1429.cpp @@ -0,0 +1,28 @@ +class FirstUnique { + public: + FirstUnique(vector& nums) { + for (const int num : nums) + add(num); + } + + int showFirstUnique() { + return unique.empty() ? -1 : unique.front(); + } + + void add(int value) { + const auto it = valueToIterator.find(value); + if (it == valueToIterator.cend()) { + unique.push_back(value); + valueToIterator[value] = prev(unique.end()); + } else if (it->second != unique.end()) { + // We have added this value before, and this is the second time we're + // adding it. So, erase the value from `unique` and mark it as erased. + unique.erase(it->second); + valueToIterator[value] = unique.end(); + } + } + + private: + list unique; + unordered_map::iterator> valueToIterator; +}; diff --git a/solutions/1429. First Unique Number/1429.java b/solutions/1429. First Unique Number/1429.java new file mode 100644 index 00000000000..a6c1baec350 --- /dev/null +++ b/solutions/1429. First Unique Number/1429.java @@ -0,0 +1,24 @@ +class FirstUnique { + public FirstUnique(int[] nums) { + for (final int num : nums) + add(num); + } + + public int showFirstUnique() { + return unique.isEmpty() ? -1 : unique.iterator().next(); + } + + public void add(int value) { + if (!seen.contains(value)) { + unique.add(value); + seen.add(value); + } else if (unique.contains(value)) { + // We have added this value before, and this is the second time we're + // adding it. So, erase the value from `unique`. + unique.remove(value); + } + } + + private Set seen = new HashSet<>(); + private Set unique = new LinkedHashSet<>(); +} diff --git a/solutions/1429. First Unique Number/1429.py b/solutions/1429. First Unique Number/1429.py new file mode 100644 index 00000000000..95c3859391d --- /dev/null +++ b/solutions/1429. First Unique Number/1429.py @@ -0,0 +1,18 @@ +class FirstUnique: + def __init__(self, nums: List[int]): + self.seen = set() + self.unique = {} + for num in nums: + self.add(num) + + def showFirstUnique(self) -> int: + return next(iter(self.unique), -1) + + def add(self, value: int) -> None: + if value not in self.seen: + self.seen.add(value) + self.unique[value] = 1 + elif value in self.unique: + # We have added this value before, and this is the second time we're + # adding it. So, erase the value from `unique`. + self.unique.pop(value) diff --git a/solutions/143. Reorder List/143.cpp b/solutions/143. Reorder List/143.cpp new file mode 100644 index 00000000000..877ffb61227 --- /dev/null +++ b/solutions/143. Reorder List/143.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + void reorderList(ListNode* head) { + if (!head || !head->next) + return; + + ListNode* mid = findMid(head); + ListNode* reversed = reverse(mid); + merge(head, reversed); + } + + private: + ListNode* findMid(ListNode* head) { + ListNode* prev = nullptr; + ListNode* slow = head; + ListNode* fast = head; + + while (fast != nullptr && fast->next != nullptr) { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + prev->next = nullptr; + + return slow; + } + + ListNode* reverse(ListNode* head) { + ListNode* prev = nullptr; + ListNode* curr = head; + + while (curr) { + ListNode* next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + + return prev; + } + + void merge(ListNode* l1, ListNode* l2) { + while (l2) { + ListNode* next = l1->next; + l1->next = l2; + l1 = l2; + l2 = next; + } + } +}; diff --git a/solutions/143. Reorder List/143.java b/solutions/143. Reorder List/143.java new file mode 100644 index 00000000000..ffaf4a30bd2 --- /dev/null +++ b/solutions/143. Reorder List/143.java @@ -0,0 +1,48 @@ +class Solution { + public void reorderList(ListNode head) { + if (head == null || head.next == null) + return; + + ListNode mid = findMid(head); + ListNode reversed = reverse(mid); + merge(head, reversed); + } + + private ListNode findMid(ListNode head) { + ListNode prev = null; + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) { + prev = slow; + slow = slow.next; + fast = fast.next.next; + } + prev.next = null; + + return slow; + } + + private ListNode reverse(ListNode head) { + ListNode prev = null; + ListNode curr = head; + + while (curr != null) { + ListNode next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + } + + return prev; + } + + private void merge(ListNode l1, ListNode l2) { + while (l2 != null) { + ListNode next = l1.next; + l1.next = l2; + l1 = l2; + l2 = next; + } + } +} diff --git a/solutions/143. Reorder List/143.py b/solutions/143. Reorder List/143.py new file mode 100644 index 00000000000..953a23005f6 --- /dev/null +++ b/solutions/143. Reorder List/143.py @@ -0,0 +1,40 @@ +class Solution: + def reorderList(self, head: ListNode) -> None: + def findMid(head: ListNode): + prev = None + slow = head + fast = head + + while fast and fast.next: + prev = slow + slow = slow.next + fast = fast.next.next + prev.next = None + + return slow + + def reverse(head: ListNode) -> ListNode: + prev = None + curr = head + + while curr: + next = curr.next + curr.next = prev + prev = curr + curr = next + + return prev + + def merge(l1: ListNode, l2: ListNode) -> None: + while l2: + next = l1.next + l1.next = l2 + l1 = l2 + l2 = next + + if not head or not head.next: + return + + mid = findMid(head) + reversed = reverse(mid) + merge(head, reversed) diff --git a/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.cpp b/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.cpp new file mode 100644 index 00000000000..5894b2192c7 --- /dev/null +++ b/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool isValidSequence(TreeNode* root, vector& arr) { + return isValidSequence(root, arr, 0); + } + + private: + bool isValidSequence(TreeNode* root, const vector& arr, int i) { + if (root == nullptr) + return false; + if (i == arr.size() - 1) + return root->val == arr[i] && root->left == nullptr && + root->right == nullptr; + return root->val == arr[i] && (isValidSequence(root->left, arr, i + 1) || + isValidSequence(root->right, arr, i + 1)); + } +}; diff --git a/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.java b/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.java new file mode 100644 index 00000000000..9ed27d3d512 --- /dev/null +++ b/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.java @@ -0,0 +1,14 @@ +class Solution { + public boolean isValidSequence(TreeNode root, int[] arr) { + return isValidSequence(root, arr, 0); + } + + private boolean isValidSequence(TreeNode root, int[] arr, int i) { + if (root == null) + return false; + if (i == arr.length - 1) + return root.val == arr[i] && root.left == null && root.right == null; + return root.val == arr[i] && + (isValidSequence(root.left, arr, i + 1) || isValidSequence(root.right, arr, i + 1)); + } +} diff --git a/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.py b/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.py new file mode 100644 index 00000000000..57909ee180b --- /dev/null +++ b/solutions/1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/1430.py @@ -0,0 +1,10 @@ +class Solution: + def isValidSequence(self, root: Optional[TreeNode], arr: List[int]) -> bool: + def isValidSequence(root: Optional[TreeNode], i: int) -> bool: + if not root: + return False + if i == len(arr) - 1: + return root.val == arr[i] and not root.left and not root.right + return root.val == arr[i] and (isValidSequence(root.left, i + 1) or isValidSequence(root.right, i + 1)) + + return isValidSequence(root, 0) diff --git a/solutions/1431. Kids With the Greatest Number of Candies/1431.cpp b/solutions/1431. Kids With the Greatest Number of Candies/1431.cpp new file mode 100644 index 00000000000..059c8029ef5 --- /dev/null +++ b/solutions/1431. Kids With the Greatest Number of Candies/1431.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector kidsWithCandies(vector& candies, int extraCandies) { + vector ans; + const int maxCandy = ranges::max(candies); + + for (const int candy : candies) + ans.push_back(candy + extraCandies >= maxCandy); + + return ans; + } +}; diff --git a/solutions/1431. Kids With the Greatest Number of Candies/1431.java b/solutions/1431. Kids With the Greatest Number of Candies/1431.java new file mode 100644 index 00000000000..952e160d44d --- /dev/null +++ b/solutions/1431. Kids With the Greatest Number of Candies/1431.java @@ -0,0 +1,11 @@ +class Solution { + public List kidsWithCandies(int[] candies, int extraCandies) { + List ans = new ArrayList<>(); + final int maxCandy = Arrays.stream(candies).max().getAsInt(); + + for (final int candy : candies) + ans.add(candy + extraCandies >= maxCandy); + + return ans; + } +} diff --git a/solutions/1431. Kids With the Greatest Number of Candies/1431.py b/solutions/1431. Kids With the Greatest Number of Candies/1431.py new file mode 100644 index 00000000000..31d0d5b37bb --- /dev/null +++ b/solutions/1431. Kids With the Greatest Number of Candies/1431.py @@ -0,0 +1,4 @@ +class Solution: + def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: + maxCandy = max(candies) + return [candy + extraCandies >= maxCandy for candy in candies] diff --git a/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.cpp b/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.cpp new file mode 100644 index 00000000000..03c9e59ae0c --- /dev/null +++ b/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxDiff(int num) { + const string s = to_string(num); + int firstNot9 = s.find_first_not_of('9'); + int firstNot01 = s.find_first_not_of("01"); + if (firstNot9 == string::npos) + firstNot9 = 0; + if (firstNot01 == string::npos) + firstNot01 = 0; + + string a = s; + string b = s; + replace(a.begin(), a.end(), s[firstNot9], '9'); + replace(b.begin(), b.end(), s[firstNot01], firstNot01 == 0 ? '1' : '0'); + return stoi(a) - stoi(b); + } +}; diff --git a/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.java b/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.java new file mode 100644 index 00000000000..3df965de754 --- /dev/null +++ b/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.java @@ -0,0 +1,17 @@ +class Solution { + public int maxDiff(int num) { + final String s = String.valueOf(num); + final int firstNot9 = firstNot(s, '9', '9'); + final int firstNot01 = firstNot(s, '0', '1'); + final String a = s.replace(s.charAt(firstNot9), '9'); + final String b = s.replace(s.charAt(firstNot01), firstNot01 == 0 ? '1' : '0'); + return Integer.parseInt(a) - Integer.parseInt(b); + } + + private int firstNot(final String s, char a, char b) { + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) != a && s.charAt(i) != b) + return i; + return 0; + } +} diff --git a/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.py b/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.py new file mode 100644 index 00000000000..ed180f1b5f3 --- /dev/null +++ b/solutions/1432. Max Difference You Can Get From Changing an Integer/1432.py @@ -0,0 +1,15 @@ +class Solution: + def maxDiff(self, num: int) -> int: + s = str(num) + + def firstNot(s: str, t: str) -> int: + for i, c in enumerate(s): + if all(c != d for d in t): + return i + return 0 + + firstNot9 = firstNot(s, '9') + firstNot01 = firstNot(s, '01') + a = s.replace(s[firstNot9], '9') + b = s.replace(s[firstNot01], '1' if firstNot01 == 0 else '0') + return int(a) - int(b) diff --git a/solutions/1433. Check If a String Can Break Another String/1433-2.cpp b/solutions/1433. Check If a String Can Break Another String/1433-2.cpp new file mode 100644 index 00000000000..98f5f7d0a45 --- /dev/null +++ b/solutions/1433. Check If a String Can Break Another String/1433-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool checkIfCanBreak(string s1, string s2) { + vector count(26); + + for (const char c : s1) + ++count[c - 'a']; + + for (const char c : s2) + --count[c - 'a']; + + for (int i = 1; i < 26; ++i) + count[i] += count[i - 1]; + + return ranges::all_of(count, [](int c) { return c <= 0; }) || + ranges::all_of(count, [](int c) { return c >= 0; }); + } +}; diff --git a/solutions/1433. Check If a String Can Break Another String/1433-2.java b/solutions/1433. Check If a String Can Break Another String/1433-2.java new file mode 100644 index 00000000000..0fb1f9fa098 --- /dev/null +++ b/solutions/1433. Check If a String Can Break Another String/1433-2.java @@ -0,0 +1,16 @@ +class Solution { + public boolean checkIfCanBreak(String s1, String s2) { + int[] count = new int[26]; + + for (final char c : s1.toCharArray()) + ++count[c - 'a']; + + for (final char c : s2.toCharArray()) + --count[c - 'a']; + + for (int i = 1; i < 26; ++i) + count[i] += count[i - 1]; + + return Arrays.stream(count).allMatch(c -> c <= 0) || Arrays.stream(count).allMatch(c -> c >= 0); + } +} diff --git a/solutions/1433. Check If a String Can Break Another String/1433-2.py b/solutions/1433. Check If a String Can Break Another String/1433-2.py new file mode 100644 index 00000000000..b2eae91010a --- /dev/null +++ b/solutions/1433. Check If a String Can Break Another String/1433-2.py @@ -0,0 +1,10 @@ +class Solution: + def checkIfCanBreak(self, s1: str, s2: str) -> bool: + count = collections.Counter(s1) + count.subtract(collections.Counter(s2)) + + for a, b in itertools.pairwise(string.ascii_lowercase): + count[b] += count[a] + + return all(value <= 0 for value in count.values()) or \ + all(value >= 0 for value in count.values()) diff --git a/solutions/1433. Check If a String Can Break Another String/1433.cpp b/solutions/1433. Check If a String Can Break Another String/1433.cpp new file mode 100644 index 00000000000..a58c0086109 --- /dev/null +++ b/solutions/1433. Check If a String Can Break Another String/1433.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool checkIfCanBreak(string s1, string s2) { + vector count1(26); + vector count2(26); + + for (const char c : s1) + ++count1[c - 'a']; + + for (const char c : s2) + ++count2[c - 'a']; + + return canBreak(count1, count2) || canBreak(count2, count1); + } + + private: + // Returns true if count1 can break count2. + bool canBreak(const vector& count1, const vector& count2) { + int diff = 0; + for (int i = 0; i < 26; ++i) { + diff += count2[i] - count1[i]; + // count2 is alphabetically greater than count1. + if (diff < 0) + return false; + } + return true; + } +}; diff --git a/solutions/1433. Check If a String Can Break Another String/1433.java b/solutions/1433. Check If a String Can Break Another String/1433.java new file mode 100644 index 00000000000..427ef41d98c --- /dev/null +++ b/solutions/1433. Check If a String Can Break Another String/1433.java @@ -0,0 +1,26 @@ +class Solution { + public boolean checkIfCanBreak(String s1, String s2) { + int[] count1 = new int[26]; + int[] count2 = new int[26]; + + for (final char c : s1.toCharArray()) + ++count1[c - 'a']; + + for (final char c : s2.toCharArray()) + ++count2[c - 'a']; + + return canBreak(count1, count2) || canBreak(count2, count1); + } + + // Returns true if count1 can break count2. + private boolean canBreak(int[] count1, int[] count2) { + int diff = 0; + for (int i = 0; i < 26; ++i) { + diff += count2[i] - count1[i]; + // count2 is alphabetically greater than count1. + if (diff < 0) + return false; + } + return true; + } +} diff --git a/solutions/1433. Check If a String Can Break Another String/1433.py b/solutions/1433. Check If a String Can Break Another String/1433.py new file mode 100644 index 00000000000..165420664eb --- /dev/null +++ b/solutions/1433. Check If a String Can Break Another String/1433.py @@ -0,0 +1,16 @@ +class Solution: + def checkIfCanBreak(self, s1: str, s2: str) -> bool: + count1 = collections.Counter(s1) + count2 = collections.Counter(s2) + + def canBreak(count1: Dict[str, int], count2: Dict[str, int]) -> bool: + """Returns True if count1 can break count2.""" + diff = 0 + for c in string.ascii_lowercase: + diff += count2[c] - count1[c] + # count2 is alphabetically greater than count1. + if diff < 0: + return False + return True + + return canBreak(count1, count2) or canBreak(count2, count1) diff --git a/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.cpp b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.cpp new file mode 100644 index 00000000000..391bef061d5 --- /dev/null +++ b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int numberWays(vector>& hats) { + constexpr int kMod = 1'000'000'007; + constexpr int nHats = 40; + const int nPeople = hats.size(); + const int nAssignments = 1 << nPeople; + vector> hatToPeople(nHats + 1); + // dp[i][j] := the number of ways to assign hats 1, 2, ..., i to people, + // where j is the bitmask of the current assignment + vector> dp(nHats + 1, vector(nAssignments)); + dp[0][0] = 1; + + for (int i = 0; i < nPeople; ++i) + for (const int hat : hats[i]) + hatToPeople[hat].push_back(i); + + for (int h = 1; h <= nHats; ++h) + for (int j = 0; j < nAssignments; ++j) { + // We can cover the assignment j in 2 ways: + // 1. Assign the first h - 1 hats to people without using the hat `h`. + dp[h][j] += dp[h - 1][j]; + dp[h][j] %= kMod; + for (const int p : hatToPeople[h]) + if (j >> p & 1) { + // 2. Assign the first h - 1 hats to people without the person `p` + // and assign the hat `h` to the person `p`. + dp[h][j] += dp[h - 1][j ^ 1 << p]; + dp[h][j] %= kMod; + } + } + + return dp[nHats][nAssignments - 1]; + } +}; diff --git a/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.java b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.java new file mode 100644 index 00000000000..d1b3e297d84 --- /dev/null +++ b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-2.java @@ -0,0 +1,37 @@ +class Solution { + public int numberWays(List> hats) { + final int kMod = 1_000_000_007; + final int nHats = 40; + final int nPeople = hats.size(); + final int nAssignments = 1 << nPeople; + List[] hatToPeople = new List[nHats + 1]; + // dp[i][j] := the number of ways to assign hats 1, 2, ..., i to people, + // where j is the bitmask of the current assignment + int[][] dp = new int[nHats + 1][nAssignments]; + dp[0][0] = 1; + + for (int i = 1; i <= nHats; ++i) + hatToPeople[i] = new ArrayList<>(); + + for (int i = 0; i < nPeople; ++i) + for (final int hat : hats.get(i)) + hatToPeople[hat].add(i); + + for (int h = 1; h <= nHats; ++h) + for (int j = 0; j < nAssignments; ++j) { + // We can cover the assignment j in 2 ways: + // 1. Assign the first h - 1 hats to people without using the hat `h`. + dp[h][j] += dp[h - 1][j]; + dp[h][j] %= kMod; + for (final int p : hatToPeople[h]) + if ((j >> p & 1) == 1) { + // 2. Assign the first h - 1 hats to people without the person `p` + // and assign the hat `h` to the person `p`. + dp[h][j] += dp[h - 1][j ^ 1 << p]; + dp[h][j] %= kMod; + } + } + + return dp[nHats][nAssignments - 1]; + } +} diff --git a/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.cpp b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.cpp new file mode 100644 index 00000000000..b25c3febf86 --- /dev/null +++ b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int numberWays(vector>& hats) { + constexpr int kMod = 1'000'000'007; + constexpr int nHats = 40; + const int nPeople = hats.size(); + const int nAssignments = 1 << nPeople; + vector> hatToPeople(nHats + 1); + // dp[i] := the number of ways to assign the hats so far to people, where i + // is the bitmask of the current assignment + vector dp(nAssignments); + dp[0] = 1; + + for (int i = 0; i < nPeople; ++i) + for (const int hat : hats[i]) + hatToPeople[hat].push_back(i); + + for (int h = 1; h <= nHats; ++h) + for (int j = nAssignments - 1; j >= 0; --j) + for (const int p : hatToPeople[h]) + if (j >> p & 1) { + dp[j] += dp[j ^ 1 << p]; + dp[j] %= kMod; + } + + return dp[nAssignments - 1]; + } +}; diff --git a/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.java b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.java new file mode 100644 index 00000000000..fd84f567730 --- /dev/null +++ b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434-3.java @@ -0,0 +1,30 @@ +class Solution { + public int numberWays(List> hats) { + final int kMod = 1_000_000_007; + final int nHats = 40; + final int nPeople = hats.size(); + final int nAssignments = 1 << nPeople; + List[] hatToPeople = new List[nHats + 1]; + // dp[i] := the number of ways to assign the hats so far to people, where i + // is the bitmask of the current assignment + int[] dp = new int[nAssignments]; + dp[0] = 1; + + for (int i = 1; i <= nHats; ++i) + hatToPeople[i] = new ArrayList<>(); + + for (int i = 0; i < nPeople; ++i) + for (final int hat : hats.get(i)) + hatToPeople[hat].add(i); + + for (int h = 1; h <= nHats; ++h) + for (int j = nAssignments - 1; j >= 0; --j) + for (final int p : hatToPeople[h]) + if ((j >> p & 1) == 1) { + dp[j] += dp[j ^ 1 << p]; + dp[j] %= kMod; + } + + return dp[nAssignments - 1]; + } +} diff --git a/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.cpp b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.cpp new file mode 100644 index 00000000000..3ee8bd73d22 --- /dev/null +++ b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + int numberWays(vector>& hats) { + constexpr int nHats = 40; + const int nPeople = hats.size(); + vector> hatToPeople(nHats + 1); + vector> mem(nHats + 1, vector(1 << nPeople, -1)); + + for (int i = 0; i < nPeople; ++i) + for (const int hat : hats[i]) + hatToPeople[hat].push_back(i); + + return numberWays(hats, 0, 1, hatToPeople, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of ways to assign hats 1, 2, ..., h to people, where + // `assignment` is the bitmask of the current assignment. + int numberWays(const vector>& hats, int assignment, int h, + const vector>& hatToPeople, + vector>& mem) { + // All the people are assigned. + if (assignment == (1 << hats.size()) - 1) + return 1; + if (h > 40) + return 0; + if (mem[h][assignment] != -1) + return mem[h][assignment]; + + // Don't wear the hat `h`. + mem[h][assignment] = numberWays(hats, assignment, h + 1, hatToPeople, mem); + + for (const int p : hatToPeople[h]) { + // The person `p` was assigned the hat `h` before. + if (assignment >> p & 1) + continue; + // Assign the hat `h` to the person `p`. + mem[h][assignment] += + numberWays(hats, assignment | 1 << p, h + 1, hatToPeople, mem); + mem[h][assignment] %= kMod; + } + + return mem[h][assignment]; + } +}; diff --git a/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.java b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.java new file mode 100644 index 00000000000..d081ce0c12e --- /dev/null +++ b/solutions/1434. Number of Ways to Wear Different Hats to Each Other/1434.java @@ -0,0 +1,46 @@ +class Solution { + public int numberWays(List> hats) { + final int nHats = 40; + final int nPeople = hats.size(); + List[] hatToPeople = new List[nHats + 1]; + Integer[][] mem = new Integer[nHats + 1][1 << nPeople]; + + for (int i = 1; i <= nHats; ++i) + hatToPeople[i] = new ArrayList<>(); + + for (int i = 0; i < nPeople; ++i) + for (final int hat : hats.get(i)) + hatToPeople[hat].add(i); + + return numberWays(hats, 0, 1, hatToPeople, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of ways to assign hats 1, 2, ..., h to people, where + // `assignment` is the bitmask of the current assignment. + private int numberWays(List> hats, int assignment, int h, + List[] hatToPeople, Integer[][] mem) { + // All the people are assigned. + if (assignment == (1 << hats.size()) - 1) + return 1; + if (h > 40) + return 0; + if (mem[h][assignment] != null) + return mem[h][assignment]; + + // Don't wear the hat `h`. + int ans = numberWays(hats, assignment, h + 1, hatToPeople, mem); + + for (final int p : hatToPeople[h]) { + // The person `p` was assigned the hat `h` before. + if ((assignment >> p & 1) == 1) + continue; + // Assign the hat `h` to the person `p`. + ans += numberWays(hats, assignment | 1 << p, h + 1, hatToPeople, mem); + ans %= kMod; + } + + return mem[h][assignment] = ans; + } +} diff --git a/solutions/1435. Create a Session Bar Chart/1435.sql b/solutions/1435. Create a Session Bar Chart/1435.sql new file mode 100644 index 00000000000..7b396211827 --- /dev/null +++ b/solutions/1435. Create a Session Bar Chart/1435.sql @@ -0,0 +1,21 @@ +SELECT '[0-5>' AS bin, + SUM(duration <= 300) AS total +FROM Sessions +UNION ALL +SELECT '[5-10>' AS bin, + SUM( + duration > 300 + AND duration <= 600 + ) AS total +FROM Sessions +UNION ALL +SELECT '[10-15>' AS bin, + SUM( + duration > 600 + AND duration <= 900 + ) AS total +FROM Sessions +UNION ALL +SELECT '15 or more' AS bin, + SUM(duration > 900) AS total +FROM Sessions diff --git a/solutions/1436. Destination City/1436.py b/solutions/1436. Destination City/1436.py new file mode 100644 index 00000000000..fbda7ffd320 --- /dev/null +++ b/solutions/1436. Destination City/1436.py @@ -0,0 +1,14 @@ +class Solution: + def destCity(self, paths: List[List[str]]) -> str: + count = collections.Counter() + + for a, b in paths: + count[a] += 1 + + for a, b in paths: + if b in count: + count[b] -= 1 + if count[b] == 0: + del count[b] + else: + return b diff --git a/solutions/1437. Check If All 1's Are at Least Length K Places Away/1437.py b/solutions/1437. Check If All 1's Are at Least Length K Places Away/1437.py new file mode 100644 index 00000000000..95b59c3af0e --- /dev/null +++ b/solutions/1437. Check If All 1's Are at Least Length K Places Away/1437.py @@ -0,0 +1,18 @@ +class Solution: + def kLengthApart(self, nums: List[int], k: int) -> bool: + if k == 0: + return True + + n = len(nums) + + curr = 0 + next = 1 + + while curr < n and next < n: + if nums[next] == 1: + if nums[curr] == 1 and next - curr <= k: + return False + curr = next + next += 1 + + return True diff --git a/solutions/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/1438.cpp b/solutions/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/1438.cpp new file mode 100644 index 00000000000..f81ae05afe4 --- /dev/null +++ b/solutions/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/1438.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int longestSubarray(vector& nums, int limit) { + int ans = 1; + deque minQ; + deque maxQ; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + while (!minQ.empty() && minQ.back() > nums[r]) + minQ.pop_back(); + minQ.push_back(nums[r]); + while (!maxQ.empty() && maxQ.back() < nums[r]) + maxQ.pop_back(); + maxQ.push_back(nums[r]); + while (maxQ.front() - minQ.front() > limit) { + if (minQ.front() == nums[l]) + minQ.pop_front(); + if (maxQ.front() == nums[l]) + maxQ.pop_front(); + ++l; + } + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.cpp b/solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.cpp new file mode 100644 index 00000000000..d8931a50d55 --- /dev/null +++ b/solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.cpp @@ -0,0 +1,39 @@ +struct T { + int i; + int j; + int sum; // nums1[i] + nums2[j] + T(int i, int j, int sum) : i(i), j(j), sum(sum) {} +}; + +class Solution { + public: + int kthSmallest(vector>& mat, int k) { + vector row = mat[0]; + + for (int i = 1; i < mat.size(); ++i) + row = kSmallestPairSums(row, mat[i], k); + + return row.back(); + } + + private: + // Similar to 373. Find K Pairs with Smallest Sums + vector kSmallestPairSums(vector& nums1, vector& nums2, int k) { + vector ans; + auto compare = [&](const T& a, const T& b) { return a.sum > b.sum; }; + priority_queue, decltype(compare)> minHeap(compare); + + for (int i = 0; i < k && i < nums1.size(); ++i) + minHeap.emplace(i, 0, nums1[i] + nums2[0]); + + while (!minHeap.empty() && ans.size() < k) { + const auto [i, j, _] = minHeap.top(); + minHeap.pop(); + ans.push_back(nums1[i] + nums2[j]); + if (j + 1 < nums2.size()) + minHeap.emplace(i, j + 1, nums1[i] + nums2[j + 1]); + } + + return ans; + } +}; diff --git a/solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.java b/solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.java new file mode 100644 index 00000000000..3c144638a73 --- /dev/null +++ b/solutions/1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows/1439.java @@ -0,0 +1,40 @@ +class T { + public int i; + public int j; + public int sum; // nums1[i] + nums2[j] + public T(int i, int j, int sum) { + this.i = i; + this.j = j; + this.sum = sum; + } +} + +class Solution { + public int kthSmallest(int[][] mat, int k) { + int[] row = mat[0]; + + for (int i = 1; i < mat.length; ++i) + row = kSmallestPairSums(row, mat[i], k); + + return row[k - 1]; + } + + // Similar to 373. Find K Pairs with Smallest Sums + private int[] kSmallestPairSums(int[] nums1, int[] nums2, int k) { + List ans = new ArrayList<>(); + Queue minHeap = new PriorityQueue<>((a, b) -> a.sum - b.sum); + + for (int i = 0; i < k && i < nums1.length; ++i) + minHeap.offer(new T(i, 0, nums1[i] + nums2[0])); + + while (!minHeap.isEmpty() && ans.size() < k) { + final int i = minHeap.peek().i; + final int j = minHeap.poll().j; + ans.add(nums1[i] + nums2[j]); + if (j + 1 < nums2.length) + minHeap.offer(new T(i, j + 1, nums1[i] + nums2[j + 1])); + } + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/144. Binary Tree Preorder Traversal/144-2.cpp b/solutions/144. Binary Tree Preorder Traversal/144-2.cpp new file mode 100644 index 00000000000..947a03846a4 --- /dev/null +++ b/solutions/144. Binary Tree Preorder Traversal/144-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector preorderTraversal(TreeNode* root) { + if (root == nullptr) + return {}; + + vector ans; + stack stack{{root}}; + + while (!stack.empty()) { + root = stack.top(), stack.pop(); + ans.push_back(root->val); + if (root->right) + stack.push(root->right); + if (root->left) + stack.push(root->left); + } + + return ans; + } +}; diff --git a/solutions/144. Binary Tree Preorder Traversal/144-2.java b/solutions/144. Binary Tree Preorder Traversal/144-2.java new file mode 100644 index 00000000000..704ecdfbd67 --- /dev/null +++ b/solutions/144. Binary Tree Preorder Traversal/144-2.java @@ -0,0 +1,21 @@ +class Solution { + public List preorderTraversal(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + Deque stack = new ArrayDeque<>(); + stack.push(root); + + while (!stack.isEmpty()) { + root = stack.pop(); + ans.add(root.val); + if (root.right != null) + stack.push(root.right); + if (root.left != null) + stack.push(root.left); + } + + return ans; + } +} diff --git a/solutions/144. Binary Tree Preorder Traversal/144-2.py b/solutions/144. Binary Tree Preorder Traversal/144-2.py new file mode 100644 index 00000000000..6052c14320e --- /dev/null +++ b/solutions/144. Binary Tree Preorder Traversal/144-2.py @@ -0,0 +1,17 @@ +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + ans = [] + stack = [root] + + while stack: + node = stack.pop() + ans.append(node.val) + if node.right: + stack.append(node.right) + if node.left: + stack.append(node.left) + + return ans diff --git a/solutions/144. Binary Tree Preorder Traversal/144.cpp b/solutions/144. Binary Tree Preorder Traversal/144.cpp new file mode 100644 index 00000000000..d400218312d --- /dev/null +++ b/solutions/144. Binary Tree Preorder Traversal/144.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector preorderTraversal(TreeNode* root) { + vector ans; + preorder(root, ans); + return ans; + } + + private: + void preorder(TreeNode* root, vector& ans) { + if (root == nullptr) + return; + + ans.push_back(root->val); + preorder(root->left, ans); + preorder(root->right, ans); + } +}; diff --git a/solutions/144. Binary Tree Preorder Traversal/144.java b/solutions/144. Binary Tree Preorder Traversal/144.java new file mode 100644 index 00000000000..4874e28bd7a --- /dev/null +++ b/solutions/144. Binary Tree Preorder Traversal/144.java @@ -0,0 +1,16 @@ +class Solution { + public List preorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + preorder(root, ans); + return ans; + } + + private void preorder(TreeNode root, List ans) { + if (root == null) + return; + + ans.add(root.val); + preorder(root.left, ans); + preorder(root.right, ans); + } +} diff --git a/solutions/144. Binary Tree Preorder Traversal/144.py b/solutions/144. Binary Tree Preorder Traversal/144.py new file mode 100644 index 00000000000..b5d1f6602c2 --- /dev/null +++ b/solutions/144. Binary Tree Preorder Traversal/144.py @@ -0,0 +1,14 @@ +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + + def preorder(root: Optional[TreeNode]) -> None: + if not root: + return + + ans.append(root.val) + preorder(root.left) + preorder(root.right) + + preorder(root) + return ans diff --git a/solutions/1440. Evaluate Boolean Expression/1440.sql b/solutions/1440. Evaluate Boolean Expression/1440.sql new file mode 100644 index 00000000000..ddeb34b1816 --- /dev/null +++ b/solutions/1440. Evaluate Boolean Expression/1440.sql @@ -0,0 +1,17 @@ +SELECT Expressions.*, + ( + CASE + WHEN Expressions.operator = '<' + AND LeftOperand.value < RightOperand.value THEN 'true' + WHEN Expressions.operator = '>' + AND LeftOperand.value > RightOperand.value THEN 'true' + WHEN Expressions.operator = '=' + AND LeftOperand.value = RightOperand.value THEN 'true' + ELSE 'false' + END + ) AS value +FROM Expressions +INNER JOIN VARIABLES AS LeftOperand + ON (Expressions.left_operand = LeftOperand.name) +INNER JOIN VARIABLES AS RightOperand + ON (Expressions.right_operand = RightOperand.name); diff --git a/solutions/1441. Build an Array With Stack Operations/1441.py b/solutions/1441. Build an Array With Stack Operations/1441.py new file mode 100644 index 00000000000..c57039a1e6a --- /dev/null +++ b/solutions/1441. Build an Array With Stack Operations/1441.py @@ -0,0 +1,17 @@ +class Solution: + def buildArray(self, target: List[int], n: int) -> List[str]: + ans = [] + i = 0 # Target pointer + num = 1 # Curr num + + while i < len(target): + t = target[i] + if t == num: + ans.append("Push") + i += 1 + else: + ans.append("Push") + ans.append("Pop") + num += 1 + + return ans diff --git a/solutions/1442. Count Triplets That Can Form Two Arrays of Equal XOR/1442.py b/solutions/1442. Count Triplets That Can Form Two Arrays of Equal XOR/1442.py new file mode 100644 index 00000000000..66b6a0cc1b8 --- /dev/null +++ b/solutions/1442. Count Triplets That Can Form Two Arrays of Equal XOR/1442.py @@ -0,0 +1,19 @@ +class Solution: + def countTriplets(self, arr: List[int]) -> int: + ans = 0 + xors = [0] + prefix = 0 + + for i, a in enumerate(arr): + prefix ^= a + xors.append(prefix) + + for j in range(1, len(arr)): + for i in range(0, j): + xors_i = xors[j] ^ xors[i] + for k in range(j, len(arr)): + xors_k = xors[k + 1] ^ xors[j] + if xors_i == xors_k: + ans += 1 + + return ans diff --git a/solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.cpp b/solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.cpp new file mode 100644 index 00000000000..a635d84d1ed --- /dev/null +++ b/solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minTime(int n, vector>& edges, vector& hasApple) { + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + return dfs(graph, 0, vector(n), hasApple); + } + + private: + int dfs(const vector>& graph, int u, vector&& seen, + const vector& hasApple) { + seen[u] = true; + int totalCost = 0; + + for (const int v : graph[u]) { + if (seen[v]) + continue; + const int cost = dfs(graph, v, move(seen), hasApple); + if (cost > 0 || hasApple[v]) + totalCost += cost + 2; + } + + return totalCost; + } +}; diff --git a/solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.java b/solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.java new file mode 100644 index 00000000000..ff624e7e8f4 --- /dev/null +++ b/solutions/1443. Minimum Time to Collect All Apples in a Tree/1443.java @@ -0,0 +1,32 @@ +class Solution { + public int minTime(int n, int[][] edges, List hasApple) { + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + return dfs(graph, 0, new boolean[n], hasApple); + } + + private int dfs(List[] graph, int u, boolean[] seen, List hasApple) { + seen[u] = true; + int totalCost = 0; + + for (final int v : graph[u]) { + if (seen[v]) + continue; + final int cost = dfs(graph, v, seen, hasApple); + if (cost > 0 || hasApple.get(v)) + totalCost += cost + 2; + } + + return totalCost; + } +} diff --git a/solutions/1444. Number of Ways of Cutting a Pizza/1444.cpp b/solutions/1444. Number of Ways of Cutting a Pizza/1444.cpp new file mode 100644 index 00000000000..20adfb10920 --- /dev/null +++ b/solutions/1444. Number of Ways of Cutting a Pizza/1444.cpp @@ -0,0 +1,53 @@ +class Solution { + public: + int ways(vector& pizza, int k) { + const int M = pizza.size(); + const int N = pizza[0].size(); + vector>> mem(M, + vector>(N, vector(k, -1))); + vector> prefix(M + 1, vector(N + 1)); + + for (int i = 0; i < M; ++i) + for (int j = 0; j < N; ++j) + prefix[i + 1][j + 1] = (pizza[i][j] == 'A') + prefix[i][j + 1] + + prefix[i + 1][j] - prefix[i][j]; + + return ways(0, 0, k - 1, M, N, prefix, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of ways to cut pizza[m..M)[n..N) with k cuts. + int ways(int m, int n, int k, const int M, const int N, + const vector>& prefix, + vector>>& mem) { + if (k == 0) + return hasApple(prefix, m, M, n, N) ? 1 : 0; + if (mem[m][n][k] != -1) + return mem[m][n][k]; + + mem[m][n][k] = 0; + + for (int i = m + 1; i < M; ++i) // Cut horizontally. + if (hasApple(prefix, m, i, n, N) && hasApple(prefix, i, M, n, N)) { + mem[m][n][k] += ways(i, n, k - 1, M, N, prefix, mem); + mem[m][n][k] %= kMod; + } + + for (int j = n + 1; j < N; ++j) // Cut vertically. + if (hasApple(prefix, m, M, n, j) && hasApple(prefix, m, M, j, N)) { + mem[m][n][k] += ways(m, j, k - 1, M, N, prefix, mem); + mem[m][n][k] %= kMod; + } + + return mem[m][n][k]; + } + + // Returns true if pizza[row1..row2)[col1..col2) has apple. + bool hasApple(const vector>& prefix, int row1, int row2, int col1, + int col2) { + return (prefix[row2][col2] - prefix[row1][col2] - // + prefix[row2][col1] + prefix[row1][col1]) > 0; + }; +}; diff --git a/solutions/1444. Number of Ways of Cutting a Pizza/1444.java b/solutions/1444. Number of Ways of Cutting a Pizza/1444.java new file mode 100644 index 00000000000..1115a33d37b --- /dev/null +++ b/solutions/1444. Number of Ways of Cutting a Pizza/1444.java @@ -0,0 +1,50 @@ +class Solution { + public int ways(String[] pizza, int k) { + final int M = pizza.size(); + final int N = pizza[0].length(); + int[][][] mem = new int[M][N][k]; + int[][] prefix = new int[M + 1][N + 1]; + + for (int[][] A : mem) + Arrays.stream(mem).forEach(B -> Arrays.fill(B, -1)); + + for (int i = 0; i < M; ++i) + for (int j = 0; j < N; ++j) + prefix[i + 1][j + 1] = (pizza[i].charAt(j) == 'A' ? 1 : 0) + prefix[i][j + 1] + + prefix[i + 1][j] - prefix[i][j]; + + return ways(0, 0, k - 1, M, N, prefix, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of ways to cut pizza[m..M)[n..N) with k cuts. + private int ways(int m, int n, int k, int M, int N, int[][] prefix, int[][][] mem) { + if (k == 0) + return hasApple(prefix, m, M, n, N) ? 1 : 0; + if (mem[m][n][k] != -1) + return mem[m][n][k]; + + mem[m][n][k] = 0; + + for (int i = m + 1; i < M; ++i) // Cut horizontally. + if (hasApple(prefix, m, i, n, N) && hasApple(prefix, i, M, n, N)) { + mem[m][n][k] += ways(i, n, k - 1, M, N, prefix, mem); + mem[m][n][k] %= kMod; + } + + for (int j = n + 1; j < N; ++j) // Cut vertically. + if (hasApple(prefix, m, M, n, j) && hasApple(prefix, m, M, j, N)) { + mem[m][n][k] += ways(m, j, k - 1, M, N, prefix, mem); + mem[m][n][k] %= kMod; + } + + return mem[m][n][k]; + } + + // Returns true if pizza[row1..row2)[col1..col2) has apple. + private boolean hasApple(int[][] prefix, int row1, int row2, int col1, int col2) { + return (prefix[row2][col2] - prefix[row1][col2] - // + prefix[row2][col1] + prefix[row1][col1]) > 0; + } +} diff --git a/solutions/1444. Number of Ways of Cutting a Pizza/1444.py b/solutions/1444. Number of Ways of Cutting a Pizza/1444.py new file mode 100644 index 00000000000..93db6751170 --- /dev/null +++ b/solutions/1444. Number of Ways of Cutting a Pizza/1444.py @@ -0,0 +1,36 @@ +class Solution: + def ways(self, pizza: List[str], k: int) -> int: + kMod = 1_000_000_007 + M = len(pizza) + N = len(pizza[0]) + prefix = [[0] * (N + 1) for _ in range(M + 1)] + + for i in range(M): + for j in range(N): + prefix[i + 1][j + 1] = (pizza[i][j] == 'A') + \ + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j] + + def hasApple(row1: int, row2: int, col1: int, col2: int) -> bool: + """Returns True if pizza[row1..row2)[col1..col2) has apple.""" + return (prefix[row2][col2] - prefix[row1][col2] - + prefix[row2][col1] + prefix[row1][col1]) > 0 + + @functools.lru_cache(None) + def dp(m: int, n: int, k: int) -> int: + """Returns the number of ways to cut pizza[m..M)[n..N) with k cuts.""" + if k == 0: + return 1 if hasApple(m, M, n, N) else 0 + + res = 0 + + for i in range(m + 1, M): # Cut horizontally. + if hasApple(m, i, n, N) and hasApple(i, M, n, N): + res += dp(i, n, k - 1) + + for j in range(n + 1, N): # Cut vertically. + if hasApple(m, M, n, j) and hasApple(m, M, j, N): + res += dp(m, j, k - 1) + + return res % kMod + + return dp(0, 0, k - 1) diff --git a/solutions/1445. Apples & Oranges/1445.sql b/solutions/1445. Apples & Oranges/1445.sql new file mode 100644 index 00000000000..828aa3d8b80 --- /dev/null +++ b/solutions/1445. Apples & Oranges/1445.sql @@ -0,0 +1,5 @@ +SELECT + sale_date, + SUM(IF(fruit = 'apples', sold_num, -sold_num)) AS diff +FROM Sales +GROUP BY 1; diff --git a/solutions/1446. Consecutive Characters/1446.cpp b/solutions/1446. Consecutive Characters/1446.cpp new file mode 100644 index 00000000000..df1ee838a34 --- /dev/null +++ b/solutions/1446. Consecutive Characters/1446.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxPower(string s) { + int ans = 1; + int count = 1; + + for (int i = 1; i < s.length(); ++i) { + count = s[i] == s[i - 1] ? count + 1 : 1; + ans = max(ans, count); + } + + return ans; + } +}; diff --git a/solutions/1446. Consecutive Characters/1446.java b/solutions/1446. Consecutive Characters/1446.java new file mode 100644 index 00000000000..ac4f6aa953d --- /dev/null +++ b/solutions/1446. Consecutive Characters/1446.java @@ -0,0 +1,13 @@ +class Solution { + public int maxPower(String s) { + int ans = 1; + int count = 1; + + for (int i = 1; i < s.length(); ++i) { + count = s.charAt(i) == s.charAt(i - 1) ? count + 1 : 1; + ans = Math.max(ans, count); + } + + return ans; + } +} diff --git a/solutions/1446. Consecutive Characters/1446.py b/solutions/1446. Consecutive Characters/1446.py new file mode 100644 index 00000000000..7f597f09117 --- /dev/null +++ b/solutions/1446. Consecutive Characters/1446.py @@ -0,0 +1,10 @@ +class Solution: + def maxPower(self, s: str) -> int: + ans = 1 + count = 1 + + for i in range(1, len(s)): + count = count + 1 if s[i] == s[i - 1] else 1 + ans = max(ans, count) + + return ans diff --git a/solutions/1447. Simplified Fractions/1447.cpp b/solutions/1447. Simplified Fractions/1447.cpp new file mode 100644 index 00000000000..98a688deaa2 --- /dev/null +++ b/solutions/1447. Simplified Fractions/1447.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector simplifiedFractions(int n) { + vector ans; + for (int denominator = 2; denominator <= n; ++denominator) + for (int numerator = 1; numerator < denominator; ++numerator) + if (__gcd(denominator, numerator) == 1) + ans.push_back(to_string(numerator) + "/" + to_string(denominator)); + return ans; + } +}; diff --git a/solutions/1447. Simplified Fractions/1447.java b/solutions/1447. Simplified Fractions/1447.java new file mode 100644 index 00000000000..5b807f797a0 --- /dev/null +++ b/solutions/1447. Simplified Fractions/1447.java @@ -0,0 +1,14 @@ +class Solution { + public List simplifiedFractions(int n) { + List ans = new ArrayList<>(); + for (int denominator = 2; denominator <= n; ++denominator) + for (int numerator = 1; numerator < denominator; ++numerator) + if (gcd(denominator, numerator) == 1) + ans.add(String.valueOf(numerator) + "/" + String.valueOf(denominator)); + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/1447. Simplified Fractions/1447.py b/solutions/1447. Simplified Fractions/1447.py new file mode 100644 index 00000000000..19c233022c3 --- /dev/null +++ b/solutions/1447. Simplified Fractions/1447.py @@ -0,0 +1,8 @@ +class Solution: + def simplifiedFractions(self, n: int) -> List[str]: + ans = [] + for denominator in range(2, n + 1): + for numerator in range(1, denominator): + if math.gcd(denominator, numerator) == 1: + ans.append(str(numerator) + '/' + str(denominator)) + return ans diff --git a/solutions/1448. Count Good Nodes in Binary Tree/1448.cpp b/solutions/1448. Count Good Nodes in Binary Tree/1448.cpp new file mode 100644 index 00000000000..ce9d5c03c58 --- /dev/null +++ b/solutions/1448. Count Good Nodes in Binary Tree/1448.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int goodNodes(TreeNode* root, int mx = INT_MIN) { + if (root == nullptr) + return 0; + const int newMax = max(mx, root->val); + return (root->val >= mx) + // + goodNodes(root->left, newMax) + // + goodNodes(root->right, newMax); + } +}; diff --git a/solutions/1448. Count Good Nodes in Binary Tree/1448.java b/solutions/1448. Count Good Nodes in Binary Tree/1448.java new file mode 100644 index 00000000000..6f12aa5960e --- /dev/null +++ b/solutions/1448. Count Good Nodes in Binary Tree/1448.java @@ -0,0 +1,13 @@ +class Solution { + public int goodNodes(TreeNode root) { + return goodNodes(root, Integer.MIN_VALUE); + } + + private int goodNodes(TreeNode root, int mx) { + if (root == null) + return 0; + + final int newMax = Math.max(mx, root.val); + return (root.val >= mx ? 1 : 0) + goodNodes(root.left, newMax) + goodNodes(root.right, newMax); + } +} diff --git a/solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.cpp b/solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.cpp new file mode 100644 index 00000000000..5a6ea843d75 --- /dev/null +++ b/solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string largestNumber(vector& cost, int target) { + // dp[i] := the maximum length that cost i can achieve + vector dp(target + 1, INT_MIN); + dp[0] = 0; // If cost = 0, the best choice is the empty string "". + + for (int i = 1; i <= target; ++i) + for (int d = 0; d < 9; ++d) + if (i >= cost[d]) + dp[i] = max(dp[i], dp[i - cost[d]] + 1); + + if (dp[target] < 0) + return "0"; + + string ans; + + // Greedily build the ans string. + for (int d = 8; d >= 0; --d) + while (target >= cost[d] && dp[target] == dp[target - cost[d]] + 1) { + target -= cost[d]; + ans += '1' + d; + } + + return ans; + } +}; diff --git a/solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.java b/solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.java new file mode 100644 index 00000000000..9390cd720e6 --- /dev/null +++ b/solutions/1449. Form Largest Integer With Digits That Add up to Target/1449.java @@ -0,0 +1,27 @@ +class Solution { + public String largestNumber(int[] cost, int target) { + // dp[i] := the maximum length that cost i can achieve + int[] dp = new int[target + 1]; + Arrays.fill(dp, Integer.MIN_VALUE); + dp[0] = 0; // If cost = 0, the best choice is the empty string "". + + for (int i = 1; i <= target; ++i) + for (int d = 0; d < 9; ++d) + if (i >= cost[d]) + dp[i] = Math.max(dp[i], dp[i - cost[d]] + 1); + + if (dp[target] < 0) + return "0"; + + StringBuilder sb = new StringBuilder(); + + // Greedily build the ans string. + for (int d = 8; d >= 0; --d) + while (target >= cost[d] && dp[target] == dp[target - cost[d]] + 1) { + target -= cost[d]; + sb.append(1 + d); + } + + return sb.toString(); + } +} diff --git a/solutions/145. Binary Tree Postorder Traversal/145-2.cpp b/solutions/145. Binary Tree Postorder Traversal/145-2.cpp new file mode 100644 index 00000000000..46352b302db --- /dev/null +++ b/solutions/145. Binary Tree Postorder Traversal/145-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector postorderTraversal(TreeNode* root) { + if (root == nullptr) + return {}; + + vector ans; + stack stack{{root}}; + + while (!stack.empty()) { + root = stack.top(), stack.pop(); + ans.push_back(root->val); + if (root->left) + stack.push(root->left); + if (root->right) + stack.push(root->right); + } + + reverse(ans.begin(), ans.end()); + return ans; + } +}; diff --git a/solutions/145. Binary Tree Postorder Traversal/145-2.java b/solutions/145. Binary Tree Postorder Traversal/145-2.java new file mode 100644 index 00000000000..ba9a589eca0 --- /dev/null +++ b/solutions/145. Binary Tree Postorder Traversal/145-2.java @@ -0,0 +1,22 @@ +class Solution { + public List postorderTraversal(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + Deque stack = new ArrayDeque<>(); + stack.push(root); + + while (!stack.isEmpty()) { + root = stack.pop(); + ans.add(root.val); + if (root.left != null) + stack.push(root.left); + if (root.right != null) + stack.push(root.right); + } + + Collections.reverse(ans); + return ans; + } +} diff --git a/solutions/145. Binary Tree Postorder Traversal/145-2.py b/solutions/145. Binary Tree Postorder Traversal/145-2.py new file mode 100644 index 00000000000..304aadcc046 --- /dev/null +++ b/solutions/145. Binary Tree Postorder Traversal/145-2.py @@ -0,0 +1,17 @@ +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + ans = [] + stack = [root] + + while stack: + node = stack.pop() + ans.append(node.val) + if node.left: + stack.append(node.left) + if node.right: + stack.append(node.right) + + return ans[::-1] diff --git a/solutions/145. Binary Tree Postorder Traversal/145.cpp b/solutions/145. Binary Tree Postorder Traversal/145.cpp new file mode 100644 index 00000000000..6d9c3dcb633 --- /dev/null +++ b/solutions/145. Binary Tree Postorder Traversal/145.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector postorderTraversal(TreeNode* root) { + vector ans; + postorder(root, ans); + return ans; + } + + private: + void postorder(TreeNode* root, vector& ans) { + if (root == nullptr) + return; + + postorder(root->left, ans); + postorder(root->right, ans); + ans.push_back(root->val); + } +}; diff --git a/solutions/145. Binary Tree Postorder Traversal/145.java b/solutions/145. Binary Tree Postorder Traversal/145.java new file mode 100644 index 00000000000..9709ce1f584 --- /dev/null +++ b/solutions/145. Binary Tree Postorder Traversal/145.java @@ -0,0 +1,16 @@ +class Solution { + public List postorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + postorder(root, ans); + return ans; + } + + private void postorder(TreeNode root, List ans) { + if (root == null) + return; + + postorder(root.left, ans); + postorder(root.right, ans); + ans.add(root.val); + } +} diff --git a/solutions/145. Binary Tree Postorder Traversal/145.py b/solutions/145. Binary Tree Postorder Traversal/145.py new file mode 100644 index 00000000000..57b7b09fc07 --- /dev/null +++ b/solutions/145. Binary Tree Postorder Traversal/145.py @@ -0,0 +1,14 @@ +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + + def postorder(root: Optional[TreeNode]) -> None: + if not root: + return + + postorder(root.left) + postorder(root.right) + ans.append(root.val) + + postorder(root) + return ans diff --git a/solutions/1450. Number of Students Doing Homework at a Given Time/1450.cpp b/solutions/1450. Number of Students Doing Homework at a Given Time/1450.cpp new file mode 100644 index 00000000000..112e3629e00 --- /dev/null +++ b/solutions/1450. Number of Students Doing Homework at a Given Time/1450.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int busyStudent(vector& startTime, vector& endTime, int queryTime) { + const int n = startTime.size(); + int ans = 0; + + for (int i = 0; i < n; ++i) + if (startTime[i] <= queryTime && queryTime <= endTime[i]) + ++ans; + + return ans; + } +}; diff --git a/solutions/1451. Rearrange Words in a Sentence/1451.py b/solutions/1451. Rearrange Words in a Sentence/1451.py new file mode 100644 index 00000000000..368c9b69ec1 --- /dev/null +++ b/solutions/1451. Rearrange Words in a Sentence/1451.py @@ -0,0 +1,19 @@ +class Solution: + def arrangeWords(self, text: str) -> str: + words = text.split() + count = collections.defaultdict(list) + + for word in words: + count[len(word)].append(word.lower()) + + c2 = OrderedDict(sorted(count.items())) + + ans = [] + + for l in c2: + for word in c2[l]: + ans.append(word) + + ans[0] = ans[0].capitalize() + + return ' '.join(ans) diff --git a/solutions/1452. People Whose List of Favorite Companies Is Not a Subset of Another List/1452.py b/solutions/1452. People Whose List of Favorite Companies Is Not a Subset of Another List/1452.py new file mode 100644 index 00000000000..1e17ec2c9f3 --- /dev/null +++ b/solutions/1452. People Whose List of Favorite Companies Is Not a Subset of Another List/1452.py @@ -0,0 +1,18 @@ +class Solution: + def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]: + ans = [] + n = len(favoriteCompanies) + companies = [set(comp) for comp in favoriteCompanies] + + for i in range(n): + find = False + for j in range(n): + if i == j: + continue + if companies[i].issubset(companies[j]): + find = True + break + if not find: + ans.append(i) + + return ans diff --git a/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.cpp b/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.cpp new file mode 100644 index 00000000000..de24170d645 --- /dev/null +++ b/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.cpp @@ -0,0 +1,49 @@ +struct Point { + double x; + double y; + Point(double x, double y) : x(x), y(y) {} +}; + +class Solution { + public: + int numPoints(vector>& darts, int r) { + int ans = 1; + vector points = convertToPoints(darts); + + for (int i = 0; i < points.size(); ++i) + for (int j = i + 1; j < points.size(); ++j) + for (const Point& c : getCircles(points[i], points[j], r)) { + int count = 0; + for (const Point& point : points) + if (dist(c, point) - r <= kErr) + ++count; + ans = max(ans, count); + } + + return ans; + } + + private: + static constexpr double kErr = 1e-6; + + vector convertToPoints(const vector>& darts) { + vector points; + for (const vector& dart : darts) + points.emplace_back(dart[0], dart[1]); + return points; + } + + vector getCircles(const Point& p, const Point& q, int r) { + if (dist(p, q) - 2.0 * r > kErr) + return {}; + const Point m{(p.x + q.x) / 2, (p.y + q.y) / 2}; + const double distCM = sqrt(pow(r, 2) - pow(dist(p, q) / 2, 2)); + const double alpha = atan2(p.y - q.y, q.x - p.x); + return {Point{m.x - distCM * sin(alpha), m.y - distCM * cos(alpha)}, + Point{m.x + distCM * sin(alpha), m.y + distCM * cos(alpha)}}; + } + + double dist(const Point& p, const Point& q) { + return sqrt(pow(p.x - q.x, 2) + pow(p.y - q.y, 2)); + } +}; diff --git a/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.java b/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.java new file mode 100644 index 00000000000..2c2b6f1ac93 --- /dev/null +++ b/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.java @@ -0,0 +1,50 @@ +class Point { + public double x = 0; + public double y = 0; + public Point(double x, double y) { + this.x = x; + this.y = y; + } +} + +class Solution { + public int numPoints(int[][] darts, int r) { + int ans = 1; + List points = convertToPoints(darts); + + for (int i = 0; i < points.size(); ++i) + for (int j = i + 1; j < points.size(); ++j) + for (Point c : getCircles(points.get(i), points.get(j), r)) { + int count = 0; + for (Point point : points) + if (dist(c, point) - r <= kErr) + ++count; + ans = Math.max(ans, count); + } + + return ans; + } + + private static final double kErr = 1e-6; + + private List convertToPoints(int[][] darts) { + List points = new ArrayList<>(); + for (int[] dart : darts) + points.add(new Point(dart[0], dart[1])); + return points; + } + + private Point[] getCircles(Point p, Point q, int r) { + if (dist(p, q) - 2.0 * r > kErr) + return new Point[] {}; + Point m = new Point((p.x + q.x) / 2, (p.y + q.y) / 2); + final double distCM = Math.sqrt(Math.pow(r, 2) - Math.pow(dist(p, q) / 2, 2)); + final double alpha = Math.atan2(p.y - q.y, q.x - p.x); + return new Point[] {new Point(m.x - distCM * Math.sin(alpha), m.y - distCM * Math.cos(alpha)), + new Point(m.x + distCM * Math.sin(alpha), m.y + distCM * Math.cos(alpha))}; + } + + private double dist(Point p, Point q) { + return Math.sqrt(Math.pow(p.x - q.x, 2) + Math.pow(p.y - q.y, 2)); + } +} diff --git a/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.py b/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.py new file mode 100644 index 00000000000..a93dfa1c439 --- /dev/null +++ b/solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.py @@ -0,0 +1,34 @@ +class Point: + def __init__(self, x: float, y: float): + self.x = x + self.y = y + + +class Solution: + def numPoints(self, darts: List[List[int]], r: int) -> int: + kErr = 1e-6 + ans = 1 + points = [Point(x, y) for x, y in darts] + + def dist(p: Point, q: Point) -> float: + return ((p.x - q.x)**2 + (p.y - q.y)**2)**0.5 + + def getCircles(p: Point, q: Point) -> List[Point]: + if dist(p, q) - 2.0 * r > kErr: + return [] + m = Point((p.x + q.x) / 2, (p.y + q.y) / 2) + distCM = (r**2 - (dist(p, q) / 2)**2)**0.5 + alpha = math.atan2(p.y - q.y, q.x - p.x) + return [Point(m.x - distCM * math.sin(alpha), m.y - distCM * math.cos(alpha)), + Point(m.x + distCM * math.sin(alpha), m.y + distCM * math.cos(alpha))] + + for i in range(len(points)): + for j in range(i + 1, len(points)): + for c in getCircles(points[i], points[j]): + count = 0 + for point in points: + if dist(c, point) - r <= kErr: + count += 1 + ans = max(ans, count) + + return ans diff --git a/solutions/1454. Active Users/1454.sql b/solutions/1454. Active Users/1454.sql new file mode 100644 index 00000000000..7ce336d5b5e --- /dev/null +++ b/solutions/1454. Active Users/1454.sql @@ -0,0 +1,28 @@ +WITH + DistinctLogins AS ( + SELECT DISTINCT * FROM Logins + ), + RankedLogins AS ( + SELECT + *, + DENSE_RANK() OVER( + PARTITION BY id + ORDER BY login_date + ) AS `rank` + FROM DistinctLogins + ), + RankedLoginsWithGroupId AS ( + SELECT + *, + DATE_ADD(login_date, INTERVAL -`rank` DAY) AS group_id + FROM RankedLogins + ) +SELECT DISTINCT + id, + Accounts.name +FROM RankedLoginsWithGroupId +INNER JOIN Accounts + USING (id) +GROUP BY Accounts.id, RankedLoginsWithGroupId.group_id +HAVING COUNT(*) >= 5 +ORDER BY 1; diff --git a/solutions/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence/1455.py b/solutions/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence/1455.py new file mode 100644 index 00000000000..11d76e8582a --- /dev/null +++ b/solutions/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence/1455.py @@ -0,0 +1,9 @@ +class Solution: + def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: + words = sentence.split() + + for i, word in enumerate(words): + if word.startswith(searchWord): + return i + 1 + + return -1 diff --git a/solutions/1456. Maximum Number of Vowels in a Substring of Given Length/1456.py b/solutions/1456. Maximum Number of Vowels in a Substring of Given Length/1456.py new file mode 100644 index 00000000000..ff2425cab10 --- /dev/null +++ b/solutions/1456. Maximum Number of Vowels in a Substring of Given Length/1456.py @@ -0,0 +1,14 @@ +class Solution: + def maxVowels(self, s: str, k: int) -> int: + ans = 0 + mx = 0 + kVowels = 'aeiou' + + for i, c in enumerate(s): + if c in kVowels: + mx += 1 + if i >= k and s[i - k] in kVowels: + mx -= 1 + ans = max(ans, mx) + + return ans diff --git a/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.cpp b/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.cpp new file mode 100644 index 00000000000..16aa16b85f5 --- /dev/null +++ b/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int pseudoPalindromicPaths(TreeNode* root) { + int ans = 0; + dfs(root, 0, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int path, int& ans) { + if (root == nullptr) + return; + if (root->left == nullptr && root->right == nullptr) { + path ^= 1 << root->val; + if ((path & (path - 1)) == 0) + ++ans; + return; + } + + dfs(root->left, path ^ 1 << root->val, ans); + dfs(root->right, path ^ 1 << root->val, ans); + } +}; diff --git a/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.java b/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.java new file mode 100644 index 00000000000..f82c2a2fa66 --- /dev/null +++ b/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.java @@ -0,0 +1,22 @@ +class Solution { + public int pseudoPalindromicPaths(TreeNode root) { + dfs(root, 0); + return ans; + } + + private int ans = 0; + + private void dfs(TreeNode root, int path) { + if (root == null) + return; + if (root.left == null && root.right == null) { + path ^= 1 << root.val; + if ((path & (path - 1)) == 0) + ++ans; + return; + } + + dfs(root.left, path ^ 1 << root.val); + dfs(root.right, path ^ 1 << root.val); + } +} diff --git a/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.py b/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.py new file mode 100644 index 00000000000..41bf3c66c30 --- /dev/null +++ b/solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.py @@ -0,0 +1,19 @@ +class Solution: + def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def dfs(root: Optional[TreeNode], path: int) -> None: + nonlocal ans + if not root: + return + if not root.left and not root.right: + path ^= 1 << root.val + if path & (path - 1) == 0: + ans += 1 + return + + dfs(root.left, path ^ 1 << root.val) + dfs(root.right, path ^ 1 << root.val) + + dfs(root, 0) + return ans diff --git a/solutions/1458. Max Dot Product of Two Subsequences/1458.cpp b/solutions/1458. Max Dot Product of Two Subsequences/1458.cpp new file mode 100644 index 00000000000..d9a54c6c3d5 --- /dev/null +++ b/solutions/1458. Max Dot Product of Two Subsequences/1458.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxDotProduct(vector& nums1, vector& nums2) { + const int m = nums1.size(); + const int n = nums2.size(); + // dp[i][j] := the maximum dot product of the two subsequences nums[0..i) + // and nums2[0..j) + vector> dp(m + 1, vector(n + 1, INT_MIN)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + dp[i + 1][j + 1] = max({dp[i][j + 1], dp[i + 1][j], + max(0, dp[i][j]) + nums1[i] * nums2[j]}); + + return dp[m][n]; + } +}; diff --git a/solutions/1458. Max Dot Product of Two Subsequences/1458.java b/solutions/1458. Max Dot Product of Two Subsequences/1458.java new file mode 100644 index 00000000000..2106f6abae4 --- /dev/null +++ b/solutions/1458. Max Dot Product of Two Subsequences/1458.java @@ -0,0 +1,17 @@ +class Solution { + public int maxDotProduct(int[] nums1, int[] nums2) { + final int m = nums1.length; + final int n = nums2.length; + // dp[i][j] := the maximum dot product of the two subsequences nums[0..i) + // and nums2[0..j) + int[][] dp = new int[m + 1][n + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MIN_VALUE)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + dp[i + 1][j + 1] = Math.max(Math.max(dp[i][j + 1], dp[i + 1][j]), + Math.max(0, dp[i][j]) + nums1[i] * nums2[j]); + + return dp[m][n]; + } +} diff --git a/solutions/1458. Max Dot Product of Two Subsequences/1458.py b/solutions/1458. Max Dot Product of Two Subsequences/1458.py new file mode 100644 index 00000000000..9e68679227f --- /dev/null +++ b/solutions/1458. Max Dot Product of Two Subsequences/1458.py @@ -0,0 +1,14 @@ +class Solution: + def maxDotProduct(self, A: List[int], B: List[int]) -> int: + m = len(A) + n = len(B) + # dp[i][j] := the maximum dot product of the two subsequences nums[0..i) + # and nums2[0..j) + dp = [[-math.inf] * (n + 1) for _ in range(m + 1)] + + for i in range(m): + for j in range(n): + dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j], + max(0, dp[i][j]) + A[i] * B[j]) + + return dp[m][n] diff --git a/solutions/1459. Rectangles Area/1459.sql b/solutions/1459. Rectangles Area/1459.sql new file mode 100644 index 00000000000..e0f6eba4a28 --- /dev/null +++ b/solutions/1459. Rectangles Area/1459.sql @@ -0,0 +1,10 @@ +SELECT + P1.id AS p1, + P2.id AS p2, + ABS(p1.x_value - p2.x_value) * ABS(p1.y_value - p2.y_value) AS area +FROM Points AS P1, Points AS P2 +WHERE + P1.id < P2.id + AND P1.x_value != P2.x_value + AND P1.y_value != P2.y_value +ORDER BY area DESC, p1, p2; diff --git a/solutions/146. LRU Cache/146-2.cpp b/solutions/146. LRU Cache/146-2.cpp new file mode 100644 index 00000000000..6da31bdb152 --- /dev/null +++ b/solutions/146. LRU Cache/146-2.cpp @@ -0,0 +1,48 @@ +struct Node { + int key; + int value; + Node(int key, int value) : key(key), value(value) {} +}; + +class LRUCache { + public: + LRUCache(int capacity) : capacity(capacity) {} + + int get(int key) { + const auto it = keyToIterator.find(key); + if (it == keyToIterator.cend()) + return -1; + + const auto& listIt = it->second; + // Move it to the front. + cache.splice(cache.begin(), cache, listIt); + return listIt->value; + } + + void put(int key, int value) { + // There's no capacity issue, so just update the value. + if (const auto it = keyToIterator.find(key); it != keyToIterator.cend()) { + const auto& listIt = it->second; + // Move it to the front. + cache.splice(cache.begin(), cache, listIt); + listIt->value = value; + return; + } + + // Check the capacity. + if (cache.size() == capacity) { + const Node& lastNode = cache.back(); + // That's why we store `key` in `Node`. + keyToIterator.erase(lastNode.key); + cache.pop_back(); + } + + cache.emplace_front(key, value); + keyToIterator[key] = cache.begin(); + } + + private: + const int capacity; + list cache; + unordered_map::iterator> keyToIterator; +}; diff --git a/solutions/146. LRU Cache/146.cpp b/solutions/146. LRU Cache/146.cpp new file mode 100644 index 00000000000..d4b26c8588b --- /dev/null +++ b/solutions/146. LRU Cache/146.cpp @@ -0,0 +1,64 @@ +struct Node { + int key; + int value; + shared_ptr prev; + shared_ptr next; + Node(int key, int value) : key(key), value(value) {} +}; + +class LRUCache { + public: + LRUCache(int capacity) : capacity(capacity) { + join(head, tail); + } + + int get(int key) { + const auto it = keyToNode.find(key); + if (it == keyToNode.cend()) + return -1; + + shared_ptr node = it->second; + remove(node); + moveToHead(node); + return node->value; + } + + void put(int key, int value) { + if (const auto it = keyToNode.find(key); it != keyToNode.cend()) { + shared_ptr node = it->second; + node->value = value; + remove(node); + moveToHead(node); + return; + } + + if (keyToNode.size() == capacity) { + shared_ptr lastNode = tail->prev; + keyToNode.erase(lastNode->key); + remove(lastNode); + } + + moveToHead(make_shared(key, value)); + keyToNode[key] = head->next; + } + + private: + const int capacity; + unordered_map> keyToNode; + shared_ptr head = make_shared(-1, -1); + shared_ptr tail = make_shared(-1, -1); + + void join(shared_ptr node1, shared_ptr node2) { + node1->next = node2; + node2->prev = node1; + } + + void moveToHead(shared_ptr node) { + join(node, head->next); + join(head, node); + } + + void remove(shared_ptr node) { + join(node->prev, node->next); + } +}; diff --git a/solutions/146. LRU Cache/146.java b/solutions/146. LRU Cache/146.java new file mode 100644 index 00000000000..f0d529e8605 --- /dev/null +++ b/solutions/146. LRU Cache/146.java @@ -0,0 +1,46 @@ +class Node { + public int key; + public int value; + public Node(int key, int value) { + this.key = key; + this.value = value; + } +} + +class LRUCache { + public LRUCache(int capacity) { + this.capacity = capacity; + } + + public int get(int key) { + if (!keyToNode.containsKey(key)) + return -1; + + Node node = keyToNode.get(key); + cache.remove(node); + cache.add(node); + return node.value; + } + + public void put(int key, int value) { + if (keyToNode.containsKey(key)) { + keyToNode.get(key).value = value; + get(key); + return; + } + + if (cache.size() == capacity) { + Node lastNode = cache.iterator().next(); + cache.remove(lastNode); + keyToNode.remove(lastNode.key); + } + + Node node = new Node(key, value); + cache.add(node); + keyToNode.put(key, node); + } + + private int capacity; + private Set cache = new LinkedHashSet<>(); + private Map keyToNode = new HashMap<>(); +} diff --git a/solutions/146. LRU Cache/146.py b/solutions/146. LRU Cache/146.py new file mode 100644 index 00000000000..6ac51294899 --- /dev/null +++ b/solutions/146. LRU Cache/146.py @@ -0,0 +1,51 @@ +class Node: + def __init__(self, key: int, value: int): + self.key = key + self.value = value + self.prev = None + self.next = None + + +class LRUCache: + def __init__(self, capacity: int): + self.capacity = capacity + self.keyToNode = {} + self.head = Node(-1, -1) + self.tail = Node(-1, -1) + self.join(self.head, self.tail) + + def get(self, key: int) -> int: + if key not in self.keyToNode: + return -1 + + node = self.keyToNode[key] + self.remove(node) + self.moveToHead(node) + return node.value + + def put(self, key: int, value: int) -> None: + if key in self.keyToNode: + node = self.keyToNode[key] + node.value = value + self.remove(node) + self.moveToHead(node) + return + + if len(self.keyToNode) == self.capacity: + lastNode = self.tail.prev + del self.keyToNode[lastNode.key] + self.remove(lastNode) + + self.moveToHead(Node(key, value)) + self.keyToNode[key] = self.head.next + + def join(self, node1: Node, node2: Node): + node1.next = node2 + node2.prev = node1 + + def moveToHead(self, node: Node): + self.join(node, self.head.next) + self.join(self.head, node) + + def remove(self, node: Node): + self.join(node.prev, node.next) diff --git a/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.cpp b/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.cpp new file mode 100644 index 00000000000..2c9ae8831c7 --- /dev/null +++ b/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + bool canBeEqual(vector& target, vector& arr) { + return unordered_multiset(arr.begin(), arr.end()) == + unordered_multiset(target.begin(), target.end()); + } +}; diff --git a/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.java b/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.java new file mode 100644 index 00000000000..5319e52e236 --- /dev/null +++ b/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.java @@ -0,0 +1,9 @@ +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + return Arrays.stream(arr) + .boxed() + .collect(Collectors.groupingBy(Integer::intValue, Collectors.counting())) + .equals(Arrays.stream(target).boxed().collect( + Collectors.groupingBy(Integer::intValue, Collectors.counting()))); + } +} diff --git a/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.py b/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.py new file mode 100644 index 00000000000..685c4bdf6da --- /dev/null +++ b/solutions/1460. Make Two Arrays Equal by Reversing Subarrays/1460.py @@ -0,0 +1,3 @@ +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return collections.Counter(arr) == collections.Counter(target) diff --git a/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.cpp b/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.cpp new file mode 100644 index 00000000000..65b42acde64 --- /dev/null +++ b/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool hasAllCodes(string s, int k) { + const int n = 1 << k; + if (s.length() < n) + return false; + + // used[i] := true if i is a substring of `s` + vector used(n); + + int window = k == 1 ? 0 : stoi(s.substr(0, k - 1), nullptr, 2); + for (int i = k - 1; i < s.length(); ++i) { + // Include the s[i]. + window = (window << 1) + (s[i] - '0'); + // Discard the s[i - k]. + window &= n - 1; + used[window] = true; + } + + return ranges::all_of(used, [](bool u) { return u; }); + } +}; diff --git a/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.java b/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.java new file mode 100644 index 00000000000..9694a403591 --- /dev/null +++ b/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.java @@ -0,0 +1,21 @@ +class Solution { + public boolean hasAllCodes(String s, int k) { + final int n = 1 << k; + if (s.length() < n) + return false; + + // used[i] := true if i is a substring of `s` + boolean[] used = new boolean[n]; + + int window = k == 1 ? 0 : Integer.parseInt(s.substring(0, k - 1), 2); + for (int i = k - 1; i < s.length(); ++i) { + // Include the s[i]. + window = (window << 1) + (s.charAt(i) - '0'); + // Discard the s[i - k]. + window &= n - 1; + used[window] = true; + } + + return IntStream.range(0, used.length).mapToObj(i -> used[i]).allMatch(u -> u); + } +} diff --git a/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.py b/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.py new file mode 100644 index 00000000000..6f138b50c63 --- /dev/null +++ b/solutions/1461. Check If a String Contains All Binary Codes of Size K/1461.py @@ -0,0 +1,18 @@ +class Solution: + def hasAllCodes(self, s: str, k: int) -> bool: + n = 1 << k + if len(s) < n: + return False + + # used[i] := True if i is a substring of `s` + used = [0] * n + + windowStr = 0 if k == 1 else int(s[0:k - 1], 2) + for i in range(k - 1, len(s)): + # Include the s[i]. + windowStr = (windowStr << 1) + int(s[i]) + # Discard the s[i - k]. + windowStr &= n - 1 + used[windowStr] = True + + return all(u for u in used) diff --git a/solutions/1462. Course Schedule IV/1462-2.cpp b/solutions/1462. Course Schedule IV/1462-2.cpp new file mode 100644 index 00000000000..628ef7d2d69 --- /dev/null +++ b/solutions/1462. Course Schedule IV/1462-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector checkIfPrerequisite(int numCourses, + vector>& prerequisites, + vector>& queries) { + vector ans; + // isPrerequisite[i][j] := true if course i is a prerequisite of course j + vector> isPrerequisite(numCourses, vector(numCourses)); + + for (const vector& prerequisite : prerequisites) { + const int u = prerequisite[0]; + const int v = prerequisite[1]; + isPrerequisite[u][v] = true; + } + + for (int k = 0; k < numCourses; ++k) + for (int i = 0; i < numCourses; ++i) + for (int j = 0; j < numCourses; ++j) + isPrerequisite[i][j] = isPrerequisite[i][j] || + (isPrerequisite[i][k] && isPrerequisite[k][j]); + + for (const vector& query : queries) { + const int u = query[0]; + const int v = query[1]; + ans.push_back(isPrerequisite[u][v]); + } + + return ans; + } +}; diff --git a/solutions/1462. Course Schedule IV/1462-2.java b/solutions/1462. Course Schedule IV/1462-2.java new file mode 100644 index 00000000000..303a56f624e --- /dev/null +++ b/solutions/1462. Course Schedule IV/1462-2.java @@ -0,0 +1,27 @@ +class Solution { + public List checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { + List ans = new ArrayList<>(); + // isPrerequisite[i][j] := true if course i is a prerequisite of course j + boolean[][] isPrerequisite = new boolean[numCourses][numCourses]; + + for (int[] prerequisite : prerequisites) { + final int u = prerequisite[0]; + final int v = prerequisite[1]; + isPrerequisite[u][v] = true; + } + + for (int k = 0; k < numCourses; ++k) + for (int i = 0; i < numCourses; ++i) + for (int j = 0; j < numCourses; ++j) + isPrerequisite[i][j] = + isPrerequisite[i][j] || (isPrerequisite[i][k] && isPrerequisite[k][j]); + + for (int[] query : queries) { + final int u = query[0]; + final int v = query[1]; + ans.add(isPrerequisite[u][v]); + } + + return ans; + } +} diff --git a/solutions/1462. Course Schedule IV/1462-2.py b/solutions/1462. Course Schedule IV/1462-2.py new file mode 100644 index 00000000000..96f68b79a5e --- /dev/null +++ b/solutions/1462. Course Schedule IV/1462-2.py @@ -0,0 +1,16 @@ +class Solution: + def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: + ans = [] + # isPrerequisite[i][j] := True if course i is a prerequisite of course j. + isPrerequisite = [[False] * numCourses for _ in range(numCourses)] + + for u, v in prerequisites: + isPrerequisite[u][v] = True + + for k in range(numCourses): + for i in range(numCourses): + for j in range(numCourses): + isPrerequisite[i][j] = isPrerequisite[i][j] or \ + (isPrerequisite[i][k] and isPrerequisite[k][j]) + + return [isPrerequisite[u][v] for u, v in queries] diff --git a/solutions/1462. Course Schedule IV/1462.cpp b/solutions/1462. Course Schedule IV/1462.cpp new file mode 100644 index 00000000000..1a870db8296 --- /dev/null +++ b/solutions/1462. Course Schedule IV/1462.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector checkIfPrerequisite(int numCourses, + vector>& prerequisites, + vector>& queries) { + vector ans; + vector> graph(numCourses); + // isPrerequisite[i][j] := true if course i is a prerequisite of course j + vector> isPrerequisite(numCourses, vector(numCourses)); + + for (const vector& prerequisite : prerequisites) { + const int u = prerequisite[0]; + const int v = prerequisite[1]; + graph[u].push_back(v); + } + + // DFS from every course. + for (int i = 0; i < numCourses; ++i) + dfs(graph, i, isPrerequisite[i]); + + for (const vector& query : queries) { + const int u = query[0]; + const int v = query[1]; + ans.push_back(isPrerequisite[u][v]); + } + + return ans; + } + + void dfs(const vector>& graph, int u, vector& used) { + for (const int v : graph[u]) { + if (used[v]) + continue; + used[v] = true; + dfs(graph, v, used); + } + } +}; diff --git a/solutions/1462. Course Schedule IV/1462.java b/solutions/1462. Course Schedule IV/1462.java new file mode 100644 index 00000000000..cac577a3e30 --- /dev/null +++ b/solutions/1462. Course Schedule IV/1462.java @@ -0,0 +1,77 @@ +class Solution { + public boolean[] checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { + List ans = new ArrayList<>(); + List[] graph = new List[numCourses]; + // isPrerequisite[i][j] := true if course i is a prerequisite of course j + boolean[][] isPrerequisite = new boolean[numCourses][numCourses]; + + for (int i = 0; i < numCourses; ++i) + graph[i] = new ArrayList<>(); + + for (int[] prerequisite : prerequisites) { + final int u = prerequisite[0]; + final int v = prerequisite[1]; + graph[u].add(v); + } + + // DFS from every course. + for (int i = 0; i < numCourses; ++i) + dfs(graph, i, isPrerequisite[i]); + + for (int[] query : queries) { + final int u = query[0]; + final int v = query[1]; + ans.add(isPrerequisite[u][v]); + } + + return ans; + } + + public void dfs(const vector> &graph, int u, boolean[] used) { + for (final int v : graph[u]) { + if (used[v]) + continue; + used[v] = true; + dfs(graph, v, used); + } + } +} +class Solution { + public List checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { + List ans = new ArrayList<>(); + List[] graph = new List[numCourses]; + + for (int i = 0; i < numCourses; ++i) + graph[i] = new ArrayList<>(); + + for (int[] prerequisite : prerequisites) { + final int u = prerequisite[0]; + final int v = prerequisite[1]; + graph[u].add(v); + } + + // isPrerequisite[i][j] := true if course i is a prerequisite of course j + boolean[][] isPrerequisite = new boolean[numCourses][numCourses]; + + // DFS from every course. + for (int i = 0; i < numCourses; ++i) + dfs(graph, i, isPrerequisite[i]); + + for (int[] query : queries) { + final int u = query[0]; + final int v = query[1]; + ans.add(isPrerequisite[u][v]); + } + + return ans; + } + + public void dfs(List[] graph, int u, boolean[] used) { + for (final int v : graph[u]) { + if (used[v]) + continue; + used[v] = true; + dfs(graph, v, used); + } + } +} diff --git a/solutions/1462. Course Schedule IV/1462.py b/solutions/1462. Course Schedule IV/1462.py new file mode 100644 index 00000000000..758b5ca65b9 --- /dev/null +++ b/solutions/1462. Course Schedule IV/1462.py @@ -0,0 +1,21 @@ +class Solution: + def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: + graph = [[] for _ in range(numCourses)] + # isPrerequisite[i][j] := True if course i is a prerequisite of course j. + isPrerequisite = [[False] * numCourses for _ in range(numCourses)] + + for u, v in prerequisites: + graph[u].append(v) + + # DFS from every course. + for i in range(numCourses): + self._dfs(graph, i, isPrerequisite[i]) + + return [isPrerequisite[u][v] for u, v in queries] + + def _dfs(self, graph: List[List[int]], u: int, used: List[bool]) -> None: + for v in graph[u]: + if used[v]: + continue + used[v] = True + self._dfs(graph, v, used) diff --git a/solutions/1463. Cherry Pickup II/1463-2.cpp b/solutions/1463. Cherry Pickup II/1463-2.cpp new file mode 100644 index 00000000000..6f96b96e2c2 --- /dev/null +++ b/solutions/1463. Cherry Pickup II/1463-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int cherryPickup(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + // dp[x][y1][y2] := the maximum cherries we can collect, where the robot #1 + // is on (x, y1) and the robot #2 is on (x, y2) + vector>> dp(m + 1, + vector>(n, vector(n))); + + for (int x = m - 1; x >= 0; --x) + for (int y1 = 0; y1 < n; ++y1) + for (int y2 = 0; y2 < n; ++y2) { + const int currRow = grid[x][y1] + (y1 != y2) * grid[x][y2]; + for (int d1 = max(0, y1 - 1); d1 < min(n, y1 + 2); ++d1) + for (int d2 = max(0, y2 - 1); d2 < min(n, y2 + 2); ++d2) + dp[x][y1][y2] = max(dp[x][y1][y2], currRow + dp[x + 1][d1][d2]); + } + + return dp[0][0][n - 1]; + } +}; diff --git a/solutions/1463. Cherry Pickup II/1463-2.java b/solutions/1463. Cherry Pickup II/1463-2.java new file mode 100644 index 00000000000..54a798dc665 --- /dev/null +++ b/solutions/1463. Cherry Pickup II/1463-2.java @@ -0,0 +1,20 @@ +class Solution { + public int cherryPickup(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + // dp[x][y1][y2] := the maximum cherries we can collect, where the robot #1 + // is on (x, y1) and the robot #2 is on (x, y2) + int[][][] dp = new int[m + 1][n][n]; + + for (int x = m - 1; x >= 0; --x) + for (int y1 = 0; y1 < n; ++y1) + for (int y2 = 0; y2 < n; ++y2) { + final int currRow = grid[x][y1] + (y1 == y2 ? 0 : 1) * grid[x][y2]; + for (int d1 = Math.max(0, y1 - 1); d1 < Math.min(n, y1 + 2); ++d1) + for (int d2 = Math.max(0, y2 - 1); d2 < Math.min(n, y2 + 2); ++d2) + dp[x][y1][y2] = Math.max(dp[x][y1][y2], currRow + dp[x + 1][d1][d2]); + } + + return dp[0][0][n - 1]; + } +} diff --git a/solutions/1463. Cherry Pickup II/1463.cpp b/solutions/1463. Cherry Pickup II/1463.cpp new file mode 100644 index 00000000000..83293c6c5b1 --- /dev/null +++ b/solutions/1463. Cherry Pickup II/1463.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int cherryPickup(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector>> mem(m, + vector>(n, vector(n, -1))); + return cherryPick(grid, 0, 0, n - 1, mem); + } + + private: + // Returns the maximum cherries we can collect, where the robot #1 is on + // (x, y1) and the robot #2 is on (x, y2). + int cherryPick(const vector>& grid, int x, int y1, int y2, + vector>>& mem) { + if (x == grid.size()) + return 0; + if (y1 < 0 || y1 == grid[0].size() || y2 < 0 || y2 == grid[0].size()) + return 0; + if (mem[x][y1][y2] != -1) + return mem[x][y1][y2]; + + const int currRow = grid[x][y1] + (y1 == y2 ? 0 : 1) * grid[x][y2]; + + for (int d1 = -1; d1 <= 1; ++d1) + for (int d2 = -1; d2 <= 1; ++d2) + mem[x][y1][y2] = + max(mem[x][y1][y2], + currRow + cherryPick(grid, x + 1, y1 + d1, y2 + d2, mem)); + + return mem[x][y1][y2]; + } +}; diff --git a/solutions/1463. Cherry Pickup II/1463.java b/solutions/1463. Cherry Pickup II/1463.java new file mode 100644 index 00000000000..1d132b70361 --- /dev/null +++ b/solutions/1463. Cherry Pickup II/1463.java @@ -0,0 +1,32 @@ +class Solution { + public int cherryPickup(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[][][] mem = new int[m][n][n]; + + for (int[][] A : mem) + Arrays.stream(A).forEach(B -> Arrays.fill(B, -1)); + + return cherryPick(grid, 0, 0, n - 1, mem); + } + + // Returns the maximum cherries we can collect, where robot #1 is on (x, y1) + // and robot #2 is on (x, y2). + private int cherryPick(int[][] grid, int x, int y1, int y2, int[][][] mem) { + if (x == grid.length) + return 0; + if (y1 < 0 || y1 == grid[0].length || y2 < 0 || y2 == grid[0].length) + return 0; + if (mem[x][y1][y2] != -1) + return mem[x][y1][y2]; + + final int currRow = grid[x][y1] + (y1 == y2 ? 0 : grid[x][y2]); + + for (int d1 = -1; d1 <= 1; ++d1) + for (int d2 = -1; d2 <= 1; ++d2) + mem[x][y1][y2] = + Math.max(mem[x][y1][y2], currRow + cherryPick(grid, x + 1, y1 + d1, y2 + d2, mem)); + + return mem[x][y1][y2]; + } +} diff --git a/solutions/1464. Maximum Product of Two Elements in an Array/1464-2.cpp b/solutions/1464. Maximum Product of Two Elements in an Array/1464-2.cpp new file mode 100644 index 00000000000..567d199f18c --- /dev/null +++ b/solutions/1464. Maximum Product of Two Elements in an Array/1464-2.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int maxProduct(vector& nums) { + const auto maxIt1 = ranges::max_element(nums); + *maxIt1 *= -1; + const int max2 = ranges::max(nums); + *maxIt1 *= -1; + return (*maxIt1 - 1) * (max2 - 1); + } +}; diff --git a/solutions/1464. Maximum Product of Two Elements in an Array/1464.cpp b/solutions/1464. Maximum Product of Two Elements in an Array/1464.cpp new file mode 100644 index 00000000000..2afdaa8cb72 --- /dev/null +++ b/solutions/1464. Maximum Product of Two Elements in an Array/1464.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxProduct(vector& nums) { + int max1 = 0; + int max2 = 0; + + for (const int num : nums) + if (num > max1) + max2 = std::exchange(max1, num); + else if (num > max2) + max2 = num; + + return (max1 - 1) * (max2 - 1); + } +}; diff --git a/solutions/1464. Maximum Product of Two Elements in an Array/1464.java b/solutions/1464. Maximum Product of Two Elements in an Array/1464.java new file mode 100644 index 00000000000..e76b8821e48 --- /dev/null +++ b/solutions/1464. Maximum Product of Two Elements in an Array/1464.java @@ -0,0 +1,16 @@ +class Solution { + public int maxProduct(int[] nums) { + int max1 = 0; + int max2 = 0; + + for (final int num : nums) + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + + return (max1 - 1) * (max2 - 1); + } +} diff --git a/solutions/1464. Maximum Product of Two Elements in an Array/1464.py b/solutions/1464. Maximum Product of Two Elements in an Array/1464.py new file mode 100644 index 00000000000..a0760522b4f --- /dev/null +++ b/solutions/1464. Maximum Product of Two Elements in an Array/1464.py @@ -0,0 +1,12 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + max1 = 0 + max2 = 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/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.cpp b/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.cpp new file mode 100644 index 00000000000..b6eb00e304b --- /dev/null +++ b/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maxArea(int h, int w, vector& horizontalCuts, + vector& verticalCuts) { + constexpr int kMod = 1'000'000'007; + ranges::sort(horizontalCuts); + ranges::sort(verticalCuts); + + // the maximum gap of each direction + int maxGapX = max(verticalCuts[0], w - verticalCuts.back()); + int maxGapY = max(horizontalCuts[0], h - horizontalCuts.back()); + + for (int i = 1; i < verticalCuts.size(); ++i) + maxGapX = max(maxGapX, verticalCuts[i] - verticalCuts[i - 1]); + + for (int i = 1; i < horizontalCuts.size(); ++i) + maxGapY = max(maxGapY, horizontalCuts[i] - horizontalCuts[i - 1]); + + return static_cast(maxGapX) * maxGapY % kMod; + } +}; diff --git a/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.java b/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.java new file mode 100644 index 00000000000..b0da9b9d41d --- /dev/null +++ b/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.java @@ -0,0 +1,19 @@ +class Solution { + public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { + final int kMod = 1_000_000_007; + Arrays.sort(horizontalCuts); + Arrays.sort(verticalCuts); + + // the maximum gap of each direction + int maxGapX = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length - 1]); + int maxGapY = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length - 1]); + + for (int i = 1; i < verticalCuts.length; ++i) + maxGapX = Math.max(maxGapX, verticalCuts[i] - verticalCuts[i - 1]); + + for (int i = 1; i < horizontalCuts.length; ++i) + maxGapY = Math.max(maxGapY, horizontalCuts[i] - horizontalCuts[i - 1]); + + return (int) ((long) maxGapX * maxGapY % kMod); + } +} diff --git a/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.py b/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.py new file mode 100644 index 00000000000..b7149ec18be --- /dev/null +++ b/solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.py @@ -0,0 +1,9 @@ +class Solution: + def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: + kMod = 1_000_000_007 + # the maximum gap of each direction + maxGapX = max(b - a + for a, b in itertools.pairwise([0] + sorted(horizontalCuts) + [h])) + maxGapY = max(b - a + for a, b in itertools.pairwise([0] + sorted(verticalCuts) + [w])) + return maxGapX * maxGapY % kMod diff --git a/solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.cpp b/solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.cpp new file mode 100644 index 00000000000..ace88f6032a --- /dev/null +++ b/solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int minReorder(int n, vector>& connections) { + vector> graph(n); + + for (const vector& connection : connections) { + const int u = connection[0]; + const int v = connection[1]; + graph[u].push_back(v); + graph[v].push_back(-u); // - := u -> v + } + + return dfs(graph, 0, -1); + } + + private: + int dfs(const vector>& graph, int u, int parent) { + int change = 0; + + for (const int v : graph[u]) { + if (abs(v) == parent) + continue; + if (v > 0) + ++change; + change += dfs(graph, abs(v), u); + } + + return change; + } +}; diff --git a/solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.java b/solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.java new file mode 100644 index 00000000000..ef284d6df8d --- /dev/null +++ b/solutions/1466. Reorder Routes to Make All Paths Lead to the City Zero/1466.java @@ -0,0 +1,31 @@ +class Solution { + public int minReorder(int n, int[][] connections) { + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] connection : connections) { + final int u = connection[0]; + final int v = connection[1]; + graph[u].add(v); + graph[v].add(-u); // - := u -> v + } + + return dfs(graph, 0, -1); + } + + private int dfs(List[] graph, int u, int parent) { + int change = 0; + + for (final int v : graph[u]) { + if (Math.abs(v) == parent) + continue; + if (v > 0) + ++change; + change += dfs(graph, Math.abs(v), u); + } + + return change; + } +} diff --git a/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.cpp b/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.cpp new file mode 100644 index 00000000000..8022e70899e --- /dev/null +++ b/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.cpp @@ -0,0 +1,38 @@ +enum class BoxCase { kEqualBalls, kEqualDistantBalls }; + +class Solution { + public: + double getProbability(vector& balls) { + const int n = accumulate(balls.begin(), balls.end(), 0) / 2; + return cases(balls, 0, 0, 0, 0, 0, n, BoxCase::kEqualDistantBalls) / + cases(balls, 0, 0, 0, 0, 0, n, BoxCase::kEqualBalls); + } + + private: + const vector fact{1, 1, 2, 6, 24, 120, 720}; + + // Assume we have two boxes A and B. + double cases(const vector& balls, int i, int ballsCountA, + int ballsCountB, int colorsCountA, int colorsCountB, int n, + BoxCase boxCase) { + if (ballsCountA > n || ballsCountB > n) + return 0; + if (i == balls.size()) + return boxCase == BoxCase::kEqualBalls ? 1 : colorsCountA == colorsCountB; + + double ans = 0; + + // balls taken from A for `balls[i]` + for (int ballsTakenA = 0; ballsTakenA <= balls[i]; ++ballsTakenA) { + const int ballsTakenB = balls[i] - ballsTakenA; + const int newcolorsCountA = colorsCountA + (ballsTakenA > 0); + const int newcolorsCountB = colorsCountB + (ballsTakenB > 0); + ans += cases(balls, i + 1, ballsCountA + ballsTakenA, + ballsCountB + ballsTakenB, newcolorsCountA, newcolorsCountB, + n, boxCase) / + (fact[ballsTakenA] * fact[ballsTakenB]); + } + + return ans; + } +}; diff --git a/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.java b/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.java new file mode 100644 index 00000000000..39db6b5b4a8 --- /dev/null +++ b/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.java @@ -0,0 +1,34 @@ +enum BoxCase { kEqualBalls, kEqualDistantBalls } + +class Solution { + public double getProbability(int[] balls) { + final int n = Arrays.stream(balls).sum() / 2; + return cases(balls, 0, 0, 0, 0, 0, n, BoxCase.kEqualDistantBalls) / + cases(balls, 0, 0, 0, 0, 0, n, BoxCase.kEqualBalls); + } + + private int[] fact = {1, 1, 2, 6, 24, 120, 720}; + + // Assume we have two boxes A and B. + double cases(int[] balls, int i, int ballsCountA, int ballsCountB, int colorsCountA, + int colorsCountB, int n, BoxCase boxCase) { + if (ballsCountA > n || ballsCountB > n) + return 0; + if (i == balls.length) + return boxCase == BoxCase.kEqualBalls ? 1 : (colorsCountA == colorsCountB ? 1 : 0); + + double ans = 0; + + // balls taken from A for `balls[i]` + for (int ballsTakenA = 0; ballsTakenA <= balls[i]; ++ballsTakenA) { + final int ballsTakenB = balls[i] - ballsTakenA; + final int newcolorsCountA = colorsCountA + (ballsTakenA > 0 ? 1 : 0); + final int newcolorsCountB = colorsCountB + (ballsTakenB > 0 ? 1 : 0); + ans += cases(balls, i + 1, ballsCountA + ballsTakenA, ballsCountB + ballsTakenB, + newcolorsCountA, newcolorsCountB, n, boxCase) / + (fact[ballsTakenA] * fact[ballsTakenB]); + } + + return ans; + } +} diff --git a/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.py b/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.py new file mode 100644 index 00000000000..acae68a0983 --- /dev/null +++ b/solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.py @@ -0,0 +1,35 @@ +from enum import Enum + + +class BoxCase(Enum): + kEqualDistantBalls = 0 + kEqualBalls = 1 + + +class Solution: + def getProbability(self, balls: List[int]) -> float: + n = sum(balls) // 2 + fact = [1, 1, 2, 6, 24, 120, 720] + + def cases(i: int, ballsCountA: int, ballsCountB: int, + colorsCountA: int, colorsCountB, boxCase: BoxCase) -> float: + if ballsCountA > n or ballsCountB > n: + return 0 + if i == len(balls): + return 1 if boxCase == BoxCase.kEqualBalls else colorsCountA == colorsCountB + + ans = 0.0 + + # balls taken from A for `balls[i]` + for ballsTakenA in range(balls[i] + 1): + ballsTakenB = balls[i] - ballsTakenA + newcolorsCountA = colorsCountA + (ballsTakenA > 0) + newcolorsCountB = colorsCountB + (ballsTakenB > 0) + ans += cases(i + 1, ballsCountA + ballsTakenA, ballsCountB + ballsTakenB, + newcolorsCountA, newcolorsCountB, boxCase) / \ + (fact[ballsTakenA] * fact[ballsTakenB]) + + return ans + + return cases(0, 0, 0, 0, 0, BoxCase.kEqualDistantBalls) / \ + cases(0, 0, 0, 0, 0, BoxCase.kEqualBalls) diff --git a/solutions/1468. Calculate Salaries/1468.sql b/solutions/1468. Calculate Salaries/1468.sql new file mode 100644 index 00000000000..a793b7c2b4e --- /dev/null +++ b/solutions/1468. Calculate Salaries/1468.sql @@ -0,0 +1,19 @@ +WITH + SalariesWithMaxSalary AS ( + SELECT + *, + MAX(salary) OVER(PARTITION BY company_id) AS max_salary + FROM Salaries + ) +SELECT + company_id, + employee_id, + employee_name, + ROUND( + CASE + WHEN max_salary < 1000 THEN salary + WHEN max_salary BETWEEN 1000 AND 10000 THEN salary * 0.76 + ELSE salary * 0.51 + END + ) AS salary +FROM SalariesWithMaxSalary; diff --git a/solutions/1469. Find All The Lonely Nodes/1469.cpp b/solutions/1469. Find All The Lonely Nodes/1469.cpp new file mode 100644 index 00000000000..c016a0ba3f0 --- /dev/null +++ b/solutions/1469. Find All The Lonely Nodes/1469.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector getLonelyNodes(TreeNode* root) { + vector ans; + + dfs(root, false, ans); + + return ans; + } + + private: + void dfs(TreeNode* root, bool isLonely, vector& ans) { + if (root == nullptr) + return; + if (isLonely) + ans.push_back(root->val); + + dfs(root->left, root->right == nullptr, ans); + dfs(root->right, root->left == nullptr, ans); + } +}; diff --git a/solutions/1469. Find All The Lonely Nodes/1469.java b/solutions/1469. Find All The Lonely Nodes/1469.java new file mode 100644 index 00000000000..afbb55b95e9 --- /dev/null +++ b/solutions/1469. Find All The Lonely Nodes/1469.java @@ -0,0 +1,19 @@ +class Solution { + public List getLonelyNodes(TreeNode root) { + List ans = new ArrayList<>(); + + dfs(root, false, ans); + + return ans; + } + + private void dfs(TreeNode root, boolean isLonely, List ans) { + if (root == null) + return; + if (isLonely) + ans.add(root.val); + + dfs(root.left, root.right == null, ans); + dfs(root.right, root.left == null, ans); + } +} diff --git a/solutions/147. Insertion Sort List/147.cpp b/solutions/147. Insertion Sort List/147.cpp new file mode 100644 index 00000000000..17017f0dca3 --- /dev/null +++ b/solutions/147. Insertion Sort List/147.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + ListNode* insertionSortList(ListNode* head) { + ListNode dummy(0); + ListNode* prev = &dummy; // the last and thus largest of the sorted list + + while (head != nullptr) { // the current inserting node + ListNode* next = head->next; // Cache the next inserting node. + if (prev->val >= head->val) + prev = &dummy; // Move `prev` to the front. + while (prev->next && prev->next->val < head->val) + prev = prev->next; + head->next = prev->next; + prev->next = head; + head = next; // Update the current inserting node. + } + + return dummy.next; + } +}; diff --git a/solutions/147. Insertion Sort List/147.java b/solutions/147. Insertion Sort List/147.java new file mode 100644 index 00000000000..8412d6e92b0 --- /dev/null +++ b/solutions/147. Insertion Sort List/147.java @@ -0,0 +1,19 @@ +class Solution { + public ListNode insertionSortList(ListNode head) { + ListNode dummy = new ListNode(0); + ListNode prev = dummy; // the last and thus largest of the sorted list + + while (head != null) { // the current inserting node + ListNode next = head.next; // Cache the next inserting node. + if (prev.val >= head.val) + prev = dummy; // Move `prev` to the front. + while (prev.next != null && prev.next.val < head.val) + prev = prev.next; + head.next = prev.next; + prev.next = head; + head = next; // Update the current inserting node. + } + + return dummy.next; + } +} diff --git a/solutions/147. Insertion Sort List/147.py b/solutions/147. Insertion Sort List/147.py new file mode 100644 index 00000000000..470ed7b3bc1 --- /dev/null +++ b/solutions/147. Insertion Sort List/147.py @@ -0,0 +1,16 @@ +class Solution: + def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(0) + prev = dummy # the last and thus largest of the sorted list + + while head: # the current inserting node + next = head.next # Cache the next inserting node. + if prev.val >= head.val: + prev = dummy # Move `prev` to the front. + while prev.next and prev.next.val < head.val: + prev = prev.next + head.next = prev.next + prev.next = head + head = next # Update the current inserting node. + + return dummy.next diff --git a/solutions/1470. Shuffle the Array/1470.cpp b/solutions/1470. Shuffle the Array/1470.cpp new file mode 100644 index 00000000000..2ef32d90dd2 --- /dev/null +++ b/solutions/1470. Shuffle the Array/1470.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector shuffle(vector& nums, int n) { + vector ans; + for (int i = 0; i < n; ++i) { + ans.push_back(nums[i]); + ans.push_back(nums[i + n]); + } + return ans; + } +}; diff --git a/solutions/1470. Shuffle the Array/1470.java b/solutions/1470. Shuffle the Array/1470.java new file mode 100644 index 00000000000..2f4e1be75a5 --- /dev/null +++ b/solutions/1470. Shuffle the Array/1470.java @@ -0,0 +1,10 @@ +class Solution { + public int[] shuffle(int[] nums, int n) { + int[] ans = new int[2 * n]; + for (int i = 0; i < n; ++i) { + ans[i * 2] = nums[i]; + ans[i * 2 + 1] = nums[i + n]; + } + return ans; + } +} diff --git a/solutions/1470. Shuffle the Array/1470.py b/solutions/1470. Shuffle the Array/1470.py new file mode 100644 index 00000000000..9f81cdc6608 --- /dev/null +++ b/solutions/1470. Shuffle the Array/1470.py @@ -0,0 +1,7 @@ +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + ans = [] + for a, b in zip(nums[:n], nums[n:]): + ans.append(a) + ans.append(b) + return ans diff --git a/solutions/1471. The k Strongest Values in an Array/1471-2.cpp b/solutions/1471. The k Strongest Values in an Array/1471-2.cpp new file mode 100644 index 00000000000..e3a54196546 --- /dev/null +++ b/solutions/1471. The k Strongest Values in an Array/1471-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector getStrongest(vector& arr, int k) { + const int midIndex = (arr.size() - 1) / 2; + nth_element(arr.begin(), arr.begin() + midIndex, arr.end()); + const int median = arr[midIndex]; + + nth_element(arr.begin(), arr.begin() + k, arr.end(), [&](int a, int b) { + const int da = abs(a - median); + const int db = abs(b - median); + return da == db ? a > b : da > db; + }); + + arr.resize(k); + return arr; + } +}; diff --git a/solutions/1471. The k Strongest Values in an Array/1471.cpp b/solutions/1471. The k Strongest Values in an Array/1471.cpp new file mode 100644 index 00000000000..8c1ce7d8d21 --- /dev/null +++ b/solutions/1471. The k Strongest Values in an Array/1471.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector getStrongest(vector& arr, int k) { + ranges::sort(arr); + + const int n = arr.size(); + const int median = arr[(n - 1) / 2]; + vector ans; + + for (int l = 0, r = n - 1; k > 0; --k) + if (median - arr[l] > arr[r] - median) + ans.push_back(arr[l++]); + else + ans.push_back(arr[r--]); + + return ans; + } +}; diff --git a/solutions/1471. The k Strongest Values in an Array/1471.java b/solutions/1471. The k Strongest Values in an Array/1471.java new file mode 100644 index 00000000000..4ffa75e6886 --- /dev/null +++ b/solutions/1471. The k Strongest Values in an Array/1471.java @@ -0,0 +1,17 @@ +class Solution { + public int[] getStrongest(int[] arr, int k) { + Arrays.sort(arr); + + final int n = arr.length; + final int median = arr[(n - 1) / 2]; + int[] ans = new int[k]; + + for (int i = 0, l = 0, r = n - 1; i < k; ++i) + if (median - arr[l] > arr[r] - median) + ans[i] = arr[l++]; + else + ans[i] = arr[r--]; + + return ans; + } +} diff --git a/solutions/1471. The k Strongest Values in an Array/1471.py b/solutions/1471. The k Strongest Values in an Array/1471.py new file mode 100644 index 00000000000..111bffcd69f --- /dev/null +++ b/solutions/1471. The k Strongest Values in an Array/1471.py @@ -0,0 +1,18 @@ +class Solution: + def getStrongest(self, arr: List[int], k: int) -> List[int]: + arr.sort() + + ans = [] + median = arr[(len(arr) - 1) // 2] + l = 0 + r = len(arr) - 1 + + for _ in range(k): + if median - arr[l] > arr[r] - median: + ans.append(arr[l]) + l -= 1 + else: + ans.append(arr[r]) + r += 1 + + return ans diff --git a/solutions/1472. Design Browser History/1472-2.cpp b/solutions/1472. Design Browser History/1472-2.cpp new file mode 100644 index 00000000000..968ef0825ac --- /dev/null +++ b/solutions/1472. Design Browser History/1472-2.cpp @@ -0,0 +1,27 @@ +class BrowserHistory { + public: + BrowserHistory(string homepage) { + visit(homepage); + } + + void visit(string url) { + history.push(url); + future = stack(); + } + + string back(int steps) { + while (history.size() > 1 && steps-- > 0) + future.push(history.top()), history.pop(); + return history.top(); + } + + string forward(int steps) { + while (!future.empty() && steps-- > 0) + history.push(future.top()), future.pop(); + return history.top(); + } + + private: + stack history; + stack future; +}; diff --git a/solutions/1472. Design Browser History/1472-2.java b/solutions/1472. Design Browser History/1472-2.java new file mode 100644 index 00000000000..ece847bd530 --- /dev/null +++ b/solutions/1472. Design Browser History/1472-2.java @@ -0,0 +1,25 @@ +class BrowserHistory { + public BrowserHistory(String homepage) { + visit(homepage); + } + + public void visit(String url) { + history.push(url); + future = new ArrayDeque<>(); + } + + public String back(int steps) { + while (history.size() > 1 && steps-- > 0) + future.push(history.pop()); + return history.peek(); + } + + public String forward(int steps) { + while (!future.isEmpty() && steps-- > 0) + history.push(future.pop()); + return history.peek(); + } + + private Deque history = new ArrayDeque<>(); + private Deque future; +} diff --git a/solutions/1472. Design Browser History/1472-2.py b/solutions/1472. Design Browser History/1472-2.py new file mode 100644 index 00000000000..0bb74d50c8d --- /dev/null +++ b/solutions/1472. Design Browser History/1472-2.py @@ -0,0 +1,20 @@ +class BrowserHistory: + def __init__(self, homepage: str): + self.history = [] + self.visit(homepage) + + def visit(self, url: str) -> None: + self.history.append(url) + self.future = [] + + def back(self, steps: int) -> str: + while len(self.history) > 1 and steps > 0: + self.future.append(self.history.pop()) + steps -= 1 + return self.history[-1] + + def forward(self, steps: int) -> str: + while self.future and steps > 0: + self.history.append(self.future.pop()) + steps -= 1 + return self.history[-1] diff --git a/solutions/1472. Design Browser History/1472-3.cpp b/solutions/1472. Design Browser History/1472-3.cpp new file mode 100644 index 00000000000..0265506e9ae --- /dev/null +++ b/solutions/1472. Design Browser History/1472-3.cpp @@ -0,0 +1,34 @@ +struct Node { + Node(const string& url) : url(url) {} + Node* prev = nullptr; + Node* next = nullptr; + const string url; +}; + +class BrowserHistory { + public: + BrowserHistory(string homepage) { + curr = new Node(homepage); + } + + void visit(string url) { + curr->next = new Node(url); + curr->next->prev = curr; + curr = curr->next; + } + + string back(int steps) { + while (curr->prev && steps-- > 0) + curr = curr->prev; + return curr->url; + } + + string forward(int steps) { + while (curr->next && steps-- > 0) + curr = curr->next; + return curr->url; + } + + private: + Node* curr = nullptr; +}; diff --git a/solutions/1472. Design Browser History/1472-3.java b/solutions/1472. Design Browser History/1472-3.java new file mode 100644 index 00000000000..cae5c5eed0e --- /dev/null +++ b/solutions/1472. Design Browser History/1472-3.java @@ -0,0 +1,34 @@ +class Node { + public Node prev; + public Node next; + public final String url; + public Node(final String url) { + this.url = url; + } +} + +class BrowserHistory { + public BrowserHistory(String homepage) { + curr = new Node(homepage); + } + + public void visit(String url) { + curr.next = new Node(url); + curr.next.prev = curr; + curr = curr.next; + } + + public String back(int steps) { + while (curr.prev != null && steps-- > 0) + curr = curr.prev; + return curr.url; + } + + public String forward(int steps) { + while (curr.next != null && steps-- > 0) + curr = curr.next; + return curr.url; + } + + private Node curr; +} diff --git a/solutions/1472. Design Browser History/1472-3.py b/solutions/1472. Design Browser History/1472-3.py new file mode 100644 index 00000000000..da39bb6d357 --- /dev/null +++ b/solutions/1472. Design Browser History/1472-3.py @@ -0,0 +1,27 @@ +class Node: + def __init__(self, url: str): + self.prev = None + self.next = None + self.url = url + + +class BrowserHistory: + def __init__(self, homepage: str): + self.curr = Node(homepage) + + def visit(self, url: str) -> None: + self.curr.next = Node(url) + self.curr.next.prev = self.curr + self.curr = self.curr.next + + def back(self, steps: int) -> str: + while self.curr.prev and steps > 0: + self.curr = self.curr.prev + steps -= 1 + return self.curr.url + + def forward(self, steps: int) -> str: + while self.curr.next and steps > 0: + self.curr = self.curr.next + steps -= 1 + return self.curr.url diff --git a/solutions/1472. Design Browser History/1472.cpp b/solutions/1472. Design Browser History/1472.cpp new file mode 100644 index 00000000000..f51a2cb3667 --- /dev/null +++ b/solutions/1472. Design Browser History/1472.cpp @@ -0,0 +1,29 @@ +class BrowserHistory { + public: + BrowserHistory(string homepage) { + visit(homepage); + } + + void visit(string url) { + if (++index < urls.size()) + urls[index] = url; + else + urls.push_back(url); + lastIndex = index; + } + + string back(int steps) { + index = max(0, index - steps); + return urls[index]; + } + + string forward(int steps) { + index = min(lastIndex, index + steps); + return urls[index]; + } + + private: + vector urls; + int index = -1; + int lastIndex = -1; +}; diff --git a/solutions/1472. Design Browser History/1472.java b/solutions/1472. Design Browser History/1472.java new file mode 100644 index 00000000000..da1ee1f3480 --- /dev/null +++ b/solutions/1472. Design Browser History/1472.java @@ -0,0 +1,27 @@ +class BrowserHistory { + public BrowserHistory(String homepage) { + visit(homepage); + } + + public void visit(String url) { + if (++index < urls.size()) + urls.set(index, url); + else + urls.add(url); + lastIndex = index; + } + + public String back(int steps) { + index = Math.max(0, index - steps); + return urls.get(index); + } + + public String forward(int steps) { + index = Math.min(lastIndex, index + steps); + return urls.get(index); + } + + private List urls = new ArrayList<>(); + private int index = -1; + private int lastIndex = -1; +} diff --git a/solutions/1472. Design Browser History/1472.py b/solutions/1472. Design Browser History/1472.py new file mode 100644 index 00000000000..a31d227abbb --- /dev/null +++ b/solutions/1472. Design Browser History/1472.py @@ -0,0 +1,22 @@ +class BrowserHistory: + def __init__(self, homepage: str): + self.urls = [] + self.index = -1 + self.lastIndex = -1 + self.visit(homepage) + + def visit(self, url: str) -> None: + self.index += 1 + if self.index < len(self.urls): + self.urls[self.index] = url + else: + self.urls.append(url) + self.lastIndex = self.index + + def back(self, steps: int) -> str: + self.index = max(0, self.index - steps) + return self.urls[self.index] + + def forward(self, steps: int) -> str: + self.index = min(self.lastIndex, self.index + steps) + return self.urls[self.index] diff --git a/solutions/1473. Paint House III/1473.cpp b/solutions/1473. Paint House III/1473.cpp new file mode 100644 index 00000000000..605f1ac5e9f --- /dev/null +++ b/solutions/1473. Paint House III/1473.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int minCost(vector& houses, vector>& cost, int m, int n, + int target) { + vector>> mem(target + 1, + vector>(m, vector(n + 1))); + // Initialize `prevColor` to 0 (the virtual neighbor). + const int c = minCost(houses, cost, m, n, target, 0, 0, mem); + return c == kMax ? -1 : c; + } + + private: + static constexpr int kMax = 1'000'001; + + // Returns the minimum cost to paint houses[i..m) into k neighborhoods, where + // there are houses[i - 1] colors = prevColor. + int minCost(const vector& houses, const vector>& cost, + const int& m, const int& n, int k, int i, int prevColor, + vector>>& mem) { + if (i == m || k < 0) + return k == 0 ? 0 : kMax; + if (mem[k][i][prevColor] > 0) + return mem[k][i][prevColor]; + if (houses[i] > 0) // The house was painted last year. + return minCost(houses, cost, m, n, k - (prevColor != houses[i]), i + 1, + houses[i], mem); + + int res = kMax; + + // Try to paint the houses[i] with each color in 1..n. + for (int color = 1; color <= n; ++color) + res = min(res, cost[i][color - 1] + minCost(houses, cost, m, n, + k - (prevColor != color), + i + 1, color, mem)); + + return mem[k][i][prevColor] = res; + } +}; diff --git a/solutions/1473. Paint House III/1473.java b/solutions/1473. Paint House III/1473.java new file mode 100644 index 00000000000..047bd2482ec --- /dev/null +++ b/solutions/1473. Paint House III/1473.java @@ -0,0 +1,33 @@ +class Solution { + public int minCost(int[] houses, int[][] cost, int m, int n, int target) { + int[][][] mem = new int[target + 1][m][n + 1]; + // Initialize `prevColor` to 0 (the virtual neighbor). + final int c = minCost(houses, cost, m, n, target, 0, 0, mem); + return c == kMax ? -1 : c; + } + + private static final int kMax = 1_000_001; + + // Returns the minimum cost to paint houses[i..m) into k neighborhoods, where + // there are houses[i - 1] colors = prevColor. + public int minCost(int[] houses, int[][] cost, int m, int n, int k, int i, int prevColor, + int[][][] mem) { + if (i == m || k < 0) + return k == 0 ? 0 : kMax; + if (mem[k][i][prevColor] > 0) + return mem[k][i][prevColor]; + if (houses[i] > 0) // The house was painted last year. + return minCost(houses, cost, m, n, k - (prevColor == houses[i] ? 0 : 1), i + 1, houses[i], + mem); + + int ans = kMax; + + // Try to paint the houses[i] with each color in 1..n. + for (int color = 1; color <= n; ++color) + ans = Math.min(ans, cost[i][color - 1] + minCost(houses, cost, m, n, + k - (prevColor == color ? 0 : 1), i + 1, + color, mem)); + + return mem[k][i][prevColor] = ans; + } +} diff --git a/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.cpp b/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.cpp new file mode 100644 index 00000000000..a399a53105a --- /dev/null +++ b/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + ListNode* deleteNodes(ListNode* head, int m, int n) { + ListNode* curr = head; + ListNode* prev = nullptr; // prev.next == curr + + while (curr != nullptr) { + // Set the m-th node as `prev`. + for (int i = 0; i < m & curr != nullptr; ++i) { + prev = curr; + curr = curr->next; + } + // Set the (m + n + 1)-th node as `curr`. + for (int i = 0; i < n && curr != nullptr; ++i) + curr = curr->next; + // Delete the nodes [m + 1..n - 1]. + prev->next = curr; + } + + return head; + } +}; diff --git a/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.java b/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.java new file mode 100644 index 00000000000..5d32e71546f --- /dev/null +++ b/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.java @@ -0,0 +1,21 @@ +class Solution { + public ListNode deleteNodes(ListNode head, int m, int n) { + ListNode curr = head; + ListNode prev = null; // prev.next == curr + + while (curr != null) { + // Set the m-th node as `prev`. + for (int i = 0; i < m & curr != null; ++i) { + prev = curr; + curr = curr.next; + } + // Set the (m + n + 1)-th node as `curr`. + for (int i = 0; i < n && curr != null; ++i) + curr = curr.next; + // Delete the nodes [m + 1..n - 1]. + prev.next = curr; + } + + return head; + } +} diff --git a/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.py b/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.py new file mode 100644 index 00000000000..ae9e932a6e5 --- /dev/null +++ b/solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.py @@ -0,0 +1,21 @@ +class Solution: + def deleteNodes(self, head: Optional[ListNode], m: int, n: int) -> Optional[ListNode]: + curr = head + prev = None # prev.next == curr + + while curr: + # Set the m-th node as `prev`. + for _ in range(m): + if not curr: + break + prev = curr + curr = curr.next + # Set the (m + n + 1)-th node as `curr`. + for _ in range(n): + if not curr: + break + curr = curr.next + # Delete the nodes [m + 1..n - 1]. + prev.next = curr + + return head diff --git a/solutions/1475. Final Prices With a Special Discount in a Shop/1475.cpp b/solutions/1475. Final Prices With a Special Discount in a Shop/1475.cpp new file mode 100644 index 00000000000..f7289ad1c2d --- /dev/null +++ b/solutions/1475. Final Prices With a Special Discount in a Shop/1475.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector finalPrices(vector& prices) { + vector ans{prices}; + stack stack; + + for (int j = 0; j < prices.size(); ++j) { + // stack[-1] : = i in the problem description. + while (!stack.empty() && prices[j] <= prices[stack.top()]) + ans[stack.top()] -= prices[j], stack.pop(); + stack.push(j); + } + + return ans; + } +}; diff --git a/solutions/1475. Final Prices With a Special Discount in a Shop/1475.java b/solutions/1475. Final Prices With a Special Discount in a Shop/1475.java new file mode 100644 index 00000000000..e9ba3f85e25 --- /dev/null +++ b/solutions/1475. Final Prices With a Special Discount in a Shop/1475.java @@ -0,0 +1,15 @@ +class Solution { + public int[] finalPrices(int[] prices) { + int[] ans = prices.clone(); + Deque stack = new ArrayDeque<>(); + + for (int j = 0; j < prices.length; ++j) { + // stack[-1] := i in the problem description. + while (!stack.isEmpty() && prices[j] <= prices[stack.peek()]) + ans[stack.pop()] -= prices[j]; + stack.push(j); + } + + return ans; + } +} diff --git a/solutions/1475. Final Prices With a Special Discount in a Shop/1475.py b/solutions/1475. Final Prices With a Special Discount in a Shop/1475.py new file mode 100644 index 00000000000..a9a97604c4b --- /dev/null +++ b/solutions/1475. Final Prices With a Special Discount in a Shop/1475.py @@ -0,0 +1,12 @@ +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + ans = prices.copy() + stack = [] + + for i, price in enumerate(prices): + # stack[-1] := i in the problem description. + while stack and prices[stack[-1]] >= price: + ans[stack.pop()] -= price + stack.append(i) + + return ans diff --git a/solutions/1476. Subrectangle Queries/1476.cpp b/solutions/1476. Subrectangle Queries/1476.cpp new file mode 100644 index 00000000000..fa74ab0668e --- /dev/null +++ b/solutions/1476. Subrectangle Queries/1476.cpp @@ -0,0 +1,22 @@ +class SubrectangleQueries { + public: + SubrectangleQueries(vector>& rectangle) : rectangle(rectangle) {} + + void updateSubrectangle(int row1, int col1, int row2, int col2, + int newValue) { + updates.push_back({row1, col1, row2, col2, newValue}); + } + + int getValue(int row, int col) { + for (int i = updates.size() - 1; i >= 0; --i) { + auto [r1, c1, r2, c2, v] = updates[i]; + if (r1 <= row && row <= r2 && c1 <= col && col <= c2) + return v; + } + return rectangle[row][col]; + } + + private: + const vector>& rectangle; + vector> updates; // [r1, c1, r2, c2, v] +}; diff --git a/solutions/1476. Subrectangle Queries/1476.java b/solutions/1476. Subrectangle Queries/1476.java new file mode 100644 index 00000000000..26234254661 --- /dev/null +++ b/solutions/1476. Subrectangle Queries/1476.java @@ -0,0 +1,26 @@ +class SubrectangleQueries { + public SubrectangleQueries(int[][] rectangle) { + this.rectangle = rectangle; + } + + public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { + updates.add(new int[] {row1, col1, row2, col2, newValue}); + } + + public int getValue(int row, int col) { + for (int i = updates.size() - 1; i >= 0; --i) { + int[] update = updates.get(i); + final int r1 = update[0]; + final int c1 = update[1]; + final int r2 = update[2]; + final int c2 = update[3]; + final int v = update[4]; + if (r1 <= row && row <= r2 && c1 <= col && col <= c2) + return v; + } + return rectangle[row][col]; + } + + private int[][] rectangle; + private List updates = new ArrayList<>(); // [r1, c1, r2, c2, v] +} diff --git a/solutions/1476. Subrectangle Queries/1476.py b/solutions/1476. Subrectangle Queries/1476.py new file mode 100644 index 00000000000..4f2f29f0069 --- /dev/null +++ b/solutions/1476. Subrectangle Queries/1476.py @@ -0,0 +1,13 @@ +class SubrectangleQueries: + def __init__(self, rectangle: List[List[int]]): + self.rectangle = rectangle + self.updates = [] + + def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: + self.updates.append((row1, col1, row2, col2, newValue)) + + def getValue(self, row: int, col: int) -> int: + for r1, c1, r2, c2, v in reversed(self.updates): + if r1 <= row <= r2 and c1 <= col <= c2: + return v + return self.rectangle[row][col] diff --git a/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.cpp b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.cpp new file mode 100644 index 00000000000..26040008906 --- /dev/null +++ b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minSumOfLengths(vector& arr, int target) { + int ans = INT_MAX; + int sum = 0; // the window sum + // best[i] := the minimum length of subarrays in arr[0..i] that have + // sum = target + vector best(arr.size(), INT_MAX); + + for (int l = 0, r = 0; r < arr.size(); ++r) { + sum += arr[r]; // Expand the window. + while (sum > target) + sum -= arr[l++]; // Shrink the window. + if (sum == target) { + if (l > 0 && best[l - 1] != INT_MAX) + ans = min(ans, best[l - 1] + r - l + 1); + best[r] = min(best[r], r - l + 1); + } + if (r > 0) + best[r] = min(best[r], best[r - 1]); + } + + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.java b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.java new file mode 100644 index 00000000000..6358af6986c --- /dev/null +++ b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477-2.java @@ -0,0 +1,25 @@ +class Solution { + public int minSumOfLengths(int[] arr, int target) { + int ans = Integer.MAX_VALUE; + int sum = 0; // the window sum + // best[i] := the minimum length of subarrays in arr[0..i] that have + // sum = target + int[] best = new int[arr.length]; + Arrays.fill(best, Integer.MAX_VALUE); + + for (int l = 0, r = 0; r < arr.length; ++r) { + sum += arr[r]; // Expand the window. + while (sum > target) + sum -= arr[l++]; // Shrink the window. + if (sum == target) { + if (l > 0 && best[l - 1] != Integer.MAX_VALUE) + ans = Math.min(ans, best[l - 1] + r - l + 1); + best[r] = Math.min(best[r], r - l + 1); + } + if (r > 0) + best[r] = Math.min(best[r], best[r - 1]); + } + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.cpp b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.cpp new file mode 100644 index 00000000000..f1b0c99333c --- /dev/null +++ b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minSumOfLengths(vector& arr, int target) { + int ans = INT_MAX; + int leftLength = INT_MAX; + int prefix = 0; + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < arr.size(); ++i) { + prefix += arr[i]; + prefixToIndex[prefix] = i; + } + + prefix = 0; + + for (int i = 0; i < arr.size(); ++i) { + prefix += arr[i]; + if (const auto it = prefixToIndex.find(prefix - target); + it != prefixToIndex.cend()) + leftLength = min(leftLength, i - it->second); + if (leftLength < INT_MAX) + if (const auto it = prefixToIndex.find(prefix + target); + it != prefixToIndex.cend()) + ans = min(ans, leftLength + it->second - i); + } + + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.java b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.java new file mode 100644 index 00000000000..13224c40502 --- /dev/null +++ b/solutions/1477. Find Two Non-overlapping Sub-arrays Each With Target Sum/1477.java @@ -0,0 +1,27 @@ +class Solution { + public int minSumOfLengths(int[] arr, int target) { + int ans = Integer.MAX_VALUE; + int leftLength = Integer.MAX_VALUE; + int prefix = 0; + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < arr.length; ++i) { + prefix += arr[i]; + prefixToIndex.put(prefix, i); + } + + prefix = 0; + + for (int i = 0; i < arr.length; ++i) { + prefix += arr[i]; + if (prefixToIndex.containsKey(prefix - target)) + leftLength = Math.min(leftLength, i - prefixToIndex.get(prefix - target)); + if (leftLength < Integer.MAX_VALUE) + if (prefixToIndex.containsKey(prefix + target)) + ans = Math.min(ans, leftLength + prefixToIndex.get(prefix + target) - i); + } + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/1478. Allocate Mailboxes/1478.cpp b/solutions/1478. Allocate Mailboxes/1478.cpp new file mode 100644 index 00000000000..bab4a10e9fa --- /dev/null +++ b/solutions/1478. Allocate Mailboxes/1478.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int minDistance(vector& houses, int k) { + const int n = houses.size(); + vector> mem(n, vector(k + 1, INT_MAX)); + // cost[i][j] := the minimum cost to allocate mailboxes between houses[i] + // and houses[j] + vector> cost(n, vector(n)); + + ranges::sort(houses); + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + const int median = houses[(i + j) / 2]; + for (int x = i; x <= j; ++x) + cost[i][j] += abs(houses[x] - median); + } + + return minDistance(houses, 0, k, cost, mem); + } + + private: + static constexpr int kMax = 1'000'000; + + // Returns the minimum distance to allocate k mailboxes for houses[i..n). + int minDistance(const vector& houses, int i, int k, + const vector>& cost, vector>& mem) { + if (i == houses.size() && k == 0) + return 0; + if (i == houses.size() || k == 0) + return kMax; + if (mem[i][k] != INT_MAX) + return mem[i][k]; + + for (int j = i; j < houses.size(); ++j) + mem[i][k] = min( + mem[i][k], cost[i][j] + minDistance(houses, j + 1, k - 1, cost, mem)); + + return mem[i][k]; + } +}; diff --git a/solutions/1478. Allocate Mailboxes/1478.java b/solutions/1478. Allocate Mailboxes/1478.java new file mode 100644 index 00000000000..16c5e24d976 --- /dev/null +++ b/solutions/1478. Allocate Mailboxes/1478.java @@ -0,0 +1,38 @@ +class Solution { + public int minDistance(int[] houses, int k) { + final int n = houses.length; + int[][] mem = new int[n][k + 1]; + // cost[i][j] := the minimum cost to allocate mailboxes between houses[i] + // and houses[j] + int[][] cost = new int[n][n]; + + Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + Arrays.sort(houses); + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + int median = houses[(i + j) / 2]; + for (int x = i; x <= j; ++x) + cost[i][j] += Math.abs(houses[x] - median); + } + + return minDistance(houses, 0, k, cost, mem); + } + + private static final int kMax = 1_000_000; + + // Returns the minimum distance to allocate k mailboxes for houses[i..n). + private int minDistance(int[] houses, int i, int k, int[][] cost, int[][] mem) { + if (i == houses.length && k == 0) + return 0; + if (i == houses.length || k == 0) + return kMax; + if (mem[i][k] != Integer.MAX_VALUE) + return mem[i][k]; + + for (int j = i; j < houses.length; ++j) + mem[i][k] = Math.min(mem[i][k], cost[i][j] + minDistance(houses, j + 1, k - 1, cost, mem)); + + return mem[i][k]; + } +} diff --git a/solutions/1479. Sales by Day of the Week/1479.sql b/solutions/1479. Sales by Day of the Week/1479.sql new file mode 100644 index 00000000000..cff57a396f9 --- /dev/null +++ b/solutions/1479. Sales by Day of the Week/1479.sql @@ -0,0 +1,14 @@ +SELECT + Items.item_category AS Category, + SUM(IF(WEEKDAY(Orders.order_date) = 0, Orders.quantity, 0)) AS Monday, + SUM(IF(WEEKDAY(Orders.order_date) = 1, Orders.quantity, 0)) AS Tuesday, + SUM(IF(WEEKDAY(Orders.order_date) = 2, Orders.quantity, 0)) AS Wednesday, + SUM(IF(WEEKDAY(Orders.order_date) = 3, Orders.quantity, 0)) AS Thursday, + SUM(IF(WEEKDAY(Orders.order_date) = 4, Orders.quantity, 0)) AS Friday, + SUM(IF(WEEKDAY(Orders.order_date) = 5, Orders.quantity, 0)) AS Saturday, + SUM(IF(WEEKDAY(Orders.order_date) = 6, Orders.quantity, 0)) AS Sunday +FROM Items +LEFT JOIN Orders + USING (item_id) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/148. Sort List/148.cpp b/solutions/148. Sort List/148.cpp new file mode 100644 index 00000000000..2fba9e07dfd --- /dev/null +++ b/solutions/148. Sort List/148.cpp @@ -0,0 +1,57 @@ +class Solution { + public: + ListNode* sortList(ListNode* head) { + const int length = getLength(head); + ListNode dummy(0, head); + + for (int k = 1; k < length; k *= 2) { + ListNode* curr = dummy.next; + ListNode* tail = &dummy; + while (curr) { + ListNode* l = curr; + ListNode* r = split(l, k); + curr = split(r, k); + auto [mergedHead, mergedTail] = merge(l, r); + tail->next = mergedHead; + tail = mergedTail; + } + } + + return dummy.next; + } + + private: + int getLength(ListNode* head) { + int length = 0; + for (ListNode* curr = head; curr; curr = curr->next) + ++length; + return length; + } + + ListNode* split(ListNode* head, int k) { + while (--k && head) + head = head->next; + ListNode* rest = head ? head->next : nullptr; + if (head != nullptr) + head->next = nullptr; + return rest; + } + + pair merge(ListNode* l1, ListNode* l2) { + ListNode dummy(0); + ListNode* tail = &dummy; + + while (l1 && l2) { + if (l1->val > l2->val) + swap(l1, l2); + tail->next = l1; + l1 = l1->next; + tail = tail->next; + } + tail->next = l1 ? l1 : l2; + while (tail->next) + tail = tail->next; + + return {dummy.next, tail}; + } +}; diff --git a/solutions/148. Sort List/148.java b/solutions/148. Sort List/148.java new file mode 100644 index 00000000000..928791846bf --- /dev/null +++ b/solutions/148. Sort List/148.java @@ -0,0 +1,58 @@ +class Solution { + public ListNode sortList(ListNode head) { + final int length = getLength(head); + ListNode dummy = new ListNode(0, head); + + for (int k = 1; k < length; k *= 2) { + ListNode curr = dummy.next; + ListNode tail = dummy; + while (curr != null) { + ListNode l = curr; + ListNode r = split(l, k); + curr = split(r, k); + ListNode[] merged = merge(l, r); + tail.next = merged[0]; + tail = merged[1]; + } + } + + return dummy.next; + } + + private int getLength(ListNode head) { + int length = 0; + for (ListNode curr = head; curr != null; curr = curr.next) + ++length; + return length; + } + + private ListNode split(ListNode head, int k) { + while (--k > 0 && head != null) + head = head.next; + ListNode rest = head == null ? null : head.next; + if (head != null) + head.next = null; + return rest; + } + + private ListNode[] merge(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode tail = dummy; + + while (l1 != null && l2 != null) { + if (l1.val > l2.val) { + ListNode temp = l1; + l1 = l2; + l2 = temp; + } + tail.next = l1; + l1 = l1.next; + tail = tail.next; + } + tail.next = l1 == null ? l2 : l1; + while (tail.next != null) + tail = tail.next; + + return new ListNode[] {dummy.next, tail}; + } +} diff --git a/solutions/148. Sort List/148.py b/solutions/148. Sort List/148.py new file mode 100644 index 00000000000..abe45b123c9 --- /dev/null +++ b/solutions/148. Sort List/148.py @@ -0,0 +1,49 @@ +class Solution: + def sortList(self, head: ListNode) -> ListNode: + def split(head: ListNode, k: int) -> ListNode: + while k > 1 and head: + head = head.next + k -= 1 + rest = head.next if head else None + if head: + head.next = None + return rest + + def merge(l1: ListNode, l2: ListNode) -> tuple: + dummy = ListNode(0) + tail = dummy + + while l1 and l2: + if l1.val > l2.val: + l1, l2 = l2, l1 + tail.next = l1 + l1 = l1.next + tail = tail.next + tail.next = l1 if l1 else l2 + while tail.next: + tail = tail.next + + return dummy.next, tail + + length = 0 + curr = head + while curr: + length += 1 + curr = curr.next + + dummy = ListNode(0, head) + + k = 1 + while k < length: + curr = dummy.next + tail = dummy + while curr: + l = curr + r = split(l, k) + curr = split(r, k) + mergedHead, mergedTail = merge(l, r) + tail.next = mergedHead + tail = mergedTail + k *= 2 + + return dummy.next diff --git a/solutions/1480. Running Sum of 1d Array/1480.cpp b/solutions/1480. Running Sum of 1d Array/1480.cpp new file mode 100644 index 00000000000..e8ab938bf7b --- /dev/null +++ b/solutions/1480. Running Sum of 1d Array/1480.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + vector runningSum(vector& nums) { + vector ans; + int sum = 0; + for (const int num : nums) + ans.push_back(sum += num); + return ans; + } +}; diff --git a/solutions/1480. Running Sum of 1d Array/1480.java b/solutions/1480. Running Sum of 1d Array/1480.java new file mode 100644 index 00000000000..226e1014abf --- /dev/null +++ b/solutions/1480. Running Sum of 1d Array/1480.java @@ -0,0 +1,9 @@ +class Solution { + public int[] runningSum(int[] nums) { + int[] ans = new int[nums.length]; + int sum = 0; + for (int i = 0; i < nums.length; ++i) + ans[i] = sum += nums[i]; + return ans; + } +} diff --git a/solutions/1480. Running Sum of 1d Array/1480.py b/solutions/1480. Running Sum of 1d Array/1480.py new file mode 100644 index 00000000000..4b25218063f --- /dev/null +++ b/solutions/1480. Running Sum of 1d Array/1480.py @@ -0,0 +1,3 @@ +class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + return itertools.accumulate(nums) diff --git a/solutions/1481. Least Number of Unique Integers after K Removals/1481.cpp b/solutions/1481. Least Number of Unique Integers after K Removals/1481.cpp new file mode 100644 index 00000000000..f775314ffc8 --- /dev/null +++ b/solutions/1481. Least Number of Unique Integers after K Removals/1481.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int findLeastNumOfUniqueInts(vector& arr, int k) { + unordered_map count; + priority_queue, greater<>> minHeap; + + for (const int a : arr) + ++count[a]; + + for (const auto& [_, freq] : count) + minHeap.push(freq); + + // Greedily remove the k least frequent numbers to have the least number of + // unique integers. + while (k > 0) + k -= minHeap.top(), minHeap.pop(); + + return minHeap.size() + (k < 0 ? 1 : 0); + } +}; diff --git a/solutions/1481. Least Number of Unique Integers after K Removals/1481.java b/solutions/1481. Least Number of Unique Integers after K Removals/1481.java new file mode 100644 index 00000000000..15082ca6378 --- /dev/null +++ b/solutions/1481. Least Number of Unique Integers after K Removals/1481.java @@ -0,0 +1,16 @@ +class Solution { + public int findLeastNumOfUniqueInts(int[] arr, int k) { + Map count = new HashMap<>(); + + for (final int a : arr) + count.merge(a, 1, Integer::sum); + + Queue minHeap = new PriorityQueue<>(count.values()); + + // Greedily remove the k least frequent numbers to have the least number of unique integers. + while (k > 0) + k -= minHeap.poll(); + + return minHeap.size() + (k < 0 ? 1 : 0); + } +} diff --git a/solutions/1481. Least Number of Unique Integers after K Removals/1481.py b/solutions/1481. Least Number of Unique Integers after K Removals/1481.py new file mode 100644 index 00000000000..9264ca325f9 --- /dev/null +++ b/solutions/1481. Least Number of Unique Integers after K Removals/1481.py @@ -0,0 +1,10 @@ +class Solution: + def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: + minHeap = list(collections.Counter(arr).values()) + heapq.heapify(minHeap) + + # Greedily remove the k least frequent numbers to have the least number of unique integers. + while k > 0: + k -= heapq.heappop(minHeap) + + return len(minHeap) + (1 if k < 0 else 0) diff --git a/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.cpp b/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.cpp new file mode 100644 index 00000000000..f6fc3989c09 --- /dev/null +++ b/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int minDays(vector& bloomDay, int m, int k) { + if (bloomDay.size() < static_cast(m) * k) + return -1; + + int l = ranges::min(bloomDay); + int r = ranges::max(bloomDay); + + while (l < r) { + const int mid = (l + r) / 2; + if (getBouquetCount(bloomDay, k, mid) >= m) + r = mid; + else + l = mid + 1; + } + + return l; + } + + private: + // Returns the number of bouquets (k flowers needed) can be made after the + // `waitingDays`.. + int getBouquetCount(const vector& bloomDay, int k, int waitingDays) { + int bouquetCount = 0; + int requiredFlowers = k; + for (const int day : bloomDay) + if (day > waitingDays) { + // Reset `requiredFlowers` since there was not enough adjacent flowers. + requiredFlowers = k; + } else if (--requiredFlowers == 0) { + // Use k adjacent flowers to make a bouquet. + ++bouquetCount; + requiredFlowers = k; + } + return bouquetCount; + } +}; diff --git a/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.java b/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.java new file mode 100644 index 00000000000..715c68169f7 --- /dev/null +++ b/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.java @@ -0,0 +1,36 @@ +class Solution { + public int minDays(int[] bloomDay, int m, int k) { + if (bloomDay.length < (long) m * k) + return -1; + + int l = Arrays.stream(bloomDay).min().getAsInt(); + int r = Arrays.stream(bloomDay).max().getAsInt(); + + while (l < r) { + final int mid = (l + r) / 2; + if (getBouquetCount(bloomDay, k, mid) >= m) + r = mid; + else + l = mid + 1; + } + + return l; + } + + // Returns the number of bouquets (k flowers needed) can be made after the + // `waitingDays`.. + private int getBouquetCount(int[] bloomDay, int k, int waitingDays) { + int bouquetCount = 0; + int requiredFlowers = k; + for (final int day : bloomDay) + if (day > waitingDays) { + // Reset `requiredFlowers` since there was not enough adjacent flowers. + requiredFlowers = k; + } else if (--requiredFlowers == 0) { + // Use k adjacent flowers to make a bouquet. + ++bouquetCount; + requiredFlowers = k; + } + return bouquetCount; + } +} diff --git a/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.py b/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.py new file mode 100644 index 00000000000..3eaa61bba20 --- /dev/null +++ b/solutions/1482. Minimum Number of Days to Make m Bouquets/1482.py @@ -0,0 +1,35 @@ +class Solution: + def minDays(self, bloomDay: List[int], m: int, k: int) -> int: + if len(bloomDay) < m * k: + return -1 + + def getBouquetCount(waitingDays: int) -> int: + """ + Returns the number of bouquets (k flowers needed) can be made after the + `waitingDays`. + """ + bouquetCount = 0 + requiredFlowers = k + for day in bloomDay: + if day > waitingDays: + # Reset `requiredFlowers` since there was not enough adjacent flowers. + requiredFlowers = k + else: + requiredFlowers -= 1 + if requiredFlowers == 0: + # Use k adjacent flowers to make a bouquet. + bouquetCount += 1 + requiredFlowers = k + return bouquetCount + + l = min(bloomDay) + r = max(bloomDay) + + while l < r: + mid = (l + r) // 2 + if getBouquetCount(mid) >= m: + r = mid + else: + l = mid + 1 + + return l diff --git a/solutions/1483. Kth Ancestor of a Tree Node/1483.cpp b/solutions/1483. Kth Ancestor of a Tree Node/1483.cpp new file mode 100644 index 00000000000..36b5eaeed51 --- /dev/null +++ b/solutions/1483. Kth Ancestor of a Tree Node/1483.cpp @@ -0,0 +1,27 @@ +class TreeAncestor { + public: + TreeAncestor(int n, vector& parent) + : maxLevel(32 - __builtin_clz(n)), dp(n, vector(maxLevel)) { + // Node i's 2^0 ancestor is its direct parent. + for (int i = 0; i < n; ++i) + dp[i][0] = parent[i]; + + for (int j = 1; j < maxLevel; ++j) + for (int i = 0; i < n; ++i) + if (dp[i][j - 1] == -1) // There's no such ancestor. + dp[i][j] = -1; + else // A(i, 2^j) = A(A(i, 2^{j - 1}), 2^{j - 1}) + dp[i][j] = dp[dp[i][j - 1]][j - 1]; + } + + int getKthAncestor(int node, int k) { + for (int j = 0; j < maxLevel && node != -1; ++j) + if (k >> j & 1) + node = dp[node][j]; + return node; + } + + private: + const int maxLevel; + vector> dp; // dp[i][j] := node i's 2^j-th ancestor +}; diff --git a/solutions/1483. Kth Ancestor of a Tree Node/1483.java b/solutions/1483. Kth Ancestor of a Tree Node/1483.java new file mode 100644 index 00000000000..23520df5f52 --- /dev/null +++ b/solutions/1483. Kth Ancestor of a Tree Node/1483.java @@ -0,0 +1,27 @@ +class TreeAncestor { + public TreeAncestor(int n, int[] parent) { + this.maxLevel = 32 - Integer.numberOfLeadingZeros(n); + this.dp = new int[n][maxLevel]; + + // Node i's 2^0 ancestor is its direct parent. + for (int i = 0; i < n; ++i) + dp[i][0] = parent[i]; + + for (int j = 1; j < maxLevel; ++j) + for (int i = 0; i < n; ++i) + if (dp[i][j - 1] == -1) // There's no such ancestor. + dp[i][j] = -1; + else // A(i, 2^j) = A(A(i, 2^{j - 1}), 2^{j - 1}) + dp[i][j] = dp[dp[i][j - 1]][j - 1]; + } + + public int getKthAncestor(int node, int k) { + for (int j = 0; j < maxLevel && node != -1; ++j) + if ((k >> j & 1) == 1) + node = dp[node][j]; + return node; + } + + private final int maxLevel; + private int[][] dp; // dp[i][j] := node i's 2^j-th ancestor +} diff --git a/solutions/1483. Kth Ancestor of a Tree Node/1483.py b/solutions/1483. Kth Ancestor of a Tree Node/1483.py new file mode 100644 index 00000000000..5c35a7f9f5d --- /dev/null +++ b/solutions/1483. Kth Ancestor of a Tree Node/1483.py @@ -0,0 +1,24 @@ +class TreeAncestor: + def __init__(self, n: int, parent: List[int]): + self.maxLevel = n.bit_length() + # dp[i][j] := node i's 2^j-th ancestor + self.dp = [[0] * self.maxLevel for _ in range(n)] + + # Node i's 2^0 ancestor is its direct parent + for i in range(n): + self.dp[i][0] = parent[i] + + for j in range(1, self.maxLevel): + for i in range(n): + if self.dp[i][j - 1] == -1: # There's no such ancestor + self.dp[i][j] = -1 + else: # A(i, 2^j) = A(A(i, 2^{j - 1}), 2^{j - 1}) + self.dp[i][j] = self.dp[self.dp[i][j - 1]][j - 1] + + def getKthAncestor(self, node: int, k: int) -> int: + for j in range(self.maxLevel): + if node == -1: + break + if k >> j & 1: + node = self.dp[node][j] + return node diff --git a/solutions/1484. Group Sold Products By The Date/1484.sql b/solutions/1484. Group Sold Products By The Date/1484.sql new file mode 100644 index 00000000000..3e95ddde2e7 --- /dev/null +++ b/solutions/1484. Group Sold Products By The Date/1484.sql @@ -0,0 +1,6 @@ +SELECT + sell_date, + COUNT(DISTINCT product) AS num_sold, + GROUP_CONCAT(DISTINCT product ORDER BY product) AS products +FROM Activities +GROUP BY 1; diff --git a/solutions/1485. Clone Binary Tree With Random Pointer/1485.cpp b/solutions/1485. Clone Binary Tree With Random Pointer/1485.cpp new file mode 100644 index 00000000000..28b63347113 --- /dev/null +++ b/solutions/1485. Clone Binary Tree With Random Pointer/1485.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + NodeCopy* copyRandomBinaryTree(Node* root) { + if (root == nullptr) + return nullptr; + if (const auto it = map.find(root); it != map.cend()) + return it->second; + + NodeCopy* newNode = new NodeCopy(root->val); + map[root] = newNode; + + newNode->left = copyRandomBinaryTree(root->left); + newNode->right = copyRandomBinaryTree(root->right); + newNode->random = copyRandomBinaryTree(root->random); + return newNode; + } + + private: + unordered_map map; +}; diff --git a/solutions/1485. Clone Binary Tree With Random Pointer/1485.java b/solutions/1485. Clone Binary Tree With Random Pointer/1485.java new file mode 100644 index 00000000000..cea4c9ab610 --- /dev/null +++ b/solutions/1485. Clone Binary Tree With Random Pointer/1485.java @@ -0,0 +1,18 @@ +class Solution { + public NodeCopy copyRandomBinaryTree(Node root) { + if (root == null) + return null; + if (map.containsKey(root)) + return map.get(root); + + NodeCopy newNode = new NodeCopy(root.val); + map.put(root, newNode); + + newNode.left = copyRandomBinaryTree(root.left); + newNode.right = copyRandomBinaryTree(root.right); + newNode.random = copyRandomBinaryTree(root.random); + return newNode; + } + + private Map map = new HashMap<>(); +} diff --git a/solutions/1486. XOR Operation in an Array/1486.cpp b/solutions/1486. XOR Operation in an Array/1486.cpp new file mode 100644 index 00000000000..f5610519d3e --- /dev/null +++ b/solutions/1486. XOR Operation in an Array/1486.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int xorOperation(int n, int start) { + int ans = 0; + for (int i = 0; i < n; ++i) + ans ^= start + 2 * i; + return ans; + } +}; diff --git a/solutions/1486. XOR Operation in an Array/1486.java b/solutions/1486. XOR Operation in an Array/1486.java new file mode 100644 index 00000000000..6df86d9b3ac --- /dev/null +++ b/solutions/1486. XOR Operation in an Array/1486.java @@ -0,0 +1,8 @@ +class Solution { + public int xorOperation(int n, int start) { + int ans = 0; + for (int i = 0; i < n; ++i) + ans ^= start + 2 * i; + return ans; + } +} diff --git a/solutions/1486. XOR Operation in an Array/1486.py b/solutions/1486. XOR Operation in an Array/1486.py new file mode 100644 index 00000000000..c9f833a6647 --- /dev/null +++ b/solutions/1486. XOR Operation in an Array/1486.py @@ -0,0 +1,4 @@ +class Solution: + def xorOperation(self, n: int, start: int) -> int: + return functools.reduce(operator.xor, + [start + 2 * i for i in range(n)]) diff --git a/solutions/1487. Making File Names Unique/1487.cpp b/solutions/1487. Making File Names Unique/1487.cpp new file mode 100644 index 00000000000..fca40384cf7 --- /dev/null +++ b/solutions/1487. Making File Names Unique/1487.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector getFolderNames(vector& names) { + vector ans; + unordered_map nameToSuffix; + + for (const string& name : names) + if (const auto it = nameToSuffix.find(name); it != nameToSuffix.cend()) { + int suffix = it->second; + string newName = getName(name, ++suffix); + while (nameToSuffix.contains(newName)) + newName = getName(name, ++suffix); + nameToSuffix[name] = suffix; + nameToSuffix[newName] = 0; + ans.push_back(newName); + } else { + nameToSuffix[name] = 0; + ans.push_back(name); + } + + return ans; + } + + private: + string getName(const string& name, int suffix) { + return name + "(" + to_string(suffix) + ")"; + } +}; diff --git a/solutions/1487. Making File Names Unique/1487.java b/solutions/1487. Making File Names Unique/1487.java new file mode 100644 index 00000000000..81c1962c40a --- /dev/null +++ b/solutions/1487. Making File Names Unique/1487.java @@ -0,0 +1,28 @@ +class Solution { + public String[] getFolderNames(String[] names) { + String[] ans = new String[names.length]; + Map nameToSuffix = new HashMap<>(); + + for (int i = 0; i < names.length; ++i) { + final String name = names[i]; + if (nameToSuffix.containsKey(name)) { + int suffix = nameToSuffix.get(name); + String newName = getName(name, ++suffix); + while (nameToSuffix.containsKey(newName)) + newName = getName(name, ++suffix); + nameToSuffix.put(name, suffix); + nameToSuffix.put(newName, 0); + ans[i] = newName; + } else { + nameToSuffix.put(name, 0); + ans[i] = name; + } + } + + return ans; + } + + private String getName(final String name, int suffix) { + return name + "(" + String.valueOf(suffix) + ")"; + } +} diff --git a/solutions/1487. Making File Names Unique/1487.py b/solutions/1487. Making File Names Unique/1487.py new file mode 100644 index 00000000000..a9f49c717d1 --- /dev/null +++ b/solutions/1487. Making File Names Unique/1487.py @@ -0,0 +1,23 @@ +class Solution: + def getFolderNames(self, names: List[str]) -> List[str]: + ans = [] + nameToSuffix = {} + + for name in names: + if name in nameToSuffix: + suffix = nameToSuffix[name] + 1 + newName = self._getName(name, suffix) + while newName in nameToSuffix: + suffix += 1 + newName = self._getName(name, suffix) + nameToSuffix[name] = suffix + nameToSuffix[newName] = 0 + ans.append(newName) + else: + nameToSuffix[name] = 0 + ans.append(name) + + return ans + + def _getName(self, name: str, suffix: int) -> str: + return name + '(' + str(suffix) + ')' diff --git a/solutions/1488. Avoid Flood in The City/1488.cpp b/solutions/1488. Avoid Flood in The City/1488.cpp new file mode 100644 index 00000000000..b031cba8972 --- /dev/null +++ b/solutions/1488. Avoid Flood in The City/1488.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector avoidFlood(vector& rains) { + vector ans(rains.size(), -1); + unordered_map lakeIdToFullDay; + set emptyDays; // indices of rains[i] == 0 + + for (int i = 0; i < rains.size(); ++i) { + const int lakeId = rains[i]; + if (lakeId == 0) { + emptyDays.insert(i); + continue; + } + if (const auto itFullDay = lakeIdToFullDay.find(lakeId); + itFullDay != lakeIdToFullDay.cend()) { + // The lake was full in a previous day. Greedily find the closest day + // to make the lake empty. + const auto itEmptyDay = emptyDays.upper_bound(itFullDay->second); + if (itEmptyDay == emptyDays.cend()) // Not found. + return {}; + // Empty the lake at this day. + ans[*itEmptyDay] = lakeId; + emptyDays.erase(itEmptyDay); + } + // The lake with `lakeId` becomes full at the day `i`. + lakeIdToFullDay[lakeId] = i; + } + + // Empty an arbitrary lake if there are remaining empty days. + for (const int emptyDay : emptyDays) + ans[emptyDay] = 1; + + return ans; + } +}; diff --git a/solutions/1488. Avoid Flood in The City/1488.java b/solutions/1488. Avoid Flood in The City/1488.java new file mode 100644 index 00000000000..e60565d4063 --- /dev/null +++ b/solutions/1488. Avoid Flood in The City/1488.java @@ -0,0 +1,35 @@ +class Solution { + public int[] avoidFlood(int[] rains) { + int[] ans = new int[rains.length]; + Arrays.fill(ans, -1); + Map lakeIdToFullDay = new HashMap<>(); + TreeSet emptyDays = new TreeSet<>(); // indices of rains[i] == 0 + + for (int i = 0; i < rains.length; ++i) { + final int lakeId = rains[i]; + if (lakeId == 0) { + emptyDays.add(i); + continue; + } + if (lakeIdToFullDay.containsKey(lakeId)) { + final int fullDay = lakeIdToFullDay.get(lakeId); + // The lake was full in a previous day. Greedily find the closest day + // to make the lake empty. + Integer emptyDay = emptyDays.higher(fullDay); + if (emptyDay == null) // Not found. + return new int[] {}; + // Empty the lake at this day. + ans[emptyDay] = lakeId; + emptyDays.remove(emptyDay); + } + // The lake with `lakeId` becomes full at the day `i`. + lakeIdToFullDay.put(lakeId, i); + } + + // Empty an arbitrary lake if there are remaining empty days. + for (final int emptyDay : emptyDays) + ans[emptyDay] = 1; + + return ans; + } +} diff --git a/solutions/1488. Avoid Flood in The City/1488.py b/solutions/1488. Avoid Flood in The City/1488.py new file mode 100644 index 00000000000..c4dae6c1741 --- /dev/null +++ b/solutions/1488. Avoid Flood in The City/1488.py @@ -0,0 +1,32 @@ +from sortedcontainers import SortedSet + + +class Solution: + def avoidFlood(self, rains: List[int]) -> List[int]: + ans = [-1] * len(rains) + lakeIdToFullDay = {} + emptyDays = SortedSet() # indices of rains[i] == 0 + + for i, lakeId in enumerate(rains): + if lakeId == 0: + emptyDays.add(i) + continue + # The lake was full in a previous day. Greedily find the closest day + # to make the lake empty. + if lakeId in lakeIdToFullDay: + fullDay = lakeIdToFullDay[lakeId] + emptyDayIndex = emptyDays.bisect_right(fullDay) + if emptyDayIndex == len(emptyDays): # Not found. + return [] + # Empty the lake at this day. + emptyDay = emptyDays[emptyDayIndex] + ans[emptyDay] = lakeId + emptyDays.discard(emptyDay) + # The lake with `lakeId` becomes full at the day `i`. + lakeIdToFullDay[lakeId] = i + + # Empty an arbitrary lake if there are remaining empty days. + for emptyDay in emptyDays: + ans[emptyDay] = 1 + + return ans diff --git a/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.cpp b/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.cpp new file mode 100644 index 00000000000..f34ac0ce9c4 --- /dev/null +++ b/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.cpp @@ -0,0 +1,94 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + vector> findCriticalAndPseudoCriticalEdges( + int n, vector>& edges) { + vector criticalEdges; + vector pseudoCriticalEdges; + + // Record the index information, so edges[i] := (u, v, weight, index). + for (int i = 0; i < edges.size(); ++i) + edges[i].push_back(i); + + // Sort by the weight. + sort( + edges.begin(), edges.end(), + [](const vector& a, const vector& b) { return a[2] < b[2]; }); + + const int mstWeight = getMSTWeight(n, edges, {}, -1); + + for (const vector& edge : edges) { + const int index = edge[3]; + // Deleting the `edge` increases the MST's weight or makes the MST + // invalid. + if (getMSTWeight(n, edges, {}, index) > mstWeight) + criticalEdges.push_back(index); + // If an edge can be in any MST, we can always add `edge` to the edge set. + else if (getMSTWeight(n, edges, edge, -1) == mstWeight) + pseudoCriticalEdges.push_back(index); + } + + return {criticalEdges, pseudoCriticalEdges}; + } + + private: + int getMSTWeight(int n, const vector>& edges, + const vector& firstEdge, int deletedEdgeIndex) { + int mstWeight = 0; + UnionFind uf(n); + + if (!firstEdge.empty()) { + uf.unionByRank(firstEdge[0], firstEdge[1]); + mstWeight += firstEdge[2]; + } + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int weight = edge[2]; + const int index = edge[3]; + if (index == deletedEdgeIndex) + continue; + if (uf.find(u) == uf.find(v)) + continue; + uf.unionByRank(u, v); + mstWeight += weight; + } + + const int root = uf.find(0); + for (int i = 0; i < n; ++i) + if (uf.find(i) != root) + return INT_MAX; + + return mstWeight; + } +}; diff --git a/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.java b/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.java new file mode 100644 index 00000000000..d3663182c3b --- /dev/null +++ b/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.java @@ -0,0 +1,89 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) { + List criticalEdges = new ArrayList<>(); + List pseudoCriticalEdges = new ArrayList<>(); + + // Record the index information, so edges[i] := (u, v, weight, index). + for (int i = 0; i < edges.length; ++i) + edges[i] = new int[] {edges[i][0], edges[i][1], edges[i][2], i}; + + // Sort by the weight. + Arrays.sort(edges, (a, b) -> a[2] - b[2]); + + final int mstWeight = getMSTWeight(n, edges, new int[] {}, -1); + + for (int[] edge : edges) { + final int index = edge[3]; + // Deleting the `edge` increases the MST's weight or makes the MST + // invalid. + if (getMSTWeight(n, edges, new int[] {}, index) > mstWeight) + criticalEdges.add(index); + // If an edge can be in any MST, we can always add `edge` to the edge set. + else if (getMSTWeight(n, edges, edge, -1) == mstWeight) + pseudoCriticalEdges.add(index); + } + + return new ArrayList<>(Arrays.asList(criticalEdges, pseudoCriticalEdges)); + } + + private int getMSTWeight(int n, int[][] edges, int[] firstEdge, int deletedEdgeIndex) { + int mstWeight = 0; + UnionFind uf = new UnionFind(n); + + if (firstEdge.length == 4) { + uf.unionByRank(firstEdge[0], firstEdge[1]); + mstWeight += firstEdge[2]; + } + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int weight = edge[2]; + final int index = edge[3]; + if (index == deletedEdgeIndex) + continue; + if (uf.find(u) == uf.find(v)) + continue; + uf.unionByRank(u, v); + mstWeight += weight; + } + + final int root = uf.find(0); + for (int i = 0; i < n; ++i) + if (uf.find(i) != root) + return Integer.MAX_VALUE; + + return mstWeight; + } +} diff --git a/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.py b/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.py new file mode 100644 index 00000000000..5ab27cf8962 --- /dev/null +++ b/solutions/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/1489.py @@ -0,0 +1,71 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]: + criticalEdges = [] + pseudoCriticalEdges = [] + + # Record the index information, so edges[i] := (u, v, weight, index). + for i in range(len(edges)): + edges[i].append(i) + + # Sort by the weight. + edges.sort(key=lambda x: x[2]) + + def getMSTWeight(firstEdge: List[int], deletedEdgeIndex: int) -> Union[int, float]: + mstWeight = 0 + uf = UnionFind(n) + + if firstEdge: + uf.unionByRank(firstEdge[0], firstEdge[1]) + mstWeight += firstEdge[2] + + for u, v, weight, index in edges: + if index == deletedEdgeIndex: + continue + if uf.find(u) == uf.find(v): + continue + uf.unionByRank(u, v) + mstWeight += weight + + root = uf.find(0) + if any(uf.find(i) != root for i in range(n)): + return math.inf + + return mstWeight + + mstWeight = getMSTWeight([], -1) + + for edge in edges: + index = edge[3] + # Deleting the `edge` increases the weight of the MST or makes the MST + # invalid. + if getMSTWeight([], index) > mstWeight: + criticalEdges.append(index) + # If an edge can be in any MST, we can always add `edge` to the edge set. + elif getMSTWeight(edge, -1) == mstWeight: + pseudoCriticalEdges.append(index) + + return [criticalEdges, pseudoCriticalEdges] diff --git a/solutions/149. Max Points on a Line/149.cpp b/solutions/149. Max Points on a Line/149.cpp new file mode 100644 index 00000000000..80ea930bcd3 --- /dev/null +++ b/solutions/149. Max Points on a Line/149.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int maxPoints(vector>& points) { + int ans = 0; + + for (int i = 0; i < points.size(); ++i) { + unordered_map, int, PairHash> slopeCount; + const vector p1{points[i]}; + int samePoints = 1; + int maxPoints = 0; // the maximum number of points with the same slope + for (int j = i + 1; j < points.size(); ++j) { + const vector p2{points[j]}; + if (p1 == p2) + ++samePoints; + else + maxPoints = max(maxPoints, ++slopeCount[getSlope(p1, p2)]); + } + ans = max(ans, samePoints + maxPoints); + } + + return ans; + } + + private: + pair getSlope(const vector& p, const vector& q) { + const int dx = p[0] - q[0]; + const int dy = p[1] - q[1]; + if (dx == 0) + return {0, p[0]}; + if (dy == 0) + return {p[1], 0}; + const int d = __gcd(dx, dy); + return {dx / d, dy / d}; + } + + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/149. Max Points on a Line/149.java b/solutions/149. Max Points on a Line/149.java new file mode 100644 index 00000000000..9166f503ca3 --- /dev/null +++ b/solutions/149. Max Points on a Line/149.java @@ -0,0 +1,40 @@ +class Solution { + public int maxPoints(int[][] points) { + int ans = 0; + + for (int i = 0; i < points.length; ++i) { + Map, Integer> slopeCount = new HashMap<>(); + int[] p1 = points[i]; + int samePoints = 1; + int maxPoints = 0; // the maximum number of points with the same slope + for (int j = i + 1; j < points.length; ++j) { + int[] p2 = points[j]; + if (p1[0] == p2[0] && p1[1] == p2[1]) + ++samePoints; + else { + Pair slope = getSlope(p1, p2); + slopeCount.merge(slope, 1, Integer::sum); + maxPoints = Math.max(maxPoints, slopeCount.get(slope)); + } + } + ans = Math.max(ans, samePoints + maxPoints); + } + + return ans; + } + + private Pair getSlope(int[] p, int[] q) { + final int dx = p[0] - q[0]; + final int dy = p[1] - q[1]; + if (dx == 0) + return new Pair<>(0, p[0]); + if (dy == 0) + return new Pair<>(p[1], 0); + final int d = gcd(dx, dy); + return new Pair<>(dx / d, dy / y); + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/149. Max Points on a Line/149.py b/solutions/149. Max Points on a Line/149.py new file mode 100644 index 00000000000..58836aac3d8 --- /dev/null +++ b/solutions/149. Max Points on a Line/149.py @@ -0,0 +1,32 @@ +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + ans = 0 + + def gcd(a: int, b: int) -> int: + return a if b == 0 else gcd(b, a % b) + + def getSlope(p: List[int], q: List[int]) -> Tuple[int, int]: + dx = p[0] - q[0] + dy = p[1] - q[1] + if dx == 0: + return (0, p[0]) + if dy == 0: + return (p[1], 0) + d = gcd(dx, dy) + return (dx // d, dy // d) + + for i, p in enumerate(points): + slopeCount = collections.defaultdict(int) + samePoints = 1 + maxPoints = 0 # the maximum number of points with the same slope + for j in range(i + 1, len(points)): + q = points[j] + if p == q: + samePoints += 1 + else: + slope = getSlope(p, q) + slopeCount[slope] += 1 + maxPoints = max(maxPoints, slopeCount[slope]) + ans = max(ans, samePoints + maxPoints) + + return ans diff --git a/solutions/1490. Clone N-ary Tree/1490.cpp b/solutions/1490. Clone N-ary Tree/1490.cpp new file mode 100644 index 00000000000..95cf27cfa5d --- /dev/null +++ b/solutions/1490. Clone N-ary Tree/1490.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + Node* cloneTree(Node* root) { + if (root == nullptr) + return nullptr; + if (const auto it = map.find(root); it != map.cend()) + return it->second; + + Node* newNode = new Node(root->val); + map[root] = newNode; + + for (Node* child : root->children) + newNode->children.push_back(cloneTree(child)); + + return newNode; + } + + private: + unordered_map map; +}; diff --git a/solutions/1490. Clone N-ary Tree/1490.java b/solutions/1490. Clone N-ary Tree/1490.java new file mode 100644 index 00000000000..62fc858d43f --- /dev/null +++ b/solutions/1490. Clone N-ary Tree/1490.java @@ -0,0 +1,18 @@ +class Solution { + public Node cloneTree(Node root) { + if (root == null) + return null; + if (map.containsKey(root)) + return map.get(root); + + Node newNode = new Node(root.val); + map.put(root, newNode); + + for (Node child : root.children) + newNode.children.add(cloneTree(child)); + + return newNode; + } + + private Map map = new HashMap<>(); +} diff --git a/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.cpp b/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.cpp new file mode 100644 index 00000000000..5fcfdb7c1bc --- /dev/null +++ b/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + double average(vector& salary) { + const double sum = accumulate(salary.begin(), salary.end(), 0.0); + const int mx = ranges::max(salary); + const int mn = ranges::min(salary); + return (sum - mx - mn) / (salary.size() - 2); + } +}; diff --git a/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.java b/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.java new file mode 100644 index 00000000000..23d45eaa268 --- /dev/null +++ b/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.java @@ -0,0 +1,8 @@ +class Solution { + public double average(int[] salary) { + final double sum = Arrays.stream(salary).sum(); + final int mx = Arrays.stream(salary).max().getAsInt(); + final int mn = Arrays.stream(salary).min().getAsInt(); + return (sum - mx - mn) / (salary.length - 2); + } +} diff --git a/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.py b/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.py new file mode 100644 index 00000000000..b811945853b --- /dev/null +++ b/solutions/1491. Average Salary Excluding the Minimum and Maximum Salary/1491.py @@ -0,0 +1,3 @@ +class Solution: + def average(self, salary: List[int]) -> float: + return (sum(salary) - max(salary) - min(salary)) / (len(salary) - 2) diff --git a/solutions/1492. The kth Factor of n/1492.cpp b/solutions/1492. The kth Factor of n/1492.cpp new file mode 100644 index 00000000000..16a9f82681b --- /dev/null +++ b/solutions/1492. The kth Factor of n/1492.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int kthFactor(int n, int k) { + // If i is a divisor of n, then n / i is also a divisor of n. So, we can + // find all the divisors of n by processing the numbers <= sqrt(n). + int factor = 1; + int i = 0; // the i-th factor + + for (; factor * factor < n; ++factor) + if (n % factor == 0 && ++i == k) + return factor; + + for (factor = n / factor; factor >= 1; --factor) + if (n % factor == 0 && ++i == k) + return n / factor; + + return -1; + } +}; diff --git a/solutions/1492. The kth Factor of n/1492.java b/solutions/1492. The kth Factor of n/1492.java new file mode 100644 index 00000000000..f5ca3931285 --- /dev/null +++ b/solutions/1492. The kth Factor of n/1492.java @@ -0,0 +1,18 @@ +class Solution { + public int kthFactor(int n, int k) { + // If i is a divisor of n, then n / i is also a divisor of n. So, we can + // find all the divisors of n by processing the numbers <= sqrt(n). + int factor = 1; + int i = 0; // the i-th factor + + for (; factor * factor < n; ++factor) + if (n % factor == 0 && ++i == k) + return factor; + + for (factor = n / factor; factor >= 1; --factor) + if (n % factor == 0 && ++i == k) + return n / factor; + + return -1; + } +} diff --git a/solutions/1492. The kth Factor of n/1492.py b/solutions/1492. The kth Factor of n/1492.py new file mode 100644 index 00000000000..197ec7f1f03 --- /dev/null +++ b/solutions/1492. The kth Factor of n/1492.py @@ -0,0 +1,23 @@ +class Solution: + def kthFactor(self, n: int, k: int) -> int: + # If i is a divisor of n, then n // i is also a divisor of n. So, we can + # find all the divisors of n by processing the numbers <= sqrt(n). + factor = 1 + i = 0 # the i-th factor + + while factor < math.isqrt(n): + if n % factor == 0: + i += 1 + if i == k: + return factor + factor += 1 + + factor = n // factor + while factor >= 1: + if n % factor == 0: + i += 1 + if i == k: + return n // factor + factor -= 1 + + return -1 diff --git a/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.cpp b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.cpp new file mode 100644 index 00000000000..fbb17378112 --- /dev/null +++ b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int longestSubarray(vector& nums) { + int l = 0; + int count0 = 0; + + for (const int num : nums) { + if (num == 0) + ++count0; + if (count0 > 1 && nums[l++] == 0) + --count0; + } + + return nums.size() - l - 1; + } +}; diff --git a/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.java b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.java new file mode 100644 index 00000000000..08aca8a3a62 --- /dev/null +++ b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.java @@ -0,0 +1,15 @@ +class Solution { + public int longestSubarray(int[] nums) { + int l = 0; + int count0 = 0; + + for (final int num : nums) { + if (num == 0) + ++count0; + if (count0 > 1 && nums[l++] == 0) + --count0; + } + + return nums.length - l - 1; + } +} diff --git a/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.py b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.py new file mode 100644 index 00000000000..aa22d7ed0e9 --- /dev/null +++ b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.py @@ -0,0 +1,14 @@ +class Solution: + def longestSubarray(self, nums: List[int]) -> int: + l = 0 + count0 = 0 + + for num in nums: + if num == 0: + count0 += 1 + if count0 > 1: + if nums[l] == 0: + count0 -= 1 + l += 1 + + return len(nums) - l - 1 diff --git a/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.cpp b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.cpp new file mode 100644 index 00000000000..c7db2bf08a7 --- /dev/null +++ b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int longestSubarray(vector& nums) { + int ans = 0; + int count0 = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (nums[r] == 0) + ++count0; + while (count0 == 2) + if (nums[l++] == 0) + --count0; + ans = max(ans, r - l); + } + + return ans; + } +}; diff --git a/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.java b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.java new file mode 100644 index 00000000000..3c26d728127 --- /dev/null +++ b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.java @@ -0,0 +1,17 @@ +class Solution { + public int longestSubarray(int[] nums) { + int ans = 0; + int count0 = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (nums[r] == 0) + ++count0; + while (count0 == 2) + if (nums[l++] == 0) + --count0; + ans = Math.max(ans, r - l); + } + + return ans; + } +} diff --git a/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.py b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.py new file mode 100644 index 00000000000..2dce475ff3d --- /dev/null +++ b/solutions/1493. Longest Subarray of 1's After Deleting One Element/1493.py @@ -0,0 +1,16 @@ +class Solution: + def longestSubarray(self, nums: List[int]) -> int: + ans = 0 + count0 = 0 + + l = 0 + for r, num in enumerate(nums): + if num == 0: + count0 += 1 + while count0 == 2: + if nums[l] == 0: + count0 -= 1 + l += 1 + ans = max(ans, r - l) + + return ans diff --git a/solutions/1494. Parallel Courses II/1494.cpp b/solutions/1494. Parallel Courses II/1494.cpp new file mode 100644 index 00000000000..aa9c38049e9 --- /dev/null +++ b/solutions/1494. Parallel Courses II/1494.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int minNumberOfSemesters(int n, vector>& relations, int k) { + // dp[i] := the minimum number of semesters to take the courses, where i is + // the bitmask of the taken courses + vector dp(1 << n, n); + // prereq[i] := the bitmask of all the dependencies of the i-th course + vector prereq(n); + + for (const vector& relation : relations) { + const int prevCourse = relation[0] - 1; + const int nextCourse = relation[1] - 1; + prereq[nextCourse] |= 1 << prevCourse; + } + + dp[0] = 0; // Don't need time to finish 0 course. + + for (int i = 0; i < dp.size(); ++i) { + // the bitmask of all the courses can be taken + int coursesCanBeTaken = 0; + // Can take the j-th course if i contains all of j's prerequisites. + for (int j = 0; j < n; ++j) + if ((i & prereq[j]) == prereq[j]) + coursesCanBeTaken |= 1 << j; + // Don't take any course which is already taken. + // (i represents set of courses that are already taken) + coursesCanBeTaken &= ~i; + // Enumerate every bitmask subset of `coursesCanBeTaken`. + for (unsigned s = coursesCanBeTaken; s > 0; + s = (s - 1) & coursesCanBeTaken) + if (popcount(s) <= k) + // Any combination of courses (if <= k) can be taken now. + // i | s := combining courses taken with courses can be taken. + dp[i | s] = min(dp[i | s], dp[i] + 1); + } + + return dp.back(); + } +}; diff --git a/solutions/1494. Parallel Courses II/1494.java b/solutions/1494. Parallel Courses II/1494.java new file mode 100644 index 00000000000..5c1d81efb38 --- /dev/null +++ b/solutions/1494. Parallel Courses II/1494.java @@ -0,0 +1,38 @@ +class Solution { + public int minNumberOfSemesters(int n, int[][] relations, int k) { + // dp[i] := the minimum number of semesters to take the courses, where i is + // the bitmask of the taken courses + int[] dp = new int[1 << n]; + Arrays.fill(dp, n); + // prereq[i] := the bitmask of all the dependencies of the i-th course + int[] prereq = new int[n]; + + for (int[] r : relations) { + final int prevCourse = r[0] - 1; + final int nextCourse = r[1] - 1; + prereq[nextCourse] |= 1 << prevCourse; + } + + dp[0] = 0; // Don't need time to finish 0 course. + + for (int i = 0; i < dp.size(); ++i) { + // the bitmask of all the courses can be taken + int coursesCanBeTaken = 0; + // Can take the j-th course if i contains all of j's prerequisites. + for (int j = 0; j < n; ++j) + if ((i & prereq[j]) == prereq[j]) + coursesCanBeTaken |= 1 << j; + // Don't take any course which is already taken. + // (i represents set of courses that are already taken) + coursesCanBeTaken &= ~i; + // Enumerate every bitmask subset of `coursesCanBeTaken`. + for (int s = coursesCanBeTaken; s > 0; s = (s - 1) & coursesCanBeTaken) + if (Integer.bitCount(s) <= k) + // Any combination of courses (if <= k) can be taken now. + // i | s := combining courses taken with courses can be taken. + dp[i | s] = Math.min(dp[i | s], dp[i] + 1); + } + + return dp[(1 << n) - 1]; + } +} diff --git a/solutions/1494. Parallel Courses II/1494.py b/solutions/1494. Parallel Courses II/1494.py new file mode 100644 index 00000000000..a225f658b9a --- /dev/null +++ b/solutions/1494. Parallel Courses II/1494.py @@ -0,0 +1,33 @@ +class Solution: + def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int: + # dp[i] := the minimum number of semesters to take the courses, where i is + # the bitmask of the taken courses + dp = [n] * (1 << n) + # prereq[i] := bitmask of all dependencies of course i + prereq = [0] * n + + for prevCourse, nextCourse in relations: + prereq[nextCourse - 1] |= 1 << prevCourse - 1 + + dp[0] = 0 # Don't need time to finish 0 course. + + for i in range(1 << n): + # the bitmask of all the courses can be taken + coursesCanBeTaken = 0 + # Can take the j-th course if i contains all of j's prerequisites. + for j in range(n): + if (i & prereq[j]) == prereq[j]: + coursesCanBeTaken |= 1 << j + # Don't take any course which is already taken. + # (i represents set of courses that are already taken) + coursesCanBeTaken &= ~i + # Enumerate every bitmask subset of `coursesCanBeTaken`. + s = coursesCanBeTaken + while s: + if s.bit_count() <= k: + # Any combination of courses (if <= k) can be taken now. + # i | s := combining courses taken with courses can be taken. + dp[i | s] = min(dp[i | s], dp[i] + 1) + s = (s - 1) & coursesCanBeTaken + + return dp[-1] diff --git a/solutions/1495. Friendly Movies Streamed Last Month/1495.sql b/solutions/1495. Friendly Movies Streamed Last Month/1495.sql new file mode 100644 index 00000000000..b6f4c289854 --- /dev/null +++ b/solutions/1495. Friendly Movies Streamed Last Month/1495.sql @@ -0,0 +1,8 @@ +SELECT DISTINCT Content.title +FROM Content +INNER JOIN TVProgram + USING (content_id) +WHERE + Content.kids_content = 'Y' + AND Content.content_type = 'Movies' + AND DATE_FORMAT(TVProgram.program_date, '%Y-%m') = '2020-06'; diff --git a/solutions/1496. Path Crossing/1496.cpp b/solutions/1496. Path Crossing/1496.cpp new file mode 100644 index 00000000000..a2bcd4158cb --- /dev/null +++ b/solutions/1496. Path Crossing/1496.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + bool isPathCrossing(string path) { + set seen; + + seen.insert(0); + + int x = 0; + int y = 0; + + for (const char c : path) { + switch (c) { + case 'N': + ++y; + break; + case 'S': + --y; + break; + case 'E': + ++x; + break; + case 'W': + --x; + break; + } + const int key = x * 20001 + y; + if (seen.contains(key)) + return true; + seen.insert(key); + } + + return false; + } +}; diff --git a/solutions/1497. Check If Array Pairs Are Divisible by k/1497.cpp b/solutions/1497. Check If Array Pairs Are Divisible by k/1497.cpp new file mode 100644 index 00000000000..ee248e97752 --- /dev/null +++ b/solutions/1497. Check If Array Pairs Are Divisible by k/1497.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool canArrange(vector& arr, int k) { + vector count(k); + + for (int a : arr) { + a %= k; + ++count[a < 0 ? a + k : a]; + } + + if (count[0] % 2 != 0) + return false; + + for (int i = 1; i <= k / 2; ++i) + if (count[i] != count[k - i]) + return false; + + return true; + } +}; diff --git a/solutions/1497. Check If Array Pairs Are Divisible by k/1497.java b/solutions/1497. Check If Array Pairs Are Divisible by k/1497.java new file mode 100644 index 00000000000..12eb338a071 --- /dev/null +++ b/solutions/1497. Check If Array Pairs Are Divisible by k/1497.java @@ -0,0 +1,19 @@ +class Solution { + public boolean canArrange(int[] arr, int k) { + int[] count = new int[k]; + + for (int a : arr) { + a %= k; + ++count[a < 0 ? a + k : a]; + } + + if (count[0] % 2 != 0) + return false; + + for (int i = 1; i <= k / 2; i++) + if (count[i] != count[k - i]) + return false; + + return true; + } +} diff --git a/solutions/1497. Check If Array Pairs Are Divisible by k/1497.py b/solutions/1497. Check If Array Pairs Are Divisible by k/1497.py new file mode 100644 index 00000000000..3d2866ec08e --- /dev/null +++ b/solutions/1497. Check If Array Pairs Are Divisible by k/1497.py @@ -0,0 +1,10 @@ +class Solution: + def canArrange(self, arr: List[int], k: int) -> bool: + count = [0] * k + + for a in arr: + a %= k + count[a if a >= 0 else a + k] += 1 + + return count[0] % 2 == 0 and \ + all(count[i] == count[k - i] for i in range(1, k // 2 + 1)) diff --git a/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.cpp b/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.cpp new file mode 100644 index 00000000000..3afecced3d7 --- /dev/null +++ b/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int numSubseq(vector& nums, int target) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + vector pows(n, 1); // pows[i] = 2^i % kMod + + for (int i = 1; i < n; ++i) + pows[i] = pows[i - 1] * 2 % kMod; + + ranges::sort(nums); + + for (int l = 0, r = n - 1; l <= r;) + if (nums[l] + nums[r] <= target) { + ans += pows[r - l]; + ans %= kMod; + ++l; + } else { + --r; + } + + return ans; + } +}; diff --git a/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.java b/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.java new file mode 100644 index 00000000000..fee017d20e6 --- /dev/null +++ b/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.java @@ -0,0 +1,25 @@ +class Solution { + public int numSubseq(int[] nums, int target) { + final int kMod = 1_000_000_007; + final int n = nums.length; + int ans = 0; + int[] pows = new int[n]; // pows[i] = 2^i % kMod + pows[0] = 1; + + for (int i = 1; i < n; ++i) + pows[i] = pows[i - 1] * 2 % kMod; + + Arrays.sort(nums); + + for (int l = 0, r = n - 1; l <= r;) + if (nums[l] + nums[r] <= target) { + ans += pows[r - l]; + ans %= kMod; + ++l; + } else { + --r; + } + + return ans; + } +} diff --git a/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.py b/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.py new file mode 100644 index 00000000000..7117194ac41 --- /dev/null +++ b/solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.py @@ -0,0 +1,18 @@ +class Solution: + def numSubseq(self, nums: List[int], target: int) -> int: + kMod = 1_000_000_007 + n = len(nums) + ans = 0 + + nums.sort() + + l = 0 + r = n - 1 + while l <= r: + if nums[l] + nums[r] <= target: + ans += pow(2, r - l, kMod) + l += 1 + else: + r -= 1 + + return ans % kMod diff --git a/solutions/1499. Max Value of Equation/1499-2.cpp b/solutions/1499. Max Value of Equation/1499-2.cpp new file mode 100644 index 00000000000..c83a95498d1 --- /dev/null +++ b/solutions/1499. Max Value of Equation/1499-2.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int findMaxValueOfEquation(vector>& points, int k) { + int ans = INT_MIN; + deque> maxQ; // (y - x, x) max queue + + for (const vector& point : points) { + const int x = point[0]; + const int y = point[1]; + // Remove the invalid points, xj - xi > k. + while (!maxQ.empty() && x - maxQ.front().second > k) + maxQ.pop_front(); + if (!maxQ.empty()) + ans = max(ans, x + y + maxQ.front().first); + // Remove the points that contribute less value and have a bigger x. + while (!maxQ.empty() && y - x >= maxQ.back().first) + maxQ.pop_back(); + maxQ.emplace_back(y - x, x); + } + + return ans; + } +}; diff --git a/solutions/1499. Max Value of Equation/1499-2.java b/solutions/1499. Max Value of Equation/1499-2.java new file mode 100644 index 00000000000..f40880970ee --- /dev/null +++ b/solutions/1499. Max Value of Equation/1499-2.java @@ -0,0 +1,22 @@ +class Solution { + public int findMaxValueOfEquation(int[][] points, int k) { + int ans = Integer.MIN_VALUE; + Deque> maxQ = new ArrayDeque<>(); // (y - x, x) + + for (int[] point : points) { + final int x = point[0]; + final int y = point[1]; + // Remove the invalid points, xj - xi > k + while (!maxQ.isEmpty() && x - maxQ.peekFirst().getValue() > k) + maxQ.pollFirst(); + if (!maxQ.isEmpty()) + ans = Math.max(ans, x + y + maxQ.peekFirst().getKey()); + // Remove the points that contribute less value and have a bigger x. + while (!maxQ.isEmpty() && y - x >= maxQ.peekLast().getKey()) + maxQ.pollLast(); + maxQ.offerLast(new Pair<>(y - x, x)); + } + + return ans; + } +} diff --git a/solutions/1499. Max Value of Equation/1499-2.py b/solutions/1499. Max Value of Equation/1499-2.py new file mode 100644 index 00000000000..454f2a66916 --- /dev/null +++ b/solutions/1499. Max Value of Equation/1499-2.py @@ -0,0 +1,17 @@ +class Solution: + def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: + ans = -math.inf + maxQ = collections.deque() # (y - x, x) + + for x, y in points: + # Remove the invalid points, xj - xi > k + while maxQ and x - maxQ[0][1] > k: + maxQ.popleft() + if maxQ: + ans = max(ans, x + y + maxQ[0][0]) + # Remove the points that contribute less value and have a bigger x. + while maxQ and y - x >= maxQ[-1][0]: + maxQ.pop() + maxQ.append((y - x, x)) + + return ans diff --git a/solutions/1499. Max Value of Equation/1499.cpp b/solutions/1499. Max Value of Equation/1499.cpp new file mode 100644 index 00000000000..04c10ab5bd5 --- /dev/null +++ b/solutions/1499. Max Value of Equation/1499.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findMaxValueOfEquation(vector>& points, int k) { + int ans = INT_MIN; + priority_queue> maxHeap; // (y - x, x) + + for (const vector& p : points) { + const int x = p[0]; + const int y = p[1]; + while (!maxHeap.empty() && x - maxHeap.top().second > k) + maxHeap.pop(); + if (!maxHeap.empty()) + ans = max(ans, x + y + maxHeap.top().first); + maxHeap.emplace(y - x, x); + } + + return ans; + } +}; diff --git a/solutions/1499. Max Value of Equation/1499.java b/solutions/1499. Max Value of Equation/1499.java new file mode 100644 index 00000000000..ba2582802c9 --- /dev/null +++ b/solutions/1499. Max Value of Equation/1499.java @@ -0,0 +1,22 @@ +class Solution { + public int findMaxValueOfEquation(int[][] points, int k) { + int ans = Integer.MIN_VALUE; + // (y - x, x) + Queue> maxHeap = + new PriorityQueue<>((a, b) + -> a.getKey().equals(b.getKey()) ? b.getValue() - a.getValue() + : b.getKey() - a.getKey()); + + for (int[] p : points) { + final int x = p[0]; + final int y = p[1]; + while (!maxHeap.isEmpty() && x - maxHeap.peek().getValue() > k) + maxHeap.poll(); + if (!maxHeap.isEmpty()) + ans = Math.max(ans, x + y + maxHeap.peek().getKey()); + maxHeap.offer(new Pair<>(y - x, x)); + } + + return ans; + } +} diff --git a/solutions/1499. Max Value of Equation/1499.py b/solutions/1499. Max Value of Equation/1499.py new file mode 100644 index 00000000000..424f6556e8c --- /dev/null +++ b/solutions/1499. Max Value of Equation/1499.py @@ -0,0 +1,13 @@ +class Solution: + def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: + ans = -math.inf + maxHeap = [] # (y - x, x) + + for x, y in points: + while maxHeap and x + maxHeap[0][1] > k: + heapq.heappop(maxHeap) + if maxHeap: + ans = max(ans, x + y - maxHeap[0][0]) + heapq.heappush(maxHeap, (x - y, -x)) + + return ans diff --git a/solutions/15. 3Sum/15.cpp b/solutions/15. 3Sum/15.cpp new file mode 100644 index 00000000000..da670622c4e --- /dev/null +++ b/solutions/15. 3Sum/15.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector> threeSum(vector& nums) { + if (nums.size() < 3) + return {}; + + vector> ans; + + ranges::sort(nums); + + for (int i = 0; i + 2 < nums.size(); ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + // Choose nums[i] as the first number in the triplet, then search the + // remaining numbers in [i + 1, n - 1]. + int l = i + 1; + int r = nums.size() - 1; + while (l < r) { + const int sum = nums[i] + nums[l] + nums[r]; + if (sum == 0) { + ans.push_back({nums[i], nums[l++], nums[r--]}); + while (l < r && nums[l] == nums[l - 1]) + ++l; + while (l < r && nums[r] == nums[r + 1]) + --r; + } else if (sum < 0) { + ++l; + } else { + --r; + } + } + } + + return ans; + } +}; diff --git a/solutions/15. 3Sum/15.java b/solutions/15. 3Sum/15.java new file mode 100644 index 00000000000..9a8fee9b980 --- /dev/null +++ b/solutions/15. 3Sum/15.java @@ -0,0 +1,35 @@ +class Solution { + public List> threeSum(int[] nums) { + if (nums.length < 3) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + + Arrays.sort(nums); + + for (int i = 0; i + 2 < nums.length; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + // Choose nums[i] as the first number in the triplet, then search the + // remaining numbers in [i + 1, n - 1]. + int l = i + 1; + int r = nums.length - 1; + while (l < r) { + final int sum = nums[i] + nums[l] + nums[r]; + if (sum == 0) { + ans.add(Arrays.asList(nums[i], nums[l++], nums[r--])); + while (l < r && nums[l] == nums[l - 1]) + ++l; + while (l < r && nums[r] == nums[r + 1]) + --r; + } else if (sum < 0) { + ++l; + } else { + --r; + } + } + } + + return ans; + } +} diff --git a/solutions/15. 3Sum/15.py b/solutions/15. 3Sum/15.py new file mode 100644 index 00000000000..dfa36a4ca41 --- /dev/null +++ b/solutions/15. 3Sum/15.py @@ -0,0 +1,32 @@ +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + if len(nums) < 3: + return [] + + ans = [] + + nums.sort() + + for i in range(len(nums) - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + # Choose nums[i] as the first number in the triplet, then search the + # remaining numbers in [i + 1, n - 1]. + l = i + 1 + r = len(nums) - 1 + while l < r: + summ = nums[i] + nums[l] + nums[r] + if summ == 0: + ans.append((nums[i], nums[l], nums[r])) + l += 1 + r -= 1 + while nums[l] == nums[l - 1] and l < r: + l += 1 + while nums[r] == nums[r + 1] and l < r: + r -= 1 + elif summ < 0: + l += 1 + else: + r -= 1 + + return ans diff --git a/solutions/150. Evaluate Reverse Polish Notation/150.cpp b/solutions/150. Evaluate Reverse Polish Notation/150.cpp new file mode 100644 index 00000000000..fdc1b237d18 --- /dev/null +++ b/solutions/150. Evaluate Reverse Polish Notation/150.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int evalRPN(vector& tokens) { + stack stack; + const unordered_map> op{ + {"+", std::plus()}, + {"-", std::minus()}, + {"*", std::multiplies()}, + {"/", std::divides()}}; + + for (const string& token : tokens) + if (op.contains(token)) { + const long b = stack.top(); + stack.pop(); + const long a = stack.top(); + stack.pop(); + stack.push(op.at(token)(a, b)); + } else { + stack.push(stoi(token)); + } + + return stack.top(); + } +}; diff --git a/solutions/150. Evaluate Reverse Polish Notation/150.java b/solutions/150. Evaluate Reverse Polish Notation/150.java new file mode 100644 index 00000000000..29b29452be1 --- /dev/null +++ b/solutions/150. Evaluate Reverse Polish Notation/150.java @@ -0,0 +1,18 @@ +class Solution { + public int evalRPN(String[] tokens) { + final Map> op = Map.of( + "+", (a, b) -> a + b, "-", (a, b) -> a - b, "*", (a, b) -> a * b, "/", (a, b) -> a / b); + Deque stack = new ArrayDeque<>(); + + for (final String token : tokens) + if (op.containsKey(token)) { + final long b = stack.pop(); + final long a = stack.pop(); + stack.push(op.get(token).apply(a, b)); + } else { + stack.push(Long.parseLong(token)); + } + + return stack.pop().intValue(); + } +} diff --git a/solutions/150. Evaluate Reverse Polish Notation/150.py b/solutions/150. Evaluate Reverse Polish Notation/150.py new file mode 100644 index 00000000000..2cc51d6d24e --- /dev/null +++ b/solutions/150. Evaluate Reverse Polish Notation/150.py @@ -0,0 +1,19 @@ +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + stack = [] + op = { + '+': lambda a, b: a + b, + '-': lambda a, b: a - b, + '*': lambda a, b: a * b, + '/': lambda a, b: int(a / b), + } + + for token in tokens: + if token in op: + b = stack.pop() + a = stack.pop() + stack.append(op[token](a, b)) + else: + stack.append(int(token)) + + return stack.pop() diff --git a/solutions/1500. Design a File Sharing System/1500.cpp b/solutions/1500. Design a File Sharing System/1500.cpp new file mode 100644 index 00000000000..7d1c7f52319 --- /dev/null +++ b/solutions/1500. Design a File Sharing System/1500.cpp @@ -0,0 +1,45 @@ +class FileSharing { + public: + FileSharing(int m) {} + + int join(vector ownedChunks) { + const int userId = getMinUserId(); + userToChunks[userId] = {ownedChunks.begin(), ownedChunks.end()}; + for (const int chunk : ownedChunks) + chunkToUsers[chunk].insert(userId); + return userId; + } + + void leave(int userID) { + for (const int chunk : userToChunks[userID]) { + chunkToUsers[chunk].erase(userID); + if (chunkToUsers[chunk].empty()) + chunkToUsers.erase(chunk); + } + userToChunks.erase(userID); + availableUserIds.push(userID); + } + + vector request(int userID, int chunkID) { + const auto it = chunkToUsers.find(chunkID); + if (it == chunkToUsers.end()) + return {}; + vector userIds{it->second.begin(), it->second.end()}; + userToChunks[userID].insert(chunkID); + chunkToUsers[chunkID].insert(userID); + return userIds; + } + + private: + unordered_map> userToChunks; + unordered_map> chunkToUsers; + priority_queue, greater<>> availableUserIds; + + int getMinUserId() { + if (availableUserIds.empty()) + return userToChunks.size() + 1; + const int minUserId = availableUserIds.top(); + availableUserIds.pop(); + return minUserId; + } +}; diff --git a/solutions/1500. Design a File Sharing System/1500.java b/solutions/1500. Design a File Sharing System/1500.java new file mode 100644 index 00000000000..a8030d6be07 --- /dev/null +++ b/solutions/1500. Design a File Sharing System/1500.java @@ -0,0 +1,35 @@ +class FileSharing { + public int join(List ownedChunks) { + final int userId = + availableUserIds.isEmpty() ? userToChunks.size() + 1 : availableUserIds.poll(); + userToChunks.put(userId, new HashSet<>(ownedChunks)); + for (final int chunk : ownedChunks) { + chunkToUsers.putIfAbsent(chunk, new TreeSet<>()); + chunkToUsers.get(chunk).add(userId); + } + return userId; + } + + public void leave(int userID) { + for (final int chunk : userToChunks.get(userID)) { + chunkToUsers.get(chunk).remove(userID); + if (chunkToUsers.get(chunk).isEmpty()) + chunkToUsers.remove(chunk); + } + userToChunks.remove(userID); + availableUserIds.offer(userID); + } + + public List request(int userID, int chunkID) { + if (!chunkToUsers.containsKey(chunkID)) + return new ArrayList<>(); + List userIds = new ArrayList<>(chunkToUsers.get(chunkID)); + userToChunks.get(userID).add(chunkID); + chunkToUsers.get(chunkID).add(userID); + return userIds; + } + + private Map> userToChunks = new HashMap<>(); + private Map> chunkToUsers = new HashMap<>(); + private Queue availableUserIds = new PriorityQueue<>(); +} diff --git a/solutions/1500. Design a File Sharing System/1500.py b/solutions/1500. Design a File Sharing System/1500.py new file mode 100644 index 00000000000..8b3446a74a6 --- /dev/null +++ b/solutions/1500. Design a File Sharing System/1500.py @@ -0,0 +1,34 @@ +from sortedcontainers import SortedSet + + +class FileSharing: + def __init__(self, m: int): + self.userToChunks: Dict[int, SortedSet[int]] = {} + self.chunkToUsers: Dict[int, SortedSet[int]] = {} + self.availableUserIds: List[int] = [] + + def join(self, ownedChunks: List[int]) -> int: + userId = heapq.heappop(self.availableUserIds) if self.availableUserIds \ + else len(self.userToChunks) + 1 + self.userToChunks[userId] = SortedSet(ownedChunks) + for chunk in ownedChunks: + self.chunkToUsers.setdefault(chunk, SortedSet()).add(userId) + return userId + + def leave(self, userID: int) -> None: + if userID not in self.userToChunks: + return + for chunk in self.userToChunks[userID]: + self.chunkToUsers[chunk].discard(userID) + if not self.chunkToUsers[chunk]: + del self.chunkToUsers[chunk] + del self.userToChunks[userID] + heapq.heappush(self.availableUserIds, userID) + + def request(self, userID: int, chunkID: int) -> List[int]: + if chunkID not in self.chunkToUsers: + return [] + userIds = list(self.chunkToUsers[chunkID]) + self.userToChunks[userID].add(chunkID) + self.chunkToUsers[chunkID].add(userID) + return userIds diff --git a/solutions/1501. Countries You Can Safely Invest In/1501.sql b/solutions/1501. Countries You Can Safely Invest In/1501.sql new file mode 100644 index 00000000000..b85ac97ed02 --- /dev/null +++ b/solutions/1501. Countries You Can Safely Invest In/1501.sql @@ -0,0 +1,10 @@ +SELECT Country.name AS country +FROM Person +INNER JOIN Country + ON (SUBSTRING(Person.phone_number, 1, 3) = Country.country_code) +INNER JOIN Calls + ON (Person.id IN (Calls.caller_id, Calls.callee_id)) +GROUP BY 1 +HAVING AVG(Calls.duration) > ( + SELECT AVG(duration) FROM Calls + ); diff --git a/solutions/1502. Can Make Arithmetic Progression From Sequence/1502-2.cpp b/solutions/1502. Can Make Arithmetic Progression From Sequence/1502-2.cpp new file mode 100644 index 00000000000..449badd9b14 --- /dev/null +++ b/solutions/1502. Can Make Arithmetic Progression From Sequence/1502-2.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool canMakeArithmeticProgression(vector& arr) { + const int n = arr.size(); + const int mx = ranges::max(arr); + const int mn = ranges::min(arr); + const int range = mx - mn; + if (range % (n - 1) != 0) + return false; + const int diff = range / (n - 1); + if (diff == 0) + return true; + + for (int i = 0; i < n;) { + const int gap = arr[i] - mn; + if (gap % diff != 0) + return false; + if (gap == i * diff) { + ++i; + } else { + const int rightIndex = gap / diff; + swap(arr[i], arr[rightIndex]); + } + } + + return true; + } +}; diff --git a/solutions/1502. Can Make Arithmetic Progression From Sequence/1502.cpp b/solutions/1502. Can Make Arithmetic Progression From Sequence/1502.cpp new file mode 100644 index 00000000000..34e63e19f7f --- /dev/null +++ b/solutions/1502. Can Make Arithmetic Progression From Sequence/1502.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool canMakeArithmeticProgression(vector& arr) { + const int n = arr.size(); + const int mx = ranges::max(arr); + const int mn = ranges::min(arr); + const int range = mx - mn; + if (range % (n - 1) != 0) + return false; + const int diff = range / (n - 1); + if (diff == 0) + return true; + + unordered_set seen; + + for (const int a : arr) { + if ((a - min) % diff != 0) + return false; + if (!seen.insert(a).second) + return false; + } + + return true; + } +}; diff --git a/solutions/1503. Last Moment Before All Ants Fall Out of a Plank/1503.cpp b/solutions/1503. Last Moment Before All Ants Fall Out of a Plank/1503.cpp new file mode 100644 index 00000000000..ead6336c7c4 --- /dev/null +++ b/solutions/1503. Last Moment Before All Ants Fall Out of a Plank/1503.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int getLastMoment(int n, vector& left, vector& right) { + const int maxLeft = left.empty() ? 0 : ranges::max(left); + const int minRight = right.empty() ? n : ranges::min(right); + return max(maxLeft, n - minRight); + } +}; diff --git a/solutions/1504. Count Submatrices With All Ones/1504-2.cpp b/solutions/1504. Count Submatrices With All Ones/1504-2.cpp new file mode 100644 index 00000000000..df4a283a87c --- /dev/null +++ b/solutions/1504. Count Submatrices With All Ones/1504-2.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int numSubmat(vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + int ans = 0; + vector hist(n); + + for (const vector& row : mat) { + for (int i = 0; i < row.size(); ++i) + hist[i] = row[i] == 0 ? 0 : hist[i] + 1; + ans += count(hist); + } + + return ans; + } + + private: + int count(const vector& A) { + // submatrices[i] := the number of submatrices, where the i-th column is the + // right border + vector submatrices(A.size()); + stack stack; + + for (int i = 0; i < A.size(); ++i) { + while (!stack.empty() && A[stack.top()] >= A[i]) + stack.pop(); + if (!stack.empty()) { + const int prevIndex = stack.top(); + submatrices[i] = submatrices[prevIndex] + A[i] * (i - prevIndex); + } else { + submatrices[i] = A[i] * (i + 1); + } + stack.push(i); + } + + return accumulate(submatrices.begin(), submatrices.end(), 0); + } +}; diff --git a/solutions/1504. Count Submatrices With All Ones/1504-2.java b/solutions/1504. Count Submatrices With All Ones/1504-2.java new file mode 100644 index 00000000000..c48c7a154fc --- /dev/null +++ b/solutions/1504. Count Submatrices With All Ones/1504-2.java @@ -0,0 +1,36 @@ +class Solution { + public int numSubmat(int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + int ans = 0; + int[] hist = new int[n]; + + for (int[] row : mat) { + for (int i = 0; i < row.length; ++i) + hist[i] = row[i] == 0 ? 0 : hist[i] + 1; + ans += count(hist); + } + + return ans; + } + + private int count(int[] A) { + // submatrices[i] := the number of submatrices, where the i-th column is the right border + int[] submatrices = new int[A.length]; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < A.length; ++i) { + while (!stack.isEmpty() && A[stack.peek()] >= A[i]) + stack.pop(); + if (!stack.isEmpty()) { + final int prevIndex = stack.peek(); + submatrices[i] = submatrices[prevIndex] + A[i] * (i - prevIndex); + } else { + submatrices[i] = A[i] * (i + 1); + } + stack.push(i); + } + + return Arrays.stream(submatrices).sum(); + } +} diff --git a/solutions/1504. Count Submatrices With All Ones/1504.cpp b/solutions/1504. Count Submatrices With All Ones/1504.cpp new file mode 100644 index 00000000000..d70613eb512 --- /dev/null +++ b/solutions/1504. Count Submatrices With All Ones/1504.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int numSubmat(vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + int ans = 0; + + for (int baseRow = 0; baseRow < m; ++baseRow) { + vector row(n, 1); + for (int i = baseRow; i < m; ++i) { + for (int j = 0; j < n; ++j) + row[j] &= mat[i][j]; + ans += count(row); + } + } + + return ans; + } + + private: + int count(vector& row) { + int ans = 0; + int length = 0; + + for (const int a : row) { + length = a == 0 ? 0 : length + 1; + ans += length; + } + + return ans; + } +}; diff --git a/solutions/1504. Count Submatrices With All Ones/1504.java b/solutions/1504. Count Submatrices With All Ones/1504.java new file mode 100644 index 00000000000..3748a6d2927 --- /dev/null +++ b/solutions/1504. Count Submatrices With All Ones/1504.java @@ -0,0 +1,31 @@ +class Solution { + public int numSubmat(int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + int ans = 0; + + for (int baseRow = 0; baseRow < m; ++baseRow) { + int[] row = new int[n]; + Arrays.fill(row, 1); + for (int i = baseRow; i < m; ++i) { + for (int j = 0; j < n; ++j) + row[j] &= mat[i][j]; + ans += count(row); + } + } + + return ans; + } + + private int count(int[] row) { + int ans = 0; + int length = 0; + + for (final int a : row) { + length = a == 0 ? 0 : length + 1; + ans += length; + } + + return ans; + } +} diff --git a/solutions/1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits/1505.cpp b/solutions/1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits/1505.cpp new file mode 100644 index 00000000000..50d21fc6cf3 --- /dev/null +++ b/solutions/1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits/1505.cpp @@ -0,0 +1,63 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + string minInteger(string num, int k) { + const int n = num.length(); + string ans; + FenwickTree tree(n); + vector used(n); + vector> numToIndices(10); + + for (int i = 0; i < n; ++i) + numToIndices[num[i] - '0'].push(i); + + while (k > 0 && ans.length() < n) + for (int d = 0; d < 10; ++d) { + if (numToIndices[d].empty()) + continue; + const int i = numToIndices[d].front(); + const int cost = i - tree.get(i); + if (cost > k) + continue; + k -= cost; + ans += '0' + d; + used[i] = true; + tree.add(i + 1, 1); + numToIndices[d].pop(); + break; // Scan from 0 -> 9 again. + } + + for (int i = 0; i < n; ++i) + if (!used[i]) + ans += num[i]; + + return ans; + } +}; diff --git a/solutions/1506. Find Root of N-Ary Tree/1506.cpp b/solutions/1506. Find Root of N-Ary Tree/1506.cpp new file mode 100644 index 00000000000..42b26e62d58 --- /dev/null +++ b/solutions/1506. Find Root of N-Ary Tree/1506.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + Node* findRoot(vector tree) { + int sum = 0; + + for (Node* node : tree) { + sum ^= node->val; + for (Node* child : node->children) + sum ^= child->val; + } + + for (Node* node : tree) + if (node->val == sum) + return node; + + throw; + } +}; diff --git a/solutions/1506. Find Root of N-Ary Tree/1506.java b/solutions/1506. Find Root of N-Ary Tree/1506.java new file mode 100644 index 00000000000..795cd786678 --- /dev/null +++ b/solutions/1506. Find Root of N-Ary Tree/1506.java @@ -0,0 +1,17 @@ +class Solution { + public Node findRoot(List tree) { + int sum = 0; + + for (Node node : tree) { + sum ^= node.val; + for (Node child : node.children) + sum ^= child.val; + } + + for (Node node : tree) + if (node.val == sum) + return node; + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1506. Find Root of N-Ary Tree/1506.py b/solutions/1506. Find Root of N-Ary Tree/1506.py new file mode 100644 index 00000000000..081306471ca --- /dev/null +++ b/solutions/1506. Find Root of N-Ary Tree/1506.py @@ -0,0 +1,12 @@ +class Solution: + def findRoot(self, tree: List['Node']) -> 'Node': + sum = 0 + + for node in tree: + sum ^= node.val + for child in node.children: + sum ^= child.val + + for node in tree: + if node.val == sum: + return node diff --git a/solutions/1507. Reformat Date/1507.cpp b/solutions/1507. Reformat Date/1507.cpp new file mode 100644 index 00000000000..8f3b05a429e --- /dev/null +++ b/solutions/1507. Reformat Date/1507.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string reformatDate(string date) { + const unordered_map monthToNumString{ + {"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 int index1 = date.find_first_of(' '); + const int index2 = date.find_first_of(' ', index1 + 1); + const string day = index1 == 4 ? date.substr(0, 2) : string("0") + date[0]; + const string month = + monthToNumString.at(date.substr(index1 + 1, index2 - (index1 + 1))); + const string year = date.substr(index2 + 1); + return year + "-" + month + "-" + day; + } +}; diff --git a/solutions/1507. Reformat Date/1507.java b/solutions/1507. Reformat Date/1507.java new file mode 100644 index 00000000000..177d941214b --- /dev/null +++ b/solutions/1507. Reformat Date/1507.java @@ -0,0 +1,28 @@ +class Solution { + public String reformatDate(String date) { + Map months = getMonths(); + String[] words = date.split("\\s+"); + final String day = + (words[0].length() == 4) ? words[0].substring(0, 2) : "0" + words[0].substring(0, 1); + final String month = months.get(words[1]); + final String year = words[2]; + return year + "-" + month + "-" + day; + } + + private Map getMonths() { + Map months = new HashMap<>(); + months.put("Jan", "01"); + months.put("Feb", "02"); + months.put("Mar", "03"); + months.put("Apr", "04"); + months.put("May", "05"); + months.put("Jun", "06"); + months.put("Jul", "07"); + months.put("Aug", "08"); + months.put("Sep", "09"); + months.put("Oct", "10"); + months.put("Nov", "11"); + months.put("Dec", "12"); + return months; + } +} diff --git a/solutions/1507. Reformat Date/1507.py b/solutions/1507. Reformat Date/1507.py new file mode 100644 index 00000000000..62661102489 --- /dev/null +++ b/solutions/1507. Reformat Date/1507.py @@ -0,0 +1,10 @@ +class Solution: + def reformatDate(self, date: str) -> str: + monthToNumString = { + '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] if len(day) == 4 else '0' + day[:-2] + return f'{year}-{monthToNumString[month]}-{day}' diff --git a/solutions/1508. Range Sum of Sorted Subarray Sums/1508.cpp b/solutions/1508. Range Sum of Sorted Subarray Sums/1508.cpp new file mode 100644 index 00000000000..5048cd541e8 --- /dev/null +++ b/solutions/1508. Range Sum of Sorted Subarray Sums/1508.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + int rangeSum(vector& nums, int n, int left, int right) { + constexpr int kMod = 1'000'000'007; + + auto subarraysAndSumNoGreaterThan = [&](int m) -> pair { + int count = 0; // the number of subarrays <= m + long total = 0; // sum(subarrays) + int sum = 0; // the current sum + int window = 0; // the window sum + + for (int i = 0, j = 0; j < n; ++j) { + sum += nums[j] * (j - i + 1); + window += nums[j]; // Extend each subarray that ends in j. + while (window > m) { + sum -= window; + window -= nums[i++]; // Shrink the window. + } + count += j - i + 1; + total += sum; + } + + return {count, total}; + }; + + // [L, R] is the possible range of the sum of any subarray. + const int L = ranges::min(nums); + const int R = accumulate(nums.begin(), nums.end(), 0); + + auto firstKSubarraysSum = [&](int k) -> long { + int l = L; + int r = R; + + while (l < r) { + const int m = l + (r - l) / 2; + if (subarraysAndSumNoGreaterThan(m).first < k) + l = m + 1; + else + r = m; + } + + const auto& [count, total] = subarraysAndSumNoGreaterThan(l); + // If count != k, there're subarray(s) have the same sum as l. + return total - l * (count - k); + }; + + return (firstKSubarraysSum(right) - firstKSubarraysSum(left - 1)) % kMod; + } +}; diff --git a/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.cpp b/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.cpp new file mode 100644 index 00000000000..c2ca3de5752 --- /dev/null +++ b/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minDifference(vector& nums) { + const int n = nums.size(); + if (n < 5) + return 0; + + int ans = INT_MAX; + + ranges::sort(nums); + + // 1. Change nums[0..i) to nums[i]. + // 2. Change nums[n - 3 + i..n) to nums[n - 4 + i]. + for (int i = 0; i <= 3; ++i) + ans = min(ans, nums[n - 4 + i] - nums[i]); + + return ans; + } +}; diff --git a/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.java b/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.java new file mode 100644 index 00000000000..5cb3ec96c84 --- /dev/null +++ b/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.java @@ -0,0 +1,18 @@ +class Solution { + public int minDifference(int[] nums) { + final int n = nums.length; + if (n < 5) + return 0; + + int ans = Integer.MAX_VALUE; + + Arrays.sort(nums); + + // 1. Change nums[0..i) to nums[i]. + // 2. Change nums[n - 3 + i..n) to nums[n - 4 + i]. + for (int i = 0; i <= 3; ++i) + ans = Math.min(ans, nums[n - 4 + i] - nums[i]); + + return ans; + } +} diff --git a/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.py b/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.py new file mode 100644 index 00000000000..db30d4d4e0b --- /dev/null +++ b/solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.py @@ -0,0 +1,16 @@ +class Solution: + def minDifference(self, nums: List[int]) -> int: + n = len(nums) + if n < 5: + return 0 + + ans = math.inf + + nums.sort() + + # 1. Change nums[0..i) to nums[i]. + # 2. Change nums[n - 3 + i..n) to nums[n - 4 + i]. + for i in range(4): + ans = min(ans, nums[n - 4 + i] - nums[i]) + + return ans diff --git a/solutions/151. Reverse Words in a String/151.cpp b/solutions/151. Reverse Words in a String/151.cpp new file mode 100644 index 00000000000..1c818913bfc --- /dev/null +++ b/solutions/151. Reverse Words in a String/151.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + string reverseWords(string s) { + reverse(s.begin(), s.end()); // Reverse the whole string. + reverseWords(s, s.length()); // Reverse each word. + return cleanSpaces(s, s.length()); // Clean up the spaces. + } + + private: + void reverseWords(string& s, int n) { + int i = 0; + int j = 0; + + while (i < n) { + while (i < j || i < n && s[i] == ' ') // Skip the spaces. + ++i; + while (j < i || j < n && s[j] != ' ') // Skip the spaces. + ++j; + reverse(s.begin() + i, s.begin() + j); // Reverse the word. + } + } + + // Trim leading, trailing, and middle spaces + string cleanSpaces(string& s, int n) { + int i = 0; + int j = 0; + + while (j < n) { + while (j < n && s[j] == ' ') // Skip the spaces. + ++j; + while (j < n && s[j] != ' ') // Keep non spaces + s[i++] = s[j++]; + while (j < n && s[j] == ' ') // Skip the spaces. + ++j; + if (j < n) // Keep only one space. + s[i++] = ' '; + } + + return s.substr(0, i); + } +}; diff --git a/solutions/151. Reverse Words in a String/151.java b/solutions/151. Reverse Words in a String/151.java new file mode 100644 index 00000000000..6b55b6ad4d6 --- /dev/null +++ b/solutions/151. Reverse Words in a String/151.java @@ -0,0 +1,47 @@ +class Solution { + public String reverseWords(String s) { + StringBuilder sb = new StringBuilder(s).reverse(); // Reverse the whole string. + reverseWords(sb, sb.length()); // Reverse each word. + return cleanSpaces(sb, sb.length()); // Clean up the spaces. + } + + private void reverseWords(StringBuilder sb, int n) { + int i = 0; + int j = 0; + + while (i < n) { + while (i < j || i < n && sb.charAt(i) == ' ') // Skip the spaces. + ++i; + while (j < i || j < n && sb.charAt(j) != ' ') // Skip the spaces. + ++j; + reverse(sb, i, j - 1); // Reverse the word. + } + } + + // Trim leading, trailing, and middle spaces + private String cleanSpaces(StringBuilder sb, int n) { + int i = 0; + int j = 0; + + while (j < n) { + while (j < n && sb.charAt(j) == ' ') // Skip the spaces. + ++j; + while (j < n && sb.charAt(j) != ' ') // Keep non spaces + sb.setCharAt(i++, sb.charAt(j++)); + while (j < n && sb.charAt(j) == ' ') // Skip the spaces. + ++j; + if (j < n) // Keep only one space. + sb.setCharAt(i++, ' '); + } + + return sb.substring(0, i).toString(); + } + + private void reverse(StringBuilder sb, int l, int r) { + while (l < r) { + final char temp = sb.charAt(l); + sb.setCharAt(l++, sb.charAt(r)); + sb.setCharAt(r--, temp); + } + } +} diff --git a/solutions/151. Reverse Words in a String/151.py b/solutions/151. Reverse Words in a String/151.py new file mode 100644 index 00000000000..a6dd5d4dc4c --- /dev/null +++ b/solutions/151. Reverse Words in a String/151.py @@ -0,0 +1,3 @@ +class Solution: + def reverseWords(self, s: str) -> str: + return ' '.join(reversed(s.split())) diff --git a/solutions/1510. Stone Game IV/1510.cpp b/solutions/1510. Stone Game IV/1510.cpp new file mode 100644 index 00000000000..f4aa21b481c --- /dev/null +++ b/solutions/1510. Stone Game IV/1510.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool winnerSquareGame(int n) { + // dp[i] := the winning result for n = i + vector dp(n + 1); + + for (int i = 1; i <= n; ++i) + for (int j = 1; j * j <= i; ++j) + if (!dp[i - j * j]) { // Removing j^2 stones make the opponent lose. + dp[i] = true; // So, we win. + break; + } + + return dp[n]; + } +}; diff --git a/solutions/1510. Stone Game IV/1510.java b/solutions/1510. Stone Game IV/1510.java new file mode 100644 index 00000000000..43cb872e0bf --- /dev/null +++ b/solutions/1510. Stone Game IV/1510.java @@ -0,0 +1,15 @@ +class Solution { + public boolean winnerSquareGame(int n) { + // dp[i] := the winning result for n = i + boolean[] dp = new boolean[n + 1]; + + for (int i = 1; i <= n; ++i) + for (int j = 1; j * j <= i; ++j) + if (!dp[i - j * j]) { // Removing j^2 stones make the opponent lose. + dp[i] = true; // So, we win. + break; + } + + return dp[n]; + } +} diff --git a/solutions/1511. Customer Order Frequency/1511.sql b/solutions/1511. Customer Order Frequency/1511.sql new file mode 100644 index 00000000000..0a1e26922d5 --- /dev/null +++ b/solutions/1511. Customer Order Frequency/1511.sql @@ -0,0 +1,24 @@ +SELECT + Customers.customer_id, + Customers.name +FROM Customers +INNER JOIN Orders + USING (customer_id) +INNER JOIN Product + USING (product_id) +GROUP BY 1 +HAVING + SUM( + IF( + DATE_FORMAT(Orders.order_date, '%Y-%m') = '2020-06', + Orders.quantity * price, + 0 + ) + ) >= 100 + AND SUM( + IF( + DATE_FORMAT(Orders.order_date, '%Y-%m') = '2020-07', + Orders.quantity * price, + 0 + ) + ) >= 100; diff --git a/solutions/1512. Number of Good Pairs/1512.cpp b/solutions/1512. Number of Good Pairs/1512.cpp new file mode 100644 index 00000000000..b95a05026a4 --- /dev/null +++ b/solutions/1512. Number of Good Pairs/1512.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int numIdenticalPairs(vector& nums) { + int ans = 0; + vector count(101); + + for (const int num : nums) + ans += count[num]++; + + return ans; + } +}; diff --git a/solutions/1513. Number of Substrings With Only 1s/1513.cpp b/solutions/1513. Number of Substrings With Only 1s/1513.cpp new file mode 100644 index 00000000000..47277e811a3 --- /dev/null +++ b/solutions/1513. Number of Substrings With Only 1s/1513.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int numSub(string s) { + constexpr int kMod = 1'000'000'007; + + int ans = 0; + int l = -1; + + for (int i = 0; i < s.length(); ++i) { + if (s[i] == '0') + l = i; // Handle the reset value. + ans = (ans + i - l) % kMod; + } + + return ans; + } +}; diff --git a/solutions/1514. Path with Maximum Probability/1514.cpp b/solutions/1514. Path with Maximum Probability/1514.cpp new file mode 100644 index 00000000000..c45d05ec014 --- /dev/null +++ b/solutions/1514. Path with Maximum Probability/1514.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + double maxProbability(int n, vector>& edges, + vector& succProb, int start, int end) { + // {a: [(b, probability_ab)]} + vector>> graph(n); + // (the probability to reach u, u) + priority_queue> maxHeap; + maxHeap.emplace(1.0, start); + vector seen(n); + + for (int i = 0; i < edges.size(); ++i) { + const int u = edges[i][0]; + const int v = edges[i][1]; + const double prob = succProb[i]; + graph[u].emplace_back(v, prob); + graph[v].emplace_back(u, prob); + } + + while (!maxHeap.empty()) { + const auto [prob, u] = maxHeap.top(); + maxHeap.pop(); + if (u == end) + return prob; + if (seen[u]) + continue; + seen[u] = true; + for (const auto& [nextNode, edgeProb] : graph[u]) { + if (seen[nextNode]) + continue; + maxHeap.emplace(prob * edgeProb, nextNode); + } + } + + return 0; + } +}; diff --git a/solutions/1514. Path with Maximum Probability/1514.java b/solutions/1514. Path with Maximum Probability/1514.java new file mode 100644 index 00000000000..6c08a555423 --- /dev/null +++ b/solutions/1514. Path with Maximum Probability/1514.java @@ -0,0 +1,42 @@ +class Solution { + public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { + // {a: [(b, probability_ab)]} + List>[] graph = new List[n]; + // (the probability to reach u, u) + Queue> maxHeap = + new PriorityQueue<>((a, b) -> Double.compare(b.getKey(), a.getKey())); + + maxHeap.offer(new Pair<>(1.0, start)); + boolean[] seen = new boolean[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int i = 0; i < edges.length; ++i) { + final int u = edges[i][0]; + final int v = edges[i][1]; + final double prob = succProb[i]; + graph[u].add(new Pair<>(v, prob)); + graph[v].add(new Pair<>(u, prob)); + } + + while (!maxHeap.isEmpty()) { + final double prob = maxHeap.peek().getKey(); + final int u = maxHeap.poll().getValue(); + if (u == end) + return prob; + if (seen[u]) + continue; + seen[u] = true; + for (Pair node : graph[u]) { + final int nextNode = node.getKey(); + final double edgeProb = node.getValue(); + if (seen[nextNode]) + continue; + maxHeap.add(new Pair<>(prob * edgeProb, nextNode)); + } + } + + return 0; + } +} diff --git a/solutions/1514. Path with Maximum Probability/1514.py b/solutions/1514. Path with Maximum Probability/1514.py new file mode 100644 index 00000000000..720fe668ea2 --- /dev/null +++ b/solutions/1514. Path with Maximum Probability/1514.py @@ -0,0 +1,24 @@ +class Solution: + def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: + graph = [[] for _ in range(n)] # {a: [(b, probability_ab)]} + maxHeap = [(-1.0, start)] # (the probability to reach u, u) + seen = [False] * n + + for i, ((u, v), prob) in enumerate(zip(edges, succProb)): + graph[u].append((v, prob)) + graph[v].append((u, prob)) + + while maxHeap: + prob, u = heapq.heappop(maxHeap) + prob *= -1 + if u == end: + return prob + if seen[u]: + continue + seen[u] = True + for nextNode, edgeProb in graph[u]: + if seen[nextNode]: + continue + heapq.heappush(maxHeap, (-prob * edgeProb, nextNode)) + + return 0 diff --git a/solutions/1515. Best Position for a Service Centre/1515.cpp b/solutions/1515. Best Position for a Service Centre/1515.cpp new file mode 100644 index 00000000000..6bc3e0e4209 --- /dev/null +++ b/solutions/1515. Best Position for a Service Centre/1515.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + double getMinDistSum(vector>& positions) { + constexpr double kErr = 1e-6; + double currX = 50; + double currY = 50; + double ans = distSum(positions, currX, currY); + double step = 1; + + while (step > kErr) { + bool shouldDecreaseStep = true; + for (const auto& [dx, dy] : vector>{ + {0, step}, {0, -step}, {step, 0}, {-step, 0}}) { + const double x = currX + dx; + const double y = currY + dy; + const double newDistSum = distSum(positions, x, y); + if (newDistSum < ans) { + ans = newDistSum; + currX = x; + currY = y; + shouldDecreaseStep = false; + } + } + if (shouldDecreaseStep) + step /= 10; + } + + return ans; + } + + private: + double distSum(const vector>& positions, double a, double b) { + double sum = 0; + for (const vector& p : positions) + sum += sqrt(pow(a - p[0], 2) + pow(b - p[1], 2)); + return sum; + } +}; diff --git a/solutions/1515. Best Position for a Service Centre/1515.java b/solutions/1515. Best Position for a Service Centre/1515.java new file mode 100644 index 00000000000..464f88c6999 --- /dev/null +++ b/solutions/1515. Best Position for a Service Centre/1515.java @@ -0,0 +1,35 @@ +class Solution { + public double getMinDistSum(int[][] positions) { + final double kErr = 1e-6; + double currX = 50; + double currY = 50; + double ans = distSum(positions, currX, currY); + double step = 1; + + while (step > kErr) { + boolean shouldDecreaseStep = true; + for (double[] dirs : new double[][] {{0, step}, {0, -step}, {step, 0}, {-step, 0}}) { + final double x = currX + dirs[0]; + final double y = currY + dirs[1]; + final double newDistSum = distSum(positions, x, y); + if (newDistSum < ans) { + ans = newDistSum; + currX = x; + currY = y; + shouldDecreaseStep = false; + } + } + if (shouldDecreaseStep) + step /= 10; + } + + return ans; + } + + private double distSum(int[][] positions, double a, double b) { + double sum = 0; + for (int[] p : positions) + sum += Math.sqrt(Math.pow(a - p[0], 2) + Math.pow(b - p[1], 2)); + return sum; + } +} diff --git a/solutions/1515. Best Position for a Service Centre/1515.py b/solutions/1515. Best Position for a Service Centre/1515.py new file mode 100644 index 00000000000..2d7d87b0617 --- /dev/null +++ b/solutions/1515. Best Position for a Service Centre/1515.py @@ -0,0 +1,27 @@ +class Solution: + def getMinDistSum(self, positions: List[List[int]]) -> float: + def distSum(a: float, b: float) -> float: + return sum(math.sqrt((a - x)**2 + (b - y)**2) + for x, y in positions) + + kErr = 1e-6 + currX = 50 + currY = 50 + ans = distSum(currX, currY) + step = 1 + + while step > kErr: + shouldDecreaseStep = True + for dx, dy in [(0, step), (0, -step), (step, 0), (-step, 0)]: + x = currX + dx + y = currY + dy + newDistSum = distSum(x, y) + if newDistSum < ans: + ans = newDistSum + currX = x + currY = y + shouldDecreaseStep = False + if shouldDecreaseStep: + step /= 10 + + return ans diff --git a/solutions/1516. Move Sub-Tree of N-Ary Tree/1516.cpp b/solutions/1516. Move Sub-Tree of N-Ary Tree/1516.cpp new file mode 100644 index 00000000000..7a07dc54268 --- /dev/null +++ b/solutions/1516. Move Sub-Tree of N-Ary Tree/1516.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + Node* moveSubTree(Node* root, Node* p, Node* q) { + if (find(q->children.begin(), q->children.end(), p) != q->children.end()) + return root; + + // Create a dummy node for the case when root == p. + Node* dummy = new Node(0, {root}); + + // Get each parent of p and q. + Node* pParent = getParent(dummy, p); + Node* qParent = getParent(p, q); + + // Get p's original index in p's parent. + vector& pSiblings = pParent->children; + const int pIndex = + find(pSiblings.begin(), pSiblings.end(), p) - pSiblings.begin(); + pSiblings.erase(pSiblings.begin() + pIndex); + + q->children.push_back(p); + + // If q is in p's subtree, qParent != nullptr. + if (qParent != nullptr) { + vector& qSiblings = qParent->children; + std::erase(qSiblings, q); + pSiblings.insert(pSiblings.begin() + pIndex, q); + } + + return dummy->children[0]; + } + + private: + Node* getParent(Node* root, Node* target) { + for (Node* child : root->children) { + if (child == target) + return root; + Node* res = getParent(child, target); + if (res != nullptr) + return res; + } + return nullptr; + } +}; diff --git a/solutions/1516. Move Sub-Tree of N-Ary Tree/1516.py b/solutions/1516. Move Sub-Tree of N-Ary Tree/1516.py new file mode 100644 index 00000000000..45734e8afb7 --- /dev/null +++ b/solutions/1516. Move Sub-Tree of N-Ary Tree/1516.py @@ -0,0 +1,33 @@ +class Solution: + def moveSubTree(self, root: 'Node', p: 'Node', q: 'Node') -> 'Node': + if p in q.children: + return root + + # Create a dummy Node for the case when root == p + dummy = Node(None, [root]) + + # Get each parent of p and q + pParent = self._getParent(dummy, p) + qParent = self._getParent(p, q) + + # Get p's original index in p's parent + pIndex = pParent.children.index(p) + pParent.children.pop(pIndex) + + q.children.append(p) + + # If q is in the p's subtree, qParent != None + if qParent: + qParent.children.remove(q) + pParent.children.insert(pIndex, q) + + return dummy.children[0] + + def _getParent(self, root: 'Node', target: 'Node') -> Optional['Node']: + for child in root.children: + if child == target: + return root + res = self._getParent(child, target) + if res: + return res + return None diff --git a/solutions/1517. Find Users With Valid E-Mails/1517.sql b/solutions/1517. Find Users With Valid E-Mails/1517.sql new file mode 100644 index 00000000000..73ca1ea0457 --- /dev/null +++ b/solutions/1517. Find Users With Valid E-Mails/1517.sql @@ -0,0 +1,3 @@ +SELECT * +FROM Users +WHERE REGEXP_LIKE(mail, '^[A-Za-z]+[A-Za-z0-9\_\.\-]*@leetcode\\.com$'); diff --git a/solutions/1518. Water Bottles/1518-2.cpp b/solutions/1518. Water Bottles/1518-2.cpp new file mode 100644 index 00000000000..ec2541be87d --- /dev/null +++ b/solutions/1518. Water Bottles/1518-2.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int numWaterBottles(int numBottles, int numExchange) { + return numBottles + (numBottles - 1) / (numExchange - 1); + } +}; diff --git a/solutions/1518. Water Bottles/1518.cpp b/solutions/1518. Water Bottles/1518.cpp new file mode 100644 index 00000000000..3b18bb835d7 --- /dev/null +++ b/solutions/1518. Water Bottles/1518.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int numWaterBottles(int numBottles, int numExchange) { + int ans = numBottles; + + while (numBottles >= numExchange) { + ans += numBottles / numExchange; + numBottles = numBottles / numExchange + numBottles % numExchange; + } + + return ans; + } +}; diff --git a/solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.cpp b/solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.cpp new file mode 100644 index 00000000000..f8cb89c996c --- /dev/null +++ b/solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector countSubTrees(int n, vector>& edges, string labels) { + vector ans(n); + vector> tree(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + dfs(tree, 0, -1, labels, ans); + return ans; + } + + private: + vector dfs(const vector>& tree, int u, int parent, + const string& labels, vector& ans) { + // count[i] := the number of letters down from ('a' + i) + vector count(26); + + for (const int v : tree[u]) { + if (v == parent) + continue; + vector childCount = dfs(tree, v, u, labels, ans); + for (int i = 0; i < 26; ++i) + count[i] += childCount[i]; + } + + ans[u] = ++count[labels[u] - 'a']; // the u itself + return count; + } +}; diff --git a/solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.java b/solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.java new file mode 100644 index 00000000000..70f1f4adb7b --- /dev/null +++ b/solutions/1519. Number of Nodes in the Sub-Tree With the Same Label/1519.java @@ -0,0 +1,35 @@ +class Solution { + public int[] countSubTrees(int n, int[][] edges, String labels) { + int[] ans = new int[n]; + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + dfs(graph, 0, -1, labels, ans); + return ans; + } + + private int[] dfs(List[] graph, int u, int parent, final String labels, int[] ans) { + // count[i] := the number of letters down from ('a' + i) + int[] count = new int[26]; + + for (final int v : graph[u]) { + if (v == parent) + continue; + int[] childCount = dfs(graph, v, u, labels, ans); + for (int i = 0; i < 26; ++i) + count[i] += childCount[i]; + } + + ans[u] = ++count[labels.charAt(u) - 'a']; // the u itself + return count; + } +} diff --git a/solutions/152. Maximum Product Subarray/152.cpp b/solutions/152. Maximum Product Subarray/152.cpp new file mode 100644 index 00000000000..4c00b8ccfb6 --- /dev/null +++ b/solutions/152. Maximum Product Subarray/152.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int maxProduct(vector& nums) { + int ans = nums[0]; + int dpMin = nums[0]; // the minimum so far + int dpMax = nums[0]; // the maximum so far + + for (int i = 1; i < nums.size(); ++i) { + const int num = nums[i]; + const int prevMin = dpMin; // dpMin[i - 1] + const int prevMax = dpMax; // dpMax[i - 1] + if (num < 0) { + dpMin = min(prevMax * num, num); + dpMax = max(prevMin * num, num); + } else { + dpMin = min(prevMin * num, num); + dpMax = max(prevMax * num, num); + } + ans = max(ans, dpMax); + } + + return ans; + } +}; diff --git a/solutions/152. Maximum Product Subarray/152.java b/solutions/152. Maximum Product Subarray/152.java new file mode 100644 index 00000000000..fb0da9c0e5e --- /dev/null +++ b/solutions/152. Maximum Product Subarray/152.java @@ -0,0 +1,23 @@ +class Solution { + public int maxProduct(int[] nums) { + int ans = nums[0]; + int dpMin = nums[0]; // the minimum so far + int dpMax = nums[0]; // the maximum so far + + for (int i = 1; i < nums.length; ++i) { + final int num = nums[i]; + final int prevMin = dpMin; // dpMin[i - 1] + final int prevMax = dpMax; // dpMax[i - 1] + if (num < 0) { + dpMin = Math.min(prevMax * num, num); + dpMax = Math.max(prevMin * num, num); + } else { + dpMin = Math.min(prevMin * num, num); + dpMax = Math.max(prevMax * num, num); + } + ans = Math.max(ans, dpMax); + } + + return ans; + } +} diff --git a/solutions/152. Maximum Product Subarray/152.py b/solutions/152. Maximum Product Subarray/152.py new file mode 100644 index 00000000000..100049d58c8 --- /dev/null +++ b/solutions/152. Maximum Product Subarray/152.py @@ -0,0 +1,20 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + ans = nums[0] + dpMin = nums[0] # the minimum so far + dpMax = nums[0] # the maximum so far + + for i in range(1, len(nums)): + num = nums[i] + prevMin = dpMin # dpMin[i - 1] + prevMax = dpMax # dpMax[i - 1] + if num < 0: + dpMin = min(prevMax * num, num) + dpMax = max(prevMin * num, num) + else: + dpMin = min(prevMin * num, num) + dpMax = max(prevMax * num, num) + + ans = max(ans, dpMax) + + return ans diff --git a/solutions/1520. Maximum Number of Non-Overlapping Substrings/1520.cpp b/solutions/1520. Maximum Number of Non-Overlapping Substrings/1520.cpp new file mode 100644 index 00000000000..459902e1494 --- /dev/null +++ b/solutions/1520. Maximum Number of Non-Overlapping Substrings/1520.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + vector maxNumOfSubstrings(string s) { + const int n = s.length(); + vector ans; + // leftmost[i] := the leftmost index of ('a' + i) + vector leftmost(26, n); + // rightmost[i] := the rightmost index of ('a' + i) + vector rightmost(26, -1); + + for (int i = 0; i < n; ++i) { + leftmost[s[i] - 'a'] = min(leftmost[s[i] - 'a'], i); + rightmost[s[i] - 'a'] = i; + } + + auto getNewRight = [&](int i) { + int right = rightmost[s[i] - 'a']; + for (int j = i; j <= right; ++j) { + if (leftmost[s[j] - 'a'] < i) // Find a letter's leftmost index < i. + return -1; + // Expand the right dynamically. + right = max(right, rightmost[s[j] - 'a']); + } + return right; + }; + + int right = -1; // the rightmost index of the last substring + for (int i = 0; i < n; ++i) { + // the current index is the first appearance + if (i == leftmost[s[i] - 'a']) { + const int newRight = getNewRight(i); + if (newRight == -1) + continue; // Find a letter's leftmost index < i. + if (i <= right && !ans.empty()) + ans.back() = s.substr(i, newRight - i + 1); + else + ans.push_back(s.substr(i, newRight - i + 1)); + right = newRight; + } + } + + return ans; + } +}; diff --git a/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.cpp b/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.cpp new file mode 100644 index 00000000000..762018e2293 --- /dev/null +++ b/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int closestToTarget(vector& arr, int target) { + int ans = INT_MAX; + // all the values of subarrays that end in the previous number + unordered_set prev; + + for (const int num : arr) { + unordered_set curr{num}; + // Extend each subarray that ends in the previous number. Due to + // monotonicity of the AND operation, the size of `curr` will be at most + // num.bit_count() + 1. + for (const int val : prev) + curr.insert(val & num); + for (const int val : curr) + ans = min(ans, abs(target - val)); + prev = move(curr); + } + + return ans; + } +}; diff --git a/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.java b/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.java new file mode 100644 index 00000000000..49121f0a329 --- /dev/null +++ b/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.java @@ -0,0 +1,21 @@ +class Solution { + public int closestToTarget(int[] arr, int target) { + int ans = Integer.MAX_VALUE; + // all the values of subarrays that end in the previous number + Set prev = new HashSet<>(); + + for (final int num : arr) { + HashSet curr = new HashSet<>(Arrays.asList(num)); + // Extend each subarray that ends in the previous number. Due to + // monotonicity of the AND operation, the size of `curr` will be at most + // Integer.bitCount(num) + 1. + for (final int val : prev) + curr.add(val & num); + for (final int val : curr) + ans = Math.min(ans, Math.abs(target - val)); + prev = curr; + } + + return ans; + } +} diff --git a/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.py b/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.py new file mode 100644 index 00000000000..7b95a8649a9 --- /dev/null +++ b/solutions/1521. Find a Value of a Mysterious Function Closest to Target/1521.py @@ -0,0 +1,13 @@ +class Solution: + def closestToTarget(self, arr: List[int], target: int) -> int: + ans = math.inf + dp = set() # all the values of subarrays that end in the current number + + for num in arr: + # Extend each subarray that ends in the dpious number. Due to + # monotonicity of the AND operation, the size of `dp` will be at most + # num.bit_count() + 1. + dp = {num} | {val & num for val in dp} + ans = min(ans, min(abs(target - val) for val in dp)) + + return ans diff --git a/solutions/1522. Diameter of N-Ary Tree/1522.cpp b/solutions/1522. Diameter of N-Ary Tree/1522.cpp new file mode 100644 index 00000000000..a46c1bac31d --- /dev/null +++ b/solutions/1522. Diameter of N-Ary Tree/1522.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int diameter(Node* root) { + int ans = 0; + maxDepth(root, ans); + return ans; + } + + private: + // Returns the maximum depth of the subtree rooted at `root`. + int maxDepth(Node* root, int& ans) { + int maxSubDepth1 = 0; + int maxSubDepth2 = 0; + for (Node* child : root->children) { + const int maxSubDepth = maxDepth(child, ans); + if (maxSubDepth > maxSubDepth1) { + maxSubDepth2 = maxSubDepth1; + maxSubDepth1 = maxSubDepth; + } else if (maxSubDepth > maxSubDepth2) { + maxSubDepth2 = maxSubDepth; + } + } + ans = max(ans, maxSubDepth1 + maxSubDepth2); + return 1 + maxSubDepth1; + } +}; diff --git a/solutions/1522. Diameter of N-Ary Tree/1522.java b/solutions/1522. Diameter of N-Ary Tree/1522.java new file mode 100644 index 00000000000..0da884ed90b --- /dev/null +++ b/solutions/1522. Diameter of N-Ary Tree/1522.java @@ -0,0 +1,25 @@ +class Solution { + public int diameter(Node root) { + maxDepth(root); + return ans; + } + + private int ans = 0; + + // Returns the maximum depth of the subtree rooted at `root`. + private int maxDepth(Node root) { + int maxSubDepth1 = 0; + int maxSubDepth2 = 0; + for (Node child : root.children) { + final int maxSubDepth = maxDepth(child); + if (maxSubDepth > maxSubDepth1) { + maxSubDepth2 = maxSubDepth1; + maxSubDepth1 = maxSubDepth; + } else if (maxSubDepth > maxSubDepth2) { + maxSubDepth2 = maxSubDepth; + } + } + ans = Math.max(ans, maxSubDepth1 + maxSubDepth2); + return 1 + maxSubDepth1; + } +} diff --git a/solutions/1522. Diameter of N-Ary Tree/1522.py b/solutions/1522. Diameter of N-Ary Tree/1522.py new file mode 100644 index 00000000000..f1d7392f16b --- /dev/null +++ b/solutions/1522. Diameter of N-Ary Tree/1522.py @@ -0,0 +1,21 @@ +class Solution: + def diameter(self, root: 'Node') -> int: + ans = 0 + + def maxDepth(root: 'Node') -> int: + """Returns the maximum depth of the subtree rooted at `root`.""" + nonlocal ans + maxSubDepth1 = 0 + maxSubDepth2 = 0 + for child in root.children: + maxSubDepth = maxDepth(child) + if maxSubDepth > maxSubDepth1: + maxSubDepth2 = maxSubDepth1 + maxSubDepth1 = maxSubDepth + elif maxSubDepth > maxSubDepth2: + maxSubDepth2 = maxSubDepth + ans = max(ans, maxSubDepth1 + maxSubDepth2) + return 1 + maxSubDepth1 + + maxDepth(root) + return ans diff --git a/solutions/1523. Count Odd Numbers in an Interval Range/1523.cpp b/solutions/1523. Count Odd Numbers in an Interval Range/1523.cpp new file mode 100644 index 00000000000..6e72b7f58c3 --- /dev/null +++ b/solutions/1523. Count Odd Numbers in an Interval Range/1523.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int countOdds(int low, int high) { + return (high + 1) / 2 - low / 2; + } +}; diff --git a/solutions/1524. Number of Sub-arrays With Odd Sum/1524-2.cpp b/solutions/1524. Number of Sub-arrays With Odd Sum/1524-2.cpp new file mode 100644 index 00000000000..16f3f784412 --- /dev/null +++ b/solutions/1524. Number of Sub-arrays With Odd Sum/1524-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int numOfSubarrays(vector& arr) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + long dp0 = 0; + long dp1 = 0; + + for (const int a : arr) { + if (a % 2 == 1) { + const int cache = dp0; + dp0 = dp1; + dp1 = cache + 1; + } else { + ++dp0; + } + ans = (ans + dp1) % kMod; + } + + return ans; + } +}; diff --git a/solutions/1524. Number of Sub-arrays With Odd Sum/1524.cpp b/solutions/1524. Number of Sub-arrays With Odd Sum/1524.cpp new file mode 100644 index 00000000000..a8024a240de --- /dev/null +++ b/solutions/1524. Number of Sub-arrays With Odd Sum/1524.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int numOfSubarrays(vector& arr) { + constexpr int kMod = 1'000'000'007; + const int n = arr.size(); + long ans = 0; + // dp0[i] := the number of subarrays that end in arr[i - 1] with an even sum + vector dp0(n + 1); + // dp1[i] := the number of subarrays that end in arr[i - 1] with an odd sum + vector dp1(n + 1); + + for (int i = 1; i <= n; ++i) { + if (arr[i - 1] % 2 == 1) { + dp0[i] = dp1[i - 1]; + dp1[i] = dp0[i - 1] + 1; + } else { + dp0[i] = dp0[i - 1] + 1; + dp1[i] = dp1[i - 1]; + } + ans = (ans + dp1[i]) % kMod; + } + + return ans; + } +}; diff --git a/solutions/1525. Number of Good Ways to Split a String/1525.cpp b/solutions/1525. Number of Good Ways to Split a String/1525.cpp new file mode 100644 index 00000000000..e247b3961a8 --- /dev/null +++ b/solutions/1525. Number of Good Ways to Split a String/1525.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int numSplits(string s) { + const int n = s.length(); + int ans = 0; + // prefix[i] := the number of unique letters in s[0..i] + vector prefix(n); + // suffix[i] := of unique letters in s[i..n) + vector suffix(n); + unordered_set seen; + + for (int i = 0; i < n; ++i) { + seen.insert(s[i]); + prefix[i] = seen.size(); + } + + seen.clear(); + + for (int i = n - 1; i >= 0; --i) { + seen.insert(s[i]); + suffix[i] = seen.size(); + } + + for (int i = 0; i + 1 < n; ++i) + if (prefix[i] == suffix[i + 1]) + ++ans; + + return ans; + } +}; diff --git a/solutions/1525. Number of Good Ways to Split a String/1525.java b/solutions/1525. Number of Good Ways to Split a String/1525.java new file mode 100644 index 00000000000..0144d3e71e7 --- /dev/null +++ b/solutions/1525. Number of Good Ways to Split a String/1525.java @@ -0,0 +1,27 @@ +class Solution { + public int numSplits(String s) { + final int n = s.length(); + int ans = 0; + int[] prefix = new int[n]; + int[] suffix = new int[n]; + Set seen = new HashSet<>(); + + for (int i = 0; i < n; ++i) { + seen.add(s.charAt(i)); + prefix[i] = seen.size(); + } + + seen.clear(); + + for (int i = n - 1; i >= 0; --i) { + seen.add(s.charAt(i)); + suffix[i] = seen.size(); + } + + for (int i = 0; i + 1 < n; ++i) + if (prefix[i] == suffix[i + 1]) + ++ans; + + return ans; + } +} diff --git a/solutions/1525. Number of Good Ways to Split a String/1525.py b/solutions/1525. Number of Good Ways to Split a String/1525.py new file mode 100644 index 00000000000..0decbab06ea --- /dev/null +++ b/solutions/1525. Number of Good Ways to Split a String/1525.py @@ -0,0 +1,23 @@ +class Solution: + def numSplits(self, s: str) -> int: + n = len(s) + ans = 0 + seen = set() + prefix = [0] * n + suffix = [0] * n + + for i in range(n): + seen.add(s[i]) + prefix[i] = len(seen) + + seen.clear() + + for i in reversed(range(n)): + seen.add(s[i]) + suffix[i] = len(seen) + + for i in range(n - 1): + if prefix[i] == suffix[i + 1]: + ans += 1 + + return ans diff --git a/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.cpp b/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.cpp new file mode 100644 index 00000000000..907286d4de2 --- /dev/null +++ b/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int minNumberOperations(vector& target) { + int ans = target.front(); + + for (int i = 1; i < target.size(); ++i) + if (target[i] > target[i - 1]) + ans += target[i] - target[i - 1]; + + return ans; + } +}; diff --git a/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.java b/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.java new file mode 100644 index 00000000000..68066b46b0b --- /dev/null +++ b/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.java @@ -0,0 +1,11 @@ +class Solution { + public int minNumberOperations(int[] target) { + int ans = target[0]; + + for (int i = 1; i < target.length; ++i) + if (target[i] > target[i - 1]) + ans += target[i] - target[i - 1]; + + return ans; + } +} diff --git a/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.py b/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.py new file mode 100644 index 00000000000..71991e0a935 --- /dev/null +++ b/solutions/1526. Minimum Number of Increments on Subarrays to Form a Target Array/1526.py @@ -0,0 +1,9 @@ +class Solution: + def minNumberOperations(self, target: List[int]) -> int: + ans = target[0] + + for a, b in zip(target, target[1:]): + if a < b: + ans += b - a + + return ans diff --git a/solutions/1527. Patients With a Condition/1527.sql b/solutions/1527. Patients With a Condition/1527.sql new file mode 100644 index 00000000000..c22bea0fe56 --- /dev/null +++ b/solutions/1527. Patients With a Condition/1527.sql @@ -0,0 +1,5 @@ +SELECT * +FROM Patients +WHERE + conditions LIKE 'DIAB1%' + OR conditions LIKE '% DIAB1%'; diff --git a/solutions/1528. Shuffle String/1528.cpp b/solutions/1528. Shuffle String/1528.cpp new file mode 100644 index 00000000000..8da8b62fcba --- /dev/null +++ b/solutions/1528. Shuffle String/1528.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + string restoreString(string s, vector& indices) { + string ans(s.length(), '.'); + + for (int i = 0; i < indices.size(); ++i) + ans[indices[i]] = s[i]; + + return ans; + } +}; diff --git a/solutions/1529. Minimum Suffix Flips/1529.cpp b/solutions/1529. Minimum Suffix Flips/1529.cpp new file mode 100644 index 00000000000..1310fb40e4e --- /dev/null +++ b/solutions/1529. Minimum Suffix Flips/1529.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minFlips(string target) { + int ans = 0; + int state = 0; + + for (const char c : target) + if (c - '0' != state) { + state = c - '0'; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1529. Minimum Suffix Flips/1529.java b/solutions/1529. Minimum Suffix Flips/1529.java new file mode 100644 index 00000000000..2c7d974d70a --- /dev/null +++ b/solutions/1529. Minimum Suffix Flips/1529.java @@ -0,0 +1,14 @@ +class Solution { + public int minFlips(String target) { + int ans = 0; + int state = 0; + + for (final char c : target.toCharArray()) + if (c - '0' != state) { + state = c - '0'; + ++ans; + } + + return ans; + } +} diff --git a/solutions/153. Find Minimum in Rotated Sorted Array/153.cpp b/solutions/153. Find Minimum in Rotated Sorted Array/153.cpp new file mode 100644 index 00000000000..f269ce8211d --- /dev/null +++ b/solutions/153. Find Minimum in Rotated Sorted Array/153.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int findMin(vector& nums) { + int l = 0; + int r = nums.size() - 1; + + while (l < r) { + const int m = (l + r) / 2; + if (nums[m] < nums[r]) + r = m; + else + l = m + 1; + } + + return nums[l]; + } +}; diff --git a/solutions/153. Find Minimum in Rotated Sorted Array/153.java b/solutions/153. Find Minimum in Rotated Sorted Array/153.java new file mode 100644 index 00000000000..da5e3973a8f --- /dev/null +++ b/solutions/153. Find Minimum in Rotated Sorted Array/153.java @@ -0,0 +1,16 @@ +class Solution { + public int findMin(int[] nums) { + int l = 0; + int r = nums.length - 1; + + while (l < r) { + final int m = (l + r) / 2; + if (nums[m] < nums[r]) + r = m; + else + l = m + 1; + } + + return nums[l]; + } +} diff --git a/solutions/153. Find Minimum in Rotated Sorted Array/153.py b/solutions/153. Find Minimum in Rotated Sorted Array/153.py new file mode 100644 index 00000000000..18d4b234146 --- /dev/null +++ b/solutions/153. Find Minimum in Rotated Sorted Array/153.py @@ -0,0 +1,13 @@ +class Solution: + def findMin(self, nums: List[int]) -> int: + l = 0 + r = len(nums) - 1 + + while l < r: + m = (l + r) // 2 + if nums[m] < nums[r]: + r = m + else: + l = m + 1 + + return nums[l] diff --git a/solutions/1530. Number of Good Leaf Nodes Pairs/1530.cpp b/solutions/1530. Number of Good Leaf Nodes Pairs/1530.cpp new file mode 100644 index 00000000000..b8a5718d885 --- /dev/null +++ b/solutions/1530. Number of Good Leaf Nodes Pairs/1530.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int countPairs(TreeNode* root, int distance) { + int ans = 0; + + dfs(root, distance, ans); + + return ans; + } + + private: + vector dfs(TreeNode* root, int distance, int& ans) { + vector d(distance + 1); // {distance: the number of leaf nodes} + if (root == nullptr) + return d; + if (root->left == nullptr && root->right == nullptr) { + d[0] = 1; + return d; + } + + const vector dl = dfs(root->left, distance, ans); + const vector dr = dfs(root->right, distance, ans); + + for (int i = 0; i < distance; ++i) + for (int j = 0; j < distance; ++j) + if (i + j + 2 <= distance) + ans += dl[i] * dr[j]; + + for (int i = 0; i < distance; ++i) + d[i + 1] = dl[i] + dr[i]; + + return d; + } +}; diff --git a/solutions/1530. Number of Good Leaf Nodes Pairs/1530.java b/solutions/1530. Number of Good Leaf Nodes Pairs/1530.java new file mode 100644 index 00000000000..37c7f7b8cfc --- /dev/null +++ b/solutions/1530. Number of Good Leaf Nodes Pairs/1530.java @@ -0,0 +1,32 @@ +class Solution { + public int countPairs(TreeNode root, int distance) { + dfs(root, distance); + + return ans; + } + + private int ans = 0; + + private int[] dfs(TreeNode root, int distance) { + int[] d = new int[distance + 1]; // {distance: the number of leaf nodes} + if (root == null) + return d; + if (root.left == null && root.right == null) { + d[0] = 1; + return d; + } + + int[] dl = dfs(root.left, distance); + int[] dr = dfs(root.right, distance); + + for (int i = 0; i < distance; ++i) + for (int j = 0; j < distance; ++j) + if (i + j + 2 <= distance) + ans += dl[i] * dr[j]; + + for (int i = 0; i < distance; ++i) + d[i + 1] = dl[i] + dr[i]; + + return d; + } +} diff --git a/solutions/1531. String Compression II/1531.cpp b/solutions/1531. String Compression II/1531.cpp new file mode 100644 index 00000000000..9b8322d4c98 --- /dev/null +++ b/solutions/1531. String Compression II/1531.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int getLengthOfOptimalCompression(string s, int k) { + vector> mem(s.length(), vector(k + 1, kMax)); + return compression(s, 0, k, mem); + } + + private: + static constexpr int kMax = 101; + + // Returns the length of the optimal compression of s[i..n) with at most k + // deletion. + int compression(const string& s, int i, int k, vector>& mem) { + if (k < 0) + return kMax; + if (i == s.length() || s.length() - i <= k) + return 0; + if (mem[i][k] != kMax) + return mem[i][k]; + + int maxFreq = 0; // the maximum frequency in s[i..j] + vector count(128); + + // Make letters in s[i..j] be the same. + // Keep the letter that has the maximum frequency in this range and remove + // the other letters. + for (int j = i; j < s.length(); ++j) { + maxFreq = max(maxFreq, ++count[s[j]]); + mem[i][k] = min( // + mem[i][k], // + getLength(maxFreq) + + compression(s, j + 1, k - (j - i + 1 - maxFreq), mem)); + } + + return mem[i][k]; + } + + // Returns the length to compress `maxFreq`. + int getLength(int maxFreq) { + if (maxFreq == 1) + return 1; // c + if (maxFreq < 10) + return 2; // [1-9]c + if (maxFreq < 100) + return 3; // [1-9][0-9]c + return 4; // [1-9][0-9][0-9]c + } +}; diff --git a/solutions/1531. String Compression II/1531.java b/solutions/1531. String Compression II/1531.java new file mode 100644 index 00000000000..04389a0da5d --- /dev/null +++ b/solutions/1531. String Compression II/1531.java @@ -0,0 +1,46 @@ +class Solution { + public int getLengthOfOptimalCompression(String s, int k) { + int[][] mem = new int[s.length()][k + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, kMax)); + return compression(s, 0, k, mem); + } + + private static final int kMax = 101; + + // Returns the length of the optimal compression of s[i..n) with at most k + // deletion. + private int compression(final String s, int i, int k, int[][] mem) { + if (k < 0) + return kMax; + if (i == s.length() || s.length() - i <= k) + return 0; + if (mem[i][k] != kMax) + return mem[i][k]; + + int maxFreq = 0; + int[] count = new int[128]; + + // Make letters in s[i..j] be the same. + // Keep the letter that has the maximum frequency in this range and remove + // the other letters. + for (int j = i; j < s.length(); ++j) { + maxFreq = Math.max(maxFreq, ++count[s.charAt(j)]); + mem[i][k] = Math.min( // + mem[i][k], // + getLength(maxFreq) + compression(s, j + 1, k - (j - i + 1 - maxFreq), mem)); + } + + return mem[i][k]; + } + + // Returns the length to compress `maxFreq`. + private int getLength(int maxFreq) { + if (maxFreq == 1) + return 1; // c + if (maxFreq < 10) + return 2; // [1-9]c + if (maxFreq < 100) + return 3; // [1-9][0-9]c + return 4; // [1-9][0-9][0-9]c + } +} diff --git a/solutions/1531. String Compression II/1531.py b/solutions/1531. String Compression II/1531.py new file mode 100644 index 00000000000..6e93f79e17a --- /dev/null +++ b/solutions/1531. String Compression II/1531.py @@ -0,0 +1,36 @@ +class Solution: + def getLengthOfOptimalCompression(self, s: str, k: int) -> int: + def getLength(maxFreq: int) -> int: + """Returns the length to compress `maxFreq`.""" + if maxFreq == 1: + return 1 # c + if maxFreq < 10: + return 2 # [1-9]c + if maxFreq < 100: + return 3 # [1-9][0-9]c + return 4 # [1-9][0-9][0-9]c + + @functools.lru_cache(None) + def dp(i: int, k: int) -> int: + """Returns the length of optimal dp of s[i..n) with at most k deletion.""" + if k < 0: + return math.inf + if i == len(s) or len(s) - i <= k: + return 0 + + ans = math.inf + maxFreq = 0 # the maximum frequency in s[i..j] + count = collections.Counter() + + # Make letters in s[i..j] be the same. + # Keep the letter that has the maximum frequency in this range and remove + # the other letters. + for j in range(i, len(s)): + count[s[j]] += 1 + maxFreq = max(maxFreq, count[s[j]]) + ans = min(ans, getLength(maxFreq) + + dp(j + 1, k - (j - i + 1 - maxFreq))) + + return ans + + return dp(0, k) diff --git a/solutions/1532. The Most Recent Three Orders/1532.sql b/solutions/1532. The Most Recent Three Orders/1532.sql new file mode 100644 index 00000000000..11cba777550 --- /dev/null +++ b/solutions/1532. The Most Recent Three Orders/1532.sql @@ -0,0 +1,22 @@ +WITH + OrdersWithRowNumber AS ( + SELECT + order_id, + order_date, + customer_id, + ROW_NUMBER() OVER( + PARTITION BY customer_id + ORDER BY order_date DESC + ) AS `row_number` + FROM Orders + ) +SELECT + Customers.name AS customer_name, + Customers.customer_id, + OrdersWithRowNumber.order_id, + OrdersWithRowNumber.order_date +FROM OrdersWithRowNumber +INNER JOIN Customers + USING (customer_id) +WHERE `row_number` <= 3 +ORDER BY customer_name, customer_id, order_date DESC; diff --git a/solutions/1533. Find the Index of the Large Integer/1533-2.cpp b/solutions/1533. Find the Index of the Large Integer/1533-2.cpp new file mode 100644 index 00000000000..e730b533863 --- /dev/null +++ b/solutions/1533. Find the Index of the Large Integer/1533-2.cpp @@ -0,0 +1,35 @@ +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * int compareSub(int l, int r, int x, int y); + * + * // Returns the length of the array + * int length(); + * }; + */ + +class Solution { + public: + int getIndex(ArrayReader& reader) { + int l = 0; + int r = reader.length() - 1; + + while (l < r) { + const int m = (l + r) / 2; + const int res = (r - l + 1) % 2 == 0 ? reader.compareSub(l, m, m + 1, r) + : reader.compareSub(l, m, m, r); + if (res == -1) + l = m + 1; + else // res == 1 || res == 0 + r = m; + } + + return l; + } +}; diff --git a/solutions/1533. Find the Index of the Large Integer/1533-2.java b/solutions/1533. Find the Index of the Large Integer/1533-2.java new file mode 100644 index 00000000000..30f9d6e4899 --- /dev/null +++ b/solutions/1533. Find the Index of the Large Integer/1533-2.java @@ -0,0 +1,33 @@ +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * public int compareSub(int l, int r, int x, int y) {} + * + * // Returns the length of the array + * public int length() {} + * } + */ + +class Solution { + public int getIndex(ArrayReader reader) { + int l = 0; + int r = reader.length() - 1; + + while (l < r) { + final int m = (l + r) / 2; + final int res = (r - l + 1) % 2 == 0 ? reader.compareSub(l, m, m + 1, r) // + : reader.compareSub(l, m, m, r); + if (res == -1) + l = m + 1; + else // res == 1 || res == 0 + r = m; + } + + return l; + } +} diff --git a/solutions/1533. Find the Index of the Large Integer/1533-2.py b/solutions/1533. Find the Index of the Large Integer/1533-2.py new file mode 100644 index 00000000000..414f2d4434f --- /dev/null +++ b/solutions/1533. Find the Index of the Large Integer/1533-2.py @@ -0,0 +1,31 @@ +# """ +# This is ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class ArrayReader(object): +# # Compares the sum of arr[l..r] with the sum of arr[x..y] +# # return 1 if sum(arr[l..r]) > sum(arr[x..y]) +# # return 0 if sum(arr[l..r]) == sum(arr[x..y]) +# # return -1 if sum(arr[l..r]) < sum(arr[x..y]) +# def compareSub(self, l: int, r: int, x: int, y: int) -> int: +# +# # Returns the length of the array +# def length(self) -> int: +# + + +class Solution: + def getIndex(self, reader: 'ArrayReader') -> int: + l = 0 + r = reader.length() - 1 + + while l < r: + m = (l + r) // 2 + res = reader.compareSub(l, m, m + 1, r) if (r - l + 1) % 2 == 0 \ + else reader.compareSub(l, m, m, r) + if res == -1: + l = m + 1 + else: # res == 1 or res == 0 + r = m + + return l diff --git a/solutions/1533. Find the Index of the Large Integer/1533.cpp b/solutions/1533. Find the Index of the Large Integer/1533.cpp new file mode 100644 index 00000000000..0fd7f30688e --- /dev/null +++ b/solutions/1533. Find the Index of the Large Integer/1533.cpp @@ -0,0 +1,47 @@ +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * int compareSub(int l, int r, int x, int y); + * + * // Returns the length of the array + * int length(); + * }; + */ + +class Solution { + public: + int getIndex(ArrayReader& reader) { + int l = 0; + int r = reader.length() - 1; + + while (l < r) { + const int m = (l + r) / 2; + if ((r - l) % 2 == 0) { + const int res = reader.compareSub(l, m - 1, m + 1, r); + if (res == 0) + return m; + if (res == 1) { + r = m - 1; + } else { // res == -1 + l = m + 1; + } + } else { + const int res = reader.compareSub(l, m, m + 1, r); + // res is either 1 or -1. + if (res == 1) { + r = m; + } else { // res == -1 + l = m + 1; + } + } + } + + return l; + } +}; diff --git a/solutions/1533. Find the Index of the Large Integer/1533.java b/solutions/1533. Find the Index of the Large Integer/1533.java new file mode 100644 index 00000000000..2cff8e8ecfe --- /dev/null +++ b/solutions/1533. Find the Index of the Large Integer/1533.java @@ -0,0 +1,45 @@ +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * public int compareSub(int l, int r, int x, int y) {} + * + * // Returns the length of the array + * public int length() {} + * } + */ + +class Solution { + public int getIndex(ArrayReader reader) { + int l = 0; + int r = reader.length() - 1; + + while (l < r) { + final int m = (l + r) / 2; + if ((r - l) % 2 == 0) { + final int res = reader.compareSub(l, m - 1, m + 1, r); + if (res == 0) + return m; + if (res == 1) { + r = m - 1; + } else { // res == -1 + l = m + 1; + } + } else { + final int res = reader.compareSub(l, m, m + 1, r); + // res is either 1 or -1. + if (res == 1) { + r = m; + } else { // res == -1 + l = m + 1; + } + } + } + + return l; + } +} diff --git a/solutions/1533. Find the Index of the Large Integer/1533.py b/solutions/1533. Find the Index of the Large Integer/1533.py new file mode 100644 index 00000000000..63ace42966d --- /dev/null +++ b/solutions/1533. Find the Index of the Large Integer/1533.py @@ -0,0 +1,40 @@ +# """ +# This is ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class ArrayReader(object): +# # Compares the sum of arr[l..r] with the sum of arr[x..y] +# # return 1 if sum(arr[l..r]) > sum(arr[x..y]) +# # return 0 if sum(arr[l..r]) == sum(arr[x..y]) +# # return -1 if sum(arr[l..r]) < sum(arr[x..y]) +# def compareSub(self, l: int, r: int, x: int, y: int) -> int: +# +# # Returns the length of the array +# def length(self) -> int: +# + + +class Solution: + def getIndex(self, reader: 'ArrayReader') -> int: + l = 0 + r = reader.length() - 1 + + while l < r: + m = (l + r) // 2 + if (r - l) % 2 == 0: + res = reader.compareSub(l, m - 1, m + 1, r) + if res == 0: + return m + if res == 1: + r = m - 1 + else: # res == -1 + l = m + 1 + else: + res = reader.compareSub(l, m, m + 1, r) + # res is either 1 or -1. + if res == 1: + r = m + else: # res == -1 + l = m + 1 + + return l diff --git a/solutions/1534. Count Good Triplets/1534.cpp b/solutions/1534. Count Good Triplets/1534.cpp new file mode 100644 index 00000000000..282353b69e1 --- /dev/null +++ b/solutions/1534. Count Good Triplets/1534.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int countGoodTriplets(vector& arr, int a, int b, int c) { + int ans = 0; + for (int i = 0; i < arr.size(); ++i) + for (int j = i + 1; j < arr.size(); ++j) + for (int k = j + 1; k < arr.size(); ++k) + if (abs(arr[i] - arr[j]) <= a && // + abs(arr[j] - arr[k]) <= b && // + abs(arr[i] - arr[k]) <= c) + ++ans; + return ans; + } +}; diff --git a/solutions/1534. Count Good Triplets/1534.java b/solutions/1534. Count Good Triplets/1534.java new file mode 100644 index 00000000000..04c0e21300d --- /dev/null +++ b/solutions/1534. Count Good Triplets/1534.java @@ -0,0 +1,13 @@ +class Solution { + public int countGoodTriplets(int[] arr, int a, int b, int c) { + int ans = 0; + for (int i = 0; i < arr.length; ++i) + for (int j = i + 1; j < arr.length; ++j) + for (int k = j + 1; k < arr.length; ++k) + if (Math.abs(arr[i] - arr[j]) <= a && // + Math.abs(arr[j] - arr[k]) <= b && // + Math.abs(arr[i] - arr[k]) <= c) + ++ans; + return ans; + } +} diff --git a/solutions/1534. Count Good Triplets/1534.py b/solutions/1534. Count Good Triplets/1534.py new file mode 100644 index 00000000000..290171e277f --- /dev/null +++ b/solutions/1534. Count Good Triplets/1534.py @@ -0,0 +1,8 @@ +class Solution: + def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: + return sum(abs(arr[i] - arr[j]) <= a and + abs(arr[j] - arr[k]) <= b and + abs(arr[i] - arr[k]) <= c + for i in range(len(arr)) + for j in range(i + 1, len(arr)) + for k in range(j + 1, len(arr))) diff --git a/solutions/1535. Find the Winner of an Array Game/1535.cpp b/solutions/1535. Find the Winner of an Array Game/1535.cpp new file mode 100644 index 00000000000..9c12e0b1ff8 --- /dev/null +++ b/solutions/1535. Find the Winner of an Array Game/1535.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int getWinner(vector& arr, int k) { + int ans = arr[0]; + int wins = 0; + + for (int i = 1; i < arr.size() && wins < k; ++i) + if (arr[i] > ans) { + ans = arr[i]; + wins = 1; + } else { + ++wins; + } + + return ans; + } +}; diff --git a/solutions/1535. Find the Winner of an Array Game/1535.java b/solutions/1535. Find the Winner of an Array Game/1535.java new file mode 100644 index 00000000000..aed63abd50c --- /dev/null +++ b/solutions/1535. Find the Winner of an Array Game/1535.java @@ -0,0 +1,16 @@ +class Solution { + public int getWinner(int[] arr, int k) { + int ans = arr[0]; + int wins = 0; + + for (int i = 1; i < arr.length && wins < k; ++i) + if (arr[i] > ans) { + ans = arr[i]; + wins = 1; + } else { + ++wins; + } + + return ans; + } +} diff --git a/solutions/1535. Find the Winner of an Array Game/1535.py b/solutions/1535. Find the Winner of an Array Game/1535.py new file mode 100644 index 00000000000..d51cfd3dfbd --- /dev/null +++ b/solutions/1535. Find the Winner of an Array Game/1535.py @@ -0,0 +1,15 @@ +class Solution: + def getWinner(self, arr: List[int], k: int) -> int: + ans = arr[0] + wins = 0 + + i = 1 + while i < len(arr) and wins < k: + if arr[i] > ans: + ans = arr[i] + wins = 1 + else: + wins += 1 + i += 1 + + return ans diff --git a/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.cpp b/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.cpp new file mode 100644 index 00000000000..c40b5a2b0b2 --- /dev/null +++ b/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minSwaps(vector>& grid) { + const int n = grid.size(); + int ans = 0; + // suffixZeros[i] := the number of suffix zeros in the i-th row + vector suffixZeros; + + for (const vector row : grid) { + const auto itLastOne = find(row.rbegin(), row.rend(), 1); + const int suffixZeroCount = distance(row.rbegin(), itLastOne); + suffixZeros.push_back(suffixZeroCount); + } + + for (int i = 0; i < n; ++i) { + const int neededZeros = n - 1 - i; + // Get the first row with suffix zeros >= `neededZeros` in + // suffixZeros[i:..n). + const auto it = find_if(suffixZeros.begin() + i, suffixZeros.end(), + [&](int count) { return count >= neededZeros; }); + if (it == suffixZeros.end()) + return -1; + const int j = distance(suffixZeros.begin(), it); + // Move the rows[j] to the rows[i]. + for (int k = j; k > i; --k) + suffixZeros[k] = suffixZeros[k - 1]; + ans += j - i; + } + + return ans; + } +}; diff --git a/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.java b/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.java new file mode 100644 index 00000000000..01d7d38da9f --- /dev/null +++ b/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.java @@ -0,0 +1,40 @@ +class Solution { + public int minSwaps(int[][] grid) { + final int n = grid.length; + int ans = 0; + // suffixZeros[i] := the number of suffix zeros in the i-th row + int[] suffixZeros = new int[n]; + + for (int i = 0; i < grid.length; ++i) + suffixZeros[i] = getSuffixZeroCount(grid[i]); + + for (int i = 0; i < n; ++i) { + final int neededZeros = n - 1 - i; + // Get the first row with suffix zeros >= `neededZeros` in suffixZeros[i:..n). + final int j = getFirstRowWithEnoughZeros(suffixZeros, i, neededZeros); + if (j == -1) + return -1; + // Move the rows[j] to the rows[i]. + for (int k = j; k > i; --k) + suffixZeros[k] = suffixZeros[k - 1]; + ans += j - i; + } + + return ans; + } + + private int getSuffixZeroCount(int[] row) { + for (int i = row.length - 1; i >= 0; --i) + if (row[i] == 1) + return row.length - i - 1; + return row.length; + } + + // Returns first row that has suffix zeros > `neededZeros` in suffixZeros[i:..n). + private int getFirstRowWithEnoughZeros(int[] suffixZeros, int i, int neededZeros) { + for (int j = i; j < suffixZeros.length; ++j) + if (suffixZeros[j] >= neededZeros) + return j; + return -1; + } +} diff --git a/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.py b/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.py new file mode 100644 index 00000000000..754493ed65b --- /dev/null +++ b/solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.py @@ -0,0 +1,19 @@ +class Solution: + def minSwaps(self, grid: List[List[int]]) -> int: + n = len(grid) + ans = 0 + # suffixZeros[i] := the number of suffix zeros in the i-th row + suffixZeros = [n if 1 not in row else row[::-1].index(1) for row in grid] + + for i in range(n): + neededZeros = n - 1 - i + # Get the first row with suffix zeros >= `neededZeros` in suffixZeros[i:..n). + j = next((j for j in range(i, n) if suffixZeros[j] >= neededZeros), -1) + if j == -1: + return -1 + # Move the rows[j] to the rows[i]. + for k in range(j, i, -1): + suffixZeros[k] = suffixZeros[k - 1] + ans += j - i + + return ans diff --git a/solutions/1537. Get the Maximum Score/1537.cpp b/solutions/1537. Get the Maximum Score/1537.cpp new file mode 100644 index 00000000000..5df8e707c2d --- /dev/null +++ b/solutions/1537. Get the Maximum Score/1537.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int maxSum(vector& nums1, vector& nums2) { + constexpr int kMod = 1'000'000'007; + // Keep the running the sum of `nums1` and `nums2` before the next + // rendezvous. Since `nums1` and `nums2` are increasing, move forward on the + // smaller one to ensure we don't miss any rendezvous. When meet rendezvous, + // choose the better path. + long ans = 0; + // sum(nums1) in (the prevoious rendezvous, the next rendezvous) + long sum1 = 0; + // sum(nums2) in (the prevoious rendezvous, the next rendezvous) + long sum2 = 0; + int i = 0; // nums1's index + int j = 0; // nums2's index + + while (i < nums1.size() && j < nums2.size()) + if (nums1[i] < nums2[j]) { + sum1 += nums1[i++]; + } else if (nums1[i] > nums2[j]) { + sum2 += nums2[j++]; + } else { // An rendezvous happens. + ans += max(sum1, sum2) + nums1[i]; + sum1 = 0; + sum2 = 0; + ++i; + ++j; + } + + while (i < nums1.size()) + sum1 += nums1[i++]; + + while (j < nums2.size()) + sum2 += nums2[j++]; + + return (ans + max(sum1, sum2)) % kMod; + } +}; diff --git a/solutions/1537. Get the Maximum Score/1537.java b/solutions/1537. Get the Maximum Score/1537.java new file mode 100644 index 00000000000..063523f0bd7 --- /dev/null +++ b/solutions/1537. Get the Maximum Score/1537.java @@ -0,0 +1,36 @@ +class Solution { + public int maxSum(int[] nums1, int[] nums2) { + final int kMod = 1_000_000_007; + // Keep the running the sum of `nums1` and `nums2` before the next rendezvous. + // Since `nums1` and `nums2` are increasing, move forward on the smaller one + // to ensure we don't miss any rendezvous. When meet rendezvous, choose the + // better path. + long ans = 0; + // sum(nums1) in (the prevoious rendezvous, the next rendezvous) + long sum1 = 0; + // sum(nums2) in (the prevoious rendezvous, the next rendezvous) + int i = 0; // nums1's index + int j = 0; // nums2's index + + while (i < nums1.length && j < nums2.length) + if (nums1[i] < nums2[j]) { + sum1 += nums1[i++]; + } else if (nums1[i] > nums2[j]) { + sum2 += nums2[j++]; + } else { // An rendezvous happens. + ans += Math.max(sum1, sum2) + nums1[i]; + sum1 = 0; + sum2 = 0; + ++i; + ++j; + } + + while (i < nums1.length) + sum1 += nums1[i++]; + + while (j < nums2.length) + sum2 += nums2[j++]; + + return (int) ((ans + Math.max(sum1, sum2)) % kMod); + } +} diff --git a/solutions/1537. Get the Maximum Score/1537.py b/solutions/1537. Get the Maximum Score/1537.py new file mode 100644 index 00000000000..e60a95b2f45 --- /dev/null +++ b/solutions/1537. Get the Maximum Score/1537.py @@ -0,0 +1,35 @@ +class Solution: + def maxSum(self, nums1: List[int], nums2: List[int]) -> int: + # Keep the running the sum of `nums1` and `nums2` before the next rendezvous. + # Since `nums1` and `nums2` are increasing, move forward on the smaller one + # to ensure we don't miss any rendezvous. When meet rendezvous, choose the + # better path. + ans = 0 + sum1 = 0 # sum(nums1) in (the prevoious rendezvous, the next rendezvous) + sum2 = 0 # sum(nums2) in (the prevoious rendezvous, the next rendezvous) + i = 0 # nums1's index + j = 0 # nums2's index + + while i < len(nums1) and j < len(nums2): + if nums1[i] < nums2[j]: + sum1 += nums1[i] + i += 1 + elif nums1[i] > nums2[j]: + sum2 += nums2[j] + j += 1 + else: # An rendezvous happens. + ans += max(sum1, sum2) + nums1[i] + sum1 = 0 + sum2 = 0 + i += 1 + j += 1 + + while i < len(nums1): + sum1 += nums1[i] + i += 1 + + while j < len(nums2): + sum2 += nums2[j] + j += 1 + + return (ans + max(sum1, sum2)) % (10**9 + 7) diff --git a/solutions/1538. Guess the Majority in a Hidden Array/1538.cpp b/solutions/1538. Guess the Majority in a Hidden Array/1538.cpp new file mode 100644 index 00000000000..b8044b5c888 --- /dev/null +++ b/solutions/1538. Guess the Majority in a Hidden Array/1538.cpp @@ -0,0 +1,69 @@ +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * // Compares 4 different elements in the array + * // Returns 4 if the values of the 4 elements are the same (0 or 1). + * // Returns 2 if three elements have a value equal to 0 and one element has + * // value equal to 1 or vice versa. + * // Returns 0 if two element have a value equal to 0 and two elements have + * // a value equal to 1. + * int query(int a, int b, int c, int d); + * + * // Returns the length of the array + * int length(); + * }; + */ + +class Solution { + public: + int guessMajority(ArrayReader& reader) { + const int n = reader.length(); + const int query0123 = reader.query(0, 1, 2, 3); + const int query1234 = reader.query(1, 2, 3, 4); + // the number of numbers that are same as `nums[0]` + int count0 = 1; + // the number of numbers that are different from `nums[0]` + int countNot0 = 0; + // any index i s.t. nums[i] != nums[0] + int indexNot0 = -1; + + // Find which group nums[1..3] belong to. + for (int i = 1; i <= 3; ++i) { + vector abcd = getABCD(i); + if (reader.query(abcd[0], abcd[1], abcd[2], abcd[3]) == query1234) { + ++count0; + } else { + ++countNot0; + indexNot0 = i; + } + } + + // Find which group nums[4..n) belong to. + for (int i = 4; i < n; ++i) + if (reader.query(1, 2, 3, i) == query0123) { + ++count0; + } else { + ++countNot0; + indexNot0 = i; + } + + if (count0 == countNot0) + return -1; + if (count0 > countNot0) + return 0; + return indexNot0; + } + + // Returns [0..4] except i. + private: + vector getABCD(int i) { + vector abcd{0}; + for (int j = 1; j <= 3; ++j) + if (j != i) + abcd.push_back(j); + abcd.push_back(4); + return abcd; + } +}; diff --git a/solutions/1538. Guess the Majority in a Hidden Array/1538.java b/solutions/1538. Guess the Majority in a Hidden Array/1538.java new file mode 100644 index 00000000000..1e825514052 --- /dev/null +++ b/solutions/1538. Guess the Majority in a Hidden Array/1538.java @@ -0,0 +1,66 @@ +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * // Compares 4 different elements in the array + * // Returns 4 if the values of the 4 elements are the same (0 or 1). + * // Returns 2 if three elements have a value equal to 0 and one element has + * // value equal to 1 or vice versa. + * // Returns 0 if two element have a value equal to 0 and two elements have + * // a value equal to 1. + * public int query(int a, int b, int c, int d); + * + * // Returns the length of the array + * public int length(); + * }; + */ + +class Solution { + public int guessMajority(ArrayReader reader) { + final int n = reader.length(); + final int query0123 = reader.query(0, 1, 2, 3); + final int query1234 = reader.query(1, 2, 3, 4); + // the number of numbers that are same as `nums[0]` + int count0 = 1; + // the number of numbers that are different from `nums[0]` + int countNot0 = 0; + // any index i s.t. nums[i] != nums[0] + int indexNot0 = -1; + + // Find which group nums[1..3] belong to. + for (int i = 1; i <= 3; ++i) { + List abcd = getABCD(i); + if (reader.query(abcd.get(0), abcd.get(1), abcd.get(2), abcd.get(3)) == query1234) { + ++count0; + } else { + ++countNot0; + indexNot0 = i; + } + } + + // Find which group nums[4..n) belong to. + for (int i = 4; i < n; ++i) + if (reader.query(1, 2, 3, i) == query0123) { + ++count0; + } else { + ++countNot0; + indexNot0 = i; + } + + if (count0 == countNot0) + return -1; + if (count0 > countNot0) + return 0; + return indexNot0; + } + + // Returns [0..4] except i. + private List getABCD(int i) { + List abcd = new ArrayList<>(Arrays.asList(0)); + for (int j = 1; j <= 3; ++j) + if (j != i) + abcd.add(j); + abcd.add(4); + return abcd; + } +} diff --git a/solutions/1538. Guess the Majority in a Hidden Array/1538.py b/solutions/1538. Guess the Majority in a Hidden Array/1538.py new file mode 100644 index 00000000000..3bee5a7b2a4 --- /dev/null +++ b/solutions/1538. Guess the Majority in a Hidden Array/1538.py @@ -0,0 +1,48 @@ +# """ +# This is the ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class ArrayReader(object): +# # Compares 4 different elements in the array +# # Returns 4 if the values of the 4 elements are the same (0 or 1). +# # Returns 2 if three elements have a value equal to 0 and one element has +# # value equal to 1 or vice versa. +# # Returns 0 if two element have a value equal to 0 and two elements have a +# # value equal to 1. +# def query(self, a: int, b: int, c: int, d: int) -> int: +# +# # Returns the length of the array +# def length(self) -> int: +# + +class Solution: + def guessMajority(self, reader: 'ArrayReader') -> int: + n = reader.length() + query0123 = reader.query(0, 1, 2, 3) + query1234 = reader.query(1, 2, 3, 4) + count0 = 1 # the number of numbers that are same as `nums[0]` + countNot0 = 0 # the number of numbers that are different from `nums[0]` + indexNot0 = -1 # any index i s.t. nums[i] != nums[0] + + # Find which group nums[1..3] belong to. + for i in range(1, 4): + abcd = [0] + [num for num in [1, 2, 3] if num != i] + [4] + if reader.query(*abcd) == query1234: # nums[i] == nums[0] + count0 += 1 + else: + countNot0 += 1 + indexNot0 = i + + # Find which group nums[4..n) belong to. + for i in range(4, n): + if reader.query(1, 2, 3, i) == query0123: # nums[i] == nums[0] + count0 += 1 + else: + countNot0 += 1 + indexNot0 = i + + if count0 == countNot0: + return -1 + if count0 > countNot0: + return 0 + return indexNot0 diff --git a/solutions/1539. Kth Missing Positive Number/1539.cpp b/solutions/1539. Kth Missing Positive Number/1539.cpp new file mode 100644 index 00000000000..feb309ed4ff --- /dev/null +++ b/solutions/1539. Kth Missing Positive Number/1539.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int findKthPositive(vector& arr, int k) { + int l = 0; + int r = arr.size(); + + // Find the first index l s.t. nMissing(l) = A[l] - l - 1 >= k. + while (l < r) { + const int m = (l + r) / 2; + if (arr[m] - m - 1 >= k) + r = m; + else + l = m + 1; + } + + // The k-th missing positive + // = A[l - 1] + k - nMissing(l - 1) + // = A[l - 1] + k - (A[l - 1] - (l - 1) - 1) + // = A[l - 1] + k - (A[l - 1] - l) + // = l + k + return l + k; + } +}; diff --git a/solutions/1539. Kth Missing Positive Number/1539.java b/solutions/1539. Kth Missing Positive Number/1539.java new file mode 100644 index 00000000000..19f0c2b12b5 --- /dev/null +++ b/solutions/1539. Kth Missing Positive Number/1539.java @@ -0,0 +1,22 @@ +class Solution { + public int findKthPositive(int[] arr, int k) { + int l = 0; + int r = arr.length; + + // Find the first index l s.t. nMissing(l) = A[l] - l - 1 >= k. + while (l < r) { + final int m = (l + r) / 2; + if (arr[m] - m - 1 >= k) + r = m; + else + l = m + 1; + } + + // The k-th missing positive + // = A[l - 1] + k - nMissing(l - 1) + // = A[l - 1] + k - (A[l - 1] - (l - 1) - 1) + // = A[l - 1] + k - (A[l - 1] - l) + // = l + k + return l + k; + } +} diff --git a/solutions/154. Find Minimum in Rotated Sorted Array II/154.cpp b/solutions/154. Find Minimum in Rotated Sorted Array II/154.cpp new file mode 100644 index 00000000000..18940997d9e --- /dev/null +++ b/solutions/154. Find Minimum in Rotated Sorted Array II/154.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findMin(vector& nums) { + int l = 0; + int r = nums.size() - 1; + + while (l < r) { + const int m = (l + r) / 2; + if (nums[m] == nums[r]) + --r; + else if (nums[m] < nums[r]) + r = m; + else + l = m + 1; + } + + return nums[l]; + } +}; diff --git a/solutions/154. Find Minimum in Rotated Sorted Array II/154.java b/solutions/154. Find Minimum in Rotated Sorted Array II/154.java new file mode 100644 index 00000000000..74a759997de --- /dev/null +++ b/solutions/154. Find Minimum in Rotated Sorted Array II/154.java @@ -0,0 +1,18 @@ +class Solution { + public int findMin(int[] nums) { + int l = 0; + int r = nums.length - 1; + + while (l < r) { + final int m = (l + r) / 2; + if (nums[m] == nums[r]) + --r; + else if (nums[m] < nums[r]) + r = m; + else + l = m + 1; + } + + return nums[l]; + } +} diff --git a/solutions/154. Find Minimum in Rotated Sorted Array II/154.py b/solutions/154. Find Minimum in Rotated Sorted Array II/154.py new file mode 100644 index 00000000000..6237873bec7 --- /dev/null +++ b/solutions/154. Find Minimum in Rotated Sorted Array II/154.py @@ -0,0 +1,15 @@ +class Solution: + def findMin(self, nums: List[int]) -> int: + l = 0 + r = len(nums) - 1 + + while l < r: + m = (l + r) // 2 + if nums[m] == nums[r]: + r -= 1 + elif nums[m] < nums[r]: + r = m + else: + l = m + 1 + + return nums[l] diff --git a/solutions/1540. Can Convert String in K Moves/1540-2.cpp b/solutions/1540. Can Convert String in K Moves/1540-2.cpp new file mode 100644 index 00000000000..86fc3f79ce5 --- /dev/null +++ b/solutions/1540. Can Convert String in K Moves/1540-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + bool canConvertString(string s, string t, int k) { + if (s.length() != t.length()) + return false; + + // e.g. s = "aab", t = "bbc", so shiftCount[1] = 3. + // 1. a -> b, need 1 move. + // 2. a -> b, need 1 + 26 moves. + // 3. b -> c, need 1 + 26 * 2 moves. + vector shiftCount(26); + + for (int i = 0; i < s.length(); ++i) { + const int shift = (t[i] - s[i] + 26) % 26; + if (shift == 0) + continue; + if (shift + 26 * shiftCount[shift] > k) + return false; + ++shiftCount[shift]; + } + + return true; + } +}; diff --git a/solutions/1540. Can Convert String in K Moves/1540-2.java b/solutions/1540. Can Convert String in K Moves/1540-2.java new file mode 100644 index 00000000000..fd31178e9cc --- /dev/null +++ b/solutions/1540. Can Convert String in K Moves/1540-2.java @@ -0,0 +1,23 @@ +class Solution { + public boolean canConvertString(String s, String t, int k) { + if (s.length() != t.length()) + return false; + + // e.g. s = "aab", t = "bbc", so shiftCount[1] = 3 + // 1. a -> b, need 1 move. + // 2. a -> b, need 1 + 26 moves. + // 3. b -> c, need 1 + 26 * 2 moves. + int[] shiftCount = new int[26]; + + for (int i = 0; i < s.length(); ++i) { + final int shift = (t.charAt(i) - s.charAt(i) + 26) % 26; + if (shift == 0) + continue; + if (shift + 26 * shiftCount[shift] > k) + return false; + ++shiftCount[shift]; + } + + return true; + } +} diff --git a/solutions/1540. Can Convert String in K Moves/1540-2.py b/solutions/1540. Can Convert String in K Moves/1540-2.py new file mode 100644 index 00000000000..1159a430614 --- /dev/null +++ b/solutions/1540. Can Convert String in K Moves/1540-2.py @@ -0,0 +1,20 @@ +class Solution: + def canConvertString(self, s: str, t: str, k: int) -> bool: + if len(s) != len(t): + return False + + # e.g. s = "aab", t = "bbc", so shiftCount[1] = 3 + # 1. a -> b, need 1 move. + # 2. a -> b, need 1 + 26 moves. + # 3. b -> c, need 1 + 26 * 2 moves. + shiftCount = [0] * 26 + + for a, b in zip(s, t): + shift = (ord(b) - ord(a) + 26) % 26 + if shift == 0: + continue + if shift + 26 * shiftCount[shift] > k: + return False + shiftCount[shift] += 1 + + return True diff --git a/solutions/1540. Can Convert String in K Moves/1540.cpp b/solutions/1540. Can Convert String in K Moves/1540.cpp new file mode 100644 index 00000000000..f8bdf1444d1 --- /dev/null +++ b/solutions/1540. Can Convert String in K Moves/1540.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool canConvertString(string s, string t, int k) { + if (s.length() != t.length()) + return false; + + // e.g. s = "aab", t = "bbc", so shiftCount[1] = 3 + // 1. a -> b, need 1 move. + // 2. a -> b, need 1 + 26 moves. + // 3. b -> c, need 1 + 26 * 2 moves. + vector shiftCount(26); + + for (int i = 0; i < s.length(); ++i) + ++shiftCount[(t[i] - s[i] + 26) % 26]; + + for (int shift = 1; shift < 26; ++shift) + if (shift + 26 * (shiftCount[shift] - 1) > k) + return false; + + return true; + } +}; diff --git a/solutions/1540. Can Convert String in K Moves/1540.java b/solutions/1540. Can Convert String in K Moves/1540.java new file mode 100644 index 00000000000..6fe380008b6 --- /dev/null +++ b/solutions/1540. Can Convert String in K Moves/1540.java @@ -0,0 +1,21 @@ +class Solution { + public boolean canConvertString(String s, String t, int k) { + if (s.length() != t.length()) + return false; + + // e.g. s = "aab", t = "bbc", so shiftCount[1] = 3 + // 1. a -> b, need 1 move. + // 2. a -> b, need 1 + 26 moves. + // 3. b -> c, need 1 + 26 * 2 moves. + int[] shiftCount = new int[26]; + + for (int i = 0; i < s.length(); ++i) + ++shiftCount[(t.charAt(i) - s.charAt(i) + 26) % 26]; + + for (int shift = 1; shift < 26; ++shift) + if (shift + 26 * (shiftCount[shift] - 1) > k) + return false; + + return true; + } +} diff --git a/solutions/1540. Can Convert String in K Moves/1540.py b/solutions/1540. Can Convert String in K Moves/1540.py new file mode 100644 index 00000000000..66e2903f832 --- /dev/null +++ b/solutions/1540. Can Convert String in K Moves/1540.py @@ -0,0 +1,19 @@ +class Solution: + def canConvertString(self, s: str, t: str, k: int) -> bool: + if len(s) != len(t): + return False + + # e.g. s = "aab", t = "bbc", so shiftCount[1] = 3 + # 1. a -> b, need 1 move. + # 2. a -> b, need 1 + 26 moves. + # 3. b -> c, need 1 + 26 * 2 moves. + shiftCount = [0] * 26 + + for a, b in zip(s, t): + shiftCount[(ord(b) - ord(a) + 26) % 26] += 1 + + for shift in range(1, 26): + if shift + 26 * (shiftCount[shift] - 1) > k: + return False + + return True diff --git a/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.cpp b/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.cpp new file mode 100644 index 00000000000..93c345f973d --- /dev/null +++ b/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minInsertions(string s) { + int neededRight = 0; // Increment by 2 for each '('. + int missingLeft = 0; // Increment by 1 for each missing '('. + int missingRight = 0; // Increment by 1 for each missing ')'. + + for (const char c : s) + if (c == '(') { + if (neededRight % 2 == 1) { + // e.g. "()(..." + ++missingRight; + --neededRight; + } + neededRight += 2; + } else if (--neededRight < 0) { // c == ')' + // e.g. "()))..." + ++missingLeft; + neededRight += 2; + } + + return neededRight + missingLeft + missingRight; + } +}; diff --git a/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.java b/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.java new file mode 100644 index 00000000000..0e767b1853b --- /dev/null +++ b/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.java @@ -0,0 +1,23 @@ +class Solution { + public int minInsertions(String s) { + int neededRight = 0; // Increment by 2 for each '('. + int missingLeft = 0; // Increment by 1 for each missing '('. + int missingRight = 0; // Increment by 1 for each missing ')'. + + for (final char c : s.toCharArray()) + if (c == '(') { + if (neededRight % 2 == 1) { + // e.g. "()(..." + ++missingRight; + --neededRight; + } + neededRight += 2; + } else if (--neededRight < 0) { // c == ')' + // e.g. "()))..." + ++missingLeft; + neededRight += 2; + } + + return neededRight + missingLeft + missingRight; + } +} diff --git a/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.py b/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.py new file mode 100644 index 00000000000..76fc3779379 --- /dev/null +++ b/solutions/1541. Minimum Insertions to Balance a Parentheses String/1541.py @@ -0,0 +1,21 @@ +class Solution: + def minInsertions(self, s: str) -> int: + neededRight = 0 # Increment by 2 for each '('. + missingLeft = 0 # Increment by 1 for each missing '('. + missingRight = 0 # Increment by 1 for each missing ')'. + + for c in s: + if c == '(': + if neededRight % 2 == 1: + # e.g. '()(...' + missingRight += 1 + neededRight -= 1 + neededRight += 2 + else: # c == ')' + neededRight -= 1 + if neededRight < 0: + # e.g. '()))...' + missingLeft += 1 + neededRight += 2 + + return neededRight + missingLeft + missingRight diff --git a/solutions/1542. Find Longest Awesome Substring/1542.cpp b/solutions/1542. Find Longest Awesome Substring/1542.cpp new file mode 100644 index 00000000000..6f4ea2322bc --- /dev/null +++ b/solutions/1542. Find Longest Awesome Substring/1542.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int longestAwesome(string s) { + int ans = 0; + int prefix = 0; // the binary prefix + vector prefixToIndex(1024, s.length()); + prefixToIndex[0] = -1; + + for (int i = 0; i < s.length(); ++i) { + prefix ^= 1 << s[i] - '0'; + ans = max(ans, i - prefixToIndex[prefix]); + for (int j = 0; j < 10; ++j) + ans = max(ans, i - prefixToIndex[prefix ^ 1 << j]); + prefixToIndex[prefix] = min(prefixToIndex[prefix], i); + } + + return ans; + } +}; diff --git a/solutions/1542. Find Longest Awesome Substring/1542.java b/solutions/1542. Find Longest Awesome Substring/1542.java new file mode 100644 index 00000000000..74dc13e6937 --- /dev/null +++ b/solutions/1542. Find Longest Awesome Substring/1542.java @@ -0,0 +1,19 @@ +class Solution { + public int longestAwesome(String s) { + int ans = 0; + int prefix = 0; // the binary prefix + int[] prefixToIndex = new int[1024]; + Arrays.fill(prefixToIndex, s.length()); + prefixToIndex[0] = -1; + + for (int i = 0; i < s.length(); ++i) { + prefix ^= 1 << s.charAt(i) - '0'; + ans = Math.max(ans, i - prefixToIndex[prefix]); + for (int j = 0; j < 10; ++j) + ans = Math.max(ans, i - prefixToIndex[prefix ^ 1 << j]); + prefixToIndex[prefix] = Math.min(prefixToIndex[prefix], i); + } + + return ans; + } +} diff --git a/solutions/1542. Find Longest Awesome Substring/1542.py b/solutions/1542. Find Longest Awesome Substring/1542.py new file mode 100644 index 00000000000..0a051987fcd --- /dev/null +++ b/solutions/1542. Find Longest Awesome Substring/1542.py @@ -0,0 +1,15 @@ +class Solution: + def longestAwesome(self, s: str) -> int: + ans = 0 + prefix = 0 # the binary prefix + prefixToIndex = [len(s)] * 1024 + prefixToIndex[0] = -1 + + for i, c in enumerate(s): + prefix ^= 1 << ord(c) - ord('0') + ans = max(ans, i - prefixToIndex[prefix]) + for j in range(10): + ans = max(ans, i - prefixToIndex[prefix ^ 1 << j]) + prefixToIndex[prefix] = min(prefixToIndex[prefix], i) + + return ans diff --git a/solutions/1543. Fix Product Name Format/1543.sql b/solutions/1543. Fix Product Name Format/1543.sql new file mode 100644 index 00000000000..4325b06fd2f --- /dev/null +++ b/solutions/1543. Fix Product Name Format/1543.sql @@ -0,0 +1,7 @@ +SELECT + LOWER(TRIM(product_name)) AS product_name, + DATE_FORMAT(sale_date, '%Y-%m') AS sale_date, + COUNT(*) AS total +FROM Sales +GROUP BY 1, 2 +ORDER BY 1, 2; diff --git a/solutions/1544. Make The String Great/1544.cpp b/solutions/1544. Make The String Great/1544.cpp new file mode 100644 index 00000000000..5512e74a804 --- /dev/null +++ b/solutions/1544. Make The String Great/1544.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + string makeGood(string s) { + string ans; + for (const char c : s) + if (!ans.empty() && isBadPair(ans.back(), c)) + ans.pop_back(); + else + ans.push_back(c); + return ans; + } + + bool isBadPair(char a, char b) { + return a != b && tolower(a) == tolower(b); + } +}; diff --git a/solutions/1544. Make The String Great/1544.java b/solutions/1544. Make The String Great/1544.java new file mode 100644 index 00000000000..574dc4a7d92 --- /dev/null +++ b/solutions/1544. Make The String Great/1544.java @@ -0,0 +1,15 @@ +class Solution { + public String makeGood(String s) { + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) + if (sb.length() > 0 && isBadPair(sb.charAt(sb.length() - 1), c)) + sb.deleteCharAt(sb.length() - 1); + else + sb.append(c); + return sb.toString(); + } + + private boolean isBadPair(char a, char b) { + return a != b && Character.toLowerCase(a) == Character.toLowerCase(b); + } +} diff --git a/solutions/1544. Make The String Great/1544.py b/solutions/1544. Make The String Great/1544.py new file mode 100644 index 00000000000..eebea511215 --- /dev/null +++ b/solutions/1544. Make The String Great/1544.py @@ -0,0 +1,12 @@ +class Solution: + def makeGood(self, s: str) -> str: + ans = [] + for c in s: + if ans and self._is_bad_pair(ans[-1], c): + ans.pop() + else: + ans.append(c) + return ''.join(ans) + + def _is_bad_pair(self, a: str, b: str) -> bool: + return a != b and a.lower() == b.lower() diff --git a/solutions/1545. Find Kth Bit in Nth Binary String/1545.cpp b/solutions/1545. Find Kth Bit in Nth Binary String/1545.cpp new file mode 100644 index 00000000000..d1f330a3f73 --- /dev/null +++ b/solutions/1545. Find Kth Bit in Nth Binary String/1545.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + char findKthBit(int n, int k) { + if (n == 1) + return '0'; + const int midIndex = pow(2, n - 1); // 1-indexed + if (k == midIndex) + return '1'; + if (k < midIndex) + return findKthBit(n - 1, k); + return findKthBit(n - 1, midIndex * 2 - k) == '0' ? '1' : '0'; + } +}; diff --git a/solutions/1545. Find Kth Bit in Nth Binary String/1545.java b/solutions/1545. Find Kth Bit in Nth Binary String/1545.java new file mode 100644 index 00000000000..ce343858944 --- /dev/null +++ b/solutions/1545. Find Kth Bit in Nth Binary String/1545.java @@ -0,0 +1,12 @@ +class Solution { + public char findKthBit(int n, int k) { + if (n == 1) + return '0'; + final int midIndex = (int) Math.pow(2, n - 1); // 1-indexed + if (k == midIndex) + return '1'; + if (k < midIndex) + return findKthBit(n - 1, k); + return findKthBit(n - 1, midIndex * 2 - k) == '0' ? '1' : '0'; + } +} diff --git a/solutions/1545. Find Kth Bit in Nth Binary String/1545.py b/solutions/1545. Find Kth Bit in Nth Binary String/1545.py new file mode 100644 index 00000000000..77e81dd1773 --- /dev/null +++ b/solutions/1545. Find Kth Bit in Nth Binary String/1545.py @@ -0,0 +1,10 @@ +class Solution: + def findKthBit(self, n: int, k: int) -> str: + if n == 1: + return '0' + midIndex = pow(2, n - 1) # 1-indexed + if k == midIndex: + return '1' + if k < midIndex: + return self.findKthBit(n - 1, k) + return '1' if self.findKthBit(n - 1, midIndex * 2 - k) == '0' else '0' diff --git a/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.cpp b/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.cpp new file mode 100644 index 00000000000..4f4b92352bd --- /dev/null +++ b/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int maxNonOverlapping(vector& nums, int target) { + // Ending the subarray ASAP always has a better result. + int ans = 0; + int prefix = 0; + unordered_set prefixes{0}; + + // Greedily find the subarrays that equal to the target. + for (const int num : nums) { + // Check if there is a subarray ends in here and equals to the target. + prefix += num; + if (prefixes.contains(prefix - target)) { + // Find one and discard all the prefixes that have been used. + ++ans; + prefix = 0; + prefixes = {0}; + } else { + prefixes.insert(prefix); + } + } + + return ans; + } +}; diff --git a/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.java b/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.java new file mode 100644 index 00000000000..0e8963f5ad6 --- /dev/null +++ b/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.java @@ -0,0 +1,24 @@ +class Solution { + public static int maxNonOverlapping(int[] nums, int target) { + // Ending the subarray ASAP always has a better result. + int ans = 0; + int prefix = 0; + Set prefixes = new HashSet<>(Arrays.asList(0)); + + // Greedily find the subarrays that equal to the target. + for (int num : nums) { + prefix += num; + // Check if there is a subarray ends in here and equals to the target. + if (prefixes.contains(prefix - target)) { + // Find one and discard all the prefixes that have been used. + ans++; + prefix = 0; + prefixes = new HashSet<>(Arrays.asList(0)); + } else { + prefixes.add(prefix); + } + } + + return ans; + } +} diff --git a/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.py b/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.py new file mode 100644 index 00000000000..19e120c3a99 --- /dev/null +++ b/solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.py @@ -0,0 +1,20 @@ +class Solution: + def maxNonOverlapping(self, nums: List[int], target: int) -> int: + # Ending the subarray ASAP always has a better result. + ans = 0 + prefix = 0 + prefixes = {0} + + # Greedily find the subarrays that equal to the target. + for num in nums: + # Check if there is a subarray ends in here and equals to the target. + prefix += num + if prefix - target in prefixes: + # Find one and discard all the prefixes that have been used. + ans += 1 + prefix = 0 + prefixes = {0} + else: + prefixes.add(prefix) + + return ans diff --git a/solutions/1547. Minimum Cost to Cut a Stick/1547-2.cpp b/solutions/1547. Minimum Cost to Cut a Stick/1547-2.cpp new file mode 100644 index 00000000000..606e827e34b --- /dev/null +++ b/solutions/1547. Minimum Cost to Cut a Stick/1547-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minCost(int n, vector& cuts) { + cuts.push_back(0); + cuts.push_back(n); + ranges::sort(cuts); + + // dp[i][j] := minCost(cuts[i..j]) + vector> dp(cuts.size(), vector(cuts.size())); + + for (int d = 2; d < cuts.size(); ++d) + for (int i = 0; i + d < cuts.size(); ++i) { + const int j = i + d; + dp[i][j] = INT_MAX; + for (int k = i + 1; k < j; ++k) + dp[i][j] = min(dp[i][j], cuts[j] - cuts[i] + dp[i][k] + dp[k][j]); + } + + return dp[0][cuts.size() - 1]; + } +}; diff --git a/solutions/1547. Minimum Cost to Cut a Stick/1547-2.java b/solutions/1547. Minimum Cost to Cut a Stick/1547-2.java new file mode 100644 index 00000000000..2d31f7185f3 --- /dev/null +++ b/solutions/1547. Minimum Cost to Cut a Stick/1547-2.java @@ -0,0 +1,23 @@ +class Solution { + public int minCost(int n, int[] cuts) { + int[] A = new int[cuts.length + 2]; + System.arraycopy(cuts, 0, A, 1, cuts.length); + A[0] = 0; + A[A.length - 1] = n; + + Arrays.sort(A); + + // dp[i][j] := minCost(cuts[i..j]) + int[][] dp = new int[A.length][A.length]; + + for (int d = 2; d < A.length; ++d) + for (int i = 0; i + d < A.length; ++i) { + final int j = i + d; + dp[i][j] = Integer.MAX_VALUE; + for (int k = i + 1; k < j; ++k) + dp[i][j] = Math.min(dp[i][j], A[j] - A[i] + dp[i][k] + dp[k][j]); + } + + return dp[0][A.length - 1]; + } +} diff --git a/solutions/1547. Minimum Cost to Cut a Stick/1547-2.py b/solutions/1547. Minimum Cost to Cut a Stick/1547-2.py new file mode 100644 index 00000000000..d9c44863d4b --- /dev/null +++ b/solutions/1547. Minimum Cost to Cut a Stick/1547-2.py @@ -0,0 +1,14 @@ +class Solution: + def minCost(self, n: int, cuts: List[int]) -> int: + A = sorted([0] + cuts + [n]) + + dp = [[0] * len(A) for _ in range(len(A))] + + for d in range(2, len(A)): + for i in range(len(A) - d): + j = i + d + dp[i][j] = math.inf + for k in range(i + 1, j): + dp[i][j] = min(dp[i][j], A[j] - A[i] + dp[i][k] + dp[k][j]) + + return dp[0][len(A) - 1] diff --git a/solutions/1547. Minimum Cost to Cut a Stick/1547.cpp b/solutions/1547. Minimum Cost to Cut a Stick/1547.cpp new file mode 100644 index 00000000000..3831f5f2541 --- /dev/null +++ b/solutions/1547. Minimum Cost to Cut a Stick/1547.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minCost(int n, vector& cuts) { + cuts.push_back(0); + cuts.push_back(n); + ranges::sort(cuts); + vector> mem(cuts.size(), vector(cuts.size(), INT_MAX)); + return minCost(cuts, 0, cuts.size() - 1, mem); + } + + private: + // Returns minCost(cuts[i..j]). + int minCost(const vector& cuts, int i, int j, vector>& mem) { + if (j - i <= 1) + return 0; + if (mem[i][j] != INT_MAX) + return mem[i][j]; + + for (int k = i + 1; k < j; ++k) + mem[i][j] = min(mem[i][j], cuts[j] - cuts[i] + minCost(cuts, i, k, mem) + + minCost(cuts, k, j, mem)); + + return mem[i][j]; + } +}; diff --git a/solutions/1547. Minimum Cost to Cut a Stick/1547.java b/solutions/1547. Minimum Cost to Cut a Stick/1547.java new file mode 100644 index 00000000000..510fc8287d7 --- /dev/null +++ b/solutions/1547. Minimum Cost to Cut a Stick/1547.java @@ -0,0 +1,26 @@ +class Solution { + public int minCost(int n, int[] cuts) { + int[] extendedCuts = new int[cuts.length + 2]; + int[][] mem = new int[extendedCuts.length][extendedCuts.length]; + System.arraycopy(cuts, 0, extendedCuts, 1, cuts.length); + extendedCuts[0] = 0; + extendedCuts[extendedCuts.length - 1] = n; + Arrays.sort(extendedCuts); + Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + return minCost(extendedCuts, 0, extendedCuts.length - 1, mem); + } + + // Returns minCost(cuts[i..j]). + private int minCost(int[] cuts, int i, int j, int[][] mem) { + if (j - i <= 1) + return 0; + if (mem[i][j] != Integer.MAX_VALUE) + return mem[i][j]; + + for (int k = i + 1; k < j; ++k) + mem[i][j] = Math.min(mem[i][j], + cuts[j] - cuts[i] + minCost(cuts, i, k, mem) + minCost(cuts, k, j, mem)); + + return mem[i][j]; + } +} diff --git a/solutions/1547. Minimum Cost to Cut a Stick/1547.py b/solutions/1547. Minimum Cost to Cut a Stick/1547.py new file mode 100644 index 00000000000..22312038c6d --- /dev/null +++ b/solutions/1547. Minimum Cost to Cut a Stick/1547.py @@ -0,0 +1,12 @@ +class Solution: + def minCost(self, n: int, cuts: List[int]) -> int: + A = sorted([0] + cuts + [n]) + + @functools.lru_cache(None) + def dp(i, j): + if j - i <= 1: + return 0 + + return min(A[j] - A[i] + dp(i, k) + dp(k, j) for k in range(i + 1, j)) + + return dp(0, len(A) - 1) diff --git a/solutions/1548. The Most Similar Path in a Graph/1548.cpp b/solutions/1548. The Most Similar Path in a Graph/1548.cpp new file mode 100644 index 00000000000..b4bd8740270 --- /dev/null +++ b/solutions/1548. The Most Similar Path in a Graph/1548.cpp @@ -0,0 +1,66 @@ +class Solution { + public: + vector mostSimilar(int n, vector>& roads, + vector& names, vector& targetPath) { + this->names = names; + this->targetPath = targetPath; + // cost[i][j] := the minimum cost to start from names[i] in path[j] + this->cost.resize(names.size(), vector(targetPath.size(), -1)); + // next[i][j] := the best next of names[i] in path[j] + this->next.resize(names.size(), vector(targetPath.size())); + this->graph.resize(n); + + for (const vector& road : roads) { + graph[road[0]].push_back(road[1]); + graph[road[1]].push_back(road[0]); + } + + int minDist = INT_MAX; + int start = 0; + + for (int i = 0; i < n; ++i) { + const int dist = dfs(i, 0); + if (dist < minDist) { + minDist = dist; + start = i; + } + } + + vector ans; + + while (ans.size() < targetPath.size()) { + ans.push_back(start); + start = next[start][ans.size() - 1]; + } + + return ans; + } + + private: + vector names; + vector targetPath; + vector> cost; + vector> next; + vector> graph; + + int dfs(int nameIndex, int pathIndex) { + if (cost[nameIndex][pathIndex] != -1) + return cost[nameIndex][pathIndex]; + + const int editDist = names[nameIndex] != targetPath[pathIndex]; + if (pathIndex == targetPath.size() - 1) + return editDist; + + int minDist = INT_MAX; + + for (const int v : graph[nameIndex]) { + const int dist = dfs(v, pathIndex + 1); + if (dist < minDist) { + minDist = dist; + next[nameIndex][pathIndex] = v; + } + } + + return cost[nameIndex][pathIndex] = editDist + minDist; + } +}; diff --git a/solutions/1548. The Most Similar Path in a Graph/1548.java b/solutions/1548. The Most Similar Path in a Graph/1548.java new file mode 100644 index 00000000000..3807ad6ba54 --- /dev/null +++ b/solutions/1548. The Most Similar Path in a Graph/1548.java @@ -0,0 +1,69 @@ +class Solution { + public List mostSimilar(int n, int[][] roads, String[] names, String[] targetPath) { + this.names = names; + this.targetPath = targetPath; + // cost[i][j] := the minimum cost to start from names[i] in path[j] + this.cost = new int[names.length][targetPath.length]; + // next[i][j] := the best next of names[i] in path[j] + this.next = new int[names.length][targetPath.length]; + this.graph = new List[n]; + + Arrays.stream(cost).forEach(a -> Arrays.fill(a, -1)); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] road : roads) { + graph[road[0]].add(road[1]); + graph[road[1]].add(road[0]); + } + + int minDist = Integer.MAX_VALUE; + int start = 0; + + // Start from different names + for (int i = 0; i < names.length; ++i) { + final int dist = dfs(i, 0); + if (dist < minDist) { + minDist = dist; + start = i; + } + } + + List ans = new ArrayList<>(); + + while (ans.size() < targetPath.length) { + ans.add(start); + start = next[start][ans.size() - 1]; + } + + return ans; + } + + private String[] names; + private String[] targetPath; + private int[][] cost; + private int[][] next; + private List[] graph; + + private int dfs(int nameIndex, int pathIndex) { + if (cost[nameIndex][pathIndex] != -1) + return cost[nameIndex][pathIndex]; + + final int editDist = names[nameIndex].equals(targetPath[pathIndex]) ? 0 : 1; + if (pathIndex == targetPath.length - 1) + return editDist; + + int minDist = Integer.MAX_VALUE; + + for (final int v : graph[nameIndex]) { + final int dist = dfs(v, pathIndex + 1); + if (dist < minDist) { + minDist = dist; + next[nameIndex][pathIndex] = v; + } + } + + return cost[nameIndex][pathIndex] = editDist + minDist; + } +} diff --git a/solutions/1548. The Most Similar Path in a Graph/1548.py b/solutions/1548. The Most Similar Path in a Graph/1548.py new file mode 100644 index 00000000000..276dcf9960c --- /dev/null +++ b/solutions/1548. The Most Similar Path in a Graph/1548.py @@ -0,0 +1,48 @@ +class Solution: + def mostSimilar(self, n: int, roads: List[List[int]], names: List[str], + targetPath: List[str]) -> List[int]: + # cost[i][j] := the minimum cost to start from names[i] in path[j] + cost = [[-1] * len(targetPath) for _ in range(len(names))] + # next[i][j] := the best next of names[i] in path[j] + next = [[0] * len(targetPath) for _ in range(len(names))] + graph = [[] for _ in range(n)] + + for u, v in roads: + graph[u].append(v) + graph[v].append(u) + + minDist = math.inf + start = 0 + + def dfs(nameIndex: int, pathIndex: int) -> int: + if cost[nameIndex][pathIndex] != -1: + return cost[nameIndex][pathIndex] + + editDist = names[nameIndex] != targetPath[pathIndex] + if pathIndex == len(targetPath) - 1: + return editDist + + minDist = math.inf + + for v in graph[nameIndex]: + dist = dfs(v, pathIndex + 1) + if dist < minDist: + minDist = dist + next[nameIndex][pathIndex] = v + + cost[nameIndex][pathIndex] = editDist + minDist + return editDist + minDist + + for i in range(n): + dist = dfs(i, 0) + if dist < minDist: + minDist = dist + start = i + + ans = [] + + while len(ans) < len(targetPath): + ans.append(start) + start = next[start][len(ans) - 1] + + return ans diff --git a/solutions/1549. The Most Recent Orders for Each Product/1549.sql b/solutions/1549. The Most Recent Orders for Each Product/1549.sql new file mode 100644 index 00000000000..7f4ccaa789c --- /dev/null +++ b/solutions/1549. The Most Recent Orders for Each Product/1549.sql @@ -0,0 +1,23 @@ +WITH + RankedProducts AS ( + SELECT + Products.product_name, + Products.product_id, + Orders.order_id, + Orders.order_date, + RANK() OVER( + PARTITION BY Products.product_name + ORDER BY Orders.order_date DESC + ) `rank` + FROM Products + INNER JOIN Orders + USING (product_id) + ) +SELECT + RankedProducts.product_name, + RankedProducts.product_id, + RankedProducts.order_id, + RankedProducts.order_date +FROM RankedProducts +WHERE `rank` = 1 +ORDER BY 1, 2, 3; diff --git a/solutions/155. Min Stack/155.cpp b/solutions/155. Min Stack/155.cpp new file mode 100644 index 00000000000..68ef0f3045d --- /dev/null +++ b/solutions/155. Min Stack/155.cpp @@ -0,0 +1,24 @@ +class MinStack { + public: + void push(int x) { + if (stack.empty()) + stack.emplace(x, x); + else + stack.emplace(x, min(x, stack.top().second)); + } + + void pop() { + stack.pop(); + } + + int top() { + return stack.top().first; + } + + int getMin() { + return stack.top().second; + } + + private: + stack> stack; // {x, min} +}; diff --git a/solutions/155. Min Stack/155.java b/solutions/155. Min Stack/155.java new file mode 100644 index 00000000000..4585753cec2 --- /dev/null +++ b/solutions/155. Min Stack/155.java @@ -0,0 +1,22 @@ +class MinStack { + public void push(int x) { + if (stack.isEmpty()) + stack.push(new int[] {x, x}); + else + stack.push(new int[] {x, Math.min(x, stack.peek()[1])}); + } + + public void pop() { + stack.pop(); + } + + public int top() { + return stack.peek()[0]; + } + + public int getMin() { + return stack.peek()[1]; + } + + private Stack stack = new Stack<>(); // {x, min} +} diff --git a/solutions/155. Min Stack/155.py b/solutions/155. Min Stack/155.py new file mode 100644 index 00000000000..2bab031b3bb --- /dev/null +++ b/solutions/155. Min Stack/155.py @@ -0,0 +1,16 @@ +class MinStack: + def __init__(self): + self.stack = [] + + def push(self, x: int) -> None: + mn = x if not self.stack else min(self.stack[-1][1], x) + self.stack.append([x, mn]) + + def pop(self) -> None: + self.stack.pop() + + def top(self) -> int: + return self.stack[-1][0] + + def getMin(self) -> int: + return self.stack[-1][1] diff --git a/solutions/1550. Three Consecutive Odds/1550.cpp b/solutions/1550. Three Consecutive Odds/1550.cpp new file mode 100644 index 00000000000..dc08e336bc0 --- /dev/null +++ b/solutions/1550. Three Consecutive Odds/1550.cpp @@ -0,0 +1,13 @@ + +class Solution { + public: + bool threeConsecutiveOdds(vector& arr) { + int count = 0; + for (const int a : arr) { + count = a % 2 == 0 ? 0 : count + 1; + if (count == 3) + return true; + } + return false; + } +}; diff --git a/solutions/1550. Three Consecutive Odds/1550.java b/solutions/1550. Three Consecutive Odds/1550.java new file mode 100644 index 00000000000..87afe7a50fe --- /dev/null +++ b/solutions/1550. Three Consecutive Odds/1550.java @@ -0,0 +1,11 @@ +class Solution { + public boolean threeConsecutiveOdds(int[] arr) { + int count = 0; + for (final int a : arr) { + count = a % 2 == 0 ? 0 : count + 1; + if (count == 3) + return true; + } + return false; + } +} diff --git a/solutions/1550. Three Consecutive Odds/1550.py b/solutions/1550. Three Consecutive Odds/1550.py new file mode 100644 index 00000000000..d7c51efcf2c --- /dev/null +++ b/solutions/1550. Three Consecutive Odds/1550.py @@ -0,0 +1,8 @@ +class Solution: + def threeConsecutiveOdds(self, arr: List[int]) -> bool: + count = 0 + for a in arr: + count = 0 if a % 2 == 0 else count + 1 + if count == 3: + return True + return False diff --git a/solutions/1551. Minimum Operations to Make Array Equal/1551.cpp b/solutions/1551. Minimum Operations to Make Array Equal/1551.cpp new file mode 100644 index 00000000000..96faa39d0b3 --- /dev/null +++ b/solutions/1551. Minimum Operations to Make Array Equal/1551.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minOperations(int n) { + // median := median of arr + // diffs[i] := median - arr[i] where i <= i <= n / 2 + // ans := sum(diffs) + // e.g. + // n = 5, arr = [1, 3, 5, 7, 9], diffs = [4, 2] + // ans = (4 + 2) * 2 / 2 = 6 + // n = 6, arr = [1, 3, 5, 7, 9, 11], diffs = [5, 3, 1] + // ans = (5 + 1) * 3 / 2 = 9 + const int halfSize = n / 2; + const int median = (arr(n) + arr(1)) / 2; + const int firstDiff = median - arr(1); + const int lastDiff = median - arr(halfSize); + return (firstDiff + lastDiff) * halfSize / 2; + } + + private: + // Returns the i-th element of `arr`, where 1 <= i <= n. + int arr(int i) { + return (i - 1) * 2 + 1; + } +}; diff --git a/solutions/1551. Minimum Operations to Make Array Equal/1551.java b/solutions/1551. Minimum Operations to Make Array Equal/1551.java new file mode 100644 index 00000000000..ba0e73f5e67 --- /dev/null +++ b/solutions/1551. Minimum Operations to Make Array Equal/1551.java @@ -0,0 +1,22 @@ +class Solution { + public int minOperations(int n) { + // median := median of arr + // diffs[i] := median - arr[i] where i <= i <= n / 2 + // ans := sum(diffs) + // e.g. + // n = 5, arr = [1, 3, 5, 7, 9], diffs = [4, 2] + // ans = (4 + 2) * 2 / 2 = 6 + // n = 6, arr = [1, 3, 5, 7, 9, 11], diffs = [5, 3, 1] + // ans = (5 + 1) * 3 / 2 = 9 + final int halfSize = n / 2; + final int median = (arr(n) + arr(1)) / 2; + final int firstDiff = median - arr(1); + final int lastDiff = median - arr(halfSize); + return (firstDiff + lastDiff) * halfSize / 2; + } + + // Returns the i-th element of `arr`, where 1 <= i <= n. + private int arr(int i) { + return (i - 1) * 2 + 1; + } +} diff --git a/solutions/1551. Minimum Operations to Make Array Equal/1551.py b/solutions/1551. Minimum Operations to Make Array Equal/1551.py new file mode 100644 index 00000000000..0e747231087 --- /dev/null +++ b/solutions/1551. Minimum Operations to Make Array Equal/1551.py @@ -0,0 +1,19 @@ +class Solution: + def minOperations(self, n: int) -> int: + def arr(self, i: int) -> int: + """Returns the i-th element of `arr`, where 1 <= i <= n.""" + return (i - 1) * 2 + 1 + + # median := median of arr + # diffs[i] := median - arr[i] where i <= i <= n // 2 + # ans := sum(diffs) + # e.g. + # n = 5, arr = [1, 3, 5, 7, 9], diffs = [4, 2] + # ans = (4 + 2) * 2 // 2 = 6 + # n = 6, arr = [1, 3, 5, 7, 9, 11], diffs = [5, 3, 1] + # ans = (5 + 1) * 3 // 2 = 9 + halfSize = n // 2 + median = (arr(n) + arr(1)) // 2 + firstDiff = median - arr(1) + lastDiff = median - arr(halfSize) + return (firstDiff + lastDiff) * halfSize // 2 diff --git a/solutions/1552. Magnetic Force Between Two Balls/1552.cpp b/solutions/1552. Magnetic Force Between Two Balls/1552.cpp new file mode 100644 index 00000000000..eaef1e2cacc --- /dev/null +++ b/solutions/1552. Magnetic Force Between Two Balls/1552.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int maxDistance(vector& position, int m) { + ranges::sort(position); + + int l = 1; + int r = position.back() - position.front(); + + while (l < r) { + const int mid = r - (r - l) / 2; + if (numBalls(position, mid) >= m) // There're too many balls. + l = mid; + else // There're too few balls. + r = mid - 1; + } + + return l; + } + + private: + int numBalls(const vector& position, int force) { + int balls = 0; + int prevPosition = -force; + for (const int pos : position) + if (pos - prevPosition >= force) { + ++balls; + prevPosition = pos; + } + return balls; + } +}; diff --git a/solutions/1552. Magnetic Force Between Two Balls/1552.java b/solutions/1552. Magnetic Force Between Two Balls/1552.java new file mode 100644 index 00000000000..aeb1c4de1c6 --- /dev/null +++ b/solutions/1552. Magnetic Force Between Two Balls/1552.java @@ -0,0 +1,29 @@ +class Solution { + public int maxDistance(int[] position, int m) { + Arrays.sort(position); + + int l = 1; + int r = position[position.length - 1] - position[0]; + + while (l < r) { + final int mid = r - (r - l) / 2; + if (numBalls(position, mid) >= m) // There're too many balls. + l = mid; + else // There're too few balls. + r = mid - 1; + } + + return l; + } + + private int numBalls(int[] position, int force) { + int balls = 0; + int prevPosition = -force; + for (final int pos : position) + if (pos - prevPosition >= force) { + balls++; + prevPosition = pos; + } + return balls; + } +} diff --git a/solutions/1552. Magnetic Force Between Two Balls/1552.py b/solutions/1552. Magnetic Force Between Two Balls/1552.py new file mode 100644 index 00000000000..3e4a7661430 --- /dev/null +++ b/solutions/1552. Magnetic Force Between Two Balls/1552.py @@ -0,0 +1,24 @@ +class Solution: + def maxDistance(self, position: List[int], m: int) -> int: + position.sort() + + l = 1 + r = position[-1] - position[0] + + def numBalls(force: int) -> int: + balls = 0 + prevPosition = -force + for pos in position: + if pos - prevPosition >= force: + balls += 1 + prevPosition = pos + return balls + + while l < r: + mid = r - (r - l) // 2 + if numBalls(mid) >= m: + l = mid + else: + r = mid - 1 + + return l diff --git a/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.cpp b/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.cpp new file mode 100644 index 00000000000..e23b04f2d8e --- /dev/null +++ b/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minDays(int n) { + if (n <= 1) + return n; + if (const auto it = mem.find(n); it != mem.cend()) + return it->second; + return mem[n] = 1 + min(minDays(n / 3) + n % 3, // + minDays(n / 2) + n % 2); + } + + private: + unordered_map mem; +}; diff --git a/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.java b/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.java new file mode 100644 index 00000000000..3e6a18360d0 --- /dev/null +++ b/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.java @@ -0,0 +1,15 @@ +class Solution { + public int minDays(int n) { + if (n <= 1) + return n; + if (dp.containsKey(n)) + return dp.get(n); + + final int res = 1 + Math.min(minDays(n / 3) + n % 3, // + minDays(n / 2) + n % 2); + dp.put(n, res); + return res; + } + + private Map dp = new HashMap<>(); +} diff --git a/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.py b/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.py new file mode 100644 index 00000000000..ae0d574b19f --- /dev/null +++ b/solutions/1553. Minimum Number of Days to Eat N Oranges/1553.py @@ -0,0 +1,7 @@ +class Solution: + @functools.lru_cache(None) + def minDays(self, n: int) -> int: + if n <= 1: + return n + return 1 + min(self.minDays(n // 3) + n % 3, + self.minDays(n // 2) + n % 2) diff --git a/solutions/1554. Strings Differ by One Character/1554-2.cpp b/solutions/1554. Strings Differ by One Character/1554-2.cpp new file mode 100644 index 00000000000..77e20777ffd --- /dev/null +++ b/solutions/1554. Strings Differ by One Character/1554-2.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + bool differByOne(vector& dict) { + const int m = dict[0].length(); + vector wordToHash; + + for (const string& word : dict) + wordToHash.push_back(getHash(word)); + + // Compute the hash without each letter. + // e.g. hash of "abc" = 26^2 * 'a' + 26 * 'b' + 'c' + // newHash of "a*c" = hash - 26 * 'b' + int coefficient = 1; + for (int j = m - 1; j >= 0; --j) { + unordered_map> newHashToIndices; + for (int i = 0; i < dict.size(); ++i) { + const string& word = dict[i]; + const int newHash = + (wordToHash[i] - + static_cast(coefficient) * val(word[j]) % kMod + kMod) % + kMod; + if (const auto it = newHashToIndices.find(newHash); + it != newHashToIndices.cend()) + for (const int index : it->second) + // word[0..j) == dict[index][0..j) && + // word[j + 1..n) == dict[index][j + 1..n) + if (equal(word.begin(), word.begin() + j, dict[index].begin()) && + equal(word.begin() + j + 1, word.end(), + dict[index].begin() + j + 1)) + return true; + newHashToIndices[newHash].push_back(i); + } + coefficient = 26L * coefficient % kMod; + } + + return false; + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the hash of `s`. Assume the length of `s` is m. + // e.g. getHash(s) = 26^(m - 1) * s[0] + 26^(m - 2) * s[1] + ... + s[m - 1]. + int getHash(const string& s) { + int hash = 0; + for (const char c : s) + hash = (26L * hash + val(c)) % kMod; + return hash; + } + + constexpr int val(char c) { + return c - 'a'; + } +}; diff --git a/solutions/1554. Strings Differ by One Character/1554-2.java b/solutions/1554. Strings Differ by One Character/1554-2.java new file mode 100644 index 00000000000..22480dbc86a --- /dev/null +++ b/solutions/1554. Strings Differ by One Character/1554-2.java @@ -0,0 +1,51 @@ +class Solution { + public boolean differByOne(String[] dict) { + final int m = dict[0].length(); + int[] wordToHash = new int[dict.length]; + + for (int i = 0; i < dict.length; ++i) + wordToHash[i] = getHash(dict[i]); + + // Compute the hash without each letter. + // e.g. hash of "abc" = 26^2 * 'a' + 26 * 'b' + 'c' + // newHash of "a*c" = hash - 26 * 'b' + int coefficient = 1; + for (int j = m - 1; j >= 0; --j) { + Map> newHashToIndices = new HashMap<>(); + for (int i = 0; i < dict.length; ++i) { + final int newHash = + (int) ((wordToHash[i] - (long) coefficient * val(dict[i].charAt(j)) % kMod + kMod) % + kMod); + if (newHashToIndices.containsKey(newHash)) { + for (final int index : newHashToIndices.get(newHash)) { + if (dict[i].substring(0, j).equals(dict[index].substring(0, j)) && + dict[i].substring(j + 1).equals(dict[index].substring(j + 1))) { + return true; + } + } + } + newHashToIndices.putIfAbsent(newHash, new ArrayList<>()); + newHashToIndices.get(newHash).add(i); + } + coefficient = (int) ((26L * coefficient) % kMod); + } + + return false; + } + + private static final int kMod = 1_000_000_007; + + // Returns the hash of `s`. Assume the length of `s` is m. + // e.g. getHash(s) = 26^(m - 1) * s[0] + 26^(m - 2) * s[1] + ... + s[m - 1]. + private int getHash(String s) { + int hash = 0; + for (final char c : s.toCharArray()) { + hash = (int) ((26L * hash + val(c)) % kMod); + } + return hash; + } + + private int val(char c) { + return c - 'a'; + } +} diff --git a/solutions/1554. Strings Differ by One Character/1554-2.py b/solutions/1554. Strings Differ by One Character/1554-2.py new file mode 100644 index 00000000000..c448e25a970 --- /dev/null +++ b/solutions/1554. Strings Differ by One Character/1554-2.py @@ -0,0 +1,35 @@ +class Solution: + def differByOne(self, dict: List[str]) -> bool: + kMod = 1_000_000_007 + m = len(dict[0]) + + def val(c: str) -> int: + return ord(c) - ord('a') + + def getHash(s: str) -> int: + """Returns the hash of `s`. Assume the length of `s` is m. + + e.g. getHash(s) = 26^(m - 1) * s[0] + 26^(m - 2) * s[1] + ... + s[m - 1]. + """ + hash = 0 + for c in s: + hash = (26 * hash + val(c)) + return hash + + wordToHash = [getHash(word) for word in dict] + + # Compute the hash without each letter. + # e.g. hash of "abc" = 26^2 * 'a' + 26 * 'b' + 'c' + # newHash of "a*c" = hash - 26 * 'b' + coefficient = 1 + for j in range(m - 1, -1, -1): + newHashToIndices = collections.defaultdict(list) + for i, (word, hash) in enumerate(zip(dict, wordToHash)): + newHash = (hash - coefficient * val(word[j]) % kMod + kMod) % kMod + if any(word[:j] == dict[index][:j] and word[j + 1:] == dict[index][j + 1:] + for index in newHashToIndices[newHash]): + return True + newHashToIndices[newHash].append(i) + coefficient = (26 * coefficient) % kMod + + return False diff --git a/solutions/1554. Strings Differ by One Character/1554.cpp b/solutions/1554. Strings Differ by One Character/1554.cpp new file mode 100644 index 00000000000..470d61010c1 --- /dev/null +++ b/solutions/1554. Strings Differ by One Character/1554.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool differByOne(vector& dict) { + unordered_set seen; + + for (string& word : dict) { + for (char& c : word) { + const char cache = c; + for (char next = 'a'; next <= 'z'; ++next) { + if (next == cache) + continue; + c = next; + if (seen.contains(word)) + return true; + } + c = cache; + } + seen.insert(word); + } + + return false; + } +}; diff --git a/solutions/1555. Bank Account Summary/1555.sql b/solutions/1555. Bank Account Summary/1555.sql new file mode 100644 index 00000000000..5f3c05b21d9 --- /dev/null +++ b/solutions/1555. Bank Account Summary/1555.sql @@ -0,0 +1,21 @@ +WITH + UpdatedUsers AS ( + SELECT + Users.user_id, + Users.user_name, + Users.credit + SUM( + CASE + WHEN Users.user_id = Transactions.paid_by THEN -Transactions.amount + WHEN Users.user_id = Transactions.paid_to THEN Transactions.amount + ELSE 0 + END + ) AS credit + FROM Users + LEFT JOIN Transactions + ON (Users.user_id IN (Transactions.paid_by, Transactions.paid_to)) + GROUP BY 1 + ) +SELECT + *, + IF(credit < 0, 'Yes', 'No') AS credit_limit_breached +FROM UpdatedUsers; \ No newline at end of file diff --git a/solutions/1556. Thousand Separator/1556.cpp b/solutions/1556. Thousand Separator/1556.cpp new file mode 100644 index 00000000000..fe8964e51c3 --- /dev/null +++ b/solutions/1556. Thousand Separator/1556.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + string thousandSeparator(int n) { + const string s = to_string(n); + string ans; + + for (int i = 0; i < s.length(); ++i) { + if (i > 0 && (s.length() - i) % 3 == 0) + ans += '.'; + ans += s[i]; + } + + return ans; + } +}; diff --git a/solutions/1556. Thousand Separator/1556.java b/solutions/1556. Thousand Separator/1556.java new file mode 100644 index 00000000000..1f784b604d9 --- /dev/null +++ b/solutions/1556. Thousand Separator/1556.java @@ -0,0 +1,14 @@ +class Solution { + public String thousandSeparator(int n) { + final String s = Integer.toString(n); + StringBuilder ans = new StringBuilder(); + + for (int i = 0; i < s.length(); ++i) { + if (i > 0 && (s.length() - i) % 3 == 0) + ans.append('.'); + ans.append(s.charAt(i)); + } + + return ans.toString(); + } +} diff --git a/solutions/1556. Thousand Separator/1556.py b/solutions/1556. Thousand Separator/1556.py new file mode 100644 index 00000000000..b777074e8aa --- /dev/null +++ b/solutions/1556. Thousand Separator/1556.py @@ -0,0 +1,3 @@ +class Solution: + def thousandSeparator(self, n: int) -> str: + return f'{n:,}'.replace(',', '.') diff --git a/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.cpp b/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.cpp new file mode 100644 index 00000000000..84f519b2fe7 --- /dev/null +++ b/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector findSmallestSetOfVertices(int n, vector>& edges) { + vector ans; + vector inDegrees(n); + + for (const vector& edge : edges) + ++inDegrees[edge[1]]; + + for (int i = 0; i < inDegrees.size(); ++i) + if (inDegrees[i] == 0) + ans.push_back(i); + + return ans; + } +}; diff --git a/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.java b/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.java new file mode 100644 index 00000000000..d07c63f279d --- /dev/null +++ b/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.java @@ -0,0 +1,15 @@ +class Solution { + public List findSmallestSetOfVertices(int n, List> edges) { + List ans = new ArrayList<>(); + int[] inDegrees = new int[n]; + + for (List edge : edges) + ++inDegrees[edge.get(1)]; + + for (int i = 0; i < inDegrees.length; ++i) + if (inDegrees[i] == 0) + ans.add(i); + + return ans; + } +} diff --git a/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.py b/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.py new file mode 100644 index 00000000000..bb87861850a --- /dev/null +++ b/solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.py @@ -0,0 +1,8 @@ +class Solution: + def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: + inDegrees = [0] * n + + for _, v in edges: + inDegrees[v] += 1 + + return [i for i, d in enumerate(inDegrees) if d == 0] diff --git a/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.cpp b/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.cpp new file mode 100644 index 00000000000..a7f6f511016 --- /dev/null +++ b/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int minOperations(vector& nums) { + const int maxNum = ranges::max(nums); + return accumulate(nums.begin(), nums.end(), 0, + [](int subtotal, unsigned num) { + return subtotal + popcount(num); + }) + (maxNum == 0 ? 0 : (int)log2(maxNum)); + } +}; diff --git a/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.java b/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.java new file mode 100644 index 00000000000..de1243cccfc --- /dev/null +++ b/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.java @@ -0,0 +1,7 @@ +class Solution { + public int minOperations(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + return Arrays.stream(nums).map(num -> Integer.bitCount(num)).sum() + + (maxNum == 0 ? 0 : (int) (Math.log(maxNum) / Math.log(2))); + } +} diff --git a/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.py b/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.py new file mode 100644 index 00000000000..6f06a8a091b --- /dev/null +++ b/solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.py @@ -0,0 +1,5 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + maxNum = max(nums) + return sum(num.bit_count() for num in nums) + \ + (0 if maxNum == 0 else maxNum.bit_length() - 1) diff --git a/solutions/1559. Detect Cycles in 2D Grid/1559.cpp b/solutions/1559. Detect Cycles in 2D Grid/1559.cpp new file mode 100644 index 00000000000..f24d9af90ed --- /dev/null +++ b/solutions/1559. Detect Cycles in 2D Grid/1559.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + bool containsCycle(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (seen[i][j]) + continue; + if (dfs(grid, i, j, -1, -1, grid[i][j], seen)) + return true; + } + + return false; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + bool dfs(const vector>& grid, int i, int j, int prevI, int prevJ, + char c, vector>& seen) { + seen[i][j] = true; + + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) + continue; + if (x == prevI && y == prevJ) + continue; + if (grid[x][y] != c) + continue; + if (seen[x][y]) + return true; + if (dfs(grid, x, y, i, j, c, seen)) + return true; + } + + return false; + } +}; diff --git a/solutions/1559. Detect Cycles in 2D Grid/1559.java b/solutions/1559. Detect Cycles in 2D Grid/1559.java new file mode 100644 index 00000000000..2c2f66f9a51 --- /dev/null +++ b/solutions/1559. Detect Cycles in 2D Grid/1559.java @@ -0,0 +1,40 @@ +class Solution { + public boolean containsCycle(char[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + boolean[][] seen = new boolean[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (seen[i][j]) + continue; + if (dfs(grid, i, j, -1, -1, grid[i][j], seen)) + return true; + } + + return false; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private boolean dfs(char[][] grid, int i, int j, int prevI, int prevJ, char c, boolean[][] seen) { + seen[i][j] = true; + + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) + continue; + if (x == prevI && y == prevJ) + continue; + if (grid[x][y] != c) + continue; + if (seen[x][y]) + return true; + if (dfs(grid, x, y, i, j, c, seen)) + return true; + } + + return false; + } +} diff --git a/solutions/156. Binary Tree Upside Down/156-2.cpp b/solutions/156. Binary Tree Upside Down/156-2.cpp new file mode 100644 index 00000000000..cfbe8352e13 --- /dev/null +++ b/solutions/156. Binary Tree Upside Down/156-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + TreeNode* upsideDownBinaryTree(TreeNode* root) { + TreeNode* prevRoot = nullptr; + TreeNode* prevRightChild = nullptr; + + while (root != nullptr) { + TreeNode* nextRoot = root->left; // Cache the next root. + root->left = prevRightChild; + prevRightChild = root->right; + root->right = prevRoot; + prevRoot = root; // Record the previous root. + root = nextRoot; // Update the root. + } + + return prevRoot; + } +}; diff --git a/solutions/156. Binary Tree Upside Down/156-2.java b/solutions/156. Binary Tree Upside Down/156-2.java new file mode 100644 index 00000000000..4ed39ff4963 --- /dev/null +++ b/solutions/156. Binary Tree Upside Down/156-2.java @@ -0,0 +1,17 @@ +class Solution { + public TreeNode upsideDownBinaryTree(TreeNode root) { + TreeNode prevRoot = null; + TreeNode prevRightChild = null; + + while (root != null) { + TreeNode nextRoot = root.left; // Cache the next root. + root.left = prevRightChild; + prevRightChild = root.right; + root.right = prevRoot; + prevRoot = root; // Record the previous root. + root = nextRoot; // Update the root. + } + + return prevRoot; + } +} diff --git a/solutions/156. Binary Tree Upside Down/156-2.py b/solutions/156. Binary Tree Upside Down/156-2.py new file mode 100644 index 00000000000..e5c4e0455e3 --- /dev/null +++ b/solutions/156. Binary Tree Upside Down/156-2.py @@ -0,0 +1,14 @@ +class Solution: + def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + prevRoot = None + prevRightChild = None + + while root: + nextRoot = root.left # Cache the next root. + root.left = prevRightChild + prevRightChild = root.right + root.right = prevRoot + prevRoot = root # Record the previous root. + root = nextRoot # Update the root. + + return prevRoot diff --git a/solutions/156. Binary Tree Upside Down/156.cpp b/solutions/156. Binary Tree Upside Down/156.cpp new file mode 100644 index 00000000000..141c8b69979 --- /dev/null +++ b/solutions/156. Binary Tree Upside Down/156.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + TreeNode* upsideDownBinaryTree(TreeNode* root) { + if (root == nullptr || root->left == nullptr) + return root; + + TreeNode* newRoot = upsideDownBinaryTree(root->left); + root->left->left = root->right; // 2's left = 3 (root's right) + root->left->right = root; // 2's right = 1 (root) + root->left = nullptr; + root->right = nullptr; + return newRoot; + } +}; diff --git a/solutions/156. Binary Tree Upside Down/156.java b/solutions/156. Binary Tree Upside Down/156.java new file mode 100644 index 00000000000..e8439358c8e --- /dev/null +++ b/solutions/156. Binary Tree Upside Down/156.java @@ -0,0 +1,13 @@ +class Solution { + public TreeNode upsideDownBinaryTree(TreeNode root) { + if (root == null || root.left == null) + return root; + + TreeNode newRoot = upsideDownBinaryTree(root.left); + root.left.left = root.right; // 2's left = 3 (root's right) + root.left.right = root; // 2's right = 1 (root) + root.left = null; + root.right = null; + return newRoot; + } +} diff --git a/solutions/156. Binary Tree Upside Down/156.py b/solutions/156. Binary Tree Upside Down/156.py new file mode 100644 index 00000000000..a9ac070e5ae --- /dev/null +++ b/solutions/156. Binary Tree Upside Down/156.py @@ -0,0 +1,11 @@ +class Solution: + def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root or not root.left: + return root + + newRoot = self.upsideDownBinaryTree(root.left) + root.left.left = root.right # 2's left = 3 (root's right) + root.left.right = root # 2's right = 1 (root) + root.left = None + root.right = None + return newRoot diff --git a/solutions/1560. Most Visited Sector in a Circular Track/1560.cpp b/solutions/1560. Most Visited Sector in a Circular Track/1560.cpp new file mode 100644 index 00000000000..8d06b4aa767 --- /dev/null +++ b/solutions/1560. Most Visited Sector in a Circular Track/1560.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector mostVisited(int n, vector& rounds) { + // 1. If start <= end, [start, end] is the most visited. + // + // s --------- n + // 1 -------------- n + // 1 ------ e + // + // 2. If start > end, [1, end] and [start, n] are the most visited. + // + // s -- n + // 1 -------------- n + // 1 ------ e + const int start = rounds.front(); + const int end = rounds.back(); + vector ans; + for (int i = 1; i <= n; ++i) + if (start <= end) { + if (start <= i && i <= end) + ans.push_back(i); + } else { // start > end + if (i >= start || i <= end) + ans.push_back(i); + } + return ans; + } +}; diff --git a/solutions/1560. Most Visited Sector in a Circular Track/1560.java b/solutions/1560. Most Visited Sector in a Circular Track/1560.java new file mode 100644 index 00000000000..a64083fddbb --- /dev/null +++ b/solutions/1560. Most Visited Sector in a Circular Track/1560.java @@ -0,0 +1,27 @@ +class Solution { + public List mostVisited(int n, int[] rounds) { + // 1. If start <= end, [start, end] is the most visited. + // + // s --------- n + // 1 -------------- n + // 1 ------ e + // + // 2. If start > end, [1, end] and [start, n] are the most visited. + // + // s -- n + // 1 -------------- n + // 1 ------ e + final int start = rounds[0]; + final int end = rounds[rounds.length - 1]; + List ans = new ArrayList<>(); + for (int i = 1; i <= n; ++i) + if (start <= end) { + if (start <= i && i <= end) + ans.add(i); + } else { // start > end + if (i >= start || i <= end) + ans.add(i); + } + return ans; + } +} diff --git a/solutions/1560. Most Visited Sector in a Circular Track/1560.py b/solutions/1560. Most Visited Sector in a Circular Track/1560.py new file mode 100644 index 00000000000..e7c6af3a750 --- /dev/null +++ b/solutions/1560. Most Visited Sector in a Circular Track/1560.py @@ -0,0 +1,18 @@ +class Solution: + def mostVisited(self, n: int, rounds: List[int]) -> List[int]: + # 1. if start <= end, [start, end] is the most visited. + # + # s --------- n + # 1 -------------- n + # 1 ------ e + # + # 2. if start > end, [1, end] and [start, n] are the most visited. + # + # s -- n + # 1 -------------- n + # 1 ------ e + start = rounds[0] + end = rounds[-1] + if start <= end: + return range(start, end + 1) + return list(range(1, end + 1)) + list(range(start, n + 1)) diff --git a/solutions/1561. Maximum Number of Coins You Can Get/1561.cpp b/solutions/1561. Maximum Number of Coins You Can Get/1561.cpp new file mode 100644 index 00000000000..d9052629870 --- /dev/null +++ b/solutions/1561. Maximum Number of Coins You Can Get/1561.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxCoins(vector& piles) { + ranges::sort(piles); + + int ans = 0; + + // piles = [S S M L M L], pick all the M. + for (int i = piles.size() / 3; i < piles.size(); i += 2) + ans += piles[i]; + + return ans; + } +}; diff --git a/solutions/1561. Maximum Number of Coins You Can Get/1561.java b/solutions/1561. Maximum Number of Coins You Can Get/1561.java new file mode 100644 index 00000000000..13508043f68 --- /dev/null +++ b/solutions/1561. Maximum Number of Coins You Can Get/1561.java @@ -0,0 +1,13 @@ +class Solution { + public int maxCoins(int[] piles) { + Arrays.sort(piles); + + int ans = 0; + + // piles = [S S M L M L], pick all the M. + for (int i = piles.length / 3; i < piles.length; i += 2) + ans += piles[i]; + + return ans; + } +} diff --git a/solutions/1561. Maximum Number of Coins You Can Get/1561.py b/solutions/1561. Maximum Number of Coins You Can Get/1561.py new file mode 100644 index 00000000000..fcfd0d7c99d --- /dev/null +++ b/solutions/1561. Maximum Number of Coins You Can Get/1561.py @@ -0,0 +1,3 @@ +class Solution: + def maxCoins(self, piles: List[int]) -> int: + return sum(sorted(piles)[len(piles) // 3::2]) diff --git a/solutions/1562. Find Latest Group of Size M/1562.cpp b/solutions/1562. Find Latest Group of Size M/1562.cpp new file mode 100644 index 00000000000..73f600cbcec --- /dev/null +++ b/solutions/1562. Find Latest Group of Size M/1562.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int findLatestStep(vector& arr, int m) { + if (arr.size() == m) + return arr.size(); + + int ans = -1; + int step = 0; + // sizes[i] := the size of the group starting from i or ending in i + // (1-indexed) + vector sizes(arr.size() + 2); + + for (const int i : arr) { + ++step; + // In the previous step, there exists a group with a size of m. + if (sizes[i - 1] == m || sizes[i + 1] == m) + ans = step - 1; + const int head = i - sizes[i - 1]; + const int tail = i + sizes[i + 1]; + sizes[head] = tail - head + 1; + sizes[tail] = tail - head + 1; + } + + return ans; + } +}; diff --git a/solutions/1562. Find Latest Group of Size M/1562.java b/solutions/1562. Find Latest Group of Size M/1562.java new file mode 100644 index 00000000000..c638831c0d0 --- /dev/null +++ b/solutions/1562. Find Latest Group of Size M/1562.java @@ -0,0 +1,25 @@ +class Solution { + public int findLatestStep(int[] arr, int m) { + if (arr.length == m) + return arr.length; + + int ans = -1; + int step = 0; + // sizes[i] := the size of the group starting from i or ending in i + // (1-indexed) + int[] sizes = new int[arr.length + 2]; + + for (final int i : arr) { + ++step; + // In the previous step, there exists a group with a size of m. + if (sizes[i - 1] == m || sizes[i + 1] == m) + ans = step - 1; + final int head = i - sizes[i - 1]; + final int tail = i + sizes[i + 1]; + sizes[head] = tail - head + 1; + sizes[tail] = tail - head + 1; + } + + return ans; + } +} diff --git a/solutions/1562. Find Latest Group of Size M/1562.py b/solutions/1562. Find Latest Group of Size M/1562.py new file mode 100644 index 00000000000..c13c39136df --- /dev/null +++ b/solutions/1562. Find Latest Group of Size M/1562.py @@ -0,0 +1,22 @@ +class Solution: + def findLatestStep(self, arr: List[int], m: int) -> int: + if len(arr) == m: + return len(arr) + + ans = -1 + step = 0 + # sizes[i] := the size of the group starting from i or ending in i + # (1-indexed) + sizes = [0] * (len(arr) + 2) + + for i in arr: + step += 1 + # In the previous step, there exists a group with a size of m. + if sizes[i - 1] == m or sizes[i + 1] == m: + ans = step - 1 + head = i - sizes[i - 1] + tail = i + sizes[i + 1] + sizes[head] = tail - head + 1 + sizes[tail] = tail - head + 1 + + return ans diff --git a/solutions/1563. Stone Game V/1563.cpp b/solutions/1563. Stone Game V/1563.cpp new file mode 100644 index 00000000000..cba701c7977 --- /dev/null +++ b/solutions/1563. Stone Game V/1563.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int stoneGameV(vector& stoneValue) { + const int n = stoneValue.size(); + vector> mem(n, vector(n, INT_MIN)); + vector prefix(n + 1); + partial_sum(stoneValue.begin(), stoneValue.end(), prefix.begin() + 1); + return stoneGameV(stoneValue, 0, n - 1, prefix, mem); + } + + private: + // Returns the maximum score that Alice can obtain from stoneValue[i..j]. + int stoneGameV(const vector& stoneValue, int i, int j, + const vector& prefix, vector>& mem) { + if (i == j) + return 0; + if (mem[i][j] > 0) + return mem[i][j]; + + // Try all the possible partitions. + for (int p = i; p < j; ++p) { + // sum(stoneValue[i..p]) + const int leftSum = prefix[p + 1] - prefix[i]; + const int throwRight = + leftSum + stoneGameV(stoneValue, i, p, prefix, mem); + // sum(stoneValue[p + 1..j]) + const int rightSum = prefix[j + 1] - prefix[p + 1]; + const int throwLeft = + rightSum + stoneGameV(stoneValue, p + 1, j, prefix, mem); + if (leftSum < rightSum) // Bob throws the right row. + mem[i][j] = max(mem[i][j], throwRight); + else if (leftSum > rightSum) // Bob throws the left row. + mem[i][j] = max(mem[i][j], throwLeft); + else // Alice decides which row to throw. + mem[i][j] = max({mem[i][j], throwLeft, throwRight}); + } + + return mem[i][j]; + } +}; diff --git a/solutions/1563. Stone Game V/1563.java b/solutions/1563. Stone Game V/1563.java new file mode 100644 index 00000000000..683ddd0d49c --- /dev/null +++ b/solutions/1563. Stone Game V/1563.java @@ -0,0 +1,37 @@ +class Solution { + public int stoneGameV(int[] stoneValue) { + final int n = stoneValue.length; + int[][] mem = new int[n][n]; + int[] prefix = new int[n + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MIN_VALUE)); + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + stoneValue[i]; + return stoneGameV(stoneValue, 0, n - 1, prefix, mem); + } + + // Returns the maximum score that Alice can obtain from stoneValue[i..j]. + private int stoneGameV(int[] stoneValue, int i, int j, int[] prefix, int[][] mem) { + if (i == j) + return 0; + if (mem[i][j] != Integer.MIN_VALUE) + return mem[i][j]; + + // Try all the possible partitions. + for (int p = i; p < j; ++p) { + // sum(stoneValue[i..p]) + final int leftSum = prefix[p + 1] - prefix[i]; + final int throwRight = leftSum + stoneGameV(stoneValue, i, p, prefix, mem); + // sum(stoneValue[p + 1..j]) + final int rightSum = prefix[j + 1] - prefix[p + 1]; + final int throwLeft = rightSum + stoneGameV(stoneValue, p + 1, j, prefix, mem); + if (leftSum < rightSum) + mem[i][j] = Math.max(mem[i][j], throwRight); + else if (leftSum > rightSum) + mem[i][j] = Math.max(mem[i][j], throwLeft); + else + mem[i][j] = Math.max(Math.max(mem[i][j], throwLeft), throwRight); + } + + return mem[i][j]; + } +} diff --git a/solutions/1564. Put Boxes Into the Warehouse I/1564-2.cpp b/solutions/1564. Put Boxes Into the Warehouse I/1564-2.cpp new file mode 100644 index 00000000000..8ff83570519 --- /dev/null +++ b/solutions/1564. Put Boxes Into the Warehouse I/1564-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxBoxesInWarehouse(vector& boxes, vector& warehouse) { + int i = 0; // warehouse's index + + ranges::sort(boxes, greater<>()); + + for (const int box : boxes) + if (i < warehouse.size() && warehouse[i] >= box) + ++i; + + return i; + } +}; diff --git a/solutions/1564. Put Boxes Into the Warehouse I/1564-2.java b/solutions/1564. Put Boxes Into the Warehouse I/1564-2.java new file mode 100644 index 00000000000..add20cb412c --- /dev/null +++ b/solutions/1564. Put Boxes Into the Warehouse I/1564-2.java @@ -0,0 +1,16 @@ +class Solution { + public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { + boxes = Arrays.stream(boxes) + .boxed() + .sorted(Collections.reverseOrder()) + .mapToInt(Integer::intValue) + .toArray(); + int i = 0; // warehouse's index + + for (final int box : boxes) + if (i < warehouse.length && warehouse[i] >= box) + ++i; + + return i; + } +} diff --git a/solutions/1564. Put Boxes Into the Warehouse I/1564-2.py b/solutions/1564. Put Boxes Into the Warehouse I/1564-2.py new file mode 100644 index 00000000000..20555f59886 --- /dev/null +++ b/solutions/1564. Put Boxes Into the Warehouse I/1564-2.py @@ -0,0 +1,9 @@ +class Solution: + def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int: + i = 0 # warehouse's index + + for box in sorted(boxes, reverse=True): + if i < len(warehouse) and warehouse[i] >= box: + i += 1 + + return i diff --git a/solutions/1564. Put Boxes Into the Warehouse I/1564.cpp b/solutions/1564. Put Boxes Into the Warehouse I/1564.cpp new file mode 100644 index 00000000000..3ddde06f9f1 --- /dev/null +++ b/solutions/1564. Put Boxes Into the Warehouse I/1564.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxBoxesInWarehouse(vector& boxes, vector& warehouse) { + vector realWarehouse{warehouse[0]}; + + for (int i = 1; i < warehouse.size(); ++i) + realWarehouse.push_back(min(realWarehouse.back(), warehouse[i])); + + ranges::sort(boxes); + int i = 0; // boxes' index + for (int j = realWarehouse.size() - 1; j >= 0; j--) + if (i < boxes.size() && boxes[i] <= realWarehouse[j]) + ++i; + + return i; + } +}; diff --git a/solutions/1564. Put Boxes Into the Warehouse I/1564.java b/solutions/1564. Put Boxes Into the Warehouse I/1564.java new file mode 100644 index 00000000000..d816edbd077 --- /dev/null +++ b/solutions/1564. Put Boxes Into the Warehouse I/1564.java @@ -0,0 +1,17 @@ +class Solution { + public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { + int[] realWarehouse = new int[warehouse.length]; + realWarehouse[0] = warehouse[0]; + + for (int i = 1; i < warehouse.length; i++) + realWarehouse[i] = Math.min(realWarehouse[i - 1], warehouse[i]); + + Arrays.sort(boxes); + int i = 0; // boxes' index + for (int j = realWarehouse.length - 1; j >= 0; j--) + if (i < boxes.length && boxes[i] <= realWarehouse[j]) + ++i; + + return i; + } +} diff --git a/solutions/1564. Put Boxes Into the Warehouse I/1564.py b/solutions/1564. Put Boxes Into the Warehouse I/1564.py new file mode 100644 index 00000000000..65601e6da86 --- /dev/null +++ b/solutions/1564. Put Boxes Into the Warehouse I/1564.py @@ -0,0 +1,14 @@ +class Solution: + def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int: + realWarehouse = [warehouse[0]] + + for i in range(1, len(warehouse)): + realWarehouse.append(min(realWarehouse[-1], warehouse[i])) + + boxes.sort() + i = 0 # boxes' index + for height in reversed(realWarehouse): + if i < len(boxes) and boxes[i] <= height: + i += 1 + + return i diff --git a/solutions/1565. Unique Orders and Customers Per Month/1565.sql b/solutions/1565. Unique Orders and Customers Per Month/1565.sql new file mode 100644 index 00000000000..05bc18388fb --- /dev/null +++ b/solutions/1565. Unique Orders and Customers Per Month/1565.sql @@ -0,0 +1,7 @@ +SELECT + DATE_FORMAT(order_date, '%Y-%m') AS month, + COUNT(order_id) AS order_count, + COUNT(DISTINCT customer_id) AS customer_count +FROM Orders +WHERE invoice > 20 +GROUP BY 1; diff --git a/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.cpp b/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.cpp new file mode 100644 index 00000000000..645a3fcea96 --- /dev/null +++ b/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool containsPattern(vector& arr, int m, int k) { + int count = 0; + for (int i = m; i < arr.size(); ++i) { + count = arr[i] == arr[i - m] ? count + 1 : 0; + if (count == m * k - m) + return true; + } + return false; + } +}; diff --git a/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.java b/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.java new file mode 100644 index 00000000000..5dfa9c07192 --- /dev/null +++ b/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.java @@ -0,0 +1,11 @@ +class Solution { + public boolean containsPattern(int[] arr, int m, int k) { + int count = 0; + for (int i = m; i < arr.length; ++i) { + count = arr[i] == arr[i - m] ? count + 1 : 0; + if (count == m * k - m) + return true; + } + return false; + } +} diff --git a/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.py b/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.py new file mode 100644 index 00000000000..e29fe4c13fa --- /dev/null +++ b/solutions/1566. Detect Pattern of Length M Repeated K or More Times/1566.py @@ -0,0 +1,8 @@ +class Solution: + def containsPattern(self, arr: List[int], m: int, k: int) -> bool: + count = 0 + for i in range(m, len(arr)): + count = count + 1 if arr[i] == arr[i - m] else 0 + if count == m * k - m: + return True + return False diff --git a/solutions/1567. Maximum Length of Subarray With Positive Product/1567.cpp b/solutions/1567. Maximum Length of Subarray With Positive Product/1567.cpp new file mode 100644 index 00000000000..ebb57489efa --- /dev/null +++ b/solutions/1567. Maximum Length of Subarray With Positive Product/1567.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int getMaxLen(vector& nums) { + int ans = 0; + // the maximum length of subarrays ending in `num` with a negative product + int neg = 0; + // the maximum length of subarrays ending in `num` with a positive product + int pos = 0; + + for (const int num : nums) { + pos = num == 0 ? 0 : pos + 1; + neg = num == 0 || neg == 0 ? 0 : neg + 1; + if (num < 0) + swap(pos, neg); + ans = max(ans, pos); + } + + return ans; + } +}; diff --git a/solutions/1567. Maximum Length of Subarray With Positive Product/1567.java b/solutions/1567. Maximum Length of Subarray With Positive Product/1567.java new file mode 100644 index 00000000000..14bd164129a --- /dev/null +++ b/solutions/1567. Maximum Length of Subarray With Positive Product/1567.java @@ -0,0 +1,22 @@ +class Solution { + public int getMaxLen(int[] nums) { + int ans = 0; + // the maximum length of subarrays ending in `num` with a negative product + int neg = 0; + // the maximum length of subarrays ending in `num` with a positive product + int pos = 0; + + for (final int num : nums) { + pos = num == 0 ? 0 : pos + 1; + neg = num == 0 || neg == 0 ? 0 : neg + 1; + if (num < 0) { + final int temp = pos; + pos = neg; + neg = temp; + } + ans = Math.max(ans, pos); + } + + return ans; + } +} diff --git a/solutions/1567. Maximum Length of Subarray With Positive Product/1567.py b/solutions/1567. Maximum Length of Subarray With Positive Product/1567.py new file mode 100644 index 00000000000..d5a0de77935 --- /dev/null +++ b/solutions/1567. Maximum Length of Subarray With Positive Product/1567.py @@ -0,0 +1,16 @@ +class Solution: + def getMaxLen(self, nums: List[int]) -> int: + ans = 0 + # the maximum length of subarrays ending in `num` with a negative product + neg = 0 + # the maximum length of subarrays ending in `num` with a positive product + pos = 0 + + for num in nums: + pos = 0 if num == 0 else pos + 1 + neg = 0 if num == 0 or neg == 0 else neg + 1 + if num < 0: + pos, neg = neg, pos + ans = max(ans, pos) + + return ans diff --git a/solutions/1568. Minimum Number of Days to Disconnect Island/1568.cpp b/solutions/1568. Minimum Number of Days to Disconnect Island/1568.cpp new file mode 100644 index 00000000000..865d40a42da --- /dev/null +++ b/solutions/1568. Minimum Number of Days to Disconnect Island/1568.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + int minDays(vector>& grid) { + if (disconnected(grid)) + return 0; + + // Try to remove 1 land. + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == 1) { + grid[i][j] = 0; + if (disconnected(grid)) + return 1; + grid[i][j] = 1; + } + + // Remove 2 lands. + return 2; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + bool disconnected(const vector>& grid) { + int islandsCount = 0; + vector> seen(grid.size(), vector(grid[0].size())); + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) { + if (grid[i][j] == 0 || seen[i][j]) + continue; + if (++islandsCount > 1) + return true; + dfs(grid, i, j, seen); + } + return islandsCount != 1; + } + + void dfs(const vector>& grid, int i, int j, + vector>& seen) { + seen[i][j] = true; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) + continue; + if (grid[x][y] == 0 || seen[x][y]) + continue; + dfs(grid, x, y, seen); + } + } +}; diff --git a/solutions/1568. Minimum Number of Days to Disconnect Island/1568.java b/solutions/1568. Minimum Number of Days to Disconnect Island/1568.java new file mode 100644 index 00000000000..ae814f22182 --- /dev/null +++ b/solutions/1568. Minimum Number of Days to Disconnect Island/1568.java @@ -0,0 +1,49 @@ +class Solution { + public int minDays(int[][] grid) { + if (disconnected(grid)) + return 0; + + // Try to remove 1 land. + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 1) { + grid[i][j] = 0; + if (disconnected(grid)) + return 1; + grid[i][j] = 1; + } + + // Remove 2 lands. + return 2; + } + + private final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private boolean disconnected(int[][] grid) { + int islandsCount = 0; + boolean[][] seen = new boolean[grid.length][grid[0].length]; + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) { + if (grid[i][j] == 0 || seen[i][j]) + continue; + if (++islandsCount > 1) + return true; + dfs(grid, i, j, seen); + } + + return islandsCount != 1; + } + + private void dfs(int[][] grid, int i, int j, boolean[][] seen) { + seen[i][j] = true; + for (int[] dir : dirs) { + int x = i + dir[0]; + int y = j + dir[1]; + if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) + continue; + if (grid[x][y] == 0 || seen[x][y]) + continue; + dfs(grid, x, y, seen); + } + } +} diff --git a/solutions/1568. Minimum Number of Days to Disconnect Island/1568.py b/solutions/1568. Minimum Number of Days to Disconnect Island/1568.py new file mode 100644 index 00000000000..02451a8d09c --- /dev/null +++ b/solutions/1568. Minimum Number of Days to Disconnect Island/1568.py @@ -0,0 +1,44 @@ +class Solution: + def minDays(self, grid: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + + def dfs(grid: List[List[int]], i: int, j: int, seen: Set[Tuple[int, int]]): + seen.add((i, j)) + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if grid[x][y] == 0 or (x, y) in seen: + continue + dfs(grid, x, y, seen) + + def disconnected(grid: List[List[int]]) -> bool: + islandsCount = 0 + seen = set() + for i in range(m): + for j in range(n): + if grid[i][j] == 0 or (i, j) in seen: + continue + if islandsCount > 1: + return True + islandsCount += 1 + dfs(grid, i, j, seen) + return islandsCount != 1 + + if disconnected(grid): + return 0 + + # Try to remove 1 land. + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + grid[i][j] = 0 + if disconnected(grid): + return 1 + grid[i][j] = 1 + + # Remove 2 lands. + return 2 diff --git a/solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.cpp b/solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.cpp new file mode 100644 index 00000000000..a66150086f1 --- /dev/null +++ b/solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int numOfWays(vector& nums) { + comb = generate(nums.size() + 1); + return ways(nums) - 1; + } + + private: + static constexpr int kMod = 1'000'000'007; + // comb[n][k] := C(n, k) + vector> comb; + + int ways(const vector& nums) { + if (nums.size() <= 2) + return 1; + + vector left; + vector right; + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] < nums[0]) + left.push_back(nums[i]); + else + right.push_back(nums[i]); + + long ans = comb[nums.size() - 1][left.size()]; + ans = (ans * ways(left)) % kMod; + ans = (ans * ways(right)) % kMod; + return ans; + } + + // Same as 118. Pascal's Triangle + vector> generate(int numRows) { + vector> comb; + + for (int i = 0; i < numRows; ++i) + comb.push_back(vector(i + 1, 1)); + + for (int i = 2; i < numRows; ++i) + for (int j = 1; j < comb[i].size() - 1; ++j) + comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % kMod; + + return comb; + } +}; diff --git a/solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.java b/solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.java new file mode 100644 index 00000000000..12b5e6c1558 --- /dev/null +++ b/solutions/1569. Number of Ways to Reorder Array to Get Same BST/1569.java @@ -0,0 +1,46 @@ +class Solution { + public int numOfWays(int[] nums) { + comb = generate(nums.length + 1); + return ways(Arrays.stream(nums).boxed().collect(Collectors.toList())) - 1; + } + + private static final int kMod = 1_000_000_007; + // comb[n][k] := C(n, k) + private List> comb; + + private int ways(List nums) { + if (nums.size() <= 2) + return 1; + + List left = new ArrayList<>(); + List right = new ArrayList<>(); + + for (int i = 1; i < nums.size(); ++i) + if (nums.get(i) < nums.get(0)) + left.add(nums.get(i)); + else + right.add(nums.get(i)); + + long ans = comb.get(nums.size() - 1).get(left.size()); + ans = (ans * ways(left)) % kMod; + ans = (ans * ways(right)) % kMod; + return (int) ans; + } + + // Same as 118. Pascal's Triangle + public List> generate(int numRows) { + List> comb = new ArrayList<>(); + + for (int i = 0; i < numRows; ++i) { + Integer[] temp = new Integer[i + 1]; + Arrays.fill(temp, 1); + comb.add(Arrays.asList(temp)); + } + + for (int i = 2; i < numRows; ++i) + for (int j = 1; j < comb.get(i).size() - 1; ++j) + comb.get(i).set(j, (comb.get(i - 1).get(j - 1) + comb.get(i - 1).get(j)) % kMod); + + return comb; + } +} diff --git a/solutions/157. Read N Characters Given Read4/157-2.cpp b/solutions/157. Read N Characters Given Read4/157-2.cpp new file mode 100644 index 00000000000..1d9d050da26 --- /dev/null +++ b/solutions/157. Read N Characters Given Read4/157-2.cpp @@ -0,0 +1,39 @@ +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char *buf4); + */ + +class Solution { + public: + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + int read(char* buf, int n) { + char* buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size + int i = 0; // buf's index + + // While we're not reaching the tail (< 4 characters). + while (i + 4 < n) { + const int k = read4(buf + i); // Directly write to the buf. + if (k == 0) // Reach the EOF. + return i; + i += k; + } + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } +}; diff --git a/solutions/157. Read N Characters Given Read4/157.cpp b/solutions/157. Read N Characters Given Read4/157.cpp new file mode 100644 index 00000000000..1cf87ec836b --- /dev/null +++ b/solutions/157. Read N Characters Given Read4/157.cpp @@ -0,0 +1,31 @@ +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char *buf4); + */ + +class Solution { + public: + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + int read(char* buf, int n) { + char* buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } +}; diff --git a/solutions/157. Read N Characters Given Read4/157.java b/solutions/157. Read N Characters Given Read4/157.java new file mode 100644 index 00000000000..b275d07e8a2 --- /dev/null +++ b/solutions/157. Read N Characters Given Read4/157.java @@ -0,0 +1,30 @@ +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char[] buf4); + */ + +public class Solution extends Reader4 { + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + public int read(char[] buf, int n) { + char[] buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } +} diff --git a/solutions/157. Read N Characters Given Read4/157.py b/solutions/157. Read N Characters Given Read4/157.py new file mode 100644 index 00000000000..f7e2a1120f6 --- /dev/null +++ b/solutions/157. Read N Characters Given Read4/157.py @@ -0,0 +1,31 @@ +""" +The read4 API is already defined for you. + def read4(buf4: List[chr]) -> int: + +# Below is an example of how the read4 API can be called. +file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a' +buf4 = [' '] * 4 # Create buffer with enough space to store characters +read4(buf4) # Read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e' +read4(buf4) # Read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i' +read4(buf4) # Read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file +""" + + +class Solution: + def read(self, buf: List[str], n: int) -> int: + buf4 = [' '] * 4 + i4 = 0 # buf4's index + n4 = 0 # buf4's size + i = 0 # buf's index + + while i < n: + if i4 == n4: # All the characters in the buf4 are consumed. + i4 = 0 # Reset the buf4's index. + n4 = read4(buf4) # Read <= 4 characters from the file to the buf4. + if n4 == 0: # Reach the EOF. + return i + buf[i] = buf4[i4] + i += 1 + i4 += 1 + + return i diff --git a/solutions/1570. Dot Product of Two Sparse Vectors/1570-2.cpp b/solutions/1570. Dot Product of Two Sparse Vectors/1570-2.cpp new file mode 100644 index 00000000000..2ad2e943b6e --- /dev/null +++ b/solutions/1570. Dot Product of Two Sparse Vectors/1570-2.cpp @@ -0,0 +1,26 @@ +class SparseVector { + public: + SparseVector(vector& nums) { + for (int i = 0; i < nums.size(); ++i) + if (nums[i]) + v.push_back({i, nums[i]}); + } + + // Returns the dot product of the two sparse vectors. + int dotProduct(SparseVector& vec) { + int ans = 0; + + for (int i = 0, j = 0; i < v.size() && j < vec.v.size();) + if (v[i].first == vec.v[j].first) + ans += v[i++].second * vec.v[j++].second; + else if (v[i].first < vec.v[j].first) + ++i; + else + ++j; + + return ans; + } + + private: + vector> v; // [(index, num)] +}; diff --git a/solutions/1570. Dot Product of Two Sparse Vectors/1570-2.java b/solutions/1570. Dot Product of Two Sparse Vectors/1570-2.java new file mode 100644 index 00000000000..12ec20303e2 --- /dev/null +++ b/solutions/1570. Dot Product of Two Sparse Vectors/1570-2.java @@ -0,0 +1,34 @@ +class T { + public int index; + public int num; + + public T(int index, int num) { + this.index = index; + this.num = num; + } +} + +class SparseVector { + SparseVector(int[] nums) { + for (int i = 0; i < nums.length; ++i) + if (nums[i] != 0) + v.add(new T(i, nums[i])); + } + + // Returns the dot product of the two sparse vectors. + public int dotProduct(SparseVector vec) { + int ans = 0; + + for (int i = 0, j = 0; i < v.size() && j < vec.v.size();) + if (v.get(i).index == vec.v.get(j).index) + ans += v.get(i++).num * vec.v.get(j++).num; + else if (v.get(i).index < vec.v.get(j).index) + ++i; + else + ++j; + + return ans; + } + + private List v = new ArrayList<>(); // [(index, num)] +} diff --git a/solutions/1570. Dot Product of Two Sparse Vectors/1570.cpp b/solutions/1570. Dot Product of Two Sparse Vectors/1570.cpp new file mode 100644 index 00000000000..472e1090b3a --- /dev/null +++ b/solutions/1570. Dot Product of Two Sparse Vectors/1570.cpp @@ -0,0 +1,25 @@ +class SparseVector { + public: + SparseVector(vector& nums) { + for (int i = 0; i < nums.size(); ++i) + if (nums[i]) + indexToNum[i] = nums[i]; + } + + // Returns the dot product of the two sparse vectors. + int dotProduct(SparseVector& vec) { + if (indexToNum.size() < vec.indexToNum.size()) + return vec.dotProduct(*this); + + int ans = 0; + + for (const auto& [index, num] : vec.indexToNum) + if (const auto it = indexToNum.find(index); it != indexToNum.cend()) + ans += num * it->second; + + return ans; + } + + private: + unordered_map indexToNum; // {index: num} +}; diff --git a/solutions/1570. Dot Product of Two Sparse Vectors/1570.java b/solutions/1570. Dot Product of Two Sparse Vectors/1570.java new file mode 100644 index 00000000000..1bf2fa75f37 --- /dev/null +++ b/solutions/1570. Dot Product of Two Sparse Vectors/1570.java @@ -0,0 +1,23 @@ +class SparseVector { + SparseVector(int[] nums) { + for (int i = 0; i < nums.length; ++i) + if (nums[i] != 0) + indexToNum.put(i, nums[i]); + } + + // Returns the dot product of the two sparse vectors. + public int dotProduct(SparseVector vec) { + if (indexToNum.size() < vec.indexToNum.size()) + return vec.dotProduct(this); + + int ans = 0; + + for (final int index : vec.indexToNum.keySet()) + if (indexToNum.containsKey(index)) + ans += vec.indexToNum.get(index) * indexToNum.get(index); + + return ans; + } + + private Map indexToNum = new HashMap<>(); +} diff --git a/solutions/1571. Warehouse Manager/1571.sql b/solutions/1571. Warehouse Manager/1571.sql new file mode 100644 index 00000000000..09204acebc5 --- /dev/null +++ b/solutions/1571. Warehouse Manager/1571.sql @@ -0,0 +1,9 @@ +SELECT + Warehouse.name AS warehouse_name, + SUM( + Warehouse.units * Products.width * Products.length * Products.height + ) AS volume +FROM Warehouse +INNER JOIN Products + USING (product_id) +GROUP BY 1; diff --git a/solutions/1572. Matrix Diagonal Sum/1572.cpp b/solutions/1572. Matrix Diagonal Sum/1572.cpp new file mode 100644 index 00000000000..f3843744f85 --- /dev/null +++ b/solutions/1572. Matrix Diagonal Sum/1572.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int diagonalSum(vector>& mat) { + const int n = mat.size(); + int ans = 0; + + for (int i = 0; i < n; ++i) { + ans += mat[i][i]; + ans += mat[n - 1 - i][i]; + } + + return n % 2 == 0 ? ans : ans - mat[n / 2][n / 2]; + } +}; diff --git a/solutions/1572. Matrix Diagonal Sum/1572.java b/solutions/1572. Matrix Diagonal Sum/1572.java new file mode 100644 index 00000000000..9975634fc09 --- /dev/null +++ b/solutions/1572. Matrix Diagonal Sum/1572.java @@ -0,0 +1,13 @@ +class Solution { + public int diagonalSum(int[][] mat) { + final int n = mat.length; + int ans = 0; + + for (int i = 0; i < n; ++i) { + ans += mat[i][i]; + ans += mat[n - 1 - i][i]; + } + + return n % 2 == 0 ? ans : ans - mat[n / 2][n / 2]; + } +} diff --git a/solutions/1572. Matrix Diagonal Sum/1572.py b/solutions/1572. Matrix Diagonal Sum/1572.py new file mode 100644 index 00000000000..b978462e5fa --- /dev/null +++ b/solutions/1572. Matrix Diagonal Sum/1572.py @@ -0,0 +1,10 @@ +class Solution: + def diagonalSum(self, mat: List[List[int]]) -> int: + n = len(mat) + ans = 0 + + for i in range(n): + ans += mat[i][i] + ans += mat[n - 1 - i][i] + + return ans if n % 2 == 0 else ans - mat[n // 2][n // 2] diff --git a/solutions/1573. Number of Ways to Split a String/1573.cpp b/solutions/1573. Number of Ways to Split a String/1573.cpp new file mode 100644 index 00000000000..5279abad7f9 --- /dev/null +++ b/solutions/1573. Number of Ways to Split a String/1573.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int numWays(string s) { + constexpr int kMod = 1'000'000'007; + const int ones = ranges::count(s, '1'); + if (ones % 3 != 0) + return 0; + if (ones == 0) { + const long n = s.size(); + return (n - 1) * (n - 2) / 2 % kMod; + } + + int s1End = -1; + int s2Start = -1; + int s2End = -1; + int s3Start = -1; + int onesSoFar = 0; + + for (int i = 0; i < s.length(); ++i) { + if (s[i] == '1') + ++onesSoFar; + if (s1End == -1 && onesSoFar == ones / 3) + s1End = i; + else if (s2Start == -1 && onesSoFar == ones / 3 + 1) + s2Start = i; + if (s2End == -1 && onesSoFar == ones / 3 * 2) + s2End = i; + else if (s3Start == -1 && onesSoFar == ones / 3 * 2 + 1) + s3Start = i; + } + + return static_cast(s2Start - s1End) * (s3Start - s2End) % kMod; + } +}; diff --git a/solutions/1573. Number of Ways to Split a String/1573.java b/solutions/1573. Number of Ways to Split a String/1573.java new file mode 100644 index 00000000000..5ef1e6a4cb5 --- /dev/null +++ b/solutions/1573. Number of Ways to Split a String/1573.java @@ -0,0 +1,33 @@ +public class Solution { + public int numWays(String s) { + final int kMod = 1_000_000_007; + final int ones = (int) s.chars().filter(c -> c == '1').count(); + if (ones % 3 != 0) + return 0; + if (ones == 0) { + final long n = s.length(); + return (int) ((n - 1) * (n - 2) / 2 % kMod); + } + + int s1End = -1; + int s2Start = -1; + int s2End = -1; + int s3Start = -1; + int onesSoFar = 0; + + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == '1') + ++onesSoFar; + if (s1End == -1 && onesSoFar == ones / 3) + s1End = i; + else if (s2Start == -1 && onesSoFar == ones / 3 + 1) + s2Start = i; + if (s2End == -1 && onesSoFar == ones / 3 * 2) + s2End = i; + else if (s3Start == -1 && onesSoFar == ones / 3 * 2 + 1) + s3Start = i; + } + + return (int) ((long) (s2Start - s1End) * (s3Start - s2End) % kMod); + } +} diff --git a/solutions/1573. Number of Ways to Split a String/1573.py b/solutions/1573. Number of Ways to Split a String/1573.py new file mode 100644 index 00000000000..d0b564fd758 --- /dev/null +++ b/solutions/1573. Number of Ways to Split a String/1573.py @@ -0,0 +1,29 @@ +class Solution: + def numWays(self, s: str) -> int: + kMod = 1_000_000_007 + ones = s.count('1') + if ones % 3 != 0: + return 0 + if ones == 0: + n = len(s) + return (n - 1) * (n - 2) // 2 % kMod + + s1End = -1 + s2Start = -1 + s2End = -1 + s3Start = -1 + onesSoFar = 0 + + for i, c in enumerate(s): + if c == '1': + onesSoFar += 1 + if s1End == -1 and onesSoFar == ones // 3: + s1End = i + elif s2Start == -1 and onesSoFar == ones // 3 + 1: + s2Start = i + if s2End == -1 and onesSoFar == ones // 3 * 2: + s2End = i + elif s3Start == -1 and onesSoFar == ones // 3 * 2 + 1: + s3Start = i + + return (s2Start - s1End) * (s3Start - s2End) % kMod diff --git a/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.cpp b/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.cpp new file mode 100644 index 00000000000..69e80d607f4 --- /dev/null +++ b/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int findLengthOfShortestSubarray(vector& arr) { + const int n = arr.size(); + int l = 0; + int r = n - 1; + + // arr[0..l] is non-decreasing. + while (l < n - 1 && arr[l + 1] >= arr[l]) + ++l; + // arr[r..n - 1] is non-decreasing. + while (r > 0 && arr[r - 1] <= arr[r]) + --r; + // Remove arr[l + 1..n - 1] or arr[0..r - 1]. + int ans = min(n - 1 - l, r); + + // Since arr[0..l] and arr[r..n - 1] are non-decreasing, we place pointers + // at the rightmost indices, l and n - 1, and greedily shrink them toward + // the leftmost indices, 0 and r, respectively. By removing arr[i + 1..j], + // we ensure that `arr` becomes non-decreasing. + int i = l; + int j = n - 1; + while (i >= 0 && j >= r && j > i) { + if (arr[i] <= arr[j]) + --j; + else + --i; + ans = min(ans, j - i); + } + + return ans; + } +}; diff --git a/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.java b/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.java new file mode 100644 index 00000000000..51e32dfb242 --- /dev/null +++ b/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.java @@ -0,0 +1,32 @@ +class Solution { + public int findLengthOfShortestSubarray(int[] arr) { + final int n = arr.length; + int l = 0; + int r = n - 1; + + // arr[0..l] is non-decreasing prefix. + while (l < n - 1 && arr[l + 1] >= arr[l]) + ++l; + // arr[r..n - 1] is non-decreasing suffix. + while (r > 0 && arr[r - 1] <= arr[r]) + --r; + // Remove arr[l + 1..n - 1] or arr[0..r - 1] + int ans = Math.min(n - 1 - l, r); + + // Since arr[0..l] and arr[r..n - 1] are non-decreasing, we place pointers + // at the rightmost indices, l and n - 1, and greedily shrink them toward + // the leftmost indices, 0 and r, respectively. By removing arr[i + 1..j], + // we ensure that `arr` becomes non-decreasing. + int i = l; + int j = n - 1; + while (i >= 0 && j >= r && j > i) { + if (arr[i] <= arr[j]) + --j; + else + --i; + ans = Math.min(ans, j - i); + } + + return ans; + } +} diff --git a/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.py b/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.py new file mode 100644 index 00000000000..f58d90b0f0d --- /dev/null +++ b/solutions/1574. Shortest Subarray to be Removed to Make Array Sorted/1574.py @@ -0,0 +1,29 @@ +class Solution: + def findLengthOfShortestSubarray(self, arr: List[int]) -> int: + n = len(arr) + l = 0 + r = n - 1 + + # arr[0..l] is non-decreasing. + while l < n - 1 and arr[l + 1] >= arr[l]: + l += 1 + # arr[r..n - 1] is non-decreasing. + while r > 0 and arr[r - 1] <= arr[r]: + r -= 1 + # Remove arr[l + 1..n - 1] or arr[0..r - 1]. + ans = min(n - 1 - l, r) + + # Since arr[0..l] and arr[r..n - 1] are non-decreasing, we place pointers + # at the rightmost indices, l and n - 1, and greedily shrink them toward + # the leftmost indices, 0 and r, respectively. By removing arr[i + 1..j], + # we ensure that `arr` becomes non-decreasing. + i = l + j = n - 1 + while i >= 0 and j >= r and j > i: + if arr[i] <= arr[j]: + j -= 1 + else: + i -= 1 + ans = min(ans, j - i) + + return ans diff --git a/solutions/1575. Count All Possible Routes/1575-2.cpp b/solutions/1575. Count All Possible Routes/1575-2.cpp new file mode 100644 index 00000000000..be1fad97bf5 --- /dev/null +++ b/solutions/1575. Count All Possible Routes/1575-2.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int countRoutes(vector& locations, int start, int finish, int fuel) { + constexpr int kMod = 1'000'000'007; + const int n = locations.size(); + // dp[i][j] := the number of ways to reach the `finish` city from the i-th + // city with `j` fuel + vector> dp(n, vector(fuel + 1)); + + for (int f = 0; f <= fuel; ++f) + dp[finish][f] = 1; + + for (int f = 0; f <= fuel; ++f) + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + const int requiredFuel = abs(locations[i] - locations[j]); + if (requiredFuel <= f) { + dp[i][f] += dp[j][f - requiredFuel]; + dp[i][f] %= kMod; + } + } + + return dp[start][fuel]; + } +}; diff --git a/solutions/1575. Count All Possible Routes/1575-2.java b/solutions/1575. Count All Possible Routes/1575-2.java new file mode 100644 index 00000000000..5172ae9cb3f --- /dev/null +++ b/solutions/1575. Count All Possible Routes/1575-2.java @@ -0,0 +1,26 @@ +class Solution { + public int countRoutes(int[] locations, int start, int finish, int fuel) { + final int kMod = 1_000_000_007; + int n = locations.length; + // dp[i][j] := the number of ways to reach the `finish` city from the i-th + // city with `j` fuel + int[][] dp = new int[n][fuel + 1]; + + for (int f = 0; f <= fuel; ++f) + dp[finish][f] = 1; + + for (int f = 0; f <= fuel; ++f) + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + final int requiredFuel = Math.abs(locations[i] - locations[j]); + if (requiredFuel <= f) { + dp[i][f] += dp[j][f - requiredFuel]; + dp[i][f] %= kMod; + } + } + + return dp[start][fuel]; + } +} diff --git a/solutions/1575. Count All Possible Routes/1575-2.py b/solutions/1575. Count All Possible Routes/1575-2.py new file mode 100644 index 00000000000..ce6aa53ac5a --- /dev/null +++ b/solutions/1575. Count All Possible Routes/1575-2.py @@ -0,0 +1,22 @@ +class Solution: + def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: + kMod = 1_000_000_007 + n = len(locations) + # dp[i][j] := the number of ways to reach the `finish` city from the i-th + # city with `j` fuel + dp = [[0] * (fuel + 1) for _ in range(n)] + + for f in range(fuel + 1): + dp[finish][f] = 1 + + for f in range(fuel + 1): + for i in range(n): + for j in range(n): + if i == j: + continue + requiredFuel = abs(locations[i] - locations[j]) + if requiredFuel <= f: + dp[i][f] += dp[j][f - requiredFuel] + dp[i][f] %= kMod + + return dp[start][fuel] diff --git a/solutions/1575. Count All Possible Routes/1575.cpp b/solutions/1575. Count All Possible Routes/1575.cpp new file mode 100644 index 00000000000..353ed9c6c42 --- /dev/null +++ b/solutions/1575. Count All Possible Routes/1575.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int countRoutes(vector& locations, int start, int finish, int fuel) { + vector> mem(locations.size(), vector(fuel + 1, -1)); + return countRoutes(locations, start, finish, fuel, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of ways to reach the `finish` city from the i-th city + // with `fuel` fuel. + int countRoutes(const vector& locations, int i, int finish, int fuel, + vector>& mem) { + if (fuel < 0) + return 0; + if (mem[i][fuel] != -1) + return mem[i][fuel]; + + int res = i == finish ? 1 : 0; + for (int j = 0; j < locations.size(); ++j) { + if (j == i) + continue; + res += countRoutes(locations, j, finish, + fuel - abs(locations[i] - locations[j]), mem); + res %= kMod; + } + + return mem[i][fuel] = res; + } +}; diff --git a/solutions/1575. Count All Possible Routes/1575.java b/solutions/1575. Count All Possible Routes/1575.java new file mode 100644 index 00000000000..53729f35c92 --- /dev/null +++ b/solutions/1575. Count All Possible Routes/1575.java @@ -0,0 +1,27 @@ +class Solution { + public int countRoutes(int[] locations, int start, int finish, int fuel) { + Integer[][] mem = new Integer[locations.length][fuel + 1]; + return countRoutes(locations, start, finish, fuel, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of ways to reach the `finish` city from the i-th city + // with `fuel` fuel. + private int countRoutes(int[] locations, int i, int finish, int fuel, Integer[][] mem) { + if (fuel < 0) + return 0; + if (mem[i][fuel] != null) + return mem[i][fuel]; + + int res = (i == finish) ? 1 : 0; + for (int j = 0; j < locations.length; ++j) { + if (j == i) + continue; + res += countRoutes(locations, j, finish, fuel - Math.abs(locations[i] - locations[j]), mem); + res %= kMod; + } + + return mem[i][fuel] = res; + } +} diff --git a/solutions/1575. Count All Possible Routes/1575.py b/solutions/1575. Count All Possible Routes/1575.py new file mode 100644 index 00000000000..64071f1736e --- /dev/null +++ b/solutions/1575. Count All Possible Routes/1575.py @@ -0,0 +1,23 @@ +class Solution: + def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def dp(i: int, fuel: int) -> int: + """ + Returns the number of ways to reach the `finish` city from the i-th city + with `fuel` fuel. + """ + if fuel < 0: + return 0 + + res = 1 if i == finish else 0 + for j in range(len(locations)): + if j == i: + continue + res += dp(j, fuel - abs(locations[i] - locations[j])) + res %= kMod + + return res + + return dp(start, fuel) diff --git a/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.cpp b/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.cpp new file mode 100644 index 00000000000..96cbccc98e2 --- /dev/null +++ b/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + string modifyString(string s) { + string ans; + + for (int i = 0; i < s.length(); ++i) + if (s[i] == '?') + ans += nextAvailable(ans, s, i); + else + ans += s[i]; + + return ans; + } + + private: + char nextAvailable(const string& ans, const string& s, int i) { + char c = 'a'; + while ((i > 0 && ans[i - 1] == c) || // + (i + 1 < s.size() && c == s[i + 1])) + ++c; + return c; + } +}; diff --git a/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.java b/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.java new file mode 100644 index 00000000000..d084dbe01e4 --- /dev/null +++ b/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.java @@ -0,0 +1,20 @@ +class Solution { + public String modifyString(String s) { + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) == '?') + sb.append(nextAvailable(sb, s, i)); + else + sb.append(s.charAt(i)); + + return sb.toString(); + } + + private char nextAvailable(StringBuilder sb, final String s, int i) { + char c = 'a'; + while ((i > 0 && sb.charAt(i - 1) == c) || (i + 1 < s.length() && c == s.charAt(i + 1))) + ++c; + return c; + } +} diff --git a/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.py b/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.py new file mode 100644 index 00000000000..c619aa78d3e --- /dev/null +++ b/solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.py @@ -0,0 +1,18 @@ +class Solution: + def modifyString(self, s: str) -> str: + ans = [] + + def nextAvailable(ans: List[int], s: str, i: int) -> str: + c = 'a' + while (i > 0 and ans[i - 1] == c) or \ + (i + 1 < len(s) and c == s[i + 1]): + c = chr(ord(c) + 1) + return c + + for i, c in enumerate(s): + if c == '?': + ans.append(nextAvailable(ans, s, i)) + else: + ans.append(c) + + return ''.join(ans) diff --git a/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.cpp b/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.cpp new file mode 100644 index 00000000000..7ed761149f3 --- /dev/null +++ b/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int numTriplets(vector& nums1, vector& nums2) { + return countTriplets(nums1, nums2) + countTriplets(nums2, nums1); + } + + private: + // Returns the number of triplet (i, j, k) if A[i]^2 == B[j] * B[k]. + int countTriplets(const vector& A, const vector& B) { + int res = 0; + unordered_map count; + + for (const int b : B) + ++count[b]; + + for (const int a : A) { + const long target = static_cast(a) * a; + for (const auto& [b, freq] : count) { + if (target % b > 0 || !count.contains(target / b)) + continue; + if (target / b == b) + res += freq * (freq - 1); + else + res += freq * count[target / b]; + } + } + + return res / 2; + } +}; diff --git a/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.java b/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.java new file mode 100644 index 00000000000..b4b579a2dfd --- /dev/null +++ b/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.java @@ -0,0 +1,30 @@ +class Solution { + public int numTriplets(int[] nums1, int[] nums2) { + return countTriplets(nums1, nums2) + countTriplets(nums2, nums1); + } + + // Returns the number of triplet (i, j, k) if A[i]^2 == B[j] * B[k]. + private int countTriplets(int[] A, int[] B) { + int res = 0; + Map count = new HashMap<>(); + + for (final int b : B) + count.merge(b, 1, Integer::sum); + + for (final int a : A) { + long target = (long) a * a; + for (Map.Entry entry : count.entrySet()) { + final int b = entry.getKey(); + final int freq = entry.getValue(); + if (target % b > 0 || !count.containsKey((int) (target / b))) + continue; + if (target / b == b) + res += freq * (freq - 1); + else + res += freq * count.get((int) (target / b)); + } + } + + return res / 2; + } +} diff --git a/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.py b/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.py new file mode 100644 index 00000000000..56ead1a5da3 --- /dev/null +++ b/solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.py @@ -0,0 +1,20 @@ +class Solution: + def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: + def countTriplets(A: List[int], B: List[int]): + """Returns the number of triplet (i, j, k) if A[i]^2 == B[j] * B[k].""" + res = 0 + count = collections.Counter(B) + + for a in A: + target = a * a + for b, freq in count.items(): + if target % b > 0 or target // b not in count: + continue + if target // b == b: + res += freq * (freq - 1) + else: + res += freq * count[target // b] + + return res // 2 + + return countTriplets(nums1, nums2) + countTriplets(nums2, nums1) diff --git a/solutions/1578. Minimum Time to Make Rope Colorful/1578.cpp b/solutions/1578. Minimum Time to Make Rope Colorful/1578.cpp new file mode 100644 index 00000000000..a878726cddb --- /dev/null +++ b/solutions/1578. Minimum Time to Make Rope Colorful/1578.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minCost(string colors, vector& neededTime) { + int ans = 0; + int maxNeededTime = neededTime[0]; + + for (int i = 1; i < colors.length(); ++i) + if (colors[i] == colors[i - 1]) { + ans += min(maxNeededTime, neededTime[i]); + // For each continuous group, Bob needs to remove every balloon except + // the one with the maximum `neededTime`. So, he should hold the balloon + // with the highest `neededTime` in his hand. + maxNeededTime = max(maxNeededTime, neededTime[i]); + } else { + // If the current balloon is different from the previous one, discard + // the balloon from the previous group and hold the new one in hand. + maxNeededTime = neededTime[i]; + } + + return ans; + } +}; diff --git a/solutions/1578. Minimum Time to Make Rope Colorful/1578.java b/solutions/1578. Minimum Time to Make Rope Colorful/1578.java new file mode 100644 index 00000000000..75b1a13e115 --- /dev/null +++ b/solutions/1578. Minimum Time to Make Rope Colorful/1578.java @@ -0,0 +1,20 @@ +class Solution { + public int minCost(String colors, int[] neededTime) { + int ans = 0; + int maxNeededTime = neededTime[0]; + + for (int i = 1; i < colors.length(); ++i) + if (colors.charAt(i) == colors.charAt(i - 1)) { + ans += Math.min(maxNeededTime, neededTime[i]); + // For each continuous group, Bob needs to remove every balloon except the one with the max + // `neededTime`. So, he should hold the balloon with the highest `neededTime` in his hand. + maxNeededTime = Math.max(maxNeededTime, neededTime[i]); + } else { + // If the current balloon is different from the previous one, discard the balloon from the + // previous group and hold the new one in hand. + maxNeededTime = neededTime[i]; + } + + return ans; + } +} diff --git a/solutions/1578. Minimum Time to Make Rope Colorful/1578.py b/solutions/1578. Minimum Time to Make Rope Colorful/1578.py new file mode 100644 index 00000000000..d6dd5f7e3ae --- /dev/null +++ b/solutions/1578. Minimum Time to Make Rope Colorful/1578.py @@ -0,0 +1,18 @@ +class Solution: + def minCost(self, colors: str, neededTime: List[int]) -> int: + ans = 0 + maxNeededTime = neededTime[0] + + for i in range(1, len(colors)): + if colors[i] == colors[i - 1]: + ans += min(maxNeededTime, neededTime[i]) + # For each continuous group, Bob needs to remove every balloon except + # the one with the maximum `neededTime`. So, he should hold the balloon + # with the highest `neededTime` in his hand. + maxNeededTime = max(maxNeededTime, neededTime[i]) + else: + # If the current balloon is different from the previous one, discard + # the balloon from the previous group and hold the new one in hand. + maxNeededTime = neededTime[i] + + return ans diff --git a/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.cpp b/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.cpp new file mode 100644 index 00000000000..c418afba964 --- /dev/null +++ b/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.cpp @@ -0,0 +1,75 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + bool unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + return true; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + int maxNumEdgesToRemove(int n, vector>& edges) { + UnionFind alice(n); + UnionFind bob(n); + int requiredEdges = 0; + + // Greedily put type 3 edges in the front. + sort( + edges.begin(), edges.end(), + [](const vector& a, const vector& b) { return a[0] > b[0]; }); + + for (const vector& edge : edges) { + const int type = edge[0]; + const int u = edge[1] - 1; + const int v = edge[2] - 1; + switch (type) { + case 3: // Can be traversed by Alice and Bob. + // Note that we should use | instead of || because if the first + // expression is true, short-circuiting will skip the second + // expression. + if (alice.unionByRank(u, v) | bob.unionByRank(u, v)) + ++requiredEdges; + break; + case 2: // Can be traversed by Bob. + if (bob.unionByRank(u, v)) + ++requiredEdges; + case 1: // Can be traversed by Alice. + if (alice.unionByRank(u, v)) + ++requiredEdges; + } + } + + return alice.getCount() == 1 && bob.getCount() == 1 + ? edges.size() - requiredEdges + : -1; + } +}; diff --git a/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.java b/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.java new file mode 100644 index 00000000000..e86032513c9 --- /dev/null +++ b/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.java @@ -0,0 +1,72 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public boolean unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + return true; + } + + public int getCount() { + return count; + } + + private int count; + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int maxNumEdgesToRemove(int n, int[][] edges) { + UnionFind alice = new UnionFind(n); + UnionFind bob = new UnionFind(n); + int requiredEdges = 0; + + // Greedily put type 3 edges in the front. + Arrays.sort(edges, (a, b) -> b[0] - a[0]); + + for (int[] edge : edges) { + final int type = edge[0]; + final int u = edge[1] - 1; + final int v = edge[2] - 1; + switch (type) { + case 3: // Can be traversed by Alice and Bob. + // Note that we should use | instead of || because if the first + // expression is true, short-circuiting will skip the second + // expression. + if (alice.unionByRank(u, v) | bob.unionByRank(u, v)) + ++requiredEdges; + break; + case 2: // Can be traversed by Bob. + if (bob.unionByRank(u, v)) + ++requiredEdges; + case 1: // Can be traversed by Alice. + if (alice.unionByRank(u, v)) + ++requiredEdges; + } + } + + return alice.getCount() == 1 && bob.getCount() == 1 ? edges.length - requiredEdges : -1; + } +} diff --git a/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.py b/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.py new file mode 100644 index 00000000000..3e8aea2ebf3 --- /dev/null +++ b/solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.py @@ -0,0 +1,53 @@ +class UnionFind: + def __init__(self, n: int): + self.count = n + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> bool: + i = self._find(u) + j = self._find(v) + if i == j: + return False + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + self.count -= 1 + return True + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: + alice = UnionFind(n) + bob = UnionFind(n) + requiredEdges = 0 + + # Greedily put type 3 edges in the front. + for type, u, v in sorted(edges, reverse=True): + u -= 1 + v -= 1 + if type == 3: # Can be traversed by Alice and Bob. + # Note that we should use | instead of or because if the first + # expression is True, short-circuiting will skip the second + # expression. + if alice.unionByRank(u, v) | bob.unionByRank(u, v): + requiredEdges += 1 + elif type == 2: # Can be traversed by Bob. + if bob.unionByRank(u, v): + requiredEdges += 1 + else: # type == 1 Can be traversed by Alice. + if alice.unionByRank(u, v): + requiredEdges += 1 + + return len(edges) - requiredEdges \ + if alice.count == 1 and bob.count == 1 \ + else -1 diff --git a/solutions/158. Read N Characters Given Read4 II - Call multiple times/158-2.cpp b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158-2.cpp new file mode 100644 index 00000000000..449ce2ad3a4 --- /dev/null +++ b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158-2.cpp @@ -0,0 +1,46 @@ +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char *buf4); + */ + +class Solution { + public: + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + int read(char* buf, int n) { + int i = 0; // buf's index + + // Put the remaining characteres in the buf4 to the buf. + while (i4 < n4 && i < n) + buf[i++] = buf4[i4++]; + + // While we're not reaching the tail (< 4 characters). + while (i + 4 < n) { + const int k = read4(buf + i); // Directly write to the buf. + if (k == 0) // Reach the EOF. + return i; + i += k; + } + + // Reach the tail. + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } + + private: + char* buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size +}; diff --git a/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.cpp b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.cpp new file mode 100644 index 00000000000..e84bf8f0753 --- /dev/null +++ b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.cpp @@ -0,0 +1,33 @@ +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char *buf4); + */ + +class Solution { + public: + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + int read(char* buf, int n) { + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } + + private: + char* buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size +}; diff --git a/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.java b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.java new file mode 100644 index 00000000000..f538b99b924 --- /dev/null +++ b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.java @@ -0,0 +1,31 @@ +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char[] buf4); + */ + +public class Solution extends Reader4 { + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + public int read(char[] buf, int n) { + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } + + private char[] buf4 = new char[4]; + private int i4 = 0; // buf4's index + private int n4 = 0; // buf4's size +} diff --git a/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.py b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.py new file mode 100644 index 00000000000..7584ba13dfe --- /dev/null +++ b/solutions/158. Read N Characters Given Read4 II - Call multiple times/158.py @@ -0,0 +1,23 @@ +# The read4 API is already defined for you. +# Def read4(buf4: List[str]) -> int: + +class Solution: + def read(self, buf: List[str], n: int) -> int: + i = 0 # buf's index + + while i < n: + if self.i4 == self.n4: # All the characters in the buf4 are consumed. + self.i4 = 0 # Reset the buf4's index. + # Read <= 4 characters from the file to the buf4. + self.n4 = read4(self.buf4) + if self.n4 == 0: # Reach the EOF. + return i + buf[i] = self.buf4[self.i4] + i += 1 + self.i4 += 1 + + return i + + buf4 = [' '] * 4 + i4 = 0 # buf4's index + n4 = 0 # buf4's size diff --git a/solutions/1580. Put Boxes Into the Warehouse II/1580.cpp b/solutions/1580. Put Boxes Into the Warehouse II/1580.cpp new file mode 100644 index 00000000000..4e6824d382f --- /dev/null +++ b/solutions/1580. Put Boxes Into the Warehouse II/1580.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxBoxesInWarehouse(vector& boxes, vector& warehouse) { + int l = 0; + int r = warehouse.size() - 1; + + ranges::sort(boxes, greater<>()); + + for (const int box : boxes) { + if (l > r) + return warehouse.size(); + if (box <= warehouse[l]) + ++l; + else if (box <= warehouse[r]) + --r; + } + + return l + (warehouse.size() - r - 1); + } +}; diff --git a/solutions/1580. Put Boxes Into the Warehouse II/1580.java b/solutions/1580. Put Boxes Into the Warehouse II/1580.java new file mode 100644 index 00000000000..e2623230f31 --- /dev/null +++ b/solutions/1580. Put Boxes Into the Warehouse II/1580.java @@ -0,0 +1,23 @@ +class Solution { + public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { + int l = 0; + int r = warehouse.length - 1; + + boxes = Arrays.stream(boxes) + .boxed() + .sorted(Collections.reverseOrder()) + .mapToInt(Integer::intValue) + .toArray(); + + for (final int box : boxes) { + if (l > r) + return warehouse.length; + if (box <= warehouse[l]) + ++l; + else if (box <= warehouse[r]) + --r; + } + + return l + (warehouse.length - r - 1); + } +} diff --git a/solutions/1580. Put Boxes Into the Warehouse II/1580.py b/solutions/1580. Put Boxes Into the Warehouse II/1580.py new file mode 100644 index 00000000000..0487f3f7bbc --- /dev/null +++ b/solutions/1580. Put Boxes Into the Warehouse II/1580.py @@ -0,0 +1,14 @@ +class Solution: + def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int: + l = 0 + r = len(warehouse) - 1 + + for box in sorted(boxes, reverse=True): + if l > r: + return len(warehouse) + if box <= warehouse[l]: + l += 1 + elif box <= warehouse[r]: + r -= 1 + + return l + (len(warehouse) - r - 1) diff --git a/solutions/1581. Customer Who Visited but Did Not Make Any Transactions/1581.sql b/solutions/1581. Customer Who Visited but Did Not Make Any Transactions/1581.sql new file mode 100644 index 00000000000..ad8674c2769 --- /dev/null +++ b/solutions/1581. Customer Who Visited but Did Not Make Any Transactions/1581.sql @@ -0,0 +1,8 @@ +SELECT + Visits.customer_id, + COUNT(Visits.visit_id) AS count_no_trans +FROM Visits +LEFT JOIN Transactions + USING (visit_id) +WHERE Transactions.transaction_id IS NULL +GROUP BY 1; diff --git a/solutions/1582. Special Positions in a Binary Matrix/1582.cpp b/solutions/1582. Special Positions in a Binary Matrix/1582.cpp new file mode 100644 index 00000000000..84220c0c21b --- /dev/null +++ b/solutions/1582. Special Positions in a Binary Matrix/1582.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int numSpecial(vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + int ans = 0; + vector rowOnes(m); + vector colOnes(n); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 1) { + ++rowOnes[i]; + ++colOnes[j]; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 1 && rowOnes[i] == 1 && colOnes[j] == 1) + ++ans; + + return ans; + } +}; diff --git a/solutions/1582. Special Positions in a Binary Matrix/1582.java b/solutions/1582. Special Positions in a Binary Matrix/1582.java new file mode 100644 index 00000000000..733d431e1b9 --- /dev/null +++ b/solutions/1582. Special Positions in a Binary Matrix/1582.java @@ -0,0 +1,23 @@ +class Solution { + public int numSpecial(int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + int ans = 0; + int[] rowOnes = new int[m]; + int[] colOnes = new int[n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 1) { + ++rowOnes[i]; + ++colOnes[j]; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 1 && rowOnes[i] == 1 && colOnes[j] == 1) + ++ans; + + return ans; + } +} diff --git a/solutions/1582. Special Positions in a Binary Matrix/1582.py b/solutions/1582. Special Positions in a Binary Matrix/1582.py new file mode 100644 index 00000000000..00c5fc8b7de --- /dev/null +++ b/solutions/1582. Special Positions in a Binary Matrix/1582.py @@ -0,0 +1,20 @@ +class Solution: + def numSpecial(self, mat: List[List[int]]) -> int: + m = len(mat) + n = len(mat[0]) + ans = 0 + rowOnes = [0] * m + colOnes = [0] * n + + for i in range(m): + for j in range(n): + if mat[i][j] == 1: + rowOnes[i] += 1 + colOnes[j] += 1 + + for i in range(m): + for j in range(n): + if mat[i][j] == 1 and rowOnes[i] == 1 and colOnes[j] == 1: + ans += 1 + + return ans diff --git a/solutions/1583. Count Unhappy Friends/1583.cpp b/solutions/1583. Count Unhappy Friends/1583.cpp new file mode 100644 index 00000000000..a627542a361 --- /dev/null +++ b/solutions/1583. Count Unhappy Friends/1583.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int unhappyFriends(int n, vector>& preferences, + vector>& pairs) { + int ans = 0; + vector matches(n); + vector> prefer(n); + + for (const vector& pair : pairs) { + const int x = pair[0]; + const int y = pair[1]; + matches[x] = y; + matches[y] = x; + } + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n - 1; ++j) + prefer[i][preferences[i][j]] = j; + + for (int x = 0; x < n; ++x) + for (const auto& [u, _] : prefer[x]) { + const int y = matches[x]; + const int v = matches[u]; + if (prefer[x][u] < prefer[x][y] && prefer[u][x] < prefer[u][v]) { + ++ans; + break; + } + } + + return ans; + } +}; diff --git a/solutions/1583. Count Unhappy Friends/1583.java b/solutions/1583. Count Unhappy Friends/1583.java new file mode 100644 index 00000000000..73566dc1369 --- /dev/null +++ b/solutions/1583. Count Unhappy Friends/1583.java @@ -0,0 +1,33 @@ +class Solution { + public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { + int ans = 0; + int[] matches = new int[n]; + Map[] prefer = new Map[n]; + + for (int[] pair : pairs) { + final int x = pair[0]; + final int y = pair[1]; + matches[x] = y; + matches[y] = x; + } + + for (int i = 0; i < n; ++i) + prefer[i] = new HashMap<>(); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n - 1; ++j) + prefer[i].put(preferences[i][j], j); + + for (int x = 0; x < n; ++x) + for (final int u : preferences[x]) { + final int y = matches[x]; + final int v = matches[u]; + if (prefer[x].get(u) < prefer[x].get(y) && prefer[u].get(x) < prefer[u].get(v)) { + ++ans; + break; + } + } + + return ans; + } +} diff --git a/solutions/1583. Count Unhappy Friends/1583.py b/solutions/1583. Count Unhappy Friends/1583.py new file mode 100644 index 00000000000..f6787b66676 --- /dev/null +++ b/solutions/1583. Count Unhappy Friends/1583.py @@ -0,0 +1,23 @@ +class Solution: + def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: + ans = 0 + matches = [0] * n + prefer = [{} for _ in range(n)] + + for x, y in pairs: + matches[x] = y + matches[y] = x + + for i in range(n): + for j in range(n - 1): + prefer[i][preferences[i][j]] = j + + for x in range(n): + for u in prefer[x].keys(): + y = matches[x] + v = matches[u] + if prefer[x][u] < prefer[x][y] and prefer[u][x] < prefer[u][v]: + ans += 1 + break + + return ans diff --git a/solutions/1584. Min Cost to Connect All Points/1584.cpp b/solutions/1584. Min Cost to Connect All Points/1584.cpp new file mode 100644 index 00000000000..73e842a67ee --- /dev/null +++ b/solutions/1584. Min Cost to Connect All Points/1584.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minCostConnectPoints(vector>& points) { + // dist[i] := the minimum distance to connect the points[i] + vector dist(points.size(), INT_MAX); + int ans = 0; + + for (int i = 0; i < points.size() - 1; ++i) { + for (int j = i + 1; j < points.size(); ++j) { + // Try to connect the points[i] with the points[j]. + dist[j] = min(dist[j], abs(points[i][0] - points[j][0]) + + abs(points[i][1] - points[j][1])); + // Swap the points[j] (the point with the mnimum distance) with the + // points[i + 1]. + if (dist[j] < dist[i + 1]) { + swap(points[j], points[i + 1]); + swap(dist[j], dist[i + 1]); + } + } + ans += dist[i + 1]; + } + + return ans; + } +}; diff --git a/solutions/1584. Min Cost to Connect All Points/1584.java b/solutions/1584. Min Cost to Connect All Points/1584.java new file mode 100644 index 00000000000..739398cae67 --- /dev/null +++ b/solutions/1584. Min Cost to Connect All Points/1584.java @@ -0,0 +1,29 @@ +class Solution { + public int minCostConnectPoints(int[][] points) { + // dist[i] := the minimum distance to connect the points[i] + int[] dist = new int[points.length]; + Arrays.fill(dist, Integer.MAX_VALUE); + int ans = 0; + + for (int i = 0; i < points.length - 1; ++i) { + for (int j = i + 1; j < points.length; ++j) { + // Try to connect the points[i] with the points[j]. + dist[j] = Math.min(dist[j], Math.abs(points[i][0] - points[j][0]) + + Math.abs(points[i][1] - points[j][1])); + // Swap the points[j] (the point with the minimum distance) with the + // points[i + 1]. + if (dist[j] < dist[i + 1]) { + final int[] tempPoint = points[j]; + points[j] = points[i + 1]; + points[i + 1] = tempPoint; + final int tempDist = dist[j]; + dist[j] = dist[i + 1]; + dist[i + 1] = tempDist; + } + } + ans += dist[i + 1]; + } + + return ans; + } +} diff --git a/solutions/1584. Min Cost to Connect All Points/1584.py b/solutions/1584. Min Cost to Connect All Points/1584.py new file mode 100644 index 00000000000..0665319ad63 --- /dev/null +++ b/solutions/1584. Min Cost to Connect All Points/1584.py @@ -0,0 +1,19 @@ +class Solution: + def minCostConnectPoints(self, points: List[int]) -> int: + # dist[i] := the minimum distance to connect the points[i] + dist = [math.inf] * len(points) + ans = 0 + + for i in range(len(points) - 1): + for j in range(i + 1, len(points)): + # Try to connect the points[i] with the points[j]. + dist[j] = min(dist[j], abs(points[i][0] - points[j][0]) + + abs(points[i][1] - points[j][1])) + # Swap the points[j] (the point with the mnimum distance) with the + # points[i + 1]. + if dist[j] < dist[i + 1]: + points[j], points[i + 1] = points[i + 1], points[j] + dist[j], dist[i + 1] = dist[i + 1], dist[j] + ans += dist[i + 1] + + return ans diff --git a/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.cpp b/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.cpp new file mode 100644 index 00000000000..5846c6e73eb --- /dev/null +++ b/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + bool isTransformable(string s, string t) { + if (getCount(s) != getCount(t)) + return false; + + vector> positions(10); + + for (int i = 0; i < s.length(); ++i) + positions[s[i] - '0'].push(i); + + // For each digit in `t`, check if we can put this digit in `s` at the same + // position as `t`. Ensure that all the left digits are equal to or greater + // than it. This is because the only operation we can perform is sorting in + // ascending order. If there is a digit to the left that is smaller than it, + // we can never move it to the same position as in `t`. However, if all the + // digits to its left are equal to or greater than it, we can move it one + // position to the left until it reaches the same position as in `t`. + for (const char c : t) { + const int d = c - '0'; + const int front = positions[d].front(); + positions[d].pop(); + for (int smaller = 0; smaller < d; ++smaller) + if (!positions[smaller].empty() && positions[smaller].front() < front) + return false; + } + return true; + } + + private: + vector getCount(const string& s) { + vector count(10); + for (const char c : s) + ++count[c - '0']; + return count; + } +}; diff --git a/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.java b/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.java new file mode 100644 index 00000000000..58ff737147f --- /dev/null +++ b/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.java @@ -0,0 +1,37 @@ +class Solution { + public boolean isTransformable(String s, String t) { + if (!Arrays.equals(getCount(s), getCount(t))) + return false; + + Queue[] positions = new Queue[10]; + for (int i = 0; i < 10; i++) + positions[i] = new LinkedList<>(); + + for (int i = 0; i < s.length(); i++) + positions[s.charAt(i) - '0'].offer(i); + + // For each digit in `t`, check if we can put this digit in `s` at the same + // position as `t`. Ensure that all the left digits are equal to or greater + // than it. This is because the only operation we can perform is sorting in + // ascending order. If there is a digit to the left that is smaller than it, + // we can never move it to the same position as in `t`. However, if all the + // digits to its left are equal to or greater than it, we can move it one + // position to the left until it reaches the same position as in `t`. + for (final char c : t.toCharArray()) { + final int d = c - '0'; + final int front = positions[d].poll(); + for (int smaller = 0; smaller < d; ++smaller) + if (!positions[smaller].isEmpty() && positions[smaller].peek() < front) + return false; + } + + return true; + } + + private int[] getCount(String s) { + int[] count = new int[10]; + for (char c : s.toCharArray()) + count[c - '0']++; + return count; + } +} diff --git a/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.py b/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.py new file mode 100644 index 00000000000..6c38cd8cc78 --- /dev/null +++ b/solutions/1585. Check If String Is Transformable With Substring Sort Operations/1585.py @@ -0,0 +1,25 @@ +class Solution: + def isTransformable(self, s: str, t: str) -> bool: + if collections.Counter(s) != collections.Counter(t): + return False + + positions = [collections.deque() for _ in range(10)] + + for i, c in enumerate(s): + positions[int(c)].append(i) + + # For each digit in `t`, check if we can put this digit in `s` at the same + # position as `t`. Ensure that all the left digits are equal to or greater + # than it. This is because the only operation we can perform is sorting in + # ascending order. If there is a digit to the left that is smaller than it, + # we can never move it to the same position as in `t`. However, if all the + # digits to its left are equal to or greater than it, we can move it one + # position to the left until it reaches the same position as in `t`. + for c in t: + d = int(c) + front = positions[d].popleft() + for smaller in range(d): + if positions[smaller] and positions[smaller][0] < front: + return False + + return True diff --git a/solutions/1586. Binary Search Tree Iterator II/1586.cpp b/solutions/1586. Binary Search Tree Iterator II/1586.cpp new file mode 100644 index 00000000000..98202073700 --- /dev/null +++ b/solutions/1586. Binary Search Tree Iterator II/1586.cpp @@ -0,0 +1,40 @@ +class BSTIterator { + public: + BSTIterator(TreeNode* root) { + pushLeftsUntilNull(root); + } + + bool hasNext() { + return !nexts.empty(); + } + + int next() { + auto [root, fromNext] = nexts.top(); + nexts.pop(); + if (fromNext) + pushLeftsUntilNull(root->right); + prevsAndCurr.push(root); + return root->val; + } + + bool hasPrev() { + return prevsAndCurr.size() > 1; + } + + int prev() { + nexts.push({prevsAndCurr.top(), /*fromNext=*/false}); + prevsAndCurr.pop(); + return prevsAndCurr.top()->val; + } + + private: + stack prevsAndCurr; + stack> nexts; + + void pushLeftsUntilNull(TreeNode* root) { + while (root != nullptr) { + nexts.push({root, /*fromtNext=*/true}); + root = root->left; + } + } +}; diff --git a/solutions/1586. Binary Search Tree Iterator II/1586.java b/solutions/1586. Binary Search Tree Iterator II/1586.java new file mode 100644 index 00000000000..64b61655014 --- /dev/null +++ b/solutions/1586. Binary Search Tree Iterator II/1586.java @@ -0,0 +1,38 @@ +class BSTIterator { + public BSTIterator(TreeNode root) { + pushLeftsUntilNull(root); + } + + public boolean hasNext() { + return !nexts.isEmpty(); + } + + public int next() { + Pair pair = nexts.pop(); + TreeNode root = pair.getKey(); + boolean fromNext = pair.getValue(); + if (fromNext) + pushLeftsUntilNull(root.right); + prevsAndCurr.push(root); + return root.val; + } + + public boolean hasPrev() { + return prevsAndCurr.size() > 1; + } + + public int prev() { + nexts.push(new Pair<>(prevsAndCurr.pop(), /*fromNext=*/false)); + return prevsAndCurr.peek().val; + } + + private void pushLeftsUntilNull(TreeNode root) { + while (root != null) { + nexts.push(new Pair<>(root, /*fromNext=*/true)); + root = root.left; + } + } + + private Deque prevsAndCurr = new ArrayDeque<>(); + private Deque> nexts = new ArrayDeque<>(); +} diff --git a/solutions/1586. Binary Search Tree Iterator II/1586.py b/solutions/1586. Binary Search Tree Iterator II/1586.py new file mode 100644 index 00000000000..b5b328424f7 --- /dev/null +++ b/solutions/1586. Binary Search Tree Iterator II/1586.py @@ -0,0 +1,27 @@ +class BSTIterator: + def __init__(self, root: Optional[TreeNode]): + self.prevsAndCurr = [] + self.nexts = [] + self._pushLeftsUntilNull(root) + + def hasNext(self) -> bool: + return len(self.nexts) > 0 + + def next(self) -> int: + root, fromNext = self.nexts.pop() + if fromNext: + self._pushLeftsUntilNull(root.right) + self.prevsAndCurr.append(root) + return root.val + + def hasPrev(self) -> bool: + return len(self.prevsAndCurr) > 1 + + def prev(self) -> int: + self.nexts.append((self.prevsAndCurr.pop(), False)) + return self.prevsAndCurr[-1].val + + def _pushLeftsUntilNull(self, root): + while root: + self.nexts.append((root, True)) + root = root.left diff --git a/solutions/1587. Bank Account Summary II/1587.sql b/solutions/1587. Bank Account Summary II/1587.sql new file mode 100644 index 00000000000..bc35e6c75ce --- /dev/null +++ b/solutions/1587. Bank Account Summary II/1587.sql @@ -0,0 +1,8 @@ +SELECT + Users.name, + SUM(amount) AS balance +FROM Users +INNER JOIN Transactions + USING (account) +GROUP BY 1 +HAVING balance > 10000; diff --git a/solutions/1588. Sum of All Odd Length Subarrays/1588.cpp b/solutions/1588. Sum of All Odd Length Subarrays/1588.cpp new file mode 100644 index 00000000000..ceb64b8c548 --- /dev/null +++ b/solutions/1588. Sum of All Odd Length Subarrays/1588.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int sumOddLengthSubarrays(vector& arr) { + int ans = 0; + // Maintain two sums of subarrays ending in the previous index. + // Each time we meet a new number, we'll consider "how many times" it should + // contribute to the newly built subarrays by calculating the number of + // previous even/odd-length subarrays. + int prevEvenSum = 0; // the sum of even-length subarrays + int prevOddSum = 0; // the sum of odd-length subarrays + + for (int i = 0; i < arr.size(); ++i) { + // (i + 1) / 2 := the number of previous odd-length subarrays. + const int currEvenSum = prevOddSum + ((i + 1) / 2) * arr[i]; + // i / 2 + 1 := the number of previous even-length subarrays + // (including 0). + const int currOddSum = prevEvenSum + (i / 2 + 1) * arr[i]; + ans += currOddSum; + prevEvenSum = currEvenSum; + prevOddSum = currOddSum; + } + + return ans; + } +}; diff --git a/solutions/1588. Sum of All Odd Length Subarrays/1588.java b/solutions/1588. Sum of All Odd Length Subarrays/1588.java new file mode 100644 index 00000000000..0bf9c6dd8cd --- /dev/null +++ b/solutions/1588. Sum of All Odd Length Subarrays/1588.java @@ -0,0 +1,24 @@ +class Solution { + public int sumOddLengthSubarrays(int[] arr) { + int ans = 0; + // Maintain two sums of subarrays ending in the previous index. + // Each time we meet a new number, we'll consider "how many times" it should + // contribute to the newly built subarrays by calculating the number of + // previous even/odd-length subarrays. + int prevEvenSum = 0; // the sum of even-length subarrays + int prevOddSum = 0; // the sum of odd-length subarrays + + for (int i = 0; i < arr.length; ++i) { + // (i + 1) / 2 := the number of previous odd-length subarrays. + final int currEvenSum = prevOddSum + ((i + 1) / 2) * arr[i]; + // i / 2 + 1 := the number of previous even-length subarrays + // (including 0). + final int currOddSum = prevEvenSum + (i / 2 + 1) * arr[i]; + ans += currOddSum; + prevEvenSum = currEvenSum; + prevOddSum = currOddSum; + } + + return ans; + } +} diff --git a/solutions/1588. Sum of All Odd Length Subarrays/1588.py b/solutions/1588. Sum of All Odd Length Subarrays/1588.py new file mode 100644 index 00000000000..177dcefa091 --- /dev/null +++ b/solutions/1588. Sum of All Odd Length Subarrays/1588.py @@ -0,0 +1,21 @@ +class Solution: + def sumOddLengthSubarrays(self, arr: List[int]) -> int: + ans = 0 + # Maintain two sums of subarrays ending in the previous index. + # Each time we meet a new number, we'll consider 'how many times' it should + # contribute to the newly built subarrays by calculating the number of + # previous even/odd-length subarrays. + prevEvenSum = 0 # the sum of even-length subarrays + prevOddSum = 0 # the sum of odd-length subarrays + + for i, a in enumerate(arr): + # (i + 1) // 2 := the number of previous odd-length subarrays. + currEvenSum = prevOddSum + ((i + 1) // 2) * a + # i // 2 + 1 := the number of previous even-length subarrays + # (including 0). + currOddSum = prevEvenSum + (i // 2 + 1) * a + ans += currOddSum + prevEvenSum = currEvenSum + prevOddSum = currOddSum + + return ans diff --git a/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.cpp b/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.cpp new file mode 100644 index 00000000000..2cb253e44bc --- /dev/null +++ b/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maxSumRangeQuery(vector& nums, vector>& requests) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + // count[i] := the number of times nums[i] has been requested + vector count(nums.size()); + + for (const vector& request : requests) { + const int start = request[0]; + const int end = request[1]; + ++count[start]; + if (end + 1 < nums.size()) + --count[end + 1]; + } + + for (int i = 1; i < nums.size(); ++i) + count[i] += count[i - 1]; + + ranges::sort(count); + ranges::sort(nums); + + for (int i = 0; i < nums.size(); ++i) { + ans += static_cast(nums[i]) * count[i]; + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.java b/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.java new file mode 100644 index 00000000000..092524e3480 --- /dev/null +++ b/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.java @@ -0,0 +1,29 @@ +class Solution { + public int maxSumRangeQuery(int[] nums, int[][] requests) { + final int kMod = 1_000_000_007; + long ans = 0; + // count[i] := the number of times nums[i] has been requested + int[] count = new int[nums.length]; + + for (int[] request : requests) { + final int start = request[0]; + final int end = request[1]; + ++count[start]; + if (end + 1 < nums.length) + --count[end + 1]; + } + + for (int i = 1; i < nums.length; ++i) + count[i] += count[i - 1]; + + Arrays.sort(count); + Arrays.sort(nums); + + for (int i = 0; i < nums.length; ++i) { + ans += (long) nums[i] * count[i]; + ans %= kMod; + } + + return (int) ans; + } +} diff --git a/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.py b/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.py new file mode 100644 index 00000000000..ff6891d7408 --- /dev/null +++ b/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.py @@ -0,0 +1,20 @@ +class Solution: + def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int: + kMod = 1_000_000_007 + ans = 0 + # count[i] := the number of times nums[i] has been requested + count = [0] * len(nums) + + for start, end in requests: + count[start] += 1 + if end + 1 < len(nums): + count[end + 1] -= 1 + + for i in range(1, len(nums)): + count[i] += count[i - 1] + + for num, c in zip(sorted(nums), sorted(count)): + ans += num * c + ans %= kMod + + return ans diff --git a/solutions/159. Longest Substring with At Most Two Distinct Characters/159.cpp b/solutions/159. Longest Substring with At Most Two Distinct Characters/159.cpp new file mode 100644 index 00000000000..36334c92598 --- /dev/null +++ b/solutions/159. Longest Substring with At Most Two Distinct Characters/159.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int lengthOfLongestSubstringTwoDistinct(string s) { + int ans = 0; + int distinct = 0; + vector count(128); + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s[r]] == 1) + ++distinct; + while (distinct == 3) + if (--count[s[l++]] == 0) + --distinct; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/159. Longest Substring with At Most Two Distinct Characters/159.java b/solutions/159. Longest Substring with At Most Two Distinct Characters/159.java new file mode 100644 index 00000000000..231d9ec74b8 --- /dev/null +++ b/solutions/159. Longest Substring with At Most Two Distinct Characters/159.java @@ -0,0 +1,18 @@ +class Solution { + public int lengthOfLongestSubstringTwoDistinct(String s) { + int ans = 0; + int distinct = 0; + int[] count = new int[128]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s.charAt(r)] == 1) + ++distinct; + while (distinct == 3) + if (--count[s.charAt(l++)] == 0) + --distinct; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/159. Longest Substring with At Most Two Distinct Characters/159.py b/solutions/159. Longest Substring with At Most Two Distinct Characters/159.py new file mode 100644 index 00000000000..d5344b8ebfe --- /dev/null +++ b/solutions/159. Longest Substring with At Most Two Distinct Characters/159.py @@ -0,0 +1,19 @@ +class Solution: + def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: + ans = 0 + distinct = 0 + count = [0] * 128 + + l = 0 + for r, c in enumerate(s): + count[ord(c)] += 1 + if count[ord(c)] == 1: + distinct += 1 + while distinct == 3: + count[ord(s[l])] -= 1 + if count[ord(s[l])] == 0: + distinct -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/1590. Make Sum Divisible by P/1590.cpp b/solutions/1590. Make Sum Divisible by P/1590.cpp new file mode 100644 index 00000000000..68a0f4bcbf7 --- /dev/null +++ b/solutions/1590. Make Sum Divisible by P/1590.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minSubarray(vector& nums, int p) { + const long sum = accumulate(nums.begin(), nums.end(), 0L); + const int remainder = sum % p; + if (remainder == 0) + return 0; + + unordered_map prefixToIndex{{0, -1}}; + int ans = nums.size(); + int prefix = 0; + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i]; + prefix %= p; + const int target = (prefix - remainder + p) % p; + if (const auto it = prefixToIndex.find(target); + it != prefixToIndex.cend()) + ans = min(ans, i - it->second); + prefixToIndex[prefix] = i; + } + + return ans == nums.size() ? -1 : ans; + } +}; diff --git a/solutions/1590. Make Sum Divisible by P/1590.java b/solutions/1590. Make Sum Divisible by P/1590.java new file mode 100644 index 00000000000..b98fd234679 --- /dev/null +++ b/solutions/1590. Make Sum Divisible by P/1590.java @@ -0,0 +1,24 @@ +class Solution { + public int minSubarray(int[] nums, int p) { + final long sum = Arrays.stream(nums).asLongStream().sum(); + final int remainder = (int) (sum % p); + if (remainder == 0) + return 0; + + int ans = nums.length; + int prefix = 0; + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i]; + prefix %= p; + final int target = (prefix - remainder + p) % p; + if (prefixToIndex.containsKey(target)) + ans = Math.min(ans, i - prefixToIndex.get(target)); + prefixToIndex.put(prefix, i); + } + + return ans == nums.length ? -1 : ans; + } +} diff --git a/solutions/1590. Make Sum Divisible by P/1590.py b/solutions/1590. Make Sum Divisible by P/1590.py new file mode 100644 index 00000000000..7bc5447a2cd --- /dev/null +++ b/solutions/1590. Make Sum Divisible by P/1590.py @@ -0,0 +1,20 @@ +class Solution: + def minSubarray(self, nums: List[int], p: int) -> int: + summ = sum(nums) + remainder = summ % p + if remainder == 0: + return 0 + + ans = len(nums) + prefix = 0 + prefixToIndex = {0: -1} + + for i, num in enumerate(nums): + prefix += num + prefix %= p + target = (prefix - remainder + p) % p + if target in prefixToIndex: + ans = min(ans, i - prefixToIndex[target]) + prefixToIndex[prefix] = i + + return -1 if ans == len(nums) else ans diff --git a/solutions/1591. Strange Printer II/1591.cpp b/solutions/1591. Strange Printer II/1591.cpp new file mode 100644 index 00000000000..28c29203f85 --- /dev/null +++ b/solutions/1591. Strange Printer II/1591.cpp @@ -0,0 +1,58 @@ +enum class State { kInit, kVisiting, kVisited }; + +class Solution { + public: + bool isPrintable(vector>& targetGrid) { + constexpr int kMaxColor = 60; + const int m = targetGrid.size(); + const int n = targetGrid[0].size(); + // graph[u] := {v1, v2} means v1 and v2 cover u + vector> graph(kMaxColor + 1); + + for (int color = 1; color <= kMaxColor; ++color) { + // Get the rectangle of the current color. + int minI = m; + int minJ = n; + int maxI = -1; + int maxJ = -1; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (targetGrid[i][j] == color) { + minI = min(minI, i); + minJ = min(minJ, j); + maxI = max(maxI, i); + maxJ = max(maxJ, j); + } + // Add any color covering the current as the children. + for (int i = minI; i <= maxI; ++i) + for (int j = minJ; j <= maxJ; ++j) + if (targetGrid[i][j] != color) + graph[color].insert(targetGrid[i][j]); + } + + vector states(kMaxColor + 1); + + for (int color = 1; color <= kMaxColor; ++color) + if (hasCycle(graph, color, states)) + return false; + + return true; + } + + private: + bool hasCycle(const vector>& graph, int u, + vector& states) { + if (states[u] == State::kVisiting) + return true; + if (states[u] == State::kVisited) + return false; + + states[u] = State::kVisiting; + for (const int v : graph[u]) + if (hasCycle(graph, v, states)) + return true; + states[u] = State::kVisited; + + return false; + } +}; diff --git a/solutions/1591. Strange Printer II/1591.java b/solutions/1591. Strange Printer II/1591.java new file mode 100644 index 00000000000..c39e8d46091 --- /dev/null +++ b/solutions/1591. Strange Printer II/1591.java @@ -0,0 +1,57 @@ +enum State { kInit, kVisiting, kVisited } + +class Solution { + public boolean isPrintable(int[][] targetGrid) { + final int kMaxColor = 60; + final int m = targetGrid.length; + final int n = targetGrid[0].length; + // graph[u] := {v1, v2} means v1 and v2 cover u + Set[] graph = new HashSet[kMaxColor + 1]; + + for (int color = 1; color <= kMaxColor; ++color) { + // Get the rectangle of the current color. + int minI = m; + int minJ = n; + int maxI = -1; + int maxJ = -1; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (targetGrid[i][j] == color) { + minI = Math.min(minI, i); + minJ = Math.min(minJ, j); + maxI = Math.max(maxI, i); + maxJ = Math.max(maxJ, j); + } + // Add any color covering the current as the children. + graph[color] = new HashSet<>(); + for (int i = minI; i <= maxI; ++i) + for (int j = minJ; j <= maxJ; ++j) + if (targetGrid[i][j] != color) { + graph[color].add(targetGrid[i][j]); + } + } + + State[] states = new State[kMaxColor + 1]; + + for (int color = 1; color <= kMaxColor; ++color) + if (hasCycle(graph, color, states)) + return false; + + return true; + } + + private boolean hasCycle(Set[] graph, int u, State[] states) { + if (states[u] == State.kVisiting) + return true; + if (states[u] == State.kVisited) + return false; + + states[u] = State.kVisiting; + for (int v : graph[u]) + if (hasCycle(graph, v, states)) + return true; + states[u] = State.kVisited; + + return false; + } +} diff --git a/solutions/1591. Strange Printer II/1591.py b/solutions/1591. Strange Printer II/1591.py new file mode 100644 index 00000000000..b50a95179b8 --- /dev/null +++ b/solutions/1591. Strange Printer II/1591.py @@ -0,0 +1,54 @@ +from enum import Enum + + +class State(Enum): + kInit = 0 + kVisiting = 1 + kVisited = 2 + + +class Solution: + def isPrintable(self, targetGrid: List[List[int]]) -> bool: + kMaxColor = 60 + m = len(targetGrid) + n = len(targetGrid[0]) + + # graph[u] := {v1, v2} means v1 and v2 cover u + graph = [set() for _ in range(kMaxColor + 1)] + + for color in range(1, kMaxColor + 1): + # Get the rectangle of the current color. + minI = m + minJ = n + maxI = -1 + maxJ = -1 + for i in range(m): + for j in range(n): + if targetGrid[i][j] == color: + minI = min(minI, i) + minJ = min(minJ, j) + maxI = max(maxI, i) + maxJ = max(maxJ, j) + + # Add any color covering the current as the children. + for i in range(minI, maxI + 1): + for j in range(minJ, maxJ + 1): + if targetGrid[i][j] != color: + graph[color].add(targetGrid[i][j]) + + states = [State.kInit] * (kMaxColor + 1) + + def hasCycle(u: int) -> bool: + if states[u] == State.kVisiting: + return True + if states[u] == State.kVisited: + return False + + states[u] = State.kVisiting + if any(hasCycle(v) for v in graph[u]): + return True + states[u] = State.kVisited + + return False + + return not (any(hasCycle(i) for i in range(1, kMaxColor + 1))) diff --git a/solutions/1592. Rearrange Spaces Between Words/1592.cpp b/solutions/1592. Rearrange Spaces Between Words/1592.cpp new file mode 100644 index 00000000000..2bf8ea2842f --- /dev/null +++ b/solutions/1592. Rearrange Spaces Between Words/1592.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + string reorderSpaces(string text) { + const int spaces = ranges::count(text, ' '); + string ans; + vector words; + + istringstream iss(text); + string word; + + while (iss >> word) + words.push_back(word); + + if (words.size() == 1) + return word + string(spaces, ' '); + + const int gapSize = spaces / (words.size() - 1); + const int remains = spaces % (words.size() - 1); + + for (int i = 0; i < words.size() - 1; ++i) + ans += words[i] + string(gapSize, ' '); + ans += words.back() + string(remains, ' '); + + return ans; + } +}; diff --git a/solutions/1592. Rearrange Spaces Between Words/1592.java b/solutions/1592. Rearrange Spaces Between Words/1592.java new file mode 100644 index 00000000000..7517ae7d87b --- /dev/null +++ b/solutions/1592. Rearrange Spaces Between Words/1592.java @@ -0,0 +1,10 @@ +class Solution { + public String reorderSpaces(String text) { + final String[] words = text.trim().split("\\s+"); + final int spaces = (int) text.chars().filter(c -> c == ' ').count(); + final int n = words.length; + final int gapSize = n == 1 ? 0 : spaces / (n - 1); + final int remains = n == 1 ? spaces : spaces % (n - 1); + return String.join(" ".repeat(gapSize), words) + " ".repeat(remains); + } +} diff --git a/solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.cpp b/solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.cpp new file mode 100644 index 00000000000..8c1923b642b --- /dev/null +++ b/solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maxUniqueSplit(string s) { + size_t ans = 0; + dfs(s, 0, {}, ans); + return ans; + } + + private: + void dfs(const string& s, int start, unordered_set&& seen, + size_t& ans) { + if (start == s.length()) { + ans = max(ans, seen.size()); + return; + } + + for (int i = 1; start + i <= s.length(); ++i) { + const string cand = s.substr(start, i); + if (seen.contains(cand)) + continue; + seen.insert(cand); + dfs(s, start + i, move(seen), ans); + seen.erase(cand); + } + } +}; diff --git a/solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.java b/solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.java new file mode 100644 index 00000000000..71f3f3e5def --- /dev/null +++ b/solutions/1593. Split a String Into the Max Number of Unique Substrings/1593.java @@ -0,0 +1,24 @@ +class Solution { + public int maxUniqueSplit(String s) { + dfs(s, 0, new HashSet<>()); + return ans; + } + + private int ans = 0; + + private void dfs(final String s, int start, Set seen) { + if (start == s.length()) { + ans = Math.max(ans, seen.size()); + return; + } + + for (int i = start + 1; i <= s.length(); ++i) { + final String cand = s.substring(start, i); + if (seen.contains(cand)) + continue; + seen.add(cand); + dfs(s, i, seen); + seen.remove(cand); + } + } +} diff --git a/solutions/1594. Maximum Non Negative Product in a Matrix/1594.cpp b/solutions/1594. Maximum Non Negative Product in a Matrix/1594.cpp new file mode 100644 index 00000000000..cc226e3e6f9 --- /dev/null +++ b/solutions/1594. Maximum Non Negative Product in a Matrix/1594.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int maxProductPath(vector>& grid) { + constexpr int kMod = 1'000'000'007; + const int m = grid.size(); + const int n = grid[0].size(); + // dpMin[i][j] := the minimum product from (0, 0) to (i, j) + // dpMax[i][j] := the maximum product from (0, 0) to (i, j) + vector> dpMin(m, vector(n)); + vector> dpMax(m, vector(n)); + + dpMin[0][0] = dpMax[0][0] = grid[0][0]; + + for (int i = 1; i < m; ++i) + dpMin[i][0] = dpMax[i][0] = dpMin[i - 1][0] * grid[i][0]; + + for (int j = 1; j < n; ++j) + dpMin[0][j] = dpMax[0][j] = dpMin[0][j - 1] * grid[0][j]; + + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (grid[i][j] < 0) { + dpMin[i][j] = max(dpMax[i - 1][j], dpMax[i][j - 1]) * grid[i][j]; + dpMax[i][j] = min(dpMin[i - 1][j], dpMin[i][j - 1]) * grid[i][j]; + } else { + dpMin[i][j] = min(dpMin[i - 1][j], dpMin[i][j - 1]) * grid[i][j]; + dpMax[i][j] = max(dpMax[i - 1][j], dpMax[i][j - 1]) * grid[i][j]; + } + + const long mx = max(dpMin.back().back(), dpMax.back().back()); + return mx < 0 ? -1 : mx % kMod; + } +}; diff --git a/solutions/1594. Maximum Non Negative Product in a Matrix/1594.java b/solutions/1594. Maximum Non Negative Product in a Matrix/1594.java new file mode 100644 index 00000000000..63a1b34e86e --- /dev/null +++ b/solutions/1594. Maximum Non Negative Product in a Matrix/1594.java @@ -0,0 +1,32 @@ +class Solution { + public int maxProductPath(int[][] grid) { + final int kMod = 1_000_000_007; + final int m = grid.length; + final int n = grid[0].length; + // dpMin[i][j] := the minimum product from (0, 0) to (i, j) + // dpMax[i][j] := the maximum product from (0, 0) to (i, j) + long[][] dpMin = new long[m][n]; + long[][] dpMax = new long[m][n]; + + dpMin[0][0] = dpMax[0][0] = grid[0][0]; + + for (int i = 1; i < m; ++i) + dpMin[i][0] = dpMax[i][0] = dpMin[i - 1][0] * grid[i][0]; + + for (int j = 1; j < n; ++j) + dpMin[0][j] = dpMax[0][j] = dpMin[0][j - 1] * grid[0][j]; + + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (grid[i][j] < 0) { + dpMin[i][j] = Math.max(dpMax[i - 1][j], dpMax[i][j - 1]) * grid[i][j]; + dpMax[i][j] = Math.min(dpMin[i - 1][j], dpMin[i][j - 1]) * grid[i][j]; + } else { + dpMin[i][j] = Math.min(dpMin[i - 1][j], dpMin[i][j - 1]) * grid[i][j]; + dpMax[i][j] = Math.max(dpMax[i - 1][j], dpMax[i][j - 1]) * grid[i][j]; + } + + final long mx = Math.max(dpMin[m - 1][n - 1], dpMax[m - 1][n - 1]); + return mx < 0 ? -1 : (int) (mx % kMod); + } +} diff --git a/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.cpp b/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.cpp new file mode 100644 index 00000000000..4aec2d7a4c4 --- /dev/null +++ b/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + int connectTwoGroups(vector>& cost) { + const int m = cost.size(); + const int n = cost[0].size(); + vector> mem(m, vector(1 << n, INT_MAX)); + // minCosts[j] := the minimum cost of connecting group2's point j + vector minCosts(n); + + for (int j = 0; j < n; ++j) { + int minCostIndex = 0; + for (int i = 1; i < m; ++i) + if (cost[i][j] < cost[minCostIndex][j]) + minCostIndex = i; + minCosts[j] = cost[minCostIndex][j]; + } + + return connectTwoGroups(cost, 0, 0, minCosts, mem); + } + + private: + // Returns the minimum cost to connect group1's points[i..n) with group2's + // points, where `mask` is the bitmask of the connected points in group2. + int connectTwoGroups(const vector>& cost, int i, int mask, + const vector& minCosts, vector>& mem) { + if (i == cost.size()) { + // All the points in group 1 are connected, so greedily assign the + // minimum cost for the unconnected points of group2. + int res = 0; + for (int j = 0; j < cost[0].size(); ++j) + if ((mask >> j & 1) == 0) + res += minCosts[j]; + return res; + } + if (mem[i][mask] != INT_MAX) + return mem[i][mask]; + + for (int j = 0; j < cost[0].size(); ++j) + mem[i][mask] = + min(mem[i][mask], + cost[i][j] + + connectTwoGroups(cost, i + 1, mask | 1 << j, minCosts, mem)); + + return mem[i][mask]; + } +}; diff --git a/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.java b/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.java new file mode 100644 index 00000000000..8a445a198b5 --- /dev/null +++ b/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.java @@ -0,0 +1,42 @@ +class Solution { + public int connectTwoGroups(List> cost) { + final int m = cost.size(); + final int n = cost.get(0).size(); + Integer[][] mem = new Integer[m][1 << n]; + // minCosts[j] := the minimum cost of connecting group2's point j + int[] minCosts = new int[n]; + + for (int j = 0; j < n; ++j) { + int minCostIndex = 0; + for (int i = 1; i < m; ++i) + if (cost.get(i).get(j) < cost.get(minCostIndex).get(j)) + minCostIndex = i; + minCosts[j] = cost.get(minCostIndex).get(j); + } + + return connectTwoGroups(cost, 0, 0, minCosts, mem); + } + + // Returns the minimum cost to connect group1's points[i..n) with group2's + // points, where `mask` is the bitmask of the connected points in group2. + private int connectTwoGroups(List> cost, int i, int mask, int[] minCosts, + Integer[][] mem) { + if (i == cost.size()) { + // All the points in group 1 are connected, so greedily assign the + // minimum cost for the unconnected points of group2. + int res = 0; + for (int j = 0; j < cost.get(0).size(); ++j) + if ((mask >> j & 1) == 0) + res += minCosts[j]; + return res; + } + if (mem[i][mask] != null) + return mem[i][mask]; + + int res = Integer.MAX_VALUE; + for (int j = 0; j < cost.get(0).size(); ++j) + res = Math.min(res, cost.get(i).get(j) + + connectTwoGroups(cost, i + 1, mask | 1 << j, minCosts, mem)); + return mem[i][mask] = res; + } +} diff --git a/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.py b/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.py new file mode 100644 index 00000000000..92c09a01346 --- /dev/null +++ b/solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.py @@ -0,0 +1,20 @@ +class Solution: + def connectTwoGroups(self, cost: List[List[int]]) -> int: + # minCosts[j] := the minimum cost of connecting group2's point j + minCosts = [min(col) for col in zip(*cost)] + + @functools.lru_cache(None) + def dp(i: int, mask: int) -> int: + """ + Returns the minimum cost to connect group1's points[i..n) with group2's + points, where `mask` is the bitmask of the connected points in group2. + """ + if i == len(cost): + # All the points in group 1 are connected, so greedily assign the + # minimum cost for the unconnected points of group2. + return sum(minCost for j, minCost in enumerate(minCosts) + if (mask >> j & 1) == 0) + return min(cost[i][j] + dp(i + 1, mask | 1 << j) + for j in range(len(cost[0]))) + + return dp(0, 0) diff --git a/solutions/1596. The Most Frequently Ordered Products for Each Customer/1596.sql b/solutions/1596. The Most Frequently Ordered Products for Each Customer/1596.sql new file mode 100644 index 00000000000..0d07da4cddf --- /dev/null +++ b/solutions/1596. The Most Frequently Ordered Products for Each Customer/1596.sql @@ -0,0 +1,21 @@ +WITH + RankedOrders AS ( + SELECT + Orders.customer_id, + Orders.product_id, + Products.product_name, + RANK() OVER( + PARTITION BY Orders.customer_id + ORDER BY COUNT(Orders.product_id) DESC + ) AS `rank` + FROM Orders + INNER JOIN Products + USING (product_id) + GROUP BY 1, 2 + ) +SELECT + customer_id, + product_id, + product_name +FROM RankedOrders +WHERE `rank` = 1; diff --git a/solutions/1597. Build Binary Expression Tree From Infix Expression/1597.cpp b/solutions/1597. Build Binary Expression Tree From Infix Expression/1597.cpp new file mode 100644 index 00000000000..091323898c3 --- /dev/null +++ b/solutions/1597. Build Binary Expression Tree From Infix Expression/1597.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + Node* expTree(string s) { + stack nodes; + stack ops; // [operators | parentheses] + + for (const char c : s) + if (isdigit(c)) { + nodes.push(new Node(c)); + } else if (c == '(') { + ops.push(c); + } else if (c == ')') { + while (ops.top() != '(') + nodes.push(buildNode(pop(ops), pop(nodes), pop(nodes))); + ops.pop(); // Remove '('. + } else if (c == '+' || c == '-' || c == '*' || c == '/') { + while (!ops.empty() && compare(ops.top(), c)) + nodes.push(buildNode(pop(ops), pop(nodes), pop(nodes))); + ops.push(c); + } + + while (!ops.empty()) + nodes.push(buildNode(pop(ops), pop(nodes), pop(nodes))); + + return nodes.top(); + } + + private: + Node* buildNode(char op, Node* right, Node* left) { + return new Node(op, left, right); + } + + // Returns true if op1 is a operator and priority(op1) >= priority(op2). + bool compare(char op1, char op2) { + if (op1 == '(' || op1 == ')') + return false; + return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-'; + } + + char pop(stack& ops) { + const char op = ops.top(); + ops.pop(); + return op; + } + + Node* pop(stack& nodes) { + Node* node = nodes.top(); + nodes.pop(); + return node; + } +}; diff --git a/solutions/1597. Build Binary Expression Tree From Infix Expression/1597.java b/solutions/1597. Build Binary Expression Tree From Infix Expression/1597.java new file mode 100644 index 00000000000..51bded00fbf --- /dev/null +++ b/solutions/1597. Build Binary Expression Tree From Infix Expression/1597.java @@ -0,0 +1,37 @@ +class Solution { + public Node expTree(String s) { + Deque nodes = new ArrayDeque<>(); + Deque ops = new ArrayDeque<>(); // [operators | parentheses] + + for (final char c : s.toCharArray()) + if (Character.isDigit(c)) { + nodes.push(new Node(c)); + } else if (c == '(') { + ops.push(c); + } else if (c == ')') { + while (ops.peek() != '(') + nodes.push(buildNode(ops.pop(), nodes.pop(), nodes.pop())); + ops.pop(); // Remove '('. + } else { // c == '+' || c == '-' || c == '*' || c == '/' + while (!ops.isEmpty() && compare(ops.peek(), c)) + nodes.push(buildNode(ops.pop(), nodes.pop(), nodes.pop())); + ops.push(c); + } + + while (!ops.isEmpty()) + nodes.push(buildNode(ops.pop(), nodes.pop(), nodes.pop())); + + return nodes.peek(); + } + + private Node buildNode(char op, Node right, Node left) { + return new Node(op, left, right); + } + + // Returns true if op1 is a operator and priority(op1) >= priority(op2). + boolean compare(char op1, char op2) { + if (op1 == '(' || op1 == ')') + return false; + return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-'; + } +} diff --git a/solutions/1598. Crawler Log Folder/1598.cpp b/solutions/1598. Crawler Log Folder/1598.cpp new file mode 100644 index 00000000000..8c1f87d361b --- /dev/null +++ b/solutions/1598. Crawler Log Folder/1598.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minOperations(vector& logs) { + int ans = 0; + + for (const string& log : logs) { + if (log == "./") + continue; + if (log == "../") + ans = max(0, ans - 1); + else + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1598. Crawler Log Folder/1598.java b/solutions/1598. Crawler Log Folder/1598.java new file mode 100644 index 00000000000..6eff8fb0a5c --- /dev/null +++ b/solutions/1598. Crawler Log Folder/1598.java @@ -0,0 +1,16 @@ +class Solution { + public int minOperations(String[] logs) { + int ans = 0; + + for (final String log : logs) { + if (log.equals("./")) + continue; + if (log.equals("../")) + ans = Math.max(0, ans - 1); + else + ++ans; + } + + return ans; + } +} diff --git a/solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.cpp b/solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.cpp new file mode 100644 index 00000000000..2f8052955c7 --- /dev/null +++ b/solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int minOperationsMaxProfit(vector& customers, int boardingCost, + int runningCost) { + int waiting = 0; + int profit = 0; + int maxProfit = 0; + int rotate = 0; + int maxRotate = -1; + int i = 0; + + while (waiting > 0 || i < customers.size()) { + if (i < customers.size()) + waiting += customers[i++]; + // Onboard new customers. + const int newOnboard = min(waiting, 4); + waiting -= newOnboard; + profit += newOnboard * boardingCost - runningCost; + ++rotate; + if (profit > maxProfit) { + maxProfit = profit; + maxRotate = rotate; + } + } + + return maxRotate; + } +}; diff --git a/solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.java b/solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.java new file mode 100644 index 00000000000..989f659e146 --- /dev/null +++ b/solutions/1599. Maximum Profit of Operating a Centennial Wheel/1599.java @@ -0,0 +1,26 @@ +class Solution { + public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) { + int waiting = 0; + int profit = 0; + int maxProfit = 0; + int rotate = 0; + int maxRotate = -1; + int i = 0; + + while (waiting > 0 || i < customers.length) { + if (i < customers.length) + waiting += customers[i++]; + // Onboard new customers. + final int newOnboard = Math.min(waiting, 4); + waiting -= newOnboard; + profit += newOnboard * boardingCost - runningCost; + ++rotate; + if (profit > maxProfit) { + maxProfit = profit; + maxRotate = rotate; + } + } + + return maxRotate; + } +} diff --git a/solutions/16. 3Sum Closest/16.cpp b/solutions/16. 3Sum Closest/16.cpp new file mode 100644 index 00000000000..2d11e0e5f0d --- /dev/null +++ b/solutions/16. 3Sum Closest/16.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int threeSumClosest(vector& nums, int target) { + int ans = nums[0] + nums[1] + nums[2]; + + ranges::sort(nums); + + for (int i = 0; i + 2 < nums.size(); ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + // Choose nums[i] as the first number in the triplet, then search the + // remaining numbers in [i + 1, n - 1]. + int l = i + 1; + int r = nums.size() - 1; + while (l < r) { + const int sum = nums[i] + nums[l] + nums[r]; + if (sum == target) + return sum; + if (abs(sum - target) < abs(ans - target)) + ans = sum; + if (sum < target) + ++l; + else + --r; + } + } + + return ans; + } +}; diff --git a/solutions/16. 3Sum Closest/16.java b/solutions/16. 3Sum Closest/16.java new file mode 100644 index 00000000000..15679e67dc8 --- /dev/null +++ b/solutions/16. 3Sum Closest/16.java @@ -0,0 +1,29 @@ +class Solution { + public int threeSumClosest(int[] nums, int target) { + int ans = nums[0] + nums[1] + nums[2]; + + Arrays.sort(nums); + + for (int i = 0; i + 2 < nums.length; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + // Choose nums[i] as the first number in the triplet, then search the + // remaining numbers in [i + 1, n - 1]. + int l = i + 1; + int r = nums.length - 1; + while (l < r) { + final int sum = nums[i] + nums[l] + nums[r]; + if (sum == target) + return sum; + if (Math.abs(sum - target) < Math.abs(ans - target)) + ans = sum; + if (sum < target) + ++l; + else + --r; + } + } + + return ans; + } +} diff --git a/solutions/16. 3Sum Closest/16.py b/solutions/16. 3Sum Closest/16.py new file mode 100644 index 00000000000..25dbd767419 --- /dev/null +++ b/solutions/16. 3Sum Closest/16.py @@ -0,0 +1,25 @@ +class Solution: + def threeSumClosest(self, nums: List[int], target: int) -> int: + ans = nums[0] + nums[1] + nums[2] + + nums.sort() + + for i in range(len(nums) - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + # Choose nums[i] as the first number in the triplet, then search the + # remaining numbers in [i + 1, n - 1]. + l = i + 1 + r = len(nums) - 1 + while l < r: + summ = nums[i] + nums[l] + nums[r] + if summ == target: + return summ + if abs(summ - target) < abs(ans - target): + ans = summ + if summ < target: + l += 1 + else: + r -= 1 + + return ans diff --git a/solutions/160. Intersection of Two Linked Lists/160.cpp b/solutions/160. Intersection of Two Linked Lists/160.cpp new file mode 100644 index 00000000000..b3cf44f38fd --- /dev/null +++ b/solutions/160. Intersection of Two Linked Lists/160.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) { + ListNode* a = headA; + ListNode* b = headB; + + while (a != b) { + a = a == nullptr ? headB : a->next; + b = b == nullptr ? headA : b->next; + } + + return a; + } +}; diff --git a/solutions/160. Intersection of Two Linked Lists/160.java b/solutions/160. Intersection of Two Linked Lists/160.java new file mode 100644 index 00000000000..5ff44ef5d0c --- /dev/null +++ b/solutions/160. Intersection of Two Linked Lists/160.java @@ -0,0 +1,13 @@ +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + ListNode a = headA; + ListNode b = headB; + + while (a != b) { + a = a == null ? headB : a.next; + b = b == null ? headA : b.next; + } + + return a; + } +} diff --git a/solutions/160. Intersection of Two Linked Lists/160.py b/solutions/160. Intersection of Two Linked Lists/160.py new file mode 100644 index 00000000000..7d227c2ed02 --- /dev/null +++ b/solutions/160. Intersection of Two Linked Lists/160.py @@ -0,0 +1,10 @@ +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: + a = headA + b = headB + + while a != b: + a = a.next if a else headB + b = b.next if b else headA + + return a diff --git a/solutions/1600. Throne Inheritance/1600.cpp b/solutions/1600. Throne Inheritance/1600.cpp new file mode 100644 index 00000000000..ca7034a31af --- /dev/null +++ b/solutions/1600. Throne Inheritance/1600.cpp @@ -0,0 +1,33 @@ +class ThroneInheritance { + public: + ThroneInheritance(string kingName) : kingName(kingName) {} + + void birth(string parentName, string childName) { + family[parentName].push_back(childName); + } + + void death(string name) { + dead.insert(name); + } + + vector getInheritanceOrder() { + vector ans; + dfs(kingName, ans); + return ans; + } + + private: + unordered_set dead; + unordered_map> family; + string kingName; + + void dfs(const string& name, vector& ans) { + if (!dead.contains(name)) + ans.push_back(name); + if (!family.contains(name)) + return; + + for (const string& child : family[name]) + dfs(child, ans); + } +}; diff --git a/solutions/1600. Throne Inheritance/1600.java b/solutions/1600. Throne Inheritance/1600.java new file mode 100644 index 00000000000..0e7ab8a2109 --- /dev/null +++ b/solutions/1600. Throne Inheritance/1600.java @@ -0,0 +1,34 @@ +class ThroneInheritance { + public ThroneInheritance(String kingName) { + this.kingName = kingName; + } + + public void birth(String parentName, String childName) { + family.putIfAbsent(parentName, new ArrayList<>()); + family.get(parentName).add(childName); + } + + public void death(String name) { + dead.add(name); + } + + public List getInheritanceOrder() { + List ans = new ArrayList<>(); + dfs(kingName, ans); + return ans; + } + + private Set dead = new HashSet<>(); + private Map> family = new HashMap<>(); + private String kingName; + + private void dfs(final String name, List ans) { + if (!dead.contains(name)) + ans.add(name); + if (!family.containsKey(name)) + return; + + for (final String child : family.get(name)) + dfs(child, ans); + } +} diff --git a/solutions/1601. Maximum Number of Achievable Transfer Requests/1601.cpp b/solutions/1601. Maximum Number of Achievable Transfer Requests/1601.cpp new file mode 100644 index 00000000000..cc958440167 --- /dev/null +++ b/solutions/1601. Maximum Number of Achievable Transfer Requests/1601.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maximumRequests(int n, vector>& requests) { + int ans = 0; + vector degrees(n); // degrees[i] := degrees of the i-th building + + function dfs = [&](int i, int processedReqs) { + if (i == requests.size()) { + if (ranges::all_of(degrees, [](int d) { return d == 0; })) + ans = max(ans, processedReqs); + return; + } + + // Skip the requests[i]. + dfs(i + 1, processedReqs); + + // Process the requests[i]. + --degrees[requests[i][0]]; + ++degrees[requests[i][1]]; + dfs(i + 1, processedReqs + 1); + --degrees[requests[i][1]]; + ++degrees[requests[i][0]]; + }; + + dfs(0, 0); + + return ans; + } +}; diff --git a/solutions/1601. Maximum Number of Achievable Transfer Requests/1601.java b/solutions/1601. Maximum Number of Achievable Transfer Requests/1601.java new file mode 100644 index 00000000000..89c3ab6123f --- /dev/null +++ b/solutions/1601. Maximum Number of Achievable Transfer Requests/1601.java @@ -0,0 +1,27 @@ +class Solution { + public int maximumRequests(int n, int[][] requests) { + dfs(0, 0, requests, new int[n]); + + return ans; + } + + private int ans = 0; + + private void dfs(int i, int processedReqs, int[][] requests, int[] degrees) { + if (i == requests.length) { + if (Arrays.stream(degrees).allMatch(d -> d == 0)) + ans = Math.max(ans, processedReqs); + return; + } + + // Skip the requests[i]. + dfs(i + 1, processedReqs, requests, degrees); + + // Process the requests[i]. + --degrees[requests[i][0]]; + ++degrees[requests[i][1]]; + dfs(i + 1, processedReqs + 1, requests, degrees); + --degrees[requests[i][1]]; + ++degrees[requests[i][0]]; + } +} diff --git a/solutions/1602. Find Nearest Right Node in Binary Tree/1602.cpp b/solutions/1602. Find Nearest Right Node in Binary Tree/1602.cpp new file mode 100644 index 00000000000..467a39b334e --- /dev/null +++ b/solutions/1602. Find Nearest Right Node in Binary Tree/1602.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) { + TreeNode* ans = nullptr; + int targetDepth = -1; + dfs(root, u, 0, targetDepth, ans); + return ans; + } + + private: + void dfs(TreeNode* root, TreeNode* u, int depth, int& targetDepth, + TreeNode*& ans) { + if (root == nullptr) + return; + if (root == u) { + targetDepth = depth; + return; + } + if (depth == targetDepth && ans == nullptr) { + ans = root; + return; + } + dfs(root->left, u, depth + 1, targetDepth, ans); + dfs(root->right, u, depth + 1, targetDepth, ans); + } +}; diff --git a/solutions/1602. Find Nearest Right Node in Binary Tree/1602.java b/solutions/1602. Find Nearest Right Node in Binary Tree/1602.java new file mode 100644 index 00000000000..43d7fcaa8e0 --- /dev/null +++ b/solutions/1602. Find Nearest Right Node in Binary Tree/1602.java @@ -0,0 +1,24 @@ +class Solution { + public TreeNode findNearestRightNode(TreeNode root, TreeNode u) { + dfs(root, u, 0); + return ans; + } + + private TreeNode ans = null; + private int targetDepth = -1; + + private void dfs(TreeNode root, TreeNode u, int depth) { + if (root == null) + return; + if (root == u) { + targetDepth = depth; + return; + } + if (depth == targetDepth && ans == null) { + ans = root; + return; + } + dfs(root.left, u, depth + 1); + dfs(root.right, u, depth + 1); + } +} diff --git a/solutions/1602. Find Nearest Right Node in Binary Tree/1602.py b/solutions/1602. Find Nearest Right Node in Binary Tree/1602.py new file mode 100644 index 00000000000..625b59a5f08 --- /dev/null +++ b/solutions/1602. Find Nearest Right Node in Binary Tree/1602.py @@ -0,0 +1,21 @@ +class Solution: + def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: + ans = None + targetDepth = -1 + + def dfs(root: TreeNode, depth: int) -> None: + nonlocal ans + nonlocal targetDepth + if not root: + return + if root == u: + targetDepth = depth + return + if depth == targetDepth and not ans: + ans = root + return + dfs(root.left, depth + 1) + dfs(root.right, depth + 1) + + dfs(root, 0) + return ans diff --git a/solutions/1603. Design Parking System/1603.cpp b/solutions/1603. Design Parking System/1603.cpp new file mode 100644 index 00000000000..218bd7eaa2d --- /dev/null +++ b/solutions/1603. Design Parking System/1603.cpp @@ -0,0 +1,13 @@ +class ParkingSystem { + public: + ParkingSystem(int big, int medium, int small) { + count = {big, medium, small}; + } + + bool addCar(int carType) { + return count[carType - 1]-- > 0; + } + + private: + vector count; +}; diff --git a/solutions/1603. Design Parking System/1603.java b/solutions/1603. Design Parking System/1603.java new file mode 100644 index 00000000000..fd3c4a4468b --- /dev/null +++ b/solutions/1603. Design Parking System/1603.java @@ -0,0 +1,11 @@ +class ParkingSystem { + public ParkingSystem(int big, int medium, int small) { + count = new int[] {big, medium, small}; + } + + public boolean addCar(int carType) { + return count[carType - 1]-- > 0; + } + + private int[] count; +} diff --git a/solutions/1603. Design Parking System/1603.py b/solutions/1603. Design Parking System/1603.py new file mode 100644 index 00000000000..6d21ae388ed --- /dev/null +++ b/solutions/1603. Design Parking System/1603.py @@ -0,0 +1,7 @@ +class ParkingSystem: + def __init__(self, big: int, medium: int, small: int): + self.count = [big, medium, small] + + def addCar(self, carType: int) -> bool: + self.count[carType - 1] -= 1 + return self.count[carType - 1] >= 0 diff --git a/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.cpp b/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.cpp new file mode 100644 index 00000000000..f636ac8f08f --- /dev/null +++ b/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector alertNames(vector& keyName, vector& keyTime) { + vector ans; + unordered_map> nameToMinutes; + + for (int i = 0; i < keyName.size(); ++i) { + const int minutes = getMinutes(keyTime[i]); + nameToMinutes[keyName[i]].push_back(minutes); + } + + for (auto& [name, minutes] : nameToMinutes) + if (hasAlert(minutes)) + ans.push_back(name); + + ranges::sort(ans); + return ans; + } + + private: + // Returns true if any worker uses the key-card three or more times in an + // one-hour period. + bool hasAlert(vector& minutes) { + if (minutes.size() > 70) + return true; + ranges::sort(minutes); + for (int i = 2; i < minutes.size(); ++i) + if (minutes[i - 2] + 60 >= minutes[i]) + return true; + return false; + } + + int getMinutes(const string& time) { + const int h = stoi(time.substr(0, 2)); + const int m = stoi(time.substr(3)); + return 60 * h + m; + } +}; diff --git a/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.java b/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.java new file mode 100644 index 00000000000..6afeff20013 --- /dev/null +++ b/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.java @@ -0,0 +1,38 @@ +class Solution { + public List alertNames(String[] keyName, String[] keyTime) { + List ans = new ArrayList<>(); + HashMap> nameToMinutes = new HashMap<>(); + + for (int i = 0; i < keyName.length; i++) { + final int minutes = getMinutes(keyTime[i]); + nameToMinutes.putIfAbsent(keyName[i], new ArrayList<>()); + nameToMinutes.get(keyName[i]).add(minutes); + } + + for (Map.Entry> entry : nameToMinutes.entrySet()) { + final String name = entry.getKey(); + List minutes = entry.getValue(); + if (hasAlert(minutes)) + ans.add(name); + } + + Collections.sort(ans); + return ans; + } + + private boolean hasAlert(List minutes) { + if (minutes.size() > 70) + return true; + Collections.sort(minutes); + for (int i = 2; i < minutes.size(); i++) + if (minutes.get(i - 2) + 60 >= minutes.get(i)) + return true; + return false; + } + + private int getMinutes(String time) { + final int h = Integer.parseInt(time.substring(0, 2)); + final int m = Integer.parseInt(time.substring(3)); + return 60 * h + m; + } +} diff --git a/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.py b/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.py new file mode 100644 index 00000000000..78af698707a --- /dev/null +++ b/solutions/1604. Alert Using Same Key-Card Three or More Times in a One Hour Period/1604.py @@ -0,0 +1,23 @@ +class Solution: + def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]: + nameToMinutes = collections.defaultdict(list) + + for name, time in zip(keyName, keyTime): + minutes = self._getMinutes(time) + nameToMinutes[name].append(minutes) + + return sorted([name for name, minutes in nameToMinutes.items() + if self._hasAlert(minutes)]) + + def _hasAlert(self, minutes: List[int]) -> bool: + if len(minutes) > 70: + return True + minutes.sort() + for i in range(2, len(minutes)): + if minutes[i - 2] + 60 >= minutes[i]: + return True + return False + + def _getMinutes(self, time: str) -> int: + h, m = map(int, time.split(':')) + return 60 * h + m diff --git a/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.cpp b/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.cpp new file mode 100644 index 00000000000..aacd00aef2a --- /dev/null +++ b/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector> restoreMatrix(vector& rowSum, vector& colSum) { + const int m = rowSum.size(); + const int n = colSum.size(); + vector> ans(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + ans[i][j] = min(rowSum[i], colSum[j]); + rowSum[i] -= ans[i][j]; + colSum[j] -= ans[i][j]; + } + + return ans; + } +}; diff --git a/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.java b/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.java new file mode 100644 index 00000000000..6c765991fec --- /dev/null +++ b/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.java @@ -0,0 +1,16 @@ +class Solution { + public int[][] restoreMatrix(int[] rowSum, int[] colSum) { + final int m = rowSum.length; + final int n = colSum.length; + int[][] ans = new int[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + ans[i][j] = Math.min(rowSum[i], colSum[j]); + rowSum[i] -= ans[i][j]; + colSum[j] -= ans[i][j]; + } + + return ans; + } +} diff --git a/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.py b/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.py new file mode 100644 index 00000000000..42dbec773e2 --- /dev/null +++ b/solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.py @@ -0,0 +1,13 @@ +class Solution: + def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: + m = len(rowSum) + n = len(colSum) + ans = [[0] * n for _ in range(m)] + + for i in range(m): + for j in range(n): + ans[i][j] = min(rowSum[i], colSum[j]) + rowSum[i] -= ans[i][j] + colSum[j] -= ans[i][j] + + return ans diff --git a/solutions/1606. Find Servers That Handled Most Number of Requests/1606.cpp b/solutions/1606. Find Servers That Handled Most Number of Requests/1606.cpp new file mode 100644 index 00000000000..c27287d6a68 --- /dev/null +++ b/solutions/1606. Find Servers That Handled Most Number of Requests/1606.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + vector busiestServers(int k, vector& arrival, vector& load) { + vector ans; + vector times(k); + set idleServers; + // (endTime, server) + priority_queue, vector>, greater<>> minHeap; + + for (int i = 0; i < k; ++i) + idleServers.insert(i); + + for (int i = 0; i < arrival.size(); ++i) { + // Pop all the servers that are available now. + while (!minHeap.empty() && minHeap.top().first <= arrival[i]) { + idleServers.insert(minHeap.top().second); + minHeap.pop(); + } + // Get the next available server. + const int server = getNextAvailableServer(idleServers, i, k); + if (server == -1) + continue; + ++times[server]; + minHeap.emplace(arrival[i] + load[i], server); + idleServers.erase(server); + } + + const int busiest = ranges::max(times); + for (int i = 0; i < k; ++i) + if (times[i] == busiest) + ans.push_back(i); + return ans; + } + + private: + int getNextAvailableServer(const set& idleServers, int ithRequest, + int k) { + if (idleServers.empty()) + return -1; + const auto it = idleServers.lower_bound(ithRequest % k); + return it == idleServers.cend() ? *idleServers.begin() : *it; + } +}; diff --git a/solutions/1606. Find Servers That Handled Most Number of Requests/1606.java b/solutions/1606. Find Servers That Handled Most Number of Requests/1606.java new file mode 100644 index 00000000000..805a307b658 --- /dev/null +++ b/solutions/1606. Find Servers That Handled Most Number of Requests/1606.java @@ -0,0 +1,40 @@ +class Solution { + public List busiestServers(int k, int[] arrival, int[] load) { + List ans = new ArrayList<>(); + int[] times = new int[k]; + TreeSet idleServers = new TreeSet<>(); + // (endTime, server) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + for (int i = 0; i < k; ++i) + idleServers.add(i); + + for (int i = 0; i < arrival.length; ++i) { + // Pop all the servers that are available now. + while (!minHeap.isEmpty() && minHeap.peek().getKey() <= arrival[i]) { + idleServers.add(minHeap.peek().getValue()); + minHeap.poll(); + } + // Get the next available server. + final int server = getNextAvailableServer(idleServers, i, k); + if (server == -1) + continue; + ++times[server]; + minHeap.offer(new Pair<>(arrival[i] + load[i], server)); + idleServers.remove(server); + } + + final int busiest = Arrays.stream(times).max().getAsInt(); + for (int i = 0; i < k; ++i) + if (times[i] == busiest) + ans.add(i); + return ans; + } + + private int getNextAvailableServer(TreeSet idleServers, int ithRequest, int k) { + if (idleServers.isEmpty()) + return -1; + Integer server = idleServers.ceiling(ithRequest % k); + return server == null ? idleServers.first() : server; + } +} diff --git a/solutions/1607. Sellers With No Sales/1607.sql b/solutions/1607. Sellers With No Sales/1607.sql new file mode 100644 index 00000000000..83d8791f5c1 --- /dev/null +++ b/solutions/1607. Sellers With No Sales/1607.sql @@ -0,0 +1,8 @@ +SELECT Seller.seller_name +FROM Seller +LEFT JOIN Orders + ON ( + Seller.seller_id = Orders.seller_id + AND YEAR(Orders.sale_date) = 2020) +WHERE Orders.order_id IS NULL +ORDER BY 1; diff --git a/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.cpp b/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.cpp new file mode 100644 index 00000000000..91443dce4e0 --- /dev/null +++ b/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int specialArray(vector& nums) { + ranges::sort(nums); + + if (nums[0] >= nums.size()) + return nums.size(); + + for (int i = 1; i < nums.size(); ++i) { + const int count = nums.size() - i; + if (nums[i - 1] < count && nums[i] >= count) + return count; + } + + return -1; + } +}; diff --git a/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.java b/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.java new file mode 100644 index 00000000000..8b2864e925c --- /dev/null +++ b/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.java @@ -0,0 +1,16 @@ +class Solution { + public int specialArray(int[] nums) { + Arrays.sort(nums); + + if (nums[0] >= nums.length) + return nums.length; + + for (int i = 1; i < nums.length; ++i) { + final int count = nums.length - i; + if (nums[i - 1] < count && nums[i] >= count) + return count; + } + + return -1; + } +} diff --git a/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.py b/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.py new file mode 100644 index 00000000000..f0672e7a2e9 --- /dev/null +++ b/solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.py @@ -0,0 +1,13 @@ +class Solution: + def specialArray(self, nums: List[int]) -> int: + nums.sort() + + if nums[0] >= len(nums): + return len(nums) + + for i, (a, b) in enumerate(itertools.pairwise(nums)): + count = len(nums) - i - 1 + if a < count and b >= count: + return count + + return -1 diff --git a/solutions/1609. Even Odd Tree/1609.cpp b/solutions/1609. Even Odd Tree/1609.cpp new file mode 100644 index 00000000000..3e77b203d9c --- /dev/null +++ b/solutions/1609. Even Odd Tree/1609.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + bool isEvenOddTree(TreeNode* root) { + queue q{{root}}; + bool isEven = true; + + for (; !q.empty(); isEven = !isEven) { + int prevVal = isEven ? INT_MIN : INT_MAX; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + if (isEven && (node->val % 2 == 0 || node->val <= prevVal)) + return false; // invalid case on even level + if (!isEven && (node->val % 2 == 1 || node->val >= prevVal)) + return false; // invalid case on odd level + prevVal = node->val; + if (node->left != nullptr) + q.push(node->left); + if (node->right != nullptr) + q.push(node->right); + } + } + + return true; + } +}; diff --git a/solutions/1609. Even Odd Tree/1609.java b/solutions/1609. Even Odd Tree/1609.java new file mode 100644 index 00000000000..c309d94e8ce --- /dev/null +++ b/solutions/1609. Even Odd Tree/1609.java @@ -0,0 +1,24 @@ +class Solution { + public boolean isEvenOddTree(TreeNode root) { + Queue q = new LinkedList<>(Arrays.asList(root)); + boolean isEven = true; + + for (; !q.isEmpty(); isEven = !isEven) { + int prevVal = isEven ? Integer.MIN_VALUE : Integer.MAX_VALUE; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + if (isEven && (node.val % 2 == 0 || node.val <= prevVal)) + return false; // invalid case on even level + if (!isEven && (node.val % 2 == 1 || node.val >= prevVal)) + return false; // invalid case on odd level + prevVal = node.val; + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + } + + return true; + } +} diff --git a/solutions/1609. Even Odd Tree/1609.py b/solutions/1609. Even Odd Tree/1609.py new file mode 100644 index 00000000000..1792ac724c6 --- /dev/null +++ b/solutions/1609. Even Odd Tree/1609.py @@ -0,0 +1,21 @@ +class Solution: + def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: + q = collections.deque([root]) + isEven = True + + while q: + prevVal = -math.inf if isEven else math.inf + for _ in range(sz): + node = q.popleft() + if isEven and (node.val % 2 == 0 or node.val <= prevVal): + return False # invalid case on even level + if not isEven and (node.val % 2 == 1 or node.val >= prevVal): + return False # invalid case on odd level + prevVal = node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + isEven = not isEven + + return True diff --git a/solutions/161. One Edit Distance/161.cpp b/solutions/161. One Edit Distance/161.cpp new file mode 100644 index 00000000000..1165a265872 --- /dev/null +++ b/solutions/161. One Edit Distance/161.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool isOneEditDistance(string s, string t) { + const int m = s.length(); + const int n = t.length(); + if (m > n) // Make sure that |s| <= |t|. + return isOneEditDistance(t, s); + + for (int i = 0; i < m; ++i) + if (s[i] != t[i]) { + if (m == n) + return s.substr(i + 1) == t.substr(i + 1); // Replace s[i] with t[i]. + return s.substr(i) == t.substr(i + 1); // Delete t[i]. + } + + return m + 1 == n; // Delete t[-1]. + } +}; diff --git a/solutions/161. One Edit Distance/161.java b/solutions/161. One Edit Distance/161.java new file mode 100644 index 00000000000..bb691c2c7f5 --- /dev/null +++ b/solutions/161. One Edit Distance/161.java @@ -0,0 +1,17 @@ +class Solution { + public boolean isOneEditDistance(String s, String t) { + final int m = s.length(); + final int n = t.length(); + if (m > n) // Make sure that |s| <= |t|. + return isOneEditDistance(t, s); + + for (int i = 0; i < m; ++i) + if (s.charAt(i) != t.charAt(i)) { + if (m == n) + return s.substring(i + 1).equals(t.substring(i + 1)); // Replace s[i] with t[i]. + return s.substring(i).equals(t.substring(i + 1)); // Delete t[i]. + } + + return m + 1 == n; // Delete t[-1]. + } +} diff --git a/solutions/161. One Edit Distance/161.py b/solutions/161. One Edit Distance/161.py new file mode 100644 index 00000000000..122ecff4c87 --- /dev/null +++ b/solutions/161. One Edit Distance/161.py @@ -0,0 +1,14 @@ +class Solution: + def isOneEditDistance(self, s: str, t: str) -> bool: + m = len(s) + n = len(t) + if m > n: # Make sure that |s| <= |t|. + return self.isOneEditDistance(t, s) + + for i in range(m): + if s[i] != t[i]: + if m == n: + return s[i + 1:] == t[i + 1:] # Replace s[i] with t[i]. + return s[i:] == t[i + 1:] # Delete t[i]. + + return m + 1 == n # Delete t[-1]. diff --git a/solutions/1610. Maximum Number of Visible Points/1610.cpp b/solutions/1610. Maximum Number of Visible Points/1610.cpp new file mode 100644 index 00000000000..09ea64bd68e --- /dev/null +++ b/solutions/1610. Maximum Number of Visible Points/1610.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int visiblePoints(vector>& points, int angle, + vector& location) { + const int posX = location[0]; + const int posY = location[1]; + int maxVisible = 0; + int same = 0; + vector pointAngles; + + for (const vector& p : points) { + const int x = p[0]; + const int y = p[1]; + if (x == posX && y == posY) + ++same; + else + pointAngles.push_back(getAngle(y - posY, x - posX)); + } + + ranges::sort(pointAngles); + + const int n = pointAngles.size(); + for (int i = 0; i < n; ++i) + pointAngles.push_back(pointAngles[i] + 360); + + for (int l = 0, r = 0; r < pointAngles.size(); ++r) { + while (pointAngles[r] - pointAngles[l] > angle) + ++l; + maxVisible = max(maxVisible, r - l + 1); + } + + return maxVisible + same; + } + + private: + double getAngle(int dy, int dx) { + return atan2(dy, dx) * 180 / M_PI; + } +}; diff --git a/solutions/1610. Maximum Number of Visible Points/1610.java b/solutions/1610. Maximum Number of Visible Points/1610.java new file mode 100644 index 00000000000..5e3659f59ee --- /dev/null +++ b/solutions/1610. Maximum Number of Visible Points/1610.java @@ -0,0 +1,36 @@ +class Solution { + public int visiblePoints(List> points, int angle, List location) { + final int posX = location.get(0); + final int posY = location.get(1); + int maxVisible = 0; + int same = 0; + List pointAngles = new ArrayList<>(); + + for (List p : points) { + final int x = p.get(0); + final int y = p.get(1); + if (x == posX && y == posY) + ++same; + else + pointAngles.add(getAngle(y - posY, x - posX)); + } + + Collections.sort(pointAngles); + + final int n = pointAngles.size(); + for (int i = 0; i < n; ++i) + pointAngles.add(pointAngles.get(i) + 360); + + for (int l = 0, r = 0; r < pointAngles.size(); ++r) { + while (pointAngles.get(r) - pointAngles.get(l) > angle) + ++l; + maxVisible = Math.max(maxVisible, r - l + 1); + } + + return maxVisible + same; + } + + private double getAngle(int dy, int dx) { + return Math.atan2(dy, dx) * 180 / Math.PI; + } +} diff --git a/solutions/1610. Maximum Number of Visible Points/1610.py b/solutions/1610. Maximum Number of Visible Points/1610.py new file mode 100644 index 00000000000..dadf3ed56c3 --- /dev/null +++ b/solutions/1610. Maximum Number of Visible Points/1610.py @@ -0,0 +1,25 @@ +class Solution: + def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int: + posX, posY = location + maxVisible = 0 + same = 0 + A = [] + + for x, y in points: + if x == posX and y == posY: + same += 1 + else: + A.append(math.atan2(y - posY, x - posX)) + + A.sort() + A = A + [a + 2.0 * math.pi for a in A] + + angleInRadians = math.pi * (angle / 180) + + l = 0 + for r in range(len(A)): + while A[r] - A[l] > angleInRadians: + l += 1 + maxVisible = max(maxVisible, r - l + 1) + + return maxVisible + same diff --git a/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.cpp b/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.cpp new file mode 100644 index 00000000000..a5d58adcefc --- /dev/null +++ b/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minimumOneBitOperations(int n) { + // Observation: e.g. n = 2^2 + // 100 (2^2 needs 2^3 - 1 ops) + // op1 -> 101 + // op2 -> 111 + // op1 -> 110 + // op2 -> 010 (2^1 needs 2^2 - 1 ops) + // op1 -> 011 + // op2 -> 001 (2^0 needs 2^1 - 1 ops) + // op1 -> 000 + // + // So 2^k needs 2^(k + 1) - 1 ops. Note this is reversible, i.e., 0 -> 2^k + // also takes 2^(k + 1) - 1 ops. + + // e.g. n = 1XXX, our first goal is to change 1XXX -> 1100. + // - If the second bit is 1, you only need to consider the cost of turning + // the last 2 bits to 0. + // - If the second bit is 0, you need to add up the cost of flipping the + // second bit from 0 to 1. + // XOR determines the cost minimumOneBitOperations(1XXX^1100) accordingly. + // Then, 1100 -> 0100 needs 1 op. Finally, 0100 -> 0 needs 2^3 - 1 ops. + if (n == 0) + return 0; + // x is the largest 2^k <= n. + // x | x >> 1 -> x >> 1 needs 1 op. + // x >> 1 -> 0 needs x = 2^k - 1 ops. + int x = 1; + while (x * 2 <= n) + x <<= 1; + return minimumOneBitOperations(n ^ (x | x >> 1)) + 1 + x - 1; + } +}; diff --git a/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.java b/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.java new file mode 100644 index 00000000000..c916e6d1b52 --- /dev/null +++ b/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.java @@ -0,0 +1,33 @@ +class Solution { + public int minimumOneBitOperations(int n) { + // Observation: e.g. n = 2^2 + // 100 (2^2 needs 2^3 - 1 ops) + // op1 -> 101 + // op2 -> 111 + // op1 -> 110 + // op2 -> 010 (2^1 needs 2^2 - 1 ops) + // op1 -> 011 + // op2 -> 001 (2^0 needs 2^1 - 1 ops) + // op1 -> 000 + // + // So 2^k needs 2^(k + 1) - 1 ops. Note this is reversible, i.e., 0 -> 2^k + // also takes 2^(k + 1) - 1 ops. + + // e.g. n = 1XXX, our first goal is to change 1XXX -> 1100. + // - If the second bit is 1, you only need to consider the cost of turning + // the last 2 bits to 0. + // - If the second bit is 0, you need to add up the cost of flipping the + // second bit from 0 to 1. + // XOR determines the cost minimumOneBitOperations(1XXX^1100) accordingly. + // Then, 1100 -> 0100 needs 1 op. Finally, 0100 -> 0 needs 2^3 - 1 ops. + if (n == 0) + return 0; + // x is the largest 2^k <= n. + // x | x >> 1 -> x >> 1 needs 1 op. + // x >> 1 -> 0 needs x = 2^k - 1 ops. + int x = 1; + while (x * 2 <= n) + x <<= 1; + return minimumOneBitOperations(n ^ (x | x >> 1)) + 1 + x - 1; + } +} diff --git a/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.py b/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.py new file mode 100644 index 00000000000..c1b9a6eb481 --- /dev/null +++ b/solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.py @@ -0,0 +1,29 @@ +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + # Observation: e.g. n = 2^2 + # 100 (2^2 needs 2^3 - 1 ops) + # op1 -> 101 + # op2 -> 111 + # op1 -> 110 + # op2 -> 010 (2^1 needs 2^2 - 1 ops) + # op1 -> 011 + # op2 -> 001 (2^0 needs 2^1 - 1 ops) + # op1 -> 000 + # + # So 2^k needs 2^(k + 1) - 1 ops. Note this is reversible, i.e., 0 -> 2^k + # also takes 2^(k + 1) - 1 ops. + + # e.g. n = 1XXX, our first goal is to change 1XXX -> 1100. + # - If the second bit is 1, you only need to consider the cost of turning + # the last 2 bits to 0. + # - If the second bit is 0, you need to add up the cost of flipping the + # second bit from 0 to 1. + # XOR determines the cost minimumOneBitOperations(1XXX^1100) accordingly. + # Then, 1100 -> 0100 needs 1 op. Finally, 0100 -> 0 needs 2^3 - 1 ops. + if n == 0: + return 0 + # x is the largest 2^k <= n. + # x | x >> 1 -> x >> 1 needs 1 op. + # x >> 1 -> 0 needs x = 2^k - 1 ops. + x = 1 << n.bit_length() - 1 + return self.minimumOneBitOperations(n ^ (x | x >> 1)) + 1 + x - 1 diff --git a/solutions/1612. Check If Two Expression Trees are Equivalent/1612.cpp b/solutions/1612. Check If Two Expression Trees are Equivalent/1612.cpp new file mode 100644 index 00000000000..862d50b2175 --- /dev/null +++ b/solutions/1612. Check If Two Expression Trees are Equivalent/1612.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool checkEquivalence(Node* root1, Node* root2) { + vector count(26); + dfs(root1, count, 1); + dfs(root2, count, -1); + return ranges::count_if(count, [](int c) { return c != 0; }) == 0; + } + + private: + void dfs(Node* root, vector& count, int add) { + if (root == nullptr) + return; + if ('a' <= root->val && root->val <= 'z') + count[root->val - 'a'] += add; + dfs(root->left, count, add); + dfs(root->right, count, add); + } +}; diff --git a/solutions/1612. Check If Two Expression Trees are Equivalent/1612.java b/solutions/1612. Check If Two Expression Trees are Equivalent/1612.java new file mode 100644 index 00000000000..0c16839b878 --- /dev/null +++ b/solutions/1612. Check If Two Expression Trees are Equivalent/1612.java @@ -0,0 +1,17 @@ +class Solution { + public boolean checkEquivalence(Node root1, Node root2) { + int[] count = new int[26]; + dfs(root1, count, 1); + dfs(root2, count, -1); + return Arrays.stream(count).filter(c -> c != 0).count() == 0; + } + + private void dfs(Node root, int[] count, int add) { + if (root == null) + return; + if ('a' <= root.val && root.val <= 'z') + count[root.val - 'a'] += add; + dfs(root.left, count, add); + dfs(root.right, count, add); + } +} diff --git a/solutions/1612. Check If Two Expression Trees are Equivalent/1612.py b/solutions/1612. Check If Two Expression Trees are Equivalent/1612.py new file mode 100644 index 00000000000..a2138e74834 --- /dev/null +++ b/solutions/1612. Check If Two Expression Trees are Equivalent/1612.py @@ -0,0 +1,15 @@ +class Solution: + def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: + count = collections.Counter() + + def dfs(root: 'Node', add: int) -> None: + if not root: + return + if 'a' <= root.val <= 'z': + count[root.val] += add + dfs(root.left, add) + dfs(root.right, add) + + dfs(root1, 1) + dfs(root2, -1) + return all(value == 0 for value in count.values()) diff --git a/solutions/1613. Find the Missing IDs/1613.sql b/solutions/1613. Find the Missing IDs/1613.sql new file mode 100644 index 00000000000..c892c4b4fb8 --- /dev/null +++ b/solutions/1613. Find the Missing IDs/1613.sql @@ -0,0 +1,17 @@ +WITH + RECURSIVE Ids AS ( + SELECT 1 AS id + UNION ALL + SELECT id + 1 + FROM Ids + WHERE id < ( + SELECT MAX(customer_id) + FROM Customers + ) + ) +SELECT Ids.id AS ids +FROM Ids +LEFT JOIN Customers + ON (Ids.id = Customers.customer_id) +WHERE Customers.customer_id IS NULL +ORDER BY 1; diff --git a/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.cpp b/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.cpp new file mode 100644 index 00000000000..ea9e3717b83 --- /dev/null +++ b/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxDepth(string s) { + int ans = 0; + int opened = 0; + + for (const char c : s) + if (c == '(') + ans = max(ans, ++opened); + else if (c == ')') + --opened; + + return ans; + } +}; diff --git a/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.java b/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.java new file mode 100644 index 00000000000..80a2bea950c --- /dev/null +++ b/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.java @@ -0,0 +1,14 @@ +class Solution { + public int maxDepth(String s) { + int ans = 0; + int opened = 0; + + for (final char c : s.toCharArray()) + if (c == '(') + ans = Math.max(ans, ++opened); + else if (c == ')') + --opened; + + return ans; + } +} diff --git a/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.py b/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.py new file mode 100644 index 00000000000..7f08bfd85fe --- /dev/null +++ b/solutions/1614. Maximum Nesting Depth of the Parentheses/1614.py @@ -0,0 +1,13 @@ +class Solution: + def maxDepth(self, s: str) -> int: + ans = 0 + opened = 0 + + for c in s: + if c == '(': + opened += 1 + ans = max(ans, opened) + elif c == ')': + opened -= 1 + + return ans diff --git a/solutions/1615. Maximal Network Rank/1615.cpp b/solutions/1615. Maximal Network Rank/1615.cpp new file mode 100644 index 00000000000..4206ec1192e --- /dev/null +++ b/solutions/1615. Maximal Network Rank/1615.cpp @@ -0,0 +1,71 @@ +class Solution { + public: + int maximalNetworkRank(int n, vector>& roads) { + vector degrees(n); + + for (const vector& road : roads) { + const int u = road[0]; + const int v = road[1]; + ++degrees[u]; + ++degrees[v]; + } + + // Find the first maximum and the second maximum degrees. + int maxDegree1 = 0; + int maxDegree2 = 0; + for (const int degree : degrees) { + if (degree > maxDegree1) { + maxDegree2 = maxDegree1; + maxDegree1 = degree; + } else if (degree > maxDegree2) { + maxDegree2 = degree; + } + } + + // There can be multiple nodes with `maxDegree1` or `maxDegree2`. + // Find the counts of such nodes. + int countMaxDegree1 = 0; + int countMaxDegree2 = 0; + for (const int degree : degrees) + if (degree == maxDegree1) + ++countMaxDegree1; + else if (degree == maxDegree2) + ++countMaxDegree2; + + if (countMaxDegree1 == 1) { + // 1. If there is only one node with degree = `maxDegree1`, then we'll + // need to use the node with degree = `maxDegree2`. The answer in general + // will be (maxDegree1 + maxDegree2), but if the two nodes that we're + // considering are connected, then we'll have to subtract 1. + const int edgeCount = + getEdgeCount(roads, degrees, maxDegree1, maxDegree2) + + getEdgeCount(roads, degrees, maxDegree2, maxDegree1); + return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount ? 1 : 0); + } else { + // 2. If there are more than one node with degree = `maxDegree1`, then we + // can consider `maxDegree1` twice, and we don't need to use `maxDegree2`. + // The answer in general will be 2 * maxDegree1, but if the two nodes that + // we're considering are connected, then we'll have to subtract 1. + const int edgeCount = + getEdgeCount(roads, degrees, maxDegree1, maxDegree1); + const int maxPossibleEdgeCount = + countMaxDegree1 * (countMaxDegree1 - 1) / 2; + return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount ? 1 : 0); + } + } + + private: + // Returns the number of edges (u, v) where degress[u] == degreeU and + // degrees[v] == degreeV. + int getEdgeCount(const vector>& roads, const vector& degrees, + int degreeU, int degreeV) { + int edgeCount = 0; + for (const vector& road : roads) { + const int u = road[0]; + const int v = road[1]; + if (degrees[u] == degreeU && degrees[v] == degreeV) + ++edgeCount; + } + return edgeCount; + } +}; diff --git a/solutions/1615. Maximal Network Rank/1615.java b/solutions/1615. Maximal Network Rank/1615.java new file mode 100644 index 00000000000..8aa22504ee9 --- /dev/null +++ b/solutions/1615. Maximal Network Rank/1615.java @@ -0,0 +1,64 @@ +class Solution { + public int maximalNetworkRank(int n, int[][] roads) { + int[] degrees = new int[n]; + + for (int[] road : roads) { + final int u = road[0]; + final int v = road[1]; + ++degrees[u]; + ++degrees[v]; + } + + // Find the first maximum and the second maximum degrees. + int maxDegree1 = 0; + int maxDegree2 = 0; + for (final int degree : degrees) + if (degree > maxDegree1) { + maxDegree2 = maxDegree1; + maxDegree1 = degree; + } else if (degree > maxDegree2) { + maxDegree2 = degree; + } + + // There can be multiple nodes with `maxDegree1` or `maxDegree2`. + // Find the counts of such nodes. + int countMaxDegree1 = 0; + int countMaxDegree2 = 0; + for (final int degree : degrees) + if (degree == maxDegree1) + ++countMaxDegree1; + else if (degree == maxDegree2) + ++countMaxDegree2; + + if (countMaxDegree1 == 1) { + // 1. If there is only one node with degree = `maxDegree1`, then we'll + // need to use the node with degree = `maxDegree2`. The answer in general + // will be (maxDegree1 + maxDegree2), but if the two nodes that we're + // considering are connected, then we'll have to subtract 1. + final int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree2) + + getEdgeCount(roads, degrees, maxDegree2, maxDegree1); + return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount ? 1 : 0); + } else { + // 2. If there are more than one node with degree = `maxDegree1`, then we + // can consider `maxDegree1` twice, and we don't need to use `maxDegree2`. + // The answer in general will be 2 * maxDegree1, but if the two nodes that + // we're considering are connected, then we'll have to subtract 1. + final int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree1); + final int maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) / 2; + return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount ? 1 : 0); + } + } + + // Returns the number of edges (u, v) where degress[u] == degreeU and + // degrees[v] == degreeV. + private int getEdgeCount(int[][] roads, int[] degrees, int degreeU, int degreeV) { + int edgeCount = 0; + for (int[] road : roads) { + final int u = road[0]; + final int v = road[1]; + if (degrees[u] == degreeU && degrees[v] == degreeV) + ++edgeCount; + } + return edgeCount; + } +} diff --git a/solutions/1615. Maximal Network Rank/1615.py b/solutions/1615. Maximal Network Rank/1615.py new file mode 100644 index 00000000000..906a2b6d31f --- /dev/null +++ b/solutions/1615. Maximal Network Rank/1615.py @@ -0,0 +1,55 @@ +class Solution: + def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: + degrees = [0] * n + + for u, v in roads: + degrees[u] += 1 + degrees[v] += 1 + + # Find the first maximum and the second maximum degrees. + maxDegree1 = 0 + maxDegree2 = 0 + for degree in degrees: + if degree > maxDegree1: + maxDegree2 = maxDegree1 + maxDegree1 = degree + elif degree > maxDegree2: + maxDegree2 = degree + + # There can be multiple nodes with `maxDegree1` or `maxDegree2`. + # Find the counts of such nodes. + countMaxDegree1 = 0 + countMaxDegree2 = 0 + for degree in degrees: + if degree == maxDegree1: + countMaxDegree1 += 1 + elif degree == maxDegree2: + countMaxDegree2 += 1 + + if countMaxDegree1 == 1: + # 1. If there is only one node with degree = `maxDegree1`, then we'll + # need to use the node with degree = `maxDegree2`. The answer in general + # will be (maxDegree1 + maxDegree2), but if the two nodes that we're + # considering are connected, then we'll have to subtract 1. + edgeCount = self._getEdgeCount(roads, degrees, maxDegree1, maxDegree2) + \ + self._getEdgeCount(roads, degrees, maxDegree2, maxDegree1) + return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount) + else: + # 2. If there are more than one node with degree = `maxDegree1`, then we + # can consider `maxDegree1` twice, and we don't need to use `maxDegree2`. + # The answer in general will be 2 * maxDegree1, but if the two nodes that + # we're considering are connected, then we'll have to subtract 1. + edgeCount = self._getEdgeCount(roads, degrees, maxDegree1, maxDegree1) + maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) // 2 + return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount) + + def _getEdgeCount(self, roads: List[List[int]], degrees: List[int], degreeU: int, degreeV: int) -> int: + """ + Returns the number of edges (u, v) where degress[u] == degreeU and + degrees[v] == degreeV. + """ + edgeCount = 0 + for u, v in roads: + if degrees[u] == degreeU and degrees[v] == degreeV: + edgeCount += 1 + return edgeCount diff --git a/solutions/1616. Split Two Strings to Make Palindrome/1616.cpp b/solutions/1616. Split Two Strings to Make Palindrome/1616.cpp new file mode 100644 index 00000000000..81d28811429 --- /dev/null +++ b/solutions/1616. Split Two Strings to Make Palindrome/1616.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool checkPalindromeFormation(string a, string b) { + return check(a, b) || check(b, a); + } + + private: + bool check(const string& a, const string& b) { + for (int i = 0, j = a.length() - 1; i < j; ++i, --j) + if (a[i] != b[j]) + // a[0:i] + a[i..j] + b[j + 1:] or + // a[0:i] + b[i..j] + b[j + 1:] + return isPalindrome(a, i, j) || isPalindrome(b, i, j); + return true; + } + + bool isPalindrome(const string& s, int i, int j) { + while (i < j) + if (s[i++] != s[j--]) + return false; + return true; + } +}; diff --git a/solutions/1616. Split Two Strings to Make Palindrome/1616.java b/solutions/1616. Split Two Strings to Make Palindrome/1616.java new file mode 100644 index 00000000000..9b2dfd7a567 --- /dev/null +++ b/solutions/1616. Split Two Strings to Make Palindrome/1616.java @@ -0,0 +1,21 @@ +public class Solution { + public boolean checkPalindromeFormation(String a, String b) { + return check(a, b) || check(b, a); + } + + private boolean check(String a, String b) { + for (int i = 0, j = a.length() - 1; i < j; ++i, --j) + if (a.charAt(i) != b.charAt(j)) + // a[0:i] + a[i..j] + b[j + 1:] or + // a[0:i] + b[i..j] + b[j + 1:] + return isPalindrome(a, i, j) || isPalindrome(b, i, j); + return true; + } + + private boolean isPalindrome(String s, int i, int j) { + while (i < j) + if (s.charAt(i++) != s.charAt(j--)) + return false; + return true; + } +} diff --git a/solutions/1616. Split Two Strings to Make Palindrome/1616.py b/solutions/1616. Split Two Strings to Make Palindrome/1616.py new file mode 100644 index 00000000000..3784de233a6 --- /dev/null +++ b/solutions/1616. Split Two Strings to Make Palindrome/1616.py @@ -0,0 +1,22 @@ +class Solution: + def checkPalindromeFormation(self, a: str, b: str) -> bool: + return self._check(a, b) or self._check(b, a) + + def _check(self, a: str, b: str) -> bool: + i, j = 0, len(a) - 1 + while i < j: + if a[i] != b[j]: + # a[0:i] + a[i..j] + b[j + 1:] or + # a[0:i] + b[i..j] + b[j + 1:] + return self._isPalindrome(a, i, j) or self._isPalindrome(b, i, j) + i += 1 + j -= 1 + return True + + def _isPalindrome(self, s: str, i: int, j: int) -> bool: + while i < j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True diff --git a/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.cpp b/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.cpp new file mode 100644 index 00000000000..66be8b20611 --- /dev/null +++ b/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.cpp @@ -0,0 +1,58 @@ +class Solution { + public: + vector countSubgraphsForEachDiameter(int n, vector>& edges) { + const int maxMask = 1 << n; + const vector> dist = floydWarshall(n, edges); + vector ans(n - 1); + + // mask := the subset of the cities + for (int mask = 0; mask < maxMask; ++mask) { + const int maxDist = getMaxDist(mask, dist, n); + if (maxDist > 0) + ++ans[maxDist - 1]; + } + + return ans; + } + + private: + vector> floydWarshall(int n, const vector>& edges) { + vector> dist(n, vector(n, n)); + + for (int i = 0; i < n; ++i) + dist[i][i] = 0; + + for (const vector& edge : edges) { + const int u = edge[0] - 1; + const int v = edge[1] - 1; + dist[u][v] = 1; + dist[v][u] = 1; + } + + for (int k = 0; k < n; ++k) + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); + + return dist; + } + + int getMaxDist(int mask, const vector>& dist, int n) { + int maxDist = 0; + int edgeCount = 0; + int cityCount = 0; + for (int u = 0; u < n; ++u) { + if ((mask >> u & 1) == 0) // u is not in the subset. + continue; + ++cityCount; + for (int v = u + 1; v < n; ++v) { + if ((mask >> v & 1) == 0) // v is not in the subset. + continue; + if (dist[u][v] == 1) // u and v are connected. + ++edgeCount; + maxDist = max(maxDist, dist[u][v]); + } + } + return edgeCount == cityCount - 1 ? maxDist : 0; + } +}; diff --git a/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.java b/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.java new file mode 100644 index 00000000000..1d985f1db57 --- /dev/null +++ b/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.java @@ -0,0 +1,58 @@ +class Solution { + public int[] countSubgraphsForEachDiameter(int n, int[][] edges) { + final int maxMask = 1 << n; + final int[][] dist = floydWarshall(n, edges); + int[] ans = new int[n - 1]; + + // mask := the subset of the cities + for (int mask = 0; mask < maxMask; ++mask) { + int maxDist = getMaxDist(mask, dist, n); + if (maxDist > 0) + ++ans[maxDist - 1]; + } + + return ans; + } + + private int[][] floydWarshall(int n, int[][] edges) { + int[][] dist = new int[n][n]; + for (int i = 0; i < n; ++i) + Arrays.fill(dist[i], n); + + for (int i = 0; i < n; ++i) + dist[i][i] = 0; + + for (int[] edge : edges) { + final int u = edge[0] - 1; + final int v = edge[1] - 1; + dist[u][v] = 1; + dist[v][u] = 1; + } + + for (int k = 0; k < n; ++k) + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + + return dist; + } + + private int getMaxDist(int mask, int[][] dist, int n) { + int maxDist = 0; + int edgeCount = 0; + int cityCount = 0; + for (int u = 0; u < n; ++u) { + if ((mask >> u & 1) == 0) // u is not in the subset. + continue; + ++cityCount; + for (int v = u + 1; v < n; ++v) { + if ((mask >> v & 1) == 0) // v is not in the subset. + continue; + if (dist[u][v] == 1) // u and v are connected. + ++edgeCount; + maxDist = Math.max(maxDist, dist[u][v]); + } + } + return edgeCount == cityCount - 1 ? maxDist : 0; + } +} diff --git a/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.py b/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.py new file mode 100644 index 00000000000..d95c344a9b9 --- /dev/null +++ b/solutions/1617. Count Subtrees With Max Distance Between Cities/1617.py @@ -0,0 +1,47 @@ +class Solution: + def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: + maxMask = 1 << n + dist = self._floydWarshall(n, edges) + ans = [0] * (n - 1) + + # mask := the subset of the cities + for mask in range(maxMask): + maxDist = self._getMaxDist(mask, dist, n) + if maxDist > 0: + ans[maxDist - 1] += 1 + + return ans + + def _floydWarshall(self, n: int, edges: List[List[int]]) -> List[List[int]]: + dist = [[n] * n for _ in range(n)] + + for i in range(n): + dist[i][i] = 0 + + for u, v in edges: + dist[u - 1][v - 1] = 1 + dist[v - 1][u - 1] = 1 + + for k in range(n): + for i in range(n): + for j in range(n): + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + + return dist + + def _getMaxDist(self, mask: int, dist: List[List[int]], n: int) -> int: + maxDist = 0 + edgeCount = 0 + cityCount = 0 + for u in range(n): + if (mask >> u) & 1 == 0: # u is not in the subset. + continue + cityCount += 1 + for v in range(u + 1, n): + if (mask >> v) & 1 == 0: # v is not in the subset. + continue + if dist[u][v] == 1: # u and v are connected. + edgeCount += 1 + maxDist = max(maxDist, dist[u][v]) + + return maxDist if edgeCount == cityCount - 1 else 0 diff --git a/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.cpp b/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.cpp new file mode 100644 index 00000000000..f641241e385 --- /dev/null +++ b/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.cpp @@ -0,0 +1,44 @@ +/** + * // This is the FontInfo's API interface. + * // You should not implement it, or speculate about its implementation + * class FontInfo { + * public: + * // Return the width of char ch when fontSize is used. + * int getWidth(int fontSize, char ch); + * + * // Return Height of any char when fontSize is used. + * int getHeight(int fontSize) + * }; + */ +class Solution { + public: + int maxFont(string text, int w, int h, vector& fonts, + FontInfo fontInfo) { + vector count(26); + + for (const char c : text) + ++count[c - 'a']; + + int l = 0; + int r = fonts.size() - 1; + + while (l < r) { + const int m = (l + r + 1) / 2; + if (fontInfo.getHeight(fonts[m]) <= h && + getWidthSum(count, fonts[m], fontInfo) <= w) + l = m; + else + r = m - 1; + } + + return getWidthSum(count, fonts[l], fontInfo) <= w ? fonts[l] : -1; + } + + private: + int getWidthSum(const vector& count, int font, FontInfo& fontInfo) { + int width = 0; + for (int i = 0; i < 26; ++i) + width += count[i] * fontInfo.getWidth(font, (char)('a' + i)); + return width; + } +}; diff --git a/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.java b/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.java new file mode 100644 index 00000000000..57a7ae34f57 --- /dev/null +++ b/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.java @@ -0,0 +1,38 @@ +/** + * // This is the FontInfo's API interface. + * // You should not implement it, or speculate about its implementation + * interface FontInfo { + * // Return the width of char ch when fontSize is used. + * public int getWidth(int fontSize, char ch) {} + * // Return Height of any char when fontSize is used. + * public int getHeight(int fontSize) + * } + */ +class Solution { + public int maxFont(String text, int w, int h, int[] fonts, FontInfo fontInfo) { + int[] count = new int[26]; + + for (final char c : text.toCharArray()) + ++count[c - 'a']; + + int l = 0; + int r = fonts.length - 1; + + while (l < r) { + final int m = (l + r + 1) / 2; + if (fontInfo.getHeight(fonts[m]) <= h && getWidthSum(count, fonts[m], fontInfo) <= w) + l = m; + else + r = m - 1; + } + + return getWidthSum(count, fonts[l], fontInfo) <= w ? fonts[l] : -1; + } + + private int getWidthSum(int[] count, int font, FontInfo fontInfo) { + int width = 0; + for (int i = 0; i < 26; ++i) + width += count[i] * fontInfo.getWidth(font, (char) ('a' + i)); + return width; + } +} diff --git a/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.py b/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.py new file mode 100644 index 00000000000..a481df5e19d --- /dev/null +++ b/solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.py @@ -0,0 +1,31 @@ +# """ +# This is FontInfo's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class FontInfo(object): +# Return the width of char ch when fontSize is used. +# def getWidth(self, fontSize: int, ch: str) -> int: +# pass +# +# def getHeight(self, fontSize: int) -> int: +# pass +class Solution: + def maxFont(self, text: str, w: int, h: int, fonts: List[int], fontInfo: 'FontInfo') -> int: + count = collections.Counter(text) + l = 0 + r = len(fonts) - 1 + + while l < r: + m = (l + r + 1) // 2 + if fontInfo.getHeight(fonts[m]) <= h and self._getWidthSum(count, fonts[m], fontInfo) <= w: + l = m + else: + r = m - 1 + + return fonts[l] if self._getWidthSum(count, fonts[l], fontInfo) <= w else -1 + + def _getWidthSum(self, count: List[int], font: int, fontInfo: 'FontInfo') -> int: + width = 0 + for c in string.ascii_lowercase: + width += count[c] * fontInfo.getWidth(font, c) + return width diff --git a/solutions/1619. Mean of Array After Removing Some Elements/1619.cpp b/solutions/1619. Mean of Array After Removing Some Elements/1619.cpp new file mode 100644 index 00000000000..7e51cda6eea --- /dev/null +++ b/solutions/1619. Mean of Array After Removing Some Elements/1619.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + double trimMean(vector& arr) { + int offset = arr.size() / 20; + nth_element(arr.begin(), arr.begin() + offset, arr.end()); + nth_element(arr.begin() + offset, arr.end() - offset, arr.end()); + double sum = accumulate(arr.begin() + offset, arr.end() - offset, 0.0); + return sum / (arr.size() - offset * 2); + } +}; diff --git a/solutions/1619. Mean of Array After Removing Some Elements/1619.java b/solutions/1619. Mean of Array After Removing Some Elements/1619.java new file mode 100644 index 00000000000..ac63a81ac22 --- /dev/null +++ b/solutions/1619. Mean of Array After Removing Some Elements/1619.java @@ -0,0 +1,7 @@ +class Solution { + public double trimMean(int[] arr) { + Arrays.sort(arr); + final int offset = arr.length / 20; + return Arrays.stream(Arrays.copyOfRange(arr, offset, arr.length - offset)).average().orElse(0); + } +} diff --git a/solutions/1619. Mean of Array After Removing Some Elements/1619.py b/solutions/1619. Mean of Array After Removing Some Elements/1619.py new file mode 100644 index 00000000000..069df82ceb9 --- /dev/null +++ b/solutions/1619. Mean of Array After Removing Some Elements/1619.py @@ -0,0 +1,5 @@ +class Solution: + def trimMean(self, arr: List[int]) -> float: + arr.sort() + offset = len(arr) // 20 + return mean(arr[offset:-offset]) diff --git a/solutions/162. Find Peak Element/162.cpp b/solutions/162. Find Peak Element/162.cpp new file mode 100644 index 00000000000..526ebbadaa5 --- /dev/null +++ b/solutions/162. Find Peak Element/162.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int findPeakElement(vector& nums) { + int l = 0; + int r = nums.size() - 1; + + while (l < r) { + const int m = (l + r) / 2; + if (nums[m] >= nums[m + 1]) + r = m; + else + l = m + 1; + } + + return l; + } +}; diff --git a/solutions/162. Find Peak Element/162.java b/solutions/162. Find Peak Element/162.java new file mode 100644 index 00000000000..b889780a0ec --- /dev/null +++ b/solutions/162. Find Peak Element/162.java @@ -0,0 +1,16 @@ +class Solution { + public int findPeakElement(int[] nums) { + int l = 0; + int r = nums.length - 1; + + while (l < r) { + final int m = (l + r) / 2; + if (nums[m] >= nums[m + 1]) + r = m; + else + l = m + 1; + } + + return l; + } +} diff --git a/solutions/162. Find Peak Element/162.py b/solutions/162. Find Peak Element/162.py new file mode 100644 index 00000000000..e84170084b3 --- /dev/null +++ b/solutions/162. Find Peak Element/162.py @@ -0,0 +1,13 @@ +class Solution: + def findPeakElement(self, nums: List[int]) -> int: + l = 0 + r = len(nums) - 1 + + while l < r: + m = (l + r) // 2 + if nums[m] >= nums[m + 1]: + r = m + else: + l = m + 1 + + return l diff --git a/solutions/1620. Coordinate With Maximum Network Quality/1620.cpp b/solutions/1620. Coordinate With Maximum Network Quality/1620.cpp new file mode 100644 index 00000000000..b4616ab569e --- /dev/null +++ b/solutions/1620. Coordinate With Maximum Network Quality/1620.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector bestCoordinate(vector>& towers, int radius) { + constexpr int kMax = 50; + const int n = towers.size(); + vector ans(2); + int maxQuality = 0; + + for (int i = 0; i <= kMax; ++i) + for (int j = 0; j <= kMax; ++j) { + int qualitySum = 0; + for (const vector& tower : towers) { + const double d = dist(tower, i, j); + if (d <= radius) { + const int q = tower[2]; + qualitySum += static_cast(q / (1 + d)); + } + } + if (qualitySum > maxQuality) { + maxQuality = qualitySum; + ans = {i, j}; + } + } + + return ans; + } + + private: + // Returns the distance between the tower and the coordinate. + double dist(const vector& tower, int i, int j) { + return sqrt(pow(tower[0] - i, 2) + pow(tower[1] - j, 2)); + } +}; diff --git a/solutions/1620. Coordinate With Maximum Network Quality/1620.java b/solutions/1620. Coordinate With Maximum Network Quality/1620.java new file mode 100644 index 00000000000..59be5dde3fb --- /dev/null +++ b/solutions/1620. Coordinate With Maximum Network Quality/1620.java @@ -0,0 +1,33 @@ +class Solution { + public int[] bestCoordinate(int[][] towers, int radius) { + final int kMax = 50; + final int n = towers.length; + int[] ans = new int[2]; + int maxQuality = 0; + + for (int i = 0; i <= kMax; ++i) { + for (int j = 0; j <= kMax; ++j) { + int qualitySum = 0; + for (int[] tower : towers) { + double d = dist(tower, i, j); + if (d <= radius) { + final int q = tower[2]; + qualitySum += (int) (q / (1 + d)); + } + } + if (qualitySum > maxQuality) { + maxQuality = qualitySum; + ans[0] = i; + ans[1] = j; + } + } + } + + return ans; + } + + // Returns the distance between the tower and the coordinate. + private double dist(int[] tower, int i, int j) { + return Math.sqrt(Math.pow(tower[0] - i, 2) + Math.pow(tower[1] - j, 2)); + } +} diff --git a/solutions/1620. Coordinate With Maximum Network Quality/1620.py b/solutions/1620. Coordinate With Maximum Network Quality/1620.py new file mode 100644 index 00000000000..5a185e8da84 --- /dev/null +++ b/solutions/1620. Coordinate With Maximum Network Quality/1620.py @@ -0,0 +1,24 @@ +class Solution: + def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]: + kMax = 50 + n = len(towers) + ans = [0] * 2 + maxQuality = 0 + + def dist(tower: List[int], i: int, j: int) -> float: + """Returns the distance between the tower and the coordinate.""" + return math.sqrt((tower[0] - i)**2 + (tower[1] - j)**2) + + for i in range(kMax + 1): + for j in range(kMax + 1): + qualitySum = 0 + for tower in towers: + q = tower[2] + d = dist(tower, i, j) + if d <= radius: + qualitySum += int(q / (1 + d)) + if qualitySum > maxQuality: + maxQuality = qualitySum + ans = [i, j] + + return ans diff --git a/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.cpp b/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.cpp new file mode 100644 index 00000000000..68270c89999 --- /dev/null +++ b/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int numberOfSets(int n, int k) { + vector>> mem( + n, vector>(k + 1, vector(2, -1))); + return numberOfSets(0, k, /*drawing=*/false, n, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + int numberOfSets(int i, int k, bool drawing, int n, + vector>>& mem) { + if (k == 0) // Find a way to draw k segments. + return 1; + if (i == n) // Reach the end. + return 0; + if (mem[i][k][drawing] != -1) + return mem[i][k][drawing]; + if (drawing) + // 1. Keep drawing at i and move to i + 1. + // 2. Stop at i so decrease k. We can start from i for the next segment. + return mem[i][k][drawing] = (numberOfSets(i + 1, k, true, n, mem) + + numberOfSets(i, k - 1, false, n, mem)) % + kMod; + // 1. Skip i and move to i + 1. + // 2. Start at i and move to i + 1. + return mem[i][k][drawing] = (numberOfSets(i + 1, k, false, n, mem) + + numberOfSets(i + 1, k, true, n, mem)) % + kMod; + } +}; diff --git a/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.java b/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.java new file mode 100644 index 00000000000..3a66eeb31a5 --- /dev/null +++ b/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.java @@ -0,0 +1,28 @@ +class Solution { + public int numberOfSets(int n, int k) { + Integer[][][] mem = new Integer[n][k + 1][2]; + return numberOfSets(0, k, /*drawing=*/false, n, mem); + } + + private static final int kMod = 1_000_000_007; + + private int numberOfSets(int i, int k, boolean drawing, int n, Integer[][][] mem) { + if (k == 0) // Find a way to draw k segments. + return 1; + if (i == n) // Reach the end. + return 0; + if (mem[i][k][drawing ? 1 : 0] != null) + return mem[i][k][drawing ? 1 : 0]; + if (drawing) + // 1. Keep drawing at i and move to i + 1. + // 2. Stop at i so decrease k. We can start from i for the next segment. + return mem[i][k][drawing ? 1 : 0] = (numberOfSets(i + 1, k, true, n, mem) + // + numberOfSets(i, k - 1, false, n, mem)) % + kMod; + // 1. Skip i and move to i + 1. + // 2. Start at i and move to i + 1. + return mem[i][k][drawing ? 1 : 0] = (numberOfSets(i + 1, k, false, n, mem) + // + numberOfSets(i + 1, k, true, n, mem)) % + kMod; + } +} diff --git a/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.py b/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.py new file mode 100644 index 00000000000..352517a4f30 --- /dev/null +++ b/solutions/1621. Number of Sets of K Non-Overlapping Line Segments/1621.py @@ -0,0 +1,19 @@ +class Solution: + def numberOfSets(self, n: int, k: int) -> int: + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def dp(i: int, k: int, drawing: bool) -> int: + if k == 0: # Find a way to draw k segments. + return 1 + if i == n: # Reach the end. + return 0 + if drawing: + # 1. Keep drawing at i and move to i + 1. + # 2. Stop at i so decrease k. We can start from i for the next segment. + return (dp(i + 1, k, True) + dp(i, k - 1, False)) % kMod + # 1. Skip i and move to i + 1. + # 2. Start at i and move to i + 1. + return (dp(i + 1, k, False) + dp(i + 1, k, True)) % kMod + + return dp(0, k, False) diff --git a/solutions/1622. Fancy Sequence/1622.cpp b/solutions/1622. Fancy Sequence/1622.cpp new file mode 100644 index 00000000000..f24a60daf72 --- /dev/null +++ b/solutions/1622. Fancy Sequence/1622.cpp @@ -0,0 +1,44 @@ +class Fancy { + public: + // To undo a * val + b and get the original value, we append (val - b) / a. + // By Fermat's little theorem: + // a^(p - 1) ≡ 1 (mod p) + // a^(p - 2) ≡ a^(-1) (mod p) + // So, (val - b) / a ≡ (val - b) * a^(p - 2) (mod p) + void append(int val) { + const long x = (val - b + kMod) % kMod; + vals.push_back(x * modPow(a, kMod - 2) % kMod); + } + + // If the value is a * val + b, then the value after adding by `inc` will be + // a * val + b + inc. So, we adjust b to b + inc. + void addAll(int inc) { + b = (b + inc) % kMod; + } + + // If the value is a * val + b, then the value after multiplying by `m` will + // be a * m * val + b * m. So, we adjust a to a * m and b to b * m. + void multAll(int m) { + a = (a * m) % kMod; + b = (b * m) % kMod; + } + + int getIndex(int idx) { + return idx >= vals.size() ? -1 : (a * vals[idx] + b) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + // For each `val` in `vals`, it actually represents a * val + b. + vector vals; + unsigned long a = 1; + unsigned long b = 0; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/1622. Fancy Sequence/1622.java b/solutions/1622. Fancy Sequence/1622.java new file mode 100644 index 00000000000..751846ebf41 --- /dev/null +++ b/solutions/1622. Fancy Sequence/1622.java @@ -0,0 +1,42 @@ +class Fancy { + // To undo a * val + b and get the original value, we append (val - b) / a. + // By Fermat's little theorem: + // a^(p - 1) ≡ 1 (mod p) + // a^(p - 2) ≡ a^(-1) (mod p) + // So, (val - b) / a ≡ (val - b) * a^(p - 2) (mod p) + public void append(int val) { + final long x = (val - b + kMod) % kMod; + vals.add(x * modPow(a, kMod - 2) % kMod); + } + + // If the value is a * val + b, then the value after adding by `inc` will be + // a * val + b + inc. So, we adjust b to b + inc. + public void addAll(int inc) { + b = (b + inc) % kMod; + } + + // If the value is a * val + b, then the value after multiplying by `m` will + // be a * m * val + b * m. So, we adjust a to a * m and b to b * m. + public void multAll(int m) { + a = (a * m) % kMod; + b = (b * m) % kMod; + } + + public int getIndex(int idx) { + return idx >= vals.size() ? -1 : (int) ((a * vals.get(idx) + b) % kMod); + } + + private static final int kMod = 1_000_000_007; + // For each `val` in `vals`, it actually represents a * val + b. + private List vals = new ArrayList<>(); + private long a = 1; + private long b = 0; + + private int modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return (int) (x * modPow(x % kMod, (n - 1)) % kMod); + return modPow(x * x % kMod, (n / 2)) % kMod; + } +} diff --git a/solutions/1622. Fancy Sequence/1622.py b/solutions/1622. Fancy Sequence/1622.py new file mode 100644 index 00000000000..251848d5d72 --- /dev/null +++ b/solutions/1622. Fancy Sequence/1622.py @@ -0,0 +1,31 @@ +class Fancy: + def __init__(self): + self.kMod = 1_000_000_007 + # For each `val` in `vals`, it actually represents a * val + b. + self.vals = [] + self.a = 1 + self.b = 0 + + # To undo a * val + b and get the original value, we append (val - b) // a. + # By Fermat's little theorem: + # a^(p - 1) ≡ 1 (mod p) + # a^(p - 2) ≡ a^(-1) (mod p) + # So, (val - b) / a ≡ (val - b) * a^(p - 2) (mod p) + def append(self, val: int) -> None: + x = (val - self.b + self.kMod) % self.kMod + self.vals.append(x * pow(self.a, self.kMod - 2, self.kMod)) + + # If the value is a * val + b, then the value after adding by `inc` will be + # a * val + b + inc. So, we adjust b to b + inc. + def addAll(self, inc: int) -> None: + self.b = (self.b + inc) % self.kMod + + # If the value is a * val + b, then the value after multiplying by `m` will + # be a * m * val + b * m. So, we adjust a to a * m and b to b * m. + def multAll(self, m: int) -> None: + self.a = (self.a * m) % self.kMod + self.b = (self.b * m) % self.kMod + + def getIndex(self, idx: int) -> int: + return -1 if idx >= len(self.vals) \ + else (self.a * self.vals[idx] + self.b) % self.kMod diff --git a/solutions/1623. All Valid Triplets That Can Represent a Country/1623.sql b/solutions/1623. All Valid Triplets That Can Represent a Country/1623.sql new file mode 100644 index 00000000000..51c21c02e6c --- /dev/null +++ b/solutions/1623. All Valid Triplets That Can Represent a Country/1623.sql @@ -0,0 +1,12 @@ +SELECT + SchoolA.student_name AS member_A, + SchoolB.student_name AS member_B, + SchoolC.student_name AS member_C +FROM SchoolA, SchoolB, SchoolC +WHERE + SchoolA.student_id != SchoolB.student_id + AND SchoolA.student_id != SchoolC.student_id + AND SchoolB.student_id != SchoolC.student_id + AND SchoolA.student_name != SchoolB.student_name + AND SchoolA.student_name != SchoolC.student_name + AND SchoolB.student_name != SchoolC.student_name; diff --git a/solutions/1624. Largest Substring Between Two Equal Characters/1624.cpp b/solutions/1624. Largest Substring Between Two Equal Characters/1624.cpp new file mode 100644 index 00000000000..854fbdf5acd --- /dev/null +++ b/solutions/1624. Largest Substring Between Two Equal Characters/1624.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxLengthBetweenEqualCharacters(string s) { + int ans = -1; + vector lastSeen(26, -1); + + for (int i = 0; i < s.length(); ++i) { + const int c = s[i] - 'a'; + if (lastSeen[c] == -1) + lastSeen[c] = i; + else + ans = max(ans, i - lastSeen[c] - 1); + } + + return ans; + } +}; diff --git a/solutions/1624. Largest Substring Between Two Equal Characters/1624.java b/solutions/1624. Largest Substring Between Two Equal Characters/1624.java new file mode 100644 index 00000000000..21e4476d983 --- /dev/null +++ b/solutions/1624. Largest Substring Between Two Equal Characters/1624.java @@ -0,0 +1,17 @@ +class Solution { + public int maxLengthBetweenEqualCharacters(String s) { + int ans = -1; + int[] lastSeen = new int[26]; + Arrays.fill(lastSeen, -1); + + for (int i = 0; i < s.length(); ++i) { + final int c = s.charAt(i) - 'a'; + if (lastSeen[c] == -1) + lastSeen[c] = i; + else + ans = Math.max(ans, i - lastSeen[c] - 1); + } + + return ans; + } +} diff --git a/solutions/1624. Largest Substring Between Two Equal Characters/1624.py b/solutions/1624. Largest Substring Between Two Equal Characters/1624.py new file mode 100644 index 00000000000..8cbee8221e4 --- /dev/null +++ b/solutions/1624. Largest Substring Between Two Equal Characters/1624.py @@ -0,0 +1,12 @@ +class Solution: + def maxLengthBetweenEqualCharacters(self, s: str) -> int: + ans = -1 + lastSeen = {} + + for i, c in enumerate(s): + if c not in lastSeen: + lastSeen[c] = i + else: + ans = max(ans, i - lastSeen[c] - 1) + + return ans diff --git a/solutions/1625. Lexicographically Smallest String After Applying Operations/1625.cpp b/solutions/1625. Lexicographically Smallest String After Applying Operations/1625.cpp new file mode 100644 index 00000000000..aa2d1478800 --- /dev/null +++ b/solutions/1625. Lexicographically Smallest String After Applying Operations/1625.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + string findLexSmallestString(string s, int a, int b) { + string ans = s; + + dfs(s, a, b, {}, ans); + + return ans; + } + + private: + void dfs(string s, int a, int b, unordered_set&& seen, string& ans) { + if (seen.contains(s)) + return; + + seen.insert(s); + ans = min(ans, s); + + dfs(add(s, a), a, b, move(seen), ans); + dfs(rotate(s, b), a, b, move(seen), ans); + } + + string add(string& s, int a) { + for (int i = 1; i < s.length(); i += 2) + s[i] = '0' + (s[i] - '0' + a) % 10; + return s; + } + + string rotate(const string& s, int b) { + const int n = s.length(); + return s.substr(n - b, n) + s.substr(0, n - b); + } +}; diff --git a/solutions/1625. Lexicographically Smallest String After Applying Operations/1625.java b/solutions/1625. Lexicographically Smallest String After Applying Operations/1625.java new file mode 100644 index 00000000000..66cbfe32cff --- /dev/null +++ b/solutions/1625. Lexicographically Smallest String After Applying Operations/1625.java @@ -0,0 +1,35 @@ +class Solution { + public String findLexSmallestString(String s, int a, int b) { + ans = s; + + dfs(s, a, b, new HashSet<>()); + + return ans; + } + + private String ans; + + private void dfs(String s, int a, int b, Set seen) { + if (seen.contains(s)) + return; + + seen.add(s); + if (ans.compareTo(s) > 0) + ans = s; + + dfs(add(s, a), a, b, seen); + dfs(rotate(s, b), a, b, seen); + } + + private String add(final String s, int a) { + StringBuilder sb = new StringBuilder(s); + for (int i = 1; i < sb.length(); i += 2) + sb.setCharAt(i, (char) ('0' + (s.charAt(i) - '0' + a) % 10)); + return sb.toString(); + } + + private String rotate(final String s, int b) { + final int n = s.length(); + return s.substring(n - b, n) + s.substring(0, n - b); + } +} diff --git a/solutions/1626. Best Team With No Conflicts/1626.cpp b/solutions/1626. Best Team With No Conflicts/1626.cpp new file mode 100644 index 00000000000..0e0f909cc12 --- /dev/null +++ b/solutions/1626. Best Team With No Conflicts/1626.cpp @@ -0,0 +1,35 @@ +struct Player { + int age; + int score; + Player(int age, int score) : age(age), score(score) {} +}; + +class Solution { + public: + int bestTeamScore(vector& scores, vector& ages) { + const int n = scores.size(); + vector players; + // dp[i] := the maximum score of choosing the players[0..i] with the + // players[i] being selected + vector dp(n); + + for (int i = 0; i < n; ++i) + players.emplace_back(ages[i], scores[i]); + + ranges::sort(players, [](const Player& a, const Player& b) { + return a.age == b.age ? a.score > b.score : a.age > b.age; + }); + + for (int i = 0; i < n; ++i) { + // For each player, choose it first. + dp[i] = players[i].score; + // players[j].age >= players[i].age since we sort in descending order. + // So, we only have to check that players[j].score >= players[i].score. + for (int j = 0; j < i; ++j) + if (players[j].score >= players[i].score) + dp[i] = max(dp[i], dp[j] + players[i].score); + } + + return ranges::max(dp); + } +}; diff --git a/solutions/1626. Best Team With No Conflicts/1626.java b/solutions/1626. Best Team With No Conflicts/1626.java new file mode 100644 index 00000000000..e4a8b03f51c --- /dev/null +++ b/solutions/1626. Best Team With No Conflicts/1626.java @@ -0,0 +1,34 @@ +class Player { + public int age; + public int score; + public Player(int age, int score) { + this.age = age; + this.score = score; + } +}; + +class Solution { + public int bestTeamScore(int[] scores, int[] ages) { + final int n = scores.length; + Player[] players = new Player[n]; + // dp[i] := the maximum score of choosing the players[0..i] with the players[i] being selected + int[] dp = new int[n]; + + for (int i = 0; i < n; ++i) + players[i] = new Player(ages[i], scores[i]); + + Arrays.sort(players, (a, b) -> a.age == b.age ? b.score - a.score : b.age - a.age); + + for (int i = 0; i < n; ++i) { + // For each player, choose it first. + dp[i] = players[i].score; + // players[j].age >= players[i].age since we sort in descending order. + // So, we only have to check that players[j].score >= players[i].score. + for (int j = 0; j < i; ++j) + if (players[j].score >= players[i].score) + dp[i] = Math.max(dp[i], dp[j] + players[i].score); + } + + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/1627. Graph Connectivity With Threshold/1627.cpp b/solutions/1627. Graph Connectivity With Threshold/1627.cpp new file mode 100644 index 00000000000..d8faf1471cc --- /dev/null +++ b/solutions/1627. Graph Connectivity With Threshold/1627.cpp @@ -0,0 +1,51 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + bool unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + return true; + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + vector areConnected(int n, int threshold, + vector>& queries) { + vector ans; + UnionFind uf(n + 1); + + for (int z = threshold + 1; z <= n; ++z) + for (int x = z * 2; x <= n; x += z) + uf.unionByRank(z, x); + + for (const vector& query : queries) { + const int a = query[0]; + const int b = query[1]; + ans.push_back(uf.find(a) == uf.find(b)); + } + + return ans; + } +}; diff --git a/solutions/1627. Graph Connectivity With Threshold/1627.java b/solutions/1627. Graph Connectivity With Threshold/1627.java new file mode 100644 index 00000000000..593b84e28ed --- /dev/null +++ b/solutions/1627. Graph Connectivity With Threshold/1627.java @@ -0,0 +1,50 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public boolean unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + return true; + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public List areConnected(int n, int threshold, int[][] queries) { + List ans = new ArrayList<>(); + UnionFind uf = new UnionFind(n + 1); + + for (int z = threshold + 1; z <= n; ++z) + for (int x = z * 2; x <= n; x += z) + uf.unionByRank(z, x); + + for (int[] query : queries) { + final int a = query[0]; + final int b = query[1]; + ans.add(uf.find(a) == uf.find(b)); + } + + return ans; + } +} diff --git a/solutions/1627. Graph Connectivity With Threshold/1627.py b/solutions/1627. Graph Connectivity With Threshold/1627.py new file mode 100644 index 00000000000..4fa36277940 --- /dev/null +++ b/solutions/1627. Graph Connectivity With Threshold/1627.py @@ -0,0 +1,34 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> bool: + i = self.find(u) + j = self.find(v) + if i == j: + return False + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + return True + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: + uf = UnionFind(n + 1) + + for z in range(threshold + 1, n + 1): + for x in range(z * 2, n + 1, z): + uf.unionByRank(z, x) + + return [uf.find(a) == uf.find(b) for a, b in queries] diff --git a/solutions/1628. Design an Expression Tree With Evaluate Function/1628.cpp b/solutions/1628. Design an Expression Tree With Evaluate Function/1628.cpp new file mode 100644 index 00000000000..7b3ec6bd980 --- /dev/null +++ b/solutions/1628. Design an Expression Tree With Evaluate Function/1628.cpp @@ -0,0 +1,61 @@ +/** + * This is the interface for the expression tree Node. + * You should not remove it, and you can define some classes to implement it. + */ + +class Node { + public: + virtual ~Node() {}; + virtual int evaluate() const = 0; + + protected: + // define your fields here +}; + +class ExpNode : public Node { + public: + ExpNode(const string& val, ExpNode* left, ExpNode* right) + : val(val), left(left), right(right) {} + + int evaluate() const override { + return left == nullptr && right == nullptr + ? stoi(val) + : op.at(val)(left->evaluate(), right->evaluate()); + } + + private: + static const inline unordered_map> op{ + {"+", std::plus()}, + {"-", std::minus()}, + {"*", std::multiplies()}, + {"/", std::divides()}}; + const string val; + const ExpNode* const left; + const ExpNode* const right; +}; + +/** + * This is the TreeBuilder class. + * You can treat it as the driver code that takes the postinfix input + * and returns the expression tree represnting it as a Node. + */ + +class TreeBuilder { + public: + Node* buildTree(vector& postfix) { + stack stack; + + for (const string& val : postfix) + if (val == "+" || val == "-" || val == "*" || val == "/") { + ExpNode* right = stack.top(); + stack.pop(); + ExpNode* left = stack.top(); + stack.pop(); + stack.push(new ExpNode(val, left, right)); + } else { + stack.push(new ExpNode(val, nullptr, nullptr)); + } + + return stack.top(); + } +}; diff --git a/solutions/1628. Design an Expression Tree With Evaluate Function/1628.java b/solutions/1628. Design an Expression Tree With Evaluate Function/1628.java new file mode 100644 index 00000000000..d4fd2286c41 --- /dev/null +++ b/solutions/1628. Design an Expression Tree With Evaluate Function/1628.java @@ -0,0 +1,52 @@ +/** + * This is the interface for the expression tree Node. + * You should not remove it, and you can define some classes to implement it. + */ + +abstract class Node { + public abstract int evaluate(); + // define your fields here +}; + +class ExpNode extends Node { + public ExpNode(String val, ExpNode left, ExpNode right) { + this.val = val; + this.left = left; + this.right = right; + } + + public int evaluate() { + if (left == null && right == null) + return Integer.parseInt(val); + return op.get(val).apply(left.evaluate(), right.evaluate()); + } + + private static final Map> op = + Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b, "*", (a, b) -> a *b, "/", (a, b) -> a / b); + private final String val; + private final ExpNode left; + private final ExpNode right; +} + +/** + * This is the TreeBuilder class. + * You can treat it as the driver code that takes the postinfix input + * and returns the expression tree represnting it as a Node. + */ + +class TreeBuilder { + Node buildTree(String[] postfix) { + Deque stack = new ArrayDeque<>(); + + for (final String val : postfix) + if (val.equals("+") || val.equals("-") || val.equals("*") || val.equals("/")) { + ExpNode right = stack.pop(); + ExpNode left = stack.pop(); + stack.push(new ExpNode(val, left, right)); + } else { + stack.push(new ExpNode(val, null, null)); + } + + return stack.pop(); + } +} diff --git a/solutions/1628. Design an Expression Tree With Evaluate Function/1628.py b/solutions/1628. Design an Expression Tree With Evaluate Function/1628.py new file mode 100644 index 00000000000..f2e73a0122f --- /dev/null +++ b/solutions/1628. Design an Expression Tree With Evaluate Function/1628.py @@ -0,0 +1,54 @@ +from abc import ABC, abstractmethod + +""" +This is the interface for the expression tree Node. +You should not remove it, and you can define some classes to implement it. +""" + + +class Node(ABC): + @abstractmethod + # define your fields here + def evaluate(self) -> int: + pass + + +class ExpNode(Node): + op = { + '+': lambda a, b: a + b, + '-': lambda a, b: a - b, + '*': lambda a, b: a * b, + '/': lambda a, b: int(a / b), + } + + def __init__(self, val: str, left: Optional['ExpNode'], right: Optional['ExpNode']): + self.val = val + self.left = left + self.right = right + + def evaluate(self) -> int: + if not self.left and not self.right: + return int(self.val) + return ExpNode.op[self.val](self.left.evaluate(), self.right.evaluate()) + + +""" +This is the TreeBuilder class. +You can treat it as the driver code that takes the postinfix input +and returns the expression tree represnting it as a Node. +""" + + +class TreeBuilder(object): + def buildTree(self, postfix: List[str]) -> 'Node': + stack: List[Optional[ExpNode]] = [] + + for val in postfix: + if val in '+-*/': + right = stack.pop() + left = stack.pop() + stack.append(ExpNode(val, left, right)) + else: + stack.append(ExpNode(val, None, None)) + + return stack.pop() diff --git a/solutions/1629. Slowest Key/1629.cpp b/solutions/1629. Slowest Key/1629.cpp new file mode 100644 index 00000000000..a66f3b54e6f --- /dev/null +++ b/solutions/1629. Slowest Key/1629.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + char slowestKey(vector& releaseTimes, string keysPressed) { + char ans = keysPressed[0]; + int maxDuration = releaseTimes[0]; + + for (int i = 1; i < keysPressed.length(); ++i) { + const int duration = releaseTimes[i] - releaseTimes[i - 1]; + if (duration > maxDuration || + (duration == maxDuration && keysPressed[i] > ans)) { + ans = keysPressed[i]; + maxDuration = duration; + } + } + + return ans; + } +}; diff --git a/solutions/1629. Slowest Key/1629.java b/solutions/1629. Slowest Key/1629.java new file mode 100644 index 00000000000..d0f24290d85 --- /dev/null +++ b/solutions/1629. Slowest Key/1629.java @@ -0,0 +1,16 @@ +class Solution { + public char slowestKey(int[] releaseTimes, String keysPressed) { + char ans = keysPressed.charAt(0); + int maxDuration = releaseTimes[0]; + + for (int i = 1; i < keysPressed.length(); ++i) { + final int duration = releaseTimes[i] - releaseTimes[i - 1]; + if (duration > maxDuration || (duration == maxDuration && keysPressed.charAt(i) > ans)) { + ans = keysPressed.charAt(i); + maxDuration = duration; + } + } + + return ans; + } +} diff --git a/solutions/1629. Slowest Key/1629.py b/solutions/1629. Slowest Key/1629.py new file mode 100644 index 00000000000..390c3dedd85 --- /dev/null +++ b/solutions/1629. Slowest Key/1629.py @@ -0,0 +1,12 @@ +class Solution: + def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: + ans = keysPressed[0] + maxDuration = releaseTimes[0] + + for i in range(1, len(keysPressed)): + duration = releaseTimes[i] - releaseTimes[i-1] + if duration > maxDuration or (duration == maxDuration and keysPressed[i] > ans): + ans = keysPressed[i] + maxDuration = duration + + return ans diff --git a/solutions/163. Missing Ranges/163.cpp b/solutions/163. Missing Ranges/163.cpp new file mode 100644 index 00000000000..6c6fb1e527b --- /dev/null +++ b/solutions/163. Missing Ranges/163.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector findMissingRanges(vector& nums, int lower, int upper) { + if (nums.empty()) + return {getRange(lower, upper)}; + + vector ans; + + if (nums.front() > lower) + ans.push_back(getRange(lower, nums.front() - 1)); + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] > nums[i - 1] + 1) + ans.push_back(getRange(nums[i - 1] + 1, nums[i] - 1)); + + if (nums.back() < upper) + ans.push_back(getRange(nums.back() + 1, upper)); + + return ans; + } + + private: + string getRange(int lo, int hi) { + if (lo == hi) + return to_string(lo); + return to_string(lo) + "->" + to_string(hi); + } +}; diff --git a/solutions/163. Missing Ranges/163.java b/solutions/163. Missing Ranges/163.java new file mode 100644 index 00000000000..35013d4aff9 --- /dev/null +++ b/solutions/163. Missing Ranges/163.java @@ -0,0 +1,26 @@ +class Solution { + public List findMissingRanges(int[] nums, int lower, int upper) { + if (nums.length == 0) + return new ArrayList<>(Arrays.asList(getRange(lower, upper))); + + List ans = new ArrayList<>(); + + if (nums[0] > lower) + ans.add(getRange(lower, nums[0] - 1)); + + for (int i = 1; i < nums.length; ++i) + if (nums[i] > nums[i - 1] + 1) + ans.add(getRange(nums[i - 1] + 1, nums[i] - 1)); + + if (nums[nums.length - 1] < upper) + ans.add(getRange(nums[nums.length - 1] + 1, upper)); + + return ans; + } + + private String getRange(int lo, int hi) { + if (lo == hi) + return String.valueOf(lo); + return lo + "->" + hi; + } +} diff --git a/solutions/163. Missing Ranges/163.py b/solutions/163. Missing Ranges/163.py new file mode 100644 index 00000000000..ca1f33ddd0a --- /dev/null +++ b/solutions/163. Missing Ranges/163.py @@ -0,0 +1,23 @@ +class Solution: + def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: + def getRange(lo: int, hi: int) -> str: + if lo == hi: + return str(lo) + return str(lo) + '->' + str(hi) + + if not nums: + return [getRange(lower, upper)] + + ans = [] + + if nums[0] > lower: + ans.append(getRange(lower, nums[0] - 1)) + + for prev, curr in zip(nums, nums[1:]): + if curr > prev + 1: + ans.append(getRange(prev + 1, curr - 1)) + + if nums[-1] < upper: + ans.append(getRange(nums[-1] + 1, upper)) + + return ans diff --git a/solutions/1630. Arithmetic Subarrays/1630.cpp b/solutions/1630. Arithmetic Subarrays/1630.cpp new file mode 100644 index 00000000000..66347212b05 --- /dev/null +++ b/solutions/1630. Arithmetic Subarrays/1630.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + vector checkArithmeticSubarrays(vector& nums, vector& l, + vector& r) { + vector ans; + + for (int i = 0; i < l.size(); ++i) + ans.push_back(isArithmetic(nums, l[i], r[i])); + + return ans; + } + + private: + bool isArithmetic(vector& nums, int l, int r) { + if (r - l < 2) + return true; + + unordered_set numsSet; + int mn = INT_MAX; + int mx = INT_MIN; + + for (int i = l; i <= r; ++i) { + mn = min(mn, nums[i]); + mx = max(mx, nums[i]); + numsSet.insert(nums[i]); + } + + if ((mx - mn) % (r - l) != 0) + return false; + + const int interval = (mx - mn) / (r - l); + + for (int k = 1; k <= r - l; ++k) + if (!numsSet.contains(mn + k * interval)) + return false; + + return true; + } +}; diff --git a/solutions/1630. Arithmetic Subarrays/1630.java b/solutions/1630. Arithmetic Subarrays/1630.java new file mode 100644 index 00000000000..db875ea767d --- /dev/null +++ b/solutions/1630. Arithmetic Subarrays/1630.java @@ -0,0 +1,36 @@ +class Solution { + public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { + List ans = new ArrayList<>(); + + for (int i = 0; i < l.length; ++i) + ans.add(isArithmetic(nums, l[i], r[i])); + + return ans; + } + + private boolean isArithmetic(int[] nums, int l, int r) { + if (r - l < 2) + return true; + + int mn = Integer.MAX_VALUE; + int mx = Integer.MIN_VALUE; + Set numsSet = new HashSet<>(); + + for (int i = l; i <= r; ++i) { + mn = Math.min(mn, nums[i]); + mx = Math.max(mx, nums[i]); + numsSet.add(nums[i]); + } + + if ((mx - mn) % (r - l) != 0) + return false; + + final int interval = (mx - mn) / (r - l); + + for (int k = 1; k <= r - l; ++k) + if (!numsSet.contains(mn + k * interval)) + return false; + + return true; + } +} diff --git a/solutions/1630. Arithmetic Subarrays/1630.py b/solutions/1630. Arithmetic Subarrays/1630.py new file mode 100644 index 00000000000..4e5d8a8b514 --- /dev/null +++ b/solutions/1630. Arithmetic Subarrays/1630.py @@ -0,0 +1,23 @@ +class Solution: + def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: + return [self._isArithmetic(nums, a, b) for a, b in zip(l, r)] + + def _isArithmetic(self, nums: List[int], l: int, r: int) -> bool: + if r - l < 2: + return True + + numsSet = set() + mn = math.inf + mx = -math.inf + + for i in range(l, r+1): + mn = min(mn, nums[i]) + mx = max(mx, nums[i]) + numsSet.add(nums[i]) + + if (mx - mn) % (r - l) != 0: + return False + + interval = (mx - mn) // (r - l) + return all(mn + k * interval in numsSet + for k in range(1, r - l + 1)) diff --git a/solutions/1631. Path With Minimum Effort/1631.cpp b/solutions/1631. Path With Minimum Effort/1631.cpp new file mode 100644 index 00000000000..8f7a1397f77 --- /dev/null +++ b/solutions/1631. Path With Minimum Effort/1631.cpp @@ -0,0 +1,47 @@ +struct T { + int i; + int j; + int d; + T(int i, int j, int d) : i(i), j(j), d(d) {} +}; + +class Solution { + public: + int minimumEffortPath(vector>& heights) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = heights.size(); + const int n = heights[0].size(); + auto compare = [](const T& a, const T& b) { return a.d > b.d; }; + priority_queue, decltype(compare)> minHeap(compare); + // diff[i][j] := the maximum absolute difference to reach (i, j) + vector> diff(m, vector(n, INT_MAX)); + vector> seen(m, vector(n)); + + minHeap.emplace(0, 0, 0); + diff[0][0] = 0; + + while (!minHeap.empty()) { + const auto [i, j, d] = minHeap.top(); + minHeap.pop(); + if (i == m - 1 && j == n - 1) + return d; + seen[i][j] = true; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + const int newDiff = abs(heights[i][j] - heights[x][y]); + const int maxDiff = max(diff[i][j], newDiff); + if (diff[x][y] > maxDiff) { + diff[x][y] = maxDiff; + minHeap.emplace(x, y, maxDiff); + } + } + } + + throw; + } +}; diff --git a/solutions/1631. Path With Minimum Effort/1631.java b/solutions/1631. Path With Minimum Effort/1631.java new file mode 100644 index 00000000000..573284bfc60 --- /dev/null +++ b/solutions/1631. Path With Minimum Effort/1631.java @@ -0,0 +1,51 @@ +class T { + public int i; + public int j; + public int d; // Max difference of (i, j) and its neighbors + public T(int i, int j, int d) { + this.i = i; + this.j = j; + this.d = d; + } +} + +class Solution { + public int minimumEffortPath(int[][] heights) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = heights.length; + final int n = heights[0].length; + Queue minHeap = new PriorityQueue<>((a, b) -> a.d - b.d); + // dist[i][j] := the maximum absolute difference to reach (i, j) + int[][] diff = new int[m][n]; + Arrays.stream(diff).forEach(row -> Arrays.fill(row, Integer.MAX_VALUE)); + boolean[][] seen = new boolean[m][n]; + + minHeap.offer(new T(0, 0, 0)); + diff[0][0] = 0; + + while (!minHeap.isEmpty()) { + final int i = minHeap.peek().i; + final int j = minHeap.peek().j; + final int d = minHeap.poll().d; + if (i == m - 1 && j == n - 1) + return d; + seen[i][j] = true; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + final int newDiff = Math.abs(heights[i][j] - heights[x][y]); + final int maxDiff = Math.max(diff[i][j], newDiff); + if (diff[x][y] > maxDiff) { + diff[x][y] = maxDiff; + minHeap.offer(new T(x, y, maxDiff)); + } + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1631. Path With Minimum Effort/1631.py b/solutions/1631. Path With Minimum Effort/1631.py new file mode 100644 index 00000000000..1fa93048950 --- /dev/null +++ b/solutions/1631. Path With Minimum Effort/1631.py @@ -0,0 +1,29 @@ +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(heights) + n = len(heights[0]) + # diff[i][j] := the maximum absolute difference to reach (i, j) + diff = [[math.inf] * n for _ in range(m)] + seen = set() + + minHeap = [(0, 0, 0)] # (d, i, j) + diff[0][0] = 0 + + while minHeap: + d, i, j = heapq.heappop(minHeap) + if i == m - 1 and j == n - 1: + return d + seen.add((i, j)) + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if (x, y) in seen: + continue + newDiff = abs(heights[i][j] - heights[x][y]) + maxDiff = max(diff[i][j], newDiff) + if diff[x][y] > maxDiff: + diff[x][y] = maxDiff + heapq.heappush(minHeap, (diff[x][y], x, y)) diff --git a/solutions/1632. Rank Transform of a Matrix/1632.cpp b/solutions/1632. Rank Transform of a Matrix/1632.cpp new file mode 100644 index 00000000000..4042ea8cae6 --- /dev/null +++ b/solutions/1632. Rank Transform of a Matrix/1632.cpp @@ -0,0 +1,64 @@ +class UnionFind { + public: + void union_(int u, int v) { + if (!id.contains(u)) + id[u] = u; + if (!id.contains(v)) + id[v] = v; + const int i = find(u); + const int j = find(v); + if (i != j) + id[i] = j; + } + + unordered_map> getGroupIdToValues() { + unordered_map> groupIdToValues; + for (const auto& [u, _] : id) + groupIdToValues[find(u)].push_back(u); + return groupIdToValues; + } + + private: + unordered_map id; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + vector> matrixRankTransform(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + vector> ans(m, vector(n)); + // {val: [(i, j)]} + map>> valToGrids; + // rank[i] := the maximum rank of the row or column so far + vector maxRankSoFar(m + n); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + valToGrids[matrix[i][j]].emplace_back(i, j); + + for (const auto& [val, grids] : valToGrids) { + UnionFind uf; + for (const auto& [i, j] : grids) + // Union i-th row with j-th col. + uf.union_(i, j + m); + for (const auto& [groupId, values] : uf.getGroupIdToValues()) { + // Get the maximum rank of all the included rows and columns. + int maxRank = 0; + for (const int i : values) + maxRank = max(maxRank, maxRankSoFar[i]); + // Update all the rows and columns to maxRank + 1. + for (const int i : values) + maxRankSoFar[i] = maxRank + 1; + } + for (const auto& [i, j] : grids) + ans[i][j] = maxRankSoFar[i]; + } + + return ans; + } +}; diff --git a/solutions/1632. Rank Transform of a Matrix/1632.java b/solutions/1632. Rank Transform of a Matrix/1632.java new file mode 100644 index 00000000000..e859c4b9baa --- /dev/null +++ b/solutions/1632. Rank Transform of a Matrix/1632.java @@ -0,0 +1,74 @@ +class UnionFind { + public void union(int u, int v) { + id.putIfAbsent(u, u); + id.putIfAbsent(v, v); + final int i = find(u); + final int j = find(v); + if (i != j) + id.put(i, j); + } + + public Map> getGroupIdToValues() { + Map> groupIdToValues = new HashMap<>(); + for (Map.Entry entry : id.entrySet()) { + final int u = entry.getKey(); + final int i = find(u); + groupIdToValues.putIfAbsent(i, new ArrayList<>()); + groupIdToValues.get(i).add(u); + } + return groupIdToValues; + } + + private Map id = new HashMap<>(); + + private int find(int u) { + return id.getOrDefault(u, u) == u ? u : find(id.get(u)); + } +} + +class Solution { + public int[][] matrixRankTransform(int[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + int[][] ans = new int[m][n]; + // {val: [(i, j)]} + TreeMap>> valToGrids = new TreeMap<>(); + // rank[i] := the maximum rank of the row or column so far + int[] maxRankSoFar = new int[m + n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + final int val = matrix[i][j]; + valToGrids.putIfAbsent(val, new ArrayList<>()); + valToGrids.get(val).add(new Pair<>(i, j)); + } + + for (Map.Entry>> entry : valToGrids.entrySet()) { + final int val = entry.getKey(); + List> grids = entry.getValue(); + UnionFind uf = new UnionFind(); + for (Pair grid : grids) { + final int i = grid.getKey(); + final int j = grid.getValue(); + // Union i-th row with j-th col. + uf.union(i, j + m); + } + for (List values : uf.getGroupIdToValues().values()) { + // Get the maximum rank of all the included rows and columns. + int maxRank = 0; + for (final int i : values) + maxRank = Math.max(maxRank, maxRankSoFar[i]); + // Update all the rows and columns to maxRank + 1. + for (final int i : values) + maxRankSoFar[i] = maxRank + 1; + } + for (Pair grid : grids) { + final int i = grid.getKey(); + final int j = grid.getValue(); + ans[i][j] = maxRankSoFar[i]; + } + } + + return ans; + } +} diff --git a/solutions/1632. Rank Transform of a Matrix/1632.py b/solutions/1632. Rank Transform of a Matrix/1632.py new file mode 100644 index 00000000000..9193a1bf4b0 --- /dev/null +++ b/solutions/1632. Rank Transform of a Matrix/1632.py @@ -0,0 +1,53 @@ +class UnionFind: + def __init__(self): + self.id = {} + + def union(self, u: int, v: int) -> None: + self.id.setdefault(u, u) + self.id.setdefault(v, v) + i = self._find(u) + j = self._find(v) + if i != j: + self.id[i] = j + + def getGroupIdToValues(self) -> Dict[int, List[int]]: + groupIdToValues = collections.defaultdict(list) + for u in self.id.keys(): + groupIdToValues[self._find(u)].append(u) + return groupIdToValues + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]: + m = len(matrix) + n = len(matrix[0]) + ans = [[0] * n for _ in range(m)] + # {val: [(i, j)]} + valToGrids = collections.defaultdict(list) + # rank[i] := the maximum rank of the row or column so far + maxRankSoFar = [0] * (m + n) + + for i, row in enumerate(matrix): + for j, val in enumerate(row): + valToGrids[val].append((i, j)) + + for _, grids in sorted(valToGrids.items()): + uf = UnionFind() + for i, j in grids: + # Union i-th row with j-th col. + uf.union(i, j + m) + for values in uf.getGroupIdToValues().values(): + # Get the maximum rank of all the included rows and columns. + maxRank = max(maxRankSoFar[i] for i in values) + for i in values: + # Update all the rows and columns to maxRank + 1. + maxRankSoFar[i] = maxRank + 1 + for i, j in grids: + ans[i][j] = maxRankSoFar[i] + + return ans diff --git a/solutions/1633. Percentage of Users Attended a Contest/1633.sql b/solutions/1633. Percentage of Users Attended a Contest/1633.sql new file mode 100644 index 00000000000..f5431cf3d4b --- /dev/null +++ b/solutions/1633. Percentage of Users Attended a Contest/1633.sql @@ -0,0 +1,12 @@ +SELECT + contest_id, + ROUND( + COUNT(user_id) * 100 / ( + SELECT COUNT(*) + FROM Users + ), + 2 + ) AS percentage +FROM Register +GROUP BY 1 +ORDER BY percentage DESC, contest_id; diff --git a/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.cpp b/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.cpp new file mode 100644 index 00000000000..90dc1d21930 --- /dev/null +++ b/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.cpp @@ -0,0 +1,55 @@ +/** + * Definition for polynomial singly-linked list. + * struct PolyNode { + * int coefficient, power; + * PolyNode *next; + * PolyNode(): coefficient(0), power(0), next(nullptr) {}; + * PolyNode(int x, int y): coefficient(x), power(y), next(nullptr) {}; + * PolyNode(int x, int y, PolyNode* next): coefficient(x), power(y), + * next(next) {}; + * }; + */ + +class Solution { + public: + PolyNode* addPoly(PolyNode* poly1, PolyNode* poly2) { + PolyNode* dummy = new PolyNode(); + PolyNode* curr = dummy; + PolyNode* p = poly1; // poly1's pointer + PolyNode* q = poly2; // poly2's pointer + + while (p != nullptr && q != nullptr) { + if (p->power > q->power) { + curr->next = new PolyNode(p->coefficient, p->power); + curr = curr->next; + p = p->next; + } else if (p->power < q->power) { + curr->next = new PolyNode(q->coefficient, q->power); + curr = curr->next; + q = q->next; + } else { // p->power == q->power + const int sumCoefficient = p->coefficient + q->coefficient; + if (sumCoefficient != 0) { + curr->next = new PolyNode(sumCoefficient, p->power); + curr = curr->next; + } + p = p->next; + q = q->next; + } + } + + while (p != nullptr) { + curr->next = new PolyNode(p->coefficient, p->power); + curr = curr->next; + p = p->next; + } + + while (q != nullptr) { + curr->next = new PolyNode(q->coefficient, q->power); + curr = curr->next; + q = q->next; + } + + return dummy->next; + } +}; diff --git a/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.java b/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.java new file mode 100644 index 00000000000..2db741b06ce --- /dev/null +++ b/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.java @@ -0,0 +1,57 @@ +/** + * Definition for polynomial singly-linked list. + * class PolyNode { + * int coefficient, power; + * PolyNode next = null; + * PolyNode() {} + * PolyNode(int x, int y) { this.coefficient = x; this.power = y; } + * PolyNode(int x, int y, PolyNode next) { + * this.coefficient = x; + * this.power = y; + * this.next = next; + * } + * } + */ + +class Solution { + public PolyNode addPoly(PolyNode poly1, PolyNode poly2) { + PolyNode dummy = new PolyNode(); + PolyNode curr = dummy; + PolyNode p = poly1; // poly1's pointer + PolyNode q = poly2; // poly2's pointer + + while (p != null && q != null) { + if (p.power > q.power) { + curr.next = new PolyNode(p.coefficient, p.power); + curr = curr.next; + p = p.next; + } else if (p.power < q.power) { + curr.next = new PolyNode(q.coefficient, q.power); + curr = curr.next; + q = q.next; + } else { // p.power == q.power + final int sumCoefficient = p.coefficient + q.coefficient; + if (sumCoefficient != 0) { + curr.next = new PolyNode(sumCoefficient, p.power); + curr = curr.next; + } + p = p.next; + q = q.next; + } + } + + while (p != null) { + curr.next = new PolyNode(p.coefficient, p.power); + curr = curr.next; + p = p.next; + } + + while (q != null) { + curr.next = new PolyNode(q.coefficient, q.power); + curr = curr.next; + q = q.next; + } + + return dummy.next; + } +} diff --git a/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.py b/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.py new file mode 100644 index 00000000000..bede8484ed8 --- /dev/null +++ b/solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.py @@ -0,0 +1,42 @@ +# Definition for polynomial singly-linked list. +# class PolyNode: +# def __init__(self, x=0, y=0, next=None): +# self.coefficient = x +# self.power = y +# self.next = next + +class Solution: + def addPoly(self, poly1: 'PolyNode', poly2: 'PolyNode') -> 'PolyNode': + dummy = PolyNode() + curr = dummy + p = poly1 # poly1's pointer + q = poly2 # poly2's pointer + + while p and q: + if p.power > q.power: + curr.next = PolyNode(p.coefficient, p.power) + curr = curr.next + p = p.next + elif p.power < q.power: + curr.next = PolyNode(q.coefficient, q.power) + curr = curr.next + q = q.next + else: # p.power == q.power + sumCoefficient = p.coefficient + q.coefficient + if sumCoefficient != 0: + curr.next = PolyNode(sumCoefficient, p.power) + curr = curr.next + p = p.next + q = q.next + + while p: + curr.next = PolyNode(p.coefficient, p.power) + curr = curr.next + p = p.next + + while q: + curr.next = PolyNode(q.coefficient, q.power) + curr = curr.next + q = q.next + + return dummy.next diff --git a/solutions/1635. Hopper Company Queries I/1635.sql b/solutions/1635. Hopper Company Queries I/1635.sql new file mode 100644 index 00000000000..796f17e52d1 --- /dev/null +++ b/solutions/1635. Hopper Company Queries I/1635.sql @@ -0,0 +1,29 @@ +WITH + RECURSIVE Calendar AS ( + SELECT 1 AS month + UNION ALL + SELECT month + 1 + FROM Calendar + WHERE month < 12 + ) +SELECT + Calendar.month, + ( + SELECT COUNT(*) + FROM Drivers + WHERE + YEAR(Drivers.join_date) < '2020' + OR ( + YEAR(Drivers.join_date) = '2020' + AND MONTH(Drivers.join_date) <= Calendar.month) + ) AS active_drivers, + ( + SELECT COUNT(*) + FROM AcceptedRides + INNER JOIN Rides + USING (ride_id) + WHERE + YEAR(Rides.requested_at) = '2020' + AND MONTH(Rides.requested_at) = Calendar.month + ) AS accepted_rides +FROM Calendar; diff --git a/solutions/1636. Sort Array by Increasing Frequency/1636.cpp b/solutions/1636. Sort Array by Increasing Frequency/1636.cpp new file mode 100644 index 00000000000..c27dabec436 --- /dev/null +++ b/solutions/1636. Sort Array by Increasing Frequency/1636.cpp @@ -0,0 +1,32 @@ +struct T { + int num; + int freq; + T(int num, int freq) : num(num), freq(freq) {} +}; + +class Solution { + public: + vector frequencySort(vector& nums) { + vector ans; + auto compare = [](const T& a, const T& b) { + return a.freq == b.freq ? a.num < b.num : a.freq > b.freq; + }; + priority_queue, decltype(compare)> heap(compare); + unordered_map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [num, freq] : count) + heap.emplace(num, freq); + + while (!heap.empty()) { + const auto [num, freq] = heap.top(); + heap.pop(); + for (int i = 0; i < freq; ++i) + ans.push_back(num); + } + + return ans; + } +}; diff --git a/solutions/1636. Sort Array by Increasing Frequency/1636.java b/solutions/1636. Sort Array by Increasing Frequency/1636.java new file mode 100644 index 00000000000..02a7d7ffd7d --- /dev/null +++ b/solutions/1636. Sort Array by Increasing Frequency/1636.java @@ -0,0 +1,33 @@ +class T { + public int num; + public int freq; + public T(int num, int freq) { + this.num = num; + this.freq = freq; + } +}; + +class Solution { + public int[] frequencySort(int[] nums) { + int[] ans = new int[nums.length]; + int ansIndex = 0; + Map count = new HashMap<>(); + Queue heap = + new PriorityQueue<>((a, b) -> a.freq == b.freq ? b.num - a.num : a.freq - b.freq); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (Map.Entry entry : count.entrySet()) + heap.offer(new T(entry.getKey(), entry.getValue())); + + while (!heap.isEmpty()) { + final int num = heap.peek().num; + final int freq = heap.poll().freq; + for (int i = 0; i < freq; ++i) + ans[ansIndex++] = num; + } + + return ans; + } +} diff --git a/solutions/1636. Sort Array by Increasing Frequency/1636.py b/solutions/1636. Sort Array by Increasing Frequency/1636.py new file mode 100644 index 00000000000..4d51cd9393e --- /dev/null +++ b/solutions/1636. Sort Array by Increasing Frequency/1636.py @@ -0,0 +1,25 @@ +class T: + def __init__(self, num: int, freq: int): + self.num = num + self.freq = freq + + def __lt__(self, other): + if self.freq == other.freq: + return self.num > other.num + return self.freq < other.freq + + +class Solution: + def frequencySort(self, nums: List[int]) -> List[int]: + ans = [] + heap = [] + + for num, freq in collections.Counter(nums).items(): + heapq.heappush(heap, T(num, freq)) + + while len(heap) > 0: + num = heap[0].num + freq = heapq.heappop(heap).freq + ans.extend([num] * freq) + + return ans diff --git a/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.cpp b/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.cpp new file mode 100644 index 00000000000..c37809249f4 --- /dev/null +++ b/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maxWidthOfVerticalArea(vector>& points) { + int ans = 0; + vector xs; + + for (const vector& point : points) { + const int x = point[0]; + xs.push_back(x); + } + + ranges::sort(xs); + + for (int i = 1; i < xs.size(); ++i) + ans = max(ans, xs[i] - xs[i - 1]); + + return ans; + } +}; diff --git a/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.java b/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.java new file mode 100644 index 00000000000..62ef8a60001 --- /dev/null +++ b/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.java @@ -0,0 +1,16 @@ +class Solution { + public int maxWidthOfVerticalArea(int[][] points) { + int ans = 0; + int[] xs = new int[points.length]; + + for (int i = 0; i < points.length; ++i) + xs[i] = points[i][0]; + + Arrays.sort(xs); + + for (int i = 1; i < xs.length; ++i) + ans = Math.max(ans, xs[i] - xs[i - 1]); + + return ans; + } +} diff --git a/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.py b/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.py new file mode 100644 index 00000000000..aafe6faeb90 --- /dev/null +++ b/solutions/1637. Widest Vertical Area Between Two Points Containing No Points/1637.py @@ -0,0 +1,4 @@ +class Solution: + def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: + xs = sorted([x for x, _ in points]) + return max(b - a for a, b in itertools.pairwise(xs)) diff --git a/solutions/1638. Count Substrings That Differ by One Character/1638.cpp b/solutions/1638. Count Substrings That Differ by One Character/1638.cpp new file mode 100644 index 00000000000..8bc091a1dff --- /dev/null +++ b/solutions/1638. Count Substrings That Differ by One Character/1638.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int countSubstrings(string s, string t) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) + ans += count(s, t, i, 0); + + for (int j = 1; j < t.length(); ++j) + ans += count(s, t, 0, j); + + return ans; + } + + private: + // Returns the number of substrings of s[i..n) and t[j..n) that differ by one + // letter. + int count(const string& s, const string& t, int i, int j) { + int res = 0; + // the number of substrings starting at s[i] and t[j] ending in the current + // index with zero different letter + int dp0 = 0; + // the number of substrings starting at s[i] and t[j] ending in the current + // index with one different letter + int dp1 = 0; + + for (; i < s.length() && j < t.length(); ++i, ++j) { + if (s[i] == t[j]) { + ++dp0; + } else { + dp1 = dp0 + 1; + dp0 = 0; + } + res += dp1; + } + + return res; + } +}; diff --git a/solutions/1638. Count Substrings That Differ by One Character/1638.java b/solutions/1638. Count Substrings That Differ by One Character/1638.java new file mode 100644 index 00000000000..2dd4c681da2 --- /dev/null +++ b/solutions/1638. Count Substrings That Differ by One Character/1638.java @@ -0,0 +1,37 @@ +class Solution { + public int countSubstrings(String s, String t) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) + ans += count(s, t, i, 0); + + for (int j = 1; j < t.length(); ++j) + ans += count(s, t, 0, j); + + return ans; + } + + // Returns the number of substrings of s[i..n) and t[j..n) that differ by one + // letter. + private int count(final String s, final String t, int i, int j) { + int res = 0; + // the number of substrings starting at s[i] and t[j] ending in the current + // index with zero different letter + int dp0 = 0; + // the number of substrings starting at s[i] and t[j] ending in the current + // index with one different letter + int dp1 = 0; + + for (; i < s.length() && j < t.length(); ++i, ++j) { + if (s.charAt(i) == t.charAt(j)) { + ++dp0; + } else { + dp1 = dp0 + 1; + dp0 = 0; + } + res += dp1; + } + + return res; + } +} diff --git a/solutions/1638. Count Substrings That Differ by One Character/1638.py b/solutions/1638. Count Substrings That Differ by One Character/1638.py new file mode 100644 index 00000000000..fc853bef067 --- /dev/null +++ b/solutions/1638. Count Substrings That Differ by One Character/1638.py @@ -0,0 +1,32 @@ +class Solution: + def countSubstrings(self, s: str, t: str) -> int: + ans = 0 + + for i in range(len(s)): + ans += self._count(s, t, i, 0) + + for j in range(1, len(t)): + ans += self._count(s, t, 0, j) + + return ans + + def _count(self, s: str, t: str, i: int, j: int) -> int: + """Returns the number of substrings of s[i..n) and t[j:] that differ by one char.""" + res = 0 + # the number of substrings starting at s[i] and t[j] ending in the current + # index with zero different letter + dp0 = 0 + # the number of substrings starting at s[i] and t[j] ending in the current + # index with one different letter + dp1 = 0 + + while i < len(s) and j < len(t): + if s[i] == t[j]: + dp0 += 1 + else: + dp0, dp1 = 0, dp0 + 1 + res += dp1 + i += 1 + j += 1 + + return res diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.cpp b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.cpp new file mode 100644 index 00000000000..cf0eae5c1c8 --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int numWays(vector& words, string target) { + constexpr int kMod = 1'000'000'007; + const int wordLength = words[0].length(); + // dp[i][j] := the number of ways to form the first i characters of the + // `target` using the j first characters in each word + vector> dp(target.length() + 1, vector(wordLength + 1)); + // counts[j] := the count map of words[i][j], where 0 <= i < |words| + vector> counts(wordLength, vector(26)); + + for (int i = 0; i < wordLength; ++i) + for (const string& word : words) + ++counts[i][word[i] - 'a']; + + dp[0][0] = 1; + + for (int i = 0; i <= target.length(); ++i) + for (int j = 0; j < wordLength; ++j) { + if (i < target.length()) + // Pick the character target[i] from word[j]. + dp[i + 1][j + 1] = + dp[i][j] * static_cast(counts[j][target[i] - 'a']) % kMod; + // Skip the word[j]. + dp[i][j + 1] = (dp[i][j + 1] + dp[i][j]) % kMod; + } + + return dp[target.length()][wordLength]; + }; +}; diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.java b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.java new file mode 100644 index 00000000000..98afd0b1c36 --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.java @@ -0,0 +1,28 @@ +class Solution { + public int numWays(String[] words, String target) { + final int kMod = 1_000_000_007; + final int wordLength = words[0].length(); + // dp[i][j] := the number of ways to form the first i characters of the + // `target` using the j first characters in each word + int[][] dp = new int[target.length() + 1][wordLength + 1]; + // counts[j] := the count map of words[i][j], where 0 <= i < |words| + int[][] counts = new int[wordLength][26]; + + for (int i = 0; i < wordLength; ++i) + for (final String word : words) + ++counts[i][word.charAt(i) - 'a']; + + dp[0][0] = 1; + + for (int i = 0; i <= target.length(); ++i) + for (int j = 0; j < wordLength; ++j) { + if (i < target.length()) + // Pick the character target[i] from word[j]. + dp[i + 1][j + 1] = (int) ((dp[i][j] * (long) counts[j][target.charAt(i) - 'a']) % kMod); + // Skip the word[j]. + dp[i][j + 1] = (dp[i][j + 1] + dp[i][j]) % kMod; + } + + return dp[target.length()][wordLength]; + } +} diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.py b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.py new file mode 100644 index 00000000000..1eca501774a --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.py @@ -0,0 +1,27 @@ +class Solution: + def numWays(self, words: List[str], target: str) -> int: + kMod = 1_000_000_007 + wordLength = len(words[0]) + # dp[i][j] := the number of ways to form the first i characters of the + # `target` using the j first characters in each word + dp = [[0] * (wordLength + 1) for _ in range(len(target) + 1)] + # counts[j] := the count map of words[i][j], where 0 <= i < |words| + counts = [collections.Counter() for _ in range(wordLength)] + + for i in range(wordLength): + for word in words: + counts[i][word[i]] += 1 + + dp[0][0] = 1 + + for i in range(len(target) + 1): + for j in range(wordLength): + if i < len(target): + # Pick the character target[i] from word[j]. + dp[i + 1][j + 1] = dp[i][j] * counts[j][target[i]] + dp[i + 1][j + 1] %= kMod + # Skip the word[j]. + dp[i][j + 1] += dp[i][j] + dp[i][j + 1] %= kMod + + return dp[len(target)][wordLength] diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.cpp b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.cpp new file mode 100644 index 00000000000..bf9c091e402 --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int numWays(vector& words, string target) { + constexpr int kMod = 1'000'000'007; + const int wordLength = words[0].length(); + // dp[i] := the number of ways to form the first i characters of the + // `target` + vector dp(target.size() + 1); + dp[0] = 1; + + for (int j = 0; j < wordLength; ++j) { + vector count(26); + for (const string& word : words) + ++count[word[j] - 'a']; + for (int i = target.size(); i > 0; --i) { + dp[i] += dp[i - 1] * count[target[i - 1] - 'a']; + dp[i] %= kMod; + } + } + + return dp[target.length()]; + }; +}; diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.java b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.java new file mode 100644 index 00000000000..0cf9b042e7d --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.java @@ -0,0 +1,21 @@ +class Solution { + public int numWays(String[] words, String target) { + final int kMod = 1_000_000_007; + final int wordLength = words[0].length(); + // dp[i] := the number of ways to form the first i characters of `target` + long[] dp = new long[target.length() + 1]; + dp[0] = 1; + + for (int j = 0; j < wordLength; ++j) { + int[] count = new int[26]; + for (final String word : words) + ++count[word.charAt(j) - 'a']; + for (int i = target.length(); i > 0; --i) { + dp[i] += dp[i - 1] * count[target.charAt(i - 1) - 'a']; + dp[i] %= kMod; + } + } + + return (int) dp[target.length()]; + } +} diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.py b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.py new file mode 100644 index 00000000000..d7fd5ef929b --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-3.py @@ -0,0 +1,14 @@ +class Solution: + def numWays(self, words: List[str], target: str) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of ways to form the first i characters of `target` + dp = [0] * (len(target) + 1) + dp[0] = 1 + + for j in range(len(words[0])): + count = collections.Counter(word[j] for word in words) + for i in range(len(target), 0, -1): + dp[i] += dp[i - 1] * count[target[i - 1]] + dp[i] %= kMod + + return dp[len(target)] diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.cpp b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.cpp new file mode 100644 index 00000000000..5a67be36748 --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int numWays(vector& words, string target) { + const int wordLength = words[0].length(); + vector> mem(target.length(), vector(wordLength, -1)); + // counts[j] := the count map of words[i][j], where 0 <= i < |words| + vector> counts(wordLength, vector(26)); + + for (int i = 0; i < wordLength; ++i) + for (const string& word : words) + ++counts[i][word[i] - 'a']; + + return numWays(target, 0, 0, counts, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of ways to form target[i..n) using word[j..n). + int numWays(const string& target, int i, int j, + const vector>& counts, vector>& mem) { + if (i == target.length()) + return 1; + if (j == counts.size()) + return 0; + if (mem[i][j] != -1) + return mem[i][j]; + return mem[i][j] = (numWays(target, i + 1, j + 1, counts, mem) * + static_cast(counts[j][target[i] - 'a']) + + numWays(target, i, j + 1, counts, mem)) % + kMod; + }; +}; diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.java b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.java new file mode 100644 index 00000000000..76b69e0ee03 --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.java @@ -0,0 +1,30 @@ +class Solution { + public int numWays(String[] words, String target) { + final int wordLength = words[0].length(); + Integer[][] mem = new Integer[target.length()][wordLength]; + // counts[j] := the count map of words[i][j], where 0 <= i < |words| + int[][] counts = new int[wordLength][26]; + + for (int i = 0; i < wordLength; ++i) + for (final String word : words) + ++counts[i][word.charAt(i) - 'a']; + + return numWays(target, 0, 0, counts, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of ways to form target[i..n) using word[j..n). + private int numWays(final String target, int i, int j, int[][] counts, Integer[][] mem) { + if (i == target.length()) + return 1; + if (j == counts.length) + return 0; + if (mem[i][j] != null) + return mem[i][j]; + return mem[i][j] = (int) ((numWays(target, i + 1, j + 1, counts, mem) * + (long) (counts[j][target.charAt(i) - 'a']) + + numWays(target, i, j + 1, counts, mem)) % + kMod); + } +} diff --git a/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.py b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.py new file mode 100644 index 00000000000..ade1f6346e7 --- /dev/null +++ b/solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.py @@ -0,0 +1,21 @@ +class Solution: + def numWays(self, words: List[str], target: str) -> int: + kMod = 1_000_000_007 + wordLength = len(words[0]) + # counts[j] := the count map of words[i][j], where 0 <= i < |words| + counts = [collections.Counter() for _ in range(wordLength)] + + for i in range(wordLength): + for word in words: + counts[i][word[i]] += 1 + + @functools.lru_cache(None) + def dp(i: int, j: int): + """Returns the number of ways to form target[i..n) using word[j..n).""" + if i == len(target): + return 1 + if j == wordLength: + return 0 + return (dp(i + 1, j + 1) * counts[j][target[i]] + dp(i, j + 1)) % kMod + + return dp(0, 0) diff --git a/solutions/164. Maximum Gap/164.cpp b/solutions/164. Maximum Gap/164.cpp new file mode 100644 index 00000000000..1c95ebf97db --- /dev/null +++ b/solutions/164. Maximum Gap/164.cpp @@ -0,0 +1,39 @@ +struct Bucket { + int mn; + int mx; +}; + +class Solution { + public: + int maximumGap(vector& nums) { + if (nums.size() < 2) + return 0; + + const int mn = ranges::min(nums); + const int mx = ranges::max(nums); + if (mn == mx) + return 0; + + const int gap = ceil((mx - mn) / (double)(nums.size() - 1)); + const int bucketSize = (mx - mn) / gap + 1; + vector buckets(bucketSize, {INT_MAX, INT_MIN}); + + for (const int num : nums) { + const int i = (num - mn) / gap; + buckets[i].mn = min(buckets[i].mn, num); + buckets[i].mx = max(buckets[i].mx, num); + } + + int ans = 0; + int prevMax = mn; + + for (const Bucket& bucket : buckets) { + if (bucket.mn == INT_MAX) + continue; // empty bucket + ans = max(ans, bucket.mn - prevMax); + prevMax = bucket.mx; + } + + return ans; + } +}; diff --git a/solutions/164. Maximum Gap/164.java b/solutions/164. Maximum Gap/164.java new file mode 100644 index 00000000000..696aa59d81c --- /dev/null +++ b/solutions/164. Maximum Gap/164.java @@ -0,0 +1,45 @@ +class Bucket { + public int mn; + public int mx; + public Bucket(int mn, int mx) { + this.mn = mn; + this.mx = mx; + } +} + +class Solution { + public int maximumGap(int[] nums) { + if (nums.length < 2) + return 0; + + final int mn = Arrays.stream(nums).min().getAsInt(); + final int mx = Arrays.stream(nums).max().getAsInt(); + if (mn == mx) + return 0; + + final int gap = (int) Math.ceil((double) (mx - mn) / (nums.length - 1)); + final int bucketsLength = (mx - mn) / gap + 1; + Bucket[] buckets = new Bucket[bucketsLength]; + + for (int i = 0; i < buckets.length; ++i) + buckets[i] = new Bucket(Integer.MAX_VALUE, Integer.MIN_VALUE); + + for (final int num : nums) { + final int i = (num - mn) / gap; + buckets[i].mn = Math.min(buckets[i].mn, num); + buckets[i].mx = Math.max(buckets[i].mx, num); + } + + int ans = 0; + int prevMax = mn; + + for (final Bucket bucket : buckets) { + if (bucket.mn == Integer.MAX_VALUE) // empty bucket + continue; + ans = Math.max(ans, bucket.mn - prevMax); + prevMax = bucket.mx; + } + + return ans; + } +} diff --git a/solutions/164. Maximum Gap/164.py b/solutions/164. Maximum Gap/164.py new file mode 100644 index 00000000000..4d2fb4887c9 --- /dev/null +++ b/solutions/164. Maximum Gap/164.py @@ -0,0 +1,35 @@ +class Bucket: + def __init__(self, mn: int, mx: int): + self.mn = mn + self.mx = mx + + +class Solution: + def maximumGap(self, nums: List[int]) -> int: + if len(nums) < 2: + return 0 + + mn = min(nums) + mx = max(nums) + if mn == mx: + return 0 + + gap = math.ceil((mx - mn) / (len(nums) - 1)) + bucketSize = (mx - mn) // gap + 1 + buckets = [Bucket(math.inf, -math.inf) for _ in range(bucketSize)] + + for num in nums: + i = (num - mn) // gap + buckets[i].mn = min(buckets[i].mn, num) + buckets[i].mx = max(buckets[i].mx, num) + + ans = 0 + prevMax = mn + + for bucket in buckets: + if bucket.mn == math.inf: + continue # empty bucket + ans = max(ans, bucket.mn - prevMax) + prevMax = bucket.mx + + return ans diff --git a/solutions/1640. Check Array Formation Through Concatenation/1640.cpp b/solutions/1640. Check Array Formation Through Concatenation/1640.cpp new file mode 100644 index 00000000000..4928f84ed21 --- /dev/null +++ b/solutions/1640. Check Array Formation Through Concatenation/1640.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool canFormArray(vector& arr, vector>& pieces) { + vector concatenated; + unordered_map> startToPiece; + + for (const vector& piece : pieces) + startToPiece[piece[0]] = piece; + + for (const int a : arr) + if (startToPiece.contains(a)) + for (const int num : startToPiece[a]) + concatenated.push_back(num); + + return concatenated == arr; + } +}; diff --git a/solutions/1640. Check Array Formation Through Concatenation/1640.java b/solutions/1640. Check Array Formation Through Concatenation/1640.java new file mode 100644 index 00000000000..180ae2e0476 --- /dev/null +++ b/solutions/1640. Check Array Formation Through Concatenation/1640.java @@ -0,0 +1,15 @@ +class Solution { + public boolean canFormArray(int[] arr, int[][] pieces) { + List concatenated = new ArrayList<>(); + Map startToPiece = new HashMap<>(); + + for (int[] piece : pieces) + startToPiece.put(piece[0], piece); + + for (final int a : arr) + for (final int num : startToPiece.getOrDefault(a, new int[])) + concatenated.add(num); + + return Arrays.equals(concatenated.stream().mapToInt(Integer::intValue).toArray(), arr); + } +} diff --git a/solutions/1640. Check Array Formation Through Concatenation/1640.py b/solutions/1640. Check Array Formation Through Concatenation/1640.py new file mode 100644 index 00000000000..c62f39b9c8b --- /dev/null +++ b/solutions/1640. Check Array Formation Through Concatenation/1640.py @@ -0,0 +1,9 @@ +class Solution: + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: + concatenated = [] + startToPiece = {piece[0]: piece for piece in pieces} + + for a in arr: + concatenated += startToPiece.get(a, []) + + return concatenated == arr diff --git a/solutions/1641. Count Sorted Vowel Strings/1641-2.cpp b/solutions/1641. Count Sorted Vowel Strings/1641-2.cpp new file mode 100644 index 00000000000..aea15477a49 --- /dev/null +++ b/solutions/1641. Count Sorted Vowel Strings/1641-2.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int countVowelStrings(int n) { + return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24; + } +}; diff --git a/solutions/1641. Count Sorted Vowel Strings/1641-2.java b/solutions/1641. Count Sorted Vowel Strings/1641-2.java new file mode 100644 index 00000000000..e41df45e93f --- /dev/null +++ b/solutions/1641. Count Sorted Vowel Strings/1641-2.java @@ -0,0 +1,5 @@ +class Solution { + public int countVowelStrings(int n) { + return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24; + } +} diff --git a/solutions/1641. Count Sorted Vowel Strings/1641.cpp b/solutions/1641. Count Sorted Vowel Strings/1641.cpp new file mode 100644 index 00000000000..9ee03bbb869 --- /dev/null +++ b/solutions/1641. Count Sorted Vowel Strings/1641.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countVowelStrings(int n) { + // dp[0] := the number of lexicographically sorted string that end in 'a' + // dp[1] := the number of lexicographically sorted string that end in 'e' + // dp[2] := the number of lexicographically sorted string that end in 'i' + // dp[3] := the number of lexicographically sorted string that end in 'o' + // dp[4] := the number of lexicographically sorted string that end in 'u' + vector dp(5, 1); + + for (int i = 2; i <= n; ++i) { + vector newDp(5); + for (int j = 0; j < 5; ++j) + for (int k = 0; k <= j; ++k) + newDp[j] += dp[k]; + dp = move(newDp); + } + + return accumulate(dp.begin(), dp.end(), 0); + } +}; diff --git a/solutions/1641. Count Sorted Vowel Strings/1641.java b/solutions/1641. Count Sorted Vowel Strings/1641.java new file mode 100644 index 00000000000..976932c9a4c --- /dev/null +++ b/solutions/1641. Count Sorted Vowel Strings/1641.java @@ -0,0 +1,21 @@ +class Solution { + public int countVowelStrings(int n) { + // dp[0] := the number of lexicographically sorted string that end in 'a' + // dp[1] := the number of lexicographically sorted string that end in 'e' + // dp[2] := the number of lexicographically sorted string that end in 'i' + // dp[3] := the number of lexicographically sorted string that end in 'o' + // dp[4] := the number of lexicographically sorted string that end in 'u' + int[] dp = new int[5]; + Arrays.fill(dp, 1); + + for (int i = 2; i <= n; ++i) { + int[] newDp = new int[5]; + for (int j = 0; j < 5; ++j) + for (int k = 0; k <= j; ++k) + newDp[j] += dp[k]; + dp = newDp; + } + + return Arrays.stream(dp).sum(); + } +} diff --git a/solutions/1642. Furthest Building You Can Reach/1642.cpp b/solutions/1642. Furthest Building You Can Reach/1642.cpp new file mode 100644 index 00000000000..33fb9d2b9e4 --- /dev/null +++ b/solutions/1642. Furthest Building You Can Reach/1642.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int furthestBuilding(vector& heights, int bricks, int ladders) { + priority_queue, greater> minHeap; + + for (int i = 1; i < heights.size(); ++i) { + const int diff = heights[i] - heights[i - 1]; + if (diff <= 0) + continue; + minHeap.push(diff); + // If we run out of ladders, greedily use as less bricks as possible. + if (minHeap.size() > ladders) + bricks -= minHeap.top(), minHeap.pop(); + if (bricks < 0) + return i - 1; + } + + return heights.size() - 1; + } +}; diff --git a/solutions/1642. Furthest Building You Can Reach/1642.java b/solutions/1642. Furthest Building You Can Reach/1642.java new file mode 100644 index 00000000000..b6f3410525f --- /dev/null +++ b/solutions/1642. Furthest Building You Can Reach/1642.java @@ -0,0 +1,19 @@ +class Solution { + public int furthestBuilding(int[] heights, int bricks, int ladders) { + Queue minHeap = new PriorityQueue<>(); + + for (int i = 1; i < heights.length; ++i) { + final int diff = heights[i] - heights[i - 1]; + if (diff <= 0) + continue; + minHeap.offer(diff); + // If we run out of ladders, greedily use as less bricks as possible. + if (minHeap.size() > ladders) + bricks -= minHeap.poll(); + if (bricks < 0) + return i - 1; + } + + return heights.length - 1; + } +} diff --git a/solutions/1642. Furthest Building You Can Reach/1642.py b/solutions/1642. Furthest Building You Can Reach/1642.py new file mode 100644 index 00000000000..5c693179ac2 --- /dev/null +++ b/solutions/1642. Furthest Building You Can Reach/1642.py @@ -0,0 +1,16 @@ +class Solution: + def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: + minHeap = [] + + for i, (a, b) in enumerate(itertools.pairwise(heights)): + diff = b - a + if diff <= 0: + continue + heapq.heappush(minHeap, diff) + # If we run out of ladders, greedily use as less bricks as possible. + if len(minHeap) > ladders: + bricks -= heapq.heappop(minHeap) + if bricks < 0: + return i + + return len(heights) - 1 diff --git a/solutions/1643. Kth Smallest Instructions/1643.cpp b/solutions/1643. Kth Smallest Instructions/1643.cpp new file mode 100644 index 00000000000..6b75ee22ca8 --- /dev/null +++ b/solutions/1643. Kth Smallest Instructions/1643.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + string kthSmallestPath(vector& destination, int k) { + string ans; + int v = destination[0]; + int h = destination[1]; + const int totalSteps = v + h; + const vector> comb = getComb(totalSteps - 1, v); + + for (int i = 0; i < totalSteps; ++i) { + // If 'H' is picked, we can reach ranks [1, availableRank]. + const int availableRank = comb[h + v - 1][v]; + if (availableRank >= k) { // Should pick 'H'. + ans += 'H'; + --h; + } else { // Should pick 'V'. + k -= availableRank; + ans += 'V'; + --v; + } + } + + return ans; + } + + private: + // C(n, k) = C(n - 1, k) + C(n - 1, k - 1) + vector> getComb(int n, int k) { + vector> comb(n + 1, vector(k + 1)); + for (int i = 0; i <= n; ++i) + comb[i][0] = 1; + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) + comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1]; + return comb; + } +}; diff --git a/solutions/1643. Kth Smallest Instructions/1643.java b/solutions/1643. Kth Smallest Instructions/1643.java new file mode 100644 index 00000000000..15339768729 --- /dev/null +++ b/solutions/1643. Kth Smallest Instructions/1643.java @@ -0,0 +1,34 @@ +class Solution { + public String kthSmallestPath(int[] destination, int k) { + StringBuilder sb = new StringBuilder(); + int v = destination[0]; + int h = destination[1]; + final int totalSteps = v + h; + final int[][] comb = getComb(totalSteps - 1, v); + + for (int i = 0; i < totalSteps; ++i) { + // If 'H' is picked, we can reach ranks [1, availableRank]. + final int availableRank = comb[h + v - 1][v]; + if (availableRank >= k) { // Should pick 'H'. + sb.append('H'); + --h; + } else { // Should pick 'V'. + k -= availableRank; + sb.append('V'); + --v; + } + } + + return sb.toString(); + } + + private int[][] getComb(int n, int k) { + int[][] comb = new int[n + 1][k + 1]; + for (int i = 0; i <= n; ++i) + comb[i][0] = 1; + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) + comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1]; + return comb; + } +} diff --git a/solutions/1643. Kth Smallest Instructions/1643.py b/solutions/1643. Kth Smallest Instructions/1643.py new file mode 100644 index 00000000000..7a6cd95714a --- /dev/null +++ b/solutions/1643. Kth Smallest Instructions/1643.py @@ -0,0 +1,17 @@ +class Solution: + def kthSmallestPath(self, destination: List[int], k: int) -> str: + ans = [] + v, h = destination + + for _ in range(h + v): + # If pick 'H', then we're able to reack 1, 2, ..., availableRank. + availableRank = math.comb(h + v - 1, v) + if availableRank >= k: # Should pick 'H'. + ans.append('H') + h -= 1 + else: # Should pick 'V'. + k -= availableRank + ans.append('V') + v -= 1 + + return ''.join(ans) diff --git a/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.cpp b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.cpp new file mode 100644 index 00000000000..e67118530a6 --- /dev/null +++ b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + TreeNode* ans = getLCA(root, p, q); + if (ans == p) // Search q in the subtree rooted at p. + return getLCA(p, q, q) == nullptr ? nullptr : ans; + if (ans == q) // Search p in the subtree rooted at q. + return getLCA(q, p, p) == nullptr ? nullptr : ans; + return ans; // (ans != p && ans != q) || ans == nullptr + } + + private: + TreeNode* getLCA(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr || root == p || root == q) + return root; + TreeNode* left = getLCA(root->left, p, q); + TreeNode* right = getLCA(root->right, p, q); + if (left != nullptr && right != nullptr) + return root; + return left == nullptr ? right : left; + } +}; diff --git a/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.java b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.java new file mode 100644 index 00000000000..a8a075ba75b --- /dev/null +++ b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.java @@ -0,0 +1,20 @@ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + TreeNode ans = getLCA(root, p, q); + if (ans == p) // Search q in the subtree rooted at p. + return getLCA(p, q, q) == null ? null : ans; + if (ans == q) // Search p in the subtree rooted at q. + return getLCA(q, p, p) == null ? null : ans; + return ans; // (ans != p && ans != q) || ans == null + } + + private TreeNode getLCA(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) + return root; + TreeNode left = getLCA(root.left, p, q); + TreeNode right = getLCA(root.right, p, q); + if (left != null && right != null) + return root; + return left == null ? right : left; + } +} diff --git a/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.py b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.py new file mode 100644 index 00000000000..f12551396e9 --- /dev/null +++ b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.py @@ -0,0 +1,17 @@ +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + def getLCA(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if not root or root == p or root == q: + return root + left = getLCA(root.left, p, q) + right = getLCA(root.right, p, q) + if left and right: + return root + return left or right + + ans = getLCA(root, p, q) + if ans == p: # Search q in the subtree rooted at p. + return ans if getLCA(p, q, q) else None + if ans == q: # Search p in the subtree rooted at q. + return ans if getLCA(q, p, p) else None + return ans # (ans != p and ans != q) or ans is None diff --git a/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.cpp b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.cpp new file mode 100644 index 00000000000..5f060004257 --- /dev/null +++ b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + bool seenP = false; + bool seenQ = false; + TreeNode* lca = getLCA(root, p, q, seenP, seenQ); + return seenP && seenQ ? lca : nullptr; + } + + private: + TreeNode* getLCA(TreeNode* root, TreeNode* p, TreeNode* q, bool& seenP, + bool& seenQ) { + if (root == nullptr) + return nullptr; + // Need to traverse the entire tree to update `seenP` and `seenQ`. + TreeNode* left = getLCA(root->left, p, q, seenP, seenQ); + TreeNode* right = getLCA(root->right, p, q, seenP, seenQ); + if (root == p) { + seenP = true; + return root; + } + if (root == q) { + seenQ = true; + return root; + } + if (left != nullptr && right != nullptr) + return root; + return left == nullptr ? right : left; + } +}; diff --git a/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.java b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.java new file mode 100644 index 00000000000..653172020c1 --- /dev/null +++ b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.java @@ -0,0 +1,28 @@ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + TreeNode lca = getLCA(root, p, q); + return seenP && seenQ ? lca : null; + } + + private boolean seenP = false; + private boolean seenQ = false; + + private TreeNode getLCA(TreeNode root, TreeNode p, TreeNode q) { + if (root == null) + return null; + // Need to traverse the entire tree to update `seenP` and `seenQ`. + TreeNode left = getLCA(root.left, p, q); + TreeNode right = getLCA(root.right, p, q); + if (root == p) { + seenP = true; + return root; + } + if (root == q) { + seenQ = true; + return root; + } + if (left != null && right != null) + return root; + return left == null ? right : left; + } +} diff --git a/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.py b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.py new file mode 100644 index 00000000000..a21da924f7b --- /dev/null +++ b/solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644.py @@ -0,0 +1,25 @@ +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + seenP = False + seenQ = False + + def getLCA(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + nonlocal seenP + nonlocal seenQ + if not root: + return None + # Need to traverse the entire tree to update `seenP` and `seenQ`. + left = getLCA(root.left, p, q) + right = getLCA(root.right, p, q) + if root == p: + seenP = True + return root + if root == q: + seenQ = True + return root + if left and right: + return root + return left or right + + lca = getLCA(root, p, q) + return lca if seenP and seenQ else None diff --git a/solutions/1645. Hopper Company Queries II/1645.sql b/solutions/1645. Hopper Company Queries II/1645.sql new file mode 100644 index 00000000000..304e73c3cb9 --- /dev/null +++ b/solutions/1645. Hopper Company Queries II/1645.sql @@ -0,0 +1,33 @@ +WITH + RECURSIVE Calendar AS ( + SELECT 1 AS month + UNION ALL + SELECT month + 1 + FROM Calendar + WHERE month < 12 + ) +SELECT + Calendar.month, + IFNULL( + ROUND( + ( + SELECT COUNT(DISTINCT AcceptedRides.driver_id) + FROM AcceptedRides + INNER JOIN Rides + USING (ride_id) + WHERE + YEAR(Rides.requested_at) = '2020' + AND MONTH(Rides.requested_at) = Calendar.month + ) / ( + SELECT COUNT(*) + FROM Drivers + WHERE YEAR(Drivers.join_date) < '2020' + OR ( + YEAR(Drivers.join_date) = '2020' + AND MONTH(Drivers.join_date) <= Calendar.month) + ) * 100, + 2 + ), + 0 + ) AS working_percentage +FROM Calendar; diff --git a/solutions/1646. Get Maximum in Generated Array/1646.cpp b/solutions/1646. Get Maximum in Generated Array/1646.cpp new file mode 100644 index 00000000000..b61a26d80d7 --- /dev/null +++ b/solutions/1646. Get Maximum in Generated Array/1646.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int getMaximumGenerated(int n) { + if (n == 0) + return 0; + if (n == 1) + return 1; + + vector nums(n + 1); + nums[1] = 1; + + for (int i = 1; (2 * i + 1) <= n; ++i) { + nums[2 * i] = nums[i]; + nums[2 * i + 1] = nums[i] + nums[i + 1]; + } + + return ranges::max(nums); + } +}; diff --git a/solutions/1646. Get Maximum in Generated Array/1646.java b/solutions/1646. Get Maximum in Generated Array/1646.java new file mode 100644 index 00000000000..79d28427ec6 --- /dev/null +++ b/solutions/1646. Get Maximum in Generated Array/1646.java @@ -0,0 +1,18 @@ +class Solution { + public int getMaximumGenerated(int n) { + if (n == 0) + return 0; + if (n == 1) + return 1; + + int[] nums = new int[n + 1]; + nums[1] = 1; + + for (int i = 1; (2 * i + 1) <= n; ++i) { + nums[2 * i] = nums[i]; + nums[2 * i + 1] = nums[i] + nums[i + 1]; + } + + return Arrays.stream(nums).max().getAsInt(); + } +} diff --git a/solutions/1646. Get Maximum in Generated Array/1646.py b/solutions/1646. Get Maximum in Generated Array/1646.py new file mode 100644 index 00000000000..1224b0bf44d --- /dev/null +++ b/solutions/1646. Get Maximum in Generated Array/1646.py @@ -0,0 +1,17 @@ +class Solution: + def getMaximumGenerated(self, n: int) -> int: + if n == 0: + return 0 + if n == 1: + return 1 + + nums = [0] * (n + 1) + nums[1] = 1 + + i = 1 + while 2 * i + 1 <= n: + nums[2 * i] = nums[i] + nums[2 * i + 1] = nums[i] + nums[i + 1] + i += 1 + + return max(nums) diff --git a/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.cpp b/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.cpp new file mode 100644 index 00000000000..282eba010e1 --- /dev/null +++ b/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minDeletions(string s) { + int ans = 0; + vector count(26); + unordered_set usedFreq; + + for (const char c : s) + ++count[c - 'a']; + + for (int freq : count) + while (freq > 0 && !usedFreq.insert(freq).second) { + --freq; // Delete ('a' + i). + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.java b/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.java new file mode 100644 index 00000000000..423f1cb6e2a --- /dev/null +++ b/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.java @@ -0,0 +1,20 @@ +class Solution { + public int minDeletions(String s) { + int ans = 0; + int[] count = new int[26]; + Set usedFreq = new HashSet<>(); + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (int freq : count) { + while (freq > 0 && usedFreq.contains(freq)) { + --freq; // Delete ('a' + i). + ++ans; + } + usedFreq.add(freq); + } + + return ans; + } +} diff --git a/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.py b/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.py new file mode 100644 index 00000000000..98e5af148b6 --- /dev/null +++ b/solutions/1647. Minimum Deletions to Make Character Frequencies Unique/1647.py @@ -0,0 +1,13 @@ +class Solution: + def minDeletions(self, s: str) -> int: + ans = 0 + count = collections.Counter(s) + usedFreq = set() + + for freq in count.values(): + while freq > 0 and freq in usedFreq: + freq -= 1 # Delete ('a' + i). + ans += 1 + usedFreq.add(freq) + + return ans diff --git a/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.cpp b/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.cpp new file mode 100644 index 00000000000..ef0ff8851a8 --- /dev/null +++ b/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int maxProfit(vector& inventory, int orders) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + long largestCount = 1; + + ranges::sort(inventory, greater<>()); + + for (int i = 0; i < inventory.size(); ++i, ++largestCount) + if (i == inventory.size() - 1 || inventory[i] > inventory[i + 1]) { + // If we are at the last inventory, or inventory[i] > inventory[i + 1]. + // In either case, we will pick inventory[i - largestCount + 1..i]. + const int pick = (i == inventory.size() - 1) + ? inventory[i] + : inventory[i] - inventory[i + 1]; + if (largestCount * pick >= orders) { + // We have run out of orders, so we need to recalculate the number of + // balls that we actually pick for inventory[i - largestCount + 1..i]. + const int actualPick = orders / largestCount; + const int remaining = orders % largestCount; + return (ans + + largestCount * + trapezoid(inventory[i], inventory[i] - actualPick + 1) + + remaining * static_cast(inventory[i] - actualPick)) % + kMod; + } + ans += largestCount * trapezoid(inventory[i], inventory[i] - pick + 1); + ans %= kMod; + orders -= largestCount * pick; + } + + throw; + } + + private: + long trapezoid(long a, long b) { + return (a + b) * (a - b + 1) / 2; + } +}; diff --git a/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.java b/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.java new file mode 100644 index 00000000000..f529047ce30 --- /dev/null +++ b/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.java @@ -0,0 +1,35 @@ +class Solution { + public int maxProfit(int[] inventory, int orders) { + final int kMod = 1_000_000_007; + long ans = 0; + long largestCount = 1; + + Arrays.sort(inventory); + + for (int i = inventory.length - 1; i >= 0; --i, ++largestCount) + if (i == 0 || inventory[i] > inventory[i - 1]) { + // If we are at the first inventory, or inventory[i] > inventory[i + 1]. + // In either case, we will pick inventory[i..i + largestCount - 1]. + final long pick = (i == 0) ? inventory[i] : inventory[i] - inventory[i - 1]; + if (largestCount * pick >= orders) { + // We have run out of orders, so we need to recalculate the number of + // balls that we actually pick for inventory[i..i + largestCount - 1]. + final long actualPick = orders / largestCount; + final long remaining = orders % largestCount; + return (int) ((ans + + largestCount * trapezoid(inventory[i], inventory[i] - actualPick + 1) + + remaining * (inventory[i] - actualPick)) % + kMod); + } + ans += largestCount * trapezoid(inventory[i], inventory[i] - pick + 1); + ans %= kMod; + orders -= largestCount * pick; + } + + throw new IllegalArgumentException(); + } + + private long trapezoid(long a, long b) { + return (a + b) * (a - b + 1) / 2; + } +} diff --git a/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.py b/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.py new file mode 100644 index 00000000000..b62dd13b41a --- /dev/null +++ b/solutions/1648. Sell Diminishing-Valued Colored Balls/1648.py @@ -0,0 +1,25 @@ +class Solution: + def maxProfit(self, inventory: List[int], orders: int) -> int: + kMod = 1_000_000_007 + ans = 0 + largestCount = 1 + + def trapezoid(a: int, b: int) -> int: + return (a + b) * (a - b + 1) // 2 + + for a, b in itertools.pairwise(sorted(inventory, reverse=True) + [0]): + if a > b: + # If we are at the last inventory, or inventory[i] > inventory[i + 1]. + # In either case, we will pick inventory[i - largestCount + 1..i]. + pick = a - b + # We have run out of orders, so we need to recalculate the number of + # balls that we actually pick for inventory[i - largestCount + 1..i]. + if largestCount * pick >= orders: + actualPick, remaining = divmod(orders, largestCount) + return (ans + + largestCount * trapezoid(a, a - actualPick + 1) + + remaining * (a - actualPick)) % kMod + ans += largestCount * trapezoid(a, a - pick + 1) + ans %= kMod + orders -= largestCount * pick + largestCount += 1 diff --git a/solutions/1649. Create Sorted Array through Instructions/1649-2.cpp b/solutions/1649. Create Sorted Array through Instructions/1649-2.cpp new file mode 100644 index 00000000000..35d139f0e82 --- /dev/null +++ b/solutions/1649. Create Sorted Array through Instructions/1649-2.cpp @@ -0,0 +1,89 @@ +template +class SegmentTree { + public: + explicit SegmentTree(const int n, const NodeType& defaultNode) + : n(n), defaultNode(defaultNode), tree(4 * n) {} + + // Adds nums[i] to val equivalently. + void add(int i, ValueType val) { + add(0, 0, n - 1, i, val); + } + + // Returns the result of the range query from nums[i..j]. + NodeType query(int i, int j) const { + return query(0, 0, n - 1, i, j); + } + + protected: + // Merges the result of the left node and the right node. + virtual NodeType merge(const NodeType& a, const NodeType& b) const = 0; + virtual NodeType makeLeafNode(ValueType val) const = 0; + + private: + const int n; // the size of the input array + const NodeType defaultNode; // default node value for non-overlapping queries + vector tree; // the segment tree + + void add(int treeIndex, int lo, int hi, int i, ValueType val) { + if (lo == hi) { + tree[treeIndex] += makeLeafNode(val); + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + add(left(treeIndex), lo, mid, i, val); + else + add(right(treeIndex), mid + 1, hi, i, val); + tree[treeIndex] = merge(tree[left(treeIndex)], tree[right(treeIndex)]); + } + + NodeType query(int treeIndex, int lo, int hi, int i, int j) const { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return defaultNode; + const int mid = (lo + hi) / 2; + return merge(query(left(treeIndex), lo, mid, i, j), + query(right(treeIndex), mid + 1, hi, i, j)); + } + + int left(int treeIndex) const { + return 2 * treeIndex + 1; + } + + int right(int treeIndex) const { + return 2 * treeIndex + 2; + } +}; + +class SumSegmentTree : public SegmentTree { + public: + explicit SumSegmentTree(int n) : SegmentTree(n, 0) {} + + protected: + int merge(const int& a, const int& b) const override { + return a + b; + } + + int makeLeafNode(int val) const override { + return val; + } +}; + +class Solution { + public: + int createSortedArray(vector& instructions) { + constexpr int kMod = 1'000'000'007; + const int mx = ranges::max(instructions); + int ans = 0; + SumSegmentTree tree(mx + 1); + + for (const int i : instructions) { + ans += min(tree.query(0, i - 1), tree.query(i + 1, mx)); + ans %= kMod; + tree.add(i, 1); + } + + return ans; + } +}; diff --git a/solutions/1649. Create Sorted Array through Instructions/1649-3.cpp b/solutions/1649. Create Sorted Array through Instructions/1649-3.cpp new file mode 100644 index 00000000000..465bebfeddd --- /dev/null +++ b/solutions/1649. Create Sorted Array through Instructions/1649-3.cpp @@ -0,0 +1,78 @@ +struct Item { + int num; + int index; +}; + +class Solution { + public: + int createSortedArray(vector& instructions) { + constexpr int kMod = 1'000'000'007; + const int n = instructions.size(); + int ans = 0; + vector items; + // lesser[i] := the number of numbers < instructions[i] + vector lesser(n); + // greater[i] := the number of numbers > instructions[i] + vector greater(n); + + for (int i = 0; i < n; ++i) + items.push_back({instructions[i], i}); + + mergeSort(items, 0, n - 1, lesser, greater); + + for (int i = 0; i < n; ++i) { + ans += min(lesser[i], greater[i]); + ans %= kMod; + } + + return ans; + } + + private: + void mergeSort(vector& items, int l, int r, vector& lesser, + vector& greater) { + if (l >= r) + return; + + const int m = (l + r) / 2; + mergeSort(items, l, m, lesser, greater); + mergeSort(items, m + 1, r, lesser, greater); + merge(items, l, m, r, lesser, greater); + } + + void merge(vector& items, int l, int m, int r, vector& lesser, + vector& greater) { + int lo = l; // the first index s.t. items[lo].num >= items[i].num + int hi = l; // the first index s.t. items[hi].num > items[i].num + + for (int i = m + 1; i <= r; ++i) { + while (lo <= m && items[lo].num < items[i].num) + ++lo; + while (hi <= m && items[hi].num <= items[i].num) + ++hi; + lesser[items[i].index] += lo - l; + greater[items[i].index] += m - hi + 1; + } + + vector sorted(r - l + 1); + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + + while (i <= m && j <= r) + if (items[i].num < items[j].num) + sorted[k++] = items[i++]; + else + sorted[k++] = items[j++]; + + // Put the possible remaining left part into the sorted array. + while (i <= m) + sorted[k++] = items[i++]; + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = items[j++]; + + copy(sorted.begin(), sorted.end(), items.begin() + l); + } +}; diff --git a/solutions/1649. Create Sorted Array through Instructions/1649.cpp b/solutions/1649. Create Sorted Array through Instructions/1649.cpp new file mode 100644 index 00000000000..3f5099f6580 --- /dev/null +++ b/solutions/1649. Create Sorted Array through Instructions/1649.cpp @@ -0,0 +1,45 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + int createSortedArray(vector& instructions) { + constexpr int kMod = 1'000'000'007; + const int mx = ranges::max(instructions); + int ans = 0; + FenwickTree tree(mx); + + for (int i = 0; i < instructions.size(); ++i) { + ans += min(tree.get(instructions[i] - 1), i - tree.get(instructions[i])); + ans %= kMod; + tree.add(instructions[i], 1); + } + + return ans; + } +}; diff --git a/solutions/165. Compare Version Numbers/165.cpp b/solutions/165. Compare Version Numbers/165.cpp new file mode 100644 index 00000000000..1fc37041726 --- /dev/null +++ b/solutions/165. Compare Version Numbers/165.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int compareVersion(string version1, string version2) { + istringstream iss1(version1); + istringstream iss2(version2); + int v1; + int v2; + char dotChar; + + while (bool(iss1 >> v1) + bool(iss2 >> v2)) { + if (v1 < v2) + return -1; + if (v1 > v2) + return 1; + iss1 >> dotChar; + iss2 >> dotChar; + v1 = 0; + v2 = 0; + } + + return 0; + }; +}; diff --git a/solutions/165. Compare Version Numbers/165.java b/solutions/165. Compare Version Numbers/165.java new file mode 100644 index 00000000000..4a308773c85 --- /dev/null +++ b/solutions/165. Compare Version Numbers/165.java @@ -0,0 +1,17 @@ +class Solution { + public int compareVersion(String version1, String version2) { + final String[] levels1 = version1.split("\\."); + final String[] levels2 = version2.split("\\."); + final int length = Math.max(levels1.length, levels2.length); + + for (int i = 0; i < length; ++i) { + final Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0; + final Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0; + final int compare = v1.compareTo(v2); + if (compare != 0) + return compare; + } + + return 0; + } +} diff --git a/solutions/165. Compare Version Numbers/165.py b/solutions/165. Compare Version Numbers/165.py new file mode 100644 index 00000000000..48c27d7ff3f --- /dev/null +++ b/solutions/165. Compare Version Numbers/165.py @@ -0,0 +1,15 @@ +class Solution: + def compareVersion(self, version1: str, version2: str) -> int: + levels1 = version1.split('.') + levels2 = version2.split('.') + length = max(len(levels1), len(levels2)) + + for i in range(length): + v1 = int(levels1[i]) if i < len(levels1) else 0 + v2 = int(levels2[i]) if i < len(levels2) else 0 + if v1 < v2: + return -1 + if v1 > v2: + return 1 + + return 0 diff --git a/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.cpp b/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.cpp new file mode 100644 index 00000000000..e2800532fbb --- /dev/null +++ b/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + // Same as 160. Intersection of Two Linked Lists + Node* lowestCommonAncestor(Node* p, Node* q) { + Node* a = p; + Node* b = q; + + while (a != b) { + a = a == nullptr ? q : a->parent; + b = b == nullptr ? p : b->parent; + } + + return a; + } +}; diff --git a/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.java b/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.java new file mode 100644 index 00000000000..f0b02878623 --- /dev/null +++ b/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.java @@ -0,0 +1,14 @@ +class Solution { + // Same as 160. Intersection of Two Linked Lists + public Node lowestCommonAncestor(Node p, Node q) { + Node a = p; + Node b = q; + + while (a != b) { + a = a == null ? q : a.parent; + b = b == null ? p : b.parent; + } + + return a; + } +} diff --git a/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.py b/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.py new file mode 100644 index 00000000000..23bdb723801 --- /dev/null +++ b/solutions/1650. Lowest Common Ancestor of a Binary Tree III/1650.py @@ -0,0 +1,11 @@ +class Solution: + # Same as 160. Intersection of Two Linked Lists + def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node': + a = p + b = q + + while a != b: + a = a.parent if a else q + b = b.parent if b else p + + return a diff --git a/solutions/1651. Hopper Company Queries III/1651.sql b/solutions/1651. Hopper Company Queries III/1651.sql new file mode 100644 index 00000000000..fff37026707 --- /dev/null +++ b/solutions/1651. Hopper Company Queries III/1651.sql @@ -0,0 +1,49 @@ +WITH + RECURSIVE Calendar AS ( + SELECT 2 AS MONTH + UNION ALL + SELECT MONTH + 1 + FROM Calendar + WHERE MONTH < 11 + ) +SELECT + Calendar.month - 1 AS MONTH, + IFNULL( + ROUND( + ( + SELECT SUM(AcceptedRides.ride_distance) + FROM Rides + INNER JOIN AcceptedRides + USING (ride_id) + WHERE + YEAR(Rides.requested_at) = '2020' + AND MONTH(Rides.requested_at) IN ( + Calendar.month - 1, + Calendar.month, + Calendar.month + 1 + ) + ) / 3, + 2 + ), + 0 + ) AS average_ride_distance, + IFNULL( + ROUND( + ( + SELECT SUM(AcceptedRides.ride_duration) + FROM Rides + INNER JOIN AcceptedRides + USING (ride_id) + WHERE + YEAR(Rides.requested_at) = '2020' + AND MONTH(Rides.requested_at) IN ( + Calendar.month - 1, + Calendar.month, + Calendar.month + 1 + ) + ) / 3, + 2 + ), + 0 + ) AS average_ride_duration +FROM Calendar; diff --git a/solutions/1652. Defuse the Bomb/1652.cpp b/solutions/1652. Defuse the Bomb/1652.cpp new file mode 100644 index 00000000000..4bc8735bd52 --- /dev/null +++ b/solutions/1652. Defuse the Bomb/1652.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector decrypt(vector& code, int k) { + const int n = code.size(); + vector ans(n); + if (k == 0) + return ans; + + int sum = 0; + int start = k > 0 ? 1 : n + k; // the start of the next k numbers + int end = k > 0 ? k : n - 1; // the end of the next k numbers + + for (int i = start; i <= end; ++i) + sum += code[i]; + + for (int i = 0; i < n; ++i) { + ans[i] = sum; + sum -= code[start++ % n]; + sum += code[++end % n]; + } + + return ans; + } +}; diff --git a/solutions/1652. Defuse the Bomb/1652.java b/solutions/1652. Defuse the Bomb/1652.java new file mode 100644 index 00000000000..06a00a584c0 --- /dev/null +++ b/solutions/1652. Defuse the Bomb/1652.java @@ -0,0 +1,23 @@ +class Solution { + public int[] decrypt(int[] code, int k) { + final int n = code.length; + int[] ans = new int[n]; + if (k == 0) + return ans; + + int sum = 0; + int start = k > 0 ? 1 : n + k; // the start of the next k numbers + int end = k > 0 ? k : n - 1; // the end of the next k numbers + + for (int i = start; i <= end; ++i) + sum += code[i]; + + for (int i = 0; i < n; ++i) { + ans[i] = sum; + sum -= code[start++ % n]; + sum += code[++end % n]; + } + + return ans; + } +} diff --git a/solutions/1652. Defuse the Bomb/1652.py b/solutions/1652. Defuse the Bomb/1652.py new file mode 100644 index 00000000000..701f04e9034 --- /dev/null +++ b/solutions/1652. Defuse the Bomb/1652.py @@ -0,0 +1,22 @@ +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + ans = [0] * n + if k == 0: + return ans + + summ = 0 + start = 1 if k > 0 else n + k # the start of the next k numbers + end = k if k > 0 else n - 1 # the end of the next k numbers + + for i in range(start, end + 1): + summ += code[i] + + for i in range(n): + ans[i] = summ + summ -= code[start % n] + start += 1 + end += 1 + summ += code[end % n] + + return ans diff --git a/solutions/1653. Minimum Deletions to Make String Balanced/1653.cpp b/solutions/1653. Minimum Deletions to Make String Balanced/1653.cpp new file mode 100644 index 00000000000..6f08292df15 --- /dev/null +++ b/solutions/1653. Minimum Deletions to Make String Balanced/1653.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + // Same as 926. Flip String to Monotone Increasing + int minimumDeletions(string s) { + // the number of characters to be deleted to make the substring so far + // balanced + int dp = 0; + int countB = 0; + + for (const char c : s) + if (c == 'a') + // 1. Delete 'a'. + // 2. Keep 'a' and delete the previous 'b's. + dp = min(dp + 1, countB); + else + ++countB; + + return dp; + } +}; diff --git a/solutions/1653. Minimum Deletions to Make String Balanced/1653.java b/solutions/1653. Minimum Deletions to Make String Balanced/1653.java new file mode 100644 index 00000000000..250de1f22cd --- /dev/null +++ b/solutions/1653. Minimum Deletions to Make String Balanced/1653.java @@ -0,0 +1,18 @@ +class Solution { + // Same as 926. Flip String to Monotone Increasing + public int minimumDeletions(String s) { + // the number of characters to be deleted to make subString so far balanced + int dp = 0; + int countB = 0; + + for (final char c : s.toCharArray()) + if (c == 'a') + // 1. Delete 'a'. + // 2. Keep 'a' and delete the previous 'b's. + dp = Math.min(dp + 1, countB); + else + ++countB; + + return dp; + } +} diff --git a/solutions/1653. Minimum Deletions to Make String Balanced/1653.py b/solutions/1653. Minimum Deletions to Make String Balanced/1653.py new file mode 100644 index 00000000000..5bfd6dbcc29 --- /dev/null +++ b/solutions/1653. Minimum Deletions to Make String Balanced/1653.py @@ -0,0 +1,15 @@ +class Solution: + # Same as 926. Flip String to Monotone Increasing + def minimumDeletions(self, s: str) -> int: + dp = 0 # the number of characters to be deleted to make subso far balanced + countB = 0 + + for c in s: + if c == 'a': + # 1. Delete 'a'. + # 2. Keep 'a' and delete the previous 'b's. + dp = min(dp + 1, countB) + else: + countB += 1 + + return dp diff --git a/solutions/1654. Minimum Jumps to Reach Home/1654.cpp b/solutions/1654. Minimum Jumps to Reach Home/1654.cpp new file mode 100644 index 00000000000..6aac9af2a48 --- /dev/null +++ b/solutions/1654. Minimum Jumps to Reach Home/1654.cpp @@ -0,0 +1,37 @@ +enum class Direction { kForward, kBackward }; + +class Solution { + public: + int minimumJumps(vector& forbidden, int a, int b, int x) { + int furthest = x + a + b; + unordered_set seenForward; + unordered_set seenBackward; + + for (const int pos : forbidden) { + seenForward.insert(pos); + seenBackward.insert(pos); + furthest = max(furthest, pos + a + b); + } + + // (direction, position) + queue> q{{{Direction::kForward, 0}}}; + + for (int ans = 0; !q.empty(); ++ans) + for (int sz = q.size(); sz > 0; --sz) { + const auto [dir, pos] = q.front(); + q.pop(); + if (pos == x) + return ans; + const int forward = pos + a; + const int backward = pos - b; + if (forward <= furthest && seenForward.insert(forward).second) + q.emplace(Direction::kForward, forward); + // It cannot jump backward twice in a row. + if (dir == Direction::kForward && backward >= 0 && + seenBackward.insert(backward).second) + q.emplace(Direction::kBackward, backward); + } + + return -1; + } +}; diff --git a/solutions/1654. Minimum Jumps to Reach Home/1654.java b/solutions/1654. Minimum Jumps to Reach Home/1654.java new file mode 100644 index 00000000000..9969972556d --- /dev/null +++ b/solutions/1654. Minimum Jumps to Reach Home/1654.java @@ -0,0 +1,36 @@ +enum Direction { kForward, kBackward } + +class Solution { + public int minimumJumps(int[] forbidden, int a, int b, int x) { + int furthest = x + a + b; + Set seenForward = new HashSet<>(); + Set seenBackward = new HashSet<>(); + + for (final int pos : forbidden) { + seenForward.add(pos); + seenBackward.add(pos); + furthest = Math.max(furthest, pos + a + b); + } + + // (direction, position) + Queue> q = + new ArrayDeque<>(Arrays.asList(new Pair<>(Direction.kForward, 0))); + + for (int ans = 0; !q.isEmpty(); ++ans) + for (int sz = q.size(); sz > 0; --sz) { + Direction dir = q.peek().getKey(); + final int pos = q.poll().getValue(); + if (pos == x) + return ans; + final int forward = pos + a; + final int backward = pos - b; + if (forward <= furthest && seenForward.add(forward)) + q.offer(new Pair<>(Direction.kForward, forward)); + // It cannot jump backward twice in a row. + if (dir == Direction.kForward && backward >= 0 && seenBackward.add(backward)) + q.offer(new Pair<>(Direction.kBackward, backward)); + } + + return -1; + } +} diff --git a/solutions/1654. Minimum Jumps to Reach Home/1654.py b/solutions/1654. Minimum Jumps to Reach Home/1654.py new file mode 100644 index 00000000000..7be93bdd502 --- /dev/null +++ b/solutions/1654. Minimum Jumps to Reach Home/1654.py @@ -0,0 +1,35 @@ +from enum import Enum + + +class Direction(Enum): + kForward = 0 + kBackward = 1 + + +class Solution: + def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: + furthest = max(x + a + b, max(pos + a + b for pos in forbidden)) + seenForward = {pos for pos in forbidden} + seenBackward = {pos for pos in forbidden} + + # (direction, position) + q = collections.deque([(Direction.kForward, 0)]) + + ans = 0 + while q: + for _ in range(len(q)): + dir, pos = q.popleft() + if pos == x: + return ans + forward = pos + a + backward = pos - b + if forward <= furthest and forward not in seenForward: + seenForward.add(forward) + q.append((Direction.kForward, forward)) + # It cannot jump backward twice in a row. + if dir == Direction.kForward and backward >= 0 and backward not in seenBackward: + seenBackward.add(backward) + q.append((Direction.kBackward, backward)) + ans += 1 + + return -1 diff --git a/solutions/1655. Distribute Repeating Integers/1655.cpp b/solutions/1655. Distribute Repeating Integers/1655.cpp new file mode 100644 index 00000000000..79d504b75a1 --- /dev/null +++ b/solutions/1655. Distribute Repeating Integers/1655.cpp @@ -0,0 +1,60 @@ +class Solution { + public: + bool canDistribute(vector& nums, vector& quantity) { + // validDistribution[i][j] := true if it's possible to distribute the i-th + // freq into a subset of quantity represented by the bitmask j + const vector freqs = getFreqs(nums); + const vector> validDistribution = + getValidDistribuition(freqs, quantity); + const int n = freqs.size(); + const int m = quantity.size(); + const int maxMask = 1 << m; + // dp[i][j] := true if it's possible to distribute freqs[i..n), where j is + // the bitmask of the selected quantity + vector> dp(n + 1, vector(maxMask)); + dp[n][maxMask - 1] = true; + + for (int i = n - 1; i >= 0; --i) + for (int mask = 0; mask < maxMask; ++mask) { + dp[i][mask] = dp[i + 1][mask]; + const int availableMask = ~mask & (maxMask - 1); + for (int submask = availableMask; submask > 0; + submask = (submask - 1) & availableMask) + if (validDistribution[i][submask]) + dp[i][mask] = dp[i][mask] || dp[i + 1][mask | submask]; + } + + return dp[0][0]; + } + + private: + vector getFreqs(const vector& nums) { + vector freqs; + unordered_map count; + for (const int num : nums) + ++count[num]; + for (const auto& [_, freq] : count) + freqs.push_back(freq); + return freqs; + } + + vector> getValidDistribuition(const vector& freqs, + const vector& quantity) { + const int maxMask = 1 << quantity.size(); + vector> validDistribution(freqs.size(), vector(maxMask)); + for (int i = 0; i < freqs.size(); ++i) + for (int mask = 0; mask < maxMask; ++mask) + if (freqs[i] >= getQuantitySum(quantity, mask)) + validDistribution[i][mask] = true; + return validDistribution; + } + + // Returns the sum of the selected quantity represented by `mask`. + int getQuantitySum(const vector& quantity, int mask) { + int sum = 0; + for (int i = 0; i < quantity.size(); ++i) + if (mask >> i & 1) + sum += quantity[i]; + return sum; + } +}; diff --git a/solutions/1655. Distribute Repeating Integers/1655.java b/solutions/1655. Distribute Repeating Integers/1655.java new file mode 100644 index 00000000000..1cc2d004903 --- /dev/null +++ b/solutions/1655. Distribute Repeating Integers/1655.java @@ -0,0 +1,53 @@ +class Solution { + public boolean canDistribute(int[] nums, int[] quantity) { + List freqs = getFreqs(nums); + // validDistribution[i][j] := true if it's possible to distribute the i-th + // freq into a subset of quantity represented by the bitmask j + boolean[][] validDistribution = getValidDistribution(freqs, quantity); + final int n = freqs.size(); + final int m = quantity.length; + final int maxMask = 1 << m; + // dp[i][j] := true if it's possible to distribute freqs[i..n), where j is + // the bitmask of the selected quantity + boolean[][] dp = new boolean[n + 1][maxMask]; + dp[n][maxMask - 1] = true; + + for (int i = n - 1; i >= 0; --i) + for (int mask = 0; mask < maxMask; ++mask) { + dp[i][mask] = dp[i + 1][mask]; + final int availableMask = ~mask & (maxMask - 1); + for (int submask = availableMask; submask > 0; submask = (submask - 1) & availableMask) + if (validDistribution[i][submask]) + dp[i][mask] = dp[i][mask] || dp[i + 1][mask | submask]; + } + + return dp[0][0]; + } + + private List getFreqs(int[] nums) { + List freqs = new ArrayList<>(); + Map count = new HashMap<>(); + for (final int num : nums) + count.merge(num, 1, Integer::sum); + return new ArrayList<>(count.values()); + } + + boolean[][] getValidDistribution(List freqs, int[] quantity) { + final int maxMask = 1 << quantity.length; + boolean[][] validDistribution = new boolean[freqs.size()][maxMask]; + for (int i = 0; i < freqs.size(); ++i) + for (int mask = 0; mask < maxMask; ++mask) + if (freqs.get(i) >= getQuantitySum(quantity, mask)) + validDistribution[i][mask] = true; + return validDistribution; + } + + // Returns the sum of the selected quantity represented by `mask`. + int getQuantitySum(int[] quantity, int mask) { + int sum = 0; + for (int i = 0; i < quantity.length; ++i) + if ((mask >> i & 1) == 1) + sum += quantity[i]; + return sum; + } +} diff --git a/solutions/1655. Distribute Repeating Integers/1655.py b/solutions/1655. Distribute Repeating Integers/1655.py new file mode 100644 index 00000000000..b3d4a1d700c --- /dev/null +++ b/solutions/1655. Distribute Repeating Integers/1655.py @@ -0,0 +1,38 @@ +class Solution: + def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: + freqs = list(collections.Counter(nums).values()) + # validDistribution[i][j] := True if it's possible to distribute the i-th + # freq into a subset of quantity represented by the bitmask j + validDistribution = self._getValidDistribution(freqs, quantity) + n = len(freqs) + m = len(quantity) + maxMask = 1 << m + # dp[i][j] := true if it's possible to distribute freqs[i..n), where j is + # the bitmask of the selected quantity + dp = [[False] * maxMask for _ in range(n + 1)] + dp[n][maxMask - 1] = True + + for i in range(n - 1, -1, -1): + for mask in range(maxMask): + dp[i][mask] = dp[i + 1][mask] + availableMask = ~mask & (maxMask - 1) + submask = availableMask + while submask > 0: + if validDistribution[i][submask]: + dp[i][mask] = dp[i][mask] or dp[i + 1][mask | submask] + submask = (submask - 1) & availableMask + + return dp[0][0] + + def _getValidDistribution(self, freqs: List[int], quantity: List[int]) -> List[List[bool]]: + maxMask = 1 << len(quantity) + validDistribution = [[False] * maxMask for _ in range(len(freqs))] + for i, freq in enumerate(freqs): + for mask in range(maxMask): + if freq >= self._getQuantitySum(quantity, mask): + validDistribution[i][mask] = True + return validDistribution + + def _getQuantitySum(self, quantity: List[int], mask: int) -> int: + """Returns the sum of the selected quantity represented by `mask`.""" + return sum(q for i, q in enumerate(quantity) if mask >> i & 1) diff --git a/solutions/1656. Design an Ordered Stream/1656.cpp b/solutions/1656. Design an Ordered Stream/1656.cpp new file mode 100644 index 00000000000..c2bdba3567a --- /dev/null +++ b/solutions/1656. Design an Ordered Stream/1656.cpp @@ -0,0 +1,18 @@ +class OrderedStream { + public: + OrderedStream(int n) : values(n) {} + + vector insert(int idKey, string value) { + --idKey; // Converts to 0-indexed. + values[idKey] = value; + if (idKey > i) + return {}; + while (i < values.size() && !values[i].empty()) + ++i; + return vector{values.begin() + idKey, values.begin() + i}; + } + + private: + vector values; + int i = 0; // values' index (0-indexed) +}; diff --git a/solutions/1656. Design an Ordered Stream/1656.java b/solutions/1656. Design an Ordered Stream/1656.java new file mode 100644 index 00000000000..2e61f4ed004 --- /dev/null +++ b/solutions/1656. Design an Ordered Stream/1656.java @@ -0,0 +1,21 @@ +class OrderedStream { + public OrderedStream(int n) { + this.values = new String[n]; + } + + public List insert(int idKey, String value) { + --idKey; // Converts to 0-indexed + values[idKey] = value; + if (idKey > i) + return new ArrayList<>(); + while (i < values.length && values[i] != null && !values[i].isEmpty()) + i++; + List res = new ArrayList<>(); + for (int j = idKey; j < i; ++j) + res.add(values[j]); + return res; + } + + private String[] values; + private int i = 0; // values' index (0-indexed) +} diff --git a/solutions/1656. Design an Ordered Stream/1656.py b/solutions/1656. Design an Ordered Stream/1656.py new file mode 100644 index 00000000000..a050e641b41 --- /dev/null +++ b/solutions/1656. Design an Ordered Stream/1656.py @@ -0,0 +1,13 @@ +class OrderedStream: + def __init__(self, n: int): + self.values = [''] * n + self.i = 0 # self.values' index (0-indexed) + + def insert(self, idKey: int, value: str) -> List[str]: + idKey -= 1 # Converts to 0-indexed. + self.values[idKey] = value + if idKey > self.i: + return [] + while self.i < len(self.values) and self.values[self.i]: + self.i += 1 + return self.values[idKey:self.i] diff --git a/solutions/1657. Determine if Two Strings Are Close/1657.cpp b/solutions/1657. Determine if Two Strings Are Close/1657.cpp new file mode 100644 index 00000000000..08b190d937c --- /dev/null +++ b/solutions/1657. Determine if Two Strings Are Close/1657.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + bool closeStrings(string word1, string word2) { + if (word1.length() != word2.length()) + return false; + + unordered_map count1; + unordered_map count2; + string s1; // Unique chars in word1 + string s2; // Unique chars in word2 + vector freqs1; // Freqs of unique chars in word1 + vector freqs2; // Freqs of unique chars in word2 + + for (const char c : word1) + ++count1[c]; + + for (const char c : word2) + ++count2[c]; + + for (const auto& [c, freq] : count1) { + s1 += c; + freqs1.push_back(freq); + } + + for (const auto& [c, freq] : count2) { + s2 += c; + freqs2.push_back(freq); + } + + ranges::sort(s1); + ranges::sort(s2); + + if (s1 != s2) + return false; + + ranges::sort(freqs1); + ranges::sort(freqs2); + return freqs1 == freqs2; + } +}; diff --git a/solutions/1657. Determine if Two Strings Are Close/1657.java b/solutions/1657. Determine if Two Strings Are Close/1657.java new file mode 100644 index 00000000000..c066b8143d8 --- /dev/null +++ b/solutions/1657. Determine if Two Strings Are Close/1657.java @@ -0,0 +1,25 @@ +class Solution { + public boolean closeStrings(String word1, String word2) { + if (word1.length() != word2.length()) + return false; + + Map count1 = new HashMap<>(); + Map count2 = new HashMap<>(); + + for (final char c : word1.toCharArray()) + count1.merge(c, 1, Integer::sum); + + for (final char c : word2.toCharArray()) + count2.merge(c, 1, Integer::sum); + + if (!count1.keySet().equals(count2.keySet())) + return false; + + List freqs1 = new ArrayList<>(count1.values()); + List freqs2 = new ArrayList<>(count2.values()); + + Collections.sort(freqs1); + Collections.sort(freqs2); + return freqs1.equals(freqs2); + } +} diff --git a/solutions/1657. Determine if Two Strings Are Close/1657.py b/solutions/1657. Determine if Two Strings Are Close/1657.py new file mode 100644 index 00000000000..a780e43e3ec --- /dev/null +++ b/solutions/1657. Determine if Two Strings Are Close/1657.py @@ -0,0 +1,11 @@ +class Solution: + def closeStrings(self, word1: str, word2: str) -> bool: + if len(word1) != len(word2): + return False + + count1 = collections.Counter(word1) + count2 = collections.Counter(word2) + if count1.keys() != count2.keys(): + return False + + return sorted(count1.values()) == sorted(count2.values()) diff --git a/solutions/1658. Minimum Operations to Reduce X to Zero/1658.cpp b/solutions/1658. Minimum Operations to Reduce X to Zero/1658.cpp new file mode 100644 index 00000000000..2c835f908da --- /dev/null +++ b/solutions/1658. Minimum Operations to Reduce X to Zero/1658.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int minOperations(vector& nums, int x) { + const int targetSum = accumulate(nums.begin(), nums.end(), 0) - x; + if (targetSum == 0) + return nums.size(); + const int maxLen = maxSubArrayLen(nums, targetSum); + return maxLen == -1 ? -1 : nums.size() - maxLen; + } + + private: + // Same as 325. Maximum Size Subarray Sum Equals k + int maxSubArrayLen(vector& nums, int k) { + int res = -1; + int prefix = 0; + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i]; + const int target = prefix - k; + if (const auto it = prefixToIndex.find(target); + it != prefixToIndex.cend()) + res = max(res, i - it->second); + // No need to check the existence of the prefix since it's unique. + prefixToIndex[prefix] = i; + } + + return res; + } +}; diff --git a/solutions/1658. Minimum Operations to Reduce X to Zero/1658.java b/solutions/1658. Minimum Operations to Reduce X to Zero/1658.java new file mode 100644 index 00000000000..707e03fb33c --- /dev/null +++ b/solutions/1658. Minimum Operations to Reduce X to Zero/1658.java @@ -0,0 +1,28 @@ +class Solution { + public int minOperations(int[] nums, int x) { + final int targetSum = Arrays.stream(nums).sum() - x; + if (targetSum == 0) + return nums.length; + final int maxLen = maxSubArrayLen(nums, targetSum); + return maxLen == -1 ? -1 : nums.length - maxLen; + } + + // Same as 325. Maximum Size Subarray Sum Equals k + private int maxSubArrayLen(int[] nums, int k) { + int res = -1; + int prefix = 0; + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i]; + final int target = prefix - k; + if (prefixToIndex.containsKey(target)) + res = Math.max(res, i - prefixToIndex.get(target)); + // No need to check the existence of the prefix since it's unique. + prefixToIndex.put(prefix, i); + } + + return res; + } +} diff --git a/solutions/1658. Minimum Operations to Reduce X to Zero/1658.py b/solutions/1658. Minimum Operations to Reduce X to Zero/1658.py new file mode 100644 index 00000000000..c25ab5ba012 --- /dev/null +++ b/solutions/1658. Minimum Operations to Reduce X to Zero/1658.py @@ -0,0 +1,23 @@ +class Solution: + def minOperations(self, nums: List[int], x: int) -> int: + targetSum = sum(nums) - x + if targetSum == 0: + return len(nums) + maxLen = self._maxSubArrayLen(nums, targetSum) + return -1 if maxLen == -1 else len(nums) - maxLen + + # Same as 325. Maximum Size Subarray Sum Equals k + def _maxSubArrayLen(self, nums: List[int], k: int) -> int: + res = -1 + prefix = 0 + prefixToIndex = {0: -1} + + for i, num in enumerate(nums): + prefix += num + target = prefix - k + if target in prefixToIndex: + res = max(res, i - prefixToIndex[target]) + # No need to check the existence of the prefix since it's unique. + prefixToIndex[prefix] = i + + return res diff --git a/solutions/1659. Maximize Grid Happiness/1659.cpp b/solutions/1659. Maximize Grid Happiness/1659.cpp new file mode 100644 index 00000000000..3e26ad8d829 --- /dev/null +++ b/solutions/1659. Maximize Grid Happiness/1659.cpp @@ -0,0 +1,78 @@ +class Solution { + public: + int getMaxGridHappiness(int m, int n, int introvertsCount, + int extrovertsCount) { + const int twoToThePowerOfN = pow(2, n); + vector>>>> mem( + m * n, vector>>>( + twoToThePowerOfN, + vector>>( + twoToThePowerOfN, + vector>(introvertsCount + 1, + vector(extrovertsCount + 1))))); + return getMaxGridHappiness(m, n, 0, 0, 0, introvertsCount, extrovertsCount, + mem); + } + + private: + // Calculates the cost based on left and up neighbors. + // + // The `diff` parameter represents the happiness change due to the current + // placed person in (i, j). We add `diff` each time we encounter a neighbor + // (left or up) who is already placed. + // + // 1. If the neighbor is an introvert, we subtract 30 from cost. + // 2. If the neighbor is an extrovert, we add 20 to from cost. + int getPlacementCost(int n, int i, int j, int inMask, int exMask, int diff) { + int cost = 0; + if (i > 0) { + if ((1 << (n - 1)) & inMask) + cost += diff - 30; + if ((1 << (n - 1)) & exMask) + cost += diff + 20; + } + if (j > 0) { + if (1 & inMask) + cost += diff - 30; + if (1 & exMask) + cost += diff + 20; + } + return cost; + } + + int getMaxGridHappiness(int m, int n, int pos, int inMask, int exMask, + int inCount, int exCount, + vector>>>>& mem) { + // `inMask` is the placement of introvert people in the last n cells. + // e.g. if we have m = 2, n = 3, i = 1, j = 1, then inMask = 0b101 means + // + // ? 1 0 + // 1 x ? (x := current position) + const int i = pos / n; + const int j = pos % n; + if (i == m) + return 0; + if (mem[pos][inMask][exMask][inCount][exCount] > 0) + return mem[pos][inMask][exMask][inCount][exCount]; + + const int shiftedInMask = (inMask << 1) & ((1 << n) - 1); + const int shiftedExMask = (exMask << 1) & ((1 << n) - 1); + + const int skip = getMaxGridHappiness(m, n, pos + 1, shiftedInMask, + shiftedExMask, inCount, exCount, mem); + const int placeIntrovert = + inCount > 0 + ? 120 + getPlacementCost(n, i, j, inMask, exMask, -30) + + getMaxGridHappiness(m, n, pos + 1, shiftedInMask | 1, + shiftedExMask, inCount - 1, exCount, mem) + : INT_MIN; + const int placeExtrovert = + exCount > 0 ? 40 + getPlacementCost(n, i, j, inMask, exMask, 20) + + getMaxGridHappiness(m, n, pos + 1, shiftedInMask, + shiftedExMask | 1, inCount, + exCount - 1, mem) + : INT_MIN; + return mem[pos][inMask][exMask][inCount][exCount] = + max({skip, placeIntrovert, placeExtrovert}); + } +}; diff --git a/solutions/1659. Maximize Grid Happiness/1659.java b/solutions/1659. Maximize Grid Happiness/1659.java new file mode 100644 index 00000000000..7105d3a8e93 --- /dev/null +++ b/solutions/1659. Maximize Grid Happiness/1659.java @@ -0,0 +1,66 @@ +public class Solution { + public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + final int twoToThePowerOfN = (int) Math.pow(2, n); + int[][][][][] mem = new int[m * n][twoToThePowerOfN][twoToThePowerOfN][introvertsCount + 1] + [extrovertsCount + 1]; + return getMaxGridHappiness(m, n, 0, 0, 0, introvertsCount, extrovertsCount, mem); + } + + // Calculates the cost based on left and up neighbors. + // + // The `diff` parameter represents the happiness change due to the current + // placed person in (i, j). We add `diff` each time we encounter a neighbor + // (left or up) who is already placed. + // + // 1. If the neighbor is an introvert, we subtract 30 from cost. + // 2. If the neighbor is an extrovert, we add 20 to from cost. + private int getPlacementCost(int n, int i, int j, int inMask, int exMask, int diff) { + int cost = 0; + if (i > 0) { + if (((1 << (n - 1)) & inMask) > 0) + cost += diff - 30; + if (((1 << (n - 1)) & exMask) > 0) + cost += diff + 20; + } + if (j > 0) { + if ((1 & inMask) > 0) + cost += diff - 30; + if ((1 & exMask) > 0) + cost += diff + 20; + } + return cost; + } + + private int getMaxGridHappiness(int m, int n, int pos, int inMask, int exMask, int inCount, + int exCount, int[][][][][] mem) { + // `inMask` is the placement of introvert people in the last n cells. + // e.g. if we have m = 2, n = 3, i = 1, j = 1, then inMask = 0b101 means + // + // ? 1 0 + // 1 x ? (x := current position) + final int i = pos / n; + final int j = pos % n; + if (i == m) + return 0; + if (mem[pos][inMask][exMask][inCount][exCount] > 0) + return mem[pos][inMask][exMask][inCount][exCount]; + + final int shiftedInMask = (inMask << 1) & ((1 << n) - 1); + final int shiftedExMask = (exMask << 1) & ((1 << n) - 1); + + final int skip = + getMaxGridHappiness(m, n, pos + 1, shiftedInMask, shiftedExMask, inCount, exCount, mem); + final int placeIntrovert = + inCount > 0 ? 120 + getPlacementCost(n, i, j, inMask, exMask, -30) + + getMaxGridHappiness(m, n, pos + 1, shiftedInMask | 1, shiftedExMask, + inCount - 1, exCount, mem) + : Integer.MIN_VALUE; + final int placeExtrovert = + exCount > 0 ? 40 + getPlacementCost(n, i, j, inMask, exMask, 20) + + getMaxGridHappiness(m, n, pos + 1, shiftedInMask, shiftedExMask | 1, + inCount, exCount - 1, mem) + : Integer.MIN_VALUE; + return mem[pos][inMask][exMask][inCount][exCount] = + Math.max(skip, Math.max(placeIntrovert, placeExtrovert)); + } +} diff --git a/solutions/1659. Maximize Grid Happiness/1659.py b/solutions/1659. Maximize Grid Happiness/1659.py new file mode 100644 index 00000000000..40e4a0c98f1 --- /dev/null +++ b/solutions/1659. Maximize Grid Happiness/1659.py @@ -0,0 +1,49 @@ +class Solution: + def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int: + def getPlacementCost(i: int, j: int, inMask: int, exMask: int, diff: int) -> int: + """Calculates the cost based on left and up neighbors. + + The `diff` parameter represents the happiness change due to the current + placed person in (i, j). We add `diff` each time we encounter a neighbor + (left or up) who is already placed. + + 1. If the neighbor is an introvert, we subtract 30 from cost. + 2. If the neighbor is an extrovert, we add 20 to from cost. + """ + cost = 0 + if i > 0: + if (1 << (n - 1)) & inMask: + cost += diff - 30 + if (1 << (n - 1)) & exMask: + cost += diff + 20 + if j > 0: + if 1 & inMask: + cost += diff - 30 + if 1 & exMask: + cost += diff + 20 + return cost + + @functools.lru_cache(None) + def dp(pos: int, inMask: int, exMask: int, inCount: int, exCount: int) -> int: + # `inMask` is the placement of introvert people in the last n cells. + # e.g. if we have m = 2, n = 3, i = 1, j = 1, then inMask = 0b101 means + # + # ? 1 0 + # 1 x ? (x := current position) + i, j = divmod(pos, n) + if i == m: + return 0 + + shiftedInMask = (inMask << 1) & ((1 << n) - 1) + shiftedExMask = (exMask << 1) & ((1 << n) - 1) + + skip = dp(pos + 1, shiftedInMask, shiftedExMask, inCount, exCount) + placeIntrovert = 120 + getPlacementCost(i, j, inMask, exMask, -30) + \ + dp(pos + 1, shiftedInMask + 1, shiftedExMask, inCount - 1, exCount) if inCount > 0 \ + else -math.inf + placeExtrovert = 40 + getPlacementCost(i, j, inMask, exMask, 20) + \ + dp(pos + 1, shiftedInMask, shiftedExMask + 1, inCount, exCount - 1) if exCount > 0 \ + else -math.inf + return max(skip, placeIntrovert, placeExtrovert) + + return dp(0, 0, 0, introvertsCount, extrovertsCount) diff --git a/solutions/166. Fraction to Recurring Decimal/166.cpp b/solutions/166. Fraction to Recurring Decimal/166.cpp new file mode 100644 index 00000000000..98581f787d2 --- /dev/null +++ b/solutions/166. Fraction to Recurring Decimal/166.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + string fractionToDecimal(int numerator, int denominator) { + if (numerator == 0) + return "0"; + + string ans; + + if (numerator < 0 ^ denominator < 0) + ans += "-"; + + long n = labs(numerator); + long d = labs(denominator); + ans += to_string(n / d); + + if (n % d == 0) + return ans; + + ans += '.'; + unordered_map seen; + + for (long r = n % d; r; r %= d) { + if (const auto it = seen.find(r); it != seen.cend()) { + ans.insert(it->second, 1, '('); + ans += ')'; + break; + } + seen[r] = ans.size(); + r *= 10; + ans += to_string(r / d); + } + + return ans; + } +}; diff --git a/solutions/166. Fraction to Recurring Decimal/166.java b/solutions/166. Fraction to Recurring Decimal/166.java new file mode 100644 index 00000000000..602eaba2896 --- /dev/null +++ b/solutions/166. Fraction to Recurring Decimal/166.java @@ -0,0 +1,34 @@ +class Solution { + public String fractionToDecimal(int numerator, int denominator) { + if (numerator == 0) + return "0"; + + StringBuilder sb = new StringBuilder(); + + if (numerator < 0 ^ denominator < 0) + sb.append("-"); + + long n = Math.abs((long) numerator); + long d = Math.abs((long) denominator); + sb.append(n / d); + + if (n % d == 0) + return sb.toString(); + + sb.append("."); + Map seen = new HashMap<>(); + + for (long r = n % d; r > 0; r %= d) { + if (seen.containsKey(r)) { + sb.insert(seen.get(r), "("); + sb.append(")"); + break; + } + seen.put(r, sb.length()); + r *= 10; + sb.append(r / d); + } + + return sb.toString(); + } +} diff --git a/solutions/166. Fraction to Recurring Decimal/166.py b/solutions/166. Fraction to Recurring Decimal/166.py new file mode 100644 index 00000000000..3f29ba77dcd --- /dev/null +++ b/solutions/166. Fraction to Recurring Decimal/166.py @@ -0,0 +1,31 @@ +class Solution: + def fractionToDecimal(self, numerator: int, denominator: int) -> str: + if numerator == 0: + return '0' + + ans = '' + + if (numerator < 0) ^ (denominator < 0): + ans += '-' + + numerator = abs(numerator) + denominator = abs(denominator) + ans += str(numerator // denominator) + + if numerator % denominator == 0: + return ans + + ans += '.' + dict = {} + + remainder = numerator % denominator + while remainder: + if remainder in dict: + ans = ans[:dict[remainder]] + '(' + ans[dict[remainder]:] + ')' + break + dict[remainder] = len(ans) + remainder *= 10 + ans += str(remainder // denominator) + remainder %= denominator + + return ans diff --git a/solutions/1660. Correct a Binary Tree/1660.cpp b/solutions/1660. Correct a Binary Tree/1660.cpp new file mode 100644 index 00000000000..5b8f720eb3d --- /dev/null +++ b/solutions/1660. Correct a Binary Tree/1660.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + TreeNode* correctBinaryTree(TreeNode* root) { + if (root == nullptr) + return nullptr; + if (root->right != nullptr && seen.contains(root->right->val)) + return nullptr; + seen.insert(root->val); + root->right = correctBinaryTree(root->right); + root->left = correctBinaryTree(root->left); + return root; + } + + private: + unordered_set seen; +}; diff --git a/solutions/1660. Correct a Binary Tree/1660.java b/solutions/1660. Correct a Binary Tree/1660.java new file mode 100644 index 00000000000..8bb5560441a --- /dev/null +++ b/solutions/1660. Correct a Binary Tree/1660.java @@ -0,0 +1,14 @@ +class Solution { + public TreeNode correctBinaryTree(TreeNode root) { + if (root == null) + return null; + if (root.right != null && seen.contains(root.right.val)) + return null; + seen.add(root.val); + root.right = correctBinaryTree(root.right); + root.left = correctBinaryTree(root.left); + return root; + } + + private Set seen = new HashSet<>(); +} diff --git a/solutions/1660. Correct a Binary Tree/1660.py b/solutions/1660. Correct a Binary Tree/1660.py new file mode 100644 index 00000000000..73fde0af486 --- /dev/null +++ b/solutions/1660. Correct a Binary Tree/1660.py @@ -0,0 +1,13 @@ +class Solution: + def __init__(self): + self.seen = set() + + def correctBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if root == None: + return None + if root.right and root.right.val in self.seen: + return None + self.seen.add(root.val) + root.right = self.correctBinaryTree(root.right) + root.left = self.correctBinaryTree(root.left) + return root diff --git a/solutions/1661. Average Time of Process per Machine/1661.sql b/solutions/1661. Average Time of Process per Machine/1661.sql new file mode 100644 index 00000000000..b39835bce8a --- /dev/null +++ b/solutions/1661. Average Time of Process per Machine/1661.sql @@ -0,0 +1,13 @@ +SELECT + StartActivity.machine_id, + ROUND( + AVG(EndActivity.timestamp - StartActivity.timestamp), + 3 + ) AS processing_time +FROM Activity AS StartActivity +INNER JOIN Activity AS EndActivity + USING (machine_id, process_id) +WHERE + StartActivity.activity_type = 'start' + AND EndActivity.activity_type = 'end' +GROUP BY 1; diff --git a/solutions/1662. Check If Two String Arrays are Equivalent/1662.cpp b/solutions/1662. Check If Two String Arrays are Equivalent/1662.cpp new file mode 100644 index 00000000000..65e626b9b9e --- /dev/null +++ b/solutions/1662. Check If Two String Arrays are Equivalent/1662.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool arrayStringsAreEqual(std::vector& word1, + std::vector& word2) { + int i = 0; // word1's index + int j = 0; // word2's index + int a = 0; // word1[i]'s index + int b = 0; // word2[j]'s index + + while (i < word1.size() && j < word2.size()) { + if (word1[i][a] != word2[j][b]) + return false; + if (++a == word1[i].size()) { + ++i; + a = 0; + } + if (++b == word2[j].size()) { + ++j; + b = 0; + } + } + + return i == word1.size() && j == word2.size(); + } +}; diff --git a/solutions/1662. Check If Two String Arrays are Equivalent/1662.java b/solutions/1662. Check If Two String Arrays are Equivalent/1662.java new file mode 100644 index 00000000000..587776cf9ba --- /dev/null +++ b/solutions/1662. Check If Two String Arrays are Equivalent/1662.java @@ -0,0 +1,23 @@ +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + int i = 0; // word1's index + int j = 0; // word2's index + int a = 0; // word1[i]'s index + int b = 0; // word2[j]'s index + + while (i < word1.length && j < word2.length) { + if (word1[i].charAt(a) != word2[j].charAt(b)) + return false; + if (++a == word1[i].length()) { + ++i; + a = 0; + } + if (++b == word2[j].length()) { + ++j; + b = 0; + } + } + + return i == word1.length && j == word2.length; + } +} diff --git a/solutions/1662. Check If Two String Arrays are Equivalent/1662.py b/solutions/1662. Check If Two String Arrays are Equivalent/1662.py new file mode 100644 index 00000000000..859f2f942c6 --- /dev/null +++ b/solutions/1662. Check If Two String Arrays are Equivalent/1662.py @@ -0,0 +1,20 @@ +class Solution: + def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: + i = 0 # word1's index + j = 0 # word2's index + a = 0 # word1[i]'s index + b = 0 # word2[j]'s index + + while i < len(word1) and j < len(word2): + if word1[i][a] != word2[j][b]: + return False + a += 1 + if a == len(word1[i]): + i += 1 + a = 0 + b += 1 + if b == len(word2[j]): + j += 1 + b = 0 + + return i == len(word1) and j == len(word2) diff --git a/solutions/1663. Smallest String With A Given Numeric Value/1663.cpp b/solutions/1663. Smallest String With A Given Numeric Value/1663.cpp new file mode 100644 index 00000000000..982d8017aed --- /dev/null +++ b/solutions/1663. Smallest String With A Given Numeric Value/1663.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + string getSmallestString(int n, int k) { + string ans; + + for (int i = 0; i < n; ++i) { + const int remainingLetters = n - 1 - i; + const int rank = max(1, k - remainingLetters * 26); + ans += 'a' + rank - 1; + k -= rank; + } + + return ans; + } +}; diff --git a/solutions/1663. Smallest String With A Given Numeric Value/1663.java b/solutions/1663. Smallest String With A Given Numeric Value/1663.java new file mode 100644 index 00000000000..48dd0e38086 --- /dev/null +++ b/solutions/1663. Smallest String With A Given Numeric Value/1663.java @@ -0,0 +1,14 @@ +class Solution { + public String getSmallestString(int n, int k) { + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < n; ++i) { + final int remainingLetters = n - 1 - i; + final int rank = Math.max(1, k - remainingLetters * 26); + sb.append((char) ('a' + rank - 1)); + k -= rank; + } + + return sb.toString(); + } +} diff --git a/solutions/1663. Smallest String With A Given Numeric Value/1663.py b/solutions/1663. Smallest String With A Given Numeric Value/1663.py new file mode 100644 index 00000000000..1803d7a5470 --- /dev/null +++ b/solutions/1663. Smallest String With A Given Numeric Value/1663.py @@ -0,0 +1,11 @@ +class Solution: + def getSmallestString(self, n: int, k: int) -> str: + ans = [] + + for i in range(n): + remainingLetters = n - 1 - i + rank = max(1, k - remainingLetters * 26) + ans.append(chr(ord('a') + rank - 1)) + k -= rank + + return ''.join(ans) diff --git a/solutions/1664. Ways to Make a Fair Array/1664-2.cpp b/solutions/1664. Ways to Make a Fair Array/1664-2.cpp new file mode 100644 index 00000000000..fbdb961d4fa --- /dev/null +++ b/solutions/1664. Ways to Make a Fair Array/1664-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int waysToMakeFair(vector& nums) { + const int n = nums.size(); + int ans = 0; + // l[0] := the sum of even-indexed nums[0..i) + // l[1] := the sum of odd-indexed nums[0..i) + // r[0] := the sum of even-indexed nums[i + 1..n) + // r[1] := the sum of odd-indexed nums[i + 1..n) + vector l(2); + vector r(2); + + for (int i = 0; i < n; ++i) + r[i % 2] += nums[i]; + + for (int i = 0; i < n; ++i) { + r[i % 2] -= nums[i]; + if (l[0] + r[1] == l[1] + r[0]) + ++ans; + l[i % 2] += nums[i]; + } + + return ans; + } +}; diff --git a/solutions/1664. Ways to Make a Fair Array/1664-2.java b/solutions/1664. Ways to Make a Fair Array/1664-2.java new file mode 100644 index 00000000000..6c390a5f25b --- /dev/null +++ b/solutions/1664. Ways to Make a Fair Array/1664-2.java @@ -0,0 +1,24 @@ +class Solution { + public int waysToMakeFair(int[] nums) { + final int n = nums.length; + int ans = 0; + // l[0] := the sum of even-indexed nums[0..i) + // l[1] := the sum of odd-indexed nums[0..i) + // r[0] := the sum of even-indexed nums[i + 1..n) + // r[1] := the sum of odd-indexed nums[i + 1..n) + int[] l = new int[2]; + int[] r = new int[2]; + + for (int i = 0; i < n; ++i) + r[i % 2] += nums[i]; + + for (int i = 0; i < n; ++i) { + r[i % 2] -= nums[i]; + if (l[0] + r[1] == l[1] + r[0]) + ++ans; + l[i % 2] += nums[i]; + } + + return ans; + } +} diff --git a/solutions/1664. Ways to Make a Fair Array/1664.cpp b/solutions/1664. Ways to Make a Fair Array/1664.cpp new file mode 100644 index 00000000000..8fb61a106d1 --- /dev/null +++ b/solutions/1664. Ways to Make a Fair Array/1664.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int waysToMakeFair(vector& nums) { + const int n = nums.size(); + int ans = 0; + vector even(n + 1); // the sum of even-indexed nums[0..i) + vector odd(n + 1); // the sum of odd-indexed nums[0..i) + + for (int i = 1; i <= n; ++i) { + odd[i] = odd[i - 1]; + even[i] = even[i - 1]; + if (i % 2 == 0) + even[i] += nums[i - 1]; + else + odd[i] += nums[i - 1]; + } + + const int sum = even.back() + odd.back(); + + for (int i = 0; i < n; ++i) { + const int evenSum = even[i] + odd.back() - odd[i + 1]; + const int oddSum = sum - nums[i] - evenSum; + if (evenSum == oddSum) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1664. Ways to Make a Fair Array/1664.java b/solutions/1664. Ways to Make a Fair Array/1664.java new file mode 100644 index 00000000000..9b2c48a9ad5 --- /dev/null +++ b/solutions/1664. Ways to Make a Fair Array/1664.java @@ -0,0 +1,28 @@ +class Solution { + public int waysToMakeFair(int[] nums) { + final int n = nums.length; + int ans = 0; + int[] even = new int[n + 1]; // the sum of even-indexed nums[0..i) + int[] odd = new int[n + 1]; // the sum of odd-indexed nums[0..i) + + for (int i = 1; i <= n; ++i) { + odd[i] = odd[i - 1]; + even[i] = even[i - 1]; + if (i % 2 == 0) + even[i] += nums[i - 1]; + else + odd[i] += nums[i - 1]; + } + + final int sum = even[n] + odd[n]; + + for (int i = 0; i < n; ++i) { + final int evenSum = even[i] + odd[n] - odd[i + 1]; + final int oddSum = sum - nums[i] - evenSum; + if (evenSum == oddSum) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.cpp b/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.cpp new file mode 100644 index 00000000000..11c53542d36 --- /dev/null +++ b/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minimumEffort(vector>& tasks) { + int ans = 0; + int prevSaved = 0; + + ranges::sort(tasks, [](const vector& a, const vector& b) { + return a[1] - a[0] > b[1] - b[0]; + }); + + for (const vector& task : tasks) { + const int actual = task[0]; + const int minimum = task[1]; + if (prevSaved < minimum) { + ans += minimum - prevSaved; + prevSaved = minimum - actual; + } else { + prevSaved -= actual; + } + } + + return ans; + } +}; diff --git a/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.java b/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.java new file mode 100644 index 00000000000..a46c0ac4b6b --- /dev/null +++ b/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.java @@ -0,0 +1,21 @@ +class Solution { + public int minimumEffort(int[][] tasks) { + int ans = 0; + int prevSaved = 0; + + Arrays.sort(tasks, (a, b) -> (b[1] - b[0]) - (a[1] - a[0])); + + for (int[] task : tasks) { + final int actual = task[0]; + final int minimum = task[1]; + if (prevSaved < minimum) { + ans += minimum - prevSaved; + prevSaved = minimum - actual; + } else { + prevSaved -= actual; + } + } + + return ans; + } +} diff --git a/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.py b/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.py new file mode 100644 index 00000000000..d42ca20197c --- /dev/null +++ b/solutions/1665. Minimum Initial Energy to Finish Tasks/1665.py @@ -0,0 +1,13 @@ +class Solution: + def minimumEffort(self, tasks: List[List[int]]) -> int: + ans = 0 + prevSaved = 0 + + for actual, minimum in sorted(tasks, key=lambda x: x[0] - x[1]): + if prevSaved < minimum: + ans += minimum - prevSaved + prevSaved = minimum - actual + else: + prevSaved -= actual + + return ans diff --git a/solutions/1666. Change the Root of a Binary Tree/1666.cpp b/solutions/1666. Change the Root of a Binary Tree/1666.cpp new file mode 100644 index 00000000000..a856c242116 --- /dev/null +++ b/solutions/1666. Change the Root of a Binary Tree/1666.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + Node* flipBinaryTree(Node* root, Node* leaf) { + return reroot(root, leaf, nullptr); + } + + private: + Node* reroot(Node* root, Node* node, Node* newParent) { + Node* oldParent = node->parent; + node->parent = newParent; + + // Clean up the child if it's the new parent. + if (node->left == newParent) + node->left = nullptr; + if (node->right == newParent) + node->right = nullptr; + + // We meet the original root, so we're done. + if (node == root) + return node; + + if (node->left) + node->right = node->left; + node->left = reroot(root, oldParent, node); + + return node; + } +}; diff --git a/solutions/1666. Change the Root of a Binary Tree/1666.java b/solutions/1666. Change the Root of a Binary Tree/1666.java new file mode 100644 index 00000000000..7a0fd6a344b --- /dev/null +++ b/solutions/1666. Change the Root of a Binary Tree/1666.java @@ -0,0 +1,26 @@ +class Solution { + public Node flipBinaryTree(Node root, Node leaf) { + return reroot(root, leaf, null); + } + + private Node reroot(Node root, Node node, Node newParent) { + Node oldParent = node.parent; + node.parent = newParent; + + // Clean up the child if it's the new parent. + if (node.left == newParent) + node.left = null; + if (node.right == newParent) + node.right = null; + + // We meet the original root, so we're done. + if (node == root) + return node; + + if (node.left != null) + node.right = node.left; + node.left = reroot(root, oldParent, node); + + return node; + } +} diff --git a/solutions/1667. Fix Names in a Table/1667.sql b/solutions/1667. Fix Names in a Table/1667.sql new file mode 100644 index 00000000000..397e336fb0c --- /dev/null +++ b/solutions/1667. Fix Names in a Table/1667.sql @@ -0,0 +1,8 @@ +SELECT + user_id, + CONCAT( + UPPER(SUBSTRING(name, 1, 1)), + LOWER(SUBSTRING(name, 2)) + ) AS name +FROM Users +ORDER BY 1; diff --git a/solutions/1668. Maximum Repeating Substring/1668.cpp b/solutions/1668. Maximum Repeating Substring/1668.cpp new file mode 100644 index 00000000000..44c2848bfc9 --- /dev/null +++ b/solutions/1668. Maximum Repeating Substring/1668.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int maxRepeating(string sequence, string word) { + int ans = 1; + string repeating = word; + while (sequence.find(repeating) != string::npos) { + ++ans; + repeating += word; + } + return ans - 1; + } +}; diff --git a/solutions/1668. Maximum Repeating Substring/1668.java b/solutions/1668. Maximum Repeating Substring/1668.java new file mode 100644 index 00000000000..6fe63ddfd5e --- /dev/null +++ b/solutions/1668. Maximum Repeating Substring/1668.java @@ -0,0 +1,8 @@ +class Solution { + public int maxRepeating(String sequence, String word) { + int ans = 1; + while (sequence.contains(word.repeat(ans))) + ++ans; + return ans - 1; + } +} diff --git a/solutions/1668. Maximum Repeating Substring/1668.py b/solutions/1668. Maximum Repeating Substring/1668.py new file mode 100644 index 00000000000..ad0bdbd1677 --- /dev/null +++ b/solutions/1668. Maximum Repeating Substring/1668.py @@ -0,0 +1,6 @@ +class Solution: + def maxRepeating(self, sequence: str, word: str) -> int: + ans = 1 + while word * ans in sequence: + ans += 1 + return ans - 1 diff --git a/solutions/1669. Merge In Between Linked Lists/1669.cpp b/solutions/1669. Merge In Between Linked Lists/1669.cpp new file mode 100644 index 00000000000..5990b02b2a0 --- /dev/null +++ b/solutions/1669. Merge In Between Linked Lists/1669.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { + ListNode* nodeBeforeA = list1; + for (int i = 0; i < a - 1; ++i) + nodeBeforeA = nodeBeforeA->next; + + ListNode* nodeB = nodeBeforeA->next; + for (int i = 0; i < b - a; ++i) + nodeB = nodeB->next; + + nodeBeforeA->next = list2; + ListNode* lastNodeInList2 = list2; + + while (lastNodeInList2->next != nullptr) + lastNodeInList2 = lastNodeInList2->next; + + lastNodeInList2->next = nodeB->next; + nodeB->next = nullptr; + return list1; + } +}; diff --git a/solutions/1669. Merge In Between Linked Lists/1669.java b/solutions/1669. Merge In Between Linked Lists/1669.java new file mode 100644 index 00000000000..1796d9ec232 --- /dev/null +++ b/solutions/1669. Merge In Between Linked Lists/1669.java @@ -0,0 +1,21 @@ +class Solution { + public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { + ListNode nodeBeforeA = list1; + for (int i = 0; i < a - 1; ++i) + nodeBeforeA = nodeBeforeA.next; + + ListNode nodeB = nodeBeforeA.next; + for (int i = 0; i < b - a; ++i) + nodeB = nodeB.next; + + nodeBeforeA.next = list2; + ListNode lastNodeInList2 = list2; + + while (lastNodeInList2.next != null) + lastNodeInList2 = lastNodeInList2.next; + + lastNodeInList2.next = nodeB.next; + nodeB.next = null; + return list1; + } +} diff --git a/solutions/1669. Merge In Between Linked Lists/1669.py b/solutions/1669. Merge In Between Linked Lists/1669.py new file mode 100644 index 00000000000..ed01e9ad2a3 --- /dev/null +++ b/solutions/1669. Merge In Between Linked Lists/1669.py @@ -0,0 +1,19 @@ +class Solution: + def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: + nodeBeforeA = list1 + for i in range(a - 1): + nodeBeforeA = nodeBeforeA.next + + nodeB = nodeBeforeA.next + for i in range(b - a): + nodeB = nodeB.next + + nodeBeforeA.next = list2 + lastNodeInList2 = list2 + + while lastNodeInList2.next: + lastNodeInList2 = lastNodeInList2.next + + lastNodeInList2.next = nodeB.next + nodeB.next = None + return list1 diff --git a/solutions/167. Two Sum II - Input array is sorted/167.cpp b/solutions/167. Two Sum II - Input array is sorted/167.cpp new file mode 100644 index 00000000000..09a2fa05179 --- /dev/null +++ b/solutions/167. Two Sum II - Input array is sorted/167.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector twoSum(vector& numbers, int target) { + int l = 0; + int r = numbers.size() - 1; + + while (numbers[l] + numbers[r] != target) + if (numbers[l] + numbers[r] < target) + ++l; + else + --r; + + return {l + 1, r + 1}; + } +}; diff --git a/solutions/167. Two Sum II - Input array is sorted/167.java b/solutions/167. Two Sum II - Input array is sorted/167.java new file mode 100644 index 00000000000..d36a2b66add --- /dev/null +++ b/solutions/167. Two Sum II - Input array is sorted/167.java @@ -0,0 +1,14 @@ +class Solution { + public int[] twoSum(int[] numbers, int target) { + int l = 0; + int r = numbers.length - 1; + + while (numbers[l] + numbers[r] != target) + if (numbers[l] + numbers[r] < target) + ++l; + else + --r; + + return new int[] {l + 1, r + 1}; + } +} diff --git a/solutions/167. Two Sum II - Input array is sorted/167.py b/solutions/167. Two Sum II - Input array is sorted/167.py new file mode 100644 index 00000000000..4220003ab01 --- /dev/null +++ b/solutions/167. Two Sum II - Input array is sorted/167.py @@ -0,0 +1,13 @@ +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + l = 0 + r = len(numbers) - 1 + + while l < r: + summ = numbers[l] + numbers[r] + if summ == target: + return [l + 1, r + 1] + if summ < target: + l += 1 + else: + r -= 1 diff --git a/solutions/1670. Design Front Middle Back Queue/1670.cpp b/solutions/1670. Design Front Middle Back Queue/1670.cpp new file mode 100644 index 00000000000..fe7cc69e72e --- /dev/null +++ b/solutions/1670. Design Front Middle Back Queue/1670.cpp @@ -0,0 +1,80 @@ +class FrontMiddleBackQueue { + public: + void pushFront(int val) { + frontQueue.push_front(val); + moveFrontToBackIfNeeded(); + } + + void pushMiddle(int val) { + if (| frontQueue | == | backQueue |) + backQueue.push_front(val); + else + frontQueue.push_back(val); + } + + void pushBack(int val) { + backQueue.push_back(val); + moveBackToFrontIfNeeded(); + } + + int popFront() { + if (!frontQueue.empty()) { + const int x = frontQueue.front(); + frontQueue.pop_front(); + moveBackToFrontIfNeeded(); + return x; + } + if (!backQueue.empty()) { + const int x = backQueue.front(); + backQueue.pop_front(); + moveFrontToBackIfNeeded(); + return x; + } + return -1; + } + + int popMiddle() { + if (frontQueue.empty() && backQueue.empty()) + return -1; + if (frontQueue.size() + 1 == backQueue.size()) { + const int x = backQueue.front(); + backQueue.pop_front(); + return x; + } else { // |frontQueue| == |backQueue| + const int x = frontQueue.back(); + frontQueue.pop_back(); + return x; + } + } + + int popBack() { + if (backQueue.empty()) + return -1; + const int x = backQueue.back(); + backQueue.pop_back(); + moveFrontToBackIfNeeded(); + return x; + } + + private: + // |frontQueue| = |backQueue| or + // |frontQueue| = |backQueue| - 1 + deque frontQueue; + deque backQueue; + + void moveFrontToBackIfNeeded() { + if (frontQueue.size() - 1 == backQueue.size()) { + const int x = frontQueue.back(); + frontQueue.pop_back(); + backQueue.push_front(x); + } + } + + void moveBackToFrontIfNeeded() { + if (frontQueue.size() + 2 == backQueue.size()) { + const int x = backQueue.front(); + backQueue.pop_front(); + frontQueue.push_back(x); + } + } +}; diff --git a/solutions/1670. Design Front Middle Back Queue/1670.java b/solutions/1670. Design Front Middle Back Queue/1670.java new file mode 100644 index 00000000000..b0213b1e7fe --- /dev/null +++ b/solutions/1670. Design Front Middle Back Queue/1670.java @@ -0,0 +1,59 @@ +class FrontMiddleBackQueue { + public void pushFront(int val) { + frontQueue.offerFirst(val); + moveFrontToBackIfNeeded(); + } + + public void pushMiddle(int val) { + if (| frontQueue | == | backQueue |) + backQueue.offerFirst(val); + else + frontQueue.offerLast(val); + } + + public void pushBack(int val) { + backQueue.offerLast(val); + moveBackToFrontIfNeeded(); + } + + public int popFront() { + if (!frontQueue.isEmpty()) { + final int x = frontQueue.removeFirst(); + moveBackToFrontIfNeeded(); + return x; + } + if (!backQueue.isEmpty()) + return backQueue.pollFirst(); + return -1; + } + + public int popMiddle() { + if (frontQueue.isEmpty() && backQueue.isEmpty()) + return -1; + if (frontQueue.size() + 1 == backQueue.size()) + return backQueue.pollFirst(); + // |frontQueue| == |backQueue| + return frontQueue.pollLast(); + } + + public int popBack() { + if (backQueue.isEmpty()) + return -1; + final int x = backQueue.removeLast(); + moveFrontToBackIfNeeded(); + return x; + } + + private void moveFrontToBackIfNeeded() { + if (frontQueue.size() - 1 == backQueue.size()) + backQueue.offerFirst(frontQueue.pollLast()); + } + + private void moveBackToFrontIfNeeded() { + if (frontQueue.size() + 2 == backQueue.size()) + frontQueue.offerLast(backQueue.pollFirst()); + } + + private Deque frontQueue = new ArrayDeque<>(); + private Deque backQueue = new ArrayDeque<>(); +} diff --git a/solutions/1670. Design Front Middle Back Queue/1670.py b/solutions/1670. Design Front Middle Back Queue/1670.py new file mode 100644 index 00000000000..973cfb4bafa --- /dev/null +++ b/solutions/1670. Design Front Middle Back Queue/1670.py @@ -0,0 +1,49 @@ +class FrontMiddleBackQueue: + def __init__(self): + self.frontQueue = collections.deque() + self.backQueue = collections.deque() + + def pushFront(self, val: int) -> None: + self.frontQueue.appendleft(val) + self._moveFrontToBackIfNeeded() + + def pushMiddle(self, val: int) -> None: + if len(self.frontQueue) == len(self.backQueue): + self.backQueue.appendleft(val) + else: + self.frontQueue.append(val) + + def pushBack(self, val: int) -> None: + self.backQueue.append(val) + self._moveBackToFrontIfNeeded() + + def popFront(self) -> int: + if self.frontQueue: + x = self.frontQueue.popleft() + self._moveBackToFrontIfNeeded() + return x + if self.backQueue: + return self.backQueue.popleft() + return -1 + + def popMiddle(self) -> int: + if not self.frontQueue and not self.backQueue: + return -1 + if len(self.frontQueue) + 1 == len(self.backQueue): + return self.backQueue.popleft() + return self.frontQueue.pop() + + def popBack(self) -> int: + if self.backQueue: + x = self.backQueue.pop() + self._moveFrontToBackIfNeeded() + return x + return -1 + + def _moveFrontToBackIfNeeded(self) -> None: + if len(self.frontQueue) - 1 == len(self.backQueue): + self.backQueue.appendleft(self.frontQueue.pop()) + + def _moveBackToFrontIfNeeded(self) -> None: + if len(self.frontQueue) + 2 == len(self.backQueue): + self.frontQueue.append(self.backQueue.popleft()) diff --git a/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.cpp b/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.cpp new file mode 100644 index 00000000000..958b28a6828 --- /dev/null +++ b/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int minimumMountainRemovals(vector& nums) { + vector l = lengthOfLIS(nums); + vector r = reversed(lengthOfLIS(reversed(nums))); + int maxMountainSeq = 0; + + for (int i = 0; i < nums.size(); ++i) + if (l[i] > 1 && r[i] > 1) + maxMountainSeq = max(maxMountainSeq, l[i] + r[i] - 1); + + return nums.size() - maxMountainSeq; + } + + private: + // Similar to 300. Longest Increasing Subsequence + vector lengthOfLIS(vector nums) { + // tail[i] := the minimum tail of all the increasing subsequences having + // length i + 1 + vector tail; + // dp[i] := the length of LIS ending in nums[i] + vector dp; + for (const int num : nums) { + if (tail.empty() || num > tail.back()) + tail.push_back(num); + else + tail[firstGreaterEqual(tail, num)] = num; + dp.push_back(tail.size()); + } + return dp; + } + + int firstGreaterEqual(const vector& A, int target) { + return ranges::lower_bound(A, target) - A.begin(); + } + + vector reversed(const vector& nums) { + return {nums.rbegin(), nums.rend()}; + } +}; diff --git a/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.java b/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.java new file mode 100644 index 00000000000..fc4375204db --- /dev/null +++ b/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.java @@ -0,0 +1,51 @@ +class Solution { + public int minimumMountainRemovals(int[] nums) { + int[] l = lengthOfLIS(nums); + int[] r = reversed(lengthOfLIS(reversed(nums))); + int maxMountainSeq = 0; + + for (int i = 0; i < nums.length; ++i) + if (l[i] > 1 && r[i] > 1) + maxMountainSeq = Math.max(maxMountainSeq, l[i] + r[i] - 1); + + return nums.length - maxMountainSeq; + } + + // Similar to 300. Longest Increasing Subsequence + private int[] lengthOfLIS(int[] nums) { + // tail[i] := the minimum tail of all the increasing subsequences with + // length i + 1 + List tail = new ArrayList<>(); + // dp[i] := the length of LIS ending in nums[i] + int[] dp = new int[nums.length]; + for (int i = 0; i < nums.length; ++i) { + final int num = nums[i]; + if (tail.isEmpty() || num > tail.get(tail.size() - 1)) + tail.add(num); + else + tail.set(firstGreaterEqual(tail, num), num); + dp[i] = tail.size(); + } + return dp; + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } + + private int[] reversed(int[] nums) { + int[] A = nums.clone(); + int l = 0; + int r = nums.length - 1; + while (l < r) + swap(A, l++, r--); + return A; + } + + private void swap(int[] A, int i, int j) { + final int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} diff --git a/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.py b/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.py new file mode 100644 index 00000000000..f5479563bf9 --- /dev/null +++ b/solutions/1671. Minimum Number of Removals to Make Mountain Array/1671.py @@ -0,0 +1,26 @@ +class Solution: + def minimumMountainRemovals(self, nums: List[int]) -> int: + left = self._lengthOfLIS(nums) + right = self._lengthOfLIS(nums[::-1])[::-1] + maxMountainSeq = 0 + + for l, r in zip(left, right): + if l > 1 and r > 1: + maxMountainSeq = max(maxMountainSeq, l + r - 1) + + return len(nums) - maxMountainSeq + + # Similar to 300. Longest Increasing Subsequence + def _lengthOfLIS(self, nums: List[int]) -> List[int]: + # tail[i] := the minimum tail of all the increasing subsequences having + # length i + 1 + tail = [] + # dp[i] := the length of LIS ending in nums[i] + dp = [] + for num in nums: + if not tail or num > tail[-1]: + tail.append(num) + else: + tail[bisect.bisect_left(tail, num)] = num + dp.append(len(tail)) + return dp diff --git a/solutions/1672. Richest Customer Wealth/1672.cpp b/solutions/1672. Richest Customer Wealth/1672.cpp new file mode 100644 index 00000000000..bbc3b32962b --- /dev/null +++ b/solutions/1672. Richest Customer Wealth/1672.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int maximumWealth(vector>& accounts) { + return accumulate(accounts.begin(), accounts.end(), 0, + [](int subtotal, const vector& account) { + return max(subtotal, accumulate(account.begin(), account.end(), 0)); + }); + } +}; diff --git a/solutions/1672. Richest Customer Wealth/1672.java b/solutions/1672. Richest Customer Wealth/1672.java new file mode 100644 index 00000000000..b285d2b481a --- /dev/null +++ b/solutions/1672. Richest Customer Wealth/1672.java @@ -0,0 +1,8 @@ +class Solution { + public int maximumWealth(int[][] accounts) { + return Arrays.stream(accounts) + .mapToInt(account -> Arrays.stream(account).sum()) + .max() + .getAsInt(); + } +} diff --git a/solutions/1672. Richest Customer Wealth/1672.py b/solutions/1672. Richest Customer Wealth/1672.py new file mode 100644 index 00000000000..dd5215b28e0 --- /dev/null +++ b/solutions/1672. Richest Customer Wealth/1672.py @@ -0,0 +1,3 @@ +class Solution: + def maximumWealth(self, accounts: List[List[int]]) -> int: + return max(map(sum, accounts)) diff --git a/solutions/1673. Find the Most Competitive Subsequence/1673.cpp b/solutions/1673. Find the Most Competitive Subsequence/1673.cpp new file mode 100644 index 00000000000..9d64b156d23 --- /dev/null +++ b/solutions/1673. Find the Most Competitive Subsequence/1673.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector mostCompetitive(vector& nums, int k) { + vector ans; + + for (int i = 0; i < nums.size(); ++i) { + // If |ans| - 1 + |nums[i..n)| >= k, then it means we still have enough + // numbers, and we can safely pop an element from ans. + while (!ans.empty() && ans.back() > nums[i] && + ans.size() - 1 + nums.size() - i >= k) + ans.pop_back(); + if (ans.size() < k) + ans.push_back(nums[i]); + } + + return ans; + } +}; diff --git a/solutions/1673. Find the Most Competitive Subsequence/1673.java b/solutions/1673. Find the Most Competitive Subsequence/1673.java new file mode 100644 index 00000000000..384dbc427af --- /dev/null +++ b/solutions/1673. Find the Most Competitive Subsequence/1673.java @@ -0,0 +1,20 @@ +class Solution { + public int[] mostCompetitive(int[] nums, int k) { + int[] ans = new int[k]; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < nums.length; ++i) { + // If |stack| - 1 + |nums[i..n)| >= k, then it means we still have enough + // numbers, and we can safely pop an element from stack. + while (!stack.isEmpty() && stack.peek() > nums[i] && stack.size() - 1 + nums.length - i >= k) + stack.pop(); + if (stack.size() < k) + stack.push(nums[i]); + } + + for (int i = 0; i < k; i++) + ans[i] = stack.pollLast(); + + return ans; + } +} diff --git a/solutions/1673. Find the Most Competitive Subsequence/1673.py b/solutions/1673. Find the Most Competitive Subsequence/1673.py new file mode 100644 index 00000000000..c7f80e65bb6 --- /dev/null +++ b/solutions/1673. Find the Most Competitive Subsequence/1673.py @@ -0,0 +1,13 @@ +class Solution: + def mostCompetitive(self, nums: List[int], k: int) -> List[int]: + ans = [] + + for i, num in enumerate(nums): + # If |ans| - 1 + |nums[i..n)| >= k, then it means we still have enough + # numbers, and we can safely pop an element from ans. + while ans and ans[-1] > nums[i] and len(ans) - 1 + len(nums) - i >= k: + ans.pop() + if len(ans) < k: + ans.append(nums[i]) + + return ans diff --git a/solutions/1674. Minimum Moves to Make Array Complementary/1674.cpp b/solutions/1674. Minimum Moves to Make Array Complementary/1674.cpp new file mode 100644 index 00000000000..89290afca12 --- /dev/null +++ b/solutions/1674. Minimum Moves to Make Array Complementary/1674.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minMoves(vector& nums, int limit) { + const int n = nums.size(); + int ans = n; + // delta[i] := the number of moves needed when target goes from i - 1 to i + vector delta(limit * 2 + 2); + + for (int i = 0; i < n / 2; ++i) { + const int a = nums[i]; + const int b = nums[n - 1 - i]; + --delta[min(a, b) + 1]; + --delta[a + b]; + ++delta[a + b + 1]; + ++delta[max(a, b) + limit + 1]; + } + + // Initially, we need `moves` when the target is 2. + for (int i = 2, moves = n; i <= limit * 2; ++i) { + moves += delta[i]; + ans = min(ans, moves); + } + + return ans; + } +}; diff --git a/solutions/1674. Minimum Moves to Make Array Complementary/1674.java b/solutions/1674. Minimum Moves to Make Array Complementary/1674.java new file mode 100644 index 00000000000..a6cc3e72bc9 --- /dev/null +++ b/solutions/1674. Minimum Moves to Make Array Complementary/1674.java @@ -0,0 +1,25 @@ +class Solution { + public int minMoves(int[] nums, int limit) { + final int n = nums.length; + int ans = n; + // delta[i] := the number of moves needed when target goes from i - 1 to i + int[] delta = new int[limit * 2 + 2]; + + for (int i = 0; i < n / 2; ++i) { + final int a = nums[i]; + final int b = nums[n - 1 - i]; + --delta[Math.min(a, b) + 1]; + --delta[a + b]; + ++delta[a + b + 1]; + ++delta[Math.max(a, b) + limit + 1]; + } + + // Initially, we need `moves` when the target is 2. + for (int i = 2, moves = n; i <= limit * 2; ++i) { + moves += delta[i]; + ans = Math.min(ans, moves); + } + + return ans; + } +} diff --git a/solutions/1674. Minimum Moves to Make Array Complementary/1674.py b/solutions/1674. Minimum Moves to Make Array Complementary/1674.py new file mode 100644 index 00000000000..b4790b682df --- /dev/null +++ b/solutions/1674. Minimum Moves to Make Array Complementary/1674.py @@ -0,0 +1,22 @@ +class Solution: + def minMoves(self, nums: List[int], limit: int) -> int: + n = len(nums) + ans = n + # delta[i] := the number of moves needed when target goes from i - 1 to i + delta = [0] * (limit * 2 + 2) + + for i in range(n // 2): + a = nums[i] + b = nums[n - 1 - i] + delta[min(a, b) + 1] -= 1 + delta[a + b] -= 1 + delta[a + b + 1] += 1 + delta[max(a, b) + limit + 1] += 1 + + # Initially, we need `moves` when the target is 2. + moves = n + for i in range(2, limit * 2 + 1): + moves += delta[i] + ans = min(ans, moves) + + return ans diff --git a/solutions/1675. Minimize Deviation in Array/1675.cpp b/solutions/1675. Minimize Deviation in Array/1675.cpp new file mode 100644 index 00000000000..aa6746e2507 --- /dev/null +++ b/solutions/1675. Minimize Deviation in Array/1675.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minimumDeviation(vector& nums) { + int ans = INT_MAX; + int mn = INT_MAX; + priority_queue maxHeap; + + for (const int num : nums) { + const int evenNum = num % 2 == 0 ? num : num * 2; + mn = min(mn, evenNum); + maxHeap.push(evenNum); + } + + while (maxHeap.top() % 2 == 0) { + const int mx = maxHeap.top(); + maxHeap.pop(); + ans = min(ans, mx - mn); + mn = min(mn, mx / 2); + maxHeap.push(mx / 2); + } + + return min(ans, maxHeap.top() - mn); + } +}; diff --git a/solutions/1675. Minimize Deviation in Array/1675.java b/solutions/1675. Minimize Deviation in Array/1675.java new file mode 100644 index 00000000000..8d5febd4eea --- /dev/null +++ b/solutions/1675. Minimize Deviation in Array/1675.java @@ -0,0 +1,22 @@ +class Solution { + public int minimumDeviation(int[] nums) { + int ans = Integer.MAX_VALUE; + int mn = Integer.MAX_VALUE; + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + for (final int num : nums) { + final int evenNum = num % 2 == 0 ? num : num * 2; + mn = Math.min(mn, evenNum); + maxHeap.offer(evenNum); + } + + while (maxHeap.peek() % 2 == 0) { + final int mx = maxHeap.poll(); + ans = Math.min(ans, mx - mn); + mn = Math.min(mn, mx / 2); + maxHeap.offer(mx / 2); + } + + return Math.min(ans, maxHeap.peek() - mn); + } +} diff --git a/solutions/1675. Minimize Deviation in Array/1675.py b/solutions/1675. Minimize Deviation in Array/1675.py new file mode 100644 index 00000000000..35fcf71c6cb --- /dev/null +++ b/solutions/1675. Minimize Deviation in Array/1675.py @@ -0,0 +1,18 @@ +class Solution: + def minimumDeviation(self, nums: List[int]) -> int: + ans = math.inf + mn = math.inf + maxHeap = [] + + for num in nums: + evenNum = num if num % 2 == 0 else num * 2 + heapq.heappush(maxHeap, -evenNum) + mn = min(mn, evenNum) + + while maxHeap[0] % 2 == 0: + mx = -heapq.heappop(maxHeap) + ans = min(ans, mx - mn) + mn = min(mn, mx // 2) + heapq.heappush(maxHeap, -mx // 2) + + return min(ans, -maxHeap[0] - mn) diff --git a/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.cpp b/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.cpp new file mode 100644 index 00000000000..cfba2716869 --- /dev/null +++ b/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + TreeNode* lowestCommonAncestor(TreeNode* root, vector& nodes) { + unordered_set nodesSet{nodes.begin(), nodes.end()}; + return lca(root, nodesSet); + } + + private: + TreeNode* lca(TreeNode* root, unordered_set& nodesSet) { + if (root == nullptr) + return nullptr; + if (nodesSet.contains(root)) + return root; + TreeNode* left = lca(root->left, nodesSet); + TreeNode* right = lca(root->right, nodesSet); + if (left != nullptr && right != nullptr) + return root; + return left == nullptr ? right : left; + } +}; diff --git a/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.java b/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.java new file mode 100644 index 00000000000..885a922d746 --- /dev/null +++ b/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.java @@ -0,0 +1,18 @@ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) { + Set nodesSet = new HashSet<>(Arrays.asList(nodes)); + return lca(root, nodesSet); + } + + private TreeNode lca(TreeNode root, Set nodesSet) { + if (root == null) + return null; + if (nodesSet.contains(root)) + return root; + TreeNode left = lca(root.left, nodesSet); + TreeNode right = lca(root.right, nodesSet); + if (left != null && right != null) + return root; + return left == null ? right : left; + } +} diff --git a/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.py b/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.py new file mode 100644 index 00000000000..a907146aa55 --- /dev/null +++ b/solutions/1676. Lowest Common Ancestor of a Binary Tree IV/1676.py @@ -0,0 +1,16 @@ +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', nodes: 'List[TreeNode]') -> 'TreeNode': + nodes = set(nodes) + + def lca(root: 'TreeNode') -> 'TreeNode': + if not root: + return None + if root in nodes: + return root + left = lca(root.left) + right = lca(root.right) + if left and right: + return root + return left or right + + return lca(root) diff --git a/solutions/1677. Product's Worth Over Invoices/1677.sql b/solutions/1677. Product's Worth Over Invoices/1677.sql new file mode 100644 index 00000000000..248ac0fbefb --- /dev/null +++ b/solutions/1677. Product's Worth Over Invoices/1677.sql @@ -0,0 +1,11 @@ +SELECT + Product.name, + IFNULL(SUM(Invoice.rest), 0) AS rest, + IFNULL(SUM(Invoice.paid), 0) AS paid, + IFNULL(SUM(Invoice.canceled), 0) AS canceled, + IFNULL(SUM(Invoice.refunded), 0) AS refunded +FROM Product +LEFT JOIN Invoice + USING (product_id) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/1678. Goal Parser Interpretation/1678.cpp b/solutions/1678. Goal Parser Interpretation/1678.cpp new file mode 100644 index 00000000000..d61dbcec5f1 --- /dev/null +++ b/solutions/1678. Goal Parser Interpretation/1678.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string interpret(string command) { + string ans; + for (int i = 0; i < command.size();) + if (command[i] == 'G') { + ans += "G"; + ++i; + } else if (command[i + 1] == ')') { + ans += "o"; + i += 2; + } else { + ans += "al"; + i += 4; + } + return ans; + } +}; diff --git a/solutions/1678. Goal Parser Interpretation/1678.java b/solutions/1678. Goal Parser Interpretation/1678.java new file mode 100644 index 00000000000..b293f717e27 --- /dev/null +++ b/solutions/1678. Goal Parser Interpretation/1678.java @@ -0,0 +1,17 @@ +class Solution { + public String interpret(String command) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < command.length();) + if (command.charAt(i) == 'G') { + sb.append("G"); + ++i; + } else if (command.charAt(i + 1) == ')') { + sb.append("o"); + i += 2; + } else { + sb.append("al"); + i += 4; + } + return sb.toString(); + } +} diff --git a/solutions/1678. Goal Parser Interpretation/1678.py b/solutions/1678. Goal Parser Interpretation/1678.py new file mode 100644 index 00000000000..dc8a7bfe9ce --- /dev/null +++ b/solutions/1678. Goal Parser Interpretation/1678.py @@ -0,0 +1,3 @@ +class Solution: + def interpret(self, command: str) -> str: + return command.replace('()', 'o').replace('(al)', 'al') diff --git a/solutions/1679. Max Number of K-Sum Pairs/1679.cpp b/solutions/1679. Max Number of K-Sum Pairs/1679.cpp new file mode 100644 index 00000000000..aee998d89c9 --- /dev/null +++ b/solutions/1679. Max Number of K-Sum Pairs/1679.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxOperations(vector& nums, int k) { + int ans = 0; + unordered_map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [num, freq] : count) + if (const auto it = count.find(k - num); it != count.end()) + ans += min(freq, it->second); + + return ans / 2; + } +}; diff --git a/solutions/1679. Max Number of K-Sum Pairs/1679.java b/solutions/1679. Max Number of K-Sum Pairs/1679.java new file mode 100644 index 00000000000..be918bf27f1 --- /dev/null +++ b/solutions/1679. Max Number of K-Sum Pairs/1679.java @@ -0,0 +1,17 @@ +class Solution { + public int maxOperations(int[] nums, int k) { + int ans = 0; + HashMap count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int num : count.keySet()) { + final int complement = k - num; + if (count.containsKey(complement)) + ans += Math.min(count.get(num), count.get(complement)); + } + + return ans / 2; + } +} diff --git a/solutions/1679. Max Number of K-Sum Pairs/1679.py b/solutions/1679. Max Number of K-Sum Pairs/1679.py new file mode 100644 index 00000000000..fc30680bc05 --- /dev/null +++ b/solutions/1679. Max Number of K-Sum Pairs/1679.py @@ -0,0 +1,5 @@ +class Solution: + def maxOperations(self, nums: List[int], k: int) -> int: + count = collections.Counter(nums) + return sum(min(count[num], count[k - num]) + for num in count) // 2 diff --git a/solutions/168. Excel Sheet Column Title/168.cpp b/solutions/168. Excel Sheet Column Title/168.cpp new file mode 100644 index 00000000000..bec7aba4b9a --- /dev/null +++ b/solutions/168. Excel Sheet Column Title/168.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + string convertToTitle(int n) { + return n == 0 ? "" + : convertToTitle((n - 1) / 26) + (char)('A' + ((n - 1) % 26)); + } +}; diff --git a/solutions/168. Excel Sheet Column Title/168.java b/solutions/168. Excel Sheet Column Title/168.java new file mode 100644 index 00000000000..813ceb67d2a --- /dev/null +++ b/solutions/168. Excel Sheet Column Title/168.java @@ -0,0 +1,5 @@ +class Solution { + public String convertToTitle(int n) { + return n == 0 ? "" : convertToTitle((n - 1) / 26) + (char) ('A' + ((n - 1) % 26)); + } +} diff --git a/solutions/168. Excel Sheet Column Title/168.py b/solutions/168. Excel Sheet Column Title/168.py new file mode 100644 index 00000000000..af4ea7ef9ca --- /dev/null +++ b/solutions/168. Excel Sheet Column Title/168.py @@ -0,0 +1,4 @@ +class Solution: + def convertToTitle(self, n: int) -> str: + return self.convertToTitle((n - 1) // 26) + \ + chr(ord('A') + (n - 1) % 26) if n else '' diff --git a/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.cpp b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.cpp new file mode 100644 index 00000000000..b250362c781 --- /dev/null +++ b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int concatenatedBinary(int n) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + int numberOfBits = 0; + + for (unsigned i = 1; i <= n; ++i) { + if (popcount(i) == 1) + ++numberOfBits; + ans = ((ans << numberOfBits) % kMod + i) % kMod; + } + + return ans; + } +}; diff --git a/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.java b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.java new file mode 100644 index 00000000000..f5b12605942 --- /dev/null +++ b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.java @@ -0,0 +1,15 @@ +class Solution { + public int concatenatedBinary(int n) { + final int kMod = 1_000_000_007; + long ans = 0; + int numberOfBits = 0; + + for (int i = 1; i <= n; ++i) { + if (Integer.bitCount(i) == 1) + ++numberOfBits; + ans = ((ans << numberOfBits) % kMod + i) % kMod; + } + + return (int) ans; + } +} diff --git a/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.py b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.py new file mode 100644 index 00000000000..42853365c02 --- /dev/null +++ b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.py @@ -0,0 +1,12 @@ +class Solution: + def concatenatedBinary(self, n: int) -> int: + kMod = 1_000_000_007 + ans = 0 + numberOfBits = 0 + + for i in range(1, n + 1): + if i.bit_count() == 1: + numberOfBits += 1 + ans = ((ans << numberOfBits) + i) % kMod + + return ans diff --git a/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.cpp b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.cpp new file mode 100644 index 00000000000..b87e2f77525 --- /dev/null +++ b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int concatenatedBinary(int n) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + + for (int i = 1; i <= n; ++i) + ans = ((ans << numberOfBits(i)) % kMod + i) % kMod; + + return ans; + } + + private: + int numberOfBits(int n) { + return log2(n) + 1; + } +}; diff --git a/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.java b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.java new file mode 100644 index 00000000000..714919f4bda --- /dev/null +++ b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.java @@ -0,0 +1,15 @@ +class Solution { + public int concatenatedBinary(int n) { + final int kMod = 1_000_000_007; + long ans = 0; + + for (int i = 1; i <= n; ++i) + ans = ((ans << numberOfBits(i)) % kMod + i) % kMod; + + return (int) ans; + } + + private int numberOfBits(int n) { + return (int) (Math.log(n) / Math.log(2)) + 1; + } +} diff --git a/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.py b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.py new file mode 100644 index 00000000000..76564355da6 --- /dev/null +++ b/solutions/1680. Concatenation of Consecutive Binary Numbers/1680.py @@ -0,0 +1,12 @@ +class Solution: + def concatenatedBinary(self, n: int) -> int: + kMod = 1_000_000_007 + ans = 0 + + def numberOfBits(n: int) -> int: + return int(math.log2(n)) + 1 + + for i in range(1, n + 1): + ans = ((ans << numberOfBits(i)) + i) % kMod + + return ans diff --git a/solutions/1681. Minimum Incompatibility/1681.cpp b/solutions/1681. Minimum Incompatibility/1681.cpp new file mode 100644 index 00000000000..e80f23b5675 --- /dev/null +++ b/solutions/1681. Minimum Incompatibility/1681.cpp @@ -0,0 +1,71 @@ +class Solution { + public: + int minimumIncompatibility(vector& nums, int k) { + constexpr int kMaxCompatibility = (16 - 1) * (16 / 2); + const int n = nums.size(); + const int subsetSize = n / k; + const int maxMask = 1 << n; + const vector incompatibilities = + getIncompatibilities(nums, subsetSize); + // dp[i] := the minimum possible sum of incompatibilities of the subset + // of numbers represented by the bitmask i + vector dp(maxMask, kMaxCompatibility); + dp[0] = 0; + + for (unsigned mask = 1; mask < maxMask; ++mask) { + // The number of 1s in `mask` isn't a multiple of `subsetSize`. + if (popcount(mask) % subsetSize != 0) + continue; + // https://cp-algorithms.com/algebra/all-submasks.html + for (int submask = mask; submask > 0; submask = (submask - 1) & mask) + if (incompatibilities[submask] != -1) // valid subset + dp[mask] = + min(dp[mask], dp[mask - submask] + incompatibilities[submask]); + } + + return dp.back() == kMaxCompatibility ? -1 : dp.back(); + } + + private: + static constexpr int kMaxNum = 16; + + // Returns an incompatibilities array where + // * incompatibilities[i] := the incompatibility of the subset of numbers + // represented by the bitmask i + // * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not + // `subsetSize` + vector getIncompatibilities(const vector& nums, int subsetSize) { + const int maxMask = 1 << nums.size(); + vector incompatibilities(maxMask, -1); + for (unsigned mask = 0; mask < maxMask; ++mask) + if (popcount(mask) == subsetSize && isUnique(nums, mask, subsetSize)) + incompatibilities[mask] = getIncompatibility(nums, mask); + return incompatibilities; + } + + // Returns true if the numbers selected by `mask` are unique. + // + // e.g. If we call isUnique(0b1010, 2, [1, 2, 1, 4]), `used` variable + // will be 0b1, which only has one 1 (less than `subsetSize`). In this case, + // we should return false. + bool isUnique(const vector& nums, int mask, int subsetSize) { + unsigned used = 0; + for (int i = 0; i < nums.size(); ++i) + if (mask >> i & 1) + used |= 1 << nums[i]; + return popcount(used) == subsetSize; + } + + // Returns the incompatibility of the selected numbers represented by the + // `mask`. + int getIncompatibility(const vector& nums, int mask) { + int mn = kMaxNum; + int mx = 0; + for (int i = 0; i < nums.size(); ++i) + if (mask >> i & 1) { + mx = max(mx, nums[i]); + mn = min(mn, nums[i]); + } + return mx - mn; + } +}; diff --git a/solutions/1681. Minimum Incompatibility/1681.java b/solutions/1681. Minimum Incompatibility/1681.java new file mode 100644 index 00000000000..cc8c42a233c --- /dev/null +++ b/solutions/1681. Minimum Incompatibility/1681.java @@ -0,0 +1,69 @@ +class Solution { + public int minimumIncompatibility(int[] nums, int k) { + final int kMaxCompatibility = (16 - 1) * (16 / 2); + final int n = nums.length; + final int subsetSize = n / k; + final int maxMask = 1 << n; + final int[] incompatibilities = getIncompatibilities(nums, subsetSize); + // dp[i] := the minimum possible sum of incompatibilities of the subset + // of numbers represented by the bitmask i + int[] dp = new int[maxMask]; + Arrays.fill(dp, kMaxCompatibility); + dp[0] = 0; + + for (int mask = 1; mask < maxMask; ++mask) { + // The number of 1s in `mask` isn't a multiple of `subsetSize`. + if (Integer.bitCount(mask) % subsetSize != 0) + continue; + // https://cp-algorithms.com/algebra/all-submasks.html + for (int submask = mask; submask > 0; submask = (submask - 1) & mask) + if (incompatibilities[submask] != -1) // valid submask + dp[mask] = Math.min(dp[mask], dp[mask - submask] + incompatibilities[submask]); + } + + return dp[maxMask - 1] == kMaxCompatibility ? -1 : dp[maxMask - 1]; + } + + private static final int kMaxNum = 16; + + // Returns an incompatibilities array where + // * incompatibilities[i] := the incompatibility of the subset of numbers + // represented by the bitmask i + // * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not + // `subsetSize` + private int[] getIncompatibilities(int[] nums, int subsetSize) { + final int maxMask = 1 << nums.length; + int[] incompatibilities = new int[maxMask]; + Arrays.fill(incompatibilities, -1); + for (int mask = 0; mask < maxMask; ++mask) + if (Integer.bitCount(mask) == subsetSize && isUnique(nums, mask, subsetSize)) + incompatibilities[mask] = getIncompatibility(nums, mask); + return incompatibilities; + } + + // Returns true if the numbers selected by `mask` are unique. + // + // e.g. If we call isUnique(0b1010, 2, [1, 2, 1, 4]), `used` variable + // will be 0b1, which only has one 1 (less than `subsetSize`). In this case, + // we should return false. + private boolean isUnique(int[] nums, int mask, int subsetSize) { + int used = 0; + for (int i = 0; i < nums.length; ++i) + if ((mask >> i & 1) == 1) + used |= 1 << nums[i]; + return Integer.bitCount(used) == subsetSize; + } + + // Returns the incompatibility of the selected numbers represented by the + // `mask`. + private int getIncompatibility(int[] nums, int mask) { + int mn = kMaxNum; + int mx = 0; + for (int i = 0; i < nums.length; ++i) + if ((mask >> i & 1) == 1) { + mx = Math.max(mx, nums[i]); + mn = Math.min(mn, nums[i]); + } + return mx - mn; + } +} diff --git a/solutions/1681. Minimum Incompatibility/1681.py b/solutions/1681. Minimum Incompatibility/1681.py new file mode 100644 index 00000000000..6d3e7a30517 --- /dev/null +++ b/solutions/1681. Minimum Incompatibility/1681.py @@ -0,0 +1,65 @@ +class Solution: + def __init__(self): + self.kMaxNum = 16 + + def minimumIncompatibility(self, nums: List[int], k: int) -> int: + kMaxCompatibility = (16 - 1) * (16 // 2) + n = len(nums) + subsetSize = n // k + maxMask = 1 << n + incompatibilities = self._getIncompatibilities(nums, subsetSize) + + # dp[i] := the minimum possible sum of incompatibilities of the subset + # of numbers represented by the bitmask i + dp = [kMaxCompatibility] * maxMask + dp[0] = 0 + + for mask in range(1, maxMask): + # The number of 1s in `mask` isn't a multiple of `subsetSize`. + if mask.bit_count() % subsetSize != 0: + continue + # https://cp-algorithms.com/algebra/all-submasks.html + submask = mask + while submask > 0: + if incompatibilities[submask] != -1: # valid submask + dp[mask] = min(dp[mask], dp[mask - submask] + + incompatibilities[submask]) + submask = (submask - 1) & mask + + return dp[-1] if dp[-1] != kMaxCompatibility else -1 + + def _getIncompatibilities(self, nums: List[int], subsetSize: int) -> List[int]: + """ + Returns an incompatibilities array where + * incompatibilities[i] := the incompatibility of the subset of numbers + represented by the bitmask i + * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not + `subsetSize` + """ + maxMask = 1 << len(nums) + incompatibilities = [-1] * maxMask + for mask in range(maxMask): + if mask.bit_count() == subsetSize and self._isUnique(nums, mask, subsetSize): + incompatibilities[mask] = self._getIncompatibility(nums, mask) + return incompatibilities + + def _isUnique(self, nums: List[int], mask: int, subsetSize: int) -> bool: + """Returns True if the numbers selected by `mask` are unique.""" + used = 0 + for i, num in enumerate(nums): + if mask >> i & 1: + used |= 1 << num + return used.bit_count() == subsetSize + + def _getIncompatibility(self, nums: List[int], mask: int) -> int: + """ + Returns the incompatibility of the selected numbers represented by the + `mask`. + """ + mn = self.kMaxNum + mx = 0 + for i, num in enumerate(nums): + if mask >> i & 1: + mx = max(mx, num) + mn = min(mn, num) + return mx - mn diff --git a/solutions/1682. Longest Palindromic Subsequence II/1682-2.cpp b/solutions/1682. Longest Palindromic Subsequence II/1682-2.cpp new file mode 100644 index 00000000000..b40d9608416 --- /dev/null +++ b/solutions/1682. Longest Palindromic Subsequence II/1682-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int longestPalindromeSubseq(string s) { + const int n = s.length(); + // dp[i][j][k] := the length of LPS(s[i..j]), where the previous letter is + // ('a' + k). + vector>> dp(n, vector>(n, vector(27))); + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) + for (int k = 0; k <= 26; ++k) { + const int j = i + d; + if (s[i] == s[j] && s[i] != 'a' + k) + dp[i][j][k] = dp[i + 1][j - 1][s[i] - 'a'] + 2; + else + dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k]); + } + + return dp[0][n - 1][26]; + } +}; diff --git a/solutions/1682. Longest Palindromic Subsequence II/1682-2.java b/solutions/1682. Longest Palindromic Subsequence II/1682-2.java new file mode 100644 index 00000000000..05bff061c21 --- /dev/null +++ b/solutions/1682. Longest Palindromic Subsequence II/1682-2.java @@ -0,0 +1,20 @@ +class Solution { + public int longestPalindromeSubseq(String s) { + final int n = s.length(); + // dp[i][j][k] := the length of LPS(s[i..j]), where the previous letter is + // ('a' + k). + int[][][] dp = new int[n][n][27]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) + for (int k = 0; k <= 26; ++k) { + final int j = i + d; + if (s.charAt(i) == s.charAt(j) && s.charAt(i) != 'a' + k) + dp[i][j][k] = dp[i + 1][j - 1][s.charAt(i) - 'a'] + 2; + else + dp[i][j][k] = Math.max(dp[i + 1][j][k], dp[i][j - 1][k]); + } + + return dp[0][n - 1][26]; + } +} diff --git a/solutions/1682. Longest Palindromic Subsequence II/1682-2.py b/solutions/1682. Longest Palindromic Subsequence II/1682-2.py new file mode 100644 index 00000000000..0f7f0f12591 --- /dev/null +++ b/solutions/1682. Longest Palindromic Subsequence II/1682-2.py @@ -0,0 +1,17 @@ +class Solution: + def longestPalindromeSubseq(self, s: str) -> int: + n = len(s) + # dp[i][j][k] := the length of LPS(s[i..j]), where the previous letter is + # ('a' + k). + dp = [[[0] * 27 for _ in range(n)] for _ in range(n)] + + for d in range(1, n): + for i in range(n - d): + for k in range(27): + j = i + d + if s[i] == s[j] and s[i] != chr(ord('a') + k): + dp[i][j][k] = dp[i + 1][j - 1][ord(s[i]) - ord('a')] + 2 + else: + dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k]) + + return dp[0][n - 1][26] diff --git a/solutions/1682. Longest Palindromic Subsequence II/1682.cpp b/solutions/1682. Longest Palindromic Subsequence II/1682.cpp new file mode 100644 index 00000000000..608731e9706 --- /dev/null +++ b/solutions/1682. Longest Palindromic Subsequence II/1682.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int longestPalindromeSubseq(string s) { + const int n = s.length(); + vector>> mem(n, vector>(n, vector(27))); + return lps(s, 0, n - 1, 26, mem); + } + + private: + // Returns the length of LPS(s[i..j]), where the previous letter is ('a' + k). + int lps(const string& s, int i, int j, int k, + vector>>& mem) { + if (i >= j) + return 0; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + if (s[i] == s[j] && s[i] != 'a' + k) + return mem[i][j][k] = lps(s, i + 1, j - 1, s[i] - 'a', mem) + 2; + return mem[i][j][k] = + max(lps(s, i + 1, j, k, mem), lps(s, i, j - 1, k, mem)); + } +}; diff --git a/solutions/1682. Longest Palindromic Subsequence II/1682.java b/solutions/1682. Longest Palindromic Subsequence II/1682.java new file mode 100644 index 00000000000..8df186c5e9e --- /dev/null +++ b/solutions/1682. Longest Palindromic Subsequence II/1682.java @@ -0,0 +1,18 @@ +class Solution { + public int longestPalindromeSubseq(String s) { + final int n = s.length(); + int[][][] mem = new int[n][n][27]; + return lps(s, 0, n - 1, 26, mem); + } + + // Returns the length of LPS(s[i..j]), where the previous letter is ('a' + k). + private int lps(final String s, int i, int j, int k, int[][][] mem) { + if (i >= j) + return 0; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + if (s.charAt(i) == s.charAt(j) && s.charAt(i) != (char) (k + 'a')) + return mem[i][j][k] = lps(s, i + 1, j - 1, s.charAt(i) - 'a', mem) + 2; + return mem[i][j][k] = Math.max(lps(s, i + 1, j, k, mem), lps(s, i, j - 1, k, mem)); + } +} diff --git a/solutions/1682. Longest Palindromic Subsequence II/1682.py b/solutions/1682. Longest Palindromic Subsequence II/1682.py new file mode 100644 index 00000000000..8850b261133 --- /dev/null +++ b/solutions/1682. Longest Palindromic Subsequence II/1682.py @@ -0,0 +1,17 @@ +class Solution: + def longestPalindromeSubseq(self, s: str) -> int: + n = len(s) + + @functools.lru_cache(None) + def dp(i: int, j: int, k: int) -> int: + """ + Returns the length of LPS(s[i..j]), where the previous letter is + ('a' + k). + """ + if i >= j: + return 0 + if s[i] == s[j] and s[i] != chr(ord('a') + k): + return dp(i + 1, j - 1, ord(s[i]) - ord('a')) + 2 + return max(dp(i + 1, j, k), dp(i, j - 1, k)) + + return dp(0, n - 1, 26) diff --git a/solutions/1683. Invalid Tweets/1683.sql b/solutions/1683. Invalid Tweets/1683.sql new file mode 100644 index 00000000000..0bcc7257c9e --- /dev/null +++ b/solutions/1683. Invalid Tweets/1683.sql @@ -0,0 +1,3 @@ +SELECT tweet_id +FROM Tweets +WHERE CHAR_LENGTH(content) > 15; diff --git a/solutions/1684. Count the Number of Consistent Strings/1684.cpp b/solutions/1684. Count the Number of Consistent Strings/1684.cpp new file mode 100644 index 00000000000..2c2c1745049 --- /dev/null +++ b/solutions/1684. Count the Number of Consistent Strings/1684.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int countConsistentStrings(string allowed, vector& words) { + return accumulate(words.begin(), words.end(), 0, + [&allowed](int subtotal, const string& word) { + return subtotal + ranges::all_of(word, [&allowed](char c) { + return allowed.find(c) != string::npos; + }); + }); + } +}; diff --git a/solutions/1684. Count the Number of Consistent Strings/1684.java b/solutions/1684. Count the Number of Consistent Strings/1684.java new file mode 100644 index 00000000000..1fb8b13882f --- /dev/null +++ b/solutions/1684. Count the Number of Consistent Strings/1684.java @@ -0,0 +1,7 @@ +class Solution { + public int countConsistentStrings(String allowed, String[] words) { + return (int) Arrays.stream(words) + .filter(word -> word.matches(String.format("[%s]*", allowed))) + .count(); + } +} diff --git a/solutions/1684. Count the Number of Consistent Strings/1684.py b/solutions/1684. Count the Number of Consistent Strings/1684.py new file mode 100644 index 00000000000..aa501c85802 --- /dev/null +++ b/solutions/1684. Count the Number of Consistent Strings/1684.py @@ -0,0 +1,4 @@ +class Solution: + def countConsistentStrings(self, allowed: str, words: List[str]) -> int: + return sum(all(c in allowed for c in word) + for word in words) diff --git a/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.cpp b/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.cpp new file mode 100644 index 00000000000..ba427aa1f4f --- /dev/null +++ b/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector getSumAbsoluteDifferences(vector& nums) { + const int n = nums.size(); + vector ans; + // prefix[i] := sum(nums[0..i]) + vector prefix(n); + // suffix[i] := sum(nums[i..n - 1]) + vector suffix(n); + + prefix[0] = nums[0]; + for (int i = 1; i < n; ++i) + prefix[i] = prefix[i - 1] + nums[i]; + + suffix[n - 1] = nums[n - 1]; + for (int i = n - 2; i >= 0; --i) + suffix[i] = suffix[i + 1] + nums[i]; + + for (int i = 0; i < nums.size(); ++i) { + const int left = nums[i] * (i + 1) - prefix[i]; + const int right = suffix[i] - nums[i] * (n - i); + ans.push_back(left + right); + } + + return ans; + } +}; diff --git a/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.java b/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.java new file mode 100644 index 00000000000..c5c88ce9323 --- /dev/null +++ b/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.java @@ -0,0 +1,24 @@ +class Solution { + public int[] getSumAbsoluteDifferences(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + int[] prefix = new int[n]; + int[] suffix = new int[n]; + + prefix[0] = nums[0]; + for (int i = 1; i < n; ++i) + prefix[i] = prefix[i - 1] + nums[i]; + + suffix[n - 1] = nums[n - 1]; + for (int i = n - 2; i >= 0; --i) + suffix[i] = suffix[i + 1] + nums[i]; + + for (int i = 0; i < nums.length; ++i) { + final int left = nums[i] * (i + 1) - prefix[i]; + final int right = suffix[i] - nums[i] * (n - i); + ans[i] = left + right; + } + + return ans; + } +} diff --git a/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.py b/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.py new file mode 100644 index 00000000000..7a9f8b9128a --- /dev/null +++ b/solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.py @@ -0,0 +1,6 @@ +class Solution: + def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: + prefix = list(itertools.accumulate(nums)) + suffix = list(itertools.accumulate(nums[::-1]))[::-1] + return [num * (i + 1) - prefix[i] + suffix[i] - num * (len(nums) - i) + for i, num in enumerate(nums)] diff --git a/solutions/1686. Stone Game VI/1686.cpp b/solutions/1686. Stone Game VI/1686.cpp new file mode 100644 index 00000000000..95ce963b4f3 --- /dev/null +++ b/solutions/1686. Stone Game VI/1686.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int stoneGameVI(vector& aliceValues, vector& bobValues) { + const int n = aliceValues.size(); + vector> values; + int a = 0; + int b = 0; + + for (int i = 0; i < n; ++i) + values.push_back({aliceValues[i], bobValues[i]}); + + ranges::sort(values, [](const vector& a, const vector& b) { + return a[0] + a[1] > b[0] + b[1]; + }); + + for (int i = 0; i < n; ++i) + if (i % 2 == 0) + a += values[i][0]; + else + b += values[i][1]; + + return a > b ? 1 : a < b ? -1 : 0; + } +}; diff --git a/solutions/1686. Stone Game VI/1686.java b/solutions/1686. Stone Game VI/1686.java new file mode 100644 index 00000000000..eee6b6092f9 --- /dev/null +++ b/solutions/1686. Stone Game VI/1686.java @@ -0,0 +1,22 @@ +class Solution { + public int stoneGameVI(int[] aliceValues, int[] bobValues) { + final int n = aliceValues.length; + int[][] values = new int[n][]; + + for (int i = 0; i < n; ++i) + values[i] = new int[] {aliceValues[i], bobValues[i]}; + + Arrays.sort(values, (a, b) -> b[0] + b[1] - a[0] - a[1]); + + int a = 0; + int b = 0; + + for (int i = 0; i < n; ++i) + if (i % 2 == 0) + a += values[i][0]; + else + b += values[i][1]; + + return Integer.compare(a, b); + } +} diff --git a/solutions/1687. Delivering Boxes from Storage to Ports/1687.cpp b/solutions/1687. Delivering Boxes from Storage to Ports/1687.cpp new file mode 100644 index 00000000000..f78863e33d3 --- /dev/null +++ b/solutions/1687. Delivering Boxes from Storage to Ports/1687.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int boxDelivering(vector>& boxes, int portsCount, int maxBoxes, + int maxWeight) { + const int n = boxes.size(); + // dp[i] := the minimum trips to deliver boxes[0..i) and return to the + // storage + vector dp(n + 1); + int trips = 2; + int weight = 0; + + for (int l = 0, r = 0; r < n; ++r) { + weight += boxes[r][1]; + + // The current box is different from the previous one, need to make one + // more trip. + if (r > 0 && boxes[r][0] != boxes[r - 1][0]) + ++trips; + + while (r - l + 1 > maxBoxes || weight > maxWeight || + // Loading boxes[l] in the previous turn is always no bad than + // loading it in this turn. + (l < r && dp[l + 1] == dp[l])) { + weight -= boxes[l][1]; + if (boxes[l][0] != boxes[l + 1][0]) + --trips; + ++l; + } + + // min trips to deliver boxes[0..r] + // = min trips to deliver boxes[0..l) + trips to deliver boxes[l..r] + dp[r + 1] = dp[l] + trips; + } + + return dp[n]; + } +}; diff --git a/solutions/1687. Delivering Boxes from Storage to Ports/1687.java b/solutions/1687. Delivering Boxes from Storage to Ports/1687.java new file mode 100644 index 00000000000..1e0add48878 --- /dev/null +++ b/solutions/1687. Delivering Boxes from Storage to Ports/1687.java @@ -0,0 +1,36 @@ +class Solution { + public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { + final int n = boxes.length; + // dp[i] := the minimum trips to deliver boxes[0..i) and return to the + // storage + int[] dp = new int[n + 1]; + int trips = 2; + int weight = 0; + + for (int l = 0, r = 0; r < n; ++r) { + weight += boxes[r][1]; + + // The current box is different from the previous one, need to make one + // more trip. + if (r > 0 && boxes[r][0] != boxes[r - 1][0]) + ++trips; + + while (r - l + 1 > maxBoxes || weight > maxWeight || + // Loading boxes[l] in the previous turn is always no bad than + // loading it in this turn. + (l < r && dp[l + 1] == dp[l])) { + weight -= boxes[l][1]; + if (boxes[l][0] != boxes[l + 1][0]) + --trips; + ++l; + } + + // the minimum trips to deliver boxes[0..r] + // = the minimum trips to deliver boxes[0..l) + + // trips to deliver boxes[l..r] + dp[r + 1] = dp[l] + trips; + } + + return dp[n]; + } +} diff --git a/solutions/1687. Delivering Boxes from Storage to Ports/1687.py b/solutions/1687. Delivering Boxes from Storage to Ports/1687.py new file mode 100644 index 00000000000..01db90b493b --- /dev/null +++ b/solutions/1687. Delivering Boxes from Storage to Ports/1687.py @@ -0,0 +1,31 @@ +class Solution: + def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: + n = len(boxes) + # dp[i] := the minimum trips to deliver boxes[0..i) and return to the + # storage + dp = [0] * (n + 1) + trips = 2 + weight = 0 + + l = 0 + for r in range(n): + weight += boxes[r][1] + + # The current box is different from the previous one, need to make one + # more trip. + if r > 0 and boxes[r][0] != boxes[r - 1][0]: + trips += 1 + + # Loading boxes[l] in the previous turn is always no bad than loading it + # in this turn + while r - l + 1 > maxBoxes or weight > maxWeight or (l < r and dp[l + 1] == dp[l]): + weight -= boxes[l][1] + if boxes[l][0] != boxes[l + 1][0]: + trips -= 1 + l += 1 + + # min trips to deliver boxes[0..r] + # = min trips to deliver boxes[0..l) + trips to deliver boxes[l..r] + dp[r + 1] = dp[l] + trips + + return dp[n] diff --git a/solutions/1688. Count of Matches in Tournament/1688.cpp b/solutions/1688. Count of Matches in Tournament/1688.cpp new file mode 100644 index 00000000000..b67acbba85c --- /dev/null +++ b/solutions/1688. Count of Matches in Tournament/1688.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int numberOfMatches(int n) { + return n - 1; + } +}; diff --git a/solutions/1688. Count of Matches in Tournament/1688.java b/solutions/1688. Count of Matches in Tournament/1688.java new file mode 100644 index 00000000000..c2ea4b1715f --- /dev/null +++ b/solutions/1688. Count of Matches in Tournament/1688.java @@ -0,0 +1,5 @@ +class Solution { + public int numberOfMatches(int n) { + return n - 1; + } +} diff --git a/solutions/1688. Count of Matches in Tournament/1688.py b/solutions/1688. Count of Matches in Tournament/1688.py new file mode 100644 index 00000000000..cfe0d5360f3 --- /dev/null +++ b/solutions/1688. Count of Matches in Tournament/1688.py @@ -0,0 +1,3 @@ +class Solution: + def numberOfMatches(self, n: int) -> int: + return n - 1 diff --git a/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.cpp b/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.cpp new file mode 100644 index 00000000000..185439782a7 --- /dev/null +++ b/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int minPartitions(string n) { + return ranges::max(n) - '0'; + } +}; diff --git a/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.java b/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.java new file mode 100644 index 00000000000..26394e29414 --- /dev/null +++ b/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.java @@ -0,0 +1,5 @@ +class Solution { + public int minPartitions(String n) { + return Character.getNumericValue(n.chars().max().getAsInt()); + } +} diff --git a/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.py b/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.py new file mode 100644 index 00000000000..86c27f79e6e --- /dev/null +++ b/solutions/1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/1689.py @@ -0,0 +1,3 @@ +class Solution: + def minPartitions(self, n: str) -> int: + return int(max(n)) diff --git a/solutions/169. Majority Element/169.cpp b/solutions/169. Majority Element/169.cpp new file mode 100644 index 00000000000..9cc3fa3d632 --- /dev/null +++ b/solutions/169. Majority Element/169.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int majorityElement(vector& nums) { + int ans; + int count = 0; + + for (const int num : nums) { + if (count == 0) + ans = num; + count += num == ans ? 1 : -1; + } + + return ans; + } +}; diff --git a/solutions/169. Majority Element/169.java b/solutions/169. Majority Element/169.java new file mode 100644 index 00000000000..e1e139284c0 --- /dev/null +++ b/solutions/169. Majority Element/169.java @@ -0,0 +1,14 @@ +class Solution { + public int majorityElement(int[] nums) { + Integer ans = null; + int count = 0; + + for (final int num : nums) { + if (count == 0) + ans = num; + count += num == ans ? 1 : -1; + } + + return ans; + } +} diff --git a/solutions/169. Majority Element/169.py b/solutions/169. Majority Element/169.py new file mode 100644 index 00000000000..8e376e6d31a --- /dev/null +++ b/solutions/169. Majority Element/169.py @@ -0,0 +1,11 @@ +class Solution: + def majorityElement(self, nums: List[int]) -> int: + ans = None + count = 0 + + for num in nums: + if count == 0: + ans = num + count += (1 if num == ans else -1) + + return ans diff --git a/solutions/1690. Stone Game VII/1690-2.cpp b/solutions/1690. Stone Game VII/1690-2.cpp new file mode 100644 index 00000000000..1d4f299c061 --- /dev/null +++ b/solutions/1690. Stone Game VII/1690-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int stoneGameVII(vector& stones) { + const int n = stones.size(); + // dp[i][j] := the maximum score you can get more than your opponent in + // stones[i..j] + vector> dp(n, vector(n)); + vector prefix(n + 1); + + partial_sum(stones.begin(), stones.end(), prefix.begin() + 1); + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + dp[i][j] = max(prefix[j + 1] - prefix[i + 1] - dp[i + 1][j], + prefix[j] - prefix[i] - dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/1690. Stone Game VII/1690-2.java b/solutions/1690. Stone Game VII/1690-2.java new file mode 100644 index 00000000000..011f675515a --- /dev/null +++ b/solutions/1690. Stone Game VII/1690-2.java @@ -0,0 +1,20 @@ +class Solution { + public int stoneGameVII(int[] stones) { + final int n = stones.length; + // dp[i][j] := the maximum score you can get more than your opponent in stones[i..j] + int[][] dp = new int[n][n]; + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; ++i) + prefix[i + 1] = stones[i] + prefix[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + dp[i][j] = Math.max(prefix[j + 1] - prefix[i + 1] - dp[i + 1][j], + prefix[j] - prefix[i] - dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/1690. Stone Game VII/1690.cpp b/solutions/1690. Stone Game VII/1690.cpp new file mode 100644 index 00000000000..a6b53a06693 --- /dev/null +++ b/solutions/1690. Stone Game VII/1690.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int stoneGameVII(vector& stones) { + const int n = stones.size(); + vector> mem(n, vector(n)); + vector prefix(n + 1); + partial_sum(stones.begin(), stones.end(), prefix.begin() + 1); + return stoneGameVII(stones, 0, n - 1, prefix, mem); + } + + private: + // Returns the maximum score you can get more than your opponent in + // stones[i..j]. + int stoneGameVII(const vector& stones, int i, int j, + const vector& prefix, vector>& mem) { + if (i == j) + return 0; + if (mem[i][j] > 0) + return mem[i][j]; + // Remove stones[i] to get sum(stones[i + 1..j]). + const int removeLeft = prefix[j + 1] - prefix[i + 1] - + stoneGameVII(stones, i + 1, j, prefix, mem); + // Remove stones[j] to get sum(stones[i..j - 1]). + const int removeRight = prefix[j] - prefix[i] - // + stoneGameVII(stones, i, j - 1, prefix, mem); + return mem[i][j] = max(removeLeft, removeRight); + } +}; diff --git a/solutions/1690. Stone Game VII/1690.java b/solutions/1690. Stone Game VII/1690.java new file mode 100644 index 00000000000..692cbc3f4db --- /dev/null +++ b/solutions/1690. Stone Game VII/1690.java @@ -0,0 +1,27 @@ +class Solution { + public int stoneGameVII(int[] stones) { + final int n = stones.length; + Integer[][] mem = new Integer[n][n]; + int[] prefix = new int[n + 1]; + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + stones[i]; + return stoneGameVII(stones, 0, n - 1, prefix, mem); + } + + // Returns the maximum score you can get more than your opponent in + // stones[i..j]. + private int stoneGameVII(int[] stones, int i, int j, int[] prefix, Integer[][] mem) { + if (i == j) + return 0; + if (mem[i][j] != null) + return mem[i][j]; + // Remove stones[i] to get sum(stones[i + 1..j]). + final int removeLeft = prefix[j + 1] - prefix[i + 1] - // + stoneGameVII(stones, i + 1, j, prefix, mem); + + // Remove stones[j] to get sum(stones[i..j - 1]). + final int removeRight = prefix[j] - prefix[i] - // + stoneGameVII(stones, i, j - 1, prefix, mem); + return mem[i][j] = Math.max(removeLeft, removeRight); + } +} diff --git a/solutions/1691. Maximum Height by Stacking Cuboids/1691.cpp b/solutions/1691. Maximum Height by Stacking Cuboids/1691.cpp new file mode 100644 index 00000000000..cba968ad748 --- /dev/null +++ b/solutions/1691. Maximum Height by Stacking Cuboids/1691.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int maxHeight(vector>& cuboids) { + // For each cuboid, sort it so that c[0] <= c[1] <= c[2]. + for (vector& cuboid : cuboids) + ranges::sort(cuboid); + + ranges::sort(cuboids); + + // dp[i] := the maximum height with cuboids[i] in the bottom + vector dp(cuboids.size()); + + for (int i = 0; i < cuboids.size(); ++i) + dp[i] = cuboids[i][2]; + + for (int i = 1; i < cuboids.size(); ++i) + for (int j = 0; j < i; ++j) + if (cuboids[j][0] <= cuboids[i][0] && // + cuboids[j][1] <= cuboids[i][1] && // + cuboids[j][2] <= cuboids[i][2]) + dp[i] = max(dp[i], dp[j] + cuboids[i][2]); + + return ranges::max(dp); + } +}; diff --git a/solutions/1691. Maximum Height by Stacking Cuboids/1691.java b/solutions/1691. Maximum Height by Stacking Cuboids/1691.java new file mode 100644 index 00000000000..1aa416ef1f0 --- /dev/null +++ b/solutions/1691. Maximum Height by Stacking Cuboids/1691.java @@ -0,0 +1,33 @@ +class Solution { + public int maxHeight(int[][] cuboids) { + // For each cuboid, sort it so that c[0] <= c[1] <= c[2]. + for (int[] cuboid : cuboids) + Arrays.sort(cuboid); + + Arrays.sort(cuboids, new Comparator() { + @Override + public int compare(int[] a, int[] b) { + if (a[0] != b[0]) + return a[0] - b[0]; + if (a[1] != b[1]) + return a[1] - b[1]; + return a[2] - b[2]; + } + }); + + // dp[i] := the maximum height with cuboids[i] in the bottom + int[] dp = new int[cuboids.length]; + + for (int i = 0; i < cuboids.length; ++i) + dp[i] = cuboids[i][2]; + + for (int i = 1; i < cuboids.length; ++i) + for (int j = 0; j < i; ++j) + if (cuboids[j][0] <= cuboids[i][0] && // + cuboids[j][1] <= cuboids[i][1] && // + cuboids[j][2] <= cuboids[i][2]) + dp[i] = Math.max(dp[i], dp[j] + cuboids[i][2]); + + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/1692. Count Ways to Distribute Candies/1692-2.cpp b/solutions/1692. Count Ways to Distribute Candies/1692-2.cpp new file mode 100644 index 00000000000..95cd997f4dc --- /dev/null +++ b/solutions/1692. Count Ways to Distribute Candies/1692-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int waysToDistribute(int n, int k) { + constexpr int kMod = 1'000'000'007; + vector> dp(k + 1, vector(n + 1)); + + for (int i = 0; i <= k; ++i) + dp[i][i] = 1; + + for (int i = 1; i <= k; ++i) + for (int j = i + 1; j <= n; ++j) + dp[i][j] = (dp[i - 1][j - 1] + i * dp[i][j - 1]) % kMod; + + return dp[k][n]; + } +}; diff --git a/solutions/1692. Count Ways to Distribute Candies/1692-2.java b/solutions/1692. Count Ways to Distribute Candies/1692-2.java new file mode 100644 index 00000000000..4480507436b --- /dev/null +++ b/solutions/1692. Count Ways to Distribute Candies/1692-2.java @@ -0,0 +1,15 @@ +class Solution { + public int waysToDistribute(int n, int k) { + final int kMod = 1_000_000_007; + long[][] dp = new long[k + 1][n + 1]; + + for (int i = 0; i <= k; ++i) + dp[i][i] = 1; + + for (int i = 1; i <= k; ++i) + for (int j = i + 1; j <= n; ++j) + dp[i][j] = (dp[i - 1][j - 1] + i * dp[i][j - 1]) % kMod; + + return (int) dp[k][n]; + } +} diff --git a/solutions/1692. Count Ways to Distribute Candies/1692.cpp b/solutions/1692. Count Ways to Distribute Candies/1692.cpp new file mode 100644 index 00000000000..d6cd861e41c --- /dev/null +++ b/solutions/1692. Count Ways to Distribute Candies/1692.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int waysToDistribute(int n, int k) { + constexpr int kMod = 1'000'000'007; + // dp[i][j] := the number of ways to distribute i candies to j bags + // dp[i][j] = 0, if i < j + // = 1, if i == j + // = dp[i - 1][j - 1] (the new candy occupies a bag) + // + dp[i - 1][j] * j (the new candy is in any of the j bags) + vector> dp(n + 1, vector(k + 1)); + + for (int i = 0; i <= k; ++i) + dp[i][i] = 1; + + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) + dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j] * j) % kMod; + + return dp[n][k]; + } +}; diff --git a/solutions/1692. Count Ways to Distribute Candies/1692.java b/solutions/1692. Count Ways to Distribute Candies/1692.java new file mode 100644 index 00000000000..03919033150 --- /dev/null +++ b/solutions/1692. Count Ways to Distribute Candies/1692.java @@ -0,0 +1,20 @@ +class Solution { + public int waysToDistribute(int n, int k) { + final int kMod = 1_000_000_007; + // dp[i][j] := the number of ways to distribute i candies to j bags + // dp[i][j] = 0, if i < j + // = 1, if i == j + // = dp[i - 1][j - 1] (the new candy occupies a bag) + // + dp[i - 1][j] * j (the new candy is in any of the j bags) + long[][] dp = new long[n + 1][k + 1]; + + for (int i = 0; i <= k; ++i) + dp[i][i] = 1; + + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) + dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j] * j) % kMod; + + return (int) dp[n][k]; + } +} diff --git a/solutions/1693. Daily Leads and Partners/1693.sql b/solutions/1693. Daily Leads and Partners/1693.sql new file mode 100644 index 00000000000..421d111b7e2 --- /dev/null +++ b/solutions/1693. Daily Leads and Partners/1693.sql @@ -0,0 +1,7 @@ +SELECT + date_id, + make_name, + COUNT(DISTINCT lead_id) AS unique_leads, + COUNT(DISTINCT partner_id) AS unique_partners +FROM DailySales +GROUP BY 1, 2; diff --git a/solutions/1694. Reformat Phone Number/1694.cpp b/solutions/1694. Reformat Phone Number/1694.cpp new file mode 100644 index 00000000000..f01f771cb80 --- /dev/null +++ b/solutions/1694. Reformat Phone Number/1694.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string reformatNumber(string number) { + string ans; + + std::erase(number, '-'); + std::erase(number, ' '); + + int i = 0; // number's index + for (i = 0; i + 4 < number.length(); i += 3) + ans += number.substr(i, 3) + '-'; + + const int countFinalDigits = number.length() - i; + if (countFinalDigits < 4) + ans += number.substr(i); + else // countFinalDigits == 4 + ans += number.substr(i, 2) + '-' + number.substr(i + 2); + + return ans; + } +}; diff --git a/solutions/1694. Reformat Phone Number/1694.java b/solutions/1694. Reformat Phone Number/1694.java new file mode 100644 index 00000000000..d2b260ea884 --- /dev/null +++ b/solutions/1694. Reformat Phone Number/1694.java @@ -0,0 +1,19 @@ +class Solution { + public String reformatNumber(String number) { + StringBuilder sb = new StringBuilder(); + + number = number.replaceAll("[-\\s]", ""); + + int i = 0; // number's index + for (i = 0; i + 4 < number.length(); i += 3) + sb.append(number.substring(i, i + 3) + '-'); + + final int countFinalDigits = number.length() - i; + if (countFinalDigits < 4) + sb.append(number.substring(i)); + else // countFinalDigits == 4 + sb.append(number.substring(i, i + 2) + '-' + number.substring(i + 2)); + + return sb.toString(); + } +} diff --git a/solutions/1694. Reformat Phone Number/1694.py b/solutions/1694. Reformat Phone Number/1694.py new file mode 100644 index 00000000000..921defcd173 --- /dev/null +++ b/solutions/1694. Reformat Phone Number/1694.py @@ -0,0 +1,18 @@ +class Solution: + def reformatNumber(self, number: str) -> str: + ans = [] + + number = number.replace("-", "").replace(" ", "") + + i = 0 # number's index + while i + 4 < len(number): + ans.append(number[i:i + 3] + '-') + i += 3 + + countFinalDigits = len(number) - i + if countFinalDigits < 4: + ans.append(number[i:]) + else: # countFinalDigits == 4 + ans.append(number[i:i + 2] + '-' + number[i + 2:]) + + return ''.join(ans) diff --git a/solutions/1695. Maximum Erasure Value/1695.cpp b/solutions/1695. Maximum Erasure Value/1695.cpp new file mode 100644 index 00000000000..feefa3ce085 --- /dev/null +++ b/solutions/1695. Maximum Erasure Value/1695.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maximumUniqueSubarray(vector& nums) { + int ans = 0; + int score = 0; + unordered_set seen; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + while (!seen.insert(nums[r]).second) { + score -= nums[l]; + seen.erase(nums[l++]); + } + score += nums[r]; + ans = max(ans, score); + } + + return ans; + } +}; diff --git a/solutions/1695. Maximum Erasure Value/1695.java b/solutions/1695. Maximum Erasure Value/1695.java new file mode 100644 index 00000000000..c3d617d68de --- /dev/null +++ b/solutions/1695. Maximum Erasure Value/1695.java @@ -0,0 +1,18 @@ +class Solution { + public int maximumUniqueSubarray(int[] nums) { + int ans = 0; + int score = 0; + Set seen = new HashSet<>(); + + for (int l = 0, r = 0; r < nums.length; ++r) { + while (!seen.add(nums[r])) { + score -= nums[l]; + seen.remove(nums[l++]); + } + score += nums[r]; + ans = Math.max(ans, score); + } + + return ans; + } +} diff --git a/solutions/1695. Maximum Erasure Value/1695.py b/solutions/1695. Maximum Erasure Value/1695.py new file mode 100644 index 00000000000..1cec3da6aac --- /dev/null +++ b/solutions/1695. Maximum Erasure Value/1695.py @@ -0,0 +1,17 @@ +class Solution: + def maximumUniqueSubarray(self, nums: List[int]) -> int: + ans = 0 + score = 0 + seen = set() + + l = 0 + for r, num in enumerate(nums): + while num in seen: + score -= nums[l] + seen.remove(nums[l]) + l += 1 + seen.add(nums[r]) + score += nums[r] + ans = max(ans, score) + + return ans diff --git a/solutions/1696. Jump Game VI/1696.cpp b/solutions/1696. Jump Game VI/1696.cpp new file mode 100644 index 00000000000..3a1809a6611 --- /dev/null +++ b/solutions/1696. Jump Game VI/1696.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int maxResult(vector& nums, int k) { + // Stores dp[i] within the bounds. + deque maxQ{0}; + // dp[i] := the maximum score to consider nums[0..i] + vector dp(nums.size()); + dp[0] = nums[0]; + + for (int i = 1; i < nums.size(); ++i) { + // Pop the index if it's out-of-bounds. + if (maxQ.front() + k < i) + maxQ.pop_front(); + dp[i] = dp[maxQ.front()] + nums[i]; + // Pop indices that won't be chosen in the future. + while (!maxQ.empty() && dp[maxQ.back()] <= dp[i]) + maxQ.pop_back(); + maxQ.push_back(i); + } + + return dp.back(); + } +}; diff --git a/solutions/1696. Jump Game VI/1696.java b/solutions/1696. Jump Game VI/1696.java new file mode 100644 index 00000000000..34690df3f71 --- /dev/null +++ b/solutions/1696. Jump Game VI/1696.java @@ -0,0 +1,22 @@ +class Solution { + public int maxResult(int[] nums, int k) { + // Stores dp[i] within the bounds. + Deque maxQ = new ArrayDeque<>(Arrays.asList(0)); + // dp[i] := the maximum score to consider nums[0..i] + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + + for (int i = 1; i < nums.length; ++i) { + // Pop the index if it's out-of-bounds. + if (maxQ.peekFirst() + k < i) + maxQ.pollFirst(); + dp[i] = dp[maxQ.peekFirst()] + nums[i]; + // Pop indices that won't be chosen in the future. + while (!maxQ.isEmpty() && dp[maxQ.peekLast()] <= dp[i]) + maxQ.pollLast(); + maxQ.offerLast(i); + } + + return dp[nums.length - 1]; + } +} diff --git a/solutions/1696. Jump Game VI/1696.py b/solutions/1696. Jump Game VI/1696.py new file mode 100644 index 00000000000..7adfe0f9180 --- /dev/null +++ b/solutions/1696. Jump Game VI/1696.py @@ -0,0 +1,19 @@ +class Solution: + def maxResult(self, nums: List[int], k: int) -> int: + # Stores dp[i] within the bounds. + maxQ = collections.deque([0]) + # dp[i] := the maximum score to consider nums[0..i] + dp = [0] * len(nums) + dp[0] = nums[0] + + for i in range(1, len(nums)): + # Pop the index if it's out-of-bounds. + if maxQ[0] + k < i: + maxQ.popleft() + dp[i] = dp[maxQ[0]] + nums[i] + # Pop indices that won't be chosen in the future. + while maxQ and dp[maxQ[-1]] <= dp[i]: + maxQ.pop() + maxQ.append(i) + + return dp[-1] diff --git a/solutions/1697. Checking Existence of Edge Length Limited Paths/1697.cpp b/solutions/1697. Checking Existence of Edge Length Limited Paths/1697.cpp new file mode 100644 index 00000000000..2a3ebc25e82 --- /dev/null +++ b/solutions/1697. Checking Existence of Edge Length Limited Paths/1697.cpp @@ -0,0 +1,57 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + vector distanceLimitedPathsExist(int n, vector>& edgeList, + vector>& queries) { + vector ans(queries.size()); + UnionFind uf(n); + + for (int i = 0; i < queries.size(); ++i) + queries[i].push_back(i); + + ranges::sort(queries, + [](const auto& a, const auto& b) { return a[2] < b[2]; }); + ranges::sort(edgeList, + [](const auto& a, const auto& b) { return a[2] < b[2]; }); + + int i = 0; // i := edgeList's index + for (const vector& query : queries) { + // Union edges whose distances < limit (query[2]). + while (i < edgeList.size() && edgeList[i][2] < query[2]) + uf.unionByRank(edgeList[i][0], edgeList[i++][1]); + if (uf.find(query[0]) == uf.find(query[1])) + ans[q.back()] = true; + } + + return ans; + } +}; diff --git a/solutions/1697. Checking Existence of Edge Length Limited Paths/1697.java b/solutions/1697. Checking Existence of Edge Length Limited Paths/1697.java new file mode 100644 index 00000000000..b0f4190b171 --- /dev/null +++ b/solutions/1697. Checking Existence of Edge Length Limited Paths/1697.java @@ -0,0 +1,59 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) { + boolean[] ans = new boolean[queries.length]; + int[][] qs = new int[queries.length][4]; + UnionFind uf = new UnionFind(n); + + for (int i = 0; i < queries.length; ++i) { + qs[i][0] = queries[i][0]; + qs[i][1] = queries[i][1]; + qs[i][2] = queries[i][2]; + qs[i][3] = i; + } + + Arrays.sort(qs, (a, b) -> a[2] - b[2]); + Arrays.sort(edgeList, (a, b) -> a[2] - b[2]); + + int i = 0; // i := edgeList's index + for (int[] q : qs) { + // Union edges whose distances < limit (q[2]). + while (i < edgeList.length && edgeList[i][2] < q[2]) + uf.unionByRank(edgeList[i][0], edgeList[i++][1]); + if (uf.find(q[0]) == uf.find(q[1])) + ans[q[3]] = true; + } + + return ans; + } +} diff --git a/solutions/1698. Number of Distinct Substrings in a String/1698.cpp b/solutions/1698. Number of Distinct Substrings in a String/1698.cpp new file mode 100644 index 00000000000..1d86552ce9d --- /dev/null +++ b/solutions/1698. Number of Distinct Substrings in a String/1698.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int countDistinct(string s) { + const int n = s.length(); + int ans = 0; + vector pow(n + 1); // pow[i] := kBase^i + vector hashes(n + 1); // hashes[i] := the hash of s[0..i) + + pow[0] = 1; + for (int i = 1; i <= n; ++i) { + pow[i] = pow[i - 1] * kBase % kMod; + hashes[i] = (hashes[i - 1] * kBase + val(s[i - 1])) % kMod; + } + + for (int length = 1; length <= n; ++length) { + unordered_set seen; + for (int i = 0; i + length <= n; ++i) + seen.insert(getHash(i, i + length, hashes, pow)); + ans += seen.size(); + } + + return ans; + } + + private: + static constexpr int kBase = 26; + static constexpr int kMod = 1'000'000'007; + + // Returns the hash of s[l..r). + long getHash(int l, int r, const vector& hashes, + const vector& pow) { + const long hash = (hashes[r] - hashes[l] * pow[r - l]) % kMod; + return hash < 0 ? hash + kMod : hash; + } + + constexpr int val(char c) { + return c - 'a'; + } +}; diff --git a/solutions/1698. Number of Distinct Substrings in a String/1698.java b/solutions/1698. Number of Distinct Substrings in a String/1698.java new file mode 100644 index 00000000000..88d4d3ade0f --- /dev/null +++ b/solutions/1698. Number of Distinct Substrings in a String/1698.java @@ -0,0 +1,36 @@ +class Solution { + public int countDistinct(String s) { + final int n = s.length(); + int ans = 0; + long[] pow = new long[n + 1]; // pow[i] := kBase^i + long[] hashes = new long[n + 1]; // hashes[i] := the hash of s[0..i) + + pow[0] = 1; + for (int i = 1; i <= n; ++i) { + pow[i] = pow[i - 1] * kBase % kMod; + hashes[i] = (hashes[i - 1] * kBase + val(s.charAt(i - 1))) % kMod; + } + + for (int length = 1; length <= n; ++length) { + Set seen = new HashSet<>(); + for (int i = 0; i + length <= n; ++i) + seen.add(getHash(i, i + length, hashes, pow)); + ans += seen.size(); + } + + return ans; + } + + private static final int kBase = 26; + private static final int kMod = 1_000_000_007; + + // Returns the hash of s[l..r). + private long getHash(int l, int r, long[] hashes, long[] pow) { + final long hash = (hashes[r] - hashes[l] * pow[r - l]) % kMod; + return hash < 0 ? hash + kMod : hash; + } + + private int val(char c) { + return c - 'a'; + } +} diff --git a/solutions/1698. Number of Distinct Substrings in a String/1698.py b/solutions/1698. Number of Distinct Substrings in a String/1698.py new file mode 100644 index 00000000000..309096d8006 --- /dev/null +++ b/solutions/1698. Number of Distinct Substrings in a String/1698.py @@ -0,0 +1,29 @@ +class Solution: + def countDistinct(self, s: str) -> int: + kBase = 26 + kMod = 1_000_000_007 + + n = len(s) + ans = 0 + pow = [1] + [0] * n # pow[i] := kBase^i + hashes = [0] * (n + 1) # hashes[i] := the hash of s[0..i) + + def val(c: str) -> int: + return ord(c) - ord('a') + + for i in range(1, n + 1): + pow[i] = pow[i - 1] * kBase % kMod + hashes[i] = (hashes[i - 1] * kBase + val(s[i - 1])) % kMod + + def getHash(l: int, r: int) -> int: + """Returns the hash of s[l..r).""" + hash = (hashes[r] - hashes[l] * pow[r - l]) % kMod + return hash + kMod if hash < 0 else hash + + for length in range(1, n + 1): + seen = set() + for i in range(n - length + 1): + seen.add(getHash(i, i + length)) + ans += len(seen) + + return ans diff --git a/solutions/1699. Number of Calls Between Two Persons/1699.sql b/solutions/1699. Number of Calls Between Two Persons/1699.sql new file mode 100644 index 00000000000..c698df12e3f --- /dev/null +++ b/solutions/1699. Number of Calls Between Two Persons/1699.sql @@ -0,0 +1,7 @@ +SELECT + LEAST(from_id, to_id) AS person1, + GREATEST(from_id, to_id) AS person2, + COUNT(*) AS call_count, + SUM(duration) AS total_duration +FROM Calls +GROUP BY 1, 2; diff --git a/solutions/17. Letter Combinations of a Phone Number/17-2.cpp b/solutions/17. Letter Combinations of a Phone Number/17-2.cpp new file mode 100644 index 00000000000..eab897d785c --- /dev/null +++ b/solutions/17. Letter Combinations of a Phone Number/17-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector letterCombinations(string digits) { + if (digits.empty()) + return {}; + + vector ans{""}; + const vector digitToLetters{"", "", "abc", "def", "ghi", + "jkl", "mno", "pqrs", "tuv", "wxyz"}; + + for (const char d : digits) { + vector temp; + for (const string& s : ans) + for (const char c : digitToLetters[d - '0']) + temp.push_back(s + c); + ans = move(temp); + } + + return ans; + } +}; diff --git a/solutions/17. Letter Combinations of a Phone Number/17-2.java b/solutions/17. Letter Combinations of a Phone Number/17-2.java new file mode 100644 index 00000000000..8a69240e6e7 --- /dev/null +++ b/solutions/17. Letter Combinations of a Phone Number/17-2.java @@ -0,0 +1,21 @@ +class Solution { + public List letterCombinations(String digits) { + if (digits.isEmpty()) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + ans.add(""); + final String[] digitToLetters = {"", "", "abc", "def", "ghi", + "jkl", "mno", "pqrs", "tuv", "wxyz"}; + + for (final char d : digits.toCharArray()) { + List temp = new ArrayList<>(); + for (final String s : ans) + for (final char c : digitToLetters[d - '0'].toCharArray()) + temp.add(s + c); + ans = temp; + } + + return ans; + } +} diff --git a/solutions/17. Letter Combinations of a Phone Number/17-2.py b/solutions/17. Letter Combinations of a Phone Number/17-2.py new file mode 100644 index 00000000000..7be99e5ab67 --- /dev/null +++ b/solutions/17. Letter Combinations of a Phone Number/17-2.py @@ -0,0 +1,17 @@ +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + if not digits: + return [] + + ans = [''] + digitToLetters = ['', '', 'abc', 'def', 'ghi', + 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] + + for d in digits: + temp = [] + for s in ans: + for c in digitToLetters[ord(d) - ord('0')]: + temp.append(s + c) + ans = temp + + return ans diff --git a/solutions/17. Letter Combinations of a Phone Number/17.cpp b/solutions/17. Letter Combinations of a Phone Number/17.cpp new file mode 100644 index 00000000000..54a4cc1f6cd --- /dev/null +++ b/solutions/17. Letter Combinations of a Phone Number/17.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector letterCombinations(string digits) { + if (digits.empty()) + return {}; + + vector ans; + + dfs(digits, 0, "", ans); + return ans; + } + + private: + const vector digitToLetters{"", "", "abc", "def", "ghi", + "jkl", "mno", "pqrs", "tuv", "wxyz"}; + + void dfs(const string& digits, int i, string&& path, vector& ans) { + if (i == digits.length()) { + ans.push_back(path); + return; + } + + for (const char letter : digitToLetters[digits[i] - '0']) { + path.push_back(letter); + dfs(digits, i + 1, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/17. Letter Combinations of a Phone Number/17.java b/solutions/17. Letter Combinations of a Phone Number/17.java new file mode 100644 index 00000000000..217ed7eacca --- /dev/null +++ b/solutions/17. Letter Combinations of a Phone Number/17.java @@ -0,0 +1,27 @@ +class Solution { + public List letterCombinations(String digits) { + if (digits.isEmpty()) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + + dfs(digits, 0, new StringBuilder(), ans); + return ans; + } + + private static final String[] digitToLetters = {"", "", "abc", "def", "ghi", + "jkl", "mno", "pqrs", "tuv", "wxyz"}; + + private void dfs(String digits, int i, StringBuilder sb, List ans) { + if (i == digits.length()) { + ans.add(sb.toString()); + return; + } + + for (final char c : digitToLetters[digits.charAt(i) - '0'].toCharArray()) { + sb.append(c); + dfs(digits, i + 1, sb, ans); + sb.deleteCharAt(sb.length() - 1); + } + } +} diff --git a/solutions/17. Letter Combinations of a Phone Number/17.py b/solutions/17. Letter Combinations of a Phone Number/17.py new file mode 100644 index 00000000000..17de30c85ce --- /dev/null +++ b/solutions/17. Letter Combinations of a Phone Number/17.py @@ -0,0 +1,21 @@ +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + if not digits: + return [] + + digitToLetters = ['', '', 'abc', 'def', 'ghi', + 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] + ans = [] + + def dfs(i: int, path: List[chr]) -> None: + if i == len(digits): + ans.append(''.join(path)) + return + + for letter in digitToLetters[ord(digits[i]) - ord('0')]: + path.append(letter) + dfs(i + 1, path) + path.pop() + + dfs(0, []) + return ans diff --git a/solutions/170. Two Sum III - Data structure design/170.cpp b/solutions/170. Two Sum III - Data structure design/170.cpp new file mode 100644 index 00000000000..9e840f507d9 --- /dev/null +++ b/solutions/170. Two Sum III - Data structure design/170.cpp @@ -0,0 +1,21 @@ +class TwoSum { + public: + void add(int number) { + ++count[number]; + } + + bool find(int value) { + for (const auto& [key, freq] : count) { + const int remain = value - key; + if (key == remain && freq > 1) + return true; + if (key != remain && count.contains(remain)) + return true; + } + + return false; + } + + private: + unordered_map count; +}; diff --git a/solutions/170. Two Sum III - Data structure design/170.java b/solutions/170. Two Sum III - Data structure design/170.java new file mode 100644 index 00000000000..9f6f587b9d3 --- /dev/null +++ b/solutions/170. Two Sum III - Data structure design/170.java @@ -0,0 +1,20 @@ +class TwoSum { + public void add(int number) { + count.merge(number, 1, Integer::sum); + } + + public boolean find(int value) { + for (Map.Entry entry : count.entrySet()) { + final int key = entry.getKey(); + final int remain = value - key; + if (key == remain && entry.getValue() > 1) + return true; + if (key != remain && count.containsKey(remain)) + return true; + } + + return false; + } + + private HashMap count = new HashMap<>(); +} diff --git a/solutions/170. Two Sum III - Data structure design/170.py b/solutions/170. Two Sum III - Data structure design/170.py new file mode 100644 index 00000000000..709063bce0e --- /dev/null +++ b/solutions/170. Two Sum III - Data structure design/170.py @@ -0,0 +1,16 @@ +class TwoSum: + def __init__(self): + self.count = collections.Counter() + + def add(self, number: int) -> None: + self.count[number] += 1 + + def find(self, value: int) -> bool: + for key, freq in self.count.items(): + remain = value - key + if key == remain and freq > 1: + return True + if key != remain and remain in self.count: + return True + + return False diff --git a/solutions/1700. Number of Students Unable to Eat Lunch/1700.cpp b/solutions/1700. Number of Students Unable to Eat Lunch/1700.cpp new file mode 100644 index 00000000000..79bb740d69f --- /dev/null +++ b/solutions/1700. Number of Students Unable to Eat Lunch/1700.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countStudents(vector& students, vector& sandwiches) { + vector count(2); + + for (const int student : students) + ++count[student]; + + for (int i = 0; i < sandwiches.size(); ++i) { + if (count[sandwiches[i]] == 0) + return sandwiches.size() - i; + --count[sandwiches[i]]; + } + + return 0; + } +}; diff --git a/solutions/1700. Number of Students Unable to Eat Lunch/1700.java b/solutions/1700. Number of Students Unable to Eat Lunch/1700.java new file mode 100644 index 00000000000..5a7d6f62b60 --- /dev/null +++ b/solutions/1700. Number of Students Unable to Eat Lunch/1700.java @@ -0,0 +1,16 @@ +class Solution { + public int countStudents(int[] students, int[] sandwiches) { + int[] count = new int[2]; + + for (final int student : students) + ++count[student]; + + for (int i = 0; i < sandwiches.length; ++i) { + if (count[sandwiches[i]] == 0) + return sandwiches.length - i; + --count[sandwiches[i]]; + } + + return 0; + } +} diff --git a/solutions/1700. Number of Students Unable to Eat Lunch/1700.py b/solutions/1700. Number of Students Unable to Eat Lunch/1700.py new file mode 100644 index 00000000000..41dfb21fb15 --- /dev/null +++ b/solutions/1700. Number of Students Unable to Eat Lunch/1700.py @@ -0,0 +1,10 @@ +class Solution: + def countStudents(self, students: List[int], sandwiches: List[int]) -> int: + count = collections.Counter(students) + + for i, sandwich in enumerate(sandwiches): + if count[sandwich] == 0: + return len(sandwiches) - i + count[sandwich] -= 1 + + return 0 diff --git a/solutions/1701. Average Waiting Time/1701.cpp b/solutions/1701. Average Waiting Time/1701.cpp new file mode 100644 index 00000000000..e5404409a4e --- /dev/null +++ b/solutions/1701. Average Waiting Time/1701.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + double averageWaitingTime(vector>& customers) { + double wait = 0; + double curr = 0; + + for (const vector& c : customers) { + curr = max(curr, 1.0 * c[0]) + c[1]; + wait += curr - c[0]; + } + + return 1.0 * wait / customers.size(); + } +}; diff --git a/solutions/1701. Average Waiting Time/1701.java b/solutions/1701. Average Waiting Time/1701.java new file mode 100644 index 00000000000..e332fb15ae1 --- /dev/null +++ b/solutions/1701. Average Waiting Time/1701.java @@ -0,0 +1,13 @@ +class Solution { + public double averageWaitingTime(int[][] customers) { + double wait = 0; + double curr = 0; + + for (int[] c : customers) { + curr = Math.max(curr, 1.0 * c[0]) + c[1]; + wait += curr - c[0]; + } + + return 1.0 * wait / customers.length; + } +} diff --git a/solutions/1702. Maximum Binary String After Change/1702.cpp b/solutions/1702. Maximum Binary String After Change/1702.cpp new file mode 100644 index 00000000000..f6d30ef752b --- /dev/null +++ b/solutions/1702. Maximum Binary String After Change/1702.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + string maximumBinaryString(string binary) { + // e.g. binary = "100110" + // Do Operation 2 -> "100011" + // Do Operation 1 -> "111011" + // So, the index of the only '0' is prefixOnes + zeros - 1. + const int zeros = ranges::count(binary, '0'); + const int prefixOnes = binary.find('0'); + + // Make the entire string as 1s. + binary.assign(binary.length(), '1'); + + // Make the only '0' if necessary. + if (prefixOnes != string::npos) + binary[prefixOnes + zeros - 1] = '0'; + return binary; + } +}; diff --git a/solutions/1702. Maximum Binary String After Change/1702.java b/solutions/1702. Maximum Binary String After Change/1702.java new file mode 100644 index 00000000000..9cbb9e98c51 --- /dev/null +++ b/solutions/1702. Maximum Binary String After Change/1702.java @@ -0,0 +1,18 @@ +class Solution { + public String maximumBinaryString(String binary) { + // e.g. binary = "100110" + // Do Operation 2 -> "100011" + // Do Operation 1 -> "111011" + // So, the index of the only '0' is prefixOnes + zeros - 1. + final int zeros = (int) binary.chars().filter(c -> c == '0').count(); + final int prefixOnes = binary.indexOf('0'); + + // Make the entire String as 1s. + StringBuilder sb = new StringBuilder("1".repeat(binary.length())); + + // Make the only '0' if necessary. + if (prefixOnes != -1) + sb.setCharAt(prefixOnes + zeros - 1, '0'); + return sb.toString(); + } +} diff --git a/solutions/1702. Maximum Binary String After Change/1702.py b/solutions/1702. Maximum Binary String After Change/1702.py new file mode 100644 index 00000000000..2f8cab2dd2d --- /dev/null +++ b/solutions/1702. Maximum Binary String After Change/1702.py @@ -0,0 +1,16 @@ +class Solution: + def maximumBinaryString(self, binary: str) -> str: + # e.g. binary = '100110' + # Do Operation 2 -> '100011' + # Do Operation 1 -> '111011' + # So, the index of the only '0' is prefixOnes + zeros - 1. + zeros = binary.count('0') + prefixOnes = binary.find('0') + + # Make the entire string as 1s. + ans = ['1'] * len(binary) + + # Make the only '0' if necessary. + if prefixOnes != -1: + ans[prefixOnes + zeros - 1] = '0' + return ''.join(ans) diff --git a/solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.cpp b/solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.cpp new file mode 100644 index 00000000000..cb058f18387 --- /dev/null +++ b/solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minMoves(vector& nums, int k) { + vector ones; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == 1) + ones.push_back(i); + + // Returns the median index of [i..i + k). + auto getMedIndex = [&](int i) { return (i + (i + k - 1)) / 2; }; + + // Calculate the first group: window[0] = A[0..k). + const int median = ones[getMedIndex(0)]; + int moves = 0; + for (int i = 0; i < k; ++i) + moves += abs(ones[i] - median); + + int ans = moves; + + for (int i = 1; i <= ones.size() - k; ++i) { + const int oldMedianIndex = ones[getMedIndex(i - 1)]; + const int newMedianIndex = ones[getMedIndex(i)]; + if (k % 2 == 1) + moves += newMedianIndex - oldMedianIndex; + moves -= newMedianIndex - ones[i - 1]; + moves += ones[i + k - 1] - newMedianIndex; + ans = min(ans, moves); + } + + auto nThSum = [&](int n) { return n * (n + 1) / 2; }; + return ans - nThSum((k - 1) / 2) - nThSum(k / 2); + } +}; diff --git a/solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.java b/solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.java new file mode 100644 index 00000000000..380256ce99f --- /dev/null +++ b/solutions/1703. Minimum Adjacent Swaps for K Consecutive Ones/1703.java @@ -0,0 +1,38 @@ +class Solution { + public int minMoves(int[] nums, int k) { + List ones = new ArrayList<>(); + + for (int i = 0; i < nums.length; ++i) + if (nums[i] == 1) + ones.add(i); + + final int median = ones.get(getMedIndex(0, k)); + int moves = 0; + for (int i = 0; i < k; ++i) + moves += Math.abs(ones.get(i) - median); + + int ans = moves; + + for (int i = 1; i <= ones.size() - k; ++i) { + final int oldMedianIndex = ones.get(getMedIndex(i - 1, k)); + final int newMedianIndex = ones.get(getMedIndex(i, k)); + if (k % 2 == 1) + moves += newMedianIndex - oldMedianIndex; + moves -= newMedianIndex - ones.get(i - 1); + moves += ones.get(i + k - 1) - newMedianIndex; + ans = Math.min(ans, moves); + } + + return ans - nThSum((k - 1) / 2) - nThSum(k / 2); + } + + // Returns the median index of [i..i + k). + private int getMedIndex(int i, int k) { + return (i + (i + k - 1)) / 2; + } + + // Returns 1 + 2 + ... + n + private int nThSum(int n) { + return n * (n + 1) / 2; + } +} diff --git a/solutions/1704. Determine if String Halves Are Alike/1704.cpp b/solutions/1704. Determine if String Halves Are Alike/1704.cpp new file mode 100644 index 00000000000..d26a6cc3bee --- /dev/null +++ b/solutions/1704. Determine if String Halves Are Alike/1704.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool halvesAreAlike(string s) { + const string a = s.substr(0, s.length() / 2); + const string b = s.substr(s.length() / 2); + const int aVowelsCount = + ranges::count_if(a, [=](char c) { return isVowel(c); }); + const int bVowelsCount = + ranges::count_if(b, [=](char c) { return isVowel(c); }); + return aVowelsCount == bVowelsCount; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/1704. Determine if String Halves Are Alike/1704.java b/solutions/1704. Determine if String Halves Are Alike/1704.java new file mode 100644 index 00000000000..9a0e20a6ed0 --- /dev/null +++ b/solutions/1704. Determine if String Halves Are Alike/1704.java @@ -0,0 +1,13 @@ +class Solution { + public boolean halvesAreAlike(String s) { + final String a = s.substring(0, s.length() / 2); + final String b = s.substring(s.length() / 2); + final int aVowelsCount = (int) a.chars().filter(c -> isVowel((char) c)).count(); + final int bVowelsCount = (int) b.chars().filter(c -> isVowel((char) c)).count(); + return aVowelsCount == bVowelsCount; + } + + private boolean isVowel(char c) { + return "aeiouAEIOU".indexOf(c) != -1; + } +} diff --git a/solutions/1704. Determine if String Halves Are Alike/1704.py b/solutions/1704. Determine if String Halves Are Alike/1704.py new file mode 100644 index 00000000000..3792659aa8c --- /dev/null +++ b/solutions/1704. Determine if String Halves Are Alike/1704.py @@ -0,0 +1,6 @@ +class Solution: + def halvesAreAlike(self, s: str) -> bool: + kVowels = 'aeiouAEIOU' + aVowelsCount = sum(c in kVowels for c in s[:len(s) // 2]) + bVowelsCount = sum(c in kVowels for c in s[len(s) // 2:]) + return aVowelsCount == bVowelsCount diff --git a/solutions/1705. Maximum Number of Eaten Apples/1705.cpp b/solutions/1705. Maximum Number of Eaten Apples/1705.cpp new file mode 100644 index 00000000000..22db9b7c93b --- /dev/null +++ b/solutions/1705. Maximum Number of Eaten Apples/1705.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int eatenApples(vector& apples, vector& days) { + const int n = apples.size(); + int ans = 0; + using P = pair; // (the rotten day, the number of apples) + priority_queue, greater<>> minHeap; + + for (int i = 0; i < n || !minHeap.empty(); ++i) { // i := day + // Remove the rotten apples. + while (!minHeap.empty() && minHeap.top().first <= i) + minHeap.pop(); + // Add today's apples. + if (i < n && apples[i] > 0) + minHeap.emplace(i + days[i], apples[i]); + // Eat one apple today. + if (!minHeap.empty()) { + const auto [rottenDay, numApples] = minHeap.top(); + minHeap.pop(); + if (numApples > 1) + minHeap.emplace(rottenDay, numApples - 1); + ++ans; + } + } + + return ans; + } +}; diff --git a/solutions/1705. Maximum Number of Eaten Apples/1705.java b/solutions/1705. Maximum Number of Eaten Apples/1705.java new file mode 100644 index 00000000000..a3a15e0a4c8 --- /dev/null +++ b/solutions/1705. Maximum Number of Eaten Apples/1705.java @@ -0,0 +1,27 @@ +class Solution { + public int eatenApples(int[] apples, int[] days) { + final int n = apples.length; + int ans = 0; + // (the rotten day, the number of apples) + Queue> minHeap = new PriorityQueue<>((a, b) -> a.getKey() - b.getKey()); + + for (int i = 0; i < n || !minHeap.isEmpty(); ++i) { + // Remove the rotten apples. + while (!minHeap.isEmpty() && minHeap.peek().getKey() <= i) + minHeap.poll(); + // Add today's apples. + if (i < n && apples[i] > 0) + minHeap.offer(new Pair<>(i + days[i], apples[i])); + // Eat one apple today. + if (!minHeap.isEmpty()) { + final int rottenDay = minHeap.peek().getKey(); + final int numApples = minHeap.poll().getValue(); + if (numApples > 1) + minHeap.offer(new Pair<>(rottenDay, numApples - 1)); + ++ans; + } + } + + return ans; + } +} diff --git a/solutions/1705. Maximum Number of Eaten Apples/1705.py b/solutions/1705. Maximum Number of Eaten Apples/1705.py new file mode 100644 index 00000000000..5ae100f7bb6 --- /dev/null +++ b/solutions/1705. Maximum Number of Eaten Apples/1705.py @@ -0,0 +1,23 @@ +class Solution: + def eatenApples(self, apples: List[int], days: List[int]) -> int: + n = len(apples) + ans = 0 + minHeap = [] # (the rotten day, the number of apples) + + i = 0 + while i < n or minHeap: + # Remove the rotten apples. + while minHeap and minHeap[0][0] <= i: + heapq.heappop(minHeap) + # Add today's apples. + if i < n and apples[i] > 0: + heapq.heappush(minHeap, (i + days[i], apples[i])) + # Eat one apple today. + if minHeap: + rottenDay, numApples = heapq.heappop(minHeap) + if numApples > 1: + heapq.heappush(minHeap, (rottenDay, numApples - 1)) + ans += 1 + i += 1 + + return ans diff --git a/solutions/1706. Where Will the Ball Fall/1706.cpp b/solutions/1706. Where Will the Ball Fall/1706.cpp new file mode 100644 index 00000000000..2e8ad84ca3c --- /dev/null +++ b/solutions/1706. Where Will the Ball Fall/1706.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector findBall(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + // dp[i] := status of the i-th column + // -1 := empty, 0 := b0, 1 := b1, ... + vector dp(n); + // ans[i] := the i-th ball's final position + vector ans(n, -1); + + iota(dp.begin(), dp.end(), 0); + + for (int i = 0; i < m; ++i) { + vector newDp(n, -1); + for (int j = 0; j < n; ++j) { + // out-of-bounds + if (j + grid[i][j] < 0 || j + grid[i][j] == n) + continue; + // Stuck + if (grid[i][j] == 1 && grid[i][j + 1] == -1 || + grid[i][j] == -1 && grid[i][j - 1] == 1) + continue; + newDp[j + grid[i][j]] = dp[j]; + } + dp = move(newDp); + } + + for (int i = 0; i < n; ++i) + if (dp[i] != -1) + ans[dp[i]] = i; + + return ans; + } +}; diff --git a/solutions/1706. Where Will the Ball Fall/1706.java b/solutions/1706. Where Will the Ball Fall/1706.java new file mode 100644 index 00000000000..03854d90e9c --- /dev/null +++ b/solutions/1706. Where Will the Ball Fall/1706.java @@ -0,0 +1,36 @@ +class Solution { + public int[] findBall(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + // dp[i] := status of the i-th column + // -1 := empty, 0 := b0, 1 := b1, ... + int[] dp = new int[n]; + // ans[i] := the i-th ball's final position + int[] ans = new int[n]; + Arrays.fill(ans, -1); + + for (int i = 0; i < n; ++i) + dp[i] = i; + + for (int i = 0; i < m; ++i) { + int[] newDp = new int[n]; + Arrays.fill(newDp, -1); + for (int j = 0; j < n; ++j) { + // out-of-bounds + if (j + grid[i][j] < 0 || j + grid[i][j] == n) + continue; + // Stuck + if (grid[i][j] == 1 && grid[i][j + 1] == -1 || grid[i][j] == -1 && grid[i][j - 1] == 1) + continue; + newDp[j + grid[i][j]] = dp[j]; + } + dp = newDp; + } + + for (int i = 0; i < n; ++i) + if (dp[i] != -1) + ans[dp[i]] = i; + + return ans; + } +} diff --git a/solutions/1706. Where Will the Ball Fall/1706.py b/solutions/1706. Where Will the Ball Fall/1706.py new file mode 100644 index 00000000000..ad9382943cc --- /dev/null +++ b/solutions/1706. Where Will the Ball Fall/1706.py @@ -0,0 +1,27 @@ +class Solution: + def findBall(self, grid: List[List[int]]) -> List[int]: + m = len(grid) + n = len(grid[0]) + # dp[i] := status of the i-th column + # -1 := empty, 0 := b0, 1 := b1, ... + dp = [i for i in range(n)] + # ans[i] := the i-th ball's final positio + ans = [-1] * n + + for i in range(m): + newDp = [-1] * n + for j in range(n): + # out-of-bounds + if j + grid[i][j] < 0 or j + grid[i][j] == n: + continue + if grid[i][j] == 1 and grid[i][j + 1] == -1 or \ + grid[i][j] == -1 and grid[i][j - 1] == 1: + continue + newDp[j + grid[i][j]] = dp[j] + dp = newDp + + for i, ball in enumerate(dp): + if ball != -1: + ans[ball] = i + + return ans diff --git a/solutions/1707. Maximum XOR With an Element From Array/1707.cpp b/solutions/1707. Maximum XOR With an Element From Array/1707.cpp new file mode 100644 index 00000000000..feb63b57d6b --- /dev/null +++ b/solutions/1707. Maximum XOR With an Element From Array/1707.cpp @@ -0,0 +1,85 @@ +struct TrieNode { + vector> children; + TrieNode() : children(2) {} +}; + +class BitTrie { + public: + BitTrie(int maxBit) : maxBit(maxBit) {} + + void insert(int num) { + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + if (node->children[bit] == nullptr) + node->children[bit] = make_shared(); + node = node->children[bit]; + } + } + + int getMaxXor(int num) { + int maxXor = 0; + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + const int toggleBit = bit ^ 1; + if (node->children[toggleBit] != nullptr) { + maxXor = maxXor | 1 << i; + node = node->children[toggleBit]; + } else if (node->children[bit] != nullptr) { + node = node->children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private: + const int maxBit; + shared_ptr root = make_shared(); +}; + +struct IndexedQuery { + int queryIndex; + int x; + int m; +}; + +class Solution { + public: + vector maximizeXor(vector& nums, vector>& queries) { + vector ans(queries.size(), -1); + const int maxNumInNums = ranges::max(nums); + const int maxNumInQuery = + ranges::max_element(queries, + [](const vector& a, const vector& b) { + return a[0] < b[0]; + })->at(0); + const int maxBit = static_cast(log2(max(maxNumInNums, maxNumInQuery))); + BitTrie bitTrie(maxBit); + + ranges::sort(nums); + + int i = 0; // nums' index + for (const auto& [queryIndex, x, m] : getIndexedQueries(queries)) { + while (i < nums.size() && nums[i] <= m) + bitTrie.insert(nums[i++]); + if (i > 0 && nums[i - 1] <= m) + ans[queryIndex] = bitTrie.getMaxXor(x); + } + + return ans; + } + + private: + vector getIndexedQueries(const vector>& queries) { + vector indexedQueries; + for (int i = 0; i < queries.size(); ++i) + indexedQueries.push_back({i, queries[i][0], queries[i][1]}); + ranges::sort( + indexedQueries, + [](const IndexedQuery& a, const IndexedQuery& b) { return a.m < b.m; }); + return indexedQueries; + } +}; diff --git a/solutions/1707. Maximum XOR With an Element From Array/1707.java b/solutions/1707. Maximum XOR With an Element From Array/1707.java new file mode 100644 index 00000000000..d049dc37b97 --- /dev/null +++ b/solutions/1707. Maximum XOR With an Element From Array/1707.java @@ -0,0 +1,76 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[2]; +} + +class BitTrie { + public BitTrie(int maxBit) { + this.maxBit = maxBit; + } + + public void insert(int num) { + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + if (node.children[bit] == null) + node.children[bit] = new TrieNode(); + node = node.children[bit]; + } + } + + public int getMaxXor(int num) { + int maxXor = 0; + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + final int toggleBit = bit ^ 1; + if (node.children[toggleBit] != null) { + maxXor = maxXor | 1 << i; + node = node.children[toggleBit]; + } else if (node.children[bit] != null) { + node = node.children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private int maxBit; + private TrieNode root = new TrieNode(); +} + +class Solution { + public int[] maximizeXor(int[] nums, int[][] queries) { + int[] ans = new int[queries.length]; + Arrays.fill(ans, -1); + final int maxNumInNums = Arrays.stream(nums).max().getAsInt(); + final int maxNumInQuery = Arrays.stream(queries).mapToInt(query -> query[0]).max().getAsInt(); + final int maxBit = (int) (Math.log(Math.max(maxNumInNums, maxNumInQuery)) / Math.log(2)); + BitTrie bitTrie = new BitTrie(maxBit); + + Arrays.sort(nums); + + int i = 0; // nums' index + for (IndexedQuery indexedQuery : getIndexedQueries(queries)) { + final int queryIndex = indexedQuery.queryIndex; + final int x = indexedQuery.x; + final int m = indexedQuery.m; + while (i < nums.length && nums[i] <= m) + bitTrie.insert(nums[i++]); + if (i > 0 && nums[i - 1] <= m) + ans[queryIndex] = bitTrie.getMaxXor(x); + } + + return ans; + } + + private record IndexedQuery(int queryIndex, int x, int m){}; + + private IndexedQuery[] getIndexedQueries(int[][] queries) { + IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; + for (int i = 0; i < queries.length; ++i) + indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]); + Arrays.sort(indexedQueries, (a, b) -> a.m - b.m); + return indexedQueries; + } +} diff --git a/solutions/1707. Maximum XOR With an Element From Array/1707.py b/solutions/1707. Maximum XOR With an Element From Array/1707.py new file mode 100644 index 00000000000..c2b825ea574 --- /dev/null +++ b/solutions/1707. Maximum XOR With an Element From Array/1707.py @@ -0,0 +1,65 @@ +class TrieNode: + def __init__(self): + self.children: List[Optional[TrieNode]] = [None] * 2 + + +class BitTrie: + def __init__(self, maxBit: int): + self.maxBit = maxBit + self.root = TrieNode() + + def insert(self, num: int) -> None: + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + if not node.children[bit]: + node.children[bit] = TrieNode() + node = node.children[bit] + + def getMaxXor(self, num: int) -> int: + maxXor = 0 + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + toggleBit = bit ^ 1 + if node.children[toggleBit]: + maxXor = maxXor | 1 << i + node = node.children[toggleBit] + elif node.children[bit]: + node = node.children[bit] + else: # There's nothing in the Bit Trie. + return 0 + return maxXor + + +class IndexedQuery: + def __init__(self, queryIndex: int, x: int, m: int): + self.queryIndex = queryIndex + self.x = x + self.m = m + + def __iter__(self): + yield self.queryIndex + yield self.x + yield self.m + + +class Solution: + def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]: + ans = [-1] * len(queries) + maxBit = int(math.log2(max(max(nums), max(x for x, _ in queries)))) + bitTrie = BitTrie(maxBit) + + nums.sort() + + i = 0 # nums' index + for queryIndex, x, m in sorted([IndexedQuery(i, x, m) + for i, (x, m) in enumerate(queries)], + key=lambda iq: iq.m): + while i < len(nums) and nums[i] <= m: + bitTrie.insert(nums[i]) + i += 1 + if i > 0 and nums[i - 1] <= m: + ans[queryIndex] = bitTrie.getMaxXor(x) + + return ans diff --git a/solutions/1708. Largest Subarray Length K/1708.cpp b/solutions/1708. Largest Subarray Length K/1708.cpp new file mode 100644 index 00000000000..1326a991f5b --- /dev/null +++ b/solutions/1708. Largest Subarray Length K/1708.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + vector largestSubarray(vector& nums, int k) { + const auto it = max_element(nums.begin(), nums.end() - k + 1); + return std::vector(it, it + k); + } +}; diff --git a/solutions/1708. Largest Subarray Length K/1708.java b/solutions/1708. Largest Subarray Length K/1708.java new file mode 100644 index 00000000000..d1da5d94f10 --- /dev/null +++ b/solutions/1708. Largest Subarray Length K/1708.java @@ -0,0 +1,9 @@ +class Solution { + public int[] largestSubarray(int[] nums, int k) { + int maxIndex = 0; + for (int i = 1; i <= nums.length - k; ++i) + if (nums[i] > nums[maxIndex]) + maxIndex = i; + return Arrays.copyOfRange(nums, maxIndex, maxIndex + k); + } +} diff --git a/solutions/1708. Largest Subarray Length K/1708.py b/solutions/1708. Largest Subarray Length K/1708.py new file mode 100644 index 00000000000..e3053cb49fa --- /dev/null +++ b/solutions/1708. Largest Subarray Length K/1708.py @@ -0,0 +1,5 @@ +class Solution: + def largestSubarray(self, nums: List[int], k: int) -> List[int]: + mx = max(nums[:len(nums) - k + 1]) + i = nums.index(mx) + return nums[i:i + k] diff --git a/solutions/1709. Biggest Window Between Visits/1709.sql b/solutions/1709. Biggest Window Between Visits/1709.sql new file mode 100644 index 00000000000..6b61c0b6281 --- /dev/null +++ b/solutions/1709. Biggest Window Between Visits/1709.sql @@ -0,0 +1,18 @@ +WITH + UserToWindow AS ( + SELECT + user_id, + DATEDIFF( + LEAD(visit_date, 1, '2021-01-01') OVER( + PARTITION BY user_id + ORDER BY visit_date + ), + visit_date + ) AS `window` + FROM userVisits + ) +SELECT + user_id, + MAX(`window`) AS biggest_window +FROM UserToWindow +GROUP BY user_id; diff --git a/solutions/171. Excel Sheet Column Number/171.cpp b/solutions/171. Excel Sheet Column Number/171.cpp new file mode 100644 index 00000000000..283117b6166 --- /dev/null +++ b/solutions/171. Excel Sheet Column Number/171.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int titleToNumber(string columnTitle) { + return accumulate( + columnTitle.begin(), columnTitle.end(), 0, + [](int subtotal, char c) { return subtotal * 26 + (c - 'A' + 1); }); + } +}; diff --git a/solutions/171. Excel Sheet Column Number/171.java b/solutions/171. Excel Sheet Column Number/171.java new file mode 100644 index 00000000000..31d8811d341 --- /dev/null +++ b/solutions/171. Excel Sheet Column Number/171.java @@ -0,0 +1,5 @@ +class Solution { + public int titleToNumber(String columnTitle) { + return columnTitle.chars().reduce(0, (subtotal, c) -> subtotal * 26 + c - '@'); + } +} diff --git a/solutions/171. Excel Sheet Column Number/171.py b/solutions/171. Excel Sheet Column Number/171.py new file mode 100644 index 00000000000..e73558e3bf8 --- /dev/null +++ b/solutions/171. Excel Sheet Column Number/171.py @@ -0,0 +1,4 @@ +class Solution: + def titleToNumber(self, columnTitle: str) -> int: + return functools.reduce(lambda subtotal, c: + subtotal * 26 + ord(c) - ord('@'), columnTitle, 0) diff --git a/solutions/1710. Maximum Units on a Truck/1710.cpp b/solutions/1710. Maximum Units on a Truck/1710.cpp new file mode 100644 index 00000000000..4615a926990 --- /dev/null +++ b/solutions/1710. Maximum Units on a Truck/1710.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maximumUnits(vector>& boxTypes, int truckSize) { + int ans = 0; + + ranges::sort(boxTypes, [](const vector& a, const vector& b) { + return b[1] < a[1]; + }); + + for (const vector& boxType : boxTypes) { + const int boxes = boxType[0]; + const int units = boxType[1]; + if (boxes >= truckSize) + return ans + truckSize * units; + ans += boxes * units; + truckSize -= boxes; + } + + return ans; + } +}; diff --git a/solutions/1710. Maximum Units on a Truck/1710.java b/solutions/1710. Maximum Units on a Truck/1710.java new file mode 100644 index 00000000000..ea573311264 --- /dev/null +++ b/solutions/1710. Maximum Units on a Truck/1710.java @@ -0,0 +1,18 @@ +class Solution { + public int maximumUnits(int[][] boxTypes, int truckSize) { + int ans = 0; + + Arrays.sort(boxTypes, (a, b) -> Integer.compare(b[1], a[1])); + + for (int[] boxType : boxTypes) { + final int boxes = boxType[0]; + final int units = boxType[1]; + if (boxes >= truckSize) + return ans + truckSize * units; + ans += boxes * units; + truckSize -= boxes; + } + + return ans; + } +} diff --git a/solutions/1710. Maximum Units on a Truck/1710.py b/solutions/1710. Maximum Units on a Truck/1710.py new file mode 100644 index 00000000000..4fbb2fd924f --- /dev/null +++ b/solutions/1710. Maximum Units on a Truck/1710.py @@ -0,0 +1,11 @@ +class Solution: + def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: + ans = 0 + + for boxes, units in sorted(boxTypes, key=lambda x: -x[1]): + if boxes >= truckSize: + return ans + truckSize * units + ans += boxes * units + truckSize -= boxes + + return ans diff --git a/solutions/1711. Count Good Meals/1711.cpp b/solutions/1711. Count Good Meals/1711.cpp new file mode 100644 index 00000000000..d7f88da58ee --- /dev/null +++ b/solutions/1711. Count Good Meals/1711.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countPairs(vector& deliciousness) { + constexpr int kMod = 1'000'000'007; + constexpr int kMaxBit = 20 + 1; + const int kMaxPower = pow(2, kMaxBit); + int ans = 0; + unordered_map count; + + for (const int d : deliciousness) { + for (int power = 1; power <= kMaxPower; power *= 2) + if (const auto it = count.find(power - d); it != count.cend()) { + ans += it->second; + ans %= kMod; + } + ++count[d]; + } + + return ans; + } +}; diff --git a/solutions/1711. Count Good Meals/1711.java b/solutions/1711. Count Good Meals/1711.java new file mode 100644 index 00000000000..b96274c813b --- /dev/null +++ b/solutions/1711. Count Good Meals/1711.java @@ -0,0 +1,19 @@ +class Solution { + public int countPairs(int[] deliciousness) { + final int kMod = 1_000_000_007; + final int kMaxBit = 20 + 1; + final int kMaxPower = (int) Math.pow(2, kMaxBit); + int ans = 0; + Map count = new HashMap<>(); + + for (final int d : deliciousness) { + for (int power = 1; power <= kMaxPower; power *= 2) { + ans += count.getOrDefault(power - d, 0); + ans %= kMod; + } + count.merge(d, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/1711. Count Good Meals/1711.py b/solutions/1711. Count Good Meals/1711.py new file mode 100644 index 00000000000..7a6e2866f2b --- /dev/null +++ b/solutions/1711. Count Good Meals/1711.py @@ -0,0 +1,15 @@ +class Solution: + def countPairs(self, deliciousness: List[int]) -> int: + kMod = 10**9 + 7 + kMaxBit = 20 + 1 + ans = 0 + count = collections.Counter() + + for d in deliciousness: + for i in range(kMaxBit + 1): + power = 1 << i + ans += count[power - d] + ans %= kMod + count[d] += 1 + + return ans diff --git a/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.cpp b/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.cpp new file mode 100644 index 00000000000..2b4455840eb --- /dev/null +++ b/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int waysToSplit(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + vector prefix(n); + + partial_sum(nums.begin(), nums.end(), prefix.begin()); + + for (int i = 0, j = 0, k = 0; i < n - 2; ++i) { + // Find the first index j s.t. + // left = prefix[i] <= mid = prefix[j] - prefix[i] + j = max(j, i + 1); + while (j < n - 1 && prefix[i] > prefix[j] - prefix[i]) + ++j; + // Find the first index k s.t. + // mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k] + k = max(k, j); + while (k < n - 1 && prefix[k] - prefix[i] <= prefix.back() - prefix[k]) + ++k; + ans += k - j; + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.java b/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.java new file mode 100644 index 00000000000..3bf10208e54 --- /dev/null +++ b/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.java @@ -0,0 +1,28 @@ +class Solution { + public int waysToSplit(int[] nums) { + final int kMod = 1_000_000_007; + final int n = nums.length; + int ans = 0; + int[] prefix = nums.clone(); + + for (int i = 1; i < n; ++i) + prefix[i] += prefix[i - 1]; + + for (int i = 0, j = 0, k = 0; i < n - 2; ++i) { + // Find the first index j s.t. + // left = prefix[i] <= mid = prefix[j] - prefix[i] + j = Math.max(j, i + 1); + while (j < n - 1 && prefix[i] > prefix[j] - prefix[i]) + ++j; + // Find the first index k s.t. + // mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k] + k = Math.max(k, j); + while (k < n - 1 && prefix[k] - prefix[i] <= prefix[prefix.length - 1] - prefix[k]) + ++k; + ans += k - j; + ans %= kMod; + } + + return ans; + } +} diff --git a/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.py b/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.py new file mode 100644 index 00000000000..d316d38b306 --- /dev/null +++ b/solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.py @@ -0,0 +1,24 @@ +class Solution: + def waysToSplit(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + n = len(nums) + ans = 0 + prefix = list(itertools.accumulate(nums)) + + j = 0 + k = 0 + for i in range(n - 2): + # Find the first index j s.t. + # left = prefix[i] <= mid = prefix[j] - prefix[i] + j = max(j, i + 1) + while j < n - 1 and prefix[i] > prefix[j] - prefix[i]: + j += 1 + # Find the first index k s.t. + # mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k] + k = max(k, j) + while k < n - 1 and prefix[k] - prefix[i] <= prefix[-1] - prefix[k]: + k += 1 + ans += k - j + ans %= kMod + + return ans diff --git a/solutions/1712. Ways to Split Array Into Three Subarrays/1712.cpp b/solutions/1712. Ways to Split Array Into Three Subarrays/1712.cpp new file mode 100644 index 00000000000..69008beed66 --- /dev/null +++ b/solutions/1712. Ways to Split Array Into Three Subarrays/1712.cpp @@ -0,0 +1,55 @@ +class Solution { + public: + int waysToSplit(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + vector prefix(n); + + partial_sum(nums.begin(), nums.end(), prefix.begin()); + + // Finds the first index j s.t. + // mid = prefix[j] - prefix[i] >= left = prefix[i]. + auto firstGreaterEqual = [&](int i) { + int l = i + 1; + int r = n - 1; + while (l < r) { + const int m = (l + r) / 2; + if (prefix[m] - prefix[i] >= prefix[i]) + r = m; + else + l = m + 1; + } + return l; + }; + + // Finds the first index k s.t. + // mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k]. + auto firstGreater = [&](int i) { + int l = i + 1; + int r = n - 1; + while (l < r) { + const int m = (l + r) / 2; + if (prefix[m] - prefix[i] > prefix.back() - prefix[m]) + r = m; + else + l = m + 1; + } + return l; + }; + + for (int i = 0; i < n - 2; ++i) { + const int j = firstGreaterEqual(i); + if (j == n - 1) + break; + const int mid = prefix[j] - prefix[i]; + const int right = prefix.back() - prefix[j]; + if (mid > right) + continue; + const int k = firstGreater(i); + ans = (ans + k - j) % kMod; + } + + return ans; + } +}; diff --git a/solutions/1712. Ways to Split Array Into Three Subarrays/1712.java b/solutions/1712. Ways to Split Array Into Three Subarrays/1712.java new file mode 100644 index 00000000000..3d2b84bb661 --- /dev/null +++ b/solutions/1712. Ways to Split Array Into Three Subarrays/1712.java @@ -0,0 +1,55 @@ +class Solution { + public int waysToSplit(int[] nums) { + final int kMod = 1_000_000_007; + final int n = nums.length; + int ans = 0; + int[] prefix = nums.clone(); + + for (int i = 1; i < n; ++i) + prefix[i] += prefix[i - 1]; + + for (int i = 0; i < n - 2; ++i) { + final int j = firstGreaterEqual(prefix, i); + if (j == n - 1) + break; + final int mid = prefix[j] - prefix[i]; + final int right = prefix[prefix.length - 1] - prefix[j]; + if (mid > right) + continue; + final int k = firstGreater(prefix, i); + ans = (ans + k - j) % kMod; + } + + return ans; + } + + // Finds the first index j s.t. + // mid = prefix[j] - prefix[i] >= left = prefix[i]. + private int firstGreaterEqual(int[] prefix, int i) { + int l = i + 1; + int r = prefix.length - 1; + while (l < r) { + final int m = (l + r) / 2; + if (prefix[m] - prefix[i] >= prefix[i]) + r = m; + else + l = m + 1; + } + return l; + }; + + // Finds the first index k s.t. + // mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k]. + private int firstGreater(int[] prefix, int i) { + int l = i + 1; + int r = prefix.length - 1; + while (l < r) { + final int m = (l + r) / 2; + if (prefix[m] - prefix[i] > prefix[prefix.length - 1] - prefix[m]) + r = m; + else + l = m + 1; + } + return l; + }; +} diff --git a/solutions/1712. Ways to Split Array Into Three Subarrays/1712.py b/solutions/1712. Ways to Split Array Into Three Subarrays/1712.py new file mode 100644 index 00000000000..9ff31fc9a21 --- /dev/null +++ b/solutions/1712. Ways to Split Array Into Three Subarrays/1712.py @@ -0,0 +1,47 @@ +class Solution: + def waysToSplit(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + n = len(nums) + ans = 0 + prefix = list(itertools.accumulate(nums)) + + def firstGreaterEqual(i: int) -> int: + """Finds the first index j s.t. + Mid = prefix[j] - prefix[i] >= left = prefix[i] + """ + l = i + 1 + r = n - 1 + while l < r: + m = (l + r) // 2 + if prefix[m] - prefix[i] >= prefix[i]: + r = m + else: + l = m + 1 + return l + + def firstGreater(i: int) -> int: + """Finds the first index k s.t. + mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k] + """ + l = i + 1 + r = n - 1 + while l < r: + m = (l + r) // 2 + if prefix[m] - prefix[i] > prefix[-1] - prefix[m]: + r = m + else: + l = m + 1 + return l + + for i in range(n - 2): + j = firstGreaterEqual(i) + if j == n - 1: + break + mid = prefix[j] - prefix[i] + right = prefix[-1] - prefix[j] + if mid > right: + continue + k = firstGreater(i) + ans = (ans + k - j) % kMod + + return ans diff --git a/solutions/1713. Minimum Operations to Make a Subsequence/1713.cpp b/solutions/1713. Minimum Operations to Make a Subsequence/1713.cpp new file mode 100644 index 00000000000..112926a1c23 --- /dev/null +++ b/solutions/1713. Minimum Operations to Make a Subsequence/1713.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int minOperations(vector& target, vector& arr) { + vector indices; + unordered_map numToIndex; + + for (int i = 0; i < target.size(); ++i) + numToIndex[target[i]] = i; + + for (const int a : arr) + if (const auto it = numToIndex.find(a); it != numToIndex.end()) + indices.push_back(it->second); + + return target.size() - lengthOfLIS(indices); + } + + private: + // Same as 300. Longest Increasing Subsequence + int lengthOfLIS(vector& nums) { + // tail[i] := the minimum tail of all the increasing subsequences having + // length i + 1 + vector tail; + for (const int num : nums) + if (tail.empty() || num > tail.back()) + tail.push_back(num); + else + tail[firstGreaterEqual(tail, num)] = num; + return tail.size(); + } + + private: + int firstGreaterEqual(const vector& A, int target) { + return ranges::lower_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/1713. Minimum Operations to Make a Subsequence/1713.java b/solutions/1713. Minimum Operations to Make a Subsequence/1713.java new file mode 100644 index 00000000000..df4ebe066ca --- /dev/null +++ b/solutions/1713. Minimum Operations to Make a Subsequence/1713.java @@ -0,0 +1,33 @@ +class Solution { + public int minOperations(int[] target, int[] arr) { + List indices = new ArrayList<>(); + Map numToIndex = new HashMap<>(); + + for (int i = 0; i < target.length; ++i) + numToIndex.put(target[i], i); + + for (final int a : arr) + if (numToIndex.containsKey(a)) + indices.add(numToIndex.get(a)); + + return target.length - lengthOfLIS(indices); + } + + // Same as 300. Longest Increasing Subsequence + private int lengthOfLIS(List nums) { + // tail[i] := the minimum tail of all the increasing subsequences with + // length i + 1 + List tail = new ArrayList<>(); + for (final int num : nums) + if (tail.isEmpty() || num > tail.get(tail.size() - 1)) + tail.add(num); + else + tail.set(firstGreaterEqual(tail, num), num); + return tail.size(); + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/1713. Minimum Operations to Make a Subsequence/1713.py b/solutions/1713. Minimum Operations to Make a Subsequence/1713.py new file mode 100644 index 00000000000..a542a41968f --- /dev/null +++ b/solutions/1713. Minimum Operations to Make a Subsequence/1713.py @@ -0,0 +1,22 @@ +class Solution: + def minOperations(self, target: List[int], arr: List[int]) -> int: + indices = [] + numToIndex = {num: i for i, num in enumerate(target)} + + for a in arr: + if a in numToIndex: + indices.append(numToIndex[a]) + + return len(target) - self._lengthOfLIS(indices) + + # Same as 300. Longest Increasing Subsequence + def _lengthOfLIS(self, nums: List[int]) -> int: + # tail[i] := the minimum tail of all the increasing subsequences having + # length i + 1 + tail = [] + for num in nums: + if not tail or num > tail[-1]: + tail.append(num) + else: + tail[bisect.bisect_left(tail, num)] = num + return len(tail) diff --git a/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.cpp b/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.cpp new file mode 100644 index 00000000000..79118dd19dd --- /dev/null +++ b/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector solve(vector& nums, vector>& queries) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + const int sqrtN = static_cast(sqrt(n)); + vector ans; + // prefix[x][y] = sum(nums[x + ay]), where a >= 0 and x + ay < n + vector> prefix(n, vector(sqrtN)); + + // Set prefix[i][j] to nums[i] to indicate the sequence starts with nums[i]. + for (int i = 0; i < n; ++i) + for (int j = 0; j < sqrtN; ++j) + prefix[i][j] = nums[i]; + + for (int x = n - 1; x >= 0; --x) + for (int y = 1; y < sqrtN; ++y) + if (x + y < n) { + prefix[x][y] += prefix[x + y][y]; + prefix[x][y] %= kMod; + } + + for (const vector& query : queries) { + const int x = query[0]; + const int y = query[1]; + if (y < sqrtN) { + ans.push_back(prefix[x][y]); + } else { + int sum = 0; + for (int i = x; i < n; i += y) + sum = (sum + nums[i]) % kMod; + ans.push_back(sum); + } + } + + return ans; + } +}; diff --git a/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.java b/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.java new file mode 100644 index 00000000000..b5f9d386dfb --- /dev/null +++ b/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.java @@ -0,0 +1,37 @@ +class Solution { + public int[] solve(int[] nums, int[][] queries) { + final int kMod = 1_000_000_007; + final int n = nums.length; + final int sqrtN = (int) Math.sqrt(n); + int[] ans = new int[queries.length]; + // prefix[x][y] = sum(nums[x + ay]), where a >= 0 and x + ay < n + int[][] prefix = new int[n][sqrtN]; + + // Set prefix[i][j] to nums[i] to indicate the sequence starts with nums[i]. + for (int i = 0; i < n; ++i) + for (int j = 0; j < sqrtN; ++j) + prefix[i][j] = nums[i]; + + for (int x = n - 1; x >= 0; --x) + for (int y = 1; y < sqrtN; ++y) + if (x + y < n) { + prefix[x][y] += prefix[x + y][y]; + prefix[x][y] %= kMod; + } + + for (int i = 0; i < queries.length; ++i) { + final int x = queries[i][0]; + final int y = queries[i][1]; + if (y < sqrtN) { + ans[i] = prefix[x][y]; + } else { + int sum = 0; + for (int j = x; j < n; j += y) + sum = (sum + nums[j]) % kMod; + ans[i] = sum; + } + } + + return ans; + } +} diff --git a/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.py b/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.py new file mode 100644 index 00000000000..127991b9f97 --- /dev/null +++ b/solutions/1714. Sum Of Special Evenly-Spaced Elements In Array/1714.py @@ -0,0 +1,18 @@ +class Solution: + def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]: + kMod = 10**9 + 7 + n = len(nums) + sqrtN = int(n**0.5) + # prefix[x][y] = sum(nums[x + ay]), where a >= 0 and x + ay < n + # Set prefix[i][j] to nums[i] to indicate the sequence starts with nums[i]. + prefix = [[num] * sqrtN for num in nums] + + for x in range(n - 1, -1, -1): + for y in range(1, sqrtN): + if x + y < n: + prefix[x][y] += prefix[x + y][y] + prefix[x][y] %= kMod + + return [prefix[x][y] if y < sqrtN + else sum(nums[x::y]) % kMod + for x, y in queries] diff --git a/solutions/1715. Count Apples and Oranges/1715.sql b/solutions/1715. Count Apples and Oranges/1715.sql new file mode 100644 index 00000000000..92dd6bf5291 --- /dev/null +++ b/solutions/1715. Count Apples and Oranges/1715.sql @@ -0,0 +1,6 @@ +SELECT + SUM(Boxes.apple_count + IFNULL(Chests.apple_count, 0)) AS apple_count, + SUM(Boxes.orange_count + IFNULL(Chests.orange_count, 0)) AS orange_count +FROM Boxes +LEFT JOIN Chests + USING (chest_id); diff --git a/solutions/1716. Calculate Money in Leetcode Bank/1716.cpp b/solutions/1716. Calculate Money in Leetcode Bank/1716.cpp new file mode 100644 index 00000000000..aabd90ec2be --- /dev/null +++ b/solutions/1716. Calculate Money in Leetcode Bank/1716.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int totalMoney(int n) { + const int weeks = n / 7; + const int firstWeek = trapezoid(1, 7); + const int lastFullWeek = trapezoid(1 + weeks - 1, 7 + weeks - 1); + const int remainingDays = trapezoid(1 + weeks, n % 7 + weeks); + return (firstWeek + lastFullWeek) * weeks / 2 + remainingDays; + } + + // Returns sum(a..b). + int trapezoid(int a, int b) { + return (a + b) * (b - a + 1) / 2; + } +}; diff --git a/solutions/1716. Calculate Money in Leetcode Bank/1716.java b/solutions/1716. Calculate Money in Leetcode Bank/1716.java new file mode 100644 index 00000000000..0988780ea4e --- /dev/null +++ b/solutions/1716. Calculate Money in Leetcode Bank/1716.java @@ -0,0 +1,14 @@ +class Solution { + public int totalMoney(int n) { + final int weeks = n / 7; + final int firstWeek = trapezoid(1, 7); + final int lastFullWeek = trapezoid(1 + weeks - 1, 7 + weeks - 1); + final int remainingDays = trapezoid(1 + weeks, n % 7 + weeks); + return (firstWeek + lastFullWeek) * weeks / 2 + remainingDays; + } + + // Returns sum(a..b). + private int trapezoid(int a, int b) { + return (a + b) * (b - a + 1) / 2; + } +} diff --git a/solutions/1716. Calculate Money in Leetcode Bank/1716.py b/solutions/1716. Calculate Money in Leetcode Bank/1716.py new file mode 100644 index 00000000000..0e206dced61 --- /dev/null +++ b/solutions/1716. Calculate Money in Leetcode Bank/1716.py @@ -0,0 +1,11 @@ +class Solution: + def totalMoney(self, n: int) -> int: + def trapezoid(a: int, b: int) -> int: + """Returns sum(a..b).""" + return (a + b) * (b - a + 1) // 2 + + weeks = n // 7 + firstWeek = trapezoid(1, 7) + lastFullWeek = trapezoid(1 + weeks - 1, 7 + weeks - 1) + remainingDays = trapezoid(1 + weeks, n % 7 + weeks) + return (firstWeek + lastFullWeek) * weeks // 2 + remainingDays diff --git a/solutions/1717. Maximum Score From Removing Substrings/1717.cpp b/solutions/1717. Maximum Score From Removing Substrings/1717.cpp new file mode 100644 index 00000000000..823b2eb5a1b --- /dev/null +++ b/solutions/1717. Maximum Score From Removing Substrings/1717.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int maximumGain(string s, int x, int y) { + // The assumption that gain("ab") > gain("ba") while removing "ba" first is + // optimal is contradicted. Only "b(ab)a" satisfies the condition of + // preventing two "ba" removals, but after removing "ab", we can still + // remove one "ba", resulting in a higher gain. Thus, removing "ba" first is + // not optimal. + return x > y ? gain(s, "ab", x, "ba", y) : gain(s, "ba", y, "ab", x); + } + + private: + // Returns the points gained by first removing sub1 ("ab" | "ba") from s with + // point1, then removing sub2 ("ab" | "ba") from s with point2. + int gain(const string& s, const string& sub1, int point1, const string& sub2, + int point2) { + int points = 0; + vector stack1; + vector stack2; + + // Remove "sub1" from s with point1 gain. + for (const char c : s) + if (!stack1.empty() && stack1.back() == sub1[0] && c == sub1[1]) { + stack1.pop_back(); + points += point1; + } else { + stack1.push_back(c); + } + + // Remove "sub2" from s with point2 gain. + for (const char c : stack1) + if (!stack2.empty() && stack2.back() == sub2[0] && c == sub2[1]) { + stack2.pop_back(); + points += point2; + } else { + stack2.push_back(c); + } + + return points; + } +}; diff --git a/solutions/1717. Maximum Score From Removing Substrings/1717.java b/solutions/1717. Maximum Score From Removing Substrings/1717.java new file mode 100644 index 00000000000..d40b7d74d05 --- /dev/null +++ b/solutions/1717. Maximum Score From Removing Substrings/1717.java @@ -0,0 +1,38 @@ +class Solution { + public int maximumGain(String s, int x, int y) { + // The assumption that gain("ab") > gain("ba") while removing "ba" first is + // optimal is contradicted. Only "b(ab)a" satisfies the condition of + // preventing two "ba" removals, but after removing "ab", we can still + // remove one "ba", resulting in a higher gain. Thus, removing "ba" first is + // not optimal. + return x > y ? gain(s, "ab", x, "ba", y) : gain(s, "ba", y, "ab", x); + } + + // Returns the points gained by first removing sub1 ("ab" | "ba") from s with + // point1, then removing sub2 ("ab" | "ba") from s with point2. + private int gain(final String s, final String sub1, int point1, final String sub2, int point2) { + int points = 0; + Stack stack1 = new Stack<>(); + Stack stack2 = new Stack<>(); + + // Remove "sub1" from s with point1 gain. + for (final char c : s.toCharArray()) + if (!stack1.isEmpty() && stack1.peek() == sub1.charAt(0) && c == sub1.charAt(1)) { + stack1.pop(); + points += point1; + } else { + stack1.push(c); + } + + // Remove "sub2" from s with point2 gain. + for (final char c : stack1) + if (!stack2.isEmpty() && stack2.peek() == sub2.charAt(0) && c == sub2.charAt(1)) { + stack2.pop(); + points += point2; + } else { + stack2.push(c); + } + + return points; + } +} diff --git a/solutions/1717. Maximum Score From Removing Substrings/1717.py b/solutions/1717. Maximum Score From Removing Substrings/1717.py new file mode 100644 index 00000000000..3fb3adfafc6 --- /dev/null +++ b/solutions/1717. Maximum Score From Removing Substrings/1717.py @@ -0,0 +1,34 @@ +class Solution: + def maximumGain(self, s: str, x: int, y: int) -> int: + # The assumption that gain('ab') > gain('ba') while removing 'ba' first is + # optimal is contradicted. Only 'b(ab)a' satisfies the condition of + # preventing two 'ba' removals, but after removing 'ab', we can still + # remove one 'ba', resulting in a higher gain. Thus, removing 'ba' first is + # not optimal. + return self._gain(s, 'ab', x, 'ba', y) if x > y \ + else self._gain(s, 'ba', y, 'ab', x) + + # Returns the points gained by first removing sub1 ('ab' | 'ba') from s with + # point1, then removing sub2 ('ab' | 'ba') from s with point2. + def _gain(self, s: str, sub1: str, point1: int, sub2: str, point2: int) -> int: + points = 0 + stack1 = [] + stack2 = [] + + # Remove 'sub1' from s with point1 gain. + for c in s: + if stack1 and stack1[-1] == sub1[0] and c == sub1[1]: + stack1.pop() + points += point1 + else: + stack1.append(c) + + # Remove 'sub2' from s with point2 gain. + for c in stack1: + if stack2 and stack2[-1] == sub2[0] and c == sub2[1]: + stack2.pop() + points += point2 + else: + stack2.append(c) + + return points diff --git a/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.cpp b/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.cpp new file mode 100644 index 00000000000..bacb824fbca --- /dev/null +++ b/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + vector constructDistancedSequence(int n) { + vector ans(2 * n - 1); + dfs(n, 0, 0, ans); + return ans; + } + + private: + bool dfs(int n, int i, int mask, vector& ans) { + if (i == ans.size()) + return true; + if (ans[i] > 0) + return dfs(n, i + 1, mask, ans); + + // Greedily fill in `ans` in descending order. + for (int num = n; num >= 1; --num) { + if (mask >> num & 1) + continue; + if (num == 1) { + ans[i] = num; + if (dfs(n, i + 1, mask | 1 << num, ans)) + return true; + ans[i] = 0; + } else { // num in [2, n] + if (i + num >= ans.size() || ans[i + num] > 0) + continue; + ans[i] = num; + ans[i + num] = num; + if (dfs(n, i + 1, mask | 1 << num, ans)) + return true; + ans[i + num] = 0; + ans[i] = 0; + } + } + + return false; + } +}; diff --git a/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.java b/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.java new file mode 100644 index 00000000000..e71a4cfafc8 --- /dev/null +++ b/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.java @@ -0,0 +1,37 @@ +class Solution { + public int[] constructDistancedSequence(int n) { + int[] ans = new int[2 * n - 1]; + dfs(n, 0, 0, ans); + return ans; + } + + private boolean dfs(int n, int i, int mask, int[] ans) { + if (i == ans.length) + return true; + if (ans[i] > 0) + return dfs(n, i + 1, mask, ans); + + // Greedily fill in `ans` in descending order. + for (int num = n; num >= 1; --num) { + if ((mask >> num & 1) == 1) + continue; + if (num == 1) { + ans[i] = num; + if (dfs(n, i + 1, mask | 1 << num, ans)) + return true; + ans[i] = 0; + } else { // num in [2, n] + if (i + num >= ans.length || ans[i + num] > 0) + continue; + ans[i] = num; + ans[i + num] = num; + if (dfs(n, i + 1, mask | 1 << num, ans)) + return true; + ans[i + num] = 0; + ans[i] = 0; + } + } + + return false; + } +} diff --git a/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.py b/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.py new file mode 100644 index 00000000000..4ada4e8b38e --- /dev/null +++ b/solutions/1718. Construct the Lexicographically Largest Valid Sequence/1718.py @@ -0,0 +1,33 @@ +class Solution: + def constructDistancedSequence(self, n: int) -> List[int]: + ans = [0] * (2 * n - 1) + + def dfs(i: int, mask: int) -> bool: + if i == len(ans): + return True + if ans[i] > 0: + return dfs(i + 1, mask) + + # Greedily fill in `ans` in descending order. + for num in range(n, 0, -1): + if (mask >> num & 1) == 1: + continue + if num == 1: + ans[i] = num + if dfs(i + 1, mask | 1 << num): + return True + ans[i] = 0 + else: # num in [2, n] + if i + num >= len(ans) or ans[i + num] > 0: + continue + ans[i] = num + ans[i + num] = num + if dfs(i + 1, mask | 1 << num): + return True + ans[i + num] = 0 + ans[i] = 0 + + return False + + dfs(0, 0) + return ans diff --git a/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.cpp b/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.cpp new file mode 100644 index 00000000000..954b3e5e0ec --- /dev/null +++ b/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.cpp @@ -0,0 +1,70 @@ +class Solution { + public: + int checkWays(vector>& pairs) { + constexpr int kMax = 501; + unordered_map> graph; + vector degrees(kMax); + vector> connected(kMax, vector(kMax)); + + for (const vector& pair : pairs) { + const int u = pair[0]; + const int v = pair[1]; + graph[u].push_back(v); + graph[v].push_back(u); + ++degrees[u]; + ++degrees[v]; + connected[u][v] = true; + connected[v][u] = true; + } + + // For each node, sort its children by degrees in descending order. + for (auto& [_, children] : graph) + ranges::sort(children, [°rees](int a, int b) { + return degrees[b] < degrees[a]; + }); + + const int root = getRoot(degrees, graph.size()); + if (root == -1) + return 0; + if (!dfs(graph, root, degrees, connected, {}, vector(kMax))) + return 0; + return hasMoreThanOneWay ? 2 : 1; + } + + private: + bool hasMoreThanOneWay = false; + + // Returns the root by finding the node with a degree that equals to n - 1. + int getRoot(const vector& degrees, int n) { + for (int i = 1; i < degrees.size(); ++i) + if (degrees[i] == n - 1) + return i; + return -1; + } + + // Returns true if each node rooted at u is connected to all of its ancestors. + bool dfs(const unordered_map>& graph, int u, + vector& degrees, vector>& connected, + vector&& ancestors, vector&& seen) { + seen[u] = true; + + for (const int ancestor : ancestors) + if (!connected[u][ancestor]) + return false; + + ancestors.push_back(u); + + for (const int v : graph.at(u)) { + if (seen[v]) + continue; + // We can swap u with v, so there are more than one way. + if (degrees[v] == degrees[u]) + hasMoreThanOneWay = true; + if (!dfs(graph, v, degrees, connected, move(ancestors), move(seen))) + return false; + } + + ancestors.pop_back(); + return true; + } +}; diff --git a/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.java b/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.java new file mode 100644 index 00000000000..b6fce365dad --- /dev/null +++ b/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.java @@ -0,0 +1,67 @@ +class Solution { + public int checkWays(int[][] pairs) { + final int kMax = 501; + Map> graph = new HashMap<>(); + int[] degrees = new int[kMax]; + boolean[][] connected = new boolean[kMax][kMax]; + + for (int[] pair : pairs) { + final int u = pair[0]; + final int v = pair[1]; + graph.putIfAbsent(u, new ArrayList<>()); + graph.putIfAbsent(v, new ArrayList<>()); + graph.get(u).add(v); + graph.get(v).add(u); + ++degrees[u]; + ++degrees[v]; + connected[u][v] = true; + connected[v][u] = true; + } + + // For each node, sort its children by degrees in descending order. + for (final int u : graph.keySet()) + graph.get(u).sort((a, b) -> Integer.compare(degrees[b], degrees[a])); + + final int root = getRoot(degrees, graph.keySet().size()); + if (root == -1) + return 0; + if (!dfs(graph, root, degrees, connected, new ArrayList<>(), new boolean[kMax])) + return 0; + return hasMoreThanOneWay ? 2 : 1; + } + + private boolean hasMoreThanOneWay = false; + + // Returns the root by finding the node with a degree that equals to n - 1. + private int getRoot(int[] degrees, int n) { + for (int i = 1; i < degrees.length; ++i) + if (degrees[i] == n - 1) + return i; + return -1; + } + + // Returns true if each node rooted at u is connected to all of its ancestors. + private boolean dfs(Map> graph, int u, int[] degrees, + boolean[][] connected, List ancestors, boolean[] seen) { + seen[u] = true; + + for (final int ancestor : ancestors) + if (!connected[u][ancestor]) + return false; + + ancestors.add(u); + + for (final int v : graph.get(u)) { + if (seen[v]) + continue; + // We can swap u with v, so there are more than one way. + if (degrees[v] == degrees[u]) + hasMoreThanOneWay = true; + if (!dfs(graph, v, degrees, connected, ancestors, seen)) + return false; + } + + ancestors.remove(ancestors.size() - 1); + return true; + } +} diff --git a/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.py b/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.py new file mode 100644 index 00000000000..7e9f7a41429 --- /dev/null +++ b/solutions/1719. Number Of Ways To Reconstruct A Tree/1719.py @@ -0,0 +1,50 @@ +class Solution: + def checkWays(self, pairs: List[List[int]]) -> int: + kMax = 501 + graph = collections.defaultdict(list) + degrees = [0] * kMax + connected = [[False] * kMax for _ in range(kMax)] + + for u, v in pairs: + graph[u].append(v) + graph[v].append(u) + degrees[u] += 1 + degrees[v] += 1 + connected[u][v] = True + connected[v][u] = True + + # For each node, sort its children by degrees in descending order. + for _, children in graph.items(): + children.sort(key=lambda a: degrees[a], reverse=True) + + # Find the root with a degree that equals to n - 1. + root = next((i for i, d in enumerate(degrees) if d == len(graph) - 1), -1) + if root == -1: + return 0 + + hasMoreThanOneWay = False + + def dfs(u: int, ancestors: List[int], seen: List[bool]) -> bool: + """ + Returns True if each node rooted at u is connected to all of its + ancestors. + """ + nonlocal hasMoreThanOneWay + seen[u] = True + for ancestor in ancestors: + if not connected[u][ancestor]: + return False + ancestors.append(u) + for v in graph[u]: + if seen[v]: + continue + if degrees[v] == degrees[u]: + hasMoreThanOneWay = True + if not dfs(v, ancestors, seen): + return False + ancestors.pop() + return True + + if not dfs(root, [], [False] * kMax): + return 0 + return 2 if hasMoreThanOneWay else 1 diff --git a/solutions/172. Factorial Trailing Zeroes/172.cpp b/solutions/172. Factorial Trailing Zeroes/172.cpp new file mode 100644 index 00000000000..ad71fc928c6 --- /dev/null +++ b/solutions/172. Factorial Trailing Zeroes/172.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int trailingZeroes(int n) { + return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); + } +}; diff --git a/solutions/172. Factorial Trailing Zeroes/172.java b/solutions/172. Factorial Trailing Zeroes/172.java new file mode 100644 index 00000000000..c4edf4b050b --- /dev/null +++ b/solutions/172. Factorial Trailing Zeroes/172.java @@ -0,0 +1,5 @@ +class Solution { + public int trailingZeroes(int n) { + return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); + } +} diff --git a/solutions/172. Factorial Trailing Zeroes/172.py b/solutions/172. Factorial Trailing Zeroes/172.py new file mode 100644 index 00000000000..43dd09693bf --- /dev/null +++ b/solutions/172. Factorial Trailing Zeroes/172.py @@ -0,0 +1,3 @@ +class Solution: + def trailingZeroes(self, n: int) -> int: + return 0 if n == 0 else n // 5 + self.trailingZeroes(n // 5) diff --git a/solutions/1720. Decode XORed Array/1720.cpp b/solutions/1720. Decode XORed Array/1720.cpp new file mode 100644 index 00000000000..e6cfd700361 --- /dev/null +++ b/solutions/1720. Decode XORed Array/1720.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector decode(vector& encoded, int first) { + vector ans(encoded.size() + 1); + ans[0] = first; + + for (int i = 0; i < encoded.size(); ++i) + ans[i + 1] = ans[i] ^ encoded[i]; + + return ans; + } +}; diff --git a/solutions/1720. Decode XORed Array/1720.java b/solutions/1720. Decode XORed Array/1720.java new file mode 100644 index 00000000000..85082b18dbb --- /dev/null +++ b/solutions/1720. Decode XORed Array/1720.java @@ -0,0 +1,11 @@ +class Solution { + public int[] decode(int[] encoded, int first) { + int[] ans = new int[encoded.length + 1]; + ans[0] = first; + + for (int i = 0; i < encoded.length; ++i) + ans[i + 1] = ans[i] ^ encoded[i]; + + return ans; + } +} diff --git a/solutions/1720. Decode XORed Array/1720.py b/solutions/1720. Decode XORed Array/1720.py new file mode 100644 index 00000000000..48081dc9039 --- /dev/null +++ b/solutions/1720. Decode XORed Array/1720.py @@ -0,0 +1,8 @@ +class Solution: + def decode(self, encoded: List[int], first: int) -> List[int]: + ans = [first] + + for e in encoded: + ans.append(e ^ ans[-1]) + + return ans diff --git a/solutions/1721. Swapping Nodes in a Linked List/1721.cpp b/solutions/1721. Swapping Nodes in a Linked List/1721.cpp new file mode 100644 index 00000000000..e7552c743e2 --- /dev/null +++ b/solutions/1721. Swapping Nodes in a Linked List/1721.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + ListNode* swapNodes(ListNode* head, int k) { + ListNode* p = nullptr; // Points the k-th node from the beginning. + ListNode* q = nullptr; // Points the k-th node from the end. + + for (ListNode* curr = head; curr != nullptr; curr = curr->next) { + if (q != nullptr) + q = q->next; + if (--k == 0) { + p = curr; + q = head; + } + } + + swap(p->val, q->val); + return head; + } +}; diff --git a/solutions/1721. Swapping Nodes in a Linked List/1721.java b/solutions/1721. Swapping Nodes in a Linked List/1721.java new file mode 100644 index 00000000000..a1dfd9f9c81 --- /dev/null +++ b/solutions/1721. Swapping Nodes in a Linked List/1721.java @@ -0,0 +1,20 @@ +class Solution { + public ListNode swapNodes(ListNode head, int k) { + ListNode p = null; // Points the k-th node from the beginning. + ListNode q = null; // Points the k-th node from the end. + + for (ListNode curr = head; curr != null; curr = curr.next) { + if (q != null) + q = q.next; + if (--k == 0) { + p = curr; + q = head; + } + } + + final int temp = p.val; + p.val = q.val; + q.val = temp; + return head; + } +} diff --git a/solutions/1721. Swapping Nodes in a Linked List/1721.py b/solutions/1721. Swapping Nodes in a Linked List/1721.py new file mode 100644 index 00000000000..13fdc07f95f --- /dev/null +++ b/solutions/1721. Swapping Nodes in a Linked List/1721.py @@ -0,0 +1,17 @@ +class Solution: + def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: + p = None # Points the k-th node from the beginning. + q = None # Points the k-th node from the end. + + curr = head + while curr: + if q: + q = q.next + k -= 1 + if k == 0: + p = curr + q = head + curr = curr.next + + p.val, q.val = q.val, p.val + return head diff --git a/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.cpp b/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.cpp new file mode 100644 index 00000000000..0da11a0f320 --- /dev/null +++ b/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.cpp @@ -0,0 +1,60 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + int minimumHammingDistance(vector& source, vector& target, + vector>& allowedSwaps) { + const int n = source.size(); + int ans = 0; + UnionFind uf(n); + vector> groupIdToCount(n); + + for (const vector& allowedSwap : allowedSwaps) { + const int a = allowedSwap[0]; + const int b = allowedSwap[1]; + uf.unionByRank(a, b); + } + + for (int i = 0; i < n; ++i) + ++groupIdToCount[uf.find(i)][source[i]]; + + for (int i = 0; i < n; ++i) { + const int groupId = uf.find(i); + unordered_map& count = groupIdToCount[groupId]; + if (!count.contains(target[i])) + ++ans; + else if (--count[target[i]] == 0) + count.erase(target[i]); + } + + return ans; + } +}; diff --git a/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.java b/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.java new file mode 100644 index 00000000000..5e9565af03c --- /dev/null +++ b/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.java @@ -0,0 +1,62 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) { + final int n = source.length; + int ans = 0; + UnionFind uf = new UnionFind(n); + Map[] groupIdToCount = new Map[n]; + + for (int i = 0; i < n; ++i) + groupIdToCount[i] = new HashMap<>(); + + for (int[] allowedSwap : allowedSwaps) { + final int a = allowedSwap[0]; + final int b = allowedSwap[1]; + uf.unionByRank(a, b); + } + + for (int i = 0; i < n; ++i) + groupIdToCount[uf.find(i)].merge(source[i], 1, Integer::sum); + + for (int i = 0; i < n; ++i) { + final int groupId = uf.find(i); + Map count = groupIdToCount[groupId]; + if (!count.containsKey(target[i])) + ++ans; + else if (count.merge(target[i], -1, Integer::sum) == 0) + count.remove(target[i]); + } + + return ans; + } +} diff --git a/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.py b/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.py new file mode 100644 index 00000000000..006094d8f09 --- /dev/null +++ b/solutions/1722. Minimize Hamming Distance After Swap Operations/1722.py @@ -0,0 +1,48 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: + n = len(source) + ans = 0 + uf = UnionFind(n) + groupIdToCount = [collections.Counter() for _ in range(n)] + + for a, b in allowedSwaps: + uf.unionByRank(a, b) + + for i in range(n): + groupIdToCount[uf.find(i)][source[i]] += 1 + + for i in range(n): + groupId = uf.find(i) + count = groupIdToCount[groupId] + if target[i] not in count: + ans += 1 + else: + count[target[i]] -= 1 + if count[target[i]] == 0: + del count[target[i]] + + return ans diff --git a/solutions/1723. Find Minimum Time to Finish All Jobs/1723.cpp b/solutions/1723. Find Minimum Time to Finish All Jobs/1723.cpp new file mode 100644 index 00000000000..e807ede640c --- /dev/null +++ b/solutions/1723. Find Minimum Time to Finish All Jobs/1723.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int minimumTimeRequired(std::vector& jobs, int k) { + int ans = accumulate(jobs.begin(), jobs.end(), 0); + vector times(k); + + ranges::sort(jobs, greater<>()); + dfs(jobs, 0, times, ans); + return ans; + } + + private: + void dfs(const vector& jobs, int s, vector& times, int& ans) { + if (s == jobs.size()) { + ans = min(ans, ranges::max(times)); + return; + } + for (int i = 0; i < times.size(); ++i) { + if (times[i] + jobs[s] >= ans) + continue; + times[i] += jobs[s]; + dfs(jobs, s + 1, times, ans); + times[i] -= jobs[s]; + if (times[i] == 0) + return; + } + }; +}; diff --git a/solutions/1723. Find Minimum Time to Finish All Jobs/1723.java b/solutions/1723. Find Minimum Time to Finish All Jobs/1723.java new file mode 100644 index 00000000000..e2d95a3f005 --- /dev/null +++ b/solutions/1723. Find Minimum Time to Finish All Jobs/1723.java @@ -0,0 +1,29 @@ +class Solution { + public int minimumTimeRequired(int[] jobs, int k) { + ans = Arrays.stream(jobs).sum(); + int[] times = new int[k]; + + Arrays.sort(jobs); + Collections.reverse(Arrays.asList(jobs)); + dfs(jobs, 0, times); + return ans; + } + + private int ans = 0; + + private void dfs(int[] jobs, int s, int[] times) { + if (s == jobs.length) { + ans = Math.min(ans, Arrays.stream(times).max().getAsInt()); + return; + } + for (int i = 0; i < times.length; ++i) { + if (times[i] + jobs[s] >= ans) + continue; + times[i] += jobs[s]; + dfs(jobs, s + 1, times); + times[i] -= jobs[s]; + if (times[i] == 0) + return; + } + } +} diff --git a/solutions/1723. Find Minimum Time to Finish All Jobs/1723.py b/solutions/1723. Find Minimum Time to Finish All Jobs/1723.py new file mode 100644 index 00000000000..3be14d1446a --- /dev/null +++ b/solutions/1723. Find Minimum Time to Finish All Jobs/1723.py @@ -0,0 +1,27 @@ +class Solution: + def minimumTimeRequired(self, jobs: List[int], k: int) -> int: + ans = sum(jobs) + times = [0] * k # times[i] := accumulate time of workers[i] + + # Assign the most time-consuming job first. + jobs.sort(reverse=True) + + def dfs(s: int) -> None: + nonlocal ans + if s == len(jobs): + ans = min(ans, max(times)) + return + for i in range(k): + # There is no need to explore assigning jobs[s] to workers[i] further as + # it would not yield better results. + if times[i] + jobs[s] >= ans: + continue + times[i] += jobs[s] + dfs(s + 1) + times[i] -= jobs[s] + # It's always non-optimal to have a worker with no jobs. + if times[i] == 0: + return + + dfs(0) + return ans diff --git a/solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.cpp b/solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.cpp new file mode 100644 index 00000000000..d7c42cafde0 --- /dev/null +++ b/solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.cpp @@ -0,0 +1,58 @@ +class UnionFind { + public: + UnionFind() {} + UnionFind(int n) { + id.resize(n); + + for (int i = 0; i < n; ++i) + id[i][0] = i; + } + + void union_(int u, int v, int limit) { + const int i = find(u, limit); + const int j = find(v, limit); + if (i == j) + return; + id[i][limit] = j; + } + + int find(int u, int limit) { + // the minimum iterator of id[u] > limit + const auto it = id[u].upper_bound(limit); + const int i = prev(it)->second; + if (i == u) + return u; + // Recursively find i's id. + const int j = find(i, limit); + id[u][limit] = j; + return j; + } + + private: + // id[i]'s (key, value) := (limit, id of node i <= limit) + vector> id; +}; + +class DistanceLimitedPathsExist { + public: + DistanceLimitedPathsExist(int n, vector>& edgeList) { + uf = UnionFind(n); + + ranges::sort(edgeList, + [](const auto& a, const auto& b) { return a[2] < b[2]; }); + + for (const vector& edge : edgeList) { + const int u = edge[0]; + const int v = edge[1]; + const int d = edge[2]; + uf.union_(u, v, d); + } + } + + bool query(int p, int q, int limit) { + return uf.find(p, limit - 1) == uf.find(q, limit - 1); + } + + private: + UnionFind uf; +}; diff --git a/solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.java b/solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.java new file mode 100644 index 00000000000..d164c7475bc --- /dev/null +++ b/solutions/1724. Checking Existence of Edge Length Limited Paths II/1724.java @@ -0,0 +1,53 @@ +class UnionFind { + public UnionFind(int n) { + id = new TreeMap[n]; + for (int i = 0; i < n; ++i) { + id[i] = new TreeMap<>(); + id[i].put(0, i); + } + } + + public void union(int u, int v, int limit) { + final int i = find(u, limit); + final int j = find(v, limit); + if (i == j) + return; + id[i].put(limit, j); + } + + public int find(int u, int limit) { + // the maximum key of id[u] <= limit + final int floorKey = id[u].floorKey(limit); + final int i = id[u].get(floorKey); + if (i == u) + return u; + // Recursively find i's id. + final int j = find(i, limit); + id[u].put(limit, j); + return j; + } + + // id[i]'s (key, value) := (limit, id of node i <= limit) + private TreeMap[] id; +} + +class DistanceLimitedPathsExist { + public DistanceLimitedPathsExist(int n, int[][] edgeList) { + uf = new UnionFind(n); + + Arrays.sort(edgeList, (a, b) -> a[2] - b[2]); + + for (int[] edge : edgeList) { + final int u = edge[0]; + final int v = edge[1]; + final int d = edge[2]; + uf.union(u, v, d); + } + } + + public boolean query(int p, int q, int limit) { + return uf.find(p, limit - 1) == uf.find(q, limit - 1); + } + + private UnionFind uf; +} diff --git a/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.cpp b/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.cpp new file mode 100644 index 00000000000..67a260a2696 --- /dev/null +++ b/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int countGoodRectangles(vector>& rectangles) { + vector minSides; + + for (const vector& rectangle : rectangles) { + const int x = rectangle[0]; + const int y = rectangle[1]; + minSides.push_back(min(x, y)); + } + + const int maxLen = ranges::max(minSides); + return ranges::count(minSides, maxLen); + } +}; diff --git a/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.java b/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.java new file mode 100644 index 00000000000..654d2eb7cda --- /dev/null +++ b/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.java @@ -0,0 +1,14 @@ +class Solution { + public int countGoodRectangles(int[][] rectangles) { + int[] minSides = new int[rectangles.length]; + + for (int i = 0; i < rectangles.length; ++i) { + final int x = rectangles[i][0]; + final int y = rectangles[i][1]; + minSides[i] = Math.min(x, y); + } + + final int maxLen = Arrays.stream(minSides).max().getAsInt(); + return (int) Arrays.stream(minSides).filter(minSide -> minSide == maxLen).count(); + } +} diff --git a/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.py b/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.py new file mode 100644 index 00000000000..976610d676e --- /dev/null +++ b/solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.py @@ -0,0 +1,4 @@ +class Solution: + def countGoodRectangles(self, rectangles: List[List[int]]) -> int: + minSides = [min(x, y) for x, y in rectangles] + return minSides.count(max(minSides)) diff --git a/solutions/1726. Tuple with Same Product/1726.cpp b/solutions/1726. Tuple with Same Product/1726.cpp new file mode 100644 index 00000000000..04e9aa4d526 --- /dev/null +++ b/solutions/1726. Tuple with Same Product/1726.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int tupleSameProduct(vector& nums) { + int ans = 0; + unordered_map count; + + for (int i = 0; i < nums.size(); ++i) + for (int j = 0; j < i; ++j) + ans += count[nums[i] * nums[j]]++ * 8; + + return ans; + } +}; diff --git a/solutions/1726. Tuple with Same Product/1726.java b/solutions/1726. Tuple with Same Product/1726.java new file mode 100644 index 00000000000..f994f4710f0 --- /dev/null +++ b/solutions/1726. Tuple with Same Product/1726.java @@ -0,0 +1,15 @@ +class Solution { + public int tupleSameProduct(int[] nums) { + int ans = 0; + Map count = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) + for (int j = 0; j < i; ++j) { + final int prod = nums[i] * nums[j]; + ans += count.getOrDefault(prod, 0) * 8; + count.merge(prod, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/1726. Tuple with Same Product/1726.py b/solutions/1726. Tuple with Same Product/1726.py new file mode 100644 index 00000000000..22745e1fb4f --- /dev/null +++ b/solutions/1726. Tuple with Same Product/1726.py @@ -0,0 +1,15 @@ +class Solution: + def tupleSameProduct(self, nums: List[int]) -> int: + # nums of ways to arrange (a, b) = 2 + # nums of ways to arrange (c, d) = 2 + # nums of ways to arrange (a, b), (c, d) = 2^3 = 8 + ans = 0 + count = collections.Counter() + + for i in range(len(nums)): + for j in range(i): + prod = nums[i] * nums[j] + ans += count[prod] * 8 + count[prod] += 1 + + return ans diff --git a/solutions/1727. Largest Submatrix With Rearrangements/1727.cpp b/solutions/1727. Largest Submatrix With Rearrangements/1727.cpp new file mode 100644 index 00000000000..065dc1333fb --- /dev/null +++ b/solutions/1727. Largest Submatrix With Rearrangements/1727.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int largestSubmatrix(vector>& matrix) { + const int n = matrix[0].size(); + int ans = 0; + vector hist(n); + + for (const vector& row : matrix) { + // Accumulate the histogram if possible. + for (int i = 0; i < n; ++i) + hist[i] = row[i] == 0 ? 0 : hist[i] + 1; + + // Get the sorted histogram. + vector sortedHist(hist); + ranges::sort(sortedHist); + + // Greedily calculate the answer. + for (int i = 0; i < n; ++i) + ans = max(ans, sortedHist[i] * (n - i)); + } + + return ans; + } +}; diff --git a/solutions/1727. Largest Submatrix With Rearrangements/1727.java b/solutions/1727. Largest Submatrix With Rearrangements/1727.java new file mode 100644 index 00000000000..4ce11136a15 --- /dev/null +++ b/solutions/1727. Largest Submatrix With Rearrangements/1727.java @@ -0,0 +1,23 @@ +class Solution { + public int largestSubmatrix(int[][] matrix) { + final int n = matrix[0].length; + int ans = 0; + int[] hist = new int[n]; + + for (int[] row : matrix) { + // Accumulate the histogram if possible. + for (int i = 0; i < n; ++i) + hist[i] = row[i] == 0 ? 0 : hist[i] + 1; + + // Get the sorted histogram. + int[] sortedHist = hist.clone(); + Arrays.sort(sortedHist); + + // Greedily calculate the answer. + for (int i = 0; i < n; ++i) + ans = Math.max(ans, sortedHist[i] * (n - i)); + } + + return ans; + } +} diff --git a/solutions/1727. Largest Submatrix With Rearrangements/1727.py b/solutions/1727. Largest Submatrix With Rearrangements/1727.py new file mode 100644 index 00000000000..7df8f087a14 --- /dev/null +++ b/solutions/1727. Largest Submatrix With Rearrangements/1727.py @@ -0,0 +1,18 @@ +class Solution: + def largestSubmatrix(self, matrix: List[List[int]]) -> int: + ans = 0 + hist = [0] * len(matrix[0]) + + for row in matrix: + # Accumulate the histogram if possible. + for i, num in enumerate(row): + hist[i] = 0 if num == 0 else hist[i] + 1 + + # Get the sorted histogram. + sortedHist = sorted(hist) + + # Greedily calculate the answer. + for i, h in enumerate(sortedHist): + ans = max(ans, h * (len(row) - i)) + + return ans diff --git a/solutions/1728. Cat and Mouse II/1728.cpp b/solutions/1728. Cat and Mouse II/1728.cpp new file mode 100644 index 00000000000..867db4fd98e --- /dev/null +++ b/solutions/1728. Cat and Mouse II/1728.cpp @@ -0,0 +1,95 @@ +class Solution { + public: + bool canMouseWin(vector& grid, int catJump, int mouseJump) { + const int m = grid.size(); + const int n = grid[0].size(); + int nFloors = 0; + int cat; // cat's position + int mouse; // mouse's position + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (grid[i][j] != '#') + ++nFloors; + if (grid[i][j] == 'C') + cat = hash(i, j, n); + else if (grid[i][j] == 'M') + mouse = hash(i, j, n); + } + + vector>> mem( + m * n, vector>(m * n, vector(nFloors * 2, -1))); + return canMouseWin(grid, cat, mouse, 0, catJump, mouseJump, m, n, nFloors, + mem); + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns true if the mouse can win, where the cat is on (i / 8, i % 8), the + // mouse is on (j / 8, j % 8), and the turns is k. + bool canMouseWin(const vector& grid, int cat, int mouse, int turn, + const int& catJump, const int& mouseJump, const int& m, + const int& n, const int& nFloors, + vector>>& mem) { + // We already search the whole touchable grid. + if (turn == nFloors * 2) + return false; + if (mem[cat][mouse][turn] != -1) + return mem[cat][mouse][turn]; + + if (turn % 2 == 0) { + // the mouse's turn + const int i = mouse / n; + const int j = mouse % n; + for (const auto& [dx, dy] : dirs) { + for (int jump = 0; jump <= mouseJump; ++jump) { + const int x = i + dx * jump; + const int y = j + dy * jump; + if (x < 0 || x == m || y < 0 || y == n) + break; + if (grid[x][y] == '#') + break; + // The mouse eats the food, so the mouse wins. + if (grid[x][y] == 'F') + return mem[cat][mouse][turn] = true; + if (canMouseWin(grid, cat, hash(x, y, n), turn + 1, catJump, + mouseJump, m, n, nFloors, mem)) + return mem[cat][mouse][turn] = true; + } + } + // The mouse can't win, so the mouse loses. + return mem[cat][mouse][turn] = false; + } else { + // the cat's turn + const int i = cat / n; + const int j = cat % n; + for (const auto& [dx, dy] : dirs) { + for (int jump = 0; jump <= catJump; ++jump) { + const int x = i + dx * jump; + const int y = j + dy * jump; + if (x < 0 || x == m || y < 0 || y == n) + break; + if (grid[x][y] == '#') + break; + // The cat eats the food, so the mouse loses. + if (grid[x][y] == 'F') + return mem[cat][mouse][turn] = false; + const int nextCat = hash(x, y, n); + // The cat catches the mouse, so the mouse loses. + if (nextCat == mouse) + return mem[cat][mouse][turn] = false; + if (!canMouseWin(grid, nextCat, mouse, turn + 1, catJump, mouseJump, + m, n, nFloors, mem)) + return mem[cat][mouse][turn] = false; + } + } + // The cat can't win, so the mouse wins. + return mem[cat][mouse][turn] = true; + } + } + + int hash(int i, int j, int n) { + return i * n + j; + } +}; diff --git a/solutions/1728. Cat and Mouse II/1728.java b/solutions/1728. Cat and Mouse II/1728.java new file mode 100644 index 00000000000..d79bc5c9b48 --- /dev/null +++ b/solutions/1728. Cat and Mouse II/1728.java @@ -0,0 +1,86 @@ +class Solution { + public boolean canMouseWin(String[] grid, int catJump, int mouseJump) { + final int m = grid.length; + final int n = grid[0].length(); + int nFloors = 0; + int cat = 0; // cat's position + int mouse = 0; // mouse's position + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (grid[i].charAt(j) != '#') + ++nFloors; + if (grid[i].charAt(j) == 'C') + cat = hash(i, j, n); + else if (grid[i].charAt(j) == 'M') + mouse = hash(i, j, n); + } + + Boolean[][][] mem = new Boolean[m * n][m * n][nFloors * 2]; + return canMouseWin(grid, cat, mouse, 0, catJump, mouseJump, m, n, nFloors, mem); + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns true if the mouse can win, where the cat is on (i / 8, i % 8), the + // mouse is on (j / 8, j % 8), and the turns is k. + private boolean canMouseWin(String[] grid, int cat, int mouse, int turn, int catJump, + int mouseJump, int m, int n, int nFloors, Boolean[][][] mem) { + // We already search the whole touchable grid. + if (turn == nFloors * 2) + return false; + if (mem[cat][mouse][turn] != null) + return mem[cat][mouse][turn]; + + if (turn % 2 == 0) { + // the mouse's turn + int i = mouse / n; + int j = mouse % n; + for (int[] dir : dirs) { + for (int jump = 0; jump <= mouseJump; ++jump) { + int x = i + dir[0] * jump; + int y = j + dir[1] * jump; + if (x < 0 || x == m || y < 0 || y == n) + break; + if (grid[x].charAt(y) == '#') + break; + // The mouse eats the food, so the mouse wins. + if (grid[x].charAt(y) == 'F') + return mem[cat][mouse][turn] = true; + if (canMouseWin(grid, cat, hash(x, y, n), turn + 1, catJump, mouseJump, m, n, nFloors, + mem)) + return mem[cat][mouse][turn] = true; + } + } + // The mouse can't win, so the mouse loses. + return mem[cat][mouse][turn] = false; + } else { + // the cat's turn + final int i = cat / n; + final int j = cat % n; + for (int[] dir : dirs) + for (int jump = 0; jump <= catJump; ++jump) { + final int x = i + dir[0] * jump; + final int y = j + dir[1] * jump; + if (x < 0 || x == m || y < 0 || y == n) + break; + if (grid[x].charAt(y) == '#') + break; + // The cat eats the food, so the mouse loses. + if (grid[x].charAt(y) == 'F') + return mem[cat][mouse][turn] = false; + final int nextCat = hash(x, y, n); + if (nextCat == mouse) + return mem[cat][mouse][turn] = false; + if (!canMouseWin(grid, nextCat, mouse, turn + 1, catJump, mouseJump, m, n, nFloors, mem)) + return mem[cat][mouse][turn] = false; + } + // The cat can't win, so the mouse wins. + return mem[cat][mouse][turn] = true; + } + } + + private int hash(int i, int j, int n) { + return i * n + j; + } +} diff --git a/solutions/1728. Cat and Mouse II/1728.py b/solutions/1728. Cat and Mouse II/1728.py new file mode 100644 index 00000000000..2cb2ae85286 --- /dev/null +++ b/solutions/1728. Cat and Mouse II/1728.py @@ -0,0 +1,75 @@ +class Solution: + def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + nFloors = 0 + cat = 0 # cat's position + mouse = 0 # mouse's position + + def hash(i: int, j: int) -> int: + return i * n + j + + for i in range(m): + for j in range(n): + if grid[i][j] != '#': + nFloors += 1 + if grid[i][j] == 'C': + cat = hash(i, j) + elif grid[i][j] == 'M': + mouse = hash(i, j) + + @functools.lru_cache(None) + def dp(cat: int, mouse: int, turn: int) -> bool: + """ + Returns True if the mouse can win, where the cat is on (i / 8, i % 8), the + mouse is on (j / 8, j % 8), and the turns is k. + """ + # We already search the whole touchable grid. + if turn == nFloors * 2: + return False + + if turn % 2 == 0: + # the mouse's turn + i = mouse // n + j = mouse % n + for dx, dy in dirs: + for jump in range(mouseJump + 1): + x = i + dx * jump + y = j + dy * jump + if x < 0 or x == m or y < 0 or y == n: + break + if grid[x][y] == '#': + break + # The mouse eats the food, so the mouse wins. + if grid[x][y] == 'F': + return True + if dp(cat, hash(x, y), turn + 1): + return True + # The mouse can't win, so the mouse loses. + return False + else: + # the cat's turn + i = cat // n + j = cat % n + for dx, dy in dirs: + for jump in range(catJump + 1): + x = i + dx * jump + y = j + dy * jump + if x < 0 or x == m or y < 0 or y == n: + break + if grid[x][y] == '#': + break + # The cat eats the food, so the mouse loses. + if grid[x][y] == 'F': + return False + nextCat = hash(x, y) + # The cat catches the mouse, so the mouse loses. + if nextCat == mouse: + return False + if not dp(nextCat, mouse, turn + 1): + return False + # The cat can't win, so the mouse wins. + return True + + return dp(cat, mouse, 0) diff --git a/solutions/1729. Find Followers Count/1729.sql b/solutions/1729. Find Followers Count/1729.sql new file mode 100644 index 00000000000..73b8fd23035 --- /dev/null +++ b/solutions/1729. Find Followers Count/1729.sql @@ -0,0 +1,6 @@ +SELECT + user_id, + COUNT(follower_id) AS followers_count +FROM Followers +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/173. Binary Search Tree Iterator/173-2.cpp b/solutions/173. Binary Search Tree Iterator/173-2.cpp new file mode 100644 index 00000000000..59095e6ec7c --- /dev/null +++ b/solutions/173. Binary Search Tree Iterator/173-2.cpp @@ -0,0 +1,27 @@ +class BSTIterator { + public: + BSTIterator(TreeNode* root) { + pushLeftsUntilNull(root); + } + + int next() { + TreeNode* root = stack.top(); + stack.pop(); + pushLeftsUntilNull(root->right); + return root->val; + } + + bool hasNext() { + return !stack.empty(); + } + + private: + stack stack; + + void pushLeftsUntilNull(TreeNode* root) { + while (root != nullptr) { + stack.push(root); + root = root->left; + } + } +}; diff --git a/solutions/173. Binary Search Tree Iterator/173-2.java b/solutions/173. Binary Search Tree Iterator/173-2.java new file mode 100644 index 00000000000..51f24e9b4ca --- /dev/null +++ b/solutions/173. Binary Search Tree Iterator/173-2.java @@ -0,0 +1,24 @@ +class BSTIterator { + public BSTIterator(TreeNode root) { + pushLeftsUntilNull(root); + } + + public int next() { + TreeNode root = stack.pop(); + pushLeftsUntilNull(root.right); + return root.val; + } + + public boolean hasNext() { + return !stack.isEmpty(); + } + + private Deque stack = new ArrayDeque<>(); + + private void pushLeftsUntilNull(TreeNode root) { + while (root != null) { + stack.push(root); + root = root.left; + } + } +} diff --git a/solutions/173. Binary Search Tree Iterator/173-2.py b/solutions/173. Binary Search Tree Iterator/173-2.py new file mode 100644 index 00000000000..3d9d1766574 --- /dev/null +++ b/solutions/173. Binary Search Tree Iterator/173-2.py @@ -0,0 +1,17 @@ +class BSTIterator: + def __init__(self, root: Optional[TreeNode]): + self.stack = [] + self._pushLeftsUntilNull(root) + + def next(self) -> int: + root = self.stack.pop() + self._pushLeftsUntilNull(root.right) + return root.val + + def hasNext(self) -> bool: + return self.stack + + def _pushLeftsUntilNull(self, root: Optional[TreeNode]) -> None: + while root: + self.stack.append(root) + root = root.left diff --git a/solutions/173. Binary Search Tree Iterator/173.cpp b/solutions/173. Binary Search Tree Iterator/173.cpp new file mode 100644 index 00000000000..b71c1f63b1b --- /dev/null +++ b/solutions/173. Binary Search Tree Iterator/173.cpp @@ -0,0 +1,26 @@ +class BSTIterator { + public: + BSTIterator(TreeNode* root) { + inorder(root); + } + + int next() { + return vals[i++]; + } + + bool hasNext() { + return i < vals.size(); + } + + private: + int i = 0; + vector vals; + + void inorder(TreeNode* root) { + if (root == nullptr) + return; + inorder(root->left); + vals.push_back(root->val); + inorder(root->right); + } +}; diff --git a/solutions/173. Binary Search Tree Iterator/173.java b/solutions/173. Binary Search Tree Iterator/173.java new file mode 100644 index 00000000000..69b1af855a7 --- /dev/null +++ b/solutions/173. Binary Search Tree Iterator/173.java @@ -0,0 +1,24 @@ +class BSTIterator { + public BSTIterator(TreeNode root) { + inorder(root); + } + + public int next() { + return vals.get(i++); + } + + public boolean hasNext() { + return i < vals.size(); + } + + private int i = 0; + private List vals = new ArrayList<>(); + + private void inorder(TreeNode root) { + if (root == null) + return; + inorder(root.left); + vals.add(root.val); + inorder(root.right); + } +} diff --git a/solutions/173. Binary Search Tree Iterator/173.py b/solutions/173. Binary Search Tree Iterator/173.py new file mode 100644 index 00000000000..be9ed7f54e3 --- /dev/null +++ b/solutions/173. Binary Search Tree Iterator/173.py @@ -0,0 +1,19 @@ +class BSTIterator: + def __init__(self, root: Optional[TreeNode]): + self.i = 0 + self.vals = [] + self._inorder(root) + + def next(self) -> int: + self.i += 1 + return self.vals[self.i - 1] + + def hasNext(self) -> bool: + return self.i < len(self.vals) + + def _inorder(self, root: Optional[TreeNode]) -> None: + if not root: + return + self._inorder(root.left) + self.vals.append(root.val) + self._inorder(root.right) diff --git a/solutions/1730. Shortest Path to Get Food/1730.cpp b/solutions/1730. Shortest Path to Get Food/1730.cpp new file mode 100644 index 00000000000..44bf62c9f3e --- /dev/null +++ b/solutions/1730. Shortest Path to Get Food/1730.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int getFood(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + queue> q{{getStartLocation(grid)}}; + + for (int ans = 0; !q.empty(); ++ans) + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] == 'X') + continue; + if (grid[x][y] == '#') + return ans + 1; + q.emplace(x, y); + grid[x][y] = 'X'; // Mark as visited. + } + } + + return -1; + } + + private: + pair getStartLocation(const vector>& grid) { + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == '*') + return {i, j}; + throw; + } +}; diff --git a/solutions/1730. Shortest Path to Get Food/1730.java b/solutions/1730. Shortest Path to Get Food/1730.java new file mode 100644 index 00000000000..5ad6faa5ada --- /dev/null +++ b/solutions/1730. Shortest Path to Get Food/1730.java @@ -0,0 +1,36 @@ +class Solution { + public int getFood(char[][] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length; + Queue q = new ArrayDeque<>(Arrays.asList(getStartLocation(grid))); + + for (int ans = 0; !q.isEmpty(); ++ans) + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] == 'X') + continue; + if (grid[x][y] == '#') + return ans + 1; + q.add(new int[] {x, y}); + grid[x][y] = 'X'; // Mark as visited. + } + } + + return -1; + } + + private int[] getStartLocation(char[][] grid) { + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == '*') + return new int[] {i, j}; + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1730. Shortest Path to Get Food/1730.py b/solutions/1730. Shortest Path to Get Food/1730.py new file mode 100644 index 00000000000..ab3f5b116ac --- /dev/null +++ b/solutions/1730. Shortest Path to Get Food/1730.py @@ -0,0 +1,31 @@ +class Solution: + def getFood(self, grid: List[List[str]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + ans = 0 + q = collections.deque([self._getStartLocation(grid)]) + + while q: + for _ in range(len(q)): + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if grid[x][y] == 'X': + continue + if grid[x][y] == '#': + return ans + 1 + q.append((x, y)) + grid[x][y] = 'X' # Mark as visited. + ans += 1 + + return -1 + + def _getStartLocation(self, grid: List[List[str]]) -> Tuple[int, int]: + for i, row in enumerate(grid): + for j, cell in enumerate(row): + if cell == '*': + return (i, j) diff --git a/solutions/1731. The Number of Employees Which Report to Each Employee/1731.sql b/solutions/1731. The Number of Employees Which Report to Each Employee/1731.sql new file mode 100644 index 00000000000..0a338f166cc --- /dev/null +++ b/solutions/1731. The Number of Employees Which Report to Each Employee/1731.sql @@ -0,0 +1,10 @@ +SELECT + Manager.employee_id, + Manager.name, + COUNT(Employee.employee_id) AS reports_count, + ROUND(AVG(Employee.age)) AS average_age +FROM Employees AS Manager +INNER JOIN Employees AS Employee + ON (Employee.reports_to = Manager.employee_id) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/1732. Find the Highest Altitude/1732.cpp b/solutions/1732. Find the Highest Altitude/1732.cpp new file mode 100644 index 00000000000..d2060c88906 --- /dev/null +++ b/solutions/1732. Find the Highest Altitude/1732.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int largestAltitude(vector& gain) { + int ans = 0; + int currAltitude = 0; + for (const int g : gain) { + currAltitude += g; + ans = max(ans, currAltitude); + } + return ans; + } +}; diff --git a/solutions/1732. Find the Highest Altitude/1732.java b/solutions/1732. Find the Highest Altitude/1732.java new file mode 100644 index 00000000000..6589abf8b80 --- /dev/null +++ b/solutions/1732. Find the Highest Altitude/1732.java @@ -0,0 +1,11 @@ +class Solution { + public int largestAltitude(int[] gain) { + int ans = 0; + int currAltitude = 0; + for (final int g : gain) { + currAltitude += g; + ans = Math.max(ans, currAltitude); + } + return ans; + } +} diff --git a/solutions/1732. Find the Highest Altitude/1732.py b/solutions/1732. Find the Highest Altitude/1732.py new file mode 100644 index 00000000000..c412da789b7 --- /dev/null +++ b/solutions/1732. Find the Highest Altitude/1732.py @@ -0,0 +1,8 @@ +class Solution: + def largestAltitude(self, gain: List[int]) -> int: + ans = 0 + currAltitude = 0 + for g in gain: + currAltitude += g + ans = max(ans, currAltitude) + return ans diff --git a/solutions/1733. Minimum Number of People to Teach/1733.cpp b/solutions/1733. Minimum Number of People to Teach/1733.cpp new file mode 100644 index 00000000000..2851885bf72 --- /dev/null +++ b/solutions/1733. Minimum Number of People to Teach/1733.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int minimumTeachings(int n, vector>& languages, + vector>& friendships) { + vector> languageSets; + unordered_set needTeach; + unordered_map languageCount; + + for (const vector& language : languages) + languageSets.push_back({language.begin(), language.end()}); + + // Find friends that can't communicate. + for (const vector& friendship : friendships) { + const int u = friendship[0] - 1; + const int v = friendship[1] - 1; + if (cantTalk(languageSets, u, v)) { + needTeach.insert(u); + needTeach.insert(v); + } + } + + // Find the most popular language. + for (const int u : needTeach) + for (const int language : languageSets[u]) + ++languageCount[language]; + + // Teach the most popular language to people who don't understand. + int maxCount = 0; + for (const auto& [_, freq] : languageCount) + maxCount = max(maxCount, freq); + + return needTeach.size() - maxCount; + } + + private: + // Returns true if u can't talk with v. + bool cantTalk(const vector>& languageSets, int u, int v) { + for (const int language : languageSets[u]) + if (languageSets[v].contains(language)) + return false; + return true; + } +}; diff --git a/solutions/1733. Minimum Number of People to Teach/1733.java b/solutions/1733. Minimum Number of People to Teach/1733.java new file mode 100644 index 00000000000..7e001ff5b36 --- /dev/null +++ b/solutions/1733. Minimum Number of People to Teach/1733.java @@ -0,0 +1,40 @@ +class Solution { + public int minimumTeachings(int n, int[][] languages, int[][] friendships) { + List> languageSets = new ArrayList<>(); + Set needTeach = new HashSet<>(); + Map languageCount = new HashMap<>(); + + for (int[] language : languages) + languageSets.add(new HashSet<>(Arrays.stream(language).boxed().toList())); + + // Find friends that can't communicate. + for (int[] friendship : friendships) { + final int u = friendship[0] - 1; + final int v = friendship[1] - 1; + if (cantTalk(languageSets, u, v)) { + needTeach.add(u); + needTeach.add(v); + } + } + + // Find the most popular language. + for (int u : needTeach) + for (final int language : languageSets.get(u)) + languageCount.merge(language, 1, Integer::sum); + + // Teach the most popular language to people who don't understand. + int maxCount = 0; + for (int freq : languageCount.values()) + maxCount = Math.max(maxCount, freq); + + return needTeach.size() - maxCount; + } + + // Returns true if u can't talk with v. + private boolean cantTalk(List> languageSets, int u, int v) { + for (int language : languageSets.get(u)) + if (languageSets.get(v).contains(language)) + return false; + return true; + } +} diff --git a/solutions/1733. Minimum Number of People to Teach/1733.py b/solutions/1733. Minimum Number of People to Teach/1733.py new file mode 100644 index 00000000000..43fa507b7de --- /dev/null +++ b/solutions/1733. Minimum Number of People to Teach/1733.py @@ -0,0 +1,19 @@ +class Solution: + def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int: + languageSets = [set(languages) for languages in languages] + needTeach = set() + languageCount = collections.Counter() + + # Find friends that can't communicate. + for u, v in friendships: + if not languageSets[u - 1] & languageSets[v - 1]: + needTeach.add(u - 1) + needTeach.add(v - 1) + + # Find the most popular language. + for u in needTeach: + for language in languageSets[u]: + languageCount[language] += 1 + + # Teach the most popular language to people don't understand. + return len(needTeach) - max(languageCount.values(), default=0) diff --git a/solutions/1734. Decode XORed Permutation/1734.cpp b/solutions/1734. Decode XORed Permutation/1734.cpp new file mode 100644 index 00000000000..3d89bcb4f29 --- /dev/null +++ b/solutions/1734. Decode XORed Permutation/1734.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector decode(vector& encoded) { + // Our goal is to find the value of a1, which will allow us to decode a2, + // a3, ..., an. This can be achieved by performing XOR operation between + // each element in `encoded` and a1. + // + // e.g. n = 3, perm = [a1, a2, a3] is a permutation of [1, 2, 3] + // encoded = [a1^a2, a2^a3] + // accumulatedEncoded = [a1^a2, a1^a3] + // a1 = (a1^a2)^(a1^a3)^(a1^a2^a3) + // a2 = a1^(a1^a2) + // a3 = a2^(a2^a3) + const int n = encoded.size() + 1; + int nXors = 0; + for (int i = 1; i <= n; i++) + nXors ^= i; + + // Instead of constructing the array, we can track of the running XOR value + // of `accumulatedEncoded`. + int runningXors = 0; + int xors = 0; // xors(accumulatedEncoded) + + for (const int encode : encoded) { + runningXors ^= encode; + xors ^= runningXors; + } + + vector ans{xors ^ nXors}; + + for (const int encode : encoded) + ans.push_back(ans.back() ^ encode); + + return ans; + } +}; diff --git a/solutions/1734. Decode XORed Permutation/1734.java b/solutions/1734. Decode XORed Permutation/1734.java new file mode 100644 index 00000000000..d1692adacc7 --- /dev/null +++ b/solutions/1734. Decode XORed Permutation/1734.java @@ -0,0 +1,36 @@ +class Solution { + public int[] decode(int[] encoded) { + // Our goal is to find the value of a1, which will allow us to decode a2, + // a3, ..., an. This can be achieved by performing XOR operation between + // each element in `encoded` and a1. + // + // e.g. n = 3, perm = [a1, a2, a3] is a permutation of [1, 2, 3] + // encoded = [a1^a2, a2^a3] + // accumulatedEncoded = [a1^a2, a1^a3] + // a1 = (a1^a2)^(a1^a3)^(a1^a2^a3) + // a2 = a1^(a1^a2) + // a3 = a2^(a2^a3) + final int n = encoded.length + 1; + int nXors = 0; + for (int i = 1; i <= n; i++) + nXors ^= i; + + // Instead of constructing the array, we can track of the running XOR value + // of `accumulatedEncoded`. + int runningXors = 0; + int xors = 0; // xors(accumulatedEncoded) + + for (final int encode : encoded) { + runningXors ^= encode; + xors ^= runningXors; + } + + int[] ans = new int[encoded.length + 1]; + ans[0] = xors ^ nXors; + + for (int i = 0; i < encoded.length; i++) + ans[i + 1] = ans[i] ^ encoded[i]; + + return ans; + } +} diff --git a/solutions/1734. Decode XORed Permutation/1734.py b/solutions/1734. Decode XORed Permutation/1734.py new file mode 100644 index 00000000000..5bf8268b460 --- /dev/null +++ b/solutions/1734. Decode XORed Permutation/1734.py @@ -0,0 +1,29 @@ +class Solution: + def decode(self, encoded: List[int]) -> List[int]: + # Our goal is to find the value of a1, which will allow us to decode a2, a3, + # ..., an. This can be achieved by performing XOR operation between each + # element in `encoded` and a1. + # + # e.g. n = 3, perm = [a1, a2, a3] is a permutation of [1, 2, 3]. + # encoded = [a1^a2, a2^a3] + # accumulatedEncoded = [a1^a2, a1^a3] + # a1 = (a1^a2)^(a1^a3)^(a1^a2^a3) + # a2 = a1^(a1^a2) + # a3 = a2^(a2^a3) + n = len(encoded) + 1 + nXors = functools.reduce(operator.xor, [i for i in range(1, n + 1)]) + + # Instead of constructing the array, we can track of the running XOR value + # of `accumulatedEncoded`. + xors = 0 # xors(accumulatedEncoded) + + for encode in encoded: + runningXors ^= encode + xors ^= runningXors + + ans = [xors ^ nXors] + + for encode in encoded: + ans.append(ans[-1] ^ encode) + + return ans diff --git a/solutions/1735. Count Ways to Make Array With Product/1735.cpp b/solutions/1735. Count Ways to Make Array With Product/1735.cpp new file mode 100644 index 00000000000..dd0c3b93272 --- /dev/null +++ b/solutions/1735. Count Ways to Make Array With Product/1735.cpp @@ -0,0 +1,68 @@ +class Solution { + public: + vector waysToFillArray(vector>& queries) { + constexpr int kMax = 10000; + constexpr int kMaxFreq = 13; // 2^13 = 8192 < kMax + const vector minPrimeFactors = sieveEratosthenes(kMax + 1); + const auto [fact, invFact] = getFactAndInvFact(kMax + kMaxFreq - 1); + vector ans; + + for (const vector& query : queries) { + const int n = query[0]; + const int k = query[1]; + int res = 1; + for (const auto& [_, freq] : getPrimeFactorsCount(k, minPrimeFactors)) + res = static_cast(res) * nCk(n - 1 + freq, freq, fact, invFact) % + kMod; + ans.push_back(res); + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Gets the minimum prime factor of i, where 1 < i <= n. + vector sieveEratosthenes(int n) { + vector minPrimeFactors(n + 1); + iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + unordered_map getPrimeFactorsCount( + int num, const vector& minPrimeFactors) { + unordered_map count; + while (num > 1) { + const int divisor = minPrimeFactors[num]; + while (num % divisor == 0) { + num /= divisor; + ++count[divisor]; + } + } + return count; + } + + pair, vector> getFactAndInvFact(int n) { + vector fact(n + 1); + vector invFact(n + 1); + vector inv(n + 1); + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return {fact, invFact}; + } + + int nCk(int n, int k, const vector& fact, const vector& invFact) { + return fact[n] * invFact[k] % kMod * invFact[n - k] % kMod; + } +}; diff --git a/solutions/1735. Count Ways to Make Array With Product/1735.java b/solutions/1735. Count Ways to Make Array With Product/1735.java new file mode 100644 index 00000000000..00a9641a254 --- /dev/null +++ b/solutions/1735. Count Ways to Make Array With Product/1735.java @@ -0,0 +1,67 @@ +class Solution { + public int[] waysToFillArray(int[][] queries) { + final int kMax = 10_000; + final int kMaxFreq = 13; // 2^13 = 8192 < kMax + final int[] minPrimeFactors = sieveEratosthenes(kMax + 1); + final long[][] factAndInvFact = getFactAndInvFact(kMax + kMaxFreq - 1); + final long[] fact = factAndInvFact[0]; + final long[] invFact = factAndInvFact[1]; + int[] ans = new int[queries.length]; + + for (int i = 0; i < queries.length; ++i) { + final int n = queries[i][0]; + final int k = queries[i][1]; + int res = 1; + for (final int freq : getPrimeFactorsCount(k, minPrimeFactors).values()) + res = (int) ((long) res * nCk(n - 1 + freq, freq, fact, invFact) % kMod); + ans[i] = res; + } + + return ans; + } + + private static final int kMod = 1_000_000_007; + + // Gets the minimum prime factor of i, where 1 < i <= n. + private int[] sieveEratosthenes(int n) { + int[] minPrimeFactors = new int[n + 1]; + for (int i = 2; i <= n; ++i) + minPrimeFactors[i] = i; + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + private Map getPrimeFactorsCount(int num, int[] minPrimeFactors) { + Map count = new HashMap<>(); + while (num > 1) { + final int divisor = minPrimeFactors[num]; + while (num % divisor == 0) { + num /= divisor; + count.put(divisor, count.merge(divisor, 1, Integer::sum)); + } + } + return count; + } + + private long[][] getFactAndInvFact(int n) { + long[] fact = new long[n + 1]; + long[] invFact = new long[n + 1]; + long[] inv = new long[n + 1]; + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return new long[][] {fact, invFact}; + } + + private int nCk(int n, int k, long[] fact, long[] invFact) { + return (int) (fact[n] * invFact[k] % kMod * invFact[n - k] % kMod); + } +} diff --git a/solutions/1735. Count Ways to Make Array With Product/1735.py b/solutions/1735. Count Ways to Make Array With Product/1735.py new file mode 100644 index 00000000000..f3ac0f36062 --- /dev/null +++ b/solutions/1735. Count Ways to Make Array With Product/1735.py @@ -0,0 +1,45 @@ +class Solution: + def waysToFillArray(self, queries: List[List[int]]) -> List[int]: + kMod = 1_000_000_007 + kMax = 10_000 + minPrimeFactors = self._sieveEratosthenes(kMax + 1) + + @functools.lru_cache(None) + def fact(i: int) -> int: + return 1 if i <= 1 else i * fact(i - 1) % kMod + + @functools.lru_cache(None) + def inv(i: int) -> int: + return pow(i, kMod - 2, kMod) + + @functools.lru_cache(None) + def nCk(n: int, k: int) -> int: + return fact(n) * inv(fact(k)) * inv(fact(n - k)) % kMod + + ans = [] + + for n, k in queries: + res = 1 + for freq in self._getPrimeFactorsCount(k, minPrimeFactors).values(): + res = res * nCk(n - 1 + freq, freq) % kMod + ans.append(res) + + return ans + + def _sieveEratosthenes(self, n: int) -> List[int]: + """Gets the minimum prime factor of i, where 1 < i <= n.""" + minPrimeFactors = [i for i in range(n + 1)] + for i in range(2, int(n**0.5) + 1): + if minPrimeFactors[i] == i: # `i` is prime. + for j in range(i * i, n, i): + minPrimeFactors[j] = min(minPrimeFactors[j], i) + return minPrimeFactors + + def _getPrimeFactorsCount(self, num: int, minPrimeFactors: List[int]) -> Dict[int, int]: + count = collections.Counter() + while num > 1: + divisor = minPrimeFactors[num] + while num % divisor == 0: + num //= divisor + count[divisor] += 1 + return count diff --git a/solutions/1736. Latest Time by Replacing Hidden Digits/1736.cpp b/solutions/1736. Latest Time by Replacing Hidden Digits/1736.cpp new file mode 100644 index 00000000000..33396ec07bd --- /dev/null +++ b/solutions/1736. Latest Time by Replacing Hidden Digits/1736.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + string maximumTime(string time) { + string ans = time; + if (time[0] == '?') + ans[0] = time[1] == '?' || time[1] < '4' ? '2' : '1'; + if (time[1] == '?') + ans[1] = ans[0] == '2' ? '3' : '9'; + if (time[3] == '?') + ans[3] = '5'; + if (time[4] == '?') + ans[4] = '9'; + return ans; + } +}; diff --git a/solutions/1736. Latest Time by Replacing Hidden Digits/1736.java b/solutions/1736. Latest Time by Replacing Hidden Digits/1736.java new file mode 100644 index 00000000000..3b2dd774001 --- /dev/null +++ b/solutions/1736. Latest Time by Replacing Hidden Digits/1736.java @@ -0,0 +1,14 @@ +class Solution { + public String maximumTime(String time) { + char[] ans = time.toCharArray(); + if (time.charAt(0) == '?') + ans[0] = time.charAt(1) == '?' || time.charAt(1) < '4' ? '2' : '1'; + if (time.charAt(1) == '?') + ans[1] = ans[0] == '2' ? '3' : '9'; + if (time.charAt(3) == '?') + ans[3] = '5'; + if (time.charAt(4) == '?') + ans[4] = '9'; + return new String(ans); + } +} diff --git a/solutions/1736. Latest Time by Replacing Hidden Digits/1736.py b/solutions/1736. Latest Time by Replacing Hidden Digits/1736.py new file mode 100644 index 00000000000..44a8a966c26 --- /dev/null +++ b/solutions/1736. Latest Time by Replacing Hidden Digits/1736.py @@ -0,0 +1,12 @@ +class Solution: + def maximumTime(self, time: str) -> str: + ans = list(time) + if time[0] == '?': + ans[0] = '2' if time[1] == '?' or time[1] < '4' else '1' + if time[1] == '?': + ans[1] = '3' if ans[0] == '2' else '9' + if time[3] == '?': + ans[3] = '5' + if time[4] == '?': + ans[4] = '9' + return ''.join(ans) diff --git a/solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.cpp b/solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.cpp new file mode 100644 index 00000000000..4275bd16f80 --- /dev/null +++ b/solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int minCharacters(string a, string b) { + const int m = a.length(); + const int n = b.length(); + vector countA(26); + vector countB(26); + + for (const char c : a) + ++countA[c - 'a']; + + for (const char c : b) + ++countB[c - 'a']; + + int ans = INT_MAX; + int prevA = 0; // the number of characters in a <= c + int prevB = 0; // the number of characters in b <= c + + for (char c = 'a'; c <= 'z'; ++c) { + // the condition 3 + ans = min(ans, m + n - countA[c - 'a'] - countB[c - 'a']); + // the conditions 1 and 2 + if (c > 'a') + ans = min({ans, m - prevA + prevB, n - prevB + prevA}); + prevA += countA[c - 'a']; + prevB += countB[c - 'a']; + } + + return ans; + } +}; diff --git a/solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.java b/solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.java new file mode 100644 index 00000000000..7136d88968f --- /dev/null +++ b/solutions/1737. Change Minimum Characters to Satisfy One of Three Conditions/1737.java @@ -0,0 +1,30 @@ +class Solution { + public int minCharacters(String a, String b) { + final int m = a.length(); + final int n = b.length(); + int[] countA = new int[26]; + int[] countB = new int[26]; + + for (final char c : a.toCharArray()) + ++countA[c - 'a']; + + for (final char c : b.toCharArray()) + ++countB[c - 'a']; + + int ans = Integer.MAX_VALUE; + int prevA = 0; // the number of characters in a <= c + int prevB = 0; // the number of characters in b <= c + + for (char c = 'a'; c <= 'z'; ++c) { + // the condition 3 + ans = Math.min(ans, m + n - countA[c - 'a'] - countB[c - 'a']); + // the conditions 1 and 2 + if (c > 'a') + ans = Math.min(ans, Math.min(m - prevA + prevB, n - prevB + prevA)); + prevA += countA[c - 'a']; + prevB += countB[c - 'a']; + } + + return ans; + } +} diff --git a/solutions/1738. Find Kth Largest XOR Coordinate Value/1738.cpp b/solutions/1738. Find Kth Largest XOR Coordinate Value/1738.cpp new file mode 100644 index 00000000000..f1e17fe50b7 --- /dev/null +++ b/solutions/1738. Find Kth Largest XOR Coordinate Value/1738.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int kthLargestValue(vector>& matrix, int k) { + const int m = matrix.size(); + const int n = matrix[0].size(); + vector> xors(m + 1, vector(n + 1)); + priority_queue, greater<>> minHeap; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) { + xors[i][j] = xors[i - 1][j] ^ xors[i][j - 1] ^ xors[i - 1][j - 1] ^ + matrix[i - 1][j - 1]; + minHeap.push(xors[i][j]); + if (minHeap.size() > k) + minHeap.pop(); + } + + return minHeap.top(); + } +}; diff --git a/solutions/1738. Find Kth Largest XOR Coordinate Value/1738.java b/solutions/1738. Find Kth Largest XOR Coordinate Value/1738.java new file mode 100644 index 00000000000..a40d9d4870b --- /dev/null +++ b/solutions/1738. Find Kth Largest XOR Coordinate Value/1738.java @@ -0,0 +1,18 @@ +class Solution { + public int kthLargestValue(int[][] matrix, int k) { + final int m = matrix.length; + final int n = matrix[0].length; + int[][] xors = new int[m + 1][n + 1]; + Queue minHeap = new PriorityQueue<>(); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) { + xors[i][j] = xors[i - 1][j] ^ xors[i][j - 1] ^ xors[i - 1][j - 1] ^ matrix[i - 1][j - 1]; + minHeap.offer(xors[i][j]); + if (minHeap.size() > k) + minHeap.poll(); + } + + return minHeap.peek(); + } +} diff --git a/solutions/1739. Building Boxes/1739.cpp b/solutions/1739. Building Boxes/1739.cpp new file mode 100644 index 00000000000..ec628a1e3ef --- /dev/null +++ b/solutions/1739. Building Boxes/1739.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minimumBoxes(int n) { + int nBoxes = 0; + int nextTouchings = 0; // j + int currLevelBoxes = 0; // 1 + 2 + ... + j + + // Find the minimum j s.t. `nBoxes` = 1 + (1 + 2) + ... + (1 + 2 + ... + j) + // >= n. + while (nBoxes < n) { + ++nextTouchings; + currLevelBoxes += nextTouchings; + nBoxes += currLevelBoxes; + } + + // If nBoxes = n, the answer is `currLevelBoxes` = 1 + 2 + ... + j. + if (nBoxes == n) + return currLevelBoxes; + + // Otherwise, need to remove the boxes in the current level and rebuild it. + nBoxes -= currLevelBoxes; + currLevelBoxes -= nextTouchings; + nextTouchings = 0; + + while (nBoxes < n) { + ++nextTouchings; + nBoxes += nextTouchings; + } + + return currLevelBoxes + nextTouchings; + } +}; diff --git a/solutions/1739. Building Boxes/1739.java b/solutions/1739. Building Boxes/1739.java new file mode 100644 index 00000000000..46434449c1a --- /dev/null +++ b/solutions/1739. Building Boxes/1739.java @@ -0,0 +1,31 @@ +class Solution { + public int minimumBoxes(int n) { + int nBoxes = 0; + int nextTouchings = 0; // j + int currLevelBoxes = 0; // 1 + 2 + ... + j + + // Find the minimum j s.t. `nBoxes` = 1 + (1 + 2) + ... + (1 + 2 + ... + j) + // >= n. + while (nBoxes < n) { + ++nextTouchings; + currLevelBoxes += nextTouchings; + nBoxes += currLevelBoxes; + } + + // If nBoxes = n, the answer is `currLevelBoxes` = 1 + 2 + ... + j. + if (nBoxes == n) + return currLevelBoxes; + + // Otherwise, need to remove the boxes in the current level and rebuild it. + nBoxes -= currLevelBoxes; + currLevelBoxes -= nextTouchings; + nextTouchings = 0; + + while (nBoxes < n) { + ++nextTouchings; + nBoxes += nextTouchings; + } + + return currLevelBoxes + nextTouchings; + } +} diff --git a/solutions/1739. Building Boxes/1739.py b/solutions/1739. Building Boxes/1739.py new file mode 100644 index 00000000000..43ade616889 --- /dev/null +++ b/solutions/1739. Building Boxes/1739.py @@ -0,0 +1,27 @@ +class Solution: + def minimumBoxes(self, n: int) -> int: + nBoxes = 0 + nextTouchings = 0 # j + currLevelBoxes = 0 # 1 + 2 + ... + j + + # Find the minimum j s.t. `nBoxes` = 1 + (1 + 2) + ... + (1 + 2 + ... + j) + # >= n + while nBoxes < n: + nextTouchings += 1 + currLevelBoxes += nextTouchings + nBoxes += currLevelBoxes + + # If nBoxes = n, the answer is `currLevelBoxes` = 1 + 2 + ... + j. + if nBoxes == n: + return currLevelBoxes + + # Otherwise, need to remove the boxes in the current level and rebuild it. + nBoxes -= currLevelBoxes + currLevelBoxes -= nextTouchings + nextTouchings = 0 + + while nBoxes < n: + nextTouchings += 1 + nBoxes += nextTouchings + + return currLevelBoxes + nextTouchings diff --git a/solutions/174. Dungeon Game/174.cpp b/solutions/174. Dungeon Game/174.cpp new file mode 100644 index 00000000000..832e36cb0a6 --- /dev/null +++ b/solutions/174. Dungeon Game/174.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int calculateMinimumHP(vector>& dungeon) { + const int m = dungeon.size(); + const int n = dungeon[0].size(); + vector> dp(m + 1, vector(n + 1, INT_MAX)); + dp[m][n - 1] = 1; + dp[m - 1][n] = 1; + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) { + dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]; + dp[i][j] = max(dp[i][j], 1); + } + + return dp[0][0]; + } +}; diff --git a/solutions/174. Dungeon Game/174.java b/solutions/174. Dungeon Game/174.java new file mode 100644 index 00000000000..8db0e317d1b --- /dev/null +++ b/solutions/174. Dungeon Game/174.java @@ -0,0 +1,18 @@ +class Solution { + public int calculateMinimumHP(int[][] dungeon) { + final int m = dungeon.length; + final int n = dungeon[0].length; + int[][] dp = new int[m + 1][n + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + dp[m][n - 1] = 1; + dp[m - 1][n] = 1; + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) { + dp[i][j] = Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]; + dp[i][j] = Math.max(dp[i][j], 1); + } + + return dp[0][0]; + } +} diff --git a/solutions/174. Dungeon Game/174.py b/solutions/174. Dungeon Game/174.py new file mode 100644 index 00000000000..3380f9e1d54 --- /dev/null +++ b/solutions/174. Dungeon Game/174.py @@ -0,0 +1,13 @@ +class Solution: + def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: + m = len(dungeon) + n = len(dungeon[0]) + dp = [math.inf] * (n + 1) + dp[n - 1] = 1 + + for i in reversed(range(m)): + for j in reversed(range(n)): + dp[j] = min(dp[j], dp[j + 1]) - dungeon[i][j] + dp[j] = max(dp[j], 1) + + return dp[0] diff --git a/solutions/1740. Find Distance in a Binary Tree/1740.cpp b/solutions/1740. Find Distance in a Binary Tree/1740.cpp new file mode 100644 index 00000000000..ad200fb9116 --- /dev/null +++ b/solutions/1740. Find Distance in a Binary Tree/1740.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int findDistance(TreeNode* root, int p, int q) { + TreeNode* lca = getLCA(root, p, q); + return dist(lca, p) + dist(lca, q); + } + + private: + TreeNode* getLCA(TreeNode* root, int p, int q) { + if (root == nullptr || root->val == p || root->val == q) + return root; + TreeNode* left = getLCA(root->left, p, q); + TreeNode* right = getLCA(root->right, p, q); + if (left != nullptr && right != nullptr) + return root; + return left == nullptr ? right : left; + } + + int dist(TreeNode* lca, int target) { + if (lca == nullptr) + return 10000; + if (lca->val == target) + return 0; + return 1 + min(dist(lca->left, target), dist(lca->right, target)); + } +}; diff --git a/solutions/1740. Find Distance in a Binary Tree/1740.java b/solutions/1740. Find Distance in a Binary Tree/1740.java new file mode 100644 index 00000000000..be45786d8a4 --- /dev/null +++ b/solutions/1740. Find Distance in a Binary Tree/1740.java @@ -0,0 +1,26 @@ +class Solution { + public int findDistance(TreeNode root, int p, int q) { + TreeNode lca = getLCA(root, p, q); + return dist(lca, p) + dist(lca, q); + } + + private TreeNode getLCA(TreeNode root, int p, int q) { + if (root == null || root.val == p || root.val == q) + return root; + + TreeNode l = getLCA(root.left, p, q); + TreeNode r = getLCA(root.right, p, q); + + if (l != null && r != null) + return root; + return l == null ? r : l; + } + + private int dist(TreeNode lca, int target) { + if (lca == null) + return 10000; + if (lca.val == target) + return 0; + return 1 + Math.min(dist(lca.left, target), dist(lca.right, target)); + } +} diff --git a/solutions/1740. Find Distance in a Binary Tree/1740.py b/solutions/1740. Find Distance in a Binary Tree/1740.py new file mode 100644 index 00000000000..a2918767576 --- /dev/null +++ b/solutions/1740. Find Distance in a Binary Tree/1740.py @@ -0,0 +1,22 @@ +class Solution: + def findDistance(self, root: TreeNode, p: int, q: int) -> int: + def getLCA(root, p, q): + if not root or root.val == p or root.val == q: + return root + + l = getLCA(root.left, p, q) + r = getLCA(root.right, p, q) + + if l and r: + return root + return l or r + + def dist(lca, target): + if not lca: + return 10000 + if lca.val == target: + return 0 + return 1 + min(dist(lca.left, target), dist(lca.right, target)) + + lca = getLCA(root, p, q) + return dist(lca, p) + dist(lca, q) diff --git a/solutions/1741. Find Total Time Spent by Each Employee/1741.sql b/solutions/1741. Find Total Time Spent by Each Employee/1741.sql new file mode 100644 index 00000000000..df2183c2257 --- /dev/null +++ b/solutions/1741. Find Total Time Spent by Each Employee/1741.sql @@ -0,0 +1,6 @@ +SELECT + event_day AS day, + emp_id, + SUM(out_time - in_time) AS total_time +FROM Employees +GROUP BY 1, 2; diff --git a/solutions/1742. Maximum Number of Balls in a Box/1742.cpp b/solutions/1742. Maximum Number of Balls in a Box/1742.cpp new file mode 100644 index 00000000000..510128e2b1f --- /dev/null +++ b/solutions/1742. Maximum Number of Balls in a Box/1742.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int countBalls(int lowLimit, int highLimit) { + const int maxDigitSum = 9 * 5; // 99999 + int ans = 0; + vector count(maxDigitSum + 1); + + for (int num = lowLimit; num <= highLimit; ++num) + ans = max(ans, ++count[getDigitSum(num)]); + + return ans; + } + + private: + int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +}; diff --git a/solutions/1742. Maximum Number of Balls in a Box/1742.java b/solutions/1742. Maximum Number of Balls in a Box/1742.java new file mode 100644 index 00000000000..eea38a1247f --- /dev/null +++ b/solutions/1742. Maximum Number of Balls in a Box/1742.java @@ -0,0 +1,21 @@ +class Solution { + public int countBalls(int lowLimit, int highLimit) { + final int maxDigitSum = 9 * 5; // 99999 + int ans = 0; + int[] count = new int[maxDigitSum + 1]; + + for (int num = lowLimit; num <= highLimit; ++num) + ans = Math.max(ans, ++count[getDigitSum(num)]); + + return ans; + } + + private int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +} diff --git a/solutions/1742. Maximum Number of Balls in a Box/1742.py b/solutions/1742. Maximum Number of Balls in a Box/1742.py new file mode 100644 index 00000000000..12a9452ac9f --- /dev/null +++ b/solutions/1742. Maximum Number of Balls in a Box/1742.py @@ -0,0 +1,15 @@ +class Solution: + def countBalls(self, lowLimit: int, highLimit: int) -> int: + maxDigitSum = 9 * 5 # 99999 + ans = 0 + count = [0] * (maxDigitSum + 1) + + for num in range(lowLimit, highLimit + 1): + digitSum = self._getDigitSum(num) + count[digitSum] += 1 + ans = max(ans, count[digitSum]) + + return ans + + def _getDigitSum(self, num: int) -> int: + return sum(int(digit) for digit in str(num)) diff --git a/solutions/1743. Restore the Array From Adjacent Pairs/1743.cpp b/solutions/1743. Restore the Array From Adjacent Pairs/1743.cpp new file mode 100644 index 00000000000..16df8b34821 --- /dev/null +++ b/solutions/1743. Restore the Array From Adjacent Pairs/1743.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector restoreArray(vector>& adjacentPairs) { + vector ans; + unordered_map> numToAdjs; + + for (const vector& pair : adjacentPairs) { + const int u = pair[0]; + const int v = pair[1]; + numToAdjs[u].push_back(v); + numToAdjs[v].push_back(u); + } + + for (const auto& [num, adjs] : numToAdjs) + if (adjs.size() == 1) { + ans.push_back(num); + ans.push_back(adjs[0]); + break; + } + + while (ans.size() < adjacentPairs.size() + 1) { + const int tail = ans.back(); + const int prev = ans[ans.size() - 2]; + const vector& adjs = numToAdjs[tail]; + if (adjs[0] == prev) + ans.push_back(adjs[1]); + else + ans.push_back(adjs[0]); + } + + return ans; + } +}; diff --git a/solutions/1743. Restore the Array From Adjacent Pairs/1743.java b/solutions/1743. Restore the Array From Adjacent Pairs/1743.java new file mode 100644 index 00000000000..7d429c9b3a8 --- /dev/null +++ b/solutions/1743. Restore the Array From Adjacent Pairs/1743.java @@ -0,0 +1,33 @@ +class Solution { + public int[] restoreArray(int[][] adjacentPairs) { + int[] ans = new int[adjacentPairs.length + 1]; + int i = 0; // ans' index + Map> numToAdjs = new HashMap<>(); + + for (int[] pair : adjacentPairs) { + numToAdjs.putIfAbsent(pair[0], new ArrayList<>()); + numToAdjs.putIfAbsent(pair[1], new ArrayList<>()); + numToAdjs.get(pair[0]).add(pair[1]); + numToAdjs.get(pair[1]).add(pair[0]); + } + + for (Map.Entry> entry : numToAdjs.entrySet()) + if (entry.getValue().size() == 1) { + ans[i++] = entry.getKey(); + ans[i++] = entry.getValue().get(0); + break; + } + + while (i < adjacentPairs.length + 1) { + final int tail = ans[i - 1]; + final int prev = ans[i - 2]; + List adjs = numToAdjs.get(tail); + if (adjs.get(0) == prev) + ans[i++] = adjs.get(1); + else + ans[i++] = adjs.get(0); + } + + return ans; + } +} diff --git a/solutions/1743. Restore the Array From Adjacent Pairs/1743.py b/solutions/1743. Restore the Array From Adjacent Pairs/1743.py new file mode 100644 index 00000000000..36dd8d2d399 --- /dev/null +++ b/solutions/1743. Restore the Array From Adjacent Pairs/1743.py @@ -0,0 +1,25 @@ +class Solution: + def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: + ans = [] + numToAdjs = collections.defaultdict(list) + + for a, b in adjacentPairs: + numToAdjs[a].append(b) + numToAdjs[b].append(a) + + for num, adjs in numToAdjs.items(): + if len(adjs) == 1: + ans.append(num) + ans.append(adjs[0]) + break + + while len(ans) < len(adjacentPairs) + 1: + tail = ans[-1] + prev = ans[-2] + adjs = numToAdjs[tail] + if adjs[0] == prev: # adjs[0] is already used + ans.append(adjs[1]) + else: + ans.append(adjs[0]) + + return ans diff --git a/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.cpp b/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.cpp new file mode 100644 index 00000000000..b71c43a6aa0 --- /dev/null +++ b/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector canEat(vector& candiesCount, vector>& queries) { + const int n = candiesCount.size(); + vector ans; + vector prefix{0}; + + for (int i = 0; i < n; ++i) + prefix.push_back(prefix.back() + candiesCount[i]); + + for (const vector& query : queries) { + const int type = query[0]; + const int day = query[1]; + const int cap = query[2]; + // the minimum day required to eat + const long minDay = prefix[type] / cap; + // the maximum day required to eat + const long maxDay = prefix[type + 1] - 1; + ans.push_back(minDay <= day && day <= maxDay); + } + + return ans; + } +}; diff --git a/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.java b/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.java new file mode 100644 index 00000000000..f7a518ed7b7 --- /dev/null +++ b/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.java @@ -0,0 +1,23 @@ +class Solution { + public boolean[] canEat(int[] candiesCount, int[][] queries) { + final int n = candiesCount.length; + boolean[] ans = new boolean[queries.length]; + long[] prefix = new long[n + 1]; + + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + candiesCount[i]; + + for (int i = 0; i < queries.length; ++i) { + final int type = queries[i][0]; + final long day = (long) queries[i][1]; + final long cap = (long) queries[i][2]; + // the minimum day required to eat + final long minDay = prefix[type] / cap; + // the maximum day required to eat + final long maxDay = prefix[type + 1] - 1; + ans[i] = minDay <= day && day <= maxDay; + } + + return ans; + } +} diff --git a/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.py b/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.py new file mode 100644 index 00000000000..2a102bbcb0a --- /dev/null +++ b/solutions/1744. Can You Eat Your Favorite Candy on Your Favorite Day?/1744.py @@ -0,0 +1,4 @@ +class Solution: + def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]: + prefix = [0] + list(itertools.accumulate(candiesCount)) + return [prefix[t] // c <= d < prefix[t + 1] for t, d, c in queries] diff --git a/solutions/1745. Palindrome Partitioning IV/1745-2.cpp b/solutions/1745. Palindrome Partitioning IV/1745-2.cpp new file mode 100644 index 00000000000..af4c7df5e89 --- /dev/null +++ b/solutions/1745. Palindrome Partitioning IV/1745-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool checkPartitioning(string s) { + const int n = s.length(); + // dp[i][j] := true if s[i..j] is a palindrome + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = true; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + if (s[i] == s[j]) + dp[i][j] = i + 1 > j - 1 || dp[i + 1][j - 1]; + } + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) + if (dp[0][i] && dp[i + 1][j] && dp[j + 1][n - 1]) + return true; + + return false; + } +}; diff --git a/solutions/1745. Palindrome Partitioning IV/1745-2.java b/solutions/1745. Palindrome Partitioning IV/1745-2.java new file mode 100644 index 00000000000..9555b10c9b2 --- /dev/null +++ b/solutions/1745. Palindrome Partitioning IV/1745-2.java @@ -0,0 +1,24 @@ +class Solution { + public boolean checkPartitioning(String s) { + final int n = s.length(); + // dp[i][j] := true if s[i..j] is a palindrome + boolean[][] dp = new boolean[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = true; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + if (s.charAt(i) == s.charAt(j)) + dp[i][j] = i + 1 > j - 1 || dp[i + 1][j - 1]; + } + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) + if (dp[0][i] && dp[i + 1][j] && dp[j + 1][n - 1]) + return true; + + return false; + } +} diff --git a/solutions/1745. Palindrome Partitioning IV/1745-2.py b/solutions/1745. Palindrome Partitioning IV/1745-2.py new file mode 100644 index 00000000000..f10dd517d9d --- /dev/null +++ b/solutions/1745. Palindrome Partitioning IV/1745-2.py @@ -0,0 +1,21 @@ +class Solution: + def checkPartitioning(self, s: str) -> bool: + n = len(s) + # dp[i][j] := true if s[i..j] is a palindrome + dp = [[False] * n for _ in range(n)] + + for i in range(n): + dp[i][i] = True + + for d in range(1, n): + for i in range(n - d): + j = i + d + if s[i] == s[j]: + dp[i][j] = i + 1 > j - 1 or dp[i + 1][j - 1] + + for i in range(n): + for j in range(i + 1, n): + if dp[0][i] and dp[i + 1][j] and dp[j + 1][n - 1]: + return True + + return False diff --git a/solutions/1745. Palindrome Partitioning IV/1745.cpp b/solutions/1745. Palindrome Partitioning IV/1745.cpp new file mode 100644 index 00000000000..e4ca86648a0 --- /dev/null +++ b/solutions/1745. Palindrome Partitioning IV/1745.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + bool checkPartitioning(string s) { + const int n = s.length(); + vector> mem(n, vector(n, -1)); + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j + 1 < n; ++j) + if (isPalindrome(s, 0, i, mem) && // + isPalindrome(s, i + 1, j, mem) && // + isPalindrome(s, j + 1, n - 1, mem)) + return true; + + return false; + } + + private: + // Returns true if s[i..j] is a palindrome. + // Returns false if s[i..j] is not a palindrome. + bool isPalindrome(const string& s, int i, int j, vector>& mem) { + if (i > j) + return true; + if (mem[i][j] != -1) + return mem[i][j]; + if (s[i] == s[j]) + return mem[i][j] = isPalindrome(s, i + 1, j - 1, mem); + return mem[i][j] = false; + } +}; diff --git a/solutions/1745. Palindrome Partitioning IV/1745.java b/solutions/1745. Palindrome Partitioning IV/1745.java new file mode 100644 index 00000000000..5b6a210a540 --- /dev/null +++ b/solutions/1745. Palindrome Partitioning IV/1745.java @@ -0,0 +1,27 @@ +class Solution { + public boolean checkPartitioning(String s) { + final int n = s.length(); + Boolean[][] mem = new Boolean[n][n]; + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j + 1 < n; ++j) + if (isPalindrome(s, 0, i, mem) && // + isPalindrome(s, i + 1, j, mem) && // + isPalindrome(s, j + 1, n - 1, mem)) + return true; + + return false; + } + + // Returns true if s[i..j] is a palindrome. + // Returns false if s[i..j] is not a palindrome. + private boolean isPalindrome(final String s, int i, int j, Boolean[][] mem) { + if (i > j) + return true; + if (mem[i][j] != null) + return mem[i][j]; + if (s.charAt(i) == s.charAt(j)) + return mem[i][j] = isPalindrome(s, i + 1, j - 1, mem); + return mem[i][j] = false; + } +} diff --git a/solutions/1745. Palindrome Partitioning IV/1745.py b/solutions/1745. Palindrome Partitioning IV/1745.py new file mode 100644 index 00000000000..5c3bfe57665 --- /dev/null +++ b/solutions/1745. Palindrome Partitioning IV/1745.py @@ -0,0 +1,17 @@ +class Solution: + def checkPartitioning(self, s: str) -> bool: + @functools.lru_cache(None) + def isPalindrome(i: int, j: int) -> bool: + """Returns True if s[i..j] is a palindrome.""" + if i > j: + return True + if s[i] == s[j]: + return isPalindrome(i + 1, j - 1) + return False + + n = len(s) + return any(isPalindrome(0, i) and + isPalindrome(i + 1, j) and + isPalindrome(j + 1, n - 1) + for i in range(n) + for j in range(i + 1, n - 1)) diff --git a/solutions/1746. Maximum Subarray Sum After One Operation/1746.cpp b/solutions/1746. Maximum Subarray Sum After One Operation/1746.cpp new file mode 100644 index 00000000000..4ca20a6a473 --- /dev/null +++ b/solutions/1746. Maximum Subarray Sum After One Operation/1746.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxSumAfterOperation(vector& nums) { + int ans = INT_MIN; + int regular = 0; + int squared = 0; + + for (const int num : nums) { + squared = max({num * num, regular + num * num, squared + num}); + regular = max(num, regular + num); + ans = max(ans, squared); + } + + return ans; + } +}; diff --git a/solutions/1746. Maximum Subarray Sum After One Operation/1746.java b/solutions/1746. Maximum Subarray Sum After One Operation/1746.java new file mode 100644 index 00000000000..6ffae0e1505 --- /dev/null +++ b/solutions/1746. Maximum Subarray Sum After One Operation/1746.java @@ -0,0 +1,15 @@ +class Solution { + public int maxSumAfterOperation(int[] nums) { + int ans = Integer.MIN_VALUE; + int regular = 0; + int squared = 0; + + for (final int num : nums) { + squared = Math.max(num * num, Math.max(regular + num * num, squared + num)); + regular = Math.max(num, regular + num); + ans = Math.max(ans, squared); + } + + return ans; + } +} diff --git a/solutions/1746. Maximum Subarray Sum After One Operation/1746.py b/solutions/1746. Maximum Subarray Sum After One Operation/1746.py new file mode 100644 index 00000000000..77ba1cd75c8 --- /dev/null +++ b/solutions/1746. Maximum Subarray Sum After One Operation/1746.py @@ -0,0 +1,12 @@ +class Solution: + def maxSumAfterOperation(self, nums: List[int]) -> int: + ans = -math.inf + regular = 0 + squared = 0 + + for num in nums: + squared = max(num**2, regular + num**2, squared + num) + regular = max(num, regular + num) + ans = max(ans, squared) + + return ans diff --git a/solutions/1747. Leetflex Banned Accounts/1747.sql b/solutions/1747. Leetflex Banned Accounts/1747.sql new file mode 100644 index 00000000000..de4408b80ae --- /dev/null +++ b/solutions/1747. Leetflex Banned Accounts/1747.sql @@ -0,0 +1,19 @@ +WITH + LogInfoNeighbors AS ( + SELECT + *, + LEAD(ip_address) OVER( + PARTITION BY account_id + ORDER BY login + ) AS next_ip_address, + LEAD(login) OVER( + PARTITION BY account_id + ORDER BY login + ) next_login + FROM LogInfo + ) +SELECT DISTINCT account_id +FROM LogInfoNeighbors +WHERE + next_login <= logout + AND ip_address != next_ip_address; diff --git a/solutions/1748. Sum of Unique Elements/1748.cpp b/solutions/1748. Sum of Unique Elements/1748.cpp new file mode 100644 index 00000000000..fcaafb6f4ee --- /dev/null +++ b/solutions/1748. Sum of Unique Elements/1748.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int sumOfUnique(vector& nums) { + constexpr int kMax = 100; + int ans = 0; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int i = 1; i <= kMax; ++i) + if (count[i] == 1) + ans += i; + + return ans; + } +}; diff --git a/solutions/1748. Sum of Unique Elements/1748.java b/solutions/1748. Sum of Unique Elements/1748.java new file mode 100644 index 00000000000..8728109e837 --- /dev/null +++ b/solutions/1748. Sum of Unique Elements/1748.java @@ -0,0 +1,16 @@ +class Solution { + public int sumOfUnique(int[] nums) { + final int kMax = 100; + int ans = 0; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int i = 1; i <= kMax; ++i) + if (count[i] == 1) + ans += i; + + return ans; + } +} diff --git a/solutions/1748. Sum of Unique Elements/1748.py b/solutions/1748. Sum of Unique Elements/1748.py new file mode 100644 index 00000000000..b012c816897 --- /dev/null +++ b/solutions/1748. Sum of Unique Elements/1748.py @@ -0,0 +1,5 @@ +class Solution: + def sumOfUnique(self, nums: List[int]) -> int: + return sum(num + for num, freq in collections.Counter(nums).items() + if freq == 1) diff --git a/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.cpp b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.cpp new file mode 100644 index 00000000000..9841e0616f5 --- /dev/null +++ b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxAbsoluteSum(vector& nums) { + int sum = 0; + int maxPrefix = 0; + int minPrefix = 0; + + for (const int num : nums) { + sum += num; + maxPrefix = max(maxPrefix, sum); + minPrefix = min(minPrefix, sum); + } + + return maxPrefix - minPrefix; + } +}; diff --git a/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.java b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.java new file mode 100644 index 00000000000..aa0b32ae8e0 --- /dev/null +++ b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.java @@ -0,0 +1,15 @@ +class Solution { + public int maxAbsoluteSum(int[] nums) { + int sum = 0; + int maxPrefix = 0; + int minPrefix = 0; + + for (final int num : nums) { + sum += num; + maxPrefix = Math.max(maxPrefix, sum); + minPrefix = Math.min(minPrefix, sum); + } + + return maxPrefix - minPrefix; + } +} diff --git a/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.py b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.py new file mode 100644 index 00000000000..faa7b052a28 --- /dev/null +++ b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749-2.py @@ -0,0 +1,12 @@ +class Solution: + def maxAbsoluteSum(self, nums): + summ = 0 + maxPrefix = 0 + minPrefix = 0 + + for num in nums: + summ += num + maxPrefix = max(maxPrefix, summ) + minPrefix = min(minPrefix, summ) + + return maxPrefix - minPrefix diff --git a/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.cpp b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.cpp new file mode 100644 index 00000000000..9b8db3c6897 --- /dev/null +++ b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxAbsoluteSum(vector& nums) { + int ans = INT_MIN; + int maxSum = 0; + int minSum = 0; + + for (const int num : nums) { + maxSum = max(num, maxSum + num); + minSum = min(num, minSum + num); + ans = max({ans, maxSum, -minSum}); + } + + return ans; + } +}; diff --git a/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.java b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.java new file mode 100644 index 00000000000..33c0e6ec628 --- /dev/null +++ b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.java @@ -0,0 +1,15 @@ +class Solution { + public int maxAbsoluteSum(int[] nums) { + int ans = Integer.MIN_VALUE; + int maxSum = 0; + int minSum = 0; + + for (final int num : nums) { + maxSum = Math.max(num, maxSum + num); + minSum = Math.min(num, minSum + num); + ans = Math.max(ans, Math.max(maxSum, -minSum)); + } + + return ans; + } +} diff --git a/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.py b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.py new file mode 100644 index 00000000000..ab8166e40fd --- /dev/null +++ b/solutions/1749. Maximum Absolute Sum of Any Subarray/1749.py @@ -0,0 +1,12 @@ +class Solution: + def maxAbsoluteSum(self, nums): + ans = -math.inf + maxSum = 0 + minSum = 0 + + for num in nums: + maxSum = max(num, maxSum + num) + minSum = min(num, minSum + num) + ans = max(ans, maxSum, -minSum) + + return ans diff --git a/solutions/175. Combine Two Tables/175.sql b/solutions/175. Combine Two Tables/175.sql new file mode 100644 index 00000000000..e063f3008c8 --- /dev/null +++ b/solutions/175. Combine Two Tables/175.sql @@ -0,0 +1,8 @@ +SELECT + Person.firstName, + Person.lastName, + Address.city, + Address.state +FROM Person +LEFT JOIN Address + USING (personId); diff --git a/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.cpp b/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.cpp new file mode 100644 index 00000000000..2863029dd3d --- /dev/null +++ b/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minimumLength(string s) { + int i = 0; + int j = s.length() - 1; + + while (i < j && s[i] == s[j]) { + const char c = s[i]; + while (i <= j && s[i] == c) + ++i; + while (i <= j && s[j] == c) + --j; + } + + return j - i + 1; + } +}; diff --git a/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.java b/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.java new file mode 100644 index 00000000000..483e247c26b --- /dev/null +++ b/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.java @@ -0,0 +1,16 @@ +class Solution { + public int minimumLength(String s) { + int i = 0; + int j = s.length() - 1; + + while (i < j && s.charAt(i) == s.charAt(j)) { + final char c = s.charAt(i); + while (i <= j && s.charAt(i) == c) + ++i; + while (i <= j && s.charAt(j) == c) + --j; + } + + return j - i + 1; + } +} diff --git a/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.py b/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.py new file mode 100644 index 00000000000..85d5d094b62 --- /dev/null +++ b/solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.py @@ -0,0 +1,13 @@ +class Solution: + def minimumLength(self, s: str) -> int: + i = 0 + j = len(s) - 1 + + while i < j and s[i] == s[j]: + c = s[i] + while i <= j and s[i] == c: + i += 1 + while i <= j and s[j] == c: + j -= 1 + + return j - i + 1 diff --git a/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.cpp b/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.cpp new file mode 100644 index 00000000000..a3803797784 --- /dev/null +++ b/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int maxValue(vector>& events, int k) { + vector> mem(events.size(), vector(k + 1, -1)); + ranges::sort(events); + return maxValue(events, 0, k, mem); + } + + private: + // Returns the maximum sum of values that you can receive by attending + // events[i..n), where k is the maximum number of attendancevents. + int maxValue(const vector>& events, int i, int k, + vector>& mem) { + if (k == 0 || i == events.size()) + return 0; + if (mem[i][k] != -1) + return mem[i][k]; + + // Binary search `events` to find the first index j + // s.t. events[j][0] > events[i][1]. + const auto it = upper_bound( + events.begin() + i, events.end(), events[i][1], + [](int end, const vector& event) { return event[0] > end; }); + const int j = distance(events.begin(), it); + return mem[i][k] = max(events[i][2] + maxValue(events, j, k - 1, mem), + maxValue(events, i + 1, k, mem)); + } +}; diff --git a/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.java b/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.java new file mode 100644 index 00000000000..955e216da7b --- /dev/null +++ b/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.java @@ -0,0 +1,33 @@ +class Solution { + public int maxValue(int[][] events, int k) { + Integer[][] mem = new Integer[events.length][k + 1]; + Arrays.sort(events, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + return maxValue(events, 0, k, mem); + } + + private int maxValue(int[][] events, int i, int k, Integer[][] mem) { + if (k == 0 || i == events.length) + return 0; + if (mem[i][k] != null) + return mem[i][k]; + + // Binary search `events` to find the first index j + // s.t. events[j][0] > events[i][1]. + final int j = firstGreaterEqual(events, i + 1, events[i][1] + 1); + return mem[i][k] = Math.max(events[i][2] + maxValue(events, j, k - 1, mem), + maxValue(events, i + 1, k, mem)); + } + + // Finds the first index l s.t events[l][0] >= target. + private int firstGreaterEqual(int[][] events, int l, int target) { + int r = events.length; + while (l < r) { + final int m = (l + r) / 2; + if (events[m][0] >= target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.py b/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.py new file mode 100644 index 00000000000..d125c621292 --- /dev/null +++ b/solutions/1751. Maximum Number of Events That Can Be Attended II/1751.py @@ -0,0 +1,19 @@ +class Solution: + def maxValue(self, events: List[List[int]], k: int) -> int: + events.sort() + + @functools.lru_cache(None) + def dp(i: int, k: int) -> int: + """ + Returns the maximum sum of values that you can receive by attending + events[i..n), where k is the maximum number of attendance. + """ + if k == 0 or i == len(events): + return 0 + + # Binary search `events` to find the first index j + # s.t. events[j][0] > events[i][1]. + j = bisect.bisect(events, [events[i][1], math.inf, math.inf], i + 1) + return max(events[i][2] + dp(j, k - 1), dp(i + 1, k)) + + return dp(0, k) diff --git a/solutions/1752. Check if Array Is Sorted and Rotated/1752.cpp b/solutions/1752. Check if Array Is Sorted and Rotated/1752.cpp new file mode 100644 index 00000000000..248d0ffc2a9 --- /dev/null +++ b/solutions/1752. Check if Array Is Sorted and Rotated/1752.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool check(vector& nums) { + const int n = nums.size(); + int rotates = 0; + + for (int i = 0; i < n; ++i) + if (nums[i] > nums[(i + 1) % n] && ++rotates > 1) + return false; + + return true; + } +}; diff --git a/solutions/1752. Check if Array Is Sorted and Rotated/1752.java b/solutions/1752. Check if Array Is Sorted and Rotated/1752.java new file mode 100644 index 00000000000..3a7464fe5ce --- /dev/null +++ b/solutions/1752. Check if Array Is Sorted and Rotated/1752.java @@ -0,0 +1,12 @@ +class Solution { + public boolean check(int[] nums) { + final int n = nums.length; + int rotates = 0; + + for (int i = 0; i < n; ++i) + if (nums[i] > nums[(i + 1) % n] && ++rotates > 1) + return false; + + return true; + } +} diff --git a/solutions/1753. Maximum Score From Removing Stones/1753.cpp b/solutions/1753. Maximum Score From Removing Stones/1753.cpp new file mode 100644 index 00000000000..db05979f39c --- /dev/null +++ b/solutions/1753. Maximum Score From Removing Stones/1753.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int maximumScore(int a, int b, int c) { + // the maximum <= the minimum + the middle + const int x = (a + b + c) / 2; + // the maximum > the minimum + the middle + const int y = a + b + c - max({a, b, c}); + return min(x, y); + } +}; diff --git a/solutions/1753. Maximum Score From Removing Stones/1753.java b/solutions/1753. Maximum Score From Removing Stones/1753.java new file mode 100644 index 00000000000..aed76baf4f0 --- /dev/null +++ b/solutions/1753. Maximum Score From Removing Stones/1753.java @@ -0,0 +1,9 @@ +class Solution { + public int maximumScore(int a, int b, int c) { + // the maximum <= the minimum + the middle + final int x = (a + b + c) / 2; + // the maximum > the minimum + the middle + final int y = a + b + c - Math.max(a, Math.max(b, c)); + return Math.min(x, y); + } +} diff --git a/solutions/1754. Largest Merge Of Two Strings/1754.cpp b/solutions/1754. Largest Merge Of Two Strings/1754.cpp new file mode 100644 index 00000000000..18bf1e5a447 --- /dev/null +++ b/solutions/1754. Largest Merge Of Two Strings/1754.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + string largestMerge(string word1, string word2) { + if (word1.empty()) + return word2; + if (word2.empty()) + return word1; + return word1 > word2 ? word1[0] + largestMerge(word1.substr(1), word2) + : word2[0] + largestMerge(word1, word2.substr(1)); + } +}; diff --git a/solutions/1754. Largest Merge Of Two Strings/1754.java b/solutions/1754. Largest Merge Of Two Strings/1754.java new file mode 100644 index 00000000000..167f08554de --- /dev/null +++ b/solutions/1754. Largest Merge Of Two Strings/1754.java @@ -0,0 +1,10 @@ +class Solution { + public String largestMerge(String word1, String word2) { + if (word1.isEmpty()) + return word2; + if (word2.isEmpty()) + return word1; + return word1.compareTo(word2) > 0 ? word1.charAt(0) + largestMerge(word1.substring(1), word2) + : word2.charAt(0) + largestMerge(word1, word2.substring(1)); + } +} diff --git a/solutions/1754. Largest Merge Of Two Strings/1754.py b/solutions/1754. Largest Merge Of Two Strings/1754.py new file mode 100644 index 00000000000..80522892247 --- /dev/null +++ b/solutions/1754. Largest Merge Of Two Strings/1754.py @@ -0,0 +1,9 @@ +class Solution: + def largestMerge(self, word1: str, word2: str) -> str: + if not word1: + return word2 + if not word2: + return word1 + if word1 > word2: + return word1[0] + self.largestMerge(word1[1:], word2) + return word2[0] + self.largestMerge(word1, word2[1:]) diff --git a/solutions/1755. Closest Subsequence Sum/1755.cpp b/solutions/1755. Closest Subsequence Sum/1755.cpp new file mode 100644 index 00000000000..555cecaf292 --- /dev/null +++ b/solutions/1755. Closest Subsequence Sum/1755.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int minAbsDifference(vector& nums, int goal) { + const int n = nums.size() / 2; + const vector lNums(nums.begin(), nums.begin() + n); + const vector rNums(nums.begin() + n, nums.end()); + int ans = INT_MAX; + vector lSums; + vector rSums; + + dfs(lNums, 0, 0, lSums); + dfs(rNums, 0, 0, rSums); + ranges::sort(rSums); + + for (const int lSum : lSums) { + const int i = firstGreaterEqual(rSums, goal - lSum); + if (i < rSums.size()) // 2^n + ans = min(ans, abs(goal - lSum - rSums[i])); + if (i > 0) + ans = min(ans, abs(goal - lSum - rSums[i - 1])); + } + + return ans; + } + + private: + void dfs(const vector& A, int i, int path, vector& sums) { + if (i == A.size()) { + sums.push_back(path); + return; + } + dfs(A, i + 1, path + A[i], sums); + dfs(A, i + 1, path, sums); + } + + int firstGreaterEqual(const vector& A, int target) { + return ranges::lower_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/1755. Closest Subsequence Sum/1755.java b/solutions/1755. Closest Subsequence Sum/1755.java new file mode 100644 index 00000000000..af822f6cfff --- /dev/null +++ b/solutions/1755. Closest Subsequence Sum/1755.java @@ -0,0 +1,38 @@ +class Solution { + public int minAbsDifference(int[] nums, int goal) { + final int n = nums.length / 2; + final int[] lNums = Arrays.copyOfRange(nums, 0, n); + final int[] rNums = Arrays.copyOfRange(nums, n, nums.length); + int ans = Integer.MAX_VALUE; + List lSums = new ArrayList<>(); + List rSums = new ArrayList<>(); + + dfs(lNums, 0, 0, lSums); + dfs(rNums, 0, 0, rSums); + Collections.sort(rSums); + + for (final int lSum : lSums) { + final int i = firstGreaterEqual(rSums, goal - lSum); + if (i < rSums.size()) // 2^n + ans = Math.min(ans, Math.abs(goal - lSum - rSums.get(i))); + if (i > 0) + ans = Math.min(ans, Math.abs(goal - lSum - rSums.get(i - 1))); + } + + return ans; + } + + private void dfs(int[] A, int i, int path, List sums) { + if (i == A.length) { + sums.add(path); + return; + } + dfs(A, i + 1, path + A[i], sums); + dfs(A, i + 1, path, sums); + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/1755. Closest Subsequence Sum/1755.py b/solutions/1755. Closest Subsequence Sum/1755.py new file mode 100644 index 00000000000..5d03c491390 --- /dev/null +++ b/solutions/1755. Closest Subsequence Sum/1755.py @@ -0,0 +1,26 @@ +class Solution: + def minAbsDifference(self, nums: List[int], goal: int) -> int: + n = len(nums) // 2 + ans = math.inf + lSums = [] + rSums = [] + + def dfs(A: List[int], i: int, path: int, sums: List[int]) -> None: + if i == len(A): + sums.append(path) + return + dfs(A, i + 1, path + A[i], sums) + dfs(A, i + 1, path, sums) + + dfs(nums[:n], 0, 0, lSums) + dfs(nums[n:], 0, 0, rSums) + rSums.sort() + + for lSum in lSums: + i = bisect_left(rSums, goal - lSum) + if i < len(rSums): # 2^n + ans = min(ans, abs(goal - lSum - rSums[i])) + if i > 0: + ans = min(ans, abs(goal - lSum - rSums[i - 1])) + + return ans diff --git a/solutions/1756. Design Most Recently Used Queue/1756.py b/solutions/1756. Design Most Recently Used Queue/1756.py new file mode 100644 index 00000000000..e828b6495df --- /dev/null +++ b/solutions/1756. Design Most Recently Used Queue/1756.py @@ -0,0 +1,16 @@ +from sortedcontainers import SortedList + + +class MRUQueue: + def __init__(self, n: int): + # [(priority value, actual value)] + self.q = SortedList((i, i) for i in range(1, n + 1)) + + def fetch(self, k: int) -> int: + _, num = self.q.pop(k - 1) + if self.q: + maxPriority = self.q[-1][0] + self.q.add((maxPriority + 1, num)) + else: + self.q.add((0, num)) + return num diff --git a/solutions/1757. Recyclable and Low Fat Products/1757.sql b/solutions/1757. Recyclable and Low Fat Products/1757.sql new file mode 100644 index 00000000000..3fccc655faf --- /dev/null +++ b/solutions/1757. Recyclable and Low Fat Products/1757.sql @@ -0,0 +1,3 @@ +SELECT product_id +FROM Products +WHERE low_fats = 'Y' AND recyclable = 'Y'; diff --git a/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.cpp b/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.cpp new file mode 100644 index 00000000000..3a5d2b026cd --- /dev/null +++ b/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int minOperations(string s) { + int cost10; // the cost to make s "1010" + + for (int i = 0; i < s.length(); ++i) + if (s[i] - '0' == i % 2) + ++cost10; + + const int cost01 = s.length() - cost10; // the cost to make s "0101" + return min(cost10, cost01); + } +}; diff --git a/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.java b/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.java new file mode 100644 index 00000000000..885fb388b19 --- /dev/null +++ b/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.java @@ -0,0 +1,12 @@ +class Solution { + public int minOperations(String s) { + int cost10 = 0; // the cost to make s "1010" + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) - '0' == i % 2) + ++cost10; + + final int cost01 = s.length() - cost10; // the cost to make s "0101" + return Math.min(cost10, cost01); + } +} diff --git a/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.py b/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.py new file mode 100644 index 00000000000..15fd89a8c72 --- /dev/null +++ b/solutions/1758. Minimum Changes To Make Alternating Binary String/1758.py @@ -0,0 +1,7 @@ +class Solution: + def minOperations(self, s: str) -> int: + # the cost to make s "1010" + cost10 = sum(int(c) == i % 2 for i, c in enumerate(s)) + # the cost to make s "0101" + cost01 = len(s) - cost10 + return min(cost10, cost01) diff --git a/solutions/1759. Count Number of Homogenous Substrings/1759.cpp b/solutions/1759. Count Number of Homogenous Substrings/1759.cpp new file mode 100644 index 00000000000..80ea604d546 --- /dev/null +++ b/solutions/1759. Count Number of Homogenous Substrings/1759.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int countHomogenous(string s) { + constexpr int kMod = 1'000'000'007; + int ans = 0; + int count = 0; + char currentChar = '@'; + + for (const char c : s) { + count = c == currentChar ? count + 1 : 1; + currentChar = c; + ans += count; + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/1759. Count Number of Homogenous Substrings/1759.java b/solutions/1759. Count Number of Homogenous Substrings/1759.java new file mode 100644 index 00000000000..bb4a71b11bf --- /dev/null +++ b/solutions/1759. Count Number of Homogenous Substrings/1759.java @@ -0,0 +1,17 @@ +class Solution { + public int countHomogenous(String s) { + final int kMod = 1_000_000_007; + int ans = 0; + int count = 0; + char currentChar = '@'; + + for (final char c : s.toCharArray()) { + count = c == currentChar ? count + 1 : 1; + currentChar = c; + ans += count; + ans %= kMod; + } + + return ans; + } +} diff --git a/solutions/1759. Count Number of Homogenous Substrings/1759.py b/solutions/1759. Count Number of Homogenous Substrings/1759.py new file mode 100644 index 00000000000..ee4804ba18f --- /dev/null +++ b/solutions/1759. Count Number of Homogenous Substrings/1759.py @@ -0,0 +1,14 @@ +class Solution: + def countHomogenous(self, s: str) -> int: + kMod = 1_000_000_007 + ans = 0 + count = 0 + currentChar = '@' + + for c in s: + count = count + 1 if c == currentChar else 1 + currentChar = c + ans += count + ans %= kMod + + return ans diff --git a/solutions/176. Second Highest Salary/176.sql b/solutions/176. Second Highest Salary/176.sql new file mode 100644 index 00000000000..f900e08219b --- /dev/null +++ b/solutions/176. Second Highest Salary/176.sql @@ -0,0 +1,8 @@ +WITH + RankedEmployees AS ( + SELECT *, DENSE_RANK() OVER(ORDER BY salary DESC) AS `rank` + FROM Employee + ) +SELECT MAX(salary) AS SecondHighestSalary +FROM RankedEmployees +WHERE `rank` = 2; diff --git a/solutions/1760. Minimum Limit of Balls in a Bag/1760.cpp b/solutions/1760. Minimum Limit of Balls in a Bag/1760.cpp new file mode 100644 index 00000000000..18c5bb31757 --- /dev/null +++ b/solutions/1760. Minimum Limit of Balls in a Bag/1760.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minimumSize(vector& nums, int maxOperations) { + int l = 1; + int r = ranges::max(nums); + + while (l < r) { + const int m = (l + r) / 2; + if (numOperations(nums, m) <= maxOperations) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Returns the number of operations required to make m penalty. + int numOperations(const vector& nums, int m) { + int operations = 0; + for (const int num : nums) + operations += (num - 1) / m; + return operations; + } +}; diff --git a/solutions/1760. Minimum Limit of Balls in a Bag/1760.java b/solutions/1760. Minimum Limit of Balls in a Bag/1760.java new file mode 100644 index 00000000000..2d661edfaa8 --- /dev/null +++ b/solutions/1760. Minimum Limit of Balls in a Bag/1760.java @@ -0,0 +1,24 @@ +class Solution { + public int minimumSize(int[] nums, int maxOperations) { + int l = 1; + int r = Arrays.stream(nums).max().getAsInt(); + + while (l < r) { + final int m = (l + r) / 2; + if (numOperations(nums, m) <= maxOperations) + r = m; + else + l = m + 1; + } + + return l; + } + + // Returns the number of operations required to make m penalty. + private int numOperations(int[] nums, int m) { + int operations = 0; + for (final int num : nums) + operations += (num - 1) / m; + return operations; + } +} diff --git a/solutions/1760. Minimum Limit of Balls in a Bag/1760.py b/solutions/1760. Minimum Limit of Balls in a Bag/1760.py new file mode 100644 index 00000000000..4941e55b5dc --- /dev/null +++ b/solutions/1760. Minimum Limit of Balls in a Bag/1760.py @@ -0,0 +1,7 @@ +class Solution: + def minimumSize(self, nums: List[int], maxOperations: int) -> int: + # Returns the number of operations required to make m penalty. + def numOperations(m: int) -> int: + return sum((num - 1) // m for num in nums) <= maxOperations + return bisect.bisect_left(range(1, max(nums)), True, + key=lambda m: numOperations(m)) + 1 diff --git a/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.cpp b/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.cpp new file mode 100644 index 00000000000..c6527896de0 --- /dev/null +++ b/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minTrioDegree(int n, vector>& edges) { + int ans = INT_MAX; + vector> graph(n); + vector degrees(n); + + for (const vector& edge : edges) { + const int u = edge[0] - 1; + const int v = edge[1] - 1; + // Store the mapping from `min(u, v)` to `max(u, v)` to speed up. + graph[min(u, v)].insert(max(u, v)); + ++degrees[u]; + ++degrees[v]; + } + + for (int u = 0; u < n; ++u) + for (const int v : graph[u]) + for (const int w : graph[u]) + if (graph[v].contains(w)) + ans = min(ans, degrees[u] + degrees[v] + degrees[w] - 6); + + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.java b/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.java new file mode 100644 index 00000000000..29ab78160fd --- /dev/null +++ b/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.java @@ -0,0 +1,27 @@ +class Solution { + public int minTrioDegree(int n, int[][] edges) { + int ans = Integer.MAX_VALUE; + Set[] graph = new Set[n]; + int[] degrees = new int[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new HashSet<>(); + + for (int[] edge : edges) { + final int u = edge[0] - 1; + final int v = edge[1] - 1; + // Store the mapping from `min(u, v)` to `max(u, v)` to speed up. + graph[Math.min(u, v)].add(Math.max(u, v)); + ++degrees[u]; + ++degrees[v]; + } + + for (int u = 0; u < n; u++) + for (final int v : graph[u]) + for (final int w : graph[u]) + if (graph[v].contains(w)) + ans = Math.min(ans, degrees[u] + degrees[v] + degrees[w] - 6); + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.py b/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.py new file mode 100644 index 00000000000..6bf28a49b30 --- /dev/null +++ b/solutions/1761. Minimum Degree of a Connected Trio in a Graph/1761.py @@ -0,0 +1,21 @@ +class Solution: + def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: + ans = math.inf + graph = [set() for _ in range(n)] + degrees = [0] * n + + for u, v in edges: + u -= 1 + v -= 1 + # Store the mapping from `min(u, v)` to `max(u, v)` to speed up. + graph[min(u, v)].add(max(u, v)) + degrees[u] += 1 + degrees[v] += 1 + + for u in range(n): + for v in graph[u]: + for w in graph[u]: + if w in graph[v]: + ans = min(ans, degrees[u] + degrees[v] + degrees[w] - 6) + + return -1 if ans == math.inf else ans diff --git a/solutions/1762. Buildings With an Ocean View/1762.cpp b/solutions/1762. Buildings With an Ocean View/1762.cpp new file mode 100644 index 00000000000..5a926a1bcef --- /dev/null +++ b/solutions/1762. Buildings With an Ocean View/1762.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector findBuildings(vector& heights) { + vector stack; + + for (int i = 0; i < heights.size(); ++i) { + while (!stack.empty() && heights[stack.back()] <= heights[i]) + stack.pop_back(); + stack.push_back(i); + } + + return stack; + } +}; diff --git a/solutions/1762. Buildings With an Ocean View/1762.java b/solutions/1762. Buildings With an Ocean View/1762.java new file mode 100644 index 00000000000..7475d40e64e --- /dev/null +++ b/solutions/1762. Buildings With an Ocean View/1762.java @@ -0,0 +1,16 @@ +class Solution { + public int[] findBuildings(int[] heights) { + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < heights.length; ++i) { + while (!stack.isEmpty() && heights[stack.peek()] <= heights[i]) + stack.pop(); + stack.push(i); + } + + int[] ans = new int[stack.size()]; + for (int i = 0; i < ans.length; ++i) + ans[ans.length - 1 - i] = stack.pop(); + return ans; + } +} diff --git a/solutions/1762. Buildings With an Ocean View/1762.py b/solutions/1762. Buildings With an Ocean View/1762.py new file mode 100644 index 00000000000..9264667013d --- /dev/null +++ b/solutions/1762. Buildings With an Ocean View/1762.py @@ -0,0 +1,10 @@ +class Solution: + def findBuildings(self, heights: List[int]) -> List[int]: + stack = [] + + for i, height in enumerate(heights): + while stack and heights[stack[-1]] <= height: + stack.pop() + stack.append(i) + + return stack diff --git a/solutions/1763. Longest Nice Substring/1763.cpp b/solutions/1763. Longest Nice Substring/1763.cpp new file mode 100644 index 00000000000..559e639777d --- /dev/null +++ b/solutions/1763. Longest Nice Substring/1763.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + string longestNiceSubstring(string s) { + if (s.length() < 2) + return ""; + + unordered_set seen{s.begin(), s.end()}; + + for (int i = 0; i < s.size(); ++i) + // If both upper and lower case letters exists in the string, keep moving, + // else take the erroneous character as a partition and check for its left + // and right parts to be nice strings. + if (!seen.contains(toggleCase(s[i]))) { + const string prefix = longestNiceSubstring(s.substr(0, i)); + const string suffix = longestNiceSubstring(s.substr(i + 1)); + return prefix.length() >= suffix.length() ? prefix : suffix; + } + + return s; + } + + private: + char toggleCase(char c) { + return islower(c) ? toupper(c) : tolower(c); + } +}; diff --git a/solutions/1763. Longest Nice Substring/1763.java b/solutions/1763. Longest Nice Substring/1763.java new file mode 100644 index 00000000000..f62af568f4f --- /dev/null +++ b/solutions/1763. Longest Nice Substring/1763.java @@ -0,0 +1,21 @@ +class Solution { + public String longestNiceSubstring(String s) { + if (s.length() < 2) + return ""; + + Set seen = s.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); + + for (int i = 0; i < s.length(); ++i) + if (!seen.contains(toggleCase(s.charAt(i)))) { + final String prefix = longestNiceSubstring(s.substring(0, i)); + final String suffix = longestNiceSubstring(s.substring(i + 1)); + return prefix.length() >= suffix.length() ? prefix : suffix; + } + + return s; + } + + private char toggleCase(char c) { + return Character.isLowerCase(c) ? Character.toUpperCase(c) : Character.toLowerCase(c); + } +} diff --git a/solutions/1763. Longest Nice Substring/1763.py b/solutions/1763. Longest Nice Substring/1763.py new file mode 100644 index 00000000000..cca77eb923e --- /dev/null +++ b/solutions/1763. Longest Nice Substring/1763.py @@ -0,0 +1,17 @@ +class Solution: + def longestNiceSubstring(self, s: str) -> str: + if len(s) < 2: + return '' + + seen = set(s) + + for i, c in enumerate(s): + # If both upper and lower case letters exists in the string, keep moving, + # else take the erroneous character as a partition and check for its left + # and right parts to be nice strings. + if c.swapcase() not in seen: + prefix = self.longestNiceSubstring(s[:i]) + suffix = self.longestNiceSubstring(s[i + 1:]) + return max(prefix, suffix, key=len) + + return s diff --git a/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.cpp b/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.cpp new file mode 100644 index 00000000000..81265e64a8b --- /dev/null +++ b/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool canChoose(vector>& groups, vector& nums) { + int i = 0; // groups' index + int j = 0; // nums' index + + while (i < groups.size() && j < nums.size()) + if (isMatch(groups[i], nums, j)) { + j += groups[i].size(); + ++i; + } else { + ++j; + } + + return i == groups.size(); + } + + private: + // Returns true if group == nums[j..j + |group|]. + bool isMatch(const vector& group, const vector& nums, int j) { + if (j + group.size() > nums.size()) + return false; + for (int i = 0; i < group.size(); ++i) + if (group[i] != nums[j + i]) + return false; + return true; + } +}; diff --git a/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.java b/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.java new file mode 100644 index 00000000000..6721c5ab0de --- /dev/null +++ b/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.java @@ -0,0 +1,26 @@ +class Solution { + public boolean canChoose(int[][] groups, int[] nums) { + int i = 0; // groups' index + int j = 0; // nums' index + + while (i < groups.length && j < nums.length) + if (isMatch(groups[i], nums, j)) { + j += groups[i].length; + ++i; + } else { + ++j; + } + + return i == groups.length; + } + + // Returns true if group == nums[j..j + |group|]. + private boolean isMatch(int[] group, int[] nums, int j) { + if (j + group.length > nums.length) + return false; + for (int i = 0; i < group.length; ++i) + if (group[i] != nums[j + i]) + return false; + return true; + } +} diff --git a/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.py b/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.py new file mode 100644 index 00000000000..8fdb93bbfaa --- /dev/null +++ b/solutions/1764. Form Array by Concatenating Subarrays of Another Array/1764.py @@ -0,0 +1,22 @@ +class Solution: + def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: + i = 0 # groups' index + j = 0 # nums' index + + while i < len(groups) and j < len(nums): + if self._isMatch(groups[i], nums, j): + j += len(groups[i]) + i += 1 + else: + j += 1 + + return i == len(groups) + + # Returns True if group == nums[j..j + |group|]. + def _isMatch(self, group: List[int], nums: List[int], j: int) -> bool: + if j + |group| > len(nums): + return False + for i, g in enumerate(group): + if g != nums[j + i]: + return False + return True diff --git a/solutions/1765. Map of Highest Peak/1765.cpp b/solutions/1765. Map of Highest Peak/1765.cpp new file mode 100644 index 00000000000..8c494cf3b76 --- /dev/null +++ b/solutions/1765. Map of Highest Peak/1765.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + vector> highestPeak(vector>& isWater) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = isWater.size(); + const int n = isWater[0].size(); + vector> ans(m, vector(n, -1)); + queue> q; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (isWater[i][j] == 1) { + q.emplace(i, j); + ans[i][j] = 0; + } + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (ans[x][y] != -1) + continue; + ans[x][y] = ans[i][j] + 1; + q.emplace(x, y); + } + } + + return ans; + } +}; diff --git a/solutions/1765. Map of Highest Peak/1765.java b/solutions/1765. Map of Highest Peak/1765.java new file mode 100644 index 00000000000..a6067e7785c --- /dev/null +++ b/solutions/1765. Map of Highest Peak/1765.java @@ -0,0 +1,34 @@ +class Solution { + public int[][] highestPeak(int[][] isWater) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = isWater.length; + final int n = isWater[0].length; + int[][] ans = new int[m][n]; + Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1)); + Queue> q = new ArrayDeque<>(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (isWater[i][j] == 1) { + q.offer(new Pair<>(i, j)); + ans[i][j] = 0; + } + + while (!q.isEmpty()) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (ans[x][y] != -1) + continue; + ans[x][y] = ans[i][j] + 1; + q.offer(new Pair<>(x, y)); + } + } + + return ans; + } +} diff --git a/solutions/1765. Map of Highest Peak/1765.py b/solutions/1765. Map of Highest Peak/1765.py new file mode 100644 index 00000000000..a51f85616a3 --- /dev/null +++ b/solutions/1765. Map of Highest Peak/1765.py @@ -0,0 +1,27 @@ +class Solution: + def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(isWater) + n = len(isWater[0]) + ans = [[-1] * n for _ in range(m)] + q = collections.deque() + + for i in range(m): + for j in range(n): + if isWater[i][j] == 1: + q.append((i, j)) + ans[i][j] = 0 + + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if ans[x][y] != -1: + continue + ans[x][y] = ans[i][j] + 1 + q.append((x, y)) + + return ans diff --git a/solutions/1766. Tree of Coprimes/1766.cpp b/solutions/1766. Tree of Coprimes/1766.cpp new file mode 100644 index 00000000000..ce558d3dcee --- /dev/null +++ b/solutions/1766. Tree of Coprimes/1766.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + vector getCoprimes(vector& nums, vector>& edges) { + vector ans(nums.size(), -1); + vector> tree(nums.size()); + // stacks[i] := (node, depth)s of nodes with value i + vector>> stacks(kMax + 1); + + for (const vector edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + dfs(tree, 0, /*prev=*/-1, /*depth=*/0, nums, stacks, ans); + return ans; + } + + private: + static constexpr int kMax = 50; + + void dfs(const vector>& tree, int u, int prev, int depth, + const vector& nums, vector>>& stacks, + vector& ans) { + ans[u] = getAncestor(u, stacks, nums); + stacks[nums[u]].push({u, depth}); + + for (const int v : tree[u]) + if (prev != v) + dfs(tree, v, u, depth + 1, nums, stacks, ans); + + stacks[nums[u]].pop(); + } + + int getAncestor(int u, const vector>>& stacks, + const vector& nums) { + int maxNode = -1; + int maxDepth = -1; + for (int i = 1; i <= kMax; ++i) + if (!stacks[i].empty() && stacks[i].top().second > maxDepth && + __gcd(nums[u], i) == 1) { + maxNode = stacks[i].top().first; + maxDepth = stacks[i].top().second; + } + return maxNode; + } +}; diff --git a/solutions/1766. Tree of Coprimes/1766.java b/solutions/1766. Tree of Coprimes/1766.java new file mode 100644 index 00000000000..7207e630815 --- /dev/null +++ b/solutions/1766. Tree of Coprimes/1766.java @@ -0,0 +1,54 @@ +class Solution { + public int[] getCoprimes(int[] nums, int[][] edges) { + int[] ans = new int[nums.length]; + Arrays.fill(ans, -1); + List[] tree = new List[nums.length]; + // stacks[i] := (node, depth)s of nodes with value i + Deque>[] stacks = new Deque[kMax + 1]; + + for (int i = 0; i < nums.length; ++i) + tree[i] = new ArrayList<>(); + + for (int i = 1; i <= kMax; ++i) + stacks[i] = new ArrayDeque<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + dfs(tree, 0, /*prev=*/-1, /*depth=*/0, nums, stacks, ans); + return ans; + } + + private static final int kMax = 50; + + private void dfs(List[] tree, int u, int prev, int depth, int[] nums, + Deque>[] stacks, int[] ans) { + ans[u] = getAncestor(u, stacks, nums); + stacks[nums[u]].push(new Pair<>(u, depth)); + + for (final int v : tree[u]) + if (prev != v) + dfs(tree, v, u, depth + 1, nums, stacks, ans); + + stacks[nums[u]].pop(); + } + + private int getAncestor(int u, Deque>[] stacks, int[] nums) { + int maxNode = -1; + int maxDepth = -1; + for (int i = 1; i <= kMax; ++i) + if (!stacks[i].isEmpty() && stacks[i].peek().getValue() > maxDepth && gcd(nums[u], i) == 1) { + maxNode = stacks[i].peek().getKey(); + maxDepth = stacks[i].peek().getValue(); + } + return maxNode; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/1766. Tree of Coprimes/1766.py b/solutions/1766. Tree of Coprimes/1766.py new file mode 100644 index 00000000000..0936f4eb352 --- /dev/null +++ b/solutions/1766. Tree of Coprimes/1766.py @@ -0,0 +1,32 @@ +class Solution: + def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: + kMax = 50 + ans = [-1] * len(nums) + tree = [[] for _ in range(len(nums))] + # stacks[i] := (node, depth)s of nodes with value i + stacks = [[] for _ in range(kMax + 1)] + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def getAncestor(u: int) -> int: + maxNode = -1 + maxDepth = -1 + for i, stack in enumerate(stacks): + if stack and stack[-1][1] > maxDepth and math.gcd(nums[u], i) == 1: + maxNode, maxDepth = stack[-1] + return maxNode + + def dfs(u: int, prev: int, depth: int) -> int: + ans[u] = getAncestor(u) + stacks[nums[u]].append((u, depth)) + + for v in tree[u]: + if prev != v: + dfs(v, u, depth + 1) + + stacks[nums[u]].pop() + + dfs(0, -1, 0) + return ans diff --git a/solutions/1767. Find the Subtasks That Did Not Execute/1767.sql b/solutions/1767. Find the Subtasks That Did Not Execute/1767.sql new file mode 100644 index 00000000000..e0b86e4ca5a --- /dev/null +++ b/solutions/1767. Find the Subtasks That Did Not Execute/1767.sql @@ -0,0 +1,10 @@ +WITH + RECURSIVE TaskToSubtask AS ( + SELECT task_id, subtasks_count AS subtask_id FROM Tasks + UNION ALL + SELECT task_id, subtask_id - 1 FROM TaskToSubtask + WHERE subtask_id > 1 + ) +SELECT * FROM TaskToSubtask +EXCEPT +SELECT * FROM Executed; diff --git a/solutions/1768. Merge Strings Alternately/1768.cpp b/solutions/1768. Merge Strings Alternately/1768.cpp new file mode 100644 index 00000000000..6fae3a200c9 --- /dev/null +++ b/solutions/1768. Merge Strings Alternately/1768.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string mergeAlternately(string word1, string word2) { + const int n = min(word1.length(), word2.length()); + string prefix; + + for (int i = 0; i < n; ++i) { + prefix += word1[i]; + prefix += word2[i]; + } + + return prefix + word1.substr(n) + word2.substr(n); + } +}; diff --git a/solutions/1768. Merge Strings Alternately/1768.java b/solutions/1768. Merge Strings Alternately/1768.java new file mode 100644 index 00000000000..b35436b0345 --- /dev/null +++ b/solutions/1768. Merge Strings Alternately/1768.java @@ -0,0 +1,13 @@ +class Solution { + public String mergeAlternately(String word1, String word2) { + final int n = Math.min(word1.length(), word2.length()); + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < n; ++i) { + sb.append(word1.charAt(i)); + sb.append(word2.charAt(i)); + } + + return sb.append(word1.substring(n)).append(word2.substring(n)).toString(); + } +} diff --git a/solutions/1768. Merge Strings Alternately/1768.py b/solutions/1768. Merge Strings Alternately/1768.py new file mode 100644 index 00000000000..d17f3c1b393 --- /dev/null +++ b/solutions/1768. Merge Strings Alternately/1768.py @@ -0,0 +1,3 @@ +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue='')) diff --git a/solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.cpp b/solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.cpp new file mode 100644 index 00000000000..dca418373f6 --- /dev/null +++ b/solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector minOperations(string boxes) { + vector ans(boxes.length()); + + for (int i = 0, count = 0, moves = 0; i < boxes.length(); ++i) { + ans[i] += moves; + count += boxes[i] - '0'; + moves += count; + } + + for (int i = boxes.length() - 1, count = 0, moves = 0; i >= 0; --i) { + ans[i] += moves; + count += boxes[i] - '0'; + moves += count; + } + + return ans; + } +}; diff --git a/solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.java b/solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.java new file mode 100644 index 00000000000..6aa70acf67b --- /dev/null +++ b/solutions/1769. Minimum Number of Operations to Move All Balls to Each Box/1769.java @@ -0,0 +1,19 @@ +class Solution { + public int[] minOperations(String boxes) { + int[] ans = new int[boxes.length()]; + + for (int i = 0, count = 0, moves = 0; i < boxes.length(); ++i) { + ans[i] += moves; + count += boxes.charAt(i) == '1' ? 1 : 0; + moves += count; + } + + for (int i = boxes.length() - 1, count = 0, moves = 0; i >= 0; --i) { + ans[i] += moves; + count += boxes.charAt(i) == '1' ? 1 : 0; + moves += count; + } + + return ans; + } +} diff --git a/solutions/177. Nth Highest Salary/177.sql b/solutions/177. Nth Highest Salary/177.sql new file mode 100644 index 00000000000..281a254c03f --- /dev/null +++ b/solutions/177. Nth Highest Salary/177.sql @@ -0,0 +1,13 @@ +CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT +BEGIN + RETURN ( + WITH + RankedEmployees AS ( + SELECT *, DENSE_RANK() OVER(ORDER BY salary DESC) AS `rank` + FROM Employee + ) + SELECT MAX(salary) AS SecondHighestSalary + FROM RankedEmployees + WHERE `rank` = N + ); +END diff --git a/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.cpp b/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.cpp new file mode 100644 index 00000000000..da6a302fa17 --- /dev/null +++ b/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maximumScore(vector& nums, vector& multipliers) { + vector> mem(multipliers.size(), + vector(multipliers.size(), -1)); + return maximumScore(nums, 0, multipliers, 0, mem); + } + + private: + // Returns the maximum score of nums[s..e] and multipliers[i]. + int maximumScore(const vector& nums, int s, + const vector& multipliers, int i, + vector>& mem) { + if (i == multipliers.size()) + return 0; + if (mem[s][i] != -1) + return mem[s][i]; + + // The number of nums picked on the start side is s. + // The number of nums picked on the end side is i - s. + // So, e = n - (i - s) - 1. + const int e = nums.size() - (i - s) - 1; + const int pickStart = nums[s] * multipliers[i] + + maximumScore(nums, s + 1, multipliers, i + 1, mem); + const int pickEnd = nums[e] * multipliers[i] + + maximumScore(nums, s, multipliers, i + 1, mem); + return mem[s][i] = max(pickStart, pickEnd); + } +}; diff --git a/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.java b/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.java new file mode 100644 index 00000000000..4c2fca2b157 --- /dev/null +++ b/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.java @@ -0,0 +1,23 @@ +class Solution { + public int maximumScore(int[] nums, int[] multipliers) { + Integer[][] mem = new Integer[multipliers.length][multipliers.length]; + return maximumScore(nums, 0, multipliers, 0, mem); + } + + private int maximumScore(int[] nums, int s, int[] multipliers, int i, Integer[][] mem) { + if (i == multipliers.length) + return 0; + if (mem[s][i] != null) + return mem[s][i]; + + // The number of nums picked on the start side is s. + // The number of nums picked on the end side is i - s. + // So, e = n - (i - s) - 1. + final int e = nums.length - (i - s) - 1; + final int pickStart = nums[s] * multipliers[i] + // + maximumScore(nums, s + 1, multipliers, i + 1, mem); + final int pickEnd = nums[e] * multipliers[i] + // + maximumScore(nums, s, multipliers, i + 1, mem); + return mem[s][i] = Math.max(pickStart, pickEnd); + } +} diff --git a/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.py b/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.py new file mode 100644 index 00000000000..a4f00a4c250 --- /dev/null +++ b/solutions/1770. Maximum Score from Performing Multiplication Operations/1770.py @@ -0,0 +1,17 @@ +class Solution: + def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: + @functools.lru_cache(2000) + def dp(s: int, i: int) -> int: + """Returns the maximum score of nums[s..e] and multipliers[i].""" + if i == len(multipliers): + return 0 + + # The number of nums picked on the start side is s. + # The number of nums picked on the end side is i - s. + # So, e = n - (i - s) - 1. + e = len(nums) - (i - s) - 1 + pickStart = nums[s] * multipliers[i] + dp(s + 1, i + 1) + pickEnd = nums[e] * multipliers[i] + dp(s, i + 1) + return max(pickStart, pickEnd) + + return dp(0, 0) diff --git a/solutions/1771. Maximize Palindrome Length From Subsequences/1771.cpp b/solutions/1771. Maximize Palindrome Length From Subsequences/1771.cpp new file mode 100644 index 00000000000..7e7fa849d5a --- /dev/null +++ b/solutions/1771. Maximize Palindrome Length From Subsequences/1771.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int longestPalindrome(string word1, string word2) { + const string& s = word1 + word2; + const int n = s.length(); + int ans = 0; + // dp[i][j] := the length of LPS(s[i..j]) + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + if (s[i] == s[j]) { + dp[i][j] = 2 + dp[i + 1][j - 1]; + if (i < word1.length() && j >= word1.length()) + ans = max(ans, dp[i][j]); + } else { + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); + } + } + + return ans; + } +}; diff --git a/solutions/1771. Maximize Palindrome Length From Subsequences/1771.java b/solutions/1771. Maximize Palindrome Length From Subsequences/1771.java new file mode 100644 index 00000000000..efd1da8fd78 --- /dev/null +++ b/solutions/1771. Maximize Palindrome Length From Subsequences/1771.java @@ -0,0 +1,26 @@ +class Solution { + public int longestPalindrome(String word1, String word2) { + final String s = word1 + word2; + final int n = s.length(); + int ans = 0; + // dp[i][j] := the length of LPS(s[i..j]) + int[][] dp = new int[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + if (s.charAt(i) == s.charAt(j)) { + dp[i][j] = 2 + dp[i + 1][j - 1]; + if (i < word1.length() && j >= word1.length()) + ans = Math.max(ans, dp[i][j]); + } else { + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + } + + return ans; + } +} diff --git a/solutions/1772. Sort Features by Popularity/1772.cpp b/solutions/1772. Sort Features by Popularity/1772.cpp new file mode 100644 index 00000000000..ecece4fca5e --- /dev/null +++ b/solutions/1772. Sort Features by Popularity/1772.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector sortFeatures(vector& features, + vector& responses) { + vector ans; + vector> featCount; // {i: count[features[i]]} + unordered_map count; + + for (const string& res : responses) { + istringstream iss(res); + unordered_set seen; + for (string token; getline(iss, token, ' ');) + seen.insert(token); + for (const string& token : seen) + ++count[token]; + } + + for (int i = 0; i < features.size(); ++i) + featCount.emplace_back(i, count[features[i]]); + + ranges::sort(featCount, + [](const pair& a, const pair& b) { + return a.second == b.second ? a.first < b.first : a.second > b.second; + }); + + for (const auto& [i, count] : featCount) + ans.push_back(features[i]); + + return ans; + } +}; diff --git a/solutions/1772. Sort Features by Popularity/1772.java b/solutions/1772. Sort Features by Popularity/1772.java new file mode 100644 index 00000000000..9be3a1e988d --- /dev/null +++ b/solutions/1772. Sort Features by Popularity/1772.java @@ -0,0 +1,21 @@ +class Solution { + public String[] sortFeatures(String[] features, String[] responses) { + String[] ans = new String[features.length]; + int[][] featCount = new int[features.length][]; // {i: count[features[i]]} + Map count = new HashMap<>(); + + for (final String res : responses) + for (final String token : new HashSet<>(Arrays.asList(res.split(" ")))) + count.merge(token, 1, Integer::sum); + + for (int i = 0; i < features.length; ++i) + featCount[i] = new int[] {i, count.getOrDefault(features[i], 0)}; + + Arrays.sort(featCount, (a, b) -> a[1] == b[1] ? a[0] - b[0] : b[1] - a[1]); + + for (int i = 0; i < features.length; ++i) + ans[i] = features[featCount[i][0]]; + + return ans; + } +} diff --git a/solutions/1773. Count Items Matching a Rule/1773.cpp b/solutions/1773. Count Items Matching a Rule/1773.cpp new file mode 100644 index 00000000000..e793556a046 --- /dev/null +++ b/solutions/1773. Count Items Matching a Rule/1773.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int countMatches(vector>& items, string ruleKey, + string ruleValue) { + const int index = ruleKey == "type" ? 0 : ruleKey == "color" ? 1 : 2; + return ranges::count_if(items, [index, &ruleValue](const auto& item) { + return item[index] == ruleValue; + }); + } +}; diff --git a/solutions/1773. Count Items Matching a Rule/1773.java b/solutions/1773. Count Items Matching a Rule/1773.java new file mode 100644 index 00000000000..727a11e58a3 --- /dev/null +++ b/solutions/1773. Count Items Matching a Rule/1773.java @@ -0,0 +1,16 @@ +class Solution { + public int countMatches(List> items, String ruleKey, String ruleValue) { + if (ruleKey.equals("type")) + return count(items, 0, ruleValue); + if (ruleKey.equals("color")) + return count(items, 1, ruleValue); + return count(items, 2, ruleValue); + } + + private int count(List> items, int index, final String ruleValue) { + return (int) items.stream() + .map(item -> item.get(index)) + .filter(s -> s.equals(ruleValue)) + .count(); + } +} diff --git a/solutions/1774. Closest Dessert Cost/1774.cpp b/solutions/1774. Closest Dessert Cost/1774.cpp new file mode 100644 index 00000000000..864a2d6883b --- /dev/null +++ b/solutions/1774. Closest Dessert Cost/1774.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int closestCost(vector& baseCosts, vector& toppingCosts, + int target) { + int ans = INT_MAX; + + for (const int baseCost : baseCosts) + dfs(toppingCosts, 0, target, baseCost, ans); + + return ans; + } + + private: + void dfs(const vector& toppingCosts, int i, int target, int currCost, + int& ans) { + if (abs(currCost - target) < abs(ans - target)) + ans = currCost; + if (i == toppingCosts.size() || currCost >= target) + return; + + for (int k = 0; k < 3; ++k) + dfs(toppingCosts, i + 1, target, currCost + k * toppingCosts[i], ans); + } +}; diff --git a/solutions/1774. Closest Dessert Cost/1774.java b/solutions/1774. Closest Dessert Cost/1774.java new file mode 100644 index 00000000000..fbfd555e03f --- /dev/null +++ b/solutions/1774. Closest Dessert Cost/1774.java @@ -0,0 +1,19 @@ +class Solution { + public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { + for (final int baseCost : baseCosts) + dfs(toppingCosts, 0, target, baseCost); + return ans; + } + + private int ans = Integer.MAX_VALUE; + + private void dfs(int[] toppingCosts, int i, int target, int currCost) { + if (Math.abs(currCost - target) < Math.abs(ans - target)) + ans = currCost; + if (i == toppingCosts.length || currCost >= target) + return; + + for (int k = 0; k < 3; ++k) + dfs(toppingCosts, i + 1, target, currCost + k * toppingCosts[i]); + } +} diff --git a/solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.cpp b/solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.cpp new file mode 100644 index 00000000000..2bbb71b3229 --- /dev/null +++ b/solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minOperations(vector& nums1, vector& nums2) { + if (nums1.size() * 6 < nums2.size() || nums2.size() * 6 < nums1.size()) + return -1; + + int sum1 = accumulate(nums1.begin(), nums1.end(), 0); + int sum2 = accumulate(nums2.begin(), nums2.end(), 0); + if (sum1 > sum2) + return minOperations(nums2, nums1); + + int ans = 0; + // increasing in `nums1` and decreasing in `nums2` + vector count(6); + + for (const int num : nums1) + ++count[6 - num]; + + for (const int num : nums2) + ++count[num - 1]; + + for (int i = 5; sum2 > sum1;) { + while (count[i] == 0) + --i; + sum1 += i; + --count[i]; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.java b/solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.java new file mode 100644 index 00000000000..1a9921dbdee --- /dev/null +++ b/solutions/1775. Equal Sum Arrays With Minimum Number of Operations/1775.java @@ -0,0 +1,28 @@ +class Solution { + public int minOperations(int[] nums1, int[] nums2) { + if (nums1.length * 6 < nums2.length || nums2.length * 6 < nums1.length) + return -1; + + int sum1 = Arrays.stream(nums1).sum(); + int sum2 = Arrays.stream(nums2).sum(); + if (sum1 > sum2) + return minOperations(nums2, nums1); + + int ans = 0; + // increasing in `nums1` and decreasing in `nums2` + int[] count = new int[6]; + + Arrays.stream(nums1).forEach(num -> ++count[6 - num]); + Arrays.stream(nums2).forEach(num -> ++count[num - 1]); + + for (int i = 5; sum2 > sum1;) { + while (count[i] == 0) + --i; + sum1 += i; + --count[i]; + ++ans; + } + + return ans; + } +} diff --git a/solutions/1776. Car Fleet II/1776.cpp b/solutions/1776. Car Fleet II/1776.cpp new file mode 100644 index 00000000000..1fa0a571c83 --- /dev/null +++ b/solutions/1776. Car Fleet II/1776.cpp @@ -0,0 +1,39 @@ +struct Car { + int pos; + int speed; + double collisionTime; + Car(int pos, int speed, double collisionTime) + : pos(pos), speed(speed), collisionTime(collisionTime) {} +}; + +class Solution { + public: + vector getCollisionTimes(vector>& cars) { + vector ans(cars.size()); + stack stack; + + for (int i = cars.size() - 1; i >= 0; --i) { + const int pos = cars[i][0]; + const int speed = cars[i][1]; + while (!stack.empty() && (speed <= stack.top().speed || + getCollisionTime(stack.top(), pos, speed) >= + stack.top().collisionTime)) + stack.pop(); + if (stack.empty()) { + stack.emplace(pos, speed, INT_MAX); + ans[i] = -1; + } else { + const double collisionTime = getCollisionTime(stack.top(), pos, speed); + stack.emplace(pos, speed, collisionTime); + ans[i] = collisionTime; + } + } + + return ans; + } + + private: + double getCollisionTime(const Car& car, int pos, int speed) { + return (car.pos - pos) / (double)(speed - car.speed); + } +}; diff --git a/solutions/1776. Car Fleet II/1776.java b/solutions/1776. Car Fleet II/1776.java new file mode 100644 index 00000000000..79e02cea4c5 --- /dev/null +++ b/solutions/1776. Car Fleet II/1776.java @@ -0,0 +1,40 @@ +class Car { + public int pos; + public int speed; + public double collisionTime; + public Car(int pos, int speed, double collisionTime) { + this.pos = pos; + this.speed = speed; + this.collisionTime = collisionTime; + } +} + +class Solution { + public double[] getCollisionTimes(int[][] cars) { + double[] ans = new double[cars.length]; + Deque stack = new ArrayDeque<>(); + + for (int i = cars.length - 1; i >= 0; --i) { + final int pos = cars[i][0]; + final int speed = cars[i][1]; + while (!stack.isEmpty() && + (speed <= stack.peek().speed || + getCollisionTime(stack.peek(), pos, speed) >= stack.peek().collisionTime)) + stack.pop(); + if (stack.isEmpty()) { + stack.push(new Car(pos, speed, Integer.MAX_VALUE)); + ans[i] = -1; + } else { + final double collisionTime = getCollisionTime(stack.peek(), pos, speed); + stack.push(new Car(pos, speed, collisionTime)); + ans[i] = collisionTime; + } + } + + return ans; + } + + private double getCollisionTime(Car car, int pos, int speed) { + return (double) (car.pos - pos) / (speed - car.speed); + } +} diff --git a/solutions/1776. Car Fleet II/1776.py b/solutions/1776. Car Fleet II/1776.py new file mode 100644 index 00000000000..468a224d5dc --- /dev/null +++ b/solutions/1776. Car Fleet II/1776.py @@ -0,0 +1,25 @@ +class Solution: + def getCollisionTimes(self, cars: List[List[int]]) -> List[float]: + ans = [] + stack = [] # (pos, speed, collisionTime) + + def getCollisionTime( + car: Tuple[int, int, int], + pos: int, speed: int) -> float: + return (car[0] - pos) / (speed - car[1]) + + for pos, speed in reversed(cars): + while stack and ( + speed <= stack[-1][1] or getCollisionTime(stack[-1], + pos, speed) >= + stack[-1][2]): + stack.pop() + if stack: + collisionTime = getCollisionTime(stack[-1], pos, speed) + stack.append((pos, speed, collisionTime)) + ans.append(collisionTime) + else: + stack.append((pos, speed, math.inf)) + ans.append(-1) + + return ans[::-1] diff --git a/solutions/1777. Product's Price for Each Store/1777.sql b/solutions/1777. Product's Price for Each Store/1777.sql new file mode 100644 index 00000000000..73fcd827da9 --- /dev/null +++ b/solutions/1777. Product's Price for Each Store/1777.sql @@ -0,0 +1,7 @@ +SELECT + product_id, + MAX(CASE WHEN store = 'store1' THEN price END) AS store1, + MAX(CASE WHEN store = 'store2' THEN price END) AS store2, + MAX(CASE WHEN store = 'store3' THEN price END) AS store3 +FROM Products +GROUP BY 1; diff --git a/solutions/1778. Shortest Path in a Hidden Grid/1778.cpp b/solutions/1778. Shortest Path in a Hidden Grid/1778.cpp new file mode 100644 index 00000000000..d338d5ae036 --- /dev/null +++ b/solutions/1778. Shortest Path in a Hidden Grid/1778.cpp @@ -0,0 +1,77 @@ +/** + * // This is the GridMaster's API interface. + * // You should not implement it, or speculate about its implementation + * class GridMaster { + * public: + * bool canMove(char direction); + * void move(char direction); + * boolean isTarget(); + * }; + */ + +enum class Grid { kUnvisited, kStart, kTarget, kBlocked, kEmpty }; + +class Solution { + public: + int findShortestPath(GridMaster& master) { + constexpr int m = 500; + constexpr int startX = m; + constexpr int startY = m; + vector> grid(m * 2, vector(m * 2, Grid::kUnvisited)); + + // Build the grid information by DFS. + dfs(master, grid, startX, startY); + + int ans = 0; + queue> q{{{startX, startY}}}; + grid[startX][startY] = Grid::kBlocked; + + // Find the steps by BFS. + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (grid[x][y] == Grid::kTarget) + return ans; + if (grid[x][y] == Grid::kBlocked) + continue; + grid[x][y] = Grid::kBlocked; + q.emplace(x, y); + } + } + } + + return -1; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + static constexpr char charTable[4] = {'R', 'D', 'L', 'U'}; + + void dfs(GridMaster& master, vector>& grid, int i, int j) { + if (grid[i][j] != Grid::kUnvisited) + return; + if (master.isTarget()) + grid[i][j] = Grid::kTarget; + else + grid[i][j] = Grid::kEmpty; + + for (int k = 0; k < 4; ++k) { + const int x = i + dirs[k][0]; + const int y = j + dirs[k][1]; + const char d = charTable[k]; + const char undoD = charTable[(k + 2) % 4]; + if (master.canMove(d)) { + master.move(d); + dfs(master, grid, x, y); + master.move(undoD); + } else { + grid[x][y] = Grid::kBlocked; + } + } + } +}; diff --git a/solutions/1778. Shortest Path in a Hidden Grid/1778.java b/solutions/1778. Shortest Path in a Hidden Grid/1778.java new file mode 100644 index 00000000000..fdda656b0e5 --- /dev/null +++ b/solutions/1778. Shortest Path in a Hidden Grid/1778.java @@ -0,0 +1,76 @@ +/** + * // This is the GridMaster's API interface. + * // You should not implement it, or speculate about its implementation + * class GridMaster { + * boolean canMove(char direction); + * void move(char direction); + * boolean isTarget(); + * }; + */ + +enum Grid { kUnvisited, kStart, kTarget, kBlocked, kEmpty } + +class Solution { + public int findShortestPath(GridMaster master) { + final int m = 500; + final int startX = m; + final int startY = m; + Grid[][] grid = new Grid[m * 2][m * 2]; + Arrays.stream(grid).forEach(A -> Arrays.fill(A, Grid.kUnvisited)); + + // Build the grid information by DFS. + dfs(master, grid, startX, startY); + + int ans = 0; + Queue q = new ArrayDeque<>(); + q.offer(new int[] {startX, startY}); + grid[startX][startY] = Grid.kBlocked; + + // Find the steps by BFS. + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (grid[x][y] == Grid.kTarget) + return ans; + if (grid[x][y] == Grid.kBlocked) + continue; + grid[x][y] = Grid.kBlocked; + q.offer(new int[] {x, y}); + } + } + } + + return -1; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + private static final char[] charTable = {'R', 'D', 'L', 'U'}; + + private void dfs(GridMaster master, Grid[][] grid, int i, int j) { + if (grid[i][j] != Grid.kUnvisited) + return; + if (master.isTarget()) + grid[i][j] = Grid.kTarget; + else + grid[i][j] = Grid.kEmpty; + + for (int k = 0; k < 4; ++k) { + final int x = i + dirs[k]; + final int y = j + dirs[k + 1]; + final char d = charTable[k]; + final char undoD = charTable[(k + 2) % 4]; + if (master.canMove(d)) { + master.move(d); + dfs(master, grid, x, y); + master.move(undoD); + } else { + grid[x][y] = Grid.kBlocked; + } + } + } +} diff --git a/solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.cpp b/solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.cpp new file mode 100644 index 00000000000..b81344c68b4 --- /dev/null +++ b/solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int nearestValidPoint(int x, int y, vector>& points) { + int ans = -1; + int minDist = INT_MAX; + + for (int i = 0; i < points.size(); ++i) { + const int dx = x - points[i][0]; + const int dy = y - points[i][1]; + if (dx == 0 || dy == 0) { + const int dist = abs(dx + dy); + if (dist < minDist) { + minDist = dist; + ans = i; + } + } + } + + return ans; + } +}; diff --git a/solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.java b/solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.java new file mode 100644 index 00000000000..73d5a3f61c5 --- /dev/null +++ b/solutions/1779. Find Nearest Point That Has the Same X or Y Coordinate/1779.java @@ -0,0 +1,20 @@ +class Solution { + public int nearestValidPoint(int x, int y, int[][] points) { + int ans = -1; + int minDist = Integer.MAX_VALUE; + + for (int i = 0; i < points.length; ++i) { + final int dx = x - points[i][0]; + final int dy = y - points[i][1]; + if (dx == 0 || dy == 0) { + final int dist = Math.abs(dx + dy); + if (dist < minDist) { + minDist = dist; + ans = i; + } + } + } + + return ans; + } +} diff --git a/solutions/178. Rank Scores/178.sql b/solutions/178. Rank Scores/178.sql new file mode 100644 index 00000000000..3edfbe968bd --- /dev/null +++ b/solutions/178. Rank Scores/178.sql @@ -0,0 +1,4 @@ +SELECT + score, + DENSE_RANK() OVER(ORDER BY score DESC) AS `rank` +FROM Scores; diff --git a/solutions/1780. Check if Number is a Sum of Powers of Three/1780.cpp b/solutions/1780. Check if Number is a Sum of Powers of Three/1780.cpp new file mode 100644 index 00000000000..f121d3941b1 --- /dev/null +++ b/solutions/1780. Check if Number is a Sum of Powers of Three/1780.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool checkPowersOfThree(int n) { + while (n > 1) { + const int r = n % 3; + if (r == 2) + return false; + n /= 3; + } + + return true; + } +}; diff --git a/solutions/1780. Check if Number is a Sum of Powers of Three/1780.java b/solutions/1780. Check if Number is a Sum of Powers of Three/1780.java new file mode 100644 index 00000000000..cbd137c657f --- /dev/null +++ b/solutions/1780. Check if Number is a Sum of Powers of Three/1780.java @@ -0,0 +1,12 @@ +class Solution { + public boolean checkPowersOfThree(int n) { + while (n > 1) { + const int r = n % 3; + if (r == 2) + return false; + n /= 3; + } + + return true; + } +} diff --git a/solutions/1780. Check if Number is a Sum of Powers of Three/1780.py b/solutions/1780. Check if Number is a Sum of Powers of Three/1780.py new file mode 100644 index 00000000000..6b78b95020f --- /dev/null +++ b/solutions/1780. Check if Number is a Sum of Powers of Three/1780.py @@ -0,0 +1,7 @@ +class Solution: + def checkPowersOfThree(self, n: int) -> bool: + while n > 1: + n, r = divmod(n, 3) + if r == 2: + return False + return True diff --git a/solutions/1781. Sum of Beauty of All Substrings/1781.cpp b/solutions/1781. Sum of Beauty of All Substrings/1781.cpp new file mode 100644 index 00000000000..e8ca24b96b0 --- /dev/null +++ b/solutions/1781. Sum of Beauty of All Substrings/1781.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int beautySum(string s) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) { + vector count(26); + for (int j = i; j < s.length(); ++j) { + ++count[s[j] - 'a']; + ans += ranges::max(count) - getMinFreq(count); + } + } + + return ans; + } + + private: + // Returns the minimum frequency > 0. + int getMinFreq(const vector& count) { + int minFreq = INT_MAX; + for (const int freq : count) + if (freq > 0) + minFreq = min(minFreq, freq); + return minFreq; + } +}; diff --git a/solutions/1781. Sum of Beauty of All Substrings/1781.java b/solutions/1781. Sum of Beauty of All Substrings/1781.java new file mode 100644 index 00000000000..7c65cb51b19 --- /dev/null +++ b/solutions/1781. Sum of Beauty of All Substrings/1781.java @@ -0,0 +1,24 @@ +class Solution { + public int beautySum(String s) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) { + int[] count = new int[26]; + for (int j = i; j < s.length(); ++j) { + ++count[s.charAt(j) - 'a']; + ans += Arrays.stream(count).max().getAsInt() - getMinFreq(count); + } + } + + return ans; + } + + // Returns the minimum frequency > 0. + private int getMin(int[] count) { + int minFreq = Integer.MAX_VALUE; + for (final int freq : count) + if (freq > 0) + minFreq = min(minFreq, freq); + return minFreq; + } +} diff --git a/solutions/1781. Sum of Beauty of All Substrings/1781.py b/solutions/1781. Sum of Beauty of All Substrings/1781.py new file mode 100644 index 00000000000..fb54c3815ed --- /dev/null +++ b/solutions/1781. Sum of Beauty of All Substrings/1781.py @@ -0,0 +1,11 @@ +class Solution: + def beautySum(self, s: str) -> int: + ans = 0 + + for i in range(len(s)): + count = collections.Counter() + for j in range(i, len(s)): + count[s[j]] += 1 + ans += max(count.values()) - min(count.values()) + + return ans diff --git a/solutions/1782. Count Pairs Of Nodes/1782.cpp b/solutions/1782. Count Pairs Of Nodes/1782.cpp new file mode 100644 index 00000000000..6c93e50ff44 --- /dev/null +++ b/solutions/1782. Count Pairs Of Nodes/1782.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + vector countPairs(int n, vector>& edges, + vector& queries) { + vector ans(queries.size()); + + // count[i] := the number of edges of node i + vector count(n + 1); + + // shared[i][j] := the number of edges incident to i or j, where i < j + vector> shared(n + 1); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + ++count[u]; + ++count[v]; + ++shared[min(u, v)][max(u, v)]; + } + + vector sortedCount(count); + ranges::sort(sortedCount); + + int k = 0; + for (const int query : queries) { + for (int i = 1, j = n; i < j;) + if (sortedCount[i] + sortedCount[j] > query) + // sortedCount[i] + sortedCount[j] > query + // sortedCount[i + 1] + sortedCount[j] > query + // ... + // sortedCount[j - 1] + sortedCount[j] > query + // So, there are (j - 1) - i + 1 = j - i pairs > query + ans[k] += (j--) - i; + else + ++i; + for (int i = 1; i <= n; ++i) + for (const auto& [j, sh] : shared[i]) + if (count[i] + count[j] > query && count[i] + count[j] - sh <= query) + --ans[k]; + ++k; + } + + return ans; + } +}; diff --git a/solutions/1782. Count Pairs Of Nodes/1782.java b/solutions/1782. Count Pairs Of Nodes/1782.java new file mode 100644 index 00000000000..222cccd1756 --- /dev/null +++ b/solutions/1782. Count Pairs Of Nodes/1782.java @@ -0,0 +1,49 @@ +class Solution { + public int[] countPairs(int n, int[][] edges, int[] queries) { + int[] ans = new int[queries.length]; + + // count[i] := the number of edges of node i + int[] count = new int[n + 1]; + + // shared[i][j] := the number of edges incident to i or j, where i < j + Map[] shared = new Map[n + 1]; + + for (int i = 1; i <= n; ++i) + shared[i] = new HashMap<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + ++count[u]; + ++count[v]; + shared[Math.min(u, v)].merge(Math.max(u, v), 1, Integer::sum); + } + + int[] sortedCount = count.clone(); + Arrays.sort(sortedCount); + + int k = 0; + for (final int query : queries) { + for (int i = 1, j = n; i < j;) + if (sortedCount[i] + sortedCount[j] > query) + // sortedCount[i] + sortedCount[j] > query + // sortedCount[i + 1] + sortedCount[j] > query + // ... + // sortedCount[j - 1] + sortedCount[j] > query + // So, there are (j - 1) - i + 1 = j - i pairs > query + ans[k] += (j--) - i; + else + ++i; + for (int i = 1; i <= n; ++i) + for (Map.Entry p : shared[i].entrySet()) { + final int j = p.getKey(); + final int sh = p.getValue(); + if (count[i] + count[j] > query && count[i] + count[j] - sh <= query) + --ans[k]; + } + ++k; + } + + return ans; + } +} diff --git a/solutions/1782. Count Pairs Of Nodes/1782.py b/solutions/1782. Count Pairs Of Nodes/1782.py new file mode 100644 index 00000000000..ec272808717 --- /dev/null +++ b/solutions/1782. Count Pairs Of Nodes/1782.py @@ -0,0 +1,37 @@ +class Solution: + def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]: + ans = [0] * len(queries) + + # count[i] := the number of edges of node i + count = [0] * (n + 1) + + # shared[i][j] := the number of edges incident to i or j, where i < j + shared = [collections.Counter() for _ in range(n + 1)] + + for u, v in edges: + count[u] += 1 + count[v] += 1 + shared[min(u, v)][max(u, v)] += 1 + + sortedCount = sorted(count) + + for k, query in enumerate(queries): + i = 1 + j = n + while i < j: + if sortedCount[i] + sortedCount[j] > query: + # sortedCount[i] + sortedCount[j] > query + # sortedCount[i + 1] + sortedCount[j] > query + # ... + # sortedCount[j - 1] + sortedCount[j] > query + # So, there are (j - 1) - i + 1 = j - i pairs > query + ans[k] += j - i + j -= 1 + else: + i += 1 + for i in range(1, n + 1): + for j, sh in shared[i].items(): + if count[i] + count[j] > query and count[i] + count[j] - sh <= query: + ans[k] -= 1 + + return ans diff --git a/solutions/1783. Grand Slam Titles/1783.sql b/solutions/1783. Grand Slam Titles/1783.sql new file mode 100644 index 00000000000..62d88b9a31b --- /dev/null +++ b/solutions/1783. Grand Slam Titles/1783.sql @@ -0,0 +1,15 @@ +SELECT + Players.player_id, + Players.player_name, + SUM(Players.player_id = Championships.Wimbledon) + SUM(Players.player_id = Championships.Fr_open) + SUM(Players.player_id = Championships.US_open) + SUM(Players.player_id = Championships.Au_open) AS grand_slams_count +FROM Players +INNER JOIN Championships + ON ( + Players.player_id IN ( + Championships.Wimbledon, + Championships.Fr_open, + Championships.US_open, + Championships.Au_open + ) + ) +GROUP BY 1; diff --git a/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.cpp b/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.cpp new file mode 100644 index 00000000000..8b24267aa86 --- /dev/null +++ b/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool checkOnesSegment(string s) { + return s.find("01") == string::npos; + } +}; diff --git a/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.java b/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.java new file mode 100644 index 00000000000..842575a877d --- /dev/null +++ b/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.java @@ -0,0 +1,5 @@ +class Solution { + public boolean checkOnesSegment(String s) { + return !s.contains("01"); + } +} diff --git a/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.py b/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.py new file mode 100644 index 00000000000..b09ffc2c379 --- /dev/null +++ b/solutions/1784. Check if Binary String Has at Most One Segment of Ones/1784.py @@ -0,0 +1,3 @@ +class Solution: + def checkOnesSegment(self, s: str) -> bool: + return '01' not in s diff --git a/solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.cpp b/solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.cpp new file mode 100644 index 00000000000..43138560df5 --- /dev/null +++ b/solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int minElements(vector& nums, int limit, int goal) { + const long sum = accumulate(nums.begin(), nums.end(), 0L); + const double diff = abs(goal - sum); + return ceil(diff / limit); + } +}; diff --git a/solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.java b/solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.java new file mode 100644 index 00000000000..e3b7585669d --- /dev/null +++ b/solutions/1785. Minimum Elements to Add to Form a Given Sum/1785.java @@ -0,0 +1,7 @@ +class Solution { + public int minElements(int[] nums, int limit, int goal) { + final long sum = Arrays.stream(nums).asLongStream().sum(); + final double diff = Math.abs(goal - sum); + return (int) Math.ceil(diff / limit); + } +} diff --git a/solutions/1786. Number of Restricted Paths From First to Last Node/1786.cpp b/solutions/1786. Number of Restricted Paths From First to Last Node/1786.cpp new file mode 100644 index 00000000000..4821c539fa5 --- /dev/null +++ b/solutions/1786. Number of Restricted Paths From First to Last Node/1786.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + int countRestrictedPaths(int n, vector>& edges) { + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0] - 1; + const int v = edge[1] - 1; + const int w = edge[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + return dijkstra(graph, 0, n - 1); + } + + private: + int dijkstra(const vector>>& graph, int src, int dst) { + constexpr int kMod = 1'000'000'007; + // ways[i] := the number of restricted path from i to n + vector ways(graph.size()); + // dist[i] := the distance to the last node of i + vector dist(graph.size(), LONG_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[dst] = 0; + ways[dst] = 1; + minHeap.emplace(dist[dst], dst); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) { + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + if (dist[v] < dist[u]) { + ways[u] += ways[v]; + ways[u] %= kMod; + } + } + } + + return ways[src]; + } +}; diff --git a/solutions/1786. Number of Restricted Paths From First to Last Node/1786.java b/solutions/1786. Number of Restricted Paths From First to Last Node/1786.java new file mode 100644 index 00000000000..cedcab385e7 --- /dev/null +++ b/solutions/1786. Number of Restricted Paths From First to Last Node/1786.java @@ -0,0 +1,54 @@ +class Solution { + public int countRestrictedPaths(int n, int[][] edges) { + List>[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0] - 1; + final int v = edge[1] - 1; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + return dijkstra(graph, 0, n - 1); + } + + private int dijkstra(List>[] graph, int src, int dst) { + final int kMod = 1_000_000_007; + // ways[i] := the number of restricted path from i to n + long[] ways = new long[graph.length]; + // dist[i] := the distance to the last node of i + long[] dist = new long[graph.length]; + Arrays.fill(dist, Long.MAX_VALUE); + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + ways[dst] = 1; + dist[dst] = 0; + minHeap.offer(new Pair<>(dist[dst], dst)); + + while (!minHeap.isEmpty()) { + final long d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + if (dist[v] < dist[u]) { + ways[u] += ways[v]; + ways[u] %= kMod; + } + } + } + + return (int) ways[src]; + } +} diff --git a/solutions/1786. Number of Restricted Paths From First to Last Node/1786.py b/solutions/1786. Number of Restricted Paths From First to Last Node/1786.py new file mode 100644 index 00000000000..e5d7edec630 --- /dev/null +++ b/solutions/1786. Number of Restricted Paths From First to Last Node/1786.py @@ -0,0 +1,34 @@ +class Solution: + def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: + graph = [[] for _ in range(n)] + + for u, v, w in edges: + graph[u - 1].append((v - 1, w)) + graph[v - 1].append((u - 1, w)) + + return self._dijkstra(graph, 0, n - 1) + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int) -> int: + kMod = 10**9 + 7 + # ways[i] := the number of restricted path from i to n + ways = [0] * len(graph) + # dist[i] := the distance to the last node of i + dist = [math.inf] * len(graph) + + ways[dst] = 1 + dist[dst] = 0 + minHeap = [(dist[dst], dst)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + if dist[v] < dist[u]: + ways[u] += ways[v] + ways[u] %= kMod + + return ways[src] diff --git a/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.cpp b/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.cpp new file mode 100644 index 00000000000..263f1ead90b --- /dev/null +++ b/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int minChanges(vector& nums, int k) { + constexpr int kMax = 1024; + const int n = nums.size(); + // counts[i] := the counter that maps at the i-th position + vector> counts(k); + // dp[i][j] := the minimum number of elements to change s.t. XOR(nums[i..k - + // 1]) is j + vector> dp(k, vector(kMax, n)); + + for (int i = 0; i < n; ++i) + ++counts[i % k][nums[i]]; + + auto countAt = [n, k](int i) -> int { return n / k + (n % k > i ? 1 : 0); }; + + // Initialize the DP array. + for (int j = 0; j < kMax; ++j) + dp[k - 1][j] = + countAt(k - 1) - (counts[k - 1].contains(j) ? counts[k - 1][j] : 0); + + for (int i = k - 2; i >= 0; --i) { + // The worst-case scenario is changing all the i-th position numbers to a + // non-existent value in the current bucket. + const int changeAll = countAt(i) + ranges::min(dp[i + 1]); + for (int j = 0; j < kMax; ++j) { + dp[i][j] = changeAll; + for (const auto& [num, freq] : counts[i]) { + // the cost to change every number in the i-th position to `num` + const int cost = countAt(i) - freq; + dp[i][j] = min(dp[i][j], dp[i + 1][j ^ num] + cost); + } + } + } + + return dp[0][0]; + } +}; diff --git a/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.java b/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.java new file mode 100644 index 00000000000..ab62e26fad9 --- /dev/null +++ b/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.java @@ -0,0 +1,44 @@ +class Solution { + public int minChanges(int[] nums, int k) { + final int kMax = 1024; + final int n = nums.length; + // counts[i] := the counter that maps at the i-th position + Map[] counts = new Map[k]; + // dp[i][j] := the minimum number of elements to change s.t. XOR(nums[i..k - 1]) is j + int[][] dp = new int[k][kMax]; + + for (int i = 0; i < k; ++i) + counts[i] = new HashMap<>(); + + for (int i = 0; i < n; ++i) + counts[i % k].merge(nums[i], 1, Integer::sum); + + Arrays.stream(dp).forEach(A -> Arrays.fill(A, n)); + + // Initialize the DP array. + for (int j = 0; j < kMax; ++j) + dp[k - 1][j] = countAt(n, k, k - 1) - counts[k - 1].getOrDefault(j, 0); + + for (int i = k - 2; i >= 0; --i) { + // The worst-case scenario is changing all the i-th position numbers to a + // non-existent value in the current bucket. + final int changeAll = countAt(n, k, i) + Arrays.stream(dp[i + 1]).min().getAsInt(); + for (int j = 0; j < kMax; ++j) { + dp[i][j] = changeAll; + for (Map.Entry entry : counts[i].entrySet()) { + final int num = entry.getKey(); + final int freq = entry.getValue(); + // the cost to change every number in the i-th position to `num` + final int cost = countAt(n, k, i) - freq; + dp[i][j] = Math.min(dp[i][j], dp[i + 1][j ^ num] + cost); + } + } + } + + return dp[0][0]; + } + + private int countAt(int n, int k, int i) { + return n / k + (n % k > i ? 1 : 0); + } +} diff --git a/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.py b/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.py new file mode 100644 index 00000000000..2388675acf2 --- /dev/null +++ b/solutions/1787. Make the XOR of All Segments Equal to Zero/1787.py @@ -0,0 +1,31 @@ +class Solution: + def minChanges(self, nums: List[int], k: int) -> int: + kMax = 1024 + n = len(nums) + # counts[i] := the counter that maps at the i-th position + counts = [collections.Counter() for _ in range(k)] + # dp[i][j] := the minimum number of elements to change s.t. XOR(nums[i..k - 1]) is j + dp = [[n] * kMax for _ in range(k)] + + for i, num in enumerate(nums): + counts[i % k][num] += 1 + + def countAt(i: int) -> int: + return n // k + (1 if n % k > i else 0) + + # Initialize the DP array. + for j in range(kMax): + dp[k - 1][j] = countAt(k - 1) - counts[k - 1][j] + + for i in range(k - 2, -1, -1): + # The worst-case scenario is changing all the i-th position numbers to a + # non-existent value in the current bucket. + changeAll = countAt(i) + min(dp[i + 1]) + for j in range(kMax): + dp[i][j] = changeAll + for num, freq in counts[i].items(): + # the cost to change every number in the i-th position to `num` + cost = countAt(i) - freq + dp[i][j] = min(dp[i][j], dp[i + 1][j ^ num] + cost) + + return dp[0][0] diff --git a/solutions/1788. Maximize the Beauty of the Garden/1788.cpp b/solutions/1788. Maximize the Beauty of the Garden/1788.cpp new file mode 100644 index 00000000000..055a88ed0e7 --- /dev/null +++ b/solutions/1788. Maximize the Beauty of the Garden/1788.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maximumBeauty(vector& flowers) { + int ans = INT_MIN; + int prefix = 0; + unordered_map flowerToPrefix; + + for (const int flower : flowers) { + if (const auto it = flowerToPrefix.find(flower); + it != flowerToPrefix.cend()) + ans = max(ans, prefix - it->second + flower * 2); + prefix += max(0, flower); + if (!flowerToPrefix.contains(flower)) + flowerToPrefix[flower] = prefix; + } + + return ans; + } +}; diff --git a/solutions/1788. Maximize the Beauty of the Garden/1788.java b/solutions/1788. Maximize the Beauty of the Garden/1788.java new file mode 100644 index 00000000000..32092a6aa51 --- /dev/null +++ b/solutions/1788. Maximize the Beauty of the Garden/1788.java @@ -0,0 +1,16 @@ +class Solution { + public int maximumBeauty(int[] flowers) { + int ans = Integer.MIN_VALUE; + int prefix = 0; + Map flowerToPrefix = new HashMap<>(); + + for (final int flower : flowers) { + if (flowerToPrefix.containsKey(flower)) + ans = Math.max(ans, prefix - flowerToPrefix.get(flower) + flower * 2); + prefix += Math.max(0, flower); + flowerToPrefix.putIfAbsent(flower, prefix); + } + + return ans; + } +} diff --git a/solutions/1788. Maximize the Beauty of the Garden/1788.py b/solutions/1788. Maximize the Beauty of the Garden/1788.py new file mode 100644 index 00000000000..0fb34c418be --- /dev/null +++ b/solutions/1788. Maximize the Beauty of the Garden/1788.py @@ -0,0 +1,13 @@ +class Solution: + def maximumBeauty(self, flowers: List[int]) -> int: + ans = -math.inf + prefix = 0 + flowerToPrefix = collections.defaultdict(int) + + for flower in flowers: + if flower in flowerToPrefix: + ans = max(ans, prefix - flowerToPrefix[flower] + flower * 2) + prefix += max(0, flower) + flowerToPrefix.setdefault(flower, prefix) + + return ans diff --git a/solutions/1789. Primary Department for Each Employee/1789.sql b/solutions/1789. Primary Department for Each Employee/1789.sql new file mode 100644 index 00000000000..a18e6703057 --- /dev/null +++ b/solutions/1789. Primary Department for Each Employee/1789.sql @@ -0,0 +1,12 @@ +SELECT + employee_id, + department_id +FROM Employee +WHERE primary_flag = 'Y' +UNION DISTINCT +SELECT + employee_id, + department_id +FROM Employee +GROUP BY 1 +HAVING COUNT(*) = 1; diff --git a/solutions/179. Largest Number/179.cpp b/solutions/179. Largest Number/179.cpp new file mode 100644 index 00000000000..892ebf29d45 --- /dev/null +++ b/solutions/179. Largest Number/179.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + string largestNumber(vector& nums) { + string ans; + + ranges::sort(nums, [](int a, int b) { + return to_string(a) + to_string(b) > to_string(b) + to_string(a); + }); + + for (const int num : nums) + ans += to_string(num); + + return ans[0] == '0' ? "0" : ans; + } +}; diff --git a/solutions/179. Largest Number/179.java b/solutions/179. Largest Number/179.java new file mode 100644 index 00000000000..2d235687c4e --- /dev/null +++ b/solutions/179. Largest Number/179.java @@ -0,0 +1,9 @@ +class Solution { + public String largestNumber(int[] nums) { + final String s = Arrays.stream(nums) + .mapToObj(String::valueOf) + .sorted((a, b) -> (b + a).compareTo(a + b)) + .collect(Collectors.joining("")); + return s.startsWith("00") ? "0" : s; + } +} diff --git a/solutions/179. Largest Number/179.py b/solutions/179. Largest Number/179.py new file mode 100644 index 00000000000..96e70e299c2 --- /dev/null +++ b/solutions/179. Largest Number/179.py @@ -0,0 +1,8 @@ +class LargerStrKey(str): + def __lt__(x: str, y: str) -> bool: + return x + y > y + x + + +class Solution: + def largestNumber(self, nums: List[int]) -> str: + return ''.join(sorted(map(str, nums), key=LargerStrKey)).lstrip('0') or '0' diff --git a/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.cpp b/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.cpp new file mode 100644 index 00000000000..1f886866dd8 --- /dev/null +++ b/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + // Similar to 859. Buddy Strings + bool areAlmostEqual(string s1, string s2) { + vector diffIndices; + for (int i = 0; i < s1.length(); ++i) + if (s1[i] != s2[i]) + diffIndices.push_back(i); + return diffIndices.empty() || (diffIndices.size() == 2 && + s1[diffIndices[0]] == s2[diffIndices[1]] && + s1[diffIndices[1]] == s2[diffIndices[0]]); + } +}; diff --git a/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.java b/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.java new file mode 100644 index 00000000000..9a02002f5b9 --- /dev/null +++ b/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.java @@ -0,0 +1,14 @@ +class Solution { + public boolean areAlmostEqual(String s1, String s2) { + List diffIndices = new ArrayList<>(); + + for (int i = 0; i < s1.length(); ++i) + if (s1.charAt(i) != s2.charAt(i)) + diffIndices.add(i); + + return diffIndices.isEmpty() || + (diffIndices.size() == 2 && + s1.charAt(diffIndices.get(0)) == s2.charAt(diffIndices.get(1)) && + s1.charAt(diffIndices.get(1)) == s2.charAt(diffIndices.get(0))); + } +} diff --git a/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.py b/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.py new file mode 100644 index 00000000000..fe58edc8ab4 --- /dev/null +++ b/solutions/1790. Check if One String Swap Can Make Strings Equal/1790.py @@ -0,0 +1,8 @@ +class Solution: + # Similar to 859. Buddy Strings + def areAlmostEqual(self, s1: str, s2: str) -> bool: + diffIndices = [i for i, (a, b) in enumerate(zip(s1, s2)) + if a != b] + return not diffIndices or (len(diffIndices) == 2 and + s1[diffIndices[0]] == s2[diffIndices[1]] and + s1[diffIndices[1]] == s2[diffIndices[0]]) diff --git a/solutions/1791. Find Center of Star Graph/1791.cpp b/solutions/1791. Find Center of Star Graph/1791.cpp new file mode 100644 index 00000000000..c25ab53587c --- /dev/null +++ b/solutions/1791. Find Center of Star Graph/1791.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int findCenter(vector>& edges) { + return edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1] + ? edges[0][0] + : edges[0][1]; + } +}; diff --git a/solutions/1791. Find Center of Star Graph/1791.java b/solutions/1791. Find Center of Star Graph/1791.java new file mode 100644 index 00000000000..8fb0b685c79 --- /dev/null +++ b/solutions/1791. Find Center of Star Graph/1791.java @@ -0,0 +1,7 @@ +class Solution { + public int findCenter(int[][] edges) { + return edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1] // + ? edges[0][0] + : edges[0][1]; + } +} diff --git a/solutions/1791. Find Center of Star Graph/1791.py b/solutions/1791. Find Center of Star Graph/1791.py new file mode 100644 index 00000000000..8ec300ccf81 --- /dev/null +++ b/solutions/1791. Find Center of Star Graph/1791.py @@ -0,0 +1,5 @@ +class Solution: + def findCenter(self, edges: List[List[int]]) -> int: + if edges[0][0] in edges[1]: + return edges[0][0] + return edges[0][1] diff --git a/solutions/1792. Maximum Average Pass Ratio/1792.cpp b/solutions/1792. Maximum Average Pass Ratio/1792.cpp new file mode 100644 index 00000000000..2c22ba54725 --- /dev/null +++ b/solutions/1792. Maximum Average Pass Ratio/1792.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + double maxAverageRatio(vector>& classes, int extraStudents) { + // (extra pass ratio, pass, total) + priority_queue> maxHeap; + + for (const vector& c : classes) { + const int pass = c[0]; + const int total = c[1]; + maxHeap.emplace(extraPassRatio(pass, total), pass, total); + } + + for (int i = 0; i < extraStudents; ++i) { + const auto [_, pass, total] = maxHeap.top(); + maxHeap.pop(); + maxHeap.emplace(extraPassRatio(pass + 1, total + 1), pass + 1, total + 1); + } + + double ratioSum = 0; + + while (!maxHeap.empty()) { + const auto [_, pass, total] = maxHeap.top(); + maxHeap.pop(); + ratioSum += pass / static_cast(total); + } + + return ratioSum / classes.size(); + } + + private: + // Returns the extra pass ratio if a brilliant student joins. + double extraPassRatio(int pass, int total) { + return (pass + 1) / static_cast(total + 1) - + pass / static_cast(total); + } +}; diff --git a/solutions/1792. Maximum Average Pass Ratio/1792.java b/solutions/1792. Maximum Average Pass Ratio/1792.java new file mode 100644 index 00000000000..7f56c5e7b7b --- /dev/null +++ b/solutions/1792. Maximum Average Pass Ratio/1792.java @@ -0,0 +1,33 @@ +class Solution { + public double maxAverageRatio(int[][] classes, int extraStudents) { + // (extra pass ratio, pass, total) + PriorityQueue maxHeap = + new PriorityQueue<>((a, b) -> Double.compare(b.extraPassRatio, a.extraPassRatio)); + + for (int[] c : classes) { + final int pass = c[0]; + final int total = c[1]; + maxHeap.offer(new T(getExtraPassRatio(pass, total), pass, total)); + } + + for (int i = 0; i < extraStudents; ++i) { + final int pass = maxHeap.peek().pass; + final int total = maxHeap.poll().total; + maxHeap.offer(new T(getExtraPassRatio(pass + 1, total + 1), pass + 1, total + 1)); + } + + double ratioSum = 0; + + while (!maxHeap.isEmpty()) + ratioSum += maxHeap.peek().pass / (double) maxHeap.poll().total; + + return ratioSum / classes.length; + } + + // Returns the extra pass ratio if a brilliant student joins. + private double getExtraPassRatio(int pass, int total) { + return (pass + 1) / (double) (total + 1) - pass / (double) total; + } + + private record T(double extraPassRatio, int pass, int total){}; +} diff --git a/solutions/1792. Maximum Average Pass Ratio/1792.py b/solutions/1792. Maximum Average Pass Ratio/1792.py new file mode 100644 index 00000000000..7dd3937bf95 --- /dev/null +++ b/solutions/1792. Maximum Average Pass Ratio/1792.py @@ -0,0 +1,15 @@ +class Solution: + def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: + def extraPassRatio(pas: int, total: int) -> float: + """Returns the extra pass ratio if a brilliant student joins.""" + return (pas + 1) / (total + 1) - pas / total + + maxHeap = [(-extraPassRatio(pas, total), pas, total) for pas, total in classes] + heapq.heapify(maxHeap) + + for _ in range(extraStudents): + _, pas, total = heapq.heappop(maxHeap) + heapq.heappush( + maxHeap, (-extraPassRatio(pas + 1, total + 1), pas + 1, total + 1)) + + return sum(pas / total for _, pas, total in maxHeap) / len(maxHeap) diff --git a/solutions/1793. Maximum Score of a Good Subarray/1793-2.cpp b/solutions/1793. Maximum Score of a Good Subarray/1793-2.cpp new file mode 100644 index 00000000000..939d029c1d6 --- /dev/null +++ b/solutions/1793. Maximum Score of a Good Subarray/1793-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maximumScore(vector& nums, int k) { + const int n = nums.size(); + int ans = nums[k]; + int mn = nums[k]; + int i = k; + int j = k; + + // Greedily expand the window and decrease the minimum as slow as possible. + while (i > 0 || j < n - 1) { + if (i == 0) + ++j; + else if (j == n - 1) + --i; + else if (nums[i - 1] < nums[j + 1]) + ++j; + else // nums[i - 1] >= nums[j + 1] + --i; + mn = min({mn, nums[i], nums[j]}); + ans = max(ans, mn * (j - i + 1)); + } + + return ans; + } +}; diff --git a/solutions/1793. Maximum Score of a Good Subarray/1793-2.java b/solutions/1793. Maximum Score of a Good Subarray/1793-2.java new file mode 100644 index 00000000000..332ae581aeb --- /dev/null +++ b/solutions/1793. Maximum Score of a Good Subarray/1793-2.java @@ -0,0 +1,25 @@ +class Solution { + public int maximumScore(int[] nums, int k) { + final int n = nums.length; + int ans = nums[k]; + int mn = nums[k]; + int i = k; + int j = k; + + // Greedily expand the window and decrease the minimum as slow as possible. + while (i > 0 || j < n - 1) { + if (i == 0) + ++j; + else if (j == n - 1) + --i; + else if (nums[i - 1] < nums[j + 1]) + ++j; + else + --i; + mn = Math.min(mn, Math.min(nums[i], nums[j])); + ans = Math.max(ans, mn * (j - i + 1)); + } + + return ans; + } +} diff --git a/solutions/1793. Maximum Score of a Good Subarray/1793-2.py b/solutions/1793. Maximum Score of a Good Subarray/1793-2.py new file mode 100644 index 00000000000..9c700d45d3e --- /dev/null +++ b/solutions/1793. Maximum Score of a Good Subarray/1793-2.py @@ -0,0 +1,22 @@ +class Solution: + def maximumScore(self, nums: List[int], k: int) -> int: + n = len(nums) + ans = nums[k] + mn = nums[k] + i = k + j = k + + # Greedily expand the window and decrease the minimum as slow as possible. + while i > 0 or j < n - 1: + if i == 0: + j += 1 + elif j == n - 1: + i -= 1 + elif nums[i - 1] < nums[j + 1]: + j += 1 + else: + i -= 1 + mn = min(mn, nums[i], nums[j]) + ans = max(ans, mn * (j - i + 1)) + + return ans diff --git a/solutions/1793. Maximum Score of a Good Subarray/1793.cpp b/solutions/1793. Maximum Score of a Good Subarray/1793.cpp new file mode 100644 index 00000000000..b61adaf42e6 --- /dev/null +++ b/solutions/1793. Maximum Score of a Good Subarray/1793.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + // Similar to 84. Largest Rectangle in Histogram + int maximumScore(vector& nums, int k) { + int ans = 0; + stack stack; + + for (int i = 0; i <= nums.size(); ++i) { + while (!stack.empty() && + (i == nums.size() || nums[stack.top()] > nums[i])) { + const int h = nums[stack.top()]; + stack.pop(); + const int w = stack.empty() ? i : i - stack.top() - 1; + if ((stack.empty() || stack.top() + 1 <= k) && i - 1 >= k) + ans = max(ans, h * w); + } + stack.push(i); + } + + return ans; + } +}; diff --git a/solutions/1793. Maximum Score of a Good Subarray/1793.java b/solutions/1793. Maximum Score of a Good Subarray/1793.java new file mode 100644 index 00000000000..41b70e55ce8 --- /dev/null +++ b/solutions/1793. Maximum Score of a Good Subarray/1793.java @@ -0,0 +1,19 @@ +class Solution { + // Similar to 84. Largest Rectangle in Histogram + public int maximumScore(int[] nums, int k) { + int ans = 0; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i <= nums.length; ++i) { + while (!stack.isEmpty() && (i == nums.length || nums[stack.peek()] > nums[i])) { + final int h = nums[stack.pop()]; + final int w = stack.isEmpty() ? i : i - stack.peek() - 1; + if ((stack.isEmpty() || stack.peek() + 1 <= k) && i - 1 >= k) + ans = Math.max(ans, h * w); + } + stack.push(i); + } + + return ans; + } +} diff --git a/solutions/1793. Maximum Score of a Good Subarray/1793.py b/solutions/1793. Maximum Score of a Good Subarray/1793.py new file mode 100644 index 00000000000..7dd461e8f70 --- /dev/null +++ b/solutions/1793. Maximum Score of a Good Subarray/1793.py @@ -0,0 +1,15 @@ +class Solution: + # Similar to 84. Largest Rectangle in Histogram + def maximumScore(self, nums: List[int], k: int) -> int: + ans = 0 + stack = [] + + for i in range(len(nums) + 1): + while stack and (i == len(nums) or nums[stack[-1]] > nums[i]): + h = nums[stack.pop()] + w = i - stack[-1] - 1 if stack else i + if (not stack or stack[-1] + 1 <= k) and i - 1 >= k: + ans = max(ans, h * w) + stack.append(i) + + return ans diff --git a/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.cpp b/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.cpp new file mode 100644 index 00000000000..c3d9745a091 --- /dev/null +++ b/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int countQuadruples(const string& s1, const string& s2) { + // To minimize j - a, the length of the substring should be 1. This is + // because for substrings with a size greater than 1, a will decrease, + // causing j - a to become larger. + int ans = 0; + int diff = INT_MAX; // diff := j - a + vector firstJ(26, -1); + vector lastA(26, -1); + + for (int j = s1.length() - 1; j >= 0; --j) + firstJ[s1[j] - 'a'] = j; + + for (int a = 0; a < s2.length(); ++a) + lastA[s2[a] - 'a'] = a; + + for (int i = 0; i < 26; ++i) { + if (firstJ[i] == -1 || lastA[i] == -1) + continue; + if (firstJ[i] - lastA[i] < diff) { + diff = firstJ[i] - lastA[i]; + ans = 0; + } + if (firstJ[i] - lastA[i] == diff) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.java b/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.java new file mode 100644 index 00000000000..10cc664e490 --- /dev/null +++ b/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.java @@ -0,0 +1,32 @@ +class Solution { + public int countQuadruples(String s1, String s2) { + // To minimize j - a, the length of the substring should be 1. This is + // because for substrings with a size greater than 1, a will decrease, + // causing j - a to become larger. + int ans = 0; + int diff = Integer.MAX_VALUE; // diff := j - a + int[] firstJ = new int[26]; + int[] lastA = new int[26]; + Arrays.fill(firstJ, -1); + Arrays.fill(lastA, -1); + + for (int j = s1.length() - 1; j >= 0; --j) + firstJ[s1.charAt(j) - 'a'] = j; + + for (int a = 0; a < s2.length(); ++a) + lastA[s2.charAt(a) - 'a'] = a; + + for (int i = 0; i < 26; ++i) { + if (firstJ[i] == -1 || lastA[i] == -1) + continue; + if (firstJ[i] - lastA[i] < diff) { + diff = firstJ[i] - lastA[i]; + ans = 0; + } + if (firstJ[i] - lastA[i] == diff) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.py b/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.py new file mode 100644 index 00000000000..5b7d52924e9 --- /dev/null +++ b/solutions/1794. Count Pairs of Equal Substrings With Minimum Difference/1794.py @@ -0,0 +1,26 @@ +class Solution: + def countQuadruples(self, s1: str, s2: str) -> int: + # To minimize j - a, the length of the substring should be 1. This is + # because for substrings with a size greater than 1, a will decrease, + # causing j - a to become larger. + ans = 0 + diff = math.inf # diff := j - a + firstJ = {} + lastA = {} + + for j in range(len(s1) - 1, -1, -1): + firstJ[s1[j]] = j + + for a in range(len(s2)): + lastA[s2[a]] = a + + for c in string.ascii_lowercase: + if c not in firstJ or c not in lastA: + continue + if firstJ[c] - lastA[c] < diff: + diff = firstJ[c] - lastA[c] + ans = 0 + if firstJ[c] - lastA[c] == diff: + ans += 1 + + return ans diff --git a/solutions/1795. Rearrange Products Table/1795.sql b/solutions/1795. Rearrange Products Table/1795.sql new file mode 100644 index 00000000000..9e29023bbfa --- /dev/null +++ b/solutions/1795. Rearrange Products Table/1795.sql @@ -0,0 +1,20 @@ +SELECT + product_id, + 'store1' AS store, + store1 AS price +FROM Products +WHERE store1 IS NOT NULL +UNION ALL +SELECT + product_id, + 'store2', + store2 +FROM Products +WHERE store2 IS NOT NULL +UNION ALL +SELECT + product_id, + 'store3', + store3 +FROM Products +WHERE store3 IS NOT NULL; diff --git a/solutions/1796. Second Largest Digit in a String/1796.cpp b/solutions/1796. Second Largest Digit in a String/1796.cpp new file mode 100644 index 00000000000..0140367ef0d --- /dev/null +++ b/solutions/1796. Second Largest Digit in a String/1796.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int secondHighest(string s) { + int maxDigit = -1; + int secondMaxDigit = -1; + + for (const char c : s) + if (isdigit(c)) { + const int digit = c - '0'; + if (digit > maxDigit) { + secondMaxDigit = maxDigit; + maxDigit = digit; + } else if (maxDigit > digit && digit > secondMaxDigit) { + secondMaxDigit = digit; + } + } + + return secondMaxDigit; + } +}; diff --git a/solutions/1796. Second Largest Digit in a String/1796.java b/solutions/1796. Second Largest Digit in a String/1796.java new file mode 100644 index 00000000000..8143275d1c9 --- /dev/null +++ b/solutions/1796. Second Largest Digit in a String/1796.java @@ -0,0 +1,19 @@ +class Solution { + public int secondHighest(String s) { + int maxDigit = -1; + int secondMaxDigit = -1; + + for (final char c : s.toCharArray()) + if (Character.isDigit(c)) { + final int digit = Character.getNumericValue(c); + if (digit > maxDigit) { + secondMaxDigit = maxDigit; + maxDigit = digit; + } else if (maxDigit > digit && digit > secondMaxDigit) { + secondMaxDigit = digit; + } + } + + return secondMaxDigit; + } +} diff --git a/solutions/1796. Second Largest Digit in a String/1796.py b/solutions/1796. Second Largest Digit in a String/1796.py new file mode 100644 index 00000000000..ad1221e3499 --- /dev/null +++ b/solutions/1796. Second Largest Digit in a String/1796.py @@ -0,0 +1,15 @@ +class Solution: + def secondHighest(self, s: str) -> int: + maxDigit = -1 + secondMaxDigit = -1 + + for c in s: + if c.isdigit(): + d = int(c) + if d > maxDigit: + secondMaxDigit = maxDigit + maxDigit = d + elif maxDigit > d > secondMaxDigit: + secondMaxDigit = d + + return secondMaxDigit diff --git a/solutions/1797. Design Authentication Manager/1797.cpp b/solutions/1797. Design Authentication Manager/1797.cpp new file mode 100644 index 00000000000..ca7017d179e --- /dev/null +++ b/solutions/1797. Design Authentication Manager/1797.cpp @@ -0,0 +1,31 @@ +class AuthenticationManager { + public: + AuthenticationManager(int timeToLive) : timeToLive(timeToLive) {} + + void generate(string tokenId, int currentTime) { + tokenIdToExpiryTime[tokenId] = currentTime; + times.emplace(currentTime); + } + + void renew(string tokenId, int currentTime) { + if (const auto it = tokenIdToExpiryTime.find(tokenId); + it == tokenIdToExpiryTime.cend() || + currentTime >= it->second + timeToLive) + return; + times.erase(tokenIdToExpiryTime[tokenId]); + tokenIdToExpiryTime[tokenId] = currentTime; + times.emplace(currentTime); + } + + int countUnexpiredTokens(int currentTime) { + const auto it = times.lower_bound(currentTime - timeToLive + 1); + // Remove expired tokens. + times.erase(times.begin(), it); + return times.size(); + } + + private: + const int timeToLive; + unordered_map tokenIdToExpiryTime; + set times; +}; diff --git a/solutions/1797. Design Authentication Manager/1797.java b/solutions/1797. Design Authentication Manager/1797.java new file mode 100644 index 00000000000..22d6c3f5013 --- /dev/null +++ b/solutions/1797. Design Authentication Manager/1797.java @@ -0,0 +1,30 @@ +public class AuthenticationManager { + public AuthenticationManager(int timeToLive) { + this.timeToLive = timeToLive; + } + + public void generate(String tokenId, int currentTime) { + tokenIdToExpiryTime.put(tokenId, currentTime); + times.add(currentTime); + } + + public void renew(String tokenId, int currentTime) { + Integer expiryTime = tokenIdToExpiryTime.get(tokenId); + if (expiryTime == null || currentTime >= expiryTime + timeToLive) + return; + times.remove(expiryTime); + tokenIdToExpiryTime.put(tokenId, currentTime); + times.add(currentTime); + } + + public int countUnexpiredTokens(int currentTime) { + final int expiryTimeThreshold = currentTime - timeToLive + 1; + // Remove expired tokens. + times.headSet(expiryTimeThreshold).clear(); + return times.size(); + } + + private final int timeToLive; + private final Map tokenIdToExpiryTime = new HashMap<>(); + private final TreeSet times = new TreeSet<>(); +} diff --git a/solutions/1797. Design Authentication Manager/1797.py b/solutions/1797. Design Authentication Manager/1797.py new file mode 100644 index 00000000000..a258d9fd5d1 --- /dev/null +++ b/solutions/1797. Design Authentication Manager/1797.py @@ -0,0 +1,27 @@ +from sortedcontainers import SortedSet + + +class AuthenticationManager: + def __init__(self, timeToLive: int): + self.timeToLive = timeToLive + self.tokenIdToExpiryTime = {} + self.times = SortedSet() + + def generate(self, tokenId: str, currentTime: int) -> None: + self.tokenIdToExpiryTime[tokenId] = currentTime + self.times.add(currentTime) + + def renew(self, tokenId: str, currentTime: int) -> None: + if tokenId not in self.tokenIdToExpiryTime or \ + currentTime >= self.tokenIdToExpiryTime[tokenId] + self.timeToLive: + return + self.times.remove(self.tokenIdToExpiryTime[tokenId]) + self.tokenIdToExpiryTime[tokenId] = currentTime + self.times.add(currentTime) + + def countUnexpiredTokens(self, currentTime: int) -> int: + i = self.times.bisect_left(currentTime - self.timeToLive + 1) + # Remove expired tokens. + for _ in range(i): + self.times.remove(self.times[0]) + return len(self.times) diff --git a/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.cpp b/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.cpp new file mode 100644 index 00000000000..fff2413a21c --- /dev/null +++ b/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int getMaximumConsecutive(vector& coins) { + int ans = 1; // the next value we want to make + + ranges::sort(coins); + + for (const int coin : coins) { + if (coin > ans) + return ans; + ans += coin; + } + + return ans; + } +}; diff --git a/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.java b/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.java new file mode 100644 index 00000000000..3906e30eb13 --- /dev/null +++ b/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.java @@ -0,0 +1,15 @@ +class Solution { + public int getMaximumConsecutive(int[] coins) { + int ans = 1; // the next value we want to make + + Arrays.sort(coins); + + for (final int coin : coins) { + if (coin > ans) + return ans; + ans += coin; + } + + return ans; + } +} diff --git a/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.py b/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.py new file mode 100644 index 00000000000..236b9fa5e9e --- /dev/null +++ b/solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.py @@ -0,0 +1,10 @@ +class Solution: + def getMaximumConsecutive(self, coins: List[int]) -> int: + ans = 1 # the next value we want to make + + for coin in sorted(coins): + if coin > ans: + return ans + ans += coin + + return ans diff --git a/solutions/1799. Maximize Score After N Operations/1799.cpp b/solutions/1799. Maximize Score After N Operations/1799.cpp new file mode 100644 index 00000000000..5addb510863 --- /dev/null +++ b/solutions/1799. Maximize Score After N Operations/1799.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maxScore(vector& nums) { + const int n = nums.size() / 2; + vector> mem(n + 1, vector(1 << n * 2)); + return maxScore(nums, 1, 0, mem); + } + + private: + // Returns the maximum score you can receive after performing the k to n + // operations, where `mask` is the bitmask of the chosen numbers. + int maxScore(const vector& nums, int k, int mask, + vector>& mem) { + if (k == mem.size()) + return 0; + if (mem[k][mask] > 0) + return mem[k][mask]; + + for (int i = 0; i < nums.size(); ++i) + for (int j = i + 1; j < nums.size(); ++j) { + const int chosenMask = 1 << i | 1 << j; + if ((mask & chosenMask) == 0) + mem[k][mask] = max(mem[k][mask], + k * __gcd(nums[i], nums[j]) + + maxScore(nums, k + 1, mask | chosenMask, mem)); + } + + return mem[k][mask]; + } +}; diff --git a/solutions/1799. Maximize Score After N Operations/1799.java b/solutions/1799. Maximize Score After N Operations/1799.java new file mode 100644 index 00000000000..1565296fb3e --- /dev/null +++ b/solutions/1799. Maximize Score After N Operations/1799.java @@ -0,0 +1,30 @@ +class Solution { + public int maxScore(int[] nums) { + final int n = nums.length / 2; + int[][] mem = new int[n + 1][1 << (n * 2)]; + return maxScore(nums, 1, 0, mem); + } + + // Returns the maximum score you can receive after performing the k to n + // operations, where `mask` is the bitmask of the chosen numbers. + private int maxScore(int[] nums, int k, int mask, int[][] mem) { + if (k == mem.length) + return 0; + if (mem[k][mask] > 0) + return mem[k][mask]; + + for (int i = 0; i < nums.length; ++i) + for (int j = i + 1; j < nums.length; ++j) { + final int chosenMask = 1 << i | 1 << j; + if ((mask & chosenMask) == 0) + mem[k][mask] = Math.max(mem[k][mask], k * gcd(nums[i], nums[j]) + + maxScore(nums, k + 1, mask | chosenMask, mem)); + } + + return mem[k][mask]; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/1799. Maximize Score After N Operations/1799.py b/solutions/1799. Maximize Score After N Operations/1799.py new file mode 100644 index 00000000000..993fa454793 --- /dev/null +++ b/solutions/1799. Maximize Score After N Operations/1799.py @@ -0,0 +1,25 @@ +class Solution: + def maxScore(self, nums: List[int]) -> int: + n = len(nums) // 2 + + @functools.lru_cache(None) + def dp(k: int, mask: int) -> int: + """ + Returns the maximum score you can receive after performing the k to n + operations, where `mask` is the bitmask of the chosen numbers. + """ + if k == n + 1: + return 0 + + res = 0 + + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + chosenMask = 1 << i | 1 << j + if (mask & chosenMask) == 0: + res = max(res, + k * math.gcd(nums[i], nums[j]) + dp(k + 1, mask | chosenMask)) + + return res + + return dp(1, 0) diff --git a/solutions/18. 4Sum/18.cpp b/solutions/18. 4Sum/18.cpp new file mode 100644 index 00000000000..2aba05cd1d9 --- /dev/null +++ b/solutions/18. 4Sum/18.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + vector> fourSum(vector& nums, int target) { + vector> ans; + vector path; + ranges::sort(nums); + nSum(nums, 4, target, 0, nums.size() - 1, path, ans); + return ans; + } + + private: + // Finds n numbers that add up to the target in [l, r]. + void nSum(const vector& nums, long n, long target, int l, int r, + vector& path, vector>& ans) { + if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n) + return; + if (n == 2) { + // Similar to the sub procedure in 15. 3Sum + while (l < r) { + const int sum = nums[l] + nums[r]; + if (sum == target) { + path.push_back(nums[l]); + path.push_back(nums[r]); + ans.push_back(path); + path.pop_back(); + path.pop_back(); + ++l; + --r; + while (l < r && nums[l] == nums[l - 1]) + ++l; + while (l < r && nums[r] == nums[r + 1]) + --r; + } else if (sum < target) { + ++l; + } else { + --r; + } + } + return; + } + + for (int i = l; i <= r; ++i) { + if (i > l && nums[i] == nums[i - 1]) + continue; + path.push_back(nums[i]); + nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans); + path.pop_back(); + } + } +}; diff --git a/solutions/18. 4Sum/18.java b/solutions/18. 4Sum/18.java new file mode 100644 index 00000000000..5ad370c3194 --- /dev/null +++ b/solutions/18. 4Sum/18.java @@ -0,0 +1,47 @@ +class Solution { + public List> fourSum(int[] nums, int target) { + List> ans = new ArrayList<>(); + Arrays.sort(nums); + nSum(nums, 4, target, 0, nums.length - 1, new ArrayList<>(), ans); + return ans; + } + + // Finds n numbers that add up to the target in [l, r]. + private void nSum(int[] nums, long n, long target, int l, int r, List path, + List> ans) { + if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n) + return; + if (n == 2) { + // Similar to the sub procedure in 15. 3Sum + while (l < r) { + final int sum = nums[l] + nums[r]; + if (sum == target) { + path.add(nums[l]); + path.add(nums[r]); + ans.add(new ArrayList<>(path)); + path.remove(path.size() - 1); + path.remove(path.size() - 1); + ++l; + --r; + while (l < r && nums[l] == nums[l - 1]) + ++l; + while (l < r && nums[r] == nums[r + 1]) + --r; + } else if (sum < target) { + ++l; + } else { + --r; + } + } + return; + } + + for (int i = l; i <= r; ++i) { + if (i > l && nums[i] == nums[i - 1]) + continue; + path.add(nums[i]); + nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/18. 4Sum/18.py b/solutions/18. 4Sum/18.py new file mode 100644 index 00000000000..f77e13c89fc --- /dev/null +++ b/solutions/18. 4Sum/18.py @@ -0,0 +1,31 @@ +class Solution: + def fourSum(self, nums: List[int], target: int): + ans = [] + + def nSum(l: int, r: int, target: int, n: int, path: List[int], ans: List[List[int]]) -> None: + """Finds n numbers that add up to the target in [l, r].""" + if r - l + 1 < n or n < 2 or target < nums[l] * n or target > nums[r] * n: + return + if n == 2: + while l < r: + summ = nums[l] + nums[r] + if summ == target: + ans.append(path + [nums[l], nums[r]]) + l += 1 + while nums[l] == nums[l - 1] and l < r: + l += 1 + elif summ < target: + l += 1 + else: + r -= 1 + return + + for i in range(l, r + 1): + if i > l and nums[i] == nums[i - 1]: + continue + + nSum(i + 1, r, target - nums[i], n - 1, path + [nums[i]], ans) + + nums.sort() + nSum(0, len(nums) - 1, target, 4, [], ans) + return ans diff --git a/solutions/180. Consecutive Numbers/180.sql b/solutions/180. Consecutive Numbers/180.sql new file mode 100644 index 00000000000..304b3f7f0f4 --- /dev/null +++ b/solutions/180. Consecutive Numbers/180.sql @@ -0,0 +1,13 @@ +WITH + LogsNeighbors AS ( + SELECT + *, + LAG(num) OVER(ORDER BY id) AS prev_num, + LEAD(num) OVER(ORDER BY id) AS next_num + FROM LOGS + ) +SELECT DISTINCT num AS ConsecutiveNums +FROM LogsNeighbors +WHERE + num = prev_num + AND num = next_num; diff --git a/solutions/1800. Maximum Ascending Subarray Sum/1800.cpp b/solutions/1800. Maximum Ascending Subarray Sum/1800.cpp new file mode 100644 index 00000000000..5b41abe03a9 --- /dev/null +++ b/solutions/1800. Maximum Ascending Subarray Sum/1800.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxAscendingSum(vector& nums) { + int ans = 0; + int sum = nums[0]; + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] > nums[i - 1]) { + sum += nums[i]; + } else { + ans = max(ans, sum); + sum = nums[i]; + } + + return max(ans, sum); + } +}; diff --git a/solutions/1800. Maximum Ascending Subarray Sum/1800.java b/solutions/1800. Maximum Ascending Subarray Sum/1800.java new file mode 100644 index 00000000000..524d84fa8dc --- /dev/null +++ b/solutions/1800. Maximum Ascending Subarray Sum/1800.java @@ -0,0 +1,16 @@ +class Solution { + public int maxAscendingSum(int[] nums) { + int ans = 0; + int sum = nums[0]; + + for (int i = 1; i < nums.length; ++i) + if (nums[i] > nums[i - 1]) { + sum += nums[i]; + } else { + ans = Math.max(ans, sum); + sum = nums[i]; + } + + return Math.max(ans, sum); + } +} diff --git a/solutions/1800. Maximum Ascending Subarray Sum/1800.py b/solutions/1800. Maximum Ascending Subarray Sum/1800.py new file mode 100644 index 00000000000..5ffee468798 --- /dev/null +++ b/solutions/1800. Maximum Ascending Subarray Sum/1800.py @@ -0,0 +1,13 @@ +class Solution: + def maxAscendingSum(self, nums: List[int]) -> int: + ans = 0 + sum = nums[0] + + for i in range(1, len(nums)): + if nums[i] > nums[i - 1]: + sum += nums[i] + else: + ans = max(ans, sum) + sum = nums[i] + + return max(ans, sum) diff --git a/solutions/1801. Number of Orders in the Backlog/1801.cpp b/solutions/1801. Number of Orders in the Backlog/1801.cpp new file mode 100644 index 00000000000..4b372ddf49f --- /dev/null +++ b/solutions/1801. Number of Orders in the Backlog/1801.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int getNumberOfBacklogOrders(vector>& orders) { + constexpr int kMod = 1'000'000'007; + int ans = 0; + priority_queue> buysMaxHeap; + priority_queue, vector>, greater<>> sellsMinHeap; + + for (const vector& order : orders) { + if (order[2] == 0) + buysMaxHeap.push(order); + else + sellsMinHeap.push(order); + while (!buysMaxHeap.empty() && !sellsMinHeap.empty() && + buysMaxHeap.top()[0] >= sellsMinHeap.top()[0]) { + const int minAmount = min(buysMaxHeap.top()[1], sellsMinHeap.top()[1]); + vector buysMaxHeapTop = buysMaxHeap.top(); + buysMaxHeap.pop(); + buysMaxHeapTop[1] -= minAmount; + if (buysMaxHeapTop[1] > 0) + buysMaxHeap.push(buysMaxHeapTop); + + vector sellsMinHeapTop = sellsMinHeap.top(); + sellsMinHeap.pop(); + sellsMinHeapTop[1] -= minAmount; + if (sellsMinHeapTop[1] > 0) + sellsMinHeap.push(sellsMinHeapTop); + } + } + + while (!buysMaxHeap.empty()) { + ans += buysMaxHeap.top()[1], buysMaxHeap.pop(); + ans %= kMod; + } + + while (!sellsMinHeap.empty()) { + ans += sellsMinHeap.top()[1], sellsMinHeap.pop(); + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/1801. Number of Orders in the Backlog/1801.java b/solutions/1801. Number of Orders in the Backlog/1801.java new file mode 100644 index 00000000000..65c9f3705ff --- /dev/null +++ b/solutions/1801. Number of Orders in the Backlog/1801.java @@ -0,0 +1,37 @@ +class Solution { + public int getNumberOfBacklogOrders(int[][] orders) { + final int kMod = 1_000_000_007; + int ans = 0; + PriorityQueue buysMaxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]); + PriorityQueue sellsMinHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + + for (int[] order : orders) { + if (order[2] == 0) + buysMaxHeap.offer(order); + else + sellsMinHeap.offer(order); + while (!buysMaxHeap.isEmpty() && !sellsMinHeap.isEmpty() && + buysMaxHeap.peek()[0] >= sellsMinHeap.peek()[0]) { + final int minAmount = Math.min(buysMaxHeap.peek()[1], sellsMinHeap.peek()[1]); + buysMaxHeap.peek()[1] -= minAmount; + sellsMinHeap.peek()[1] -= minAmount; + if (buysMaxHeap.peek()[1] == 0) + buysMaxHeap.poll(); + if (sellsMinHeap.peek()[1] == 0) + sellsMinHeap.poll(); + } + } + + while (!buysMaxHeap.isEmpty()) { + ans += buysMaxHeap.poll()[1]; + ans %= kMod; + } + + while (!sellsMinHeap.isEmpty()) { + ans += sellsMinHeap.poll()[1]; + ans %= kMod; + } + + return ans; + } +} diff --git a/solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.cpp b/solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.cpp new file mode 100644 index 00000000000..11fd43e9616 --- /dev/null +++ b/solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maxValue(int n, int index, int maxSum) { + maxSum -= n; + + int l = 0; + int r = maxSum; + + // Find the first value x s.t. if A[index] = x, then sum(A) >= maxSum. + while (l < r) { + const int m = (l + r) / 2; + if (getSum(n, index, m) >= maxSum) + r = m; + else + l = m + 1; + } + + return getSum(n, index, l) > maxSum ? l : l + 1; + } + + private: + // Returns the minimum sum if nums[index] = x. + long getSum(int n, int index, int x) { + long l = min(index, x - 1); + long r = min(n - index, x); + long lSum = ((x - 1) + (x - 1 - l + 1)) * l / 2; + long rSum = (x + (x - r + 1)) * r / 2; + return lSum + rSum; + } +}; diff --git a/solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.java b/solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.java new file mode 100644 index 00000000000..0d8f1cd4fb6 --- /dev/null +++ b/solutions/1802. Maximum Value at a Given Index in a Bounded Array/1802.java @@ -0,0 +1,28 @@ +class Solution { + public int maxValue(int n, int index, int maxSum) { + maxSum -= n; + + int l = 0; + int r = maxSum; + + // Find the first value x s.t. if A[index] = x, then sum(A) >= maxSum. + while (l < r) { + final int m = (l + r) / 2; + if (getSum(n, index, m) >= maxSum) + r = m; + else + l = m + 1; + } + + return getSum(n, index, l) > maxSum ? l : l + 1; + } + + // Returns the minimum sum if nums[index] = x. + private long getSum(int n, int index, int x) { + long l = Math.min(index, x - 1); + long r = Math.min(n - index, x); + long lSum = ((x - 1) + (x - 1 - l + 1)) * l / 2; + long rSum = (x + (x - r + 1)) * r / 2; + return lSum + rSum; + } +} diff --git a/solutions/1803. Count Pairs With XOR in a Range/1803.cpp b/solutions/1803. Count Pairs With XOR in a Range/1803.cpp new file mode 100644 index 00000000000..56bb00dca10 --- /dev/null +++ b/solutions/1803. Count Pairs With XOR in a Range/1803.cpp @@ -0,0 +1,54 @@ +struct TrieNode { + vector> children; + int count = 0; + TrieNode() : children(2) {} +}; + +class Solution { + public: + int countPairs(vector& nums, int low, int high) { + int ans = 0; + + for (const int num : nums) { + ans += getCount(num, high + 1) - getCount(num, low); + insert(num); + } + + return ans; + } + + private: + static constexpr int kHeight = 14; + shared_ptr root = make_shared(); + + void insert(int num) { + shared_ptr node = root; + for (int i = kHeight; i >= 0; --i) { + const int bit = num >> i & 1; + if (node->children[bit] == nullptr) + node->children[bit] = make_shared(); + node = node->children[bit]; + ++node->count; + } + } + + // Returns the number of numbers < limit. + int getCount(int num, int limit) { + int count = 0; + shared_ptr node = root; + for (int i = kHeight; i >= 0; --i) { + const int bit = num >> i & 1; + const int bitLimit = limit >> i & 1; + if (bitLimit == 1) { + if (node->children[bit] != nullptr) + count += node->children[bit]->count; + node = node->children[bit ^ 1]; + } else { + node = node->children[bit]; + } + if (node == nullptr) + break; + } + return count; + } +}; diff --git a/solutions/1803. Count Pairs With XOR in a Range/1803.java b/solutions/1803. Count Pairs With XOR in a Range/1803.java new file mode 100644 index 00000000000..8d9d98dfdd7 --- /dev/null +++ b/solutions/1803. Count Pairs With XOR in a Range/1803.java @@ -0,0 +1,51 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[2]; + public int count = 0; +} + +class Solution { + public int countPairs(int[] nums, int low, int high) { + int ans = 0; + + for (final int num : nums) { + ans += getCount(num, high + 1) - getCount(num, low); + insert(num); + } + + return ans; + } + + private final int kHeight = 14; + private TrieNode root = new TrieNode(); + + private void insert(int num) { + TrieNode node = root; + for (int i = kHeight; i >= 0; --i) { + final int bit = num >> i & 1; + if (node.children[bit] == null) + node.children[bit] = new TrieNode(); + node = node.children[bit]; + ++node.count; + } + } + + // Returns the number of numbers < limit. + private int getCount(int num, int limit) { + int count = 0; + TrieNode node = root; + for (int i = kHeight; i >= 0; --i) { + final int bit = num >> i & 1; + final int bitLimit = ((limit >> i) & 1); + if (bitLimit == 1) { + if (node.children[bit] != null) + count += node.children[bit].count; + node = node.children[bit ^ 1]; + } else { + node = node.children[bit]; + } + if (node == null) + break; + } + return count; + } +} diff --git a/solutions/1804. Implement Trie II (Prefix Tree)/1804.cpp b/solutions/1804. Implement Trie II (Prefix Tree)/1804.cpp new file mode 100644 index 00000000000..a4da4d18f45 --- /dev/null +++ b/solutions/1804. Implement Trie II (Prefix Tree)/1804.cpp @@ -0,0 +1,55 @@ +struct TrieNode { + vector> children; + int prefixCount = 0; + int wordCount = 0; + TrieNode() : children(26) {} +}; + +class Trie { + public: + void insert(string word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + ++node->prefixCount; + } + ++node->wordCount; + } + + int countWordsEqualTo(string word) { + shared_ptr node = find(word); + return node ? node->wordCount : 0; + } + + int countWordsStartingWith(string prefix) { + shared_ptr node = find(prefix); + return node ? node->prefixCount : 0; + } + + void erase(string word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + node = node->children[i]; + --node->prefixCount; + } + --node->wordCount; + } + + private: + shared_ptr root = make_shared(); + + shared_ptr find(const string& s) { + shared_ptr node = root; + for (const char c : s) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + return nullptr; + node = node->children[i]; + } + return node; + } +}; diff --git a/solutions/1804. Implement Trie II (Prefix Tree)/1804.java b/solutions/1804. Implement Trie II (Prefix Tree)/1804.java new file mode 100644 index 00000000000..d20dc5977ec --- /dev/null +++ b/solutions/1804. Implement Trie II (Prefix Tree)/1804.java @@ -0,0 +1,52 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int prefixCount = 0; + public int wordCount = 0; +} + +class Trie { + public void insert(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + ++node.prefixCount; + } + ++node.wordCount; + } + + public int countWordsEqualTo(String word) { + TrieNode node = find(word); + return node == null ? 0 : node.wordCount; + } + + public int countWordsStartingWith(String prefix) { + TrieNode node = find(prefix); + return node == null ? 0 : node.prefixCount; + } + + public void erase(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + node = node.children[i]; + --node.prefixCount; + } + --node.wordCount; + } + + private TrieNode root = new TrieNode(); + + private TrieNode find(final String s) { + TrieNode node = root; + for (final char c : s.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + return null; + node = node.children[i]; + } + return node; + } +} diff --git a/solutions/1805. Number of Different Integers in a String/1805-2.py b/solutions/1805. Number of Different Integers in a String/1805-2.py new file mode 100644 index 00000000000..e502e834222 --- /dev/null +++ b/solutions/1805. Number of Different Integers in a String/1805-2.py @@ -0,0 +1,3 @@ +class Solution: + def numDifferentIntegers(self, word: str) -> int: + return len(set(map(int, re.findall(r'\d+', word)))) diff --git a/solutions/1805. Number of Different Integers in a String/1805.cpp b/solutions/1805. Number of Different Integers in a String/1805.cpp new file mode 100644 index 00000000000..c30dc84e534 --- /dev/null +++ b/solutions/1805. Number of Different Integers in a String/1805.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int numDifferentIntegers(string word) { + unordered_set nums; + string curr; + + for (const char c : word) + if (isdigit(c)) { + curr += c; + } else if (curr.length() > 0) { + nums.insert(removeLeadingZeros(curr)); + curr = ""; + } + + if (curr.length() > 0) + nums.insert(removeLeadingZeros(curr)); + return nums.size(); + } + + private: + string removeLeadingZeros(const string& s) { + const int index = s.find_first_not_of('0'); + return index == string::npos ? "0" : s.substr(index); + } +}; diff --git a/solutions/1805. Number of Different Integers in a String/1805.java b/solutions/1805. Number of Different Integers in a String/1805.java new file mode 100644 index 00000000000..836fe9c931c --- /dev/null +++ b/solutions/1805. Number of Different Integers in a String/1805.java @@ -0,0 +1,25 @@ +class Solution { + public int numDifferentIntegers(String word) { + HashSet nums = new HashSet<>(); + StringBuilder sb = new StringBuilder(); + + for (final char c : word.toCharArray()) + if (Character.isDigit(c)) { + sb.append(c); + } else if (sb.length() > 0) { + nums.add(removeLeadingZeros(sb.toString())); + sb = new StringBuilder(); + } + + if (sb.length() > 0) + nums.add(removeLeadingZeros(sb.toString())); + return nums.size(); + } + + private String removeLeadingZeros(final String s) { + int index = 0; + while (index < s.length() && s.charAt(index) == '0') + ++index; + return index == s.length() ? "0" : s.substring(index); + } +} diff --git a/solutions/1805. Number of Different Integers in a String/1805.py b/solutions/1805. Number of Different Integers in a String/1805.py new file mode 100644 index 00000000000..c679cf28d06 --- /dev/null +++ b/solutions/1805. Number of Different Integers in a String/1805.py @@ -0,0 +1,20 @@ +class Solution: + def numDifferentIntegers(self, word: str) -> int: + nums = set() + curr = [] + + for c in word: + if c.isdigit(): + curr.append(c) + elif curr: + nums.add(''.join(self._removeLeadingZeros(curr))) + curr = [] + + if curr: + nums.add(''.join(self._removeLeadingZeros(curr))) + + return len(nums) + + def _removeLeadingZeros(self, s: str) -> str: + index = next((i for i, c in enumerate(s) if c != '0'), -1) + return ['0'] if index == -1 else s[index:] diff --git a/solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.cpp b/solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.cpp new file mode 100644 index 00000000000..9a1c773fb05 --- /dev/null +++ b/solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int reinitializePermutation(int n) { + int ans = 0; + int i = 1; + + do { + if (i < n / 2) + i = i * 2; + else + i = (i - n / 2) * 2 + 1; + ++ans; + } while (i != 1); + + return ans; + } +}; diff --git a/solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.java b/solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.java new file mode 100644 index 00000000000..d711620faf6 --- /dev/null +++ b/solutions/1806. Minimum Number of Operations to Reinitialize a Permutation/1806.java @@ -0,0 +1,16 @@ +class Solution { + public int reinitializePermutation(int n) { + int ans = 0; + int i = 1; + + do { + if (i < n / 2) + i = i * 2; + else + i = (i - n / 2) * 2 + 1; + ++ans; + } while (i != 1); + + return ans; + } +} diff --git a/solutions/1807. Evaluate the Bracket Pairs of a String/1807.cpp b/solutions/1807. Evaluate the Bracket Pairs of a String/1807.cpp new file mode 100644 index 00000000000..9ee1ad0daeb --- /dev/null +++ b/solutions/1807. Evaluate the Bracket Pairs of a String/1807.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string evaluate(string s, vector>& knowledge) { + string ans; + unordered_map map; + + for (const vector& list : knowledge) + map["(" + list[0] + ")"] = list[1]; + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + if (c == '(') { + const int j = s.find_first_of(')', i); + const string& key = s.substr(i, j - i + 1); + ans += map.contains(key) ? map[key] : "?"; + i = j; + } else { + ans += c; + } + } + + return ans; + } +}; diff --git a/solutions/1807. Evaluate the Bracket Pairs of a String/1807.java b/solutions/1807. Evaluate the Bracket Pairs of a String/1807.java new file mode 100644 index 00000000000..a00576d7bd0 --- /dev/null +++ b/solutions/1807. Evaluate the Bracket Pairs of a String/1807.java @@ -0,0 +1,22 @@ +class Solution { + public String evaluate(String s, List> knowledge) { + StringBuilder sb = new StringBuilder(); + Map map = new HashMap<>(); + + for (List list : knowledge) + map.put("(" + list.get(0) + ")", list.get(1)); + + for (int i = 0; i < s.length(); ++i) { + final char c = s.charAt(i); + if (c == '(') { + final int j = s.indexOf(')', i); + sb.append(map.getOrDefault(s.substring(i, j + 1), "?")); + i = j; + } else { + sb.append(c); + } + } + + return sb.toString(); + } +} diff --git a/solutions/1808. Maximize Number of Nice Divisors/1808.cpp b/solutions/1808. Maximize Number of Nice Divisors/1808.cpp new file mode 100644 index 00000000000..147f9efa0da --- /dev/null +++ b/solutions/1808. Maximize Number of Nice Divisors/1808.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int maxNiceDivisors(int primeFactors) { + if (primeFactors <= 3) + return primeFactors; + if (primeFactors % 3 == 0) + return modPow(3, primeFactors / 3) % kMod; + if (primeFactors % 3 == 1) + return 4L * modPow(3, (primeFactors - 4) / 3) % kMod; + return 2L * modPow(3, (primeFactors - 2) / 3) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/1808. Maximize Number of Nice Divisors/1808.java b/solutions/1808. Maximize Number of Nice Divisors/1808.java new file mode 100644 index 00000000000..2383bdc71b8 --- /dev/null +++ b/solutions/1808. Maximize Number of Nice Divisors/1808.java @@ -0,0 +1,21 @@ +class Solution { + public int maxNiceDivisors(int primeFactors) { + if (primeFactors <= 3) + return primeFactors; + if (primeFactors % 3 == 0) + return (int) (modPow(3, primeFactors / 3) % kMod); + if (primeFactors % 3 == 1) + return (int) (4 * modPow(3, (primeFactors - 4) / 3) % kMod); + return (int) (2 * modPow(3, (primeFactors - 2) / 3) % kMod); + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } +} diff --git a/solutions/1809. Ad-Free Sessions/1809.sql b/solutions/1809. Ad-Free Sessions/1809.sql new file mode 100644 index 00000000000..ec46286426d --- /dev/null +++ b/solutions/1809. Ad-Free Sessions/1809.sql @@ -0,0 +1,7 @@ +SELECT Playback.session_id +FROM Playback +LEFT JOIN Ads + ON ( + Playback.customer_id = Ads.customer_id + AND Ads.timestamp BETWEEN Playback.start_time AND Playback.end_time) +WHERE Ads.ad_id IS NULL; diff --git a/solutions/181. Employees Earning More Than Their Managers/181.sql b/solutions/181. Employees Earning More Than Their Managers/181.sql new file mode 100644 index 00000000000..9f77016334f --- /dev/null +++ b/solutions/181. Employees Earning More Than Their Managers/181.sql @@ -0,0 +1,5 @@ +SELECT Worker.name AS Employee +FROM Employee AS Worker +INNER JOIN Employee AS Manager + ON (Worker.managerId = Manager.id) +WHERE Worker.salary > Manager.salary; diff --git a/solutions/1810. Minimum Path Cost in a Hidden Grid/1810.cpp b/solutions/1810. Minimum Path Cost in a Hidden Grid/1810.cpp new file mode 100644 index 00000000000..3bd45cc0bac --- /dev/null +++ b/solutions/1810. Minimum Path Cost in a Hidden Grid/1810.cpp @@ -0,0 +1,79 @@ +/** + * // This is the GridMaster's API interface. + * // You should not implement it, or speculate about its implementation + * class GridMaster { + * public: + * bool canMove(char direction); + * int move(char direction); + * boolean isTarget(); + * }; + */ + +class Solution { + public: + int findShortestPath(GridMaster& master) { + constexpr int m = 100; + constexpr int startX = m; + constexpr int startY = m; + + vector target{m * 2, m * 2}; + vector> grid(m * 2, vector(m * 2, -1)); + vector> seen(m * 2, vector(m * 2)); + + // Build the grid information by DFS. + dfs(master, grid, startX, startY, target); + + priority_queue, vector>, greater<>> minHeap; + minHeap.push({0, startX, startY}); + + // Find the steps by BFS. + while (!minHeap.empty()) { + const vector tuple = minHeap.top(); + const int cost = tuple[0]; + const int i = tuple[1]; + const int j = tuple[2]; + minHeap.pop(); + if (i == target[0] && j == target[1]) + return cost; + if (seen[i][j]) + continue; + seen[i][j] = true; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == 2 * m || y < 0 || y == 2 * m) + continue; + if (seen[x][y] || grid[x][y] == -1) + continue; + const int nextCost = cost + grid[x][y]; + minHeap.push({nextCost, x, y}); + } + } + + return -1; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + static constexpr char charTable[4] = {'R', 'D', 'L', 'U'}; + + void dfs(GridMaster& master, vector>& grid, int i, int j, + vector& target) { + if (master.isTarget()) { + target[0] = i; + target[1] = j; + } + + for (int k = 0; k < 4; ++k) { + const int x = i + dirs[k][0]; + const int y = j + dirs[k][1]; + const char d = charTable[k]; + const char undoD = charTable[(k + 2) % 4]; + if (master.canMove(d) && grid[x][y] == -1) { + grid[x][y] = master.move(d); + dfs(master, grid, x, y, target); + master.move(undoD); + } + } + } +}; diff --git a/solutions/1810. Minimum Path Cost in a Hidden Grid/1810.java b/solutions/1810. Minimum Path Cost in a Hidden Grid/1810.java new file mode 100644 index 00000000000..5628e02d38b --- /dev/null +++ b/solutions/1810. Minimum Path Cost in a Hidden Grid/1810.java @@ -0,0 +1,74 @@ +/** + * // This is the GridMaster's API interface. + * // You should not implement it, or speculate about its implementation + * class GridMaster { + * boolean canMove(char direction); + * int move(char direction); + * boolean isTarget(); + * } + */ + +class Solution { + public int findShortestPath(GridMaster master) { + final int m = 100; + final int startX = m; + final int startY = m; + + int[] target = {m * 2, m * 2}; + int[][] grid = new int[m * 2][m * 2]; + boolean[][] seen = new boolean[m * 2][m * 2]; + Arrays.stream(grid).forEach(A -> Arrays.fill(A, -1)); + + // Build the grid information by DFS. + dfs(master, grid, startX, startY, target); + + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a[2] - b[2]); + minHeap.offer(new int[] {startX, startY, 0}); + + // Find the steps by BFS. + while (!minHeap.isEmpty()) { + final int i = minHeap.peek()[0]; + final int j = minHeap.peek()[1]; + final int cost = minHeap.poll()[2]; + if (i == target[0] && j == target[1]) + return cost; + if (seen[i][j]) + continue; + seen[i][j] = true; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == 2 * m || y < 0 || y == 2 * m) + continue; + if (seen[x][y] || grid[x][y] == -1) + continue; + final int nextCost = cost + grid[x][y]; + minHeap.offer(new int[] {x, y, nextCost}); + } + } + + return -1; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + private static final char[] charTable = {'R', 'D', 'L', 'U'}; + + private void dfs(GridMaster master, int[][] grid, int i, int j, int[] target) { + if (master.isTarget()) { + target[0] = i; + target[1] = j; + } + + for (int k = 0; k < 4; ++k) { + final int x = i + dirs[k]; + final int y = j + dirs[k + 1]; + final char d = charTable[k]; + final char undoD = charTable[(k + 2) % 4]; + if (master.canMove(d) && grid[x][y] == -1) { + grid[x][y] = master.move(d); + dfs(master, grid, x, y, target); + master.move(undoD); + } + } + } +} diff --git a/solutions/1811. Find Interview Candidates/1811.sql b/solutions/1811. Find Interview Candidates/1811.sql new file mode 100644 index 00000000000..296ca369eae --- /dev/null +++ b/solutions/1811. Find Interview Candidates/1811.sql @@ -0,0 +1,36 @@ +WITH + UserToContest AS ( + SELECT gold_medal AS user_id, contest_id FROM Contests + UNION ALL + SELECT silver_medal AS user_id, contest_id FROM Contests + UNION ALL + SELECT bronze_medal AS user_id, contest_id FROM Contests + ), + UserToContestWithGroupId AS ( + SELECT + user_id, + contest_id - ROW_NUMBER() OVER( + PARTITION BY user_id + ORDER BY contest_id + ) AS group_id + FROM UserToContest + ), + CandidateUserIds AS ( + -- consecutive medal winners + SELECT user_id + FROM UserToContestWithGroupId + GROUP BY user_id, group_id + HAVING COUNT(*) >= 3 + UNION DISTINCT + -- gold medal winners + SELECT gold_medal AS user_id + FROM Contests + GROUP BY user_id + HAVING COUNT(*) >= 3 + ) +SELECT + Users.name, + Users.mail +FROM CandidateUserIds +INNER JOIN Users + USING (user_id); diff --git a/solutions/1812. Determine Color of a Chessboard Square/1812.cpp b/solutions/1812. Determine Color of a Chessboard Square/1812.cpp new file mode 100644 index 00000000000..653f7b11c55 --- /dev/null +++ b/solutions/1812. Determine Color of a Chessboard Square/1812.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + bool squareIsWhite(string coordinates) { + const char letter = coordinates[0]; + const char digit = coordinates[1]; + return letter % 2 != digit % 2; + } +}; diff --git a/solutions/1812. Determine Color of a Chessboard Square/1812.java b/solutions/1812. Determine Color of a Chessboard Square/1812.java new file mode 100644 index 00000000000..0118028ba24 --- /dev/null +++ b/solutions/1812. Determine Color of a Chessboard Square/1812.java @@ -0,0 +1,7 @@ +class Solution { + public boolean squareIsWhite(String coordinates) { + final char letter = coordinates.charAt(0); + final char digit = coordinates.charAt(1); + return letter % 2 != digit % 2; + } +} diff --git a/solutions/1812. Determine Color of a Chessboard Square/1812.py b/solutions/1812. Determine Color of a Chessboard Square/1812.py new file mode 100644 index 00000000000..5306ea17cd0 --- /dev/null +++ b/solutions/1812. Determine Color of a Chessboard Square/1812.py @@ -0,0 +1,4 @@ +class Solution: + def squareIsWhite(self, coordinates: str) -> bool: + letter, digit = coordinates + return ord(letter) % 2 != int(digit) % 2 diff --git a/solutions/1813. Sentence Similarity III/1813.cpp b/solutions/1813. Sentence Similarity III/1813.cpp new file mode 100644 index 00000000000..e81c5eac76d --- /dev/null +++ b/solutions/1813. Sentence Similarity III/1813.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + bool areSentencesSimilar(string sentence1, string sentence2) { + if (sentence1.length() == sentence2.length()) + return sentence1 == sentence2; + + vector words1 = split(sentence1); + vector words2 = split(sentence2); + const int m = words1.size(); + const int n = words2.size(); + if (m > n) + return areSentencesSimilar(sentence2, sentence1); + + int i = 0; // words1's index + while (i < m && words1[i] == words2[i]) + ++i; + while (i < m && words1[i] == words2[i + n - m]) + ++i; + + return i == m; + } + + private: + vector split(const string& sentence) { + vector words; + istringstream iss(sentence); + + for (string s; iss >> s;) + words.push_back(s); + + return words; + } +}; diff --git a/solutions/1813. Sentence Similarity III/1813.java b/solutions/1813. Sentence Similarity III/1813.java new file mode 100644 index 00000000000..9c3528daed0 --- /dev/null +++ b/solutions/1813. Sentence Similarity III/1813.java @@ -0,0 +1,21 @@ +class Solution { + public boolean areSentencesSimilar(String sentence1, String sentence2) { + if (sentence1.length() == sentence2.length()) + return sentence1.equals(sentence2); + + String[] words1 = sentence1.split(" "); + String[] words2 = sentence2.split(" "); + final int m = words1.length; + final int n = words2.length; + if (m > n) + return areSentencesSimilar(sentence2, sentence1); + + int i = 0; // words1's index + while (i < m && words1[i].equals(words2[i])) + ++i; + while (i < m && words1[i].equals(words2[i + n - m])) + ++i; + + return i == m; + } +} diff --git a/solutions/1813. Sentence Similarity III/1813.py b/solutions/1813. Sentence Similarity III/1813.py new file mode 100644 index 00000000000..0f63b47a56f --- /dev/null +++ b/solutions/1813. Sentence Similarity III/1813.py @@ -0,0 +1,18 @@ +class Solution: + def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: + if len(sentence1) == len(sentence2): + return sentence1 == sentence2 + + words1 = sentence1.split() + words2 = sentence2.split() + m, n = map(len, (words1, words2)) + if m > n: + return self.areSentencesSimilar(sentence2, sentence1) + + i = 0 # words1's index + while i < m and words1[i] == words2[i]: + i += 1 + while i < m and words1[i] == words2[i + n - m]: + i += 1 + + return i == m diff --git a/solutions/1814. Count Nice Pairs in an Array/1814.cpp b/solutions/1814. Count Nice Pairs in an Array/1814.cpp new file mode 100644 index 00000000000..4e4ccb60896 --- /dev/null +++ b/solutions/1814. Count Nice Pairs in an Array/1814.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int countNicePairs(vector& nums) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + unordered_map count; + + for (const int num : nums) + ++count[num - rev(num)]; + + for (const auto& [_, freq] : count) { + ans += freq * (freq - 1) / 2; + ans %= kMod; + } + + return ans; + } + + private: + int rev(int n) { + int x = 0; + while (n) { + x = x * 10 + (n % 10); + n /= 10; + } + return x; + } +}; diff --git a/solutions/1814. Count Nice Pairs in an Array/1814.java b/solutions/1814. Count Nice Pairs in an Array/1814.java new file mode 100644 index 00000000000..55a052617a1 --- /dev/null +++ b/solutions/1814. Count Nice Pairs in an Array/1814.java @@ -0,0 +1,26 @@ +class Solution { + public int countNicePairs(int[] nums) { + final int kMod = 1_000_000_007; + long ans = 0; + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num - rev(num), 1L, Long::sum); + + for (final long freq : count.values()) { + ans += freq * (freq - 1) / 2; + ans %= kMod; + } + + return (int) ans; + } + + private int rev(int n) { + int x = 0; + while (n > 0) { + x = x * 10 + (n % 10); + n /= 10; + } + return x; + } +} diff --git a/solutions/1814. Count Nice Pairs in an Array/1814.py b/solutions/1814. Count Nice Pairs in an Array/1814.py new file mode 100644 index 00000000000..71dcf129e0e --- /dev/null +++ b/solutions/1814. Count Nice Pairs in an Array/1814.py @@ -0,0 +1,4 @@ +class Solution: + def countNicePairs(self, nums: List[int]) -> int: + freqs = collections.Counter(num - int(str(num)[::-1]) for num in nums) + return sum(freq * (freq - 1) // 2 for freq in freqs.values()) % 1000000007 diff --git a/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.cpp b/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.cpp new file mode 100644 index 00000000000..11fa2fae8b0 --- /dev/null +++ b/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int maxHappyGroups(int batchSize, vector& groups) { + int happy = 0; + vector freq(batchSize); + + for (int g : groups) { + g %= batchSize; + if (g == 0) { + ++happy; + } else if (freq[batchSize - g]) { + --freq[batchSize - g]; + ++happy; + } else { + ++freq[g]; + } + } + + return happy + dp(freq, 0, batchSize); + } + + private: + map, int> mem; + + // Returns the maximum number of partitions can be formed. + int dp(const vector& freq, int remainder, const int& batchSize) { + if (const auto it = mem.find(freq); it != mem.cend()) + return it->second; + + int ans = 0; + + if (ranges::any_of(freq, [](int f) { return f != 0; })) { + for (int i = 0; i < freq.size(); ++i) + if (freq[i]) { + vector newFreq(freq); + --newFreq[i]; + ans = max(ans, dp(newFreq, (remainder + i) % batchSize, batchSize)); + } + if (remainder == 0) + ++ans; + } + + return mem[freq] = ans; + } +}; diff --git a/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.java b/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.java new file mode 100644 index 00000000000..953a2751272 --- /dev/null +++ b/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.java @@ -0,0 +1,52 @@ +class Solution { + public int maxHappyGroups(int batchSize, int[] groups) { + int happy = 0; + int[] freq = new int[batchSize]; + + for (int g : groups) { + g %= batchSize; + if (g == 0) { + ++happy; + } else if (freq[batchSize - g] > 0) { + --freq[batchSize - g]; + ++happy; + } else { + ++freq[g]; + } + } + + return happy + dp(freq, 0, batchSize); + } + + private Map mem = new HashMap<>(); + + // Returns the maximum number of partitions can be formed. + private int dp(int[] freq, int remainder, int batchSize) { + final String hashed = hash(freq); + if (mem.containsKey(hashed)) + return mem.get(hashed); + + int ans = 0; + + if (Arrays.stream(freq).anyMatch(f -> f != 0)) { + for (int i = 0; i < freq.length; ++i) + if (freq[i] > 0) { + int[] newFreq = freq.clone(); + --newFreq[i]; + ans = Math.max(ans, dp(newFreq, (remainder + i) % batchSize, batchSize)); + } + if (remainder == 0) + ++ans; + } + + mem.put(hash(freq), ans); + return ans; + } + + private String hash(int[] freq) { + StringBuilder sb = new StringBuilder(); + for (final int f : freq) + sb.append("#").append(f); + return sb.toString(); + } +} diff --git a/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.py b/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.py new file mode 100644 index 00000000000..a566863743b --- /dev/null +++ b/solutions/1815. Maximum Number of Groups Getting Fresh Donuts/1815.py @@ -0,0 +1,29 @@ +class Solution: + def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: + happy = 0 + freq = [0] * batchSize + + for g in groups: + g %= batchSize + if g == 0: + happy += 1 + elif freq[batchSize - g]: + freq[batchSize - g] -= 1 + happy += 1 + else: + freq[g] += 1 + + @functools.lru_cache(None) + def dp(freq: int, remainder: int) -> int: + """Returns the maximum number of partitions can be formed.""" + ans = 0 + if any(freq): + for i, f in enumerate(freq): + if f: + ans = max(ans, dp(freq[:i] + (f - 1,) + + freq[i + 1:], (remainder + i) % batchSize)) + if remainder == 0: + ans += 1 + return ans + + return happy + dp(tuple(freq), 0) diff --git a/solutions/1816. Truncate Sentence/1816.cpp b/solutions/1816. Truncate Sentence/1816.cpp new file mode 100644 index 00000000000..c9759ec4c52 --- /dev/null +++ b/solutions/1816. Truncate Sentence/1816.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + string truncateSentence(string s, int k) { + for (int i = 0; i < s.length(); ++i) + if (s[i] == ' ' && --k == 0) + return s.substr(0, i); + return s; + } +}; diff --git a/solutions/1816. Truncate Sentence/1816.java b/solutions/1816. Truncate Sentence/1816.java new file mode 100644 index 00000000000..760d29d4cf0 --- /dev/null +++ b/solutions/1816. Truncate Sentence/1816.java @@ -0,0 +1,11 @@ +class Solution { + public String truncateSentence(String s, int k) { + String[] words = s.split(" "); + String[] truncated = new String[k]; + + for (int i = 0; i < k; ++i) + truncated[i] = words[i]; + + return String.join(" ", truncated); + } +} diff --git a/solutions/1816. Truncate Sentence/1816.py b/solutions/1816. Truncate Sentence/1816.py new file mode 100644 index 00000000000..6c5f267c546 --- /dev/null +++ b/solutions/1816. Truncate Sentence/1816.py @@ -0,0 +1,3 @@ +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + return ' '.join(s.split()[:k]) diff --git a/solutions/1817. Finding the Users Active Minutes/1817.cpp b/solutions/1817. Finding the Users Active Minutes/1817.cpp new file mode 100644 index 00000000000..bfe38a6591c --- /dev/null +++ b/solutions/1817. Finding the Users Active Minutes/1817.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector findingUsersActiveMinutes(vector>& logs, int k) { + vector ans(k); + unordered_map> idToTimes; + + for (const vector& log : logs) + idToTimes[log[0]].insert(log[1]); + + for (const auto& [_, mins] : idToTimes) + ++ans[mins.size() - 1]; + + return ans; + } +}; diff --git a/solutions/1817. Finding the Users Active Minutes/1817.java b/solutions/1817. Finding the Users Active Minutes/1817.java new file mode 100644 index 00000000000..b3e73d57625 --- /dev/null +++ b/solutions/1817. Finding the Users Active Minutes/1817.java @@ -0,0 +1,16 @@ +class Solution { + public int[] findingUsersActiveMinutes(int[][] logs, int k) { + int[] ans = new int[k]; + Map> idToTimes = new HashMap<>(); + + for (int[] log : logs) { + idToTimes.putIfAbsent(log[0], new HashSet<>()); + idToTimes.get(log[0]).add(log[1]); + } + + for (final int id : idToTimes.keySet()) + ++ans[idToTimes.get(id).size() - 1]; + + return ans; + } +} diff --git a/solutions/1817. Finding the Users Active Minutes/1817.py b/solutions/1817. Finding the Users Active Minutes/1817.py new file mode 100644 index 00000000000..3c2bc7673b0 --- /dev/null +++ b/solutions/1817. Finding the Users Active Minutes/1817.py @@ -0,0 +1,9 @@ +class Solution: + def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]: + idToTimes = collections.defaultdict(set) + + for id, time in logs: + idToTimes[id].add(time) + + c = collections.Counter(len(times) for times in idToTimes.values()) + return [c[i] for i in range(1, k + 1)] diff --git a/solutions/1818. Minimum Absolute Sum Difference/1818.cpp b/solutions/1818. Minimum Absolute Sum Difference/1818.cpp new file mode 100644 index 00000000000..b62c951f950 --- /dev/null +++ b/solutions/1818. Minimum Absolute Sum Difference/1818.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minAbsoluteSumDiff(vector& nums1, vector& nums2) { + constexpr int kMod = 1'000'000'007; + long sumDiff = 0; + long maxDecrement = 0; + set sorted(nums1.begin(), nums1.end()); + + for (int i = 0; i < nums1.size(); ++i) { + const long currDiff = abs(nums1[i] - nums2[i]); + sumDiff += currDiff; + const auto it = sorted.lower_bound(nums2[i]); + if (it != sorted.begin()) + maxDecrement = max(maxDecrement, currDiff - abs(*prev(it) - nums2[i])); + if (it != sorted.end()) + maxDecrement = max(maxDecrement, currDiff - abs(*it - nums2[i])); + } + + return (sumDiff - maxDecrement) % kMod; + } +}; diff --git a/solutions/1818. Minimum Absolute Sum Difference/1818.java b/solutions/1818. Minimum Absolute Sum Difference/1818.java new file mode 100644 index 00000000000..e6c645f7756 --- /dev/null +++ b/solutions/1818. Minimum Absolute Sum Difference/1818.java @@ -0,0 +1,24 @@ +class Solution { + public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { + final int kMod = 1_000_000_007; + long sumDiff = 0; + long maxDecrement = 0; + TreeSet sorted = new TreeSet<>(); + + for (final int num : nums1) + sorted.add(num); + + for (int i = 0; i < nums1.length; ++i) { + final long currDiff = (long) Math.abs(nums1[i] - nums2[i]); + sumDiff += currDiff; + Integer ceiling = sorted.ceiling(nums2[i]); + Integer floor = sorted.floor(nums2[i]); + if (ceiling != null) + maxDecrement = Math.max(maxDecrement, currDiff - (long) Math.abs(ceiling - nums2[i])); + if (floor != null) + maxDecrement = Math.max(maxDecrement, currDiff - (long) Math.abs(floor - nums2[i])); + } + + return (int) ((sumDiff - maxDecrement) % kMod); + } +} diff --git a/solutions/1818. Minimum Absolute Sum Difference/1818.py b/solutions/1818. Minimum Absolute Sum Difference/1818.py new file mode 100644 index 00000000000..ec76b669c75 --- /dev/null +++ b/solutions/1818. Minimum Absolute Sum Difference/1818.py @@ -0,0 +1,16 @@ +class Solution: + def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: + ans = math.inf + diffs = [abs(a - b) for a, b in zip(nums1, nums2)] + sumDiff = sum(diffs) + + nums1.sort() + + for num, diff in zip(nums2, diffs): + i = bisect.bisect_left(nums1, num) + if i > 0: + ans = min(ans, sumDiff - diff + abs(num - nums1[i - 1])) + if i < len(nums1): + ans = min(ans, sumDiff - diff + abs(num - nums1[i])) + + return ans % int(1e9 + 7) diff --git a/solutions/1819. Number of Different Subsequences GCDs/1819.cpp b/solutions/1819. Number of Different Subsequences GCDs/1819.cpp new file mode 100644 index 00000000000..4f14b4f4b47 --- /dev/null +++ b/solutions/1819. Number of Different Subsequences GCDs/1819.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int countDifferentSubsequenceGCDs(vector& nums) { + const int maxNum = ranges::max(nums); + int ans = 0; + // factor[i] := the GCD of numbers having factor i + vector factor(maxNum + 1); + + for (const int num : nums) + for (int i = 1; i * i <= num; ++i) + if (num % i == 0) { + const int j = num / i; + factor[i] = __gcd(factor[i], num); + factor[j] = __gcd(factor[j], num); + } + + for (int i = 1; i <= maxNum; ++i) + if (factor[i] == i) + ++ans; + + return ans; + } +}; diff --git a/solutions/1819. Number of Different Subsequences GCDs/1819.java b/solutions/1819. Number of Different Subsequences GCDs/1819.java new file mode 100644 index 00000000000..497ee80fdc1 --- /dev/null +++ b/solutions/1819. Number of Different Subsequences GCDs/1819.java @@ -0,0 +1,26 @@ +class Solution { + public int countDifferentSubsequenceGCDs(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + int ans = 0; + // factor[i] := the GCD of numbers having factor i + int[] factor = new int[maxNum + 1]; + + for (final int num : nums) + for (int i = 1; i * i <= num; ++i) + if (num % i == 0) { + final int j = num / i; + factor[i] = gcd(factor[i], num); + factor[j] = gcd(factor[j], num); + } + + for (int i = 1; i <= maxNum; ++i) + if (factor[i] == i) + ++ans; + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/182. Duplicate Emails/182.sql b/solutions/182. Duplicate Emails/182.sql new file mode 100644 index 00000000000..3b37192aa82 --- /dev/null +++ b/solutions/182. Duplicate Emails/182.sql @@ -0,0 +1,4 @@ +SELECT email +FROM Person +GROUP BY 1 +HAVING COUNT(*) > 1; diff --git a/solutions/1820. Maximum Number of Accepted Invitations/1820.cpp b/solutions/1820. Maximum Number of Accepted Invitations/1820.cpp new file mode 100644 index 00000000000..032ff2c4ffc --- /dev/null +++ b/solutions/1820. Maximum Number of Accepted Invitations/1820.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int maximumInvitations(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + vector mates(n, -1); // mates[i] := the i-th girl's mate + + for (int i = 0; i < m; ++i) + if (canInvite(grid, i, vector(n), mates)) + ++ans; + + return ans; + } + + private: + // Returns true if the i-th boy can make an invitation. + bool canInvite(const vector>& grid, int i, vector&& seen, + vector& mates) { + // The i-th boy asks each girl. + for (int j = 0; j < seen.size(); ++j) { + if (!grid[i][j] || seen[j]) + continue; + seen[j] = true; + if (mates[j] == -1 || canInvite(grid, mates[j], move(seen), mates)) { + mates[j] = i; // Match the j-th girl with i-th boy. + return true; + } + } + + return false; + } +}; diff --git a/solutions/1820. Maximum Number of Accepted Invitations/1820.java b/solutions/1820. Maximum Number of Accepted Invitations/1820.java new file mode 100644 index 00000000000..47a4e1ee5a4 --- /dev/null +++ b/solutions/1820. Maximum Number of Accepted Invitations/1820.java @@ -0,0 +1,32 @@ +class Solution { + public int maximumInvitations(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + int[] mates = new int[n]; // mates[i] := the i-th girl's mate + + Arrays.fill(mates, -1); + + for (int i = 0; i < m; ++i) + if (canInvite(grid, i, new boolean[n], mates)) + ++ans; + + return ans; + } + + // Returns true if the i-th boy can make an invitation. + private boolean canInvite(int[][] grid, int i, boolean[] seen, int[] mates) { + // The i-th boy asks each girl. + for (int j = 0; j < seen.length; ++j) { + if (grid[i][j] == 0 || seen[j]) + continue; + seen[j] = true; + if (mates[j] == -1 || canInvite(grid, mates[j], seen, mates)) { + mates[j] = i; // Match the j-th girl with i-th boy. + return true; + } + } + + return false; + } +} diff --git a/solutions/1820. Maximum Number of Accepted Invitations/1820.py b/solutions/1820. Maximum Number of Accepted Invitations/1820.py new file mode 100644 index 00000000000..c29e2751014 --- /dev/null +++ b/solutions/1820. Maximum Number of Accepted Invitations/1820.py @@ -0,0 +1,25 @@ +class Solution: + def maximumInvitations(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + ans = 0 + mates = [-1] * n # mates[i] := the i-th girl's mate + + def canInvite(i: int, seen: List[bool]) -> bool: + """Returns True if the i-th boy can make an invitation.""" + # The i-th boy asks each girl. + for j in range(n): + if not grid[i][j] or seen[j]: + continue + seen[j] = True + if mates[j] == -1 or canInvite(mates[j], seen): + mates[j] = i # Match the j-th girl with i-th boy. + return True + return False + + for i in range(m): + seen = [False] * n + if canInvite(i, seen): + ans += 1 + + return ans diff --git a/solutions/1821. Find Customers With Positive Revenue this Year/1821.sql b/solutions/1821. Find Customers With Positive Revenue this Year/1821.sql new file mode 100644 index 00000000000..be28bac2568 --- /dev/null +++ b/solutions/1821. Find Customers With Positive Revenue this Year/1821.sql @@ -0,0 +1,3 @@ +SELECT DISTINCT customer_id +FROM Customers +WHERE year = 2021 AND revenue > 0; diff --git a/solutions/1822. Sign of the Product of an Array/1822.cpp b/solutions/1822. Sign of the Product of an Array/1822.cpp new file mode 100644 index 00000000000..7adbb33e1d5 --- /dev/null +++ b/solutions/1822. Sign of the Product of an Array/1822.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int arraySign(vector& nums) { + int sign = 1; + + for (const int num : nums) { + if (num == 0) + return 0; + if (num < 0) + sign = -sign; + } + + return sign; + } +}; diff --git a/solutions/1822. Sign of the Product of an Array/1822.java b/solutions/1822. Sign of the Product of an Array/1822.java new file mode 100644 index 00000000000..c7344d4346e --- /dev/null +++ b/solutions/1822. Sign of the Product of an Array/1822.java @@ -0,0 +1,14 @@ +class Solution { + public int arraySign(int[] nums) { + int sign = 1; + + for (final int num : nums) { + if (num == 0) + return 0; + if (num < 0) + sign = -sign; + } + + return sign; + } +} diff --git a/solutions/1822. Sign of the Product of an Array/1822.py b/solutions/1822. Sign of the Product of an Array/1822.py new file mode 100644 index 00000000000..33bc2af1382 --- /dev/null +++ b/solutions/1822. Sign of the Product of an Array/1822.py @@ -0,0 +1,11 @@ +class Solution: + def arraySign(self, nums: List[int]) -> int: + sign = 1 + + for num in nums: + if num == 0: + return 0 + if num < 0: + sign = -sign + + return sign diff --git a/solutions/1823. Find the Winner of the Circular Game/1823-2.cpp b/solutions/1823. Find the Winner of the Circular Game/1823-2.cpp new file mode 100644 index 00000000000..73a5c7641eb --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int findTheWinner(int n, int k) { + // Converts back to 1-indexed. + return f(n, k) + 1; + } + + // e.g. n = 4, k = 2. + // By using 0-indexed notation, we have the following circle: + // + // 0 -> 1 -> 2 -> 3 -> 0 + // x + // 0 -> 1 -> 2 -> 0 + // + // After the first round, 1 is removed. + // So, 2 becomes 0, 3 becomes 1, and 0 becomes 2. + // Let's denote that oldIndex = f(n, k) and newIndex = f(n - 1, k). + // By observation, we know f(n, k) = (f(n - 1, k) + k) % n. + private: + int f(int n, int k) { + if (n == 1) + return 0; + return (f(n - 1, k) + k) % n; + } +}; diff --git a/solutions/1823. Find the Winner of the Circular Game/1823-2.java b/solutions/1823. Find the Winner of the Circular Game/1823-2.java new file mode 100644 index 00000000000..9aa4170855d --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823-2.java @@ -0,0 +1,23 @@ +class Solution { + public int findTheWinner(int n, int k) { + // Converts back to 1-indexed. + return f(n, k) + 1; + } + + // e.g. n = 4, k = 2. + // By using 0-indexed notation, we have the following circle: + // + // 0 -> 1 -> 2 -> 3 -> 0 + // x + // 0 -> 1 -> 2 -> 0 + // + // After the first round, 1 is removed. + // So, 2 becomes 0, 3 becomes 1, and 0 becomes 2. + // Let's denote that oldIndex = f(n, k) and newIndex = f(n - 1, k). + // By observation, we know f(n, k) = (f(n - 1, k) + k) % n. + private int f(int n, int k) { + if (n == 1) + return 0; + return (f(n - 1, k) + k) % n; + } +} diff --git a/solutions/1823. Find the Winner of the Circular Game/1823-2.py b/solutions/1823. Find the Winner of the Circular Game/1823-2.py new file mode 100644 index 00000000000..94b4ebbc69e --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823-2.py @@ -0,0 +1,20 @@ +class Solution: + def findTheWinner(self, n: int, k: int) -> int: + # e.g. n = 4, k = 2. + # By using 0-indexed notation, we have the following circle: + # + # 0 -> 1 -> 2 -> 3 -> 0 + # x + # 0 -> 1 -> 2 -> 0 + # + # After the first round, 1 is removed. + # So, 2 becomes 0, 3 becomes 1, and 0 becomes 2. + # Let's denote that oldIndex = f(n, k) and newIndex = f(n - 1, k). + # By observation, we know f(n, k) = (f(n - 1, k) + k) % n. + def f(n: int, k: int) -> int: + if n == 1: + return 0 + return (f(n - 1, k) + k) % n + + # Converts back to 1-indexed. + return f(n, k) + 1 diff --git a/solutions/1823. Find the Winner of the Circular Game/1823-3.cpp b/solutions/1823. Find the Winner of the Circular Game/1823-3.cpp new file mode 100644 index 00000000000..6d647a91bd1 --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823-3.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int findTheWinner(int n, int k) { + // Converts back to 1-indexed. + return f(n, k) + 1; + } + + // e.g. n = 4, k = 2. + // By using 0-indexed notation, we have the following circle: + // + // 0 -> 1 -> 2 -> 3 -> 0 + // x + // 0 -> 1 -> 2 -> 0 + // + // After the first round, 1 is removed. + // So, 2 becomes 0, 3 becomes 1, and 0 becomes 2. + // Let's denote that oldIndex = f(n, k) and newIndex = f(n - 1, k). + // By observation, we know f(n, k) = (f(n - 1, k) + k) % n. + private: + int f(int n, int k) { + int ans = 0; // f(1, k) + // Computes f(i, k) based on f(i - 1, k). + for (int i = 2; i <= n; ++i) + ans = (ans + k) % i; + return ans; + } +}; diff --git a/solutions/1823. Find the Winner of the Circular Game/1823-3.java b/solutions/1823. Find the Winner of the Circular Game/1823-3.java new file mode 100644 index 00000000000..99e3c7dbcd1 --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823-3.java @@ -0,0 +1,25 @@ +class Solution { + public int findTheWinner(int n, int k) { + // Converts back to 1-indexed. + return f(n, k) + 1; + } + + // e.g. n = 4, k = 2. + // By using 0-indexed notation, we have the following circle: + // + // 0 -> 1 -> 2 -> 3 -> 0 + // x + // 0 -> 1 -> 2 -> 0 + // + // After the first round, 1 is removed. + // So, 2 becomes 0, 3 becomes 1, and 0 becomes 2. + // Let's denote that oldIndex = f(n, k) and newIndex = f(n - 1, k). + // By observation, we know f(n, k) = (f(n - 1, k) + k) % n. + private int f(int n, int k) { + int ans = 0; // f(1, k) + // Computes f(i, k) based on f(i - 1, k). + for (int i = 2; i <= n; ++i) + ans = (ans + k) % i; + return ans; + } +} diff --git a/solutions/1823. Find the Winner of the Circular Game/1823-3.py b/solutions/1823. Find the Winner of the Circular Game/1823-3.py new file mode 100644 index 00000000000..0d2184d6e18 --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823-3.py @@ -0,0 +1,22 @@ +class Solution: + def findTheWinner(self, n: int, k: int) -> int: + # e.g. n = 4, k = 2. + # By using 0-indexed notation, we have the following circle: + # + # 0 -> 1 -> 2 -> 3 -> 0 + # x + # 0 -> 1 -> 2 -> 0 + # + # After the first round, 1 is removed. + # So, 2 becomes 0, 3 becomes 1, and 0 becomes 2. + # Let's denote that oldIndex = f(n, k) and newIndex = f(n - 1, k). + # By observation, we know f(n, k) = (f(n - 1, k) + k) % n. + def f(n: int, k: int) -> int: + ans = 0 # f(1, k) + # Computes f(i, k) based on f(i - 1, k). + for i in range(2, n + 1): + ans = (ans + k) % i + return ans + + # Converts back to 1-indexed. + return f(n, k) + 1 diff --git a/solutions/1823. Find the Winner of the Circular Game/1823.cpp b/solutions/1823. Find the Winner of the Circular Game/1823.cpp new file mode 100644 index 00000000000..0e947e163b9 --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int findTheWinner(int n, int k) { + // friends[i] := true if i-th friend is left + vector friends(n); + + int friendCount = n; + int fp = 0; // friends' index + + while (friendCount > 1) { + for (int i = 0; i < k; ++i, ++fp) + while (friends[fp % n]) // The friend is not there. + ++fp; // Point to the next one. + friends[(fp - 1) % n] = true; + --friendCount; + } + + const auto it = + find_if(friends.begin(), friends.end(), [](int f) { return !f; }); + return distance(friends.begin(), it) + 1; + } +}; diff --git a/solutions/1823. Find the Winner of the Circular Game/1823.java b/solutions/1823. Find the Winner of the Circular Game/1823.java new file mode 100644 index 00000000000..be657bf902f --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823.java @@ -0,0 +1,21 @@ +class Solution { + public int findTheWinner(int n, int k) { + // friends[i] := true if i-th friend is left + boolean[] friends = new boolean[n]; + + int friendCount = n; + int fp = n; // friends' index + + while (friendCount > 1) { + for (int i = 0; i < k; ++i, ++fp) + while (friends[fp % n]) // The friend is not there. + ++fp; // Point to the next one. + friends[(fp - 1) % n] = true; + --friendCount; + } + + for (fp = 0; friends[fp]; ++fp) + ; + return fp + 1; + } +} diff --git a/solutions/1823. Find the Winner of the Circular Game/1823.py b/solutions/1823. Find the Winner of the Circular Game/1823.py new file mode 100644 index 00000000000..da94d7d979e --- /dev/null +++ b/solutions/1823. Find the Winner of the Circular Game/1823.py @@ -0,0 +1,21 @@ +class Solution: + def findTheWinner(self, n: int, k: int) -> int: + # True if i-th friend is left + friends = [False] * n + + friendCount = n + fp = 0 # friends' index + + while friendCount > 1: + for _ in range(k): + while friends[fp % n]: # The friend is not there. + fp += 1 # Point to the next one. + fp += 1 + friends[(fp - 1) % n] = True + friendCount -= 1 + + fp = 0 + while friends[fp]: + fp += 1 + + return fp + 1 diff --git a/solutions/1824. Minimum Sideway Jumps/1824.cpp b/solutions/1824. Minimum Sideway Jumps/1824.cpp new file mode 100644 index 00000000000..2f91ff6b5fc --- /dev/null +++ b/solutions/1824. Minimum Sideway Jumps/1824.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minSideJumps(vector& obstacles) { + constexpr int kInf = 1e6; + // dp[i] := the minimum jump to reach the i-th lane + vector dp{kInf, 1, 0, 1}; + + for (const int obstacle : obstacles) { + if (obstacle > 0) + dp[obstacle] = kInf; + for (int i = 1; i <= 3; ++i) // the current + if (i != obstacle) + for (int j = 1; j <= 3; ++j) // the previous + dp[i] = min({dp[i], dp[j] + (i == j ? 0 : 1)}); + } + + return ranges::min(dp); + } +}; diff --git a/solutions/1824. Minimum Sideway Jumps/1824.java b/solutions/1824. Minimum Sideway Jumps/1824.java new file mode 100644 index 00000000000..c137a8279fa --- /dev/null +++ b/solutions/1824. Minimum Sideway Jumps/1824.java @@ -0,0 +1,18 @@ +class Solution { + public int minSideJumps(int[] obstacles) { + final int kInf = (int) 1e6; + // dp[i] := the minimum jump to reach the i-th lane + int[] dp = {kInf, 1, 0, 1}; + + for (final int obstacle : obstacles) { + if (obstacle > 0) + dp[obstacle] = kInf; + for (int i = 1; i <= 3; ++i) // the current + if (i != obstacle) + for (int j = 1; j <= 3; ++j) // the previous + dp[i] = Math.min(dp[i], dp[j] + (i == j ? 0 : 1)); + } + + return Arrays.stream(dp).min().getAsInt(); + } +} diff --git a/solutions/1824. Minimum Sideway Jumps/1824.py b/solutions/1824. Minimum Sideway Jumps/1824.py new file mode 100644 index 00000000000..764cb6eaf1c --- /dev/null +++ b/solutions/1824. Minimum Sideway Jumps/1824.py @@ -0,0 +1,16 @@ +class Solution: + def minSideJumps(self, obstacles: List[int]) -> int: + kInf = 1e6 + # dp[i] := the minimum jump to reach the i-th lane + dp = [kInf, 1, 0, 1] + + for obstacle in obstacles: + print(dp) + if obstacle > 0: + dp[obstacle] = kInf + for i in range(1, 4): # the current + if i != obstacle: + for j in range(1, 4): # the previous + dp[i] = min(dp[i], dp[j] + (0 if i == j else 1)) + + return min(dp) diff --git a/solutions/1825. Finding MK Average/1825-2.cpp b/solutions/1825. Finding MK Average/1825-2.cpp new file mode 100644 index 00000000000..59d2a547ee0 --- /dev/null +++ b/solutions/1825. Finding MK Average/1825-2.cpp @@ -0,0 +1,70 @@ +struct MyMap { + map map; + int size = 0; + long sum = 0; +}; + +class MKAverage { + public: + MKAverage(int m, int k) : m(m), k(k), kMidSize(m - 2 * k) {} + + void addElement(int num) { + q.push(num); + add(num); + + if (q.size() > m) { + const int removed = q.front(); + q.pop(); + remove(removed); + } + } + + int calculateMKAverage() { + return q.size() == m ? mid.sum / kMidSize : -1; + } + + private: + const int m; + const int k; + const int kMidSize; + queue q; + MyMap top; + MyMap mid; + MyMap bot; + + void add(int num) { + add(bot, num); + if (bot.size > k) + add(mid, remove(bot, bot.map.rbegin()->first)); + if (mid.size > kMidSize) + add(top, remove(mid, mid.map.rbegin()->first)); + } + + void remove(int num) { + if (bot.map.contains(num)) + remove(bot, num); + else if (mid.map.contains(num)) + remove(mid, num); + else + remove(top, num); + + if (bot.size < k) + add(bot, remove(mid, mid.map.begin()->first)); + if (mid.size < kMidSize) + add(mid, remove(top, top.map.begin()->first)); + } + + void add(MyMap& m, int num) { + ++m.map[num]; + ++m.size; + m.sum += num; + } + + int remove(MyMap& m, int num) { + if (--m.map[num] == 0) + m.map.erase(num); + --m.size; + m.sum -= num; + return num; + } +}; diff --git a/solutions/1825. Finding MK Average/1825-2.java b/solutions/1825. Finding MK Average/1825-2.java new file mode 100644 index 00000000000..4bdd5c8f022 --- /dev/null +++ b/solutions/1825. Finding MK Average/1825-2.java @@ -0,0 +1,70 @@ +class MyMap { + public TreeMap map = new TreeMap<>(); + public int size = 0; + public long sum = 0; +} + +class MKAverage { + public MKAverage(int m, int k) { + this.m = m; + this.k = k; + this.kMidSize = m - 2 * k; + } + + public void addElement(int num) { + q.offer(num); + add(num); + + if (q.size() > m) + remove(q.poll()); + } + + public int calculateMKAverage() { + return q.size() == m ? (int) (mid.sum / kMidSize) : -1; + } + + private final int m; + private final int k; + private final int kMidSize; + private Queue q = new ArrayDeque<>(); + private MyMap bot = new MyMap(); + private MyMap mid = new MyMap(); + private MyMap top = new MyMap(); + + private void add(int num) { + add(bot, num); + if (bot.size > k) + add(mid, remove(bot, bot.map.lastKey())); + if (mid.size > kMidSize) + add(top, remove(mid, mid.map.lastKey())); + } + + private void remove(int num) { + if (bot.map.containsKey(num)) + remove(bot, num); + else if (mid.map.containsKey(num)) + remove(mid, num); + else + remove(top, num); + + if (bot.size < k) + add(bot, remove(mid, mid.map.firstKey())); + if (mid.size < kMidSize) + add(mid, remove(top, top.map.firstKey())); + } + + private void add(MyMap m, int num) { + m.map.merge(num, 1, Integer::sum); + ++m.size; + m.sum += num; + } + + private int remove(MyMap m, int num) { + m.map.merge(num, -1, Integer::sum); + if (m.map.get(num) == 0) + m.map.remove(num); + --m.size; + m.sum -= num; + return num; + } +} diff --git a/solutions/1825. Finding MK Average/1825.cpp b/solutions/1825. Finding MK Average/1825.cpp new file mode 100644 index 00000000000..f387ac48337 --- /dev/null +++ b/solutions/1825. Finding MK Average/1825.cpp @@ -0,0 +1,80 @@ +class MKAverage { + public: + MKAverage(int m, int k) : m(m), k(k) {} + + void addElement(int num) { + q.push(num); + add(mid, num); + midSum += num; + + if (q.size() > m) { + const int removed = q.front(); + q.pop(); + if (top.contains(removed)) { + remove(top, removed); + --topSize; + } else if (mid.contains(removed)) { + remove(mid, removed); + midSum -= removed; + } else { + remove(bot, removed); + --botSize; + } + } + + // Move item(s) from `mid` to `top` to fill k slots. + while (!mid.empty() && topSize < k) { + midSum -= mid.rbegin()->first; + add(top, remove(mid, mid.rbegin()->first)); + ++topSize; + } + + // Rebalance `mid` and `top`. + while (!mid.empty() && mid.rbegin()->first > top.begin()->first) { + midSum -= mid.rbegin()->first; + midSum += top.begin()->first; + add(top, remove(mid, mid.rbegin()->first)); + add(mid, remove(top, top.begin()->first)); + } + + // Move item(s) from `mid` to `bot` to fill k slots. + while (!mid.empty() && botSize < k) { + midSum -= mid.begin()->first; + add(bot, remove(mid, mid.begin()->first)); + ++botSize; + } + + // Move item(s) from `mid` to `bot` to fill k slots. + while (!mid.empty() && mid.begin()->first < bot.rbegin()->first) { + midSum -= mid.begin()->first; + midSum += bot.rbegin()->first; + add(bot, remove(mid, mid.begin()->first)); + add(mid, remove(bot, bot.rbegin()->first)); + } + } + + int calculateMKAverage() { + return q.size() == m ? midSum / (m - 2 * k) : -1; + } + + private: + const int m; + const int k; + queue q; + map top; + map mid; + map bot; + int topSize = 0; + int botSize = 0; + long midSum = 0; + + void add(map& map, int num) { + ++map[num]; + } + + int remove(map& map, int num) { + if (--map[num] == 0) + map.erase(num); + return num; + } +}; diff --git a/solutions/1825. Finding MK Average/1825.java b/solutions/1825. Finding MK Average/1825.java new file mode 100644 index 00000000000..d7432230c23 --- /dev/null +++ b/solutions/1825. Finding MK Average/1825.java @@ -0,0 +1,81 @@ +class MKAverage { + public MKAverage(int m, int k) { + this.m = m; + this.k = k; + } + + public void addElement(int num) { + q.offer(num); + add(mid, num); + midSum += num; + + if (q.size() > m) { + final int removed = q.poll(); + if (top.containsKey(removed)) { + remove(top, removed); + --topSize; + } else if (mid.containsKey(removed)) { + remove(mid, removed); + midSum -= removed; + } else { + remove(bot, removed); + --botSize; + } + } + + // Move item(s) from `mid` to `top` to fill k slots. + while (!mid.isEmpty() && topSize < k) { + midSum -= mid.lastKey(); + add(top, remove(mid, mid.lastKey())); + ++topSize; + } + + // Rebalance `mid` and `top`. + while (!mid.isEmpty() && mid.lastKey() > top.firstKey()) { + midSum -= mid.lastKey(); + midSum += top.firstKey(); + add(top, remove(mid, mid.lastKey())); + add(mid, remove(top, top.firstKey())); + } + + // Move item(s) from `mid` to `bot` to fill k slots. + while (!mid.isEmpty() && botSize < k) { + midSum -= mid.firstKey(); + add(bot, remove(mid, mid.firstKey())); + ++botSize; + } + + // Rebalance mid and bot + while (!mid.isEmpty() && mid.firstKey() < bot.lastKey()) { + midSum -= mid.firstKey(); + midSum += bot.lastKey(); + add(bot, remove(mid, mid.firstKey())); + add(mid, remove(bot, bot.lastKey())); + } + } + + public int calculateMKAverage() { + return q.size() == m ? (int) (midSum / (m - 2 * k)) : -1; + } + + private final int m; + private final int k; + private Queue q = new ArrayDeque<>(); + private TreeMap top = new TreeMap<>(); + private TreeMap mid = new TreeMap<>(); + private TreeMap bot = new TreeMap<>(); + private int topSize = 0; + private int botSize = 0; + private long midSum = 0; + + private void add(TreeMap map, int num) { + map.merge(num, 1, Integer::sum); + } + + private int remove(TreeMap map, int num) { + map.put(num, map.get(num) - 1); + if (map.get(num) == 0) + map.remove(num); + return num; + } +} diff --git a/solutions/1826. Faulty Sensor/1826.cpp b/solutions/1826. Faulty Sensor/1826.cpp new file mode 100644 index 00000000000..ec169261a28 --- /dev/null +++ b/solutions/1826. Faulty Sensor/1826.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int badSensor(vector& sensor1, vector& sensor2) { + const bool oneDefect = canReplace(sensor2, sensor1); + const bool twoDefect = canReplace(sensor1, sensor2); + if (oneDefect && twoDefect) + return -1; + if (!oneDefect && !twoDefect) + return -1; + return oneDefect ? 1 : 2; + } + + private: + bool canReplace(const vector& A, const vector& B) { + int i = 0; // A's index + int j = 0; // B's index + int droppedValue = -1; + + while (i < A.size()) + if (A[i] == B[j]) { + ++i; + ++j; + } else { + droppedValue = A[i]; + ++i; + } + + return j == B.size() - 1 && B[j] != droppedValue; + } +}; diff --git a/solutions/1826. Faulty Sensor/1826.java b/solutions/1826. Faulty Sensor/1826.java new file mode 100644 index 00000000000..277ce90b965 --- /dev/null +++ b/solutions/1826. Faulty Sensor/1826.java @@ -0,0 +1,28 @@ +class Solution { + public int badSensor(int[] sensor1, int[] sensor2) { + final boolean oneDefect = canReplace(sensor2, sensor1); + final boolean twoDefect = canReplace(sensor1, sensor2); + if (oneDefect && twoDefect) + return -1; + if (!oneDefect && !twoDefect) + return -1; + return oneDefect ? 1 : 2; + } + + private boolean canReplace(int[] A, int[] B) { + int i = 0; // A's index + int j = 0; // B's index + int droppedValue = -1; + + while (i < A.length) + if (A[i] == B[j]) { + ++i; + ++j; + } else { + droppedValue = A[i]; + ++i; + } + + return j == B.length - 1 && B[j] != droppedValue; + } +} diff --git a/solutions/1826. Faulty Sensor/1826.py b/solutions/1826. Faulty Sensor/1826.py new file mode 100644 index 00000000000..e0708fb4147 --- /dev/null +++ b/solutions/1826. Faulty Sensor/1826.py @@ -0,0 +1,25 @@ +class Solution: + def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int: + # A -> B, so B is defect + def canReplace(A, B): + i = 0 # A's index + j = 0 # B's index + droppedValue = -1 + + while i < len(A): + if A[i] == B[j]: + i += 1 + j += 1 + else: + droppedValue = A[i] + i += 1 + + return j == len(B) - 1 and B[-1] != droppedValue + + oneDefect = canReplace(sensor2, sensor1) + twoDefect = canReplace(sensor1, sensor2) + if oneDefect and twoDefect: + return -1 + if not oneDefect and not twoDefect: + return -1 + return 1 if oneDefect else 2 diff --git a/solutions/1827. Minimum Operations to Make the Array Increasing/1827.cpp b/solutions/1827. Minimum Operations to Make the Array Increasing/1827.cpp new file mode 100644 index 00000000000..9ee020680ab --- /dev/null +++ b/solutions/1827. Minimum Operations to Make the Array Increasing/1827.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minOperations(vector& nums) { + int ans = 0; + int last = 0; + + for (const int num : nums) { + ans += max(0, last - num + 1); + last = max(num, last + 1); + } + + return ans; + } +}; diff --git a/solutions/1827. Minimum Operations to Make the Array Increasing/1827.java b/solutions/1827. Minimum Operations to Make the Array Increasing/1827.java new file mode 100644 index 00000000000..2b22c75bf99 --- /dev/null +++ b/solutions/1827. Minimum Operations to Make the Array Increasing/1827.java @@ -0,0 +1,13 @@ +class Solution { + public int minOperations(int[] nums) { + int ans = 0; + int last = 0; + + for (final int num : nums) { + ans += Math.max(0, last - num + 1); + last = Math.max(num, last + 1); + } + + return ans; + } +} diff --git a/solutions/1827. Minimum Operations to Make the Array Increasing/1827.py b/solutions/1827. Minimum Operations to Make the Array Increasing/1827.py new file mode 100644 index 00000000000..fd99b96950b --- /dev/null +++ b/solutions/1827. Minimum Operations to Make the Array Increasing/1827.py @@ -0,0 +1,10 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + ans = 0 + last = 0 + + for num in nums: + ans += max(0, last - num + 1) + last = max(num, last + 1) + + return ans diff --git a/solutions/1828. Queries on Number of Points Inside a Circle/1828.cpp b/solutions/1828. Queries on Number of Points Inside a Circle/1828.cpp new file mode 100644 index 00000000000..6757174b21f --- /dev/null +++ b/solutions/1828. Queries on Number of Points Inside a Circle/1828.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector countPoints(vector>& points, + vector>& queries) { + vector ans; + + for (const vector& query : queries) { + const int xj = query[0]; + const int yj = query[1]; + const int rj = query[2]; + int count = 0; + for (const vector& point : points) { + const int xi = point[0]; + const int yi = point[1]; + if (squared(xi - xj) + squared(yi - yj) <= squared(rj)) + ++count; + } + ans.push_back(count); + } + + return ans; + } + + private: + int squared(int x) { + return x * x; + } +}; diff --git a/solutions/1828. Queries on Number of Points Inside a Circle/1828.java b/solutions/1828. Queries on Number of Points Inside a Circle/1828.java new file mode 100644 index 00000000000..309012a4bf7 --- /dev/null +++ b/solutions/1828. Queries on Number of Points Inside a Circle/1828.java @@ -0,0 +1,25 @@ +class Solution { + public int[] countPoints(int[][] points, int[][] queries) { + int[] ans = new int[queries.length]; + + for (int i = 0; i < queries.length; ++i) { + final int xj = queries[i][0]; + final int yj = queries[i][1]; + final int rj = queries[i][2]; + int count = 0; + for (int[] point : points) { + final int xi = point[0]; + final int yi = point[1]; + if (squared(xi - xj) + squared(yi - yj) <= squared(rj)) + ++count; + } + ans[i] = count; + } + + return ans; + } + + private int squared(int x) { + return x * x; + } +} diff --git a/solutions/1828. Queries on Number of Points Inside a Circle/1828.py b/solutions/1828. Queries on Number of Points Inside a Circle/1828.py new file mode 100644 index 00000000000..2070de3ee4c --- /dev/null +++ b/solutions/1828. Queries on Number of Points Inside a Circle/1828.py @@ -0,0 +1,12 @@ +class Solution: + def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]: + ans = [] + + for xj, yj, rj in queries: + count = 0 + for xi, yi in points: + if (xi - xj)**2 + (yi - yj)**2 <= rj**2: + count += 1 + ans.append(count) + + return ans diff --git a/solutions/1829. Maximum XOR for Each Query/1829.cpp b/solutions/1829. Maximum XOR for Each Query/1829.cpp new file mode 100644 index 00000000000..a0a9018d2cc --- /dev/null +++ b/solutions/1829. Maximum XOR for Each Query/1829.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector getMaximumXor(vector& nums, int maximumBit) { + const int mx = (1 << maximumBit) - 1; + vector ans; + int xors = 0; + + for (const int num : nums) { + xors ^= num; + ans.push_back(xors ^ mx); + } + + reverse(ans.begin(), ans.end()); + return ans; + } +}; diff --git a/solutions/1829. Maximum XOR for Each Query/1829.java b/solutions/1829. Maximum XOR for Each Query/1829.java new file mode 100644 index 00000000000..755d322d88f --- /dev/null +++ b/solutions/1829. Maximum XOR for Each Query/1829.java @@ -0,0 +1,15 @@ +class Solution { + public int[] getMaximumXor(int[] nums, int maximumBit) { + final int n = nums.length; + final int mx = (1 << maximumBit) - 1; + int[] ans = new int[n]; + int xors = 0; + + for (int i = 0; i < n; ++i) { + xors ^= nums[i]; + ans[n - 1 - i] = xors ^ mx; + } + + return ans; + } +} diff --git a/solutions/1829. Maximum XOR for Each Query/1829.py b/solutions/1829. Maximum XOR for Each Query/1829.py new file mode 100644 index 00000000000..1e5dac39ec5 --- /dev/null +++ b/solutions/1829. Maximum XOR for Each Query/1829.py @@ -0,0 +1,11 @@ +class Solution: + def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: + mx = (1 << maximumBit) - 1 + ans = [] + xors = 0 + + for num in nums: + xors ^= num + ans.append(xors ^ mx) + + return ans[::-1] diff --git a/solutions/183. Customers Who Never Order/183.sql b/solutions/183. Customers Who Never Order/183.sql new file mode 100644 index 00000000000..2abf86989ff --- /dev/null +++ b/solutions/183. Customers Who Never Order/183.sql @@ -0,0 +1,5 @@ +SELECT Customers.name AS Customers +FROM Customers +LEFT JOIN Orders + ON (Customers.id = Orders.customerId) +WHERE Orders.id IS NULL; diff --git a/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.cpp b/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.cpp new file mode 100644 index 00000000000..90d6c8de9ef --- /dev/null +++ b/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int makeStringSorted(string s) { + const int n = s.length(); + const auto [fact, invFact] = getFactAndInvFact(n); + int ans = 0; + vector count(26); + + for (int i = n - 1; i >= 0; --i) { + const int order = s[i] - 'a'; + ++count[order]; + long perm = accumulate(count.begin(), count.begin() + order, 0) * + fact[n - 1 - i] % kMod; + for (int j = 0; j < 26; ++j) + perm = perm * invFact[count[j]] % kMod; + ans = (ans + perm) % kMod; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + pair, vector> getFactAndInvFact(int n) { + vector fact(n + 1); + vector invFact(n + 1); + vector inv(n + 1); + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return {fact, invFact}; + } +}; diff --git a/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.java b/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.java new file mode 100644 index 00000000000..113a48e9aab --- /dev/null +++ b/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.java @@ -0,0 +1,40 @@ +class Solution { + public int makeStringSorted(String s) { + final int kMod = 1_000_000_007; + final int n = s.length(); + final long[][] factAndInvFact = getFactAndInvFact(n); + final long[] fact = factAndInvFact[0]; + final long[] invFact = factAndInvFact[1]; + int ans = 0; + int[] count = new int[26]; + + for (int i = n - 1; i >= 0; --i) { + final int order = s.charAt(i) - 'a'; + ++count[order]; + long perm = Arrays.stream(count, 0, order).sum() * fact[n - 1 - i] % kMod; + for (int j = 0; j < 26; ++j) + perm = perm * invFact[count[j]] % kMod; + ans += perm; + ans %= kMod; + } + + return ans; + } + + private static final int kMod = 1_000_000_007; + + private long[][] getFactAndInvFact(int n) { + long[] fact = new long[n + 1]; + long[] invFact = new long[n + 1]; + long[] inv = new long[n + 1]; + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return new long[][] {fact, invFact}; + } +} diff --git a/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.py b/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.py new file mode 100644 index 00000000000..fea69132366 --- /dev/null +++ b/solutions/1830. Minimum Number of Operations to Make String Sorted/1830.py @@ -0,0 +1,25 @@ +class Solution: + def makeStringSorted(self, s: str) -> int: + kMod = 1_000_000_007 + ans = 0 + count = [0] * 26 + + @functools.lru_cache(None) + def fact(i: int) -> int: + return 1 if i <= 1 else i * fact(i - 1) % kMod + + @functools.lru_cache(None) + def inv(i: int) -> int: + return pow(i, kMod - 2, kMod) + + for i, c in enumerate(reversed(s)): + order = ord(c) - ord('a') + count[order] += 1 + # count[:order] := s[i] can be any character smaller than c + # fact(i) := s[i + 1..n - 1] can be any sequence of characters + perm = sum(count[:order]) * fact(i) + for j in range(26): + perm = perm * inv(fact(count[j])) % kMod + ans = (ans + perm) % kMod + + return ans diff --git a/solutions/1831. Maximum Transaction Each Day/1831.sql b/solutions/1831. Maximum Transaction Each Day/1831.sql new file mode 100644 index 00000000000..144b97803fd --- /dev/null +++ b/solutions/1831. Maximum Transaction Each Day/1831.sql @@ -0,0 +1,14 @@ +WITH + RankedTransactions AS ( + SELECT + *, + RANK() OVER( + PARTITION BY DATE(day) + ORDER BY amount DESC + ) AS `rank` + FROM Transactions + ) +SELECT transaction_id +FROM RankedTransactions +WHERE `rank` = 1 +ORDER BY 1; diff --git a/solutions/1832. Check if the Sentence Is Pangram/1832-2.cpp b/solutions/1832. Check if the Sentence Is Pangram/1832-2.cpp new file mode 100644 index 00000000000..c9149779cd7 --- /dev/null +++ b/solutions/1832. Check if the Sentence Is Pangram/1832-2.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool checkIfPangram(string sentence) { + int seen = 0; + + for (const char c : sentence) + seen |= 1 << c - 'a'; + + return seen == (1 << 26) - 1; + } +}; diff --git a/solutions/1832. Check if the Sentence Is Pangram/1832-2.java b/solutions/1832. Check if the Sentence Is Pangram/1832-2.java new file mode 100644 index 00000000000..16125a80fe8 --- /dev/null +++ b/solutions/1832. Check if the Sentence Is Pangram/1832-2.java @@ -0,0 +1,10 @@ +class Solution { + public boolean checkIfPangram(String sentence) { + int seen = 0; + + for (final char c : sentence.toCharArray()) + seen |= 1 << c - 'a'; + + return seen == (1 << 26) - 1; + } +} diff --git a/solutions/1832. Check if the Sentence Is Pangram/1832-2.py b/solutions/1832. Check if the Sentence Is Pangram/1832-2.py new file mode 100644 index 00000000000..931b015af93 --- /dev/null +++ b/solutions/1832. Check if the Sentence Is Pangram/1832-2.py @@ -0,0 +1,8 @@ +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + seen = 0 + + for c in sentence: + seen |= 1 << ord(c) - ord('a') + + return seen == (1 << 26) - 1 diff --git a/solutions/1832. Check if the Sentence Is Pangram/1832.cpp b/solutions/1832. Check if the Sentence Is Pangram/1832.cpp new file mode 100644 index 00000000000..cf431a1fde3 --- /dev/null +++ b/solutions/1832. Check if the Sentence Is Pangram/1832.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool checkIfPangram(string sentence) { + return unordered_set(sentence.begin(), sentence.end()).size() == 26; + } +}; diff --git a/solutions/1832. Check if the Sentence Is Pangram/1832.java b/solutions/1832. Check if the Sentence Is Pangram/1832.java new file mode 100644 index 00000000000..45183948f53 --- /dev/null +++ b/solutions/1832. Check if the Sentence Is Pangram/1832.java @@ -0,0 +1,10 @@ +class Solution { + public boolean checkIfPangram(String sentence) { + Set seen = new HashSet<>(); + + for (final char c : sentence.toCharArray()) + seen.add(c); + + return seen.size() == 26; + } +} diff --git a/solutions/1832. Check if the Sentence Is Pangram/1832.py b/solutions/1832. Check if the Sentence Is Pangram/1832.py new file mode 100644 index 00000000000..c297266583d --- /dev/null +++ b/solutions/1832. Check if the Sentence Is Pangram/1832.py @@ -0,0 +1,3 @@ +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + return len(set(sentence)) == 26 diff --git a/solutions/1833. Maximum Ice Cream Bars/1833.cpp b/solutions/1833. Maximum Ice Cream Bars/1833.cpp new file mode 100644 index 00000000000..67e5734f586 --- /dev/null +++ b/solutions/1833. Maximum Ice Cream Bars/1833.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxIceCream(vector& costs, int coins) { + ranges::sort(costs); + + for (int i = 0; i < costs.size(); ++i) + if (coins >= costs[i]) + coins -= costs[i]; + else + return i; + + return costs.size(); + } +}; diff --git a/solutions/1833. Maximum Ice Cream Bars/1833.java b/solutions/1833. Maximum Ice Cream Bars/1833.java new file mode 100644 index 00000000000..f834a0e36a8 --- /dev/null +++ b/solutions/1833. Maximum Ice Cream Bars/1833.java @@ -0,0 +1,13 @@ +class Solution { + public int maxIceCream(int[] costs, int coins) { + Arrays.sort(costs); + + for (int i = 0; i < costs.length; ++i) + if (coins >= costs[i]) + coins -= costs[i]; + else + return i; + + return costs.length; + } +} diff --git a/solutions/1833. Maximum Ice Cream Bars/1833.py b/solutions/1833. Maximum Ice Cream Bars/1833.py new file mode 100644 index 00000000000..36b170759d9 --- /dev/null +++ b/solutions/1833. Maximum Ice Cream Bars/1833.py @@ -0,0 +1,9 @@ +class Solution: + def maxIceCream(self, costs: List[int], coins: int) -> int: + for i, cost in enumerate(sorted(costs)): + if coins >= cost: + coins -= cost + else: + return i + + return len(costs) diff --git a/solutions/1834. Single-Threaded CPU/1834.cpp b/solutions/1834. Single-Threaded CPU/1834.cpp new file mode 100644 index 00000000000..5a7283c8d8d --- /dev/null +++ b/solutions/1834. Single-Threaded CPU/1834.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector getOrder(vector>& tasks) { + const int n = tasks.size(); + + // Add index information. + for (int i = 0; i < tasks.size(); ++i) + tasks[i].push_back(i); + + vector ans; + priority_queue, vector>, greater<>> minHeap; + int i = 0; // tasks' index + long time = 0; // the current time + + ranges::sort(tasks); + while (i < n || !minHeap.empty()) { + if (minHeap.empty()) + time = max(time, static_cast(tasks[i][0])); + while (i < n && time >= tasks[i][0]) { + minHeap.emplace(tasks[i][1], tasks[i][2]); + ++i; + } + const auto [procTime, index] = minHeap.top(); + minHeap.pop(); + time += procTime; + ans.push_back(index); + } + + return ans; + } +}; diff --git a/solutions/1834. Single-Threaded CPU/1834.java b/solutions/1834. Single-Threaded CPU/1834.java new file mode 100644 index 00000000000..d090d5fabc2 --- /dev/null +++ b/solutions/1834. Single-Threaded CPU/1834.java @@ -0,0 +1,46 @@ +class T { + public int procTime; + public int index; + + public T(int procTime, int index) { + this.procTime = procTime; + this.index = index; + } +} + +class Solution { + public int[] getOrder(int[][] tasks) { + final int n = tasks.length; + int[][] A = new int[n][3]; + + for (int i = 0; i < n; ++i) { + A[i][0] = tasks[i][0]; + A[i][1] = tasks[i][1]; + A[i][2] = i; + } + + int[] ans = new int[n]; + int ansIndex = 0; + Queue minHeap = new PriorityQueue<>( + (a, b) -> a.procTime == b.procTime ? a.index - b.index : a.procTime - b.procTime); + int i = 0; // tasks' index + long time = 0; // the current time + + Arrays.sort(A, Comparator.comparing(a -> a[0])); + + while (i < n || !minHeap.isEmpty()) { + if (minHeap.isEmpty()) + time = Math.max(time, (long) A[i][0]); + while (i < n && time >= (long) A[i][0]) { + minHeap.offer(new T(A[i][1], A[i][2])); + ++i; + } + final int procTime = minHeap.peek().procTime; + final int index = minHeap.poll().index; + time += procTime; + ans[ansIndex++] = index; + } + + return ans; + } +} diff --git a/solutions/1834. Single-Threaded CPU/1834.py b/solutions/1834. Single-Threaded CPU/1834.py new file mode 100644 index 00000000000..d5380be8585 --- /dev/null +++ b/solutions/1834. Single-Threaded CPU/1834.py @@ -0,0 +1,22 @@ +class Solution: + def getOrder(self, tasks: List[List[int]]) -> List[int]: + n = len(tasks) + A = [[*task, i] for i, task in enumerate(tasks)] + ans = [] + minHeap = [] + i = 0 # tasks' index + time = 0 # the current time + + A.sort() + + while i < n or minHeap: + if not minHeap: + time = max(time, A[i][0]) + while i < n and time >= A[i][0]: + heapq.heappush(minHeap, (A[i][1], A[i][2])) + i += 1 + procTime, index = heapq.heappop(minHeap) + time += procTime + ans.append(index) + + return ans diff --git a/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.cpp b/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.cpp new file mode 100644 index 00000000000..0027de90de8 --- /dev/null +++ b/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int getXORSum(vector& arr1, vector& arr2) { + const int xors1 = accumulate(arr1.begin(), arr1.end(), 0, bit_xor<>()); + const int xors2 = accumulate(arr2.begin(), arr2.end(), 0, bit_xor<>()); + return xors1 & xors2; + } +}; diff --git a/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.java b/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.java new file mode 100644 index 00000000000..61be706cad6 --- /dev/null +++ b/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.java @@ -0,0 +1,7 @@ +class Solution { + public int getXORSum(int[] arr1, int[] arr2) { + final int xors1 = Arrays.stream(arr1).reduce((a, b) -> a ^ b).getAsInt(); + final int xors2 = Arrays.stream(arr2).reduce((a, b) -> a ^ b).getAsInt(); + return xors1 & xors2; + } +} diff --git a/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.py b/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.py new file mode 100644 index 00000000000..a14a05070c5 --- /dev/null +++ b/solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.py @@ -0,0 +1,3 @@ +class Solution: + def getXORSum(self, arr1: List[int], arr2: List[int]) -> int: + return functools.reduce(operator.xor, arr1) & functools.reduce(operator.xor, arr2) diff --git a/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.cpp b/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.cpp new file mode 100644 index 00000000000..7dc43bcca0a --- /dev/null +++ b/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + ListNode* deleteDuplicatesUnsorted(ListNode* head) { + ListNode dummy(0, head); + unordered_map count; + + for (ListNode* curr = head; curr; curr = curr->next) + ++count[curr->val]; + + ListNode* curr = &dummy; + + while (curr) { + while (curr->next && count.contains(curr->next->val) && + count[curr->next->val] > 1) + curr->next = curr->next->next; + curr = curr->next; + } + + return dummy.next; + } +}; diff --git a/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.java b/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.java new file mode 100644 index 00000000000..a6947af56c2 --- /dev/null +++ b/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.java @@ -0,0 +1,19 @@ +class Solution { + public ListNode deleteDuplicatesUnsorted(ListNode head) { + ListNode dummy = new ListNode(0, head); + Map count = new HashMap<>(); + + for (ListNode curr = head; curr != null; curr = curr.next) + count.merge(curr.val, 1, Integer::sum); + + ListNode curr = dummy; + + while (curr != null) { + while (curr.next != null && count.containsKey(curr.next.val) && count.get(curr.next.val) > 1) + curr.next = curr.next.next; + curr = curr.next; + } + + return dummy.next; + } +} diff --git a/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.py b/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.py new file mode 100644 index 00000000000..96865fd7d3f --- /dev/null +++ b/solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.py @@ -0,0 +1,18 @@ +class Solution: + def deleteDuplicatesUnsorted(self, head: ListNode) -> ListNode: + dummy = ListNode(0, head) + count = collections.Counter() + + curr = head + while curr: + count[curr.val] += 1 + curr = curr.next + + curr = dummy + + while curr: + while curr.next and curr.next.val in count and count[curr.next.val] > 1: + curr.next = curr.next.next + curr = curr.next + + return dummy.next diff --git a/solutions/1837. Sum of Digits in Base K/1837.cpp b/solutions/1837. Sum of Digits in Base K/1837.cpp new file mode 100644 index 00000000000..336c5a63097 --- /dev/null +++ b/solutions/1837. Sum of Digits in Base K/1837.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int sumBase(int n, int k) { + int ans = 0; + + while (n) { + ans += n % k; + n /= k; + } + + return ans; + } +}; diff --git a/solutions/1837. Sum of Digits in Base K/1837.java b/solutions/1837. Sum of Digits in Base K/1837.java new file mode 100644 index 00000000000..dff059b6e88 --- /dev/null +++ b/solutions/1837. Sum of Digits in Base K/1837.java @@ -0,0 +1,12 @@ +class Solution { + public int sumBase(int n, int k) { + int ans = 0; + + while (n > 0) { + ans += n % k; + n /= k; + } + + return ans; + } +} diff --git a/solutions/1837. Sum of Digits in Base K/1837.py b/solutions/1837. Sum of Digits in Base K/1837.py new file mode 100644 index 00000000000..1cd244051f9 --- /dev/null +++ b/solutions/1837. Sum of Digits in Base K/1837.py @@ -0,0 +1,9 @@ +class Solution: + def sumBase(self, n: int, k: int) -> int: + ans = 0 + + while n: + ans += n % k + n //= k + + return ans diff --git a/solutions/1838. Frequency of the Most Frequent Element/1838.cpp b/solutions/1838. Frequency of the Most Frequent Element/1838.cpp new file mode 100644 index 00000000000..48c35941d2f --- /dev/null +++ b/solutions/1838. Frequency of the Most Frequent Element/1838.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxFrequency(vector& nums, int k) { + int ans = 0; + long sum = 0; + + ranges::sort(nums); + + for (int l = 0, r = 0; r < nums.size(); ++r) { + sum += nums[r]; + while (sum + k < static_cast(nums[r]) * (r - l + 1)) + sum -= nums[l++]; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/1838. Frequency of the Most Frequent Element/1838.java b/solutions/1838. Frequency of the Most Frequent Element/1838.java new file mode 100644 index 00000000000..c9959f63887 --- /dev/null +++ b/solutions/1838. Frequency of the Most Frequent Element/1838.java @@ -0,0 +1,17 @@ +class Solution { + public int maxFrequency(int[] nums, int k) { + int ans = 0; + long sum = 0; + + Arrays.sort(nums); + + for (int l = 0, r = 0; r < nums.length; ++r) { + sum += nums[r]; + while (sum + k < (long) nums[r] * (r - l + 1)) + sum -= nums[l++]; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/1838. Frequency of the Most Frequent Element/1838.py b/solutions/1838. Frequency of the Most Frequent Element/1838.py new file mode 100644 index 00000000000..981a49de9ee --- /dev/null +++ b/solutions/1838. Frequency of the Most Frequent Element/1838.py @@ -0,0 +1,16 @@ +class Solution: + def maxFrequency(self, nums: List[int], k: int) -> int: + ans = 0 + summ = 0 + + nums.sort() + + l = 0 + for r, num in enumerate(nums): + summ += num + while summ + k < num * (r - l + 1): + summ -= nums[l] + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/1839. Longest Substring Of All Vowels in Order/1839.cpp b/solutions/1839. Longest Substring Of All Vowels in Order/1839.cpp new file mode 100644 index 00000000000..af8c3cba6be --- /dev/null +++ b/solutions/1839. Longest Substring Of All Vowels in Order/1839.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int longestBeautifulSubstring(string word) { + int ans = 0; + int count = 1; + + for (int l = 0, r = 1; r < word.length(); ++r) { + const char curr = word[r]; + const char prev = word[r - 1]; + if (curr >= prev) { + if (curr > prev) + ++count; + if (count == 5) + ans = max(ans, r - l + 1); + } else { + count = 1; + l = r; + } + } + + return ans; + } +}; diff --git a/solutions/1839. Longest Substring Of All Vowels in Order/1839.java b/solutions/1839. Longest Substring Of All Vowels in Order/1839.java new file mode 100644 index 00000000000..994d74b8969 --- /dev/null +++ b/solutions/1839. Longest Substring Of All Vowels in Order/1839.java @@ -0,0 +1,22 @@ +class Solution { + public int longestBeautifulSubstring(String word) { + int ans = 0; + int count = 1; + + for (int l = 0, r = 1; r < word.length(); ++r) { + final char curr = word.charAt(r); + final char prev = word.charAt(r - 1); + if (curr >= prev) { + if (curr > prev) + ++count; + if (count == 5) + ans = Math.max(ans, r - l + 1); + } else { + count = 1; + l = r; + } + } + + return ans; + } +} diff --git a/solutions/1839. Longest Substring Of All Vowels in Order/1839.py b/solutions/1839. Longest Substring Of All Vowels in Order/1839.py new file mode 100644 index 00000000000..12b7df01884 --- /dev/null +++ b/solutions/1839. Longest Substring Of All Vowels in Order/1839.py @@ -0,0 +1,19 @@ +class Solution: + def longestBeautifulSubstring(self, word: str) -> int: + ans = 0 + count = 1 + + l = 0 + for r in range(1, len(word)): + curr = word[r] + prev = word[r - 1] + if curr >= prev: + if curr > prev: + count += 1 + if count == 5: + ans = max(ans, r - l + 1) + else: + count = 1 + l = r + + return ans diff --git a/solutions/184. Department Highest Salary/184.sql b/solutions/184. Department Highest Salary/184.sql new file mode 100644 index 00000000000..59ced2c54ba --- /dev/null +++ b/solutions/184. Department Highest Salary/184.sql @@ -0,0 +1,19 @@ +WITH + EmployeesWithMaxSalaryInDepartment AS ( + SELECT + Department.name AS department, + Employee.name AS employee, + Employee.salary, + MAX(Employee.salary) OVER( + PARTITION BY Employee.departmentId + ) AS max_salary + FROM Employee + LEFT JOIN Department + ON (Employee.departmentId = Department.id) + ) +SELECT + department AS Department, + employee AS Employee, + salary AS Salary +FROM EmployeesWithMaxSalaryInDepartment +WHERE salary = max_salary; diff --git a/solutions/1840. Maximum Building Height/1840.cpp b/solutions/1840. Maximum Building Height/1840.cpp new file mode 100644 index 00000000000..f36460a6824 --- /dev/null +++ b/solutions/1840. Maximum Building Height/1840.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int maxBuilding(int n, vector>& restrictions) { + vector> A(restrictions); + + A.push_back({1, 0}); + A.push_back({n, n - 1}); + ranges::sort(A); + + for (int i = 1; i < A.size(); ++i) { + const int dist = A[i][0] - A[i - 1][0]; + A[i][1] = min(A[i][1], A[i - 1][1] + dist); + } + + for (int i = A.size() - 2; i >= 0; --i) { + const int dist = A[i + 1][0] - A[i][0]; + A[i][1] = min(A[i][1], A[i + 1][1] + dist); + } + + int ans = 0; + + for (int i = 1; i < A.size(); ++i) { + const int l = A[i - 1][0]; + const int r = A[i][0]; + const int hL = A[i - 1][1]; + const int hR = A[i][1]; + ans = max(ans, max(hL, hR) + (r - l - abs(hL - hR)) / 2); + } + + return ans; + } +}; diff --git a/solutions/1840. Maximum Building Height/1840.java b/solutions/1840. Maximum Building Height/1840.java new file mode 100644 index 00000000000..830fc65fe5f --- /dev/null +++ b/solutions/1840. Maximum Building Height/1840.java @@ -0,0 +1,33 @@ +class Solution { + public int maxBuilding(int n, int[][] restrictions) { + final int k = restrictions.length; + int[][] A = new int[k + 2][2]; + System.arraycopy(restrictions, 0, A, 0, k); + A[k] = new int[] {1, 0}; + A[k + 1] = new int[] {n, n - 1}; + + Arrays.sort(A, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + + for (int i = 1; i < A.length; ++i) { + final int dist = A[i][0] - A[i - 1][0]; + A[i][1] = Math.min(A[i][1], A[i - 1][1] + dist); + } + + for (int i = A.length - 2; i >= 0; --i) { + final int dist = A[i + 1][0] - A[i][0]; + A[i][1] = Math.min(A[i][1], A[i + 1][1] + dist); + } + + int ans = 0; + + for (int i = 1; i < A.length; ++i) { + final int l = A[i - 1][0]; + final int r = A[i][0]; + final int hL = A[i - 1][1]; + final int hR = A[i][1]; + ans = Math.max(ans, Math.max(hL, hR) + (r - l - Math.abs(hL - hR)) / 2); + } + + return ans; + } +} diff --git a/solutions/1840. Maximum Building Height/1840.py b/solutions/1840. Maximum Building Height/1840.py new file mode 100644 index 00000000000..30b24fbd368 --- /dev/null +++ b/solutions/1840. Maximum Building Height/1840.py @@ -0,0 +1,18 @@ +class Solution: + def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int: + A = sorted(restrictions + [[1, 0]] + [[n, n - 1]]) + + for i in range(len(A)): + dist = A[i][0] - A[i - 1][0] + A[i][1] = min(A[i][1], A[i - 1][1] + dist) + + for i in reversed(range(len(A) - 1)): + dist = A[i + 1][0] - A[i][0] + A[i][1] = min(A[i][1], A[i + 1][1] + dist) + + ans = 0 + + for (l, hL), (r, hR) in zip(A, A[1:]): + ans = max(ans, max(hL, hR) + (r - l - abs(hL - hR)) // 2) + + return ans diff --git a/solutions/1841. League Statistics/1841.sql b/solutions/1841. League Statistics/1841.sql new file mode 100644 index 00000000000..da02d47b2e8 --- /dev/null +++ b/solutions/1841. League Statistics/1841.sql @@ -0,0 +1,44 @@ +SELECT + Teams.team_name, + SUM( + CASE + WHEN Matches.home_team_id = Teams.team_id + OR Matches.away_team_id = Teams.team_id THEN 1 + ELSE 0 + END + ) AS matches_played, + SUM( + CASE + WHEN Teams.team_id = Matches.home_team_id + AND Matches.home_team_goals > Matches.away_team_goals THEN 3 + WHEN Teams.team_id = Matches.away_team_id + AND Matches.home_team_goals < Matches.away_team_goals THEN 3 + WHEN Matches.home_team_goals = Matches.away_team_goals THEN 1 + ELSE 0 + END + ) AS points, + SUM( + CASE + WHEN Matches.home_team_id = Teams.team_id THEN Matches.home_team_goals + ELSE Matches.away_team_goals + END + ) AS goal_for, + SUM( + CASE + WHEN Matches.home_team_id = Teams.team_id THEN Matches.away_team_goals + ELSE Matches.home_team_goals + END + ) AS goal_against, + SUM( + CASE + WHEN Matches.home_team_id = Teams.team_id THEN Matches.home_team_goals - Matches.away_team_goals + ELSE Matches.away_team_goals - Matches.home_team_goals + END + ) AS goal_diff +FROM Matches +INNER JOIN Teams + ON ( + Matches.home_team_id = Teams.team_id + OR Matches.away_team_id = Teams.team_id) +GROUP BY 1 +ORDER BY points DESC, goal_diff DESC, team_name; diff --git a/solutions/1842. Next Palindrome Using Same Digits/1842.cpp b/solutions/1842. Next Palindrome Using Same Digits/1842.cpp new file mode 100644 index 00000000000..03618b0ee46 --- /dev/null +++ b/solutions/1842. Next Palindrome Using Same Digits/1842.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + string nextPalindrome(string num) { + const int n = num.length(); + vector A(n / 2); + + for (int i = 0; i < A.size(); ++i) + A[i] = num[i] - '0'; + + if (!nextPermutation(A)) + return ""; + + string s; + + for (const int a : A) + s += '0' + a; + + if (n % 2 == 1) + return s + num[n / 2] + string(s.rbegin(), s.rend()); + return s + string(s.rbegin(), s.rend()); + } + + private: + // Returns true if `nums` has the next permutation. + bool nextPermutation(vector& nums) { + const int n = nums.size(); + + // From the back to the front, find the first num < nums[i + 1]. + int i; + for (i = n - 2; i >= 0; --i) + if (nums[i] < nums[i + 1]) + break; + + if (i < 0) + return false; + + // From the back to the front, find the first num > nums[i] and swap it with + // nums[i]. + for (int j = n - 1; j > i; --j) + if (nums[j] > nums[i]) { + swap(nums[i], nums[j]); + break; + } + + // Reverse nums[i + 1..n - 1]. + reverse(nums, i + 1, n - 1); + return true; + } + + void reverse(vector& nums, int l, int r) { + while (l < r) + swap(nums[l++], nums[r--]); + } +}; diff --git a/solutions/1842. Next Palindrome Using Same Digits/1842.java b/solutions/1842. Next Palindrome Using Same Digits/1842.java new file mode 100644 index 00000000000..76012e7c510 --- /dev/null +++ b/solutions/1842. Next Palindrome Using Same Digits/1842.java @@ -0,0 +1,57 @@ +class Solution { + public String nextPalindrome(String num) { + final int n = num.length(); + int[] A = new int[n / 2]; + + for (int i = 0; i < A.length; ++i) + A[i] = num.charAt(i) - '0'; + + if (!nextPermutation(A)) + return ""; + + StringBuilder sb = new StringBuilder(); + + for (final int a : A) + sb.append(a); + + if (n % 2 == 1) + return sb.toString() + num.charAt(n / 2) + sb.reverse().toString(); + return sb.toString() + sb.reverse().toString(); + } + + private boolean nextPermutation(int[] nums) { + final int n = nums.length; + + // From the back to the front, find the first num < nums[i + 1]. + int i; + for (i = n - 2; i >= 0; --i) + if (nums[i] < nums[i + 1]) + break; + + if (i < 0) + return false; + + // From the back to the front, find the first num > nums[i] and swap it with + // nums[i]. + for (int j = n - 1; j > i; --j) + if (nums[j] > nums[i]) { + swap(nums, i, j); + break; + } + + // Reverse nums[i + 1..n - 1]. + reverse(nums, i + 1, n - 1); + return true; + } + + private void reverse(int[] nums, int l, int r) { + while (l < r) + swap(nums, l++, r--); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/1842. Next Palindrome Using Same Digits/1842.py b/solutions/1842. Next Palindrome Using Same Digits/1842.py new file mode 100644 index 00000000000..a90e921e246 --- /dev/null +++ b/solutions/1842. Next Palindrome Using Same Digits/1842.py @@ -0,0 +1,42 @@ +class Solution: + def nextPalindrome(self, num: str) -> str: + def nextPermutation(nums: List[int]) -> bool: + n = len(nums) + + # From the back to the front, find the first num < nums[i + 1]. + i = n - 2 + while i >= 0: + if nums[i] < nums[i + 1]: + break + i -= 1 + + if i < 0: + return False + + # From the back to the front, find the first num > nums[i] and swap it + # with nums[i]. + for j in range(n - 1, i, -1): + if nums[j] > nums[i]: + nums[i], nums[j] = nums[j], nums[i] + break + + def reverse(nums, l, r): + while l < r: + nums[l], nums[r] = nums[r], nums[l] + l += 1 + r -= 1 + + # Reverse nums[i + 1..n - 1]. + reverse(nums, i + 1, len(nums) - 1) + return True + + n = len(num) + A = [ord(num[i]) - ord('0') for i in range(len(num) // 2)] + + if not nextPermutation(A): + return '' + + s = ''.join([chr(ord('0') + a) for a in A]) + if n % 2 == 1: + return s + num[n // 2] + s[::-1] + return s + s[::-1] diff --git a/solutions/1843. Suspicious Bank Accounts/1843.sql b/solutions/1843. Suspicious Bank Accounts/1843.sql new file mode 100644 index 00000000000..48d6a18c5a7 --- /dev/null +++ b/solutions/1843. Suspicious Bank Accounts/1843.sql @@ -0,0 +1,18 @@ +WITH + SuspiciousAccountToMonth AS ( + SELECT + Transactions.account_id, + DATE_FORMAT(Transactions.day, '%Y%m') AS month, + Accounts.max_income + FROM Transactions + INNER JOIN Accounts + USING (account_id) + WHERE Transactions.type = 'Creditor' + GROUP BY 1, 2 + HAVING SUM(Transactions.amount) > Accounts.max_income + ) +SELECT DISTINCT CurrMonth.account_id +FROM SuspiciousAccountToMonth AS CurrMonth +INNER JOIN SuspiciousAccountToMonth AS NextMonth + USING (account_id) +WHERE PERIOD_DIFF(NextMonth.month, CurrMonth.month) = 1; diff --git a/solutions/1844. Replace All Digits with Characters/1844.cpp b/solutions/1844. Replace All Digits with Characters/1844.cpp new file mode 100644 index 00000000000..90bcf3d83d7 --- /dev/null +++ b/solutions/1844. Replace All Digits with Characters/1844.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + string replaceDigits(string s) { + for (int i = 0; i < s.length(); ++i) + s[i] += s[i - 1] - '0'; + return s; + } +}; diff --git a/solutions/1844. Replace All Digits with Characters/1844.java b/solutions/1844. Replace All Digits with Characters/1844.java new file mode 100644 index 00000000000..3db4ba16bd0 --- /dev/null +++ b/solutions/1844. Replace All Digits with Characters/1844.java @@ -0,0 +1,10 @@ +class Solution { + public String replaceDigits(String s) { + char[] A = s.toCharArray(); + + for (int i = 1; i < A.length; i += 2) + A[i] += (char) (A[i - 1] - '0'); + + return String.valueOf(A); + } +} diff --git a/solutions/1844. Replace All Digits with Characters/1844.py b/solutions/1844. Replace All Digits with Characters/1844.py new file mode 100644 index 00000000000..ea4bfab4676 --- /dev/null +++ b/solutions/1844. Replace All Digits with Characters/1844.py @@ -0,0 +1,8 @@ +class Solution: + def replaceDigits(self, s: str) -> str: + chars = list(s) + + for i in range(1, len(chars), 2): + chars[i] = chr(ord(chars[i - 1]) + ord(chars[i]) - ord('0')) + + return ''.join(chars) diff --git a/solutions/1845. Seat Reservation Manager/1845.cpp b/solutions/1845. Seat Reservation Manager/1845.cpp new file mode 100644 index 00000000000..970c4fc19e8 --- /dev/null +++ b/solutions/1845. Seat Reservation Manager/1845.cpp @@ -0,0 +1,21 @@ +class SeatManager { + public: + SeatManager(int n) {} + + int reserve() { + if (minHeap.empty()) + return ++num; + + const int minNum = minHeap.top(); + minHeap.pop(); + return minNum; + } + + void unreserve(int seatNumber) { + minHeap.push(seatNumber); + } + + private: + priority_queue, greater<>> minHeap; + int num = 0; +}; diff --git a/solutions/1845. Seat Reservation Manager/1845.java b/solutions/1845. Seat Reservation Manager/1845.java new file mode 100644 index 00000000000..6ce1d1d6cc9 --- /dev/null +++ b/solutions/1845. Seat Reservation Manager/1845.java @@ -0,0 +1,16 @@ +class SeatManager { + public SeatManager(int n) {} + + public int reserve() { + if (minHeap.isEmpty()) + return ++num; + return minHeap.poll(); + } + + public void unreserve(int seatNumber) { + minHeap.offer(seatNumber); + } + + private Queue minHeap = new PriorityQueue<>(); + private int num = 0; +} diff --git a/solutions/1845. Seat Reservation Manager/1845.py b/solutions/1845. Seat Reservation Manager/1845.py new file mode 100644 index 00000000000..46070c38087 --- /dev/null +++ b/solutions/1845. Seat Reservation Manager/1845.py @@ -0,0 +1,9 @@ +class SeatManager: + def __init__(self, n: int): + self.minHeap = [i + 1 for i in range(n)] + + def reserve(self) -> int: + return heapq.heappop(self.minHeap) + + def unreserve(self, seatNumber: int) -> None: + heapq.heappush(self.minHeap, seatNumber) diff --git a/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.cpp b/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.cpp new file mode 100644 index 00000000000..69761eebecb --- /dev/null +++ b/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int maximumElementAfterDecrementingAndRearranging(vector& arr) { + ranges::sort(arr); + arr[0] = 1; + + for (int i = 1; i < arr.size(); ++i) + arr[i] = min(arr[i], arr[i - 1] + 1); + + return arr.back(); + } +}; diff --git a/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.java b/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.java new file mode 100644 index 00000000000..1bcd135441d --- /dev/null +++ b/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.java @@ -0,0 +1,11 @@ +class Solution { + public int maximumElementAfterDecrementingAndRearranging(int[] arr) { + Arrays.sort(arr); + arr[0] = 1; + + for (int i = 1; i < arr.length; ++i) + arr[i] = Math.min(arr[i], arr[i - 1] + 1); + + return arr[arr.length - 1]; + } +} diff --git a/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.py b/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.py new file mode 100644 index 00000000000..cd1337b0aa5 --- /dev/null +++ b/solutions/1846. Maximum Element After Decreasing and Rearranging/1846.py @@ -0,0 +1,9 @@ +class Solution: + def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: + arr.sort() + arr[0] = 1 + + for i in range(1, len(arr)): + arr[i] = min(arr[i], arr[i - 1] + 1) + + return arr[-1] diff --git a/solutions/1847. Closest Room/1847.cpp b/solutions/1847. Closest Room/1847.cpp new file mode 100644 index 00000000000..ca850d5ffac --- /dev/null +++ b/solutions/1847. Closest Room/1847.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector closestRoom(vector>& rooms, + vector>& queries) { + vector ans(queries.size()); + set roomIds; + + for (int i = 0; i < queries.size(); ++i) + queries[i].push_back(i); + + auto descSize = [](const auto& a, const auto& b) { return a[1] > b[1]; }; + ranges::sort(rooms, descSize); + ranges::sort(queries, descSize); + + int i = 0; // rooms' index + for (const vector& query : queries) { + while (i < rooms.size() && rooms[i][1] >= query[1]) + roomIds.insert(rooms[i++][0]); + ans[query[2]] = searchClosestRoomId(roomIds, query[0]); + } + + return ans; + } + + private: + int searchClosestRoomId(set& roomIds, int preferred) { + const auto it = roomIds.lower_bound(preferred); + const int id1 = it == roomIds.cbegin() ? -1 : *(prev(it)); + const int id2 = it == roomIds.cend() ? -1 : *it; + if (id1 == -1) + return id2; + if (id2 == -1) + return id1; + if (abs(preferred - id1) <= abs(preferred - id2)) + return id1; + return id2; + } +}; diff --git a/solutions/1847. Closest Room/1847.java b/solutions/1847. Closest Room/1847.java new file mode 100644 index 00000000000..4a380ab405d --- /dev/null +++ b/solutions/1847. Closest Room/1847.java @@ -0,0 +1,36 @@ +class Solution { + public int[] closestRoom(int[][] rooms, int[][] queries) { + int[] ans = new int[queries.length]; + Integer[] indices = new Integer[queries.length]; + TreeSet roomIds = new TreeSet<>(); + + for (int i = 0; i < queries.length; ++i) + indices[i] = i; + + Arrays.sort(rooms, (a, b) -> b[1] - a[1]); + Arrays.sort(indices, (a, b) -> queries[b][1] - queries[a][1]); + + int i = 0; // rooms' index + for (final int index : indices) { + while (i < rooms.length && rooms[i][1] >= queries[index][1]) + roomIds.add(rooms[i++][0]); + ans[index] = searchClosestRoomId(roomIds, queries[index][0]); + } + + return ans; + } + + private int searchClosestRoomId(TreeSet roomIds, int preferred) { + Integer floor = roomIds.floor(preferred); + Integer ceiling = roomIds.ceiling(preferred); + final int id1 = floor == null ? -1 : floor; + final int id2 = ceiling == null ? -1 : ceiling; + if (id1 == -1) + return id2; + if (id2 == -1) + return id1; + if (Math.abs(preferred - id1) <= Math.abs(preferred - id2)) + return id1; + return id2; + } +} diff --git a/solutions/1847. Closest Room/1847.py b/solutions/1847. Closest Room/1847.py new file mode 100644 index 00000000000..e5a128a60fa --- /dev/null +++ b/solutions/1847. Closest Room/1847.py @@ -0,0 +1,32 @@ +from sortedcontainers import SortedList + + +class Solution: + def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]: + ans = [0] * len(queries) + qs = [[*q, i] for i, q in enumerate(queries)] + roomIds = SortedList() + + rooms.sort(key=lambda x: -x[1]) + qs.sort(key=lambda x: -x[1]) + + def searchClosestRoomId(roomIds: SortedList, preferred: int): + if not roomIds: + return -1 + + candIds = [] + i = roomIds.bisect_right(preferred) + if i > 0: + candIds.append(roomIds[i - 1]) + if i < len(roomIds): + candIds.append(roomIds[i]) + return min(candIds, key=lambda x: abs(x - preferred)) + + i = 0 # rooms' index + for preferred, minSize, index in qs: + while i < len(rooms) and rooms[i][1] >= minSize: + roomIds.add(rooms[i][0]) + i += 1 + ans[index] = searchClosestRoomId(roomIds, preferred) + + return ans diff --git a/solutions/1848. Minimum Distance to the Target Element/1848.cpp b/solutions/1848. Minimum Distance to the Target Element/1848.cpp new file mode 100644 index 00000000000..73091a99bc4 --- /dev/null +++ b/solutions/1848. Minimum Distance to the Target Element/1848.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int getMinDistance(vector& nums, int target, int start) { + int ans = INT_MAX; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == target) + ans = min(ans, abs(i - start)); + + return ans; + } +}; diff --git a/solutions/1848. Minimum Distance to the Target Element/1848.java b/solutions/1848. Minimum Distance to the Target Element/1848.java new file mode 100644 index 00000000000..b12cd6f1031 --- /dev/null +++ b/solutions/1848. Minimum Distance to the Target Element/1848.java @@ -0,0 +1,11 @@ +class Solution { + public int getMinDistance(int[] nums, int target, int start) { + int ans = Integer.MAX_VALUE; + + for (int i = 0; i < nums.length; ++i) + if (nums[i] == target) + ans = Math.min(ans, Math.abs(i - start)); + + return ans; + } +} diff --git a/solutions/1848. Minimum Distance to the Target Element/1848.py b/solutions/1848. Minimum Distance to the Target Element/1848.py new file mode 100644 index 00000000000..1f7cb18f9a5 --- /dev/null +++ b/solutions/1848. Minimum Distance to the Target Element/1848.py @@ -0,0 +1,9 @@ +class Solution: + def getMinDistance(self, nums: List[int], target: int, start: int) -> int: + ans = math.inf + + for i, num in enumerate(nums): + if num == target: + ans = min(ans, abs(i - start)) + + return ans diff --git a/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.cpp b/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.cpp new file mode 100644 index 00000000000..9d44f558f9f --- /dev/null +++ b/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool splitString(string s) { + return isValid(s, 0, -1, 0); + } + + private: + bool isValid(const string& s, int start, long prev, int segment) { + if (start == s.length() && segment > 1) + return true; + + long curr = 0; + for (int i = start; i < s.length(); ++i) { + curr = curr * 10 + s[i] - '0'; + if (curr > 9999999999L) + return false; + if ((prev == -1 || curr == prev - 1) && + isValid(s, i + 1, curr, segment + 1)) { + return true; + } + } + + return false; + } +}; diff --git a/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.java b/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.java new file mode 100644 index 00000000000..cfa696b16a3 --- /dev/null +++ b/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.java @@ -0,0 +1,21 @@ +class Solution { + public boolean splitString(String s) { + return isValid(s, 0, -1, 0); + } + + private boolean isValid(final String s, int start, long prev, int segment) { + if (start == s.length() && segment > 1) + return true; + + long curr = 0; + for (int i = start; i < s.length(); ++i) { + curr = curr * 10 + s.charAt(i) - '0'; + if (curr > 9999999999) + return false; + if ((prev == -1 || curr == prev - 1) && isValid(s, i + 1, curr, segment + 1)) + return true; + } + + return false; + } +} diff --git a/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.py b/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.py new file mode 100644 index 00000000000..08f537a0ae1 --- /dev/null +++ b/solutions/1849. Splitting a String Into Descending Consecutive Values/1849.py @@ -0,0 +1,17 @@ +class Solution: + def splitString(self, s: str) -> bool: + def isValid(s: str, start: int, prev: int, segment: int) -> bool: + if start == len(s) and segment > 1: + return True + + curr = 0 + for i in range(start, len(s)): + curr = curr * 10 + ord(s[i]) - ord('0') + if curr > 9999999999: + return False + if (prev == -1 or curr == prev - 1) and isValid(s, i + 1, curr, segment + 1): + return True + + return False + + return isValid(s, 0, -1, 0) diff --git a/solutions/185. Department Top Three Salaries/185.sql b/solutions/185. Department Top Three Salaries/185.sql new file mode 100644 index 00000000000..86d42853748 --- /dev/null +++ b/solutions/185. Department Top Three Salaries/185.sql @@ -0,0 +1,20 @@ +WITH + EmployeesWithRankInDepartment AS ( + SELECT + Department.name AS department, + Employee.name AS employee, + Employee.salary, + DENSE_RANK() OVER( + PARTITION BY Employee.departmentId + ORDER BY Employee.salary DESC + ) AS `rank` + FROM Department + INNER JOIN Employee + ON (Department.id = Employee.departmentId ) + ) +SELECT + department AS Department, + employee AS Employee, + salary AS Salary +FROM EmployeesWithRankInDepartment +WHERE `rank` <= 3; diff --git a/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.cpp b/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.cpp new file mode 100644 index 00000000000..65bfc23f3e6 --- /dev/null +++ b/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int getMinSwaps(string num, int k) { + string perm = num; + + while (k--) + next_permutation(perm.begin(), perm.end()); + + return countSteps(num, perm); + } + + private: + int countSteps(const string& A, string& B) { + int count = 0; + + for (int i = 0, j = 0; i < A.length(); ++i) { + j = i; + while (A[i] != B[j]) + ++j; + while (i < j) { + swap(B[j], B[j - 1]); + --j; + ++count; + } + } + + return count; + } +}; diff --git a/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.java b/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.java new file mode 100644 index 00000000000..03ae6f81958 --- /dev/null +++ b/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.java @@ -0,0 +1,64 @@ +class Solution { + public int getMinSwaps(String num, int k) { + int[] A = new int[num.length()]; // Original + + for (int i = 0; i < A.length; ++i) + A[i] = num.charAt(i) - '0'; + + int[] B = A.clone(); // Permutated + + for (int i = 0; i < k; ++i) + nextPermutation(B); + + return countSteps(A, B); + } + + public void nextPermutation(int[] nums) { + final int n = nums.length; + + // From the back to the front, find the first num < nums[i + 1]. + int i; + for (i = n - 2; i >= 0; --i) + if (nums[i] < nums[i + 1]) + break; + + // From the back to the front, find the first num > nums[i] and swap it with nums[i]. + if (i >= 0) + for (int j = n - 1; j > i; --j) + if (nums[j] > nums[i]) { + swap(nums, i, j); + break; + } + + // Reverse nums[i + 1..n - 1] + reverse(nums, i + 1, n - 1); + } + + private void reverse(int[] nums, int l, int r) { + while (l < r) + swap(nums, l++, r--); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + + private int countSteps(int[] A, int[] B) { + int count = 0; + + for (int i = 0, j = 0; i < A.length; ++i) { + j = i; + while (A[i] != B[j]) + ++j; + while (i < j) { + swap(B, j, j - 1); + --j; + ++count; + } + } + + return count; + } +} diff --git a/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.py b/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.py new file mode 100644 index 00000000000..75e9ed02ebe --- /dev/null +++ b/solutions/1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number/1850.py @@ -0,0 +1,50 @@ +class Solution: + def getMinSwaps(self, num: str, k: int) -> int: + def nextPermutation(nums: List[int]): + n = len(nums) + + # From the back to the front, find the first num < nums[i + 1]. + i = n - 2 + while i >= 0: + if nums[i] < nums[i + 1]: + break + i -= 1 + + # From the back to the front, find the first num > nums[i] and swap it with nums[i]. + if i >= 0: + for j in range(n - 1, i, -1): + if nums[j] > nums[i]: + nums[i], nums[j] = nums[j], nums[i] + break + + def reverse(nums, l, r): + while l < r: + nums[l], nums[r] = nums[r], nums[l] + l += 1 + r -= 1 + + # Reverse nums[i + 1..n - 1] + reverse(nums, i + 1, len(nums) - 1) + + A = [int(c) for c in num] # Original + B = A.copy() # Permutated + + for _ in range(k): + nextPermutation(B) + + def countSteps(A: List[int], B: List[int]) -> int: + count = 0 + + j = 0 + for i in range(len(A)): + j = i + while A[i] != B[j]: + j += 1 + while i < j: + B[j], B[j - 1] = B[j - 1], B[j] + j -= 1 + count += 1 + + return count + + return countSteps(A, B) diff --git a/solutions/1851. Minimum Interval to Include Each Query/1851.cpp b/solutions/1851. Minimum Interval to Include Each Query/1851.cpp new file mode 100644 index 00000000000..1c191b18b36 --- /dev/null +++ b/solutions/1851. Minimum Interval to Include Each Query/1851.cpp @@ -0,0 +1,36 @@ +struct T { + int size; + int right; + T(int size, int right) : size(size), right(right) {} +}; + +class Solution { + public: + vector minInterval(vector>& intervals, + vector& queries) { + vector ans(queries.size(), -1); + auto compare = [](const T& a, const T& b) { return a.size > b.size; }; + priority_queue, decltype(compare)> minHeap(compare); + vector> qs; + + for (int i = 0; i < queries.size(); ++i) + qs.push_back({queries[i], i}); + + ranges::sort(intervals); + ranges::sort(qs); + + int i = 0; // intervals' index + for (const vector& q : qs) { + while (i < intervals.size() && intervals[i][0] <= q[0]) { + minHeap.emplace(intervals[i][1] - intervals[i][0] + 1, intervals[i][1]); + ++i; + } + while (!minHeap.empty() && minHeap.top().right < q[0]) + minHeap.pop(); + if (!minHeap.empty()) + ans[q[1]] = minHeap.top().size; + } + + return ans; + } +}; diff --git a/solutions/1851. Minimum Interval to Include Each Query/1851.java b/solutions/1851. Minimum Interval to Include Each Query/1851.java new file mode 100644 index 00000000000..8dc7217f778 --- /dev/null +++ b/solutions/1851. Minimum Interval to Include Each Query/1851.java @@ -0,0 +1,37 @@ +class T { + public int size; + public int right; + public T(int size, int right) { + this.size = size; + this.right = right; + } +} + +class Solution { + public int[] minInterval(int[][] intervals, int[] queries) { + int[] ans = new int[queries.length]; + Arrays.fill(ans, -1); + Queue minHeap = new Queue((a, b) -> a.size - b.size); + Integer[] indices = new Integer[queries.length]; + + for (int i = 0; i < queries.length; ++i) + indices[i] = i; + + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + Arrays.sort(indices, (a, b) -> queries[a] - queries[b]); + + int i = 0; // intervals' index + for (final int index : indices) { + while (i < intervals.length && intervals[i][0] <= queries[index]) { + minHeap.offer(new T(intervals[i][1] - intervals[i][0] + 1, intervals[i][1])); + ++i; + } + while (!minHeap.isEmpty() && minHeap.peek().right < queries[index]) + minHeap.poll(); + if (!minHeap.isEmpty()) + ans[index] = minHeap.peek().size; + } + + return ans; + } +} diff --git a/solutions/1852. Distinct Numbers in Each Subarray/1852.cpp b/solutions/1852. Distinct Numbers in Each Subarray/1852.cpp new file mode 100644 index 00000000000..5fd61225026 --- /dev/null +++ b/solutions/1852. Distinct Numbers in Each Subarray/1852.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector distinctNumbers(vector& nums, int k) { + vector ans; + int distinct = 0; + unordered_map count; + + for (int i = 0; i < nums.size(); ++i) { + if (++count[nums[i]] == 1) + ++distinct; + if (i >= k && --count[nums[i - k]] == 0) + --distinct; + if (i >= k - 1) + ans.push_back(distinct); + } + + return ans; + } +}; diff --git a/solutions/1852. Distinct Numbers in Each Subarray/1852.java b/solutions/1852. Distinct Numbers in Each Subarray/1852.java new file mode 100644 index 00000000000..de87efba2af --- /dev/null +++ b/solutions/1852. Distinct Numbers in Each Subarray/1852.java @@ -0,0 +1,18 @@ +class Solution { + public int[] distinctNumbers(int[] nums, int k) { + int[] ans = new int[nums.length - k + 1]; + int distinct = 0; + Map count = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + if (count.merge(nums[i], 1, Integer::sum) == 1) + ++distinct; + if (i >= k && count.merge(nums[i - k], -1, Integer::sum) == 0) + --distinct; + if (i >= k - 1) + ans[i - k + 1] = distinct; + } + + return ans; + } +} diff --git a/solutions/1852. Distinct Numbers in Each Subarray/1852.py b/solutions/1852. Distinct Numbers in Each Subarray/1852.py new file mode 100644 index 00000000000..db41a8db399 --- /dev/null +++ b/solutions/1852. Distinct Numbers in Each Subarray/1852.py @@ -0,0 +1,18 @@ +class Solution: + def distinctNumbers(self, nums: List[int], k: int) -> List[int]: + ans = [] + count = collections.Counter() + distinct = 0 + + for i, num in enumerate(nums): + count[num] += 1 + if count[num] == 1: + distinct += 1 + if i >= k: + count[nums[i - k]] -= 1 + if count[nums[i - k]] == 0: + distinct -= 1 + if i >= k - 1: + ans.append(distinct) + + return ans diff --git a/solutions/1853. Convert Date Format/1853.sql b/solutions/1853. Convert Date Format/1853.sql new file mode 100644 index 00000000000..a0f8b5457b4 --- /dev/null +++ b/solutions/1853. Convert Date Format/1853.sql @@ -0,0 +1,2 @@ +SELECT DATE_FORMAT(day, '%W, %M %e, %Y') AS day +FROM Days diff --git a/solutions/1854. Maximum Population Year/1854.cpp b/solutions/1854. Maximum Population Year/1854.cpp new file mode 100644 index 00000000000..debb8664ac6 --- /dev/null +++ b/solutions/1854. Maximum Population Year/1854.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maximumPopulation(vector>& logs) { + constexpr int kMinYear = 1950; + constexpr int kMaxYear = 2050; + int ans = 0; + int maxPopulation = 0; + int runningPopulation = 0; + // population[i] := the population of year i + vector population(kMaxYear + 1); + + for (const vector& log : logs) { + const int birth = log[0]; + const int death = log[1]; + ++population[birth]; + --population[death]; + } + + for (int year = kMinYear; year <= kMaxYear; ++year) { + runningPopulation += population[year]; + if (runningPopulation > maxPopulation) { + maxPopulation = runningPopulation; + ans = year; + } + } + + return ans; + } +}; diff --git a/solutions/1854. Maximum Population Year/1854.java b/solutions/1854. Maximum Population Year/1854.java new file mode 100644 index 00000000000..59c99030e66 --- /dev/null +++ b/solutions/1854. Maximum Population Year/1854.java @@ -0,0 +1,28 @@ +class Solution { + public int maximumPopulation(int[][] logs) { + final int kMinYear = 1950; + final int kMaxYear = 2050; + int ans = 0; + int maxPopulation = 0; + int runningPopulation = 0; + // population[i] := the population of year i + int[] population = new int[kMaxYear + 1]; + + for (int[] log : logs) { + final int birth = log[0]; + final int death = log[1]; + ++population[birth]; + --population[death]; + } + + for (int year = kMinYear; year <= kMaxYear; ++year) { + runningPopulation += population[year]; + if (runningPopulation > maxPopulation) { + maxPopulation = runningPopulation; + ans = year; + } + } + + return ans; + } +} diff --git a/solutions/1854. Maximum Population Year/1854.py b/solutions/1854. Maximum Population Year/1854.py new file mode 100644 index 00000000000..4f87f77f20c --- /dev/null +++ b/solutions/1854. Maximum Population Year/1854.py @@ -0,0 +1,21 @@ +class Solution: + def maximumPopulation(self, logs: List[List[int]]) -> int: + kMinYear = 1950 + kMaxYear = 2050 + ans = 0 + maxPopulation = 0 + runningPopulation = 0 + # population[i] := the population of year i + population = [0] * (kMaxYear + 1) + + for birth, death in logs: + population[birth] += 1 + population[death] -= 1 + + for year in range(kMinYear, kMaxYear + 1): + runningPopulation += population[year] + if runningPopulation > maxPopulation: + maxPopulation = runningPopulation + ans = year + + return ans diff --git a/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.cpp b/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.cpp new file mode 100644 index 00000000000..2f5eb5520c4 --- /dev/null +++ b/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int maxDistance(vector& nums1, vector& nums2) { + int i = 0; + int j = 0; + + for (; i < nums1.size() && j < nums2.size(); ++j) + if (nums1[i] > nums2[j]) + ++i; + + return i == j ? 0 : j - i - 1; + } +}; diff --git a/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.java b/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.java new file mode 100644 index 00000000000..5a88e5790e5 --- /dev/null +++ b/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.java @@ -0,0 +1,12 @@ +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int i = 0; + int j = 0; + + for (; i < nums1.length && j < nums2.length; ++j) + if (nums1[i] > nums2[j]) + ++i; + + return i == j ? 0 : j - i - 1; + } +} diff --git a/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.py b/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.py new file mode 100644 index 00000000000..e41afaf58b2 --- /dev/null +++ b/solutions/1855. Maximum Distance Between a Pair of Values/1855-2.py @@ -0,0 +1,11 @@ +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + i = 0 + j = 0 + + while i < len(nums1) and j < len(nums2): + if nums1[i] > nums2[j]: + i += 1 + j += 1 + + return 0 if i == j else j - i - 1 diff --git a/solutions/1855. Maximum Distance Between a Pair of Values/1855.cpp b/solutions/1855. Maximum Distance Between a Pair of Values/1855.cpp new file mode 100644 index 00000000000..d0c45699b27 --- /dev/null +++ b/solutions/1855. Maximum Distance Between a Pair of Values/1855.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxDistance(vector& nums1, vector& nums2) { + int ans = 0; + int i = 0; + int j = 0; + + while (i < nums1.size() && j < nums2.size()) + if (nums1[i] > nums2[j]) + ++i; + else + ans = max(ans, j++ - i); + + return ans; + } +}; diff --git a/solutions/1855. Maximum Distance Between a Pair of Values/1855.java b/solutions/1855. Maximum Distance Between a Pair of Values/1855.java new file mode 100644 index 00000000000..fe9d22ff705 --- /dev/null +++ b/solutions/1855. Maximum Distance Between a Pair of Values/1855.java @@ -0,0 +1,15 @@ +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int ans = 0; + int i = 0; + int j = 0; + + while (i < nums1.length && j < nums2.length) + if (nums1[i] > nums2[j]) + ++i; + else + ans = Math.max(ans, j++ - i); + + return ans; + } +} diff --git a/solutions/1855. Maximum Distance Between a Pair of Values/1855.py b/solutions/1855. Maximum Distance Between a Pair of Values/1855.py new file mode 100644 index 00000000000..83c756ca173 --- /dev/null +++ b/solutions/1855. Maximum Distance Between a Pair of Values/1855.py @@ -0,0 +1,14 @@ +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + ans = 0 + i = 0 + j = 0 + + while i < len(nums1) and j < len(nums2): + if nums1[i] > nums2[j]: + i += 1 + else: + ans = max(ans, j - i) + j += 1 + + return ans diff --git a/solutions/1856. Maximum Subarray Min-Product/1856.cpp b/solutions/1856. Maximum Subarray Min-Product/1856.cpp new file mode 100644 index 00000000000..ab989655086 --- /dev/null +++ b/solutions/1856. Maximum Subarray Min-Product/1856.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maxSumMinProduct(vector& nums) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + stack stack; + vector prefix(nums.size() + 1); + + for (int i = 0; i < nums.size(); ++i) + prefix[i + 1] = prefix[i] + nums[i]; + + for (int i = 0; i <= nums.size(); ++i) { + while (!stack.empty() && + (i == nums.size() || nums[stack.top()] > nums[i])) { + const int minVal = nums[stack.top()]; + stack.pop(); + const long sum = + stack.empty() ? prefix[i] : prefix[i] - prefix[stack.top() + 1]; + ans = max(ans, minVal * sum); + } + stack.push(i); + } + + return ans % kMod; + } +}; diff --git a/solutions/1856. Maximum Subarray Min-Product/1856.java b/solutions/1856. Maximum Subarray Min-Product/1856.java new file mode 100644 index 00000000000..f08b60efc20 --- /dev/null +++ b/solutions/1856. Maximum Subarray Min-Product/1856.java @@ -0,0 +1,22 @@ +class Solution { + public int maxSumMinProduct(int[] nums) { + final int kMod = 1_000_000_007; + long ans = 0; + Deque stack = new ArrayDeque<>(); + long[] prefix = new long[nums.length + 1]; + + for (int i = 0; i < nums.length; ++i) + prefix[i + 1] = prefix[i] + nums[i]; + + for (int i = 0; i <= nums.length; ++i) { + while (!stack.isEmpty() && (i == nums.length || nums[stack.peek()] > nums[i])) { + final int minVal = nums[stack.pop()]; + final long sum = stack.isEmpty() ? prefix[i] : prefix[i] - prefix[stack.peek() + 1]; + ans = Math.max(ans, minVal * sum); + } + stack.push(i); + } + + return (int) (ans % kMod); + } +} diff --git a/solutions/1856. Maximum Subarray Min-Product/1856.py b/solutions/1856. Maximum Subarray Min-Product/1856.py new file mode 100644 index 00000000000..11d412d7ffb --- /dev/null +++ b/solutions/1856. Maximum Subarray Min-Product/1856.py @@ -0,0 +1,14 @@ +class Solution: + def maxSumMinProduct(self, nums: List[int]) -> int: + ans = 0 + stack = [] + prefix = [0] + list(itertools.accumulate(nums)) + + for i in range(len(nums) + 1): + while stack and (i == len(nums) or nums[stack[-1]] > nums[i]): + minVal = nums[stack.pop()] + summ = prefix[i] - prefix[stack[-1] + 1] if stack else prefix[i] + ans = max(ans, minVal * summ) + stack.append(i) + + return ans % int(1e9 + 7) diff --git a/solutions/1857. Largest Color Value in a Directed Graph/1857.cpp b/solutions/1857. Largest Color Value in a Directed Graph/1857.cpp new file mode 100644 index 00000000000..e51b7b5b07b --- /dev/null +++ b/solutions/1857. Largest Color Value in a Directed Graph/1857.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int largestPathValue(string colors, vector>& edges) { + const int n = colors.length(); + int ans = 0; + int processed = 0; + vector> graph(n); + vector inDegrees(n); + queue q; + vector> count(n, vector(26)); + + // Build the graph. + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + while (!q.empty()) { + const int out = q.front(); + q.pop(); + ++processed; + ans = max(ans, ++count[out][colors[out] - 'a']); + for (const int in : graph[out]) { + for (int i = 0; i < 26; ++i) + count[in][i] = max(count[in][i], count[out][i]); + if (--inDegrees[in] == 0) + q.push(in); + } + } + + return processed == n ? ans : -1; + } +}; diff --git a/solutions/1857. Largest Color Value in a Directed Graph/1857.java b/solutions/1857. Largest Color Value in a Directed Graph/1857.java new file mode 100644 index 00000000000..46df0c76b77 --- /dev/null +++ b/solutions/1857. Largest Color Value in a Directed Graph/1857.java @@ -0,0 +1,41 @@ +class Solution { + public int largestPathValue(String colors, int[][] edges) { + final int n = colors.length(); + int ans = 0; + int processed = 0; + List[] graph = new List[n]; + int[] inDegrees = new int[n]; + int[][] count = new int[n][26]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph. + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + Queue q = IntStream.range(0, n) + .filter(i -> inDegrees[i] == 0) + .boxed() + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + final int out = q.poll(); + ++processed; + ans = Math.max(ans, ++count[out][colors.charAt(out) - 'a']); + for (final int in : graph[out]) { + for (int i = 0; i < 26; ++i) + count[in][i] = Math.max(count[in][i], count[out][i]); + if (--inDegrees[in] == 0) + q.offer(in); + } + } + + return processed == n ? ans : -1; + } +} diff --git a/solutions/1857. Largest Color Value in a Directed Graph/1857.py b/solutions/1857. Largest Color Value in a Directed Graph/1857.py new file mode 100644 index 00000000000..3611ff4c2cd --- /dev/null +++ b/solutions/1857. Largest Color Value in a Directed Graph/1857.py @@ -0,0 +1,33 @@ +class Solution: + def largestPathValue(self, colors: str, edges: List[List[int]]) -> int: + n = len(colors) + ans = 0 + processed = 0 + graph = [[] for _ in range(n)] + inDegrees = [0] * n + q = collections.deque() + count = [[0] * 26 for _ in range(n)] + + # Build the graph. + for u, v in edges: + graph[u].append(v) + inDegrees[v] += 1 + + # Vpology + for i, degree in enumerate(inDegrees): + if degree == 0: + q.append(i) + + while q: + u = q.popleft() + processed += 1 + count[u][ord(colors[u]) - ord('a')] += 1 + ans = max(ans, count[u][ord(colors[u]) - ord('a')]) + for v in graph[u]: + for i in range(26): + count[v][i] = max(count[v][i], count[u][i]) + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + + return ans if processed == n else -1 diff --git a/solutions/1858. Longest Word With All Prefixes/1858.cpp b/solutions/1858. Longest Word With All Prefixes/1858.cpp new file mode 100644 index 00000000000..83fc418dce6 --- /dev/null +++ b/solutions/1858. Longest Word With All Prefixes/1858.cpp @@ -0,0 +1,50 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class Solution { + public: + string longestWord(vector& words) { + string ans; + + for (const string& word : words) + insert(word); + + for (const string& word : words) { + if (!allPrefixed(word)) + continue; + if (ans.length() < word.length() || + (ans.length() == word.length() && ans > word)) + ans = word; + } + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->isWord = true; + } + + bool allPrefixed(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + node = node->children[i]; + if (!node->isWord) + return false; + } + return true; + } +}; diff --git a/solutions/1858. Longest Word With All Prefixes/1858.java b/solutions/1858. Longest Word With All Prefixes/1858.java new file mode 100644 index 00000000000..0f5f12f70c1 --- /dev/null +++ b/solutions/1858. Longest Word With All Prefixes/1858.java @@ -0,0 +1,47 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class Solution { + public String longestWord(String[] words) { + String ans = ""; + + for (final String word : words) + insert(word); + + for (final String word : words) { + if (!allPrefixed(word)) + continue; + if (ans.length() < word.length() || + (ans.length() == word.length() && ans.compareTo(word) > 0)) + ans = word; + } + + return ans; + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + private boolean allPrefixed(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + node = node.children[i]; + if (!node.isWord) + return false; + } + return true; + } +} diff --git a/solutions/1858. Longest Word With All Prefixes/1858.py b/solutions/1858. Longest Word With All Prefixes/1858.py new file mode 100644 index 00000000000..d6ee9ad65a6 --- /dev/null +++ b/solutions/1858. Longest Word With All Prefixes/1858.py @@ -0,0 +1,33 @@ +class Solution: + def __init__(self): + self.root = {} + + def longestWord(self, words: List[str]) -> str: + ans = '' + + for word in words: + self.insert(word) + + for word in words: + if not self.allPrefixed(word): + continue + if len(ans) < len(word) or (len(ans) == len(word) and ans > word): + ans = word + + return ans + + def insert(self, word: str) -> None: + node = self.root + for c in word: + if c not in node: + node[c] = {} + node = node[c] + node['isWord'] = True + + def allPrefixed(self, word: str) -> bool: + node = self.root + for c in word: + node = node[c] + if 'isWord' not in node: + return False + return True diff --git a/solutions/1859. Sorting the Sentence/1859.cpp b/solutions/1859. Sorting the Sentence/1859.cpp new file mode 100644 index 00000000000..acac3eb5928 --- /dev/null +++ b/solutions/1859. Sorting the Sentence/1859.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string sortSentence(string s) { + vector words; + istringstream iss(s); + string word; + + while (iss >> word) + words.push_back(word); + + ranges::sort(words, [](const string& a, const string& b) { + return a.back() < b.back(); + }); + + string ans = trim(words[0]); + + for (int i = 1; i < words.size(); ++i) + ans += " " + trim(words[i]); + + return ans; + } + + private: + string trim(const string& s) { + return s.substr(0, s.length() - 1); + } +}; diff --git a/solutions/1859. Sorting the Sentence/1859.java b/solutions/1859. Sorting the Sentence/1859.java new file mode 100644 index 00000000000..de75cd9ef84 --- /dev/null +++ b/solutions/1859. Sorting the Sentence/1859.java @@ -0,0 +1,18 @@ +class Solution { + public String sortSentence(String s) { + String[] words = s.split(" "); + + Arrays.sort(words, (a, b) -> a.charAt(a.length() - 1) - b.charAt(b.length() - 1)); + + StringBuilder sb = new StringBuilder(trim(words[0])); + + for (int i = 1; i < words.length; ++i) + sb.append(" ").append(trim(words[i])); + + return sb.toString(); + } + + private String trim(final String s) { + return s.substring(0, s.length() - 1); + } +} diff --git a/solutions/1859. Sorting the Sentence/1859.py b/solutions/1859. Sorting the Sentence/1859.py new file mode 100644 index 00000000000..35a46df314f --- /dev/null +++ b/solutions/1859. Sorting the Sentence/1859.py @@ -0,0 +1,3 @@ +class Solution: + def sortSentence(self, s: str) -> str: + return ' '.join([w[:-1] for w in sorted(s.split(), key=lambda x: x[-1])]) diff --git a/solutions/186. Reverse Words in a String II/186.cpp b/solutions/186. Reverse Words in a String II/186.cpp new file mode 100644 index 00000000000..0cd08d4f589 --- /dev/null +++ b/solutions/186. Reverse Words in a String II/186.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + void reverseWords(vector& s) { + reverse(s.begin(), s.end()); // Reverse the whole string. + reverseWords(s, s.size()); // Reverse each word. + } + + private: + void reverseWords(vector& s, int n) { + int i = 0; + int j = 0; + + while (i < n) { + while (i < j || i < n && s[i] == ' ') // Skip the spaces. + ++i; + while (j < i || j < n && s[j] != ' ') // Skip the spaces. + ++j; + reverse(s.begin() + i, s.begin() + j); // Reverse the word. + } + } +}; diff --git a/solutions/186. Reverse Words in a String II/186.java b/solutions/186. Reverse Words in a String II/186.java new file mode 100644 index 00000000000..d384ce1bb93 --- /dev/null +++ b/solutions/186. Reverse Words in a String II/186.java @@ -0,0 +1,27 @@ +class Solution { + public void reverseWords(char[] s) { + reverse(s, 0, s.length - 1); // Reverse the whole string. + reverseWords(s, s.length); // Reverse each word. + } + + private void reverse(char[] s, int l, int r) { + while (l < r) { + final char c = s[l]; + s[l++] = s[r]; + s[r--] = c; + } + } + + private void reverseWords(char[] s, int n) { + int i = 0; + int j = 0; + + while (i < n) { + while (i < j || i < n && s[i] == ' ') // Skip the spaces. + ++i; + while (j < i || j < n && s[j] != ' ') // Skip the spaces. + ++j; + reverse(s, i, j - 1); // Reverse the word. + } + } +} diff --git a/solutions/186. Reverse Words in a String II/186.py b/solutions/186. Reverse Words in a String II/186.py new file mode 100644 index 00000000000..37fd8d0138e --- /dev/null +++ b/solutions/186. Reverse Words in a String II/186.py @@ -0,0 +1,21 @@ +class Solution: + def reverseWords(self, s: List[str]) -> None: + def reverse(l: int, r: int) -> None: + while l < r: + s[l], s[r] = s[r], s[l] + l += 1 + r -= 1 + + def reverseWords(n: int) -> None: + i = 0 + j = 0 + + while i < n: + while i < j or (i < n and s[i] == ' '): # Skip the spaces. + i += 1 + while j < i or (j < n and s[j] != ' '): # Skip the spaces. + j += 1 + reverse(i, j - 1) # Reverse the word. + + reverse(0, len(s) - 1) # Reverse the whole string. + reverseWords(len(s)) # Reverse each word. diff --git a/solutions/1860. Incremental Memory Leak/1860.cpp b/solutions/1860. Incremental Memory Leak/1860.cpp new file mode 100644 index 00000000000..7b75cbdbafe --- /dev/null +++ b/solutions/1860. Incremental Memory Leak/1860.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector memLeak(int memory1, int memory2) { + int i = 1; + + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) + memory1 -= i; + else + memory2 -= i; + ++i; + } + + return {i, memory1, memory2}; + } +}; diff --git a/solutions/1860. Incremental Memory Leak/1860.java b/solutions/1860. Incremental Memory Leak/1860.java new file mode 100644 index 00000000000..5903bb107fe --- /dev/null +++ b/solutions/1860. Incremental Memory Leak/1860.java @@ -0,0 +1,15 @@ +class Solution { + public int[] memLeak(int memory1, int memory2) { + int i = 1; + + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) + memory1 -= i; + else + memory2 -= i; + ++i; + } + + return new int[] {i, memory1, memory2}; + } +} diff --git a/solutions/1860. Incremental Memory Leak/1860.py b/solutions/1860. Incremental Memory Leak/1860.py new file mode 100644 index 00000000000..a7225b2f3e5 --- /dev/null +++ b/solutions/1860. Incremental Memory Leak/1860.py @@ -0,0 +1,12 @@ +class Solution: + def memLeak(self, memory1: int, memory2: int) -> List[int]: + i = 1 + + while memory1 >= i or memory2 >= i: + if memory1 >= memory2: + memory1 -= i + else: + memory2 -= i + i += 1 + + return [i, memory1, memory2] diff --git a/solutions/1861. Rotating the Box/1861.cpp b/solutions/1861. Rotating the Box/1861.cpp new file mode 100644 index 00000000000..9938bc174a9 --- /dev/null +++ b/solutions/1861. Rotating the Box/1861.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector> rotateTheBox(vector>& box) { + const int m = box.size(); + const int n = box[0].size(); + vector> ans(n, vector(m, '.')); + + for (int i = 0; i < m; ++i) + for (int j = n - 1, k = n - 1; j >= 0; --j) + if (box[i][j] != '.') { + if (box[i][j] == '*') + k = j; + ans[k--][m - i - 1] = box[i][j]; + } + + return ans; + } +}; diff --git a/solutions/1861. Rotating the Box/1861.java b/solutions/1861. Rotating the Box/1861.java new file mode 100644 index 00000000000..a9686bae3db --- /dev/null +++ b/solutions/1861. Rotating the Box/1861.java @@ -0,0 +1,18 @@ +class Solution { + public char[][] rotateTheBox(char[][] box) { + final int m = box.length; + final int n = box[0].length; + char[][] ans = new char[n][m]; + Arrays.stream(ans).forEach(row -> Arrays.fill(row, '.')); + + for (int i = 0; i < m; ++i) + for (int j = n - 1, k = n - 1; j >= 0; --j) + if (box[i][j] != '.') { + if (box[i][j] == '*') + k = j; + ans[k--][m - i - 1] = box[i][j]; + } + + return ans; + } +} diff --git a/solutions/1861. Rotating the Box/1861.py b/solutions/1861. Rotating the Box/1861.py new file mode 100644 index 00000000000..d0df35ea468 --- /dev/null +++ b/solutions/1861. Rotating the Box/1861.py @@ -0,0 +1,16 @@ +class Solution: + def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: + m = len(box) + n = len(box[0]) + rotated = [['.'] * m for _ in range(n)] + + for i in range(m): + k = n - 1 + for j in reversed(range(n)): + if box[i][j] != '.': + if box[i][j] == '*': + k = j + rotated[k][m - i - 1] = box[i][j] + k -= 1 + + return [''.join(row) for row in rotated] diff --git a/solutions/1862. Sum of Floored Pairs/1862.cpp b/solutions/1862. Sum of Floored Pairs/1862.cpp new file mode 100644 index 00000000000..162c6055930 --- /dev/null +++ b/solutions/1862. Sum of Floored Pairs/1862.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int sumOfFlooredPairs(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int kMax = ranges::max(nums); + long ans = 0; + // count[i] := the number of `nums` <= i + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int i = 1; i <= kMax; ++i) + count[i] += count[i - 1]; + + for (int i = 1; i <= kMax; ++i) + if (count[i] > count[i - 1]) { + long sum = 0; + for (int j = 1; i * j <= kMax; ++j) { + const int lo = i * j - 1; + const int hi = i * (j + 1) - 1; + sum += (count[min(hi, kMax)] - count[lo]) * j; + } + ans += sum * (count[i] - count[i - 1]); + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/1862. Sum of Floored Pairs/1862.java b/solutions/1862. Sum of Floored Pairs/1862.java new file mode 100644 index 00000000000..747e843b901 --- /dev/null +++ b/solutions/1862. Sum of Floored Pairs/1862.java @@ -0,0 +1,29 @@ +class Solution { + public int sumOfFlooredPairs(int[] nums) { + final int kMod = 1_000_000_007; + final int kMax = Arrays.stream(nums).max().getAsInt(); + long ans = 0; + // count[i] := the number of `nums` <= i + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int i = 1; i <= kMax; ++i) + count[i] += count[i - 1]; + + for (int i = 1; i <= kMax; ++i) + if (count[i] > count[i - 1]) { + long sum = 0; + for (int j = 1; i * j <= kMax; ++j) { + final int lo = i * j - 1; + final int hi = i * (j + 1) - 1; + sum += (count[Math.min(hi, kMax)] - count[lo]) * (long) j; + } + ans += sum * (count[i] - count[i - 1]); + ans %= kMod; + } + + return (int) ans; + } +} diff --git a/solutions/1862. Sum of Floored Pairs/1862.py b/solutions/1862. Sum of Floored Pairs/1862.py new file mode 100644 index 00000000000..a9c1f5296e8 --- /dev/null +++ b/solutions/1862. Sum of Floored Pairs/1862.py @@ -0,0 +1,26 @@ +class Solution: + def sumOfFlooredPairs(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + kMax = max(nums) + ans = 0 + count = [0] * (kMax + 1) + + for num in nums: + count[num] += 1 + + for i in range(1, kMax + 1): + count[i] += count[i - 1] + + for i in range(1, kMax + 1): + if count[i] > count[i - 1]: + summ = 0 + j = 1 + while i * j <= kMax: + lo = i * j - 1 + hi = i * (j + 1) - 1 + summ += (count[min(hi, kMax)] - count[lo]) * j + j += 1 + ans += summ * (count[i] - count[i - 1]) + ans %= kMod + + return ans diff --git a/solutions/1863. Sum of All Subset XOR Totals/1863-2.cpp b/solutions/1863. Sum of All Subset XOR Totals/1863-2.cpp new file mode 100644 index 00000000000..4909bbb9585 --- /dev/null +++ b/solutions/1863. Sum of All Subset XOR Totals/1863-2.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int subsetXORSum(vector& nums) { + return accumulate(nums.begin(), nums.end(), 0, bit_or<>()) + << nums.size() - 1; + } +}; diff --git a/solutions/1863. Sum of All Subset XOR Totals/1863-2.java b/solutions/1863. Sum of All Subset XOR Totals/1863-2.java new file mode 100644 index 00000000000..eb228957ff3 --- /dev/null +++ b/solutions/1863. Sum of All Subset XOR Totals/1863-2.java @@ -0,0 +1,5 @@ +class Solution { + public int subsetXORSum(int[] nums) { + return Arrays.stream(nums).reduce((a, b) -> a | b).getAsInt() << nums.length - 1; + } +} diff --git a/solutions/1863. Sum of All Subset XOR Totals/1863-2.py b/solutions/1863. Sum of All Subset XOR Totals/1863-2.py new file mode 100644 index 00000000000..2d84b90bc08 --- /dev/null +++ b/solutions/1863. Sum of All Subset XOR Totals/1863-2.py @@ -0,0 +1,3 @@ +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + return functools.reduce(operator.or_, nums) << len(nums) - 1 diff --git a/solutions/1863. Sum of All Subset XOR Totals/1863.cpp b/solutions/1863. Sum of All Subset XOR Totals/1863.cpp new file mode 100644 index 00000000000..a9ff15b9784 --- /dev/null +++ b/solutions/1863. Sum of All Subset XOR Totals/1863.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int subsetXORSum(vector& nums) { + return dfs(nums, 0, 0); + } + + private: + int dfs(const vector& nums, int i, int xors) { + if (i == nums.size()) + return xors; + + const int x = dfs(nums, i + 1, xors); + const int y = dfs(nums, i + 1, nums[i] ^ xors); + return x + y; + } +}; diff --git a/solutions/1863. Sum of All Subset XOR Totals/1863.java b/solutions/1863. Sum of All Subset XOR Totals/1863.java new file mode 100644 index 00000000000..3efd1c6abcf --- /dev/null +++ b/solutions/1863. Sum of All Subset XOR Totals/1863.java @@ -0,0 +1,14 @@ +class Solution { + public int subsetXORSum(int[] nums) { + return dfs(nums, 0, 0); + } + + private int dfs(int[] nums, int i, int xors) { + if (i == nums.length) + return xors; + + final int x = dfs(nums, i + 1, xors); + final int y = dfs(nums, i + 1, nums[i] ^ xors); + return x + y; + } +} diff --git a/solutions/1863. Sum of All Subset XOR Totals/1863.py b/solutions/1863. Sum of All Subset XOR Totals/1863.py new file mode 100644 index 00000000000..0944e919de1 --- /dev/null +++ b/solutions/1863. Sum of All Subset XOR Totals/1863.py @@ -0,0 +1,11 @@ +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(i: int, xors: int) -> int: + if i == len(nums): + return xors + + x = dfs(i + 1, xors) + y = dfs(i + 1, nums[i] ^ xors) + return x + y + + return dfs(0, 0) diff --git a/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.cpp b/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.cpp new file mode 100644 index 00000000000..24c2991d70c --- /dev/null +++ b/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minSwaps(string s) { + const int ones = ranges::count(s, '1'); + const int zeros = s.length() - ones; + if (abs(ones - zeros) > 1) + return -1; + if (ones > zeros) + return countSwaps(s, '1'); + if (zeros > ones) + return countSwaps(s, '0'); + return min(countSwaps(s, '1'), countSwaps(s, '0')); + } + + private: + int countSwaps(const string& s, char curr) { + int swaps = 0; + for (const char c : s) { + if (c != curr) + ++swaps; + curr ^= 1; + } + return swaps / 2; + } +}; diff --git a/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.java b/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.java new file mode 100644 index 00000000000..1815c2b661e --- /dev/null +++ b/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.java @@ -0,0 +1,23 @@ +class Solution { + public int minSwaps(String s) { + final int ones = (int) s.chars().filter(c -> c == '1').count(); + final int zeros = s.length() - ones; + if (Math.abs(ones - zeros) > 1) + return -1; + if (ones > zeros) + return countSwaps(s, '1'); + if (zeros > ones) + return countSwaps(s, '0'); + return Math.min(countSwaps(s, '1'), countSwaps(s, '0')); + } + + private int countSwaps(final String s, char curr) { + int swaps = 0; + for (final char c : s.toCharArray()) { + if (c != curr) + ++swaps; + curr ^= 1; + } + return swaps / 2; + } +} diff --git a/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.py b/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.py new file mode 100644 index 00000000000..bb1e1179c9c --- /dev/null +++ b/solutions/1864. Minimum Number of Swaps to Make the Binary String Alternating/1864.py @@ -0,0 +1,20 @@ +class Solution: + def minSwaps(self, s: str) -> int: + ones = s.count('1') + zeros = len(s) - ones + if abs(ones - zeros) > 1: + return -1 + + def countSwaps(curr: str) -> int: + swaps = 0 + for c in s: + if c != curr: + swaps += 1 + curr = chr(ord(curr) ^ 1) + return swaps // 2 + + if ones > zeros: + return countSwaps('1') + if zeros > ones: + return countSwaps('0') + return min(countSwaps('1'), countSwaps('0')) diff --git a/solutions/1865. Finding Pairs With a Certain Sum/1865.cpp b/solutions/1865. Finding Pairs With a Certain Sum/1865.cpp new file mode 100644 index 00000000000..8ffdc2b4f3e --- /dev/null +++ b/solutions/1865. Finding Pairs With a Certain Sum/1865.cpp @@ -0,0 +1,29 @@ +class FindSumPairs { + public: + FindSumPairs(vector& nums1, vector& nums2) + : nums1(nums1), nums2(nums2) { + for (const int num : nums2) + ++count2[num]; + } + + void add(int index, int val) { + --count2[nums2[index]]; + nums2[index] += val; + ++count2[nums2[index]]; + } + + int count(int tot) { + int ans = 0; + for (const int num : nums1) { + const int target = tot - num; + if (const auto it = count2.find(target); it != count2.cend()) + ans += it->second; + } + return ans; + } + + private: + vector nums1; + vector nums2; + unordered_map count2; +}; diff --git a/solutions/1865. Finding Pairs With a Certain Sum/1865.java b/solutions/1865. Finding Pairs With a Certain Sum/1865.java new file mode 100644 index 00000000000..bc3e5a16b2a --- /dev/null +++ b/solutions/1865. Finding Pairs With a Certain Sum/1865.java @@ -0,0 +1,25 @@ +class FindSumPairs { + public FindSumPairs(int[] nums1, int[] nums2) { + this.nums1 = nums1; + this.nums2 = nums2; + for (final int num : nums2) + count2.merge(num, 1, Integer::sum); + } + + public void add(int index, int val) { + count2.merge(nums2[index], -1, Integer::sum); + nums2[index] += val; + count2.merge(nums2[index], 1, Integer::sum); + } + + public int count(int tot) { + int ans = 0; + for (final int num : nums1) + ans += count2.getOrDefault(tot - num, 0); + return ans; + } + + private int[] nums1; + private int[] nums2; + private Map count2 = new HashMap<>(); +} diff --git a/solutions/1865. Finding Pairs With a Certain Sum/1865.py b/solutions/1865. Finding Pairs With a Certain Sum/1865.py new file mode 100644 index 00000000000..69c33d25220 --- /dev/null +++ b/solutions/1865. Finding Pairs With a Certain Sum/1865.py @@ -0,0 +1,16 @@ +class FindSumPairs: + def __init__(self, nums1: List[int], nums2: List[int]): + self.nums1 = nums1 + self.nums2 = nums2 + self.count2 = collections.Counter(nums2) + + def add(self, index: int, val: int) -> None: + self.count2[self.nums2[index]] -= 1 + self.nums2[index] += val + self.count2[self.nums2[index]] += 1 + + def count(self, tot: int) -> int: + ans = 0 + for num in self.nums1: + ans += self.count2[tot - num] + return ans diff --git a/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.cpp b/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.cpp new file mode 100644 index 00000000000..c212d5762b1 --- /dev/null +++ b/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long rearrangeSticks(int n, int k) { + if (n == k) + return 1; + if (k == 0) + return 0; + if (dp[n][k]) + return dp[n][k]; + return dp[n][k] = (rearrangeSticks(n - 1, k - 1) + + rearrangeSticks(n - 1, k) * (n - 1)) % + kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + vector> dp = vector>(1001, vector(1001)); +}; diff --git a/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.java b/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.java new file mode 100644 index 00000000000..78add4a27b3 --- /dev/null +++ b/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.java @@ -0,0 +1,16 @@ +class Solution { + public int rearrangeSticks(int n, int k) { + if (n == k) + return 1; + if (k == 0) + return 0; + if (dp[n][k] != 0) + return dp[n][k]; + return dp[n][k] = (int) (((long) rearrangeSticks(n - 1, k - 1) + + (long) rearrangeSticks(n - 1, k) * (n - 1)) % + kMod); + } + + private static final int kMod = 1_000_000_007; + private int[][] dp = new int[1001][1001]; +} diff --git a/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.py b/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.py new file mode 100644 index 00000000000..ff49f45ae91 --- /dev/null +++ b/solutions/1866. Number of Ways to Rearrange Sticks With K Sticks Visible/1866.py @@ -0,0 +1,11 @@ +class Solution: + @functools.lru_cache(None) + def rearrangeSticks(self, n: int, k: int) -> int: + if n == k: + return 1 + if k == 0: + return 0 + return (self.rearrangeSticks(n - 1, k - 1) + + self.rearrangeSticks(n - 1, k) * (n - 1)) % self.kMod + + kMod = 1_000_000_007 diff --git a/solutions/1867. Orders With Maximum Quantity Above Average/1867.sql b/solutions/1867. Orders With Maximum Quantity Above Average/1867.sql new file mode 100644 index 00000000000..b2f3daab105 --- /dev/null +++ b/solutions/1867. Orders With Maximum Quantity Above Average/1867.sql @@ -0,0 +1,12 @@ +WITH + GroupedOrders AS ( + SELECT + order_id, + MAX(quantity) AS max_quantity, + MAX(AVG(quantity)) OVER() AS max_avg_quantity + FROM OrdersDetails + GROUP BY 1 + ) +SELECT order_id +FROM GroupedOrders +WHERE max_quantity > max_avg_quantity; diff --git a/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.cpp b/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.cpp new file mode 100644 index 00000000000..15afb02e887 --- /dev/null +++ b/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> findRLEArray(vector>& encoded1, + vector>& encoded2) { + vector> ans; + int i = 0; // encoded1's index + int j = 0; // encodes2's index + + while (i < encoded1.size() && j < encoded2.size()) { + const int mult = encoded1[i][0] * encoded2[j][0]; + const int minFreq = min(encoded1[i][1], encoded2[j][1]); + if (!ans.empty() && mult == ans.back()[0]) + ans.back()[1] += minFreq; + else + ans.push_back({mult, minFreq}); + encoded1[i][1] -= minFreq; + encoded2[j][1] -= minFreq; + if (encoded1[i][1] == 0) + ++i; + if (encoded2[j][1] == 0) + ++j; + } + + return ans; + } +}; diff --git a/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.java b/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.java new file mode 100644 index 00000000000..83a41c996e7 --- /dev/null +++ b/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.java @@ -0,0 +1,24 @@ +class Solution { + public List> findRLEArray(int[][] encoded1, int[][] encoded2) { + List> ans = new ArrayList<>(); + int i = 0; // encoded1's index + int j = 0; // encodes2's index + + while (i < encoded1.length && j < encoded2.length) { + final int mult = encoded1[i][0] * encoded2[j][0]; + final int minFreq = Math.min(encoded1[i][1], encoded2[j][1]); + if (!ans.isEmpty() && mult == ans.get(ans.size() - 1).get(0)) + ans.get(ans.size() - 1).set(1, ans.get(ans.size() - 1).get(1) + minFreq); + else + ans.add(Arrays.asList(mult, minFreq)); + encoded1[i][1] -= minFreq; + encoded2[j][1] -= minFreq; + if (encoded1[i][1] == 0) + ++i; + if (encoded2[j][1] == 0) + ++j; + } + + return ans; + } +} diff --git a/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.py b/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.py new file mode 100644 index 00000000000..fb19e6715e8 --- /dev/null +++ b/solutions/1868. Product of Two Run-Length Encoded Arrays/1868.py @@ -0,0 +1,22 @@ +class Solution: + def findRLEArray(self, encoded1: List[List[int]], + encoded2: List[List[int]]) -> List[List[int]]: + ans = [] + i = 0 # encoded1's index + j = 0 # encoded2's index + + while i < len(encoded1) and j < len(encoded2): + mult = encoded1[i][0] * encoded2[j][0] + minFreq = min(encoded1[i][1], encoded2[j][1]) + if ans and mult == ans[-1][0]: + ans[-1][1] += minFreq + else: + ans.append([mult, minFreq]) + encoded1[i][1] -= minFreq + encoded2[j][1] -= minFreq + if encoded1[i][1] == 0: + i += 1 + if encoded2[j][1] == 0: + j += 1 + + return ans diff --git a/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.cpp b/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.cpp new file mode 100644 index 00000000000..2af1125e7bb --- /dev/null +++ b/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool checkZeroOnes(string s) { + int longestOnes = 0; + int longestZeros = 0; + int currentOnes = 0; + int currentZeros = 0; + + for (const char c : s) + if (c == '0') { + currentOnes = 0; + longestZeros = max(longestZeros, ++currentZeros); + } else { + currentZeros = 0; + longestOnes = max(longestOnes, ++currentOnes); + } + + return longestOnes > longestZeros; + } +}; diff --git a/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.java b/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.java new file mode 100644 index 00000000000..28402172244 --- /dev/null +++ b/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.java @@ -0,0 +1,19 @@ +class Solution { + public boolean checkZeroOnes(String s) { + int longestOnes = 0; + int longestZeros = 0; + int currentOnes = 0; + int currentZeros = 0; + + for (final char c : s.toCharArray()) + if (c == '0') { + currentOnes = 0; + longestZeros = Math.max(longestZeros, ++currentZeros); + } else { + currentZeros = 0; + longestOnes = Math.max(longestOnes, ++currentOnes); + } + + return longestOnes > longestZeros; + } +} diff --git a/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.py b/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.py new file mode 100644 index 00000000000..6ac5473479e --- /dev/null +++ b/solutions/1869. Longer Contiguous Segments of Ones than Zeros/1869.py @@ -0,0 +1,18 @@ +class Solution: + def checkZeroOnes(self, s: str) -> bool: + longestOnes = 0 + longestZeros = 0 + currentOnes = 0 + currentZeros = 0 + + for c in s: + if c == '0': + currentOnes = 0 + currentZeros += 1 + longestZeros = max(longestZeros, currentZeros) + else: + currentZeros = 0 + currentOnes += 1 + longestOnes = max(longestOnes, currentOnes) + + return longestOnes > longestZeros diff --git a/solutions/187. Repeated DNA Sequences/187.cpp b/solutions/187. Repeated DNA Sequences/187.cpp new file mode 100644 index 00000000000..eab9622aaf2 --- /dev/null +++ b/solutions/187. Repeated DNA Sequences/187.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector findRepeatedDnaSequences(string s) { + unordered_set ans; + unordered_set seen; + const string_view sv(s); + + for (int i = 0; i + 10 <= s.length(); ++i) { + if (seen.contains(sv.substr(i, 10))) + ans.insert(s.substr(i, 10)); + seen.insert(sv.substr(i, 10)); + } + + return {ans.begin(), ans.end()}; + } +}; diff --git a/solutions/187. Repeated DNA Sequences/187.java b/solutions/187. Repeated DNA Sequences/187.java new file mode 100644 index 00000000000..46e2c5b4037 --- /dev/null +++ b/solutions/187. Repeated DNA Sequences/187.java @@ -0,0 +1,15 @@ +class Solution { + public List findRepeatedDnaSequences(String s) { + Set ans = new HashSet<>(); + Set seen = new HashSet<>(); + + for (int i = 0; i + 10 <= s.length(); ++i) { + final String seq = s.substring(i, i + 10); + if (seen.contains(seq)) + ans.add(seq); + seen.add(seq); + } + + return new ArrayList<>(ans); + } +} diff --git a/solutions/187. Repeated DNA Sequences/187.py b/solutions/187. Repeated DNA Sequences/187.py new file mode 100644 index 00000000000..3ab1663badf --- /dev/null +++ b/solutions/187. Repeated DNA Sequences/187.py @@ -0,0 +1,12 @@ +class Solution: + def findRepeatedDnaSequences(self, s: str) -> List[str]: + ans = set() + seen = set() + + for i in range(len(s) - 9): + seq = s[i:i + 10] + if seq in seen: + ans.add(seq) + seen.add(seq) + + return list(ans) diff --git a/solutions/1870. Minimum Speed to Arrive on Time/1870.cpp b/solutions/1870. Minimum Speed to Arrive on Time/1870.cpp new file mode 100644 index 00000000000..968e8011546 --- /dev/null +++ b/solutions/1870. Minimum Speed to Arrive on Time/1870.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int minSpeedOnTime(vector& dist, double hour) { + int ans = -1; + int l = 1; + int r = 1e7; + + while (l <= r) { + const int m = (l + r) / 2; + if (time(dist, hour, m) > hour) { + l = m + 1; + } else { + ans = m; + r = m - 1; + } + } + + return ans; + } + + private: + double time(const vector& dist, double hour, int speed) { + double sum = 0; + for (int i = 0; i < dist.size() - 1; ++i) + sum += ceil((double)dist[i] / speed); + return sum + (double)dist.back() / speed; + } +}; diff --git a/solutions/1870. Minimum Speed to Arrive on Time/1870.java b/solutions/1870. Minimum Speed to Arrive on Time/1870.java new file mode 100644 index 00000000000..955d223c11c --- /dev/null +++ b/solutions/1870. Minimum Speed to Arrive on Time/1870.java @@ -0,0 +1,26 @@ +class Solution { + public int minSpeedOnTime(int[] dist, double hour) { + int ans = -1; + int l = 1; + int r = (int) 1e7; + + while (l <= r) { + final int m = (l + r) / 2; + if (time(dist, hour, m) > hour) { + l = m + 1; + } else { + ans = m; + r = m - 1; + } + } + + return ans; + } + + private double time(int[] dist, double hour, int speed) { + double sum = 0; + for (int i = 0; i < dist.length - 1; ++i) + sum += Math.ceil((double) dist[i] / speed); + return sum + (double) dist[dist.length - 1] / speed; + } +} diff --git a/solutions/1870. Minimum Speed to Arrive on Time/1870.py b/solutions/1870. Minimum Speed to Arrive on Time/1870.py new file mode 100644 index 00000000000..fa8fdf88544 --- /dev/null +++ b/solutions/1870. Minimum Speed to Arrive on Time/1870.py @@ -0,0 +1,21 @@ +class Solution: + def minSpeedOnTime(self, dist: List[int], hour: float) -> int: + ans = -1 + l = 1 + r = int(1e7) + + def time(speed: int) -> float: + summ = 0 + for i in range(len(dist) - 1): + summ += math.ceil(dist[i] / speed) + return summ + dist[-1] / speed + + while l <= r: + m = (l + r) // 2 + if time(m) > hour: + l = m + 1 + else: + ans = m + r = m - 1 + + return ans diff --git a/solutions/1871. Jump Game VII/1871.cpp b/solutions/1871. Jump Game VII/1871.cpp new file mode 100644 index 00000000000..5ca0be2dc3f --- /dev/null +++ b/solutions/1871. Jump Game VII/1871.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool canReach(string s, int minJump, int maxJump) { + int count = 0; + vector dp(s.length()); + dp[0] = true; + + for (int i = minJump; i < s.length(); ++i) { + count += dp[i - minJump]; + if (i - maxJump > 0) + count -= dp[i - maxJump - 1]; + dp[i] = count && s[i] == '0'; + } + + return dp.back(); + } +}; diff --git a/solutions/1871. Jump Game VII/1871.java b/solutions/1871. Jump Game VII/1871.java new file mode 100644 index 00000000000..33408527058 --- /dev/null +++ b/solutions/1871. Jump Game VII/1871.java @@ -0,0 +1,16 @@ +class Solution { + public boolean canReach(String s, int minJump, int maxJump) { + int count = 0; + boolean dp[] = new boolean[s.length()]; + dp[0] = true; + + for (int i = minJump; i < s.length(); ++i) { + count += dp[i - minJump] ? 1 : 0; + if (i - maxJump > 0) + count -= dp[i - maxJump - 1] ? 1 : 0; + dp[i] = count > 0 && s.charAt(i) == '0'; + } + + return dp[dp.length - 1]; + } +} diff --git a/solutions/1871. Jump Game VII/1871.py b/solutions/1871. Jump Game VII/1871.py new file mode 100644 index 00000000000..184b6a05b1f --- /dev/null +++ b/solutions/1871. Jump Game VII/1871.py @@ -0,0 +1,12 @@ +class Solution: + def canReach(self, s: str, minJump: int, maxJump: int) -> bool: + count = 0 + dp = [True] + [False] * (len(s) - 1) + + for i in range(minJump, len(s)): + count += dp[i - minJump] + if i - maxJump > 0: + count -= dp[i - maxJump - 1] + dp[i] = count and s[i] == '0' + + return dp[-1] diff --git a/solutions/1872. Stone Game VIII/1872.cpp b/solutions/1872. Stone Game VIII/1872.cpp new file mode 100644 index 00000000000..e3ebc58fe72 --- /dev/null +++ b/solutions/1872. Stone Game VIII/1872.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int stoneGameVIII(vector& stones) { + const int n = stones.size(); + vector prefix(n); + // dp[i] := the maximum score difference the current player can get when the + // game starts at i, i.e. stones[0..i] are merged into the value prefix[i] + vector dp(n, INT_MIN); + + partial_sum(stones.begin(), stones.end(), prefix.begin()); + + // Must take all when there're only two stones left. + dp[n - 2] = prefix.back(); + + for (int i = n - 3; i >= 0; --i) + dp[i] = max(dp[i + 1], prefix[i + 1] - dp[i + 1]); + + return dp[0]; + } +}; diff --git a/solutions/1872. Stone Game VIII/1872.java b/solutions/1872. Stone Game VIII/1872.java new file mode 100644 index 00000000000..d179f5c11df --- /dev/null +++ b/solutions/1872. Stone Game VIII/1872.java @@ -0,0 +1,21 @@ +class Solution { + public int stoneGameVIII(int[] stones) { + final int n = stones.length; + int[] prefix = stones.clone(); + // dp[i] := the maximum score difference the current player can get when the + // game starts at i, i.e. stones[0..i] are merged into the value prefix[i] + int[] dp = new int[n]; + Arrays.fill(dp, Integer.MIN_VALUE); + + for (int i = 1; i < prefix.length; ++i) + prefix[i] += prefix[i - 1]; + + // Must take all when there're only two stones left. + dp[n - 2] = prefix[n - 1]; + + for (int i = n - 3; i >= 0; --i) + dp[i] = Math.max(dp[i + 1], prefix[i + 1] - dp[i + 1]); + + return dp[0]; + } +} diff --git a/solutions/1872. Stone Game VIII/1872.py b/solutions/1872. Stone Game VIII/1872.py new file mode 100644 index 00000000000..5246789c208 --- /dev/null +++ b/solutions/1872. Stone Game VIII/1872.py @@ -0,0 +1,15 @@ +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + n = len(stones) + prefix = list(itertools.accumulate(stones)) + # dp[i] := the maximum score difference the current player can get when the + # game starts at i, i.e. stones[0..i] are merged into the value prefix[i] + dp = [-math.inf] * n + + # Must take all when there're only two stones left. + dp[n - 2] = prefix[-1] + + for i in reversed(range(n - 2)): + dp[i] = max(dp[i + 1], prefix[i + 1] - dp[i + 1]) + + return dp[0] diff --git a/solutions/1873. Calculate Special Bonus/1873.sql b/solutions/1873. Calculate Special Bonus/1873.sql new file mode 100644 index 00000000000..ce53fc64cc5 --- /dev/null +++ b/solutions/1873. Calculate Special Bonus/1873.sql @@ -0,0 +1,5 @@ +SELECT + employee_id, + IF(employee_id % 2 = 1 AND LEFT(name, 1) != 'M', salary, 0) AS bonus +FROM Employees +ORDER BY 1; diff --git a/solutions/1874. Minimize Product Sum of Two Arrays/1874.cpp b/solutions/1874. Minimize Product Sum of Two Arrays/1874.cpp new file mode 100644 index 00000000000..759de318e58 --- /dev/null +++ b/solutions/1874. Minimize Product Sum of Two Arrays/1874.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minProductSum(vector& nums1, vector& nums2) { + int ans = 0; + + ranges::sort(nums1); + ranges::sort(nums2, greater<>()); + + for (int i = 0; i < nums1.size(); ++i) + ans += nums1[i] * nums2[i]; + + return ans; + } +}; diff --git a/solutions/1874. Minimize Product Sum of Two Arrays/1874.java b/solutions/1874. Minimize Product Sum of Two Arrays/1874.java new file mode 100644 index 00000000000..3f97bcb6be7 --- /dev/null +++ b/solutions/1874. Minimize Product Sum of Two Arrays/1874.java @@ -0,0 +1,15 @@ +class Solution { + public int minProductSum(int[] nums1, int[] nums2) { + final int n = nums1.length; + + int ans = 0; + + Arrays.sort(nums1); + Arrays.sort(nums2); + + for (int i = 0; i < n; ++i) + ans += nums1[i] * nums2[n - 1 - i]; + + return ans; + } +} diff --git a/solutions/1874. Minimize Product Sum of Two Arrays/1874.py b/solutions/1874. Minimize Product Sum of Two Arrays/1874.py new file mode 100644 index 00000000000..f231d951e8a --- /dev/null +++ b/solutions/1874. Minimize Product Sum of Two Arrays/1874.py @@ -0,0 +1,3 @@ +class Solution: + def minProductSum(self, nums1: List[int], nums2: List[int]) -> int: + return sum([a * b for a, b in zip(sorted(nums1), sorted(nums2, reverse=True))]) diff --git a/solutions/1875. Group Employees of the Same Salary/1875.sql b/solutions/1875. Group Employees of the Same Salary/1875.sql new file mode 100644 index 00000000000..7842925e23c --- /dev/null +++ b/solutions/1875. Group Employees of the Same Salary/1875.sql @@ -0,0 +1,15 @@ +WITH + EmployeesWithCountPerSalary AS ( + SELECT + *, + COUNT(employee_id) OVER(PARTITION BY salary) AS count_per_salary + FROM Employees + ) +SELECT + employee_id, + name, + salary, + DENSE_RANK() OVER(ORDER BY salary) AS team_id +FROM EmployeesWithCountPerSalary +WHERE count_per_salary > 1 +ORDER BY team_id, employee_id; diff --git a/solutions/1876. Substrings of Size Three with Distinct Characters/1876.cpp b/solutions/1876. Substrings of Size Three with Distinct Characters/1876.cpp new file mode 100644 index 00000000000..debaaf1c4d4 --- /dev/null +++ b/solutions/1876. Substrings of Size Three with Distinct Characters/1876.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countGoodSubstrings(string s) { + int ans = 0; + + for (int i = 0; i + 2 < s.length(); ++i) { + const char a = s[i]; + const char b = s[i + 1]; + const char c = s[i + 2]; + if (a == b || a == c || b == c) + continue; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1876. Substrings of Size Three with Distinct Characters/1876.java b/solutions/1876. Substrings of Size Three with Distinct Characters/1876.java new file mode 100644 index 00000000000..f8e869a65bb --- /dev/null +++ b/solutions/1876. Substrings of Size Three with Distinct Characters/1876.java @@ -0,0 +1,16 @@ +class Solution { + public int countGoodSubstrings(String s) { + int ans = 0; + + for (int i = 0; i < s.length() - 2; ++i) { + final char a = s.charAt(i); + final char b = s.charAt(i + 1); + final char c = s.charAt(i + 2); + if (a == b || a == c || b == c) + continue; + ++ans; + } + + return ans; + } +} diff --git a/solutions/1876. Substrings of Size Three with Distinct Characters/1876.py b/solutions/1876. Substrings of Size Three with Distinct Characters/1876.py new file mode 100644 index 00000000000..cbec917101a --- /dev/null +++ b/solutions/1876. Substrings of Size Three with Distinct Characters/1876.py @@ -0,0 +1,10 @@ +class Solution: + def countGoodSubstrings(self, s: str) -> int: + ans = 0 + + for a, b, c in zip(s, s[1:], s[2:]): + if a == b or a == c or b == c: + continue + ans += 1 + + return ans diff --git a/solutions/1877. Minimize Maximum Pair Sum in Array/1877.cpp b/solutions/1877. Minimize Maximum Pair Sum in Array/1877.cpp new file mode 100644 index 00000000000..445dec29eeb --- /dev/null +++ b/solutions/1877. Minimize Maximum Pair Sum in Array/1877.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int minPairSum(vector& nums) { + int ans = 0; + + ranges::sort(nums); + + for (int i = 0, j = nums.size() - 1; i < j;) + ans = max(ans, nums[i++] + nums[j--]); + + return ans; + } +}; diff --git a/solutions/1877. Minimize Maximum Pair Sum in Array/1877.java b/solutions/1877. Minimize Maximum Pair Sum in Array/1877.java new file mode 100644 index 00000000000..516571e8058 --- /dev/null +++ b/solutions/1877. Minimize Maximum Pair Sum in Array/1877.java @@ -0,0 +1,12 @@ +class Solution { + public int minPairSum(int[] nums) { + int ans = 0; + + Arrays.sort(nums); + + for (int i = 0, j = nums.length - 1; i < j;) + ans = Math.max(ans, nums[i++] + nums[j--]); + + return ans; + } +} diff --git a/solutions/1877. Minimize Maximum Pair Sum in Array/1877.py b/solutions/1877. Minimize Maximum Pair Sum in Array/1877.py new file mode 100644 index 00000000000..d72ba5da94f --- /dev/null +++ b/solutions/1877. Minimize Maximum Pair Sum in Array/1877.py @@ -0,0 +1,4 @@ +class Solution: + def minPairSum(self, nums: List[int]) -> int: + nums.sort() + return max(nums[i] + nums[len(nums) - 1 - i] for i in range(len(nums) // 2)) diff --git a/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.cpp b/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.cpp new file mode 100644 index 00000000000..f07f7b1e062 --- /dev/null +++ b/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + vector getBiggestThree(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + set sums; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int sz = 0; i + sz < m && i - sz >= 0 && j + 2 * sz < n; ++sz) { + const int sum = sz == 0 ? grid[i][j] : getSum(grid, i, j, sz); + sums.insert(sum); + if (sums.size() > 3) + sums.erase(sums.begin()); + } + + return vector(sums.rbegin(), sums.rend()); + } + + private: + // Returns the sum of the rhombus, where the top grid is (i, j) and the edge + // size is `sz`. + int getSum(const vector>& grid, int i, int j, int sz) { + int x = i; + int y = j; + int sum = 0; + + // Go left down. + for (int k = 0; k < sz; ++k) + sum += grid[--x][++y]; + + // Go right down. + for (int k = 0; k < sz; ++k) + sum += grid[++x][++y]; + + // Go right up. + for (int k = 0; k < sz; ++k) + sum += grid[++x][--y]; + + // Go left up. + for (int k = 0; k < sz; ++k) + sum += grid[--x][--y]; + + return sum; + } +}; diff --git a/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.java b/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.java new file mode 100644 index 00000000000..eb21cb3aae2 --- /dev/null +++ b/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.java @@ -0,0 +1,44 @@ +class Solution { + public int[] getBiggestThree(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + TreeSet sums = new TreeSet<>(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int sz = 0; i + sz < m && i - sz >= 0 && j + 2 * sz < n; ++sz) { + final int sum = sz == 0 ? grid[i][j] : getSum(grid, i, j, sz); + sums.add(sum); + if (sums.size() > 3) + sums.pollFirst(); + } + + return sums.descendingSet().stream().mapToInt(Integer::intValue).toArray(); + } + + // Returns the sum of the rhombus, where the top grid is (i, j) and the edge + // size is `sz`. + private int getSum(int[][] grid, int i, int j, int sz) { + int x = i; + int y = j; + int sum = 0; + + // Go left down. + for (int k = 0; k < sz; ++k) + sum += grid[--x][++y]; + + // Go right down. + for (int k = 0; k < sz; ++k) + sum += grid[++x][++y]; + + // Go right up. + for (int k = 0; k < sz; ++k) + sum += grid[++x][--y]; + + // Go left up. + for (int k = 0; k < sz; ++k) + sum += grid[--x][--y]; + + return sum; + } +} diff --git a/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.py b/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.py new file mode 100644 index 00000000000..5a89f412d05 --- /dev/null +++ b/solutions/1878. Get Biggest Three Rhombus Sums in a Grid/1878.py @@ -0,0 +1,55 @@ +from sortedcontainers import SortedSet + + +class Solution: + def getBiggestThree(self, grid: List[List[int]]) -> List[int]: + m = len(grid) + n = len(grid[0]) + sums = SortedSet() + + for i in range(m): + for j in range(n): + sz = 0 + while i + sz < m and i - sz >= 0 and j + 2 * sz < n: + summ = grid[i][j] if sz == 0 else self._getSum(grid, i, j, sz) + sums.add(summ) + if len(sums) > 3: + sums.pop(0) + sz += 1 + + return sums + + def _getSum(self, grid: List[List[int]], i: int, j: int, sz: int) -> int: + """ + Returns the sum of the rhombus, where the top grid is (i, j) and the edge + size is `sz`. + """ + x = i + y = j + summ = 0 + + # Go left down. + for _ in range(sz): + x -= 1 + y += 1 + summ += grid[x][y] + + # Go right down. + for _ in range(sz): + x += 1 + y += 1 + summ += grid[x][y] + + # Go right up. + for _ in range(sz): + x += 1 + y -= 1 + summ += grid[x][y] + + # Go left up. + for _ in range(sz): + x -= 1 + y -= 1 + summ += grid[x][y] + + return summ diff --git a/solutions/1879. Minimum XOR Sum of Two Arrays/1879.cpp b/solutions/1879. Minimum XOR Sum of Two Arrays/1879.cpp new file mode 100644 index 00000000000..1a3ef53ccf1 --- /dev/null +++ b/solutions/1879. Minimum XOR Sum of Two Arrays/1879.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minimumXORSum(vector& nums1, vector& nums2) { + vector mem(1 << nums2.size(), INT_MAX); + return minimumXORSum(nums1, nums2, 0, mem); + } + + private: + int minimumXORSum(const vector& nums1, const vector& nums2, + unsigned mask, vector& mem) { + const int i = popcount(mask); + if (i == nums1.size()) + return 0; + if (mem[mask] < INT_MAX) + return mem[mask]; + + for (int j = 0; j < nums2.size(); ++j) + if ((mask >> j & 1) == 0) + mem[mask] = + min(mem[mask], (nums1[i] ^ nums2[j]) + + minimumXORSum(nums1, nums2, mask | 1 << j, mem)); + + return mem[mask]; + } +}; diff --git a/solutions/1879. Minimum XOR Sum of Two Arrays/1879.java b/solutions/1879. Minimum XOR Sum of Two Arrays/1879.java new file mode 100644 index 00000000000..e59a25dceec --- /dev/null +++ b/solutions/1879. Minimum XOR Sum of Two Arrays/1879.java @@ -0,0 +1,22 @@ +class Solution { + public int minimumXORSum(int[] nums1, int[] nums2) { + int[] mem = new int[1 << nums2.length]; + Arrays.fill(mem, Integer.MAX_VALUE); + return minimumXORSum(nums1, nums2, 0, mem); + } + + private int minimumXORSum(int[] nums1, int[] nums2, int mask, int[] mem) { + final int i = Integer.bitCount(mask); + if (i == nums1.length) + return 0; + if (mem[mask] < Integer.MAX_VALUE) + return mem[mask]; + + for (int j = 0; j < nums2.length; ++j) + if ((mask >> j & 1) == 0) + mem[mask] = Math.min(mem[mask], (nums1[i] ^ nums2[j]) + + minimumXORSum(nums1, nums2, mask | 1 << j, mem)); + + return mem[mask]; + } +} diff --git a/solutions/1879. Minimum XOR Sum of Two Arrays/1879.py b/solutions/1879. Minimum XOR Sum of Two Arrays/1879.py new file mode 100644 index 00000000000..2b84aa88f76 --- /dev/null +++ b/solutions/1879. Minimum XOR Sum of Two Arrays/1879.py @@ -0,0 +1,10 @@ +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + @functools.lru_cache(None) + def dp(mask: int) -> int: + i = mask.bit_count() + if i == len(nums1): + return 0 + return min((nums1[i] ^ nums2[j]) + dp(mask | 1 << j) + for j in range(len(nums2)) if not mask >> j & 1) + return dp(0) diff --git a/solutions/188. Best Time to Buy and Sell Stock IV/188.cpp b/solutions/188. Best Time to Buy and Sell Stock IV/188.cpp new file mode 100644 index 00000000000..2e247ba58c6 --- /dev/null +++ b/solutions/188. Best Time to Buy and Sell Stock IV/188.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxProfit(int k, vector& prices) { + if (k >= prices.size() / 2) { + int sell = 0; + int hold = INT_MIN; + + for (const int price : prices) { + sell = max(sell, hold + price); + hold = max(hold, sell - price); + } + + return sell; + } + + vector sell(k + 1); + vector hold(k + 1, INT_MIN); + + for (const int price : prices) + for (int i = k; i > 0; --i) { + sell[i] = max(sell[i], hold[i] + price); + hold[i] = max(hold[i], sell[i - 1] - price); + } + + return sell[k]; + } +}; diff --git a/solutions/188. Best Time to Buy and Sell Stock IV/188.java b/solutions/188. Best Time to Buy and Sell Stock IV/188.java new file mode 100644 index 00000000000..afd3f93b886 --- /dev/null +++ b/solutions/188. Best Time to Buy and Sell Stock IV/188.java @@ -0,0 +1,27 @@ +class Solution { + public int maxProfit(int k, int[] prices) { + if (k >= prices.length / 2) { + int sell = 0; + int hold = Integer.MIN_VALUE; + + for (final int price : prices) { + sell = Math.max(sell, hold + price); + hold = Math.max(hold, sell - price); + } + + return sell; + } + + int[] sell = new int[k + 1]; + int[] hold = new int[k + 1]; + Arrays.fill(hold, Integer.MIN_VALUE); + + for (final int price : prices) + for (int i = k; i > 0; --i) { + sell[i] = Math.max(sell[i], hold[i] + price); + hold[i] = Math.max(hold[i], sell[i - 1] - price); + } + + return sell[k]; + } +} diff --git a/solutions/188. Best Time to Buy and Sell Stock IV/188.py b/solutions/188. Best Time to Buy and Sell Stock IV/188.py new file mode 100644 index 00000000000..d96e5959f1f --- /dev/null +++ b/solutions/188. Best Time to Buy and Sell Stock IV/188.py @@ -0,0 +1,21 @@ +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + if k >= len(prices) // 2: + sell = 0 + hold = -math.inf + + for price in prices: + sell = max(sell, hold + price) + hold = max(hold, sell - price) + + return sell + + sell = [0] * (k + 1) + hold = [-math.inf] * (k + 1) + + for price in prices: + for i in range(k, 0, -1): + sell[i] = max(sell[i], hold[i] + price) + hold[i] = max(hold[i], sell[i - 1] - price) + + return sell[k] diff --git a/solutions/1880. Check if Word Equals Summation of Two Words/1880.cpp b/solutions/1880. Check if Word Equals Summation of Two Words/1880.cpp new file mode 100644 index 00000000000..ea30a680058 --- /dev/null +++ b/solutions/1880. Check if Word Equals Summation of Two Words/1880.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool isSumEqual(string firstWord, string secondWord, string targetWord) { + const int first = getNumber(firstWord); + const int second = getNumber(secondWord); + const int target = getNumber(targetWord); + return first + second == target; + } + + private: + int getNumber(const string& word) { + int num = 0; + for (const char c : word) + num = num * 10 + (c - 'a'); + return num; + } +}; diff --git a/solutions/1880. Check if Word Equals Summation of Two Words/1880.java b/solutions/1880. Check if Word Equals Summation of Two Words/1880.java new file mode 100644 index 00000000000..783a97d0459 --- /dev/null +++ b/solutions/1880. Check if Word Equals Summation of Two Words/1880.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { + final int first = getNumber(firstWord); + final int second = getNumber(secondWord); + final int target = getNumber(targetWord); + return first + second == target; + } + + private int getNumber(String word) { + int num = 0; + for (final char c : word.toCharArray()) + num = num * 10 + (c - 'a'); + return num; + } +} diff --git a/solutions/1880. Check if Word Equals Summation of Two Words/1880.py b/solutions/1880. Check if Word Equals Summation of Two Words/1880.py new file mode 100644 index 00000000000..ef584c9a77d --- /dev/null +++ b/solutions/1880. Check if Word Equals Summation of Two Words/1880.py @@ -0,0 +1,12 @@ +class Solution: + def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: + first = self._getNumber(firstWord) + second = self._getNumber(secondWord) + target = self._getNumber(targetWord) + return first + second == target + + def _getNumber(self, word: str) -> int: + num = 0 + for c in word: + num = num * 10 + (ord(c) - ord('a')) + return num diff --git a/solutions/1881. Maximum Value after Insertion/1881.cpp b/solutions/1881. Maximum Value after Insertion/1881.cpp new file mode 100644 index 00000000000..4f8da543020 --- /dev/null +++ b/solutions/1881. Maximum Value after Insertion/1881.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + string maxValue(string n, int x) { + bool isNegative = n[0] == '-'; + + for (int i = 0; i < n.length(); ++i) + if (!isNegative && n[i] - '0' < x || isNegative && n[i] - '0' > x) + return n.substr(0, i) + (char)('0' + x) + n.substr(i); + + return n + (char)('0' + x); + } +}; diff --git a/solutions/1881. Maximum Value after Insertion/1881.java b/solutions/1881. Maximum Value after Insertion/1881.java new file mode 100644 index 00000000000..98296607251 --- /dev/null +++ b/solutions/1881. Maximum Value after Insertion/1881.java @@ -0,0 +1,11 @@ +class Solution { + public String maxValue(String n, int x) { + boolean isNegative = n.charAt(0) == '-'; + + for (int i = 0; i < n.length(); ++i) + if (!isNegative && n.charAt(i) - '0' < x || isNegative && n.charAt(i) - '0' > x) + return n.substring(0, i) + x + n.substring(i); + + return n + x; + } +} diff --git a/solutions/1881. Maximum Value after Insertion/1881.py b/solutions/1881. Maximum Value after Insertion/1881.py new file mode 100644 index 00000000000..0e6363602cc --- /dev/null +++ b/solutions/1881. Maximum Value after Insertion/1881.py @@ -0,0 +1,9 @@ +class Solution: + def maxValue(self, n: str, x: int) -> str: + isNegative = n[0] == '-' + + for i, c in enumerate(n): + if not isNegative and ord(c) - ord('0') < x or isNegative and ord(c) - ord('0') > x: + return n[:i] + str(x) + n[i:] + + return n + str(x) diff --git a/solutions/1882. Process Tasks Using Servers/1882.cpp b/solutions/1882. Process Tasks Using Servers/1882.cpp new file mode 100644 index 00000000000..6019ae6a1a3 --- /dev/null +++ b/solutions/1882. Process Tasks Using Servers/1882.cpp @@ -0,0 +1,56 @@ +struct T { + int weight; + int index; + int freeTime; + T(int weight, int index, int freeTime) + : weight(weight), index(index), freeTime(freeTime) {} +}; + +class Solution { + public: + vector assignTasks(vector& servers, vector& tasks) { + const int n = servers.size(); + const int m = tasks.size(); + vector ans(m); + auto compareFree = [](const T& a, const T& b) { + return a.weight == b.weight ? a.index > b.index : a.weight > b.weight; + }; + auto compareUsed = [](const T& a, const T& b) { + if (a.freeTime != b.freeTime) + return a.freeTime > b.freeTime; + if (a.weight != b.weight) + return a.weight > b.weight; + return a.index > b.index; + }; + priority_queue, decltype(compareFree)> free(compareFree); + priority_queue, decltype(compareUsed)> used(compareUsed); + + for (int i = 0; i < n; ++i) + free.emplace(servers[i], i, 0); + + for (int i = 0; i < m; ++i) { // i := the current time + const int executionTime = tasks[i]; + // Pop all the servers that'll be free at time i. + while (!used.empty() && used.top().freeTime <= i) { + const T curr = used.top(); + used.pop(); + free.push(curr); + } + if (free.empty()) { + T server = used.top(); + used.pop(); + ans[i] = server.index; + server.freeTime += executionTime; + used.push(server); + } else { + T server = free.top(); + free.pop(); + ans[i] = server.index; + server.freeTime = i + executionTime; + used.push(server); + } + } + + return ans; + } +}; diff --git a/solutions/1882. Process Tasks Using Servers/1882.java b/solutions/1882. Process Tasks Using Servers/1882.java new file mode 100644 index 00000000000..ad042b80ecc --- /dev/null +++ b/solutions/1882. Process Tasks Using Servers/1882.java @@ -0,0 +1,53 @@ +class T { + public int weight; + public int index; + public int freeTime; + public T(int weight, int index, int freeTime) { + this.weight = weight; + this.index = index; + this.freeTime = freeTime; + } +} + +class Solution { + public int[] assignTasks(int[] servers, int[] tasks) { + final int n = servers.length; + final int m = tasks.length; + int[] ans = new int[m]; + Queue free = new PriorityQueue<>( + (a, b) -> a.weight == b.weight ? a.index - b.index : a.weight - b.weight); + Queue used = new PriorityQueue<>(new Comparator() { + @Override + public int compare(T a, T b) { + if (a.freeTime != b.freeTime) + return a.freeTime - b.freeTime; + if (a.weight != b.weight) + return a.weight - b.weight; + return a.index - b.index; + } + }); + + for (int i = 0; i < n; ++i) + free.offer(new T(servers[i], i, 0)); + + for (int i = 0; i < m; ++i) { // i := the current time + final int executionTime = tasks[i]; + // Poll all servers that'll be free at time i. + while (!used.isEmpty() && used.peek().freeTime <= i) + free.offer(used.poll()); + if (free.isEmpty()) { + T server = used.poll(); + ans[i] = server.index; + server.freeTime += executionTime; + used.offer(server); + } else { + T server = free.poll(); + ans[i] = server.index; + server.freeTime = i + executionTime; + used.offer(server); + } + } + + return ans; + } +} diff --git a/solutions/1882. Process Tasks Using Servers/1882.py b/solutions/1882. Process Tasks Using Servers/1882.py new file mode 100644 index 00000000000..8a4284066bf --- /dev/null +++ b/solutions/1882. Process Tasks Using Servers/1882.py @@ -0,0 +1,24 @@ +class Solution: + def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: + ans = [] + free = [] # (weight, index, freeTime) + used = [] # (freeTime, weight, index) + + for i, weight in enumerate(servers): + heapq.heappush(free, (weight, i, 0)) + + for i, executionTime in enumerate(tasks): # i := the current time + # Poll all servers that'll be free at time i. + while used and used[0][0] <= i: + curr = heapq.heappop(used) + heapq.heappush(free, (curr[1], curr[2], curr[0])) + if free: + curr = heapq.heappop(free) + ans.append(curr[1]) + heapq.heappush(used, (i + executionTime, curr[0], curr[1])) + else: + curr = heapq.heappop(used) + ans.append(curr[2]) + heapq.heappush(used, (curr[0] + executionTime, curr[1], curr[2])) + + return ans diff --git a/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.cpp b/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.cpp new file mode 100644 index 00000000000..0ba136692fa --- /dev/null +++ b/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minSkips(vector& dist, int speed, int hoursBefore) { + constexpr double kInf = 1e7; + constexpr double kEps = 1e-9; + const int n = dist.size(); + // dp[i][j] := the minimum time, where i is the number of roads we traversed + // so far and j is the number of skips we did + vector> dp(n + 1, vector(n + 1, kInf)); + dp[0][0] = 0; + + for (int i = 1; i <= n; ++i) { + const double d = dist[i - 1]; + dp[i][0] = ceil(dp[i - 1][0] + d / speed - kEps); + for (int j = 1; j <= i; ++j) + dp[i][j] = min(dp[i - 1][j - 1] + d / speed, + ceil(dp[i - 1][j] + d / speed - kEps)); + } + + for (int j = 0; j <= n; ++j) + if (dp[n][j] <= hoursBefore) + return j; + + return -1; + } +}; diff --git a/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.java b/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.java new file mode 100644 index 00000000000..71a4cf53752 --- /dev/null +++ b/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.java @@ -0,0 +1,26 @@ +class Solution { + public int minSkips(int[] dist, int speed, int hoursBefore) { + final double kInf = 1e7; + final double kEps = 1e-9; + final int n = dist.length; + // dp[i][j] := the minimum time, where i is the number of roads we traversed + // so far and j is the number of skips we did + double[][] dp = new double[n + 1][n + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, kInf)); + dp[0][0] = 0; + + for (int i = 1; i <= n; ++i) { + final double d = dist[i - 1]; + dp[i][0] = Math.ceil(dp[i - 1][0] + d / speed - kEps); + for (int j = 1; j <= i; ++j) + dp[i][j] = + Math.min(dp[i - 1][j - 1] + d / speed, Math.ceil(dp[i - 1][j] + d / speed - kEps)); + } + + for (int j = 0; j <= n; ++j) + if (dp[n][j] <= hoursBefore) + return j; + + return -1; + } +} diff --git a/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.py b/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.py new file mode 100644 index 00000000000..d422cd64d98 --- /dev/null +++ b/solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.py @@ -0,0 +1,21 @@ +class Solution: + def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: + kInf = 10**7 + kEps = 1e-9 + n = len(dist) + # dp[i][j] := the minimum time, where i is the number of roads we traversed + # so far and j is the number of skips we did + dp = [[kInf] * (n + 1) for _ in range(n + 1)] + dp[0][0] = 0 + + for i, d in enumerate(dist, 1): + dp[i][0] = math.ceil(dp[i - 1][0] + d / speed - kEps) + for j in range(1, i + 1): + dp[i][j] = min(dp[i - 1][j - 1] + d / speed, + math.ceil(dp[i - 1][j] + d / speed - kEps)) + + for j, time in enumerate(dp[-1]): + if time <= hoursBefore: + return j + + return -1 diff --git a/solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.cpp b/solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.cpp new file mode 100644 index 00000000000..f9e8d9c18a9 --- /dev/null +++ b/solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int twoEggDrop(int n) { + return superEggDrop(2, n); + } + + private: + // Same as 887. Super Egg Drop + int superEggDrop(int k, int n) { + vector> mem(k + 1, vector(n + 1, -1)); + return drop(k, n, mem); + } + + // Returns the minimum number of moves to know f with k eggs and n floors. + int drop(int k, int n, vector>& mem) { + if (k == 0) // no eggs -> done + return 0; + if (k == 1) // one egg -> drop from 1-th floor to n-th floor + return n; + if (n == 0) // no floor -> done + return 0; + if (n == 1) // one floor -> drop from that floor + return 1; + if (mem[k][n] != -1) + return mem[k][n]; + + // broken[i] := drop(k - 1, i - 1) is increasing with i + // unbroken[i] := drop(k, n - i) is decreasing with i + // mem[k][n] := 1 + min(max(broken[i], unbroken[i])), 1 <= i <= n + // Find the first index i s.t broken[i] >= unbroken[i], which minimizes + // max(broken[i], unbroken[i]). + + int l = 1; + int r = n + 1; + + while (l < r) { + const int m = (l + r) / 2; + const int broken = drop(k - 1, m - 1, mem); + const int unbroken = drop(k, n - m, mem); + if (broken >= unbroken) + r = m; + else + l = m + 1; + } + + return mem[k][n] = 1 + drop(k - 1, l - 1, mem); + } +}; diff --git a/solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.java b/solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.java new file mode 100644 index 00000000000..0a510d09228 --- /dev/null +++ b/solutions/1884. Egg Drop With 2 Eggs and N Floors/1884.java @@ -0,0 +1,41 @@ +class Solution { + public int twoEggDrop(int n) { + return superEggDrop(2, n); + } + + // Same as 887. Super Egg Drop + private int superEggDrop(int k, int n) { + int[][] mem = new int[k + 1][n + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, -1)); + return drop(k, n, mem); + } + + // Returns the minimum number of moves to know f with k eggs and n floors. + private int drop(int k, int n, int[][] mem) { + if (k == 0) // no eggs -> done + return 0; + if (k == 1) // one egg -> drop from 1-th floor to n-th floor + return n; + if (n == 0) // no floor -> done + return 0; + if (n == 1) // one floor -> drop from that floor + return 1; + if (mem[k][n] != -1) + return mem[k][n]; + + int l = 1; + int r = n + 1; + + while (l < r) { + final int m = (l + r) / 2; + final int broken = drop(k - 1, m - 1, mem); + final int unbroken = drop(k, n - m, mem); + if (broken >= unbroken) + r = m; + else + l = m + 1; + } + + return mem[k][n] = 1 + drop(k - 1, l - 1, mem); + } +} diff --git a/solutions/1885. Count Pairs in Two Arrays/1885.cpp b/solutions/1885. Count Pairs in Two Arrays/1885.cpp new file mode 100644 index 00000000000..2f197ae8b4b --- /dev/null +++ b/solutions/1885. Count Pairs in Two Arrays/1885.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + long long countPairs(vector& nums1, vector& nums2) { + long ans = 0; + vector A(nums1.size()); + + for (int i = 0; i < A.size(); ++i) + A[i] = nums1[i] - nums2[i]; + + ranges::sort(A); + + for (int i = 0; i < A.size(); ++i) { + const auto it = lower_bound(A.begin() + i + 1, A.end(), -A[i] + 1); + ans += A.cend() - it; + } + + return ans; + } +}; diff --git a/solutions/1885. Count Pairs in Two Arrays/1885.java b/solutions/1885. Count Pairs in Two Arrays/1885.java new file mode 100644 index 00000000000..8203ad5d6f1 --- /dev/null +++ b/solutions/1885. Count Pairs in Two Arrays/1885.java @@ -0,0 +1,31 @@ +class Solution { + public long countPairs(int[] nums1, int[] nums2) { + long ans = 0; + int[] A = new int[nums1.length]; // A[i] = nums1[i] - nums2[i] + + for (int i = 0; i < A.length; ++i) + A[i] = nums1[i] - nums2[i]; + + Arrays.sort(A); + + for (int i = 0; i < A.length; ++i) { + final int index = firstGreater(A, -A[i]); + ans += A.length - Math.max(i + 1, index); + } + + return ans; + } + + private int firstGreater(int[] A, int target) { + int l = 0; + int r = A.length; + while (l < r) { + final int m = (l + r) / 2; + if (A[m] > target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1885. Count Pairs in Two Arrays/1885.py b/solutions/1885. Count Pairs in Two Arrays/1885.py new file mode 100644 index 00000000000..c507414869c --- /dev/null +++ b/solutions/1885. Count Pairs in Two Arrays/1885.py @@ -0,0 +1,10 @@ +class Solution: + def countPairs(self, nums1: List[int], nums2: List[int]) -> int: + ans = 0 + A = sorted([x - y for x, y in zip(nums1, nums2)]) + + for i, a in enumerate(A): + index = bisect_left(A, -a + 1) + ans += len(A) - max(i + 1, index) + + return ans diff --git a/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.cpp b/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.cpp new file mode 100644 index 00000000000..494e82051b5 --- /dev/null +++ b/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool findRotation(vector>& mat, vector>& target) { + for (int i = 0; i < 4; ++i) { + if (mat == target) + return true; + rotate(mat); + } + return false; + } + + private: + void rotate(vector>& M) { + reverse(M.begin(), M.end()); + for (int i = 0; i < M.size(); ++i) + for (int j = i + 1; j < M.size(); ++j) + swap(M[i][j], M[j][i]); + } +}; diff --git a/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.java b/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.java new file mode 100644 index 00000000000..b0cfd18fa41 --- /dev/null +++ b/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.java @@ -0,0 +1,24 @@ +class Solution { + public boolean findRotation(int[][] mat, int[][] target) { + for (int i = 0; i < 4; ++i) { + if (Arrays.deepEquals(mat, target)) + return true; + rotate(mat); + } + return false; + } + + private void rotate(int[][] M) { + for (int i = 0, j = M.length - 1; i < j; ++i, --j) { + int[] temp = M[i]; + M[i] = M[j]; + M[j] = temp; + } + for (int i = 0; i < M.length; ++i) + for (int j = i + 1; j < M.length; ++j) { + final int temp = M[i][j]; + M[i][j] = M[j][i]; + M[j][i] = temp; + } + } +} diff --git a/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.py b/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.py new file mode 100644 index 00000000000..0b558da9775 --- /dev/null +++ b/solutions/1886. Determine Whether Matrix Can Be Obtained By Rotation/1886.py @@ -0,0 +1,7 @@ +class Solution: + def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + for _ in range(4): + if mat == target: + return True + mat = [list(x) for x in zip(*mat[::-1])] + return False diff --git a/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.cpp b/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.cpp new file mode 100644 index 00000000000..f0a25204f2c --- /dev/null +++ b/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int reductionOperations(vector& nums) { + int ans = 0; + + ranges::sort(nums); + + for (int i = nums.size() - 1; i > 0; --i) + if (nums[i] != nums[i - 1]) + ans += nums.size() - i; + + return ans; + } +}; diff --git a/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.java b/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.java new file mode 100644 index 00000000000..d8f24d0d6f8 --- /dev/null +++ b/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.java @@ -0,0 +1,13 @@ +class Solution { + public int reductionOperations(int[] nums) { + int ans = 0; + + Arrays.sort(nums); + + for (int i = nums.length - 1; i > 0; --i) + if (nums[i] != nums[i - 1]) + ans += nums.length - i; + + return ans; + } +} diff --git a/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.py b/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.py new file mode 100644 index 00000000000..65291306030 --- /dev/null +++ b/solutions/1887. Reduction Operations to Make the Array Elements Equal/1887.py @@ -0,0 +1,11 @@ +class Solution: + def reductionOperations(self, nums: List[int]) -> int: + ans = 0 + + nums.sort() + + for i in range(len(nums) - 1, 0, -1): + if nums[i] != nums[i - 1]: + ans += len(nums) - i + + return ans diff --git a/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.cpp b/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.cpp new file mode 100644 index 00000000000..e557d8ba4a3 --- /dev/null +++ b/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minFlips(string s) { + const int n = s.length(); + // count[0][0] := the number of 0s in the even indices + // count[0][1] := the number of 0s in the odd indices + // count[1][0] := the number of 1s in the even indices + // count[1][1] := the number of 1s in the odd indices + vector> count(2, vector(2)); + + for (int i = 0; i < n; ++i) + ++count[s[i] - '0'][i % 2]; + + // min(make all 0s in the even indices + make all 1s in the odd indices, + // make all 1s in the even indices + make all 0s in the odd indices) + int ans = min(count[1][0] + count[0][1], count[0][0] + count[1][1]); + + for (int i = 0; i < n; ++i) { + --count[s[i] - '0'][i % 2]; + ++count[s[i] - '0'][(n + i) % 2]; + ans = min({ans, count[1][0] + count[0][1], count[0][0] + count[1][1]}); + } + + return ans; + } +}; diff --git a/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.java b/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.java new file mode 100644 index 00000000000..045e3ca6a7c --- /dev/null +++ b/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.java @@ -0,0 +1,25 @@ +class Solution { + public int minFlips(String s) { + final int n = s.length(); + // count[0][0] := the number of 0s in the even indices + // count[0][1] := the number of 0s in the odd indices + // count[1][0] := the number of 1s in the even indices + // count[1][1] := the number of 1s in the odd indices + int[][] count = new int[2][2]; + + for (int i = 0; i < n; ++i) + ++count[s.charAt(i) - '0'][i % 2]; + + // min(make all 0s in the even indices + make all 1s in the odd indices, + // make all 1s in the even indices + make all 0s in the odd indices) + int ans = Math.min(count[1][0] + count[0][1], count[0][0] + count[1][1]); + + for (int i = 0; i < n; ++i) { + --count[s.charAt(i) - '0'][i % 2]; + ++count[s.charAt(i) - '0'][(n + i) % 2]; + ans = Math.min(ans, Math.min(count[1][0] + count[0][1], count[0][0] + count[1][1])); + } + + return ans; + } +} diff --git a/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.py b/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.py new file mode 100644 index 00000000000..b9f248f0965 --- /dev/null +++ b/solutions/1888. Minimum Number of Flips to Make the Binary String Alternating/1888.py @@ -0,0 +1,22 @@ +class Solution: + def minFlips(self, s: str) -> int: + n = len(s) + # count[0][0] := the number of '0' in the even indices + # count[0][1] := the number of '0' in the odd indices + # count[1][0] := the number of '1' in the even indices + # count[1][1] := the number of '1' in the odd indices + count = [[0] * 2 for _ in range(2)] + + for i, c in enumerate(s): + count[ord(c) - ord('0')][i % 2] += 1 + + # min(make all 0s in the even indices + make all 1s in the odd indices, + # make all 1s in the even indices + make all 0s in the odd indices) + ans = min(count[1][0] + count[0][1], count[0][0] + count[1][1]) + + for i, c in enumerate(s): + count[ord(c) - ord('0')][i % 2] -= 1 + count[ord(c) - ord('0')][(n + i) % 2] += 1 + ans = min(ans, count[1][0] + count[0][1], count[0][0] + count[1][1]) + + return ans diff --git a/solutions/1889. Minimum Space Wasted From Packaging/1889.cpp b/solutions/1889. Minimum Space Wasted From Packaging/1889.cpp new file mode 100644 index 00000000000..f6f4e3d27d7 --- /dev/null +++ b/solutions/1889. Minimum Space Wasted From Packaging/1889.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minWastedSpace(vector& packages, vector>& boxes) { + constexpr int kMod = 1'000'000'007; + constexpr long kInf = 1e11; + const long packagesSum = accumulate(packages.begin(), packages.end(), 0L); + long minBoxesSum = kInf; + + ranges::sort(packages); + + for (vector& box : boxes) { + ranges::sort(box); + if (box.back() < packages.back()) + continue; + long accu = 0; + long i = 0; + for (const int b : box) { + const long j = firstGreaterEqual(packages, b + 1); + accu += b * (j - i); + i = j; + } + minBoxesSum = min(minBoxesSum, accu); + } + + return minBoxesSum == kInf ? -1 : (minBoxesSum - packagesSum) % kMod; + } + + private: + int firstGreaterEqual(const vector& A, int target) { + return ranges::lower_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/1889. Minimum Space Wasted From Packaging/1889.java b/solutions/1889. Minimum Space Wasted From Packaging/1889.java new file mode 100644 index 00000000000..ab46c36aab6 --- /dev/null +++ b/solutions/1889. Minimum Space Wasted From Packaging/1889.java @@ -0,0 +1,39 @@ +class Solution { + public int minWastedSpace(int[] packages, int[][] boxes) { + final int kMod = 1_000_000_007; + final long kInf = (long) 1e11; + final long packagesSum = Arrays.stream(packages).mapToLong(p -> p).sum(); + long minBoxesSum = kInf; + + Arrays.sort(packages); + + for (int[] box : boxes) { + Arrays.sort(box); + if (box[box.length - 1] < packages[packages.length - 1]) + continue; + long accu = 0; + long i = 0; + for (final int b : box) { + final long j = firstGreaterEqual(packages, b + 1); + accu += b * (j - i); + i = j; + } + minBoxesSum = Math.min(minBoxesSum, accu); + } + + return minBoxesSum == kInf ? -1 : (int) ((minBoxesSum - packagesSum) % kMod); + } + + private int firstGreaterEqual(int[] A, int target) { + int l = 0; + int r = A.length; + while (l < r) { + final int m = (l + r) / 2; + if (A[m] >= target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1889. Minimum Space Wasted From Packaging/1889.py b/solutions/1889. Minimum Space Wasted From Packaging/1889.py new file mode 100644 index 00000000000..5746a1cb135 --- /dev/null +++ b/solutions/1889. Minimum Space Wasted From Packaging/1889.py @@ -0,0 +1,19 @@ +class Solution: + def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: + ans = math.inf + + packages.sort() + + for box in boxes: + box.sort() + if box[-1] < packages[-1]: + continue + accu = 0 + i = 0 + for b in box: + j = bisect.bisect(packages, b, i) + accu += b * (j - i) + i = j + ans = min(ans, accu) + + return -1 if ans == math.inf else (ans - sum(packages)) % int(1e9 + 7) diff --git a/solutions/189. Rotate Array/189.cpp b/solutions/189. Rotate Array/189.cpp new file mode 100644 index 00000000000..0aa618f946c --- /dev/null +++ b/solutions/189. Rotate Array/189.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + void rotate(vector& nums, int k) { + k %= nums.size(); + reverse(nums, 0, nums.size() - 1); + reverse(nums, 0, k - 1); + reverse(nums, k, nums.size() - 1); + } + + private: + void reverse(vector& nums, int l, int r) { + while (l < r) + swap(nums[l++], nums[r--]); + } +}; diff --git a/solutions/189. Rotate Array/189.java b/solutions/189. Rotate Array/189.java new file mode 100644 index 00000000000..ceee11eb1c2 --- /dev/null +++ b/solutions/189. Rotate Array/189.java @@ -0,0 +1,19 @@ +class Solution { + public void rotate(int[] nums, int k) { + k %= nums.length; + reverse(nums, 0, nums.length - 1); + reverse(nums, 0, k - 1); + reverse(nums, k, nums.length - 1); + } + + private void reverse(int[] nums, int l, int r) { + while (l < r) + swap(nums, l++, r--); + } + + private void swap(int[] nums, int l, int r) { + final int temp = nums[l]; + nums[l] = nums[r]; + nums[r] = temp; + } +} diff --git a/solutions/189. Rotate Array/189.py b/solutions/189. Rotate Array/189.py new file mode 100644 index 00000000000..8745ce92644 --- /dev/null +++ b/solutions/189. Rotate Array/189.py @@ -0,0 +1,12 @@ +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + k %= len(nums) + self.reverse(nums, 0, len(nums) - 1) + self.reverse(nums, 0, k - 1) + self.reverse(nums, k, len(nums) - 1) + + def reverse(self, nums: List[int], l: int, r: int) -> None: + while l < r: + nums[l], nums[r] = nums[r], nums[l] + l += 1 + r -= 1 diff --git a/solutions/1890. The Latest Login in 2020/1890.sql b/solutions/1890. The Latest Login in 2020/1890.sql new file mode 100644 index 00000000000..dedba075812 --- /dev/null +++ b/solutions/1890. The Latest Login in 2020/1890.sql @@ -0,0 +1,6 @@ +SELECT + user_id, + MAX(time_stamp) AS last_stamp +FROM Logins +WHERE YEAR(time_stamp) = 2020 +GROUP BY 1; diff --git a/solutions/1891. Cutting Ribbons/1891.cpp b/solutions/1891. Cutting Ribbons/1891.cpp new file mode 100644 index 00000000000..29e3b576b24 --- /dev/null +++ b/solutions/1891. Cutting Ribbons/1891.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int maxLength(vector& ribbons, int k) { + int l = 1; + int r = accumulate(ribbons.begin(), ribbons.end(), 0L) / k + 1; + + while (l < r) { + const int m = (l + r) / 2; + if (!isCutPossible(ribbons, m, k)) + r = m; + else + l = m + 1; + } + + return l - 1; + } + + private: + bool isCutPossible(const vector& ribbons, int length, int k) { + int count = 0; + for (const int ribbon : ribbons) + count += ribbon / length; + return count >= k; + } +}; diff --git a/solutions/1891. Cutting Ribbons/1891.java b/solutions/1891. Cutting Ribbons/1891.java new file mode 100644 index 00000000000..0ffa637084c --- /dev/null +++ b/solutions/1891. Cutting Ribbons/1891.java @@ -0,0 +1,23 @@ +class Solution { + public int maxLength(int[] ribbons, int k) { + int l = 1; + int r = (int) (Arrays.stream(ribbons).asLongStream().sum() / k) + 1; + + while (l < r) { + final int m = (l + r) / 2; + if (!isCutPossible(ribbons, m, k)) + r = m; + else + l = m + 1; + } + + return l - 1; + } + + private boolean isCutPossible(int[] ribbons, int length, int k) { + int count = 0; + for (final int ribbon : ribbons) + count += ribbon / length; + return count >= k; + } +} diff --git a/solutions/1891. Cutting Ribbons/1891.py b/solutions/1891. Cutting Ribbons/1891.py new file mode 100644 index 00000000000..0a8168c8b63 --- /dev/null +++ b/solutions/1891. Cutting Ribbons/1891.py @@ -0,0 +1,19 @@ +class Solution: + def maxLength(self, ribbons: List[int], k: int) -> int: + def isCutPossible(length: int) -> bool: + count = 0 + for ribbon in ribbons: + count += ribbon // length + return count >= k + + l = 1 + r = sum(ribbons) // k + 1 + + while l < r: + m = (l + r) // 2 + if not isCutPossible(m): + r = m + else: + l = m + 1 + + return l - 1 diff --git a/solutions/1892. Page Recommendations II/1892.sql b/solutions/1892. Page Recommendations II/1892.sql new file mode 100644 index 00000000000..181d7b82229 --- /dev/null +++ b/solutions/1892. Page Recommendations II/1892.sql @@ -0,0 +1,19 @@ +WITH + UserToFriends AS ( + SELECT user1_id AS user_id, user2_id AS friend_id FROM Friendship + UNION ALL + SELECT user2_id AS user_id, user1_id AS friend_id FROM friendship + ) +SELECT + UserToFriends.user_id, + FriendLikes.page_id, + COUNT(DISTINCT UserToFriends.friend_id) AS friends_likes +FROM UserToFriends +LEFT JOIN Likes AS FriendLikes + ON (UserToFriends.friend_id = FriendLikes.user_id) +LEFT JOIN Likes AS UserLikes + ON ( + UserToFriends.user_id = UserLikes.user_id + AND FriendLikes.page_id = UserLikes.page_id) +WHERE UserLikes.page_id IS NULL +GROUP BY 1, 2; diff --git a/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.cpp b/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.cpp new file mode 100644 index 00000000000..94bdeff7dcf --- /dev/null +++ b/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool isCovered(vector>& ranges, int left, int right) { + vector seen(52); + + for (const vector& range : ranges) { + ++seen[range[0]]; + --seen[range[1] + 1]; + } + + for (int i = 1; i < 52; ++i) + seen[i] += seen[i - 1]; + + for (int i = left; i <= right; ++i) + if (!seen[i]) + return false; + + return true; + } +}; diff --git a/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.java b/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.java new file mode 100644 index 00000000000..5d14dd90487 --- /dev/null +++ b/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.java @@ -0,0 +1,19 @@ +class Solution { + public boolean isCovered(int[][] ranges, int left, int right) { + int[] seen = new int[52]; + + for (int[] range : ranges) { + ++seen[range[0]]; + --seen[range[1] + 1]; + } + + for (int i = 1; i < 52; ++i) + seen[i] += seen[i - 1]; + + for (int i = left; i <= right; ++i) + if (seen[i] == 0) + return false; + + return true; + } +} diff --git a/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.py b/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.py new file mode 100644 index 00000000000..8ce7f845d59 --- /dev/null +++ b/solutions/1893. Check if All the Integers in a Range Are Covered/1893-2.py @@ -0,0 +1,12 @@ +class Solution: + def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: + seen = [0] * 52 + + for l, r in ranges: + seen[l] += 1 + seen[r + 1] -= 1 + + for i in range(1, 52): + seen[i] += seen[i - 1] + + return all(seen[i] for i in range(left, right + 1)) diff --git a/solutions/1893. Check if All the Integers in a Range Are Covered/1893.cpp b/solutions/1893. Check if All the Integers in a Range Are Covered/1893.cpp new file mode 100644 index 00000000000..4378d4f32bf --- /dev/null +++ b/solutions/1893. Check if All the Integers in a Range Are Covered/1893.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool isCovered(vector>& ranges, int left, int right) { + for (int i = left; i <= right; ++i) { + bool seen = false; + for (const vector& range : ranges) + if (i >= range[0] && i <= range[1]) { + seen = true; + break; + } + if (!seen) + return false; + } + + return true; + } +}; diff --git a/solutions/1893. Check if All the Integers in a Range Are Covered/1893.java b/solutions/1893. Check if All the Integers in a Range Are Covered/1893.java new file mode 100644 index 00000000000..46781f90cbc --- /dev/null +++ b/solutions/1893. Check if All the Integers in a Range Are Covered/1893.java @@ -0,0 +1,16 @@ +class Solution { + public boolean isCovered(int[][] ranges, int left, int right) { + for (int i = left; i <= right; ++i) { + boolean seen = false; + for (int[] range : ranges) + if (i >= range[0] && i <= range[1]) { + seen = true; + break; + } + if (!seen) + return false; + } + + return true; + } +} diff --git a/solutions/1893. Check if All the Integers in a Range Are Covered/1893.py b/solutions/1893. Check if All the Integers in a Range Are Covered/1893.py new file mode 100644 index 00000000000..a47e29a5927 --- /dev/null +++ b/solutions/1893. Check if All the Integers in a Range Are Covered/1893.py @@ -0,0 +1,4 @@ +class Solution: + def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: + return all(any(l <= i <= r for l, r in ranges) for i in range( + left, right + 1)) diff --git a/solutions/1894. Find the Student that Will Replace the Chalk/1894.cpp b/solutions/1894. Find the Student that Will Replace the Chalk/1894.cpp new file mode 100644 index 00000000000..aef22cc2968 --- /dev/null +++ b/solutions/1894. Find the Student that Will Replace the Chalk/1894.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int chalkReplacer(vector& chalk, int k) { + k %= accumulate(chalk.begin(), chalk.end(), 0L); + if (k == 0) + return 0; + + for (int i = 0; i < chalk.size(); ++i) { + k -= chalk[i]; + if (k < 0) + return i; + } + + throw; + } +}; diff --git a/solutions/1894. Find the Student that Will Replace the Chalk/1894.java b/solutions/1894. Find the Student that Will Replace the Chalk/1894.java new file mode 100644 index 00000000000..f1754df23ae --- /dev/null +++ b/solutions/1894. Find the Student that Will Replace the Chalk/1894.java @@ -0,0 +1,15 @@ +class Solution { + public int chalkReplacer(int[] chalk, int k) { + k %= Arrays.stream(chalk).asLongStream().sum(); + if (k == 0) + return 0; + + for (int i = 0; i < chalk.length; ++i) { + k -= chalk[i]; + if (k < 0) + return i; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1894. Find the Student that Will Replace the Chalk/1894.py b/solutions/1894. Find the Student that Will Replace the Chalk/1894.py new file mode 100644 index 00000000000..a06732b95b6 --- /dev/null +++ b/solutions/1894. Find the Student that Will Replace the Chalk/1894.py @@ -0,0 +1,10 @@ +class Solution: + def chalkReplacer(self, chalk: List[int], k: int) -> int: + k %= sum(chalk) + if k == 0: + return 0 + + for i, c in enumerate(chalk): + k -= c + if k < 0: + return i diff --git a/solutions/1895. Largest Magic Square/1895.cpp b/solutions/1895. Largest Magic Square/1895.cpp new file mode 100644 index 00000000000..cc8a113ec04 --- /dev/null +++ b/solutions/1895. Largest Magic Square/1895.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + int largestMagicSquare(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + // prefixRow[i][j] := the sum of the first j numbers in the i-th row + vector> prefixRow(m, vector(n + 1)); + // prefixCol[i][j] := the sum of the first j numbers in the i-th column + vector> prefixCol(n, vector(m + 1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + prefixRow[i][j + 1] = prefixRow[i][j] + grid[i][j]; + prefixCol[j][i + 1] = prefixCol[j][i] + grid[i][j]; + } + + for (int k = min(m, n); k >= 2; --k) + if (containsMagicSquare(grid, prefixRow, prefixCol, k)) + return k; + + return 1; + } + + private: + // Returns true if the grid contains any magic square of size k x k. + bool containsMagicSquare(const vector>& grid, + const vector>& prefixRow, + const vector>& prefixCol, int k) { + for (int i = 0; i + k - 1 < grid.size(); ++i) + for (int j = 0; j + k - 1 < grid[0].size(); ++j) + if (isMagicSquare(grid, prefixRow, prefixCol, i, j, k)) + return true; + return false; + } + + // Returns true if grid[i..i + k)[j..j + k) is a magic square. + bool isMagicSquare(const vector>& grid, + const vector>& prefixRow, + const vector>& prefixCol, int i, int j, + int k) { + int diag = 0; + int antiDiag = 0; + for (int d = 0; d < k; ++d) { + diag += grid[i + d][j + d]; + antiDiag += grid[i + d][j + k - 1 - d]; + } + if (diag != antiDiag) + return false; + for (int d = 0; d < k; ++d) { + if (getSum(prefixRow, i + d, j, j + k - 1) != diag) + return false; + if (getSum(prefixCol, j + d, i, i + k - 1) != diag) + return false; + } + return true; + } + + // Returns sum(grid[i][l..r]) or sum(grid[l..r][i]). + int getSum(const vector>& prefix, int i, int l, int r) { + return prefix[i][r + 1] - prefix[i][l]; + } +}; diff --git a/solutions/1895. Largest Magic Square/1895.java b/solutions/1895. Largest Magic Square/1895.java new file mode 100644 index 00000000000..7c44636468e --- /dev/null +++ b/solutions/1895. Largest Magic Square/1895.java @@ -0,0 +1,56 @@ +class Solution { + public int largestMagicSquare(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + // prefixRow[i][j] := the sum of the first j numbers in the i-th row + int[][] prefixRow = new int[m][n + 1]; + // prefixCol[i][j] := the sum of the first j numbers in the i-th column + int[][] prefixCol = new int[n][m + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + prefixRow[i][j + 1] = prefixRow[i][j] + grid[i][j]; + prefixCol[j][i + 1] = prefixCol[j][i] + grid[i][j]; + } + + for (int k = Math.min(m, n); k >= 2; --k) + if (containsMagicSquare(grid, prefixRow, prefixCol, k)) + return k; + + return 1; + } + + // Returns true if the grid contains any magic square of size k x k. + private boolean containsMagicSquare(int[][] grid, int[][] prefixRow, int[][] prefixCol, int k) { + for (int i = 0; i + k - 1 < grid.length; ++i) + for (int j = 0; j + k - 1 < grid[0].length; ++j) + if (isMagicSquare(grid, prefixRow, prefixCol, i, j, k)) + return true; + return false; + } + + // Returns true if grid[i..i + k)[j..j + k) is a magic square. + private boolean isMagicSquare(int[][] grid, int[][] prefixRow, int[][] prefixCol, int i, int j, + int k) { + int diag = 0; + int antiDiag = 0; + for (int d = 0; d < k; ++d) { + diag += grid[i + d][j + d]; + antiDiag += grid[i + d][j + k - 1 - d]; + } + if (diag != antiDiag) + return false; + for (int d = 0; d < k; ++d) { + if (getSum(prefixRow, i + d, j, j + k - 1) != diag) + return false; + if (getSum(prefixCol, j + d, i, i + k - 1) != diag) + return false; + } + return true; + } + + // Returns sum(grid[i][l..r]) or sum(grid[l..r][i]). + private int getSum(int[][] prefix, int i, int l, int r) { + return prefix[i][r + 1] - prefix[i][l]; + } +} diff --git a/solutions/1895. Largest Magic Square/1895.py b/solutions/1895. Largest Magic Square/1895.py new file mode 100644 index 00000000000..e4fff807433 --- /dev/null +++ b/solutions/1895. Largest Magic Square/1895.py @@ -0,0 +1,46 @@ +class Solution: + def largestMagicSquare(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + # prefixRow[i][j] := the sum of the first j numbers in the i-th row + prefixRow = [[0] * (n + 1) for _ in range(m)] + # prefixCol[i][j] := the sum of the first j numbers in the i-th column + prefixCol = [[0] * (m + 1) for _ in range(n)] + + for i in range(m): + for j in range(n): + prefixRow[i][j + 1] = prefixRow[i][j] + grid[i][j] + prefixCol[j][i + 1] = prefixCol[j][i] + grid[i][j] + + def isMagicSquare(i: int, j: int, k: int) -> bool: + """Returns True if grid[i..i + k)[j..j + k) is a magic square.""" + diag, antiDiag = 0, 0 + for d in range(k): + diag += grid[i + d][j + d] + antiDiag += grid[i + d][j + k - 1 - d] + if diag != antiDiag: + return False + for d in range(k): + if self._getSum(prefixRow, i + d, j, j + k - 1) != diag: + return False + if self._getSum(prefixCol, j + d, i, i + k - 1) != diag: + return False + return True + + def containsMagicSquare(k: int) -> bool: + """Returns True if the grid contains any magic square of size k x k.""" + for i in range(m - k + 1): + for j in range(n - k + 1): + if isMagicSquare(i, j, k): + return True + return False + + for k in range(min(m, n), 1, -1): + if containsMagicSquare(k): + return k + + return 1 + + def _getSum(self, prefix: List[List[int]], i: int, l: int, r: int) -> int: + """Returns sum(grid[i][l..r]) or sum(grid[l..r][i]).""" + return prefix[i][r + 1] - prefix[i][l] diff --git a/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.cpp b/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.cpp new file mode 100644 index 00000000000..13ce7c4dfff --- /dev/null +++ b/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.cpp @@ -0,0 +1,64 @@ +class Solution { + public: + int minOperationsToFlip(string expression) { + // [(the expression, the cost to toggle the expression)] + stack> stack; + pair lastPair; + + for (const char e : expression) { + if (e == '(' || e == '&' || e == '|') { + // These aren't expressions, so the cost is meaningless. + stack.push({e, 0}); + continue; + } + if (e == ')') { + lastPair = stack.top(); + stack.pop(); + stack.pop(); // Pop '('. + } else { // e == '0' || e == '1' + // Store the '0' or '1'. The cost to change their values is just 1, + // whether it's changing '0' to '1' or '1' to '0'. + lastPair = {e, 1}; + } + if (!stack.empty() && + (stack.top().first == '&' || stack.top().first == '|')) { + const char op = stack.top().first; + stack.pop(); + const auto [a, costA] = stack.top(); + stack.pop(); + const auto [b, costB] = lastPair; + // Determine the cost to toggle op(a, b). + if (op == '&') { + if (a == '0' && b == '0') + // Change '&' to '|' and a|b to '1'. + lastPair = {'0', 1 + min(costA, costB)}; + else if (a == '0' && b == '1') + // Change '&' to '|'. + lastPair = {'0', 1}; + else if (a == '1' && b == '0') + // Change '&' to '|'. + lastPair = {'0', 1}; + else // a == '1' and b == '1' + // Change a|b to '0'. + lastPair = {'1', min(costA, costB)}; + } else { // op == '|' + if (a == '0' && b == '0') + // Change a|b to '1'. + lastPair = {'0', min(costA, costB)}; + else if (a == '0' && b == '1') + // Change '|' to '&'. + lastPair = {'1', 1}; + else if (a == '1' && b == '0') + // Change '|' to '&'. + lastPair = {'1', 1}; + else // a == '1' and b == '1' + // Change '|' to '&' and a|b to '0'. + lastPair = {'1', 1 + min(costA, costB)}; + } + } + stack.push(lastPair); + } + + return stack.top().second; + } +}; diff --git a/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.java b/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.java new file mode 100644 index 00000000000..5bc88fec628 --- /dev/null +++ b/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.java @@ -0,0 +1,61 @@ +class Solution { + public int minOperationsToFlip(String expression) { + // [(the expression, the cost to toggle the expression)] + Deque> stack = new ArrayDeque<>(); + Pair lastPair = null; + + for (final char e : expression.toCharArray()) { + if (e == '(' || e == '&' || e == '|') { + // These aren't expressions, so the cost is meaningless. + stack.push(new Pair<>(e, 0)); + continue; + } + if (e == ')') { + lastPair = stack.pop(); + stack.pop(); // Pop '('. + } else { // e == '0' || e == '1' + // Store the '0' or '1'. The cost to change their values is just 1, + // whether it's changing '0' to '1' or '1' to '0'. + lastPair = new Pair<>(e, 1); + } + if (!stack.isEmpty() && (stack.peek().getKey() == '&' || stack.peek().getKey() == '|')) { + final char op = stack.pop().getKey(); + final char a = stack.peek().getKey(); + final int costA = stack.pop().getValue(); + final char b = lastPair.getKey(); + final int costB = lastPair.getValue(); + // Determine the cost to toggle op(a, b). + if (op == '&') { + if (a == '0' && b == '0') + // Change '&' to '|' and a|b to '1'. + lastPair = new Pair<>('0', 1 + Math.min(costA, costB)); + else if (a == '0' && b == '1') + // Change '&' to '|'. + lastPair = new Pair<>('0', 1); + else if (a == '1' && b == '0') + // Change '&' to '|'. + lastPair = new Pair<>('0', 1); + else // a == '1' and b == '1' + // Change a|b to '0'. + lastPair = new Pair<>('1', Math.min(costA, costB)); + } else { // op == '|' + if (a == '0' && b == '0') + // Change a|b to '1'. + lastPair = new Pair<>('0', Math.min(costA, costB)); + else if (a == '0' && b == '1') + // Change '|' to '&'. + lastPair = new Pair<>('1', 1); + else if (a == '1' && b == '0') + // Change '|' to '&'. + lastPair = new Pair<>('1', 1); + else // a == '1' and b == '1' + // Change '|' to '&' and a|b to '0'. + lastPair = new Pair<>('1', 1 + Math.min(costA, costB)); + } + } + stack.push(lastPair); + } + + return stack.peek().getValue(); + } +} diff --git a/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.py b/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.py new file mode 100644 index 00000000000..1bd86991294 --- /dev/null +++ b/solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.py @@ -0,0 +1,50 @@ +class Solution: + def minOperationsToFlip(self, expression: str) -> int: + stack = [] # [(the expression, the cost to toggle the expression)] + + for e in expression: + if e in '(&|': + # These aren't expressions, so the cost is meaningless. + stack.append((e, 0)) + continue + if e == ')': + lastPair = stack.pop() + stack.pop() # Pop '('. + else: # e == '0' or e == '1' + # Store the '0' or '1'. The cost to change their values is just 1, + # whether it's changing '0' to '1' or '1' to '0'. + lastPair = (e, 1) + if stack and stack[-1][0] in '&|': + op = stack.pop()[0] + a, costA = stack.pop() + b, costB = lastPair + # Determine the cost to toggle op(a, b). + if op == '&': + if a == '0' and b == '0': + # Change '&' to '|' and a|b to '1'. + lastPair = ('0', 1 + min(costA, costB)) + elif a == '0' and b == '1': + # Change '&' to '|'. + lastPair = ('0', 1) + elif a == '1' and b == '0': + # Change '&' to '|'. + lastPair = ('0', 1) + else: # a == '1' and b == '1' + # Change a|b to '0'. + lastPair = ('1', min(costA, costB)) + else: # op == '|' + if a == '0' and b == '0': + # Change a|b to '1'. + lastPair = ('0', min(costA, costB)) + elif a == '0' and b == '1': + # Change '|' to '&'. + lastPair = ('1', 1) + elif a == '1' and b == '0': + # Change '|' to '&'. + lastPair = ('1', 1) + else: # a == '1' and b == '1' + # Change '|' to '&' and a|b to '0'. + lastPair = ('1', 1 + min(costA, costB)) + stack.append(lastPair) + + return stack[-1][1] diff --git a/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.cpp b/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.cpp new file mode 100644 index 00000000000..7a0e45ef344 --- /dev/null +++ b/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool makeEqual(vector& words) { + vector count(26); + + for (const string& word : words) + for (const char c : word) + ++count[c - 'a']; + + return ranges::all_of(count, + [&](const int c) { return c % words.size() == 0; }); + } +}; diff --git a/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.java b/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.java new file mode 100644 index 00000000000..558cefe2588 --- /dev/null +++ b/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.java @@ -0,0 +1,11 @@ +class Solution { + public boolean makeEqual(String[] words) { + int[] count = new int[26]; + + for (final String word : words) + for (final char c : word.toCharArray()) + ++count[c - 'a']; + + return Arrays.stream(count).allMatch(c -> c % words.length == 0); + } +} diff --git a/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.py b/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.py new file mode 100644 index 00000000000..450610f14cf --- /dev/null +++ b/solutions/1897. Redistribute Characters to Make All Strings Equal/1897.py @@ -0,0 +1,3 @@ +class Solution: + def makeEqual(self, words: List[str]) -> bool: + return all(c % len(words) == 0 for c in collections.Counter(''.join(words)).values()) diff --git a/solutions/1898. Maximum Number of Removable Characters/1898.cpp b/solutions/1898. Maximum Number of Removable Characters/1898.cpp new file mode 100644 index 00000000000..9b076c76ea1 --- /dev/null +++ b/solutions/1898. Maximum Number of Removable Characters/1898.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int maximumRemovals(string s, string p, vector& removable) { + int l = 0; + int r = removable.size() + 1; + + while (l < r) { + const int m = (l + r) / 2; + const string removed = remove(s, removable, m); + if (isSubsequence(p, removed)) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + private: + string remove(const string& s, const vector& removable, int k) { + string removed(s); + for (int i = 0; i < k; ++i) + removed[removable[i]] = '*'; + return removed; + } + + bool isSubsequence(const string& p, const string& s) { + int i = 0; // p's index + for (int j = 0; j < s.length(); ++j) + if (p[i] == s[j]) + if (++i == p.length()) + return true; + return false; + } +}; diff --git a/solutions/1898. Maximum Number of Removable Characters/1898.java b/solutions/1898. Maximum Number of Removable Characters/1898.java new file mode 100644 index 00000000000..32e4c2e5572 --- /dev/null +++ b/solutions/1898. Maximum Number of Removable Characters/1898.java @@ -0,0 +1,33 @@ +class Solution { + public int maximumRemovals(String s, String p, int[] removable) { + int l = 0; + int r = removable.length + 1; + + while (l < r) { + final int m = (l + r) / 2; + final String removed = remove(s, removable, m); + if (isSubsequence(p, removed)) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + private String remove(final String s, int[] removable, int k) { + StringBuilder sb = new StringBuilder(s); + for (int i = 0; i < k; ++i) + sb.setCharAt(removable[i], '*'); + return sb.toString(); + } + + private boolean isSubsequence(final String p, final String s) { + int i = 0; // p's index + for (int j = 0; j < s.length(); ++j) + if (p.charAt(i) == s.charAt(j)) + if (++i == p.length()) + return true; + return false; + } +} diff --git a/solutions/1898. Maximum Number of Removable Characters/1898.py b/solutions/1898. Maximum Number of Removable Characters/1898.py new file mode 100644 index 00000000000..bb4deafda2b --- /dev/null +++ b/solutions/1898. Maximum Number of Removable Characters/1898.py @@ -0,0 +1,29 @@ +class Solution: + def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int: + l = 0 + r = len(removable) + 1 + + def remove(k: int) -> str: + removed = [c for c in s] + for i in range(k): + removed[removable[i]] = '*' + return ''.join(removed) + + def isSubsequence(p: str, s: str) -> bool: + i = 0 + for j, c in enumerate(s): + if p[i] == s[j]: + i += 1 + if i == len(p): + return True + return False + + while l < r: + m = (l + r) // 2 + removed = remove(m) + if isSubsequence(p, removed): + l = m + 1 + else: + r = m + + return l - 1 diff --git a/solutions/1899. Merge Triplets to Form Target Triplet/1899.cpp b/solutions/1899. Merge Triplets to Form Target Triplet/1899.cpp new file mode 100644 index 00000000000..fcfa1c6032b --- /dev/null +++ b/solutions/1899. Merge Triplets to Form Target Triplet/1899.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + bool mergeTriplets(vector>& triplets, vector& target) { + vector merged(target.size()); + + for (const vector& triplet : triplets) + if (equal(triplet.begin(), triplet.end(), target.begin(), + [](int a, int b) { return a <= b; })) + transform(triplet.begin(), triplet.end(), merged.begin(), + merged.begin(), [](int a, int b) { return max(a, b); }); + + return merged == target; + } +}; diff --git a/solutions/1899. Merge Triplets to Form Target Triplet/1899.java b/solutions/1899. Merge Triplets to Form Target Triplet/1899.java new file mode 100644 index 00000000000..da3a51cf68a --- /dev/null +++ b/solutions/1899. Merge Triplets to Form Target Triplet/1899.java @@ -0,0 +1,12 @@ +class Solution { + public boolean mergeTriplets(int[][] triplets, int[] target) { + int[] merged = new int[target.length]; + + for (int[] triplet : triplets) + if (triplet[0] <= target[0] && triplet[1] <= target[1] && triplet[2] <= target[2]) + for (int i = 0; i < target.length; ++i) + merged[i] = Math.max(merged[i], triplet[i]); + + return Arrays.equals(merged, target); + } +} diff --git a/solutions/1899. Merge Triplets to Form Target Triplet/1899.py b/solutions/1899. Merge Triplets to Form Target Triplet/1899.py new file mode 100644 index 00000000000..7e6a30eba57 --- /dev/null +++ b/solutions/1899. Merge Triplets to Form Target Triplet/1899.py @@ -0,0 +1,10 @@ +class Solution: + def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: + merged = [0] * len(target) + + for triplet in triplets: + if all(a <= b for a, b in zip(triplet, target)): + for i in range(3): + merged[i] = max(merged[i], triplet[i]) + + return merged == target diff --git a/solutions/19. Remove Nth Node From End of List/19.cpp b/solutions/19. Remove Nth Node From End of List/19.cpp new file mode 100644 index 00000000000..0f5b94141f9 --- /dev/null +++ b/solutions/19. Remove Nth Node From End of List/19.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode* slow = head; + ListNode* fast = head; + + while (n--) + fast = fast->next; + if (fast == nullptr) + return head->next; + + while (fast->next) { + slow = slow->next; + fast = fast->next; + } + slow->next = slow->next->next; + + return head; + } +}; diff --git a/solutions/19. Remove Nth Node From End of List/19.java b/solutions/19. Remove Nth Node From End of List/19.java new file mode 100644 index 00000000000..44c88305304 --- /dev/null +++ b/solutions/19. Remove Nth Node From End of List/19.java @@ -0,0 +1,19 @@ +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode slow = head; + ListNode fast = head; + + while (n-- > 0) + fast = fast.next; + if (fast == null) + return head.next; + + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + slow.next = slow.next.next; + + return head; + } +} diff --git a/solutions/19. Remove Nth Node From End of List/19.py b/solutions/19. Remove Nth Node From End of List/19.py new file mode 100644 index 00000000000..9a3bf6748e0 --- /dev/null +++ b/solutions/19. Remove Nth Node From End of List/19.py @@ -0,0 +1,16 @@ +class Solution: + def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: + slow = head + fast = head + + for _ in range(n): + fast = fast.next + if not fast: + return head.next + + while fast.next: + slow = slow.next + fast = fast.next + slow.next = slow.next.next + + return head diff --git a/solutions/190. Reverse Bits/190.cpp b/solutions/190. Reverse Bits/190.cpp new file mode 100644 index 00000000000..9923c2aed86 --- /dev/null +++ b/solutions/190. Reverse Bits/190.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + uint32_t reverseBits(uint32_t n) { + uint32_t ans = 0; + + for (int i = 0; i < 32; ++i) + if (n >> i & 1) + ans |= 1 << 31 - i; + + return ans; + } +}; diff --git a/solutions/190. Reverse Bits/190.java b/solutions/190. Reverse Bits/190.java new file mode 100644 index 00000000000..4b1b74a2ba7 --- /dev/null +++ b/solutions/190. Reverse Bits/190.java @@ -0,0 +1,12 @@ +public class Solution { + // You need treat n as an unsigned value + public int reverseBits(int n) { + int ans = 0; + + for (int i = 0; i < 32; ++i) + if ((n >> i & 1) == 1) + ans |= 1 << 31 - i; + + return ans; + } +} diff --git a/solutions/190. Reverse Bits/190.py b/solutions/190. Reverse Bits/190.py new file mode 100644 index 00000000000..3a18f56b0cc --- /dev/null +++ b/solutions/190. Reverse Bits/190.py @@ -0,0 +1,9 @@ +class Solution: + def reverseBits(self, n: int) -> int: + ans = 0 + + for i in range(32): + if n >> i & 1: + ans |= 1 << 31 - i + + return ans diff --git a/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.cpp b/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.cpp new file mode 100644 index 00000000000..c5e93613afd --- /dev/null +++ b/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + vector earliestAndLatest(int n, int firstPlayer, int secondPlayer) { + using P = pair; + vector>> mem(n + 1, + vector>(n + 1, vector

(n + 1))); + const auto [a, b] = solve(firstPlayer, n - secondPlayer + 1, n, mem); + return {a, b}; + } + + private: + // Returns the (earliest, latest) pair, the first player is the l-th player + // from the front, the second player is the r-th player from the end, and + // there're k people. + pair solve(int l, int r, int k, + vector>>>& mem) { + if (l == r) + return {1, 1}; + if (l > r) + swap(l, r); + if (mem[l][r][k] != pair{0, 0}) + return mem[l][r][k]; + + int a = INT_MAX; + int b = INT_MIN; + + // Enumerate all the possible positions. + for (int i = 1; i <= l; ++i) + for (int j = l - i + 1; j <= r - i; ++j) { + if (i + j > (k + 1) / 2 || i + j < l + r - k / 2) + continue; + const auto [x, y] = solve(i, j, (k + 1) / 2, mem); + a = min(a, x + 1); + b = max(b, y + 1); + } + + return mem[l][r][k] = {a, b}; + } +}; diff --git a/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.java b/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.java new file mode 100644 index 00000000000..57466ef6e52 --- /dev/null +++ b/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.java @@ -0,0 +1,33 @@ +class Solution { + public int[] earliestAndLatest(int n, int firstPlayer, int secondPlayer) { + int[][][][] mem = new int[n + 1][n + 1][n + 1][2]; + return solve(firstPlayer, n - secondPlayer + 1, n, mem); + } + + // Returns the (earliest, latest) pair, the first player is the l-th player + // from the front, the second player is the r-th player from the end, and + // there're k people. + private int[] solve(int l, int r, int k, int[][][][] mem) { + if (l == r) + return new int[] {1, 1}; + if (l > r) + return solve(r, l, k, mem); + if (!Arrays.equals(mem[l][r][k], new int[] {0, 0})) + return mem[l][r][k]; + + int a = Integer.MAX_VALUE; + int b = Integer.MIN_VALUE; + + // Enumerate all the possible positions. + for (int i = 1; i <= l; ++i) + for (int j = l - i + 1; j <= r - i; ++j) { + if (i + j > (k + 1) / 2 || i + j < l + r - k / 2) + continue; + int[] res = solve(i, j, (k + 1) / 2, mem); + a = Math.min(a, res[0] + 1); + b = Math.max(b, res[1] + 1); + } + + return mem[l][r][k] = new int[] {a, b}; + } +} diff --git a/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.py b/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.py new file mode 100644 index 00000000000..0c3dc81a6ff --- /dev/null +++ b/solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.py @@ -0,0 +1,30 @@ +class Solution: + def earliestAndLatest(self, n: int, + firstPlayer: int, secondPlayer: int) -> List[int]: + @functools.lru_cache(None) + def dp(l: int, r: int, k: int) -> List[int]: + """ + Returns the (earliest, latest) pair, the first player is the l-th player + from the front, the second player is the r-th player from the end, and + there're k people. + """ + if l == r: + return [1, 1] + if l > r: + return dp(r, l, k) + + a = math.inf + b = -math.inf + + # Enumerate all the possible positions. + for i in range(1, l + 1): + for j in range(l - i + 1, r - i + 1): + if not l + r - k // 2 <= i + j <= (k + 1) // 2: + continue + x, y = dp(i, j, (k + 1) // 2) + a = min(a, x + 1) + b = max(b, y + 1) + + return [a, b] + + return dp(firstPlayer, n - secondPlayer + 1, n) diff --git a/solutions/1901. Find a Peak Element II/1901.cpp b/solutions/1901. Find a Peak Element II/1901.cpp new file mode 100644 index 00000000000..a13c479ce6a --- /dev/null +++ b/solutions/1901. Find a Peak Element II/1901.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector findPeakGrid(vector>& mat) { + int l = 0; + int r = mat.size() - 1; + + while (l < r) { + const int m = (l + r) / 2; + if (ranges::max(mat[m]) >= ranges::max(mat[m + 1])) + r = m; + else + l = m + 1; + } + + return {l, getMaxIndex(mat[l])}; + } + + private: + int getMaxIndex(const vector& A) { + pair res{0, A[0]}; + for (int i = 1; i < A.size(); ++i) + if (A[i] > res.second) + res = {i, A[i]}; + return res.first; + } +}; diff --git a/solutions/1901. Find a Peak Element II/1901.java b/solutions/1901. Find a Peak Element II/1901.java new file mode 100644 index 00000000000..9db1c56583d --- /dev/null +++ b/solutions/1901. Find a Peak Element II/1901.java @@ -0,0 +1,24 @@ +class Solution { + public int[] findPeakGrid(int[][] mat) { + int l = 0; + int r = mat.length - 1; + + while (l < r) { + final int m = (l + r) / 2; + if (Arrays.stream(mat[m]).max().getAsInt() >= Arrays.stream(mat[m + 1]).max().getAsInt()) + r = m; + else + l = m + 1; + } + + return new int[] {l, getMaxIndex(mat[l])}; + } + + private int getMaxIndex(int[] A) { + int[] res = {0, A[0]}; + for (int i = 1; i < A.length; ++i) + if (A[i] > res[1]) + res = new int[] {i, A[i]}; + return res[0]; + } +} diff --git a/solutions/1901. Find a Peak Element II/1901.py b/solutions/1901. Find a Peak Element II/1901.py new file mode 100644 index 00000000000..28adaa31a97 --- /dev/null +++ b/solutions/1901. Find a Peak Element II/1901.py @@ -0,0 +1,13 @@ +class Solution: + def findPeakGrid(self, mat: List[List[int]]) -> List[int]: + l = 0 + r = len(mat) - 1 + + while l < r: + m = (l + r) // 2 + if max(mat[m]) >= max(mat[m + 1]): + r = m + else: + l = m + 1 + + return [l, mat[l].index(max(mat[l]))] diff --git a/solutions/1902. Depth of BST Given Insertion Order/1902.cpp b/solutions/1902. Depth of BST Given Insertion Order/1902.cpp new file mode 100644 index 00000000000..8f0827a1f95 --- /dev/null +++ b/solutions/1902. Depth of BST Given Insertion Order/1902.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maxDepthBST(vector& order) { + int ans = 1; + map valToDepth; + + for (const int val : order) { + const auto l = valToDepth.upper_bound(val); + const auto r = valToDepth.lower_bound(val); + const int leftDepth = l == valToDepth.cbegin() ? 0 : prev(l)->second; + const int rightDepth = r == valToDepth.cend() ? 0 : r->second; + const int depth = max(leftDepth, rightDepth) + 1; + ans = max(ans, depth); + valToDepth[val] = depth; + } + + return ans; + } +}; diff --git a/solutions/1902. Depth of BST Given Insertion Order/1902.java b/solutions/1902. Depth of BST Given Insertion Order/1902.java new file mode 100644 index 00000000000..21b9eeb102d --- /dev/null +++ b/solutions/1902. Depth of BST Given Insertion Order/1902.java @@ -0,0 +1,18 @@ +class Solution { + public int maxDepthBST(int[] order) { + int ans = 1; + TreeMap valToDepth = new TreeMap<>(); + + for (final int val : order) { + Map.Entry l = valToDepth.floorEntry(val); + Map.Entry r = valToDepth.ceilingEntry(val); + final int leftDepth = l == null ? 0 : l.getValue(); + final int rightDepth = r == null ? 0 : r.getValue(); + final int depth = Math.max(leftDepth, rightDepth) + 1; + ans = Math.max(ans, depth); + valToDepth.put(val, depth); + } + + return ans; + } +} diff --git a/solutions/1903. Largest Odd Number in String/1903.cpp b/solutions/1903. Largest Odd Number in String/1903.cpp new file mode 100644 index 00000000000..af3f8366616 --- /dev/null +++ b/solutions/1903. Largest Odd Number in String/1903.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + string largestOddNumber(string num) { + for (int i = num.length() - 1; i >= 0; --i) + if ((num[i] - '0') % 2 == 1) + return num.substr(0, i + 1); + return ""; + } +}; diff --git a/solutions/1903. Largest Odd Number in String/1903.java b/solutions/1903. Largest Odd Number in String/1903.java new file mode 100644 index 00000000000..26eb186a18b --- /dev/null +++ b/solutions/1903. Largest Odd Number in String/1903.java @@ -0,0 +1,8 @@ +class Solution { + public String largestOddNumber(String num) { + for (int i = num.length() - 1; i >= 0; --i) + if ((num.charAt(i) - '0') % 2 == 1) + return num.substring(0, i + 1); + return ""; + } +} diff --git a/solutions/1903. Largest Odd Number in String/1903.py b/solutions/1903. Largest Odd Number in String/1903.py new file mode 100644 index 00000000000..9acb50c13ea --- /dev/null +++ b/solutions/1903. Largest Odd Number in String/1903.py @@ -0,0 +1,6 @@ +class Solution: + def largestOddNumber(self, num: str) -> str: + for i, n in reversed(list(enumerate(num))): + if int(n) % 2 == 1: + return num[:i + 1] + return '' diff --git a/solutions/1904. The Number of Full Rounds You Have Played/1904.cpp b/solutions/1904. The Number of Full Rounds You Have Played/1904.cpp new file mode 100644 index 00000000000..44cb03cb08b --- /dev/null +++ b/solutions/1904. The Number of Full Rounds You Have Played/1904.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int numberOfRounds(string loginTime, string logoutTime) { + const int start = getMinutes(loginTime); + int finish = getMinutes(logoutTime); + if (start > finish) + finish += 60 * 24; + return max(0, finish / 15 - (start + 14) / 15); + } + + private: + int getMinutes(const string& time) { + const int h = stoi(time.substr(0, 2)); + const int m = stoi(time.substr(3)); + return 60 * h + m; + } +}; diff --git a/solutions/1904. The Number of Full Rounds You Have Played/1904.java b/solutions/1904. The Number of Full Rounds You Have Played/1904.java new file mode 100644 index 00000000000..bfbbc4309d3 --- /dev/null +++ b/solutions/1904. The Number of Full Rounds You Have Played/1904.java @@ -0,0 +1,13 @@ +class Solution { + public int numberOfRounds(String loginTime, String logoutTime) { + final int start = getMinutes(loginTime); + int finish = getMinutes(logoutTime); + if (start > finish) + finish += 60 * 24; + return Math.max(0, finish / 15 - (start + 14) / 15); + } + + private int getMinutes(final String s) { + return 60 * Integer.valueOf(s.substring(0, 2)) + Integer.valueOf(s.substring(3)); + } +} diff --git a/solutions/1904. The Number of Full Rounds You Have Played/1904.py b/solutions/1904. The Number of Full Rounds You Have Played/1904.py new file mode 100644 index 00000000000..ef3b2021b06 --- /dev/null +++ b/solutions/1904. The Number of Full Rounds You Have Played/1904.py @@ -0,0 +1,12 @@ +class Solution: + def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: + start = self._getMinutes(loginTime) + finish = self._getMinutes(logoutTime) + if start > finish: + finish += 60 * 24 + + return max(0, finish // 15 - (start + 14) // 15) + + def _getMinutes(self, time: str) -> int: + h, m = map(int, time.split(':')) + return 60 * h + m diff --git a/solutions/1905. Count Sub Islands/1905.cpp b/solutions/1905. Count Sub Islands/1905.cpp new file mode 100644 index 00000000000..04db58c1394 --- /dev/null +++ b/solutions/1905. Count Sub Islands/1905.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int countSubIslands(vector>& grid1, vector>& grid2) { + int ans = 0; + + for (int i = 0; i < grid2.size(); ++i) + for (int j = 0; j < grid2[0].size(); ++j) + if (grid2[i][j] == 1) + ans += dfs(grid1, grid2, i, j); + + return ans; + } + + private: + int dfs(const vector>& grid1, vector>& grid2, int i, + int j) { + if (i < 0 || i == grid1.size() || j < 0 || j == grid2[0].size()) + return 1; + if (grid2[i][j] != 1) + return 1; + + grid2[i][j] = 2; // Mark 2 as visited. + + return dfs(grid1, grid2, i + 1, j) & dfs(grid1, grid2, i - 1, j) & + dfs(grid1, grid2, i, j + 1) & dfs(grid1, grid2, i, j - 1) & + grid1[i][j]; + } +}; diff --git a/solutions/1905. Count Sub Islands/1905.java b/solutions/1905. Count Sub Islands/1905.java new file mode 100644 index 00000000000..ccbedafdf5f --- /dev/null +++ b/solutions/1905. Count Sub Islands/1905.java @@ -0,0 +1,25 @@ +class Solution { + public int countSubIslands(int[][] grid1, int[][] grid2) { + int ans = 0; + + for (int i = 0; i < grid2.length; ++i) + for (int j = 0; j < grid2[0].length; ++j) + if (grid2[i][j] == 1) + ans += dfs(grid1, grid2, i, j); + + return ans; + } + + private int dfs(int[][] grid1, int[][] grid2, int i, int j) { + if (i < 0 || i == grid1.length || j < 0 || j == grid2[0].length) + return 1; + if (grid2[i][j] != 1) + return 1; + + grid2[i][j] = 2; // Mark 2 as visited. + + return // + dfs(grid1, grid2, i + 1, j) & dfs(grid1, grid2, i - 1, j) & // + dfs(grid1, grid2, i, j + 1) & dfs(grid1, grid2, i, j - 1) & grid1[i][j]; + } +} diff --git a/solutions/1905. Count Sub Islands/1905.py b/solutions/1905. Count Sub Islands/1905.py new file mode 100644 index 00000000000..cfd4433c9c4 --- /dev/null +++ b/solutions/1905. Count Sub Islands/1905.py @@ -0,0 +1,24 @@ +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + m = len(grid2) + n = len(grid2[0]) + + def dfs(i: int, j: int) -> int: + if i < 0 or i == m or j < 0 or j == n: + return 1 + if grid2[i][j] != 1: + return 1 + + grid2[i][j] = 2 # Mark 2 as visited. + + return dfs(i + 1, j) & dfs(i - 1, j) & \ + dfs(i, j + 1) & dfs(i, j - 1) & grid1[i][j] + + ans = 0 + + for i in range(m): + for j in range(n): + if grid2[i][j] == 1: + ans += dfs(i, j) + + return ans diff --git a/solutions/1906. Minimum Absolute Difference Queries/1906.cpp b/solutions/1906. Minimum Absolute Difference Queries/1906.cpp new file mode 100644 index 00000000000..2c8b23f8193 --- /dev/null +++ b/solutions/1906. Minimum Absolute Difference Queries/1906.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector minDifference(vector& nums, vector>& queries) { + vector> numToIndices(101); + + for (int i = 0; i < nums.size(); ++i) + numToIndices[nums[i]].push_back(i); + + if (numToIndices[nums[0]].size() == nums.size()) + return vector(queries.size(), -1); + + vector ans; + + for (const vector& query : queries) { + const int l = query[0]; + const int r = query[1]; + int prevNum = -1; + int minDiff = 101; + for (int num = 1; num <= 100; ++num) { + const auto& indices = numToIndices[num]; + const auto it = ranges::lower_bound(indices, l); + if (it == indices.cend() || *it > r) + continue; + if (prevNum != -1) + minDiff = min(minDiff, num - prevNum); + prevNum = num; + } + ans.push_back(minDiff == 101 ? -1 : minDiff); + } + + return ans; + } +}; diff --git a/solutions/1906. Minimum Absolute Difference Queries/1906.java b/solutions/1906. Minimum Absolute Difference Queries/1906.java new file mode 100644 index 00000000000..716de6795c7 --- /dev/null +++ b/solutions/1906. Minimum Absolute Difference Queries/1906.java @@ -0,0 +1,41 @@ +class Solution { + public int[] minDifference(int[] nums, int[][] queries) { + int[] ans = new int[queries.length]; + List[] numToIndices = new List[101]; + + for (int i = 1; i <= 100; ++i) + numToIndices[i] = new ArrayList<>(); + + for (int i = 0; i < nums.length; ++i) + numToIndices[nums[i]].add(i); + + if (numToIndices[nums[0]].size() == nums.length) { + Arrays.fill(ans, -1); + return ans; + } + + for (int i = 0; i < queries.length; ++i) { + final int l = queries[i][0]; + final int r = queries[i][1]; + int prevNum = -1; + int minDiff = 101; + for (int num = 1; num <= 100; ++num) { + List indices = numToIndices[num]; + final int j = firstGreaterEqual(indices, l); + if (j == indices.size() || indices.get(j) > r) + continue; + if (prevNum != -1) + minDiff = Math.min(minDiff, num - prevNum); + prevNum = num; + } + ans[i] = minDiff == 101 ? -1 : minDiff; + } + + return ans; + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/1906. Minimum Absolute Difference Queries/1906.py b/solutions/1906. Minimum Absolute Difference Queries/1906.py new file mode 100644 index 00000000000..607cc814a26 --- /dev/null +++ b/solutions/1906. Minimum Absolute Difference Queries/1906.py @@ -0,0 +1,26 @@ +class Solution: + def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]: + numToIndices = [[] for _ in range(101)] + + for i, num in enumerate(nums): + numToIndices[num].append(i) + + if len(numToIndices[nums[0]]) == len(nums): + return [-1] * len(queries) + + ans = [] + + for l, r in queries: + prevNum = -1 + minDiff = 101 + for num in range(1, 101): + indices = numToIndices[num] + i = bisect_left(indices, l) + if i == len(indices) or indices[i] > r: + continue + if prevNum != -1: + minDiff = min(minDiff, num - prevNum) + prevNum = num + ans.append(-1 if minDiff == 101 else minDiff) + + return ans diff --git a/solutions/1907. Count Salary Categories/1907.sql b/solutions/1907. Count Salary Categories/1907.sql new file mode 100644 index 00000000000..e3649f98264 --- /dev/null +++ b/solutions/1907. Count Salary Categories/1907.sql @@ -0,0 +1,14 @@ +SELECT + 'Low Salary' AS Category, + SUM(income < 20000) AS accounts_count +FROM Accounts +UNION ALL +SELECT + 'Average Salary' Category, + SUM(income >= 20000 AND income <= 50000) AS accounts_count +FROM Accounts +UNION ALL +SELECT + 'High Salary' category, + SUM(income > 50000) AS accounts_count +FROM Accounts; diff --git a/solutions/1908. Game of Nim/1908.cpp b/solutions/1908. Game of Nim/1908.cpp new file mode 100644 index 00000000000..7f7233961ab --- /dev/null +++ b/solutions/1908. Game of Nim/1908.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool nimGame(vector& piles) { + return accumulate(piles.begin(), piles.end(), 0, bit_xor<>()) > 0; + } +}; diff --git a/solutions/1908. Game of Nim/1908.java b/solutions/1908. Game of Nim/1908.java new file mode 100644 index 00000000000..ce1a61bc336 --- /dev/null +++ b/solutions/1908. Game of Nim/1908.java @@ -0,0 +1,5 @@ +class Solution { + public boolean nimGame(int[] piles) { + return Arrays.stream(piles).reduce((a, b) -> a ^ b).getAsInt() > 0; + } +} diff --git a/solutions/1908. Game of Nim/1908.py b/solutions/1908. Game of Nim/1908.py new file mode 100644 index 00000000000..1238a8a1abc --- /dev/null +++ b/solutions/1908. Game of Nim/1908.py @@ -0,0 +1,3 @@ +class Solution: + def nimGame(self, piles: List[int]) -> bool: + return functools.reduce(operator.xor, piles) > 0 diff --git a/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.cpp b/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.cpp new file mode 100644 index 00000000000..1c88a462506 --- /dev/null +++ b/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool canBeIncreasing(vector& nums) { + bool removed = false; + + for (int i = 1; i < nums.size(); ++i) + if (nums[i - 1] >= nums[i]) { + if (removed) + return false; + removed = true; // Remove nums[i - 1]. + if (i > 1 && nums[i - 2] >= nums[i]) + nums[i] = nums[i - 1]; // Remove nums[i] instead. + } + + return true; + } +}; diff --git a/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.java b/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.java new file mode 100644 index 00000000000..33c1715441d --- /dev/null +++ b/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.java @@ -0,0 +1,16 @@ +class Solution { + public boolean canBeIncreasing(int[] nums) { + boolean removed = false; + + for (int i = 1; i < nums.length; ++i) + if (nums[i - 1] >= nums[i]) { + if (removed) + return false; + removed = true; // Remove nums[i - 1]. + if (i > 1 && nums[i - 2] >= nums[i]) + nums[i] = nums[i - 1]; // Remove nums[i] instead. + } + + return true; + } +} diff --git a/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.py b/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.py new file mode 100644 index 00000000000..81ed5fb69fd --- /dev/null +++ b/solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.py @@ -0,0 +1,13 @@ +class Solution: + def canBeIncreasing(self, nums: List[int]) -> bool: + removed = False + + for i in range(1, len(nums)): + if nums[i - 1] >= nums[i]: + if removed: + return False + removed = True # Remove nums[i - 1]. + if i > 1 and nums[i - 2] >= nums[i]: + nums[i] = nums[i - 1] # Remove nums[i] instead. + + return True diff --git a/solutions/191. Number of 1 Bits/191-2.cpp b/solutions/191. Number of 1 Bits/191-2.cpp new file mode 100644 index 00000000000..cbdcba7fc6c --- /dev/null +++ b/solutions/191. Number of 1 Bits/191-2.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int hammingWeight(uint32_t n) { + return popcount(n); + } +}; diff --git a/solutions/191. Number of 1 Bits/191-2.java b/solutions/191. Number of 1 Bits/191-2.java new file mode 100644 index 00000000000..1cfb63b20ce --- /dev/null +++ b/solutions/191. Number of 1 Bits/191-2.java @@ -0,0 +1,6 @@ +public class Solution { + // You need to treat n as an unsigned value + public int hammingWeight(int n) { + return Integer.bitCount(n); + } +} diff --git a/solutions/191. Number of 1 Bits/191-2.py b/solutions/191. Number of 1 Bits/191-2.py new file mode 100644 index 00000000000..0733135c1c1 --- /dev/null +++ b/solutions/191. Number of 1 Bits/191-2.py @@ -0,0 +1,3 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + return n.bit_count() diff --git a/solutions/191. Number of 1 Bits/191.cpp b/solutions/191. Number of 1 Bits/191.cpp new file mode 100644 index 00000000000..42d74483ba1 --- /dev/null +++ b/solutions/191. Number of 1 Bits/191.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int hammingWeight(uint32_t n) { + int ans = 0; + + for (int i = 0; i < 32; ++i) + if ((n >> i) & 1) + ++ans; + + return ans; + } +}; diff --git a/solutions/191. Number of 1 Bits/191.java b/solutions/191. Number of 1 Bits/191.java new file mode 100644 index 00000000000..05603a6bb0c --- /dev/null +++ b/solutions/191. Number of 1 Bits/191.java @@ -0,0 +1,12 @@ +public class Solution { + // You need to treat n as an unsigned value + public int hammingWeight(int n) { + int ans = 0; + + for (int i = 0; i < 32; ++i) + if (((n >> i) & 1) == 1) + ++ans; + + return ans; + } +} diff --git a/solutions/191. Number of 1 Bits/191.py b/solutions/191. Number of 1 Bits/191.py new file mode 100644 index 00000000000..9ac3654cc67 --- /dev/null +++ b/solutions/191. Number of 1 Bits/191.py @@ -0,0 +1,9 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + + for i in range(32): + if (n >> i) & 1: + ans += 1 + + return ans diff --git a/solutions/1910. Remove All Occurrences of a Substring/1910.cpp b/solutions/1910. Remove All Occurrences of a Substring/1910.cpp new file mode 100644 index 00000000000..c050e68c022 --- /dev/null +++ b/solutions/1910. Remove All Occurrences of a Substring/1910.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string removeOccurrences(string s, string part) { + const int n = s.length(); + const int k = part.length(); + + string t(n, ' '); + int j = 0; // t's index + + for (int i = 0; i < n; ++i) { + t[j++] = s[i]; + if (j >= k && t.substr(j - k, k) == part) + j -= k; + } + + return t.substr(0, j); + } +}; diff --git a/solutions/1910. Remove All Occurrences of a Substring/1910.java b/solutions/1910. Remove All Occurrences of a Substring/1910.java new file mode 100644 index 00000000000..8ae1179ba93 --- /dev/null +++ b/solutions/1910. Remove All Occurrences of a Substring/1910.java @@ -0,0 +1,17 @@ +class Solution { + public String removeOccurrences(String s, String part) { + final int n = s.length(); + final int k = part.length(); + + StringBuilder sb = new StringBuilder(s); + int j = 0; // sb's index + + for (int i = 0; i < n; ++i) { + sb.setCharAt(j++, s.charAt(i)); + if (j >= k && sb.substring(j - k, j).toString().equals(part)) + j -= k; + } + + return sb.substring(0, j).toString(); + } +} diff --git a/solutions/1910. Remove All Occurrences of a Substring/1910.py b/solutions/1910. Remove All Occurrences of a Substring/1910.py new file mode 100644 index 00000000000..91d12b70e66 --- /dev/null +++ b/solutions/1910. Remove All Occurrences of a Substring/1910.py @@ -0,0 +1,15 @@ +class Solution: + def removeOccurrences(self, s: str, part: str) -> str: + n = len(s) + k = len(part) + + t = [' '] * n + j = 0 # t's index + + for i, c in enumerate(s): + t[j] = c + j += 1 + if j >= k and ''.join(t[j - k:j]) == part: + j -= k + + return ''.join(t[:j]) diff --git a/solutions/1911. Maximum Alternating Subsequence Sum/1911.cpp b/solutions/1911. Maximum Alternating Subsequence Sum/1911.cpp new file mode 100644 index 00000000000..866ce503778 --- /dev/null +++ b/solutions/1911. Maximum Alternating Subsequence Sum/1911.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long maxAlternatingSum(vector& nums) { + long even = 0; // the maximum alternating sum ending in an even index + long odd = 0; // the maximum alternating sum ending in an odd index + + for (const int num : nums) { + even = max(even, odd + num); + odd = even - num; + } + + return even; + } +}; diff --git a/solutions/1911. Maximum Alternating Subsequence Sum/1911.java b/solutions/1911. Maximum Alternating Subsequence Sum/1911.java new file mode 100644 index 00000000000..0606d14e4ad --- /dev/null +++ b/solutions/1911. Maximum Alternating Subsequence Sum/1911.java @@ -0,0 +1,13 @@ +class Solution { + public long maxAlternatingSum(int[] nums) { + long even = 0; // the maximum alternating sum ending in an even index + long odd = 0; // the maximum alternating sum ending in an odd index + + for (final int num : nums) { + even = Math.max(even, odd + num); + odd = even - num; + } + + return even; + } +} diff --git a/solutions/1911. Maximum Alternating Subsequence Sum/1911.py b/solutions/1911. Maximum Alternating Subsequence Sum/1911.py new file mode 100644 index 00000000000..ed851a2ef1a --- /dev/null +++ b/solutions/1911. Maximum Alternating Subsequence Sum/1911.py @@ -0,0 +1,10 @@ +class Solution: + def maxAlternatingSum(self, nums: List[int]) -> int: + even = 0 # the maximum alternating sum ending in an even index + odd = 0 # the maximum alternating sum ending in an odd index + + for num in nums: + even = max(even, odd + num) + odd = even - num + + return even diff --git a/solutions/1912. Design Movie Rental System/1912.cpp b/solutions/1912. Design Movie Rental System/1912.cpp new file mode 100644 index 00000000000..e2502839b9a --- /dev/null +++ b/solutions/1912. Design Movie Rental System/1912.cpp @@ -0,0 +1,66 @@ +class MovieRentingSystem { + public: + MovieRentingSystem(int n, vector>& entries) { + for (const vector& e : entries) { + const int shop = e[0]; + const int movie = e[1]; + const int price = e[2]; + unrented[movie].insert({price, shop}); + shopAndMovieToPrice[{shop, movie}] = price; + } + } + + vector search(int movie) { + vector ans; + int i = 0; + + for (const auto& [price, shop] : unrented[movie]) { + ans.push_back(shop); + if (++i >= 5) + break; + } + + return ans; + } + + void rent(int shop, int movie) { + const int price = shopAndMovieToPrice[{shop, movie}]; + unrented[movie].erase({price, shop}); + rented.insert({price, {shop, movie}}); + } + + void drop(int shop, int movie) { + const int price = shopAndMovieToPrice[{shop, movie}]; + unrented[movie].insert({price, shop}); + rented.erase({price, {shop, movie}}); + } + + vector> report() { + vector> ans; + int i = 0; + + for (const auto& [_, shopAndMovie] : rented) { + ans.push_back({shopAndMovie.first, shopAndMovie.second}); + if (++i >= 5) + break; + } + + return ans; + } + + private: + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; + + // {movie: (price, shop)} + unordered_map>> unrented; + + // {(shop, movie): price} + unordered_map, int, PairHash> shopAndMovieToPrice; + + // (price, (shop, movie)) + set>> rented; +}; diff --git a/solutions/1912. Design Movie Rental System/1912.java b/solutions/1912. Design Movie Rental System/1912.java new file mode 100644 index 00000000000..da5c72d3841 --- /dev/null +++ b/solutions/1912. Design Movie Rental System/1912.java @@ -0,0 +1,65 @@ +class Entry { + public int price; + public int shop; + public int movie; + + public Entry(int price, int shop, int movie) { + this.price = price; + this.shop = shop; + this.movie = movie; + } +} + +class MovieRentingSystem { + public MovieRentingSystem(int n, int[][] entries) { + for (int[] e : entries) { + final int shop = e[0]; + final int movie = e[1]; + final int price = e[2]; + unrented.putIfAbsent(movie, new TreeSet<>(comparator)); + unrented.get(movie).add(new Entry(price, shop, movie)); + shopAndMovieToPrice.put(new Pair<>(shop, movie), price); + } + } + + public List search(int movie) { + return unrented.getOrDefault(movie, Collections.emptySet()) + .stream() + .limit(5) + .map(e -> e.shop) + .collect(Collectors.toList()); + } + + public void rent(int shop, int movie) { + final int price = shopAndMovieToPrice.get(new Pair<>(shop, movie)); + unrented.get(movie).remove(new Entry(price, shop, movie)); + rented.add(new Entry(price, shop, movie)); + } + + public void drop(int shop, int movie) { + final int price = shopAndMovieToPrice.get(new Pair<>(shop, movie)); + unrented.get(movie).add(new Entry(price, shop, movie)); + rented.remove(new Entry(price, shop, movie)); + } + + public List> report() { + return rented.stream().limit(5).map(e -> List.of(e.shop, e.movie)).collect(Collectors.toList()); + } + + private Comparator comparator = (a, b) -> { + if (a.price != b.price) + return Integer.compare(a.price, b.price); + if (a.shop != b.shop) + return Integer.compare(a.shop, b.shop); + return Integer.compare(a.movie, b.movie); + }; + + // {movie: (price, shop)} + private Map> unrented = new HashMap<>(); + + // {(shop, movie): price} + private Map, Integer> shopAndMovieToPrice = new HashMap<>(); + + // (price, shop, movie) + private Set rented = new TreeSet<>(comparator); +} diff --git a/solutions/1912. Design Movie Rental System/1912.py b/solutions/1912. Design Movie Rental System/1912.py new file mode 100644 index 00000000000..7fafb6efd96 --- /dev/null +++ b/solutions/1912. Design Movie Rental System/1912.py @@ -0,0 +1,28 @@ +from sortedcontainers import SortedList + + +class MovieRentingSystem: + def __init__(self, n: int, entries: List[List[int]]): + self.unrented = collections.defaultdict( + SortedList) # {movie: (price, shop)} + self.shopAndMovieToPrice = {} # {(shop, movie): price} + self.rented = SortedList() # (price, shop, movie) + for shop, movie, price in entries: + self.unrented[movie].add((price, shop)) + self.shopAndMovieToPrice[(shop, movie)] = price + + def search(self, movie: int) -> List[int]: + return [shop for _, shop in self.unrented[movie][:5]] + + def rent(self, shop: int, movie: int) -> None: + price = self.shopAndMovieToPrice[(shop, movie)] + self.unrented[movie].remove((price, shop)) + self.rented.add((price, shop, movie)) + + def drop(self, shop: int, movie: int) -> None: + price = self.shopAndMovieToPrice[(shop, movie)] + self.unrented[movie].add((price, shop)) + self.rented.remove((price, shop, movie)) + + def report(self) -> List[List[int]]: + return [[shop, movie] for _, shop, movie in self.rented[:5]] diff --git a/solutions/1913. Maximum Product Difference Between Two Pairs/1913.cpp b/solutions/1913. Maximum Product Difference Between Two Pairs/1913.cpp new file mode 100644 index 00000000000..e2b430478c3 --- /dev/null +++ b/solutions/1913. Maximum Product Difference Between Two Pairs/1913.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maxProductDifference(vector& nums) { + int max1 = INT_MIN; + int max2 = INT_MIN; + int min1 = INT_MAX; + int min2 = INT_MAX; + + for (const int num : nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + if (num < min1) { + min2 = min1; + min1 = num; + } else if (num < min2) { + min2 = num; + } + } + + return max1 * max2 - min1 * min2; + } +}; diff --git a/solutions/1913. Maximum Product Difference Between Two Pairs/1913.java b/solutions/1913. Maximum Product Difference Between Two Pairs/1913.java new file mode 100644 index 00000000000..50a2aa94fc9 --- /dev/null +++ b/solutions/1913. Maximum Product Difference Between Two Pairs/1913.java @@ -0,0 +1,25 @@ +class Solution { + public int maxProductDifference(int[] nums) { + int max1 = Integer.MIN_VALUE; + int max2 = Integer.MIN_VALUE; + int min1 = Integer.MAX_VALUE; + int min2 = Integer.MAX_VALUE; + + for (final int num : nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + if (num < min1) { + min2 = min1; + min1 = num; + } else if (num < min2) { + min2 = num; + } + } + + return max1 * max2 - min1 * min2; + } +} diff --git a/solutions/1913. Maximum Product Difference Between Two Pairs/1913.py b/solutions/1913. Maximum Product Difference Between Two Pairs/1913.py new file mode 100644 index 00000000000..95b10944b5d --- /dev/null +++ b/solutions/1913. Maximum Product Difference Between Two Pairs/1913.py @@ -0,0 +1,20 @@ +class Solution: + def maxProductDifference(self, nums: List[int]) -> int: + max1 = -math.inf + max2 = -math.inf + min1 = math.inf + min2 = math.inf + + for num in nums: + if num > max1: + max2 = max1 + max1 = num + elif num > max2: + max2 = num + if num < min1: + min2 = min1 + min1 = num + elif num < min2: + min2 = num + + return max1 * max2 - min1 * min2 diff --git a/solutions/1914. Cyclically Rotating a Grid/1914.cpp b/solutions/1914. Cyclically Rotating a Grid/1914.cpp new file mode 100644 index 00000000000..aa437a2e639 --- /dev/null +++ b/solutions/1914. Cyclically Rotating a Grid/1914.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + vector> rotateGrid(vector>& grid, int k) { + const int m = grid.size(); + const int n = grid[0].size(); + int t = 0; // the top + int l = 0; // the left + int b = m - 1; // the bottom + int r = n - 1; // the right + + while (t < b && l < r) { + const int elementInThisLayer = 2 * (b - t + 1) + 2 * (r - l + 1) - 4; + const int netRotations = k % elementInThisLayer; + for (int rotate = 0; rotate < netRotations; ++rotate) { + const int topLeft = grid[t][l]; + for (int j = l; j < r; ++j) + grid[t][j] = grid[t][j + 1]; + for (int i = t; i < b; ++i) + grid[i][r] = grid[i + 1][r]; + for (int j = r; j > l; --j) + grid[b][j] = grid[b][j - 1]; + for (int i = b; i > t; --i) + grid[i][l] = grid[i - 1][l]; + grid[t + 1][l] = topLeft; + } + ++t; + ++l; + --b; + --r; + } + + return grid; + } +}; diff --git a/solutions/1914. Cyclically Rotating a Grid/1914.java b/solutions/1914. Cyclically Rotating a Grid/1914.java new file mode 100644 index 00000000000..1e2e703499f --- /dev/null +++ b/solutions/1914. Cyclically Rotating a Grid/1914.java @@ -0,0 +1,33 @@ +class Solution { + public int[][] rotateGrid(int[][] grid, int k) { + final int m = grid.length; + final int n = grid[0].length; + int t = 0; // the top + int l = 0; // the left + int b = m - 1; // the bottom + int r = n - 1; // the right + + while (t < b && l < r) { + final int elementInThisLayer = 2 * (b - t + 1) + 2 * (r - l + 1) - 4; + final int netRotations = k % elementInThisLayer; + for (int rotate = 0; rotate < netRotations; ++rotate) { + final int topLeft = grid[t][l]; + for (int j = l; j < r; ++j) + grid[t][j] = grid[t][j + 1]; + for (int i = t; i < b; ++i) + grid[i][r] = grid[i + 1][r]; + for (int j = r; j > l; --j) + grid[b][j] = grid[b][j - 1]; + for (int i = b; i > t; --i) + grid[i][l] = grid[i - 1][l]; + grid[t + 1][l] = topLeft; + } + ++t; + ++l; + --b; + --r; + } + + return grid; + } +} diff --git a/solutions/1914. Cyclically Rotating a Grid/1914.py b/solutions/1914. Cyclically Rotating a Grid/1914.py new file mode 100644 index 00000000000..05f78b30fb8 --- /dev/null +++ b/solutions/1914. Cyclically Rotating a Grid/1914.py @@ -0,0 +1,29 @@ +class Solution: + def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m = len(grid) + n = len(grid[0]) + t = 0 # the top + l = 0 # the left + b = m - 1 # the bottom + r = n - 1 # the right + + while t < b and l < r: + elementInThisLayer = 2 * (b - t + 1) + 2 * (r - l + 1) - 4 + netRotations = k % elementInThisLayer + for _ in range(netRotations): + topLeft = grid[t][l] + for j in range(l, r): + grid[t][j] = grid[t][j + 1] + for i in range(t, b): + grid[i][r] = grid[i + 1][r] + for j in range(r, l, - 1): + grid[b][j] = grid[b][j - 1] + for i in range(b, t, -1): + grid[i][l] = grid[i - 1][l] + grid[t + 1][l] = topLeft + t += 1 + l += 1 + b -= 1 + r -= 1 + + return grid diff --git a/solutions/1915. Number of Wonderful Substrings/1915.cpp b/solutions/1915. Number of Wonderful Substrings/1915.cpp new file mode 100644 index 00000000000..02a8ed87b67 --- /dev/null +++ b/solutions/1915. Number of Wonderful Substrings/1915.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long wonderfulSubstrings(string word) { + long ans = 0; + int prefix = 0; // the binary prefix + vector count(1024); // the binary prefix count + count[0] = 1; // the empty string "" + + for (const char c : word) { + prefix ^= 1 << c - 'a'; + // All the letters occur even number of times. + ans += count[prefix]; + // ('a' + i) occurs odd number of times. + for (int i = 0; i < 10; ++i) + ans += count[prefix ^ 1 << i]; + ++count[prefix]; + } + + return ans; + } +}; diff --git a/solutions/1915. Number of Wonderful Substrings/1915.java b/solutions/1915. Number of Wonderful Substrings/1915.java new file mode 100644 index 00000000000..38c365c34fa --- /dev/null +++ b/solutions/1915. Number of Wonderful Substrings/1915.java @@ -0,0 +1,20 @@ +class Solution { + public long wonderfulSubstrings(String word) { + long ans = 0; + int prefix = 0; // the binary prefix + int[] count = new int[1024]; // the binary prefix count + count[0] = 1; // the empty string "" + + for (final char c : word.toCharArray()) { + prefix ^= 1 << c - 'a'; + // All the letters occur even number of times. + ans += count[prefix]; + // ('a' + i) occurs odd number of times. + for (int i = 0; i < 10; ++i) + ans += count[prefix ^ 1 << i]; + ++count[prefix]; + } + + return ans; + } +} diff --git a/solutions/1915. Number of Wonderful Substrings/1915.py b/solutions/1915. Number of Wonderful Substrings/1915.py new file mode 100644 index 00000000000..fdb3025f251 --- /dev/null +++ b/solutions/1915. Number of Wonderful Substrings/1915.py @@ -0,0 +1,16 @@ +class Solution: + def wonderfulSubstrings(self, word: str) -> int: + ans = 0 + prefix = 0 # the binary prefix + count = [0] * 1024 # the binary prefix count + count[0] = 1 # the empty string "" + + for c in word: + prefix ^= 1 << ord(c) - ord('a') + # All the letters occur even number of times. + ans += count[prefix] + # `c` occurs odd number of times. + ans += sum(count[prefix ^ 1 << i] for i in range(10)) + count[prefix] += 1 + + return ans diff --git a/solutions/1916. Count Ways to Build Rooms in an Ant Colony/1916.py b/solutions/1916. Count Ways to Build Rooms in an Ant Colony/1916.py new file mode 100644 index 00000000000..8075671eae3 --- /dev/null +++ b/solutions/1916. Count Ways to Build Rooms in an Ant Colony/1916.py @@ -0,0 +1,23 @@ +class Solution: + def waysToBuildRooms(self, prevRoom: List[int]) -> int: + kMod = 1_000_000_007 + graph = collections.defaultdict(list) + + for i, prev in enumerate(prevRoom): + graph[prev].append(i) + + def dfs(node: int) -> Tuple[int, int]: + if not graph[node]: + return 1, 1 + + ans = 1 + l = 0 + + for child in graph[node]: + temp, r = dfs(child) + ans = (ans * temp * math.comb(l + r, r)) % kMod + l += r + + return ans, l + 1 + + return dfs(0)[0] diff --git a/solutions/1917. Leetcodify Friends Recommendations/1917.sql b/solutions/1917. Leetcodify Friends Recommendations/1917.sql new file mode 100644 index 00000000000..5d928c2ac81 --- /dev/null +++ b/solutions/1917. Leetcodify Friends Recommendations/1917.sql @@ -0,0 +1,27 @@ +WITH + RecommendedUserPairs AS ( + SELECT + Listen1.user_id AS user1_id, + Listen2.user_id AS user2_id + FROM Listens AS Listen1 + INNER JOIN Listens AS Listen2 + USING (song_id, day) + WHERE + Listen1.user_id < Listen2.user_id + AND NOT EXISTS( + SELECT * FROM Friendship + WHERE + Listen1.user_id = Friendship.user1_id + AND Listen2.user_id = Friendship.user2_id) + GROUP BY Listen1.user_id, Listen2.user_id, Listen1.day + HAVING COUNT(DISTINCT Listen1.song_id) >= 3 + ) +SELECT + user1_id AS user_id, + user2_id AS recommended_id +FROM RecommendedUserPairs +UNION +SELECT + user2_id AS user_id, + user1_id AS recommended_id +FROM RecommendedUserPairs; diff --git a/solutions/1918. Kth Smallest Subarray Sum/1918.cpp b/solutions/1918. Kth Smallest Subarray Sum/1918.cpp new file mode 100644 index 00000000000..9aa9932047b --- /dev/null +++ b/solutions/1918. Kth Smallest Subarray Sum/1918.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int kthSmallestSubarraySum(vector& nums, int k) { + int l = 0; + int r = accumulate(nums.begin(), nums.end(), 0); + + while (l < r) { + const int m = (l + r) / 2; + if (numSubarrayLessThan(nums, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int numSubarrayLessThan(const vector& nums, int m) { + int res = 0; + int sum = 0; + for (int l = 0, r = 0; r < nums.size(); ++r) { + sum += nums[r]; + while (sum > m) + sum -= nums[l++]; + res += r - l + 1; + } + return res; + } +}; diff --git a/solutions/1918. Kth Smallest Subarray Sum/1918.java b/solutions/1918. Kth Smallest Subarray Sum/1918.java new file mode 100644 index 00000000000..4d94c1c29c7 --- /dev/null +++ b/solutions/1918. Kth Smallest Subarray Sum/1918.java @@ -0,0 +1,28 @@ +class Solution { + public int kthSmallestSubarraySum(int[] nums, int k) { + int l = 0; + int r = Arrays.stream(nums).sum(); + + while (l < r) { + final int m = (l + r) / 2; + if (numSubarrayLessThan(nums, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private int numSubarrayLessThan(int[] nums, int m) { + int res = 0; + int sum = 0; + for (int l = 0, r = 0; r < nums.length; ++r) { + sum += nums[r]; + while (sum > m) + sum -= nums[l++]; + res += r - l + 1; + } + return res; + } +} diff --git a/solutions/1918. Kth Smallest Subarray Sum/1918.py b/solutions/1918. Kth Smallest Subarray Sum/1918.py new file mode 100644 index 00000000000..59f196fa668 --- /dev/null +++ b/solutions/1918. Kth Smallest Subarray Sum/1918.py @@ -0,0 +1,16 @@ +class Solution: + def kthSmallestSubarraySum(self, nums: List[int], k: int) -> int: + def numSubarrayLessThan(m: int) -> int: + res = 0 + summ = 0 + l = 0 + for r, num in enumerate(nums): + summ += num + while summ > m: + summ -= nums[l] + l += 1 + res += r - l + 1 + return res + + return bisect.bisect_left(range(0, sum(nums)), k, + key=lambda m: numSubarrayLessThan(m)) diff --git a/solutions/1919. Leetcodify Similar Friends/1919.sql b/solutions/1919. Leetcodify Similar Friends/1919.sql new file mode 100644 index 00000000000..0620582c98a --- /dev/null +++ b/solutions/1919. Leetcodify Similar Friends/1919.sql @@ -0,0 +1,15 @@ +SELECT DISTINCT + Listen1.user_id AS user1_id, + Listen2.user_id AS user2_id +FROM Listens AS Listen1 +INNER JOIN Listens AS Listen2 + USING (song_id, day) +WHERE + Listen1.user_id < Listen2.user_id + AND EXISTS( + SELECT * FROM Friendship + WHERE + Listen1.user_id = Friendship.user1_id + AND Listen2.user_id = Friendship.user2_id) +GROUP BY Listen1.user_id, Listen2.user_id, Listen1.day +HAVING COUNT(DISTINCT Listen1.song_id) >= 3 diff --git a/solutions/192. Word Frequency/192.sh b/solutions/192. Word Frequency/192.sh new file mode 100644 index 00000000000..77aa7962faa --- /dev/null +++ b/solutions/192. Word Frequency/192.sh @@ -0,0 +1 @@ +cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{ print $2, $1 }' diff --git a/solutions/1920. Build Array from Permutation/1920.cpp b/solutions/1920. Build Array from Permutation/1920.cpp new file mode 100644 index 00000000000..24cad4578f8 --- /dev/null +++ b/solutions/1920. Build Array from Permutation/1920.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector buildArray(vector& nums) { + const int n = nums.size(); + + for (int i = 0; i < n; ++i) + nums[i] += n * (nums[nums[i]] % n); + + for (int i = 0; i < n; ++i) + nums[i] /= n; + + return nums; + } +}; diff --git a/solutions/1920. Build Array from Permutation/1920.java b/solutions/1920. Build Array from Permutation/1920.java new file mode 100644 index 00000000000..5eb6a830383 --- /dev/null +++ b/solutions/1920. Build Array from Permutation/1920.java @@ -0,0 +1,13 @@ +class Solution { + public int[] buildArray(int[] nums) { + final int n = nums.length; + + for (int i = 0; i < n; ++i) + nums[i] += n * (nums[nums[i]] % n); + + for (int i = 0; i < n; ++i) + nums[i] /= n; + + return nums; + } +} diff --git a/solutions/1920. Build Array from Permutation/1920.py b/solutions/1920. Build Array from Permutation/1920.py new file mode 100644 index 00000000000..1ca2334e93a --- /dev/null +++ b/solutions/1920. Build Array from Permutation/1920.py @@ -0,0 +1,11 @@ +class Solution: + def buildArray(self, nums: List[int]) -> List[int]: + n = len(nums) + + for i, num in enumerate(nums): + nums[i] += n * (nums[num] % n) + + for i in range(n): + nums[i] //= n + + return nums diff --git a/solutions/1921. Eliminate Maximum Number of Monsters/1921.cpp b/solutions/1921. Eliminate Maximum Number of Monsters/1921.cpp new file mode 100644 index 00000000000..2b94319c06c --- /dev/null +++ b/solutions/1921. Eliminate Maximum Number of Monsters/1921.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int eliminateMaximum(vector& dist, vector& speed) { + const int n = dist.size(); + vector arrivalTime(n); + + for (int i = 0; i < n; ++i) + arrivalTime[i] = (dist[i] - 1) / speed[i]; + + ranges::sort(arrivalTime); + + for (int i = 0; i < n; ++i) + if (i > arrivalTime[i]) + return i; + + return n; + } +}; diff --git a/solutions/1921. Eliminate Maximum Number of Monsters/1921.java b/solutions/1921. Eliminate Maximum Number of Monsters/1921.java new file mode 100644 index 00000000000..3b98f57a2aa --- /dev/null +++ b/solutions/1921. Eliminate Maximum Number of Monsters/1921.java @@ -0,0 +1,17 @@ +class Solution { + public int eliminateMaximum(int[] dist, int[] speed) { + final int n = dist.length; + int[] arrivalTime = new int[n]; + + for (int i = 0; i < n; ++i) + arrivalTime[i] = (dist[i] - 1) / speed[i]; + + Arrays.sort(arrivalTime); + + for (int i = 0; i < n; ++i) + if (i > arrivalTime[i]) + return i; + + return n; + } +} diff --git a/solutions/1921. Eliminate Maximum Number of Monsters/1921.py b/solutions/1921. Eliminate Maximum Number of Monsters/1921.py new file mode 100644 index 00000000000..39d19c65899 --- /dev/null +++ b/solutions/1921. Eliminate Maximum Number of Monsters/1921.py @@ -0,0 +1,6 @@ +class Solution: + def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: + for i, arrivalTime in enumerate(sorted([(d - 1) // s for d, s in zip(dist, speed)])): + if i > arrivalTime: + return i + return len(dist) diff --git a/solutions/1922. Count Good Numbers/1922.cpp b/solutions/1922. Count Good Numbers/1922.cpp new file mode 100644 index 00000000000..13f6cdaa7ab --- /dev/null +++ b/solutions/1922. Count Good Numbers/1922.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countGoodNumbers(long long n) { + return modPow(4 * 5, n / 2) * (n % 2 == 0 ? 1 : 5) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } +}; diff --git a/solutions/1922. Count Good Numbers/1922.java b/solutions/1922. Count Good Numbers/1922.java new file mode 100644 index 00000000000..c7bbf3f31fb --- /dev/null +++ b/solutions/1922. Count Good Numbers/1922.java @@ -0,0 +1,15 @@ +class Solution { + public int countGoodNumbers(long n) { + return (int) (modPow(4 * 5, n / 2) * (n % 2 == 0 ? 1 : 5) % kMod); + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } +} diff --git a/solutions/1922. Count Good Numbers/1922.py b/solutions/1922. Count Good Numbers/1922.py new file mode 100644 index 00000000000..a0b2aeb34c0 --- /dev/null +++ b/solutions/1922. Count Good Numbers/1922.py @@ -0,0 +1,12 @@ +class Solution: + def countGoodNumbers(self, n: int) -> int: + kMod = 1_000_000_007 + + def modPow(x: int, n: int) -> int: + if n == 0: + return 1 + if n % 2 == 1: + return x * modPow(x, n - 1) % kMod + return modPow(x * x % kMod, n // 2) + + return modPow(4 * 5, n // 2) * (1 if n % 2 == 0 else 5) % kMod diff --git a/solutions/1923. Longest Common Subpath/1923.cpp b/solutions/1923. Longest Common Subpath/1923.cpp new file mode 100644 index 00000000000..cb43c88ad48 --- /dev/null +++ b/solutions/1923. Longest Common Subpath/1923.cpp @@ -0,0 +1,56 @@ +class Solution { + public: + int longestCommonSubpath(int n, vector>& paths) { + int l = 0; + int r = paths[0].size(); + + while (l < r) { + const int m = l + (r - l + 1) / 2; + if (checkCommonSubpath(paths, m)) + l = m; + else + r = m - 1; + } + + return l; + } + + static constexpr long kMod = 8'417'508'174'513; + static constexpr long kBase = 165'131; + + // Returns true if there's a common subpath of length m for all the paths. + bool checkCommonSubpath(const vector>& paths, int m) { + vector> hashSets; + + // Calculate the hash values for subpaths of length m for every path. + for (const vector& path : paths) + hashSets.push_back(rabinKarp(path, m)); + + // Check if there is a common subpath of length m. + for (const long subpathHash : hashSets[0]) + if (ranges::all_of(hashSets, + [subpathHash](const unordered_set& hashSet) { + return hashSet.contains(subpathHash); + })) + return true; + + return false; + } + + // Returns the hash values for subpaths of length m in the path. + unordered_set rabinKarp(const vector& path, int m) { + unordered_set hashes; + long maxPower = 1; + long hash = 0; + for (int i = 0; i < path.size(); ++i) { + hash = (hash * kBase + path[i]) % kMod; + if (i >= m) + hash = (hash - path[i - m] * maxPower % kMod + kMod) % kMod; + else + maxPower = maxPower * kBase % kMod; + if (i >= m - 1) + hashes.insert(hash); + } + return hashes; + } +}; diff --git a/solutions/1923. Longest Common Subpath/1923.java b/solutions/1923. Longest Common Subpath/1923.java new file mode 100644 index 00000000000..ff25a6cd7ac --- /dev/null +++ b/solutions/1923. Longest Common Subpath/1923.java @@ -0,0 +1,52 @@ +class Solution { + public int longestCommonSubpath(int n, int[][] paths) { + int l = 0; + int r = paths[0].length; + + while (l < r) { + final int m = l + (r - l + 1) / 2; + if (checkCommonSubpath(paths, m)) + l = m; + else + r = m - 1; + } + + return l; + } + + private static final long kMod = 8_417_508_174_513L; + private static final long kBase = 165_131L; + + // Returns true if there's a common subpath of length m for all the paths. + private boolean checkCommonSubpath(int[][] paths, int m) { + Set[] hashSets = new Set[paths.length]; + + // Calculate the hash values for subpaths of length m for every path. + for (int i = 0; i < paths.length; ++i) + hashSets[i] = rabinKarp(paths[i], m); + + // Check if there is a common subpath of length m. + for (final long subpathHash : hashSets[0]) + if (Arrays.stream(hashSets).allMatch(hashSet -> hashSet.contains(subpathHash))) + return true; + + return false; + } + + // Returns the hash values for subpaths of length m in the path. + private Set rabinKarp(int[] path, int m) { + Set hashes = new HashSet<>(); + long maxPower = 1; + long hash = 0; + for (int i = 0; i < path.length; ++i) { + hash = (hash * kBase + path[i]) % kMod; + if (i >= m) + hash = (hash - path[i - m] * maxPower % kMod + kMod) % kMod; + else + maxPower = maxPower * kBase % kMod; + if (i >= m - 1) + hashes.add(hash); + } + return hashes; + } +} diff --git a/solutions/1923. Longest Common Subpath/1923.py b/solutions/1923. Longest Common Subpath/1923.py new file mode 100644 index 00000000000..5e1d14f1ed9 --- /dev/null +++ b/solutions/1923. Longest Common Subpath/1923.py @@ -0,0 +1,49 @@ +class Solution: + def __init__(self): + self.kMod = 8_417_508_174_513 + self.kBase = 165_131 + + def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int: + l = 0 + r = len(paths[0]) + + while l < r: + m = l + (r - l + 1) // 2 + if self._checkCommonSubpath(paths, m): + l = m + else: + r = m - 1 + + return l + + def _checkCommonSubpath(self, paths: List[List[int]], m: int) -> bool: + """ + Returns True if there's a common subpath of length m for all the paths. + """ + # Calculate the hash values for subpaths of length m for every path. + hashSets = [self._rabinKarp(path, m) for path in paths] + + # Check if there is a common subpath of length m. + for subpathHash in hashSets[0]: + if all(subpathHash in hashSet for hashSet in hashSets): + return True + + return False + + def _rabinKarp(self, path: List[int], m: int) -> Set[int]: + """Returns the hash values for subpaths of length m in the path.""" + hashes = set() + maxPower = 1 + hash = 0 + + for i, num in enumerate(path): + hash = (hash * self.kBase + num) % self.kMod + if i >= m: + hash = (hash - path[i - m] * maxPower % + self.kMod + self.kMod) % self.kMod + else: + maxPower = maxPower * self.kBase % self.kMod + if i >= m - 1: + hashes.add(hash) + + return hashes diff --git a/solutions/1924. Erect the Fence II/1924.cpp b/solutions/1924. Erect the Fence II/1924.cpp new file mode 100644 index 00000000000..3d7e0672a39 --- /dev/null +++ b/solutions/1924. Erect the Fence II/1924.cpp @@ -0,0 +1,103 @@ +struct Point { + double x; + double y; + Point(double x, double y) : x(x), y(y) {} +}; + +struct Disk { + Point center; + double radius; + Disk(const Point& center, double radius) : center(center), radius(radius) {} +}; + +class Solution { + public: + vector outerTrees(vector>& trees) { + vector points; + for (int i = 0; i < trees.size(); ++i) + points.emplace_back(trees[i][0], trees[i][1]); + Disk disk = welzl(points, 0, {}); + return {disk.center.x, disk.center.y, disk.radius}; + } + + private: + // Returns the smallest disk that encloses points[i..n). + // https://en.wikipedia.org/wiki/Smallest-disk_problem#Welzl's_algorithm + Disk welzl(const vector& points, int i, vector planePoints) { + if (i == points.size() || planePoints.size() == 3) + return trivial(planePoints); + Disk disk = welzl(points, i + 1, planePoints); + if (inside(disk, points[i])) + return disk; + return welzl(points, i + 1, addPlanePoint(planePoints, points[i])); + } + + vector addPlanePoint(const vector& planePoints, + const Point& point) { + vector newPlanePoints(planePoints); + newPlanePoints.push_back(point); + return newPlanePoints; + } + // Returns the smallest disk that encloses `planePoints`. + Disk trivial(const vector& planePoints) { + if (planePoints.empty()) + return Disk(Point(0, 0), 0); + if (planePoints.size() == 1) + return Disk(Point(planePoints[0].x, planePoints[0].y), 0); + if (planePoints.size() == 2) + return getDisk(planePoints[0], planePoints[1]); + + Disk disk01 = getDisk(planePoints[0], planePoints[1]); + if (inside(disk01, planePoints[2])) + return disk01; + + Disk disk02 = getDisk(planePoints[0], planePoints[2]); + if (inside(disk02, planePoints[1])) + return disk02; + + Disk disk12 = getDisk(planePoints[1], planePoints[2]); + if (inside(disk12, planePoints[0])) + return disk12; + + return getDisk(planePoints[0], planePoints[1], planePoints[2]); + } + + // Returns the smallest disk that encloses the points A and B. + Disk getDisk(const Point& A, const Point& B) { + const double x = (A.x + B.x) / 2; + const double y = (A.y + B.y) / 2; + return Disk(Point(x, y), distance(A, B) / 2); + } + + // Returns the smallest disk that encloses the points A, B, and C. + Disk getDisk(const Point& A, const Point& B, const Point& C) { + // Calculate midpoints. + Point mAB((A.x + B.x) / 2, (A.y + B.y) / 2); + Point mBC((B.x + C.x) / 2, (B.y + C.y) / 2); + + // Calculate the slopes and the perpendicular slopes. + const double slopeAB = (B.y - A.y) / (B.x - A.x); + const double slopeBC = (C.y - B.y) / (C.x - B.x); + const double perpSlopeAB = -1 / slopeAB; + const double perpSlopeBC = -1 / slopeBC; + + // Calculate the center. + const double x = + (perpSlopeBC * mBC.x - perpSlopeAB * mAB.x + mAB.y - mBC.y) / + (perpSlopeBC - perpSlopeAB); + const double y = perpSlopeAB * (x - mAB.x) + mAB.y; + Point center(x, y); + return Disk(center, distance(center, A)); + } + + // Returns true if the point is inside the disk. + bool inside(Disk disk, Point point) { + return disk.radius > 0 && distance(disk.center, point) <= disk.radius; + } + + double distance(Point A, Point B) { + const double dx = A.x - B.x; + const double dy = A.y - B.y; + return sqrt(dx * dx + dy * dy); + } +}; diff --git a/solutions/1924. Erect the Fence II/1924.java b/solutions/1924. Erect the Fence II/1924.java new file mode 100644 index 00000000000..9636c5d5931 --- /dev/null +++ b/solutions/1924. Erect the Fence II/1924.java @@ -0,0 +1,106 @@ +class Point { + public double x; + public double y; + public Point(double x, double y) { + this.x = x; + this.y = y; + } +} + +class Disk { + public Point center; + public double radius; + public Disk(Point center, double radius) { + this.center = center; + this.radius = radius; + } +} + +class Solution { + public double[] outerTrees(int[][] trees) { + Point[] points = new Point[trees.length]; + for (int i = 0; i < trees.length; ++i) + points[i] = new Point(trees[i][0], trees[i][1]); + Disk disk = welzl(points, 0, new ArrayList<>()); + return new double[] {disk.center.x, disk.center.y, disk.radius}; + } + + // Returns the smallest disk that encloses points[i..n). + // https://en.wikipedia.org/wiki/Smallest-disk_problem#Welzl's_algorithm + private Disk welzl(Point[] points, int i, List planePoints) { + if (i == points.length || planePoints.size() == 3) + return trivial(planePoints); + Disk disk = welzl(points, i + 1, planePoints); + if (inside(disk, points[i])) + return disk; + return welzl(points, i + 1, addPlanePoints(planePoints, points[i])); + } + + private List addPlanePoints(List planePoints, Point point) { + List newPlanePoints = new ArrayList<>(planePoints); + newPlanePoints.add(point); + return newPlanePoints; + } + + // Returns the smallest disk that encloses `planePoints`. + private Disk trivial(List planePoints) { + if (planePoints.isEmpty()) + return null; + if (planePoints.size() == 1) + return new Disk(new Point(planePoints.get(0).x, planePoints.get(0).y), 0); + if (planePoints.size() == 2) + return getDisk(planePoints.get(0), planePoints.get(1)); + + Disk disk01 = getDisk(planePoints.get(0), planePoints.get(1)); + if (inside(disk01, planePoints.get(2))) + return disk01; + + Disk disk02 = getDisk(planePoints.get(0), planePoints.get(2)); + if (inside(disk02, planePoints.get(1))) + return disk02; + + Disk disk12 = getDisk(planePoints.get(1), planePoints.get(2)); + if (inside(disk12, planePoints.get(0))) + return disk12; + + return getDisk(planePoints.get(0), planePoints.get(1), planePoints.get(2)); + } + + // Returns the smallest disk that encloses the points A and B. + private Disk getDisk(Point A, Point B) { + final double x = (A.x + B.x) / 2; + final double y = (A.y + B.y) / 2; + return new Disk(new Point(x, y), distance(A, B) / 2); + } + + // Returns the smallest disk that encloses the points A, B, and C. + private Disk getDisk(Point A, Point B, Point C) { + // Calculate midpoints. + Point mAB = new Point((A.x + B.x) / 2, (A.y + B.y) / 2); + Point mBC = new Point((B.x + C.x) / 2, (B.y + C.y) / 2); + + // Calculate the slopes and the perpendicular slopes. + final double slopeAB = (B.y - A.y) / (B.x - A.x); + final double slopeBC = (C.y - B.y) / (C.x - B.x); + final double perpSlopeAB = -1 / slopeAB; + final double perpSlopeBC = -1 / slopeBC; + + // Calculate the center. + final double x = + (perpSlopeBC * mBC.x - perpSlopeAB * mAB.x + mAB.y - mBC.y) / (perpSlopeBC - perpSlopeAB); + final double y = perpSlopeAB * (x - mAB.x) + mAB.y; + Point center = new Point(x, y); + return new Disk(center, distance(center, A)); + } + + // Returns true if the point is inside the disk. + private boolean inside(Disk disk, Point point) { + return disk != null && distance(disk.center, point) <= disk.radius; + } + + private double distance(Point A, Point B) { + final double dx = A.x - B.x; + final double dy = A.y - B.y; + return Math.sqrt(dx * dx + dy * dy); + } +} diff --git a/solutions/1924. Erect the Fence II/1924.py b/solutions/1924. Erect the Fence II/1924.py new file mode 100644 index 00000000000..a971920b32d --- /dev/null +++ b/solutions/1924. Erect the Fence II/1924.py @@ -0,0 +1,89 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Point: + x: float + y: float + + +@dataclass(frozen=True) +class Disk: + center: Point + radius: float + + +class Solution: + def outerTrees(self, trees: List[List[int]]) -> List[float]: + points = [Point(x, y) for x, y in trees] + disk = self._welzl(points, 0, []) + return [disk.center.x, disk.center.y, disk.radius] + + def _welzl(self, points: List[Point], i: int, planePoints: List[Point]) -> Disk: + """Returns the smallest disk that encloses points[i..n). + + https://en.wikipedia.org/wiki/Smallest-disk_problem#Welzl's_algorithm + """ + if i == len(points) or len(planePoints) == 3: + return self._trivial(planePoints) + disk = self._welzl(points, i + 1, planePoints) + if self._inside(disk, points[i]): + return disk + return self._welzl(points, i + 1, planePoints + [points[i]]) + + def _trivial(self, planePoints: List[Point]) -> Disk: + """Returns the smallest disk that encloses `planePoints`.""" + if len(planePoints) == 0: + return Disk(Point(0, 0), 0) + if len(planePoints) == 1: + return Disk(Point(planePoints[0].x, planePoints[0].y), 0) + if len(planePoints) == 2: + return self._getDisk(planePoints[0], planePoints[1]) + + disk01 = self._getDisk(planePoints[0], planePoints[1]) + if self._inside(disk01, planePoints[2]): + return disk01 + + disk02 = self._getDisk(planePoints[0], planePoints[2]) + if self._inside(disk02, planePoints[1]): + return disk02 + + disk12 = self._getDisk(planePoints[1], planePoints[2]) + if self._inside(disk12, planePoints[0]): + return disk12 + + return self._getDiskFromThree(planePoints[0], planePoints[1], planePoints[2]) + + def _getDisk(self, A: Point, B: Point) -> Disk: + """Returns the smallest disk that encloses the points A and B.""" + x = (A.x + B.x) / 2 + y = (A.y + B.y) / 2 + return Disk(Point(x, y), self._distance(A, B) / 2) + + def _getDiskFromThree(self, A: Point, B: Point, C: Point) -> Disk: + """Returns the smallest disk that encloses the points A, B, and C.""" + # Calculate midpoints. + mAB = Point((A.x + B.x) / 2, (A.y + B.y) / 2) + mBC = Point((B.x + C.x) / 2, (B.y + C.y) / 2) + + # Calculate the slopes and the perpendicular slopes. + slopeAB = math.inf if B.x == A.x else (B.y - A.y) / (B.x - A.x) + slopeBC = math.inf if C.x == B.x else (C.y - B.y) / (C.x - B.x) + perpSlopeAB = math.inf if slopeAB == 0 else -1 / slopeAB + perpSlopeBC = math.inf if slopeBC == 0 else -1 / slopeBC + + # Calculate the center. + x = (perpSlopeBC * mBC.x - perpSlopeAB * mAB.x + + mAB.y - mBC.y) / (perpSlopeBC - perpSlopeAB) + y = perpSlopeAB * (x - mAB.x) + mAB.y + center = Point(x, y) + return Disk(center, self._distance(center, A)) + + def _inside(self, disk: Disk, point: Point) -> bool: + """Returns True if the point is inside the disk.""" + return disk.radius > 0 and self._distance(disk.center, point) <= disk.radius + + def _distance(self, A: Point, B: Point) -> float: + dx = A.x - B.x + dy = A.y - B.y + return math.sqrt(dx**2 + dy**2) diff --git a/solutions/1925. Count Square Sum Triples/1925.cpp b/solutions/1925. Count Square Sum Triples/1925.cpp new file mode 100644 index 00000000000..ce8fec4e2bc --- /dev/null +++ b/solutions/1925. Count Square Sum Triples/1925.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countTriples(int n) { + int ans = 0; + unordered_set squared; + + for (int i = 1; i <= n; ++i) + squared.insert(i * i); + + for (const int a : squared) + for (const int b : squared) + if (squared.contains(a + b)) + ++ans; + + return ans; + } +}; diff --git a/solutions/1925. Count Square Sum Triples/1925.java b/solutions/1925. Count Square Sum Triples/1925.java new file mode 100644 index 00000000000..09f6dad6aca --- /dev/null +++ b/solutions/1925. Count Square Sum Triples/1925.java @@ -0,0 +1,16 @@ +class Solution { + public int countTriples(int n) { + int ans = 0; + Set squared = new HashSet<>(); + + for (int i = 1; i <= n; ++i) + squared.add(i * i); + + for (final int a : squared) + for (final int b : squared) + if (squared.contains(a + b)) + ++ans; + + return ans; + } +} diff --git a/solutions/1925. Count Square Sum Triples/1925.py b/solutions/1925. Count Square Sum Triples/1925.py new file mode 100644 index 00000000000..b841ed6f16a --- /dev/null +++ b/solutions/1925. Count Square Sum Triples/1925.py @@ -0,0 +1,14 @@ +class Solution: + def countTriples(self, n: int) -> int: + ans = 0 + squared = set() + + for i in range(1, n + 1): + squared.add(i * i) + + for a in squared: + for b in squared: + if a + b in squared: + ans += 1 + + return ans diff --git a/solutions/1926. Nearest Exit from Entrance in Maze/1926.cpp b/solutions/1926. Nearest Exit from Entrance in Maze/1926.cpp new file mode 100644 index 00000000000..335cd309049 --- /dev/null +++ b/solutions/1926. Nearest Exit from Entrance in Maze/1926.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int nearestExit(vector>& maze, vector& entrance) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = maze.size(); + const int n = maze[0].size(); + int ans = 0; + queue> q{{{entrance[0], entrance[1]}}}; + vector> seen(m, vector(n)); + seen[entrance[0]][entrance[1]] = true; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y] || maze[x][y] == '+') + continue; + if (x == 0 || x == m - 1 || y == 0 || y == n - 1) + return ans; + q.emplace(x, y); + seen[x][y] = true; + } + } + } + + return -1; + } +}; diff --git a/solutions/1926. Nearest Exit from Entrance in Maze/1926.java b/solutions/1926. Nearest Exit from Entrance in Maze/1926.java new file mode 100644 index 00000000000..b872f6dc2ff --- /dev/null +++ b/solutions/1926. Nearest Exit from Entrance in Maze/1926.java @@ -0,0 +1,33 @@ +class Solution { + public int nearestExit(char[][] maze, int[] entrance) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = maze.length; + final int n = maze[0].length; + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {entrance[0], entrance[1]})); + boolean[][] seen = new boolean[m][n]; + seen[entrance[0]][entrance[1]] = true; + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y] || maze[x][y] == '+') + continue; + if (x == 0 || x == m - 1 || y == 0 || y == n - 1) + return ans; + q.offer(new int[] {x, y}); + seen[x][y] = true; + } + } + } + + return -1; + } +} diff --git a/solutions/1926. Nearest Exit from Entrance in Maze/1926.py b/solutions/1926. Nearest Exit from Entrance in Maze/1926.py new file mode 100644 index 00000000000..4d4485400f2 --- /dev/null +++ b/solutions/1926. Nearest Exit from Entrance in Maze/1926.py @@ -0,0 +1,26 @@ +class Solution: + def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(maze) + n = len(maze[0]) + ans = 0 + q = collections.deque([(entrance[0], entrance[1])]) + seen = {(entrance[0], entrance[1])} + + while q: + ans += 1 + for _ in range(len(q)): + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if (x, y) in seen or maze[x][y] == '+': + continue + if x == 0 or x == m - 1 or y == 0 or y == n - 1: + return ans + q.append((x, y)) + seen.add((x, y)) + + return -1 diff --git a/solutions/1927. Sum Game/1927.cpp b/solutions/1927. Sum Game/1927.cpp new file mode 100644 index 00000000000..e875eafb015 --- /dev/null +++ b/solutions/1927. Sum Game/1927.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool sumGame(string num) { + const int n = num.length(); + double ans = 0.0; + + for (int i = 0; i < n / 2; ++i) + ans += getExpectation(num[i]); + + for (int i = n / 2; i < n; ++i) + ans -= getExpectation(num[i]); + + return ans != 0.0; + } + + private: + double getExpectation(char c) { + return c == '?' ? 4.5 : c - '0'; + } +}; diff --git a/solutions/1927. Sum Game/1927.java b/solutions/1927. Sum Game/1927.java new file mode 100644 index 00000000000..fbb0ca80401 --- /dev/null +++ b/solutions/1927. Sum Game/1927.java @@ -0,0 +1,18 @@ +class Solution { + public boolean sumGame(String num) { + final int n = num.length(); + double ans = 0.0; + + for (int i = 0; i < n / 2; ++i) + ans += getExpectation(num.charAt(i)); + + for (int i = n / 2; i < n; ++i) + ans -= getExpectation(num.charAt(i)); + + return ans != 0.0; + } + + private double getExpectation(char c) { + return c == '?' ? 4.5 : c - '0'; + } +} diff --git a/solutions/1927. Sum Game/1927.py b/solutions/1927. Sum Game/1927.py new file mode 100644 index 00000000000..ac427b72ea0 --- /dev/null +++ b/solutions/1927. Sum Game/1927.py @@ -0,0 +1,15 @@ +class Solution: + def sumGame(self, num: str) -> bool: + n = len(num) + ans = 0.0 + + def getExpectation(c: str) -> float: + return 4.5 if c == '?' else ord(c) - ord('0') + + for i in range(n // 2): + ans += getExpectation(num[i]) + + for i in range(n // 2, n): + ans -= getExpectation(num[i]) + + return ans != 0.0 diff --git a/solutions/1928. Minimum Cost to Reach Destination in Time/1928.cpp b/solutions/1928. Minimum Cost to Reach Destination in Time/1928.cpp new file mode 100644 index 00000000000..dc18f42478a --- /dev/null +++ b/solutions/1928. Minimum Cost to Reach Destination in Time/1928.cpp @@ -0,0 +1,57 @@ +class Solution { + public: + int minCost(int maxTime, vector>& edges, + vector& passingFees) { + const int n = passingFees.size(); + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + return dijkstra(graph, 0, n - 1, maxTime, passingFees); + } + + private: + int dijkstra(const vector>>& graph, int src, int dst, + int maxTime, const vector& passingFees) { + // cost[i] := the minimum cost to reach the i-th city + vector cost(graph.size(), INT_MAX); + // dist[i] := the minimum time to reach the i-th city + vector dist(graph.size(), maxTime + 1); + using T = tuple; // (cost[u], dist[u], u) + priority_queue, greater<>> minHeap; + + cost[src] = passingFees[src]; + dist[src] = 0; + minHeap.emplace(cost[src], dist[src], src); + + while (!minHeap.empty()) { + const auto [currCost, d, u] = minHeap.top(); + minHeap.pop(); + if (u == dst) + return cost[dst]; + if (d > dist[u] && currCost > cost[u]) + continue; + for (const auto& [v, w] : graph[u]) { + if (d + w > maxTime) + continue; + // Go from u -> v. + if (currCost + passingFees[v] < cost[v]) { + cost[v] = currCost + passingFees[v]; + dist[v] = d + w; + minHeap.emplace(cost[v], dist[v], v); + } else if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(currCost + passingFees[v], dist[v], v); + } + } + } + + return -1; + } +}; diff --git a/solutions/1928. Minimum Cost to Reach Destination in Time/1928.java b/solutions/1928. Minimum Cost to Reach Destination in Time/1928.java new file mode 100644 index 00000000000..f8d7e984b0a --- /dev/null +++ b/solutions/1928. Minimum Cost to Reach Destination in Time/1928.java @@ -0,0 +1,60 @@ +class Solution { + public int minCost(int maxTime, int[][] edges, int[] passingFees) { + final int n = passingFees.length; + List>[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int t = edge[2]; + graph[u].add(new Pair<>(v, t)); + graph[v].add(new Pair<>(u, t)); + } + + return dijkstra(graph, 0, n - 1, maxTime, passingFees); + } + + private int dijkstra(List>[] graph, int src, int dst, int maxTime, + int[] passingFees) { + int[] cost = new int[graph.length]; // cost[i] := the minimum cost to reach the i-th city + int[] dist = new int[graph.length]; // dist[i] := the minimum distance to reach the i-th city + Arrays.fill(cost, Integer.MAX_VALUE); + Arrays.fill(dist, maxTime + 1); + // (cost[u], dist[u], u) + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + + cost[0] = passingFees[0]; + dist[0] = 0; + minHeap.offer(new int[] {cost[src], dist[src], src}); + + while (!minHeap.isEmpty()) { + final int currCost = minHeap.peek()[0]; + final int d = minHeap.peek()[1]; + final int u = minHeap.poll()[2]; + if (u == dst) + return cost[dst]; + if (d > dist[u] && currCost > cost[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w > maxTime) + continue; + // Go from x -> y + if (currCost + passingFees[v] < cost[v]) { + cost[v] = currCost + passingFees[v]; + dist[v] = d + w; + minHeap.offer(new int[] {cost[v], dist[v], v}); + } else if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new int[] {currCost + passingFees[v], dist[v], v}); + } + } + } + + return -1; + } +} diff --git a/solutions/1928. Minimum Cost to Reach Destination in Time/1928.py b/solutions/1928. Minimum Cost to Reach Destination in Time/1928.py new file mode 100644 index 00000000000..97b1fe873e8 --- /dev/null +++ b/solutions/1928. Minimum Cost to Reach Destination in Time/1928.py @@ -0,0 +1,40 @@ +class Solution: + def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int: + n = len(passingFees) + graph = [[] for _ in range(n)] + + for u, v, w in edges: + graph[u].append((v, w)) + graph[v].append((u, w)) + + return self._dijkstra(graph, 0, n - 1, maxTime, passingFees) + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int, maxTime: int, passingFees: List[int]) -> int: + # cost[i] := the minimum cost to reach the i-th city + cost = [math.inf for _ in range(len(graph))] + # dist[i] := the minimum time to reach the i-th city + dist = [maxTime + 1 for _ in range(len(graph))] + + cost[src] = passingFees[src] + dist[src] = 0 + minHeap = [(cost[src], dist[src], src)] # (cost[u], dist[u], u) + + while minHeap: + currCost, d, u = heapq.heappop(minHeap) + if u == dst: + return cost[dst] + if d > dist[u] and currCost > cost[u]: + continue + for v, w in graph[u]: + if d + w > maxTime: + continue + # Go from u -> v. + if currCost + passingFees[v] < cost[v]: + cost[v] = currCost + passingFees[v] + dist[v] = d + w + heapq.heappush(minHeap, (cost[v], dist[v], v)) + elif d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (currCost + passingFees[v], dist[v], v)) + + return -1 diff --git a/solutions/1929. Concatenation of Array/1929.cpp b/solutions/1929. Concatenation of Array/1929.cpp new file mode 100644 index 00000000000..645a6e692ea --- /dev/null +++ b/solutions/1929. Concatenation of Array/1929.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector getConcatenation(vector& nums) { + const int n = nums.size(); + + for (int i = 0; i < n; ++i) + nums.push_back(nums[i]); + + return nums; + } +}; diff --git a/solutions/1929. Concatenation of Array/1929.java b/solutions/1929. Concatenation of Array/1929.java new file mode 100644 index 00000000000..5a7563c28ec --- /dev/null +++ b/solutions/1929. Concatenation of Array/1929.java @@ -0,0 +1,12 @@ +class Solution { + public int[] getConcatenation(int[] nums) { + final int n = nums.length; + + int[] ans = new int[n * 2]; + + for (int i = 0; i < n; ++i) + ans[i] = ans[i + n] = nums[i]; + + return ans; + } +} diff --git a/solutions/1929. Concatenation of Array/1929.py b/solutions/1929. Concatenation of Array/1929.py new file mode 100644 index 00000000000..26f01f4dbf1 --- /dev/null +++ b/solutions/1929. Concatenation of Array/1929.py @@ -0,0 +1,3 @@ +class Solution: + def getConcatenation(self, nums: List[int]) -> List[int]: + return nums * 2 diff --git a/solutions/193. Valid Phone Numbers/193.sh b/solutions/193. Valid Phone Numbers/193.sh new file mode 100644 index 00000000000..cb98aaa7956 --- /dev/null +++ b/solutions/193. Valid Phone Numbers/193.sh @@ -0,0 +1 @@ +grep -e "^[0-9]\{3\}\-[0-9]\{3\}\-[0-9]\{4\}$" -e "^([0-9]\{3\}) [0-9]\{3\}\-[0-9]\{4\}$" file.txt diff --git a/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.cpp b/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.cpp new file mode 100644 index 00000000000..c0b048ba51e --- /dev/null +++ b/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countPalindromicSubsequence(string s) { + int ans = 0; + vector first(26, s.length()); + vector last(26); + + for (int i = 0; i < s.length(); ++i) { + const int index = s[i] - 'a'; + first[index] = min(first[index], i); + last[index] = i; + } + + for (int i = 0; i < 26; ++i) + if (first[i] < last[i]) + ans += unordered_set(s.begin() + first[i] + 1, s.begin() + last[i]) + .size(); + + return ans; + } +}; diff --git a/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.java b/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.java new file mode 100644 index 00000000000..b4d7bb2ed3d --- /dev/null +++ b/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.java @@ -0,0 +1,21 @@ +class Solution { + public int countPalindromicSubsequence(String s) { + int ans = 0; + int[] first = new int[26]; + int[] last = new int[26]; + + Arrays.fill(first, s.length()); + + for (int i = 0; i < s.length(); ++i) { + final int index = s.charAt(i) - 'a'; + first[index] = Math.min(first[index], i); + last[index] = i; + } + + for (int i = 0; i < 26; ++i) + if (first[i] < last[i]) + ans += s.substring(first[i] + 1, last[i]).chars().distinct().count(); + + return ans; + } +} diff --git a/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.py b/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.py new file mode 100644 index 00000000000..e396f9e1971 --- /dev/null +++ b/solutions/1930. Unique Length-3 Palindromic Subsequences/1930.py @@ -0,0 +1,16 @@ +class Solution: + def countPalindromicSubsequence(self, s: str) -> int: + ans = 0 + first = [len(s)] * 26 + last = [0] * 26 + + for i, c in enumerate(s): + index = ord(c) - ord('a') + first[index] = min(first[index], i) + last[index] = i + + for f, l in zip(first, last): + if f < l: + ans += len(set(s[f + 1:l])) + + return ans diff --git a/solutions/1931. Painting a Grid With Three Different Colors/1931.cpp b/solutions/1931. Painting a Grid With Three Different Colors/1931.cpp new file mode 100644 index 00000000000..c97c55613ac --- /dev/null +++ b/solutions/1931. Painting a Grid With Three Different Colors/1931.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int colorTheGrid(int m, int n) { + this->m = m; + this->n = n; + return dp(0, 0, 0, 0); + } + + private: + static constexpr int kMod = 1'000'000'007; + int m; + int n; + vector> mem = vector>(1000, vector(1024)); + + int dp(int r, int c, int prevColMask, int currColMask) { + if (c == n) + return 1; + if (mem[c][prevColMask]) + return mem[c][prevColMask]; + if (r == m) + return dp(0, c + 1, currColMask, 0); + + int ans = 0; + + // 1 := red, 2 := green, 3 := blue + for (int color = 1; color <= 3; ++color) { + if (getColor(prevColMask, r) == color) + continue; + if (r > 0 && getColor(currColMask, r - 1) == color) + continue; + ans += dp(r + 1, c, prevColMask, setColor(currColMask, r, color)); + ans %= kMod; + } + + if (r == 0) + mem[c][prevColMask] = ans; + + return ans; + } + + // e.g. __ __ __ __ __ + // 01 10 11 11 11 + // R G B B B + // getColor(0110111111, 3) -> G + int getColor(int mask, int r) { + return mask >> r * 2 & 3; + } + + int setColor(int mask, int r, int color) { + return mask | color << r * 2; + } +}; diff --git a/solutions/1931. Painting a Grid With Three Different Colors/1931.java b/solutions/1931. Painting a Grid With Three Different Colors/1931.java new file mode 100644 index 00000000000..39cf3a4bd24 --- /dev/null +++ b/solutions/1931. Painting a Grid With Three Different Colors/1931.java @@ -0,0 +1,50 @@ +class Solution { + public int colorTheGrid(int m, int n) { + this.m = m; + this.n = n; + return dp(0, 0, 0, 0); + } + + private static final int kMod = 1_000_000_007; + private int m; + private int n; + private int[][] mem = new int[1000][1024]; + + private int dp(int r, int c, int prevColMask, int currColMask) { + if (c == n) + return 1; + if (mem[c][prevColMask] != 0) + return mem[c][prevColMask]; + if (r == m) + return dp(0, c + 1, currColMask, 0); + + int ans = 0; + + // 1 := red, 2 := green, 3 := blue + for (int color = 1; color <= 3; ++color) { + if (getColor(prevColMask, r) == color) + continue; + if (r > 0 && getColor(currColMask, r - 1) == color) + continue; + ans += dp(r + 1, c, prevColMask, setColor(currColMask, r, color)); + ans %= kMod; + } + + if (r == 0) + mem[c][prevColMask] = ans; + + return ans; + } + + // e.g. __ __ __ __ __ + // 01 10 11 11 11 + // R G B B B + // getColor(0110111111, 3) -> G + private int getColor(int mask, int r) { + return mask >> r * 2 & 3; + } + + private int setColor(int mask, int r, int color) { + return mask | color << r * 2; + } +} diff --git a/solutions/1931. Painting a Grid With Three Different Colors/1931.py b/solutions/1931. Painting a Grid With Three Different Colors/1931.py new file mode 100644 index 00000000000..72525f13361 --- /dev/null +++ b/solutions/1931. Painting a Grid With Three Different Colors/1931.py @@ -0,0 +1,31 @@ +class Solution: + def colorTheGrid(self, m: int, n: int) -> int: + def getColor(mask: int, r: int) -> int: + return mask >> r * 2 & 3 + + def setColor(mask: int, r: int, color: int) -> int: + return mask | color << r * 2 + + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def dp(r: int, c: int, prevColMask: int, currColMask: int) -> int: + if c == n: + return 1 + if r == m: + return dp(0, c + 1, currColMask, 0) + + ans = 0 + + # 1 := red, 2 := green, 3 := blue + for color in range(1, 4): + if getColor(prevColMask, r) == color: + continue + if r > 0 and getColor(currColMask, r - 1) == color: + continue + ans += dp(r + 1, c, prevColMask, setColor(currColMask, r, color)) + ans %= kMod + + return ans + + return dp(0, 0, 0, 0) diff --git a/solutions/1932. Merge BSTs to Create Single BST/1932.cpp b/solutions/1932. Merge BSTs to Create Single BST/1932.cpp new file mode 100644 index 00000000000..dc0172500e8 --- /dev/null +++ b/solutions/1932. Merge BSTs to Create Single BST/1932.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + TreeNode* canMerge(vector& trees) { + unordered_map valToNode; // {val: node} + unordered_map count; // {val: freq} + + for (TreeNode* tree : trees) { + valToNode[tree->val] = tree; + ++count[tree->val]; + if (tree->left) + ++count[tree->left->val]; + if (tree->right) + ++count[tree->right->val]; + } + + for (TreeNode* tree : trees) + if (count[tree->val] == 1) { + if (isValidBST(tree, nullptr, nullptr, valToNode) && + valToNode.size() <= 1) + return tree; + return nullptr; + } + + return nullptr; + } + + private: + bool isValidBST(TreeNode* tree, TreeNode* minNode, TreeNode* maxNode, + unordered_map& valToNode) { + if (tree == nullptr) + return true; + if (minNode && tree->val <= minNode->val) + return false; + if (maxNode && tree->val >= maxNode->val) + return false; + if (!tree->left && !tree->right && valToNode.contains(tree->val)) { + const int val = tree->val; + tree->left = valToNode[val]->left; + tree->right = valToNode[val]->right; + valToNode.erase(val); + } + + return isValidBST(tree->left, minNode, tree, valToNode) && + isValidBST(tree->right, tree, maxNode, valToNode); + } +}; diff --git a/solutions/1932. Merge BSTs to Create Single BST/1932.java b/solutions/1932. Merge BSTs to Create Single BST/1932.java new file mode 100644 index 00000000000..a87a36b8d11 --- /dev/null +++ b/solutions/1932. Merge BSTs to Create Single BST/1932.java @@ -0,0 +1,44 @@ +class Solution { + public TreeNode canMerge(List trees) { + Map valToNode = new HashMap<>(); // {val: node} + Map count = new HashMap<>(); // {val: freq} + + for (TreeNode tree : trees) { + valToNode.put(tree.val, tree); + count.merge(tree.val, 1, Integer::sum); + if (tree.left != null) + count.merge(tree.left.val, 1, Integer::sum); + if (tree.right != null) + count.merge(tree.right.val, 1, Integer::sum); + } + + for (TreeNode tree : trees) + if (count.get(tree.val) == 1) { + if (isValidBST(tree, null, null, valToNode) && valToNode.size() <= 1) + return tree; + return null; + } + + return null; + } + + private boolean isValidBST(TreeNode tree, TreeNode minNode, TreeNode maxNode, + Map valToNode) { + if (tree == null) + return true; + if (minNode != null && tree.val <= minNode.val) + return false; + if (maxNode != null && tree.val >= maxNode.val) + return false; + if (tree.left == null && tree.right == null && valToNode.containsKey(tree.val)) { + final int val = tree.val; + tree.left = valToNode.get(val).left; + tree.right = valToNode.get(val).right; + valToNode.remove(val); + } + + return // + isValidBST(tree.left, minNode, tree, valToNode) && // + isValidBST(tree.right, tree, maxNode, valToNode); + } +} diff --git a/solutions/1932. Merge BSTs to Create Single BST/1932.py b/solutions/1932. Merge BSTs to Create Single BST/1932.py new file mode 100644 index 00000000000..2416f6ae912 --- /dev/null +++ b/solutions/1932. Merge BSTs to Create Single BST/1932.py @@ -0,0 +1,35 @@ +class Solution: + def canMerge(self, trees: List[TreeNode]) -> Optional[TreeNode]: + valToNode = {} # {val: node} + count = collections.Counter() # {val: freq} + + for tree in trees: + valToNode[tree.val] = tree + count[tree.val] += 1 + if tree.left: + count[tree.left.val] += 1 + if tree.right: + count[tree.right.val] += 1 + + def isValidBST(tree: Optional[TreeNode], minNode: Optional[TreeNode], maxNode: Optional[TreeNode]) -> bool: + if not tree: + return True + if minNode and tree.val <= minNode.val: + return False + if maxNode and tree.val >= maxNode.val: + return False + if not tree.left and not tree.right and tree.val in valToNode: + val = tree.val + tree.left = valToNode[val].left + tree.right = valToNode[val].right + del valToNode[val] + + return isValidBST(tree.left, minNode, tree) and isValidBST(tree.right, tree, maxNode) + + for tree in trees: + if count[tree.val] == 1: + if isValidBST(tree, None, None) and len(valToNode) <= 1: + return tree + return None + + return None diff --git a/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.cpp b/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.cpp new file mode 100644 index 00000000000..3b1f6ed414f --- /dev/null +++ b/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + bool isDecomposable(string s) { + int twos = 0; + int groupLength = 0; + char letter = '@'; // the running letter + + for (const char c : s) + if (c == letter) { + ++groupLength; + } else { + if (groupLength % 3 == 1) + return false; + if (groupLength % 3 == 2 && ++twos > 1) + return false; + groupLength = 1; + letter = c; + } + + // Check the final group. + if (groupLength % 3 == 1) + return false; + if (groupLength % 3 == 2 && ++twos > 1) + return false; + return twos == 1; + } +}; diff --git a/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.java b/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.java new file mode 100644 index 00000000000..8693c1b3452 --- /dev/null +++ b/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.java @@ -0,0 +1,26 @@ +class Solution { + public boolean isDecomposable(String s) { + int twos = 0; + int groupLength = 0; + char letter = '@'; // the running letter + + for (final char c : s.toCharArray()) + if (c == letter) { + ++groupLength; + } else { + if (groupLength % 3 == 1) + return false; + if (groupLength % 3 == 2 && ++twos > 1) + return false; + groupLength = 1; + letter = c; + } + + // Check the final group. + if (groupLength % 3 == 1) + return false; + if (groupLength % 3 == 2 && ++twos > 1) + return false; + return twos == 1; + } +} diff --git a/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.py b/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.py new file mode 100644 index 00000000000..f71621f6414 --- /dev/null +++ b/solutions/1933. Check if String Is Decomposable Into Value-Equal Substrings/1933.py @@ -0,0 +1,14 @@ +class Solution: + def isDecomposable(self, s: str) -> bool: + twos = 0 + + for _, group in itertools.groupby(s): + groupLength = len(list(group)) + if groupLength % 3 == 1: + return False + if groupLength % 3 == 2: + twos += 1 + if twos > 1: + return False + + return twos == 1 diff --git a/solutions/1934. Confirmation Rate/1934.sql b/solutions/1934. Confirmation Rate/1934.sql new file mode 100644 index 00000000000..84176e5fd40 --- /dev/null +++ b/solutions/1934. Confirmation Rate/1934.sql @@ -0,0 +1,7 @@ +SELECT + Signups.user_id, + IFNULL(ROUND(AVG(Confirmations.action = 'confirmed'), 2), 0) AS confirmation_rate +FROM Signups +LEFT JOIN Confirmations + USING (user_id) +GROUP BY 1; diff --git a/solutions/1935. Maximum Number of Words You Can Type/1935.cpp b/solutions/1935. Maximum Number of Words You Can Type/1935.cpp new file mode 100644 index 00000000000..2bd29194735 --- /dev/null +++ b/solutions/1935. Maximum Number of Words You Can Type/1935.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int canBeTypedWords(string text, string brokenLetters) { + int ans = 0; + istringstream iss(text); + vector broken(26); + + for (const char c : brokenLetters) + broken[c - 'a'] = true; + + for (string word; iss >> word;) + ans += canBeTyped(word, broken); + + return ans; + } + + private: + bool canBeTyped(const string& word, const vector& broken) { + for (const char c : word) + if (broken[c - 'a']) + return false; + return true; + } +}; diff --git a/solutions/1935. Maximum Number of Words You Can Type/1935.java b/solutions/1935. Maximum Number of Words You Can Type/1935.java new file mode 100644 index 00000000000..4f85ac0881f --- /dev/null +++ b/solutions/1935. Maximum Number of Words You Can Type/1935.java @@ -0,0 +1,21 @@ +class Solution { + public int canBeTypedWords(String text, String brokenLetters) { + int ans = 0; + boolean[] broken = new boolean[26]; + + for (final char c : brokenLetters.toCharArray()) + broken[c - 'a'] = true; + + for (final String word : text.split(" ")) + ans += canBeTyped(word, broken); + + return ans; + } + + private int canBeTyped(final String word, boolean[] broken) { + for (final char c : word.toCharArray()) + if (broken[c - 'a']) + return 0; + return 1; + } +} diff --git a/solutions/1935. Maximum Number of Words You Can Type/1935.py b/solutions/1935. Maximum Number of Words You Can Type/1935.py new file mode 100644 index 00000000000..0494b94282b --- /dev/null +++ b/solutions/1935. Maximum Number of Words You Can Type/1935.py @@ -0,0 +1,9 @@ +class Solution: + def canBeTypedWords(self, text: str, brokenLetters: str) -> int: + ans = 0 + broken = set(brokenLetters) + + for word in text.split(): + ans += all(c not in broken for c in word) + + return ans diff --git a/solutions/1936. Add Minimum Number of Rungs/1936.cpp b/solutions/1936. Add Minimum Number of Rungs/1936.cpp new file mode 100644 index 00000000000..a279c8b4b57 --- /dev/null +++ b/solutions/1936. Add Minimum Number of Rungs/1936.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int addRungs(vector& rungs, int dist) { + int ans = 0; + int prev = 0; + + for (const int rung : rungs) { + ans += (rung - prev - 1) / dist; + prev = rung; + } + + return ans; + } +}; diff --git a/solutions/1936. Add Minimum Number of Rungs/1936.java b/solutions/1936. Add Minimum Number of Rungs/1936.java new file mode 100644 index 00000000000..89cf1b9738d --- /dev/null +++ b/solutions/1936. Add Minimum Number of Rungs/1936.java @@ -0,0 +1,13 @@ +class Solution { + public int addRungs(int[] rungs, int dist) { + int ans = 0; + int prev = 0; + + for (final int rung : rungs) { + ans += (rung - prev - 1) / dist; + prev = rung; + } + + return ans; + } +} diff --git a/solutions/1936. Add Minimum Number of Rungs/1936.py b/solutions/1936. Add Minimum Number of Rungs/1936.py new file mode 100644 index 00000000000..6e1f0cbda4c --- /dev/null +++ b/solutions/1936. Add Minimum Number of Rungs/1936.py @@ -0,0 +1,10 @@ +class Solution: + def addRungs(self, rungs: List[int], dist: int) -> int: + ans = 0 + prev = 0 + + for rung in rungs: + ans += (rung - prev - 1) // dist + prev = rung + + return ans diff --git a/solutions/1937. Maximum Number of Points with Cost/1937.cpp b/solutions/1937. Maximum Number of Points with Cost/1937.cpp new file mode 100644 index 00000000000..868b6ac320c --- /dev/null +++ b/solutions/1937. Maximum Number of Points with Cost/1937.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + long long maxPoints(vector>& points) { + const int n = points[0].size(); + // dp[j] := the maximum number of points you can have if points[i][j] is the + // most recent cell you picked + vector dp(n); + + for (const vector& row : points) { + vector leftToRight(n); + long runningMax = 0; + + for (int j = 0; j < n; ++j) { + runningMax = max(runningMax - 1, dp[j]); + leftToRight[j] = runningMax; + } + + vector rightToLeft(n); + runningMax = 0; + + for (int j = n - 1; j >= 0; --j) { + runningMax = max(runningMax - 1, dp[j]); + rightToLeft[j] = runningMax; + } + + for (int j = 0; j < n; ++j) + dp[j] = max(leftToRight[j], rightToLeft[j]) + row[j]; + } + + return ranges::max(dp); + } +}; diff --git a/solutions/1937. Maximum Number of Points with Cost/1937.java b/solutions/1937. Maximum Number of Points with Cost/1937.java new file mode 100644 index 00000000000..4095257a3f1 --- /dev/null +++ b/solutions/1937. Maximum Number of Points with Cost/1937.java @@ -0,0 +1,31 @@ +class Solution { + public long maxPoints(int[][] points) { + final int n = points[0].length; + // dp[j] := the maximum number of points you can have if points[i][j] is the + // most recent cell you picked + long[] dp = new long[n]; + + for (int[] row : points) { + long[] leftToRight = new long[n]; + long runningMax = 0; + + for (int j = 0; j < n; ++j) { + runningMax = Math.max(runningMax - 1, dp[j]); + leftToRight[j] = runningMax; + } + + long[] rightToLeft = new long[n]; + runningMax = 0; + + for (int j = n - 1; j >= 0; --j) { + runningMax = Math.max(runningMax - 1, dp[j]); + rightToLeft[j] = runningMax; + } + + for (int j = 0; j < n; ++j) + dp[j] = Math.max(leftToRight[j], rightToLeft[j]) + row[j]; + } + + return Arrays.stream(dp).max().getAsLong(); + } +} diff --git a/solutions/1937. Maximum Number of Points with Cost/1937.py b/solutions/1937. Maximum Number of Points with Cost/1937.py new file mode 100644 index 00000000000..8147fa04c6b --- /dev/null +++ b/solutions/1937. Maximum Number of Points with Cost/1937.py @@ -0,0 +1,24 @@ +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + n = len(points[0]) + # dp[j] := the maximum number of points you can have if points[i][j] is the + # most recent cell you picked + dp = [0] * n + + for row in points: + leftToRight = [0] * n + runningMax = 0 + for j in range(n): + runningMax = max(runningMax - 1, dp[j]) + leftToRight[j] = runningMax + + rightToLeft = [0] * n + runningMax = 0 + for j in range(n - 1, - 1, -1): + runningMax = max(runningMax - 1, dp[j]) + rightToLeft[j] = runningMax + + for j in range(n): + dp[j] = max(leftToRight[j], rightToLeft[j]) + row[j] + + return max(dp) diff --git a/solutions/1938. Maximum Genetic Difference Query/1938.cpp b/solutions/1938. Maximum Genetic Difference Query/1938.cpp new file mode 100644 index 00000000000..681c550ccc6 --- /dev/null +++ b/solutions/1938. Maximum Genetic Difference Query/1938.cpp @@ -0,0 +1,84 @@ +struct TrieNode { + vector> children; + int count = 0; + TrieNode() : children(2) {} +}; + +class Trie { + public: + void update(int num, int val) { + shared_ptr node = root; + for (int i = kHeight; i >= 0; --i) { + const int bit = (num >> i) & 1; + if (node->children[bit] == nullptr) + node->children[bit] = make_shared(); + node = node->children[bit]; + node->count += val; + } + } + + int query(int num) { + int ans = 0; + shared_ptr node = root; + for (int i = kHeight; i >= 0; --i) { + const int bit = (num >> i) & 1; + const int targetBit = bit ^ 1; + if (node->children[targetBit] && node->children[targetBit]->count) { + ans += 1 << i; + node = node->children[targetBit]; + } else { + node = node->children[targetBit ^ 1]; + } + } + return ans; + } + + private: + static constexpr int kHeight = 17; + shared_ptr root = make_shared(); +}; + +class Solution { + public: + vector maxGeneticDifference(vector& parents, + vector>& queries) { + const int n = parents.size(); + vector ans(queries.size()); + int rootVal = -1; + vector> tree(n); + // {node: (index, val)} + unordered_map>> nodeToQueries; + Trie trie; + + for (int i = 0; i < parents.size(); ++i) + if (parents[i] == -1) + rootVal = i; + else + tree[parents[i]].push_back(i); + + for (int i = 0; i < queries.size(); ++i) { + const int node = queries[i][0]; + const int val = queries[i][1]; + nodeToQueries[node].emplace_back(i, val); + } + + dfs(rootVal, trie, tree, nodeToQueries, ans); + return ans; + } + + private: + void dfs(int node, Trie& trie, const vector>& tree, + const unordered_map>>& nodeToQueries, + vector& ans) { + trie.update(node, 1); + + if (const auto it = nodeToQueries.find(node); it != nodeToQueries.cend()) + for (const auto& [i, val] : it->second) + ans[i] = trie.query(val); + + for (const int child : tree[node]) + dfs(child, trie, tree, nodeToQueries, ans); + + trie.update(node, -1); + } +}; diff --git a/solutions/1938. Maximum Genetic Difference Query/1938.java b/solutions/1938. Maximum Genetic Difference Query/1938.java new file mode 100644 index 00000000000..e7ca4641455 --- /dev/null +++ b/solutions/1938. Maximum Genetic Difference Query/1938.java @@ -0,0 +1,85 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[2]; + public int count = 0; +} + +class Trie { + public void update(int num, int val) { + TrieNode node = root; + for (int i = kHeight; i >= 0; --i) { + final int bit = (num >> i) & 1; + if (node.children[bit] == null) + node.children[bit] = new TrieNode(); + node = node.children[bit]; + node.count += val; + } + } + + public int query(int num) { + int ans = 0; + TrieNode node = root; + for (int i = kHeight; i >= 0; --i) { + final int bit = (num >> i) & 1; + final int targetBit = bit ^ 1; + if (node.children[targetBit] != null && node.children[targetBit].count > 0) { + ans += 1 << i; + node = node.children[targetBit]; + } else { + node = node.children[targetBit ^ 1]; + } + } + return ans; + } + + private static final int kHeight = 17; + TrieNode root = new TrieNode(); +} + +class Solution { + public int[] maxGeneticDifference(int[] parents, int[][] queries) { + final int n = parents.length; + int[] ans = new int[queries.length]; + int rootVal = -1; + List[] tree = new List[n]; + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + // {node: (index, val)} + Map>> nodeToQueries = new HashMap<>(); + Trie trie = new Trie(); + + for (int i = 0; i < parents.length; ++i) + if (parents[i] == -1) + rootVal = i; + else + tree[parents[i]].add(i); + + for (int i = 0; i < queries.length; ++i) { + final int node = queries[i][0]; + final int val = queries[i][1]; + nodeToQueries.putIfAbsent(node, new ArrayList<>()); + nodeToQueries.get(node).add(new Pair<>(i, val)); + } + + dfs(rootVal, trie, tree, nodeToQueries, ans); + return ans; + } + + private void dfs(int node, Trie trie, List[] tree, + Map>> nodeToQueries, int[] ans) { + trie.update(node, 1); + + if (nodeToQueries.containsKey(node)) + for (Pair query : nodeToQueries.get(node)) { + final int i = query.getKey(); + final int val = query.getValue(); + ans[i] = trie.query(val); + } + + for (final int child : tree[node]) + dfs(child, trie, tree, nodeToQueries, ans); + + trie.update(node, -1); + } +} diff --git a/solutions/1938. Maximum Genetic Difference Query/1938.py b/solutions/1938. Maximum Genetic Difference Query/1938.py new file mode 100644 index 00000000000..e972d61aacc --- /dev/null +++ b/solutions/1938. Maximum Genetic Difference Query/1938.py @@ -0,0 +1,66 @@ +class TrieNode: + def __init__(self): + self.children = [None] * 2 + self.count = 0 + + +class Trie: + def __init__(self): + self.root = TrieNode() + self.kHeight = 17 + + def update(self, num: int, val: int) -> None: + node = self.root + for i in range(self.kHeight, -1, -1): + bit = (num >> i) & 1 + if not node.children[bit]: + node.children[bit] = TrieNode() + node = node.children[bit] + node.count += val + + def query(self, num: int) -> int: + ans = 0 + node = self.root + for i in range(self.kHeight, -1, -1): + bit = (num >> i) & 1 + targetBit = bit ^ 1 + if node.children[targetBit] and node.children[targetBit].count > 0: + ans += 1 << i + node = node.children[targetBit] + else: + node = node.children[targetBit ^ 1] + return ans + + +class Solution: + def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]: + n = len(parents) + ans = [0] * len(queries) + rootVal = -1 + tree = [[] for _ in range(n)] + nodeToQueries = collections.defaultdict(list) # {node: (index, val)} + trie = Trie() + + for i, parent in enumerate(parents): + if parent == -1: + rootVal = i + else: + tree[parent].append(i) + + for i, (node, val) in enumerate(queries): + nodeToQueries[node].append((i, val)) + + def dfs(node: int) -> None: + trie.update(node, 1) + + # Answer queries for node + for i, val in nodeToQueries[node]: + ans[i] = trie.query(val) + + for child in tree[node]: + dfs(child) + + trie.update(node, -1) + + dfs(rootVal) + return ans diff --git a/solutions/1939. Users That Actively Request Confirmation Messages/1939.sql b/solutions/1939. Users That Actively Request Confirmation Messages/1939.sql new file mode 100644 index 00000000000..b6e6b12e4b9 --- /dev/null +++ b/solutions/1939. Users That Actively Request Confirmation Messages/1939.sql @@ -0,0 +1,16 @@ +WITH + UserToTimestampDiff AS ( + SELECT user_id, + TIMESTAMPDIFF( + SECOND, + time_stamp, + LEAD(time_stamp) OVER( + PARTITION BY user_id + ORDER BY time_stamp + ) + ) AS timestamp_diff + FROM Confirmations + ) +SELECT DISTINCT user_id +FROM UserToTimestampDiff +WHERE timestamp_diff <= 24 * 60 * 60; diff --git a/solutions/194. Transpose File/194.sh b/solutions/194. Transpose File/194.sh new file mode 100644 index 00000000000..a31688b8f8c --- /dev/null +++ b/solutions/194. Transpose File/194.sh @@ -0,0 +1,13 @@ +awk '{ + for (i = 1; i <= NF; ++i) { + if (NR == 1) { + arr[i] = $i; + } else { + arr[i] = arr[i] " " $i; + } + } +} END { + for (i = 1; i <= NF; ++i) { + print arr[i]; + } +}' file.txt diff --git a/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940-2.py b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940-2.py new file mode 100644 index 00000000000..44edc857ef4 --- /dev/null +++ b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940-2.py @@ -0,0 +1,3 @@ +class Solution: + def longestCommonSubsequence(self, arrays: List[List[int]]) -> List[int]: + return sorted(functools.reduce(lambda a, b: set(a) & set(b), arrays)) diff --git a/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.cpp b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.cpp new file mode 100644 index 00000000000..fde91ddac98 --- /dev/null +++ b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector longestCommonSubsequence(vector>& arrays) { + constexpr int kMax = 100; + vector ans; + vector count(kMax + 1); + + for (const vector& array : arrays) + for (const int a : array) + if (++count[a] == arrays.size()) + ans.push_back(a); + + return ans; + } +}; diff --git a/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.java b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.java new file mode 100644 index 00000000000..9896275c2b9 --- /dev/null +++ b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.java @@ -0,0 +1,14 @@ +class Solution { + public List longestCommonSubsequence(int[][] arrays) { + final int kMax = 100; + List ans = new ArrayList<>(); + int[] count = new int[kMax + 1]; + + for (int[] array : arrays) + for (final int a : array) + if (++count[a] == arrays.length) + ans.add(a); + + return ans; + } +} diff --git a/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.py b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.py new file mode 100644 index 00000000000..d04155b233f --- /dev/null +++ b/solutions/1940. Longest Common Subsequence Between Sorted Arrays/1940.py @@ -0,0 +1,13 @@ +class Solution: + def longestCommonSubsequence(self, arrays: List[List[int]]) -> List[int]: + kMax = 100 + ans = [] + count = [0] * (kMax + 1) + + for array in arrays: + for a in array: + count[a] += 1 + if count[a] == len(arrays): + ans.append(a) + + return ans diff --git a/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.cpp b/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.cpp new file mode 100644 index 00000000000..bd112cb2993 --- /dev/null +++ b/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool areOccurrencesEqual(string s) { + vector count(26); + for (const char c : s) + ++count[c - 'a']; + return equalFreq(count, count[s[0] - 'a']); + } + + private: + bool equalFreq(const vector& count, int theFreq) { + return ranges::all_of( + count, [theFreq](int freq) { return freq == 0 || freq == theFreq; }); + } +}; diff --git a/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.java b/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.java new file mode 100644 index 00000000000..2b335eaa941 --- /dev/null +++ b/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.java @@ -0,0 +1,12 @@ +class Solution { + public boolean areOccurrencesEqual(String s) { + int[] count = new int[26]; + for (final char c : s.toCharArray()) + ++count[c - 'a']; + return equalFreq(count, count[s.charAt(0) - 'a']); + } + + private boolean equalFreq(int[] count, int theFreq) { + return Arrays.stream(count).allMatch(freq -> freq == 0 || freq == theFreq); + } +} diff --git a/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.py b/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.py new file mode 100644 index 00000000000..6c4746a37a2 --- /dev/null +++ b/solutions/1941. Check if All Characters Have Equal Number of Occurrences/1941.py @@ -0,0 +1,3 @@ +class Solution: + def areOccurrencesEqual(self, s: str) -> bool: + return len(set(collections.Counter(s).values())) == 1 diff --git a/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.cpp b/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.cpp new file mode 100644 index 00000000000..e3b91b9fc61 --- /dev/null +++ b/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int smallestChair(vector>& times, int targetFriend) { + int nextUnsatChair = 0; + priority_queue, greater<>> emptyChairs; + using P = pair; // (leaving, chair) + priority_queue, greater<>> occupied; + + for (int i = 0; i < times.size(); ++i) + times[i].push_back(i); + + ranges::sort(times); + + for (const vector& time : times) { + const int arrival = time[0]; + const int leaving = time[1]; + const int i = time[2]; + while (!occupied.empty() && occupied.top().first <= arrival) + emptyChairs.push(occupied.top().second), occupied.pop(); + if (i == targetFriend) + return emptyChairs.empty() ? nextUnsatChair : emptyChairs.top(); + if (emptyChairs.empty()) + occupied.emplace(leaving, nextUnsatChair++); + else + occupied.emplace(leaving, emptyChairs.top()), emptyChairs.pop(); + } + + throw; + } +}; diff --git a/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.java b/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.java new file mode 100644 index 00000000000..14a3666a7ca --- /dev/null +++ b/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.java @@ -0,0 +1,33 @@ +class Solution { + public int smallestChair(int[][] times, int targetFriend) { + int nextUnsatChair = 0; + PriorityQueue emptyChairs = new PriorityQueue<>(); + PriorityQueue> occupied = + new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + for (int i = 0; i < times.length; ++i) { + int[] time = times[i]; + time = Arrays.copyOf(time, time.length + 1); + time[time.length - 1] = i; + times[i] = time; + } + + Arrays.sort(times, (a, b) -> a[0] - b[0]); + + for (int[] time : times) { + final int arrival = time[0]; + final int leaving = time[1]; + final int i = time[2]; + while (!occupied.isEmpty() && occupied.peek().getKey() <= arrival) + emptyChairs.add(occupied.poll().getValue()); + if (i == targetFriend) + return emptyChairs.isEmpty() ? nextUnsatChair : emptyChairs.peek(); + if (emptyChairs.isEmpty()) + occupied.add(new Pair<>(leaving, nextUnsatChair++)); + else + occupied.add(new Pair<>(leaving, emptyChairs.poll())); + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.py b/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.py new file mode 100644 index 00000000000..10e485d7c23 --- /dev/null +++ b/solutions/1942. The Number of the Smallest Unoccupied Chair/1942.py @@ -0,0 +1,23 @@ +class Solution: + def smallestChair(self, times: List[List[int]], targetFriend: int) -> int: + nextUnsatChair = 0 + emptyChairs = [] + occupied = [] # (leaving, chair) + + for i in range(len(times)): + times[i].append(i) + + times.sort(key=lambda time: time[0]) + + for arrival, leaving, i in times: + while len(occupied) > 0 and occupied[0][0] <= arrival: + unsatChair = heapq.heappop(occupied)[1] + heapq.heappush(emptyChairs, unsatChair) + if i == targetFriend: + return emptyChairs[0] if len(emptyChairs) > 0 else nextUnsatChair + if len(emptyChairs) == 0: + heapq.heappush(occupied, (leaving, nextUnsatChair)) + nextUnsatChair += 1 + else: + emptyChair = heapq.heappop(emptyChairs) + heapq.heappush(occupied, (leaving, emptyChair)) diff --git a/solutions/1943. Describe the Painting/1943.cpp b/solutions/1943. Describe the Painting/1943.cpp new file mode 100644 index 00000000000..82a6b91cf48 --- /dev/null +++ b/solutions/1943. Describe the Painting/1943.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> splitPainting(vector>& segments) { + vector> ans; + int prevIndex = 0; + long runningMix = 0; + map timeline; + + for (const vector& segment : segments) { + const int start = segment[0]; + const int end = segment[1]; + const int color = segment[2]; + timeline[start] += color; + timeline[end] -= color; + } + + for (const auto& [i, mix] : timeline) { + if (runningMix > 0) + ans.push_back({prevIndex, i, runningMix}); + runningMix += mix; + prevIndex = i; + } + + return ans; + } +}; diff --git a/solutions/1943. Describe the Painting/1943.java b/solutions/1943. Describe the Painting/1943.java new file mode 100644 index 00000000000..6256a25ea1e --- /dev/null +++ b/solutions/1943. Describe the Painting/1943.java @@ -0,0 +1,26 @@ +class Solution { + public List> splitPainting(int[][] segments) { + List> ans = new ArrayList<>(); + int prevIndex = 0; + long runningMix = 0; + TreeMap timeline = new TreeMap<>(); + + for (int[] segment : segments) { + final int start = segment[0]; + final int end = segment[1]; + final int color = segment[2]; + timeline.merge(start, (long) color, Long::sum); + timeline.merge(end, (long) -color, Long::sum); + } + + for (final int i : timeline.keySet()) { + final long mix = timeline.get(i); + if (runningMix > 0) + ans.add(List.of((long) prevIndex, (long) i, runningMix)); + runningMix += mix; + prevIndex = i; + } + + return ans; + } +} diff --git a/solutions/1943. Describe the Painting/1943.py b/solutions/1943. Describe the Painting/1943.py new file mode 100644 index 00000000000..b57861431bb --- /dev/null +++ b/solutions/1943. Describe the Painting/1943.py @@ -0,0 +1,21 @@ +from sortedcontainers import SortedDict + + +class Solution: + def splitPainting(self, segments: List[List[int]]) -> List[List[int]]: + ans = [] + prevIndex = 0 + runningMix = 0 + timeline = SortedDict() + + for start, end, color in segments: + timeline[start] = timeline.get(start, 0) + color + timeline[end] = timeline.get(end, 0) - color + + for i, mix in timeline.items(): + if runningMix > 0: + ans.append([prevIndex, i, runningMix]) + runningMix += mix + prevIndex = i + + return ans diff --git a/solutions/1944. Number of Visible People in a Queue/1944.cpp b/solutions/1944. Number of Visible People in a Queue/1944.cpp new file mode 100644 index 00000000000..7d55144cb52 --- /dev/null +++ b/solutions/1944. Number of Visible People in a Queue/1944.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector canSeePersonsCount(vector& heights) { + const int n = heights.size(); + vector ans(n); + stack stack; + + for (int i = 0; i < n; ++i) { + while (!stack.empty() && heights[stack.top()] <= heights[i]) + ++ans[stack.top()], stack.pop(); + if (!stack.empty()) + ++ans[stack.top()]; + stack.push(i); + } + + return ans; + } +}; diff --git a/solutions/1944. Number of Visible People in a Queue/1944.java b/solutions/1944. Number of Visible People in a Queue/1944.java new file mode 100644 index 00000000000..3269c5d27c7 --- /dev/null +++ b/solutions/1944. Number of Visible People in a Queue/1944.java @@ -0,0 +1,17 @@ +class Solution { + public int[] canSeePersonsCount(int[] heights) { + final int n = heights.length; + int[] ans = new int[n]; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < n; ++i) { + while (!stack.isEmpty() && heights[stack.peek()] <= heights[i]) + ++ans[stack.pop()]; + if (!stack.isEmpty()) + ++ans[stack.peek()]; + stack.push(i); + } + + return ans; + } +} diff --git a/solutions/1944. Number of Visible People in a Queue/1944.py b/solutions/1944. Number of Visible People in a Queue/1944.py new file mode 100644 index 00000000000..b18713a5c2a --- /dev/null +++ b/solutions/1944. Number of Visible People in a Queue/1944.py @@ -0,0 +1,13 @@ +class Solution: + def canSeePersonsCount(self, heights: List[int]) -> List[int]: + ans = [0] * len(heights) + stack = [] + + for i, height in enumerate(heights): + while stack and heights[stack[-1]] <= height: + ans[stack.pop()] += 1 + if stack: + ans[stack[-1]] += 1 + stack.append(i) + + return ans diff --git a/solutions/1945. Sum of Digits of String After Convert/1945.cpp b/solutions/1945. Sum of Digits of String After Convert/1945.cpp new file mode 100644 index 00000000000..a518a0222b3 --- /dev/null +++ b/solutions/1945. Sum of Digits of String After Convert/1945.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int getLucky(string s, int k) { + int ans = convert(s); + for (int i = 1; i < k; ++i) + ans = getDigitSum(ans); + return ans; + } + + private: + int convert(string s) { + int sum = 0; + for (const char c : s) { + const int val = c - 'a' + 1; + // Do one transform to prevent integer overflow. + sum += val < 10 ? val : (val % 10 + val / 10); + } + return sum; + } + + int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +}; diff --git a/solutions/1945. Sum of Digits of String After Convert/1945.java b/solutions/1945. Sum of Digits of String After Convert/1945.java new file mode 100644 index 00000000000..9a868fc3df3 --- /dev/null +++ b/solutions/1945. Sum of Digits of String After Convert/1945.java @@ -0,0 +1,27 @@ +class Solution { + public int getLucky(String s, int k) { + int ans = convert(s); + for (int i = 1; i < k; ++i) + ans = getDigitSum(ans); + return ans; + } + + private int convert(final String s) { + int sum = 0; + for (final char c : s.toCharArray()) { + final int val = c - 'a' + 1; + // Do one transform to prevent integer overflow. + sum += val < 10 ? val : (val % 10 + val / 10); + } + return sum; + } + + private int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +} diff --git a/solutions/1945. Sum of Digits of String After Convert/1945.py b/solutions/1945. Sum of Digits of String After Convert/1945.py new file mode 100644 index 00000000000..7a049fcdc0a --- /dev/null +++ b/solutions/1945. Sum of Digits of String After Convert/1945.py @@ -0,0 +1,12 @@ +class Solution: + def getLucky(self, s: str, k: int) -> int: + ans = self._convert(s) + for _ in range(k): + ans = self._getDigitSum(ans) + return ans + + def _convert(self, s: str) -> int: + return int(''.join(str(ord(c) - ord('a') + 1) for c in s)) + + def _getDigitSum(self, num: int) -> int: + return sum(int(digit) for digit in str(num)) diff --git a/solutions/1946. Largest Number After Mutating Substring/1946.cpp b/solutions/1946. Largest Number After Mutating Substring/1946.cpp new file mode 100644 index 00000000000..7798aa9700a --- /dev/null +++ b/solutions/1946. Largest Number After Mutating Substring/1946.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string maximumNumber(string num, vector& change) { + bool mutated = false; + + for (char& c : num) { + const int d = c - '0'; + c = '0' + max(d, change[d]); + if (mutated && d > change[d]) + return num; + if (d < change[d]) + mutated = true; + } + + return num; + } +}; diff --git a/solutions/1946. Largest Number After Mutating Substring/1946.java b/solutions/1946. Largest Number After Mutating Substring/1946.java new file mode 100644 index 00000000000..805f7f14204 --- /dev/null +++ b/solutions/1946. Largest Number After Mutating Substring/1946.java @@ -0,0 +1,18 @@ +class Solution { + public String maximumNumber(String num, int[] change) { + StringBuilder sb = new StringBuilder(num); + boolean mutated = false; + + for (int i = 0; i < num.length(); ++i) { + final int d = num.charAt(i) - '0'; + final char c = (char) ('0' + Math.max(d, change[d])); + sb.setCharAt(i, c); + if (mutated && d > change[d]) + return sb.toString(); + if (d < change[d]) + mutated = true; + } + + return sb.toString(); + } +} diff --git a/solutions/1946. Largest Number After Mutating Substring/1946.py b/solutions/1946. Largest Number After Mutating Substring/1946.py new file mode 100644 index 00000000000..c0dbb9849f4 --- /dev/null +++ b/solutions/1946. Largest Number After Mutating Substring/1946.py @@ -0,0 +1,14 @@ +class Solution: + def maximumNumber(self, num: str, change: List[int]) -> str: + numList = list(num) + mutated = False + + for i, c in enumerate(numList): + d = int(c) + numList[i] = chr(ord('0') + max(d, change[d])) + if mutated and d > change[d]: + return ''.join(numList) + if d < change[d]: + mutated = True + + return ''.join(numList) diff --git a/solutions/1947. Maximum Compatibility Score Sum/1947.cpp b/solutions/1947. Maximum Compatibility Score Sum/1947.cpp new file mode 100644 index 00000000000..ea97d40ecc9 --- /dev/null +++ b/solutions/1947. Maximum Compatibility Score Sum/1947.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int maxCompatibilitySum(vector>& students, + vector>& mentors) { + int ans = 0; + dfs(students, mentors, 0, /*score=*/0, vector(students.size()), ans); + return ans; + } + + private: + void dfs(const vector>& students, + const vector>& mentors, int i, int scoreSum, + vector&& used, int& ans) { + if (i == students.size()) { + ans = max(ans, scoreSum); + return; + } + for (int j = 0; j < students.size(); ++j) { + if (used[j]) + continue; + used[j] = true; // The `mentors[j]` is used. + dfs(students, mentors, i + 1, + scoreSum + getScore(students[i], mentors[j]), move(used), ans); + used[j] = false; + } + } + + int getScore(const vector& student, const vector& mentor) { + int score = 0; + for (int i = 0; i < student.size(); ++i) + if (student[i] == mentor[i]) + ++score; + return score; + } +}; diff --git a/solutions/1947. Maximum Compatibility Score Sum/1947.java b/solutions/1947. Maximum Compatibility Score Sum/1947.java new file mode 100644 index 00000000000..44448e2673a --- /dev/null +++ b/solutions/1947. Maximum Compatibility Score Sum/1947.java @@ -0,0 +1,30 @@ +class Solution { + public int maxCompatibilitySum(int[][] students, int[][] mentors) { + dfs(students, mentors, 0, /*score=*/0, new boolean[students.length]); + return ans; + } + + private int ans = 0; + + private void dfs(int[][] students, int[][] mentors, int i, int scoreSum, boolean[] used) { + if (i == students.length) { + ans = Math.max(ans, scoreSum); + return; + } + for (int j = 0; j < students.length; ++j) { + if (used[j]) + continue; + used[j] = true; // The `mentors[j]` is used. + dfs(students, mentors, i + 1, scoreSum + getScore(students[i], mentors[j]), used); + used[j] = false; + } + } + + private int getScore(int[] student, int[] mentor) { + int score = 0; + for (int i = 0; i < student.length; ++i) + if (student[i] == mentor[i]) + ++score; + return score; + } +} diff --git a/solutions/1947. Maximum Compatibility Score Sum/1947.py b/solutions/1947. Maximum Compatibility Score Sum/1947.py new file mode 100644 index 00000000000..b755aabc195 --- /dev/null +++ b/solutions/1947. Maximum Compatibility Score Sum/1947.py @@ -0,0 +1,20 @@ +class Solution: + def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int: + ans = 0 + + def dfs(i: int, scoreSum: int, used: List[bool]) -> None: + nonlocal ans + if i == len(students): + ans = max(ans, scoreSum) + return + + for j, mentor in enumerate(mentors): + if used[j]: + continue + used[j] = True # The `mentors[j]` is used. + dfs(i + 1, scoreSum + sum(s == m + for s, m in zip(students[i], mentor)), used) + used[j] = False + + dfs(0, 0, [False] * len(students)) + return ans diff --git a/solutions/1948. Delete Duplicate Folders in System/1948.cpp b/solutions/1948. Delete Duplicate Folders in System/1948.cpp new file mode 100644 index 00000000000..5809d0afef9 --- /dev/null +++ b/solutions/1948. Delete Duplicate Folders in System/1948.cpp @@ -0,0 +1,61 @@ +struct TrieNode { + unordered_map> children; + bool deleted = false; +}; + +class Solution { + public: + vector> deleteDuplicateFolder(vector>& paths) { + vector> ans; + vector path; + unordered_map>> subtreeToNodes; + + ranges::sort(paths); + + for (const vector& path : paths) { + shared_ptr node = root; + for (const string& s : path) { + if (!node->children.contains(s)) + node->children[s] = make_shared(); + node = node->children[s]; + } + } + + buildSubtreeToRoots(root, subtreeToNodes); + + for (const auto& [_, nodes] : subtreeToNodes) + if (nodes.size() > 1) + for (shared_ptr node : nodes) + node->deleted = true; + + constructPath(root, path, ans); + return ans; + } + + private: + shared_ptr root = make_shared(); + + string buildSubtreeToRoots( + shared_ptr node, + unordered_map>>& subtreeToNodes) { + string subtree = "("; + for (const auto& [s, child] : node->children) + subtree += s + buildSubtreeToRoots(child, subtreeToNodes); + subtree += ")"; + if (subtree != "()") + subtreeToNodes[subtree].push_back(node); + return subtree; + } + + void constructPath(shared_ptr node, vector& path, + vector>& ans) { + for (const auto& [s, child] : node->children) + if (!child->deleted) { + path.push_back(s); + constructPath(child, path, ans); + path.pop_back(); + } + if (!path.empty()) + ans.push_back(path); + } +}; diff --git a/solutions/1948. Delete Duplicate Folders in System/1948.java b/solutions/1948. Delete Duplicate Folders in System/1948.java new file mode 100644 index 00000000000..23aa91a55d0 --- /dev/null +++ b/solutions/1948. Delete Duplicate Folders in System/1948.java @@ -0,0 +1,69 @@ +class TrieNode { + public Map children = new HashMap<>(); + public boolean deleted = false; +} + +class Solution { + public List> deleteDuplicateFolder(List> paths) { + List> ans = new ArrayList<>(); + Map> subtreeToNodes = new HashMap<>(); + + Collections.sort(paths, (a, b) -> { + for (int i = 0; i < Math.min(a.size(), b.size()); ++i) { + final int c = a.get(i).compareTo(b.get(i)); + if (c != 0) + return c; + } + return Integer.compare(a.size(), b.size()); + }); + + for (List path : paths) { + TrieNode node = root; + for (final String s : path) { + node.children.putIfAbsent(s, new TrieNode()); + node = node.children.get(s); + } + } + + buildSubtreeToRoots(root, subtreeToNodes); + + for (List nodes : subtreeToNodes.values()) + if (nodes.size() > 1) + for (TrieNode node : nodes) + node.deleted = true; + + constructPath(root, new ArrayList<>(), ans); + return ans; + } + + private TrieNode root = new TrieNode(); + + private StringBuilder buildSubtreeToRoots(TrieNode node, + Map> subtreeToNodes) { + StringBuilder sb = new StringBuilder("("); + for (final String s : node.children.keySet()) { + TrieNode child = node.children.get(s); + sb.append(s).append(buildSubtreeToRoots(child, subtreeToNodes)); + } + sb.append(")"); + final String subtree = sb.toString(); + if (!subtree.equals("()")) { + subtreeToNodes.putIfAbsent(subtree, new ArrayList<>()); + subtreeToNodes.get(subtree).add(node); + } + return sb; + } + + private void constructPath(TrieNode node, List path, List> ans) { + for (final String s : node.children.keySet()) { + TrieNode child = node.children.get(s); + if (!child.deleted) { + path.add(s); + constructPath(child, path, ans); + path.remove(path.size() - 1); + } + } + if (!path.isEmpty()) + ans.add(new ArrayList<>(path)); + } +} diff --git a/solutions/1948. Delete Duplicate Folders in System/1948.py b/solutions/1948. Delete Duplicate Folders in System/1948.py new file mode 100644 index 00000000000..23775870537 --- /dev/null +++ b/solutions/1948. Delete Duplicate Folders in System/1948.py @@ -0,0 +1,44 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode) + self.deleted = False + + +class Solution: + def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]: + ans = [] + root = TrieNode() + subtreeToNodes: Dict[str, List[TrieNode]] = collections.defaultdict(list) + + # Construct the Trie + for path in sorted(paths): + node = root + for s in path: + node = node.children[s] + + # For each subtree, fill in the {subtree encoding: [root]} hash table + def buildSubtreeToRoots(node: TrieNode) -> str: + subtree = '(' + ''.join(s + buildSubtreeToRoots(node.children[s]) + for s in node.children) + ')' + if subtree != '()': + subtreeToNodes[subtree].append(node) + return subtree + + buildSubtreeToRoots(root) + + # Mark nodes that should be deleted + for nodes in subtreeToNodes.values(): + if len(nodes) > 1: + for node in nodes: + node.deleted = True + + # Construct the answer array for nodes that haven't been deleted + def constructPath(node: TrieNode, path: List[str]) -> None: + for s, child in node.children.items(): + if not child.deleted: + constructPath(child, path + [s]) + if path: + ans.append(path) + + constructPath(root, []) + return ans diff --git a/solutions/1949. Strong Friendship/1949.sql b/solutions/1949. Strong Friendship/1949.sql new file mode 100644 index 00000000000..e7a2dc9c11b --- /dev/null +++ b/solutions/1949. Strong Friendship/1949.sql @@ -0,0 +1,24 @@ +WITH + TwoWayFriendship AS ( + SELECT user1_id AS user_id, user2_id AS friend_id FROM Friendship + UNION ALL + SELECT user2_id, user1_id FROM Friendship + ) +SELECT + User1.user_id AS user1_id, + User2.user_id AS user2_id, + COUNT(*) AS common_friend +FROM TwoWayFriendship AS User1 +INNER JOIN TwoWayFriendship AS User2 + ON ( + User1.friend_id = User2.friend_id + AND User1.user_id < User2.user_id) +WHERE EXISTS ( + SELECT * + FROM Friendship + WHERE + Friendship.user1_id = User1.user_id + AND Friendship.user2_id = User2.user_id +) +GROUP BY 1, 2 +HAVING common_friend >= 3; diff --git a/solutions/195. Tenth Line/195.sh b/solutions/195. Tenth Line/195.sh new file mode 100644 index 00000000000..6db7b065d8e --- /dev/null +++ b/solutions/195. Tenth Line/195.sh @@ -0,0 +1 @@ +awk 'NR == 10' file.txt diff --git a/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.cpp b/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.cpp new file mode 100644 index 00000000000..5e31d8878ed --- /dev/null +++ b/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + // Similar to 1950. Maximum of Minimum Values in All Subarrays + vector findMaximums(vector& nums) { + const int n = nums.size(); + vector ans(n); + // prevMin[i] := the index k s.t. + // nums[k] is the previous minimum in nums[0..n) + vector prevMin(n, -1); + // nextMin[i] := the index k s.t. + // nums[k] is the next minimum innums[i + 1..n) + vector nextMin(n, n); + stack stack; + + for (int i = 0; i < n; ++i) { + while (!stack.empty() && nums[stack.top()] > nums[i]) { + const int index = stack.top(); + stack.pop(); + nextMin[index] = i; + } + if (!stack.empty()) + prevMin[i] = stack.top(); + stack.push(i); + } + + // For each nums[i], let l = nextMin[i] + 1 and r = nextMin[i] - 1. + // nums[i] is the minimum in nums[l..r]. + // So, the ans[r - l + 1] will be at least nums[i]. + for (int i = 0; i < n; ++i) { + const int sz = nextMin[i] - prevMin[i] - 1; + ans[sz - 1] = max(ans[sz - 1], nums[i]); + } + + // ans[i] should always >= ans[i + 1..n). + for (int i = n - 2; i >= 0; --i) + ans[i] = max(ans[i], ans[i + 1]); + + return ans; + } +}; diff --git a/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.java b/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.java new file mode 100644 index 00000000000..ea0837a7831 --- /dev/null +++ b/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.java @@ -0,0 +1,41 @@ +class Solution { + // Similar to 1950. Maximum of Minimum Values in All Subarrays + public int[] findMaximums(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + // prevMin[i] := the index k s.t. + // nums[k] is the previous minimum in nums[0..n) + int[] prevMin = new int[n]; + // nextMin[i] := the index k s.t. + // nums[k] is the next minimum innums[i + 1..n) + int[] nextMin = new int[n]; + Deque stack = new ArrayDeque<>(); + + Arrays.fill(prevMin, -1); + Arrays.fill(nextMin, n); + + for (int i = 0; i < n; ++i) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + final int index = stack.pop(); + nextMin[index] = i; + } + if (!stack.isEmpty()) + prevMin[i] = stack.peek(); + stack.push(i); + } + + // For each nums[i], let l = nextMin[i] + 1 and r = nextMin[i] - 1. + // nums[i] is the minimum in nums[l..r]. + // So, the ans[r - l + 1] will be at least nums[i]. + for (int i = 0; i < n; ++i) { + final int sz = nextMin[i] - prevMin[i] - 1; + ans[sz - 1] = Math.max(ans[sz - 1], nums[i]); + } + + // ans[i] should always >= ans[i + 1..n). + for (int i = n - 2; i >= 0; --i) + ans[i] = Math.max(ans[i], ans[i + 1]); + + return ans; + } +} diff --git a/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.py b/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.py new file mode 100644 index 00000000000..e4e8d315d9a --- /dev/null +++ b/solutions/1950. Maximum of Minimum Values in All Subarrays/1950.py @@ -0,0 +1,33 @@ +class Solution: + # Similar to 1950. Maximum of Minimum Values in All Subarrays + def findMaximums(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [0] * n + # prevMin[i] := the index k s.t. + # nums[k] is the previous minimum in nums[0..n) + prevMin = [-1] * n + # nextMin[i] := the index k s.t. + # nums[k] is the next minimum innums[i + 1..n) + nextMin = [n] * n + stack = [] + + for i, num in enumerate(nums): + while stack and nums[stack[-1]] > nums[i]: + index = stack.pop() + nextMin[index] = i + if stack: + prevMin[i] = stack[-1] + stack.append(i) + + # For each nums[i], let l = nextMin[i] + 1 and r = nextMin[i] - 1. + # nums[i] is the minimum in nums[l..r]. + # So, the ans[r - l + 1] will be at least nums[i]. + for num, l, r in zip(nums, prevMin, nextMin): + sz = r - l - 1 + ans[sz - 1] = max(ans[sz - 1], num) + + # ans[i] should always >= ans[i + 1..n). + for i in range(n - 2, -1, -1): + ans[i] = max(ans[i], ans[i + 1]) + + return ans diff --git a/solutions/1951. All the Pairs With the Maximum Number of Common Followers/1951.sql b/solutions/1951. All the Pairs With the Maximum Number of Common Followers/1951.sql new file mode 100644 index 00000000000..ecfad1b92e1 --- /dev/null +++ b/solutions/1951. All the Pairs With the Maximum Number of Common Followers/1951.sql @@ -0,0 +1,15 @@ +WITH + RankedRelations AS ( + SELECT + User1.user_id AS user1_id, + User2.user_id AS user2_id, + RANK() OVER(ORDER BY COUNT(User1.follower_id) DESC) AS `rank` + FROM Relations AS User1 + INNER JOIN Relations AS User2 + USING (follower_id) + WHERE User1.user_id < User2.user_id + GROUP BY 1, 2 + ) +SELECT user1_id, user2_id +FROM RankedRelations +WHERE `rank` = 1; diff --git a/solutions/1952. Three Divisors/1952.cpp b/solutions/1952. Three Divisors/1952.cpp new file mode 100644 index 00000000000..17872e4d370 --- /dev/null +++ b/solutions/1952. Three Divisors/1952.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool isThree(int n) { + if (n == 1) + return false; + // The numbers with exactly three divisors are perfect squares of a prime + // number. + const int root = sqrt(n); + return root * root == n && isPrime(root); + } + + private: + bool isPrime(int num) { + for (int i = 2; i <= sqrt(num); ++i) + if (num % i == 0) + return false; + return true; + } +}; diff --git a/solutions/1952. Three Divisors/1952.java b/solutions/1952. Three Divisors/1952.java new file mode 100644 index 00000000000..9c9f558ade2 --- /dev/null +++ b/solutions/1952. Three Divisors/1952.java @@ -0,0 +1,17 @@ +class Solution { + public boolean isThree(int n) { + if (n == 1) + return false; + // The numbers with exactly three divisors are perfect squares of a prime + // number. + final int root = (int) Math.sqrt(n); + return root * root == n && isPrime(root); + } + + private boolean isPrime(int num) { + for (int i = 2; i <= Math.sqrt(num); ++i) + if (num % i == 0) + return false; + return true; + } +} diff --git a/solutions/1952. Three Divisors/1952.py b/solutions/1952. Three Divisors/1952.py new file mode 100644 index 00000000000..0d251deb384 --- /dev/null +++ b/solutions/1952. Three Divisors/1952.py @@ -0,0 +1,10 @@ +class Solution: + def isThree(self, n: int) -> bool: + if n == 1: + return False + # The numbers with exactly three divisors are perfect squares of a prime + # number. + root = math.isqrt(n) + return root**2 == n and \ + all(root % i != 0 + for i in range(2, math.isqrt(root) + 1)) diff --git a/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.cpp b/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.cpp new file mode 100644 index 00000000000..7cc0ce04652 --- /dev/null +++ b/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + long long numberOfWeeks(vector& milestones) { + // The best strategy is to pick "max, nonMax, max, nonMax, ...". + const int mx = ranges::max(milestones); + const long sum = accumulate(milestones.begin(), milestones.end(), 0L); + const long nonMax = sum - mx; + return min(sum, 2 * nonMax + 1); + } +}; diff --git a/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.java b/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.java new file mode 100644 index 00000000000..d6aafa2f3d9 --- /dev/null +++ b/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.java @@ -0,0 +1,9 @@ +class Solution { + public long numberOfWeeks(int[] milestones) { + // The best strategy is to pick "max, nonMax, max, nonMax, ...". + final int mx = Arrays.stream(milestones).max().getAsInt(); + final long sum = Arrays.stream(milestones).asLongStream().sum(); + final long nonMax = sum - mx; + return Math.min(sum, 2 * nonMax + 1); + } +} diff --git a/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.py b/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.py new file mode 100644 index 00000000000..77876578e74 --- /dev/null +++ b/solutions/1953. Maximum Number of Weeks for Which You Can Work/1953.py @@ -0,0 +1,6 @@ +class Solution: + def numberOfWeeks(self, milestones: List[int]) -> int: + # The best strategy is to pick 'max, nonMax, max, nonMax, ...'. + summ = sum(milestones) + nonMax = summ - max(milestones) + return min(summ, 2 * nonMax + 1) diff --git a/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.cpp b/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.cpp new file mode 100644 index 00000000000..fdb2b282cf7 --- /dev/null +++ b/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + long long minimumPerimeter(long long neededApples) { + long l = 1; + long r = 100'000; // \sqrt [3] {10^{15}} + + while (l < r) { + const long m = (l + r) / 2; + if (numApples(m) >= neededApples) + r = m; + else + l = m + 1; + } + + return l * 8; + } + + private: + // Returns the number of apples at the k-th level. + // k := the level making perimeter = 8k + // p(k) := the number of apples at the k-th level on the perimeter + // n(k) := the number of apples at the k-th level not no the perimeter + // + // p(1) = 1 + 2 + // p(2) = 3 + 2 + 3 + 4 + // p(3) = 5 + 4 + 3 + 4 + 5 + 6 + // p(4) = 7 + 6 + 5 + 4 + 5 + 6 + 7 + 8 + // p(k) = k + 2(k+1) + 2(k+2) + ... + 2(k+k-1) + 2k + // = k + 2k^2 + 2*k(k-1)/2 + // = k + 2k^2 + k^2 - k = 3k^2 + // + // n(k) = p(1) + p(2) + p(3) + ... + p(k) + // = 3*1 + 3*4 + 3*9 + ... + 3*k^2 + // = 3 * (1 + 4 + 9 + ... + k^2) + // = 3 * k(k+1)(2k+1)/6 = k(k+1)(2k+1)/2 + // So, the number of apples at the k-th level should be + // k(k+1)(2k+1)/2 * 4 = 2k(k+1)(2k+1) + long numApples(long k) { + return 2 * k * (k + 1) * (2 * k + 1); + } +}; diff --git a/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.java b/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.java new file mode 100644 index 00000000000..d18449c7673 --- /dev/null +++ b/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.java @@ -0,0 +1,39 @@ +class Solution { + public long minimumPerimeter(long neededApples) { + long l = 1; + long r = 100_000; // \sqrt [3] {10^{15}} + + while (l < r) { + final long m = (l + r) / 2; + if (numApples(m) >= neededApples) + r = m; + else + l = m + 1; + } + + return l * 8; + } + + // Returns the number of apples at the k-th level. + // k := the level making perimeter = 8k + // p(k) := the number of apples at the k-th level on the perimeter + // n(k) := the number of apples at the k-th level not no the perimeter + // + // p(1) = 1 + 2 + // p(2) = 3 + 2 + 3 + 4 + // p(3) = 5 + 4 + 3 + 4 + 5 + 6 + // p(4) = 7 + 6 + 5 + 4 + 5 + 6 + 7 + 8 + // p(k) = k + 2(k+1) + 2(k+2) + ... + 2(k+k-1) + 2k + // = k + 2k^2 + 2k(k-1)/2 + // = k + 2k^2 + k^2 - k = 3k^2 + // + // n(k) = p(1) + p(2) + p(3) + ... + p(k) + // = 31 + 34 + 39 + ... + 3k^2 + // = 3 * (1 + 4 + 9 + ... + k^2) + // = 3 * k(k+1)(2k+1)/6 = k(k+1)(2k+1)/2 + // So, the number of apples at the k-th level should be + // k(k+1)(2k+1)/2 * 4 = 2k(k+1)(2k+1) + private long numApples(long k) { + return 2L * k * (k + 1) * (2 * k + 1); + } +} diff --git a/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.py b/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.py new file mode 100644 index 00000000000..8b723a36508 --- /dev/null +++ b/solutions/1954. Minimum Garden Perimeter to Collect Enough Apples/1954.py @@ -0,0 +1,28 @@ +class Solution: + def minimumPerimeter(self, neededApples: int) -> int: + def numApples(k: int) -> int: + """Returns the number of apples at the k-th level. + + k := the level making perimeter = 8k + p(k) := the number of apples at the k-th level on the perimeter + n(k) := the number of apples at the k-th level not no the perimeter + + p(1) = 1 + 2 + p(2) = 3 + 2 + 3 + 4 + p(3) = 5 + 4 + 3 + 4 + 5 + 6 + p(4) = 7 + 6 + 5 + 4 + 5 + 6 + 7 + 8 + p(k) = k + 2(k+1) + 2(k+2) + ... + 2(k+k-1) + 2k + = k + 2k^2 + 2*k(k-1)//2 + = k + 2k^2 + k^2 - k = 3k^2 + + n(k) = p(1) + p(2) + p(3) + ... + p(k) + = 3*1 + 3*4 + 3*9 + ... + 3*k^2 + = 3 * (1 + 4 + 9 + ... + k^2) + = 3 * k(k+1)(2k+1)//6 = k(k+1)(2k+1)//2 + So, the number of apples at the k-th level should be + k(k+1)(2k+1)//2 * 4 = 2k(k+1)(2k+1) + """ + return 2 * k * (k + 1) * (2 * k + 1) + + return bisect.bisect_left(range(100_000), neededApples, + key=lambda m: numApples(m)) * 8 diff --git a/solutions/1955. Count Number of Special Subsequences/1955-2.cpp b/solutions/1955. Count Number of Special Subsequences/1955-2.cpp new file mode 100644 index 00000000000..21e90e674cd --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955-2.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int countSpecialSubsequences(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + // dp[i][j] := the number of increasing subsequences of the first i numbers + // that end in j + vector> dp(n, vector(3)); + + if (nums[0] == 0) + dp[0][0] = 1; + + for (int i = 1; i < n; ++i) { + for (int ending = 0; ending < 3; ++ending) + dp[i][ending] = dp[i - 1][ending]; + + if (nums[i] == 0) + // 1. The number of the previous subsequences that end in 0. + // 2. Append a 0 to the previous subsequences that end in 0. + // 3. Start a new subsequence from this 0. + dp[i][0] = dp[i - 1][0] * 2 + 1; + else if (nums[i] == 1) + // 1. The number of the previous subsequences that end in 1. + // 2. Append a 1 to the previous subsequences that end in 1. + // 3. Append a 1 to the previous subsequences that end in 0. + dp[i][1] = dp[i - 1][1] * 2 + dp[i - 1][0]; + else // nums[i] == 2 + // 1. The number of the previous subsequences that end in 2. + // 2. Append a 2 to the previous subsequences that end in 2. + // 3. Append a 2 to the previous subsequences that end in 1. + dp[i][2] = dp[i - 1][2] * 2 + dp[i - 1][1]; + + for (int ending = 0; ending < 3; ++ending) + dp[i][ending] %= kMod; + } + + return dp.back()[2]; + } +}; diff --git a/solutions/1955. Count Number of Special Subsequences/1955-2.java b/solutions/1955. Count Number of Special Subsequences/1955-2.java new file mode 100644 index 00000000000..3bb2effd010 --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955-2.java @@ -0,0 +1,38 @@ +class Solution { + public int countSpecialSubsequences(int[] nums) { + final int kMod = 1_000_000_007; + final int n = nums.length; + // dp[i][j] := the number of increasing subsequences of the first i numbers + // that end in j + long[][] dp = new long[n][3]; + + if (nums[0] == 0) + dp[0][0] = 1; + + for (int i = 1; i < n; ++i) { + for (int ending = 0; ending < 3; ++ending) + dp[i][ending] = dp[i - 1][ending]; + + if (nums[i] == 0) + // 1. The number of the previous subsequences that end in 0. + // 2. Append a 0 to the previous subsequences that end in 0. + // 3. Start a new subsequence from this 0. + dp[i][0] = dp[i - 1][0] * 2 + 1; + else if (nums[i] == 1) + // 1. The number of the previous subsequences that end in 1. + // 2. Append a 1 to the previous subsequences that end in 1. + // 3. Append a 1 to the previous subsequences that end in 0. + dp[i][1] = dp[i - 1][1] * 2 + dp[i - 1][0]; + else // nums[i] == 2 + // 1. The number of the previous subsequences that end in 2. + // 2. Append a 2 to the previous subsequences that end in 2. + // 3. Append a 2 to the previous subsequences that end in 1. + dp[i][2] = dp[i - 1][2] * 2 + dp[i - 1][1]; + + for (int ending = 0; ending < 3; ++ending) + dp[i][ending] %= kMod; + } + + return (int) dp[n - 1][2]; + } +} diff --git a/solutions/1955. Count Number of Special Subsequences/1955-2.py b/solutions/1955. Count Number of Special Subsequences/1955-2.py new file mode 100644 index 00000000000..44776aad8d7 --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955-2.py @@ -0,0 +1,35 @@ +class Solution: + def countSpecialSubsequences(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + n = len(nums) + # dp[i][j] := the number of increasing subsequences of the first i numbers + # that end in j + dp = [[0] * 3 for _ in range(n)] + + if nums[0] == 0: + dp[0][0] = 1 + + for i in range(1, n): + for ending in range(3): + dp[i][ending] = dp[i - 1][ending] + + if nums[i] == 0: + # 1. The number of the previous subsequences that end in 0. + # 2. Append a 0 to the previous subsequences that end in 0. + # 3. Start a new subsequence from this 0. + dp[i][0] = dp[i - 1][0] * 2 + 1 + elif nums[i] == 1: + # 1. The number of the previous subsequences that end in 1. + # 2. Append a 1 to the previous subsequences that end in 1. + # 3. Append a 1 to the previous subsequences that end in 0. + dp[i][1] = dp[i - 1][1] * 2 + dp[i - 1][0] + else: # nums[i] == 2 + # 1. The number of the previous subsequences that end in 2. + # 2. Append a 2 to the previous subsequences that end in 2. + # 3. Append a 2 to the previous subsequences that end in 1. + dp[i][2] = dp[i - 1][2] * 2 + dp[i - 1][1] + + for ending in range(3): + dp[i][ending] %= kMod + + return dp[-1][2] diff --git a/solutions/1955. Count Number of Special Subsequences/1955-3.cpp b/solutions/1955. Count Number of Special Subsequences/1955-3.cpp new file mode 100644 index 00000000000..7a32645799c --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955-3.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int countSpecialSubsequences(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + // dp[j] := the number of increasing subsequences of the numbers so far that + // end in j + vector dp(3); + + if (nums[0] == 0) + dp[0] = 1; + + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) + dp[0] = dp[0] * 2 + 1; + else if (nums[i] == 1) + dp[1] = dp[1] * 2 + dp[0]; + else // nums[i] == 2 + dp[2] = dp[2] * 2 + dp[1]; + + for (int ending = 0; ending < 3; ++ending) + dp[ending] %= kMod; + } + + return dp[2]; + } +}; diff --git a/solutions/1955. Count Number of Special Subsequences/1955-3.java b/solutions/1955. Count Number of Special Subsequences/1955-3.java new file mode 100644 index 00000000000..89f571e9b0e --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955-3.java @@ -0,0 +1,26 @@ +class Solution { + public int countSpecialSubsequences(int[] nums) { + final int kMod = 1_000_000_007; + final int n = nums.length; + // dp[j] := the number of increasing subsequences of the numbers so far that + // end in j + long[] dp = new long[3]; + + if (nums[0] == 0) + dp[0] = 1; + + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) + dp[0] = dp[0] * 2 + 1; + else if (nums[i] == 1) + dp[1] = dp[1] * 2 + dp[0]; + else // nums[i] == 2 + dp[2] = dp[2] * 2 + dp[1]; + + for (int ending = 0; ending < 3; ++ending) + dp[ending] %= kMod; + } + + return (int) dp[2]; + } +} diff --git a/solutions/1955. Count Number of Special Subsequences/1955-3.py b/solutions/1955. Count Number of Special Subsequences/1955-3.py new file mode 100644 index 00000000000..7556a1401f3 --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955-3.py @@ -0,0 +1,23 @@ +class Solution: + def countSpecialSubsequences(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + n = len(nums) + # dp[j] := the number of increasing subsequences of the numbers so far that + # end in j + dp = [0] * 3 + + if nums[0] == 0: + dp[0] = 1 + + for i in range(1, n): + if nums[i] == 0: + dp[0] = dp[0] * 2 + 1 + elif nums[i] == 1: + dp[1] = dp[1] * 2 + dp[0] + else: # nums[i] == 2 + dp[2] = dp[2] * 2 + dp[1] + + for ending in range(3): + dp[ending] %= kMod + + return dp[2] diff --git a/solutions/1955. Count Number of Special Subsequences/1955.cpp b/solutions/1955. Count Number of Special Subsequences/1955.cpp new file mode 100644 index 00000000000..8e345887e97 --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int countSpecialSubsequences(vector& nums) { + vector> mem(nums.size(), vector(4, -1)); + return countSpecialSubsequences(nums, 0, -1, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of increasing subsequences of the first i numbers, where + // the previous number is `prev`. + int countSpecialSubsequences(const vector& nums, int i, int prev, + vector>& mem) { + if (i == nums.size()) + return prev == 2; + const int j = prev + 1; // Map -1/0/1/2 to 0/1/2/3 respectively. + if (mem[i][j] != -1) + return mem[i][j]; + + long res = 0; + + // Don't include `nums[i]`. + res += countSpecialSubsequences(nums, i + 1, prev, mem); + + // Include `nums[i]`. + if (nums[i] == prev) + res += countSpecialSubsequences(nums, i + 1, prev, mem); + if (prev == -1 && nums[i] == 0) + res += countSpecialSubsequences(nums, i + 1, 0, mem); + if (prev == 0 && nums[i] == 1) + res += countSpecialSubsequences(nums, i + 1, 1, mem); + if (prev == 1 && nums[i] == 2) + res += countSpecialSubsequences(nums, i + 1, 2, mem); + + res %= kMod; + return mem[i][j] = res; + } +}; diff --git a/solutions/1955. Count Number of Special Subsequences/1955.java b/solutions/1955. Count Number of Special Subsequences/1955.java new file mode 100644 index 00000000000..06930024e00 --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955.java @@ -0,0 +1,36 @@ +class Solution { + public int countSpecialSubsequences(int[] nums) { + Integer[][] mem = new Integer[nums.length][4]; + return countSpecialSubsequences(nums, 0, -1, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of increasing subsequences of the first i numbers, where + // the previous number is `prev`. + int countSpecialSubsequences(int[] nums, int i, int prev, Integer[][] mem) { + if (i == nums.length) + return prev == 2 ? 1 : 0; + final int j = prev + 1; // Map -1/0/1/2 to 0/1/2/3 respectively. + if (mem[i][j] != null) + return mem[i][j]; + + long res = 0; + + // Don't include `nums[i]`. + res += countSpecialSubsequences(nums, i + 1, prev, mem); + + // Include `nums[i]`. + if (nums[i] == prev) + res += countSpecialSubsequences(nums, i + 1, prev, mem); + if (prev == -1 && nums[i] == 0) + res += countSpecialSubsequences(nums, i + 1, 0, mem); + if (prev == 0 && nums[i] == 1) + res += countSpecialSubsequences(nums, i + 1, 1, mem); + if (prev == 1 && nums[i] == 2) + res += countSpecialSubsequences(nums, i + 1, 2, mem); + + res %= kMod; + return mem[i][j] = (int) res; + } +} diff --git a/solutions/1955. Count Number of Special Subsequences/1955.py b/solutions/1955. Count Number of Special Subsequences/1955.py new file mode 100644 index 00000000000..d586f5c127d --- /dev/null +++ b/solutions/1955. Count Number of Special Subsequences/1955.py @@ -0,0 +1,32 @@ +class Solution: + def countSpecialSubsequences(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def dp(i: int, prev: int) -> int: + """ + Returns the number of increasing subsequences of the first i numbers, + where the the previous number is j - 1. + """ + if i == len(nums): + return prev == 2 + + res = 0 + + # Don't include `nums[i]`. + res += dp(i + 1, prev) + + # Include `nums[i]`. + if nums[i] == prev: + res += dp(i + 1, prev) + if prev == -1 and nums[i] == 0: + res += dp(i + 1, 0) + if prev == 0 and nums[i] == 1: + res += dp(i + 1, 1) + if prev == 1 and nums[i] == 2: + res += dp(i + 1, 2) + + res %= kMod + return res + + return dp(0, -1) diff --git a/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.cpp b/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.cpp new file mode 100644 index 00000000000..09850dc4ff0 --- /dev/null +++ b/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minDayskVariants(vector>& points, int k) { + constexpr int kMax = 100; + int ans = INT_MAX; + + for (int a = 1; a <= kMax; ++a) + for (int b = 1; b <= kMax; ++b) { + // Stores the k minimum distances of points that can reach (a, b). + priority_queue maxHeap; + for (const vector& point : points) { + const int x = point[0]; + const int y = point[1]; + maxHeap.push(abs(x - a) + abs(y - b)); + if (maxHeap.size() > k) + maxHeap.pop(); + } + ans = min(ans, maxHeap.top()); + } + + return ans; + } +}; diff --git a/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.java b/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.java new file mode 100644 index 00000000000..279ced51d1e --- /dev/null +++ b/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.java @@ -0,0 +1,22 @@ +class Solution { + public int minDayskVariants(int[][] points, int k) { + final int kMax = 100; + int ans = Integer.MAX_VALUE; + + for (int a = 1; a <= kMax; ++a) + for (int b = 1; b <= kMax; ++b) { + // Stores the k minimum distances of points that can reach (a, b). + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + for (int[] point : points) { + final int x = point[0]; + final int y = point[1]; + maxHeap.offer(Math.abs(x - a) + Math.abs(y - b)); + if (maxHeap.size() > k) + maxHeap.poll(); + } + ans = Math.min(ans, maxHeap.peek()); + } + + return ans; + } +} diff --git a/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.py b/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.py new file mode 100644 index 00000000000..9620b72def6 --- /dev/null +++ b/solutions/1956. Minimum Time For K Virus Variants to Spread/1956.py @@ -0,0 +1,16 @@ +class Solution: + def minDayskVariants(self, points: List[List[int]], k: int) -> int: + kMax = 100 + ans = math.inf + + for a in range(1, kMax + 1): + for b in range(1, kMax + 1): + # Stores the k minimum distances of points that can reach (a, b). + maxHeap = [] + for x, y in points: + heapq.heappush(maxHeap, -abs(x - a) + -abs(y - b)) + if len(maxHeap) > k: + heapq.heappop(maxHeap) + ans = min(ans, -maxHeap[0]) + + return ans diff --git a/solutions/1957. Delete Characters to Make Fancy String/1957.cpp b/solutions/1957. Delete Characters to Make Fancy String/1957.cpp new file mode 100644 index 00000000000..21ac2ea70d9 --- /dev/null +++ b/solutions/1957. Delete Characters to Make Fancy String/1957.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + string makeFancyString(string s) { + string ans; + for (const char c : s) + if (ans.length() < 2 || ans.back() != c || ans[ans.size() - 2] != c) + ans.push_back(c); + return ans; + } +}; diff --git a/solutions/1957. Delete Characters to Make Fancy String/1957.java b/solutions/1957. Delete Characters to Make Fancy String/1957.java new file mode 100644 index 00000000000..52c9bbb01ca --- /dev/null +++ b/solutions/1957. Delete Characters to Make Fancy String/1957.java @@ -0,0 +1,10 @@ +class Solution { + public String makeFancyString(String s) { + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) + if (sb.length() < 2 || // + sb.charAt(sb.length() - 1) != c || sb.charAt(sb.length() - 2) != c) + sb.append(c); + return sb.toString(); + } +} diff --git a/solutions/1957. Delete Characters to Make Fancy String/1957.py b/solutions/1957. Delete Characters to Make Fancy String/1957.py new file mode 100644 index 00000000000..969d6832e56 --- /dev/null +++ b/solutions/1957. Delete Characters to Make Fancy String/1957.py @@ -0,0 +1,7 @@ +class Solution: + def makeFancyString(self, s: str) -> str: + ans = [] + for c in s: + if len(ans) < 2 or ans[-1] != c or ans[-2] != c: + ans.append(c) + return ''.join(ans) diff --git a/solutions/1958. Check if Move is Legal/1958.cpp b/solutions/1958. Check if Move is Legal/1958.cpp new file mode 100644 index 00000000000..c9e160d8b42 --- /dev/null +++ b/solutions/1958. Check if Move is Legal/1958.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool checkMove(vector>& board, int rMove, int cMove, + char color) { + const vector> dirs{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, + {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + + for (const auto& [dx, dy] : dirs) { + int cellsCount = 2; + int i = rMove + dx; + int j = cMove + dy; + while (0 <= i && i < 8 && 0 <= j && j < 8) { + // There are no free cells in between. + if (board[i][j] == '.') + break; + // Need >= 3 cells. + if (cellsCount == 2 && board[i][j] == color) + break; + // >= 3 cells. + if (board[i][j] == color) + return true; + i += dx; + j += dy; + ++cellsCount; + } + } + + return false; + } +}; diff --git a/solutions/1958. Check if Move is Legal/1958.java b/solutions/1958. Check if Move is Legal/1958.java new file mode 100644 index 00000000000..6c16ac5b50d --- /dev/null +++ b/solutions/1958. Check if Move is Legal/1958.java @@ -0,0 +1,29 @@ +class Solution { + public boolean checkMove(char[][] board, int rMove, int cMove, char color) { + final int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + + for (int k = 0; k < 8; ++k) { + final int dx = dir[0][0]; + final int dy = dir[0][1]; + int cellsCount = 2; + int i = rMove + dx; + int j = cMove + dy; + while (0 <= i && i < 8 && 0 <= j && j < 8) { + // There are no free cells in between. + if (board[i][j] == '.') + break; + // Need >= 3 cells. + if (cellsCount == 2 && board[i][j] == color) + break; + // >= 3 cells. + if (board[i][j] == color) + return true; + i += dx; + j += dy; + ++cellsCount; + } + } + + return false; + } +} diff --git a/solutions/1958. Check if Move is Legal/1958.py b/solutions/1958. Check if Move is Legal/1958.py new file mode 100644 index 00000000000..0081889c5f5 --- /dev/null +++ b/solutions/1958. Check if Move is Legal/1958.py @@ -0,0 +1,24 @@ +class Solution: + def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool: + dirs = ((-1, -1), (-1, 0), (-1, 1), (0, -1), + (0, 1), (1, -1), (1, 0), (1, 1)) + + for dx, dy in dirs: + cellsCount = 2 + i = rMove + dx + j = cMove + dy + while 0 <= i < 8 and 0 <= j < 8: + # There are no free cells in between. + if board[i][j] == '.': + break + # Need >= 3 cells. + if cellsCount == 2 and board[i][j] == color: + break + # >= 3 cells. + if board[i][j] == color: + return True + i += dx + j += dy + cellsCount += 1 + + return False diff --git a/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.cpp b/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.cpp new file mode 100644 index 00000000000..a101fe5e5de --- /dev/null +++ b/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minSpaceWastedKResizing(vector& nums, int k) { + vector> mem(nums.size(), vector(k + 1, -1)); + return minSpaceWasted(nums, 0, k, mem); + } + + private: + static constexpr int kMax = 200'000'000; + + // Returns the minimum space wasted for nums[i..n) if you can resize k times. + int minSpaceWasted(const vector& nums, int i, int k, + vector>& mem) { + if (i == nums.size()) + return 0; + if (k == -1) + return kMax; + if (mem[i][k] != -1) + return mem[i][k]; + + int res = kMax; + int sum = 0; + int maxNum = nums[i]; + + for (int j = i; j < nums.size(); ++j) { + sum += nums[j]; + maxNum = max(maxNum, nums[j]); + const int wasted = maxNum * (j - i + 1) - sum; + res = min(res, minSpaceWasted(nums, j + 1, k - 1, mem) + wasted); + } + + return mem[i][k] = res; + } +}; diff --git a/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.java b/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.java new file mode 100644 index 00000000000..d57d1fff7c0 --- /dev/null +++ b/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.java @@ -0,0 +1,31 @@ +class Solution { + public int minSpaceWastedKResizing(int[] nums, int k) { + Integer[][] mem = new Integer[nums.length][k + 1]; + return minSpaceWasted(nums, 0, k, mem); + } + + private static final int kMax = 200_000_000; + + // Returns the minimum space wasted for nums[i..n) if you can resize k times. + private int minSpaceWasted(int[] nums, int i, int k, Integer[][] mem) { + if (i == nums.length) + return 0; + if (k == -1) + return kMax; + if (mem[i][k] != null) + return mem[i][k]; + + int res = kMax; + int sum = 0; + int maxNum = nums[i]; + + for (int j = i; j < nums.length; ++j) { + sum += nums[j]; + maxNum = Math.max(maxNum, nums[j]); + final int wasted = maxNum * (j - i + 1) - sum; + res = Math.min(res, minSpaceWasted(nums, j + 1, k - 1, mem) + wasted); + } + + return mem[i][k] = res; + } +} diff --git a/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.py b/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.py new file mode 100644 index 00000000000..d7015254c02 --- /dev/null +++ b/solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.py @@ -0,0 +1,27 @@ +class Solution: + def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int: + kMax = 200_000_000 + + @functools.lru_cache(None) + def dp(i: int, k: int) -> int: + """ + Returns the minimum space wasted for nums[i..n) if you can resize k times. + """ + if i == len(nums): + return 0 + if k == -1: + return kMax + + res = kMax + summ = 0 + maxNum = nums[i] + + for j in range(i, len(nums)): + summ += nums[j] + maxNum = max(maxNum, nums[j]) + wasted = maxNum * (j - i + 1) - summ + res = min(res, dp(j + 1, k - 1) + wasted) + + return res + + return dp(0, k) diff --git a/solutions/196. Delete Duplicate Emails/196.sql b/solutions/196. Delete Duplicate Emails/196.sql new file mode 100644 index 00000000000..1ac1362c806 --- /dev/null +++ b/solutions/196. Delete Duplicate Emails/196.sql @@ -0,0 +1,5 @@ +DELETE P2 +FROM Person AS P1 +INNER JOIN Person AS P2 + ON (P1.email = P2.email) +WHERE P1.id < P2.id; diff --git a/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.cpp b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.cpp new file mode 100644 index 00000000000..339f9813750 --- /dev/null +++ b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.cpp @@ -0,0 +1,72 @@ +class Solution { + public: + long long maxProduct(string s) { + const int n = s.length(); + long ans = 1; + vector pow(n + 1); // pow[i] := kBase^i + vector hashFromL(n + 1); // hashFromL[i] = the hash of s[0..i) + vector hashFromR(n + 1); // hashFromR[i] = the hash of s[i..n) + vector l(n); // l[i] := the maximum length of palindromes in s[0..i) + vector r(n); // r[i] := the maximum length of palindromes in s[i..n) + + pow[0] = 1; + for (int i = 1; i <= n; ++i) + pow[i] = pow[i - 1] * kBase % kMod; + + for (int i = 1; i <= n; ++i) + hashFromL[i] = (hashFromL[i - 1] * kBase + val(s[i - 1])) % kMod; + + for (int i = n - 1; i >= 0; --i) + hashFromR[i] = (hashFromR[i + 1] * kBase + val(s[i])) % kMod; + + int mx = 1; // the maximum length of palindromes so far + for (int i = 0; i < n; i++) { + if (i - mx - 1 >= 0 && + isPalindrome(i - mx - 1, i + 1, hashFromL, hashFromR, pow)) + mx += 2; + l[i] = mx; + } + + // Fill in r. + mx = 1; + for (int i = n - 1; i >= 0; i--) { + if (i + mx + 2 <= n && + isPalindrome(i, i + mx + 2, hashFromL, hashFromR, pow)) + mx += 2; + r[i] = mx; + } + + for (int i = 0; i + 1 < n; ++i) + ans = max(ans, static_cast(l[i]) * r[i + 1]); + + return ans; + } + + private: + static constexpr int kBase = 26; + static constexpr int kMod = 1'000'000'007; + + // Returns true if s[l..r) is a palindrome. + bool isPalindrome(int l, int r, const vector& hashFromL, + const vector& hashFromR, const vector& pow) { + return leftHash(l, r, hashFromL, pow) == rightHash(l, r, hashFromR, pow); + } + + // Returns the hash of s[l..r) from the left. + long leftHash(int l, int r, const vector& hashFromL, + const vector& pow) { + const long hash = (hashFromL[r] - hashFromL[l] * pow[r - l]) % kMod; + return hash < 0 ? hash + kMod : hash; + } + + // Returns the hash of s[l..r) from the right. + long rightHash(int l, int r, const vector& hashFromR, + const vector& pow) { + const long hash = (hashFromR[l] - hashFromR[r] * pow[r - l]) % kMod; + return hash < 0 ? hash + kMod : hash; + } + + constexpr int val(char c) { + return c - 'a'; + } +}; diff --git a/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.java b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.java new file mode 100644 index 00000000000..df57de4f61c --- /dev/null +++ b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.java @@ -0,0 +1,65 @@ +class Solution { + public long maxProduct(String s) { + final int n = s.length(); + long ans = 1; + long[] pow = new long[n + 1]; // pow[i] := kBase^i + long[] hashFromL = new long[n + 1]; // hashFromL[i] = the hash of s[0..i) + long[] hashFromR = new long[n + 1]; // hashFromR[i] = the hash of s[i..n) + int[] l = new int[n]; // l[i] := the maximum length of palindromes in s[0..i) + int[] r = new int[n]; // r[i] := the maximum length of palindromes in s[i..n) + + pow[0] = 1; + for (int i = 1; i <= n; ++i) + pow[i] = pow[i - 1] * kBase % kMod; + + for (int i = 1; i <= n; ++i) + hashFromL[i] = (hashFromL[i - 1] * kBase + val(s.charAt(i - 1))) % kMod; + + for (int i = n - 1; i >= 0; --i) + hashFromR[i] = (hashFromR[i + 1] * kBase + val(s.charAt(i))) % kMod; + + int mx = 1; // the maximum length of palindromes so far + for (int i = 0; i < n; i++) { + if (i - mx - 1 >= 0 && isPalindrome(i - mx - 1, i + 1, hashFromL, hashFromR, pow)) + mx += 2; + l[i] = mx; + } + + // Fill in r. + mx = 1; + for (int i = n - 1; i >= 0; i--) { + if (i + mx + 2 <= n && isPalindrome(i, i + mx + 2, hashFromL, hashFromR, pow)) + mx += 2; + r[i] = mx; + } + + for (int i = 0; i + 1 < n; ++i) + ans = Math.max(ans, (long) l[i] * r[i + 1]); + + return ans; + } + + private static final int kBase = 26; + private static final int kMod = 1_000_000_007; + + // Returns true if s[l..r) is a palindrome. + private boolean isPalindrome(int l, int r, long[] hashFromL, long[] hashFromR, long[] pow) { + return leftHash(l, r, hashFromL, pow) == rightHash(l, r, hashFromR, pow); + } + + // Returns the hash of s[l..r) from the left. + private long leftHash(int l, int r, long[] hashFromL, long[] pow) { + final long hash = (hashFromL[r] - hashFromL[l] * pow[r - l]) % kMod; + return hash < 0 ? hash + kMod : hash; + } + + // Returns the hash of s[l..r) from the right. + private long rightHash(int l, int r, long[] hashFromR, long[] pow) { + final long hash = (hashFromR[l] - hashFromR[r] * pow[r - l]) % kMod; + return hash < 0 ? hash + kMod : hash; + } + + private int val(char c) { + return c - 'a'; + } +} diff --git a/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.py b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.py new file mode 100644 index 00000000000..53e50b3425f --- /dev/null +++ b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960-2.py @@ -0,0 +1,55 @@ +class Solution: + def maxProduct(self, s: str) -> int: + kBase = 26 + kMod = 1_000_000_007 + n = len(s) + ans = 1 + pow = [1] + [0] * n # pow[i] := kBase^i + hashFromL = [0] * (n + 1) # hashFromL[i] = the hash of s[0..i) + hashFromR = [0] * (n + 1) # hashFromR[i] = the hash of s[i..n) + l = [0] * n # l[i] := the maximum length of palindromes in s[0..i) + r = [0] * n # r[i] := the maximum length of palindromes in s[i..n) + + for i in range(1, n + 1): + pow[i] = pow[i - 1] * kBase % kMod + + def val(c: str) -> int: + return ord(c) - ord('a') + + for i in range(1, n + 1): + hashFromL[i] = (hashFromL[i - 1] * kBase + val(s[i - 1])) % kMod + + for i in reversed(range(n)): + hashFromR[i] = (hashFromR[i + 1] * kBase + val(s[i])) % kMod + + # Returns the hash of s[l..r) from the left. + def leftHash(l: int, r: int) -> int: + hash = (hashFromL[r] - hashFromL[l] * pow[r - l]) % kMod + return hash + kMod if hash < 0 else hash + + # Returns the hash of s[l..r) from the right. + def rightHash(l: int, r: int) -> int: + hash = (hashFromR[l] - hashFromR[r] * pow[r - l]) % kMod + return hash + kMod if hash < 0 else hash + + def isPalindrome(l: int, r: int) -> bool: + """Returns True if s[l..r) is a palindrome.""" + return leftHash(l, r) == rightHash(l, r) + + mx = 1 # the maximum length of palindromes so far + for i in range(n): + if i - mx - 1 >= 0 and isPalindrome(i - mx - 1, i + 1): + mx += 2 + l[i] = mx + + # Fill in r. + mx = 1 + for i in reversed(range(n)): + if i + mx + 2 <= n and isPalindrome(i, i + mx + 2): + mx += 2 + r[i] = mx + + for i in range(n - 1): + ans = max(ans, l[i] * r[i + 1]) + + return ans diff --git a/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.cpp b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.cpp new file mode 100644 index 00000000000..51b7b472970 --- /dev/null +++ b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + long long maxProduct(string s) { + const int n = s.length(); + long ans = 1; + // l[i] := the maximum length of palindromes in s[0..i) + vector l = manacher(s, n); + // r[i] := the maximum length of palindromes in s[i..n) + vector r = manacher(string(s.rbegin(), s.rend()), n); + reverse(r.begin(), r.end()); + + for (int i = 0; i + 1 < n; ++i) + ans = max(ans, static_cast(l[i]) * r[i + 1]); + + return ans; + } + + private: + vector manacher(const string& s, int n) { + vector maxExtends(n); + vector l2r(n, 1); + int center = 0; + + for (int i = 0; i < n; ++i) { + const int r = center + maxExtends[center] - 1; + const int mirrorIndex = center - (i - center); + int extend = i > r ? 1 : min(maxExtends[mirrorIndex], r - i + 1); + while (i - extend >= 0 && i + extend < n && + s[i - extend] == s[i + extend]) { + l2r[i + extend] = 2 * extend + 1; + ++extend; + } + maxExtends[i] = extend; + if (i + maxExtends[i] >= r) + center = i; + } + + for (int i = 1; i < n; ++i) + l2r[i] = max(l2r[i], l2r[i - 1]); + + return l2r; + } +}; diff --git a/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.java b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.java new file mode 100644 index 00000000000..a44acb991c2 --- /dev/null +++ b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.java @@ -0,0 +1,53 @@ +class Solution { + public long maxProduct(String s) { + final int n = s.length(); + long ans = 1; + // l[i] := the maximum length of palindromes in s[0..i) + int[] l = manacher(s, n); + // r[i] := the maximum length of palindromes in s[i..n) + int[] r = manacher(new StringBuilder(s).reverse().toString(), n); + + reverse(r, 0, n - 1); + + for (int i = 0; i + 1 < n; ++i) + ans = Math.max(ans, (long) l[i] * r[i + 1]); + + return ans; + } + + private int[] manacher(final String s, int n) { + int[] maxExtends = new int[n]; + int[] l2r = new int[n]; + Arrays.fill(l2r, 1); + int center = 0; + + for (int i = 0; i < n; ++i) { + final int r = center + maxExtends[center] - 1; + final int mirrorIndex = center - (i - center); + int extend = i > r ? 1 : Math.min(maxExtends[mirrorIndex], r - i + 1); + while (i - extend >= 0 && i + extend < n && s.charAt(i - extend) == s.charAt(i + extend)) { + l2r[i + extend] = 2 * extend + 1; + ++extend; + } + maxExtends[i] = extend; + if (i + maxExtends[i] >= r) + center = i; + } + + for (int i = 1; i < n; ++i) + l2r[i] = Math.max(l2r[i], l2r[i - 1]); + + return l2r; + } + + private void reverse(int[] A, int l, int r) { + while (l < r) + swap(A, l++, r--); + } + + private void swap(int[] A, int i, int j) { + final int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} diff --git a/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.py b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.py new file mode 100644 index 00000000000..2e75c5a2a63 --- /dev/null +++ b/solutions/1960. Maximum Product of the Length of Two Palindromic Substrings/1960.py @@ -0,0 +1,30 @@ +class Solution: + def maxProduct(self, s: str) -> int: + n = len(s) + + def manacher(s: str) -> List[int]: + maxExtends = [0] * n + l2r = [1] * n + center = 0 + + for i in range(n): + r = center + maxExtends[center] - 1 + mirrorIndex = center - (i - center) + extend = 1 if i > r else min(maxExtends[mirrorIndex], r - i + 1) + while i - extend >= 0 and i + extend < n and s[i - extend] == s[i + extend]: + l2r[i + extend] = 2 * extend + 1 + extend += 1 + maxExtends[i] = extend + if i + maxExtends[i] >= r: + center = i + + for i in range(1, n): + l2r[i] = max(l2r[i], l2r[i - 1]) + + return l2r + + # l[i] := the maximum length of palindromes in s[0..i) + l = manacher(s) + # r[i] := the maximum length of palindromes in s[i..n) + r = manacher(s[::-1])[::-1] + return max(l[i] * r[i + 1] for i in range(n - 1)) diff --git a/solutions/1961. Check If String Is a Prefix of Array/1961.cpp b/solutions/1961. Check If String Is a Prefix of Array/1961.cpp new file mode 100644 index 00000000000..cf489af3db5 --- /dev/null +++ b/solutions/1961. Check If String Is a Prefix of Array/1961.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool isPrefixString(string s, vector& words) { + string prefix; + for (const string& word : words) { + prefix += word; + if (prefix == s) + return true; + } + return false; + } +}; diff --git a/solutions/1961. Check If String Is a Prefix of Array/1961.java b/solutions/1961. Check If String Is a Prefix of Array/1961.java new file mode 100644 index 00000000000..48fc49fd540 --- /dev/null +++ b/solutions/1961. Check If String Is a Prefix of Array/1961.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isPrefixString(String s, String[] words) { + StringBuilder sb = new StringBuilder(); + for (final String word : words) { + sb.append(word); + // Do not call `toString()` unless the length matches. + if (sb.length() == s.length() && sb.toString().equals(s)) + return true; + } + return false; + } +} diff --git a/solutions/1961. Check If String Is a Prefix of Array/1961.py b/solutions/1961. Check If String Is a Prefix of Array/1961.py new file mode 100644 index 00000000000..60db33d46b7 --- /dev/null +++ b/solutions/1961. Check If String Is a Prefix of Array/1961.py @@ -0,0 +1,8 @@ +class Solution: + def isPrefixString(self, s: str, words: List[str]) -> bool: + prefix = [] + for word in words: + prefix.append(word) + if ''.join(prefix) == s: + return True + return False diff --git a/solutions/1962. Remove Stones to Minimize the Total/1962.cpp b/solutions/1962. Remove Stones to Minimize the Total/1962.cpp new file mode 100644 index 00000000000..dad3280af8d --- /dev/null +++ b/solutions/1962. Remove Stones to Minimize the Total/1962.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minStoneSum(vector& piles, int k) { + int ans = accumulate(piles.begin(), piles.end(), 0); + priority_queue maxHeap; + + for (const int pile : piles) + maxHeap.push(pile); + + for (int i = 0; i < k; ++i) { + const int maxPile = maxHeap.top(); + maxHeap.pop(); + maxHeap.push(maxPile - maxPile / 2); + ans -= maxPile / 2; + } + + return ans; + } +}; diff --git a/solutions/1962. Remove Stones to Minimize the Total/1962.java b/solutions/1962. Remove Stones to Minimize the Total/1962.java new file mode 100644 index 00000000000..85fe67a5537 --- /dev/null +++ b/solutions/1962. Remove Stones to Minimize the Total/1962.java @@ -0,0 +1,17 @@ +class Solution { + public int minStoneSum(int[] piles, int k) { + int ans = Arrays.stream(piles).sum(); + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + for (final int pile : piles) + maxHeap.offer(pile); + + for (int i = 0; i < k; ++i) { + final int maxPile = maxHeap.poll(); + maxHeap.offer(maxPile - maxPile / 2); + ans -= maxPile / 2; + } + + return ans; + } +} diff --git a/solutions/1962. Remove Stones to Minimize the Total/1962.py b/solutions/1962. Remove Stones to Minimize the Total/1962.py new file mode 100644 index 00000000000..22330ac9b13 --- /dev/null +++ b/solutions/1962. Remove Stones to Minimize the Total/1962.py @@ -0,0 +1,9 @@ +class Solution: + def minStoneSum(self, piles: List[int], k: int) -> int: + maxHeap = [-pile for pile in piles] + heapq.heapify(maxHeap) + + for _ in range(k): + heapq.heapreplace(maxHeap, maxHeap[0] // 2) + + return -sum(maxHeap) diff --git a/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.cpp b/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.cpp new file mode 100644 index 00000000000..37031d6c021 --- /dev/null +++ b/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minSwaps(string s) { + // Cancel out all the matched pairs, then we'll be left with "]]]..[[[". + // The answer is ceil(the number of unmatched pairs / 2). + int unmatched = 0; + + for (const char c : s) + if (c == '[') + ++unmatched; + else if (unmatched > 0) // c == ']' and there's a match. + --unmatched; + + return (unmatched + 1) / 2; + } +}; diff --git a/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.java b/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.java new file mode 100644 index 00000000000..fc4f2924b80 --- /dev/null +++ b/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.java @@ -0,0 +1,15 @@ +class Solution { + public int minSwaps(String s) { + // Cancel out all the matched pairs, then we'll be left with "]]]..[[[". + // The answer is ceil(the number of unmatched pairs / 2). + int unmatched = 0; + + for (final char c : s.toCharArray()) + if (c == '[') + ++unmatched; + else if (unmatched > 0) // c == ']' and there's a match. + --unmatched; + + return (unmatched + 1) / 2; + } +} diff --git a/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.py b/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.py new file mode 100644 index 00000000000..2ec195bdc6b --- /dev/null +++ b/solutions/1963. Minimum Number of Swaps to Make the String Balanced/1963.py @@ -0,0 +1,13 @@ +class Solution: + def minSwaps(self, s: str) -> int: + # Cancel out all the matched pairs, then we'll be left with ']]]..[[['. + # The answer is ceil(# of unmatched pairs // 2). + unmatched = 0 + + for c in s: + if c == '[': + unmatched += 1 + elif unmatched > 0: # c == ']' and there's a match. + unmatched -= 1 + + return (unmatched + 1) // 2 diff --git a/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.cpp b/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.cpp new file mode 100644 index 00000000000..b4c214c5d70 --- /dev/null +++ b/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + // Similar to 300. Longest Increasing Subsequence + vector longestObstacleCourseAtEachPosition(vector& obstacles) { + vector ans; + // tail[i] := the minimum tail of all the increasing subsequences having + // length i + 1 + vector tail; + + for (const int obstacle : obstacles) + if (tail.empty() || obstacle >= tail.back()) { + tail.push_back(obstacle); + ans.push_back(tail.size()); + } else { + const int index = firstGreater(tail, obstacle); + tail[index] = obstacle; + ans.push_back(index + 1); + } + + return ans; + } + + private: + int firstGreater(const vector& A, int target) { + return ranges::upper_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.java b/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.java new file mode 100644 index 00000000000..042575ea3b8 --- /dev/null +++ b/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.java @@ -0,0 +1,34 @@ +class Solution { + // Similar to 300. Longest Increasing Subsequence + public int[] longestObstacleCourseAtEachPosition(int[] obstacles) { + List ans = new ArrayList<>(); + // tail[i] := the minimum tail of all the increasing subsequences with + // length i + 1 + List tail = new ArrayList<>(); + + for (final int obstacle : obstacles) + if (tail.isEmpty() || obstacle >= tail.get(tail.size() - 1)) { + tail.add(obstacle); + ans.add(tail.size()); + } else { + final int index = firstGreater(tail, obstacle); + tail.set(index, obstacle); + ans.add(index + 1); + } + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private int firstGreater(List A, int target) { + int l = 0; + int r = A.size(); + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m) > target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.py b/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.py new file mode 100644 index 00000000000..54b20873099 --- /dev/null +++ b/solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.py @@ -0,0 +1,18 @@ +class Solution: + # Similar to 300. Longest Increasing Subsequence + def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]: + ans = [] + # tail[i] := the minimum tail of all the increasing subsequences having + # length i + 1 + tail = [] + + for obstacle in obstacles: + if not tail or obstacle >= tail[-1]: + tail.append(obstacle) + ans.append(len(tail)) + else: + index = bisect.bisect_right(tail, obstacle) + tail[index] = obstacle + ans.append(index + 1) + + return ans diff --git a/solutions/1965. Employees With Missing Information/1965.sql b/solutions/1965. Employees With Missing Information/1965.sql new file mode 100644 index 00000000000..bae465e07fa --- /dev/null +++ b/solutions/1965. Employees With Missing Information/1965.sql @@ -0,0 +1,12 @@ +SELECT Employees.employee_id +FROM Employees +LEFT JOIN Salaries + USING (employee_id) +WHERE Salaries.salary IS NULL +UNION ALL +SELECT Salaries.employee_id +FROM Salaries +LEFT JOIN Employees + USING (employee_id) +WHERE Employees.name IS NULL +ORDER BY 1; diff --git a/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.cpp b/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.cpp new file mode 100644 index 00000000000..3d84e25a192 --- /dev/null +++ b/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int binarySearchableNumbers(vector& nums) { + const int n = nums.size(); + int ans = 0; + // prefixMaxs[i] := max(nums[0..i)) + vector prefixMaxs(n); + // suffixMins[i] := min(nums[i + 1..n)) + vector suffixMins(n); + + // Fill in `prefixMaxs`. + prefixMaxs[0] = INT_MIN; + for (int i = 1; i < n; ++i) + prefixMaxs[i] = max(prefixMaxs[i - 1], nums[i - 1]); + + // Fill in `suffixMins`. + suffixMins[n - 1] = INT_MAX; + for (int i = n - 2; i >= 0; --i) + suffixMins[i] = min(suffixMins[i + 1], nums[i + 1]); + + for (int i = 0; i < n; ++i) + if (prefixMaxs[i] < nums[i] && nums[i] < suffixMins[i]) + ++ans; + + return ans; + } +}; diff --git a/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.java b/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.java new file mode 100644 index 00000000000..8f4e069a766 --- /dev/null +++ b/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.java @@ -0,0 +1,26 @@ +class Solution { + public int binarySearchableNumbers(int[] nums) { + final int n = nums.length; + int ans = 0; + // prefixMaxs[i] := Math.max(nums[0..i)) + int[] prefixMaxs = new int[n]; + // suffixMins[i] := Math.min(nums[i + 1..n)) + int[] suffixMins = new int[n]; + + // Fill in `prefixMaxs`. + prefixMaxs[0] = Integer.MIN_VALUE; + for (int i = 1; i < n; ++i) + prefixMaxs[i] = Math.max(prefixMaxs[i - 1], nums[i - 1]); + + // Fill in `suffixMins`. + suffixMins[n - 1] = Integer.MAX_VALUE; + for (int i = n - 2; i >= 0; --i) + suffixMins[i] = Math.min(suffixMins[i + 1], nums[i + 1]); + + for (int i = 0; i < n; ++i) + if (prefixMaxs[i] < nums[i] && nums[i] < suffixMins[i]) + ++ans; + + return ans; + } +} diff --git a/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.py b/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.py new file mode 100644 index 00000000000..730c13d5949 --- /dev/null +++ b/solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.py @@ -0,0 +1,19 @@ +class Solution: + def binarySearchableNumbers(self, nums: List[int]) -> int: + n = len(nums) + # prefixMaxs[i] := max(nums[0..i)) + prefixMaxs = [0] * n + # suffixMins[i] := min(nums[i + 1..n)) + suffixMins = [0] * n + + # Fill in `prefixMaxs`. + prefixMaxs[0] = -math.inf + for i in range(1, n): + prefixMaxs[i] = max(prefixMaxs[i - 1], nums[i - 1]) + + # Fill in `suffixMins`. + suffixMins[n - 1] = math.inf + for i in range(n - 2, -1, -1): + suffixMins[i] = min(suffixMins[i + 1], nums[i + 1]) + + return sum(prefixMaxs[i] < nums[i] < suffixMins[i] for i in range(n)) diff --git a/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.cpp b/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.cpp new file mode 100644 index 00000000000..6b91990b0f8 --- /dev/null +++ b/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int numOfStrings(vector& patterns, string word) { + return ranges::count_if(patterns, [&word](const string& pattern) { + return word.find(pattern) != word.npos; + }); + } +}; diff --git a/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.java b/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.java new file mode 100644 index 00000000000..da301e6c28c --- /dev/null +++ b/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.java @@ -0,0 +1,5 @@ +class Solution { + public int numOfStrings(String[] patterns, String word) { + return (int) Arrays.stream(patterns).filter(pattern -> word.contains(pattern)).count(); + } +} diff --git a/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.py b/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.py new file mode 100644 index 00000000000..a7d17ac754b --- /dev/null +++ b/solutions/1967. Number of Strings That Appear as Substrings in Word/1967.py @@ -0,0 +1,3 @@ +class Solution: + def numOfStrings(self, patterns: List[str], word: str) -> int: + return sum(pattern in word for pattern in patterns) diff --git a/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.cpp b/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.cpp new file mode 100644 index 00000000000..45e3e302846 --- /dev/null +++ b/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + vector rearrangeArray(vector& nums) { + ranges::sort(nums); + for (int i = 1; i < nums.size(); i += 2) + swap(nums[i], nums[i - 1]); + return nums; + } +}; diff --git a/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.java b/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.java new file mode 100644 index 00000000000..aceba00e725 --- /dev/null +++ b/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.java @@ -0,0 +1,11 @@ +class Solution { + public int[] rearrangeArray(int[] nums) { + Arrays.sort(nums); + for (int i = 1; i < nums.length; i += 2) { + final int temp = nums[i]; + nums[i] = nums[i - 1]; + nums[i - 1] = temp; + } + return nums; + } +} diff --git a/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.py b/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.py new file mode 100644 index 00000000000..035f0d6a4b7 --- /dev/null +++ b/solutions/1968. Array With Elements Not Equal to Average of Neighbors/1968.py @@ -0,0 +1,6 @@ +class Solution: + def rearrangeArray(self, nums: List[int]) -> List[int]: + nums.sort() + for i in range(1, len(nums), 2): + nums[i], nums[i - 1] = nums[i - 1], nums[i] + return nums diff --git a/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.cpp b/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.cpp new file mode 100644 index 00000000000..6cec5f4964e --- /dev/null +++ b/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minNonZeroProduct(int p) { + // Can always turn [1..2^p - 1] to [1, 1, ..., 2^p - 2, 2^p - 2, 2^p - 1]. + const long n = 1L << p; + const long halfCount = n / 2 - 1; + return modPow(n - 2, halfCount) * ((n - 1) % kMod) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1L; + x %= kMod; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x, n / 2) % kMod; + } +}; diff --git a/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.java b/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.java new file mode 100644 index 00000000000..431ce4595c1 --- /dev/null +++ b/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.java @@ -0,0 +1,19 @@ +class Solution { + public int minNonZeroProduct(int p) { + // Can always turn [1..2^p - 1] to [1, 1, ..., 2^p - 2, 2^p - 2, 2^p - 1]. + final long n = 1L << p; + final long halfCount = n / 2 - 1; + return (int) (modPow(n - 2, halfCount) * ((n - 1) % kMod) % kMod); + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1L; + x %= kMod; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x, n / 2) % kMod; + } +} diff --git a/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.py b/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.py new file mode 100644 index 00000000000..da86afd207f --- /dev/null +++ b/solutions/1969. Minimum Non-Zero Product of the Array Elements/1969.py @@ -0,0 +1,7 @@ +class Solution: + def minNonZeroProduct(self, p: int) -> int: + kMod = 1_000_000_007 + # Can always turn [1..2^p - 1] to [1, 1, ..., 2^p - 2, 2^p - 2, 2^p - 1]. + n = 1 << p + halfCount = n // 2 - 1 + return pow(n - 2, halfCount, kMod) * ((n - 1) % kMod) % kMod diff --git a/solutions/197. Rising Temperature/197.sql b/solutions/197. Rising Temperature/197.sql new file mode 100644 index 00000000000..d14b1d5d878 --- /dev/null +++ b/solutions/197. Rising Temperature/197.sql @@ -0,0 +1,5 @@ +SELECT Today.id +FROM Weather AS Today +INNER JOIN Weather AS Yesterday + ON (DATE_SUB(Today.recordDate, INTERVAL 1 DAY) = Yesterday.recordDate) +WHERE Today.temperature > Yesterday.temperature; diff --git a/solutions/1970. Last Day Where You Can Still Cross/1970.cpp b/solutions/1970. Last Day Where You Can Still Cross/1970.cpp new file mode 100644 index 00000000000..5b775103a02 --- /dev/null +++ b/solutions/1970. Last Day Where You Can Still Cross/1970.cpp @@ -0,0 +1,59 @@ +class Solution { + public: + int latestDayToCross(int row, int col, vector>& cells) { + int ans = 0; + int l = 1; + int r = cells.size() - 1; + + while (l <= r) { + const int m = (l + r) / 2; + if (canWalk(m, row, col, cells)) { + ans = m; + l = m + 1; + } else { + r = m - 1; + } + } + + return ans; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + bool canWalk(int day, int row, int col, const vector>& cells) { + vector> matrix(row, vector(col)); + for (int i = 0; i < day; ++i) { + const int x = cells[i][0] - 1; + const int y = cells[i][1] - 1; + matrix[x][y] = 1; + } + + queue> q; + + for (int j = 0; j < col; ++j) + if (matrix[0][j] == 0) { + q.emplace(0, j); + matrix[0][j] = 1; + } + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == row || y < 0 || y == col) + continue; + if (matrix[x][y] == 1) + continue; + if (x == row - 1) + return true; + q.emplace(x, y); + matrix[x][y] = 1; + } + } + + return false; + } +}; diff --git a/solutions/1970. Last Day Where You Can Still Cross/1970.java b/solutions/1970. Last Day Where You Can Still Cross/1970.java new file mode 100644 index 00000000000..14af2cc0aa6 --- /dev/null +++ b/solutions/1970. Last Day Where You Can Still Cross/1970.java @@ -0,0 +1,57 @@ +class Solution { + public int latestDayToCross(int row, int col, int[][] cells) { + int ans = 0; + int l = 1; + int r = cells.length - 1; + + while (l <= r) { + final int m = (l + r) / 2; + if (canWalk(m, row, col, cells)) { + ans = m; + l = m + 1; + } else { + r = m - 1; + } + } + + return ans; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private boolean canWalk(int day, int row, int col, int[][] cells) { + int[][] matrix = new int[row][col]; + for (int i = 0; i < day; ++i) { + final int x = cells[i][0] - 1; + final int y = cells[i][1] - 1; + matrix[x][y] = 1; + } + + Queue q = new ArrayDeque<>(); + + for (int j = 0; j < col; ++j) + if (matrix[0][j] == 0) { + q.offer(new int[] {0, j}); + matrix[0][j] = 1; + } + + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == row || y < 0 || y == col) + continue; + if (matrix[x][y] == 1) + continue; + if (x == row - 1) + return true; + q.offer(new int[] {x, y}); + matrix[x][y] = 1; + } + } + + return false; + } +} diff --git a/solutions/1970. Last Day Where You Can Still Cross/1970.py b/solutions/1970. Last Day Where You Can Still Cross/1970.py new file mode 100644 index 00000000000..e77a6cdf91b --- /dev/null +++ b/solutions/1970. Last Day Where You Can Still Cross/1970.py @@ -0,0 +1,46 @@ +class Solution: + def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + + def canWalk(day: int) -> bool: + matrix = [[0] * col for _ in range(row)] + for i in range(day): + x, y = cells[i] + matrix[x - 1][y - 1] = 1 + + q = collections.deque() + + for j in range(col): + if matrix[0][j] == 0: + q.append((0, j)) + matrix[0][j] = 1 + + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == row or y < 0 or y == col: + continue + if matrix[x][y] == 1: + continue + if x == row - 1: + return True + q.append((x, y)) + matrix[x][y] = 1 + + return False + + ans = 0 + l = 1 + r = len(cells) - 1 + + while l <= r: + m = (l + r) // 2 + if canWalk(m): + ans = m + l = m + 1 + else: + r = m - 1 + + return ans diff --git a/solutions/1971. Find if Path Exists in Graph/1971.cpp b/solutions/1971. Find if Path Exists in Graph/1971.cpp new file mode 100644 index 00000000000..af6702e0ed4 --- /dev/null +++ b/solutions/1971. Find if Path Exists in Graph/1971.cpp @@ -0,0 +1,45 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + bool validPath(int n, vector>& edges, int source, + int destination) { + UnionFind uf(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + uf.unionByRank(u, v); + } + + return uf.find(source) == uf.find(destination); + } +}; diff --git a/solutions/1971. Find if Path Exists in Graph/1971.java b/solutions/1971. Find if Path Exists in Graph/1971.java new file mode 100644 index 00000000000..1e0f18a1a9d --- /dev/null +++ b/solutions/1971. Find if Path Exists in Graph/1971.java @@ -0,0 +1,44 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public boolean validPath(int n, int[][] edges, int source, int destination) { + UnionFind uf = new UnionFind(n); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + uf.unionByRank(u, v); + } + + return uf.find(source) == uf.find(destination); + } +} diff --git a/solutions/1971. Find if Path Exists in Graph/1971.py b/solutions/1971. Find if Path Exists in Graph/1971.py new file mode 100644 index 00000000000..1c31ebcfb94 --- /dev/null +++ b/solutions/1971. Find if Path Exists in Graph/1971.py @@ -0,0 +1,32 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: + uf = UnionFind(n) + + for u, v in edges: + uf.unionByRank(u, v) + + return uf.find(source) == uf.find(destination) diff --git a/solutions/1972. First and Last Call On the Same Day/1972.sql b/solutions/1972. First and Last Call On the Same Day/1972.sql new file mode 100644 index 00000000000..cbc86d41c06 --- /dev/null +++ b/solutions/1972. First and Last Call On the Same Day/1972.sql @@ -0,0 +1,26 @@ +WITH + TwoWayCalls AS ( + SELECT caller_id, recipient_id, call_time FROM Calls + UNION ALL + SELECT recipient_id, caller_id, call_time FROM Calls + ), + RankedCalls AS ( + SELECT + caller_id, + recipient_id, + DATE(call_time) AS `date`, + RANK() OVER( + PARTITION BY caller_id, DATE(call_time) + ORDER BY call_time ASC + ) AS rank_asc + RANK() OVER( + PARTITION BY caller_id, DATE(call_time) + ORDER BY call_time DESC + ) AS rank_desc + FROM TwoWayCalls + ) +SELECT DISTINCT caller_id AS user_id +FROM RankedCalls +WHERE rank_asc = 1 OR rank_desc = 1 +GROUP BY caller_id, `date` +HAVING COUNT(DISTINCT recipient_id) = 1; diff --git a/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.cpp b/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.cpp new file mode 100644 index 00000000000..fedf2bd322e --- /dev/null +++ b/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.cpp @@ -0,0 +1,22 @@ +struct T { + long sum; + int count; +}; + +class Solution { + public: + int equalToDescendants(TreeNode* root) { + return dfs(root).count; + } + + private: + T dfs(TreeNode* root) { + if (root == nullptr) + return T{.sum = 0, .count = 0}; + T left = dfs(root->left); + T right = dfs(root->right); + return T{.sum = root->val + left.sum + right.sum, + .count = left.count + right.count + + (root->val == left.sum + right.sum ? 1 : 0)}; + } +}; diff --git a/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.java b/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.java new file mode 100644 index 00000000000..f7ee447918e --- /dev/null +++ b/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.java @@ -0,0 +1,16 @@ +class Solution { + public int equalToDescendants(TreeNode root) { + return dfs(root).count; + } + + private T dfs(TreeNode root) { + if (root == null) + return new T(0, 0); + T left = dfs(root.left); + T right = dfs(root.right); + return new T(root.val + left.sum + right.sum, + left.count + right.count + (root.val == left.sum + right.sum ? 1 : 0)); + } + + private record T(long sum, int count){}; +} diff --git a/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.py b/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.py new file mode 100644 index 00000000000..1962e6af494 --- /dev/null +++ b/solutions/1973. Count Nodes Equal to Sum of Descendants/1973.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True) +class T: + summ: int + count: int + + +class Solution: + def equalToDescendants(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]) -> T: + if not root: + return T(0, 0) + left = dfs(root.left) + right = dfs(root.right) + return T(root.val + left.summ + right.summ, + left.count + right.count + + (1 if root.val == left.summ + right.summ else 0)) + + return dfs(root).count diff --git a/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.cpp b/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.cpp new file mode 100644 index 00000000000..f5b0b5a0744 --- /dev/null +++ b/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minTimeToType(string word) { + int moves = 0; + char letter = 'a'; + + for (const char c : word) { + const int diff = abs(c - letter); + moves += min(diff, 26 - diff); + letter = c; + } + + return moves + word.length(); + } +}; diff --git a/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.java b/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.java new file mode 100644 index 00000000000..c28a4bc36dd --- /dev/null +++ b/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.java @@ -0,0 +1,14 @@ +class Solution { + public int minTimeToType(String word) { + int moves = 0; + char letter = 'a'; + + for (final char c : word.toCharArray()) { + final int diff = Math.abs(c - letter); + moves += Math.min(diff, 26 - diff); + letter = c; + } + + return moves + word.length(); + } +} diff --git a/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.py b/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.py new file mode 100644 index 00000000000..84626f6ef3b --- /dev/null +++ b/solutions/1974. Minimum Time to Type Word Using Special Typewriter/1974.py @@ -0,0 +1,11 @@ +class Solution: + def minTimeToType(self, word: str) -> int: + moves = 0 + letter = 'a' + + for c in word: + diff = abs(ord(c) - ord(letter)) + moves += min(diff, 26 - diff) + letter = c + + return moves + len(word) diff --git a/solutions/1975. Maximum Matrix Sum/1975.cpp b/solutions/1975. Maximum Matrix Sum/1975.cpp new file mode 100644 index 00000000000..89cc40122b9 --- /dev/null +++ b/solutions/1975. Maximum Matrix Sum/1975.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + long long maxMatrixSum(vector>& matrix) { + long absSum = 0; + int minAbs = INT_MAX; + // 0 := even number of negatives + // 1 := odd number of negatives + int oddNeg = 0; + + for (const vector& row : matrix) + for (const int num : row) { + absSum += abs(num); + minAbs = min(minAbs, abs(num)); + if (num < 0) + oddNeg ^= 1; + } + + return absSum - oddNeg * minAbs * 2; + } +}; diff --git a/solutions/1975. Maximum Matrix Sum/1975.java b/solutions/1975. Maximum Matrix Sum/1975.java new file mode 100644 index 00000000000..7686393d7f5 --- /dev/null +++ b/solutions/1975. Maximum Matrix Sum/1975.java @@ -0,0 +1,19 @@ +class Solution { + public long maxMatrixSum(int[][] matrix) { + long absSum = 0; + int minAbs = Integer.MAX_VALUE; + // 0 := even number of negatives + // 1 := odd number of negatives + int oddNeg = 0; + + for (int[] row : matrix) + for (final int num : row) { + absSum += Math.abs(num); + minAbs = Math.min(minAbs, Math.abs(num)); + if (num < 0) + oddNeg ^= 1; + } + + return absSum - oddNeg * minAbs * 2; + } +} diff --git a/solutions/1975. Maximum Matrix Sum/1975.py b/solutions/1975. Maximum Matrix Sum/1975.py new file mode 100644 index 00000000000..0b8dec0d581 --- /dev/null +++ b/solutions/1975. Maximum Matrix Sum/1975.py @@ -0,0 +1,16 @@ +class Solution: + def maxMatrixSum(self, matrix: List[List[int]]) -> int: + absSum = 0 + minAbs = math.inf + # 0 := even number of negatives + # 1 := odd number of negatives + oddNeg = 0 + + for row in matrix: + for num in row: + absSum += abs(num) + minAbs = min(minAbs, abs(num)) + if num < 0: + oddNeg ^= 1 + + return absSum - oddNeg * minAbs * 2 diff --git a/solutions/1976. Number of Ways to Arrive at Destination/1976.cpp b/solutions/1976. Number of Ways to Arrive at Destination/1976.cpp new file mode 100644 index 00000000000..36ca47ac6dc --- /dev/null +++ b/solutions/1976. Number of Ways to Arrive at Destination/1976.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int countPaths(int n, vector>& roads) { + vector>> graph(n); + + for (const vector& road : roads) { + const int u = road[0]; + const int v = road[1]; + const int w = road[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + return dijkstra(graph, 0, n - 1); + } + + private: + // Similar to 1786. Number of Restricted Paths From First to Last Node + int dijkstra(const vector>>& graph, int src, int dst) { + constexpr int kMod = 1'000'000'007; + vector ways(graph.size()); + vector dist(graph.size(), LONG_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + ways[src] = 1; + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + ways[v] = ways[u]; + minHeap.emplace(dist[v], v); + } else if (d + w == dist[v]) { + ways[v] += ways[u]; + ways[v] %= kMod; + } + } + + return ways[dst]; + } +}; diff --git a/solutions/1976. Number of Ways to Arrive at Destination/1976.java b/solutions/1976. Number of Ways to Arrive at Destination/1976.java new file mode 100644 index 00000000000..2bce18064c9 --- /dev/null +++ b/solutions/1976. Number of Ways to Arrive at Destination/1976.java @@ -0,0 +1,52 @@ +class Solution { + public int countPaths(int n, int[][] roads) { + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] road : roads) { + final int u = road[0]; + final int v = road[1]; + final int w = road[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + return dijkstra(graph, 0, n - 1); + } + + private int dijkstra(List>[] graph, int src, int dst) { + final int kMod = 1_000_000_007; + long[] ways = new long[graph.length]; + Arrays.fill(ways, 0); + long[] dist = new long[graph.length]; + Arrays.fill(dist, Long.MAX_VALUE); + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + ways[src] = 1; + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final long d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + ways[v] = ways[u]; + minHeap.offer(new Pair<>(dist[v], v)); + } else if (d + w == dist[v]) { + ways[v] += ways[u]; + ways[v] %= kMod; + } + } + } + + return (int) ways[dst]; + } +} diff --git a/solutions/1976. Number of Ways to Arrive at Destination/1976.py b/solutions/1976. Number of Ways to Arrive at Destination/1976.py new file mode 100644 index 00000000000..ba578594821 --- /dev/null +++ b/solutions/1976. Number of Ways to Arrive at Destination/1976.py @@ -0,0 +1,33 @@ +class Solution: + def countPaths(self, n: int, roads: List[List[int]]) -> int: + graph = [[] for _ in range(n)] + + for u, v, w in roads: + graph[u].append((v, w)) + graph[v].append((u, w)) + + return self._dijkstra(graph, 0, n - 1) + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int) -> int: + kMod = 10**9 + 7 + ways = [0] * len(graph) + dist = [math.inf] * len(graph) + + ways[src] = 1 + dist[src] = 0 + minHeap = [(dist[src], src)] + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < dist[v]: + dist[v] = d + w + ways[v] = ways[u] + heapq.heappush(minHeap, (dist[v], v)) + elif d + w == dist[v]: + ways[v] += ways[u] + ways[v] %= kMod + + return ways[dst] diff --git a/solutions/1977. Number of Ways to Separate Numbers/1977.cpp b/solutions/1977. Number of Ways to Separate Numbers/1977.cpp new file mode 100644 index 00000000000..19d40c300bc --- /dev/null +++ b/solutions/1977. Number of Ways to Separate Numbers/1977.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int numberOfCombinations(string num) { + if (num[0] == '0') + return 0; + + constexpr int kMod = 1'000'000'007; + const int n = num.size(); + // dp[i][k] := the number of possible lists of integers ending in num[i] + // with the length of the last number being 1..k + vector> dp(n, vector(n + 1)); + // lcs[i][j] := the number of the same digits in num[i..n) and num[j..n) + vector> lcs(n + 1, vector(n + 1)); + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j < n; ++j) + if (num[i] == num[j]) + lcs[i][j] = lcs[i + 1][j + 1] + 1; + + for (int i = 0; i < n; ++i) + for (int k = 1; k <= i + 1; ++k) { + dp[i][k] += dp[i][k - 1]; + dp[i][k] %= kMod; + // The last number is num[s..i]. + const int s = i - k + 1; + if (num[s] == '0') + // the number of possible lists of integers ending in num[i] with the + // length of the last number being k + continue; + if (s == 0) { + // the whole string + dp[i][k] += 1; + continue; + } + if (s < k) { + // The length k is not enough, so add the number of possible lists of + // integers in num[0..s - 1]. + dp[i][k] += dp[s - 1][s]; + continue; + } + const int l = lcs[s - k][s]; + if (l >= k || num[s - k + l] <= num[s + l]) + // Have enough length k and num[s - k..s - 1] <= num[j..i]. + dp[i][k] += dp[s - 1][k]; + else + // Have enough length k but num[s - k..s - 1] > num[j..i]. + dp[i][k] += dp[s - 1][k - 1]; + } + + return dp[n - 1][n] % kMod; + } +}; diff --git a/solutions/1977. Number of Ways to Separate Numbers/1977.java b/solutions/1977. Number of Ways to Separate Numbers/1977.java new file mode 100644 index 00000000000..2e9199c8b15 --- /dev/null +++ b/solutions/1977. Number of Ways to Separate Numbers/1977.java @@ -0,0 +1,51 @@ +class Solution { + public int numberOfCombinations(String num) { + if (num.charAt(0) == '0') + return 0; + + final int kMod = 1_000_000_007; + final int n = num.length(); + // dp[i][k] := the number of possible lists of integers ending in num[i] with + // the length of the last number being 1..k + long[][] dp = new long[n][n + 1]; + // lcs[i][j] := the number of the same digits in num[i..n) and num[j..n) + int[][] lcs = new int[n + 1][n + 1]; + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j < n; ++j) + if (num.charAt(i) == num.charAt(j)) + lcs[i][j] = lcs[i + 1][j + 1] + 1; + + for (int i = 0; i < n; ++i) + for (int k = 1; k <= i + 1; ++k) { + dp[i][k] += dp[i][k - 1]; + dp[i][k] %= kMod; + // The last number is num[s..i]. + final int s = i - k + 1; + if (num.charAt(s) == '0') + // the number of possible lists of integers ending in num[i] with the + // length of the last number being k + continue; + if (s == 0) { + // the whole string + dp[i][k] += 1; + continue; + } + if (s < k) { + // The length k is not enough, so add the number of possible lists of + // integers in num[0..s - 1]. + dp[i][k] += dp[s - 1][s]; + continue; + } + final int l = lcs[s - k][s]; + if (l >= k || num.charAt(s - k + l) <= num.charAt(s + l)) + // Have enough length k and num[s - k..s - 1] <= num[j..i]. + dp[i][k] += dp[s - 1][k]; + else + // Have enough length k but num[s - k..s - 1] > num[j..i]. + dp[i][k] += dp[s - 1][k - 1]; + } + + return (int) dp[n - 1][n] % kMod; + } +} diff --git a/solutions/1977. Number of Ways to Separate Numbers/1977.py b/solutions/1977. Number of Ways to Separate Numbers/1977.py new file mode 100644 index 00000000000..3a56a823744 --- /dev/null +++ b/solutions/1977. Number of Ways to Separate Numbers/1977.py @@ -0,0 +1,45 @@ +class Solution: + def numberOfCombinations(self, num: str) -> int: + if num[0] == '0': + return 0 + + kMod = 1_000_000_007 + n = len(num) + # dp[i][k] := the number of possible lists of integers ending in num[i] + # with the length of the last number being 1..k + dp = [[0] * (n + 1) for _ in range(n)] + # lcs[i][j] := the number of the same digits in num[i..n) and num[j..n) + lcs = [[0] * (n + 1) for _ in range(n + 1)] + + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + if num[i] == num[j]: + lcs[i][j] = lcs[i + 1][j + 1] + 1 + + for i in range(n): + for k in range(1, i + 2): + dp[i][k] += dp[i][k - 1] + dp[i][k] %= kMod + # The last number is num[s..i]. + s = i - k + 1 + if num[s] == '0': + # the number of possible lists of integers ending in num[i] with the + # length of the last number being k + continue + if s == 0: # the whole string + dp[i][k] += 1 + continue + if s < k: + # The length k is not enough, so add the number of possible lists of + # integers in num[0..s - 1]. + dp[i][k] += dp[s - 1][s] + continue + l = lcs[s - k][s] + if l >= k or num[s - k + l] <= num[s + l]: + # Have enough length k and num[s - k..s - 1] <= num[j..i]. + dp[i][k] += dp[s - 1][k] + else: + # Have enough length k but num[s - k..s - 1] > num[j..i]. + dp[i][k] += dp[s - 1][k - 1] + + return dp[n - 1][n] % kMod diff --git a/solutions/1978. Employees Whose Manager Left the Company/1978.sql b/solutions/1978. Employees Whose Manager Left the Company/1978.sql new file mode 100644 index 00000000000..971979537c3 --- /dev/null +++ b/solutions/1978. Employees Whose Manager Left the Company/1978.sql @@ -0,0 +1,9 @@ +SELECT Employee.employee_id +FROM Employees AS Employee +LEFT JOIN Employees AS Manager + ON (Employee.manager_id = Manager.employee_id) +WHERE + Employee.salary < 30000 + AND Employee.manager_id IS NOT NULL + AND Manager.employee_id IS NULL +ORDER BY 1; diff --git a/solutions/1979. Find Greatest Common Divisor of Array/1979.cpp b/solutions/1979. Find Greatest Common Divisor of Array/1979.cpp new file mode 100644 index 00000000000..dd913edc8ed --- /dev/null +++ b/solutions/1979. Find Greatest Common Divisor of Array/1979.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int findGCD(vector& nums) { + return __gcd(ranges::min(nums), ranges::max(nums)); + } +}; diff --git a/solutions/1979. Find Greatest Common Divisor of Array/1979.java b/solutions/1979. Find Greatest Common Divisor of Array/1979.java new file mode 100644 index 00000000000..2eb0a692291 --- /dev/null +++ b/solutions/1979. Find Greatest Common Divisor of Array/1979.java @@ -0,0 +1,11 @@ +class Solution { + public int findGCD(int[] nums) { + final int mn = Arrays.stream(nums).min().getAsInt(); + final int mx = Arrays.stream(nums).max().getAsInt(); + return gcd(mn, mx); + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/1979. Find Greatest Common Divisor of Array/1979.py b/solutions/1979. Find Greatest Common Divisor of Array/1979.py new file mode 100644 index 00000000000..a708fa1b689 --- /dev/null +++ b/solutions/1979. Find Greatest Common Divisor of Array/1979.py @@ -0,0 +1,3 @@ +class Solution: + def findGCD(self, nums: List[int]) -> int: + return math.gcd(min(nums), max(nums)) diff --git a/solutions/198. House Robber/198-2.cpp b/solutions/198. House Robber/198-2.cpp new file mode 100644 index 00000000000..92476323d11 --- /dev/null +++ b/solutions/198. House Robber/198-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int rob(vector& nums) { + int prev1 = 0; // dp[i - 1] + int prev2 = 0; // dp[i - 2] + + for (const int num : nums) { + const int dp = max(prev1, prev2 + num); + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } +}; diff --git a/solutions/198. House Robber/198-2.java b/solutions/198. House Robber/198-2.java new file mode 100644 index 00000000000..a83ba4e230e --- /dev/null +++ b/solutions/198. House Robber/198-2.java @@ -0,0 +1,14 @@ +class Solution { + public int rob(int[] nums) { + int prev1 = 0; // dp[i - 1] + int prev2 = 0; // dp[i - 2] + + for (final int num : nums) { + final int dp = Math.max(prev1, prev2 + num); + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } +} diff --git a/solutions/198. House Robber/198-2.py b/solutions/198. House Robber/198-2.py new file mode 100644 index 00000000000..2122b49d2ef --- /dev/null +++ b/solutions/198. House Robber/198-2.py @@ -0,0 +1,11 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + prev1 = 0 # dp[i - 1] + prev2 = 0 # dp[i - 2] + + for num in nums: + dp = max(prev1, prev2 + num) + prev2 = prev1 + prev1 = dp + + return prev1 diff --git a/solutions/198. House Robber/198.cpp b/solutions/198. House Robber/198.cpp new file mode 100644 index 00000000000..55df52326a7 --- /dev/null +++ b/solutions/198. House Robber/198.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int rob(vector& nums) { + if (nums.empty()) + return 0; + if (nums.size() == 1) + return nums[0]; + + // dp[i] := the maximum money of robbing nums[0..i] + vector dp(nums.size()); + dp[0] = nums[0]; + dp[1] = max(nums[0], nums[1]); + + for (int i = 2; i < nums.size(); ++i) + dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]); + + return dp.back(); + } +}; diff --git a/solutions/198. House Robber/198.java b/solutions/198. House Robber/198.java new file mode 100644 index 00000000000..57f79aa4f17 --- /dev/null +++ b/solutions/198. House Robber/198.java @@ -0,0 +1,19 @@ +class Solution { + public int rob(int[] nums) { + final int n = nums.length; + if (n == 0) + return 0; + if (n == 1) + return nums[0]; + + // dp[i] := the maximum money of robbing nums[0..i] + int[] dp = new int[n]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + + for (int i = 2; i < n; ++i) + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); + + return dp[n - 1]; + } +} diff --git a/solutions/198. House Robber/198.py b/solutions/198. House Robber/198.py new file mode 100644 index 00000000000..58b4af4ff31 --- /dev/null +++ b/solutions/198. House Robber/198.py @@ -0,0 +1,16 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + if not nums: + return 0 + if len(nums) == 1: + return nums[0] + + # dp[i]:= max money of robbing nums[0..i] + dp = [0] * len(nums) + dp[0] = nums[0] + dp[1] = max(nums[0], nums[1]) + + for i in range(2, len(nums)): + dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]) + + return dp[-1] diff --git a/solutions/1980. Find Unique Binary String/1980-2.cpp b/solutions/1980. Find Unique Binary String/1980-2.cpp new file mode 100644 index 00000000000..fd3373ed4fd --- /dev/null +++ b/solutions/1980. Find Unique Binary String/1980-2.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + string findDifferentBinaryString(vector& nums) { + string ans; + + // Flip the i-th bit for each nums[i] so that `ans` is unique. + for (int i = 0; i < nums.size(); ++i) + ans += nums[i][i] == '0' ? '1' : '0'; + + return ans; + } +}; diff --git a/solutions/1980. Find Unique Binary String/1980-2.java b/solutions/1980. Find Unique Binary String/1980-2.java new file mode 100644 index 00000000000..0222665d895 --- /dev/null +++ b/solutions/1980. Find Unique Binary String/1980-2.java @@ -0,0 +1,11 @@ +class Solution { + public String findDifferentBinaryString(String[] nums) { + StringBuilder sb = new StringBuilder(); + + // Flip the i-th bit for each nums[i] so that `ans` is unique. + for (int i = 0; i < nums.length; ++i) + sb.append(nums[i].charAt(i) == '0' ? '1' : '0'); + + return sb.toString(); + } +} diff --git a/solutions/1980. Find Unique Binary String/1980-2.py b/solutions/1980. Find Unique Binary String/1980-2.py new file mode 100644 index 00000000000..f5a86241a79 --- /dev/null +++ b/solutions/1980. Find Unique Binary String/1980-2.py @@ -0,0 +1,3 @@ +class Solution: + def findDifferentBinaryString(self, nums: List[str]) -> str: + return ''.join('1' if num[i] == '0' else '0' for i, num in enumerate(nums)) diff --git a/solutions/1980. Find Unique Binary String/1980.cpp b/solutions/1980. Find Unique Binary String/1980.cpp new file mode 100644 index 00000000000..e5636befe49 --- /dev/null +++ b/solutions/1980. Find Unique Binary String/1980.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string findDifferentBinaryString(vector& nums) { + const int bitSize = nums[0].length(); + const int maxNum = 1 << bitSize; + unordered_set numsSet; + + for (const string& num : nums) + numsSet.insert(stoi(num, nullptr, 2)); + + for (int num = 0; num < maxNum; ++num) + if (!numsSet.contains(num)) + return std::bitset<16>(num).to_string().substr(16 - bitSize); + + throw; + } +}; diff --git a/solutions/1980. Find Unique Binary String/1980.java b/solutions/1980. Find Unique Binary String/1980.java new file mode 100644 index 00000000000..04edc655da1 --- /dev/null +++ b/solutions/1980. Find Unique Binary String/1980.java @@ -0,0 +1,16 @@ +class Solution { + public String findDifferentBinaryString(String[] nums) { + final int bitSize = nums[0].length(); + final int maxNum = 1 << bitSize; + Set numsSet = Arrays.stream(nums) + .mapToInt(num -> Integer.parseInt(num, 2)) + .boxed() + .collect(Collectors.toSet()); + + for (int num = 0; num < maxNum; ++num) + if (!numsSet.contains(num)) + return String.format("%" + bitSize + "s", Integer.toBinaryString(num)).replace(' ', '0'); + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/1980. Find Unique Binary String/1980.py b/solutions/1980. Find Unique Binary String/1980.py new file mode 100644 index 00000000000..e4458872c71 --- /dev/null +++ b/solutions/1980. Find Unique Binary String/1980.py @@ -0,0 +1,9 @@ +class Solution: + def findDifferentBinaryString(self, nums: List[str]) -> str: + bitSize = len(nums[0]) + maxNum = 1 << bitSize + numsSet = {int(num, 2) for num in nums} + + for num in range(maxNum): + if num not in numsSet: + return f'{num:0>{bitSize}b}' diff --git a/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.cpp b/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.cpp new file mode 100644 index 00000000000..165106765ca --- /dev/null +++ b/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int minimizeTheDifference(vector>& mat, int target) { + const int minSum = getMinSum(mat); + if (minSum >= target) // No need to consider any larger combination. + return minSum - target; + + const int maxSum = getMaxSum(mat); + vector> mem(mat.size(), vector(maxSum + 1, -1)); + return minimizeTheDifference(mat, 0, 0, target, mem); + } + + private: + int minimizeTheDifference(const vector>& mat, int i, int sum, + int target, vector>& mem) { + if (i == mat.size()) + return abs(sum - target); + if (mem[i][sum] != -1) + return mem[i][sum]; + int res = INT_MAX; + for (const int num : mat[i]) + res = min(res, minimizeTheDifference(mat, i + 1, sum + num, target, mem)); + return mem[i][sum] = res; + } + + int getMinSum(const vector>& mat) { + return accumulate(mat.begin(), mat.end(), 0, + [](int subtotal, const vector& row) { + return subtotal + ranges::min(row); + }); + } + + int getMaxSum(const vector>& mat) { + return accumulate(mat.begin(), mat.end(), 0, + [](int subtotal, const vector& row) { + return subtotal + ranges::max(row); + }); + } +}; diff --git a/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.java b/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.java new file mode 100644 index 00000000000..10d8a5a7cbc --- /dev/null +++ b/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.java @@ -0,0 +1,22 @@ +class Solution { + public int minimizeTheDifference(int[][] mat, int target) { + final int minSum = Arrays.stream(mat).mapToInt(A -> Arrays.stream(A).min().getAsInt()).sum(); + if (minSum >= target) // No need to consider any larger combination. + return minSum - target; + + final int maxSum = Arrays.stream(mat).mapToInt(A -> Arrays.stream(A).max().getAsInt()).sum(); + Integer[][] mem = new Integer[mat.length][maxSum + 1]; + return minimizeTheDifference(mat, 0, 0, target, mem); + } + + private int minimizeTheDifference(int[][] mat, int i, int sum, int target, Integer[][] mem) { + if (i == mat.length) + return Math.abs(sum - target); + if (mem[i][sum] != null) + return mem[i][sum]; + int res = Integer.MAX_VALUE; + for (final int num : mat[i]) + res = Math.min(res, minimizeTheDifference(mat, i + 1, sum + num, target, mem)); + return mem[i][sum] = res; + } +} diff --git a/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.py b/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.py new file mode 100644 index 00000000000..cac1462af1b --- /dev/null +++ b/solutions/1981. Minimize the Difference Between Target and Chosen Elements/1981.py @@ -0,0 +1,13 @@ +class Solution: + def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: + minSum = sum(min(row) for row in mat) + if minSum >= target: # No need to consider any larger combination. + return minSum - target + + @functools.lru_cache(None) + def dp(i: int, summ: int) -> int: + if i == len(mat): + return abs(summ - target) + return min(dp(i + 1, summ + num) for num in mat[i]) + + return dp(0, 0) diff --git a/solutions/1982. Find Array Given Subset Sums/1982.cpp b/solutions/1982. Find Array Given Subset Sums/1982.cpp new file mode 100644 index 00000000000..0a669e6c71a --- /dev/null +++ b/solutions/1982. Find Array Given Subset Sums/1982.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + vector recoverArray(int n, vector& sums) { + ranges::sort(sums); + return recover(sums); + } + + private: + vector recover(const vector& sums) { + if (sums.size() == 1) // sums[0] must be 0. + return {}; + + // Either num or -num must be in the final array. + // num + sumsExcludingNum = sumsIncludingNum + // -num + sumsIncludingNum = sumsExcludingNum + unordered_map count; + for (const int sum : sums) + ++count[sum]; + + const int num = sums[1] - sums[0]; + vector sumsExcludingNum; + vector sumsIncludingNum; + bool chooseSumsIncludingNum = false; + + for (const int sum : sums) { + if (count[sum] == 0) + continue; + --count[sum]; + --count[sum + num]; + sumsExcludingNum.push_back(sum); + sumsIncludingNum.push_back(sum + num); + if (sum + num == 0) + chooseSumsIncludingNum = true; + } + + // Choose `sumsExludingNum` by default since we want to gradually strip + // `num` from each sum in `sums` to have the final array. However, we should + // always choose the group of sums with 0 since it's a must-have. + vector recovered = + recover(chooseSumsIncludingNum ? sumsIncludingNum : sumsExcludingNum); + recovered.push_back(chooseSumsIncludingNum ? -num : num); + return recovered; + } +}; diff --git a/solutions/1982. Find Array Given Subset Sums/1982.java b/solutions/1982. Find Array Given Subset Sums/1982.java new file mode 100644 index 00000000000..dc34c7c6f83 --- /dev/null +++ b/solutions/1982. Find Array Given Subset Sums/1982.java @@ -0,0 +1,42 @@ +class Solution { + public int[] recoverArray(int n, int[] sums) { + Arrays.sort(sums); + return recover(sums).stream().mapToInt(Integer::intValue).toArray(); + } + + private List recover(int[] sums) { + if (sums.length == 1) // sums[0] must be 0. + return new ArrayList<>(); + + Map count = Arrays.stream(sums).boxed().collect( + Collectors.groupingBy(Function.identity(), Collectors.counting())); + + // Either num or -num must be in the final array. + // num + sumsExcludingNum = sumsIncludingNum + // -num + sumsIncludingNum = sumsExcludingNum + final int num = sums[1] - sums[0]; + int i = 0; // sumsExcludingNum/sumsIncludingNum's index + int[] sumsExcludingNum = new int[sums.length / 2]; + int[] sumsIncludingNum = new int[sums.length / 2]; + boolean chooseSumsIncludingNum = false; + + for (final int sum : sums) { + if (count.get(sum) == 0) + continue; + count.merge(sum, -1L, Long::sum); + count.merge(sum + num, -1L, Long::sum); + sumsExcludingNum[i] = sum; + sumsIncludingNum[i] = sum + num; + ++i; + if (sum + num == 0) + chooseSumsIncludingNum = true; + } + + // Choose `sumsExludingNum` by default since we want to gradually strip + // `num` from each sum in `sums` to have the final array. However, we should + // always choose the group of sums with 0 since it's a must-have. + List recovered = recover(chooseSumsIncludingNum ? sumsIncludingNum : sumsExcludingNum); + recovered.add(chooseSumsIncludingNum ? -num : num); + return recovered; + } +} diff --git a/solutions/1982. Find Array Given Subset Sums/1982.py b/solutions/1982. Find Array Given Subset Sums/1982.py new file mode 100644 index 00000000000..602228cba03 --- /dev/null +++ b/solutions/1982. Find Array Given Subset Sums/1982.py @@ -0,0 +1,32 @@ +class Solution: + def recoverArray(self, n: int, sums: List[int]) -> List[int]: + def recover(sums: List[int]) -> List[int]: + if len(sums) == 1: + return [] + + count = collections.Counter(sums) + # Either num or -num must be in the final array. + # num + sumsExcludingNum = sumsIncludingNum + # -num + sumsIncludingNum = sumsExcludingNum + num = sums[1] - sums[0] + sumsExcludingNum = [] + sumsIncludingNum = [] + chooseSumsExcludingNum = True + + for summ in sums: + if count[summ] == 0: + continue + count[summ] -= 1 + count[summ + num] -= 1 + sumsExcludingNum.append(summ) + sumsIncludingNum.append(summ + num) + if summ + num == 0: + chooseSumsExcludingNum = False + + # Choose `sumsExludingNum` by default since we want to gradually strip + # `num` from each sum in `sums` to have the final array. However, we should + # always choose the group of sums with 0 since it's a must-have. + return [num] + recover(sumsExcludingNum) if chooseSumsExcludingNum \ + else [-num] + recover(sumsIncludingNum) + + return recover(sorted(sums)) diff --git a/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.cpp b/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.cpp new file mode 100644 index 00000000000..96a2c9764c7 --- /dev/null +++ b/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int widestPairOfIndices(vector& nums1, vector& nums2) { + int ans = 0; + int prefix = 0; + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < nums1.size(); ++i) { + prefix += nums1[i] - nums2[i]; + if (const auto it = prefixToIndex.find(prefix); + it != prefixToIndex.cend()) + ans = max(ans, i - it->second); + else + prefixToIndex[prefix] = i; + } + + return ans; + } +}; diff --git a/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.java b/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.java new file mode 100644 index 00000000000..135bb914efc --- /dev/null +++ b/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.java @@ -0,0 +1,18 @@ +class Solution { + public int widestPairOfIndices(int[] nums1, int[] nums2) { + int ans = 0; + int prefix = 0; + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < nums1.length; ++i) { + prefix += nums1[i] - nums2[i]; + if (prefixToIndex.containsKey(prefix)) + ans = Math.max(ans, i - prefixToIndex.get(prefix)); + else + prefixToIndex.put(prefix, i); + } + + return ans; + } +} diff --git a/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.py b/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.py new file mode 100644 index 00000000000..a3a04905135 --- /dev/null +++ b/solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.py @@ -0,0 +1,11 @@ +class Solution: + def widestPairOfIndices(self, nums1: List[int], nums2: List[int]) -> int: + ans = 0 + prefix = 0 + prefixToIndex = {0: -1} + + for i, (num1, num2) in enumerate(zip(nums1, nums2)): + prefix += num1 - num2 + ans = max(ans, i - prefixToIndex.setdefault(prefix, i)) + + return ans diff --git a/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.cpp b/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.cpp new file mode 100644 index 00000000000..ce904f35dc8 --- /dev/null +++ b/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int minimumDifference(vector& nums, int k) { + ranges::sort(nums); + + int ans = nums[k - 1] - nums[0]; + + for (int i = k; i < nums.size(); ++i) + ans = min(ans, nums[i] - nums[i - k + 1]); + + return ans; + } +}; diff --git a/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.java b/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.java new file mode 100644 index 00000000000..efd63534719 --- /dev/null +++ b/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.java @@ -0,0 +1,12 @@ +class Solution { + public int minimumDifference(int[] nums, int k) { + Arrays.sort(nums); + + int ans = nums[k - 1] - nums[0]; + + for (int i = k; i < nums.length; ++i) + ans = Math.min(ans, nums[i] - nums[i - k + 1]); + + return ans; + } +} diff --git a/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.py b/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.py new file mode 100644 index 00000000000..6ceae1bd55a --- /dev/null +++ b/solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.py @@ -0,0 +1,9 @@ +class Solution: + def minimumDifference(self, nums: List[int], k: int) -> int: + nums.sort() + ans = nums[k - 1] - nums[0] + + for i in range(k, len(nums)): + ans = min(ans, nums[i] - nums[i - k + 1]) + + return ans diff --git a/solutions/1985. Find the Kth Largest Integer in the Array/1985.cpp b/solutions/1985. Find the Kth Largest Integer in the Array/1985.cpp new file mode 100644 index 00000000000..4283a24240f --- /dev/null +++ b/solutions/1985. Find the Kth Largest Integer in the Array/1985.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + // Similar to 215. Kth Largest Element in an Array + string kthLargestNumber(vector& nums, int k) { + auto compare = [](const string& a, const string& b) { + return a.length() == b.length() ? a > b : a.length() > b.length(); + }; + priority_queue, decltype(compare)> minHeap(compare); + + for (const string& num : nums) { + minHeap.push(num); + if (minHeap.size() > k) + minHeap.pop(); + } + + return minHeap.top(); + } +}; diff --git a/solutions/1985. Find the Kth Largest Integer in the Array/1985.java b/solutions/1985. Find the Kth Largest Integer in the Array/1985.java new file mode 100644 index 00000000000..88c8a3f0daf --- /dev/null +++ b/solutions/1985. Find the Kth Largest Integer in the Array/1985.java @@ -0,0 +1,15 @@ +class Solution { + // Similar to 215. Kth Largest Element in an Array + public String kthLargestNumber(String[] nums, int k) { + Queue minHeap = new PriorityQueue<>( + (a, b) -> a.length() == b.length() ? a.compareTo(b) : a.length() - b.length()); + + for (final String num : nums) { + minHeap.offer(num); + if (minHeap.size() > k) + minHeap.poll(); + } + + return minHeap.poll(); + } +} diff --git a/solutions/1985. Find the Kth Largest Integer in the Array/1985.py b/solutions/1985. Find the Kth Largest Integer in the Array/1985.py new file mode 100644 index 00000000000..12d0c5b28d5 --- /dev/null +++ b/solutions/1985. Find the Kth Largest Integer in the Array/1985.py @@ -0,0 +1,11 @@ +class Solution: + # Similar to 215. Kth Largest Element in an Array + def kthLargestNumber(self, nums: List[str], k: int) -> str: + minHeap = [] + + for num in nums: + heapq.heappush(minHeap, int(num)) + if len(minHeap) > k: + heapq.heappop(minHeap) + + return str(minHeap[0]) diff --git a/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.cpp b/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.cpp new file mode 100644 index 00000000000..c9f3731148d --- /dev/null +++ b/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int minSessions(vector& tasks, int sessionTime) { + for (int numSessions = 1; numSessions <= tasks.size(); ++numSessions) + if (dfs(tasks, 0, vector(numSessions), sessionTime)) + return numSessions; + throw; + } + + // Returns true if we can assign tasks[s..n) to `sessions`. Note that + // `sessions` may be occupied by some tasks. + bool dfs(const vector& tasks, int s, vector&& sessions, + const int& sessionTime) { + if (s == tasks.size()) + return true; + + for (int& session : sessions) { + // Can't assign the tasks[s] to this session. + if (session + tasks[s] > sessionTime) + continue; + // Assign the tasks[s] to this session. + session += tasks[s]; + if (dfs(tasks, s + 1, move(sessions), sessionTime)) + return true; + // Backtracking. + session -= tasks[s]; + // If it's the first time we assign the tasks[s] to this session, then + // future `session`s can't satisfy either. + if (session == 0) + return false; + } + + return false; + } +}; diff --git a/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.java b/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.java new file mode 100644 index 00000000000..0fb0f62ebb2 --- /dev/null +++ b/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.java @@ -0,0 +1,33 @@ +class Solution { + public int minSessions(int[] tasks, int sessionTime) { + for (int numSessions = 1; numSessions <= tasks.length; ++numSessions) + if (dfs(tasks, 0, new int[numSessions], sessionTime)) + return numSessions; + throw new IllegalArgumentException(); + } + + // Returns true if we can assign tasks[s..n) to `sessions`. Note that `sessions` + // may be occupied by some tasks. + private boolean dfs(int[] tasks, int s, int[] sessions, int sessionTime) { + if (s == tasks.length) + return true; + + for (int i = 0; i < sessions.length; ++i) { + // Can't assign the tasks[s] to this session. + if (sessions[i] + tasks[s] > sessionTime) + continue; + // Assign the tasks[s] to this session. + sessions[i] += tasks[s]; + if (dfs(tasks, s + 1, sessions, sessionTime)) + return true; + // Backtracking. + sessions[i] -= tasks[s]; + // If it's the first time we assign the tasks[s] to this session, then future + // `session`s can't satisfy either. + if (sessions[i] == 0) + return false; + } + + return false; + } +} diff --git a/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.py b/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.py new file mode 100644 index 00000000000..8e6b1123ca0 --- /dev/null +++ b/solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.py @@ -0,0 +1,28 @@ +class Solution: + def minSessions(self, tasks: List[int], sessionTime: int) -> int: + # Returns True if we can assign tasks[s..n) to `sessions`. Note that `sessions` + # may be occupied by some tasks. + def dfs(s: int, sessions: List[int]) -> bool: + if s == len(tasks): + return True + + for i, session in enumerate(sessions): + # Can't assign the tasks[s] to this session. + if session + tasks[s] > sessionTime: + continue + # Assign the tasks[s] to this session. + sessions[i] += tasks[s] + if dfs(s + 1, sessions): + return True + # Backtracking. + sessions[i] -= tasks[s] + # If it's the first time we assign the tasks[s] to this session, then future + # `session`s can't satisfy either. + if sessions[i] == 0: + return False + + return False + + for numSessions in range(1, len(tasks) + 1): + if dfs(0, [0] * numSessions): + return numSessions diff --git a/solutions/1987. Number of Unique Good Subsequences/1987.cpp b/solutions/1987. Number of Unique Good Subsequences/1987.cpp new file mode 100644 index 00000000000..10bfe7c618e --- /dev/null +++ b/solutions/1987. Number of Unique Good Subsequences/1987.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + // Similar to 940. Distinct Subsequences II + int numberOfUniqueGoodSubsequences(string binary) { + constexpr int kMod = 1'000'000'007; + // endsIn[i] := the number of subsequence that end in ('0' + i) + vector endsIn(2); + + for (const char c : binary) { + endsIn[c - '0'] = (endsIn[0] + endsIn[1]) % kMod; + // Don't count '0' since we want to avoid the leading zeros case. + // However, we can always count '1'. + if (c == '1') + ++endsIn[1]; + } + + // Count '0' in the end. + return (endsIn[0] + endsIn[1] + + (binary.find('0') == string::npos ? 0 : 1)) % + kMod; + } +}; diff --git a/solutions/1987. Number of Unique Good Subsequences/1987.java b/solutions/1987. Number of Unique Good Subsequences/1987.java new file mode 100644 index 00000000000..81658ae3ba5 --- /dev/null +++ b/solutions/1987. Number of Unique Good Subsequences/1987.java @@ -0,0 +1,19 @@ +class Solution { + // Similar to 940. Distinct Subsequences II + public int numberOfUniqueGoodSubsequences(String binary) { + final int kMod = 1_000_000_007; + // endsIn[i] := the number of subsequence that end in ('0' + i) + int[] endsIn = new int[2]; + + for (final char c : binary.toCharArray()) { + endsIn[c - '0'] = (endsIn[0] + endsIn[1]) % kMod; + // Don't count '0' since we want to avoid the leading zeros case. + // However, we can always count '1'. + if (c == '1') + ++endsIn[1]; + } + + // Count '0' in the end. + return (endsIn[0] + endsIn[1] + (binary.indexOf('0') == -1 ? 0 : 1)) % kMod; + } +} diff --git a/solutions/1987. Number of Unique Good Subsequences/1987.py b/solutions/1987. Number of Unique Good Subsequences/1987.py new file mode 100644 index 00000000000..04f76b83cca --- /dev/null +++ b/solutions/1987. Number of Unique Good Subsequences/1987.py @@ -0,0 +1,16 @@ +class Solution: + # Similar to 940. Distinct Subsequences II + def numberOfUniqueGoodSubsequences(self, binary: str) -> int: + kMod = 1_000_000_007 + # endsIn[i] := the number of subsequence that end in ('0' + i) + endsIn = {'0': 0, '1': 0} + + for c in binary: + endsIn[c] = sum(endsIn.values()) % kMod + # Don't count '0' since we want to avoid the leading zeros case. + # However, we can always count '1'. + if c == '1': + endsIn['1'] += 1 + + # Count '0' in the end. + return (sum(endsIn.values()) + ('0' in binary)) % kMod diff --git a/solutions/1988. Find Cutoff Score for Each School/1988.sql b/solutions/1988. Find Cutoff Score for Each School/1988.sql new file mode 100644 index 00000000000..85136e6d60d --- /dev/null +++ b/solutions/1988. Find Cutoff Score for Each School/1988.sql @@ -0,0 +1,7 @@ +SELECT + Schools.school_id, + IFNULL(MIN(Exam.score), -1) AS score +FROM Schools +LEFT JOIN Exam + ON (capacity >= student_count) +GROUP BY 1; diff --git a/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.cpp b/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.cpp new file mode 100644 index 00000000000..549e6ea669f --- /dev/null +++ b/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int catchMaximumAmountofPeople(vector& team, int dist) { + int ans = 0; + int i = 0; // 0s index + int j = 0; // 1s index + + while (i < team.size() && j < team.size()) + if (i + dist < j || team[i] != 0) { + // Find the next 0 that can be caught by 1. + ++i; + } else if (j + dist < i || team[j] != 1) { + // Find the next 1 that can catch 0. + ++j; + } else { + // team[j] catches team[i], so move both. + ++ans; + ++i; + ++j; + } + + return ans; + } +}; diff --git a/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.java b/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.java new file mode 100644 index 00000000000..e2151a3b662 --- /dev/null +++ b/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.java @@ -0,0 +1,23 @@ +class Solution { + public int catchMaximumAmountofPeople(int[] team, int dist) { + int ans = 0; + int i = 0; // 0s index + int j = 0; // 1s index + + while (i < team.length && j < team.length) + if (i + dist < j || team[i] != 0) { + // Find the next 0 that can be caught by 1. + ++i; + } else if (j + dist < i || team[j] != 1) { + // Find the next 1 that can catch 0. + ++j; + } else { + // team[j] catches team[i], so move both. + ++ans; + ++i; + ++j; + } + + return ans; + } +} diff --git a/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.py b/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.py new file mode 100644 index 00000000000..32e6f9e9ca8 --- /dev/null +++ b/solutions/1989. Maximum Number of People That Can Be Caught in Tag/1989.py @@ -0,0 +1,20 @@ +class Solution: + def catchMaximumAmountofPeople(self, team: List[int], dist: int) -> int: + ans = 0 + i = 0 # 0s index + j = 0 # 1s index + + while i < len(team) and j < len(team): + if i + dist < j or team[i] != 0: + # Find the next 0 that can be caught by 1. + i += 1 + elif j + dist < i or team[j] != 1: + # Find the next 1 that can catch 0. + j += 1 + else: + # team[j] catches team[i], so move both. + ans += 1 + i += 1 + j += 1 + + return ans diff --git a/solutions/199. Binary Tree Right Side View/199-2.cpp b/solutions/199. Binary Tree Right Side View/199-2.cpp new file mode 100644 index 00000000000..b28f5ebbbf0 --- /dev/null +++ b/solutions/199. Binary Tree Right Side View/199-2.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector rightSideView(TreeNode* root) { + vector ans; + dfs(root, 0, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int depth, vector& ans) { + if (root == nullptr) + return; + + if (depth == ans.size()) + ans.push_back(root->val); + dfs(root->right, depth + 1, ans); + dfs(root->left, depth + 1, ans); + } +}; diff --git a/solutions/199. Binary Tree Right Side View/199-2.java b/solutions/199. Binary Tree Right Side View/199-2.java new file mode 100644 index 00000000000..813ff92d1f0 --- /dev/null +++ b/solutions/199. Binary Tree Right Side View/199-2.java @@ -0,0 +1,17 @@ +class Solution { + public List rightSideView(TreeNode root) { + List ans = new ArrayList<>(); + dfs(root, 0, ans); + return ans; + } + + private void dfs(TreeNode root, int depth, List ans) { + if (root == null) + return; + + if (depth == ans.size()) + ans.add(root.val); + dfs(root.right, depth + 1, ans); + dfs(root.left, depth + 1, ans); + } +} diff --git a/solutions/199. Binary Tree Right Side View/199-2.py b/solutions/199. Binary Tree Right Side View/199-2.py new file mode 100644 index 00000000000..71ccb521c83 --- /dev/null +++ b/solutions/199. Binary Tree Right Side View/199-2.py @@ -0,0 +1,15 @@ +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + + def dfs(root: Optional[TreeNode], depth: int) -> None: + if not root: + return + + if depth == len(ans): + ans.append(root.val) + dfs(root.right, depth + 1) + dfs(root.left, depth + 1) + + dfs(root, 0) + return ans diff --git a/solutions/199. Binary Tree Right Side View/199.cpp b/solutions/199. Binary Tree Right Side View/199.cpp new file mode 100644 index 00000000000..4b5c60f4513 --- /dev/null +++ b/solutions/199. Binary Tree Right Side View/199.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector rightSideView(TreeNode* root) { + if (root == nullptr) + return {}; + + vector ans; + queue q{{root}}; + + while (!q.empty()) { + const int size = q.size(); + for (int i = 0; i < size; ++i) { + TreeNode* node = q.front(); + q.pop(); + if (i == size - 1) + ans.push_back(node->val); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + } + + return ans; + } +}; diff --git a/solutions/199. Binary Tree Right Side View/199.java b/solutions/199. Binary Tree Right Side View/199.java new file mode 100644 index 00000000000..407e756fe28 --- /dev/null +++ b/solutions/199. Binary Tree Right Side View/199.java @@ -0,0 +1,24 @@ +class Solution { + public List rightSideView(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + final int size = q.size(); + for (int i = 0; i < size; ++i) { + TreeNode node = q.poll(); + if (i == size - 1) + ans.add(node.val); + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + } + + return ans; + } +} diff --git a/solutions/199. Binary Tree Right Side View/199.py b/solutions/199. Binary Tree Right Side View/199.py new file mode 100644 index 00000000000..2a367ef2b66 --- /dev/null +++ b/solutions/199. Binary Tree Right Side View/199.py @@ -0,0 +1,20 @@ +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + ans = [] + q = collections.deque([root]) + + while q: + size = len(q) + for i in range(size): + root = q.popleft() + if i == size - 1: + ans.append(root.val) + if root.left: + q.append(root.left) + if root.right: + q.append(root.right) + + return ans diff --git a/solutions/1990. Count the Number of Experiments/1990.sql b/solutions/1990. Count the Number of Experiments/1990.sql new file mode 100644 index 00000000000..577c2362466 --- /dev/null +++ b/solutions/1990. Count the Number of Experiments/1990.sql @@ -0,0 +1,24 @@ +WITH + Platforms AS ( + SELECT 'Android' AS platform + UNION ALL + SELECT 'IOS' AS platform + UNION ALL + SELECT 'Web' AS platform + ), + ExperimentNames AS ( + SELECT 'Reading' AS experiment_name + UNION ALL + SELECT 'Sports' + UNION ALL + SELECT 'Programming' + ) +SELECT + Platforms.platform, + ExperimentNames.experiment_name, + COUNT(experiment_id) AS num_experiments +FROM Platforms +CROSS JOIN ExperimentNames +LEFT JOIN Experiments + USING (platform, experiment_name) +GROUP BY 1, 2; diff --git a/solutions/1991. Find the Middle Index in Array/1991.cpp b/solutions/1991. Find the Middle Index in Array/1991.cpp new file mode 100644 index 00000000000..1cc5e74cf7e --- /dev/null +++ b/solutions/1991. Find the Middle Index in Array/1991.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int findMiddleIndex(vector& nums) { + int prefix = 0; + int suffix = accumulate(nums.begin(), nums.end(), 0); + + for (int i = 0; i < nums.size(); ++i) { + suffix -= nums[i]; + if (prefix == suffix) + return i; + prefix += nums[i]; + } + + return -1; + } +}; diff --git a/solutions/1991. Find the Middle Index in Array/1991.java b/solutions/1991. Find the Middle Index in Array/1991.java new file mode 100644 index 00000000000..53961b7cf2e --- /dev/null +++ b/solutions/1991. Find the Middle Index in Array/1991.java @@ -0,0 +1,15 @@ +class Solution { + public int findMiddleIndex(int[] nums) { + int prefix = 0; + int suffix = Arrays.stream(nums).sum(); + + for (int i = 0; i < nums.length; ++i) { + suffix -= nums[i]; + if (prefix == suffix) + return i; + prefix += nums[i]; + } + + return -1; + } +} diff --git a/solutions/1991. Find the Middle Index in Array/1991.py b/solutions/1991. Find the Middle Index in Array/1991.py new file mode 100644 index 00000000000..eb1f9c40886 --- /dev/null +++ b/solutions/1991. Find the Middle Index in Array/1991.py @@ -0,0 +1,12 @@ +class Solution: + def findMiddleIndex(self, nums: List[int]) -> int: + prefix = 0 + suffix = sum(nums) + + for i, num in enumerate(nums): + suffix -= num + if prefix == suffix: + return i + prefix += num + + return -1 diff --git a/solutions/1992. Find All Groups of Farmland/1992.cpp b/solutions/1992. Find All Groups of Farmland/1992.cpp new file mode 100644 index 00000000000..3e6c4f217dc --- /dev/null +++ b/solutions/1992. Find All Groups of Farmland/1992.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector> findFarmland(vector>& land) { + vector> ans; + + for (int i = 0; i < land.size(); ++i) + for (int j = 0; j < land[0].size(); ++j) + if (land[i][j] == 1) { + int x = i; + int y = j; + dfs(land, i, j, x, y); + ans.push_back({i, j, x, y}); + } + + return ans; + } + + private: + void dfs(vector>& land, int i, int j, int& x, int& y) { + if (i < 0 || i == land.size() || j < 0 || j == land[0].size()) + return; + if (land[i][j] != 1) + return; + land[i][j] = 2; // Mark as visited. + x = max(x, i); + y = max(y, j); + dfs(land, i + 1, j, x, y); + dfs(land, i, j + 1, x, y); + } +}; diff --git a/solutions/1992. Find All Groups of Farmland/1992.java b/solutions/1992. Find All Groups of Farmland/1992.java new file mode 100644 index 00000000000..fb2fcfd0109 --- /dev/null +++ b/solutions/1992. Find All Groups of Farmland/1992.java @@ -0,0 +1,27 @@ +class Solution { + public int[][] findFarmland(int[][] land) { + List ans = new ArrayList<>(); + + for (int i = 0; i < land.length; ++i) + for (int j = 0; j < land[0].length; ++j) + if (land[i][j] == 1) { + int[] cell = new int[] {i, j}; + dfs(land, i, j, cell); + ans.add(new int[] {i, j, cell[0], cell[1]}); + } + + return ans.stream().toArray(int[][] ::new); + } + + private void dfs(int[][] land, int i, int j, int[] cell) { + if (i < 0 || i == land.length || j < 0 || j == land[0].length) + return; + if (land[i][j] != 1) + return; + land[i][j] = 2; // Mark as visited. + cell[0] = Math.max(cell[0], i); + cell[1] = Math.max(cell[1], j); + dfs(land, i + 1, j, cell); + dfs(land, i, j + 1, cell); + } +} diff --git a/solutions/1992. Find All Groups of Farmland/1992.py b/solutions/1992. Find All Groups of Farmland/1992.py new file mode 100644 index 00000000000..de3ffbfecbd --- /dev/null +++ b/solutions/1992. Find All Groups of Farmland/1992.py @@ -0,0 +1,23 @@ +class Solution: + def findFarmland(self, land: List[List[int]]) -> List[List[int]]: + ans = [] + + def dfs(i: int, j: int, cell: List[int]) -> None: + if i < 0 or i == len(land) or j < 0 or j == len(land[0]): + return + if land[i][j] != 1: + return + land[i][j] = 2 # Mark as visited. + cell[0] = max(cell[0], i) + cell[1] = max(cell[1], j) + dfs(i + 1, j, cell) + dfs(i, j + 1, cell) + + for i in range(len(land)): + for j in range(len(land[0])): + if land[i][j] == 1: + cell = [i, j] + dfs(i, j, cell) + ans.append([i, j, *cell]) + + return ans diff --git a/solutions/1993. Operations on Tree/1993.cpp b/solutions/1993. Operations on Tree/1993.cpp new file mode 100644 index 00000000000..15e748215e8 --- /dev/null +++ b/solutions/1993. Operations on Tree/1993.cpp @@ -0,0 +1,57 @@ +struct Node { + vector children; + int lockedBy = -1; +}; + +class LockingTree { + public: + LockingTree(vector& parent) : parent(parent) { + nodes.resize(parent.size()); + for (int i = 1; i < parent.size(); ++i) + nodes[parent[i]].children.push_back(i); + } + + bool lock(int num, int user) { + if (nodes[num].lockedBy != -1) + return false; + return nodes[num].lockedBy = user; + } + + bool unlock(int num, int user) { + if (nodes[num].lockedBy != user) + return false; + return nodes[num].lockedBy = -1; + } + + bool upgrade(int num, int user) { + if (nodes[num].lockedBy != -1) + return false; + if (!anyLockedDescendant(num)) + return false; + + // Walk up the hierarchy to ensure that there are no locked ancestors. + for (int i = num; i != -1; i = parent[i]) + if (nodes[i].lockedBy != -1) + return false; + + unlockDescendants(num); + return nodes[num].lockedBy = user; + } + + bool anyLockedDescendant(int i) { + return nodes[i].lockedBy != -1 || + ranges::any_of(nodes[i].children, [=](const int child) { + return anyLockedDescendant(child); + }); + } + + void unlockDescendants(int i) { + nodes[i].lockedBy = -1; + for (const int child : nodes[i].children) + unlockDescendants(child); + } + + private: + const vector parent; + vector nodes; +}; diff --git a/solutions/1993. Operations on Tree/1993.java b/solutions/1993. Operations on Tree/1993.java new file mode 100644 index 00000000000..bbe7aa216ec --- /dev/null +++ b/solutions/1993. Operations on Tree/1993.java @@ -0,0 +1,59 @@ +class Node { + public List children = new ArrayList<>(); + public int lockedBy = -1; +} + +class LockingTree { + public LockingTree(int[] parent) { + this.parent = parent; + nodes = new Node[parent.length]; + for (int i = 0; i < parent.length; ++i) + nodes[i] = new Node(); + for (int i = 1; i < parent.length; ++i) + nodes[parent[i]].children.add(i); + } + + public boolean lock(int num, int user) { + if (nodes[num].lockedBy != -1) + return false; + nodes[num].lockedBy = user; + return true; + } + + public boolean unlock(int num, int user) { + if (nodes[num].lockedBy != user) + return false; + nodes[num].lockedBy = -1; + return true; + } + + public boolean upgrade(int num, int user) { + if (nodes[num].lockedBy != -1) + return false; + if (!anyLockedDescendant(num)) + return false; + + // Walk up the hierarchy to ensure that there are no locked ancestors. + for (int i = num; i != -1; i = parent[i]) + if (nodes[i].lockedBy != -1) + return false; + + unlockDescendants(num); + nodes[num].lockedBy = user; + return true; + } + + public boolean anyLockedDescendant(int i) { + return nodes[i].lockedBy != -1 || + nodes[i].children.stream().anyMatch(child -> anyLockedDescendant(child)); + } + + public void unlockDescendants(int i) { + nodes[i].lockedBy = -1; + for (final int child : nodes[i].children) + unlockDescendants(child); + } + + private int[] parent; + private Node[] nodes; +} diff --git a/solutions/1993. Operations on Tree/1993.py b/solutions/1993. Operations on Tree/1993.py new file mode 100644 index 00000000000..18909ede3bd --- /dev/null +++ b/solutions/1993. Operations on Tree/1993.py @@ -0,0 +1,51 @@ +class Node: + def __init__(self): + self.children: List[int] = [] + self.lockedBy = -1 + + +class LockingTree: + def __init__(self, parent: List[int]): + self.parent = parent + self.nodes = [Node() for _ in range(len(parent))] + for i in range(1, len(parent)): + self.nodes[parent[i]].children.append(i) + + def lock(self, num: int, user: int) -> bool: + if self.nodes[num].lockedBy != -1: + return False + self.nodes[num].lockedBy = user + return True + + def unlock(self, num: int, user: int) -> bool: + if self.nodes[num].lockedBy != user: + return False + self.nodes[num].lockedBy = -1 + return True + + def upgrade(self, num: int, user: int) -> bool: + if self.nodes[num].lockedBy != -1: + return False + if not self._anyLockedDescendant(num): + return False + + # Walk up the hierarchy to ensure that there are no locked ancestors. + i = num + while i != -1: + if self.nodes[i].lockedBy != -1: + return False + i = self.parent[i] + + self._unlockDescendants(num) + self.nodes[num].lockedBy = user + return True + + def _anyLockedDescendant(self, i: int) -> bool: + return self.nodes[i].lockedBy != -1 or \ + any(self._anyLockedDescendant(child) + for child in self.nodes[i].children) + + def _unlockDescendants(self, i: int) -> None: + self.nodes[i].lockedBy = -1 + for child in self.nodes[i].children: + self._unlockDescendants(child) diff --git a/solutions/1994. The Number of Good Subsets/1994.cpp b/solutions/1994. The Number of Good Subsets/1994.cpp new file mode 100644 index 00000000000..8b3aadfa911 --- /dev/null +++ b/solutions/1994. The Number of Good Subsets/1994.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int numberOfGoodSubsets(vector& nums) { + const vector primes{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + const int n = 1 << primes.size(); + const int maxNum = ranges::max(nums); + vector dp(n); + vector count(maxNum + 1); + + dp[0] = 1; + + for (const int num : nums) + ++count[num]; + + for (int num = 2; num <= maxNum; ++num) { + if (count[num] == 0) + continue; + if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0) + continue; + const int numPrimesMask = getPrimesMask(num, primes); + for (int primesMask = 0; primesMask < n; ++primesMask) { + if ((primesMask & numPrimesMask) > 0) + continue; + const int nextPrimesMask = primesMask | numPrimesMask; + dp[nextPrimesMask] += dp[primesMask] * count[num]; + dp[nextPrimesMask] %= kMod; + } + } + + return modPow(2, count[1]) * + (accumulate(dp.begin() + 1, dp.end(), 0L) % kMod) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + int getPrimesMask(int num, const vector& primes) { + int primesMask = 0; + for (int i = 0; i < primes.size(); ++i) + if (num % primes[i] == 0) + primesMask |= 1 << i; + return primesMask; + } + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/1994. The Number of Good Subsets/1994.java b/solutions/1994. The Number of Good Subsets/1994.java new file mode 100644 index 00000000000..81ec47cf752 --- /dev/null +++ b/solutions/1994. The Number of Good Subsets/1994.java @@ -0,0 +1,49 @@ +class Solution { + public int numberOfGoodSubsets(int[] nums) { + final int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + final int n = 1 << primes.length; + final int maxNum = Arrays.stream(nums).max().getAsInt(); + long[] dp = new long[n]; + int[] count = new int[maxNum + 1]; + + dp[0] = 1; + + for (final int num : nums) + ++count[num]; + + for (int num = 2; num <= maxNum; ++num) { + if (count[num] == 0) + continue; + if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0) + continue; + final int numPrimesMask = getPrimesMask(num, primes); + for (int primesMask = 0; primesMask < n; ++primesMask) { + if ((primesMask & numPrimesMask) > 0) + continue; + final int nextPrimesMask = primesMask | numPrimesMask; + dp[nextPrimesMask] += dp[primesMask] * count[num]; + dp[nextPrimesMask] %= kMod; + } + } + + return (int) (modPow(2, count[1]) * ((Arrays.stream(dp).sum() - 1) % kMod) % kMod); + } + + private static final int kMod = 1_000_000_007; + + private int getPrimesMask(int num, int[] primes) { + int primesMask = 0; + for (int i = 0; i < primes.length; ++i) + if (num % primes[i] == 0) + primesMask |= 1 << i; + return primesMask; + } + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } +} diff --git a/solutions/1994. The Number of Good Subsets/1994.py b/solutions/1994. The Number of Good Subsets/1994.py new file mode 100644 index 00000000000..edb42141275 --- /dev/null +++ b/solutions/1994. The Number of Good Subsets/1994.py @@ -0,0 +1,26 @@ +class Solution: + def numberOfGoodSubsets(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + n = 1 << len(primes) + # dp[i] := the number of good subsets with set of primes = i bit mask + dp = [1] + [0] * (n - 1) + count = collections.Counter(nums) + + for num, freq in count.items(): + if num == 1: + continue + if any(num % squared == 0 for squared in [4, 9, 25]): + continue + numPrimesMask = sum(1 << i + for i, prime in enumerate(primes) + if num % prime == 0) + for primesMask in range(n): + # Skip since there're commen set of primes (becomes invalid subset) + if primesMask & numPrimesMask > 0: + continue + nextPrimesMask = numPrimesMask | primesMask + dp[nextPrimesMask] += dp[primesMask] * freq + dp[nextPrimesMask] %= kMod + + return (1 << count[1]) * sum(dp[1:]) % kMod diff --git a/solutions/1995. Count Special Quadruplets/1995-2.cpp b/solutions/1995. Count Special Quadruplets/1995-2.cpp new file mode 100644 index 00000000000..8b273ee2271 --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995-2.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countQuadruplets(vector& nums) { + const int n = nums.size(); + int ans = 0; + unordered_map count; + + for (int c = n - 1; c > 1; --c) { // `c` also represents `d`. + for (int b = c - 1; b > 0; --b) + for (int a = b - 1; a >= 0; --a) + if (const auto it = count.find(nums[a] + nums[b] + nums[c]); + it != count.cend()) + ans += it->second; + ++count[nums[c]]; // c := d + } + + return ans; + } +}; diff --git a/solutions/1995. Count Special Quadruplets/1995-2.java b/solutions/1995. Count Special Quadruplets/1995-2.java new file mode 100644 index 00000000000..3a8618da420 --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995-2.java @@ -0,0 +1,16 @@ +class Solution { + public int countQuadruplets(int[] nums) { + final int n = nums.length; + int ans = 0; + Map count = new HashMap<>(); + + for (int c = n - 1; c > 1; --c) { // `c` also represents `d`. + for (int b = c - 1; b > 0; --b) + for (int a = b - 1; a >= 0; --a) + ans += count.getOrDefault(nums[a] + nums[b] + nums[c], 0); + count.merge(nums[c], 1, Integer::sum); // c := d + } + + return ans; + } +} diff --git a/solutions/1995. Count Special Quadruplets/1995-2.py b/solutions/1995. Count Special Quadruplets/1995-2.py new file mode 100644 index 00000000000..0097c3dae92 --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995-2.py @@ -0,0 +1,13 @@ +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + count = collections.Counter() + + for c in range(n - 1, 1, -1): # `c` also represents `d`. + for b in range(c - 1, 0, -1): + for a in range(b - 1, -1, -1): + ans += count[nums[a] + nums[b] + nums[c]] + count[nums[c]] += 1 # c := d + + return ans diff --git a/solutions/1995. Count Special Quadruplets/1995-3.cpp b/solutions/1995. Count Special Quadruplets/1995-3.cpp new file mode 100644 index 00000000000..930f8beddca --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995-3.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int countQuadruplets(vector& nums) { + const int n = nums.size(); + int ans = 0; + unordered_map count; + + // nums[a] + nums[b] + nums[c] == nums[d] + // => nums[a] + nums[b] == nums[d] - nums[c] + for (int b = n - 1; b > 0; --b) { // `b` also represents `c`. + for (int a = b - 1; a >= 0; --a) + if (const auto it = count.find(nums[a] + nums[b]); it != count.cend()) + ans += it->second; + for (int d = n - 1; d > b; --d) + ++count[nums[d] - nums[b]]; // b := c + } + + return ans; + } +}; diff --git a/solutions/1995. Count Special Quadruplets/1995-3.java b/solutions/1995. Count Special Quadruplets/1995-3.java new file mode 100644 index 00000000000..e91c0c455a3 --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995-3.java @@ -0,0 +1,18 @@ +class Solution { + public int countQuadruplets(int[] nums) { + final int n = nums.length; + int ans = 0; + Map count = new HashMap<>(); + + // nums[a] + nums[b] + nums[c] == nums[d] + // => nums[a] + nums[b] == nums[d] - nums[c] + for (int b = n - 1; b > 0; --b) { // `b` also represents `c`. + for (int a = b - 1; a >= 0; --a) + ans += count.getOrDefault(nums[a] + nums[b], 0); + for (int d = n - 1; d > b; --d) + count.merge(nums[d] - nums[b], 1, Integer::sum); // b := c + } + + return ans; + } +} diff --git a/solutions/1995. Count Special Quadruplets/1995-3.py b/solutions/1995. Count Special Quadruplets/1995-3.py new file mode 100644 index 00000000000..cd545c8c6f1 --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995-3.py @@ -0,0 +1,15 @@ +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + count = collections.Counter() + + # nums[a] + nums[b] + nums[c] == nums[d] + # => nums[a] + nums[b] == nums[d] - nums[c] + for b in range(n - 1, 0, -1): # `b` also represents `c`. + for a in range(b - 1, -1, -1): + ans += count[nums[a] + nums[b]] + for d in range(n - 1, b, -1): + count[nums[d] - nums[b]] += 1 # b := c + + return ans diff --git a/solutions/1995. Count Special Quadruplets/1995.cpp b/solutions/1995. Count Special Quadruplets/1995.cpp new file mode 100644 index 00000000000..20135aefded --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int countQuadruplets(std::vector& nums) { + const int n = nums.size(); + int ans = 0; + + for (int a = 0; a < n; ++a) + for (int b = a + 1; b < n; ++b) + for (int c = b + 1; c < n; ++c) + for (int d = c + 1; d < n; ++d) + if (nums[a] + nums[b] + nums[c] == nums[d]) + ++ans; + + return ans; + } +}; diff --git a/solutions/1995. Count Special Quadruplets/1995.java b/solutions/1995. Count Special Quadruplets/1995.java new file mode 100644 index 00000000000..903b2001df2 --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995.java @@ -0,0 +1,15 @@ +class Solution { + public int countQuadruplets(int[] nums) { + final int n = nums.length; + int ans = 0; + + for (int a = 0; a < n; ++a) + for (int b = a + 1; b < n; ++b) + for (int c = b + 1; c < n; ++c) + for (int d = c + 1; d < n; ++d) + if (nums[a] + nums[b] + nums[c] == nums[d]) + ++ans; + + return ans; + } +} diff --git a/solutions/1995. Count Special Quadruplets/1995.py b/solutions/1995. Count Special Quadruplets/1995.py new file mode 100644 index 00000000000..fe96ef6a21a --- /dev/null +++ b/solutions/1995. Count Special Quadruplets/1995.py @@ -0,0 +1,8 @@ +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + n = len(nums) + return sum(nums[a] + nums[b] + nums[c] == nums[d] + for a in range(n) + for b in range(a + 1, n) + for c in range(b + 1, n) + for d in range(c + 1, n)) diff --git a/solutions/1996. The Number of Weak Characters in the Game/1996-2.cpp b/solutions/1996. The Number of Weak Characters in the Game/1996-2.cpp new file mode 100644 index 00000000000..7679c45f82f --- /dev/null +++ b/solutions/1996. The Number of Weak Characters in the Game/1996-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int numberOfWeakCharacters(vector>& properties) { + int ans = 0; + const int maxAttack = (*ranges::max_element( + properties, [](const vector& a, const vector& b) { + return a[0] < b[0]; + }))[0]; + // maxDefenses[i] := the maximum defense for the i-th attack + vector maxDefenses(maxAttack + 2); + + for (const vector& property : properties) { + const int attack = property[0]; + const int defense = property[1]; + maxDefenses[attack] = max(maxDefenses[attack], defense); + } + + for (int i = maxAttack; i >= 1; --i) + maxDefenses[i] = max(maxDefenses[i], maxDefenses[i + 1]); + + for (const vector& property : properties) { + const int attack = property[0]; + const int defense = property[1]; + if (maxDefenses[attack + 1] > defense) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/1996. The Number of Weak Characters in the Game/1996-2.java b/solutions/1996. The Number of Weak Characters in the Game/1996-2.java new file mode 100644 index 00000000000..46fff6c73e9 --- /dev/null +++ b/solutions/1996. The Number of Weak Characters in the Game/1996-2.java @@ -0,0 +1,26 @@ +class Solution { + public int numberOfWeakCharacters(int[][] properties) { + int ans = 0; + final int maxAttack = Arrays.stream(properties).mapToInt(p -> p[0]).max().getAsInt(); + // maxDefenses[i] := the maximum defense for the i-th attack + int[] maxDefenses = new int[maxAttack + 2]; + + for (int[] property : properties) { + final int attack = property[0]; + final int defense = property[1]; + maxDefenses[attack] = Math.max(maxDefenses[attack], defense); + } + + for (int i = maxAttack; i >= 1; --i) + maxDefenses[i] = Math.max(maxDefenses[i], maxDefenses[i + 1]); + + for (int[] property : properties) { + final int attack = property[0]; + final int defense = property[1]; + if (maxDefenses[attack + 1] > defense) + ++ans; + } + + return ans; + } +} diff --git a/solutions/1996. The Number of Weak Characters in the Game/1996-2.py b/solutions/1996. The Number of Weak Characters in the Game/1996-2.py new file mode 100644 index 00000000000..259379e190c --- /dev/null +++ b/solutions/1996. The Number of Weak Characters in the Game/1996-2.py @@ -0,0 +1,18 @@ +class Solution: + def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: + ans = 0 + maxAttack = max(attack for attack, _ in properties) + # maxDefenses[i] := the maximum defense for the i-th attack + maxDefenses = [0] * (maxAttack + 2) + + for attack, defense in properties: + maxDefenses[attack] = max(maxDefenses[attack], defense) + + for i in range(maxAttack, 0, -1): + maxDefenses[i] = max(maxDefenses[i], maxDefenses[i + 1]) + + for attack, defense in properties: + if maxDefenses[attack + 1] > defense: + ans += 1 + + return ans diff --git a/solutions/1996. The Number of Weak Characters in the Game/1996.cpp b/solutions/1996. The Number of Weak Characters in the Game/1996.cpp new file mode 100644 index 00000000000..1025f8df220 --- /dev/null +++ b/solutions/1996. The Number of Weak Characters in the Game/1996.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int numberOfWeakCharacters(vector>& properties) { + // Sort properties by `attack` in descending order, then by `defense` in + // ascending order. + ranges::sort(properties, [](const vector& a, const vector& b) { + return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0]; + }); + + int ans = 0; + int maxDefense = 0; + + for (const vector& property : properties) { + const int defense = property[1]; + if (defense < maxDefense) + ++ans; + maxDefense = max(maxDefense, defense); + } + + return ans; + } +}; diff --git a/solutions/1996. The Number of Weak Characters in the Game/1996.java b/solutions/1996. The Number of Weak Characters in the Game/1996.java new file mode 100644 index 00000000000..afe5360dea0 --- /dev/null +++ b/solutions/1996. The Number of Weak Characters in the Game/1996.java @@ -0,0 +1,19 @@ +class Solution { + public int numberOfWeakCharacters(int[][] properties) { + // Sort properties by `attack` in descending order, then by `defense` in + // ascending order. + Arrays.sort(properties, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); + + int ans = 0; + int maxDefense = 0; + + for (int[] property : properties) { + final int defense = property[1]; + if (defense < maxDefense) + ++ans; + maxDefense = Math.max(maxDefense, defense); + } + + return ans; + } +} diff --git a/solutions/1996. The Number of Weak Characters in the Game/1996.py b/solutions/1996. The Number of Weak Characters in the Game/1996.py new file mode 100644 index 00000000000..0d9bc789ac6 --- /dev/null +++ b/solutions/1996. The Number of Weak Characters in the Game/1996.py @@ -0,0 +1,13 @@ +class Solution: + def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: + ans = 0 + maxDefense = 0 + + # Sort properties by `attack` in descending order, then by `defense` in + # ascending order. + for _, defense in sorted(properties, key=lambda x: (-x[0], x[1])): + if defense < maxDefense: + ans += 1 + maxDefense = max(maxDefense, defense) + + return ans diff --git a/solutions/1997. First Day Where You Have Been in All the Rooms/1997.cpp b/solutions/1997. First Day Where You Have Been in All the Rooms/1997.cpp new file mode 100644 index 00000000000..fd2511a70d9 --- /dev/null +++ b/solutions/1997. First Day Where You Have Been in All the Rooms/1997.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int firstDayBeenInAllRooms(vector& nextVisit) { + constexpr int kMod = 1'000'000'007; + const int n = nextVisit.size(); + // dp[i] := the number of days to visit room i for the first time + vector dp(n); + + // Whenever we visit i, visit times of room[0..i - 1] are all even. + // Therefore, the rooms before i can be seen as reset and we can safely + // reuse dp[0..i - 1] as first-time visit to get second-time visit. + for (int i = 1; i < n; ++i) + // The total days to visit room[i] is the sum of + // * dp[i - 1]: 1st-time visit room[i - 1] + // * 1: visit room[nextVisit[i - 1]] + // * dp[i - 1] - dp[nextVisit[i - 1]]: 2-time visit room[i - 1] + // * 1: visit room[i] + dp[i] = (2L * dp[i - 1] - dp[nextVisit[i - 1]] + 2 + kMod) % kMod; + + return dp.back(); + } +}; diff --git a/solutions/1997. First Day Where You Have Been in All the Rooms/1997.java b/solutions/1997. First Day Where You Have Been in All the Rooms/1997.java new file mode 100644 index 00000000000..37daa68cd47 --- /dev/null +++ b/solutions/1997. First Day Where You Have Been in All the Rooms/1997.java @@ -0,0 +1,21 @@ +class Solution { + public int firstDayBeenInAllRooms(int[] nextVisit) { + final int kMod = 1_000_000_007; + final int n = nextVisit.length; + // dp[i] := the number of days to visit room i for the first time + int[] dp = new int[n]; + + // Whenever we visit i, visit times of room[0..i - 1] are all even. + // Therefore, the rooms before i can be seen as reset and we can safely + // reuse dp[0..i - 1] as first-time visit to get second-time visit. + for (int i = 1; i < n; ++i) + // The total days to visit room[i] is the sum of + // * dp[i - 1]: 1st-time visit room[i - 1] + // * 1: visit room[nextVisit[i - 1]] + // * dp[i - 1] - dp[nextVisit[i - 1]]: 2-time visit room[i - 1] + // * 1: visit room[i] + dp[i] = (int) ((2L * dp[i - 1] - dp[nextVisit[i - 1]] + 2 + kMod) % kMod); + + return dp[n - 1]; + } +} diff --git a/solutions/1997. First Day Where You Have Been in All the Rooms/1997.py b/solutions/1997. First Day Where You Have Been in All the Rooms/1997.py new file mode 100644 index 00000000000..943aeb84438 --- /dev/null +++ b/solutions/1997. First Day Where You Have Been in All the Rooms/1997.py @@ -0,0 +1,19 @@ +class Solution: + def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int: + kMod = 1_000_000_007 + n = len(nextVisit) + # dp[i] := the number of days to visit room i for the first time + dp = [0] * n + + # Whenever we visit i, visit times of room[0..i - 1] are all even. + # Therefore, the rooms before i can be seen as reset and we can safely + # reuse dp[0..i - 1] as first-time visit to get second-time visit. + for i in range(1, n): + # The total days to visit room[i] is the sum of + # * dp[i - 1]: 1st-time visit room[i - 1] + # * 1: visit room[nextVisit[i - 1]] + # * dp[i - 1] - dp[nextVisit[i - 1]]: 2-time visit room[i - 1] + # * 1: visit room[i] + dp[i] = (2 * dp[i - 1] - dp[nextVisit[i - 1]] + 2) % kMod + + return dp[-1] diff --git a/solutions/1998. GCD Sort of an Array/1998.cpp b/solutions/1998. GCD Sort of an Array/1998.cpp new file mode 100644 index 00000000000..de09787a3d3 --- /dev/null +++ b/solutions/1998. GCD Sort of an Array/1998.cpp @@ -0,0 +1,75 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + bool gcdSort(vector& nums) { + const int maxNum = ranges::max(nums); + const vector minPrimeFactors = sieveEratosthenes(maxNum + 1); + UnionFind uf(maxNum + 1); + + for (const int num : nums) + for (const int primeFactor : getPrimeFactors(num, minPrimeFactors)) + uf.unionByRank(num, primeFactor); + + vector sortedNums(nums); + ranges::sort(sortedNums); + + for (int i = 0; i < nums.size(); ++i) + // Can't swap nums[i] with sortedNums[i]. + if (uf.find(nums[i]) != uf.find(sortedNums[i])) + return false; + + return true; + } + + private: + // Gets the minimum prime factor of i, where 1 < i <= n. + vector sieveEratosthenes(int n) { + vector minPrimeFactors(n + 1); + iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + vector getPrimeFactors(int num, const vector& minPrimeFactors) { + vector primeFactors; + while (num > 1) { + const int divisor = minPrimeFactors[num]; + primeFactors.push_back(divisor); + while (num % divisor == 0) + num /= divisor; + } + return primeFactors; + } +}; diff --git a/solutions/1998. GCD Sort of an Array/1998.java b/solutions/1998. GCD Sort of an Array/1998.java new file mode 100644 index 00000000000..e36ca8146ce --- /dev/null +++ b/solutions/1998. GCD Sort of an Array/1998.java @@ -0,0 +1,75 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public boolean gcdSort(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + final int[] minPrimeFactors = sieveEratosthenes(maxNum + 1); + UnionFind uf = new UnionFind(maxNum + 1); + + for (final int num : nums) + for (final int primeFactor : getPrimeFactors(num, minPrimeFactors)) + uf.unionByRank(num, primeFactor); + + int[] sortedNums = nums.clone(); + Arrays.sort(sortedNums); + + for (int i = 0; i < nums.length; ++i) + // Can't swap nums[i] with sortedNums[i]. + if (uf.find(nums[i]) != uf.find(sortedNums[i])) + return false; + + return true; + } + + // Gets the minimum prime factor of i, where 1 < i <= n. + private int[] sieveEratosthenes(int n) { + int[] minPrimeFactors = new int[n + 1]; + for (int i = 2; i <= n; ++i) + minPrimeFactors[i] = i; + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + private List getPrimeFactors(int num, int[] minPrimeFactors) { + List primeFactors = new ArrayList<>(); + while (num > 1) { + final int divisor = minPrimeFactors[num]; + primeFactors.add(divisor); + while (num % divisor == 0) + num /= divisor; + } + return primeFactors; + } +} diff --git a/solutions/1998. GCD Sort of an Array/1998.py b/solutions/1998. GCD Sort of an Array/1998.py new file mode 100644 index 00000000000..6e94a6b213b --- /dev/null +++ b/solutions/1998. GCD Sort of an Array/1998.py @@ -0,0 +1,59 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return False + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + return True + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def gcdSort(self, nums: List[int]) -> bool: + maxNum = max(nums) + minPrimeFactors = self._sieveEratosthenes(maxNum + 1) + uf = UnionFind(maxNum + 1) + + for num in nums: + for primeFactor in self._getPrimeFactors(num, minPrimeFactors): + uf.unionByRank(num, primeFactor) + + for a, b in zip(nums, sorted(nums)): + # Can't swap nums[i] with sortedNums[i]. + if uf.find(a) != uf.find(b): + return False + + return True + + def _sieveEratosthenes(self, n: int) -> List[int]: + """Gets the minimum prime factor of i, where 1 < i <= n.""" + minPrimeFactors = [i for i in range(n + 1)] + for i in range(2, int(n**0.5) + 1): + if minPrimeFactors[i] == i: # `i` is prime. + for j in range(i * i, n, i): + minPrimeFactors[j] = min(minPrimeFactors[j], i) + return minPrimeFactors + + def _getPrimeFactors(self, num: int, minPrimeFactors: List[int]) -> List[int]: + primeFactors = [] + while num > 1: + divisor = minPrimeFactors[num] + primeFactors.append(divisor) + while num % divisor == 0: + num //= divisor + return primeFactors diff --git a/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.cpp b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.cpp new file mode 100644 index 00000000000..8681cbdccfb --- /dev/null +++ b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int findInteger(int k, int digit1, int digit2) { + return findInteger(k, digit1, digit2, 0); + } + + private: + int findInteger(int k, int d1, int d2, long x) { + if (x > INT_MAX) + return -1; + if (x > k && x % k == 0) + return x; + // Skip if d1/d2 and x are zero. + const int a = (x + d1 == 0) ? -1 : findInteger(k, d1, d2, x * 10 + d1); + const int b = (x + d2 == 0) ? -1 : findInteger(k, d1, d2, x * 10 + d2); + if (a == -1) + return b; + if (b == -1) + return a; + return min(a, b); + } +}; diff --git a/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.java b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.java new file mode 100644 index 00000000000..34e5ccf91d8 --- /dev/null +++ b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.java @@ -0,0 +1,20 @@ +class Solution { + public int findInteger(int k, int digit1, int digit2) { + return findInteger(k, digit1, digit2, 0); + } + + private int findInteger(int k, int d1, int d2, long x) { + if (x > Integer.MAX_VALUE) + return -1; + if (x > k && x % k == 0) + return (int) x; + // Skip if d1/d2 and x are zero. + final int a = (x + d1 == 0) ? -1 : findInteger(k, d1, d2, x * 10 + d1); + final int b = (x + d2 == 0) ? -1 : findInteger(k, d1, d2, x * 10 + d2); + if (a == -1) + return b; + if (b == -1) + return a; + return Math.min(a, b); + } +} diff --git a/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.py b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.py new file mode 100644 index 00000000000..786d2181e76 --- /dev/null +++ b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999-2.py @@ -0,0 +1,17 @@ +class Solution: + def findInteger(self, k: int, digit1: int, digit2: int) -> int: + def dfs(x: int) -> int: + if x > 2**31 - 1: + return -1 + if x > k and x % k == 0: + return x + # Skip if digit1/digit2 and x are zero. + a = -1 if x + digit1 == 0 else dfs(x * 10 + digit1) + b = -1 if x + digit2 == 0 else dfs(x * 10 + digit2) + if a == -1: + return b + if b == -1: + return a + return min(a, b) + + return dfs(0) diff --git a/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.cpp b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.cpp new file mode 100644 index 00000000000..70cea23b27d --- /dev/null +++ b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int findInteger(int k, int digit1, int digit2) { + const int minDigit = min(digit1, digit2); + const int maxDigit = max(digit1, digit2); + const vector digits = minDigit == maxDigit + ? vector{minDigit} + : vector{minDigit, maxDigit}; + queue q; + + for (const int digit : digits) + q.push(digit); + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + if (u > k && u % k == 0) + return u; + if (u == 0) + continue; + for (const int digit : digits) { + const long nextNum = u * 10L + digit; + if (nextNum > INT_MAX) + continue; + q.push(nextNum); + } + } + + return -1; + } +}; diff --git a/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.java b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.java new file mode 100644 index 00000000000..be1cb474c78 --- /dev/null +++ b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.java @@ -0,0 +1,28 @@ +class Solution { + public int findInteger(int k, int digit1, int digit2) { + final int minDigit = Math.min(digit1, digit2); + final int maxDigit = Math.max(digit1, digit2); + final int[] digits = + minDigit == maxDigit ? new int[] {minDigit} : new int[] {minDigit, maxDigit}; + Queue q = new ArrayDeque<>(); + + for (final int digit : digits) + q.offer(digit); + + while (!q.isEmpty()) { + final int u = q.poll(); + if (u > k && u % k == 0) + return u; + if (u == 0) + continue; + for (final int digit : digits) { + final long nextNum = u * 10L + digit; + if (nextNum > Integer.MAX_VALUE) + continue; + q.offer((int) nextNum); + } + } + + return -1; + } +} diff --git a/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.py b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.py new file mode 100644 index 00000000000..c3f7149e141 --- /dev/null +++ b/solutions/1999. Smallest Greater Multiple Made of Two Digits/1999.py @@ -0,0 +1,23 @@ +class Solution: + def findInteger(self, k: int, digit1: int, digit2: int) -> int: + minDigit = min(digit1, digit2) + maxDigit = max(digit1, digit2) + digits = [minDigit] if minDigit == maxDigit else [minDigit, maxDigit] + q = collections.deque() + + for digit in digits: + q.append(digit) + + while q: + u = q.popleft() + if u > k and u % k == 0: + return u + if u == 0: + continue + for digit in digits: + nextNum = u * 10 + digit + if nextNum > 2**31 - 1: + continue + q.append(nextNum) + + return -1 diff --git a/solutions/2. Add Two Numbers/2.cpp b/solutions/2. Add Two Numbers/2.cpp new file mode 100644 index 00000000000..4be12b44f8e --- /dev/null +++ b/solutions/2. Add Two Numbers/2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode dummy(0); + ListNode* curr = &dummy; + int carry = 0; + + while (l1 != nullptr || l2 != nullptr || carry > 0) { + if (l1 != nullptr) { + carry += l1->val; + l1 = l1->next; + } + if (l2 != nullptr) { + carry += l2->val; + l2 = l2->next; + } + curr->next = new ListNode(carry % 10); + carry /= 10; + curr = curr->next; + } + + return dummy.next; + } +}; diff --git a/solutions/2. Add Two Numbers/2.java b/solutions/2. Add Two Numbers/2.java new file mode 100644 index 00000000000..404a4877b2c --- /dev/null +++ b/solutions/2. Add Two Numbers/2.java @@ -0,0 +1,23 @@ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode curr = dummy; + int carry = 0; + + while (l1 != null || l2 != null || carry > 0) { + if (l1 != null) { + carry += l1.val; + l1 = l1.next; + } + if (l2 != null) { + carry += l2.val; + l2 = l2.next; + } + curr.next = new ListNode(carry % 10); + carry /= 10; + curr = curr.next; + } + + return dummy.next; + } +} diff --git a/solutions/2. Add Two Numbers/2.py b/solutions/2. Add Two Numbers/2.py new file mode 100644 index 00000000000..5482a0a7775 --- /dev/null +++ b/solutions/2. Add Two Numbers/2.py @@ -0,0 +1,18 @@ +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode(0) + curr = dummy + carry = 0 + + while carry or l1 or l2: + if l1: + carry += l1.val + l1 = l1.next + if l2: + carry += l2.val + l2 = l2.next + curr.next = ListNode(carry % 10) + carry //= 10 + curr = curr.next + + return dummy.next diff --git a/solutions/20. Valid Parentheses/20.cpp b/solutions/20. Valid Parentheses/20.cpp new file mode 100644 index 00000000000..9573d651059 --- /dev/null +++ b/solutions/20. Valid Parentheses/20.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool isValid(string s) { + stack stack; + + for (const char c : s) + if (c == '(') + stack.push(')'); + else if (c == '{') + stack.push('}'); + else if (c == '[') + stack.push(']'); + else if (stack.empty() || pop(stack) != c) + return false; + + return stack.empty(); + } + + private: + int pop(stack& stack) { + const int c = stack.top(); + stack.pop(); + return c; + } +}; diff --git a/solutions/20. Valid Parentheses/20.java b/solutions/20. Valid Parentheses/20.java new file mode 100644 index 00000000000..5e38fb5f9f0 --- /dev/null +++ b/solutions/20. Valid Parentheses/20.java @@ -0,0 +1,17 @@ +class Solution { + public boolean isValid(String s) { + Deque stack = new ArrayDeque<>(); + + for (final char c : s.toCharArray()) + if (c == '(') + stack.push(')'); + else if (c == '{') + stack.push('}'); + else if (c == '[') + stack.push(']'); + else if (stack.isEmpty() || stack.pop() != c) + return false; + + return stack.isEmpty(); + } +} diff --git a/solutions/20. Valid Parentheses/20.py b/solutions/20. Valid Parentheses/20.py new file mode 100644 index 00000000000..a708e404006 --- /dev/null +++ b/solutions/20. Valid Parentheses/20.py @@ -0,0 +1,15 @@ +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + + for c in s: + if c == '(': + stack.append(')') + elif c == '{': + stack.append('}') + elif c == '[': + stack.append(']') + elif not stack or stack.pop() != c: + return False + + return not stack diff --git a/solutions/200. Number of Islands/200-2.cpp b/solutions/200. Number of Islands/200-2.cpp new file mode 100644 index 00000000000..85bd5429ac2 --- /dev/null +++ b/solutions/200. Number of Islands/200-2.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int numIslands(vector>& grid) { + int ans = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == '1') { + dfs(grid, i, j); + ++ans; + } + + return ans; + } + + private: + void dfs(vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] != '1') + return; + + grid[i][j] = '2'; // Mark '2' as visited. + dfs(grid, i + 1, j); + dfs(grid, i - 1, j); + dfs(grid, i, j + 1); + dfs(grid, i, j - 1); + } +}; diff --git a/solutions/200. Number of Islands/200-2.java b/solutions/200. Number of Islands/200-2.java new file mode 100644 index 00000000000..d8a70428303 --- /dev/null +++ b/solutions/200. Number of Islands/200-2.java @@ -0,0 +1,27 @@ +class Solution { + public int numIslands(char[][] grid) { + int ans = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == '1') { + dfs(grid, i, j); + ++ans; + } + + return ans; + } + + private void dfs(char[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] != '1') + return; + + grid[i][j] = '2'; // Mark '2' as visited. + dfs(grid, i + 1, j); + dfs(grid, i - 1, j); + dfs(grid, i, j + 1); + dfs(grid, i, j - 1); + } +} diff --git a/solutions/200. Number of Islands/200-2.py b/solutions/200. Number of Islands/200-2.py new file mode 100644 index 00000000000..e6a5ef47319 --- /dev/null +++ b/solutions/200. Number of Islands/200-2.py @@ -0,0 +1,26 @@ +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + m = len(grid) + n = len(grid[0]) + + def dfs(i: int, j: int) -> None: + if i < 0 or i == m or j < 0 or j == n: + return + if grid[i][j] != '1': + return + + grid[i][j] = '2' # Mark '2' as visited. + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1) + + ans = 0 + + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + dfs(i, j) + ans += 1 + + return ans diff --git a/solutions/200. Number of Islands/200.cpp b/solutions/200. Number of Islands/200.cpp new file mode 100644 index 00000000000..0edaa4ba0fe --- /dev/null +++ b/solutions/200. Number of Islands/200.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int numIslands(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + + auto bfs = [&](int r, int c) { + queue> q{{{r, c}}}; + grid[r][c] = '2'; // Mark '2' as visited. + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] != '1') + continue; + q.emplace(x, y); + grid[x][y] = '2'; // Mark '2' as visited. + } + } + }; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == '1') { + bfs(i, j); + ++ans; + } + + return ans; + } +}; diff --git a/solutions/200. Number of Islands/200.java b/solutions/200. Number of Islands/200.java new file mode 100644 index 00000000000..44fe950f882 --- /dev/null +++ b/solutions/200. Number of Islands/200.java @@ -0,0 +1,36 @@ +class Solution { + public int numIslands(char[][] grid) { + int ans = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == '1') { + bfs(grid, i, j); + ++ans; + } + + return ans; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private void bfs(char[][] grid, int r, int c) { + Queue q = new ArrayDeque<>(); + q.offer(new int[] {r, c}); + grid[r][c] = '2'; // Mark '2' as visited. + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) + continue; + if (grid[x][y] != '1') + continue; + q.offer(new int[] {x, y}); + grid[x][y] = '2'; // Mark '2' as visited. + } + } + } +} diff --git a/solutions/200. Number of Islands/200.py b/solutions/200. Number of Islands/200.py new file mode 100644 index 00000000000..1c778aec09f --- /dev/null +++ b/solutions/200. Number of Islands/200.py @@ -0,0 +1,30 @@ +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + + def bfs(r, c): + q = collections.deque([(r, c)]) + grid[r][c] = '2' # Mark '2' as visited. + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if grid[x][y] != '1': + continue + q.append((x, y)) + grid[x][y] = '2' # Mark '2' as visited. + + ans = 0 + + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + bfs(i, j) + ans += 1 + + return ans diff --git a/solutions/2000. Reverse Prefix of Word/2000.cpp b/solutions/2000. Reverse Prefix of Word/2000.cpp new file mode 100644 index 00000000000..d77834ac7c7 --- /dev/null +++ b/solutions/2000. Reverse Prefix of Word/2000.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + string reversePrefix(string word, char ch) { + reverse(word.begin(), word.begin() + word.find(ch) + 1); + return word; + } +}; diff --git a/solutions/2000. Reverse Prefix of Word/2000.java b/solutions/2000. Reverse Prefix of Word/2000.java new file mode 100644 index 00000000000..dace0c7ff09 --- /dev/null +++ b/solutions/2000. Reverse Prefix of Word/2000.java @@ -0,0 +1,9 @@ +class Solution { + public String reversePrefix(String word, char ch) { + final int i = word.indexOf(ch) + 1; + return new StringBuilder(word.substring(0, i)) // + .reverse() // + .append(word.substring(i)) // + .toString(); + } +} diff --git a/solutions/2000. Reverse Prefix of Word/2000.py b/solutions/2000. Reverse Prefix of Word/2000.py new file mode 100644 index 00000000000..cb50bd1d29d --- /dev/null +++ b/solutions/2000. Reverse Prefix of Word/2000.py @@ -0,0 +1,4 @@ +class Solution: + def reversePrefix(self, word: str, ch: str) -> str: + i = word.find(ch) + 1 + return word[:i][::-1] + word[i:] diff --git a/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.cpp b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.cpp new file mode 100644 index 00000000000..503b2879652 --- /dev/null +++ b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + long long interchangeableRectangles(vector>& rectangles) { + long ans = 0; + unordered_map, int, PairHash> ratioCount; + + for (const vector& rectangle : rectangles) { + const int width = rectangle[0]; + const int height = rectangle[1]; + const int d = __gcd(width, height); + ++ratioCount[{width / d, height / d}]; + } + + for (const auto& [_, count] : ratioCount) + ans += static_cast(count) * (count - 1) / 2; + + return ans; + } + + private: + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.java b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.java new file mode 100644 index 00000000000..d3c7075854d --- /dev/null +++ b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.java @@ -0,0 +1,22 @@ +class Solution { + public long interchangeableRectangles(int[][] rectangles) { + long ans = 0; + Map, Integer> ratioCount = new HashMap<>(); + + for (int[] rectangle : rectangles) { + final int width = rectangle[0]; + final int height = rectangle[1]; + final int d = gcd(width, height); + ratioCount.merge(new Pair<>(width / d, height / d), 1, Integer::sum); + } + + for (final int count : ratioCount.values()) + ans += (long) count * (count - 1) / 2; + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.py b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.py new file mode 100644 index 00000000000..88a4c370b58 --- /dev/null +++ b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001-2.py @@ -0,0 +1,12 @@ +class Solution: + def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: + ratioCount = collections.Counter() + + def gcd(a: int, b: int) -> int: + return a if b == 0 else gcd(b, a % b) + + for width, height in rectangles: + d = gcd(width, height) + ratioCount[(width // d, height // d)] += 1 + + return sum(c * (c - 1) // 2 for c in ratioCount.values()) diff --git a/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.cpp b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.cpp new file mode 100644 index 00000000000..7d518209662 --- /dev/null +++ b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long long interchangeableRectangles(vector>& rectangles) { + long ans = 0; + unordered_map ratioCount; + + for (const vector& rectangle : rectangles) { + const int width = rectangle[0]; + const int height = rectangle[1]; + ++ratioCount[1.0 * width / height]; + } + + for (const auto& [_, count] : ratioCount) + ans += static_cast(count) * (count - 1) / 2; + + return ans; + } +}; diff --git a/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.java b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.java new file mode 100644 index 00000000000..37e906a8994 --- /dev/null +++ b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.java @@ -0,0 +1,17 @@ +class Solution { + public long interchangeableRectangles(int[][] rectangles) { + long ans = 0; + Map ratioCount = new HashMap<>(); + + for (int[] rectangle : rectangles) { + final int width = rectangle[0]; + final int height = rectangle[1]; + ratioCount.merge(1.0 * width / height, 1, Integer::sum); + } + + for (final int count : ratioCount.values()) + ans += 1L * count * (count - 1) / 2; + + return ans; + } +} diff --git a/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.py b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.py new file mode 100644 index 00000000000..0d336ecbdb0 --- /dev/null +++ b/solutions/2001. Number of Pairs of Interchangeable Rectangles/2001.py @@ -0,0 +1,9 @@ +class Solution: + def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: + ratioCount = collections.Counter() + + for width, height in rectangles: + ratioCount[width / height] += 1 + + return sum(count * (count - 1) // 2 + for count in ratioCount.values()) diff --git a/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.cpp b/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.cpp new file mode 100644 index 00000000000..91700945fd0 --- /dev/null +++ b/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int maxProduct(string s) { + size_t ans = 0; + dfs(s, 0, "", "", ans); + return ans; + } + + private: + void dfs(const string& s, int i, string&& s1, string&& s2, size_t& ans) { + if (i == s.length()) { + if (isPalindrome(s1) && isPalindrome(s2)) + ans = max(ans, s1.length() * s2.length()); + return; + } + + s1.push_back(s[i]); + dfs(s, i + 1, move(s1), move(s2), ans); + s1.pop_back(); + + s2.push_back(s[i]); + dfs(s, i + 1, move(s1), move(s2), ans); + s2.pop_back(); + + dfs(s, i + 1, move(s1), move(s2), ans); + } + + bool isPalindrome(const string& s) { + int i = 0; + int j = s.length() - 1; + while (i < j) { + if (s[i] != s[j]) + return false; + ++i; + --j; + } + return true; + } +}; diff --git a/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.java b/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.java new file mode 100644 index 00000000000..007e2f0e6bb --- /dev/null +++ b/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.java @@ -0,0 +1,38 @@ +class Solution { + public int maxProduct(String s) { + dfs(s, 0, new StringBuilder(), new StringBuilder()); + return ans; + } + + private int ans = 0; + + private void dfs(final String s, int i, StringBuilder sb1, StringBuilder sb2) { + if (i == s.length()) { + if (isPalindrome(sb1) && isPalindrome(sb2)) + ans = Math.max(ans, sb1.length() * sb2.length()); + return; + } + + final int sb1Length = sb1.length(); + dfs(s, i + 1, sb1.append(s.charAt(i)), sb2); + sb1.setLength(sb1Length); + + final int sb2Length = sb2.length(); + dfs(s, i + 1, sb1, sb2.append(s.charAt(i))); + sb2.setLength(sb2Length); + + dfs(s, i + 1, sb1, sb2); + } + + private boolean isPalindrome(StringBuilder sb) { + int i = 0; + int j = sb.length() - 1; + while (i < j) { + if (sb.charAt(i) != sb.charAt(j)) + return false; + ++i; + --j; + } + return true; + } +} diff --git a/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.py b/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.py new file mode 100644 index 00000000000..77d6b2c8f4e --- /dev/null +++ b/solutions/2002. Maximum Product of the Length of Two Palindromic Subsequences/2002.py @@ -0,0 +1,28 @@ +class Solution: + def maxProduct(self, s: str) -> int: + ans = 0 + + def isPalindrome(s: str) -> bool: + i = 0 + j = len(s) - 1 + while i < j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True + + @functools.lru_cache(None) + def dfs(i: int, s1: str, s2: str) -> None: + nonlocal ans + if i == len(s): + if isPalindrome(s1) and isPalindrome(s2): + ans = max(ans, len(s1) * len(s2)) + return + + dfs(i + 1, s1 + s[i], s2) + dfs(i + 1, s1, s2 + s[i]) + dfs(i + 1, s1, s2) + + dfs(0, '', '') + return ans diff --git a/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.cpp b/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.cpp new file mode 100644 index 00000000000..055dc87a5c0 --- /dev/null +++ b/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.cpp @@ -0,0 +1,53 @@ +class Solution { + public: + vector smallestMissingValueSubtree(vector& parents, + vector& nums) { + const int n = parents.size(); + vector ans(n, 1); + vector> tree(n); + unordered_set seen; + int minMiss = 1; + + for (int i = 1; i < n; ++i) + tree[parents[i]].push_back(i); + + int nodeThatsOne = getNode(nums); + if (nodeThatsOne == -1) + return ans; + + int u = nodeThatsOne; + int prev = -1; // the u that just handled + + // Upward from `nodeThatsOne` to the root `u`. + while (u != -1) { + for (const int v : tree[u]) { + if (v == prev) + continue; + dfs(v, tree, seen, nums); + } + seen.insert(nums[u]); + while (seen.contains(minMiss)) + ++minMiss; + ans[u] = minMiss; + prev = u; + u = parents[u]; + } + + return ans; + } + + private: + int getNode(const vector& nums) { + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == 1) + return i; + return -1; + } + + void dfs(int u, const vector>& tree, unordered_set& seen, + const vector& nums) { + seen.insert(nums[u]); + for (const int v : tree[u]) + dfs(v, tree, seen, nums); + } +}; diff --git a/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.java b/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.java new file mode 100644 index 00000000000..d176bfb38d1 --- /dev/null +++ b/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.java @@ -0,0 +1,53 @@ +class Solution { + public int[] smallestMissingValueSubtree(int[] parents, int[] nums) { + final int n = parents.length; + int[] ans = new int[n]; + Arrays.fill(ans, 1); + List[] tree = new List[n]; + Set seen = new HashSet<>(); + int minMiss = 1; + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int i = 1; i < n; ++i) + tree[parents[i]].add(i); + + final int nodeThatsOne = getNode(nums); + if (nodeThatsOne == -1) + return ans; + + int u = nodeThatsOne; + int prev = -1; // the u that just handled + + // Upward from `nodeThatsOne` to the root `u`. + while (u != -1) { + for (final int v : tree[u]) { + if (v == prev) + continue; + dfs(v, tree, seen, nums); + } + seen.add(nums[u]); + while (seen.contains(minMiss)) + ++minMiss; + ans[u] = minMiss; + prev = u; + u = parents[u]; + } + + return ans; + } + + private void dfs(int u, List[] tree, Set seen, int[] nums) { + seen.add(nums[u]); + for (final int v : tree[u]) + dfs(v, tree, seen, nums); + } + + private int getNode(int[] nums) { + for (int i = 0; i < nums.length; ++i) + if (nums[i] == 1) + return i; + return -1; + } +} diff --git a/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.py b/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.py new file mode 100644 index 00000000000..480eb7b124f --- /dev/null +++ b/solutions/2003. Smallest Missing Genetic Value in Each Subtree/2003.py @@ -0,0 +1,43 @@ +class Solution: + def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]: + n = len(parents) + ans = [1] * n + tree = [[] for _ in range(n)] + seen = set() + minMiss = 1 + + for i in range(1, n): + tree[parents[i]].append(i) + + def getNode(nums: List[int]) -> int: + for i, num in enumerate(nums): + if num == 1: + return i + return -1 + + nodeThatsOne = getNode(nums) + if nodeThatsOne == -1: + return ans + + u = nodeThatsOne + prev = -1 # the u that just handled + + def dfs(u: int) -> None: + seen.add(nums[u]) + for v in tree[u]: + dfs(v) + + # Upward from `nodeThatsOne` to the root `u`. + while u != -1: + for v in tree[u]: + if v == prev: + continue + dfs(v) + seen.add(nums[u]) + while minMiss in seen: + minMiss += 1 + ans[u] = minMiss + prev = u + u = parents[u] + + return ans diff --git a/solutions/2004. The Number of Seniors and Juniors to Join the Company/2004.sql b/solutions/2004. The Number of Seniors and Juniors to Join the Company/2004.sql new file mode 100644 index 00000000000..79511676a32 --- /dev/null +++ b/solutions/2004. The Number of Seniors and Juniors to Join the Company/2004.sql @@ -0,0 +1,39 @@ +WITH + AccumualtedCandidates AS ( + SELECT + employee_id, + experience, + ROW_NUMBER() OVER( + PARTITION BY experience + ORDER BY salary, employee_id + ) AS candidate_count, + SUM(salary) OVER( + PARTITION BY experience + ORDER BY salary, employee_id + ) AS accumulated_salary + FROM Candidates + ), + MaxHiredSeniors AS ( + SELECT + IFNULL(MAX(candidate_count), 0) AS accepted_candidates, + IFNULL(MAX(accumulated_salary), 0) AS accumulated_salary + FROM AccumualtedCandidates + WHERE + experience = 'Senior' + AND accumulated_salary < 70000 + ) +SELECT + 'Senior' AS experience, + accepted_candidates +FROM MaxHiredSeniors +UNION ALL +SELECT + 'Junior' AS experience, + COUNT(*) AS accepted_candidates +FROM AccumualtedCandidates AS Juniors +WHERE + experience = 'Junior' + AND Juniors.accumulated_salary < ( + SELECT 70000 - MaxHiredSeniors.accumulated_salary + FROM MaxHiredSeniors + ); diff --git a/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.cpp b/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.cpp new file mode 100644 index 00000000000..e54b34f97f4 --- /dev/null +++ b/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool findGameWinner(int n) { + return n % 6 != 1; + } +}; diff --git a/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.java b/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.java new file mode 100644 index 00000000000..34f9f05c7d2 --- /dev/null +++ b/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.java @@ -0,0 +1,5 @@ +class Solution { + public boolean findGameWinner(int n) { + return n % 6 != 1; + } +} diff --git a/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.py b/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.py new file mode 100644 index 00000000000..41081e5d423 --- /dev/null +++ b/solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.py @@ -0,0 +1,3 @@ +class Solution: + def findGameWinner(self, n: int) -> bool: + return n % 6 != 1 diff --git a/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.cpp b/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.cpp new file mode 100644 index 00000000000..eda9c17da14 --- /dev/null +++ b/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int countKDifference(vector& nums, int k) { + constexpr int kMax = 100; + int ans = 0; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int i = k + 1; i <= kMax; ++i) + ans += count[i] * count[i - k]; + + return ans; + } +}; diff --git a/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.java b/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.java new file mode 100644 index 00000000000..3bd73f92e66 --- /dev/null +++ b/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.java @@ -0,0 +1,15 @@ +class Solution { + public int countKDifference(int[] nums, int k) { + final int kMax = 100; + int ans = 0; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int i = k + 1; i <= kMax; ++i) + ans += count[i] * count[i - k]; + + return ans; + } +} diff --git a/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.py b/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.py new file mode 100644 index 00000000000..76f7178b585 --- /dev/null +++ b/solutions/2006. Count Number of Pairs With Absolute Difference K/2006.py @@ -0,0 +1,4 @@ +class Solution: + def countKDifference(self, nums: List[int], k: int) -> int: + count = collections.Counter(nums) + return sum(count[i] * count[i - k] for i in range(k + 1, 101)) diff --git a/solutions/2007. Find Original Array From Doubled Array/2007.cpp b/solutions/2007. Find Original Array From Doubled Array/2007.cpp new file mode 100644 index 00000000000..52678b404aa --- /dev/null +++ b/solutions/2007. Find Original Array From Doubled Array/2007.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector findOriginalArray(vector& changed) { + vector ans; + queue q; + + ranges::sort(changed); + + for (const int num : changed) + if (!q.empty() && num == q.front()) { + q.pop(); + } else { + q.push(num * 2); + ans.push_back(num); + } + + return q.empty() ? ans : vector(); + } +}; diff --git a/solutions/2007. Find Original Array From Doubled Array/2007.java b/solutions/2007. Find Original Array From Doubled Array/2007.java new file mode 100644 index 00000000000..f6b6ad286ae --- /dev/null +++ b/solutions/2007. Find Original Array From Doubled Array/2007.java @@ -0,0 +1,18 @@ +class Solution { + public int[] findOriginalArray(int[] changed) { + List ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(); + + Arrays.sort(changed); + + for (final int num : changed) + if (!q.isEmpty() && num == q.peek()) { + q.poll(); + } else { + q.offer(num * 2); + ans.add(num); + } + + return q.isEmpty() ? ans.stream().mapToInt(Integer::intValue).toArray() : new int[] {}; + } +} diff --git a/solutions/2007. Find Original Array From Doubled Array/2007.py b/solutions/2007. Find Original Array From Doubled Array/2007.py new file mode 100644 index 00000000000..b171caccc32 --- /dev/null +++ b/solutions/2007. Find Original Array From Doubled Array/2007.py @@ -0,0 +1,13 @@ +class Solution: + def findOriginalArray(self, changed: List[int]) -> List[int]: + ans = [] + q = collections.deque() + + for num in sorted(changed): + if q and num == q[0]: + q.popleft() + else: + q.append(num * 2) + ans.append(num) + + return [] if q else ans diff --git a/solutions/2008. Maximum Earnings From Taxi/2008-2.cpp b/solutions/2008. Maximum Earnings From Taxi/2008-2.cpp new file mode 100644 index 00000000000..b3734ce8e90 --- /dev/null +++ b/solutions/2008. Maximum Earnings From Taxi/2008-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long maxTaxiEarnings(int n, vector>& rides) { + vector>> endToStartAndEarns(n + 1); + // dp[i] := the maximum dollars you can earn ending in i + vector dp(n + 1); + + for (const vector& ride : rides) { + const int start = ride[0]; + const int end = ride[1]; + const int tip = ride[2]; + const int earn = end - start + tip; + endToStartAndEarns[end].emplace_back(start, earn); + } + + for (int i = 1; i <= n; ++i) { + dp[i] = dp[i - 1]; + for (const auto& [start, earn] : endToStartAndEarns[i]) + dp[i] = max(dp[i], dp[start] + earn); + } + + return dp[n]; + } +}; diff --git a/solutions/2008. Maximum Earnings From Taxi/2008-2.java b/solutions/2008. Maximum Earnings From Taxi/2008-2.java new file mode 100644 index 00000000000..ce682aeb87a --- /dev/null +++ b/solutions/2008. Maximum Earnings From Taxi/2008-2.java @@ -0,0 +1,29 @@ +class Solution { + public long maxTaxiEarnings(int n, int[][] rides) { + List>[] endToStartAndEarns = new List[n + 1]; + // dp[i] := the maximum dollars you can earn ending in i + long[] dp = new long[n + 1]; + + for (int i = 1; i <= n; ++i) + endToStartAndEarns[i] = new ArrayList<>(); + + for (int[] ride : rides) { + final int start = ride[0]; + final int end = ride[1]; + final int tip = ride[2]; + final int earn = end - start + tip; + endToStartAndEarns[end].add(new Pair<>(start, earn)); + } + + for (int i = 1; i <= n; ++i) { + dp[i] = dp[i - 1]; + for (Pair pair : endToStartAndEarns[i]) { + final int start = pair.getKey(); + final int earn = pair.getValue(); + dp[i] = Math.max(dp[i], dp[start] + earn); + } + } + + return dp[n]; + } +} diff --git a/solutions/2008. Maximum Earnings From Taxi/2008-2.py b/solutions/2008. Maximum Earnings From Taxi/2008-2.py new file mode 100644 index 00000000000..d0fd8052199 --- /dev/null +++ b/solutions/2008. Maximum Earnings From Taxi/2008-2.py @@ -0,0 +1,16 @@ +class Solution: + def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: + endToStartAndEarns = [[] for _ in range(n + 1)] + # dp[i] := the maximum dollars you can earn starting at i + dp = [0] * (n + 1) + + for start, end, tip in rides: + earn = end - start + tip + endToStartAndEarns[end].append((start, earn)) + + for i in range(1, n + 1): + dp[i] = dp[i - 1] + for start, earn in endToStartAndEarns[i]: + dp[i] = max(dp[i], dp[start] + earn) + + return dp[n] diff --git a/solutions/2008. Maximum Earnings From Taxi/2008.cpp b/solutions/2008. Maximum Earnings From Taxi/2008.cpp new file mode 100644 index 00000000000..033cddc07e2 --- /dev/null +++ b/solutions/2008. Maximum Earnings From Taxi/2008.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long maxTaxiEarnings(int n, vector>& rides) { + vector>> startToEndAndEarns(n); + // dp[i] := the maximum dollars you can earn starting at i + vector dp(n + 1); + + for (const vector& ride : rides) { + const int start = ride[0]; + const int end = ride[1]; + const int tip = ride[2]; + const int earn = end - start + tip; + startToEndAndEarns[start].emplace_back(end, earn); + } + + for (int i = n - 1; i >= 1; --i) { + dp[i] = dp[i + 1]; + for (const auto& [end, earn] : startToEndAndEarns[i]) + dp[i] = max(dp[i], dp[end] + earn); + } + + return dp[1]; + } +}; diff --git a/solutions/2008. Maximum Earnings From Taxi/2008.java b/solutions/2008. Maximum Earnings From Taxi/2008.java new file mode 100644 index 00000000000..f2710814c62 --- /dev/null +++ b/solutions/2008. Maximum Earnings From Taxi/2008.java @@ -0,0 +1,29 @@ +class Solution { + public long maxTaxiEarnings(int n, int[][] rides) { + List>[] startToEndAndEarns = new List[n]; + // dp[i] := the maximum dollars you can earn starting at i + long[] dp = new long[n + 1]; + + for (int i = 1; i < n; ++i) + startToEndAndEarns[i] = new ArrayList<>(); + + for (int[] ride : rides) { + final int start = ride[0]; + final int end = ride[1]; + final int tip = ride[2]; + final int earn = end - start + tip; + startToEndAndEarns[start].add(new Pair<>(end, earn)); + } + + for (int i = n - 1; i >= 1; --i) { + dp[i] = dp[i + 1]; + for (Pair pair : startToEndAndEarns[i]) { + final int end = pair.getKey(); + final int earn = pair.getValue(); + dp[i] = Math.max(dp[i], dp[end] + earn); + } + } + + return dp[1]; + } +} diff --git a/solutions/2008. Maximum Earnings From Taxi/2008.py b/solutions/2008. Maximum Earnings From Taxi/2008.py new file mode 100644 index 00000000000..359f7ffb36a --- /dev/null +++ b/solutions/2008. Maximum Earnings From Taxi/2008.py @@ -0,0 +1,16 @@ +class Solution: + def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: + startToEndAndEarns = [[] for _ in range(n)] + # dp[i] := the maximum dollars you can earn starting at i + dp = [0] * (n + 1) + + for start, end, tip in rides: + earn = end - start + tip + startToEndAndEarns[start].append((end, earn)) + + for i in range(n - 1, 0, -1): + dp[i] = dp[i + 1] + for end, earn in startToEndAndEarns[i]: + dp[i] = max(dp[i], dp[end] + earn) + + return dp[1] diff --git a/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.cpp b/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.cpp new file mode 100644 index 00000000000..fd77f2ecc2c --- /dev/null +++ b/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minOperations(vector& nums) { + const int n = nums.size(); + int ans = n; + + ranges::sort(nums); + nums.erase(unique(nums.begin(), nums.end()), nums.end()); + + for (int i = 0; i < nums.size(); ++i) { + const int start = nums[i]; + const int end = start + n - 1; + const int index = firstGreater(nums, end); + const int uniqueLength = index - i; + ans = min(ans, n - uniqueLength); + } + + return ans; + } + + private: + int firstGreater(const vector& A, int target) { + return ranges::upper_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.java b/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.java new file mode 100644 index 00000000000..7968de6da73 --- /dev/null +++ b/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.java @@ -0,0 +1,24 @@ +class Solution { + public int minOperations(int[] nums) { + final int n = nums.length; + int ans = n; + + Arrays.sort(nums); + nums = Arrays.stream(nums).distinct().toArray(); + + for (int i = 0; i < nums.length; ++i) { + final int start = nums[i]; + final int end = start + n - 1; + final int index = firstGreater(nums, end); + final int uniqueLength = index - i; + ans = Math.min(ans, n - uniqueLength); + } + + return ans; + } + + private int firstGreater(int[] A, int target) { + final int i = Arrays.binarySearch(A, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.py b/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.py new file mode 100644 index 00000000000..f6cafb0469f --- /dev/null +++ b/solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.py @@ -0,0 +1,13 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + n = len(nums) + ans = n + nums = sorted(set(nums)) + + for i, start in enumerate(nums): + end = start + n - 1 + index = bisect_right(nums, end) + uniqueLength = index - i + ans = min(ans, n - uniqueLength) + + return ans diff --git a/solutions/201. Bitwise AND of Numbers Range/201.cpp b/solutions/201. Bitwise AND of Numbers Range/201.cpp new file mode 100644 index 00000000000..b679a85f32f --- /dev/null +++ b/solutions/201. Bitwise AND of Numbers Range/201.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int rangeBitwiseAnd(int m, int n) { + int shiftBits = 0; + + while (m != n) { + m >>= 1; + n >>= 1; + ++shiftBits; + } + + return m << shiftBits; + } +}; diff --git a/solutions/201. Bitwise AND of Numbers Range/201.java b/solutions/201. Bitwise AND of Numbers Range/201.java new file mode 100644 index 00000000000..a402dfe0add --- /dev/null +++ b/solutions/201. Bitwise AND of Numbers Range/201.java @@ -0,0 +1,13 @@ +class Solution { + public int rangeBitwiseAnd(int m, int n) { + int shiftBits = 0; + + while (m != n) { + m >>= 1; + n >>= 1; + ++shiftBits; + } + + return m << shiftBits; + } +} diff --git a/solutions/201. Bitwise AND of Numbers Range/201.py b/solutions/201. Bitwise AND of Numbers Range/201.py new file mode 100644 index 00000000000..bf4b878bfe1 --- /dev/null +++ b/solutions/201. Bitwise AND of Numbers Range/201.py @@ -0,0 +1,3 @@ +class Solution: + def rangeBitwiseAnd(self, m: int, n: int) -> int: + return self.rangeBitwiseAnd(m >> 1, n >> 1) << 1 if m < n else m diff --git a/solutions/2010. The Number of Seniors and Juniors to Join the Company II/2010.sql b/solutions/2010. The Number of Seniors and Juniors to Join the Company II/2010.sql new file mode 100644 index 00000000000..de28e1bcc7d --- /dev/null +++ b/solutions/2010. The Number of Seniors and Juniors to Join the Company II/2010.sql @@ -0,0 +1,38 @@ +WITH + AccumualtedCandidates AS ( + SELECT + employee_id, + experience, + ROW_NUMBER() OVER( + PARTITION BY experience + ORDER BY salary, employee_id + ) AS candidate_count, + SUM(salary) OVER( + PARTITION BY experience + ORDER BY salary, employee_id + ) AS accumulated_salary + FROM Candidates + ), + HiredSeniors AS ( + SELECT + employee_id, + accumulated_salary + FROM AccumualtedCandidates + WHERE + experience = 'Senior' + AND accumulated_salary < 70000 + ) +SELECT HiredSeniors.employee_id +FROM HiredSeniors +UNION ALL +SELECT Juniors.employee_id +FROM AccumualtedCandidates AS Juniors +WHERE + experience = 'Junior' + AND Juniors.accumulated_salary < ( + SELECT 70000 - IFNULL(MAX(accumulated_salary), 0) + FROM AccumualtedCandidates + WHERE + experience = 'Senior' + AND accumulated_salary < 70000 + ); diff --git a/solutions/2011. Final Value of Variable After Performing Operations/2011.cpp b/solutions/2011. Final Value of Variable After Performing Operations/2011.cpp new file mode 100644 index 00000000000..5ac91925b6e --- /dev/null +++ b/solutions/2011. Final Value of Variable After Performing Operations/2011.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int finalValueAfterOperations(vector& operations) { + int ans = 0; + + for (const string& op : operations) + ans += op[1] == '+' ? 1 : -1; + + return ans; + } +}; diff --git a/solutions/2011. Final Value of Variable After Performing Operations/2011.java b/solutions/2011. Final Value of Variable After Performing Operations/2011.java new file mode 100644 index 00000000000..e46506be2e5 --- /dev/null +++ b/solutions/2011. Final Value of Variable After Performing Operations/2011.java @@ -0,0 +1,10 @@ +class Solution { + public int finalValueAfterOperations(String[] operations) { + int ans = 0; + + for (final String op : operations) + ans += op.charAt(1) == '+' ? 1 : -1; + + return ans; + } +} diff --git a/solutions/2011. Final Value of Variable After Performing Operations/2011.py b/solutions/2011. Final Value of Variable After Performing Operations/2011.py new file mode 100644 index 00000000000..df104785189 --- /dev/null +++ b/solutions/2011. Final Value of Variable After Performing Operations/2011.py @@ -0,0 +1,3 @@ +class Solution: + def finalValueAfterOperations(self, operations: List[str]) -> int: + return sum(op[1] == '+' or -1 for op in operations) diff --git a/solutions/2012. Sum of Beauty in the Array/2012.cpp b/solutions/2012. Sum of Beauty in the Array/2012.cpp new file mode 100644 index 00000000000..25706e123e8 --- /dev/null +++ b/solutions/2012. Sum of Beauty in the Array/2012.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int sumOfBeauties(vector& nums) { + const int n = nums.size(); + int ans = 0; + vector minOfRight(n); + minOfRight.back() = nums.back(); + + for (int i = n - 2; i >= 2; --i) + minOfRight[i] = min(nums[i], minOfRight[i + 1]); + + int maxOfLeft = nums[0]; + + for (int i = 1; i <= n - 2; ++i) { + if (maxOfLeft < nums[i] && nums[i] < minOfRight[i + 1]) + ans += 2; + else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) + ans += 1; + maxOfLeft = max(maxOfLeft, nums[i]); + } + + return ans; + } +}; diff --git a/solutions/2012. Sum of Beauty in the Array/2012.java b/solutions/2012. Sum of Beauty in the Array/2012.java new file mode 100644 index 00000000000..cf83feb39df --- /dev/null +++ b/solutions/2012. Sum of Beauty in the Array/2012.java @@ -0,0 +1,23 @@ +class Solution { + public int sumOfBeauties(int[] nums) { + final int n = nums.length; + int ans = 0; + int[] minOfRight = new int[n]; + minOfRight[n - 1] = nums[n - 1]; + + for (int i = n - 2; i >= 2; --i) + minOfRight[i] = Math.min(nums[i], minOfRight[i + 1]); + + int maxOfLeft = nums[0]; + + for (int i = 1; i <= n - 2; ++i) { + if (maxOfLeft < nums[i] && nums[i] < minOfRight[i + 1]) + ans += 2; + else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) + ans += 1; + maxOfLeft = Math.max(maxOfLeft, nums[i]); + } + + return ans; + } +} diff --git a/solutions/2012. Sum of Beauty in the Array/2012.py b/solutions/2012. Sum of Beauty in the Array/2012.py new file mode 100644 index 00000000000..c20b31656c7 --- /dev/null +++ b/solutions/2012. Sum of Beauty in the Array/2012.py @@ -0,0 +1,19 @@ +class Solution: + def sumOfBeauties(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + minOfRight = [0] * (n - 1) + [nums[-1]] + + for i in range(n - 2, 1, -1): + minOfRight[i] = min(nums[i], minOfRight[i + 1]) + + maxOfLeft = nums[0] + + for i in range(1, n - 1): + if maxOfLeft < nums[i] < minOfRight[i + 1]: + ans += 2 + elif nums[i - 1] < nums[i] < nums[i + 1]: + ans += 1 + maxOfLeft = max(maxOfLeft, nums[i]) + + return ans diff --git a/solutions/2013. Detect Squares/2013.cpp b/solutions/2013. Detect Squares/2013.cpp new file mode 100644 index 00000000000..5ce3d53753d --- /dev/null +++ b/solutions/2013. Detect Squares/2013.cpp @@ -0,0 +1,32 @@ +class DetectSquares { + public: + void add(vector point) { + ++pointCount[getHash(point[0], point[1])]; + } + + int count(vector point) { + const int x1 = point[0]; + const int y1 = point[1]; + int ans = 0; + + for (const auto& [hash, count] : pointCount) { + const int x3 = hash >> 10; + const int y3 = hash & 1023; + if (x1 != x3 && abs(x1 - x3) == abs(y1 - y3)) { + const int p = getHash(x1, y3); + const int q = getHash(x3, y1); + if (pointCount.contains(p) && pointCount.contains(q)) + ans += count * pointCount[p] * pointCount[q]; + } + } + + return ans; + } + + private: + unordered_map pointCount; + + int getHash(int i, int j) { + return i << 10 | j; + } +}; diff --git a/solutions/2013. Detect Squares/2013.java b/solutions/2013. Detect Squares/2013.java new file mode 100644 index 00000000000..b5c557ea09f --- /dev/null +++ b/solutions/2013. Detect Squares/2013.java @@ -0,0 +1,31 @@ +class DetectSquares { + public void add(int[] point) { + pointCount.merge(getHash(point[0], point[1]), 1, Integer::sum); + } + + public int count(int[] point) { + final int x1 = point[0]; + final int y1 = point[1]; + int ans = 0; + + for (final int hash : pointCount.keySet()) { + final int count = pointCount.get(hash); + final int x3 = hash >> 10; + final int y3 = hash & 1023; + if (x1 != x3 && Math.abs(x1 - x3) == Math.abs(y1 - y3)) { + final int p = getHash(x1, y3); + final int q = getHash(x3, y1); + if (pointCount.containsKey(p) && pointCount.containsKey(q)) + ans += count * pointCount.get(p) * pointCount.get(q); + } + } + + return ans; + } + + private Map pointCount = new HashMap<>(); + + private int getHash(int i, int j) { + return i << 10 | j; + } +} diff --git a/solutions/2013. Detect Squares/2013.py b/solutions/2013. Detect Squares/2013.py new file mode 100644 index 00000000000..51ef25157aa --- /dev/null +++ b/solutions/2013. Detect Squares/2013.py @@ -0,0 +1,14 @@ +class DetectSquares: + def __init__(self): + self.pointCount = collections.Counter() + + def add(self, point: List[int]) -> None: + self.pointCount[tuple(point)] += 1 + + def count(self, point: List[int]) -> int: + x1, y1 = point + ans = 0 + for (x3, y3), c in self.pointCount.items(): + if x1 != x3 and abs(x1 - x3) == abs(y1 - y3): + ans += c * self.pointCount[(x1, y3)] * self.pointCount[(x3, y1)] + return ans diff --git a/solutions/2014. Longest Subsequence Repeated k Times/2014.cpp b/solutions/2014. Longest Subsequence Repeated k Times/2014.cpp new file mode 100644 index 00000000000..cbd2bc8159a --- /dev/null +++ b/solutions/2014. Longest Subsequence Repeated k Times/2014.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + string longestSubsequenceRepeatedK(string s, int k) { + string ans; + vector count(26); + vector possibleChars; + // Stores subsequences, where the length grows by 1 each time. + queue q{{""}}; + + for (const char c : s) + ++count[c - 'a']; + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c - 'a'] >= k) + possibleChars.push_back(c); + + while (!q.empty()) { + const string currSubseq = q.front(); + q.pop(); + if (currSubseq.length() * k > s.length()) + return ans; + for (const char c : possibleChars) { + const string& newSubseq = currSubseq + c; + if (isSubsequence(newSubseq, s, k)) { + q.push(newSubseq); + ans = newSubseq; + } + } + } + + return ans; + } + + private: + bool isSubsequence(const string& subseq, string& s, int k) { + int i = 0; // subseq's index + for (const char c : s) + if (c == subseq[i]) + if (++i == subseq.length()) { + if (--k == 0) + return true; + i = 0; + } + return false; + } +}; diff --git a/solutions/2014. Longest Subsequence Repeated k Times/2014.java b/solutions/2014. Longest Subsequence Repeated k Times/2014.java new file mode 100644 index 00000000000..61e8e71f809 --- /dev/null +++ b/solutions/2014. Longest Subsequence Repeated k Times/2014.java @@ -0,0 +1,43 @@ +public class Solution { + public String longestSubsequenceRepeatedK(String s, int k) { + String ans = ""; + int[] count = new int[26]; + List possibleChars = new ArrayList<>(); + // Stores subsequences, where the length grows by 1 each time. + Queue q = new ArrayDeque<>(Arrays.asList("")); + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c - 'a'] >= k) + possibleChars.add(c); + + while (!q.isEmpty()) { + final String currSubseq = q.poll(); + if (currSubseq.length() * k > s.length()) + return ans; + for (final char c : possibleChars) { + final String newSubseq = currSubseq + c; + if (isSubsequence(newSubseq, s, k)) { + q.offer(newSubseq); + ans = newSubseq; + } + } + } + + return ans; + } + + private boolean isSubsequence(final String subseq, final String s, int k) { + int i = 0; // subseq's index + for (final char c : s.toCharArray()) + if (c == subseq.charAt(i)) + if (++i == subseq.length()) { + if (--k == 0) + return true; + i = 0; + } + return false; + } +} diff --git a/solutions/2014. Longest Subsequence Repeated k Times/2014.py b/solutions/2014. Longest Subsequence Repeated k Times/2014.py new file mode 100644 index 00000000000..dbea009bf52 --- /dev/null +++ b/solutions/2014. Longest Subsequence Repeated k Times/2014.py @@ -0,0 +1,38 @@ +class Solution: + def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: + ans = '' + count = [0] * 26 + possibleChars = [] + # Stores subsequences, where the length grows by 1 each time. + q = collections.deque(['']) + + for c in s: + count[ord(c) - ord('a')] += 1 + + for c in string.ascii_lowercase: + if count[ord(c) - ord('a')] >= k: + possibleChars.append(c) + + def isSubsequence(subseq: str, s: str, k: int) -> bool: + i = 0 # subseq's index + for c in s: + if c == subseq[i]: + i += 1 + if i == len(subseq): + k -= 1 + if k == 0: + return True + i = 0 + return False + + while q: + currSubseq = q.popleft() + if len(currSubseq) * k > len(s): + return ans + for c in possibleChars: + newSubseq = currSubseq + c + if isSubsequence(newSubseq, s, k): + q.append(newSubseq) + ans = newSubseq + + return ans diff --git a/solutions/2015. Average Height of Buildings in Each Segment/2015.cpp b/solutions/2015. Average Height of Buildings in Each Segment/2015.cpp new file mode 100644 index 00000000000..85f247ec5ce --- /dev/null +++ b/solutions/2015. Average Height of Buildings in Each Segment/2015.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + vector> averageHeightOfBuildings(vector>& buildings) { + vector> ans; + vector> events; + + for (const vector& b : buildings) { + const int start = b[0]; + const int end = b[1]; + const int height = b[2]; + events.emplace_back(start, height); + events.emplace_back(end, -height); + } + + ranges::sort(events); + + int prev = 0; + int count = 0; + int sumHeight = 0; + + for (const auto& [curr, h] : events) { + const int height = abs(h); + if (sumHeight > 0 && curr > prev) { + const int avgHeight = sumHeight / count; + if (!ans.empty() && ans.back()[1] == prev && avgHeight == ans.back()[2]) + ans.back()[1] = curr; + else + ans.push_back({prev, curr, avgHeight}); + } + sumHeight += h; + count += h > 0 ? 1 : -1; + prev = curr; + } + + return ans; + } +}; diff --git a/solutions/2015. Average Height of Buildings in Each Segment/2015.java b/solutions/2015. Average Height of Buildings in Each Segment/2015.java new file mode 100644 index 00000000000..723387f3ee9 --- /dev/null +++ b/solutions/2015. Average Height of Buildings in Each Segment/2015.java @@ -0,0 +1,39 @@ +class Solution { + public int[][] averageHeightOfBuildings(int[][] buildings) { + List ans = new ArrayList<>(); + List> events = new ArrayList<>(); + + for (int[] b : buildings) { + final int start = b[0]; + final int end = b[1]; + final int height = b[2]; + events.add(new Pair<>(start, height)); + events.add(new Pair<>(end, -height)); + } + + Collections.sort(events, Comparator.comparing(Pair::getKey)); + + int prev = 0; + int count = 0; + int sumHeight = 0; + + for (Pair event : events) { + final int curr = event.getKey(); + final int h = event.getValue(); + final int height = Math.abs(h); + if (sumHeight > 0 && curr > prev) { + final int avgHeight = sumHeight / count; + if (!ans.isEmpty() && ans.get(ans.size() - 1)[1] == prev && + avgHeight == ans.get(ans.size() - 1)[2]) + ans.get(ans.size() - 1)[1] = curr; + else + ans.add(new int[] {prev, curr, avgHeight}); + } + sumHeight += h; + count += h > 0 ? 1 : -1; + prev = curr; + } + + return ans.stream().toArray(int[][] ::new); + } +} diff --git a/solutions/2015. Average Height of Buildings in Each Segment/2015.py b/solutions/2015. Average Height of Buildings in Each Segment/2015.py new file mode 100644 index 00000000000..4fd6e06abd8 --- /dev/null +++ b/solutions/2015. Average Height of Buildings in Each Segment/2015.py @@ -0,0 +1,26 @@ +class Solution: + def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]: + ans = [] + events = [] + + for start, end, height in buildings: + events.append((start, height)) + events.append((end, -height)) + + prev = 0 + count = 0 + sumHeight = 0 + + for curr, h in sorted(events): + height = abs(h) + if sumHeight > 0 and curr > prev: + avgHeight = sumHeight // count + if ans and ans[-1][1] == prev and avgHeight == ans[-1][2]: + ans[-1][1] = curr + else: + ans.append([prev, curr, avgHeight]) + sumHeight += h + count += 1 if h > 0 else -1 + prev = curr + + return ans diff --git a/solutions/2016. Maximum Difference Between Increasing Elements/2016.cpp b/solutions/2016. Maximum Difference Between Increasing Elements/2016.cpp new file mode 100644 index 00000000000..372f156bc28 --- /dev/null +++ b/solutions/2016. Maximum Difference Between Increasing Elements/2016.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maximumDifference(vector& nums) { + int ans = -1; + int mn = nums[0]; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > mn) + ans = max(ans, nums[i] - mn); + mn = min(mn, nums[i]); + } + + return ans; + } +}; diff --git a/solutions/2016. Maximum Difference Between Increasing Elements/2016.java b/solutions/2016. Maximum Difference Between Increasing Elements/2016.java new file mode 100644 index 00000000000..2a352dcfc36 --- /dev/null +++ b/solutions/2016. Maximum Difference Between Increasing Elements/2016.java @@ -0,0 +1,14 @@ +class Solution { + public int maximumDifference(int[] nums) { + int ans = -1; + int mn = nums[0]; + + for (int i = 1; i < nums.length; ++i) { + if (nums[i] > mn) + ans = Math.max(ans, nums[i] - mn); + mn = Math.min(mn, nums[i]); + } + + return ans; + } +} diff --git a/solutions/2016. Maximum Difference Between Increasing Elements/2016.py b/solutions/2016. Maximum Difference Between Increasing Elements/2016.py new file mode 100644 index 00000000000..2a344bc1ce1 --- /dev/null +++ b/solutions/2016. Maximum Difference Between Increasing Elements/2016.py @@ -0,0 +1,11 @@ +class Solution: + def maximumDifference(self, nums: List[int]) -> int: + ans = -1 + mn = nums[0] + + for i in range(len(nums)): + if nums[i] > mn: + ans = max(ans, nums[i] - mn) + mn = min(mn, nums[i]) + + return ans diff --git a/solutions/2017. Grid Game/2017.cpp b/solutions/2017. Grid Game/2017.cpp new file mode 100644 index 00000000000..8e6594fca56 --- /dev/null +++ b/solutions/2017. Grid Game/2017.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + long long gridGame(vector>& grid) { + const int n = grid[0].size(); + long ans = LONG_MAX; + long sumRow0 = accumulate(grid[0].begin(), grid[0].end(), 0L); + long sumRow1 = 0; + + for (int i = 0; i < n; ++i) { + sumRow0 -= grid[0][i]; + ans = min(ans, max(sumRow0, sumRow1)); + sumRow1 += grid[1][i]; + } + + return ans; + } +}; diff --git a/solutions/2017. Grid Game/2017.java b/solutions/2017. Grid Game/2017.java new file mode 100644 index 00000000000..31cb06a0dc3 --- /dev/null +++ b/solutions/2017. Grid Game/2017.java @@ -0,0 +1,16 @@ +class Solution { + public long gridGame(int[][] grid) { + final int n = grid[0].length; + long ans = Long.MAX_VALUE; + long sumRow0 = Arrays.stream(grid[0]).asLongStream().sum(); + long sumRow1 = 0; + + for (int i = 0; i < n; ++i) { + sumRow0 -= grid[0][i]; + ans = Math.min(ans, Math.max(sumRow0, sumRow1)); + sumRow1 += grid[1][i]; + } + + return ans; + } +} diff --git a/solutions/2017. Grid Game/2017.py b/solutions/2017. Grid Game/2017.py new file mode 100644 index 00000000000..779e8c52df3 --- /dev/null +++ b/solutions/2017. Grid Game/2017.py @@ -0,0 +1,13 @@ +class Solution: + def gridGame(self, grid: List[List[int]]) -> int: + n = len(grid[0]) + ans = math.inf + sumRow0 = sum(grid[0]) + sumRow1 = 0 + + for i in range(n): + sumRow0 -= grid[0][i] + ans = min(ans, max(sumRow0, sumRow1)) + sumRow1 += grid[1][i] + + return ans diff --git a/solutions/2018. Check if Word Can Be Placed In Crossword/2018.cpp b/solutions/2018. Check if Word Can Be Placed In Crossword/2018.cpp new file mode 100644 index 00000000000..35ec9075b2d --- /dev/null +++ b/solutions/2018. Check if Word Can Be Placed In Crossword/2018.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + bool placeWordInCrossword(vector>& board, string word) { + for (const vector>& state : {board, getRotated(board)}) + for (const vector& chars : state) + for (const string& token : getTokens(join(chars))) + for (const string& letters : + {word, string(word.rbegin(), word.rend())}) + if (letters.length() == token.length()) + if (canFit(letters, token)) + return true; + return false; + } + + private: + vector> getRotated(const vector>& board) { + const int m = board.size(); + const int n = board[0].size(); + vector> rotated(n, vector(m)); + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + rotated[j][i] = board[i][j]; + return rotated; + } + + vector getTokens(const string& row) { + vector tokens; + int start = 0; + int end; + string token; + do { + end = row.find('#', start); + token = row.substr(start, end - start); + if (!token.empty()) + tokens.push_back(token); + start = end + 1; + } while (end != string::npos); + return tokens; + } + + string join(const vector& chars) { + string joined; + for (const char c : chars) + joined += c; + return joined; + } + + bool canFit(const string& letters, const string& token) { + for (int i = 0; i < letters.length(); ++i) + if (token[i] != ' ' && token[i] != letters[i]) + return false; + return true; + } +}; diff --git a/solutions/2018. Check if Word Can Be Placed In Crossword/2018.java b/solutions/2018. Check if Word Can Be Placed In Crossword/2018.java new file mode 100644 index 00000000000..389ecd61ffe --- /dev/null +++ b/solutions/2018. Check if Word Can Be Placed In Crossword/2018.java @@ -0,0 +1,30 @@ +class Solution { + public boolean placeWordInCrossword(char[][] board, String word) { + for (char[][] state : new char[][][] {board, getRotated(board)}) + for (char[] chars : state) + for (final String token : String.valueOf(chars).split("#")) + for (final String letters : + new String[] {word, new StringBuilder(word).reverse().toString()}) + if (letters.length() == token.length()) + if (canFit(letters, token)) + return true; + return false; + } + + private char[][] getRotated(char[][] board) { + final int m = board.length; + final int n = board[0].length; + char[][] rotated = new char[n][m]; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + rotated[j][i] = board[i][j]; + return rotated; + } + + private boolean canFit(final String letters, final String token) { + for (int i = 0; i < letters.length(); ++i) + if (token.charAt(i) != ' ' && token.charAt(i) != letters.charAt(i)) + return false; + return true; + } +} diff --git a/solutions/2018. Check if Word Can Be Placed In Crossword/2018.py b/solutions/2018. Check if Word Can Be Placed In Crossword/2018.py new file mode 100644 index 00000000000..01a0710baed --- /dev/null +++ b/solutions/2018. Check if Word Can Be Placed In Crossword/2018.py @@ -0,0 +1,10 @@ +class Solution: + def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool: + for x in board, zip(*board): + for row in x: + for token in ''.join(row).split('#'): + for letters in word, word[::-1]: + if len(token) == len(letters): + if all(c in (' ', letter) for c, letter in zip(token, letters)): + return True + return False diff --git a/solutions/2019. The Score of Students Solving Math Expression/2019.cpp b/solutions/2019. The Score of Students Solving Math Expression/2019.cpp new file mode 100644 index 00000000000..f0374ea6228 --- /dev/null +++ b/solutions/2019. The Score of Students Solving Math Expression/2019.cpp @@ -0,0 +1,67 @@ +class Solution { + public: + int scoreOfStudents(string s, vector& answers) { + const int n = s.length() / 2 + 1; + const unordered_map> func{ + {'+', plus()}, {'*', multiplies()}}; + int ans = 0; + vector>> dp(n, vector>(n)); + unordered_map count; + + for (int i = 0; i < n; ++i) + dp[i][i].insert(s[i * 2] - '0'); + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + for (int k = i; k < j; ++k) { + const char op = s[k * 2 + 1]; + for (const int a : dp[i][k]) + for (const int b : dp[k + 1][j]) { + const int res = func.at(op)(a, b); + if (res <= 1000) + dp[i][j].insert(res); + } + } + } + + const int correctAnswer = eval(s); + + for (const int answer : answers) + ++count[answer]; + + for (const auto& [answer, freq] : count) + if (answer == correctAnswer) + ans += 5 * freq; + else if (dp[0][n - 1].contains(answer)) + ans += 2 * freq; + + return ans; + } + + private: + int eval(const string& s) { + int ans = 0; + int prevNum = 0; + int currNum = 0; + char op = '+'; + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + if (isdigit(c)) + currNum = currNum * 10 + (c - '0'); + if (!isdigit(c) || i == s.length() - 1) { + if (op == '+') { + ans += prevNum; + prevNum = currNum; + } else if (op == '*') { + prevNum = prevNum * currNum; + } + op = c; + currNum = 0; + } + } + + return ans + prevNum; + } +}; diff --git a/solutions/2019. The Score of Students Solving Math Expression/2019.java b/solutions/2019. The Score of Students Solving Math Expression/2019.java new file mode 100644 index 00000000000..4fc2fa651fc --- /dev/null +++ b/solutions/2019. The Score of Students Solving Math Expression/2019.java @@ -0,0 +1,73 @@ +class Solution { + public int scoreOfStudents(String s, int[] answers) { + final int n = s.length() / 2 + 1; + int ans = 0; + Set[][] dp = new Set[n][n]; + Map count = new HashMap<>(); + + for (int i = 0; i < n; ++i) + for (int j = i; j < n; ++j) + dp[i][j] = new HashSet<>(); + + for (int i = 0; i < n; ++i) + dp[i][i].add(s.charAt(i * 2) - '0'); + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + for (int k = i; k < j; ++k) { + final char op = s.charAt(k * 2 + 1); + for (final int a : dp[i][k]) + for (final int b : dp[k + 1][j]) { + final int res = func(op, a, b); + if (res <= 1000) + dp[i][j].add(res); + } + } + } + + final int correctAnswer = eval(s); + + for (final int answer : answers) + count.merge(answer, 1, Integer::sum); + + for (final int answer : count.keySet()) + if (answer == correctAnswer) + ans += 5 * count.get(answer); + else if (dp[0][n - 1].contains(answer)) + ans += 2 * count.get(answer); + + return ans; + } + + private int eval(final String s) { + int ans = 0; + int currNum = 0; + int prevNum = 0; + char op = '+'; + + for (int i = 0; i < s.length(); ++i) { + final char c = s.charAt(i); + if (Character.isDigit(c)) + currNum = currNum * 10 + (c - '0'); + if (!Character.isDigit(c) || i == s.length() - 1) { + if (op == '+') { + ans += prevNum; + prevNum = currNum; + } else if (op == '*') { + prevNum = prevNum * currNum; + } + op = c; + currNum = 0; + } + } + + return ans + prevNum; + } + + private int func(char op, int a, int b) { + if (op == '+') + return a + b; + return a * b; + } +} diff --git a/solutions/2019. The Score of Students Solving Math Expression/2019.py b/solutions/2019. The Score of Students Solving Math Expression/2019.py new file mode 100644 index 00000000000..1611a27c420 --- /dev/null +++ b/solutions/2019. The Score of Students Solving Math Expression/2019.py @@ -0,0 +1,30 @@ +class Solution: + def scoreOfStudents(self, s: str, answers: List[int]) -> int: + n = len(s) // 2 + 1 + ans = 0 + func = {'+': operator.add, '*': operator.mul} + dp = [[set() for j in range(n)] for _ in range(n)] + + for i in range(n): + dp[i][i].add(int(s[i * 2])) + + for d in range(1, n): + for i in range(n - d): + j = i + d + for k in range(i, j): + op = s[k * 2 + 1] + for a in dp[i][k]: + for b in dp[k + 1][j]: + res = func[op](a, b) + if res <= 1000: + dp[i][j].add(res) + + correctAnswer = eval(s) + + for answer, freq in collections.Counter(answers).items(): + if answer == correctAnswer: + ans += 5 * freq + elif answer in dp[0][n - 1]: + ans += 2 * freq + + return ans diff --git a/solutions/202. Happy Number/202.cpp b/solutions/202. Happy Number/202.cpp new file mode 100644 index 00000000000..ac0413b338b --- /dev/null +++ b/solutions/202. Happy Number/202.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + bool isHappy(int n) { + int slow = squaredSum(n); + int fast = squaredSum(squaredSum(n)); + + while (slow != fast) { + slow = squaredSum(slow); + fast = squaredSum(squaredSum(fast)); + } + + return slow == 1; + } + + private: + int squaredSum(int n) { + int sum = 0; + while (n) { + sum += pow(n % 10, 2); + n /= 10; + } + return sum; + }; +}; diff --git a/solutions/202. Happy Number/202.java b/solutions/202. Happy Number/202.java new file mode 100644 index 00000000000..a5404b68bc3 --- /dev/null +++ b/solutions/202. Happy Number/202.java @@ -0,0 +1,22 @@ +class Solution { + public boolean isHappy(int n) { + int slow = squaredSum(n); + int fast = squaredSum(squaredSum(n)); + + while (slow != fast) { + slow = squaredSum(slow); + fast = squaredSum(squaredSum(fast)); + } + + return slow == 1; + } + + private int squaredSum(int n) { + int sum = 0; + while (n > 0) { + sum += Math.pow(n % 10, 2); + n /= 10; + } + return sum; + } +} diff --git a/solutions/202. Happy Number/202.py b/solutions/202. Happy Number/202.py new file mode 100644 index 00000000000..fa8454e80b3 --- /dev/null +++ b/solutions/202. Happy Number/202.py @@ -0,0 +1,17 @@ +class Solution: + def isHappy(self, n: int) -> bool: + def squaredSum(n: int) -> bool: + summ = 0 + while n: + summ += pow(n % 10, 2) + n //= 10 + return summ + + slow = squaredSum(n) + fast = squaredSum(squaredSum(n)) + + while slow != fast: + slow = squaredSum(slow) + fast = squaredSum(squaredSum(fast)) + + return slow == 1 diff --git a/solutions/2020. Number of Accounts That Did Not Stream/2020.sql b/solutions/2020. Number of Accounts That Did Not Stream/2020.sql new file mode 100644 index 00000000000..502954388fa --- /dev/null +++ b/solutions/2020. Number of Accounts That Did Not Stream/2020.sql @@ -0,0 +1,7 @@ +SELECT COUNT(Subscriptions.account_id) AS accounts_count +FROM Subscriptions +LEFT JOIN Streams + USING (account_id) +WHERE + 2021 BETWEEN YEAR(Subscriptions.start_date) AND YEAR(Subscriptions.end_date) + AND YEAR(Streams.stream_date) != 2021; diff --git a/solutions/2021. Brightest Position on Street/2021.cpp b/solutions/2021. Brightest Position on Street/2021.cpp new file mode 100644 index 00000000000..cf1a17a252a --- /dev/null +++ b/solutions/2021. Brightest Position on Street/2021.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int brightestPosition(vector>& lights) { + int ans = INT_MAX; + int maxBrightness = -1; + int currBrightness = 0; + map line; + + for (const vector& light : lights) { + const int position = light[0]; + const int range = light[1]; + ++line[position - range]; + --line[position + range + 1]; + } + + for (const auto& [pos, brightness] : line) { + currBrightness += brightness; + if (currBrightness > maxBrightness) { + maxBrightness = currBrightness; + ans = pos; + } + } + + return ans; + } +}; diff --git a/solutions/2021. Brightest Position on Street/2021.java b/solutions/2021. Brightest Position on Street/2021.java new file mode 100644 index 00000000000..a8007273ada --- /dev/null +++ b/solutions/2021. Brightest Position on Street/2021.java @@ -0,0 +1,26 @@ +class Solution { + public int brightestPosition(int[][] lights) { + int ans = Integer.MAX_VALUE; + int maxBrightness = -1; + int currBrightness = 0; + Map line = new TreeMap<>(); + + for (int[] light : lights) { + final int position = light[0]; + final int range = light[1]; + line.merge(position - range, 1, Integer::sum); + line.merge(position + range + 1, -1, Integer::sum); + } + + for (final int pos : line.keySet()) { + final int brightness = line.get(pos); + currBrightness += brightness; + if (currBrightness > maxBrightness) { + maxBrightness = currBrightness; + ans = pos; + } + } + + return ans; + } +} diff --git a/solutions/2021. Brightest Position on Street/2021.py b/solutions/2021. Brightest Position on Street/2021.py new file mode 100644 index 00000000000..6ae145d9604 --- /dev/null +++ b/solutions/2021. Brightest Position on Street/2021.py @@ -0,0 +1,23 @@ +from sortedcontainers import SortedDict + + +class Solution: + def brightestPosition(self, lights: List[List[int]]) -> int: + ans = math.inf + maxBrightness = -1 + currBrightness = 0 + line = SortedDict() + + for position, rg in lights: + start = position - rg + end = position + rg + 1 + line[start] = line.get(start, 0) + 1 + line[end] = line.get(end, 0) - 1 + + for pos, brightness in line.items(): + currBrightness += brightness + if currBrightness > maxBrightness: + maxBrightness = currBrightness + ans = pos + + return ans diff --git a/solutions/2022. Convert 1D Array Into 2D Array/2022.cpp b/solutions/2022. Convert 1D Array Into 2D Array/2022.cpp new file mode 100644 index 00000000000..5dc284301a0 --- /dev/null +++ b/solutions/2022. Convert 1D Array Into 2D Array/2022.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector> construct2DArray(vector& original, int m, int n) { + if (original.size() != m * n) + return {}; + + vector> ans(m, vector(n)); + + for (int i = 0; i < original.size(); ++i) + ans[i / n][i % n] = original[i]; + + return ans; + } +}; diff --git a/solutions/2022. Convert 1D Array Into 2D Array/2022.java b/solutions/2022. Convert 1D Array Into 2D Array/2022.java new file mode 100644 index 00000000000..b1d40b741d4 --- /dev/null +++ b/solutions/2022. Convert 1D Array Into 2D Array/2022.java @@ -0,0 +1,13 @@ +class Solution { + public int[][] construct2DArray(int[] original, int m, int n) { + if (original.length != m * n) + return new int[][] {}; + + int[][] ans = new int[m][n]; + + for (int i = 0; i < original.length; ++i) + ans[i / n][i % n] = original[i]; + + return ans; + } +} diff --git a/solutions/2022. Convert 1D Array Into 2D Array/2022.py b/solutions/2022. Convert 1D Array Into 2D Array/2022.py new file mode 100644 index 00000000000..bde17ad849e --- /dev/null +++ b/solutions/2022. Convert 1D Array Into 2D Array/2022.py @@ -0,0 +1,11 @@ +class Solution: + def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: + if len(original) != m * n: + return [] + + ans = [[0] * n for _ in range(m)] + + for i, num in enumerate(original): + ans[i // n][i % n] = num + + return ans diff --git a/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.cpp b/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.cpp new file mode 100644 index 00000000000..d83c7416219 --- /dev/null +++ b/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int numOfPairs(vector& nums, string target) { + const int n = target.length(); + int ans = 0; + unordered_map count; + + for (const string& num : nums) { + const int k = num.length(); + if (k >= n) + continue; + if (target.substr(0, k) == num) + ans += count[target.substr(k)]; + if (target.substr(n - k) == num) + ans += count[target.substr(0, n - k)]; + ++count[num]; + } + + return ans; + } +}; diff --git a/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.java b/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.java new file mode 100644 index 00000000000..871180bf4c1 --- /dev/null +++ b/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.java @@ -0,0 +1,20 @@ +class Solution { + public int numOfPairs(String[] nums, String target) { + final int n = target.length(); + int ans = 0; + Map count = new HashMap<>(); + + for (final String num : nums) { + final int k = num.length(); + if (k >= n) + continue; + if (target.substring(0, k).equals(num)) + ans += count.getOrDefault(target.substring(k), 0); + if (target.substring(n - k).equals(num)) + ans += count.getOrDefault(target.substring(0, n - k), 0); + count.merge(num, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.py b/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.py new file mode 100644 index 00000000000..0fd0a6c1d14 --- /dev/null +++ b/solutions/2023. Number of Pairs of Strings With Concatenation Equal to Target/2023.py @@ -0,0 +1,14 @@ +class Solution: + def numOfPairs(self, nums: List[str], target: str) -> int: + ans = 0 + count = collections.Counter() + + for num in nums: + k = len(num) + if target[:k] == num: + ans += count[target[k:]] + if target[-k:] == num: + ans += count[target[:-k]] + count[num] += 1 + + return ans diff --git a/solutions/2024. Maximize the Confusion of an Exam/2024.cpp b/solutions/2024. Maximize the Confusion of an Exam/2024.cpp new file mode 100644 index 00000000000..6d43045fba7 --- /dev/null +++ b/solutions/2024. Maximize the Confusion of an Exam/2024.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxConsecutiveAnswers(string answerKey, int k) { + int ans = 0; + int maxCount = 0; + vector count(2); + + for (int l = 0, r = 0; r < answerKey.length(); ++r) { + maxCount = max(maxCount, ++count[answerKey[r] == 'T']); + while (maxCount + k < r - l + 1) + --count[answerKey[l++] == 'T']; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/2024. Maximize the Confusion of an Exam/2024.java b/solutions/2024. Maximize the Confusion of an Exam/2024.java new file mode 100644 index 00000000000..5d01c59561c --- /dev/null +++ b/solutions/2024. Maximize the Confusion of an Exam/2024.java @@ -0,0 +1,16 @@ +class Solution { + public int maxConsecutiveAnswers(String answerKey, int k) { + int ans = 0; + int maxCount = 0; + int[] count = new int[2]; + + for (int l = 0, r = 0; r < answerKey.length(); ++r) { + maxCount = Math.max(maxCount, ++count[answerKey.charAt(r) == 'T' ? 1 : 0]); + while (maxCount + k < r - l + 1) + --count[answerKey.charAt(l++) == 'T' ? 1 : 0]; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/2024. Maximize the Confusion of an Exam/2024.py b/solutions/2024. Maximize the Confusion of an Exam/2024.py new file mode 100644 index 00000000000..3ddc423ed67 --- /dev/null +++ b/solutions/2024. Maximize the Confusion of an Exam/2024.py @@ -0,0 +1,16 @@ +class Solution: + def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: + ans = 0 + maxCount = 0 + count = collections.Counter() + + l = 0 + for r, c in enumerate(answerKey): + count[c == 'T'] += 1 + maxCount = max(maxCount, count[c == 'T']) + while maxCount + k < r - l + 1: + count[answerKey[l] == 'T'] -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/2025. Maximum Number of Ways to Partition an Array/2025.cpp b/solutions/2025. Maximum Number of Ways to Partition an Array/2025.cpp new file mode 100644 index 00000000000..9d9f785b79a --- /dev/null +++ b/solutions/2025. Maximum Number of Ways to Partition an Array/2025.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int waysToPartition(vector& nums, int k) { + const int n = nums.size(); + const long sum = accumulate(nums.begin(), nums.end(), 0L); + long prefix = 0; + // count of sum(A[0..k)) - sum(A[k..n)) for k in [0..i) + unordered_map l; + // count of sum(A[0..k)) - sum(A[k..n)) for k in [i..n) + unordered_map r; + + for (int pivot = 1; pivot < n; ++pivot) { + prefix += nums[pivot - 1]; + const long suffix = sum - prefix; + ++r[prefix - suffix]; + } + + int ans = r[0]; + prefix = 0; + + for (const int num : nums) { + ans = max(ans, l[k - num] + r[num - k]); + prefix += num; + const long suffix = sum - prefix; + const long diff = prefix - suffix; + --r[diff]; + ++l[diff]; + } + + return ans; + } +}; diff --git a/solutions/2025. Maximum Number of Ways to Partition an Array/2025.java b/solutions/2025. Maximum Number of Ways to Partition an Array/2025.java new file mode 100644 index 00000000000..8a745d78fb5 --- /dev/null +++ b/solutions/2025. Maximum Number of Ways to Partition an Array/2025.java @@ -0,0 +1,32 @@ +class Solution { + public int waysToPartition(int[] nums, int k) { + final int n = nums.length; + final long sum = Arrays.stream(nums).asLongStream().sum(); + long prefix = 0; + // count of sum(A[0..k)) - sum(A[k..n)) for k in [0..i) + Map l = new HashMap<>(); + // count of sum(A[0..k)) - sum(A[k..n)) for k in [i..n) + Map r = new HashMap<>(); + + for (int pivot = 1; pivot < n; ++pivot) { + prefix += nums[pivot - 1]; + final long suffix = sum - prefix; + r.merge(prefix - suffix, 1, Integer::sum); + } + + int ans = r.getOrDefault(0L, 0); + prefix = 0; + + for (final int num : nums) { + final long change = (long) k - num; + ans = Math.max(ans, l.getOrDefault(change, 0) + r.getOrDefault(-change, 0)); + prefix += num; + final long suffix = sum - prefix; + final long diff = prefix - suffix; + r.merge(diff, -1, Integer::sum); + l.merge(diff, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/2025. Maximum Number of Ways to Partition an Array/2025.py b/solutions/2025. Maximum Number of Ways to Partition an Array/2025.py new file mode 100644 index 00000000000..e159139e3d2 --- /dev/null +++ b/solutions/2025. Maximum Number of Ways to Partition an Array/2025.py @@ -0,0 +1,27 @@ +class Solution: + def waysToPartition(self, nums: List[int], k: int) -> int: + n = len(nums) + summ = sum(nums) + prefix = 0 + # Count of sum(A[0..k)) - sum(A[k..n)) for k in [0..i) + l = collections.Counter() + # Count of sum(A[0..k)) - sum(A[k..n)) for k in [i..n) + r = collections.Counter() + + for pivot in range(1, n): + prefix += nums[pivot - 1] + suffix = summ - prefix + r[prefix - suffix] += 1 + + ans = r[0] + prefix = 0 + + for num in nums: + ans = max(ans, l[k - num] + r[num - k]) + prefix += num + suffix = summ - prefix + diff = prefix - suffix + r[diff] -= 1 + l[diff] += 1 + + return ans diff --git a/solutions/2026. Low-Quality Problems/2026.sql b/solutions/2026. Low-Quality Problems/2026.sql new file mode 100644 index 00000000000..59eef63200e --- /dev/null +++ b/solutions/2026. Low-Quality Problems/2026.sql @@ -0,0 +1,4 @@ +SELECT problem_id +FROM Problems +WHERE likes / (likes + dislikes) < 0.6 +ORDER BY 1; diff --git a/solutions/2027. Minimum Moves to Convert String/2027.cpp b/solutions/2027. Minimum Moves to Convert String/2027.cpp new file mode 100644 index 00000000000..a64bba4cd57 --- /dev/null +++ b/solutions/2027. Minimum Moves to Convert String/2027.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minimumMoves(string s) { + int ans = 0; + + for (int i = 0; i < s.length();) + if (s[i] == 'O') { + ++i; + } else { + ++ans; + i += 3; + } + + return ans; + } +}; diff --git a/solutions/2027. Minimum Moves to Convert String/2027.java b/solutions/2027. Minimum Moves to Convert String/2027.java new file mode 100644 index 00000000000..069612aa015 --- /dev/null +++ b/solutions/2027. Minimum Moves to Convert String/2027.java @@ -0,0 +1,15 @@ +class Solution { + public int minimumMoves(String s) { + int ans = 0; + + for (int i = 0; i < s.length();) + if (s.charAt(i) == 'O') { + ++i; + } else { + ++ans; + i += 3; + } + + return ans; + } +} diff --git a/solutions/2027. Minimum Moves to Convert String/2027.py b/solutions/2027. Minimum Moves to Convert String/2027.py new file mode 100644 index 00000000000..eb91dea192f --- /dev/null +++ b/solutions/2027. Minimum Moves to Convert String/2027.py @@ -0,0 +1,13 @@ +class Solution: + def minimumMoves(self, s: str) -> int: + ans = 0 + + i = 0 + while i < len(s): + if s[i] == 'O': + i += 1 + else: + ans += 1 + i += 3 + + return ans diff --git a/solutions/2028. Find Missing Observations/2028.cpp b/solutions/2028. Find Missing Observations/2028.cpp new file mode 100644 index 00000000000..60a855cf7d6 --- /dev/null +++ b/solutions/2028. Find Missing Observations/2028.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector missingRolls(vector& rolls, int mean, int n) { + const int targetSum = (rolls.size() + n) * mean; + int missingSum = targetSum - accumulate(rolls.begin(), rolls.end(), 0); + if (missingSum > n * 6 || missingSum < n) + return {}; + + vector ans(n, missingSum / n); + missingSum %= n; + for (int i = 0; i < missingSum; ++i) + ++ans[i]; + + return ans; + } +}; diff --git a/solutions/2028. Find Missing Observations/2028.java b/solutions/2028. Find Missing Observations/2028.java new file mode 100644 index 00000000000..9a58e77a8f4 --- /dev/null +++ b/solutions/2028. Find Missing Observations/2028.java @@ -0,0 +1,16 @@ +class Solution { + public int[] missingRolls(int[] rolls, int mean, int n) { + final int targetSum = (rolls.length + n) * mean; + int missingSum = targetSum - Arrays.stream(rolls).sum(); + if (missingSum > n * 6 || missingSum < n) + return new int[] {}; + + int[] ans = new int[n]; + Arrays.fill(ans, missingSum / n); + missingSum %= n; + for (int i = 0; i < missingSum; ++i) + ++ans[i]; + + return ans; + } +} diff --git a/solutions/2028. Find Missing Observations/2028.py b/solutions/2028. Find Missing Observations/2028.py new file mode 100644 index 00000000000..a972c663c07 --- /dev/null +++ b/solutions/2028. Find Missing Observations/2028.py @@ -0,0 +1,12 @@ +class Solution: + def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: + targetSum = (len(rolls) + n) * mean + missingSum = targetSum - sum(rolls) + if missingSum > n * 6 or missingSum < n: + return [] + + ans = [missingSum // n] * n + for i in range(missingSum % n): + ans[i] += 1 + + return ans diff --git a/solutions/2029. Stone Game IX/2029.cpp b/solutions/2029. Stone Game IX/2029.cpp new file mode 100644 index 00000000000..7eb14d8dff6 --- /dev/null +++ b/solutions/2029. Stone Game IX/2029.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool stoneGameIX(vector& stones) { + vector count(3); + + for (const int stone : stones) + ++count[stone % 3]; + + if (count[0] % 2 == 0) + return min(count[1], count[2]) > 0; + return abs(count[1] - count[2]) > 2; + } +}; diff --git a/solutions/2029. Stone Game IX/2029.java b/solutions/2029. Stone Game IX/2029.java new file mode 100644 index 00000000000..77bd0f33d98 --- /dev/null +++ b/solutions/2029. Stone Game IX/2029.java @@ -0,0 +1,12 @@ +class Solution { + public boolean stoneGameIX(int[] stones) { + int[] count = new int[3]; + + for (final int stone : stones) + ++count[stone % 3]; + + if (count[0] % 2 == 0) + return Math.min(count[1], count[2]) > 0; + return Math.abs(count[1] - count[2]) > 2; + } +} diff --git a/solutions/2029. Stone Game IX/2029.py b/solutions/2029. Stone Game IX/2029.py new file mode 100644 index 00000000000..671453d6d83 --- /dev/null +++ b/solutions/2029. Stone Game IX/2029.py @@ -0,0 +1,6 @@ +class Solution: + def stoneGameIX(self, stones: List[int]) -> bool: + count = collections.Counter(stone % 3 for stone in stones) + if count[0] % 2 == 0: + return min(count[1], count[2]) > 0 + return abs(count[1] - count[2]) > 2 diff --git a/solutions/203. Remove Linked List Elements/203.cpp b/solutions/203. Remove Linked List Elements/203.cpp new file mode 100644 index 00000000000..2ccdd14d549 --- /dev/null +++ b/solutions/203. Remove Linked List Elements/203.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + ListNode* removeElements(ListNode* head, int val) { + ListNode dummy(0, head); + ListNode* prev = &dummy; + + for (; head; head = head->next) + if (head->val != val) { + prev->next = head; + prev = prev->next; + } + prev->next = nullptr; // In case that the last value equals `val`. + + return dummy.next; + } +}; diff --git a/solutions/203. Remove Linked List Elements/203.java b/solutions/203. Remove Linked List Elements/203.java new file mode 100644 index 00000000000..147c6ba7d1a --- /dev/null +++ b/solutions/203. Remove Linked List Elements/203.java @@ -0,0 +1,15 @@ +class Solution { + public ListNode removeElements(ListNode head, int val) { + ListNode dummy = new ListNode(0, head); + ListNode prev = dummy; + + for (; head != null; head = head.next) + if (head.val != val) { + prev.next = head; + prev = prev.next; + } + prev.next = null; // In case that the last value equals `val`. + + return dummy.next; + } +} diff --git a/solutions/203. Remove Linked List Elements/203.py b/solutions/203. Remove Linked List Elements/203.py new file mode 100644 index 00000000000..d471cc55a94 --- /dev/null +++ b/solutions/203. Remove Linked List Elements/203.py @@ -0,0 +1,13 @@ +class Solution: + def removeElements(self, head: ListNode, val: int) -> ListNode: + dummy = ListNode(0, head) + prev = dummy + + while head: + if head.val != val: + prev.next = head + prev = prev.next + head = head.next + prev.next = None + + return dummy.next diff --git a/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.cpp b/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.cpp new file mode 100644 index 00000000000..81acdcb2f3d --- /dev/null +++ b/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + string smallestSubsequence(string s, int k, char letter, int repetition) { + string ans; + vector stack; + int required = repetition; + int nLetters = ranges::count(s, letter); + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + while (!stack.empty() && stack.back() > c && + stack.size() + s.length() - i - 1 >= k && + (stack.back() != letter || nLetters > required)) { + const char popped = stack.back(); + stack.pop_back(); + if (popped == letter) + ++required; + } + if (stack.size() < k) + if (c == letter) { + stack.push_back(c); + --required; + } else if (k > stack.size() + required) { + stack.push_back(c); + } + if (c == letter) + --nLetters; + } + + for (const char c : stack) + ans += c; + + return ans; + } +}; diff --git a/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.java b/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.java new file mode 100644 index 00000000000..4d6b189da78 --- /dev/null +++ b/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.java @@ -0,0 +1,30 @@ +class Solution { + public String smallestSubsequence(String s, int k, char letter, int repetition) { + StringBuilder sb = new StringBuilder(); + Deque stack = new ArrayDeque<>(); + int required = repetition; + int nLetters = (int) s.chars().filter(c -> c == letter).count(); + + for (int i = 0; i < s.length(); ++i) { + final char c = s.charAt(i); + while (!stack.isEmpty() && stack.peek() > c && stack.size() + s.length() - i - 1 >= k && + (stack.peek() != letter || nLetters > required)) + if (stack.pop() == letter) + ++required; + if (stack.size() < k) + if (c == letter) { + stack.push(c); + --required; + } else if (k - stack.size() > required) { + stack.push(c); + } + if (c == letter) + --nLetters; + } + + for (final char c : stack) + sb.append(c); + + return sb.reverse().toString(); + } +} diff --git a/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.py b/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.py new file mode 100644 index 00000000000..20428829d72 --- /dev/null +++ b/solutions/2030. Smallest K-Length Subsequence With Occurrences of a Letter/2030.py @@ -0,0 +1,26 @@ +class Solution: + def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str: + stack = [] # running string + required = repetition + nLetters = s.count(letter) + + for i, c in enumerate(s): + # Make sure the length is sufficient: + # Len(stack) := the length of running string + # Len(s) - i := the length of remain chars + # -1 := we're going to pop a char + while stack and stack[-1] > c \ + and len(stack) + len(s) - i - 1 >= k \ + and (stack[-1] != letter or nLetters > required): + if stack.pop() == letter: + required += 1 + if len(stack) < k: + if c == letter: + stack.append(c) + required -= 1 + elif k - len(stack) > required: + stack.append(c) + if c == letter: + nLetters -= 1 + + return ''.join(stack) diff --git a/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.cpp b/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.cpp new file mode 100644 index 00000000000..09ddc860673 --- /dev/null +++ b/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.cpp @@ -0,0 +1,56 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + int subarraysWithMoreZerosThanOnes(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + int prefix = 0; + // Map [-n, n] to [1, 2 * n + 1]. + FenwickTree tree(2 * n + 1); + tree.add(remap(0, n), 1); + + for (const int num : nums) { + prefix += num == 0 ? -1 : 1; + // If prefix[j] > prefix[i], where 0 <= i < j < |prefix|, that means that + // there are more ones than zeros in nums[i + 1, j]. + ans += tree.get(remap(prefix - 1, n)); + ans %= kMod; + tree.add(remap(prefix, n), 1); + } + + return ans; + } + + private: + int remap(int i, int n) { + return i + n + 1; + } +}; diff --git a/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.java b/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.java new file mode 100644 index 00000000000..7a1dc290c5c --- /dev/null +++ b/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.java @@ -0,0 +1,51 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public int subarraysWithMoreZerosThanOnes(int[] nums) { + final int kMod = 1_000_000_007; + final int n = nums.length; + int ans = 0; + int prefix = 0; + FenwickTree tree = new FenwickTree(2 * n + 1); + tree.add(remap(0, n), 1); + + for (final int num : nums) { + prefix += num == 0 ? -1 : 1; + ans += tree.get(remap(prefix - 1, n)); + ans %= kMod; + tree.add(remap(prefix, n), 1); + } + + return ans; + } + + private int remap(int i, int n) { + return i + n + 1; + } +} diff --git a/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.py b/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.py new file mode 100644 index 00000000000..0f1fb2b8daf --- /dev/null +++ b/solutions/2031. Count Subarrays With More Ones Than Zeros/2031.py @@ -0,0 +1,35 @@ +class FenwichTree: + def __init__(self, n: int): + self.n = n + self.sums = [0] * (2 * n + 1) + + def add(self, i: int, delta: int) -> None: + i += self.n + 1 # re-mapping + while i < len(self.sums): + self.sums[i] += delta + i += i & -i + + def get(self, i: int) -> int: + i += self.n + 1 # re-mapping + summ = 0 + while i > 0: + summ += self.sums[i] + i -= i & -i + return summ + + +class Solution: + def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + ans = 0 + prefix = 0 + tree = FenwichTree(len(nums)) + tree.add(0, 1) + + for num in nums: + prefix += -1 if num == 0 else 1 + ans += tree.get(prefix - 1) + ans %= kMod + tree.add(prefix, 1) + + return ans diff --git a/solutions/2032. Two Out of Three/2032.cpp b/solutions/2032. Two Out of Three/2032.cpp new file mode 100644 index 00000000000..5bdf1665350 --- /dev/null +++ b/solutions/2032. Two Out of Three/2032.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector twoOutOfThree(vector& nums1, vector& nums2, + vector& nums3) { + vector ans; + vector count(101); + + for (const vector& nums : {nums1, nums2, nums3}) + update(count, nums); + + for (int i = 1; i <= 100; ++i) + if (count[i] >= 2) + ans.push_back(i); + + return ans; + } + + private: + void update(vector& count, const vector& nums) { + for (const int num : unordered_set(nums.begin(), nums.end())) + ++count[num]; + } +}; diff --git a/solutions/2032. Two Out of Three/2032.java b/solutions/2032. Two Out of Three/2032.java new file mode 100644 index 00000000000..91d2db0a724 --- /dev/null +++ b/solutions/2032. Two Out of Three/2032.java @@ -0,0 +1,20 @@ +class Solution { + public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) { + List ans = new ArrayList<>(); + int[] count = new int[101]; + + for (int[] nums : new int[][] {nums1, nums2, nums3}) + update(count, nums); + + for (int i = 1; i <= 100; ++i) + if (count[i] >= 2) + ans.add(i); + + return ans; + } + + private void update(int[] count, int[] nums) { + for (final int num : Arrays.stream(nums).boxed().collect(Collectors.toSet())) + ++count[num]; + } +} diff --git a/solutions/2032. Two Out of Three/2032.py b/solutions/2032. Two Out of Three/2032.py new file mode 100644 index 00000000000..216f0395469 --- /dev/null +++ b/solutions/2032. Two Out of Three/2032.py @@ -0,0 +1,6 @@ +class Solution: + def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]: + count = collections.Counter() + for nums in nums1, nums2, nums3: + count.update(set(nums)) + return [i for i, c in count.items() if c >= 2] diff --git a/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.cpp b/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.cpp new file mode 100644 index 00000000000..0121b1ace51 --- /dev/null +++ b/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minOperations(vector>& grid, int x) { + vector A; + for (const vector& row : grid) + A.insert(A.end(), row.begin(), row.end()); + if (ranges::any_of(A, [&](int a) { return (a - A[0]) % x; })) + return -1; + + int ans = 0; + + nth_element(A.begin(), A.begin() + A.size() / 2, A.end()); + + for (const int a : A) + ans += abs(a - A[A.size() / 2]) / x; + + return ans; + } +}; diff --git a/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.java b/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.java new file mode 100644 index 00000000000..d2645f7cfe2 --- /dev/null +++ b/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.java @@ -0,0 +1,22 @@ +class Solution { + public int minOperations(int[][] grid, int x) { + final int m = grid.length; + final int n = grid[0].length; + + int[] A = new int[m * n]; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + A[i * n + j] = grid[i][j]; + if (Arrays.stream(A).anyMatch(a -> (a - A[0]) % x != 0)) + return -1; + + int ans = 0; + + Arrays.sort(A); + + for (final int a : A) + ans += Math.abs(a - A[A.length / 2]) / x; + + return ans; + } +} diff --git a/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.py b/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.py new file mode 100644 index 00000000000..13e0c52a76a --- /dev/null +++ b/solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.py @@ -0,0 +1,12 @@ +class Solution: + def minOperations(self, grid: List[List[int]], x: int) -> int: + A = sorted([a for row in grid for a in row]) + if any((a - A[0]) % x for a in A): + return -1 + + ans = 0 + + for a in A: + ans += abs(a - A[len(A) // 2]) // x + + return ans diff --git a/solutions/2034. Stock Price Fluctuation/2034-2.cpp b/solutions/2034. Stock Price Fluctuation/2034-2.cpp new file mode 100644 index 00000000000..3500fc04cda --- /dev/null +++ b/solutions/2034. Stock Price Fluctuation/2034-2.cpp @@ -0,0 +1,28 @@ +class StockPrice { + public: + void update(int timestamp, int price) { + if (const auto it = timestampToPrice.find(timestamp); + it != timestampToPrice.cend()) { + const int prevPrice = it->second; + prices.erase(prices.equal_range(prevPrice).first); + } + timestampToPrice[timestamp] = price; + prices.insert(price); + } + + int current() { + return timestampToPrice.rbegin()->second; + } + + int maximum() { + return *prices.rbegin(); + } + + int minimum() { + return *prices.begin(); + } + + private: + map timestampToPrice; + multiset prices; +}; diff --git a/solutions/2034. Stock Price Fluctuation/2034.cpp b/solutions/2034. Stock Price Fluctuation/2034.cpp new file mode 100644 index 00000000000..8d51c7a9969 --- /dev/null +++ b/solutions/2034. Stock Price Fluctuation/2034.cpp @@ -0,0 +1,28 @@ +class StockPrice { + public: + void update(int timestamp, int price) { + if (timestampToPrice.contains(timestamp)) { + const int prevPrice = timestampToPrice[timestamp]; + if (--pricesCount[prevPrice] == 0) + pricesCount.erase(prevPrice); + } + timestampToPrice[timestamp] = price; + ++pricesCount[price]; + } + + int current() { + return timestampToPrice.rbegin()->second; + } + + int maximum() { + return pricesCount.rbegin()->first; + } + + int minimum() { + return pricesCount.begin()->first; + } + + private: + map timestampToPrice; + map pricesCount; +}; diff --git a/solutions/2034. Stock Price Fluctuation/2034.java b/solutions/2034. Stock Price Fluctuation/2034.java new file mode 100644 index 00000000000..3222aacde4b --- /dev/null +++ b/solutions/2034. Stock Price Fluctuation/2034.java @@ -0,0 +1,26 @@ +class StockPrice { + public void update(int timestamp, int price) { + if (timestampToPrice.containsKey(timestamp)) { + final int prevPrice = timestampToPrice.get(timestamp); + if (pricesCount.merge(prevPrice, -1, Integer::sum) == 0) + pricesCount.remove(prevPrice); + } + timestampToPrice.put(timestamp, price); + pricesCount.merge(price, 1, Integer::sum); + } + + public int current() { + return timestampToPrice.lastEntry().getValue(); + } + + public int maximum() { + return pricesCount.lastKey(); + } + + public int minimum() { + return pricesCount.firstKey(); + } + + private TreeMap timestampToPrice = new TreeMap<>(); + private TreeMap pricesCount = new TreeMap<>(); +} diff --git a/solutions/2034. Stock Price Fluctuation/2034.py b/solutions/2034. Stock Price Fluctuation/2034.py new file mode 100644 index 00000000000..095d1a2aa3a --- /dev/null +++ b/solutions/2034. Stock Price Fluctuation/2034.py @@ -0,0 +1,25 @@ +from sortedcontainers import SortedDict + + +class StockPrice: + def __init__(self): + self.timestampToPrice = SortedDict() + self.pricesCount = SortedDict() + + def update(self, timestamp: int, price: int) -> None: + if timestamp in self.timestampToPrice: + prevPrice = self.timestampToPrice[timestamp] + self.pricesCount[prevPrice] -= 1 + if self.pricesCount[prevPrice] == 0: + del self.pricesCount[prevPrice] + self.timestampToPrice[timestamp] = price + self.pricesCount[price] = self.pricesCount.get(price, 0) + 1 + + def current(self) -> int: + return self.timestampToPrice.peekitem(-1)[1] + + def maximum(self) -> int: + return self.pricesCount.peekitem(-1)[0] + + def minimum(self) -> int: + return self.pricesCount.peekitem(0)[0] diff --git a/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.cpp b/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.cpp new file mode 100644 index 00000000000..1914e76823b --- /dev/null +++ b/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int minimumDifference(vector& nums) { + const int n = nums.size() / 2; + const int sum = accumulate(nums.begin(), nums.end(), 0); + const int goal = sum / 2; + const vector lNums(nums.begin(), nums.begin() + n); + const vector rNums(nums.begin() + n, nums.end()); + int ans = INT_MAX; + vector> lSums(n + 1); + vector> rSums(n + 1); + + dfs(lNums, 0, 0, 0, lSums); + dfs(rNums, 0, 0, 0, rSums); + + for (int lCount = 0; lCount <= n; ++lCount) { + auto& l = lSums[lCount]; + auto& r = rSums[n - lCount]; + ranges::sort(r); + for (const int lSum : l) { + const int i = firstGreaterEqual(r, goal - lSum); + if (i < r.size()) { + const int sumPartOne = sum - lSum - r[i]; + const int sumPartTwo = sum - sumPartOne; + ans = min(ans, abs(sumPartOne - sumPartTwo)); + } + if (i > 0) { + const int sumPartOne = sum - lSum - r[i - 1]; + const int sumPartTwo = sum - sumPartOne; + ans = min(ans, abs(sumPartOne - sumPartTwo)); + } + } + } + + return ans; + } + + private: + void dfs(const vector& A, int i, int count, int path, + vector>& sums) { + if (i == A.size()) { + sums[count].push_back(path); + return; + } + dfs(A, i + 1, count + 1, path + A[i], sums); + dfs(A, i + 1, count, path, sums); + } + + int firstGreaterEqual(const vector& A, int target) { + return ranges::lower_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.java b/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.java new file mode 100644 index 00000000000..c52677aa5df --- /dev/null +++ b/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.java @@ -0,0 +1,55 @@ +class Solution { + public int minimumDifference(int[] nums) { + final int n = nums.length / 2; + final int sum = Arrays.stream(nums).sum(); + final int goal = sum / 2; + final int[] lNums = Arrays.copyOfRange(nums, 0, n); + final int[] rNums = Arrays.copyOfRange(nums, n, nums.length); + int ans = Integer.MAX_VALUE; + List[] lSums = new List[n + 1]; + List[] rSums = new List[n + 1]; + + for (int i = 0; i <= n; ++i) { + lSums[i] = new ArrayList<>(); + rSums[i] = new ArrayList<>(); + } + + dfs(lNums, 0, 0, 0, lSums); + dfs(rNums, 0, 0, 0, rSums); + + for (int lCount = 0; lCount <= n; ++lCount) { + List l = lSums[lCount]; + List r = rSums[n - lCount]; + Collections.sort(r); + for (final int lSum : l) { + final int i = firstGreaterEqual(r, goal - lSum); + if (i < r.size()) { + final int sumPartOne = sum - lSum - r.get(i); + final int sumPartTwo = sum - sumPartOne; + ans = Math.min(ans, Math.abs(sumPartOne - sumPartTwo)); + } + if (i > 0) { + final int sumPartOne = sum - lSum - r.get(i - 1); + final int sumPartTwo = sum - sumPartOne; + ans = Math.min(ans, Math.abs(sumPartOne - sumPartTwo)); + } + } + } + + return ans; + } + + private void dfs(int[] A, int i, int count, int path, List[] sums) { + if (i == A.length) { + sums[count].add(path); + return; + } + dfs(A, i + 1, count + 1, path + A[i], sums); + dfs(A, i + 1, count, path, sums); + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.py b/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.py new file mode 100644 index 00000000000..8fd43093b65 --- /dev/null +++ b/solutions/2035. Partition Array Into Two Arrays to Minimize Sum Difference/2035.py @@ -0,0 +1,37 @@ +class Solution: + def minimumDifference(self, nums: List[int]) -> int: + n = len(nums) // 2 + summ = sum(nums) + goal = summ // 2 + lNums = nums[:n] + rNums = nums[n:] + ans = abs(sum(lNums) - sum(rNums)) + lSums = [[] for _ in range(n + 1)] + rSums = [[] for _ in range(n + 1)] + + def dfs(A: List[int], i: int, count: int, path: int, sums: List[List[int]]): + if i == len(A): + sums[count].append(path) + return + dfs(A, i + 1, count + 1, path + A[i], sums) + dfs(A, i + 1, count, path, sums) + + dfs(lNums, 0, 0, 0, lSums) + dfs(rNums, 0, 0, 0, rSums) + + for lCount in range(n): + l = lSums[lCount] + r = rSums[n - lCount] + r.sort() + for lSum in l: + i = bisect_left(r, goal - lSum) + if i < len(r): + sumPartOne = summ - lSum - r[i] + sumPartTwo = summ - sumPartOne + ans = min(ans, abs(sumPartOne - sumPartTwo)) + if i > 0: + sumPartOne = summ - lSum - r[i - 1] + sumPartTwo = summ - sumPartOne + ans = min(ans, abs(sumPartOne - sumPartTwo)) + + return ans diff --git a/solutions/2036. Maximum Alternating Subarray Sum/2036.cpp b/solutions/2036. Maximum Alternating Subarray Sum/2036.cpp new file mode 100644 index 00000000000..d39015dcc4d --- /dev/null +++ b/solutions/2036. Maximum Alternating Subarray Sum/2036.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + long long maximumAlternatingSubarraySum(vector& nums) { + long ans = INT_MIN; + long even = 0; // the subarray sum starting from an even index + long odd = 0; // the subarray sum starting from an odd index + + for (int i = 0; i < nums.size(); ++i) { + if (i % 2 == 0) // Must pick. + even += nums[i]; + else // Start a fresh subarray or subtract `nums[i]`. + even = max(0L, even - nums[i]); + ans = max(ans, even); + } + + for (int i = 1; i < nums.size(); ++i) { + if (i % 2 == 1) // Must pick. + odd += nums[i]; + else // Start a fresh subarray or subtract `nums[i]`. + odd = max(0L, odd - nums[i]); + ans = max(ans, odd); + } + + return ans; + } +}; diff --git a/solutions/2036. Maximum Alternating Subarray Sum/2036.java b/solutions/2036. Maximum Alternating Subarray Sum/2036.java new file mode 100644 index 00000000000..6972c9a9f41 --- /dev/null +++ b/solutions/2036. Maximum Alternating Subarray Sum/2036.java @@ -0,0 +1,25 @@ +class Solution { + public long maximumAlternatingSubarraySum(int[] nums) { + long ans = Integer.MIN_VALUE; + long even = 0; // the subarray sum starting from an even index + long odd = 0; // the subarray sum starting from an odd index + + for (int i = 0; i < nums.length; ++i) { + if (i % 2 == 0) // Must pick. + even += nums[i]; + else // Start a fresh subarray or subtract `nums[i]`. + even = Math.max(0, even - nums[i]); + ans = Math.max(ans, even); + } + + for (int i = 1; i < nums.length; ++i) { + if (i % 2 == 1) // Must pick. + odd += nums[i]; + else // Start a fresh subarray or subtract `nums[i]`. + odd = Math.max(0, odd - nums[i]); + ans = Math.max(ans, odd); + } + + return ans; + } +} diff --git a/solutions/2036. Maximum Alternating Subarray Sum/2036.py b/solutions/2036. Maximum Alternating Subarray Sum/2036.py new file mode 100644 index 00000000000..072c4883092 --- /dev/null +++ b/solutions/2036. Maximum Alternating Subarray Sum/2036.py @@ -0,0 +1,21 @@ +class Solution: + def maximumAlternatingSubarraySum(self, nums: List[int]) -> int: + ans = -math.inf + even = 0 # the subarray sum starting from an even index + odd = 0 # the subarray sum starting from an odd index + + for i in range(len(nums)): + if i % 2 == 0: # Must pick. + even += nums[i] + else: # Start a fresh subarray or subtract `nums[i]`. + even = max(0, even - nums[i]) + ans = max(ans, even) + + for i in range(1, len(nums)): + if i % 2 == 1: # Must pick. + odd += nums[i] + else: # Start a fresh subarray or subtract `nums[i]`. + odd = max(0, odd - nums[i]) + ans = max(ans, odd) + + return ans diff --git a/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.cpp b/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.cpp new file mode 100644 index 00000000000..6edd42b219a --- /dev/null +++ b/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minMovesToSeat(vector& seats, vector& students) { + int ans = 0; + + ranges::sort(seats); + ranges::sort(students); + + for (int i = 0; i < seats.size(); ++i) + ans += abs(seats[i] - students[i]); + + return ans; + } +}; diff --git a/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.java b/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.java new file mode 100644 index 00000000000..51faface618 --- /dev/null +++ b/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.java @@ -0,0 +1,13 @@ +class Solution { + public int minMovesToSeat(int[] seats, int[] students) { + int res = 0; + + Arrays.sort(seats); + Arrays.sort(students); + + for (int i = 0; i < seats.length; ++i) + res += Math.abs(seats[i] - students[i]); + + return res; + } +} diff --git a/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.py b/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.py new file mode 100644 index 00000000000..4de9292f0a9 --- /dev/null +++ b/solutions/2037. Minimum Number of Moves to Seat Everyone/2037.py @@ -0,0 +1,3 @@ +class Solution: + def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: + return sum(abs(seat - student) for seat, student in zip(sorted(seats), sorted(students))) diff --git a/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.cpp b/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.cpp new file mode 100644 index 00000000000..4a1301c1984 --- /dev/null +++ b/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool winnerOfGame(string colors) { + int countAAA = 0; + int countBBB = 0; + + for (int i = 1; i + 1 < colors.length(); ++i) + if (colors[i - 1] == colors[i] && colors[i] == colors[i + 1]) + if (colors[i] == 'A') + ++countAAA; + else + ++countBBB; + + return countAAA > countBBB; + } +}; diff --git a/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.java b/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.java new file mode 100644 index 00000000000..35ae548f2a6 --- /dev/null +++ b/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.java @@ -0,0 +1,15 @@ +class Solution { + public boolean winnerOfGame(String colors) { + int countAAA = 0; + int countBBB = 0; + + for (int i = 1; i + 1 < colors.length(); ++i) + if (colors.charAt(i - 1) == colors.charAt(i) && colors.charAt(i) == colors.charAt(i + 1)) + if (colors.charAt(i) == 'A') + ++countAAA; + else + ++countBBB; + + return countAAA > countBBB; + } +} diff --git a/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.py b/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.py new file mode 100644 index 00000000000..bd29f21a6cf --- /dev/null +++ b/solutions/2038. Remove Colored Pieces if Both Neighbors are the Same Color/2038.py @@ -0,0 +1,12 @@ +class Solution: + def winnerOfGame(self, colors: str) -> bool: + countAAA = 0 + countBBB = 0 + + for a, b, c in zip(colors, colors[1:], colors[2:]): + if 'A' == a == b == c: + countAAA += 1 + elif 'B' == a == b == c: + countBBB += 1 + + return countAAA > countBBB diff --git a/solutions/2039. The Time When the Network Becomes Idle/2039.cpp b/solutions/2039. The Time When the Network Becomes Idle/2039.cpp new file mode 100644 index 00000000000..727925035a7 --- /dev/null +++ b/solutions/2039. The Time When the Network Becomes Idle/2039.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int networkBecomesIdle(vector>& edges, vector& patience) { + const int n = patience.size(); + int ans = 0; + vector> graph(n); + queue q{{0}}; + vector dist(n, INT_MAX); // dist[i] := the distance between i and 0 + dist[0] = 0; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) + if (dist[v] == INT_MAX) { + dist[v] = dist[u] + 1; + q.push(v); + } + } + } + + for (int i = 1; i < n; ++i) { + const int numResending = (dist[i] * 2 - 1) / patience[i]; + const int lastResendingTime = patience[i] * numResending; + const int lastArrivingTime = lastResendingTime + dist[i] * 2; + ans = max(ans, lastArrivingTime); + } + + return ans + 1; + } +}; diff --git a/solutions/2039. The Time When the Network Becomes Idle/2039.java b/solutions/2039. The Time When the Network Becomes Idle/2039.java new file mode 100644 index 00000000000..e24e27b84a3 --- /dev/null +++ b/solutions/2039. The Time When the Network Becomes Idle/2039.java @@ -0,0 +1,41 @@ +class Solution { + public int networkBecomesIdle(int[][] edges, int[] patience) { + final int n = patience.length; + int ans = 0; + List[] graph = new List[n]; + Queue q = new ArrayDeque<>(Arrays.asList(0)); + int[] dist = new int[n]; // dist[i] := the distance between i and 0 + Arrays.fill(dist, Integer.MAX_VALUE); + dist[0] = 0; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.poll(); + for (final int v : graph[u]) + if (dist[v] == Integer.MAX_VALUE) { + dist[v] = dist[u] + 1; + q.offer(v); + } + } + } + + for (int i = 1; i < n; ++i) { + final int numResending = (dist[i] * 2 - 1) / patience[i]; + final int lastResendingTime = patience[i] * numResending; + final int lastArrivingTime = lastResendingTime + dist[i] * 2; + ans = Math.max(ans, lastArrivingTime); + } + + return ans + 1; + } +} diff --git a/solutions/2039. The Time When the Network Becomes Idle/2039.py b/solutions/2039. The Time When the Network Becomes Idle/2039.py new file mode 100644 index 00000000000..44de0b6f28a --- /dev/null +++ b/solutions/2039. The Time When the Network Becomes Idle/2039.py @@ -0,0 +1,28 @@ +class Solution: + def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int: + n = len(patience) + ans = 0 + graph = [[] for _ in range(n)] + q = collections.deque([0]) + dist = [math.inf] * n # dist[i] := the distance between i and 0 + dist[0] = 0 + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + while q: + for _ in range(len(q)): + u = q.popleft() + for v in graph[u]: + if dist[v] == math.inf: + dist[v] = dist[u] + 1 + q.append(v) + + for i in range(1, n): + numResending = (dist[i] * 2 - 1) // patience[i] + lastResendingTime = patience[i] * numResending + lastArrivingTime = lastResendingTime + dist[i] * 2 + ans = max(ans, lastArrivingTime) + + return ans + 1 diff --git a/solutions/204. Count Primes/204.cpp b/solutions/204. Count Primes/204.cpp new file mode 100644 index 00000000000..8e09813ab54 --- /dev/null +++ b/solutions/204. Count Primes/204.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countPrimes(int n) { + if (n <= 2) + return 0; + const vector isPrime = sieveEratosthenes(n); + return ranges::count(isPrime, true); + } + + private: + vector sieveEratosthenes(int n) { + vector isPrime(n, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +}; diff --git a/solutions/204. Count Primes/204.java b/solutions/204. Count Primes/204.java new file mode 100644 index 00000000000..133ff95d8d3 --- /dev/null +++ b/solutions/204. Count Primes/204.java @@ -0,0 +1,24 @@ +class Solution { + public int countPrimes(int n) { + if (n <= 2) + return 0; + final boolean[] isPrime = sieveEratosthenes(n); + int ans = 0; + return (int) IntStream.range(0, isPrime.length) + .mapToObj(i -> isPrime[i]) + .filter(p -> p) + .count(); + } + + private boolean[] sieveEratosthenes(int n) { + boolean[] isPrime = new boolean[n]; + Arrays.fill(isPrime, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +} diff --git a/solutions/204. Count Primes/204.py b/solutions/204. Count Primes/204.py new file mode 100644 index 00000000000..53b787d6f85 --- /dev/null +++ b/solutions/204. Count Primes/204.py @@ -0,0 +1,15 @@ +class Solution: + def countPrimes(self, n: int) -> int: + if n <= 2: + return 0 + return sum(self._sieveEratosthenes(n)) + + def _sieveEratosthenes(self, n: int) -> List[bool]: + isPrime = [True] * n + isPrime[0] = False + isPrime[1] = False + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n, i): + isPrime[j] = False + return isPrime diff --git a/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.cpp b/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.cpp new file mode 100644 index 00000000000..e17fd2d47a9 --- /dev/null +++ b/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.cpp @@ -0,0 +1,63 @@ +class Solution { + public: + long long kthSmallestProduct(vector& nums1, vector& nums2, + long long k) { + vector A1; + vector A2; + vector B1; + vector B2; + + seperate(nums1, A1, A2); + seperate(nums2, B1, B2); + + const long negCount = A1.size() * B2.size() + A2.size() * B1.size(); + int sign = 1; + + if (k > negCount) { + k -= negCount; // Find (k - negCount)-th positive. + } else { + k = negCount - k + 1; // Find (negCount - k + 1)-th abs(negative). + sign = -1; + swap(B1, B2); + } + + long l = 0; + long r = 1e10; + + while (l < r) { + const long m = (l + r) / 2; + if (numProductNoGreaterThan(A1, B1, m) + + numProductNoGreaterThan(A2, B2, m) >= + k) + r = m; + else + l = m + 1; + } + + return sign * l; + } + + private: + void seperate(const vector& A, vector& A1, vector& A2) { + for (const int a : A) + if (a < 0) + A1.push_back(-a); + else + A2.push_back(a); + reverse(A1.begin(), A1.end()); // Reverse to sort ascending + } + + long numProductNoGreaterThan(const vector& A, const vector& B, + long m) { + long count = 0; + int j = B.size() - 1; + // For each a, find the first index j s.t. a * B[j] <= m + // So numProductNoGreaterThan m for this row will be j + 1 + for (const long a : A) { + while (j >= 0 && a * B[j] > m) + --j; + count += j + 1; + } + return count; + } +}; diff --git a/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.java b/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.java new file mode 100644 index 00000000000..867f6970818 --- /dev/null +++ b/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.java @@ -0,0 +1,59 @@ +class Solution { + public long kthSmallestProduct(int[] nums1, int[] nums2, long k) { + List A1 = new ArrayList<>(); + List A2 = new ArrayList<>(); + List B1 = new ArrayList<>(); + List B2 = new ArrayList<>(); + + seperate(nums1, A1, A2); + seperate(nums2, B1, B2); + + final long negCount = A1.size() * B2.size() + A2.size() * B1.size(); + int sign = 1; + + if (k > negCount) { + k -= negCount; // Find (k - negCount)-th positive. + } else { + k = negCount - k + 1; // Find (negCount - k + 1)-th abs(negative). + sign = -1; + List temp = B1; + B1 = B2; + B2 = temp; + } + + long l = 0; + long r = (long) 1e10; + + while (l < r) { + final long m = (l + r) / 2; + if (numProductNoGreaterThan(A1, B1, m) + numProductNoGreaterThan(A2, B2, m) >= k) + r = m; + else + l = m + 1; + } + + return sign * l; + } + + private void seperate(int[] A, List A1, List A2) { + for (final int a : A) + if (a < 0) + A1.add(-a); + else + A2.add(a); + Collections.reverse(A1); // Reverse to sort ascending + } + + private long numProductNoGreaterThan(List A, List B, long m) { + long count = 0; + int j = B.size() - 1; + // For each a, find the first index j s.t. a * B[j] <= m + // So numProductNoGreaterThan m for this row will be j + 1 + for (final long a : A) { + while (j >= 0 && a * B.get(j) > m) + --j; + count += j + 1; + } + return count; + } +} diff --git a/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.py b/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.py new file mode 100644 index 00000000000..8a65ceec61d --- /dev/null +++ b/solutions/2040. Kth Smallest Product of Two Sorted Arrays/2040.py @@ -0,0 +1,40 @@ +class Solution: + def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int: + A1 = [-num for num in nums1 if num < 0][::-1] # Reverse to sort ascending + A2 = [num for num in nums1 if num >= 0] + B1 = [-num for num in nums2 if num < 0][::-1] # Reverse to sort ascending + B2 = [num for num in nums2 if num >= 0] + + negCount = len(A1) * len(B2) + len(A2) * len(B1) + + if k > negCount: # Find (k - negCount)-th positive + k -= negCount + sign = 1 + else: + k = negCount - k + 1 # Find (negCount - k + 1)-th abs(negative). + sign = -1 + B1, B2 = B2, B1 + + def numProductNoGreaterThan(A: List[int], B: List[int], m: int) -> int: + ans = 0 + j = len(B) - 1 + for i in range(len(A)): + # For each A[i], find the first index j s.t. A[i] * B[j] <= m + # So numProductNoGreaterThan m for this row will be j + 1 + while j >= 0 and A[i] * B[j] > m: + j -= 1 + ans += j + 1 + return ans + + l = 0 + r = 10**10 + + while l < r: + m = (l + r) // 2 + if numProductNoGreaterThan(A1, B1, m) + \ + numProductNoGreaterThan(A2, B2, m) >= k: + r = m + else: + l = m + 1 + + return sign * l diff --git a/solutions/2041. Accepted Candidates From the Interviews/2041.sql b/solutions/2041. Accepted Candidates From the Interviews/2041.sql new file mode 100644 index 00000000000..da59b6c3868 --- /dev/null +++ b/solutions/2041. Accepted Candidates From the Interviews/2041.sql @@ -0,0 +1,7 @@ +SELECT Candidates.candidate_id +FROM Candidates +INNER JOIN Rounds + USING (interview_id) +WHERE Candidates.years_of_exp >= 2 +GROUP BY 1 +HAVING SUM(Rounds.score) > 15; diff --git a/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.cpp b/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.cpp new file mode 100644 index 00000000000..a6180772c2b --- /dev/null +++ b/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool areNumbersAscending(string s) { + int prev = 0; + istringstream iss(s); + + for (string token; iss >> token;) + if (isdigit(token[0])) { + const int num = stoi(token); + if (num <= prev) + return false; + prev = num; + } + + return true; + } +}; diff --git a/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.java b/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.java new file mode 100644 index 00000000000..a5812725974 --- /dev/null +++ b/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.java @@ -0,0 +1,15 @@ +class Solution { + public boolean areNumbersAscending(String s) { + int prev = 0; + + for (final String token : s.split(" ")) + if (Character.isDigit(token.charAt(0))) { + final int num = Integer.parseInt(token); + if (num <= prev) + return false; + prev = num; + } + + return true; + } +} diff --git a/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.py b/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.py new file mode 100644 index 00000000000..fb2b310b883 --- /dev/null +++ b/solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.py @@ -0,0 +1,12 @@ +class Solution: + def areNumbersAscending(self, s: str) -> bool: + prev = 0 + + for token in s.split(): + if token.isdigit(): + num = int(token) + if num <= prev: + return False + prev = num + + return True diff --git a/solutions/2043. Simple Bank System/2043.cpp b/solutions/2043. Simple Bank System/2043.cpp new file mode 100644 index 00000000000..d1f782efec0 --- /dev/null +++ b/solutions/2043. Simple Bank System/2043.cpp @@ -0,0 +1,33 @@ +class Bank { + public: + Bank(vector& balance) : balance(move(balance)) {} + + bool transfer(int account1, int account2, long long money) { + if (!isValid(account2)) + return false; + return withdraw(account1, money) && deposit(account2, money); + } + + bool deposit(int account, long long money) { + if (!isValid(account)) + return false; + balance[account - 1] += money; + return true; + } + + bool withdraw(int account, long long money) { + if (!isValid(account)) + return false; + if (balance[account - 1] < money) + return false; + balance[account - 1] -= money; + return true; + } + + private: + vector balance; + + bool isValid(int account) { + return 1 <= account && account <= balance.size(); + } +}; diff --git a/solutions/2043. Simple Bank System/2043.java b/solutions/2043. Simple Bank System/2043.java new file mode 100644 index 00000000000..33a20f4c83e --- /dev/null +++ b/solutions/2043. Simple Bank System/2043.java @@ -0,0 +1,33 @@ +public class Bank { + public Bank(long[] balance) { + this.balance = balance; + } + + public boolean transfer(int account1, int account2, long money) { + if (!isValid(account2)) + return false; + return withdraw(account1, money) && deposit(account2, money); + } + + public boolean deposit(int account, long money) { + if (!isValid(account)) + return false; + balance[account - 1] += money; + return true; + } + + public boolean withdraw(int account, long money) { + if (!isValid(account)) + return false; + if (balance[account - 1] < money) + return false; + balance[account - 1] -= money; + return true; + } + + private long[] balance; + + private boolean isValid(int account) { + return 1 <= account && account <= balance.length; + } +} diff --git a/solutions/2043. Simple Bank System/2043.py b/solutions/2043. Simple Bank System/2043.py new file mode 100644 index 00000000000..7fe5b743d16 --- /dev/null +++ b/solutions/2043. Simple Bank System/2043.py @@ -0,0 +1,25 @@ +class Bank: + def __init__(self, balance: List[int]): + self.balance = balance + + def transfer(self, account1: int, account2: int, money: int) -> bool: + if not self._isValid(account2): + return False + return self.withdraw(account1, money) and self.deposit(account2, money) + + def deposit(self, account: int, money: int) -> bool: + if not self._isValid(account): + return False + self.balance[account - 1] += money + return True + + def withdraw(self, account: int, money: int) -> bool: + if not self._isValid(account): + return False + if self.balance[account - 1] < money: + return False + self.balance[account - 1] -= money + return True + + def _isValid(self, account: int) -> bool: + return 1 <= account <= len(self.balance) diff --git a/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.cpp b/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.cpp new file mode 100644 index 00000000000..f63772fef19 --- /dev/null +++ b/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countMaxOrSubsets(vector& nums) { + const int ors = accumulate(nums.begin(), nums.end(), 0, bit_or<>()); + int ans = 0; + dfs(nums, 0, 0, ors, ans); + return ans; + } + + private: + void dfs(const vector& nums, int i, int path, const int& ors, int& ans) { + if (i == nums.size()) { + if (path == ors) + ++ans; + return; + } + + dfs(nums, i + 1, path, ors, ans); + dfs(nums, i + 1, path | nums[i], ors, ans); + } +}; diff --git a/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.java b/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.java new file mode 100644 index 00000000000..beeea472c0f --- /dev/null +++ b/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.java @@ -0,0 +1,20 @@ +class Solution { + public int countMaxOrSubsets(int[] nums) { + final int ors = Arrays.stream(nums).reduce((a, b) -> a | b).getAsInt(); + dfs(nums, 0, 0, ors); + return ans; + } + + private int ans = 0; + + private void dfs(int[] nums, int i, int path, final int ors) { + if (i == nums.length) { + if (path == ors) + ++ans; + return; + } + + dfs(nums, i + 1, path, ors); + dfs(nums, i + 1, path | nums[i], ors); + } +} diff --git a/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.py b/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.py new file mode 100644 index 00000000000..b7bdab43fac --- /dev/null +++ b/solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.py @@ -0,0 +1,17 @@ +class Solution: + def countMaxOrSubsets(self, nums: List[int]) -> int: + ors = functools.reduce(operator.or_, nums) + ans = 0 + + def dfs(i: int, path: int) -> None: + nonlocal ans + if i == len(nums): + if path == ors: + ans += 1 + return + + dfs(i + 1, path) + dfs(i + 1, path | nums[i]) + + dfs(0, 0) + return ans diff --git a/solutions/2045. Second Minimum Time to Reach Destination/2045.cpp b/solutions/2045. Second Minimum Time to Reach Destination/2045.cpp new file mode 100644 index 00000000000..04549fc49df --- /dev/null +++ b/solutions/2045. Second Minimum Time to Reach Destination/2045.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int secondMinimum(int n, vector>& edges, int time, int change) { + vector> graph(n + 1); + queue> q{{{1, 0}}}; + // minTime[i][0] := the first minimum time to reach the node i + // minTime[i][1] := the second minimum time to reach the node i + vector> minTime(n + 1, vector(2, INT_MAX)); + minTime[1][0] = 0; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + while (!q.empty()) { + const auto [i, prevTime] = q.front(); + q.pop(); + // Start from green. + // If `numChangeSignal` is odd, now red. + // If `numChangeSignal` is even, now green. + const int numChangeSignal = prevTime / change; + const int waitTime = + numChangeSignal % 2 == 0 ? 0 : change - prevTime % change; + const int newTime = prevTime + waitTime + time; + for (const int j : graph[i]) + if (newTime < minTime[j][0]) { + minTime[j][0] = newTime; + q.emplace(j, newTime); + } else if (minTime[j][0] < newTime && newTime < minTime[j][1]) { + if (j == n) + return newTime; + minTime[j][1] = newTime; + q.emplace(j, newTime); + } + } + + throw; + } +}; diff --git a/solutions/2045. Second Minimum Time to Reach Destination/2045.java b/solutions/2045. Second Minimum Time to Reach Destination/2045.java new file mode 100644 index 00000000000..e80697e76db --- /dev/null +++ b/solutions/2045. Second Minimum Time to Reach Destination/2045.java @@ -0,0 +1,44 @@ +class Solution { + public int secondMinimum(int n, int[][] edges, int time, int change) { + List[] graph = new List[n + 1]; + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {1, 0})); // (index, time) + // minTime[i][0] := the first minimum time to reach the node i + // minTime[i][1] := the second minimum time to reach the node i + int[][] minTime = new int[n + 1][2]; + Arrays.stream(minTime).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + minTime[1][0] = 0; + + for (int i = 1; i <= n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int prevTime = q.poll()[1]; + // Start from green. + // If `numChangeSignal` is odd, now red. + // If `numChangeSignal` is even, now green. + final int numChangeSignal = prevTime / change; + final int waitTime = numChangeSignal % 2 == 0 ? 0 : change - prevTime % change; + final int newTime = prevTime + waitTime + time; + for (final int j : graph[i]) + if (newTime < minTime[j][0]) { + minTime[j][0] = newTime; + q.offer(new int[] {j, newTime}); + } else if (minTime[j][0] < newTime && newTime < minTime[j][1]) { + if (j == n) + return newTime; + minTime[j][1] = newTime; + q.offer(new int[] {j, newTime}); + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2045. Second Minimum Time to Reach Destination/2045.py b/solutions/2045. Second Minimum Time to Reach Destination/2045.py new file mode 100644 index 00000000000..8be783d4cb5 --- /dev/null +++ b/solutions/2045. Second Minimum Time to Reach Destination/2045.py @@ -0,0 +1,31 @@ +class Solution: + def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int: + graph = [[] for _ in range(n + 1)] + q = collections.deque([(1, 0)]) + # minTime[i][0] := the first minimum time to reach the node i + # minTime[i][1] := the second minimum time to reach the node i + minTime = [[math.inf] * 2 for _ in range(n + 1)] + minTime[1][0] = 0 + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + while q: + i, prevTime = q.popleft() + # Start from green. + # If `numChangeSignal` is odd, now red. + # If numChangeSignal is even -> now gree + numChangeSignal = prevTime // change + waitTime = 0 if numChangeSignal % 2 == 0 \ + else change - (prevTime % change) + newTime = prevTime + waitTime + time + for j in graph[i]: + if newTime < minTime[j][0]: + minTime[j][0] = newTime + q.append((j, newTime)) + elif minTime[j][0] < newTime < minTime[j][1]: + if j == n: + return newTime + minTime[j][1] = newTime + q.append((j, newTime)) diff --git a/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.cpp b/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.cpp new file mode 100644 index 00000000000..a69d15f6fe9 --- /dev/null +++ b/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + ListNode* sortLinkedList(ListNode* head) { + ListNode* prev = head; + ListNode* curr = head->next; + + while (curr) + if (curr->val < 0) { + prev->next = curr->next; + curr->next = head; + head = curr; + curr = prev->next; + } else { + prev = curr; + curr = curr->next; + } + + return head; + } +}; diff --git a/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.java b/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.java new file mode 100644 index 00000000000..d31a3e5e876 --- /dev/null +++ b/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.java @@ -0,0 +1,19 @@ +class Solution { + public ListNode sortLinkedList(ListNode head) { + ListNode prev = head; + ListNode curr = head.next; + + while (curr != null) + if (curr.val < 0) { + prev.next = curr.next; + curr.next = head; + head = curr; + curr = prev.next; + } else { + prev = curr; + curr = curr.next; + } + + return head; + } +} diff --git a/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.py b/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.py new file mode 100644 index 00000000000..b32183a4281 --- /dev/null +++ b/solutions/2046. Sort Linked List Already Sorted Using Absolute Values/2046.py @@ -0,0 +1,16 @@ +class Solution: + def sortLinkedList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = head + curr = head.next + + while curr: + if curr.val < 0: + prev.next = curr.next + curr.next = head + head = curr + curr = prev.next + else: + prev = curr + curr = curr.next + + return head diff --git a/solutions/2047. Number of Valid Words in a Sentence/2047-2.cpp b/solutions/2047. Number of Valid Words in a Sentence/2047-2.cpp new file mode 100644 index 00000000000..8191c1ddd39 --- /dev/null +++ b/solutions/2047. Number of Valid Words in a Sentence/2047-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int countValidWords(string sentence) { + const regex re("[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?"); + int ans = 0; + istringstream iss(sentence); + + for (string token; iss >> token;) + if (regex_match(token, re)) + ++ans; + + return ans; + } +}; diff --git a/solutions/2047. Number of Valid Words in a Sentence/2047-2.java b/solutions/2047. Number of Valid Words in a Sentence/2047-2.java new file mode 100644 index 00000000000..e2152e18bf7 --- /dev/null +++ b/solutions/2047. Number of Valid Words in a Sentence/2047-2.java @@ -0,0 +1,12 @@ +class Solution { + public int countValidWords(String sentence) { + final String regex = "[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?"; + int ans = 0; + + for (final String token : sentence.trim().split("\\s+")) + if (token.matches(regex)) + ++ans; + + return ans; + } +} diff --git a/solutions/2047. Number of Valid Words in a Sentence/2047-2.py b/solutions/2047. Number of Valid Words in a Sentence/2047-2.py new file mode 100644 index 00000000000..9fc9501cf3b --- /dev/null +++ b/solutions/2047. Number of Valid Words in a Sentence/2047-2.py @@ -0,0 +1,4 @@ +class Solution: + def countValidWords(self, sentence: str) -> int: + pattern = re.compile(r'^[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?$') + return sum(pattern.search(token) != None for token in sentence.strip().split()) diff --git a/solutions/2047. Number of Valid Words in a Sentence/2047.cpp b/solutions/2047. Number of Valid Words in a Sentence/2047.cpp new file mode 100644 index 00000000000..d4f4f003900 --- /dev/null +++ b/solutions/2047. Number of Valid Words in a Sentence/2047.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int countValidWords(string sentence) { + int ans = 0; + istringstream iss(sentence); + + for (string token; iss >> token;) + if (isValid(token)) + ++ans; + + return ans; + } + + private: + bool isValid(const string& token) { + int countHyphen = 0; + for (int i = 0; i < token.length(); ++i) { + const char c = token[i]; + if (isdigit(c)) + return false; + if (c == '-') { + if (i == 0 || !isalpha(token[i - 1])) + return false; + if (i + 1 == token.length() || !isalpha(token[i + 1])) + return false; + if (++countHyphen > 1) + return false; + } else if (c == '!' || c == '.' || c == ',') { + if (i != token.length() - 1) + return false; + } + } + return true; + } +}; diff --git a/solutions/2047. Number of Valid Words in a Sentence/2047.java b/solutions/2047. Number of Valid Words in a Sentence/2047.java new file mode 100644 index 00000000000..0ac11b9488d --- /dev/null +++ b/solutions/2047. Number of Valid Words in a Sentence/2047.java @@ -0,0 +1,32 @@ +class Solution { + public int countValidWords(String sentence) { + int ans = 0; + + for (final String token : sentence.trim().split("\\s+")) + if (isValid(token)) + ++ans; + + return ans; + } + + private boolean isValid(final String token) { + int countHyphen = 0; + for (int i = 0; i < token.length(); ++i) { + final char c = token.charAt(i); + if (Character.isDigit(c)) + return false; + if (c == '-') { + if (i == 0 || !Character.isLowerCase(token.charAt(i - 1))) + return false; + if (i + 1 == token.length() || !Character.isLowerCase(token.charAt(i + 1))) + return false; + if (++countHyphen > 1) + return false; + } else if (c == '!' || c == '.' || c == ',') { + if (i != token.length() - 1) + return false; + } + } + return true; + } +} diff --git a/solutions/2047. Number of Valid Words in a Sentence/2047.py b/solutions/2047. Number of Valid Words in a Sentence/2047.py new file mode 100644 index 00000000000..20235025b8d --- /dev/null +++ b/solutions/2047. Number of Valid Words in a Sentence/2047.py @@ -0,0 +1,21 @@ +class Solution: + def countValidWords(self, sentence: str) -> int: + def isValid(token: str) -> bool: + countHyphen = 0 + for i, c in enumerate(token): + if c.isdigit(): + return False + if c == '-': + if i == 0 or not token[i - 1].isalpha(): + return False + if i == len(token) - 1 or not token[i + 1].isalpha(): + return False + if countHyphen == 1: + return False + countHyphen += 1 + if c in ['!', '.', ',']: + if i != len(token) - 1: + return False + return True + + return sum(isValid(token) for token in sentence.split()) diff --git a/solutions/2048. Next Greater Numerically Balanced Number/2048.cpp b/solutions/2048. Next Greater Numerically Balanced Number/2048.cpp new file mode 100644 index 00000000000..ed0d0b215d7 --- /dev/null +++ b/solutions/2048. Next Greater Numerically Balanced Number/2048.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int nextBeautifulNumber(int n) { + while (!isBalance(++n)) + ; + return n; + } + + private: + bool isBalance(int num) { + vector count(10); + while (num) { + if (num % 10 == 0) + return false; + ++count[num % 10]; + num /= 10; + } + for (int i = 1; i < 10; ++i) + if (count[i] && count[i] != i) + return false; + return true; + } +}; diff --git a/solutions/2048. Next Greater Numerically Balanced Number/2048.java b/solutions/2048. Next Greater Numerically Balanced Number/2048.java new file mode 100644 index 00000000000..9caac53069c --- /dev/null +++ b/solutions/2048. Next Greater Numerically Balanced Number/2048.java @@ -0,0 +1,21 @@ +class Solution { + public int nextBeautifulNumber(int n) { + while (!isBalance(++n)) + ; + return n; + } + + private boolean isBalance(int num) { + int[] count = new int[10]; + while (num > 0) { + if (num % 10 == 0) + return false; + ++count[num % 10]; + num /= 10; + } + for (int i = 1; i < 10; ++i) + if (count[i] > 0 && count[i] != i) + return false; + return true; + } +} diff --git a/solutions/2048. Next Greater Numerically Balanced Number/2048.py b/solutions/2048. Next Greater Numerically Balanced Number/2048.py new file mode 100644 index 00000000000..2e0fd2aca9e --- /dev/null +++ b/solutions/2048. Next Greater Numerically Balanced Number/2048.py @@ -0,0 +1,15 @@ +class Solution: + def nextBeautifulNumber(self, n: int) -> int: + def isBalance(num: int) -> bool: + count = [0] * 10 + while num: + if num % 10 == 0: + return False + count[num % 10] += 1 + num //= 10 + return all(c == i for i, c in enumerate(count) if c) + + n += 1 + while not isBalance(n): + n += 1 + return n diff --git a/solutions/2049. Count Nodes With the Highest Score/2049.cpp b/solutions/2049. Count Nodes With the Highest Score/2049.cpp new file mode 100644 index 00000000000..f699aa90aba --- /dev/null +++ b/solutions/2049. Count Nodes With the Highest Score/2049.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int countHighestScoreNodes(vector& parents) { + int ans = 0; + vector> tree(parents.size()); + + for (int i = 0; i < parents.size(); ++i) { + if (parents[i] == -1) + continue; + tree[parents[i]].push_back(i); + } + + dfs(tree, 0, 0, ans); + return ans; + } + + private: + int dfs(const vector>& tree, int u, long&& maxScore, int& ans) { + int count = 1; + long score = 1; + for (const int v : tree[u]) { + const int childCount = dfs(tree, v, move(maxScore), ans); + count += childCount; + score *= childCount; + } + const int aboveCount = tree.size() - count; + score *= max(aboveCount, 1); + if (score > maxScore) { + maxScore = score; + ans = 1; + } else if (score == maxScore) { + ++ans; + } + return count; + } +}; diff --git a/solutions/2049. Count Nodes With the Highest Score/2049.java b/solutions/2049. Count Nodes With the Highest Score/2049.java new file mode 100644 index 00000000000..5d70471dd6c --- /dev/null +++ b/solutions/2049. Count Nodes With the Highest Score/2049.java @@ -0,0 +1,39 @@ +class Solution { + public int countHighestScoreNodes(int[] parents) { + List[] tree = new List[parents.length]; + + for (int i = 0; i < tree.length; ++i) + tree[i] = new ArrayList<>(); + + for (int i = 0; i < parents.length; ++i) { + if (parents[i] == -1) + continue; + tree[parents[i]].add(i); + } + + dfs(tree, 0); + return ans; + } + + private int ans = 0; + private long maxScore = 0; + + private int dfs(List[] tree, int u) { + int count = 1; + long score = 1; + for (final int v : tree[u]) { + final int childCount = dfs(tree, v); + count += childCount; + score *= childCount; + } + final int aboveCount = tree.length - count; + score *= Math.max(aboveCount, 1); + if (score > maxScore) { + maxScore = score; + ans = 1; + } else if (score == maxScore) { + ++ans; + } + return count; + } +} diff --git a/solutions/2049. Count Nodes With the Highest Score/2049.py b/solutions/2049. Count Nodes With the Highest Score/2049.py new file mode 100644 index 00000000000..e820c94695c --- /dev/null +++ b/solutions/2049. Count Nodes With the Highest Score/2049.py @@ -0,0 +1,31 @@ +class Solution: + def countHighestScoreNodes(self, parents: List[int]) -> int: + tree = [[] for _ in range(len(parents))] + + for i, parent in enumerate(parents): + if parent == -1: + continue + tree[parent].append(i) + + ans = 0 + maxScore = 0 + + def dfs(u: int) -> int: # Returns node count + nonlocal ans + nonlocal maxScore + count = 1 + score = 1 + for v in tree[u]: + childCount = dfs(v) + count += childCount + score *= childCount + score *= len(parents) - count or 1 + if score > maxScore: + maxScore = score + ans = 1 + elif score == maxScore: + ans += 1 + return count + + dfs(0) + return ans diff --git a/solutions/205. Isomorphic Strings/205.cpp b/solutions/205. Isomorphic Strings/205.cpp new file mode 100644 index 00000000000..cb82d9fadcb --- /dev/null +++ b/solutions/205. Isomorphic Strings/205.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool isIsomorphic(string s, string t) { + vector charToIndex_s(128); + vector charToIndex_t(128); + + for (int i = 0; i < s.length(); ++i) { + if (charToIndex_s[s[i]] != charToIndex_t[t[i]]) + return false; + charToIndex_s[s[i]] = i + 1; + charToIndex_t[t[i]] = i + 1; + } + + return true; + } +}; diff --git a/solutions/205. Isomorphic Strings/205.java b/solutions/205. Isomorphic Strings/205.java new file mode 100644 index 00000000000..0f13ed990dd --- /dev/null +++ b/solutions/205. Isomorphic Strings/205.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isIsomorphic(String s, String t) { + Map charToIndex_s = new HashMap<>(); + Map charToIndex_t = new HashMap<>(); + + for (Integer i = 0; i < s.length(); ++i) + if (charToIndex_s.put(s.charAt(i), i) != charToIndex_t.put(t.charAt(i), i)) + return false; + + return true; + } +} diff --git a/solutions/205. Isomorphic Strings/205.py b/solutions/205. Isomorphic Strings/205.py new file mode 100644 index 00000000000..bda9043bcd4 --- /dev/null +++ b/solutions/205. Isomorphic Strings/205.py @@ -0,0 +1,3 @@ +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + return [*map(s.index, s)] == [*map(t.index, t)] diff --git a/solutions/2050. Parallel Courses III/2050.cpp b/solutions/2050. Parallel Courses III/2050.cpp new file mode 100644 index 00000000000..3f07a8d100f --- /dev/null +++ b/solutions/2050. Parallel Courses III/2050.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minimumTime(int n, vector>& relations, vector& time) { + vector> graph(n); + vector inDegrees(n); + queue q; + vector dist(time); + + // Build the graph. + for (const vector& r : relations) { + const int u = r[0] - 1; + const int v = r[1] - 1; + graph[u].push_back(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) { + dist[v] = max(dist[v], dist[u] + time[v]); + if (--inDegrees[v] == 0) + q.push(v); + } + } + + return ranges::max(dist); + } +}; diff --git a/solutions/2050. Parallel Courses III/2050.java b/solutions/2050. Parallel Courses III/2050.java new file mode 100644 index 00000000000..17524c5a093 --- /dev/null +++ b/solutions/2050. Parallel Courses III/2050.java @@ -0,0 +1,35 @@ +class Solution { + public int minimumTime(int n, int[][] relations, int[] time) { + List[] graph = new List[n]; + int[] inDegrees = new int[n]; + int[] dist = time.clone(); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph. + for (int[] r : relations) { + final int u = r[0] - 1; + final int v = r[1] - 1; + graph[u].add(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + Queue q = IntStream.range(0, n) + .filter(i -> inDegrees[i] == 0) + .boxed() + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + final int u = q.poll(); + for (final int v : graph[u]) { + dist[v] = Math.max(dist[v], dist[u] + time[v]); + if (--inDegrees[v] == 0) + q.offer(v); + } + } + + return Arrays.stream(dist).max().getAsInt(); + } +} diff --git a/solutions/2050. Parallel Courses III/2050.py b/solutions/2050. Parallel Courses III/2050.py new file mode 100644 index 00000000000..322ef8b2781 --- /dev/null +++ b/solutions/2050. Parallel Courses III/2050.py @@ -0,0 +1,25 @@ +class Solution: + def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int: + graph = [[] for _ in range(n)] + inDegrees = [0] * n + dist = time.copy() + + # Build the graph. + for a, b in relations: + u = a - 1 + v = b - 1 + graph[u].append(v) + inDegrees[v] += 1 + + # Perform topological sorting. + q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) + + while q: + u = q.popleft() + for v in graph[u]: + dist[v] = max(dist[v], dist[u] + time[v]) + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + + return max(dist) diff --git a/solutions/2051. The Category of Each Member in the Store/2051.sql b/solutions/2051. The Category of Each Member in the Store/2051.sql new file mode 100644 index 00000000000..92900f33d4f --- /dev/null +++ b/solutions/2051. The Category of Each Member in the Store/2051.sql @@ -0,0 +1,15 @@ +SELECT + Members.member_id, + Members.name, + CASE + WHEN COUNT(Visits.visit_id) = 0 THEN 'Bronze' + WHEN COUNT(Purchases.visit_id) / COUNT(Visits.visit_id) >= 0.8 THEN 'Diamond' + WHEN COUNT(Purchases.visit_id) / COUNT(Visits.visit_id) >= 0.5 THEN 'Gold' + ELSE 'Silver' + END AS category +FROM Members +LEFT JOIN Visits + USING (member_id) +LEFT JOIN Purchases + USING (visit_id) +GROUP BY 1; diff --git a/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.cpp b/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.cpp new file mode 100644 index 00000000000..5225a54bac5 --- /dev/null +++ b/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int minimumCost(string sentence, int k) { + if (sentence.length() <= k) + return 0; + + vector words = getWords(sentence); + + // dp[i] := the minimum cost of the first i words + vector dp(words.size() + 1); + + for (int i = 1; i <= words.size(); ++i) { + int n = words[i - 1].length(); // the length of the current row + dp[i] = dp[i - 1] + (k - n) * (k - n); + // Gradually add words[j - 1], words[j - 2], .... + for (int j = i - 1; j > 0; --j) { + n += words[j - 1].length() + 1; + if (n > k) + break; + dp[i] = min(dp[i], dp[j - 1] + (k - n) * (k - n)); + } + } + + int lastRowLen = words.back().length(); + int i = words.size() - 2; + + while (i > 0 && lastRowLen + words[i].length() + 1 <= k) + lastRowLen += words[i--].length() + 1; + + return *min_element(dp.begin() + i + 1, dp.end()); + } + + private: + vector getWords(const string& sentence) { + vector words; + istringstream iss(sentence); + for (string token; iss >> token;) + words.push_back(token); + return words; + } +}; diff --git a/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.java b/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.java new file mode 100644 index 00000000000..62d17ff2e20 --- /dev/null +++ b/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.java @@ -0,0 +1,30 @@ +class Solution { + public int minimumCost(String sentence, int k) { + if (sentence.length() <= k) + return 0; + + String[] words = sentence.split(" "); + // dp[i] := the minimum cost of the first i words + int[] dp = new int[words.length + 1]; + + for (int i = 1; i <= words.length; ++i) { + int n = words[i - 1].length(); // the length of the current row + dp[i] = dp[i - 1] + (k - n) * (k - n); + // Gradually add words[j - 1], words[j - 2], .... + for (int j = i - 1; j > 0; --j) { + n += words[j - 1].length() + 1; + if (n > k) + break; + dp[i] = Math.min(dp[i], dp[j - 1] + (k - n) * (k - n)); + } + } + + int lastRowLen = words[words.length - 1].length(); + int i = words.length - 2; + + while (i > 0 && lastRowLen + words[i].length() + 1 <= k) + lastRowLen += words[i--].length(); + + return Arrays.stream(dp, i + 1, words.length).min().getAsInt(); + } +} diff --git a/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.py b/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.py new file mode 100644 index 00000000000..6389d6cdbe3 --- /dev/null +++ b/solutions/2052. Minimum Cost to Separate Sentence Into Rows/2052.py @@ -0,0 +1,28 @@ +class Solution: + def minimumCost(self, sentence: str, k: int) -> int: + if len(sentence) <= k: + return 0 + + words = sentence.split() + + # dp[i] := the minimum cost of the first i words + dp = [0] * (len(words) + 1) + + for i in range(1, len(words) + 1): + n = len(words[i - 1]) # the length of the current row + dp[i] = dp[i - 1] + (k - n)**2 + # Gradually add words[j - 1], words[j - 2], .... + for j in range(i - 1, 0, -1): + n += len(words[j - 1]) + 1 + if n > k: + break + dp[i] = min(dp[i], dp[j - 1] + (k - n)**2) + + lastRowLen = len(words[-1]) + i = len(words) - 2 # Greedily put words into last row + + while i > 0 and lastRowLen + len(words[i]) + 1 <= k: + lastRowLen += len(words[i]) + 1 + i -= 1 + + return min(dp[i + 1:len(words)]) diff --git a/solutions/2053. Kth Distinct String in an Array/2053.cpp b/solutions/2053. Kth Distinct String in an Array/2053.cpp new file mode 100644 index 00000000000..3254947c5fc --- /dev/null +++ b/solutions/2053. Kth Distinct String in an Array/2053.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + string kthDistinct(vector& arr, int k) { + unordered_map count; + + for (const string& a : arr) + ++count[a]; + + for (const string& a : arr) + if (count[a] == 1 && --k == 0) + return a; + + return ""; + } +}; diff --git a/solutions/2053. Kth Distinct String in an Array/2053.java b/solutions/2053. Kth Distinct String in an Array/2053.java new file mode 100644 index 00000000000..d302107bdbe --- /dev/null +++ b/solutions/2053. Kth Distinct String in an Array/2053.java @@ -0,0 +1,14 @@ +class Solution { + public String kthDistinct(String[] arr, int k) { + Map count = new HashMap<>(); + + for (final String a : arr) + count.merge(a, 1, Integer::sum); + + for (final String a : arr) + if (count.get(a) == 1 && --k == 0) + return a; + + return ""; + } +} diff --git a/solutions/2053. Kth Distinct String in an Array/2053.py b/solutions/2053. Kth Distinct String in an Array/2053.py new file mode 100644 index 00000000000..8b25bd1add1 --- /dev/null +++ b/solutions/2053. Kth Distinct String in an Array/2053.py @@ -0,0 +1,11 @@ +class Solution: + def kthDistinct(self, arr: List[str], k: int) -> str: + count = collections.Counter(arr) + + for a in arr: + if count[a] == 1: + k -= 1 + if k == 0: + return a + + return '' diff --git a/solutions/2054. Two Best Non-Overlapping Events/2054.cpp b/solutions/2054. Two Best Non-Overlapping Events/2054.cpp new file mode 100644 index 00000000000..2895d858b15 --- /dev/null +++ b/solutions/2054. Two Best Non-Overlapping Events/2054.cpp @@ -0,0 +1,36 @@ +struct Event { + int time; + int value; + bool isStart; + Event(int time, int value, bool isStart) + : time(time), value(value), isStart(isStart) {} +}; + +class Solution { + public: + int maxTwoEvents(vector>& events) { + int ans = 0; + int maxValue = 0; + vector evts; + + for (const vector& event : events) { + const int start = event[0]; + const int end = event[1]; + const int value = event[2]; + evts.emplace_back(start, value, true); + evts.emplace_back(end + 1, value, false); + } + + ranges::sort(evts, [](const Event& a, const Event& b) { + return a.time == b.time ? a.isStart < b.isStart : a.time < b.time; + }); + + for (const auto& [_, value, isStart] : evts) + if (isStart) + ans = max(ans, value + maxValue); + else + maxValue = max(maxValue, value); + + return ans; + } +}; diff --git a/solutions/2054. Two Best Non-Overlapping Events/2054.java b/solutions/2054. Two Best Non-Overlapping Events/2054.java new file mode 100644 index 00000000000..b52680b9a43 --- /dev/null +++ b/solutions/2054. Two Best Non-Overlapping Events/2054.java @@ -0,0 +1,36 @@ +class Event { + public int time; + public int value; + public int isStart; + public Event(int time, int value, int isStart) { + this.time = time; + this.value = value; + this.isStart = isStart; + } +}; + +class Solution { + public int maxTwoEvents(int[][] events) { + int ans = 0; + int maxValue = 0; + Event[] evts = new Event[events.length * 2]; + + for (int i = 0; i < events.length; ++i) { + final int start = events[i][0]; + final int end = events[i][1]; + final int value = events[i][2]; + evts[i * 2] = new Event(start, value, 1); + evts[i * 2 + 1] = new Event(end + 1, value, 0); + } + + Arrays.sort(evts, (a, b) -> a.time == b.time ? a.isStart - b.isStart : a.time - b.time); + + for (Event evt : evts) + if (evt.isStart == 1) + ans = Math.max(ans, evt.value + maxValue); + else + maxValue = Math.max(maxValue, evt.value); + + return ans; + } +} diff --git a/solutions/2054. Two Best Non-Overlapping Events/2054.py b/solutions/2054. Two Best Non-Overlapping Events/2054.py new file mode 100644 index 00000000000..4862002566e --- /dev/null +++ b/solutions/2054. Two Best Non-Overlapping Events/2054.py @@ -0,0 +1,20 @@ +class Solution: + def maxTwoEvents(self, events: List[List[int]]) -> int: + ans = 0 + maxValue = 0 + evts = [] # (time, isStart, value) + + for s, e, v in events: + evts.append((s, 1, v)) + evts.append((e + 1, 0, v)) + + # When two events have the same time, the one is not start will be in the front + evts.sort() + + for _, isStart, value in evts: + if isStart: + ans = max(ans, value + maxValue) + else: + maxValue = max(maxValue, value) + + return ans diff --git a/solutions/2055. Plates Between Candles/2055-2.cpp b/solutions/2055. Plates Between Candles/2055-2.cpp new file mode 100644 index 00000000000..70c57288cc7 --- /dev/null +++ b/solutions/2055. Plates Between Candles/2055-2.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + vector platesBetweenCandles(string s, vector>& queries) { + const int n = s.length(); + vector ans; + vector closestLeftCandle(n); + vector closestRightCandle(n); + vector candleCount( + n); // candleCount[i] := the number of candles in s[0..i] + int candle = -1; + int count = 0; + + for (int i = 0; i < n; ++i) { + if (s[i] == '|') { + candle = i; + ++count; + } + closestLeftCandle[i] = candle; + candleCount[i] = count; + } + + candle = -1; + for (int i = n - 1; i >= 0; --i) { + if (s[i] == '|') + candle = i; + closestRightCandle[i] = candle; + } + + for (const vector& query : queries) { + const int left = query[0]; + const int right = query[1]; + const int l = closestRightCandle[left]; + const int r = closestLeftCandle[right]; + if (l == -1 || r == -1 || l > r) { + ans.push_back(0); + } else { + const int lengthBetweenCandles = r - l + 1; + const int numCandles = candleCount[r] - candleCount[l] + 1; + ans.push_back(lengthBetweenCandles - numCandles); + } + } + + return ans; + } +}; diff --git a/solutions/2055. Plates Between Candles/2055-2.java b/solutions/2055. Plates Between Candles/2055-2.java new file mode 100644 index 00000000000..9f198d3e9ea --- /dev/null +++ b/solutions/2055. Plates Between Candles/2055-2.java @@ -0,0 +1,41 @@ +class Solution { + public int[] platesBetweenCandles(String s, int[][] queries) { + final int n = s.length(); + int[] ans = new int[queries.length]; + int[] closestLeftCandle = new int[n]; + int[] closestRightCandle = new int[n]; + int[] candleCount = new int[n]; // candleCount[i] := the number of candles in s[0..i] + int candle = -1; + int count = 0; + + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == '|') { + candle = i; + ++count; + } + closestLeftCandle[i] = candle; + candleCount[i] = count; + } + + candle = -1; + for (int i = n - 1; i >= 0; --i) { + if (s.charAt(i) == '|') + candle = i; + closestRightCandle[i] = candle; + } + + for (int i = 0; i < queries.length; ++i) { + final int left = queries[i][0]; + final int right = queries[i][1]; + final int l = closestRightCandle[left]; + final int r = closestLeftCandle[right]; + if (i == -1 || r == -1 || l > r) + continue; + final int lengthBetweenCandles = r - l + 1; + final int numCandles = candleCount[r] - candleCount[l] + 1; + ans[i] = lengthBetweenCandles - numCandles; + } + + return ans; + } +} diff --git a/solutions/2055. Plates Between Candles/2055-2.py b/solutions/2055. Plates Between Candles/2055-2.py new file mode 100644 index 00000000000..979ed8d0f32 --- /dev/null +++ b/solutions/2055. Plates Between Candles/2055-2.py @@ -0,0 +1,34 @@ +class Solution: + def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: + n = len(s) + ans = [] + closestLeftCandle = [0] * n + closestRightCandle = [0] * n + candleCount = [0] * n # candleCount[i] := the number of candles in s[0..i] + candle = -1 + count = 0 + + for i, c in enumerate(s): + if c == '|': + candle = i + count += 1 + closestLeftCandle[i] = candle + candleCount[i] = count + + candle = -1 + for i, c in reversed(list(enumerate(s))): + if c == '|': + candle = i + closestRightCandle[i] = candle + + for left, right in queries: + l = closestRightCandle[left] + r = closestLeftCandle[right] + if l == -1 or r == -1 or l > r: + ans.append(0) + else: + lengthBetweenCandles = r - l + 1 + numCandles = candleCount[r] - candleCount[l] + 1 + ans.append(lengthBetweenCandles - numCandles) + + return ans diff --git a/solutions/2055. Plates Between Candles/2055.cpp b/solutions/2055. Plates Between Candles/2055.cpp new file mode 100644 index 00000000000..168c087b6ae --- /dev/null +++ b/solutions/2055. Plates Between Candles/2055.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector platesBetweenCandles(string s, vector>& queries) { + vector ans; + vector indices; // indices of '|' + + for (int i = 0; i < s.length(); ++i) + if (s[i] == '|') + indices.push_back(i); + + for (const vector& query : queries) { + const int left = query[0]; + const int right = query[1]; + const int l = ranges::lower_bound(indices, left) - indices.begin(); + const int r = ranges::upper_bound(indices, right) - indices.begin() - 1; + if (l < r) { + const int lengthBetweenCandles = indices[r] - indices[l] + 1; + const int numCandles = r - l + 1; + ans.push_back(lengthBetweenCandles - numCandles); + } else { + ans.push_back(0); + } + } + + return ans; + } +}; diff --git a/solutions/2055. Plates Between Candles/2055.java b/solutions/2055. Plates Between Candles/2055.java new file mode 100644 index 00000000000..2ad6bbd9f52 --- /dev/null +++ b/solutions/2055. Plates Between Candles/2055.java @@ -0,0 +1,29 @@ +class Solution { + public int[] platesBetweenCandles(String s, int[][] queries) { + int[] ans = new int[queries.length]; + List indices = new ArrayList<>(); // indices of '|' + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) == '|') + indices.add(i); + + for (int i = 0; i < queries.length; ++i) { + final int left = queries[i][0]; + final int right = queries[i][1]; + final int l = firstGreaterEqual(indices, left); + final int r = firstGreaterEqual(indices, right + 1) - 1; + if (l < r) { + final int lengthBetweenCandles = indices.get(r) - indices.get(l) + 1; + final int numCandles = r - l + 1; + ans[i] = lengthBetweenCandles - numCandles; + } + } + + return ans; + } + + private int firstGreaterEqual(List indices, int target) { + final int i = Collections.binarySearch(indices, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2055. Plates Between Candles/2055.py b/solutions/2055. Plates Between Candles/2055.py new file mode 100644 index 00000000000..53d641f8ddd --- /dev/null +++ b/solutions/2055. Plates Between Candles/2055.py @@ -0,0 +1,16 @@ +class Solution: + def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: + ans = [] + indices = [i for i, c in enumerate(s) if c == '|'] # indices of '|' + + for left, right in queries: + l = bisect.bisect_left(indices, left) + r = bisect.bisect_right(indices, right) - 1 + if l < r: + lengthBetweenCandles = indices[r] - indices[l] + 1 + numCandles = r - l + 1 + ans.append(lengthBetweenCandles - numCandles) + else: + ans.append(0) + + return ans diff --git a/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.cpp b/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.cpp new file mode 100644 index 00000000000..3a7891bcce0 --- /dev/null +++ b/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.cpp @@ -0,0 +1,89 @@ +class Solution { + public: + int countCombinations(vector& pieces, + vector>& positions) { + const int n = pieces.size(); + unordered_set hashedBoards; + // Stores all possible move combinations for `pieces`. Each element is a + // vector of moves, one for each piece in the input order. e.g., if pieces = + // ["rook", "bishop"], one element might be [[1,0], [1,1]], representing a + // rook moving right and a bishop moving diagonally up-right. + vector>> pieceMovesList; + + getPieceMovesList(pieces, 0, {}, pieceMovesList); + + for (const vector>& pieceMoves : pieceMovesList) + dfs(positions, n, pieceMoves, (1 << n) - 1, hashedBoards); + + return hashedBoards.size(); + } + + private: + const unordered_map>> kPieceToMoves{ + {"rook", {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}}, + {"bishop", {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}}, + {"queen", + {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}}}; + + // Generates all possible combinations of moves. + void getPieceMovesList(const vector& pieces, int i, + vector>&& path, + vector>>& pieceMovesList) { + if (i == pieces.size()) { + pieceMovesList.push_back(path); + return; + } + for (const pair& move : kPieceToMoves.at(pieces[i])) { + path.push_back(move); + getPieceMovesList(pieces, i + 1, std::move(path), pieceMovesList); + path.pop_back(); + } + } + + // Performs a depth-first search to explore all possible board states. + void dfs(const vector>& board, int n, + const vector>& pieceMoves, int activeMask, + unordered_set& hashedBoards) { + if (activeMask == 0) + return; + hashedBoards.insert(getHash(board)); + for (int nextActiveMask = 1; nextActiveMask < 1 << n; ++nextActiveMask) { + if ((activeMask & nextActiveMask) != nextActiveMask) + continue; + + // Copy the board. + vector> nextBoard = board; + + // Move the pieces that are active in this turn. + for (int i = 0; i < n; ++i) + if (nextActiveMask >> i & 1) { + nextBoard[i][0] += pieceMoves[i].first; + nextBoard[i][1] += pieceMoves[i].second; + } + + // No two or more pieces occupy the same square. + if (getUniqueSize(nextBoard) < n) + continue; + + // Every piece needs to be in the boundary. + if (ranges::all_of(nextBoard, [](const vector& pos) { + return 1 <= pos[0] && pos[0] <= 8 && 1 <= pos[1] && pos[1] <= 8; + })) + dfs(nextBoard, n, pieceMoves, nextActiveMask, hashedBoards); + } + } + + long long getHash(const vector>& board) { + long long hash = 0; + for (const vector& pos : board) + hash = (hash * 64) + ((pos[0] - 1) << 3) + (pos[1] - 1); + return hash; + } + + int getUniqueSize(const vector>& board) { + unordered_set unique; + for (const vector& pos : board) + unique.insert(pos[0] * 8 + pos[1]); + return unique.size(); + } +}; diff --git a/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.java b/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.java new file mode 100644 index 00000000000..9a638ae7835 --- /dev/null +++ b/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.java @@ -0,0 +1,91 @@ +class Solution { + public int countCombinations(String[] pieces, int[][] positions) { + final int n = pieces.length; + Set hashedBoards = new HashSet<>(); + // Stores all possible move combinations for `pieces`. Each element is a + // vector of moves, one for each piece in the input order. e.g., if pieces = + // ["rook", "bishop"], one element might be [[1,0], [1,1]], representing a + // rook moving right and a bishop moving diagonally up-right. + List> combMoves = new ArrayList<>(); + + getCombMoves(pieces, 0, new ArrayList<>(), combMoves); + + for (List combMove : combMoves) + dfs(positions, n, combMove, (1 << n) - 1, hashedBoards); + + return hashedBoards.size(); + } + + private static Map kMoves = new HashMap<>(); + + static { + kMoves.put("rook", new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}); + kMoves.put("bishop", new int[][] {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}); + kMoves.put("queen", + new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}); + } + + // Generates all possible combinations of moves for the given pieces. + private void getCombMoves(String[] pieces, int ithPiece, List path, + List> combMoves) { + if (ithPiece == pieces.length) { + combMoves.add(new ArrayList<>(path)); + return; + } + + for (int[] move : kMoves.get(pieces[ithPiece])) { + path.add(move); + getCombMoves(pieces, ithPiece + 1, path, combMoves); + path.remove(path.size() - 1); + } + } + + // Performs a depth-first search to explore all possible board states. + private void dfs(int[][] board, int n, List combMove, int activeMask, + Set hashedBoards) { + if (activeMask == 0) + return; + hashedBoards.add(getHash(board)); + + for (int nextActiveMask = 1; nextActiveMask < 1 << n; ++nextActiveMask) { + if ((activeMask & nextActiveMask) != nextActiveMask) + continue; + + // Copy the board. + int[][] nextBoard = new int[n][]; + for (int i = 0; i < n; ++i) + nextBoard[i] = board[i].clone(); + + // Move the pieces that are active in this turn. + for (int i = 0; i < n; ++i) + if ((nextActiveMask >> i & 1) == 1) { + nextBoard[i][0] += combMove.get(i)[0]; + nextBoard[i][1] += combMove.get(i)[1]; + } + + // No two or more pieces occupy the same square. + if (getUniqueSize(nextBoard) < n) + continue; + + // Every piece needs to be in the boundary. + if (Arrays.stream(nextBoard).allMatch(p -> 1 <= p[0] && p[0] <= 8 && 1 <= p[1] && p[1] <= 8)) + dfs(nextBoard, n, combMove, nextActiveMask, hashedBoards); + } + } + + // Generates a unique hash for the given board state. + private long getHash(int[][] board) { + long hash = 0; + for (int[] pos : board) + hash = (hash * 64) + (pos[0] - 1 << 3) + (pos[1] - 1); + return hash; + } + + // Counts the number of unique positions on the board occupied by the pieces. + private int getUniqueSize(int[][] board) { + Set unique = new HashSet<>(); + for (int[] pos : board) + unique.add(pos[0] * 8 + pos[1]); + return unique.size(); + } +} diff --git a/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.py b/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.py new file mode 100644 index 00000000000..026171e79dc --- /dev/null +++ b/solutions/2056. Number of Valid Move Combinations On Chessboard/2056.py @@ -0,0 +1,42 @@ +class Solution: + def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int: + n = len(pieces) + moves = {"rook": [(1, 0), (-1, 0), (0, 1), (0, -1)], + "bishop": [(1, 1), (1, -1), (-1, 1), (-1, -1)], + "queen": [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]} + hashedBoards = set() + + def getHash(board: List[List[int]]) -> Tuple: + return tuple([tuple(pos) for pos in board]) + + def dfs(board: List[List[int]], pieceMoves: List[Tuple[int, int]], activeMask: int) -> None: + """Performs a depth-first search to explore all possible board states.""" + if activeMask == 0: + return + hashedBoards.add(getHash(board)) + + for nextActiveMask in range(1, 1 << n): + if activeMask & nextActiveMask != nextActiveMask: + continue + + # Copy the board. + nextBoard = [pos.copy() for pos in board] + + # Move the pieces that are active in this turn. + for i in range(n): + if nextActiveMask >> i & 1: + nextBoard[i][0] += pieceMoves[i][0] + nextBoard[i][1] += pieceMoves[i][1] + + # No two or more pieces occupy the same square. + if len(set(getHash(nextBoard))) < n: + continue + + # Every piece needs to be in the boundary. + if all(1 <= x <= 8 and 1 <= y <= 8 for x, y in nextBoard): + dfs(nextBoard, pieceMoves, nextActiveMask) + + for pieceMoves in itertools.product(*(moves[piece] for piece in pieces)): + dfs(positions, pieceMoves, (1 << n) - 1) + + return len(hashedBoards) diff --git a/solutions/2057. Smallest Index With Equal Value/2057.cpp b/solutions/2057. Smallest Index With Equal Value/2057.cpp new file mode 100644 index 00000000000..b858cff6313 --- /dev/null +++ b/solutions/2057. Smallest Index With Equal Value/2057.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int smallestEqual(vector& nums) { + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == i % 10) + return i; + return -1; + } +}; diff --git a/solutions/2057. Smallest Index With Equal Value/2057.java b/solutions/2057. Smallest Index With Equal Value/2057.java new file mode 100644 index 00000000000..db061998012 --- /dev/null +++ b/solutions/2057. Smallest Index With Equal Value/2057.java @@ -0,0 +1,8 @@ +class Solution { + public int smallestEqual(int[] nums) { + for (int i = 0; i < nums.length; ++i) + if (nums[i] == i % 10) + return i; + return -1; + } +} diff --git a/solutions/2057. Smallest Index With Equal Value/2057.py b/solutions/2057. Smallest Index With Equal Value/2057.py new file mode 100644 index 00000000000..c54b0369510 --- /dev/null +++ b/solutions/2057. Smallest Index With Equal Value/2057.py @@ -0,0 +1,3 @@ +class Solution: + def smallestEqual(self, nums: List[int]) -> int: + return next((i for i, num in enumerate(nums) if i % 10 == num), -1) diff --git a/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.cpp b/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.cpp new file mode 100644 index 00000000000..2cc79c83adf --- /dev/null +++ b/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector nodesBetweenCriticalPoints(ListNode* head) { + int minDistance = INT_MAX; + int firstMaIndex = -1; + int prevMaIndex = -1; + int index = 1; + ListNode* prev = head; // Point to the index 0. + ListNode* curr = head->next; // Point to the index 1. + + while (curr->next) { + if (curr->val > prev->val && curr->val > curr->next->val || + curr->val < prev->val && curr->val < curr->next->val) { + if (firstMaIndex == -1) // Only assign once. + firstMaIndex = index; + if (prevMaIndex != -1) + minDistance = min(minDistance, index - prevMaIndex); + prevMaIndex = index; + } + prev = curr; + curr = curr->next; + ++index; + } + + if (minDistance == INT_MAX) + return {-1, -1}; + return {minDistance, prevMaIndex - firstMaIndex}; + } +}; diff --git a/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.java b/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.java new file mode 100644 index 00000000000..17c310ef8fb --- /dev/null +++ b/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.java @@ -0,0 +1,28 @@ +class Solution { + public int[] nodesBetweenCriticalPoints(ListNode head) { + int minDistance = Integer.MAX_VALUE; + int firstMaIndex = -1; + int prevMaIndex = -1; + int index = 1; + ListNode prev = head; // Point to the index 0. + ListNode curr = head.next; // Point to the index 1. + + while (curr.next != null) { + if (curr.val > prev.val && curr.val > curr.next.val || + curr.val < prev.val && curr.val < curr.next.val) { + if (firstMaIndex == -1) // Only assign once. + firstMaIndex = index; + if (prevMaIndex != -1) + minDistance = Math.min(minDistance, index - prevMaIndex); + prevMaIndex = index; + } + prev = curr; + curr = curr.next; + ++index; + } + + if (minDistance == Integer.MAX_VALUE) + return new int[] {-1, -1}; + return new int[] {minDistance, prevMaIndex - firstMaIndex}; + } +} diff --git a/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.py b/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.py new file mode 100644 index 00000000000..801cee05d19 --- /dev/null +++ b/solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.py @@ -0,0 +1,24 @@ +class Solution: + def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: + minDistance = math.inf + firstMaIndex = -1 + prevMaIndex = -1 + index = 1 + prev = head # Point to the index 0. + curr = head.next # Point to the index 1. + + while curr.next: + if curr.val > prev.val and curr.val > curr.next.val or \ + curr.val < prev.val and curr.val < curr.next.val: + if firstMaIndex == -1: # Only assign once. + firstMaIndex = index + if prevMaIndex != -1: + minDistance = min(minDistance, index - prevMaIndex) + prevMaIndex = index + prev = curr + curr = curr.next + index += 1 + + if minDistance == math.inf: + return [-1, -1] + return [minDistance, prevMaIndex - firstMaIndex] diff --git a/solutions/2059. Minimum Operations to Convert Number/2059.cpp b/solutions/2059. Minimum Operations to Convert Number/2059.cpp new file mode 100644 index 00000000000..e8e854dd508 --- /dev/null +++ b/solutions/2059. Minimum Operations to Convert Number/2059.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minimumOperations(vector& nums, int start, int goal) { + int ans = 0; + queue q{{start}}; + vector seen(1001); + seen[start] = true; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const int x = q.front(); + q.pop(); + for (const int num : nums) { + for (const int res : {x + num, x - num, x ^ num}) { + if (res == goal) + return ans; + if (res < 0 || res > 1000 || seen[res]) + continue; + seen[res] = true; + q.push(res); + } + } + } + } + + return -1; + } +}; diff --git a/solutions/2059. Minimum Operations to Convert Number/2059.java b/solutions/2059. Minimum Operations to Convert Number/2059.java new file mode 100644 index 00000000000..8f1dc341c52 --- /dev/null +++ b/solutions/2059. Minimum Operations to Convert Number/2059.java @@ -0,0 +1,27 @@ +class Solution { + public int minimumOperations(int[] nums, int start, int goal) { + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(start)); + boolean[] seen = new boolean[1001]; + seen[start] = true; + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + final int x = q.poll(); + for (final int num : nums) { + for (final int res : new int[] {x + num, x - num, x ^ num}) { + if (res == goal) + return ans; + if (res < 0 || res > 1000 || seen[res]) + continue; + seen[res] = true; + q.offer(res); + } + } + } + } + + return -1; + } +} diff --git a/solutions/2059. Minimum Operations to Convert Number/2059.py b/solutions/2059. Minimum Operations to Convert Number/2059.py new file mode 100644 index 00000000000..f6bd26db3c6 --- /dev/null +++ b/solutions/2059. Minimum Operations to Convert Number/2059.py @@ -0,0 +1,20 @@ +class Solution: + def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: + ans = 0 + q = collections.deque([start]) + seen = {start} + + while q: + ans += 1 + for _ in range(len(q)): + x = q.popleft() + for num in nums: + for res in (x + num, x - num, x ^ num): + if res == goal: + return ans + if res < 0 or res > 1000 or res in seen: + continue + seen.add(res) + q.append(res) + + return -1 diff --git a/solutions/206. Reverse Linked List/206-2.cpp b/solutions/206. Reverse Linked List/206-2.cpp new file mode 100644 index 00000000000..7035c6855fd --- /dev/null +++ b/solutions/206. Reverse Linked List/206-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + ListNode* reverseList(ListNode* head) { + ListNode* prev = nullptr; + + while (head) { + ListNode* next = head->next; + head->next = prev; + prev = head; + head = next; + } + + return prev; + } +}; diff --git a/solutions/206. Reverse Linked List/206-2.java b/solutions/206. Reverse Linked List/206-2.java new file mode 100644 index 00000000000..bf5bf4b2038 --- /dev/null +++ b/solutions/206. Reverse Linked List/206-2.java @@ -0,0 +1,14 @@ +class Solution { + public ListNode reverseList(ListNode head) { + ListNode prev = null; + + while (head != null) { + ListNode next = head.next; + head.next = prev; + prev = head; + head = next; + } + + return prev; + } +} diff --git a/solutions/206. Reverse Linked List/206-2.py b/solutions/206. Reverse Linked List/206-2.py new file mode 100644 index 00000000000..dd77eab9723 --- /dev/null +++ b/solutions/206. Reverse Linked List/206-2.py @@ -0,0 +1,12 @@ +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + curr = head + + while curr: + next = curr.next + curr.next = prev + prev = curr + curr = next + + return prev diff --git a/solutions/206. Reverse Linked List/206.cpp b/solutions/206. Reverse Linked List/206.cpp new file mode 100644 index 00000000000..8fc42d847fa --- /dev/null +++ b/solutions/206. Reverse Linked List/206.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + ListNode* reverseList(ListNode* head) { + if (!head || !head->next) + return head; + + ListNode* newHead = reverseList(head->next); + head->next->next = head; + head->next = nullptr; + return newHead; + } +}; diff --git a/solutions/206. Reverse Linked List/206.java b/solutions/206. Reverse Linked List/206.java new file mode 100644 index 00000000000..0ce5128634b --- /dev/null +++ b/solutions/206. Reverse Linked List/206.java @@ -0,0 +1,11 @@ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) + return head; + + ListNode newHead = reverseList(head.next); + head.next.next = head; + head.next = null; + return newHead; + } +} diff --git a/solutions/206. Reverse Linked List/206.py b/solutions/206. Reverse Linked List/206.py new file mode 100644 index 00000000000..2e8dcda36b5 --- /dev/null +++ b/solutions/206. Reverse Linked List/206.py @@ -0,0 +1,9 @@ +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head or not head.next: + return head + + newHead = self.reverseList(head.next) + head.next.next = head + head.next = None + return newHead diff --git a/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.cpp b/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.cpp new file mode 100644 index 00000000000..c0a3c9f24e0 --- /dev/null +++ b/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.cpp @@ -0,0 +1,67 @@ +class Solution { + public: + bool possiblyEquals(string s1, string s2) { + vector>> mem( + s1.length() + 1, vector>(s2.length() + 1)); + return f(s1, s2, 0, 0, 0, mem); + } + + private: + // Returns true if s1[i..n) matches s2[j..n), accounting for the padding + // difference. Here, `paddingDiff` represents the signed padding. A positive + // `paddingDiff` indicates that s1 has an additional number of offset bytes + // compared to s2. + bool f(const string& s1, const string& s2, int i, int j, int paddingDiff, + vector>>& mem) { + if (const auto it = mem[i][j].find(paddingDiff); it != mem[i][j].cend()) + return it->second; + if (i == s1.length() && j == s2.length()) + return paddingDiff == 0; + if (i < s1.length() && isdigit(s1[i])) { + // Add padding on s1. + const int nextLetterIndex = getNextLetterIndex(s1, i); + for (const int num : getNums(s1.substr(i, nextLetterIndex - i))) + if (f(s1, s2, nextLetterIndex, j, paddingDiff + num, mem)) + return true; + } else if (j < s2.length() && isdigit(s2[j])) { + // Add padding on s2. + const int nextLetterIndex = getNextLetterIndex(s2, j); + for (const int num : getNums(s2.substr(j, nextLetterIndex - j))) + if (f(s1, s2, i, nextLetterIndex, paddingDiff - num, mem)) + return true; + } else if (paddingDiff > 0) { + // `s1` has more padding, so j needs to catch up. + if (j < s2.length()) + return f(s1, s2, i, j + 1, paddingDiff - 1, mem); + } else if (paddingDiff < 0) { + // `s2` has more padding, so i needs to catch up. + if (i < s1.length()) + return f(s1, s2, i + 1, j, paddingDiff + 1, mem); + } else { // paddingDiff == 0 + // There's no padding difference, so consume the next letter. + if (i < s1.length() && j < s2.length() && s1[i] == s2[j]) + return f(s1, s2, i + 1, j + 1, 0, mem); + } + return mem[i][j][paddingDiff] = false; + } + + int getNextLetterIndex(const string& s, int i) { + int j = i; + while (i < s.length() && isdigit(s[j])) + ++j; + return j; + } + + vector getNums(const string& s) { + vector nums{stoi(s)}; + if (s.length() == 2) { + nums.push_back(stoi(s.substr(0, 1)) + stoi(s.substr(1, 1))); + } else if (s.length() == 3) { + nums.push_back(stoi(s.substr(0, 1)) + stoi(s.substr(1, 2))); + nums.push_back(stoi(s.substr(0, 2)) + stoi(s.substr(2, 1))); + nums.push_back(stoi(s.substr(0, 1)) + stoi(s.substr(1, 1)) + + stoi(s.substr(2, 1))); + } + return nums; + } +}; diff --git a/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.java b/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.java new file mode 100644 index 00000000000..9a967c12936 --- /dev/null +++ b/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.java @@ -0,0 +1,68 @@ +class Solution { + public boolean possiblyEquals(String s1, String s2) { + Map[][] mem = new Map[s1.length() + 1][s2.length() + 1]; + for (int i = 0; i <= s1.length(); ++i) + for (int j = 0; j <= s2.length(); ++j) + mem[i][j] = new HashMap<>(); + return f(s1, s2, 0, 0, 0, mem); + } + + // Returns true if s1[i..n) matches s2[j..n), accounting for the padding + // difference. Here, `paddingDiff` represents the signed padding. A positive + // `paddingDiff` indicates that s1 has an additional number of offset bytes + // compared to s2. + private boolean f(final String s1, final String s2, int i, int j, int paddingDiff, + Map[][] mem) { + if (mem[i][j].containsKey(paddingDiff)) + return mem[i][j].get(paddingDiff); + if (i == s1.length() && j == s2.length()) + return paddingDiff == 0; + if (i < s1.length() && Character.isDigit(s1.charAt(i))) { + // Add padding on s1. + final int nextLetterIndex = getNextLetterIndex(s1, i); + for (final int num : getNums(s1.substring(i, nextLetterIndex))) + if (f(s1, s2, nextLetterIndex, j, paddingDiff + num, mem)) + return true; + } else if (j < s2.length() && Character.isDigit(s2.charAt(j))) { + // Add padding on s2. + final int nextLetterIndex = getNextLetterIndex(s2, j); + for (final int num : getNums(s2.substring(j, nextLetterIndex))) + if (f(s1, s2, i, nextLetterIndex, paddingDiff - num, mem)) + return true; + } else if (paddingDiff > 0) { + // `s1` has more padding, so j needs to catch up. + if (j < s2.length()) + return f(s1, s2, i, j + 1, paddingDiff - 1, mem); + } else if (paddingDiff < 0) { + // `s2` has more padding, so i needs to catch up. + if (i < s1.length()) + return f(s1, s2, i + 1, j, paddingDiff + 1, mem); + } else { // paddingDiff == 0 + // There's no padding difference, so consume the next letter. + if (i < s1.length() && j < s2.length() && s1.charAt(i) == s2.charAt(j)) + return f(s1, s2, i + 1, j + 1, 0, mem); + } + mem[i][j].put(paddingDiff, false); + return false; + } + + private int getNextLetterIndex(final String s, int i) { + int j = i; + while (j < s.length() && Character.isDigit(s.charAt(j))) + ++j; + return j; + } + + private List getNums(final String s) { + List nums = new ArrayList<>(Arrays.asList(Integer.parseInt(s))); + if (s.length() == 2) { + nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2))); + } else if (s.length() == 3) { + nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 3))); + nums.add(Integer.parseInt(s.substring(0, 2)) + Integer.parseInt(s.substring(2, 3))); + nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2)) + + Integer.parseInt(s.substring(2, 3))); + } + return nums; + } +} diff --git a/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.py b/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.py new file mode 100644 index 00000000000..3bb582525d5 --- /dev/null +++ b/solutions/2060. Check if an Original String Exists Given Two Encoded Strings/2060.py @@ -0,0 +1,51 @@ +class Solution: + def possiblyEquals(self, s1: str, s2: str) -> bool: + def getNums(s: str) -> Set[int]: + nums = {int(s)} + for i in range(1, len(s)): + nums |= {x + y for x in getNums(s[:i]) for y in getNums(s[i:])} + return nums + + def getNextLetterIndex(s: str, i: int) -> int: + j = i + while j < len(s) and s[j].isdigit(): + j += 1 + return j + + @functools.lru_cache(None) + def dp(i: int, j: int, paddingDiff: int) -> bool: + """ + Returns True if s1[i..n) matches s2[j..n), accounting for the padding + difference. Here, `paddingDiff` represents the signed padding. A positive + `paddingDiff` indicates that s1 has an additional number of offset bytes + compared to s2. + """ + if i == len(s1) and j == len(s2): + return paddingDiff == 0 + # Add padding on s1. + if i < len(s1) and s1[i].isdigit(): + nextLetterIndex = getNextLetterIndex(s1, i) + for num in getNums(s1[i:nextLetterIndex]): + if dp(nextLetterIndex, j, paddingDiff + num): + return True + # Add padding on s2. + elif j < len(s2) and s2[j].isdigit(): + nextLetterIndex = getNextLetterIndex(s2, j) + for num in getNums(s2[j:nextLetterIndex]): + if dp(i, nextLetterIndex, paddingDiff - num): + return True + # `s1` has more padding, so j needs to catch up. + elif paddingDiff > 0: + if j < len(s2): + return dp(i, j + 1, paddingDiff - 1) + # `s2` has more padding, so i needs to catch up. + elif paddingDiff < 0: + if i < len(s1): + return dp(i + 1, j, paddingDiff + 1) + # There's no padding difference, so consume the next letter. + else: # paddingDiff == 0 + if i < len(s1) and j < len(s2) and s1[i] == s2[j]: + return dp(i + 1, j + 1, 0) + return False + + return dp(0, 0, 0) diff --git a/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.cpp b/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.cpp new file mode 100644 index 00000000000..c7f0a324ac3 --- /dev/null +++ b/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int numberOfCleanRooms(vector>& room) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = room.size(); + const int n = room[0].size(); + int ans = 1; + int i = 0; + int j = 0; + int state = 0; // 0 := right, 1 := down, 2 := left, 3 := up + vector> seen(m, vector(n)); // seen[i][j] := bitmask + seen[i][j] |= 1 << state; + room[i][j] = 2; // 2 := cleaned + + while (true) { + const int x = i + dirs[state][0]; + const int y = j + dirs[state][1]; + if (x < 0 || x == m || y < 0 || y == n || room[x][y] == 1) { + // Turn 90 degrees clockwise. + state = (state + 1) % 4; + } else { + // Walk to (x, y). + if (room[x][y] == 0) { + ++ans; + room[x][y] = 2; + } + i = x; + j = y; + } + if (seen[i][j] >> state & 1) + return ans; + seen[i][j] |= (1 << state); + } + } +}; diff --git a/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.java b/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.java new file mode 100644 index 00000000000..c17b901b286 --- /dev/null +++ b/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.java @@ -0,0 +1,34 @@ +class Solution { + public int numberOfCleanRooms(int[][] room) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = room.length; + final int n = room[0].length; + int ans = 1; + int i = 0; + int j = 0; + int state = 0; // 0 := right, 1 := down, 2 := left, 3 := up + int[][] seen = new int[m][n]; // seen[i][j] := bitmask + seen[i][j] |= 1 << state; + room[i][j] = 2; // 2 := cleaned + + while (true) { + final int x = i + dirs[state]; + final int y = j + dirs[state + 1]; + if (x < 0 || x == m || y < 0 || y == n || room[x][y] == 1) { + // Turn 90 degrees clockwise. + state = (state + 1) % 4; + } else { + // Walk to (x, y). + if (room[x][y] == 0) { + ++ans; + room[x][y] = 2; + } + i = x; + j = y; + } + if ((seen[i][j] >> state & 1) == 1) + return ans; + seen[i][j] |= (1 << state); + } + } +} diff --git a/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.py b/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.py new file mode 100644 index 00000000000..de18e66b76a --- /dev/null +++ b/solutions/2061. Number of Spaces Cleaning Robot Cleaned/2061.py @@ -0,0 +1,28 @@ +class Solution: + def numberOfCleanRooms(self, room: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(room) + n = len(room[0]) + ans = 1 + i = 0 + j = 0 + state = 0 # 0 := right, 1 := down, 2 := left, 3 := up + seen = {(i, j, state)} + room[i][j] = 2 # 2 := cleaned + + while True: + x = i + dirs[state] + y = j + dirs[state + 1] + if x < 0 or x == m or y < 0 or y == n or room[x][y] == 1: + # Turn 90 degrees clockwise. + state = (state + 1) % 4 + else: + # Walk to (x, y). + if room[x][y] == 0: + ans += 1 + room[x][y] = 2 + i = x + j = y + if (x, y, state) in seen: + return ans + seen.add((x, y, state)) diff --git a/solutions/2062. Count Vowel Substrings of a String/2062.cpp b/solutions/2062. Count Vowel Substrings of a String/2062.cpp new file mode 100644 index 00000000000..4ae1d032535 --- /dev/null +++ b/solutions/2062. Count Vowel Substrings of a String/2062.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int countVowelSubstrings(string word) { + return countVowelSubstringsAtMost(word, 5) - + countVowelSubstringsAtMost(word, 4); + } + + private: + int countVowelSubstringsAtMost(const string& s, int goal) { + int ans = 0; + int k = goal; + vector count(26); + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (!isVowel(s[r])) { // Fresh start. + l = r + 1; + k = goal; + count = vector(26); + continue; + } + if (++count[s[r] - 'a'] == 1) + --k; + while (k == -1) + if (--count[s[l++] - 'a'] == 0) + ++k; + ans += r - l + 1; // s[l..r], s[l + 1..r], ..., s[r] + } + + return ans; + } + + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiou"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/2062. Count Vowel Substrings of a String/2062.java b/solutions/2062. Count Vowel Substrings of a String/2062.java new file mode 100644 index 00000000000..2093e0b7e92 --- /dev/null +++ b/solutions/2062. Count Vowel Substrings of a String/2062.java @@ -0,0 +1,32 @@ +class Solution { + public int countVowelSubstrings(String word) { + return countVowelSubstringsAtMost(word, 5) - countVowelSubstringsAtMost(word, 4); + } + + private int countVowelSubstringsAtMost(final String s, int goal) { + int ans = 0; + int k = goal; + int[] count = new int[26]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (!isVowel(s.charAt(r))) { // Fresh start. + l = r + 1; + k = goal; + count = new int[26]; + continue; + } + if (++count[s.charAt(r) - 'a'] == 1) + --k; + while (k == -1) + if (--count[s.charAt(l++) - 'a'] == 0) + ++k; + ans += r - l + 1; // s[l..r], s[l + 1..r], ..., s[r] + } + + return ans; + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(c) != -1; + } +} diff --git a/solutions/2062. Count Vowel Substrings of a String/2062.py b/solutions/2062. Count Vowel Substrings of a String/2062.py new file mode 100644 index 00000000000..c33aceddd53 --- /dev/null +++ b/solutions/2062. Count Vowel Substrings of a String/2062.py @@ -0,0 +1,29 @@ +class Solution: + def countVowelSubstrings(self, word: str) -> int: + kVowels = 'aeiou' + + def countVowelSubstringsAtMost(goal: int) -> int: + ans = 0 + k = goal + count = collections.Counter() + + l = 0 + for r, c in enumerate(word): + if c not in kVowels: # Fresh start. + l = r + 1 + k = goal + count = collections.Counter() + continue + count[c] += 1 + if count[c] == 1: + k -= 1 + while k == -1: + count[word[l]] -= 1 + if count[word[l]] == 0: + k += 1 + l += 1 + ans += r - l + 1 # s[l..r], s[l + 1..r], ..., s[r] + + return ans + + return countVowelSubstringsAtMost(5) - countVowelSubstringsAtMost(4) diff --git a/solutions/2063. Vowels of All Substrings/2063-2.cpp b/solutions/2063. Vowels of All Substrings/2063-2.cpp new file mode 100644 index 00000000000..b86167e74b6 --- /dev/null +++ b/solutions/2063. Vowels of All Substrings/2063-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long long countVowels(string word) { + long ans = 0; + + for (int i = 0; i < word.length(); ++i) + if (isVowel(word[i])) + ans += (i + 1) * (word.length() - i); + + return ans; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiou"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/2063. Vowels of All Substrings/2063-2.java b/solutions/2063. Vowels of All Substrings/2063-2.java new file mode 100644 index 00000000000..756b6c75ec0 --- /dev/null +++ b/solutions/2063. Vowels of All Substrings/2063-2.java @@ -0,0 +1,15 @@ +class Solution { + public long countVowels(String word) { + long ans = 0; + + for (int i = 0; i < word.length(); ++i) + if (isVowel(word.charAt(i))) + ans += (i + 1) * (long) (word.length() - i); + + return ans; + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(c) != -1; + } +} diff --git a/solutions/2063. Vowels of All Substrings/2063-2.py b/solutions/2063. Vowels of All Substrings/2063-2.py new file mode 100644 index 00000000000..c5045143c3f --- /dev/null +++ b/solutions/2063. Vowels of All Substrings/2063-2.py @@ -0,0 +1,5 @@ +class Solution: + def countVowels(self, word: str) -> int: + return sum((i + 1) * (len(word) - i) + for i, c in enumerate(word) + if c in 'aeiou') diff --git a/solutions/2063. Vowels of All Substrings/2063.cpp b/solutions/2063. Vowels of All Substrings/2063.cpp new file mode 100644 index 00000000000..433838d09ad --- /dev/null +++ b/solutions/2063. Vowels of All Substrings/2063.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + long long countVowels(string word) { + // dp[i] := the sum of the number of vowels of word[0..i), ..., + // word[i - 1..i) + vector dp(word.length() + 1); + + for (int i = 1; i <= word.length(); ++i) { + dp[i] = dp[i - 1]; + if (isVowel(word[i - 1])) + dp[i] += i; + } + + return accumulate(dp.begin(), dp.end(), 0L); + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiou"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/2063. Vowels of All Substrings/2063.java b/solutions/2063. Vowels of All Substrings/2063.java new file mode 100644 index 00000000000..cdae4a6c1ef --- /dev/null +++ b/solutions/2063. Vowels of All Substrings/2063.java @@ -0,0 +1,19 @@ +class Solution { + public long countVowels(String word) { + // dp[i] := the sum of the number of vowels of word[0..i), ..., + // word[i - 1..i) + long[] dp = new long[word.length() + 1]; + + for (int i = 1; i <= word.length(); ++i) { + dp[i] = dp[i - 1]; + if (isVowel(word.charAt(i - 1))) + dp[i] += i; + } + + return Arrays.stream(dp).sum(); + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(c) != -1; + } +} diff --git a/solutions/2063. Vowels of All Substrings/2063.py b/solutions/2063. Vowels of All Substrings/2063.py new file mode 100644 index 00000000000..32faafacf55 --- /dev/null +++ b/solutions/2063. Vowels of All Substrings/2063.py @@ -0,0 +1,12 @@ +class Solution: + def countVowels(self, word: str) -> int: + # dp[i] := the sum of the number of vowels of word[0..i), ..., + # word[i - 1..i) + dp = [0] * (len(word) + 1) + + for i, c in enumerate(word): + dp[i + 1] = dp[i] + if c in 'aeiou': + dp[i + 1] += i + 1 + + return sum(dp) diff --git a/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.cpp b/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.cpp new file mode 100644 index 00000000000..d15a63a84d4 --- /dev/null +++ b/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minimizedMaximum(int n, vector& quantities) { + int l = 1; + int r = ranges::max(quantities); + + while (l < r) { + const int m = (l + r) / 2; + if (numStores(quantities, m) <= n) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int numStores(const vector& quantities, int m) { + // ceil(q / m) + return accumulate( + quantities.begin(), quantities.end(), 0, + [&](int subtotal, int q) { return subtotal + (q - 1) / m + 1; }); + } +}; diff --git a/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.java b/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.java new file mode 100644 index 00000000000..fa202b6a020 --- /dev/null +++ b/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.java @@ -0,0 +1,21 @@ +class Solution { + public int minimizedMaximum(int n, int[] quantities) { + int l = 1; + int r = Arrays.stream(quantities).max().getAsInt(); + + while (l < r) { + final int m = (l + r) / 2; + if (numStores(quantities, m) <= n) + r = m; + else + l = m + 1; + } + + return l; + } + + private int numStores(int[] quantities, int m) { + // ceil(q / m) + return Arrays.stream(quantities).reduce(0, (subtotal, q) -> subtotal + (q - 1) / m + 1); + } +} diff --git a/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.py b/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.py new file mode 100644 index 00000000000..dbd392d8a4e --- /dev/null +++ b/solutions/2064. Minimized Maximum of Products Distributed to Any Store/2064.py @@ -0,0 +1,16 @@ +class Solution: + def minimizedMaximum(self, n: int, quantities: List[int]) -> int: + l = 1 + r = max(quantities) + + def numStores(m: int) -> int: + return sum((q - 1) // m + 1 for q in quantities) + + while l < r: + m = (l + r) // 2 + if numStores(m) <= n: + r = m + else: + l = m + 1 + + return l diff --git a/solutions/2065. Maximum Path Quality of a Graph/2065-2.py b/solutions/2065. Maximum Path Quality of a Graph/2065-2.py new file mode 100644 index 00000000000..094089d03ef --- /dev/null +++ b/solutions/2065. Maximum Path Quality of a Graph/2065-2.py @@ -0,0 +1,21 @@ +class Solution: + def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: + ans = 0 + graph = [[] for _ in range(len(values))] + # (node, quality, remainingTime, seen) + q = collections.deque([(0, values[0], maxTime, {0})]) + + for u, v, time in edges: + graph[u].append((v, time)) + graph[v].append((u, time)) + + while q: + u, quality, remainingTime, seen = q.popleft() + if u == 0: + ans = max(ans, quality) + for v, time in graph[u]: + if time <= remainingTime: + q.append( + (v, quality + values[v] * (v not in seen), remainingTime - time, seen | set([v]))) + + return ans diff --git a/solutions/2065. Maximum Path Quality of a Graph/2065.cpp b/solutions/2065. Maximum Path Quality of a Graph/2065.cpp new file mode 100644 index 00000000000..c9d727e1bfa --- /dev/null +++ b/solutions/2065. Maximum Path Quality of a Graph/2065.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int maximalPathQuality(vector& values, vector>& edges, + int maxTime) { + const int n = values.size(); + int ans = 0; + vector>> graph(n); + vector seen(n); + seen[0] = 1; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int time = edge[2]; + graph[u].emplace_back(v, time); + graph[v].emplace_back(u, time); + } + + dfs(graph, values, 0, values[0], maxTime, seen, ans); + return ans; + } + + private: + void dfs(const vector>>& graph, + const vector& values, int u, int quality, int remainingTime, + vector& seen, int& ans) { + if (u == 0) + ans = max(ans, quality); + for (const auto& [v, time] : graph[u]) { + if (time > remainingTime) + continue; + const int newQuality = quality + values[v] * (seen[v] == 0); + ++seen[v]; + dfs(graph, values, v, newQuality, remainingTime - time, seen, ans); + --seen[v]; + } + } +}; diff --git a/solutions/2065. Maximum Path Quality of a Graph/2065.java b/solutions/2065. Maximum Path Quality of a Graph/2065.java new file mode 100644 index 00000000000..9af77cf4419 --- /dev/null +++ b/solutions/2065. Maximum Path Quality of a Graph/2065.java @@ -0,0 +1,40 @@ +class Solution { + public int maximalPathQuality(int[] values, int[][] edges, int maxTime) { + final int n = values.length; + List>[] graph = new List[n]; + int[] seen = new int[n]; + seen[0] = 1; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int time = edge[2]; + graph[u].add(new Pair<>(v, time)); + graph[v].add(new Pair<>(u, time)); + } + + dfs(graph, values, 0, values[0], maxTime, seen); + return ans; + } + + private int ans = 0; + + private void dfs(List>[] graph, int[] values, int u, int quality, + int remainingTime, int[] seen) { + if (u == 0) + ans = Math.max(ans, quality); + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int time = pair.getValue(); + if (time > remainingTime) + continue; + final int newQuality = quality + values[v] * (seen[v] == 0 ? 1 : 0); + ++seen[v]; + dfs(graph, values, v, newQuality, remainingTime - time, seen); + --seen[v]; + } + } +} diff --git a/solutions/2065. Maximum Path Quality of a Graph/2065.py b/solutions/2065. Maximum Path Quality of a Graph/2065.py new file mode 100644 index 00000000000..b590fed3052 --- /dev/null +++ b/solutions/2065. Maximum Path Quality of a Graph/2065.py @@ -0,0 +1,26 @@ +class Solution: + def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: + n = len(values) + ans = 0 + graph = [[] for _ in range(n)] + seen = [0] * n + seen[0] = 1 + + for u, v, time in edges: + graph[u].append((v, time)) + graph[v].append((u, time)) + + def dfs(u: int, quality: int, remainingTime: int): + nonlocal ans + if u == 0: + ans = max(ans, quality) + for v, time in graph[u]: + if time > remainingTime: + continue + newQuality = quality + values[v] * (seen[v] == 0) + seen[v] += 1 + dfs(v, newQuality, remainingTime - time) + seen[v] -= 1 + + dfs(0, values[0], maxTime) + return ans diff --git a/solutions/2066. Account Balance/2066.sql b/solutions/2066. Account Balance/2066.sql new file mode 100644 index 00000000000..5647daca754 --- /dev/null +++ b/solutions/2066. Account Balance/2066.sql @@ -0,0 +1,9 @@ +SELECT + account_id, + day, + SUM(IF(type = 'Deposit', amount, -amount)) OVER( + PARTITION BY account_id + ORDER BY day + ) AS balance +FROM Transactions +ORDER BY 1, 2; diff --git a/solutions/2067. Number of Equal Count Substrings/2067.cpp b/solutions/2067. Number of Equal Count Substrings/2067.cpp new file mode 100644 index 00000000000..d6ce878fbd3 --- /dev/null +++ b/solutions/2067. Number of Equal Count Substrings/2067.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int equalCountSubstrings(string s, int count) { + const int maxUnique = unordered_set(s.begin(), s.end()).size(); + int ans = 0; + + for (int unique = 1; unique <= maxUnique; ++unique) { + const int windowSize = unique * count; + vector lettersCount(26); + int uniqueCount = 0; + for (int i = 0; i < s.length(); ++i) { + if (++lettersCount[s[i] - 'a'] == count) + ++uniqueCount; + if (i >= windowSize && + --lettersCount[s[i - windowSize] - 'a'] == count - 1) + --uniqueCount; + ans += uniqueCount == unique; + } + } + + return ans; + } +}; diff --git a/solutions/2067. Number of Equal Count Substrings/2067.java b/solutions/2067. Number of Equal Count Substrings/2067.java new file mode 100644 index 00000000000..b8f7dfda3c6 --- /dev/null +++ b/solutions/2067. Number of Equal Count Substrings/2067.java @@ -0,0 +1,21 @@ +class Solution { + public int equalCountSubstrings(String s, int count) { + final int maxUnique = s.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()).size(); + int ans = 0; + + for (int unique = 1; unique <= maxUnique; ++unique) { + final int windowSize = unique * count; + int[] lettersCount = new int[26]; + int uniqueCount = 0; + for (int i = 0; i < s.length(); ++i) { + if (++lettersCount[s.charAt(i) - 'a'] == count) + ++uniqueCount; + if (i >= windowSize && --lettersCount[s.charAt(i - windowSize) - 'a'] == count - 1) + --uniqueCount; + ans += uniqueCount == unique ? 1 : 0; + } + } + + return ans; + } +} diff --git a/solutions/2067. Number of Equal Count Substrings/2067.py b/solutions/2067. Number of Equal Count Substrings/2067.py new file mode 100644 index 00000000000..3ea83bcf4ab --- /dev/null +++ b/solutions/2067. Number of Equal Count Substrings/2067.py @@ -0,0 +1,20 @@ +class Solution: + def equalCountSubstrings(self, s: str, count: int) -> int: + maxUnique = len(set(s)) + ans = 0 + + for unique in range(1, maxUnique + 1): + windowSize = unique * count + lettersCount = collections.Counter() + uniqueCount = 0 + for i, c in enumerate(s): + lettersCount[c] += 1 + if lettersCount[c] == count: + uniqueCount += 1 + if i >= windowSize: + lettersCount[s[i - windowSize]] -= 1 + if lettersCount[s[i - windowSize]] == count - 1: + uniqueCount -= 1 + ans += uniqueCount == unique + + return ans diff --git a/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.cpp b/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.cpp new file mode 100644 index 00000000000..9881c75cc71 --- /dev/null +++ b/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + bool checkAlmostEquivalent(string word1, string word2) { + vector count(26); + + for (const char c : word1) + ++count[c - 'a']; + + for (const char c : word2) + --count[c - 'a']; + + return ranges::all_of(count, [](int freq) { return abs(freq) <= 3; }); + } +}; diff --git a/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.java b/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.java new file mode 100644 index 00000000000..c95095e54f2 --- /dev/null +++ b/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.java @@ -0,0 +1,13 @@ +class Solution { + public boolean checkAlmostEquivalent(String word1, String word2) { + int[] count = new int[26]; + + for (final char c : word1.toCharArray()) + ++count[c - 'a']; + + for (final char c : word2.toCharArray()) + --count[c - 'a']; + + return Arrays.stream(count).allMatch(freq -> Math.abs(freq) <= 3); + } +} diff --git a/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.py b/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.py new file mode 100644 index 00000000000..f4a8eae2a8b --- /dev/null +++ b/solutions/2068. Check Whether Two Strings are Almost Equivalent/2068.py @@ -0,0 +1,5 @@ +class Solution: + def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: + count = collections.Counter(word1) + count.subtract(collections.Counter(word2)) + return all(abs(freq) <= 3 for freq in count.values()) diff --git a/solutions/2069. Walking Robot Simulation II/2069.cpp b/solutions/2069. Walking Robot Simulation II/2069.cpp new file mode 100644 index 00000000000..ed94fcf9ecf --- /dev/null +++ b/solutions/2069. Walking Robot Simulation II/2069.cpp @@ -0,0 +1,32 @@ +class Robot { + public: + Robot(int width, int height) { + pos.push_back({{0, 0}, "South"}); + for (int i = 1; i < width; ++i) + pos.push_back({{i, 0}, "East"}); + for (int j = 1; j < height; ++j) + pos.push_back({{width - 1, j}, "North"}); + for (int i = width - 2; i >= 0; --i) + pos.push_back({{i, height - 1}, "West"}); + for (int j = height - 2; j > 0; --j) + pos.push_back({{0, j}, "South"}); + } + + void step(int num) { + isOrigin = false; + i = (i + num) % pos.size(); + } + + vector getPos() { + return pos[i].first; + } + + string getDir() { + return isOrigin ? "East" : pos[i].second; + } + + private: + bool isOrigin = true; + int i = 0; + vector, string>> pos; +}; diff --git a/solutions/2069. Walking Robot Simulation II/2069.java b/solutions/2069. Walking Robot Simulation II/2069.java new file mode 100644 index 00000000000..c933a21a645 --- /dev/null +++ b/solutions/2069. Walking Robot Simulation II/2069.java @@ -0,0 +1,30 @@ +class Robot { + public Robot(int width, int height) { + pos.add(new Pair<>(new int[] {0, 0}, "South")); + for (int i = 1; i < width; ++i) + pos.add(new Pair<>(new int[] {i, 0}, "East")); + for (int j = 1; j < height; ++j) + pos.add(new Pair<>(new int[] {width - 1, j}, "North")); + for (int i = width - 2; i >= 0; --i) + pos.add(new Pair<>(new int[] {i, height - 1}, "West")); + for (int j = height - 2; j > 0; --j) + pos.add(new Pair<>(new int[] {0, j}, "South")); + } + + public void step(int num) { + isOrigin = false; + i = (i + num) % pos.size(); + } + + public int[] getPos() { + return pos.get(i).getKey(); + } + + public String getDir() { + return isOrigin ? "East" : pos.get(i).getValue(); + } + + private boolean isOrigin = true; + private int i = 0; + private List> pos = new ArrayList<>(); +} diff --git a/solutions/2069. Walking Robot Simulation II/2069.py b/solutions/2069. Walking Robot Simulation II/2069.py new file mode 100644 index 00000000000..53bbb225752 --- /dev/null +++ b/solutions/2069. Walking Robot Simulation II/2069.py @@ -0,0 +1,19 @@ +class Robot: + def __init__(self, width: int, height: int): + self.isOrigin = True + self.i = 0 + self.pos = [((0, 0), 'South')] + \ + [((i, 0), 'East') for i in range(1, width)] + \ + [((width - 1, j), 'North') for j in range(1, height)] + \ + [((i, height - 1), 'West') for i in range(width - 2, -1, -1)] +\ + [((0, j), 'South') for j in range(height - 2, 0, -1)] + + def step(self, num: int) -> None: + self.isOrigin = False + self.i = (self.i + num) % len(self.pos) + + def getPos(self) -> List[int]: + return self.pos[self.i][0] + + def getDir(self) -> str: + return 'East' if self.isOrigin else self.pos[self.i][1] diff --git a/solutions/207. Course Schedule/207.cpp b/solutions/207. Course Schedule/207.cpp new file mode 100644 index 00000000000..0a2e52243fa --- /dev/null +++ b/solutions/207. Course Schedule/207.cpp @@ -0,0 +1,38 @@ +enum class State { kInit, kVisiting, kVisited }; + +class Solution { + public: + bool canFinish(int numCourses, vector>& prerequisites) { + vector> graph(numCourses); + vector states(numCourses); + + for (const vector& prerequisite : prerequisites) { + const int u = prerequisite[1]; + const int v = prerequisite[0]; + graph[u].push_back(v); + } + + for (int i = 0; i < numCourses; ++i) + if (hasCycle(graph, i, states)) + return false; + + return true; + } + + private: + bool hasCycle(const vector>& graph, int u, + vector& states) { + if (states[u] == State::kVisiting) + return true; + if (states[u] == State::kVisited) + return false; + + states[u] = State::kVisiting; + for (const int v : graph[u]) + if (hasCycle(graph, v, states)) + return true; + states[u] = State::kVisited; + + return false; + } +}; diff --git a/solutions/207. Course Schedule/207.java b/solutions/207. Course Schedule/207.java new file mode 100644 index 00000000000..92dc03c5917 --- /dev/null +++ b/solutions/207. Course Schedule/207.java @@ -0,0 +1,38 @@ +enum State { kInit, kVisiting, kVisited } + +class Solution { + public boolean canFinish(int numCourses, int[][] prerequisites) { + List[] graph = new List[numCourses]; + State[] states = new State[numCourses]; + + for (int i = 0; i < numCourses; ++i) + graph[i] = new ArrayList<>(); + + for (int[] prerequisite : prerequisites) { + final int u = prerequisite[1]; + final int v = prerequisite[0]; + graph[u].add(v); + } + + for (int i = 0; i < numCourses; ++i) + if (hasCycle(graph, i, states)) + return false; + + return true; + } + + private boolean hasCycle(List[] graph, int u, State[] states) { + if (states[u] == State.kVisiting) + return true; + if (states[u] == State.kVisited) + return false; + + states[u] = State.kVisiting; + for (final int v : graph[u]) + if (hasCycle(graph, v, states)) + return true; + states[u] = State.kVisited; + + return false; + } +} diff --git a/solutions/207. Course Schedule/207.py b/solutions/207. Course Schedule/207.py new file mode 100644 index 00000000000..6291b740730 --- /dev/null +++ b/solutions/207. Course Schedule/207.py @@ -0,0 +1,31 @@ +from enum import Enum + + +class State(Enum): + kInit = 0 + kVisiting = 1 + kVisited = 2 + + +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: + graph = [[] for _ in range(numCourses)] + states = [State.kInit] * numCourses + + for v, u in prerequisites: + graph[u].append(v) + + def hasCycle(u: int) -> bool: + if states[u] == State.kVisiting: + return True + if states[u] == State.kVisited: + return False + + states[u] = State.kVisiting + if any(hasCycle(v) for v in graph[u]): + return True + states[u] = State.kVisited + + return False + + return not any(hasCycle(i) for i in range(numCourses)) diff --git a/solutions/2070. Most Beautiful Item for Each Query/2070.cpp b/solutions/2070. Most Beautiful Item for Each Query/2070.cpp new file mode 100644 index 00000000000..3f3590d84a8 --- /dev/null +++ b/solutions/2070. Most Beautiful Item for Each Query/2070.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector maximumBeauty(vector>& items, vector& queries) { + vector ans; + vector prices; + vector maxBeautySoFar(items.size() + 1); + + ranges::sort(items); + + for (const vector& item : items) + prices.push_back(item[0]); + + for (int i = 0; i < items.size(); ++i) + maxBeautySoFar[i + 1] = max(maxBeautySoFar[i], items[i][1]); + + for (const int query : queries) { + const int i = ranges::upper_bound(prices, query) - prices.begin(); + ans.push_back(maxBeautySoFar[i]); + } + + return ans; + } +}; diff --git a/solutions/2070. Most Beautiful Item for Each Query/2070.java b/solutions/2070. Most Beautiful Item for Each Query/2070.java new file mode 100644 index 00000000000..a251cee47bb --- /dev/null +++ b/solutions/2070. Most Beautiful Item for Each Query/2070.java @@ -0,0 +1,32 @@ +class Solution { + public int[] maximumBeauty(int[][] items, int[] queries) { + int[] ans = new int[queries.length]; + int[] prices = new int[items.length]; + int[] maxBeautySoFar = new int[items.length + 1]; + + Arrays.sort(items, (a, b) -> a[0] - b[0]); + + for (int i = 0; i < items.length; ++i) + maxBeautySoFar[i + 1] = Math.max(maxBeautySoFar[i], items[i][1]); + + for (int i = 0; i < queries.length; ++i) { + final int index = firstGreater(items, queries[i]); + ans[i] = maxBeautySoFar[index]; + } + + return ans; + } + + private int firstGreater(int[][] items, int q) { + int l = 0; + int r = items.length; + while (l < r) { + final int m = (l + r) / 2; + if (items[m][0] > q) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/2070. Most Beautiful Item for Each Query/2070.py b/solutions/2070. Most Beautiful Item for Each Query/2070.py new file mode 100644 index 00000000000..801757de815 --- /dev/null +++ b/solutions/2070. Most Beautiful Item for Each Query/2070.py @@ -0,0 +1,9 @@ +class Solution: + def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]: + prices, beauties = zip(*sorted(items)) + maxBeautySoFar = [0] * (len(beauties) + 1) + + for i, beauty in enumerate(beauties): + maxBeautySoFar[i + 1] = max(maxBeautySoFar[i], beauty) + + return [maxBeautySoFar[bisect_right(prices, query)] for query in queries] diff --git a/solutions/2071. Maximum Number of Tasks You Can Assign/2071.cpp b/solutions/2071. Maximum Number of Tasks You Can Assign/2071.cpp new file mode 100644 index 00000000000..9053ebd8656 --- /dev/null +++ b/solutions/2071. Maximum Number of Tasks You Can Assign/2071.cpp @@ -0,0 +1,56 @@ +class Solution { + public: + int maxTaskAssign(vector& tasks, vector& workers, int pills, + int strength) { + int ans = 0; + int l = 0; + int r = min(tasks.size(), workers.size()); + + ranges::sort(tasks); + ranges::sort(workers); + + // Returns true if we can finish k tasks. + auto canComplete = [&](int k, int pillsLeft) { + // k strongest workers + map sortedWorkers; + for (int i = workers.size() - k; i < workers.size(); ++i) + ++sortedWorkers[workers[i]]; + + // Out of the k smallest tasks, start from the biggest one. + for (int i = k - 1; i >= 0; --i) { + // Find the first worker that has strength >= tasks[i]. + auto it = sortedWorkers.lower_bound(tasks[i]); + if (it != sortedWorkers.end()) { + if (--(it->second) == 0) + sortedWorkers.erase(it); + } else if (pillsLeft > 0) { + // Find the first worker that has strength >= tasks[i] - strength. + it = sortedWorkers.lower_bound(tasks[i] - strength); + if (it != sortedWorkers.end()) { + if (--(it->second) == 0) + sortedWorkers.erase(it); + --pillsLeft; + } else { + return false; + } + } else { + return false; + } + } + + return true; + }; + + while (l <= r) { + const int m = (l + r) / 2; + if (canComplete(m, pills)) { + ans = m; + l = m + 1; + } else { + r = m - 1; + } + } + + return ans; + } +}; diff --git a/solutions/2071. Maximum Number of Tasks You Can Assign/2071.java b/solutions/2071. Maximum Number of Tasks You Can Assign/2071.java new file mode 100644 index 00000000000..3e08d8301f3 --- /dev/null +++ b/solutions/2071. Maximum Number of Tasks You Can Assign/2071.java @@ -0,0 +1,59 @@ +class Solution { + public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) { + int ans = 0; + int l = 0; + int r = Math.min(tasks.length, workers.length); + + Arrays.sort(tasks); + Arrays.sort(workers); + + while (l <= r) { + final int m = (l + r) / 2; + if (canComplete(tasks, workers, pills, strength, m)) { + ans = m; + l = m + 1; + + } else { + r = m - 1; + } + } + + return ans; + } + + // Returns true if we can finish k tasks. + private boolean canComplete(int[] tasks, int[] workers, int pillsLeft, int strength, int k) { + // k strongest workers + TreeMap sortedWorkers = new TreeMap<>(); + for (int i = workers.length - k; i < workers.length; ++i) + sortedWorkers.merge(workers[i], 1, Integer::sum); + + // Out of the k smallest tasks, start from the biggest one. + for (int i = k - 1; i >= 0; --i) { + // Find the first worker that has strength >= tasks[i]. + Integer lo = sortedWorkers.ceilingKey(tasks[i]); + if (lo != null) { + sortedWorkers.merge(lo, -1, Integer::sum); + if (sortedWorkers.get(lo) == 0) { + sortedWorkers.remove(lo); + } + } else if (pillsLeft > 0) { + // Find the first worker that has strength >= tasks[i] - strength. + lo = sortedWorkers.ceilingKey(tasks[i] - strength); + if (lo != null) { + sortedWorkers.merge(lo, -1, Integer::sum); + if (sortedWorkers.get(lo) == 0) { + sortedWorkers.remove(lo); + } + --pillsLeft; + } else { + return false; + } + } else { + return false; + } + } + + return true; + } +} diff --git a/solutions/2071. Maximum Number of Tasks You Can Assign/2071.py b/solutions/2071. Maximum Number of Tasks You Can Assign/2071.py new file mode 100644 index 00000000000..34e774b7616 --- /dev/null +++ b/solutions/2071. Maximum Number of Tasks You Can Assign/2071.py @@ -0,0 +1,45 @@ +from sortedcontainers import SortedList + + +class Solution: + def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int: + tasks.sort() + workers.sort() + + def canComplete(k: int, pillsLeft: int) -> bool: + """Returns True if we can finish k tasks.""" + # k strongest workers + sortedWorkers = SortedList(workers[-k:]) + + # Out of the k smallest tasks, start from the biggest one. + for i in reversed(range(k)): + # Find the first worker that has strength >= tasks[i]. + index = sortedWorkers.bisect_left(tasks[i]) + if index < len(sortedWorkers): + sortedWorkers.pop(index) + elif pillsLeft > 0: + # Find the first worker that has strength >= tasks[i] - strength. + index = sortedWorkers.bisect_left(tasks[i] - strength) + if index < len(sortedWorkers): + sortedWorkers.pop(index) + pillsLeft -= 1 + else: + return False + else: + return False + + return True + + ans = 0 + l = 0 + r = min(len(tasks), len(workers)) + + while l <= r: + m = (l + r) // 2 + if canComplete(m, pills): + ans = m + l = m + 1 + else: + r = m - 1 + + return ans diff --git a/solutions/2072. The Winner University/2072.sql b/solutions/2072. The Winner University/2072.sql new file mode 100644 index 00000000000..dfe16e2caee --- /dev/null +++ b/solutions/2072. The Winner University/2072.sql @@ -0,0 +1,18 @@ +WITH + NY AS ( + SELECT COUNT(student_id) AS `count` + FROM NewYork + WHERE score >= 90 + ), + CA AS ( + SELECT COUNT(student_id) AS `count` + FROM California + WHERE score >= 90 + ) +SELECT + CASE + WHEN NY.`count` > CA.`count` THEN 'New York University' + WHEN NY.`count` < CA.`count` THEN 'California University' + ELSE 'No Winner' + END AS Winner +FROM NY, CA; diff --git a/solutions/2073. Time Needed to Buy Tickets/2073.cpp b/solutions/2073. Time Needed to Buy Tickets/2073.cpp new file mode 100644 index 00000000000..474a3addb11 --- /dev/null +++ b/solutions/2073. Time Needed to Buy Tickets/2073.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int timeRequiredToBuy(vector& tickets, int k) { + int ans = 0; + + for (int i = 0; i < tickets.size(); ++i) + if (i <= k) + ans += min(tickets[i], tickets[k]); + else + ans += min(tickets[i], tickets[k] - 1); + + return ans; + } +}; diff --git a/solutions/2073. Time Needed to Buy Tickets/2073.java b/solutions/2073. Time Needed to Buy Tickets/2073.java new file mode 100644 index 00000000000..b2df56c17b9 --- /dev/null +++ b/solutions/2073. Time Needed to Buy Tickets/2073.java @@ -0,0 +1,13 @@ +class Solution { + public int timeRequiredToBuy(int[] tickets, int k) { + int ans = 0; + + for (int i = 0; i < tickets.length; ++i) + if (i <= k) + ans += Math.min(tickets[i], tickets[k]); + else + ans += Math.min(tickets[i], tickets[k] - 1); + + return ans; + } +} diff --git a/solutions/2073. Time Needed to Buy Tickets/2073.py b/solutions/2073. Time Needed to Buy Tickets/2073.py new file mode 100644 index 00000000000..5f48a931615 --- /dev/null +++ b/solutions/2073. Time Needed to Buy Tickets/2073.py @@ -0,0 +1,11 @@ +class Solution: + def timeRequiredToBuy(self, tickets: List[int], k: int) -> int: + ans = 0 + + for i, ticket in enumerate(tickets): + if i <= k: + ans += min(ticket, tickets[k]) + else: + ans += min(ticket, tickets[k] - 1) + + return ans diff --git a/solutions/2074. Reverse Nodes in Even Length Groups/2074.cpp b/solutions/2074. Reverse Nodes in Even Length Groups/2074.cpp new file mode 100644 index 00000000000..ab97bafa411 --- /dev/null +++ b/solutions/2074. Reverse Nodes in Even Length Groups/2074.cpp @@ -0,0 +1,55 @@ +class Solution { + public: + ListNode* reverseEvenLengthGroups(ListNode* head) { + // prev -> (head -> ... -> tail) -> next -> ... + ListNode dummy(0, head); + ListNode* prev = &dummy; + ListNode* tail = head; + ListNode* next = head->next; + int groupLength = 1; + + while (true) { + if (groupLength % 2 == 1) { + prev->next = head; + prev = tail; + } else { + tail->next = nullptr; + prev->next = reverse(head); + // Prev -> (tail -> ... -> head) -> next -> ... + head->next = next; + prev = head; + } + if (next == nullptr) + break; + head = next; + const auto [theTail, theLength] = getTailAndLength(head, groupLength + 1); + tail = theTail; + next = tail->next; + groupLength = theLength; + } + + return dummy.next; + } + + private: + pair getTailAndLength(ListNode* head, int groupLength) { + int length = 1; + ListNode* tail = head; + while (length < groupLength && tail->next) { + tail = tail->next; + ++length; + } + return {tail, length}; + } + + ListNode* reverse(ListNode* head) { + ListNode* prev = nullptr; + while (head) { + ListNode* next = head->next; + head->next = prev; + prev = head; + head = next; + } + return prev; + } +}; diff --git a/solutions/2074. Reverse Nodes in Even Length Groups/2074.java b/solutions/2074. Reverse Nodes in Even Length Groups/2074.java new file mode 100644 index 00000000000..991276b2e38 --- /dev/null +++ b/solutions/2074. Reverse Nodes in Even Length Groups/2074.java @@ -0,0 +1,53 @@ +class Solution { + public ListNode reverseEvenLengthGroups(ListNode head) { + // prev -> (head -> ... -> tail) -> next -> ... + ListNode dummy = new ListNode(0, head); + ListNode prev = dummy; + ListNode tail = head; + ListNode next = head.next; + int groupLength = 1; + + while (true) { + if (groupLength % 2 == 1) { + prev.next = head; + prev = tail; + } else { + tail.next = null; + prev.next = reverse(head); + // Prev -> (tail -> ... -> head) -> next -> ... + head.next = next; + prev = head; + } + if (next == null) + break; + head = next; + Pair res = getTailAndLength(head, groupLength + 1); + tail = res.getKey(); + next = tail.next; + groupLength = res.getValue(); + } + + return dummy.next; + } + + private Pair getTailAndLength(ListNode head, int groupLength) { + int length = 1; + ListNode tail = head; + while (length < groupLength && tail.next != null) { + tail = tail.next; + ++length; + } + return new Pair<>(tail, length); + } + + ListNode reverse(ListNode head) { + ListNode prev = null; + while (head != null) { + ListNode next = head.next; + head.next = prev; + prev = head; + head = next; + } + return prev; + } +} diff --git a/solutions/2074. Reverse Nodes in Even Length Groups/2074.py b/solutions/2074. Reverse Nodes in Even Length Groups/2074.py new file mode 100644 index 00000000000..e0f5700a2c1 --- /dev/null +++ b/solutions/2074. Reverse Nodes in Even Length Groups/2074.py @@ -0,0 +1,44 @@ +class Solution: + def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]: + # prev -> (head -> ... -> tail) -> next -> ... + dummy = ListNode(0, head) + prev = dummy + tail = head + next = head.next + groupLength = 1 + + def getTailAndLength(head: Optional[ListNode], groupLength: int) -> Tuple[Optional[ListNode], int]: + length = 1 + tail = head + while length < groupLength and tail.next: + tail = tail.next + length += 1 + return tail, length + + def reverse(head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + while head: + next = head.next + head.next = prev + prev = head + head = next + return prev + + while True: + if groupLength % 2 == 1: + prev.next = head + prev = tail + else: + tail.next = None + prev.next = reverse(head) + # Prev -> (tail -> ... -> head) -> next -> ... + head.next = next + prev = head + if not next: + break + head = next + tail, length = getTailAndLength(head, groupLength + 1) + next = tail.next + groupLength = length + + return dummy.next diff --git a/solutions/2075. Decode the Slanted Ciphertext/2075-2.py b/solutions/2075. Decode the Slanted Ciphertext/2075-2.py new file mode 100644 index 00000000000..fd861ec7a5a --- /dev/null +++ b/solutions/2075. Decode the Slanted Ciphertext/2075-2.py @@ -0,0 +1,12 @@ +class Solution: + def decodeCiphertext(self, encodedText: str, rows: int) -> str: + n = len(encodedText) + cols = n // rows + + ans = [] + + for j in range(cols): + for i in range(j, n, cols + 1): + ans.append(encodedText[i]) + + return ''.join(ans).rstrip() diff --git a/solutions/2075. Decode the Slanted Ciphertext/2075.py b/solutions/2075. Decode the Slanted Ciphertext/2075.py new file mode 100644 index 00000000000..1a2f39b527b --- /dev/null +++ b/solutions/2075. Decode the Slanted Ciphertext/2075.py @@ -0,0 +1,21 @@ +class Solution: + def decodeCiphertext(self, encodedText: str, rows: int) -> str: + n = len(encodedText) + cols = n // rows + + ans = [] + matrix = [[' '] * cols for _ in range(rows)] + + for i in range(rows): + for j in range(cols): + matrix[i][j] = encodedText[i * cols + j] + + for col in range(cols): + i = 0 + j = col + while i < rows and j < cols: + ans.append(matrix[i][j]) + i += 1 + j += 1 + + return ''.join(ans).rstrip() diff --git a/solutions/2076. Process Restricted Friend Requests/2076.cpp b/solutions/2076. Process Restricted Friend Requests/2076.cpp new file mode 100644 index 00000000000..66f33fe0932 --- /dev/null +++ b/solutions/2076. Process Restricted Friend Requests/2076.cpp @@ -0,0 +1,58 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + vector friendRequests(int n, vector>& restrictions, + vector>& requests) { + vector ans; + UnionFind uf(n); + + for (const vector& request : requests) { + const int i = uf.find(request[0]); + const int j = uf.find(request[1]); + bool isValid = true; + if (i != j) + for (const vector& restriction : restrictions) { + const int x = uf.find(restriction[0]); + const int y = uf.find(restriction[1]); + if (i == x && j == y || i == y && j == x) { + isValid = false; + break; + } + } + ans.push_back(isValid); + if (isValid) + uf.unionByRank(i, j); + } + + return ans; + } +}; diff --git a/solutions/2076. Process Restricted Friend Requests/2076.java b/solutions/2076. Process Restricted Friend Requests/2076.java new file mode 100644 index 00000000000..b9e41e0cefe --- /dev/null +++ b/solutions/2076. Process Restricted Friend Requests/2076.java @@ -0,0 +1,57 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) { + boolean[] ans = new boolean[requests.length]; + UnionFind uf = new UnionFind(n); + + for (int i = 0; i < requests.length; ++i) { + final int pu = uf.find(requests[i][0]); + final int pv = uf.find(requests[i][1]); + boolean isValid = true; + if (pu != pv) + for (int[] restriction : restrictions) { + final int px = uf.find(restriction[0]); + final int py = uf.find(restriction[1]); + if (pu == px && pv == py || pu == py && pv == px) { + isValid = false; + break; + } + } + ans[i] = isValid; + if (isValid) + uf.unionByRank(pu, pv); + } + + return ans; + } +} diff --git a/solutions/2076. Process Restricted Friend Requests/2076.py b/solutions/2076. Process Restricted Friend Requests/2076.py new file mode 100644 index 00000000000..db1cddf02c7 --- /dev/null +++ b/solutions/2076. Process Restricted Friend Requests/2076.py @@ -0,0 +1,45 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]: + ans = [] + uf = UnionFind(n) + + for u, v in requests: + pu = uf.find(u) + pv = uf.find(v) + isValid = True + if pu != pv: + for x, y in restrictions: + px = uf.find(x) + py = uf.find(y) + if (pu, pv) in [(px, py), (py, px)]: + isValid = False + break + ans.append(isValid) + if isValid: + uf.unionByRank(pu, pv) + + return ans diff --git a/solutions/2077. Paths in Maze That Lead to Same Room/2077.py b/solutions/2077. Paths in Maze That Lead to Same Room/2077.py new file mode 100644 index 00000000000..a9e6d3f5593 --- /dev/null +++ b/solutions/2077. Paths in Maze That Lead to Same Room/2077.py @@ -0,0 +1,15 @@ +class Solution: + def numberOfPaths(self, n: int, corridors: List[List[int]]) -> int: + ans = 0 + graph = [[False] * 1001 for _ in range(n + 1)] + + for u, v in corridors: + graph[u][v] = True + graph[v][u] = True + + for u, v in corridors: + for i in range(1, n + 1): + if graph[u][i] and graph[i][v]: + ans += 1 + + return ans // 3 diff --git a/solutions/2078. Two Furthest Houses With Different Colors/2078.cpp b/solutions/2078. Two Furthest Houses With Different Colors/2078.cpp new file mode 100644 index 00000000000..dcf904d47c7 --- /dev/null +++ b/solutions/2078. Two Furthest Houses With Different Colors/2078.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxDistance(vector& colors) { + // The maximum distance always includes either the first or the last house. + const int n = colors.size(); + int i = 0; // the leftmost index, where colors[i] != colors[-1] + int j = n - 1; // the rightmost index, where colors[j] != colors[0] + while (colors[i] == colors.back()) + ++i; + while (colors[j] == colors.front()) + --j; + return max(n - 1 - i, j); + } +}; diff --git a/solutions/2078. Two Furthest Houses With Different Colors/2078.java b/solutions/2078. Two Furthest Houses With Different Colors/2078.java new file mode 100644 index 00000000000..bbfce2e5c19 --- /dev/null +++ b/solutions/2078. Two Furthest Houses With Different Colors/2078.java @@ -0,0 +1,12 @@ +class Solution { + public int maxDistance(int[] colors) { + final int n = colors.length; + int i = 0; // the leftmost index, where colors[i] != colors[n - 1] + int j = n - 1; // the rightmost index, where colors[j] != colors[0] + while (colors[i] == colors[n - 1]) + ++i; + while (colors[j] == colors[0]) + --j; + return Math.max(n - 1 - i, j); + } +} diff --git a/solutions/2078. Two Furthest Houses With Different Colors/2078.py b/solutions/2078. Two Furthest Houses With Different Colors/2078.py new file mode 100644 index 00000000000..a8e93c7accd --- /dev/null +++ b/solutions/2078. Two Furthest Houses With Different Colors/2078.py @@ -0,0 +1,11 @@ +class Solution: + def maxDistance(self, colors: List[int]) -> int: + # The maximum distance always includes either the first or the last house. + n = len(colors) + i = 0 # the leftmost index, where colors[i] != colors[-1] + j = n - 1 # the rightmost index, where colors[j] != colors[0] + while colors[i] == colors[-1]: + i += 1 + while colors[j] == colors[0]: + j -= 1 + return max(n - 1 - i, j) diff --git a/solutions/2079. Watering Plants/2079.py b/solutions/2079. Watering Plants/2079.py new file mode 100644 index 00000000000..4d8c01456ff --- /dev/null +++ b/solutions/2079. Watering Plants/2079.py @@ -0,0 +1,13 @@ +class Solution: + def wateringPlants(self, plants: List[int], capacity: int) -> int: + ans = 0 + currCapacity = 0 + + for i, plant in enumerate(plants): + if currCapacity + plant <= capacity: + currCapacity += plant + else: + currCapacity = plant # Reset + ans += i * 2 + + return ans + len(plants) diff --git a/solutions/208. Implement Trie (Prefix Tree)/208.cpp b/solutions/208. Implement Trie (Prefix Tree)/208.cpp new file mode 100644 index 00000000000..214a88f7858 --- /dev/null +++ b/solutions/208. Implement Trie (Prefix Tree)/208.cpp @@ -0,0 +1,42 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class Trie { + public: + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->isWord = true; + } + + bool search(const string& word) { + shared_ptr node = find(word); + return node && node->isWord; + } + + bool startsWith(const string& prefix) { + return find(prefix) != nullptr; + } + + private: + shared_ptr root = make_shared(); + + shared_ptr find(const string& prefix) { + shared_ptr node = root; + for (const char c : prefix) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + return nullptr; + node = node->children[i]; + } + return node; + } +}; diff --git a/solutions/208. Implement Trie (Prefix Tree)/208.java b/solutions/208. Implement Trie (Prefix Tree)/208.java new file mode 100644 index 00000000000..8498e3e9c1e --- /dev/null +++ b/solutions/208. Implement Trie (Prefix Tree)/208.java @@ -0,0 +1,39 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class Trie { + public void insert(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + public boolean search(String word) { + TrieNode node = find(word); + return node != null && node.isWord; + } + + public boolean startsWith(String prefix) { + return find(prefix) != null; + } + + private TrieNode root = new TrieNode(); + + private TrieNode find(String prefix) { + TrieNode node = root; + for (final char c : prefix.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + return null; + node = node.children[i]; + } + return node; + } +} diff --git a/solutions/208. Implement Trie (Prefix Tree)/208.py b/solutions/208. Implement Trie (Prefix Tree)/208.py new file mode 100644 index 00000000000..fa8bd908853 --- /dev/null +++ b/solutions/208. Implement Trie (Prefix Tree)/208.py @@ -0,0 +1,30 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.isWord = False + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> None: + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + def search(self, word: str) -> bool: + node: TrieNode = self._find(word) + return node and node.isWord + + def startsWith(self, prefix: str) -> bool: + return self._find(prefix) + + def _find(self, prefix: str) -> Optional[TrieNode]: + node: TrieNode = self.root + for c in prefix: + if c not in node.children: + return None + node = node.children[c] + return node diff --git a/solutions/2080. Range Frequency Queries/2080.py b/solutions/2080. Range Frequency Queries/2080.py new file mode 100644 index 00000000000..ae855944e11 --- /dev/null +++ b/solutions/2080. Range Frequency Queries/2080.py @@ -0,0 +1,11 @@ +class RangeFreqQuery: + def __init__(self, arr: List[int]): + self.valueToIndices = collections.defaultdict(list) + for i, a in enumerate(arr): + self.valueToIndices[a].append(i) + + def query(self, left: int, right: int, value: int) -> int: + indices = self.valueToIndices[value] + i = bisect_left(indices, left) + j = bisect_right(indices, right) + return j - i diff --git a/solutions/2081. Sum of k-Mirror Numbers/2081.py b/solutions/2081. Sum of k-Mirror Numbers/2081.py new file mode 100644 index 00000000000..bef82e097b8 --- /dev/null +++ b/solutions/2081. Sum of k-Mirror Numbers/2081.py @@ -0,0 +1,26 @@ +class Solution: + def kMirror(self, k: int, n: int) -> int: + ans = 0 + A = ['0'] + + def nextKMirror(A: List[chr]) -> List[chr]: + for i in range(len(A) // 2, len(A)): + nextNum = int(A[i]) + 1 + if nextNum < k: + A[i] = str(nextNum) + A[~i] = str(nextNum) + for j in range(len(A) // 2, i): + A[j] = '0' + A[~j] = '0' + return A + return ['1'] + ['0'] * (len(A) - 1) + ['1'] + + for _ in range(n): + while True: + A = nextKMirror(A) + num = int(''.join(A), k) + if str(num)[::-1] == str(num): + break + ans += num + + return ans diff --git a/solutions/2082. The Number of Rich Customers/2082.sql b/solutions/2082. The Number of Rich Customers/2082.sql new file mode 100644 index 00000000000..b91f6a7fb4c --- /dev/null +++ b/solutions/2082. The Number of Rich Customers/2082.sql @@ -0,0 +1,3 @@ +SELECT COUNT(DISTINCT customer_id) AS rich_count +FROM Store +WHERE amount > 500; diff --git a/solutions/2083. Substrings That Begin and End With the Same Letter/2083.cpp b/solutions/2083. Substrings That Begin and End With the Same Letter/2083.cpp new file mode 100644 index 00000000000..cb2dc7095fe --- /dev/null +++ b/solutions/2083. Substrings That Begin and End With the Same Letter/2083.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + long long numberOfSubstrings(string s) { + long ans = 0; + vector count(26); + + for (const char c : s) + ans += ++count[c - 'a']; + + return ans; + } +}; diff --git a/solutions/2083. Substrings That Begin and End With the Same Letter/2083.java b/solutions/2083. Substrings That Begin and End With the Same Letter/2083.java new file mode 100644 index 00000000000..1dfe2809f81 --- /dev/null +++ b/solutions/2083. Substrings That Begin and End With the Same Letter/2083.java @@ -0,0 +1,11 @@ +class Solution { + public long numberOfSubstrings(String s) { + long ans = 0; + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ans += ++count[c - 'a']; + + return ans; + } +} diff --git a/solutions/2083. Substrings That Begin and End With the Same Letter/2083.py b/solutions/2083. Substrings That Begin and End With the Same Letter/2083.py new file mode 100644 index 00000000000..915c74cc37b --- /dev/null +++ b/solutions/2083. Substrings That Begin and End With the Same Letter/2083.py @@ -0,0 +1,10 @@ +class Solution: + def numberOfSubstrings(self, s: str) -> int: + ans = 0 + count = collections.Counter() + + for c in s: + ans += count[c] + 1 + count[c] += 1 + + return ans diff --git a/solutions/2084. Drop Type 1 Orders for Customers With Type 0 Orders/2084.sql b/solutions/2084. Drop Type 1 Orders for Customers With Type 0 Orders/2084.sql new file mode 100644 index 00000000000..457d901b787 --- /dev/null +++ b/solutions/2084. Drop Type 1 Orders for Customers With Type 0 Orders/2084.sql @@ -0,0 +1,13 @@ +WITH + RankedOrders AS ( + SELECT + *, + RANK() OVER(PARTITION BY customer_id ORDER BY order_type) AS `rank` + FROM Orders + ) +SELECT + order_id, + customer_id, + order_type +FROM RankedOrders +WHERE `rank` = 1; diff --git a/solutions/2085. Count Common Words With One Occurrence/2085.cpp b/solutions/2085. Count Common Words With One Occurrence/2085.cpp new file mode 100644 index 00000000000..b6a5bdd5058 --- /dev/null +++ b/solutions/2085. Count Common Words With One Occurrence/2085.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int countWords(vector& words1, vector& words2) { + unordered_map count; + + for (const string& word : words1) + ++count[word]; + + for (const string& word : words2) + if (const auto it = count.find(word); + it != count.cend() && it->second < 2) + --it->second; + + return ranges::count_if(count, [](const auto& c) { return c.second == 0; }); + } +}; diff --git a/solutions/2085. Count Common Words With One Occurrence/2085.java b/solutions/2085. Count Common Words With One Occurrence/2085.java new file mode 100644 index 00000000000..d4a80facafe --- /dev/null +++ b/solutions/2085. Count Common Words With One Occurrence/2085.java @@ -0,0 +1,14 @@ +class Solution { + public int countWords(String[] words1, String[] words2) { + Map count = new HashMap<>(); + + for (final String word : words1) + count.merge(word, 1, Integer::sum); + + for (final String word : words2) + if (count.containsKey(word) && count.get(word) < 2) + count.merge(word, -1, Integer::sum); + + return (int) count.values().stream().filter(v -> v == 0).count(); + } +} diff --git a/solutions/2085. Count Common Words With One Occurrence/2085.py b/solutions/2085. Count Common Words With One Occurrence/2085.py new file mode 100644 index 00000000000..92518141f8d --- /dev/null +++ b/solutions/2085. Count Common Words With One Occurrence/2085.py @@ -0,0 +1,9 @@ +class Solution: + def countWords(self, words1: List[str], words2: List[str]) -> int: + count = collections.Counter(words1) + + for word in words2: + if word in count and count[word] < 2: + count[word] -= 1 + + return sum(value == 0 for value in count.values()) diff --git a/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.cpp b/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.cpp new file mode 100644 index 00000000000..38bac6a6c6d --- /dev/null +++ b/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minimumBuckets(string street) { + for (int i = 0; i < street.length(); ++i) + if (street[i] == 'H') { + if (i > 0 && street[i - 1] == 'B') + continue; + if (i + 1 < street.length() && street[i + 1] == '.') + // Always prefer place a bucket in (i + 1) because it enhances the + // possibility to collect the upcoming houses. + street[i + 1] = 'B'; + else if (i > 0 && street[i - 1] == '.') + street[i - 1] = 'B'; + else + return -1; + } + + return ranges::count(street, 'B'); + } +}; diff --git a/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.java b/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.java new file mode 100644 index 00000000000..76fa547ddfd --- /dev/null +++ b/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.java @@ -0,0 +1,21 @@ +class Solution { + public int minimumBuckets(String street) { + final char[] A = street.toCharArray(); + + for (int i = 0; i < A.length; ++i) + if (A[i] == 'H') { + if (i > 0 && A[i - 1] == 'B') + continue; + if (i + 1 < A.length && A[i + 1] == '.') + // Always prefer place a bucket in (i + 1) because it enhances the + // possibility to collect the upcoming houses. + A[i + 1] = 'B'; + else if (i > 0 && A[i - 1] == '.') + A[i - 1] = 'B'; + else + return -1; + } + + return (int) new String(A).chars().filter(a -> a == 'B').count(); + } +} diff --git a/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.py b/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.py new file mode 100644 index 00000000000..4b367ab8c2b --- /dev/null +++ b/solutions/2086. Minimum Number of Buckets Required to Collect Rainwater from Houses/2086.py @@ -0,0 +1,18 @@ +class Solution: + def minimumBuckets(self, street: str) -> int: + A = list(street) + + for i, c in enumerate(A): + if c == 'H': + if i > 0 and A[i - 1] == 'B': + continue + if i + 1 < len(A) and A[i + 1] == '.': + # Always prefer place a bucket in (i + 1) because it enhances the + # possibility to collect the upcoming houses. + A[i + 1] = 'B' + elif i > 0 and A[i - 1] == '.': + A[i - 1] = 'B' + else: + return -1 + + return A.count('B') diff --git a/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.cpp b/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.cpp new file mode 100644 index 00000000000..3698cf390f4 --- /dev/null +++ b/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minCost(vector& startPos, vector& homePos, + vector& rowCosts, vector& colCosts) { + int ans = 0; + int i = startPos[0]; + int j = startPos[1]; + int x = homePos[0]; + int y = homePos[1]; + + while (i != x) + ans += i < x ? rowCosts[++i] : rowCosts[--i]; + while (j != y) + ans += j < y ? colCosts[++j] : colCosts[--j]; + + return ans; + } +}; diff --git a/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.java b/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.java new file mode 100644 index 00000000000..0996420bef8 --- /dev/null +++ b/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.java @@ -0,0 +1,16 @@ +class Solution { + public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) { + int ans = 0; + int i = startPos[0]; + int j = startPos[1]; + int x = homePos[0]; + int y = homePos[1]; + + while (i != x) + ans += i < x ? rowCosts[++i] : rowCosts[--i]; + while (j != y) + ans += j < y ? colCosts[++j] : colCosts[--j]; + + return ans; + } +} diff --git a/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.py b/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.py new file mode 100644 index 00000000000..f3c32c34ee2 --- /dev/null +++ b/solutions/2087. Minimum Cost Homecoming of a Robot in a Grid/2087.py @@ -0,0 +1,15 @@ +class Solution: + def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int: + ans = 0 + i, j = startPos + x, y = homePos + + while i != x: + i += 1 if i < x else -1 + ans += rowCosts[i] + + while j != y: + j += 1 if j < y else -1 + ans += colCosts[j] + + return ans diff --git a/solutions/2088. Count Fertile Pyramids in a Land/2088.cpp b/solutions/2088. Count Fertile Pyramids in a Land/2088.cpp new file mode 100644 index 00000000000..b97c0eadaa9 --- /dev/null +++ b/solutions/2088. Count Fertile Pyramids in a Land/2088.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int countPyramids(vector>& grid) { + int ans = count(grid); + reverse(grid.begin(), grid.end()); + ans += count(grid); + return ans; + } + + private: + // dp[i][j] := the maximum height of the pyramid for which it is the apex + int count(vector> dp) { + int ans = 0; + for (int i = dp.size() - 2; i >= 0; --i) + for (int j = 1; j + 1 < dp[0].size(); ++j) + if (dp[i][j] == 1) { + dp[i][j] = + min({dp[i + 1][j - 1], dp[i + 1][j], dp[i + 1][j + 1]}) + 1; + ans += dp[i][j] - 1; + } + return ans; + } +}; diff --git a/solutions/2088. Count Fertile Pyramids in a Land/2088.java b/solutions/2088. Count Fertile Pyramids in a Land/2088.java new file mode 100644 index 00000000000..1fa5fa3ff66 --- /dev/null +++ b/solutions/2088. Count Fertile Pyramids in a Land/2088.java @@ -0,0 +1,24 @@ +class Solution { + public int countPyramids(int[][] grid) { + return count(reversed(grid)) + count(grid); + } + + // dp[i][j] := the maximum height of the pyramid for which it is the apex + private int count(int[][] dp) { + int ans = 0; + for (int i = dp.length - 2; i >= 0; --i) + for (int j = 1; j + 1 < dp[0].length; ++j) + if (dp[i][j] == 1) { + dp[i][j] = Math.min(dp[i + 1][j - 1], Math.min(dp[i + 1][j], dp[i + 1][j + 1])) + 1; + ans += dp[i][j] - 1; + } + return ans; + } + + private int[][] reversed(int[][] grid) { + int[][] A = new int[grid.length][]; + for (int i = 0; i < grid.length; ++i) + A[i] = grid[grid.length - i - 1].clone(); + return A; + } +} diff --git a/solutions/2088. Count Fertile Pyramids in a Land/2088.py b/solutions/2088. Count Fertile Pyramids in a Land/2088.py new file mode 100644 index 00000000000..7d4b7d51793 --- /dev/null +++ b/solutions/2088. Count Fertile Pyramids in a Land/2088.py @@ -0,0 +1,15 @@ +class Solution: + def countPyramids(self, grid: List[List[int]]) -> int: + # dp[i][j] := the maximum height of the pyramid for which it is the apex + def count(dp: List[List[int]]) -> int: + ans = 0 + for i in range(len(dp) - 2, -1, -1): + for j in range(1, len(dp[0]) - 1): + if dp[i][j] == 1: + dp[i][j] = min(dp[i + 1][j - 1], + dp[i + 1][j], + dp[i + 1][j + 1]) + 1 + ans += dp[i][j] - 1 + return ans + + return count(deepcopy(grid)[::-1]) + count(grid) diff --git a/solutions/2089. Find Target Indices After Sorting Array/2089.cpp b/solutions/2089. Find Target Indices After Sorting Array/2089.cpp new file mode 100644 index 00000000000..b80655304a5 --- /dev/null +++ b/solutions/2089. Find Target Indices After Sorting Array/2089.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector targetIndices(vector& nums, int target) { + vector ans; + const int count = ranges::count(nums, target); + int lessThan = + ranges::count_if(nums, [&](int num) { return num < target; }); + + for (int i = 0; i < count; ++i) + ans.push_back(lessThan++); + + return ans; + } +}; diff --git a/solutions/2089. Find Target Indices After Sorting Array/2089.java b/solutions/2089. Find Target Indices After Sorting Array/2089.java new file mode 100644 index 00000000000..17bf5b8ebfe --- /dev/null +++ b/solutions/2089. Find Target Indices After Sorting Array/2089.java @@ -0,0 +1,12 @@ +class Solution { + public List targetIndices(int[] nums, int target) { + List ans = new ArrayList<>(); + final int count = (int) Arrays.stream(nums).filter(num -> num == target).count(); + int lessThan = (int) Arrays.stream(nums).filter(num -> num < target).count(); + + for (int i = 0; i < count; ++i) + ans.add(lessThan++); + + return ans; + } +} diff --git a/solutions/2089. Find Target Indices After Sorting Array/2089.py b/solutions/2089. Find Target Indices After Sorting Array/2089.py new file mode 100644 index 00000000000..d05bedad74a --- /dev/null +++ b/solutions/2089. Find Target Indices After Sorting Array/2089.py @@ -0,0 +1,5 @@ +class Solution: + def targetIndices(self, nums: List[int], target: int) -> List[int]: + count = nums.count(target) + lessThan = sum(num < target for num in nums) + return [i for i in range(lessThan, lessThan + count)] diff --git a/solutions/209. Minimum Size Subarray Sum/209.cpp b/solutions/209. Minimum Size Subarray Sum/209.cpp new file mode 100644 index 00000000000..2f27aeed693 --- /dev/null +++ b/solutions/209. Minimum Size Subarray Sum/209.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minSubArrayLen(int s, vector& nums) { + int ans = INT_MAX; + int sum = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + sum += nums[r]; + while (sum >= s) { + ans = min(ans, r - l + 1); + sum -= nums[l++]; + } + } + + return ans < INT_MAX ? ans : 0; + } +}; diff --git a/solutions/209. Minimum Size Subarray Sum/209.java b/solutions/209. Minimum Size Subarray Sum/209.java new file mode 100644 index 00000000000..e1ac5341593 --- /dev/null +++ b/solutions/209. Minimum Size Subarray Sum/209.java @@ -0,0 +1,16 @@ +class Solution { + public int minSubArrayLen(int s, int[] nums) { + int ans = Integer.MAX_VALUE; + int sum = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + sum += nums[r]; + while (sum >= s) { + ans = Math.min(ans, r - l + 1); + sum -= nums[l++]; + } + } + + return ans != Integer.MAX_VALUE ? ans : 0; + } +} diff --git a/solutions/209. Minimum Size Subarray Sum/209.py b/solutions/209. Minimum Size Subarray Sum/209.py new file mode 100644 index 00000000000..4315fd8d13e --- /dev/null +++ b/solutions/209. Minimum Size Subarray Sum/209.py @@ -0,0 +1,14 @@ +class Solution: + def minSubArrayLen(self, s: int, nums: List[int]) -> int: + ans = math.inf + summ = 0 + j = 0 + + for i, num in enumerate(nums): + summ += num + while summ >= s: + ans = min(ans, i - j + 1) + summ -= nums[j] + j += 1 + + return ans if ans != math.inf else 0 diff --git a/solutions/2090. K Radius Subarray Averages/2090.cpp b/solutions/2090. K Radius Subarray Averages/2090.cpp new file mode 100644 index 00000000000..4f40203df63 --- /dev/null +++ b/solutions/2090. K Radius Subarray Averages/2090.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector getAverages(vector& nums, int k) { + const int n = nums.size(); + const int size = 2 * k + 1; + vector ans(n, -1); + if (size > n) + return ans; + + long sum = accumulate(nums.begin(), nums.begin() + size, 0L); + + for (int i = k; i + k < n; ++i) { + ans[i] = sum / size; + if (i + k + 1 < n) + sum += nums[i + k + 1] - nums[i - k]; + } + + return ans; + } +}; diff --git a/solutions/2090. K Radius Subarray Averages/2090.java b/solutions/2090. K Radius Subarray Averages/2090.java new file mode 100644 index 00000000000..db7a2c792b7 --- /dev/null +++ b/solutions/2090. K Radius Subarray Averages/2090.java @@ -0,0 +1,23 @@ +class Solution { + public int[] getAverages(int[] nums, int k) { + final int n = nums.length; + final int size = 2 * k + 1; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + if (size > n) + return ans; + + long sum = 0; + + for (int i = 0; i < size; ++i) + sum += nums[i]; + + for (int i = k; i + k < n; ++i) { + ans[i] = (int) (sum / size); + if (i + k + 1 < n) + sum += nums[i + k + 1] - nums[i - k]; + } + + return ans; + } +} diff --git a/solutions/2090. K Radius Subarray Averages/2090.py b/solutions/2090. K Radius Subarray Averages/2090.py new file mode 100644 index 00000000000..7453b4b150c --- /dev/null +++ b/solutions/2090. K Radius Subarray Averages/2090.py @@ -0,0 +1,16 @@ +class Solution: + def getAverages(self, nums: List[int], k: int) -> List[int]: + n = len(nums) + size = 2 * k + 1 + ans = [-1] * n + if size > n: + return ans + + summ = sum(nums[:size]) + + for i in range(k, n - k): + ans[i] = summ // size + if i + k + 1 < n: + summ += nums[i + k + 1] - nums[i - k] + + return ans diff --git a/solutions/2091. Removing Minimum and Maximum From Array/2091.cpp b/solutions/2091. Removing Minimum and Maximum From Array/2091.cpp new file mode 100644 index 00000000000..8daf93ae148 --- /dev/null +++ b/solutions/2091. Removing Minimum and Maximum From Array/2091.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int minimumDeletions(vector& nums) { + const int n = nums.size(); + int a = ranges::min_element(nums) - nums.begin(); + int b = ranges::max_element(nums) - nums.begin(); + if (a > b) + swap(a, b); + return min({a + 1 + n - b, b + 1, n - a}); + } +}; diff --git a/solutions/2091. Removing Minimum and Maximum From Array/2091.java b/solutions/2091. Removing Minimum and Maximum From Array/2091.java new file mode 100644 index 00000000000..f0f71f0a0c3 --- /dev/null +++ b/solutions/2091. Removing Minimum and Maximum From Array/2091.java @@ -0,0 +1,29 @@ +class Solution { + public int minimumDeletions(int[] nums) { + final int n = nums.length; + + int mn = Integer.MAX_VALUE; + int mx = Integer.MIN_VALUE; + int minIndex = -1; + int maxIndex = -1; + + for (int i = 0; i < n; ++i) { + if (nums[i] < mn) { + mn = nums[i]; + minIndex = i; + } + if (nums[i] > mx) { + mx = nums[i]; + maxIndex = i; + } + } + + final int a = Math.min(minIndex, maxIndex); + final int b = Math.max(minIndex, maxIndex); + + // min(delete from front and back, + // delete from front, + // delete from back) + return Math.min(a + 1 + n - b, Math.min(b + 1, n - a)); + } +} diff --git a/solutions/2091. Removing Minimum and Maximum From Array/2091.py b/solutions/2091. Removing Minimum and Maximum From Array/2091.py new file mode 100644 index 00000000000..a2411507815 --- /dev/null +++ b/solutions/2091. Removing Minimum and Maximum From Array/2091.py @@ -0,0 +1,8 @@ +class Solution: + def minimumDeletions(self, nums: List[int]) -> int: + n = len(nums) + a = nums.index(min(nums)) + b = nums.index(max(nums)) + if a > b: + a, b = b, a + return min(a + 1 + n - b, b + 1, n - a) diff --git a/solutions/2092. Find All People With Secret/2092.cpp b/solutions/2092. Find All People With Secret/2092.cpp new file mode 100644 index 00000000000..08d5ce3886a --- /dev/null +++ b/solutions/2092. Find All People With Secret/2092.cpp @@ -0,0 +1,70 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + bool connected(int u, int v) { + return find(u) == find(v); + } + + void reset(int u) { + id[u] = u; + } + + private: + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + vector findAllPeople(int n, vector>& meetings, + int firstPerson) { + vector ans; + UnionFind uf(n); + map>> timeToPairs; + + uf.unionByRank(0, firstPerson); + + for (const vector& m : meetings) + timeToPairs[m[2]].push_back({m[0], m[1]}); + + for (const auto& [_, pairs] : timeToPairs) { + unordered_set peopleUnioned; + for (const auto& [x, y] : pairs) { + uf.unionByRank(x, y); + peopleUnioned.insert(x); + peopleUnioned.insert(y); + } + for (const int person : peopleUnioned) + if (!uf.connected(person, 0)) + uf.reset(person); + } + + for (int i = 0; i < n; ++i) + if (uf.connected(i, 0)) + ans.push_back(i); + + return ans; + } +}; diff --git a/solutions/2092. Find All People With Secret/2092.java b/solutions/2092. Find All People With Secret/2092.java new file mode 100644 index 00000000000..43b52177358 --- /dev/null +++ b/solutions/2092. Find All People With Secret/2092.java @@ -0,0 +1,73 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public boolean connected(int u, int v) { + return find(u) == find(v); + } + + public void reset(int u) { + id[u] = u; + } + + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public List findAllPeople(int n, int[][] meetings, int firstPerson) { + List ans = new ArrayList<>(); + UnionFind uf = new UnionFind(n); + TreeMap>> timeToPairs = new TreeMap<>(); + + uf.unionByRank(0, firstPerson); + + for (int[] m : meetings) { + timeToPairs.putIfAbsent(m[2], new ArrayList<>()); + timeToPairs.get(m[2]).add(new Pair<>(m[0], m[1])); + } + + for (List> pairs : timeToPairs.values()) { + Set peopleUnioned = new HashSet<>(); + for (Pair pair : pairs) { + final int x = pair.getKey(); + final int y = pair.getValue(); + uf.unionByRank(x, y); + peopleUnioned.add(x); + peopleUnioned.add(y); + } + for (final int person : peopleUnioned) + if (!uf.connected(person, 0)) + uf.reset(person); + } + + for (int i = 0; i < n; ++i) + if (uf.connected(i, 0)) + ans.add(i); + + return ans; + } +} diff --git a/solutions/2092. Find All People With Secret/2092.py b/solutions/2092. Find All People With Secret/2092.py new file mode 100644 index 00000000000..1669caa40df --- /dev/null +++ b/solutions/2092. Find All People With Secret/2092.py @@ -0,0 +1,51 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self._find(u) + j = self._find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def connected(self, u: int, v: int) -> bool: + return self._find(self.id[u]) == self._find(self.id[v]) + + def reset(self, u: int) -> None: + self.id[u] = u + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]: + uf = UnionFind(n) + timeToPairs = collections.defaultdict(list) + + uf.unionByRank(0, firstPerson) + + for x, y, time in meetings: + timeToPairs[time].append((x, y)) + + for _, pairs in sorted(timeToPairs.items(), key=lambda x: x[0]): + peopleUnioned = set() + for x, y in pairs: + uf.unionByRank(x, y) + peopleUnioned.add(x) + peopleUnioned.add(y) + for person in peopleUnioned: + if not uf.connected(person, 0): + uf.reset(person) + + return [i for i in range(n) if uf.connected(i, 0)] diff --git a/solutions/2093. Minimum Cost to Reach City With Discounts/2093.cpp b/solutions/2093. Minimum Cost to Reach City With Discounts/2093.cpp new file mode 100644 index 00000000000..8ca2f542a65 --- /dev/null +++ b/solutions/2093. Minimum Cost to Reach City With Discounts/2093.cpp @@ -0,0 +1,45 @@ +struct T { + int u; + int d; + int leftDiscounts; + T(int u, int d, int leftDiscounts) + : u(u), d(d), leftDiscounts(leftDiscounts) {} +}; + +class Solution { + public: + int minimumCost(int n, vector>& highways, int discounts) { + vector>> graph(n); + auto compare = [](const T& a, const T& b) { return a.d > b.d; }; + priority_queue, decltype(compare)> minHeap(compare); + unordered_map minDiscounts; + + for (const vector& h : highways) { + const int city1 = h[0]; + const int city2 = h[1]; + const int toll = h[2]; + graph[city1].emplace_back(city2, toll); + graph[city2].emplace_back(city1, toll); + } + + minHeap.emplace(0, 0, discounts); + + while (!minHeap.empty()) { + const auto [u, d, leftDiscounts] = minHeap.top(); + minHeap.pop(); + if (u == n - 1) + return d; + if (const auto it = minDiscounts.find(u); + it != minDiscounts.cend() && it->second >= leftDiscounts) + continue; + minDiscounts[u] = leftDiscounts; + for (const auto& [v, w] : graph[u]) { + minHeap.emplace(v, d + w, leftDiscounts); + if (leftDiscounts > 0) + minHeap.emplace(v, d + w / 2, leftDiscounts - 1); + } + } + + return -1; + } +}; diff --git a/solutions/2093. Minimum Cost to Reach City With Discounts/2093.java b/solutions/2093. Minimum Cost to Reach City With Discounts/2093.java new file mode 100644 index 00000000000..9468544d811 --- /dev/null +++ b/solutions/2093. Minimum Cost to Reach City With Discounts/2093.java @@ -0,0 +1,50 @@ +class T { + public int u; + public int d; + public int leftDiscounts; + public T(int u, int d, int leftDiscounts) { + this.u = u; + this.d = d; + this.leftDiscounts = leftDiscounts; + } +} + +class Solution { + public int minimumCost(int n, int[][] highways, int discounts) { + List>[] graph = new List[n]; + Queue minHeap = new PriorityQueue<>((a, b) -> a.d - b.d); + Map minDiscounts = new HashMap<>(); + + for (int i = 0; i < graph.length; i++) + graph[i] = new ArrayList<>(); + + for (int[] h : highways) { + final int city1 = h[0]; + final int city2 = h[1]; + final int toll = h[2]; + graph[city1].add(new Pair<>(city2, toll)); + graph[city2].add(new Pair<>(city1, toll)); + } + + minHeap.offer(new T(0, 0, discounts)); + + while (!minHeap.isEmpty()) { + final int u = minHeap.peek().u; + final int d = minHeap.peek().d; + final int leftDiscounts = minHeap.poll().leftDiscounts; + if (u == n - 1) + return d; + if (minDiscounts.getOrDefault(u, -1) >= leftDiscounts) + continue; + minDiscounts.put(u, leftDiscounts); + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + minHeap.offer(new T(v, d + w, leftDiscounts)); + if (leftDiscounts > 0) + minHeap.offer(new T(v, d + w / 2, leftDiscounts - 1)); + } + } + return -1; + } +} diff --git a/solutions/2093. Minimum Cost to Reach City With Discounts/2093.py b/solutions/2093. Minimum Cost to Reach City With Discounts/2093.py new file mode 100644 index 00000000000..1e8a6d7233d --- /dev/null +++ b/solutions/2093. Minimum Cost to Reach City With Discounts/2093.py @@ -0,0 +1,23 @@ +class Solution: + def minimumCost(self, n: int, highways: List[List[int]], discounts: int) -> int: + graph = [[] for _ in range(n)] + minHeap = [(0, 0, discounts)] # (d, u, leftDiscounts) + minDiscounts = {} + + for city1, city2, toll in highways: + graph[city1].append((city2, toll)) + graph[city2].append((city1, toll)) + + while minHeap: + d, u, leftDiscounts = heapq.heappop(minHeap) + if u == n - 1: + return d + if u in minDiscounts and minDiscounts[u] >= leftDiscounts: + continue + minDiscounts[u] = leftDiscounts + for v, w in graph[u]: + heapq.heappush(minHeap, (d + w, v, leftDiscounts)) + if leftDiscounts > 0: + heapq.heappush(minHeap, (d + w // 2, v, leftDiscounts - 1)) + + return -1 diff --git a/solutions/2094. Finding 3-Digit Even Numbers/2094.cpp b/solutions/2094. Finding 3-Digit Even Numbers/2094.cpp new file mode 100644 index 00000000000..87897685215 --- /dev/null +++ b/solutions/2094. Finding 3-Digit Even Numbers/2094.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector findEvenNumbers(vector& digits) { + vector ans; + vector count(10); + + for (const int digit : digits) + ++count[digit]; + + // Try to construct `abc`. + for (int a = 1; a <= 9; ++a) + for (int b = 0; b <= 9; ++b) + for (int c = 0; c <= 8; c += 2) + if (count[a] > 0 && count[b] > (b == a) && + count[c] > (c == a) + (c == b)) + ans.push_back(a * 100 + b * 10 + c); + + return ans; + } +}; diff --git a/solutions/2094. Finding 3-Digit Even Numbers/2094.java b/solutions/2094. Finding 3-Digit Even Numbers/2094.java new file mode 100644 index 00000000000..0915e751e57 --- /dev/null +++ b/solutions/2094. Finding 3-Digit Even Numbers/2094.java @@ -0,0 +1,19 @@ +class Solution { + public int[] findEvenNumbers(int[] digits) { + List ans = new ArrayList<>(); + int[] count = new int[10]; + + for (final int digit : digits) + ++count[digit]; + + // Try to construct `abc`. + for (int a = 1; a <= 9; ++a) + for (int b = 0; b <= 9; ++b) + for (int c = 0; c <= 8; c += 2) + if (count[a] > 0 && count[b] > (b == a ? 1 : 0) && + count[c] > (c == a ? 1 : 0) + (c == b ? 1 : 0)) + ans.add(a * 100 + b * 10 + c); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/2094. Finding 3-Digit Even Numbers/2094.py b/solutions/2094. Finding 3-Digit Even Numbers/2094.py new file mode 100644 index 00000000000..da4070b8207 --- /dev/null +++ b/solutions/2094. Finding 3-Digit Even Numbers/2094.py @@ -0,0 +1,13 @@ +class Solution: + def findEvenNumbers(self, digits: List[int]) -> List[int]: + ans = [] + count = collections.Counter(digits) + + # Try to construct `abc`. + for a in range(1, 10): + for b in range(0, 10): + for c in range(0, 9, 2): + if count[a] > 0 and count[b] > (b == a) and count[c] > (c == a) + (c == b): + ans.append(a * 100 + b * 10 + c) + + return ans diff --git a/solutions/2095. Delete the Middle Node of a Linked List/2095.cpp b/solutions/2095. Delete the Middle Node of a Linked List/2095.cpp new file mode 100644 index 00000000000..82907f697f9 --- /dev/null +++ b/solutions/2095. Delete the Middle Node of a Linked List/2095.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + ListNode* deleteMiddle(ListNode* head) { + ListNode dummy(0, head); + ListNode* slow = &dummy; + ListNode* fast = &dummy; + + while (fast->next != nullptr && fast->next->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + } + + // Delete the middle node. + slow->next = slow->next->next; + return dummy.next; + } +}; diff --git a/solutions/2095. Delete the Middle Node of a Linked List/2095.java b/solutions/2095. Delete the Middle Node of a Linked List/2095.java new file mode 100644 index 00000000000..146d4480fdf --- /dev/null +++ b/solutions/2095. Delete the Middle Node of a Linked List/2095.java @@ -0,0 +1,16 @@ +class Solution { + public ListNode deleteMiddle(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode slow = dummy; + ListNode fast = dummy; + + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + // Delete the middle node. + slow.next = slow.next.next; + return dummy.next; + } +} diff --git a/solutions/2095. Delete the Middle Node of a Linked List/2095.py b/solutions/2095. Delete the Middle Node of a Linked List/2095.py new file mode 100644 index 00000000000..12cdf41ef30 --- /dev/null +++ b/solutions/2095. Delete the Middle Node of a Linked List/2095.py @@ -0,0 +1,13 @@ +class Solution: + def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(0, head) + slow = dummy + fast = dummy + + while fast.next and fast.next.next: + slow = slow.next + fast = fast.next.next + + # Delete the middle node. + slow.next = slow.next.next + return dummy.next diff --git a/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.cpp b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.cpp new file mode 100644 index 00000000000..b54848414c0 --- /dev/null +++ b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + string getDirections(TreeNode* root, int startValue, int destValue) { + string pathToStart; + string pathToDest; + + dfs(root, startValue, pathToStart); + dfs(root, destValue, pathToDest); + + while (!pathToStart.empty() && !pathToDest.empty() && + pathToStart.back() == pathToDest.back()) { + pathToStart.pop_back(); + pathToDest.pop_back(); + } + + return string(pathToStart.length(), 'U') + + string(pathToDest.rbegin(), pathToDest.rend()); + } + + private: + // Builds the string in the reverse order to avoid creating a new copy. + bool dfs(TreeNode* root, int val, string& path) { + if (root->val == val) + return true; + if (root->left && dfs(root->left, val, path)) + path.push_back('L'); + else if (root->right && dfs(root->right, val, path)) + path.push_back('R'); + return !path.empty(); + } +}; diff --git a/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.java b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.java new file mode 100644 index 00000000000..a3e49b11383 --- /dev/null +++ b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.java @@ -0,0 +1,29 @@ +class Solution { + public String getDirections(TreeNode root, int startValue, int destValue) { + StringBuilder pathToStart = new StringBuilder(); + StringBuilder pathToDest = new StringBuilder(); + + dfs(root, startValue, pathToStart); + dfs(root, destValue, pathToDest); + + while (pathToStart.length() > 0 && pathToDest.length() > 0 && + pathToStart.charAt(pathToStart.length() - 1) == + pathToDest.charAt(pathToDest.length() - 1)) { + pathToStart.setLength(pathToStart.length() - 1); + pathToDest.setLength(pathToDest.length() - 1); + } + + return "U".repeat(pathToStart.length()) + pathToDest.reverse().toString(); + } + + // Builds the string in the reverse order to avoid creating a new copy. + private boolean dfs(TreeNode root, int val, StringBuilder sb) { + if (root.val == val) + return true; + if (root.left != null && dfs(root.left, val, sb)) + sb.append("L"); + else if (root.right != null && dfs(root.right, val, sb)) + sb.append("R"); + return sb.length() > 0; + } +} diff --git a/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.py b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.py new file mode 100644 index 00000000000..e55bdf7d716 --- /dev/null +++ b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096-2.py @@ -0,0 +1,23 @@ +class Solution: + def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str: + # Buidl the string in reverse order to avoid creating new copy + def dfs(root: Optional[TreeNode], val: int, path: List[chr]) -> bool: + if root.val == val: + return True + if root.left and dfs(root.left, val, path): + path.append('L') + elif root.right and dfs(root.right, val, path): + path.append('R') + return len(path) > 0 + + pathToStart = [] + pathToDest = [] + + dfs(root, startValue, pathToStart) + dfs(root, destValue, pathToDest) + + while pathToStart and pathToDest and pathToStart[-1] == pathToDest[-1]: + pathToStart.pop() + pathToDest.pop() + + return 'U' * len(pathToStart) + ''.join(reversed(pathToDest)) diff --git a/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.cpp b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.cpp new file mode 100644 index 00000000000..5635cf0e50f --- /dev/null +++ b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + string getDirections(TreeNode* root, int startValue, int destValue) { + string path; + string pathToStart; + string pathToDest; + // Only this subtree matters. + dfs(lca(root, startValue, destValue), startValue, destValue, path, + pathToStart, pathToDest); + return string(pathToStart.length(), 'U') + pathToDest; + } + + private: + TreeNode* lca(TreeNode* root, int p, int q) { + if (root == nullptr || root->val == p || root->val == q) + return root; + TreeNode* left = lca(root->left, p, q); + TreeNode* right = lca(root->right, p, q); + if (left != nullptr && right != nullptr) + return root; + return left == nullptr ? right : left; + } + + void dfs(TreeNode* root, int p, int q, string& path, string& pathToStart, + string& pathToDest) { + if (root == nullptr) + return; + if (root->val == p) + pathToStart = path; + if (root->val == q) + pathToDest = path; + path.push_back('L'); + dfs(root->left, p, q, path, pathToStart, pathToDest); + path.pop_back(); + path.push_back('R'); + dfs(root->right, p, q, path, pathToStart, pathToDest); + path.pop_back(); + } +}; diff --git a/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.java b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.java new file mode 100644 index 00000000000..effd3114fe1 --- /dev/null +++ b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.java @@ -0,0 +1,33 @@ +class Solution { + public String getDirections(TreeNode root, int startValue, int destValue) { + // Only this subtree matters. + dfs(lca(root, startValue, destValue), startValue, destValue, new StringBuilder()); + return "U".repeat(pathToStart.length()) + pathToDest; + } + + private String pathToStart = ""; + private String pathToDest = ""; + + private TreeNode lca(TreeNode root, int p, int q) { + if (root == null || root.val == p || root.val == q) + return root; + TreeNode left = lca(root.left, p, q); + TreeNode right = lca(root.right, p, q); + if (left != null && right != null) + return root; + return left == null ? right : left; + } + + private void dfs(TreeNode root, int p, int q, StringBuilder path) { + if (root == null) + return; + if (root.val == p) + pathToStart = path.toString(); + if (root.val == q) + pathToDest = path.toString(); + dfs(root.left, p, q, path.append('L')); + path.deleteCharAt(path.length() - 1); + dfs(root.right, p, q, path.append('R')); + path.deleteCharAt(path.length() - 1); + } +} diff --git a/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.py b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.py new file mode 100644 index 00000000000..1f04ceb5c8e --- /dev/null +++ b/solutions/2096. Step-By-Step Directions From a Binary Tree Node to Another/2096.py @@ -0,0 +1,27 @@ +class Solution: + def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str: + def lca(root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root or root.val in (startValue, destValue): + return root + left = lca(root.left) + right = lca(root.right) + if left and right: + return root + return left or right + + def dfs(root: Optional[TreeNode], path: List[chr]) -> None: + if not root: + return + if root.val == startValue: + self.pathToStart = ''.join(path) + if root.val == destValue: + self.pathToDest = ''.join(path) + path.append('L') + dfs(root.left, path) + path.pop() + path.append('R') + dfs(root.right, path) + path.pop() + + dfs(lca(root), []) # Only this subtree matters. + return 'U' * len(self.pathToStart) + ''.join(self.pathToDest) diff --git a/solutions/2097. Valid Arrangement of Pairs/2097.cpp b/solutions/2097. Valid Arrangement of Pairs/2097.cpp new file mode 100644 index 00000000000..c1039e17026 --- /dev/null +++ b/solutions/2097. Valid Arrangement of Pairs/2097.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + vector> validArrangement(vector>& pairs) { + vector> ans; + unordered_map> graph; + unordered_map outDegree; + unordered_map inDegrees; + + for (const vector& pair : pairs) { + const int start = pair[0]; + const int end = pair[1]; + graph[start].push(end); + ++outDegree[start]; + ++inDegrees[end]; + } + + const int startNode = getStartNode(graph, outDegree, inDegrees, pairs); + euler(graph, startNode, ans); + reverse(ans.begin(), ans.end()); + return ans; + } + + private: + int getStartNode(const unordered_map>& graph, + unordered_map& outDegree, + unordered_map& inDegrees, + const vector>& pairs) { + for (const auto& [u, _] : graph) + if (outDegree[u] - inDegrees[u] == 1) + return u; + return pairs[0][0]; // Arbitrarily choose a node. + } + + void euler(unordered_map>& graph, int u, + vector>& ans) { + auto& stack = graph[u]; + while (!stack.empty()) { + const int v = stack.top(); + stack.pop(); + euler(graph, v, ans); + ans.push_back({u, v}); + } + } +}; diff --git a/solutions/2097. Valid Arrangement of Pairs/2097.java b/solutions/2097. Valid Arrangement of Pairs/2097.java new file mode 100644 index 00000000000..0691c2c950c --- /dev/null +++ b/solutions/2097. Valid Arrangement of Pairs/2097.java @@ -0,0 +1,39 @@ +class Solution { + public int[][] validArrangement(int[][] pairs) { + List ans = new ArrayList<>(); + Map> graph = new HashMap<>(); + Map outDegree = new HashMap<>(); + Map inDegrees = new HashMap<>(); + + for (int[] pair : pairs) { + final int start = pair[0]; + final int end = pair[1]; + graph.putIfAbsent(start, new ArrayDeque<>()); + graph.get(start).push(end); + outDegree.merge(start, 1, Integer::sum); + inDegrees.merge(end, 1, Integer::sum); + } + + final int startNode = getStartNode(graph, outDegree, inDegrees, pairs); + euler(graph, startNode, ans); + Collections.reverse(ans); + return ans.stream().toArray(int[][] ::new); + } + + private int getStartNode(Map> graph, Map outDegree, + Map inDegrees, int[][] pairs) { + for (final int u : graph.keySet()) + if (outDegree.getOrDefault(u, 0) - inDegrees.getOrDefault(u, 0) == 1) + return u; + return pairs[0][0]; // Arbitrarily choose a node. + } + + private void euler(Map> graph, int u, List ans) { + Deque stack = graph.get(u); + while (stack != null && !stack.isEmpty()) { + final int v = stack.pop(); + euler(graph, v, ans); + ans.add(new int[] {u, v}); + } + } +} diff --git a/solutions/2097. Valid Arrangement of Pairs/2097.py b/solutions/2097. Valid Arrangement of Pairs/2097.py new file mode 100644 index 00000000000..361c9aaf001 --- /dev/null +++ b/solutions/2097. Valid Arrangement of Pairs/2097.py @@ -0,0 +1,27 @@ +class Solution: + def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]: + ans = [] + graph = collections.defaultdict(list) + outDegree = collections.Counter() + inDegrees = collections.Counter() + + for start, end in pairs: + graph[start].append(end) + outDegree[start] += 1 + inDegrees[end] += 1 + + def getStartNode() -> int: + for u in graph.keys(): + if outDegree[u] - inDegrees[u] == 1: + return u + return pairs[0][0] # Arbitrarily choose a node. + + def euler(u: int) -> None: + stack = graph[u] + while stack: + v = stack.pop() + euler(v) + ans.append([u, v]) + + euler(getStartNode()) + return ans[::-1] diff --git a/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.cpp b/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.cpp new file mode 100644 index 00000000000..ab9f069a929 --- /dev/null +++ b/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + long long largestEvenSum(vector& nums, int k) { + ranges::sort(nums); + long sum = accumulate(nums.end() - k, nums.end(), 0L); + if (sum % 2 == 0) + return sum; + + int minOdd = -1; + int minEven = -1; + int maxOdd = -1; + int maxEven = -1; + + for (int i = nums.size() - 1; i + k >= nums.size(); --i) + if (nums[i] % 2 == 1) + minOdd = nums[i]; + else + minEven = nums[i]; + + for (int i = 0; i + k < nums.size(); ++i) + if (nums[i] % 2 == 1) + maxOdd = nums[i]; + else + maxEven = nums[i]; + + long ans = -1; + + if (maxEven >= 0 && minOdd >= 0) + ans = max(ans, sum + maxEven - minOdd); + if (maxOdd >= 0 && minEven >= 0) + ans = max(ans, sum + maxOdd - minEven); + return ans; + } +}; diff --git a/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.java b/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.java new file mode 100644 index 00000000000..ccab0b511bb --- /dev/null +++ b/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.java @@ -0,0 +1,36 @@ +class Solution { + public long largestEvenSum(int[] nums, int k) { + Arrays.sort(nums); + + long sum = 0; + int minOdd = -1; + int minEven = -1; + int maxOdd = -1; + int maxEven = -1; + + for (int i = nums.length - 1; i + k >= nums.length; --i) { + sum += nums[i]; + if (nums[i] % 2 == 1) + minOdd = nums[i]; + else + minEven = nums[i]; + } + + if (sum % 2 == 0) + return sum; + + for (int i = 0; i + k < nums.length; ++i) + if (nums[i] % 2 == 1) + maxOdd = nums[i]; + else + maxEven = nums[i]; + + long ans = -1; + + if (maxEven >= 0 && minOdd >= 0) + ans = Math.max(ans, sum + maxEven - minOdd); + if (maxOdd >= 0 && minEven >= 0) + ans = Math.max(ans, sum + maxOdd - minEven); + return ans; + } +} diff --git a/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.py b/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.py new file mode 100644 index 00000000000..ca85f90d8b2 --- /dev/null +++ b/solutions/2098. Subsequence of Size K With the Largest Even Sum/2098.py @@ -0,0 +1,31 @@ +class Solution: + def largestEvenSum(self, nums: List[int], k: int) -> int: + nums.sort() + summ = sum(nums[-k:]) + if summ % 2 == 0: + return summ + + minOdd = -1 + minEven = -1 + maxOdd = -1 + maxEven = -1 + + for i in range(len(nums) - 1, len(nums) - k - 1, -1): + if nums[i] & 1: + minOdd = nums[i] + else: + minEven = nums[i] + + for i in range(len(nums) - k): + if nums[i] & 1: + maxOdd = nums[i] + else: + maxEven = nums[i] + + ans = -1 + + if maxEven >= 0 and minOdd >= 0: + ans = max(ans, summ + maxEven - minOdd) + if maxOdd >= 0 and minEven >= 0: + ans = max(ans, summ + maxOdd - minEven) + return ans diff --git a/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.cpp b/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.cpp new file mode 100644 index 00000000000..7e0c5e01ec9 --- /dev/null +++ b/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector maxSubsequence(vector& nums, int k) { + vector ans; + vector A(nums); + nth_element(A.begin(), A.end() - k, A.end()); + const int threshold = A[A.size() - k]; + const int larger = + ranges::count_if(nums, [&](int num) { return num > threshold; }); + int equal = k - larger; + + for (const int num : nums) + if (num > threshold) { + ans.push_back(num); + } else if (num == threshold && equal) { + ans.push_back(num); + --equal; + } + + return ans; + } +}; diff --git a/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.java b/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.java new file mode 100644 index 00000000000..e77fb5381a0 --- /dev/null +++ b/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.java @@ -0,0 +1,21 @@ +class Solution { + public int[] maxSubsequence(int[] nums, int k) { + int[] ans = new int[k]; + int[] A = nums.clone(); + Arrays.sort(A); + final int threshold = A[A.length - k]; + final int larger = (int) Arrays.stream(nums).filter(num -> num > threshold).count(); + int equal = k - larger; + + int i = 0; + for (final int num : nums) + if (num > threshold) { + ans[i++] = num; + } else if (num == threshold && equal > 0) { + ans[i++] = num; + --equal; + } + + return ans; + } +} diff --git a/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.py b/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.py new file mode 100644 index 00000000000..3de572e17c1 --- /dev/null +++ b/solutions/2099. Find Subsequence of Length K With the Largest Sum/2099.py @@ -0,0 +1,15 @@ +class Solution: + def maxSubsequence(self, nums: List[int], k: int) -> List[int]: + ans = [] + threshold = sorted(nums)[-k] + larger = sum(num > threshold for num in nums) + equal = k - larger + + for num in nums: + if num > threshold: + ans.append(num) + elif num == threshold and equal: + ans.append(num) + equal -= 1 + + return ans diff --git a/solutions/21. Merge Two Sorted Lists/21.cpp b/solutions/21. Merge Two Sorted Lists/21.cpp new file mode 100644 index 00000000000..bd92e551328 --- /dev/null +++ b/solutions/21. Merge Two Sorted Lists/21.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + if (!list1 || !list2) + return list1 ? list1 : list2; + if (list1->val > list2->val) + swap(list1, list2); + list1->next = mergeTwoLists(list1->next, list2); + return list1; + } +}; diff --git a/solutions/21. Merge Two Sorted Lists/21.java b/solutions/21. Merge Two Sorted Lists/21.java new file mode 100644 index 00000000000..9db9c42e8f7 --- /dev/null +++ b/solutions/21. Merge Two Sorted Lists/21.java @@ -0,0 +1,13 @@ +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + if (list1 == null || list2 == null) + return list1 == null ? list2 : list1; + if (list1.val > list2.val) { + ListNode temp = list1; + list1 = list2; + list2 = temp; + } + list1.next = mergeTwoLists(list1.next, list2); + return list1; + } +} diff --git a/solutions/21. Merge Two Sorted Lists/21.py b/solutions/21. Merge Two Sorted Lists/21.py new file mode 100644 index 00000000000..9a2ef77976f --- /dev/null +++ b/solutions/21. Merge Two Sorted Lists/21.py @@ -0,0 +1,8 @@ +class Solution: + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: + if not list1 or not list2: + return list1 if list1 else list2 + if list1.val > list2.val: + list1, list2 = list2, list1 + list1.next = self.mergeTwoLists(list1.next, list2) + return list1 diff --git a/solutions/210. Course Schedule II/210-2.cpp b/solutions/210. Course Schedule II/210-2.cpp new file mode 100644 index 00000000000..4eca6c43cd4 --- /dev/null +++ b/solutions/210. Course Schedule II/210-2.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector findOrder(int numCourses, vector>& prerequisites) { + vector ans; + vector> graph(numCourses); + vector inDegrees(numCourses); + queue q; + + // Build the graph. + for (const vector& prerequisite : prerequisites) { + const int u = prerequisite[1]; + const int v = prerequisite[0]; + graph[u].push_back(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + for (int i = 0; i < numCourses; ++i) + if (inDegrees[i] == 0) + q.push(i); + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + ans.push_back(u); + for (const int v : graph[u]) + if (--inDegrees[v] == 0) + q.push(v); + } + + return ans.size() == numCourses ? ans : vector(); + } +}; diff --git a/solutions/210. Course Schedule II/210-2.java b/solutions/210. Course Schedule II/210-2.java new file mode 100644 index 00000000000..28a8741bfb1 --- /dev/null +++ b/solutions/210. Course Schedule II/210-2.java @@ -0,0 +1,36 @@ +class Solution { + public int[] findOrder(int numCourses, int[][] prerequisites) { + List ans = new ArrayList<>(); + List[] graph = new List[numCourses]; + int[] inDegrees = new int[numCourses]; + + for (int i = 0; i < numCourses; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph. + for (int[] prerequisite : prerequisites) { + final int u = prerequisite[1]; + final int v = prerequisite[0]; + graph[u].add(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + Queue q = IntStream.range(0, numCourses) + .filter(i -> inDegrees[i] == 0) + .boxed() + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + final int u = q.poll(); + ans.add(u); + for (final int v : graph[u]) + if (--inDegrees[v] == 0) + q.offer(v); + } + + if (ans.size() == numCourses) + return ans.stream().mapToInt(Integer::intValue).toArray(); + return new int[] {}; + } +} diff --git a/solutions/210. Course Schedule II/210-2.py b/solutions/210. Course Schedule II/210-2.py new file mode 100644 index 00000000000..5f1f02969dc --- /dev/null +++ b/solutions/210. Course Schedule II/210-2.py @@ -0,0 +1,24 @@ +class Solution: + def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: + ans = [] + graph = [[] for _ in range(numCourses)] + inDegrees = [0] * numCourses + q = collections.deque() + + # Build the graph. + for v, u in prerequisites: + graph[u].append(v) + inDegrees[v] += 1 + + # Perform topological sorting. + q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) + + while q: + u = q.popleft() + ans.append(u) + for v in graph[u]: + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + + return ans if len(ans) == numCourses else [] diff --git a/solutions/210. Course Schedule II/210.cpp b/solutions/210. Course Schedule II/210.cpp new file mode 100644 index 00000000000..541d58588ce --- /dev/null +++ b/solutions/210. Course Schedule II/210.cpp @@ -0,0 +1,41 @@ +enum class State { kInit, kVisiting, kVisited }; + +class Solution { + public: + vector findOrder(int numCourses, vector>& prerequisites) { + vector ans; + vector> graph(numCourses); + vector states(numCourses); + + for (const vector& prerequisite : prerequisites) { + const int u = prerequisite[1]; + const int v = prerequisite[0]; + graph[u].push_back(v); + } + + for (int i = 0; i < numCourses; ++i) + if (hasCycle(graph, i, states, ans)) + return {}; + + reverse(ans.begin(), ans.end()); + return ans; + } + + private: + bool hasCycle(const vector>& graph, int u, vector& states, + vector& ans) { + if (states[u] == State::kVisiting) + return true; + if (states[u] == State::kVisited) + return false; + + states[u] = State::kVisiting; + for (const int v : graph[u]) + if (hasCycle(graph, v, states, ans)) + return true; + states[u] = State::kVisited; + ans.push_back(u); + + return false; + } +}; diff --git a/solutions/210. Course Schedule II/210.java b/solutions/210. Course Schedule II/210.java new file mode 100644 index 00000000000..522a3261cb1 --- /dev/null +++ b/solutions/210. Course Schedule II/210.java @@ -0,0 +1,40 @@ +enum State { kInit, kVisiting, kVisited } + +class Solution { + public int[] findOrder(int numCourses, int[][] prerequisites) { + Deque ans = new ArrayDeque<>(); + List[] graph = new List[numCourses]; + State[] states = new State[numCourses]; + + for (int i = 0; i < numCourses; ++i) + graph[i] = new ArrayList<>(); + + for (int[] prerequisite : prerequisites) { + final int u = prerequisite[1]; + final int v = prerequisite[0]; + graph[u].add(v); + } + + for (int i = 0; i < numCourses; ++i) + if (hasCycle(graph, i, states, ans)) + return new int[] {}; + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private boolean hasCycle(List[] graph, int u, State[] states, Deque ans) { + if (states[u] == State.kVisiting) + return true; + if (states[u] == State.kVisited) + return false; + + states[u] = State.kVisiting; + for (final int v : graph[u]) + if (hasCycle(graph, v, states, ans)) + return true; + states[u] = State.kVisited; + ans.addFirst(u); + + return false; + } +} diff --git a/solutions/210. Course Schedule II/210.py b/solutions/210. Course Schedule II/210.py new file mode 100644 index 00000000000..9861d4b8bb0 --- /dev/null +++ b/solutions/210. Course Schedule II/210.py @@ -0,0 +1,36 @@ +from enum import Enum + + +class State(Enum): + kInit = 0 + kVisiting = 1 + kVisited = 2 + + +class Solution: + def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: + ans = [] + graph = [[] for _ in range(numCourses)] + states = [State.kInit] * numCourses + + for v, u in prerequisites: + graph[u].append(v) + + def hasCycle(u: int) -> bool: + if states[u] == State.kVisiting: + return True + if states[u] == State.kVisited: + return False + + states[u] = State.kVisiting + if any(hasCycle(v) for v in graph[u]): + return True + states[u] = State.kVisited + ans.append(u) + + return False + + if any(hasCycle(i) for i in range(numCourses)): + return [] + + return ans[::-1] diff --git a/solutions/2100. Find Good Days to Rob the Bank/2100.cpp b/solutions/2100. Find Good Days to Rob the Bank/2100.cpp new file mode 100644 index 00000000000..54e9db7303d --- /dev/null +++ b/solutions/2100. Find Good Days to Rob the Bank/2100.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector goodDaysToRobBank(vector& security, int time) { + const int n = security.size(); + vector ans; + // dec[i] := the number of continuous decreasing numbers before i + vector dec(n); + // inc[i] := the number of continuous increasing numbers after i + vector inc(n); + + for (int i = 1; i < n; ++i) + if (security[i - 1] >= security[i]) + dec[i] = dec[i - 1] + 1; + + for (int i = n - 2; i >= 0; --i) + if (security[i] <= security[i + 1]) + inc[i] = inc[i + 1] + 1; + + for (int i = 0; i < n; ++i) + if (dec[i] >= time && inc[i] >= time) + ans.push_back(i); + + return ans; + } +}; diff --git a/solutions/2100. Find Good Days to Rob the Bank/2100.java b/solutions/2100. Find Good Days to Rob the Bank/2100.java new file mode 100644 index 00000000000..a815a55853a --- /dev/null +++ b/solutions/2100. Find Good Days to Rob the Bank/2100.java @@ -0,0 +1,24 @@ +class Solution { + public List goodDaysToRobBank(int[] security, int time) { + final int n = security.length; + List ans = new ArrayList<>(); + // dec[i] := the number of continuous decreasing numbers before i + int[] dec = new int[n]; + // inc[i] := the number of continuous increasing numbers after i + int[] inc = new int[n]; + + for (int i = 1; i < n; ++i) + if (security[i - 1] >= security[i]) + dec[i] = dec[i - 1] + 1; + + for (int i = n - 2; i >= 0; --i) + if (security[i] <= security[i + 1]) + inc[i] = inc[i + 1] + 1; + + for (int i = 0; i < n; ++i) + if (dec[i] >= time && inc[i] >= time) + ans.add(i); + + return ans; + } +} diff --git a/solutions/2100. Find Good Days to Rob the Bank/2100.py b/solutions/2100. Find Good Days to Rob the Bank/2100.py new file mode 100644 index 00000000000..ce172db27dc --- /dev/null +++ b/solutions/2100. Find Good Days to Rob the Bank/2100.py @@ -0,0 +1,16 @@ +class Solution: + def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]: + n = len(security) + dec = [0] * n # dec[i] := the number of continuous decreasing numbers before i + inc = [0] * n # inc[i] := the number of continuous increasing numbers after i + + for i in range(1, n): + if security[i - 1] >= security[i]: + dec[i] = dec[i - 1] + 1 + + for i in range(n - 2, -1, -1): + if security[i] <= security[i + 1]: + inc[i] = inc[i + 1] + 1 + + return [i for i, (a, b) in enumerate(zip(dec, inc)) + if a >= time and b >= time] diff --git a/solutions/2101. Detonate the Maximum Bombs/2101.cpp b/solutions/2101. Detonate the Maximum Bombs/2101.cpp new file mode 100644 index 00000000000..6c399cdf877 --- /dev/null +++ b/solutions/2101. Detonate the Maximum Bombs/2101.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int maximumDetonation(vector>& bombs) { + const int n = bombs.size(); + size_t ans = 0; + vector> graph(n); + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + const long ri = bombs[i][2]; + if (ri * ri >= squaredDist(bombs, i, j)) + graph[i].push_back(j); + } + } + + for (int i = 0; i < n; ++i) { + unordered_set seen{i}; + dfs(graph, i, seen); + ans = max(ans, seen.size()); + } + + return ans; + } + + private: + void dfs(const vector>& graph, int u, unordered_set& seen) { + for (const int v : graph[u]) { + if (seen.contains(v)) + continue; + seen.insert(v); + dfs(graph, v, seen); + } + } + + long squaredDist(const vector>& bombs, int i, int j) { + return static_cast(bombs[i][0] - bombs[j][0]) * + (bombs[i][0] - bombs[j][0]) + + static_cast(bombs[i][1] - bombs[j][1]) * + (bombs[i][1] - bombs[j][1]); + } +}; diff --git a/solutions/2101. Detonate the Maximum Bombs/2101.java b/solutions/2101. Detonate the Maximum Bombs/2101.java new file mode 100644 index 00000000000..a399872b192 --- /dev/null +++ b/solutions/2101. Detonate the Maximum Bombs/2101.java @@ -0,0 +1,41 @@ +class Solution { + public int maximumDetonation(int[][] bombs) { + final int n = bombs.length; + int ans = 0; + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + final long ri = bombs[i][2]; + if (ri * ri >= squaredDist(bombs, i, j)) + graph[i].add(j); + } + } + + for (int i = 0; i < n; ++i) { + Set seen = new HashSet<>(Arrays.asList(i)); + dfs(graph, i, seen); + ans = Math.max(ans, seen.size()); + } + + return ans; + } + + private void dfs(List[] graph, int u, Set seen) { + for (final int v : graph[u]) { + if (seen.contains(v)) + continue; + seen.add(v); + dfs(graph, v, seen); + } + } + private long squaredDist(int[][] bombs, int i, int j) { + return (long) (bombs[i][0] - bombs[j][0]) * (bombs[i][0] - bombs[j][0]) + + (long) (bombs[i][1] - bombs[j][1]) * (bombs[i][1] - bombs[j][1]); + }; +} diff --git a/solutions/2101. Detonate the Maximum Bombs/2101.py b/solutions/2101. Detonate the Maximum Bombs/2101.py new file mode 100644 index 00000000000..8a045559f5f --- /dev/null +++ b/solutions/2101. Detonate the Maximum Bombs/2101.py @@ -0,0 +1,26 @@ +class Solution: + def maximumDetonation(self, bombs: List[List[int]]) -> int: + n = len(bombs) + ans = 0 + graph = [[] for _ in range(n)] + + for i, (xi, yi, ri) in enumerate(bombs): + for j, (xj, yj, rj) in enumerate(bombs): + if i == j: + continue + if ri**2 >= (xi - xj)**2 + (yi - yj)**2: + graph[i].append(j) + + def dfs(u: int, seen: Set[int]) -> None: + for v in graph[u]: + if v in seen: + continue + seen.add(v) + dfs(v, seen) + + for i in range(n): + seen = set([i]) + dfs(i, seen) + ans = max(ans, len(seen)) + + return ans diff --git a/solutions/2102. Sequentially Ordinal Rank Tracker/2102.cpp b/solutions/2102. Sequentially Ordinal Rank Tracker/2102.cpp new file mode 100644 index 00000000000..670ba76e70e --- /dev/null +++ b/solutions/2102. Sequentially Ordinal Rank Tracker/2102.cpp @@ -0,0 +1,45 @@ +struct Location { + string name; + int score; + Location(const string& name, int score) : name(move(name)), score(score) {} +}; + +class SORTracker { + public: + void add(const string& name, int score) { + l.emplace(name, score); + if (l.size() > k + 1) { + const Location location = l.top(); + l.pop(); + r.emplace(location.name, location.score); + } + } + + string get() { + const string name = l.top().name; + if (!r.empty()) { + const Location location = r.top(); + r.pop(); + l.emplace(location.name, location.score); + } + ++k; + return name; + } + + private: + struct CompareLeftMinHeap { + bool operator()(const Location& a, const Location& b) { + return a.score == b.score ? a.name < b.name : a.score > b.score; + } + }; + + struct CompareRightMaxHeap { + bool operator()(const Location& a, const Location& b) { + return a.score == b.score ? a.name > b.name : a.score < b.score; + } + }; + + priority_queue, CompareLeftMinHeap> l; + priority_queue, CompareRightMaxHeap> r; + int k = 0; +}; diff --git a/solutions/2102. Sequentially Ordinal Rank Tracker/2102.java b/solutions/2102. Sequentially Ordinal Rank Tracker/2102.java new file mode 100644 index 00000000000..04a128ad5d5 --- /dev/null +++ b/solutions/2102. Sequentially Ordinal Rank Tracker/2102.java @@ -0,0 +1,30 @@ +class Location { + public String name; + public int score; + public Location(String name, int score) { + this.name = name; + this.score = score; + } +} + +class SORTracker { + public void add(String name, int score) { + l.offer(new Location(name, score)); + if (l.size() > k + 1) + r.offer(l.poll()); + } + + public String get() { + final String name = l.peek().name; + if (!r.isEmpty()) + l.offer(r.poll()); + ++k; + return name; + } + + private Queue l = new PriorityQueue<>( + (a, b) -> a.score == b.score ? -a.name.compareTo(b.name) : a.score - b.score); + private Queue r = new PriorityQueue<>( + (a, b) -> a.score == b.score ? a.name.compareTo(b.name) : b.score - a.score); + private int k; +} diff --git a/solutions/2102. Sequentially Ordinal Rank Tracker/2102.py b/solutions/2102. Sequentially Ordinal Rank Tracker/2102.py new file mode 100644 index 00000000000..37ebfa2d730 --- /dev/null +++ b/solutions/2102. Sequentially Ordinal Rank Tracker/2102.py @@ -0,0 +1,30 @@ +class Location: + def __init__(self, name: str, score: int): + self.name = name + self.score = score + + def __lt__(self, location): + if self.score == location.score: + return self.name > location.name + return self.score < location.score + + +class SORTracker: + def __init__(self): + self.l = [] + self.r = [] + self.k = 0 the number of times get() called + + def add(self, name: str, score: int) -> None: + heapq.heappush(self.l, Location(name, score)) + if len(self.l) > self.k + 1: + location = heapq.heappop(self.l) + heapq.heappush(self.r, (-location.score, location.name)) + + def get(self) -> str: + name = self.l[0].name + if self.r: + topScore, topName = heapq.heappop(self.r) + heapq.heappush(self.l, Location(topName, -topScore)) + self.k += 1 + return name diff --git a/solutions/2103. Rings and Rods/2103.cpp b/solutions/2103. Rings and Rods/2103.cpp new file mode 100644 index 00000000000..fc7959d6745 --- /dev/null +++ b/solutions/2103. Rings and Rods/2103.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int countPoints(string rings) { + vector colors(10); + + for (int i = 0; i < rings.length(); i += 2) { + const int c = rings[i]; + const int color = c == 'R' ? 1 : c == 'G' ? 2 : 4; + colors[rings[i + 1] - '0'] |= color; + } + + return ranges::count(colors, 7); + } +}; diff --git a/solutions/2103. Rings and Rods/2103.java b/solutions/2103. Rings and Rods/2103.java new file mode 100644 index 00000000000..cbc99950c28 --- /dev/null +++ b/solutions/2103. Rings and Rods/2103.java @@ -0,0 +1,13 @@ +class Solution { + public int countPoints(String rings) { + int[] colors = new int[10]; + + for (int i = 0; i < rings.length(); i += 2) { + final char c = rings.charAt(i); + final int color = c == 'R' ? 1 : c == 'G' ? 2 : 4; + colors[rings.charAt(i + 1) - '0'] |= color; + } + + return (int) Arrays.stream(colors).filter(c -> c == 7).count(); + } +} diff --git a/solutions/2103. Rings and Rods/2103.py b/solutions/2103. Rings and Rods/2103.py new file mode 100644 index 00000000000..1500c6794ca --- /dev/null +++ b/solutions/2103. Rings and Rods/2103.py @@ -0,0 +1,9 @@ +class Solution: + def countPoints(self, rings: str) -> int: + colors = [0] * 10 + + for c, num in zip(rings[::2], rings[1::2]): + color = 1 if c == 'R' else 2 if c == 'G' else 4 + colors[int(num)] |= color + + return sum(color == 7 for color in colors) diff --git a/solutions/2104. Sum of Subarray Ranges/2104.cpp b/solutions/2104. Sum of Subarray Ranges/2104.cpp new file mode 100644 index 00000000000..635b8bacbb9 --- /dev/null +++ b/solutions/2104. Sum of Subarray Ranges/2104.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + long long subArrayRanges(vector& nums) { + return subarraySum(nums, less()) - subarraySum(nums, greater<>()); + } + + private: + long subarraySum(const vector& A, const function& op) { + const int n = A.size(); + long res = 0; + vector prev(n, -1); + vector next(n, n); + stack stack; + + for (int i = 0; i < n; ++i) { + while (!stack.empty() && op(A[stack.top()], A[i])) { + const int index = stack.top(); + stack.pop(); + next[index] = i; + } + if (!stack.empty()) + prev[i] = stack.top(); + stack.push(i); + } + + for (int i = 0; i < n; ++i) + res += static_cast(A[i]) * (i - prev[i]) * (next[i] - i); + + return res; + } +}; diff --git a/solutions/2104. Sum of Subarray Ranges/2104.java b/solutions/2104. Sum of Subarray Ranges/2104.java new file mode 100644 index 00000000000..ffe13f8f1f1 --- /dev/null +++ b/solutions/2104. Sum of Subarray Ranges/2104.java @@ -0,0 +1,37 @@ +class Solution { + public long subArrayRanges(int[] nums) { + return subarraySum(nums, '<') - subarraySum(nums, '>'); + } + + private long subarraySum(int[] A, char op) { + final int n = A.length; + long res = 0; + int[] prev = new int[n]; + int[] next = new int[n]; + Deque stack = new ArrayDeque<>(); + + Arrays.fill(prev, -1); + Arrays.fill(next, n); + + for (int i = 0; i < n; ++i) { + while (!stack.isEmpty() && func(op, A[stack.peek()], A[i])) { + final int index = stack.pop(); + next[index] = i; + } + if (!stack.isEmpty()) + prev[i] = stack.peek(); + stack.push(i); + } + + for (int i = 0; i < n; ++i) + res += (long) A[i] * (i - prev[i]) * (next[i] - i); + + return res; + } + + private boolean func(char op, int a, int b) { + if (op == '<') + return a < b; + return a > b; + } +} diff --git a/solutions/2104. Sum of Subarray Ranges/2104.py b/solutions/2104. Sum of Subarray Ranges/2104.py new file mode 100644 index 00000000000..bfb257fdc4f --- /dev/null +++ b/solutions/2104. Sum of Subarray Ranges/2104.py @@ -0,0 +1,24 @@ +class Solution: + def subArrayRanges(self, nums: List[int]) -> int: + n = len(nums) + + def sumSubarray(A: List[int], op): + res = 0 + prev = [-1] * n + next = [n] * n + stack = [] + + for i, a in enumerate(A): + while stack and op(A[stack[-1]], a): + index = stack.pop() + next[index] = i + if stack: + prev[i] = stack[-1] + stack.append(i) + + for i, a in enumerate(A): + res += a * (i - prev[i]) * (next[i] - i) + + return res + + return sumSubarray(nums, operator.lt) - sumSubarray(nums, operator.gt) diff --git a/solutions/2105. Watering Plants II/2105.cpp b/solutions/2105. Watering Plants II/2105.cpp new file mode 100644 index 00000000000..293c7d8ac88 --- /dev/null +++ b/solutions/2105. Watering Plants II/2105.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minimumRefill(vector& plants, int capacityA, int capacityB) { + int ans = 0; + int i = 0; + int j = plants.size() - 1; + int canA = capacityA; + int canB = capacityB; + + while (i < j) { + ans += (canA < plants[i]) + (canB < plants[j]); + if (canA < plants[i]) + canA = capacityA; + if (canB < plants[j]) + canB = capacityB; + canA -= plants[i++]; + canB -= plants[j--]; + } + + return ans + (i == j && max(canA, canB) < plants[i]); + } +}; diff --git a/solutions/2105. Watering Plants II/2105.java b/solutions/2105. Watering Plants II/2105.java new file mode 100644 index 00000000000..2671cf2ebe3 --- /dev/null +++ b/solutions/2105. Watering Plants II/2105.java @@ -0,0 +1,21 @@ +class Solution { + public int minimumRefill(int[] plants, int capacityA, int capacityB) { + int ans = 0; + int i = 0; + int j = plants.length - 1; + int canA = capacityA; + int canB = capacityB; + + while (i < j) { + ans += (canA < plants[i] ? 1 : 0) + (canB < plants[j] ? 1 : 0); + if (canA < plants[i]) + canA = capacityA; + if (canB < plants[j]) + canB = capacityB; + canA -= plants[i++]; + canB -= plants[j--]; + } + + return ans + (i == j && Math.max(canA, canB) < plants[i] ? 1 : 0); + } +} diff --git a/solutions/2105. Watering Plants II/2105.py b/solutions/2105. Watering Plants II/2105.py new file mode 100644 index 00000000000..0b36636b460 --- /dev/null +++ b/solutions/2105. Watering Plants II/2105.py @@ -0,0 +1,20 @@ +class Solution: + def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int: + ans = 0 + i = 0 + j = len(plants) - 1 + canA = capacityA + canB = capacityB + + while i < j: + ans += (canA < plants[i]) + (canB < plants[j]) + if canA < plants[i]: + canA = capacityA + if canB < plants[j]: + canB = capacityB + canA -= plants[i] + canB -= plants[j] + i += 1 + j -= 1 + + return ans + (i == j and max(canA, canB) < plants[i]) diff --git a/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.cpp b/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.cpp new file mode 100644 index 00000000000..22094257b05 --- /dev/null +++ b/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int maxTotalFruits(vector>& fruits, int startPos, int k) { + const int maxRight = max(startPos, fruits.back()[0]); + int ans = 0; + vector amounts(1 + maxRight); + vector prefix(2 + maxRight); + + for (const vector& f : fruits) + amounts[f[0]] = f[1]; + + partial_sum(amounts.begin(), amounts.end(), prefix.begin() + 1); + + auto getFruits = [&](int leftSteps, int rightSteps) { + const int l = max(0, startPos - leftSteps); + const int r = min(maxRight, startPos + rightSteps); + return prefix[r + 1] - prefix[l]; + }; + + // Go right first. + const int maxRightSteps = min(maxRight - startPos, k); + for (int rightSteps = 0; rightSteps <= maxRightSteps; ++rightSteps) { + const int leftSteps = max(0, k - 2 * rightSteps); // Turn left + ans = max(ans, getFruits(leftSteps, rightSteps)); + } + + // Go left first. + const int maxLeftSteps = min(startPos, k); + for (int leftSteps = 0; leftSteps <= maxLeftSteps; ++leftSteps) { + const int rightSteps = max(0, k - 2 * leftSteps); // Turn right + ans = max(ans, getFruits(leftSteps, rightSteps)); + } + + return ans; + } +}; diff --git a/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.java b/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.java new file mode 100644 index 00000000000..8e771547ec4 --- /dev/null +++ b/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.java @@ -0,0 +1,36 @@ +class Solution { + public int maxTotalFruits(int[][] fruits, int startPos, int k) { + final int maxRight = Math.max(startPos, fruits[fruits.length - 1][0]); + int ans = 0; + int[] amounts = new int[1 + maxRight]; + int[] prefix = new int[2 + maxRight]; + + for (int[] f : fruits) + amounts[f[0]] = f[1]; + + for (int i = 0; i + 1 < prefix.length; ++i) + prefix[i + 1] = prefix[i] + amounts[i]; + + // Go right first. + final int maxRightSteps = Math.min(maxRight - startPos, k); + for (int rightSteps = 0; rightSteps <= maxRightSteps; ++rightSteps) { + final int leftSteps = Math.max(0, k - 2 * rightSteps); // Turn left + ans = Math.max(ans, getFruits(startPos, maxRight, leftSteps, rightSteps, prefix)); + } + + // Go left first. + final int maxLeftSteps = Math.min(startPos, k); + for (int leftSteps = 0; leftSteps <= maxLeftSteps; ++leftSteps) { + final int rightSteps = Math.max(0, k - 2 * leftSteps); // Turn right + ans = Math.max(ans, getFruits(startPos, maxRight, leftSteps, rightSteps, prefix)); + } + + return ans; + } + + private int getFruits(int startPos, int maxRight, int leftSteps, int rightSteps, int[] prefix) { + final int l = Math.max(0, startPos - leftSteps); + final int r = Math.min(maxRight, startPos + rightSteps); + return prefix[r + 1] - prefix[l]; + } +} diff --git a/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.py b/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.py new file mode 100644 index 00000000000..b35fc3a9446 --- /dev/null +++ b/solutions/2106. Maximum Fruits Harvested After at Most K Steps/2106.py @@ -0,0 +1,25 @@ +class Solution: + def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: + ans = 0 + maxRight = max(startPos, fruits[-1][0]) + amounts = [0] * (1 + maxRight) + for position, amount in fruits: + amounts[position] = amount + prefix = [0] + list(itertools.accumulate(amounts)) + + def getFruits(leftSteps: int, rightSteps: int) -> int: + l = max(0, startPos - leftSteps) + r = min(maxRight, startPos + rightSteps) + return prefix[r + 1] - prefix[l] + + # Go right first. + for rightSteps in range(min(maxRight - startPos, k) + 1): + leftSteps = max(0, k - 2 * rightSteps) # Turn left + ans = max(ans, getFruits(leftSteps, rightSteps)) + + # Go left first. + for leftSteps in range(min(startPos, k) + 1): + rightSteps = max(0, k - 2 * leftSteps) # Turn right + ans = max(ans, getFruits(leftSteps, rightSteps)) + + return ans diff --git a/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.cpp b/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.cpp new file mode 100644 index 00000000000..4d52279d874 --- /dev/null +++ b/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int shareCandies(vector& candies, int k) { + int ans = 0; + unordered_map count; + + for (const int candy : candies) + ++count[candy]; + + int unique = count.size(); + + for (int i = 0; i < candies.size(); ++i) { + if (--count[candies[i]] == 0) { + count.erase(candies[i]); + --unique; + } + if (i >= k && ++count[candies[i - k]] == 1) + ++unique; + if (i >= k - 1) + ans = max(ans, unique); + } + + return ans; + } +}; diff --git a/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.java b/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.java new file mode 100644 index 00000000000..ef634a12b6f --- /dev/null +++ b/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.java @@ -0,0 +1,27 @@ +class Solution { + public int shareCandies(int[] candies, int k) { + int ans = 0; + Map count = new HashMap<>(); + + for (final int candy : candies) + count.merge(candy, 1, Integer::sum); + + int unique = count.size(); + + for (int i = 0; i < candies.length; ++i) { + if (count.merge(candies[i], -1, Integer::sum) == 0) { + count.remove(candies[i]); + --unique; + } + if (i >= k) { + count.merge(candies[i - k], 1, Integer::sum); + if (count.get(candies[i - k]) == 1) + ++unique; + } + if (i >= k - 1) + ans = Math.max(ans, unique); + } + + return ans; + } +} diff --git a/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.py b/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.py new file mode 100644 index 00000000000..fb136fd4170 --- /dev/null +++ b/solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.py @@ -0,0 +1,19 @@ +class Solution: + def shareCandies(self, candies: List[int], k: int) -> int: + ans = 0 + count = collections.Counter(candies) + unique = len(count) + + for i, candy in enumerate(candies): + count[candy] -= 1 + if count[candy] == 0: + del count[candy] + unique -= 1 + if i >= k: + count[candies[i - k]] += 1 + if count[candies[i - k]] == 1: + unique += 1 + if i >= k - 1: + ans = max(ans, unique) + + return ans diff --git a/solutions/2108. Find First Palindromic String in the Array/2108.cpp b/solutions/2108. Find First Palindromic String in the Array/2108.cpp new file mode 100644 index 00000000000..4e3a35604cb --- /dev/null +++ b/solutions/2108. Find First Palindromic String in the Array/2108.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + string firstPalindrome(vector& words) { + for (const string& word : words) + if (isPalindrome(word)) + return word; + return ""; + } + + private: + bool isPalindrome(const string& s) { + int i = 0; + int j = s.length() - 1; + while (i < j) + if (s[i++] != s[j--]) + return false; + return true; + } +}; diff --git a/solutions/2108. Find First Palindromic String in the Array/2108.java b/solutions/2108. Find First Palindromic String in the Array/2108.java new file mode 100644 index 00000000000..a4de6fbc7e3 --- /dev/null +++ b/solutions/2108. Find First Palindromic String in the Array/2108.java @@ -0,0 +1,17 @@ +class Solution { + public String firstPalindrome(String[] words) { + for (final String word : words) + if (isPalindrome(word)) + return word; + return ""; + } + + private boolean isPalindrome(final String s) { + int i = 0; + int j = 0; + while (i < j) + if (s.charAt(i++) != s.charAt(j--)) + return false; + return true; + } +} diff --git a/solutions/2108. Find First Palindromic String in the Array/2108.py b/solutions/2108. Find First Palindromic String in the Array/2108.py new file mode 100644 index 00000000000..93ca183e3c7 --- /dev/null +++ b/solutions/2108. Find First Palindromic String in the Array/2108.py @@ -0,0 +1,12 @@ +class Solution: + def firstPalindrome(self, words: List[str]) -> str: + def isPalindrome(s: str) -> bool: + i = 0 + j = len(s) - 1 + while i < j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True + return next((word for word in words if isPalindrome(word)), '') diff --git a/solutions/2109. Adding Spaces to a String/2109.cpp b/solutions/2109. Adding Spaces to a String/2109.cpp new file mode 100644 index 00000000000..1dd6a329cd2 --- /dev/null +++ b/solutions/2109. Adding Spaces to a String/2109.cpp @@ -0,0 +1,4 @@ +class Solution { + public: + string addSpaces(string s, vector& spaces) {} +}; diff --git a/solutions/2109. Adding Spaces to a String/2109.java b/solutions/2109. Adding Spaces to a String/2109.java new file mode 100644 index 00000000000..c29e1c5a59c --- /dev/null +++ b/solutions/2109. Adding Spaces to a String/2109.java @@ -0,0 +1,16 @@ +class Solution { + public String addSpaces(String s, int[] spaces) { + StringBuilder sb = new StringBuilder(); + int j = 0; // spaces' index + + for (int i = 0; i < s.length(); ++i) { + if (j < spaces.length && i == spaces[j]) { + sb.append(' '); + ++j; + } + sb.append(s.charAt(i)); + } + + return sb.toString(); + } +} diff --git a/solutions/2109. Adding Spaces to a String/2109.py b/solutions/2109. Adding Spaces to a String/2109.py new file mode 100644 index 00000000000..a452795915a --- /dev/null +++ b/solutions/2109. Adding Spaces to a String/2109.py @@ -0,0 +1,12 @@ +class Solution: + def addSpaces(self, s: str, spaces: List[int]) -> str: + ans = [] + j = 0 # spaces' index + + for i, c in enumerate(s): + if j < len(spaces) and i == spaces[j]: + ans.append(' ') + j += 1 + ans.append(c) + + return ''.join(ans) diff --git a/solutions/211. Add and Search Word - Data structure design/211.cpp b/solutions/211. Add and Search Word - Data structure design/211.cpp new file mode 100644 index 00000000000..edeb2d26a4f --- /dev/null +++ b/solutions/211. Add and Search Word - Data structure design/211.cpp @@ -0,0 +1,42 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class WordDictionary { + public: + void addWord(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->isWord = true; + } + + bool search(const string& word) { + return dfs(word, 0, root); + } + + private: + shared_ptr root = make_shared(); + + bool dfs(const string& word, int s, shared_ptr node) { + if (s == word.length()) + return node->isWord; + if (word[s] != '.') { + shared_ptr next = node->children[word[s] - 'a']; + return next ? dfs(word, s + 1, next) : false; + } + + // If word[s] == '.', then search all the 26 children. + for (int i = 0; i < 26; ++i) + if (node->children[i] && dfs(word, s + 1, node->children[i])) + return true; + + return false; + } +}; diff --git a/solutions/211. Add and Search Word - Data structure design/211.java b/solutions/211. Add and Search Word - Data structure design/211.java new file mode 100644 index 00000000000..a38870ab65e --- /dev/null +++ b/solutions/211. Add and Search Word - Data structure design/211.java @@ -0,0 +1,39 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class WordDictionary { + public void addWord(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + public boolean search(String word) { + return dfs(word, 0, root); + } + + private TrieNode root = new TrieNode(); + + private boolean dfs(String word, int s, TrieNode node) { + if (s == word.length()) + return node.isWord; + if (word.charAt(s) != '.') { + TrieNode next = node.children[word.charAt(s) - 'a']; + return next == null ? false : dfs(word, s + 1, next); + } + + // If word[s] == '.', then search all the 26 children. + for (int i = 0; i < 26; ++i) + if (node.children[i] != null && dfs(word, s + 1, node.children[i])) + return true; + + return false; + } +} diff --git a/solutions/211. Add and Search Word - Data structure design/211.py b/solutions/211. Add and Search Word - Data structure design/211.py new file mode 100644 index 00000000000..2cd85644c90 --- /dev/null +++ b/solutions/211. Add and Search Word - Data structure design/211.py @@ -0,0 +1,26 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.isWord = False + + +class WordDictionary: + def __init__(self): + self.root = TrieNode() + + def addWord(self, word: str) -> None: + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + def search(self, word: str) -> bool: + return self._dfs(word, 0, self.root) + + def _dfs(self, word: str, s: int, node: TrieNode) -> bool: + if s == len(word): + return node.isWord + if word[s] != '.': + child: TrieNode = node.children.get(word[s], None) + return self._dfs(word, s + 1, child) if child else False + return any(self._dfs(word, s + 1, child) for child in node.children.values()) diff --git a/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.cpp b/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.cpp new file mode 100644 index 00000000000..2576565e4b1 --- /dev/null +++ b/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + long long getDescentPeriods(vector& prices) { + long ans = 1; // prices[0] + int dp = 1; + + for (int i = 1; i < prices.size(); ++i) { + if (prices[i] == prices[i - 1] - 1) + ++dp; + else + dp = 1; + ans += dp; + } + + return ans; + } +}; diff --git a/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.java b/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.java new file mode 100644 index 00000000000..5a22150e484 --- /dev/null +++ b/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.java @@ -0,0 +1,16 @@ +class Solution { + public long getDescentPeriods(int[] prices) { + long ans = 1; // prices[0] + int dp = 1; + + for (int i = 1; i < prices.size(); ++i) { + if (prices[i] == prices[i - 1] - 1) + ++dp; + else + dp = 1; + ans += dp; + } + + return ans; + } +} diff --git a/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.py b/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.py new file mode 100644 index 00000000000..ea35d2e8103 --- /dev/null +++ b/solutions/2110. Number of Smooth Descent Periods of a Stock/2110.py @@ -0,0 +1,13 @@ +class Solution: + def getDescentPeriods(self, prices: List[int]) -> int: + ans = 1 # prices[0] + dp = 1 + + for i in range(1, len(prices)): + if prices[i] == prices[i - 1] - 1: + dp += 1 + else: + dp = 1 + ans += dp + + return ans diff --git a/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.cpp b/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.cpp new file mode 100644 index 00000000000..6c9e50c08c1 --- /dev/null +++ b/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int kIncreasing(vector& arr, int k) { + int ans = 0; + + for (int i = 0; i < k; ++i) { + vector A; + for (int j = i; j < arr.size(); j += k) + A.push_back(arr[j]); + ans += numReplaced(A); + } + + return ans; + } + + private: + int numReplaced(const vector& A) { + vector tail; + for (const int a : A) + if (tail.empty() || tail.back() <= a) + tail.push_back(a); + else + tail[firstGreater(tail, a)] = a; + return A.size() - tail.size(); + } + + int firstGreater(const vector& A, int target) { + return ranges::upper_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.java b/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.java new file mode 100644 index 00000000000..c943c308278 --- /dev/null +++ b/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.java @@ -0,0 +1,29 @@ +class Solution { + public int kIncreasing(int[] arr, int k) { + int ans = 0; + + for (int i = 0; i < k; ++i) { + List A = new ArrayList<>(); + for (int j = i; j < arr.length; j += k) + A.add(arr[j]); + ans += numReplaced(A); + } + + return ans; + } + + private int numReplaced(List A) { + List tail = new ArrayList<>(); + for (final int a : A) + if (tail.isEmpty() || tail.get(tail.size() - 1) <= a) + tail.add(a); + else + tail.set(firstGreater(tail, a), a); + return A.size() - tail.size(); + } + + private int firstGreater(List A, int target) { + final int i = Collections.binarySearch(A, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.py b/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.py new file mode 100644 index 00000000000..35d1b513b72 --- /dev/null +++ b/solutions/2111. Minimum Operations to Make the Array K-Increasing/2111.py @@ -0,0 +1,12 @@ +class Solution: + def kIncreasing(self, arr: List[int], k: int) -> int: + def numReplaced(A: List[int]) -> int: + tail = [] + for a in A: + if not tail or tail[-1] <= a: + tail.append(a) + else: + tail[bisect_right(tail, a)] = a + return len(A) - len(tail) + + return sum(numReplaced(arr[i::k]) for i in range(k)) diff --git a/solutions/2112. The Airport With the Most Traffic/2112.sql b/solutions/2112. The Airport With the Most Traffic/2112.sql new file mode 100644 index 00000000000..bb88b05864b --- /dev/null +++ b/solutions/2112. The Airport With the Most Traffic/2112.sql @@ -0,0 +1,18 @@ +WITH + AirportToCount AS ( + SELECT departure_airport AS airport_id, flights_count + FROM Flights + UNION ALL + SELECT arrival_airport, flights_count + FROM Flights + ), + RankedAirports AS ( + SELECT + airport_id, + RANK() OVER(ORDER BY SUM(flights_count) DESC) AS `rank` + FROM AirportToCount + GROUP BY 1 + ) +SELECT airport_id +FROM RankedAirports +WHERE `rank` = 1; diff --git a/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.cpp b/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.cpp new file mode 100644 index 00000000000..4bcbf0ceb74 --- /dev/null +++ b/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector elementInNums(vector& nums, vector>& queries) { + vector ans; + + for (const vector& query : queries) { + const int time = query[0]; + const int index = query[1]; + ans.push_back(f(nums, time % (2 * nums.size()), index)); + } + + return ans; + } + + private: + int f(const vector& A, int time, int index) { + const int n = A.size(); + if (time < n) { // [0, 1, 2] -> [1, 2] -> [2] + index += time; + return index >= n ? -1 : A[index]; + } else { // [] -> [0] -> [0, 1] + return index >= time - n ? -1 : A[index]; + } + } +}; diff --git a/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.java b/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.java new file mode 100644 index 00000000000..213b51a46af --- /dev/null +++ b/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.java @@ -0,0 +1,23 @@ +class Solution { + public int[] elementInNums(int[] nums, int[][] queries) { + int[] ans = new int[queries.length]; + + for (int i = 0; i < queries.length; ++i) { + final int time = queries[i][0]; + final int index = queries[i][1]; + ans[i] = f(nums, time % (2 * nums.length), index); + } + + return ans; + } + + private int f(int[] A, int time, int index) { + final int n = A.length; + if (time < n) { // [0, 1, 2] -> [1, 2] -> [2] + index += time; + return index >= n ? -1 : A[index]; + } else { // [] -> [0] -> [0, 1] + return index >= time - n ? -1 : A[index]; + } + } +} diff --git a/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.py b/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.py new file mode 100644 index 00000000000..0eb0b3da64a --- /dev/null +++ b/solutions/2113. Elements in Array After Removing and Replacing Elements/2113.py @@ -0,0 +1,12 @@ +class Solution: + def elementInNums(self, nums: List[int], queries: List[List[int]]) -> List[int]: + n = len(nums) + + def f(time: int, index: int) -> int: + if time < n: # [0, 1, 2] -> [1, 2] -> [2] + index += time + return -1 if index >= n else nums[index] + else: # [] -> [0] -> [0, 1] + return -1 if index >= time - n else nums[index] + + return [f(time % (2 * n), index) for time, index in queries] diff --git a/solutions/2114. Maximum Number of Words Found in Sentences/2114.cpp b/solutions/2114. Maximum Number of Words Found in Sentences/2114.cpp new file mode 100644 index 00000000000..ee37ba7de5f --- /dev/null +++ b/solutions/2114. Maximum Number of Words Found in Sentences/2114.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int mostWordsFound(vector& sentences) { + long maxSpaceCount = 0; + + for (const string& s : sentences) + maxSpaceCount = max(maxSpaceCount, ranges::count(s, ' ')); + + return maxSpaceCount + 1; + } +}; diff --git a/solutions/2114. Maximum Number of Words Found in Sentences/2114.java b/solutions/2114. Maximum Number of Words Found in Sentences/2114.java new file mode 100644 index 00000000000..0547bd63700 --- /dev/null +++ b/solutions/2114. Maximum Number of Words Found in Sentences/2114.java @@ -0,0 +1,8 @@ +class Solution { + public int mostWordsFound(String[] sentences) { + return 1 + Stream.of(sentences) + .mapToInt(s -> (int) s.chars().filter(c -> c == ' ').count()) + .max() + .getAsInt(); + } +} diff --git a/solutions/2114. Maximum Number of Words Found in Sentences/2114.py b/solutions/2114. Maximum Number of Words Found in Sentences/2114.py new file mode 100644 index 00000000000..7c241fe3004 --- /dev/null +++ b/solutions/2114. Maximum Number of Words Found in Sentences/2114.py @@ -0,0 +1,3 @@ +class Solution: + def mostWordsFound(self, sentences: List[str]) -> int: + return max(s.count(' ') for s in sentences) + 1 diff --git a/solutions/2115. Find All Possible Recipes from Given Supplies/2115.cpp b/solutions/2115. Find All Possible Recipes from Given Supplies/2115.cpp new file mode 100644 index 00000000000..f9de0548c5c --- /dev/null +++ b/solutions/2115. Find All Possible Recipes from Given Supplies/2115.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector findAllRecipes(vector& recipes, + vector>& ingredients, + vector& supplies) { + vector ans; + unordered_set suppliesSet(supplies.begin(), supplies.end()); + unordered_map> graph; + unordered_map inDegrees; + queue q; + + // Build the graph. + for (int i = 0; i < recipes.size(); ++i) + for (const string& ingredient : ingredients[i]) + if (!suppliesSet.contains(ingredient)) { + graph[ingredient].push_back(recipes[i]); + ++inDegrees[recipes[i]]; + } + + // Perform topological sorting. + for (const string& recipe : recipes) + if (!inDegrees.contains(recipe)) + q.push(recipe); + + while (!q.empty()) { + const string u = q.front(); + q.pop(); + ans.push_back(u); + if (!graph.contains(u)) + continue; + for (const string& v : graph[u]) + if (--inDegrees[v] == 0) + q.push(v); + } + + return ans; + } +}; diff --git a/solutions/2115. Find All Possible Recipes from Given Supplies/2115.java b/solutions/2115. Find All Possible Recipes from Given Supplies/2115.java new file mode 100644 index 00000000000..0d0077ab0df --- /dev/null +++ b/solutions/2115. Find All Possible Recipes from Given Supplies/2115.java @@ -0,0 +1,39 @@ +class Solution { + public List findAllRecipes(String[] recipes, List> ingredients, + String[] supplies) { + List ans = new ArrayList<>(); + Set suppliesSet = new HashSet<>(); + for (final String supply : supplies) + suppliesSet.add(supply); + Map> graph = new HashMap<>(); + Map inDegrees = new HashMap<>(); + + // Build the graph. + for (int i = 0; i < recipes.length; ++i) + for (final String ingredient : ingredients.get(i)) + if (!suppliesSet.contains(ingredient)) { + graph.putIfAbsent(ingredient, new ArrayList<>()); + graph.get(ingredient).add(recipes[i]); + inDegrees.merge(recipes[i], 1, Integer::sum); + } + + // Perform topological sorting. + Queue q = Arrays.stream(recipes) + .filter(recipe -> inDegrees.getOrDefault(recipe, 0) == 0) + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + final String u = q.poll(); + ans.add(u); + if (!graph.containsKey(u)) + continue; + for (final String v : graph.get(u)) { + inDegrees.merge(v, -1, Integer::sum); + if (inDegrees.get(v) == 0) + q.offer(v); + } + } + + return ans; + } +} diff --git a/solutions/2115. Find All Possible Recipes from Given Supplies/2115.py b/solutions/2115. Find All Possible Recipes from Given Supplies/2115.py new file mode 100644 index 00000000000..c5380f82ab3 --- /dev/null +++ b/solutions/2115. Find All Possible Recipes from Given Supplies/2115.py @@ -0,0 +1,29 @@ +class Solution: + def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]: + ans = [] + supplies = set(supplies) + graph = collections.defaultdict(list) + inDegrees = collections.Counter() + q = collections.deque() + + # Build the graph. + for i, recipe in enumerate(recipes): + for ingredient in ingredients[i]: + if ingredient not in supplies: + graph[ingredient].append(recipe) + inDegrees[recipe] += 1 + + # Perform topological sorting. + for recipe in recipes: + if inDegrees[recipe] == 0: + q.append(recipe) + + while q: + u = q.popleft() + ans.append(u) + for v in graph[u]: + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + + return ans diff --git a/solutions/2116. Check if a Parentheses String Can Be Valid/2116.cpp b/solutions/2116. Check if a Parentheses String Can Be Valid/2116.cpp new file mode 100644 index 00000000000..c32dc301c73 --- /dev/null +++ b/solutions/2116. Check if a Parentheses String Can Be Valid/2116.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + bool canBeValid(string s, string locked) { + if (s.length() % 2 == 1) + return false; + + const bool leftToRightIsOkay = check(s, locked, true); + reverse(s.begin(), s.end()); + reverse(locked.begin(), locked.end()); + const bool rightToLeftIsOkay = check(s, locked, false); + return leftToRightIsOkay && rightToLeftIsOkay; + } + + private: + bool check(const string& s, const string& locked, bool isForward) { + int changeable = 0; + int l = 0; + int r = 0; + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + const char lock = locked[i]; + if (lock == '0') + ++changeable; + else if (c == '(') + ++l; + else // c == ')' + ++r; + if (isForward && changeable + l - r < 0) + return false; + if (!isForward && changeable + r - l < 0) + return false; + } + + return true; + } +}; diff --git a/solutions/2116. Check if a Parentheses String Can Be Valid/2116.java b/solutions/2116. Check if a Parentheses String Can Be Valid/2116.java new file mode 100644 index 00000000000..d3e8fa9cb7d --- /dev/null +++ b/solutions/2116. Check if a Parentheses String Can Be Valid/2116.java @@ -0,0 +1,32 @@ +class Solution { + public boolean canBeValid(String s, String locked) { + if (s.length() % 2 == 1) + return false; + + return check(s, locked, true) && check(new StringBuilder(s).reverse().toString(), + new StringBuilder(locked).reverse().toString(), false); + } + + private boolean check(final String s, final String locked, boolean isForward) { + int changeable = 0; + int l = 0; + int r = 0; + + for (int i = 0; i < s.length(); ++i) { + final char c = s.charAt(i); + final char lock = locked.charAt(i); + if (lock == '0') + ++changeable; + else if (c == '(') + ++l; + else // c == ')' + ++r; + if (isForward && changeable + l - r < 0) + return false; + if (!isForward && changeable + r - l < 0) + return false; + } + + return true; + } +} diff --git a/solutions/2116. Check if a Parentheses String Can Be Valid/2116.py b/solutions/2116. Check if a Parentheses String Can Be Valid/2116.py new file mode 100644 index 00000000000..acf25746a45 --- /dev/null +++ b/solutions/2116. Check if a Parentheses String Can Be Valid/2116.py @@ -0,0 +1,25 @@ +class Solution: + def canBeValid(self, s: str, locked: str) -> bool: + if len(s) % 2 == 1: + return False + + def check(s: str, locked: str, isForward: bool) -> bool: + changeable = 0 + l = 0 + r = 0 + + for c, lock in zip(s, locked): + if lock == '0': + changeable += 1 + elif c == '(': + l += 1 + else: # c == ')' + r += 1 + if isForward and changeable + l - r < 0: + return False + if not isForward and changeable + r - l < 0: + return False + + return True + + return check(s, locked, True) and check(s[::-1], locked[::-1], False) diff --git a/solutions/2117. Abbreviating the Product of a Range/2117.cpp b/solutions/2117. Abbreviating the Product of a Range/2117.cpp new file mode 100644 index 00000000000..a6dda4d978a --- /dev/null +++ b/solutions/2117. Abbreviating the Product of a Range/2117.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + string abbreviateProduct(int left, int right) { + constexpr long maxSuf = 100'000'000'000; + double prod = 1.0; + long suf = 1; + int countDigits = 0; + int countZeros = 0; + + for (int num = left; num <= right; ++num) { + prod *= num; + while (prod >= 1.0) { + prod /= 10; + ++countDigits; + } + suf *= num; + while (suf % 10 == 0) { + suf /= 10; + ++countZeros; + } + if (suf > maxSuf) + suf %= maxSuf; + } + + if (countDigits - countZeros <= 10) { + const long tens = pow(10, countDigits - countZeros); + return to_string(static_cast(prod * tens + 0.5)) + 'e' + + to_string(countZeros); + } + + const string pre = to_string(static_cast(prod * pow(10, 5))); + string sufStr = to_string(suf); + sufStr = sufStr.substr(sufStr.length() - 5); + return pre + "..." + sufStr + 'e' + to_string(countZeros); + } +}; diff --git a/solutions/2117. Abbreviating the Product of a Range/2117.java b/solutions/2117. Abbreviating the Product of a Range/2117.java new file mode 100644 index 00000000000..7237ec3b4f8 --- /dev/null +++ b/solutions/2117. Abbreviating the Product of a Range/2117.java @@ -0,0 +1,34 @@ +class Solution { + public String abbreviateProduct(int left, int right) { + final long maxSuf = 100_000_000_000L; + double prod = 1.0; + long suf = 1; + int countDigits = 0; + int countZeros = 0; + + for (int num = left; num <= right; ++num) { + prod *= num; + while (prod >= 1.0) { + prod /= 10; + ++countDigits; + } + suf *= num; + while (suf % 10 == 0) { + suf /= 10; + ++countZeros; + } + if (suf > maxSuf) + suf %= maxSuf; + } + + if (countDigits - countZeros <= 10) { + final long tens = (long) Math.pow(10, countDigits - countZeros); + return String.valueOf((long) (prod * tens + 0.5)) + "e" + String.valueOf(countZeros); + } + + final String pre = String.valueOf((long) (prod * Math.pow(10, 5))); + String sufStr = String.valueOf(suf); + sufStr = sufStr.substring(sufStr.length() - 5); + return pre + "..." + sufStr + "e" + String.valueOf(countZeros); + } +} diff --git a/solutions/2117. Abbreviating the Product of a Range/2117.py b/solutions/2117. Abbreviating the Product of a Range/2117.py new file mode 100644 index 00000000000..80e769cce01 --- /dev/null +++ b/solutions/2117. Abbreviating the Product of a Range/2117.py @@ -0,0 +1,26 @@ +class Solution: + def abbreviateProduct(self, left: int, right: int) -> str: + prod = 1.0 + suf = 1 + countDigits = 0 + countZeros = 0 + + for num in range(left, right + 1): + prod *= num + while prod >= 1.0: + prod /= 10 + countDigits += 1 + suf *= num + while suf % 10 == 0: + suf //= 10 + countZeros += 1 + if suf > 10**8: + suf %= 10**8 + + if countDigits - countZeros <= 10: + tens = 10**(countDigits - countZeros) + return str(int(prod * tens + 0.5)) + 'e' + str(countZeros) + + pre = str(int(prod * 10 ** 5)) + suf = str(suf)[-5:] + return pre + '...' + suf + 'e' + str(countZeros) diff --git a/solutions/2118. Build the Equation/2118.sql b/solutions/2118. Build the Equation/2118.sql new file mode 100644 index 00000000000..f415038aac6 --- /dev/null +++ b/solutions/2118. Build the Equation/2118.sql @@ -0,0 +1,22 @@ +WITH + PowerToTerm AS ( + SELECT + CONCAT( + IF(factor > 0, '+', ''), + factor, + IF(power = 0, '', 'X'), + IF(power IN (0, 1), '', CONCAT('^', power)) + ) AS term, + power + FROM Terms + ORDER BY power DESC + ) +SELECT + CONCAT( + GROUP_CONCAT( + term + ORDER BY power DESC SEPARATOR '' + ), + '=0' + ) AS equation +FROM PowerToTerm; diff --git a/solutions/2119. A Number After a Double Reversal/2119-2.cpp b/solutions/2119. A Number After a Double Reversal/2119-2.cpp new file mode 100644 index 00000000000..105de633fb6 --- /dev/null +++ b/solutions/2119. A Number After a Double Reversal/2119-2.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool isSameAfterReversals(int num) { + return num == 0 || num % 10; + } +}; diff --git a/solutions/2119. A Number After a Double Reversal/2119-2.java b/solutions/2119. A Number After a Double Reversal/2119-2.java new file mode 100644 index 00000000000..7cbfc733905 --- /dev/null +++ b/solutions/2119. A Number After a Double Reversal/2119-2.java @@ -0,0 +1,5 @@ +class Solution { + public boolean isSameAfterReversals(int num) { + return num == 0 || num % 10 > 0; + } +} diff --git a/solutions/2119. A Number After a Double Reversal/2119-2.py b/solutions/2119. A Number After a Double Reversal/2119-2.py new file mode 100644 index 00000000000..9575c807608 --- /dev/null +++ b/solutions/2119. A Number After a Double Reversal/2119-2.py @@ -0,0 +1,3 @@ +class Solution: + def isSameAfterReversals(self, num: int) -> bool: + return num == 0 or num % 10 diff --git a/solutions/2119. A Number After a Double Reversal/2119.cpp b/solutions/2119. A Number After a Double Reversal/2119.cpp new file mode 100644 index 00000000000..34979a24597 --- /dev/null +++ b/solutions/2119. A Number After a Double Reversal/2119.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool isSameAfterReversals(int num) { + const int reversed1 = getReversed(num); + const int reversed2 = getReversed(reversed1); + return reversed2 == num; + } + + private: + int getReversed(int num) { + int reversed = 0; + while (num > 0) { + reversed = reversed * 10 + num % 10; + num /= 10; + } + return reversed; + } +}; diff --git a/solutions/2119. A Number After a Double Reversal/2119.java b/solutions/2119. A Number After a Double Reversal/2119.java new file mode 100644 index 00000000000..fb1734991c4 --- /dev/null +++ b/solutions/2119. A Number After a Double Reversal/2119.java @@ -0,0 +1,16 @@ +class Solution { + public boolean isSameAfterReversals(int num) { + final int reversed1 = getReversed(num); + final int reversed2 = getReversed(reversed1); + return reversed2 == num; + } + + private int getReversed(int num) { + int reversed = 0; + while (num > 0) { + reversed = reversed * 10 + num % 10; + num /= 10; + } + return reversed; + } +} diff --git a/solutions/2119. A Number After a Double Reversal/2119.py b/solutions/2119. A Number After a Double Reversal/2119.py new file mode 100644 index 00000000000..e14763d47da --- /dev/null +++ b/solutions/2119. A Number After a Double Reversal/2119.py @@ -0,0 +1,12 @@ +class Solution: + def isSameAfterReversals(self, num: int) -> bool: + def getReversed(num: int) -> int: + reversed = 0 + while num > 0: + reversed = reversed * 10 + num % 10 + num //= 10 + return reversed + + reversed1 = getReversed(num) + reversed2 = getReversed(reversed1) + return reversed2 == num diff --git a/solutions/212. Word Search II/212.cpp b/solutions/212. Word Search II/212.cpp new file mode 100644 index 00000000000..b43908b3f7f --- /dev/null +++ b/solutions/212. Word Search II/212.cpp @@ -0,0 +1,59 @@ +struct TrieNode { + vector> children; + const string* word = nullptr; + TrieNode() : children(26) {} +}; + +class Solution { + public: + vector findWords(vector>& board, vector& words) { + vector ans; + + for (const string& word : words) + insert(word); + + for (int i = 0; i < board.size(); ++i) + for (int j = 0; j < board[0].size(); ++j) + dfs(board, i, j, root, ans); + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->word = &word; + } + + void dfs(vector>& board, int i, int j, shared_ptr node, + vector& ans) { + if (i < 0 || i == board.size() || j < 0 || j == board[0].size()) + return; + if (board[i][j] == '*') + return; + + const char c = board[i][j]; + shared_ptr child = node->children[c - 'a']; + if (child == nullptr) + return; + if (child->word != nullptr) { + ans.push_back(*child->word); + child->word = nullptr; + } + + board[i][j] = '*'; + dfs(board, i + 1, j, child, ans); + dfs(board, i - 1, j, child, ans); + dfs(board, i, j + 1, child, ans); + dfs(board, i, j - 1, child, ans); + board[i][j] = c; + } +}; diff --git a/solutions/212. Word Search II/212.java b/solutions/212. Word Search II/212.java new file mode 100644 index 00000000000..f5af8c2a843 --- /dev/null +++ b/solutions/212. Word Search II/212.java @@ -0,0 +1,55 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public String word; +} + +class Solution { + public List findWords(char[][] board, String[] words) { + for (final String word : words) + insert(word); + + List ans = new ArrayList<>(); + + for (int i = 0; i < board.length; ++i) + for (int j = 0; j < board[0].length; ++j) + dfs(board, i, j, root, ans); + + return ans; + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.word = word; + } + + private void dfs(char[][] board, int i, int j, TrieNode node, List ans) { + if (i < 0 || i == board.length || j < 0 || j == board[0].length) + return; + if (board[i][j] == '*') + return; + + final char c = board[i][j]; + TrieNode child = node.children[c - 'a']; + if (child == null) + return; + if (child.word != null) { + ans.add(child.word); + child.word = null; + } + + board[i][j] = '*'; + dfs(board, i + 1, j, child, ans); + dfs(board, i - 1, j, child, ans); + dfs(board, i, j + 1, child, ans); + dfs(board, i, j - 1, child, ans); + board[i][j] = c; + } +} diff --git a/solutions/212. Word Search II/212.py b/solutions/212. Word Search II/212.py new file mode 100644 index 00000000000..766f02eb0b8 --- /dev/null +++ b/solutions/212. Word Search II/212.py @@ -0,0 +1,49 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.word: Optional[str] = None + + +class Solution: + def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: + m = len(board) + n = len(board[0]) + ans = [] + root = TrieNode() + + def insert(word: str) -> None: + node = root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.word = word + + for word in words: + insert(word) + + def dfs(i: int, j: int, node: TrieNode) -> None: + if i < 0 or i == m or j < 0 or j == n: + return + if board[i][j] == '*': + return + + c = board[i][j] + if c not in node.children: + return + + child = node.children[c] + if child.word: + ans.append(child.word) + child.word = None + + board[i][j] = '*' + dfs(i + 1, j, child) + dfs(i - 1, j, child) + dfs(i, j + 1, child) + dfs(i, j - 1, child) + board[i][j] = c + + for i in range(m): + for j in range(n): + dfs(i, j, root) + + return ans diff --git a/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.cpp b/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.cpp new file mode 100644 index 00000000000..56b7519d3f2 --- /dev/null +++ b/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + vector executeInstructions(int n, vector& startPos, string s) { + const int m = s.length(); + const int uMost = startPos[0] + 1; + const int dMost = n - startPos[0]; + const int lMost = startPos[1] + 1; + const int rMost = n - startPos[1]; + const unordered_map> moves{ + {'L', {0, -1}}, + {'R', {0, 1}}, + {'U', {-1, 0}}, + {'D', {1, 0}}, + }; + + vector ans(m); + unordered_map reachX{{0, m}}; + unordered_map reachY{{0, m}}; + int x = 0; + int y = 0; + + for (int i = m - 1; i >= 0; --i) { + const auto [dx, dy] = moves.at(s[i]); + x -= dx; + y -= dy; + reachX[x] = i; + reachY[y] = i; + int out = INT_MAX; + if (const auto it = reachX.find(x - uMost); it != reachX.cend()) + out = min(out, it->second); + if (const auto it = reachX.find(x + dMost); it != reachX.cend()) + out = min(out, it->second); + if (const auto it = reachY.find(y - lMost); it != reachY.cend()) + out = min(out, it->second); + if (const auto it = reachY.find(y + rMost); it != reachY.cend()) + out = min(out, it->second); + ans[i] = out == INT_MAX ? m - i : out - i - 1; + } + + return ans; + } +}; diff --git a/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.java b/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.java new file mode 100644 index 00000000000..39ae915e7a4 --- /dev/null +++ b/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.java @@ -0,0 +1,39 @@ +class Solution { + public int[] executeInstructions(int n, int[] startPos, String s) { + final int m = s.length(); + final int uMost = startPos[0] + 1; + final int dMost = n - startPos[0]; + final int lMost = startPos[1] + 1; + final int rMost = n - startPos[1]; + Map> moves = new HashMap<>(); + moves.put('L', new Pair<>(0, -1)); + moves.put('R', new Pair<>(0, 1)); + moves.put('U', new Pair<>(-1, 0)); + moves.put('D', new Pair<>(1, 0)); + + int[] ans = new int[m]; + Map reachX = new HashMap<>(); + Map reachY = new HashMap<>(); + reachX.put(0, m); + reachY.put(0, m); + int x = 0; + int y = 0; + + for (int i = m - 1; i >= 0; --i) { + Pair pair = moves.get(s.charAt(i)); + final int dx = pair.getKey(); + final int dy = pair.getValue(); + x -= dx; + y -= dy; + reachX.put(x, i); + reachY.put(y, i); + final int out = Math.min(Math.min(reachX.getOrDefault(x - uMost, Integer.MAX_VALUE), + reachX.getOrDefault(x + dMost, Integer.MAX_VALUE)), + Math.min(reachY.getOrDefault(y - lMost, Integer.MAX_VALUE), + reachY.getOrDefault(y + rMost, Integer.MAX_VALUE))); + ans[i] = out == Integer.MAX_VALUE ? m - i : out - i - 1; + } + + return ans; + } +} diff --git a/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.py b/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.py new file mode 100644 index 00000000000..546848f1f42 --- /dev/null +++ b/solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.py @@ -0,0 +1,27 @@ +class Solution: + def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: + moves = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)} + m = len(s) + uMost = startPos[0] + 1 + dMost = n - startPos[0] + lMost = startPos[1] + 1 + rMost = n - startPos[1] + + ans = [0] * m + reach = {(0, None): m, (None, 0): m} + x = 0 + y = 0 + + for i in reversed(range(m)): + dx, dy = moves[s[i]] + x -= dx + y -= dy + reach[(x, None)] = i + reach[(None, y)] = i + out = min(reach.get((x - uMost, None), math.inf), + reach.get((x + dMost, None), math.inf), + reach.get((None, y - lMost), math.inf), + reach.get((None, y + rMost), math.inf)) + ans[i] = m - i if out == math.inf else out - i - 1 + + return ans diff --git a/solutions/2121. Intervals Between Identical Elements/2121.cpp b/solutions/2121. Intervals Between Identical Elements/2121.cpp new file mode 100644 index 00000000000..9d8f51ed730 --- /dev/null +++ b/solutions/2121. Intervals Between Identical Elements/2121.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector getDistances(vector& arr) { + const int n = arr.size(); + vector ans(n); + vector prefix(n); + vector suffix(n); + unordered_map> numToIndices; + + for (int i = 0; i < n; ++i) + numToIndices[arr[i]].push_back(i); + + for (const auto& [_, indices] : numToIndices) { + for (int i = 1; i < indices.size(); ++i) { + const int currIndex = indices[i]; + const int prevIndex = indices[i - 1]; + prefix[currIndex] += prefix[prevIndex] + i * (currIndex - prevIndex); + } + for (int i = indices.size() - 2; i >= 0; --i) { + const int currIndex = indices[i]; + const int prevIndex = indices[i + 1]; + suffix[currIndex] += suffix[prevIndex] + + (indices.size() - i - 1) * (prevIndex - currIndex); + } + } + + for (int i = 0; i < n; ++i) + ans[i] = prefix[i] + suffix[i]; + + return ans; + } +}; diff --git a/solutions/2121. Intervals Between Identical Elements/2121.java b/solutions/2121. Intervals Between Identical Elements/2121.java new file mode 100644 index 00000000000..aefd409c29c --- /dev/null +++ b/solutions/2121. Intervals Between Identical Elements/2121.java @@ -0,0 +1,32 @@ +class Solution { + public long[] getDistances(int[] arr) { + final int n = arr.length; + long[] ans = new long[n]; + long[] prefix = new long[n]; + long[] suffix = new long[n]; + Map> numToIndices = new HashMap<>(); + + for (int i = 0; i < n; ++i) { + numToIndices.putIfAbsent(arr[i], new ArrayList<>()); + numToIndices.get(arr[i]).add(i); + } + + for (List indices : numToIndices.values()) { + for (int i = 1; i < indices.size(); ++i) { + final int currIndex = indices.get(i); + final int prevIndex = indices.get(i - 1); + prefix[currIndex] += prefix[prevIndex] + i * (currIndex - prevIndex); + } + for (int i = indices.size() - 2; i >= 0; --i) { + final int currIndex = indices.get(i); + final int prevIndex = indices.get(i + 1); + suffix[currIndex] += suffix[prevIndex] + (indices.size() - i - 1) * (prevIndex - currIndex); + } + } + + for (int i = 0; i < n; ++i) + ans[i] = prefix[i] + suffix[i]; + + return ans; + } +} diff --git a/solutions/2121. Intervals Between Identical Elements/2121.py b/solutions/2121. Intervals Between Identical Elements/2121.py new file mode 100644 index 00000000000..56a7afdc5a3 --- /dev/null +++ b/solutions/2121. Intervals Between Identical Elements/2121.py @@ -0,0 +1,21 @@ +class Solution: + def getDistances(self, arr: List[int]) -> List[int]: + prefix = [0] * len(arr) + suffix = [0] * len(arr) + numToIndices = collections.defaultdict(list) + + for i, a in enumerate(arr): + numToIndices[a].append(i) + + for indices in numToIndices.values(): + for i in range(1, len(indices)): + currIndex = indices[i] + prevIndex = indices[i - 1] + prefix[currIndex] += prefix[prevIndex] + i * (currIndex - prevIndex) + for i in range(len(indices) - 2, -1, -1): + currIndex = indices[i] + prevIndex = indices[i + 1] + suffix[currIndex] += suffix[prevIndex] + \ + (len(indices) - i - 1) * (prevIndex - currIndex) + + return [p + s for p, s in zip(prefix, suffix)] diff --git a/solutions/2122. Recover the Original Array/2122.cpp b/solutions/2122. Recover the Original Array/2122.cpp new file mode 100644 index 00000000000..4bda22e3432 --- /dev/null +++ b/solutions/2122. Recover the Original Array/2122.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + vector recoverArray(vector& nums) { + const int n = nums.size(); + unordered_map count; + + for (const int num : nums) + ++count[num]; + + ranges::sort(nums); + + for (int i = 1; i < n; ++i) { + const int x = nums[i] - nums[0]; // 2 * k + if (x <= 0 || x % 2 == 1) + continue; + vector A = getArray(nums, x, count); + if (!A.empty()) + return A; + } + + throw; + } + + private: + vector getArray(const vector& nums, int x, + unordered_map count) { + vector A; + for (const int num : nums) { + if (const auto it = count.find(num); + it == count.cend() || it->second == 0) + continue; + if (const auto it = count.find(num + x); + it == count.cend() || it->second == 0) + return {}; + --count[num]; + --count[num + x]; + A.push_back(num + x / 2); + } + return A; + } +}; diff --git a/solutions/2122. Recover the Original Array/2122.java b/solutions/2122. Recover the Original Array/2122.java new file mode 100644 index 00000000000..2f3a136d6b8 --- /dev/null +++ b/solutions/2122. Recover the Original Array/2122.java @@ -0,0 +1,38 @@ +class Solution { + public int[] recoverArray(int[] nums) { + final int n = nums.length; + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + Arrays.sort(nums); + + for (int i = 1; i < n; ++i) { + final int x = nums[i] - nums[0]; // 2 * k + if (x <= 0 || x % 2 == 1) + continue; + Map countCopy = new HashMap<>(); + countCopy.putAll(count); + int[] A = getArray(nums, x, countCopy); + if (A.length == n / 2) + return A; + } + + throw new IllegalArgumentException(); + } + + private int[] getArray(int[] nums, int x, Map count) { + List A = new ArrayList<>(); + for (final int num : nums) { + if (count.getOrDefault(num, 0) == 0) + continue; + if (count.getOrDefault(num + x, 0) == 0) + return new int[] {}; + count.merge(num, -1, Integer::sum); + count.merge(num + x, -1, Integer::sum); + A.add(num + x / 2); + } + return A.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/2122. Recover the Original Array/2122.py b/solutions/2122. Recover the Original Array/2122.py new file mode 100644 index 00000000000..565acb3a233 --- /dev/null +++ b/solutions/2122. Recover the Original Array/2122.py @@ -0,0 +1,25 @@ +class Solution: + def recoverArray(self, nums: List[int]) -> List[int]: + nums = sorted(nums) + + def getArray(x: int, count: collections.Counter) -> List[int]: + A = [] + for num in nums: + if count[num] == 0: + continue + if count[num + x] == 0: + return [] + count[num] -= 1 + count[num + x] -= 1 + A.append(num + x // 2) + return A + + count = collections.Counter(nums) + + for i in range(1, len(nums)): + x = nums[i] - nums[0] # 2 * k + if x <= 0 or x % 2 == 1: + continue + A = getArray(x, count.copy()) + if A: + return A diff --git a/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.cpp b/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.cpp new file mode 100644 index 00000000000..f2c84b19150 --- /dev/null +++ b/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + int minimumOperations(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + vector> seen(m, vector(n)); + vector> match(m, vector(n, -1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1 && match[i][j] == -1) { + const int sessionId = i * n + j; + seen[i][j] = sessionId; + ans += dfs(grid, i, j, sessionId, seen, match); + } + + return ans; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + int dfs(const vector>& grid, int i, int j, int sessionId, + vector>& seen, vector>& match) { + const int m = grid.size(); + const int n = grid[0].size(); + + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] == 0 || seen[x][y] == sessionId) + continue; + seen[x][y] = sessionId; + if (match[x][y] == -1 || + dfs(grid, match[x][y] / n, match[x][y] % n, sessionId, seen, match)) { + match[x][y] = i * n + j; + match[i][j] = x * n + y; + return 1; + } + } + + return 0; + } +}; diff --git a/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.java b/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.java new file mode 100644 index 00000000000..19968aecbe8 --- /dev/null +++ b/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.java @@ -0,0 +1,47 @@ +class Solution { + public int minimumOperations(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + int[][] seen = new int[m][n]; + int[][] match = new int[m][n]; + Arrays.stream(match).forEach(A -> Arrays.fill(A, -1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1 && match[i][j] == -1) { + final int sessionId = i * n + j; + seen[i][j] = sessionId; + if (dfs(grid, i, j, sessionId, seen, match)) + ++ans; + } + + return ans; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private boolean dfs(final int[][] grid, int i, int j, int sessionId, int[][] seen, + int[][] match) { + final int m = grid.length; + final int n = grid[0].length; + + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] == 0 || seen[x][y] == sessionId) + continue; + seen[x][y] = sessionId; + if (match[x][y] == -1 || + dfs(grid, match[x][y] / n, match[x][y] % n, sessionId, seen, match)) { + match[x][y] = i * n + j; + match[i][j] = x * n + y; + return true; + } + } + + return false; + } +} diff --git a/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.py b/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.py new file mode 100644 index 00000000000..bd1407cc766 --- /dev/null +++ b/solutions/2123. Minimum Operations to Remove Adjacent Ones in Matrix/2123.py @@ -0,0 +1,33 @@ +class Solution: + def minimumOperations(self, grid: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + seen = [[0] * n for _ in range(m)] + match = [[-1] * n for _ in range(m)] + + def dfs(i: int, j: int, sessionId: int) -> int: + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if grid[x][y] == 0 or seen[x][y] == sessionId: + continue + seen[x][y] = sessionId + if match[x][y] == -1 or dfs(*divmod(match[x][y], n), sessionId): + match[x][y] = i * n + j + match[i][j] = x * n + y + return 1 + return 0 + + ans = 0 + + for i in range(m): + for j in range(n): + if grid[i][j] == 1 and match[i][j] == -1: + sessionId = i * n + j + seen[i][j] = sessionId + ans += dfs(i, j, sessionId) + + return ans diff --git a/solutions/2124. Check if All A's Appears Before All B's/2124.cpp b/solutions/2124. Check if All A's Appears Before All B's/2124.cpp new file mode 100644 index 00000000000..43a3264e835 --- /dev/null +++ b/solutions/2124. Check if All A's Appears Before All B's/2124.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool checkString(string s) { + return s.find("ba") == string::npos; + } +}; diff --git a/solutions/2124. Check if All A's Appears Before All B's/2124.java b/solutions/2124. Check if All A's Appears Before All B's/2124.java new file mode 100644 index 00000000000..d28543fd994 --- /dev/null +++ b/solutions/2124. Check if All A's Appears Before All B's/2124.java @@ -0,0 +1,5 @@ +class Solution { + public boolean checkString(String s) { + return !s.contains("ba"); + } +} diff --git a/solutions/2124. Check if All A's Appears Before All B's/2124.py b/solutions/2124. Check if All A's Appears Before All B's/2124.py new file mode 100644 index 00000000000..2c3c2419d2a --- /dev/null +++ b/solutions/2124. Check if All A's Appears Before All B's/2124.py @@ -0,0 +1,3 @@ +class Solution: + def checkString(self, s: str) -> bool: + return 'ba' not in s diff --git a/solutions/2125. Number of Laser Beams in a Bank/2125.cpp b/solutions/2125. Number of Laser Beams in a Bank/2125.cpp new file mode 100644 index 00000000000..0a8ece4c0c5 --- /dev/null +++ b/solutions/2125. Number of Laser Beams in a Bank/2125.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int numberOfBeams(vector& bank) { + int ans = 0; + int prevOnes = 0; + + for (const string& row : bank) { + const int ones = ranges::count(row, '1'); + if (ones > 0) { + ans += prevOnes * ones; + prevOnes = ones; + } + } + + return ans; + } +}; diff --git a/solutions/2125. Number of Laser Beams in a Bank/2125.java b/solutions/2125. Number of Laser Beams in a Bank/2125.java new file mode 100644 index 00000000000..23fb930e3b5 --- /dev/null +++ b/solutions/2125. Number of Laser Beams in a Bank/2125.java @@ -0,0 +1,16 @@ +class Solution { + public int numberOfBeams(String[] bank) { + int ans = 0; + int prevOnes = 0; + + for (final String row : bank) { + final int ones = (int) row.chars().filter(c -> c == '1').count(); + if (ones > 0) { + ans += prevOnes * ones; + prevOnes = ones; + } + } + + return ans; + } +} diff --git a/solutions/2125. Number of Laser Beams in a Bank/2125.py b/solutions/2125. Number of Laser Beams in a Bank/2125.py new file mode 100644 index 00000000000..746e67f1c55 --- /dev/null +++ b/solutions/2125. Number of Laser Beams in a Bank/2125.py @@ -0,0 +1,12 @@ +class Solution: + def numberOfBeams(self, bank: List[str]) -> int: + ans = 0 + prevOnes = 0 + + for row in bank: + ones = row.count('1') + if ones: + ans += prevOnes * ones + prevOnes = ones + + return ans diff --git a/solutions/2126. Destroying Asteroids/2126.cpp b/solutions/2126. Destroying Asteroids/2126.cpp new file mode 100644 index 00000000000..75afd54bd2a --- /dev/null +++ b/solutions/2126. Destroying Asteroids/2126.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool asteroidsDestroyed(int mass, vector& asteroids) { + ranges::sort(asteroids); + + long m = mass; + + for (const int asteroid : asteroids) + if (m >= asteroid) + m += asteroid; + else + return false; + + return true; + } +}; diff --git a/solutions/2126. Destroying Asteroids/2126.java b/solutions/2126. Destroying Asteroids/2126.java new file mode 100644 index 00000000000..53314382da0 --- /dev/null +++ b/solutions/2126. Destroying Asteroids/2126.java @@ -0,0 +1,15 @@ +class Solution { + public boolean asteroidsDestroyed(int mass, int[] asteroids) { + Arrays.sort(asteroids); + + long m = mass; + + for (final int asteroid : asteroids) + if (m >= asteroid) + m += asteroid; + else + return false; + + return true; + } +} diff --git a/solutions/2126. Destroying Asteroids/2126.py b/solutions/2126. Destroying Asteroids/2126.py new file mode 100644 index 00000000000..ea0d14ba1f1 --- /dev/null +++ b/solutions/2126. Destroying Asteroids/2126.py @@ -0,0 +1,8 @@ +class Solution: + def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool: + for asteroid in sorted(asteroids): + if mass >= asteroid: + mass += asteroid + else: + return False + return True diff --git a/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.cpp b/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.cpp new file mode 100644 index 00000000000..171c2b3a187 --- /dev/null +++ b/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.cpp @@ -0,0 +1,76 @@ +enum class State { kInit, kVisiting, kVisited }; + +class Solution { + public: + int maximumInvitations(vector& favorite) { + const int n = favorite.size(); + int sumComponentsLength = 0; // the component: a -> b -> c <-> x <- y + vector> graph(n); + vector inDegrees(n); + vector maxChainLength(n, 1); + queue q; + + // Build the graph. + for (int i = 0; i < n; ++i) { + graph[i].push_back(favorite[i]); + ++inDegrees[favorite[i]]; + } + + // Perform topological sorting. + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) { + if (--inDegrees[v] == 0) + q.push(v); + maxChainLength[v] = max(maxChainLength[v], 1 + maxChainLength[u]); + } + } + + for (int i = 0; i < n; ++i) + if (favorite[favorite[i]] == i) + // i <-> favorite[i] (the cycle's length = 2) + sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]]; + + int maxCycleLength = 0; // the cycle : a -> b -> c -> a + vector parent(n, -1); + vector seen(n); + vector states(n); + + for (int i = 0; i < n; ++i) + if (!seen[i]) + findCycle(graph, i, parent, seen, states, maxCycleLength); + + return max(sumComponentsLength / 2, maxCycleLength); + } + + private: + void findCycle(const vector>& graph, int u, vector& parent, + vector& seen, vector& states, + int& maxCycleLength) { + seen[u] = true; + states[u] = State::kVisiting; + + for (const int v : graph[u]) { + if (!seen[v]) { + parent[v] = u; + findCycle(graph, v, parent, seen, states, maxCycleLength); + } else if (states[v] == State::kVisiting) { + // Find the cycle's length. + int curr = u; + int cycleLength = 1; + while (curr != v) { + curr = parent[curr]; + ++cycleLength; + } + maxCycleLength = max(maxCycleLength, cycleLength); + } + } + + states[u] = State::kVisited; + } +}; diff --git a/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.java b/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.java new file mode 100644 index 00000000000..02958f4f8b5 --- /dev/null +++ b/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.java @@ -0,0 +1,78 @@ +enum State { kInit, kVisiting, kVisited } + +class Solution { + public int maximumInvitations(int[] favorite) { + final int n = favorite.length; + int sumComponentsLength = 0; // the component: a -> b -> c <-> x <- y + List[] graph = new List[n]; + int[] inDegrees = new int[n]; + int[] maxChainLength = new int[n]; + Arrays.fill(maxChainLength, 1); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph. + for (int i = 0; i < n; ++i) { + graph[i].add(favorite[i]); + ++inDegrees[favorite[i]]; + } + + // Perform topological sorting. + Queue q = IntStream.range(0, n) + .filter(i -> inDegrees[i] == 0) + .boxed() + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + final int u = q.poll(); + for (final int v : graph[u]) { + if (--inDegrees[v] == 0) + q.offer(v); + maxChainLength[v] = Math.max(maxChainLength[v], 1 + maxChainLength[u]); + } + } + + for (int i = 0; i < n; ++i) + if (favorite[favorite[i]] == i) + // i <-> favorite[i] (the cycle's length = 2) + sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]]; + + int[] parent = new int[n]; + Arrays.fill(parent, -1); + boolean[] seen = new boolean[n]; + State[] states = new State[n]; + + for (int i = 0; i < n; ++i) + if (!seen[i]) + findCycle(graph, i, parent, seen, states); + + return Math.max(sumComponentsLength / 2, maxCycleLength); + } + + private int maxCycleLength = 0; // the cycle : a -> b -> c -> a + + private void findCycle(List[] graph, int u, int[] parent, boolean[] seen, + State[] states) { + seen[u] = true; + states[u] = State.kVisiting; + + for (final int v : graph[u]) { + if (!seen[v]) { + parent[v] = u; + findCycle(graph, v, parent, seen, states); + } else if (states[v] == State.kVisiting) { + // Find the cycle's length. + int curr = u; + int cycleLength = 1; + while (curr != v) { + curr = parent[curr]; + ++cycleLength; + } + maxCycleLength = Math.max(maxCycleLength, cycleLength); + } + } + + states[u] = State.kVisited; + } +} diff --git a/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.py b/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.py new file mode 100644 index 00000000000..0d1ced797dc --- /dev/null +++ b/solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.py @@ -0,0 +1,66 @@ +from enum import Enum + + +class State(Enum): + kInit = 0 + kVisiting = 1 + kVisited = 2 + + +class Solution: + def maximumInvitations(self, favorite: List[int]) -> int: + n = len(favorite) + sumComponentsLength = 0 # the component: a -> b -> c <-> x <- y + graph = [[] for _ in range(n)] + inDegrees = [0] * n + maxChainLength = [1] * n + + # Build the graph. + for i, f in enumerate(favorite): + graph[i].append(f) + inDegrees[f] += 1 + + # Perform topological sorting. + q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) + + while q: + u = q.popleft() + for v in graph[u]: + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + maxChainLength[v] = max(maxChainLength[v], 1 + maxChainLength[u]) + + for i in range(n): + if favorite[favorite[i]] == i: + # i <-> favorite[i] (the cycle's length = 2) + sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]] + + maxCycleLength = 0 # Cycle: a -> b -> c -> a + parent = [-1] * n + seen = set() + states = [State.kInit] * n + + def findCycle(u: int) -> None: + nonlocal maxCycleLength + seen.add(u) + states[u] = State.kVisiting + for v in graph[u]: + if v not in seen: + parent[v] = u + findCycle(v) + elif states[v] == State.kVisiting: + # Find the cycle's length. + curr = u + cycleLength = 1 + while curr != v: + curr = parent[curr] + cycleLength += 1 + maxCycleLength = max(maxCycleLength, cycleLength) + states[u] = State.kVisited + + for i in range(n): + if i not in seen: + findCycle(i) + + return max(sumComponentsLength // 2, maxCycleLength) diff --git a/solutions/2128. Remove All Ones With Row and Column Flips/2128.cpp b/solutions/2128. Remove All Ones With Row and Column Flips/2128.cpp new file mode 100644 index 00000000000..6552cc783c3 --- /dev/null +++ b/solutions/2128. Remove All Ones With Row and Column Flips/2128.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool removeOnes(vector>& grid) { + const vector revRow = getRevRow(grid[0]); + return ranges::all_of( + grid, [&](const auto& row) { return row == grid[0] || row == revRow; }); + } + + private: + vector getRevRow(vector& row) { + vector revRow; + for (const int a : row) + revRow.push_back(a ^ 1); + return revRow; + } +}; diff --git a/solutions/2128. Remove All Ones With Row and Column Flips/2128.java b/solutions/2128. Remove All Ones With Row and Column Flips/2128.java new file mode 100644 index 00000000000..518831d41f5 --- /dev/null +++ b/solutions/2128. Remove All Ones With Row and Column Flips/2128.java @@ -0,0 +1,14 @@ +class Solution { + public boolean removeOnes(int[][] grid) { + int[] revRow = getRevRow(grid[0]); + return Arrays.stream(grid).allMatch( + row -> Arrays.equals(row, grid[0]) || Arrays.equals(row, revRow)); + } + + private int[] getRevRow(int[] row) { + int[] revRow = new int[row.length]; + for (int i = 0; i < row.length; ++i) + revRow[i] = row[i] ^ 1; + return revRow; + } +} diff --git a/solutions/2128. Remove All Ones With Row and Column Flips/2128.py b/solutions/2128. Remove All Ones With Row and Column Flips/2128.py new file mode 100644 index 00000000000..44c4331c32c --- /dev/null +++ b/solutions/2128. Remove All Ones With Row and Column Flips/2128.py @@ -0,0 +1,4 @@ +class Solution: + def removeOnes(self, grid: List[List[int]]) -> bool: + revRow = [a ^ 1 for a in grid[0]] + return all(row == grid[0] or row == revRow for row in grid) diff --git a/solutions/2129. Capitalize the Title/2129.cpp b/solutions/2129. Capitalize the Title/2129.cpp new file mode 100644 index 00000000000..7ba25aaa8c7 --- /dev/null +++ b/solutions/2129. Capitalize the Title/2129.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string capitalizeTitle(string title) { + ranges::transform(title, title.begin(), ::tolower); + + int i = 0; // Point to the start of a word. + int j = 0; // Point to the end of a word. + + while (j < title.length()) { + while (j < title.length() && title[j] != ' ') + ++j; + if (j - i > 2) + title[i] = toupper(title[i]); + i = j + 1; + ++j; // Skip the spaces. + } + + return title; + } +}; diff --git a/solutions/2129. Capitalize the Title/2129.java b/solutions/2129. Capitalize the Title/2129.java new file mode 100644 index 00000000000..052aff4e198 --- /dev/null +++ b/solutions/2129. Capitalize the Title/2129.java @@ -0,0 +1,19 @@ +class Solution { + public String capitalizeTitle(String title) { + StringBuilder sb = new StringBuilder(title.toLowerCase()); + + int i = 0; // Point to the start of a word. + int j = 0; // Point to the end of a word. + + while (j < sb.length()) { + while (j < sb.length() && sb.charAt(j) != ' ') + ++j; + if (j - i > 2) + sb.setCharAt(i, Character.toUpperCase(sb.charAt(i))); + i = j + 1; + ++j; // Skip the spaces. + } + + return sb.toString(); + } +} diff --git a/solutions/2129. Capitalize the Title/2129.py b/solutions/2129. Capitalize the Title/2129.py new file mode 100644 index 00000000000..6da3917b0b8 --- /dev/null +++ b/solutions/2129. Capitalize the Title/2129.py @@ -0,0 +1,3 @@ +class Solution: + def capitalizeTitle(self, title: str) -> str: + return ' '.join(s.lower() if len(s) < 3 else s.capitalize() for s in title.split()) diff --git a/solutions/213. House Robber II/213.cpp b/solutions/213. House Robber II/213.cpp new file mode 100644 index 00000000000..ea652891440 --- /dev/null +++ b/solutions/213. House Robber II/213.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int rob(vector& nums) { + if (nums.empty()) + return 0; + if (nums.size() == 1) + return nums[0]; + + auto rob = [&](int l, int r) { + int prev1 = 0; // dp[i - 1] + int prev2 = 0; // dp[i - 2] + + for (int i = l; i <= r; ++i) { + const int dp = max(prev1, prev2 + nums[i]); + prev2 = prev1; + prev1 = dp; + } + + return prev1; + }; + + return max(rob(0, nums.size() - 2), rob(1, nums.size() - 1)); + } +}; diff --git a/solutions/213. House Robber II/213.java b/solutions/213. House Robber II/213.java new file mode 100644 index 00000000000..bb41ab23dd6 --- /dev/null +++ b/solutions/213. House Robber II/213.java @@ -0,0 +1,22 @@ +class Solution { + public int rob(int[] nums) { + if (nums.length == 0) + return 0; + if (nums.length == 1) + return nums[0]; + return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1)); + } + + private int rob(int[] nums, int l, int r) { + int prev1 = 0; // dp[i - 1] + int prev2 = 0; // dp[i - 2] + + for (int i = l; i <= r; ++i) { + final int dp = Math.max(prev1, prev2 + nums[i]); + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } +} diff --git a/solutions/213. House Robber II/213.py b/solutions/213. House Robber II/213.py new file mode 100644 index 00000000000..96737fe3eeb --- /dev/null +++ b/solutions/213. House Robber II/213.py @@ -0,0 +1,20 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + if not nums: + return 0 + if len(nums) < 2: + return nums[0] + + def rob(l: int, r: int) -> int: + dp1 = 0 + dp2 = 0 + + for i in range(l, r + 1): + temp = dp1 + dp1 = max(dp1, dp2 + nums[i]) + dp2 = temp + + return dp1 + + return max(rob(0, len(nums) - 2), + rob(1, len(nums) - 1)) diff --git a/solutions/2130. Maximum Twin Sum of a Linked List/2130.cpp b/solutions/2130. Maximum Twin Sum of a Linked List/2130.cpp new file mode 100644 index 00000000000..e7a7d9a68a7 --- /dev/null +++ b/solutions/2130. Maximum Twin Sum of a Linked List/2130.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int pairSum(ListNode* head) { + int ans = 0; + ListNode* slow = head; + ListNode* fast = head; + + // `slow` points to the start of the second half. + while (fast != nullptr && fast->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + } + + // `tail` points to the end of the reversed second half. + ListNode* tail = reverseList(slow); + + while (tail != nullptr) { + ans = max(ans, head->val + tail->val); + head = head->next; + tail = tail->next; + } + + return ans; + } + + private: + ListNode* reverseList(ListNode* head) { + ListNode* prev = nullptr; + while (head) { + auto next = head->next; + head->next = prev; + prev = head; + head = next; + } + return prev; + } +}; diff --git a/solutions/2130. Maximum Twin Sum of a Linked List/2130.java b/solutions/2130. Maximum Twin Sum of a Linked List/2130.java new file mode 100644 index 00000000000..ec6c04acfd2 --- /dev/null +++ b/solutions/2130. Maximum Twin Sum of a Linked List/2130.java @@ -0,0 +1,35 @@ +class Solution { + public int pairSum(ListNode head) { + int ans = 0; + ListNode slow = head; + ListNode fast = head; + + // `slow` points to the start of the second half. + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + // `tail` points to the end of the reversed second half. + ListNode tail = reverseList(slow); + + while (tail != null) { + ans = Math.max(ans, head.val + tail.val); + head = head.next; + tail = tail.next; + } + + return ans; + } + + private ListNode reverseList(ListNode head) { + ListNode prev = null; + while (head != null) { + ListNode next = head.next; + head.next = prev; + prev = head; + head = next; + } + return prev; + } +} diff --git a/solutions/2130. Maximum Twin Sum of a Linked List/2130.py b/solutions/2130. Maximum Twin Sum of a Linked List/2130.py new file mode 100644 index 00000000000..19e69eabbc0 --- /dev/null +++ b/solutions/2130. Maximum Twin Sum of a Linked List/2130.py @@ -0,0 +1,29 @@ +class Solution: + def pairSum(self, head: Optional[ListNode]) -> int: + def reverseList(head: ListNode) -> ListNode: + prev = None + while head: + next = head.next + head.next = prev + prev = head + head = next + return prev + + ans = 0 + slow = head + fast = head + + # `slow` points to the start of the second half. + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + # `tail` points to the end of the reversed second half. + tail = reverseList(slow) + + while tail: + ans = max(ans, head.val + tail.val) + head = head.next + tail = tail.next + + return ans diff --git a/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.cpp b/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.cpp new file mode 100644 index 00000000000..7cd3f5b9f72 --- /dev/null +++ b/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int longestPalindrome(vector& words) { + int ans = 0; + vector> count(26, vector(26)); + + for (const string& word : words) { + const int i = word[0] - 'a'; + const int j = word[1] - 'a'; + if (count[j][i]) { + ans += 4; + --count[j][i]; + } else { + ++count[i][j]; + } + } + + for (int i = 0; i < 26; ++i) + if (count[i][i]) + return ans + 2; + + return ans; + } +}; diff --git a/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.java b/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.java new file mode 100644 index 00000000000..8af43b524ba --- /dev/null +++ b/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.java @@ -0,0 +1,23 @@ +class Solution { + public int longestPalindrome(String[] words) { + int ans = 0; + int[][] count = new int[26][26]; + + for (final String word : words) { + final int i = word.charAt(0) - 'a'; + final int j = word.charAt(1) - 'a'; + if (count[j][i] > 0) { + ans += 4; + --count[j][i]; + } else { + ++count[i][j]; + } + } + + for (int i = 0; i < 26; ++i) + if (count[i][i] > 0) + return ans + 2; + + return ans; + } +} diff --git a/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.py b/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.py new file mode 100644 index 00000000000..eab3214a82d --- /dev/null +++ b/solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.py @@ -0,0 +1,19 @@ +class Solution: + def longestPalindrome(self, words: List[str]) -> int: + ans = 0 + count = [[0] * 26 for _ in range(26)] + + for a, b in words: + i = ord(a) - ord('a') + j = ord(b) - ord('a') + if count[j][i]: + ans += 4 + count[j][i] -= 1 + else: + count[i][j] += 1 + + for i in range(26): + if count[i][i]: + return ans + 2 + + return ans diff --git a/solutions/2132. Stamping the Grid/2132.cpp b/solutions/2132. Stamping the Grid/2132.cpp new file mode 100644 index 00000000000..5b3b931512a --- /dev/null +++ b/solutions/2132. Stamping the Grid/2132.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + bool possibleToStamp(vector>& grid, int stampHeight, + int stampWidth) { + const int m = grid.size(); + const int n = grid[0].size(); + // A[i][j] := the number of 1s in grid[0..i)[0..j) + vector> A(m + 1, vector(n + 1)); + // B[i][j] := the number of ways to stamp the submatrix in [0..i)[0..j) + vector> B(m + 1, vector(n + 1)); + // fit[i][j] := true if the stamps can fit with the right-bottom at (i, j) + vector> fit(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j]; + if (i + 1 >= stampHeight && j + 1 >= stampWidth) { + const int x = i - stampHeight + 1; + const int y = j - stampWidth + 1; + if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0) + fit[i][j] = true; + } + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (!grid[i][j]) { + const int x = min(i + stampHeight, m); + const int y = min(j + stampWidth, n); + if (B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0) + return false; + } + + return true; + } +}; diff --git a/solutions/2132. Stamping the Grid/2132.java b/solutions/2132. Stamping the Grid/2132.java new file mode 100644 index 00000000000..519a04e6424 --- /dev/null +++ b/solutions/2132. Stamping the Grid/2132.java @@ -0,0 +1,38 @@ +class Solution { + public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) { + final int m = grid.length; + final int n = grid[0].length; + // A[i][j] := the number of 1s in grid[0..i)[0..j) + int[][] A = new int[m + 1][n + 1]; + // B[i][j] := the number of ways to stamp the submatrix in [0..i)[0..j) + int[][] B = new int[m + 1][n + 1]; + // fit[i][j] := 1 if the stamps can fit with the right-bottom at (i, j) + int[][] fit = new int[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j]; + if (i + 1 >= stampHeight && j + 1 >= stampWidth) { + final int x = i - stampHeight + 1; + final int y = j - stampWidth + 1; + if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0) + fit[i][j] = 1; + } + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0) { + final int x = Math.min(i + stampHeight, m); + final int y = Math.min(j + stampWidth, n); + if (B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0) + return false; + } + + return true; + } +} diff --git a/solutions/2132. Stamping the Grid/2132.py b/solutions/2132. Stamping the Grid/2132.py new file mode 100644 index 00000000000..3c5834cec9d --- /dev/null +++ b/solutions/2132. Stamping the Grid/2132.py @@ -0,0 +1,33 @@ +class Solution: + def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool: + m = len(grid) + n = len(grid[0]) + # A[i][j] := the number of 1s in grid[0..i)[0..j) + A = [[0] * (n + 1) for _ in range(m + 1)] + # B[i][j] := the number of ways to stamp the submatrix in [0..i)[0..j) + B = [[0] * (n + 1) for _ in range(m + 1)] + # fit[i][j] := true if the stamps can fit with the right-bottom at (i, j) + fit = [[False] * n for _ in range(m)] + + for i in range(m): + for j in range(n): + A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j] + if i + 1 >= stampHeight and j + 1 >= stampWidth: + x = i - stampHeight + 1 + y = j - stampWidth + 1 + if A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0: + fit[i][j] = True + + for i in range(m): + for j in range(n): + B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j] + + for i in range(m): + for j in range(n): + if not grid[i][j]: + x = min(i + stampHeight, m) + y = min(j + stampWidth, n) + if B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0: + return False + + return True diff --git a/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.cpp b/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.cpp new file mode 100644 index 00000000000..16374742f4f --- /dev/null +++ b/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool checkValid(vector>& matrix) { + const int n = matrix.size(); + + for (int i = 0; i < n; ++i) { + bitset<101> row; + bitset<101> col; + for (int j = 0; j < n; ++j) { + row[matrix[i][j]] = true; + col[matrix[j][i]] = true; + } + if (min(row.contains(), col.contains()) < n) + return false; + } + + return true; + } +}; diff --git a/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.java b/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.java new file mode 100644 index 00000000000..ee62e3ceddb --- /dev/null +++ b/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.java @@ -0,0 +1,18 @@ +class Solution { + public boolean checkValid(int[][] matrix) { + final int n = matrix.length; + + for (int i = 0; i < n; ++i) { + Set row = new HashSet<>(); + Set col = new HashSet<>(); + for (int j = 0; j < n; ++j) { + row.add(matrix[i][j]); + col.add(matrix[j][i]); + } + if (Math.min(row.size(), col.size()) < n) + return false; + } + + return true; + } +} diff --git a/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.py b/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.py new file mode 100644 index 00000000000..a69eaace326 --- /dev/null +++ b/solutions/2133. Check if Every Row and Column Contains All Numbers/2133.py @@ -0,0 +1,4 @@ +class Solution: + def checkValid(self, matrix: List[List[int]]) -> bool: + return all(min(len(set(row)), len(set(col))) == len(matrix) + for row, col in zip(matrix, zip(*matrix))) diff --git a/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.cpp b/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.cpp new file mode 100644 index 00000000000..ce8e92bf2e5 --- /dev/null +++ b/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minSwaps(vector& nums) { + const int n = nums.size(); + const int k = ranges::count(nums, 1); + int ones = 0; // the number of ones in the window + int maxOnes = 0; // the maximum number of ones in the window + + for (int i = 0; i < n * 2; ++i) { + if (i >= k && nums[(i - k) % n]) + --ones; + if (nums[i % n]) + ++ones; + maxOnes = max(maxOnes, ones); + } + + return k - maxOnes; + } +}; diff --git a/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.java b/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.java new file mode 100644 index 00000000000..d6c47490ce3 --- /dev/null +++ b/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.java @@ -0,0 +1,18 @@ +class Solution { + public int minSwaps(int[] nums) { + final int n = nums.length; + final int k = (int) Arrays.stream(nums).filter(a -> a == 1).count(); + int ones = 0; // the number of ones in the window + int maxOnes = 0; // the maximum number of ones in the window + + for (int i = 0; i < n * 2; ++i) { + if (i >= k && nums[(i - k) % n] == 1) + --ones; + if (nums[i % n] == 1) + ++ones; + maxOnes = Math.max(maxOnes, ones); + } + + return k - maxOnes; + } +} diff --git a/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.py b/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.py new file mode 100644 index 00000000000..66368530b36 --- /dev/null +++ b/solutions/2134. Minimum Swaps to Group All 1's Together II/2134.py @@ -0,0 +1,15 @@ +class Solution: + def minSwaps(self, nums: List[int]) -> int: + n = len(nums) + k = nums.count(1) + ones = 0 # the number of ones in the window + maxOnes = 0 # the maximum number of ones in the window + + for i in range(n * 2): + if i >= k and nums[i % n - k]: # Magic in Python :) + ones -= 1 + if nums[i % n]: + ones += 1 + maxOnes = max(maxOnes, ones) + + return k - maxOnes diff --git a/solutions/2135. Count Words Obtained After Adding a Letter/2135.cpp b/solutions/2135. Count Words Obtained After Adding a Letter/2135.cpp new file mode 100644 index 00000000000..a5cecc1e0f7 --- /dev/null +++ b/solutions/2135. Count Words Obtained After Adding a Letter/2135.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int wordCount(vector& startWords, vector& targetWords) { + int ans = 0; + unordered_set seen; + + for (const string& w : startWords) + seen.insert(getMask(w)); + + for (const string& w : targetWords) { + const int mask = getMask(w); + for (const char c : w) + // Toggle one character. + if (seen.contains(mask ^ 1 << c - 'a')) { + ++ans; + break; + } + } + + return ans; + } + + private: + int getMask(const string& s) { + int mask = 0; + for (const char c : s) + mask ^= 1 << c - 'a'; + return mask; + } +}; diff --git a/solutions/2135. Count Words Obtained After Adding a Letter/2135.java b/solutions/2135. Count Words Obtained After Adding a Letter/2135.java new file mode 100644 index 00000000000..161aa520bb6 --- /dev/null +++ b/solutions/2135. Count Words Obtained After Adding a Letter/2135.java @@ -0,0 +1,25 @@ +class Solution { + public int wordCount(String[] startWords, String[] targetWords) { + int ans = 0; + Set seen = Arrays.stream(startWords).map(this::getMask).collect(Collectors.toSet()); + + for (final String w : targetWords) { + final int mask = getMask(w); + for (final char c : w.toCharArray()) + // Toggle one character. + if (seen.contains(mask ^ 1 << c - 'a')) { + ++ans; + break; + } + } + + return ans; + } + + private int getMask(final String s) { + int mask = 0; + for (final char c : s.toCharArray()) + mask ^= 1 << c - 'a'; + return mask; + } +} diff --git a/solutions/2135. Count Words Obtained After Adding a Letter/2135.py b/solutions/2135. Count Words Obtained After Adding a Letter/2135.py new file mode 100644 index 00000000000..2d0b34b6639 --- /dev/null +++ b/solutions/2135. Count Words Obtained After Adding a Letter/2135.py @@ -0,0 +1,20 @@ +class Solution: + def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: + def getMask(s: str) -> int: + mask = 0 + for c in s: + mask ^= 1 << ord(c) - ord('a') + return mask + + ans = 0 + seen = set(getMask(w) for w in startWords) + + for targetWord in targetWords: + mask = getMask(targetWord) + for c in targetWord: + # Toggle one character. + if mask ^ 1 << ord(c) - ord('a') in seen: + ans += 1 + break + + return ans diff --git a/solutions/2136. Earliest Possible Day of Full Bloom/2136.cpp b/solutions/2136. Earliest Possible Day of Full Bloom/2136.cpp new file mode 100644 index 00000000000..de3b1bec0af --- /dev/null +++ b/solutions/2136. Earliest Possible Day of Full Bloom/2136.cpp @@ -0,0 +1,26 @@ +struct Seed { + int p; + int g; + Seed(int p, int g) : p(p), g(g) {} +}; + +class Solution { + public: + int earliestFullBloom(vector& plantTime, vector& growTime) { + int ans = 0; + int time = 0; + vector seeds; + + for (int i = 0; i < plantTime.size(); ++i) + seeds.emplace_back(plantTime[i], growTime[i]); + + ranges::sort(seeds, [](const Seed& a, const Seed& b) { return a.g > b.g; }); + + for (const auto& [p, g] : seeds) { + time += p; + ans = max(ans, time + g); + } + + return ans; + } +}; diff --git a/solutions/2136. Earliest Possible Day of Full Bloom/2136.java b/solutions/2136. Earliest Possible Day of Full Bloom/2136.java new file mode 100644 index 00000000000..f0e4b90c605 --- /dev/null +++ b/solutions/2136. Earliest Possible Day of Full Bloom/2136.java @@ -0,0 +1,28 @@ +class Seed { + public int p; + public int g; + public Seed(int p, int g) { + this.p = p; + this.g = g; + } +}; + +class Solution { + public int earliestFullBloom(int[] plantTime, int[] growTime) { + int ans = 0; + int time = 0; + Seed[] seeds = new Seed[n]; + + for (int i = 0; i < plantTime.length; ++i) + seeds[i] = new Seed(plantTime[i], growTime[i]); + + Arrays.sort(seeds, (a, b) -> b.g - a.g); + + for (Seed seed : seeds) { + time += seed.p; + ans = Math.max(ans, time + seed.g); + } + + return ans; + } +} diff --git a/solutions/2136. Earliest Possible Day of Full Bloom/2136.py b/solutions/2136. Earliest Possible Day of Full Bloom/2136.py new file mode 100644 index 00000000000..6f2ab5753e0 --- /dev/null +++ b/solutions/2136. Earliest Possible Day of Full Bloom/2136.py @@ -0,0 +1,10 @@ +class Solution: + def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int: + ans = 0 + time = 0 + + for p, g in sorted([(p, g) for (p, g) in zip(plantTime, growTime)], key=lambda x: -x[1]): + time += p + ans = max(ans, time + g) + + return ans diff --git a/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.cpp b/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.cpp new file mode 100644 index 00000000000..0f32c9d932b --- /dev/null +++ b/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + double equalizeWater(vector& buckets, int loss) { + constexpr double kErr = 1e-5; + const double kPercentage = (100 - loss) / (double)100; + double l = 0.0; + double r = ranges::max(buckets); + + while (r - l > kErr) { + const double m = (l + r) / 2; + if (canFill(buckets, m, kPercentage)) + l = m; + else + r = m; + } + + return l; + } + + private: + bool canFill(const vector& buckets, double target, double kPercentage) { + double extra = 0.0; + double need = 0.0; + for (const int bucket : buckets) + if (bucket > target) + extra += bucket - target; + else + need += target - bucket; + return extra * kPercentage >= need; + } +}; diff --git a/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.java b/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.java new file mode 100644 index 00000000000..98850737cf4 --- /dev/null +++ b/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.java @@ -0,0 +1,29 @@ +class Solution { + public double equalizeWater(int[] buckets, int loss) { + final double kErr = 1e-5; + final double kPercentage = (100 - loss) / (double) 100; + double l = 0.0; + double r = Arrays.stream(buckets).max().getAsInt(); + + while (r - l > kErr) { + final double m = (l + r) / 2; + if (canFill(buckets, m, kPercentage)) + l = m; + else + r = m; + } + + return l; + } + + private boolean canFill(int[] buckets, double target, double kPercentage) { + double extra = 0.0; + double need = 0.0; + for (final int bucket : buckets) + if (bucket > target) + extra += bucket - target; + else + need += target - bucket; + return extra * kPercentage >= need; + }; +} diff --git a/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.py b/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.py new file mode 100644 index 00000000000..d5f688eb38b --- /dev/null +++ b/solutions/2137. Pour Water Between Buckets to Make Water Levels Equal/2137.py @@ -0,0 +1,25 @@ +class Solution: + def equalizeWater(self, buckets: List[int], loss: int) -> float: + kErr = 1e-5 + kPercentage = (100 - loss) / 100 + l = 0.0 + r = max(buckets) + + def canFill(target: float) -> bool: + extra = 0 + need = 0 + for bucket in buckets: + if bucket > target: + extra += bucket - target + else: + need += target - bucket + return extra * kPercentage >= need + + while r - l > kErr: + m = (l + r) / 2 + if canFill(m): + l = m + else: + r = m + + return l diff --git a/solutions/2138. Divide a String Into Groups of Size k/2138.cpp b/solutions/2138. Divide a String Into Groups of Size k/2138.cpp new file mode 100644 index 00000000000..ad5ea24dba2 --- /dev/null +++ b/solutions/2138. Divide a String Into Groups of Size k/2138.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector divideString(string s, int k, char fill) { + vector ans; + + for (int i = 0; i < s.length(); i += k) + ans.push_back(i + k > s.length() + ? s.substr(i) + string(i + k - s.length(), fill) + : s.substr(i, k)); + + return ans; + } +}; diff --git a/solutions/2138. Divide a String Into Groups of Size k/2138.java b/solutions/2138. Divide a String Into Groups of Size k/2138.java new file mode 100644 index 00000000000..a6c8d0bff5a --- /dev/null +++ b/solutions/2138. Divide a String Into Groups of Size k/2138.java @@ -0,0 +1,12 @@ +class Solution { + public String[] divideString(String s, int k, char fill) { + String[] ans = new String[(s.length() + k - 1) / k]; + + for (int i = 0, j = 0; i < s.length(); i += k) + ans[j++] = i + k > s.length() + ? s.substring(i) + String.valueOf(fill).repeat(i + k - s.length()) + : s.substring(i, i + k); + + return ans; + } +} diff --git a/solutions/2138. Divide a String Into Groups of Size k/2138.py b/solutions/2138. Divide a String Into Groups of Size k/2138.py new file mode 100644 index 00000000000..d0aacfad611 --- /dev/null +++ b/solutions/2138. Divide a String Into Groups of Size k/2138.py @@ -0,0 +1,7 @@ +class Solution: + def divideString(self, s: str, k: int, fill: str) -> List[str]: + return [ + s[i:] + fill * (i + k - len(s)) if i + k > len(s) + else s[i:i + k] + for i in range(0, len(s), k) + ] diff --git a/solutions/2139. Minimum Moves to Reach Target Score/2139.cpp b/solutions/2139. Minimum Moves to Reach Target Score/2139.cpp new file mode 100644 index 00000000000..6ae2d0c636e --- /dev/null +++ b/solutions/2139. Minimum Moves to Reach Target Score/2139.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minMoves(int target, int maxDoubles) { + int steps = 0; + + while (target > 1 && maxDoubles) { + if (target % 2 == 1) { + --target; + } else { + target /= 2; + --maxDoubles; + } + ++steps; + } + + return steps + target - 1; + } +}; diff --git a/solutions/2139. Minimum Moves to Reach Target Score/2139.java b/solutions/2139. Minimum Moves to Reach Target Score/2139.java new file mode 100644 index 00000000000..f997ec3da8c --- /dev/null +++ b/solutions/2139. Minimum Moves to Reach Target Score/2139.java @@ -0,0 +1,17 @@ +class Solution { + public int minMoves(int target, int maxDoubles) { + int steps = 0; + + while (target > 1 && maxDoubles > 0) { + if (target % 2 == 1) { + --target; + } else { + target /= 2; + --maxDoubles; + } + ++steps; + } + + return steps + target - 1; + } +} diff --git a/solutions/2139. Minimum Moves to Reach Target Score/2139.py b/solutions/2139. Minimum Moves to Reach Target Score/2139.py new file mode 100644 index 00000000000..349bd624e3b --- /dev/null +++ b/solutions/2139. Minimum Moves to Reach Target Score/2139.py @@ -0,0 +1,13 @@ +class Solution: + def minMoves(self, target: int, maxDoubles: int) -> int: + steps = 0 + + while target > 1 and maxDoubles: + if target % 2 == 1: + target -= 1 + else: + target //= 2 + maxDoubles -= 1 + steps += 1 + + return steps + target - 1 diff --git a/solutions/214. Shortest Palindrome/214.cpp b/solutions/214. Shortest Palindrome/214.cpp new file mode 100644 index 00000000000..e8e7be45482 --- /dev/null +++ b/solutions/214. Shortest Palindrome/214.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + string shortestPalindrome(string s) { + string t = s; + reverse(t.begin(), t.end()); + + const string_view sv_s(s); + const string_view sv_t(t); + + for (int i = 0; i < s.length(); ++i) + if (sv_s.substr(0, s.length() - i) == sv_t.substr(i)) + return t.substr(0, i) + s; + + return t + s; + } +}; diff --git a/solutions/214. Shortest Palindrome/214.java b/solutions/214. Shortest Palindrome/214.java new file mode 100644 index 00000000000..05007e50ee6 --- /dev/null +++ b/solutions/214. Shortest Palindrome/214.java @@ -0,0 +1,11 @@ +class Solution { + public String shortestPalindrome(String s) { + final String t = new StringBuilder(s).reverse().toString(); + + for (int i = 0; i < t.length(); ++i) + if (s.startsWith(t.substring(i))) + return t.substring(0, i) + s; + + return t + s; + } +} diff --git a/solutions/214. Shortest Palindrome/214.py b/solutions/214. Shortest Palindrome/214.py new file mode 100644 index 00000000000..bce739290c4 --- /dev/null +++ b/solutions/214. Shortest Palindrome/214.py @@ -0,0 +1,9 @@ +class Solution: + def shortestPalindrome(self, s: str) -> str: + t = s[::-1] + + for i in range(len(t)): + if s.startswith(t[i:]): + return t[:i] + s + + return t + s diff --git a/solutions/2140. Solving Questions With Brainpower/2140.cpp b/solutions/2140. Solving Questions With Brainpower/2140.cpp new file mode 100644 index 00000000000..40813b49ab4 --- /dev/null +++ b/solutions/2140. Solving Questions With Brainpower/2140.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long long mostPoints(vector>& questions) { + const int n = questions.size(); + // dp[i] := the maximum points starting from questions[i] + vector dp(n + 1); + + for (int i = n - 1; i >= 0; --i) { + const int points = questions[i][0]; + const int brainpower = questions[i][1]; + const int nextIndex = i + brainpower + 1; + const long nextPoints = nextIndex < n ? dp[nextIndex] : 0; + dp[i] = max(points + nextPoints, dp[i + 1]); + } + + return dp[0]; + } +}; diff --git a/solutions/2140. Solving Questions With Brainpower/2140.java b/solutions/2140. Solving Questions With Brainpower/2140.java new file mode 100644 index 00000000000..36b8e038b97 --- /dev/null +++ b/solutions/2140. Solving Questions With Brainpower/2140.java @@ -0,0 +1,17 @@ +class Solution { + public long mostPoints(int[][] questions) { + final int n = questions.length; + // dp[i] := the maximum points starting from questions[i] + long[] dp = new long[n + 1]; + + for (int i = n - 1; i >= 0; --i) { + final int points = questions[i][0]; + final int brainpower = questions[i][1]; + final int nextIndex = i + brainpower + 1; + final long nextPoints = nextIndex < n ? dp[nextIndex] : 0; + dp[i] = Math.max(points + nextPoints, dp[i + 1]); + } + + return dp[0]; + } +} diff --git a/solutions/2140. Solving Questions With Brainpower/2140.py b/solutions/2140. Solving Questions With Brainpower/2140.py new file mode 100644 index 00000000000..6b451f17e68 --- /dev/null +++ b/solutions/2140. Solving Questions With Brainpower/2140.py @@ -0,0 +1,13 @@ +class Solution: + def mostPoints(self, questions: List[List[int]]) -> int: + n = len(questions) + # dp[i] := the maximum points starting from questions[i] + dp = [0] * (n + 1) + + for i in reversed(range(n)): + points, brainpower = questions[i] + nextIndex = i + brainpower + 1 + nextPoints = dp[nextIndex] if nextIndex < n else 0 + dp[i] = max(points + nextPoints, dp[i + 1]) + + return dp[0] diff --git a/solutions/2141. Maximum Running Time of N Computers/2141.cpp b/solutions/2141. Maximum Running Time of N Computers/2141.cpp new file mode 100644 index 00000000000..ebb843cb309 --- /dev/null +++ b/solutions/2141. Maximum Running Time of N Computers/2141.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + long long maxRunTime(int n, vector& batteries) { + long sum = accumulate(batteries.begin(), batteries.end(), 0L); + + ranges::sort(batteries); + + // The maximum battery is greater than the average, so it can last forever. + // Reduce the problem from size n to size n - 1. + while (batteries.back() > sum / n) { + sum -= batteries.back(), batteries.pop_back(); + --n; + } + + // If the maximum battery <= average running time, it won't be waste, and so + // do smaller batteries. + return sum / n; + } +}; diff --git a/solutions/2141. Maximum Running Time of N Computers/2141.java b/solutions/2141. Maximum Running Time of N Computers/2141.java new file mode 100644 index 00000000000..872557372de --- /dev/null +++ b/solutions/2141. Maximum Running Time of N Computers/2141.java @@ -0,0 +1,19 @@ +class Solution { + public long maxRunTime(int n, int[] batteries) { + long sum = Arrays.stream(batteries).asLongStream().sum(); + + Arrays.sort(batteries); + + // The maximum battery is greater than the average, so it can last forever. + // Reduce the problem from size n to size n - 1. + int i = batteries.length - 1; + while (batteries[i] > sum / n) { + sum -= batteries[i--]; + --n; + } + + // If the maximum battery <= average running time, it won't be waste, and so + // do smaller batteries. + return sum / n; + } +} diff --git a/solutions/2141. Maximum Running Time of N Computers/2141.py b/solutions/2141. Maximum Running Time of N Computers/2141.py new file mode 100644 index 00000000000..ed104a4c252 --- /dev/null +++ b/solutions/2141. Maximum Running Time of N Computers/2141.py @@ -0,0 +1,15 @@ +class Solution: + def maxRunTime(self, n: int, batteries: List[int]) -> int: + summ = sum(batteries) + + batteries.sort() + + # The maximum battery is greater than the average, so it can last forever. + # Reduce the problem from size n to size n - 1. + while batteries[-1] > summ // n: + summ -= batteries.pop() + n -= 1 + + # If the maximum battery <= average running time, it won't be waste, and so + # do smaller batteries. + return summ // n diff --git a/solutions/2142. The Number of Passengers in Each Bus I/2142.sql b/solutions/2142. The Number of Passengers in Each Bus I/2142.sql new file mode 100644 index 00000000000..8e8e798b797 --- /dev/null +++ b/solutions/2142. The Number of Passengers in Each Bus I/2142.sql @@ -0,0 +1,20 @@ +WITH + RECURSIVE BusesNeighbors AS ( + SELECT + bus_id, + arrival_time, + IFNULL(LAG(arrival_time) OVER( + ORDER BY arrival_time), 0 + ) AS prev_arrival_time + FROM Buses + ) +SELECT + BusesNeighbors.bus_id, + COUNT(Passengers.passenger_id) AS passengers_cnt +FROM BusesNeighbors +LEFT JOIN Passengers + ON ( + BusesNeighbors.prev_arrival_time < Passengers.arrival_time + AND Passengers.arrival_time <= BusesNeighbors.arrival_time) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2143. Choose Numbers From Two Arrays in Range/2143.cpp b/solutions/2143. Choose Numbers From Two Arrays in Range/2143.cpp new file mode 100644 index 00000000000..58601d2a17a --- /dev/null +++ b/solutions/2143. Choose Numbers From Two Arrays in Range/2143.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int countSubranges(vector& nums1, vector& nums2) { + constexpr int kMod = 1'000'000'007; + int ans = 0; + // {sum, count}, add if choose from nums1, minus if choose from nums2 + unordered_map dp; + + for (int i = 0; i < nums1.size(); ++i) { + // edge case: nums1[i] == nums2[i] == 0, so can't put them in the + // initializer list. + unordered_map newDp; + ++newDp[nums1[i]]; + ++newDp[-nums2[i]]; + + for (const auto& [prevSum, count] : dp) { + // Choose nums1[i]. + newDp[prevSum + nums1[i]] += count; + newDp[prevSum + nums1[i]] %= kMod; + // Choose nums2[i]. + newDp[prevSum - nums2[i]] += count; + newDp[prevSum - nums2[i]] %= kMod; + } + + dp = move(newDp); + if (const auto it = dp.find(0); it != dp.cend()) { + ans += it->second; + ans %= kMod; + } + } + + return ans; + } +}; diff --git a/solutions/2143. Choose Numbers From Two Arrays in Range/2143.java b/solutions/2143. Choose Numbers From Two Arrays in Range/2143.java new file mode 100644 index 00000000000..f695edbca35 --- /dev/null +++ b/solutions/2143. Choose Numbers From Two Arrays in Range/2143.java @@ -0,0 +1,32 @@ +class Solution { + public int countSubranges(int[] nums1, int[] nums2) { + final int kMod = 1_000_000_007; + int ans = 0; + // {sum, count}, add if choose from nums1, minus if choose from nums2 + Map dp = new HashMap<>(); + + for (int i = 0; i < nums1.length; ++i) { + Map newDp = new HashMap<>(); + // edge case: nums1[i] == nums2[i] == 0, so can't put them in the + // initializer list. + newDp.merge(nums1[i], 1, Integer::sum); + newDp.merge(-nums2[i], 1, Integer::sum); + + for (final int prevSum : dp.keySet()) { + final int count = dp.get(prevSum); + final int chooseNums1 = prevSum + nums1[i]; + newDp.put(chooseNums1, (newDp.getOrDefault(chooseNums1, 0) + count) % kMod); + final int chooseNums2 = prevSum - nums2[i]; + newDp.put(chooseNums2, (newDp.getOrDefault(chooseNums2, 0) + count) % kMod); + } + + dp = newDp; + if (dp.containsKey(0)) { + ans += dp.get(0); + ans %= kMod; + } + } + + return ans; + } +} diff --git a/solutions/2143. Choose Numbers From Two Arrays in Range/2143.py b/solutions/2143. Choose Numbers From Two Arrays in Range/2143.py new file mode 100644 index 00000000000..a9958cc35e5 --- /dev/null +++ b/solutions/2143. Choose Numbers From Two Arrays in Range/2143.py @@ -0,0 +1,25 @@ +class Solution: + def countSubranges(self, nums1: List[int], nums2: List[int]) -> int: + kMod = 1_000_000_007 + ans = 0 + # {sum, count}, add if choose from nums1, minus if choose from nums2 + dp = collections.Counter() + + for a, b in zip(nums1, nums2): + newDp = collections.Counter() + newDp[a] += 1 + newDp[-b] += 1 + + for prevSum, count in dp.items(): + # Choose nums1[i] + newDp[prevSum + a] += count + newDp[prevSum + a] %= kMod + # Choose nums2[i] + newDp[prevSum - b] += count + newDp[prevSum - b] %= kMod + + dp = newDp + ans += dp[0] + ans %= kMod + + return ans diff --git a/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.cpp b/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.cpp new file mode 100644 index 00000000000..cc8cc279b9f --- /dev/null +++ b/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minimumCost(vector& cost) { + int ans = 0; + + ranges::sort(cost, [](const int a, const int b) { return a > b; }); + + for (int i = 0; i < cost.size(); ++i) + if (i % 3 != 2) + ans += cost[i]; + + return ans; + } +}; diff --git a/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.java b/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.java new file mode 100644 index 00000000000..6e06f3bab32 --- /dev/null +++ b/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.java @@ -0,0 +1,17 @@ +class Solution { + public int minimumCost(int[] cost) { + int ans = 0; + + cost = Arrays.stream(cost) + .boxed() + .sorted(Collections.reverseOrder()) + .mapToInt(Integer::intValue) + .toArray(); + + for (int i = 0; i < cost.length; ++i) + if (i % 3 != 2) + ans += cost[i]; + + return ans; + } +} diff --git a/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.py b/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.py new file mode 100644 index 00000000000..d9110aa1cac --- /dev/null +++ b/solutions/2144. Minimum Cost of Buying Candies With Discount/2144.py @@ -0,0 +1,3 @@ +class Solution: + def minimumCost(self, cost: List[int]) -> int: + return sum(cost) - sum(sorted(cost)[-3::-3]) diff --git a/solutions/2145. Count the Hidden Sequences/2145-2.cpp b/solutions/2145. Count the Hidden Sequences/2145-2.cpp new file mode 100644 index 00000000000..395b6175e17 --- /dev/null +++ b/solutions/2145. Count the Hidden Sequences/2145-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int numberOfArrays(vector& differences, int lower, int upper) { + long prefix = 0; + long mn = 0; // Starts from 0. + long mx = 0; // Starts from 0. + + for (const int d : differences) { + prefix += d; + mn = min(mn, prefix); + mx = max(mx, prefix); + } + + return max(0L, (upper - lower) - (mx - mn) + 1); + } +}; diff --git a/solutions/2145. Count the Hidden Sequences/2145-2.java b/solutions/2145. Count the Hidden Sequences/2145-2.java new file mode 100644 index 00000000000..571b40d8116 --- /dev/null +++ b/solutions/2145. Count the Hidden Sequences/2145-2.java @@ -0,0 +1,15 @@ +class Solution { + public int numberOfArrays(int[] differences, int lower, int upper) { + long prefix = 0; + long mn = 0; // Starts from 0. + long mx = 0; // Starts from 0. + + for (final int d : differences) { + prefix += d; + mn = Math.min(mn, prefix); + mx = Math.max(mx, prefix); + } + + return (int) Math.max(0L, (upper - lower) - (mx - mn) + 1); + } +} diff --git a/solutions/2145. Count the Hidden Sequences/2145-2.py b/solutions/2145. Count the Hidden Sequences/2145-2.py new file mode 100644 index 00000000000..1ae326959c8 --- /dev/null +++ b/solutions/2145. Count the Hidden Sequences/2145-2.py @@ -0,0 +1,12 @@ +class Solution: + def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int: + prefix = 0 + mn = 0 # Starts from 0. + mx = 0 # Starts from 0. + + for d in differences: + prefix += d + mn = min(mn, prefix) + mx = max(mx, prefix) + + return max(0, (upper - lower) - (mx - mn) + 1) diff --git a/solutions/2145. Count the Hidden Sequences/2145.cpp b/solutions/2145. Count the Hidden Sequences/2145.cpp new file mode 100644 index 00000000000..dd9fa61d0b4 --- /dev/null +++ b/solutions/2145. Count the Hidden Sequences/2145.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int numberOfArrays(vector& differences, int lower, int upper) { + // Starts from 0, so prefix[0] = 0. + // Changing prefix[0] to any other number doesn't affect the answer. + vector prefix(differences.size() + 1); + + for (int i = 0; i < differences.size(); ++i) + prefix[i + 1] += prefix[i] + differences[i]; + + const long mx = ranges::max(prefix); + const long mn = ranges::min(prefix); + return max(0L, (upper - lower) - (mx - mn) + 1); + } +}; diff --git a/solutions/2145. Count the Hidden Sequences/2145.java b/solutions/2145. Count the Hidden Sequences/2145.java new file mode 100644 index 00000000000..47bb99b0708 --- /dev/null +++ b/solutions/2145. Count the Hidden Sequences/2145.java @@ -0,0 +1,14 @@ +class Solution { + public int numberOfArrays(int[] differences, int lower, int upper) { + // Starts from 0, so prefix[0] = 0. + // Changing prefix[0] to any other number doesn't affect the answer. + long[] prefix = new long[differences.length + 1]; + + for (int i = 0; i < differences.length; ++i) + prefix[i + 1] += prefix[i] + differences[i]; + + final long mx = Arrays.stream(prefix).max().getAsLong(); + final long mn = Arrays.stream(prefix).min().getAsLong(); + return (int) Math.max(0L, (upper - lower) - (mx - mn) + 1); + } +} diff --git a/solutions/2145. Count the Hidden Sequences/2145.py b/solutions/2145. Count the Hidden Sequences/2145.py new file mode 100644 index 00000000000..f4046a1dbe1 --- /dev/null +++ b/solutions/2145. Count the Hidden Sequences/2145.py @@ -0,0 +1,4 @@ +class Solution: + def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int: + prefix = [0] + list(itertools.accumulate(differences)) + return max(0, (upper - lower) - (max(prefix) - min(prefix)) + 1) diff --git a/solutions/2146. K Highest Ranked Items Within a Price Range/2146.cpp b/solutions/2146. K Highest Ranked Items Within a Price Range/2146.cpp new file mode 100644 index 00000000000..658affc00fe --- /dev/null +++ b/solutions/2146. K Highest Ranked Items Within a Price Range/2146.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + vector> highestRankedKItems(vector>& grid, + vector& pricing, + vector& start, int k) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + const int low = pricing[0]; + const int high = pricing[1]; + const int row = start[0]; + const int col = start[1]; + vector> ans; + + if (low <= grid[row][col] && grid[row][col] <= high) { + ans.push_back({row, col}); + if (k == 1) + return ans; + } + + queue> q{{{row, col}}}; + vector> seen(m, vector(n)); + seen[row][col] = true; // Mark as visited. + + while (!q.empty()) { + vector> neighbors; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (!grid[x][y] || seen[x][y]) + continue; + if (low <= grid[x][y] && grid[x][y] <= high) + neighbors.push_back({x, y}); + q.emplace(x, y); + seen[x][y] = true; + } + } + ranges::sort(neighbors, [&](const vector& a, const vector& b) { + const int x1 = a[0]; + const int y1 = a[1]; + const int x2 = b[0]; + const int y2 = b[1]; + if (grid[x1][y1] != grid[x2][y2]) + return grid[x1][y1] < grid[x2][y2]; + return x1 == x2 ? y1 < y2 : x1 < x2; + }); + for (const vector& neighbor : neighbors) { + if (ans.size() < k) + ans.push_back(neighbor); + if (ans.size() == k) + return ans; + } + } + + return ans; + } +}; diff --git a/solutions/2146. K Highest Ranked Items Within a Price Range/2146.java b/solutions/2146. K Highest Ranked Items Within a Price Range/2146.java new file mode 100644 index 00000000000..922f2a9ac5b --- /dev/null +++ b/solutions/2146. K Highest Ranked Items Within a Price Range/2146.java @@ -0,0 +1,62 @@ +class Solution { + public List> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length; + final int low = pricing[0]; + final int high = pricing[1]; + final int row = start[0]; + final int col = start[1]; + List> ans = new ArrayList<>(); + + if (low <= grid[row][col] && grid[row][col] <= high) { + ans.add(Arrays.asList(row, col)); + if (k == 1) + return ans; + } + + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(row, col))); + boolean[][] seen = new boolean[m][n]; + seen[row][col] = true; // Mark as visited. + + while (!q.isEmpty()) { + List> neighbors = new ArrayList<>(); + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] == 0 || seen[x][y]) + continue; + if (low <= grid[x][y] && grid[x][y] <= high) + neighbors.add(Arrays.asList(x, y)); + q.offer(new Pair<>(x, y)); + seen[x][y] = true; + } + } + Collections.sort(neighbors, new Comparator>() { + @Override + public int compare(List a, List b) { + final int x1 = a.get(0); + final int y1 = a.get(1); + final int x2 = b.get(0); + final int y2 = b.get(1); + if (grid[x1][y1] != grid[x2][y2]) + return grid[x1][y1] - grid[x2][y2]; + return x1 == x2 ? y1 - y2 : x1 - x2; + } + }); + for (List neighbor : neighbors) { + if (ans.size() < k) + ans.add(neighbor); + if (ans.size() == k) + return ans; + } + } + + return ans; + } +} diff --git a/solutions/2146. K Highest Ranked Items Within a Price Range/2146.py b/solutions/2146. K Highest Ranked Items Within a Price Range/2146.py new file mode 100644 index 00000000000..889f79fbc15 --- /dev/null +++ b/solutions/2146. K Highest Ranked Items Within a Price Range/2146.py @@ -0,0 +1,40 @@ +class Solution: + def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + low, high = pricing + row, col = start + ans = [] + + if low <= grid[row][col] <= high: + ans.append([row, col]) + if k == 1: + return ans + + q = collections.deque([(row, col)]) + seen = {(row, col)} # Mark as visited. + + while q: + neighbors = [] + for _ in range(len(q)): + i, j = q.popleft() + for t in range(4): + x = i + dirs[t] + y = j + dirs[t + 1] + if x < 0 or x == m or y < 0 or y == n: + continue + if not grid[x][y] or (x, y) in seen: + continue + if low <= grid[x][y] <= high: + neighbors.append([x, y]) + q.append((x, y)) + seen.add((x, y)) + neighbors.sort(key=lambda x: (grid[x[0]][x[1]], x[0], x[1])) + for neighbor in neighbors: + if len(ans) < k: + ans.append(neighbor) + if len(ans) == k: + return ans + + return ans diff --git a/solutions/2147. Number of Ways to Divide a Long Corridor/2147.cpp b/solutions/2147. Number of Ways to Divide a Long Corridor/2147.cpp new file mode 100644 index 00000000000..ac7fb83b62d --- /dev/null +++ b/solutions/2147. Number of Ways to Divide a Long Corridor/2147.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int numberOfWays(string corridor) { + constexpr int kMod = 1'000'000'007; + long ans = 1; + int prevSeat = -1; + int numSeats = 0; + + for (int i = 0; i < corridor.length(); ++i) { + if (corridor[i] == 'S') { + if (++numSeats > 2 && numSeats % 2 == 1) + ans = ans * (i - prevSeat) % kMod; + prevSeat = i; + } + } + + return numSeats > 1 && numSeats % 2 == 0 ? ans : 0; + } +}; diff --git a/solutions/2147. Number of Ways to Divide a Long Corridor/2147.java b/solutions/2147. Number of Ways to Divide a Long Corridor/2147.java new file mode 100644 index 00000000000..cee0b36e572 --- /dev/null +++ b/solutions/2147. Number of Ways to Divide a Long Corridor/2147.java @@ -0,0 +1,18 @@ +class Solution { + public int numberOfWays(String corridor) { + final int kMod = 1_000_000_007; + long ans = 1; + int prevSeat = -1; + int numSeats = 0; + + for (int i = 0; i < corridor.length(); ++i) { + if (corridor.charAt(i) == 'S') { + if (++numSeats > 2 && numSeats % 2 == 1) + ans = ans * (i - prevSeat) % kMod; + prevSeat = i; + } + } + + return numSeats > 1 && numSeats % 2 == 0 ? (int) ans : 0; + } +} diff --git a/solutions/2147. Number of Ways to Divide a Long Corridor/2147.py b/solutions/2147. Number of Ways to Divide a Long Corridor/2147.py new file mode 100644 index 00000000000..056c6de2638 --- /dev/null +++ b/solutions/2147. Number of Ways to Divide a Long Corridor/2147.py @@ -0,0 +1,15 @@ +class Solution: + def numberOfWays(self, corridor: str) -> int: + kMod = 1_000_000_007 + ans = 1 + prevSeat = -1 + numSeats = 0 + + for i, c in enumerate(corridor): + if c == 'S': + numSeats += 1 + if numSeats > 2 and numSeats % 2 == 1: + ans = ans * (i - prevSeat) % kMod + prevSeat = i + + return ans if numSeats > 1 and numSeats % 2 == 0 else 0 diff --git a/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.cpp b/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.cpp new file mode 100644 index 00000000000..ed446caabda --- /dev/null +++ b/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int countElements(vector& nums) { + const int mn = ranges::min(nums); + const int mx = ranges::max(nums); + return ranges::count_if( + nums, [&](const int num) { return mn < num && num < mx; }); + } +}; diff --git a/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.java b/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.java new file mode 100644 index 00000000000..ea3fdffc29d --- /dev/null +++ b/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.java @@ -0,0 +1,7 @@ +class Solution { + public int countElements(int[] nums) { + final int mn = Arrays.stream(nums).min().getAsInt(); + final int mx = Arrays.stream(nums).max().getAsInt(); + return (int) Arrays.stream(nums).filter(num -> mn < num && num < mx).count(); + } +} diff --git a/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.py b/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.py new file mode 100644 index 00000000000..2a7e8912413 --- /dev/null +++ b/solutions/2148. Count Elements With Strictly Smaller and Greater Elements/2148.py @@ -0,0 +1,5 @@ +class Solution: + def countElements(self, nums: List[int]) -> int: + mn = min(nums) + mx = max(nums) + return sum(mn < num < mx for num in nums) diff --git a/solutions/2149. Rearrange Array Elements by Sign/2149.cpp b/solutions/2149. Rearrange Array Elements by Sign/2149.cpp new file mode 100644 index 00000000000..a6fcc2eb21c --- /dev/null +++ b/solutions/2149. Rearrange Array Elements by Sign/2149.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector rearrangeArray(vector& nums) { + vector ans; + vector pos; + vector neg; + + for (const int num : nums) + (num > 0 ? pos : neg).push_back(num); + + for (int i = 0; i < pos.size(); ++i) { + ans.push_back(pos[i]); + ans.push_back(neg[i]); + } + + return ans; + } +}; diff --git a/solutions/2149. Rearrange Array Elements by Sign/2149.java b/solutions/2149. Rearrange Array Elements by Sign/2149.java new file mode 100644 index 00000000000..d5bcbe24265 --- /dev/null +++ b/solutions/2149. Rearrange Array Elements by Sign/2149.java @@ -0,0 +1,17 @@ +class Solution { + public int[] rearrangeArray(int[] nums) { + int[] ans = new int[nums.length]; + List pos = new ArrayList<>(); + List neg = new ArrayList<>(); + + for (final int num : nums) + (num > 0 ? pos : neg).add(num); + + for (int i = 0; i < pos.size(); ++i) { + ans[i * 2] = pos.get(i); + ans[i * 2 + 1] = neg.get(i); + } + + return ans; + } +} diff --git a/solutions/2149. Rearrange Array Elements by Sign/2149.py b/solutions/2149. Rearrange Array Elements by Sign/2149.py new file mode 100644 index 00000000000..fbb5e80e670 --- /dev/null +++ b/solutions/2149. Rearrange Array Elements by Sign/2149.py @@ -0,0 +1,13 @@ +class Solution: + def rearrangeArray(self, nums: List[int]) -> List[int]: + ans = [] + pos = [] + neg = [] + + for num in nums: + (pos if num > 0 else neg).append(num) + + for p, n in zip(pos, neg): + ans += [p, n] + + return ans diff --git a/solutions/215. Kth Largest Element in an Array/215-2.cpp b/solutions/215. Kth Largest Element in an Array/215-2.cpp new file mode 100644 index 00000000000..f09f2cd1751 --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int findKthLargest(vector& nums, int k) { + return quickSelect(nums, 0, nums.size() - 1, k); + } + + private: + int quickSelect(vector& nums, int l, int r, int k) { + const int pivot = nums[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (nums[i] >= pivot) + swap(nums[nextSwapped++], nums[i]); + swap(nums[nextSwapped], nums[r]); + + const int count = nextSwapped - l + 1; // the number of `nums` >= pivot + if (count == k) + return nums[nextSwapped]; + if (count > k) + return quickSelect(nums, l, nextSwapped - 1, k); + return quickSelect(nums, nextSwapped + 1, r, k - count); + } +}; diff --git a/solutions/215. Kth Largest Element in an Array/215-2.java b/solutions/215. Kth Largest Element in an Array/215-2.java new file mode 100644 index 00000000000..856c396077d --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215-2.java @@ -0,0 +1,28 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + return quickSelect(nums, 0, nums.length - 1, k); + } + + private int quickSelect(int[] nums, int l, int r, int k) { + final int pivot = nums[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (nums[i] >= pivot) + swap(nums, nextSwapped++, i); + swap(nums, nextSwapped, r); + + final int count = nextSwapped - l + 1; // the number of `nums` >= pivot + if (count == k) + return nums[nextSwapped]; + if (count > k) + return quickSelect(nums, l, nextSwapped - 1, k); + return quickSelect(nums, nextSwapped + 1, r, k - count); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/215. Kth Largest Element in an Array/215-2.py b/solutions/215. Kth Largest Element in an Array/215-2.py new file mode 100644 index 00000000000..a04c40c8904 --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215-2.py @@ -0,0 +1,20 @@ +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + def quickSelect(l: int, r: int, k: int) -> int: + pivot = nums[r] + + nextSwapped = l + for i in range(l, r): + if nums[i] >= pivot: + nums[nextSwapped], nums[i] = nums[i], nums[nextSwapped] + nextSwapped += 1 + nums[nextSwapped], nums[r] = nums[r], nums[nextSwapped] + + count = nextSwapped - l + 1 # Number of nums >= pivot + if count == k: + return nums[nextSwapped] + if count > k: + return quickSelect(l, nextSwapped - 1, k) + return quickSelect(nextSwapped + 1, r, k - count) + + return quickSelect(0, len(nums) - 1, k) diff --git a/solutions/215. Kth Largest Element in an Array/215-3.cpp b/solutions/215. Kth Largest Element in an Array/215-3.cpp new file mode 100644 index 00000000000..933be0a346a --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215-3.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int findKthLargest(vector& nums, int k) { + return quickSelect(nums, 0, nums.size() - 1, k); + } + + private: + int quickSelect(vector& nums, int l, int r, int k) { + const int randIndex = rand() % (r - l + 1) + l; + swap(nums[randIndex], nums[r]); + const int pivot = nums[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (nums[i] >= pivot) + swap(nums[nextSwapped++], nums[i]); + swap(nums[nextSwapped], nums[r]); + + const int count = nextSwapped - l + 1; // the number of `nums` >= pivot + if (count == k) + return nums[nextSwapped]; + if (count > k) + return quickSelect(nums, l, nextSwapped - 1, k); + return quickSelect(nums, nextSwapped + 1, r, k - count); + } +}; diff --git a/solutions/215. Kth Largest Element in an Array/215-3.java b/solutions/215. Kth Largest Element in an Array/215-3.java new file mode 100644 index 00000000000..6bd47f56909 --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215-3.java @@ -0,0 +1,30 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + return quickSelect(nums, 0, nums.length - 1, k); + } + + private int quickSelect(int[] nums, int l, int r, int k) { + final int randIndex = new Random().nextInt(r - l + 1) + l; + swap(nums, randIndex, r); + final int pivot = nums[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (nums[i] >= pivot) + swap(nums, nextSwapped++, i); + swap(nums, nextSwapped, r); + + final int count = nextSwapped - l + 1; // the number of `nums` >= pivot + if (count == k) + return nums[nextSwapped]; + if (count > k) + return quickSelect(nums, l, nextSwapped - 1, k); + return quickSelect(nums, nextSwapped + 1, r, k - count); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/215. Kth Largest Element in an Array/215-3.py b/solutions/215. Kth Largest Element in an Array/215-3.py new file mode 100644 index 00000000000..6dcfa95578a --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215-3.py @@ -0,0 +1,22 @@ +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + def quickSelect(l: int, r: int, k: int) -> int: + randIndex = random.randint(0, r - l) + l + nums[randIndex], nums[r] = nums[r], nums[randIndex] + pivot = nums[r] + + nextSwapped = l + for i in range(l, r): + if nums[i] >= pivot: + nums[nextSwapped], nums[i] = nums[i], nums[nextSwapped] + nextSwapped += 1 + nums[nextSwapped], nums[r] = nums[r], nums[nextSwapped] + + count = nextSwapped - l + 1 # Number of nums >= pivot + if count == k: + return nums[nextSwapped] + if count > k: + return quickSelect(l, nextSwapped - 1, k) + return quickSelect(nextSwapped + 1, r, k - count) + + return quickSelect(0, len(nums) - 1, k) diff --git a/solutions/215. Kth Largest Element in an Array/215.cpp b/solutions/215. Kth Largest Element in an Array/215.cpp new file mode 100644 index 00000000000..3a1f6c6cd88 --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int findKthLargest(vector& nums, int k) { + priority_queue, greater<>> minHeap; + + for (const int num : nums) { + minHeap.push(num); + if (minHeap.size() > k) + minHeap.pop(); + } + + return minHeap.top(); + } +}; diff --git a/solutions/215. Kth Largest Element in an Array/215.java b/solutions/215. Kth Largest Element in an Array/215.java new file mode 100644 index 00000000000..dc020d27f12 --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215.java @@ -0,0 +1,13 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + Queue minHeap = new PriorityQueue<>(); + + for (final int num : nums) { + minHeap.offer(num); + while (minHeap.size() > k) + minHeap.poll(); + } + + return minHeap.peek(); + } +} diff --git a/solutions/215. Kth Largest Element in an Array/215.py b/solutions/215. Kth Largest Element in an Array/215.py new file mode 100644 index 00000000000..467d599478f --- /dev/null +++ b/solutions/215. Kth Largest Element in an Array/215.py @@ -0,0 +1,10 @@ +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + minHeap = [] + + for num in nums: + heapq.heappush(minHeap, num) + if len(minHeap) > k: + heapq.heappop(minHeap) + + return minHeap[0] diff --git a/solutions/2150. Find All Lonely Numbers in the Array/2150.cpp b/solutions/2150. Find All Lonely Numbers in the Array/2150.cpp new file mode 100644 index 00000000000..2f637720bad --- /dev/null +++ b/solutions/2150. Find All Lonely Numbers in the Array/2150.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector findLonely(vector& nums) { + vector ans; + unordered_map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [num, freq] : count) + if (freq == 1 && !count.contains(num - 1) && !count.contains(num + 1)) + ans.push_back(num); + + return ans; + } +}; diff --git a/solutions/2150. Find All Lonely Numbers in the Array/2150.java b/solutions/2150. Find All Lonely Numbers in the Array/2150.java new file mode 100644 index 00000000000..1c158056cb1 --- /dev/null +++ b/solutions/2150. Find All Lonely Numbers in the Array/2150.java @@ -0,0 +1,15 @@ +class Solution { + public List findLonely(int[] nums) { + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int num : count.keySet()) + if (count.get(num) == 1 && !count.containsKey(num - 1) && !count.containsKey(num + 1)) + ans.add(num); + + return ans; + } +} diff --git a/solutions/2150. Find All Lonely Numbers in the Array/2150.py b/solutions/2150. Find All Lonely Numbers in the Array/2150.py new file mode 100644 index 00000000000..9171642c704 --- /dev/null +++ b/solutions/2150. Find All Lonely Numbers in the Array/2150.py @@ -0,0 +1,7 @@ +class Solution: + def findLonely(self, nums: List[int]) -> List[int]: + count = collections.Counter(nums) + return [num for num, freq in count.items() + if freq == 1 and + count[num - 1] == 0 and + count[num + 1] == 0] diff --git a/solutions/2151. Maximum Good People Based on Statements/2151-2.cpp b/solutions/2151. Maximum Good People Based on Statements/2151-2.cpp new file mode 100644 index 00000000000..69f29309bbe --- /dev/null +++ b/solutions/2151. Maximum Good People Based on Statements/2151-2.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int maximumGood(vector>& statements) { + const int maxMask = 1 << statements.size(); + int ans = 0; + + for (unsigned mask = 0; mask < maxMask; ++mask) + if (isValid(statements, mask)) + ans = max(ans, popcount(mask)); + + return ans; + } + + private: + bool isValid(const vector>& statements, int mask) { + for (int i = 0; i < statements.size(); ++i) { + if ((mask >> i & 1) == 0) // The i-th person is bad, so no need to check. + continue; + for (int j = 0; j < statements.size(); ++j) { + if (statements[i][j] == 2) + continue; + if (statements[i][j] != (mask >> j & 1)) + return false; + } + } + return true; + } +}; diff --git a/solutions/2151. Maximum Good People Based on Statements/2151-2.java b/solutions/2151. Maximum Good People Based on Statements/2151-2.java new file mode 100644 index 00000000000..1f58680d535 --- /dev/null +++ b/solutions/2151. Maximum Good People Based on Statements/2151-2.java @@ -0,0 +1,26 @@ +class Solution { + public int maximumGood(int[][] statements) { + final int maxMask = 1 << statements.length; + int ans = 0; + + for (int mask = 0; mask < maxMask; ++mask) + if (isValid(statements, mask)) + ans = Math.max(ans, Integer.bitCount(mask)); + + return ans; + } + + private boolean isValid(int[][] statements, int mask) { + for (int i = 0; i < statements.length; ++i) { + if ((mask >> i & 1) == 0) // The i-th person is bad, so no need to check. + continue; + for (int j = 0; j < statements.length; ++j) { + if (statements[i][j] == 2) + continue; + if (statements[i][j] != (mask >> j & 1)) + return false; + } + } + return true; + } +} diff --git a/solutions/2151. Maximum Good People Based on Statements/2151-2.py b/solutions/2151. Maximum Good People Based on Statements/2151-2.py new file mode 100644 index 00000000000..485213d3b4d --- /dev/null +++ b/solutions/2151. Maximum Good People Based on Statements/2151-2.py @@ -0,0 +1,19 @@ +class Solution: + def maximumGood(self, statements: List[List[int]]) -> int: + n = len(statements) + + def isValid(mask: int) -> bool: + for i in range(n): + # The i-th person is bad, so no need to check. + if (mask >> i & 1) == 0: + continue + for j in range(n): + if statements[i][j] == 2: + continue + if statements[i][j] != (mask >> j & 1): + return False + return True + + return max(mask.bit_count() + for mask in range(1 << n) + if isValid(mask)) diff --git a/solutions/2151. Maximum Good People Based on Statements/2151.cpp b/solutions/2151. Maximum Good People Based on Statements/2151.cpp new file mode 100644 index 00000000000..adcbf78d4a6 --- /dev/null +++ b/solutions/2151. Maximum Good People Based on Statements/2151.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int maximumGood(vector>& statements) { + int ans = 0; + dfs(statements, {}, 0, 0, ans); + return ans; + } + + private: + void dfs(const vector>& statements, vector&& good, int i, + int count, int& ans) { + if (i == statements.size()) { + if (isValid(statements, good)) + ans = max(ans, count); + return; + } + + good.push_back(0); // Assume the i-th person is bad. + dfs(statements, move(good), i + 1, count, ans); + good.back() = 1; // Assume the i-th person is good. + dfs(statements, move(good), i + 1, count + 1, ans); + good.pop_back(); + } + + bool isValid(const vector>& statements, const vector& good) { + for (int i = 0; i < good.size(); ++i) { + if (!good[i]) // The i-th person is bad, so no need to check. + continue; + for (int j = 0; j < statements.size(); ++j) { + if (statements[i][j] == 2) + continue; + if (statements[i][j] != good[j]) + return false; + } + } + return true; + } +}; diff --git a/solutions/2151. Maximum Good People Based on Statements/2151.java b/solutions/2151. Maximum Good People Based on Statements/2151.java new file mode 100644 index 00000000000..2c209883b52 --- /dev/null +++ b/solutions/2151. Maximum Good People Based on Statements/2151.java @@ -0,0 +1,36 @@ +class Solution { + public int maximumGood(int[][] statements) { + dfs(statements, new ArrayList<>(), 0, 0); + return ans; + } + + private int ans = 0; + + private void dfs(int[][] statements, List good, int i, int count) { + if (i == statements.length) { + if (isValid(statements, good)) + ans = Math.max(ans, count); + return; + } + + good.add(0); // Assume the i-th person is bad. + dfs(statements, good, i + 1, count); + good.set(good.size() - 1, 1); // Assume the i-th person is good. + dfs(statements, good, i + 1, count + 1); + good.remove(good.size() - 1); + } + + private boolean isValid(int[][] statements, List good) { + for (int i = 0; i < good.size(); ++i) { + if (good.get(i) == 0) // The i-th person is bad, so no need to check. + continue; + for (int j = 0; j < statements.length; ++j) { + if (statements[i][j] == 2) + continue; + if (statements[i][j] != good.get(j)) + return false; + } + } + return true; + } +} diff --git a/solutions/2151. Maximum Good People Based on Statements/2151.py b/solutions/2151. Maximum Good People Based on Statements/2151.py new file mode 100644 index 00000000000..47906a6d6c1 --- /dev/null +++ b/solutions/2151. Maximum Good People Based on Statements/2151.py @@ -0,0 +1,31 @@ +class Solution: + def maximumGood(self, statements: List[List[int]]) -> int: + n = len(statements) + ans = 0 + + def isValid(good: List[int]) -> bool: + for i, g in enumerate(good): + if not g: # The i-th person is bad, so no need to check. + continue + for j in range(n): + if statements[i][j] == 2: + continue + if statements[i][j] != good[j]: + return False + return True + + def dfs(good: List[int], i: int, count: int) -> None: + nonlocal ans + if i == n: + if isValid(good): + ans = max(ans, count) + return + + good.append(0) # Assume the i-th person is bad. + dfs(good, i + 1, count) + good[-1] = 1 # Assume the i-th person is good. + dfs(good, i + 1, count + 1) + good.pop() + + dfs([], 0, 0) + return ans diff --git a/solutions/2152. Minimum Number of Lines to Cover Points/2152.cpp b/solutions/2152. Minimum Number of Lines to Cover Points/2152.cpp new file mode 100644 index 00000000000..2e4c688816d --- /dev/null +++ b/solutions/2152. Minimum Number of Lines to Cover Points/2152.cpp @@ -0,0 +1,53 @@ +class Solution { + public: + int minimumLines(vector>& points) { + const int allCovered = (1 << points.size()) - 1; + return dfs(points, 0, allCovered, vector(allCovered, -1)); + } + + private: + int dfs(const vector>& points, int covered, int allCovered, + vector&& mem) { + if (covered == allCovered) + return 0; + if (mem[covered] != -1) + return mem[covered]; + + const int n = points.size(); + int ans = n / 2 + (n & 1); + + for (int i = 0; i < n; ++i) { + if (covered >> i & 1) + continue; + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + // Connect the points[i] with the points[j]. + int newCovered = covered | 1 << i | 1 << j; + // Mark the points covered by this line. + const pair slope = getSlope(points[i], points[j]); + for (int k = 0; k < n; ++k) + if (getSlope(points[i], points[k]) == slope) + newCovered |= 1 << k; + ans = min(ans, 1 + dfs(points, newCovered, allCovered, move(mem))); + } + } + + return mem[covered] = ans; + } + + pair getSlope(const vector& p, const vector& q) { + const int dx = p[0] - q[0]; + const int dy = p[1] - q[1]; + if (dx == 0) + return {0, p[0]}; + if (dy == 0) + return {p[1], 0}; + const int d = __gcd(dx, dy); + const int x = dx / d; + const int y = dy / d; + if (x > 0) + return {x, y}; + return {-x, -y}; + } +}; diff --git a/solutions/2152. Minimum Number of Lines to Cover Points/2152.java b/solutions/2152. Minimum Number of Lines to Cover Points/2152.java new file mode 100644 index 00000000000..26191223c0d --- /dev/null +++ b/solutions/2152. Minimum Number of Lines to Cover Points/2152.java @@ -0,0 +1,54 @@ +class Solution { + public int minimumLines(int[][] points) { + final int allCovered = (1 << points.length) - 1; + int[] mem = new int[allCovered]; + Arrays.fill(mem, -1); + return dfs(points, 0, allCovered, mem); + } + + private int dfs(int[][] points, int covered, int allCovered, int[] mem) { + if (covered == allCovered) + return 0; + if (mem[covered] != -1) + return mem[covered]; + + final int n = points.length; + int ans = n / 2 + ((n & 1) == 1 ? 1 : 0); + + for (int i = 0; i < n; ++i) { + if ((covered >> i & 1) == 1) + continue; + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + // Connect the points[i] with the points[j]. + int newCovered = covered | 1 << i | 1 << j; + // Mark the points covered by this line. + Pair slope = getSlope(points[i], points[j]); + for (int k = 0; k < n; ++k) + if (getSlope(points[i], points[k]).equals(slope)) + newCovered |= 1 << k; + ans = Math.min(ans, 1 + dfs(points, newCovered, allCovered, mem)); + } + } + + return mem[covered] = ans; + } + + private Pair getSlope(int[] p, int[] q) { + final int dx = p[0] - q[0]; + final int dy = p[1] - q[1]; + if (dx == 0) + return new Pair<>(0, p[0]); + if (dy == 0) + return new Pair<>(p[1], 0); + final int d = gcd(dx, dy); + final int x = dx / d; + final int y = dy / d; + return x > 0 ? new Pair<>(x, y) : new Pair<>(-x, -y); + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2152. Minimum Number of Lines to Cover Points/2152.py b/solutions/2152. Minimum Number of Lines to Cover Points/2152.py new file mode 100644 index 00000000000..e03704e3722 --- /dev/null +++ b/solutions/2152. Minimum Number of Lines to Cover Points/2152.py @@ -0,0 +1,43 @@ +class Solution: + def minimumLines(self, points: List[List[int]]) -> int: + n = len(points) + allCovered = (1 << n) - 1 + maxLines = n // 2 + (n & 1) + + def getSlope(p: List[int], q: List[int]) -> Tuple[int, int]: + dx = p[0] - q[0] + dy = p[1] - q[1] + if dx == 0: + return (0, p[0]) + if dy == 0: + return (p[1], 0) + d = gcd(dx, dy) + x = dx // d + y = dy // d + return (x, y) if x > 0 else (-x, -y) + + @functools.lru_cache(None) + def dfs(covered: int) -> int: + if covered == allCovered: + return 0 + + ans = maxLines + + for i in range(n): + if covered >> i & 1: + continue + for j in range(n): + if i == j: + continue + # Connect the points[i] with the points[j]. + newCovered = covered | 1 << i | 1 << j + slope = getSlope(points[i], points[j]) + # Mark the points covered by this line. + for k in range(n): + if getSlope(points[i], points[k]) == slope: + newCovered |= 1 << k + ans = min(ans, 1 + dfs(newCovered)) + + return ans + + return dfs(0) diff --git a/solutions/2153. The Number of Passengers in Each Bus II/2153.sql b/solutions/2153. The Number of Passengers in Each Bus II/2153.sql new file mode 100644 index 00000000000..158b3ecbd41 --- /dev/null +++ b/solutions/2153. The Number of Passengers in Each Bus II/2153.sql @@ -0,0 +1,62 @@ +WITH + RECURSIVE BusesNeighbors AS ( + SELECT + bus_id, + arrival_time, + capacity, + IFNULL(LAG(arrival_time) OVER( + ORDER BY arrival_time), 0 + ) AS prev_arrival_time + FROM Buses + ), + BusesMetadata AS ( + SELECT + BusesNeighbors.bus_id, + BusesNeighbors.arrival_time, + BusesNeighbors.capacity, + BusesNeighbors.prev_arrival_time, + COUNT(Passengers.passenger_id) AS waiting, + ROW_NUMBER() OVER( + ORDER BY BusesNeighbors.arrival_time + ) AS `row_number` + FROM BusesNeighbors + LEFT JOIN Passengers + ON ( + BusesNeighbors.prev_arrival_time < Passengers.arrival_time + AND Passengers.arrival_time <= BusesNeighbors.arrival_time) + GROUP BY 1, 2, 3 + ), + Boarding AS ( + SELECT + BusesMetadata.`row_number`, + BusesMetadata.bus_id, + LEAST( + BusesMetadata.capacity, + BusesMetadata.waiting + ) AS boarded, + GREATEST( + 0, + BusesMetadata.waiting - BusesMetadata.capacity + ) AS not_boarded + FROM BusesMetadata + WHERE `row_number` = 1 + UNION ALL + SELECT + BusesMetadata.`row_number`, + BusesMetadata.bus_id, + LEAST( + BusesMetadata.capacity, + Boarding.not_boarded + BusesMetadata.waiting + ) AS boarded, + GREATEST( + 0, + Boarding.not_boarded + BusesMetadata.waiting - BusesMetadata.capacity + ) AS not_boarded + FROM BusesMetadata, Boarding + WHERE BusesMetadata.`row_number` = Boarding.`row_number` + 1 + ) +SELECT + bus_id, + boarded AS passengers_cnt +FROM Boarding +ORDER BY 1; diff --git a/solutions/2154. Keep Multiplying Found Values by Two/2155-2.cpp b/solutions/2154. Keep Multiplying Found Values by Two/2155-2.cpp new file mode 100644 index 00000000000..142c2973c5e --- /dev/null +++ b/solutions/2154. Keep Multiplying Found Values by Two/2155-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int findFinalValue(vector& nums, int original) { + vector seen(1001); + + for (const int num : nums) + seen[num] = true; + + while (original < 1001 && seen[original]) + original *= 2; + + return original; + } +}; diff --git a/solutions/2154. Keep Multiplying Found Values by Two/2155-2.java b/solutions/2154. Keep Multiplying Found Values by Two/2155-2.java new file mode 100644 index 00000000000..c8d70524efe --- /dev/null +++ b/solutions/2154. Keep Multiplying Found Values by Two/2155-2.java @@ -0,0 +1,13 @@ +class Solution { + public int findFinalValue(int[] nums, int original) { + boolean[] seen = new boolean[1001]; + + for (final int num : nums) + seen[num] = true; + + while (original < 1001 && seen[original]) + original *= 2; + + return original; + } +} diff --git a/solutions/2154. Keep Multiplying Found Values by Two/2155-2.py b/solutions/2154. Keep Multiplying Found Values by Two/2155-2.py new file mode 100644 index 00000000000..40de32f8af0 --- /dev/null +++ b/solutions/2154. Keep Multiplying Found Values by Two/2155-2.py @@ -0,0 +1,11 @@ +class Solution: + def findFinalValue(self, nums: List[int], original: int) -> int: + seen = [False] * 1001 + + for num in nums: + seen[num] = True + + while original < 1001 and seen[original]: + original *= 2 + + return original diff --git a/solutions/2154. Keep Multiplying Found Values by Two/2155.cpp b/solutions/2154. Keep Multiplying Found Values by Two/2155.cpp new file mode 100644 index 00000000000..2302e75d0c9 --- /dev/null +++ b/solutions/2154. Keep Multiplying Found Values by Two/2155.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int findFinalValue(vector& nums, int original) { + unordered_set numsSet(nums.begin(), nums.end()); + while (numsSet.contains(original)) + original *= 2; + return original; + } +}; diff --git a/solutions/2154. Keep Multiplying Found Values by Two/2155.java b/solutions/2154. Keep Multiplying Found Values by Two/2155.java new file mode 100644 index 00000000000..7691078c3d0 --- /dev/null +++ b/solutions/2154. Keep Multiplying Found Values by Two/2155.java @@ -0,0 +1,8 @@ +class Solution { + public int findFinalValue(int[] nums, int original) { + Set numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + while (numsSet.contains(original)) + original *= 2; + return original; + } +} diff --git a/solutions/2154. Keep Multiplying Found Values by Two/2155.py b/solutions/2154. Keep Multiplying Found Values by Two/2155.py new file mode 100644 index 00000000000..e9c418a40e1 --- /dev/null +++ b/solutions/2154. Keep Multiplying Found Values by Two/2155.py @@ -0,0 +1,6 @@ +class Solution: + def findFinalValue(self, nums: List[int], original: int) -> int: + numsSet = set(nums) + while original in numsSet: + original *= 2 + return original diff --git a/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.cpp b/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.cpp new file mode 100644 index 00000000000..65323c6df43 --- /dev/null +++ b/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector maxScoreIndices(vector& nums) { + const int zeros = ranges::count(nums, 0); + const int ones = nums.size() - zeros; + vector ans{0}; // the division at index 0 + int leftZeros = 0; + int leftOnes = 0; + int maxScore = ones; // `leftZeros` + `rightOnes` + + for (int i = 0; i < nums.size(); ++i) { + leftZeros += nums[i] == 0; + leftOnes += nums[i] == 1; + const int rightOnes = ones - leftOnes; + const int score = leftZeros + rightOnes; + if (maxScore == score) { + ans.push_back(i + 1); + } else if (maxScore < score) { + maxScore = score; + ans = {i + 1}; + } + } + + return ans; + } +}; diff --git a/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.java b/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.java new file mode 100644 index 00000000000..1c2f8dc471f --- /dev/null +++ b/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.java @@ -0,0 +1,26 @@ +class Solution { + public List maxScoreIndices(int[] nums) { + final int ones = Arrays.stream(nums).sum(); + final int zeros = nums.length - ones; + // the division at index 0 + List ans = new ArrayList<>(Arrays.asList(0)); + int leftZeros = 0; + int leftOnes = 0; + int maxScore = ones; // `leftZeros` + `rightOnes` + + for (int i = 0; i < nums.length; ++i) { + leftZeros += nums[i] == 0 ? 1 : 0; + leftOnes += nums[i] == 1 ? 1 : 0; + final int rightOnes = ones - leftOnes; + final int score = leftZeros + rightOnes; + if (maxScore == score) { + ans.add(i + 1); + } else if (maxScore < score) { + maxScore = score; + ans = new ArrayList<>(Arrays.asList(i + 1)); + } + } + + return ans; + } +} diff --git a/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.py b/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.py new file mode 100644 index 00000000000..74b3101aab3 --- /dev/null +++ b/solutions/2155. All Divisions With the Highest Score of a Binary Array/2155.py @@ -0,0 +1,21 @@ +class Solution: + def maxScoreIndices(self, nums: List[int]) -> List[int]: + zeros = nums.count(0) + ones = len(nums) - zeros + ans = [0] # the division at index 0 + leftZeros = 0 + leftOnes = 0 + maxScore = ones # `leftZeros` + `rightOnes` + + for i, num in enumerate(nums): + leftZeros += num == 0 + leftOnes += num == 1 + rightOnes = ones - leftOnes + score = leftZeros + rightOnes + if maxScore == score: + ans.append(i + 1) + elif maxScore < score: + maxScore = score + ans = [i + 1] + + return ans diff --git a/solutions/2156. Find Substring With Given Hash Value/2156.cpp b/solutions/2156. Find Substring With Given Hash Value/2156.cpp new file mode 100644 index 00000000000..9f464b9720d --- /dev/null +++ b/solutions/2156. Find Substring With Given Hash Value/2156.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + string subStrHash(string s, int power, int modulo, int k, int hashValue) { + long maxPower = 1; + long hash = 0; + int bestLeft = -1; + + auto val = [](char c) -> int { return c - 'a' + 1; }; + + for (int i = s.length() - 1; i >= 0; --i) { + hash = (hash * power + val(s[i])) % modulo; + if (i + k < s.length()) + hash = (hash - val(s[i + k]) * maxPower % modulo + modulo) % modulo; + else + maxPower = maxPower * power % modulo; + if (hash == hashValue) + bestLeft = i; + } + + return s.substr(bestLeft, k); + } +}; diff --git a/solutions/2156. Find Substring With Given Hash Value/2156.java b/solutions/2156. Find Substring With Given Hash Value/2156.java new file mode 100644 index 00000000000..7d45a49c4ee --- /dev/null +++ b/solutions/2156. Find Substring With Given Hash Value/2156.java @@ -0,0 +1,23 @@ +class Solution { + public String subStrHash(String s, int power, int modulo, int k, int hashValue) { + long maxPower = 1; + long hash = 0; + int bestLeft = -1; + + for (int i = s.length() - 1; i >= 0; --i) { + hash = (hash * power + val(s.charAt(i))) % modulo; + if (i + k < s.length()) + hash = (hash - val(s.charAt(i + k)) * maxPower % modulo + modulo) % modulo; + else + maxPower = maxPower * power % modulo; + if (hash == hashValue) + bestLeft = i; + } + + return s.substring(bestLeft, bestLeft + k); + } + + private int val(char c) { + return c - 'a' + 1; + } +} diff --git a/solutions/2156. Find Substring With Given Hash Value/2156.py b/solutions/2156. Find Substring With Given Hash Value/2156.py new file mode 100644 index 00000000000..05d0e125796 --- /dev/null +++ b/solutions/2156. Find Substring With Given Hash Value/2156.py @@ -0,0 +1,16 @@ +class Solution: + def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str: + maxPower = pow(power, k, modulo) + hash = 0 + + def val(c: str) -> int: + return ord(c) - ord('a') + 1 + + for i, c in reversed(list(enumerate(s))): + hash = (hash * power + val(c)) % modulo + if i + k < len(s): + hash = (hash - val(s[i + k]) * maxPower) % modulo + if hash == hashValue: + bestLeft = i + + return s[bestLeft:bestLeft + k] diff --git a/solutions/2157. Groups of Strings/2157.cpp b/solutions/2157. Groups of Strings/2157.cpp new file mode 100644 index 00000000000..01648c1092b --- /dev/null +++ b/solutions/2157. Groups of Strings/2157.cpp @@ -0,0 +1,79 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), sz(n, 1) { + iota(id.begin(), id.end(), 0); + } + + void unionBySize(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (sz[i] < sz[j]) { + sz[j] += sz[i]; + id[i] = j; + } else { + sz[i] += sz[j]; + id[j] = i; + } + --count; + } + + int getCount() const { + return count; + } + + int getMaxSize() const { + return ranges::max(sz); + } + + private: + int count; + vector id; + vector sz; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + vector groupStrings(vector& words) { + UnionFind uf(words.size()); + unordered_map maskToIndex; + unordered_map deletedMaskToIndex; + + for (int i = 0; i < words.size(); ++i) { + const int mask = getMask(words[i]); + for (int j = 0; j < 26; ++j) + if (mask >> j & 1) { + // Going to delete this bit. + const int m = mask ^ 1 << j; + if (const auto it = maskToIndex.find(m); it != maskToIndex.cend()) + uf.unionBySize(i, it->second); + if (const auto it = deletedMaskToIndex.find(m); + it != deletedMaskToIndex.cend()) + uf.unionBySize(i, it->second); + else + deletedMaskToIndex[m] = i; + } else { + // Going to add this bit. + const int m = mask | 1 << j; + if (const auto it = maskToIndex.find(m); it != maskToIndex.cend()) + uf.unionBySize(i, it->second); + } + maskToIndex[mask] = i; + } + + return {uf.getCount(), uf.getMaxSize()}; + } + + private: + int getMask(const string& s) { + int mask = 0; + for (const char c : s) + mask |= 1 << c - 'a'; + return mask; + } +}; diff --git a/solutions/2157. Groups of Strings/2157.java b/solutions/2157. Groups of Strings/2157.java new file mode 100644 index 00000000000..05db250370f --- /dev/null +++ b/solutions/2157. Groups of Strings/2157.java @@ -0,0 +1,80 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + sz = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + for (int i = 0; i < n; ++i) + sz[i] = 1; + } + + public void unionBySize(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (sz[i] < sz[j]) { + sz[j] += sz[i]; + id[i] = j; + } else { + sz[i] += sz[j]; + id[j] = i; + } + --count; + } + + public int getCount() { + return count; + } + + public int getMaxSize() { + return Arrays.stream(sz).max().getAsInt(); + } + + private int count; + private int[] id; + private int[] sz; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int[] groupStrings(String[] words) { + UnionFind uf = new UnionFind(words.length); + Map maskToIndex = new HashMap<>(); + Map deletedMaskToIndex = new HashMap<>(); + + for (int i = 0; i < words.length; ++i) { + final int mask = getMask(words[i]); + for (int j = 0; j < 26; ++j) + if ((mask >> j & 1) == 1) { + // Going to delete this bit. + final int m = mask ^ 1 << j; + if (maskToIndex.containsKey(m)) + uf.unionBySize(i, maskToIndex.get(m)); + if (deletedMaskToIndex.containsKey(m)) + uf.unionBySize(i, deletedMaskToIndex.get(m)); + else + deletedMaskToIndex.put(m, i); + } else { + // Going to add this bit. + final int m = mask | 1 << j; + if (maskToIndex.containsKey(m)) + uf.unionBySize(i, maskToIndex.get(m)); + } + maskToIndex.put(mask, i); + } + + return new int[] {uf.getCount(), uf.getMaxSize()}; + } + + private int getMask(final String s) { + int mask = 0; + for (final char c : s.toCharArray()) + mask |= 1 << c - 'a'; + return mask; + } +} diff --git a/solutions/2157. Groups of Strings/2157.py b/solutions/2157. Groups of Strings/2157.py new file mode 100644 index 00000000000..2f967580312 --- /dev/null +++ b/solutions/2157. Groups of Strings/2157.py @@ -0,0 +1,62 @@ +class UnionFind: + def __init__(self, n: int): + self.count = n + self.id = list(range(n)) + self.sz = [1] * n + + def unionBySize(self, u: int, v: int) -> None: + i = self._find(u) + j = self._find(v) + if i == j: + return + if self.sz[i] < self.sz[j]: + self.sz[j] += self.sz[i] + self.id[i] = j + else: + self.sz[i] += self.sz[j] + self.id[j] = i + self.count -= 1 + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def groupStrings(self, words: List[str]) -> List[int]: + uf = UnionFind(len(words)) + + def getMask(s: str) -> int: + mask = 0 + for c in s: + mask |= 1 << ord(c) - ord('a') + return mask + + def getAddedMasks(mask: int): + for i in range(26): + if not (mask >> i & 1): + yield mask | 1 << i + + def getDeletedMasks(mask: int): + for i in range(26): + if mask >> i & 1: + yield mask ^ 1 << i + + maskToIndex = {getMask(word): i for i, word in enumerate(words)} + deletedMaskToIndex = {} + + for i, word in enumerate(words): + mask = getMask(word) + for m in getAddedMasks(mask): + if m in maskToIndex: + uf.unionBySize(i, maskToIndex[m]) + for m in getDeletedMasks(mask): + if m in maskToIndex: + uf.unionBySize(i, maskToIndex[m]) + if m in deletedMaskToIndex: + uf.unionBySize(i, deletedMaskToIndex[m]) + else: + deletedMaskToIndex[m] = i + + return [uf.count, max(uf.sz)] diff --git a/solutions/2158. Amount of New Area Painted Each Day/2158-2.cpp b/solutions/2158. Amount of New Area Painted Each Day/2158-2.cpp new file mode 100644 index 00000000000..bb34b09aef1 --- /dev/null +++ b/solutions/2158. Amount of New Area Painted Each Day/2158-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector amountPainted(vector>& paint) { + map intervals; + vector result; + + for (const vector& p : paint) { + int eraseLen = 0; + auto it = intervals.lower_bound(p[0]); + if (it != intervals.begin() && prev(it)->second >= p[0]) + --it; + while (it != intervals.end() && p[1] >= it->first) { + eraseLen += it->second - it->first; + p[0] = min(p[0], it->first); + p[1] = max(p[1], it->second); + it = intervals.erase(it); + } + intervals.insert({p[0], p[1]}); + result.push_back(p[1] - p[0] - eraseLen); + } + + return result; + } +}; diff --git a/solutions/2158. Amount of New Area Painted Each Day/2158.cpp b/solutions/2158. Amount of New Area Painted Each Day/2158.cpp new file mode 100644 index 00000000000..803defe885f --- /dev/null +++ b/solutions/2158. Amount of New Area Painted Each Day/2158.cpp @@ -0,0 +1,52 @@ +enum class Type { kEntering, kLeaving }; + +struct Event { + int day; + int index; + Type type; + Event(int day, int index, Type type) : day(day), index(index), type(type) {} +}; + +class Solution { + public: + vector amountPainted(vector>& paint) { + const int n = paint.size(); + const int minDay = (*ranges::min_element( + paint, [](const vector& a, const vector& b) { + return a[0] < b[0]; + }))[0]; + const int maxDay = (*ranges::max_element( + paint, [](const vector& a, const vector& b) { + return a[1] < b[1]; + }))[1]; + vector ans(n); + vector events; + // Stores the indices of paints that are available now. + set runningIndices; + + for (int i = 0; i < n; ++i) { + const int start = paint[i][0]; + const int end = paint[i][1]; + events.emplace_back(start, i, Type::kEntering); // 1 := entering + events.emplace_back(end, i, Type::kLeaving); // -1 := leaving + } + + ranges::sort(events, + [](const auto& a, const auto& b) { return a.day < b.day; }); + + int i = 0; // events' index + for (int day = minDay; day < maxDay; ++day) { + while (i < events.size() && events[i].day == day) { + if (events[i].type == Type::kEntering) + runningIndices.insert(events[i].index); + else + runningIndices.erase(events[i].index); + ++i; + } + if (!runningIndices.empty()) + ++ans[*runningIndices.begin()]; + } + + return ans; + } +}; diff --git a/solutions/2158. Amount of New Area Painted Each Day/2158.java b/solutions/2158. Amount of New Area Painted Each Day/2158.java new file mode 100644 index 00000000000..d40eead37b4 --- /dev/null +++ b/solutions/2158. Amount of New Area Painted Each Day/2158.java @@ -0,0 +1,48 @@ +enum Type { kEntering, kLeaving } + +class Event { + public int day; + public int index; + public Type type; + public Event(int day, int index, Type type) { + this.day = day; + this.index = index; + this.type = type; + } +} + +class Solution { + public int[] amountPainted(int[][] paint) { + final int n = paint.length; + final int minDay = Arrays.stream(paint).mapToInt(x -> x[0]).min().getAsInt(); + final int maxDay = Arrays.stream(paint).mapToInt(x -> x[1]).max().getAsInt(); + int[] ans = new int[n]; + // Stores the indices of paints that are available now. + TreeSet runningIndices = new TreeSet<>(); + List events = new ArrayList<>(); + + for (int i = 0; i < n; ++i) { + final int start = paint[i][0]; + final int end = paint[i][1]; + events.add(new Event(start, i, Type.kEntering)); // 1 := entering + events.add(new Event(end, i, Type.kLeaving)); // -1 := leaving + } + + Collections.sort(events, (a, b) -> a.day - b.day); + + int i = 0; // events' index + for (int day = minDay; day < maxDay; ++day) { + while (i < events.size() && events.get(i).day == day) { + if (events.get(i).type == Type.kEntering) + runningIndices.add(events.get(i).index); + else + runningIndices.remove(events.get(i).index); + ++i; + } + if (!runningIndices.isEmpty()) + ++ans[runningIndices.first()]; + } + + return ans; + } +} diff --git a/solutions/2158. Amount of New Area Painted Each Day/2158.py b/solutions/2158. Amount of New Area Painted Each Day/2158.py new file mode 100644 index 00000000000..29c0a669c0e --- /dev/null +++ b/solutions/2158. Amount of New Area Painted Each Day/2158.py @@ -0,0 +1,31 @@ +from sortedcontainers import SortedList + + +class Solution: + def amountPainted(self, paint: List[List[int]]) -> List[int]: + minDay = min(s for s, e in paint) + maxDay = max(e for s, e in paint) + ans = [0] * len(paint) + # Stores the indices of paints that are available now. + runningIndices = SortedList() + events = [] # (day, index, type) + + for i, (start, end) in enumerate(paint): + events.append((start, i, 1)) # 1 := entering + events.append((end, i, -1)) # -1 := leaving + + events.sort() + + i = 0 # events' index + for day in range(minDay, maxDay): + while i < len(events) and events[i][0] == day: + day, index, type = events[i] + if type == 1: + runningIndices.add(index) + else: + runningIndices.remove(index) + i += 1 + if runningIndices: + ans[runningIndices[0]] += 1 + + return ans diff --git a/solutions/2159. Order Two Columns Independently/2159.sql b/solutions/2159. Order Two Columns Independently/2159.sql new file mode 100644 index 00000000000..df92e68332c --- /dev/null +++ b/solutions/2159. Order Two Columns Independently/2159.sql @@ -0,0 +1,21 @@ +WITH + FirstCols AS( + SELECT + first_col, + ROW_NUMBER() OVER() AS `row_number` + FROM Data + ORDER BY 1 + ), + SecondCols AS ( + SELECT + second_col, + ROW_NUMBER() OVER() AS `row_number` + FROM Data + ORDER BY 1 DESC + ) +SELECT + FirstCols.first_col, + SecondCols.second_col +FROM FirstCols +INNER JOIN SecondCols + USING (`row_number`); diff --git a/solutions/216. Combination Sum III/216.cpp b/solutions/216. Combination Sum III/216.cpp new file mode 100644 index 00000000000..88ccc6798f8 --- /dev/null +++ b/solutions/216. Combination Sum III/216.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector> combinationSum3(int k, int n) { + vector> ans; + dfs(k, n, 1, {}, ans); + return ans; + } + + private: + void dfs(int k, int n, int s, vector&& path, vector>& ans) { + if (k == 0 && n == 0) { + ans.push_back(path); + return; + } + if (k == 0 || n <= 0) + return; + + for (int i = s; i <= 9; ++i) { + path.push_back(i); + dfs(k - 1, n - i, i + 1, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/216. Combination Sum III/216.java b/solutions/216. Combination Sum III/216.java new file mode 100644 index 00000000000..4c4dc8ba147 --- /dev/null +++ b/solutions/216. Combination Sum III/216.java @@ -0,0 +1,22 @@ +class Solution { + public List> combinationSum3(int k, int n) { + List> ans = new ArrayList<>(); + dfs(k, n, 1, new ArrayList<>(), ans); + return ans; + } + + private void dfs(int k, int n, int s, List path, List> ans) { + if (k == 0 && n == 0) { + ans.add(new ArrayList<>(path)); + return; + } + if (k == 0 || n < 0) + return; + + for (int i = s; i <= 9; ++i) { + path.add(i); + dfs(k - 1, n - i, i + 1, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/216. Combination Sum III/216.py b/solutions/216. Combination Sum III/216.py new file mode 100644 index 00000000000..1b4e2da0ae2 --- /dev/null +++ b/solutions/216. Combination Sum III/216.py @@ -0,0 +1,16 @@ +class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + ans = [] + + def dfs(k: int, n: int, s: int, path: List[int]) -> None: + if k == 0 and n == 0: + ans.append(path) + return + if k == 0 or n < 0: + return + + for i in range(s, 10): + dfs(k - 1, n - i, i + 1, path + [i]) + + dfs(k, n, 1, []) + return ans diff --git a/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.cpp b/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.cpp new file mode 100644 index 00000000000..47010ff2db9 --- /dev/null +++ b/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int minimumSum(int num) { + string s = to_string(num); + ranges::sort(s); + return stoi(s.substr(0, 1) + s.substr(2, 1)) + + stoi(s.substr(1, 1) + s.substr(3, 1)); + } +}; diff --git a/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.java b/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.java new file mode 100644 index 00000000000..b50cfbf2c22 --- /dev/null +++ b/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.java @@ -0,0 +1,7 @@ +class Solution { + public int minimumSum(int num) { + char[] chars = String.valueOf(num).toCharArray(); + Arrays.sort(chars); + return (chars[0] - '0') * 10 + (chars[2] - '0') + (chars[1] - '0') * 10 + (chars[3] - '0'); + } +} diff --git a/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.py b/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.py new file mode 100644 index 00000000000..e545ec60389 --- /dev/null +++ b/solutions/2160. Minimum Sum of Four Digit Number After Splitting Digits/2160.py @@ -0,0 +1,4 @@ +class Solution: + def minimumSum(self, num: int) -> int: + s = sorted(str(num)) + return int(s[0] + s[2]) + int(s[1] + s[3]) diff --git a/solutions/2161. Partition Array According to Given Pivot/2161.cpp b/solutions/2161. Partition Array According to Given Pivot/2161.cpp new file mode 100644 index 00000000000..9afe51a6d34 --- /dev/null +++ b/solutions/2161. Partition Array According to Given Pivot/2161.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector pivotArray(vector& nums, int pivot) { + vector ans; + + for (const int num : nums) + if (num < pivot) + ans.push_back(num); + + for (const int num : nums) + if (num == pivot) + ans.push_back(num); + + for (const int num : nums) + if (num > pivot) + ans.push_back(num); + + return ans; + } +}; diff --git a/solutions/2161. Partition Array According to Given Pivot/2161.java b/solutions/2161. Partition Array According to Given Pivot/2161.java new file mode 100644 index 00000000000..21225e17204 --- /dev/null +++ b/solutions/2161. Partition Array According to Given Pivot/2161.java @@ -0,0 +1,20 @@ +class Solution { + public int[] pivotArray(int[] nums, int pivot) { + int[] ans = new int[nums.length]; + int i = 0; // ans' index + + for (final int num : nums) + if (num < pivot) + ans[i++] = num; + + for (final int num : nums) + if (num == pivot) + ans[i++] = num; + + for (final int num : nums) + if (num > pivot) + ans[i++] = num; + + return ans; + } +} diff --git a/solutions/2161. Partition Array According to Given Pivot/2161.py b/solutions/2161. Partition Array According to Given Pivot/2161.py new file mode 100644 index 00000000000..51faccbaeb5 --- /dev/null +++ b/solutions/2161. Partition Array According to Given Pivot/2161.py @@ -0,0 +1,5 @@ +class Solution: + def pivotArray(self, nums: List[int], pivot: int) -> List[int]: + return [num for num in nums if num < pivot] + \ + [num for num in nums if num == pivot] + \ + [num for num in nums if num > pivot] diff --git a/solutions/2162. Minimum Cost to Set Cooking Time/2162.cpp b/solutions/2162. Minimum Cost to Set Cooking Time/2162.cpp new file mode 100644 index 00000000000..04e02f524f0 --- /dev/null +++ b/solutions/2162. Minimum Cost to Set Cooking Time/2162.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int minCostSetTime(int startAt, int moveCost, int pushCost, + int targetSeconds) { + int ans = INT_MAX; + int mins = targetSeconds > 5999 ? 99 : targetSeconds / 60; + int secs = targetSeconds - mins * 60; + + auto getCost = [&](int mins, int secs) -> int { + int cost = 0; + char curr = '0' + startAt; + for (const char c : to_string(mins * 100 + secs)) + if (c == curr) { + cost += pushCost; + } else { + cost += moveCost + pushCost; + curr = c; + } + return cost; + }; + + while (secs < 100) { + ans = min(ans, getCost(mins, secs)); + --mins; + secs += 60; + } + + return ans; + } +}; diff --git a/solutions/2162. Minimum Cost to Set Cooking Time/2162.java b/solutions/2162. Minimum Cost to Set Cooking Time/2162.java new file mode 100644 index 00000000000..7a28986e6bb --- /dev/null +++ b/solutions/2162. Minimum Cost to Set Cooking Time/2162.java @@ -0,0 +1,28 @@ +class Solution { + public int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) { + int ans = Integer.MAX_VALUE; + int mins = targetSeconds > 5999 ? 99 : targetSeconds / 60; + int secs = targetSeconds - mins * 60; + + while (secs < 100) { + ans = Math.min(ans, getCost(startAt, moveCost, pushCost, mins, secs)); + --mins; + secs += 60; + } + + return ans; + } + + private int getCost(int startAt, int moveCost, int pushCost, int mins, int secs) { + int cost = 0; + char curr = (char) ('0' + startAt); + for (final char c : String.valueOf(mins * 100 + secs).toCharArray()) + if (c == curr) { + cost += pushCost; + } else { + cost += moveCost + pushCost; + curr = c; + } + return cost; + }; +} diff --git a/solutions/2162. Minimum Cost to Set Cooking Time/2162.py b/solutions/2162. Minimum Cost to Set Cooking Time/2162.py new file mode 100644 index 00000000000..3de2bac0b9f --- /dev/null +++ b/solutions/2162. Minimum Cost to Set Cooking Time/2162.py @@ -0,0 +1,23 @@ +class Solution: + def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int: + ans = math.inf + mins = 99 if targetSeconds > 5999 else targetSeconds // 60 + secs = targetSeconds - mins * 60 + + def getCost(mins: int, secs: int) -> int: + cost = 0 + curr = str(startAt) + for c in str(mins * 100 + secs): + if c == curr: + cost += pushCost + else: + cost += moveCost + pushCost + curr = c + return cost + + while secs < 100: + ans = min(ans, getCost(mins, secs)) + mins -= 1 + secs += 60 + + return ans diff --git a/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.cpp b/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.cpp new file mode 100644 index 00000000000..08f37358267 --- /dev/null +++ b/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + long long minimumDifference(vector& nums) { + const int n = nums.size() / 3; + long ans = LONG_MAX; + long leftSum = 0; + long rightSum = 0; + // The left part should be as small as possible. + priority_queue maxHeap; + // The right part should be as big as possible. + priority_queue, greater<>> minHeap; + // minLeftSum[i] := the minimum of the sum of n nums in nums[0..i) + vector minLeftSum(nums.size()); + + for (int i = 0; i < 2 * n; ++i) { + maxHeap.push(nums[i]); + leftSum += nums[i]; + if (maxHeap.size() == n + 1) + leftSum -= maxHeap.top(), maxHeap.pop(); + if (maxHeap.size() == n) + minLeftSum[i] = leftSum; + } + + for (int i = nums.size() - 1; i >= n; --i) { + minHeap.push(nums[i]); + rightSum += nums[i]; + if (minHeap.size() == n + 1) + rightSum -= minHeap.top(), minHeap.pop(); + if (minHeap.size() == n) + ans = min(ans, minLeftSum[i - 1] - rightSum); + } + + return ans; + } +}; diff --git a/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.java b/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.java new file mode 100644 index 00000000000..f3a0143101d --- /dev/null +++ b/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.java @@ -0,0 +1,34 @@ +class Solution { + public long minimumDifference(int[] nums) { + final int n = nums.length / 3; + long ans = Long.MAX_VALUE; + long leftSum = 0; + long rightSum = 0; + // The left part should be as small as possible. + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + // The right part should be as big as possible. + Queue minHeap = new PriorityQueue<>(); + // minLeftSum[i] := the minimum of the sum of n nums in nums[0..i) + long[] minLeftSum = new long[nums.length]; + + for (int i = 0; i < 2 * n; ++i) { + maxHeap.offer(nums[i]); + leftSum += nums[i]; + if (maxHeap.size() == n + 1) + leftSum -= maxHeap.poll(); + if (maxHeap.size() == n) + minLeftSum[i] = leftSum; + } + + for (int i = nums.length - 1; i >= n; --i) { + minHeap.offer(nums[i]); + rightSum += nums[i]; + if (minHeap.size() == n + 1) + rightSum -= minHeap.poll(); + if (minHeap.size() == n) + ans = Math.min(ans, minLeftSum[i - 1] - rightSum); + } + + return ans; + } +} diff --git a/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.py b/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.py new file mode 100644 index 00000000000..75ff684e304 --- /dev/null +++ b/solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.py @@ -0,0 +1,28 @@ +class Solution: + def minimumDifference(self, nums: List[int]) -> int: + n = len(nums) // 3 + ans = math.inf + leftSum = 0 + rightSum = 0 + maxHeap = [] # Left part, as small as possible + minHeap = [] # Right part, as big as possible + # minLeftSum[i] := the minimum of the sum of n nums in nums[0..i) + minLeftSum = [0] * len(nums) + + for i in range(2 * n): + heapq.heappush(maxHeap, -nums[i]) + leftSum += nums[i] + if len(maxHeap) == n + 1: + leftSum += heapq.heappop(maxHeap) + if len(maxHeap) == n: + minLeftSum[i] = leftSum + + for i in range(len(nums) - 1, n - 1, -1): + heapq.heappush(minHeap, nums[i]) + rightSum += nums[i] + if len(minHeap) == n + 1: + rightSum -= heapq.heappop(minHeap) + if len(minHeap) == n: + ans = min(ans, minLeftSum[i - 1] - rightSum) + + return ans diff --git a/solutions/2164. Sort Even and Odd Indices Independently/2164-2.py b/solutions/2164. Sort Even and Odd Indices Independently/2164-2.py new file mode 100644 index 00000000000..1ea2668764a --- /dev/null +++ b/solutions/2164. Sort Even and Odd Indices Independently/2164-2.py @@ -0,0 +1,5 @@ +class Solution: + def sortEvenOdd(self, nums: List[int]) -> List[int]: + nums[::2] = sorted(nums[::2]) + nums[1::2] = sorted(nums[1::2])[::-1] + return nums diff --git a/solutions/2164. Sort Even and Odd Indices Independently/2164.cpp b/solutions/2164. Sort Even and Odd Indices Independently/2164.cpp new file mode 100644 index 00000000000..7817efe03c0 --- /dev/null +++ b/solutions/2164. Sort Even and Odd Indices Independently/2164.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector sortEvenOdd(vector& nums) { + const int n = nums.size(); + vector ans(n); + vector evenCount(101); + vector oddCount(101); + + for (int i = 0; i < n; ++i) + if (i % 2 == 1) + ++oddCount[nums[i]]; + else + ++evenCount[nums[i]]; + + int ansIndex = 0; + for (int i = 1; i < 101; ++i) + while (evenCount[i]--) { + ans[ansIndex] = i; + ansIndex += 2; + } + + ansIndex = 1; + for (int i = 100; i > 0; --i) + while (oddCount[i]--) { + ans[ansIndex] = i; + ansIndex += 2; + } + + return ans; + } +}; diff --git a/solutions/2164. Sort Even and Odd Indices Independently/2164.java b/solutions/2164. Sort Even and Odd Indices Independently/2164.java new file mode 100644 index 00000000000..0dfc5b8fafc --- /dev/null +++ b/solutions/2164. Sort Even and Odd Indices Independently/2164.java @@ -0,0 +1,30 @@ +class Solution { + public int[] sortEvenOdd(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + int[] evenCount = new int[101]; + int[] oddCount = new int[101]; + + for (int i = 0; i < n; ++i) + if (i % 2 == 1) + ++oddCount[nums[i]]; + else + ++evenCount[nums[i]]; + + int ansIndex = 0; + for (int i = 1; i < 101; ++i) + while (evenCount[i]-- > 0) { + ans[ansIndex] = i; + ansIndex += 2; + } + + ansIndex = 1; + for (int i = 100; i > 0; --i) + while (oddCount[i]-- > 0) { + ans[ansIndex] = i; + ansIndex += 2; + } + + return ans; + } +} diff --git a/solutions/2164. Sort Even and Odd Indices Independently/2164.py b/solutions/2164. Sort Even and Odd Indices Independently/2164.py new file mode 100644 index 00000000000..34548ea79d1 --- /dev/null +++ b/solutions/2164. Sort Even and Odd Indices Independently/2164.py @@ -0,0 +1,21 @@ +class Solution: + def sortEvenOdd(self, nums: List[int]) -> List[int]: + ans = [0] * len(nums) + evenCount = collections.Counter(nums[::2]) + oddCount = collections.Counter(nums[1::2]) + + ansIndex = 0 + for i in range(1, 101): + while evenCount[i] > 0: + ans[ansIndex] = i + ansIndex += 2 + evenCount[i] -= 1 + + ansIndex = 1 + for i in range(100, 0, -1): + while oddCount[i] > 0: + ans[ansIndex] = i + ansIndex += 2 + oddCount[i] -= 1 + + return ans diff --git a/solutions/2165. Smallest Value of the Rearranged Number/2165.cpp b/solutions/2165. Smallest Value of the Rearranged Number/2165.cpp new file mode 100644 index 00000000000..ef15f355c79 --- /dev/null +++ b/solutions/2165. Smallest Value of the Rearranged Number/2165.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + long long smallestNumber(long long num) { + string s = to_string(abs(num)); + ranges::sort(s, [&](int a, int b) { return num < 0 ? a > b : a < b; }); + if (num > 0) + swap(s[0], s[s.find_first_not_of('0')]); + return stoll(s) * (num < 0 ? -1 : 1); + } +}; diff --git a/solutions/2165. Smallest Value of the Rearranged Number/2165.java b/solutions/2165. Smallest Value of the Rearranged Number/2165.java new file mode 100644 index 00000000000..f526cb9c166 --- /dev/null +++ b/solutions/2165. Smallest Value of the Rearranged Number/2165.java @@ -0,0 +1,15 @@ +class Solution { + public long smallestNumber(long num) { + String[] digits = String.valueOf(Math.abs(num)).split(""); + String s = Stream.of(digits).sorted().collect(Collectors.joining()); + StringBuilder sb = new StringBuilder(s); + if (num <= 0) + return -1 * Long.parseLong(sb.reverse().toString()); + if (sb.charAt(0) == '0') { + final int firstNonZeroIndex = sb.lastIndexOf("0") + 1; + sb.setCharAt(0, sb.charAt(firstNonZeroIndex)); + sb.setCharAt(firstNonZeroIndex, '0'); + } + return Long.parseLong(sb.toString()); + } +} diff --git a/solutions/2165. Smallest Value of the Rearranged Number/2165.py b/solutions/2165. Smallest Value of the Rearranged Number/2165.py new file mode 100644 index 00000000000..102e86b78b8 --- /dev/null +++ b/solutions/2165. Smallest Value of the Rearranged Number/2165.py @@ -0,0 +1,6 @@ +class Solution: + def smallestNumber(self, num: int) -> int: + s = sorted(str(abs(num)), reverse=num < 0) + firstNonZeroIndex = next((i for i, c in enumerate(s) if c != '0'), 0) + s[0], s[firstNonZeroIndex] = s[firstNonZeroIndex], s[0] + return int(''.join(s)) * (-1 if num < 0 else 1) diff --git a/solutions/2166. Design Bitset/2166.cpp b/solutions/2166. Design Bitset/2166.cpp new file mode 100644 index 00000000000..c961c9d3227 --- /dev/null +++ b/solutions/2166. Design Bitset/2166.cpp @@ -0,0 +1,44 @@ +class Bitset { + public: + Bitset(int size) : s(size, '0'), r(size, '1') {} + + void fix(int idx) { + if (s[idx] == '0') + ++cnt; + s[idx] = '1'; + r[idx] = '0'; + } + + void unfix(int idx) { + if (s[idx] == '1') + --cnt; + s[idx] = '0'; + r[idx] = '1'; + } + + void flip() { + swap(s, r); + cnt = s.length() - cnt; + } + + bool all() { + return cnt == s.length(); + } + + bool one() { + return cnt; + } + + int count() { + return cnt; + } + + string toString() { + return s; + } + + private: + string s; // the original + string r; // the reversed + int cnt = 0; +}; diff --git a/solutions/2166. Design Bitset/2166.java b/solutions/2166. Design Bitset/2166.java new file mode 100644 index 00000000000..8bbe710f39f --- /dev/null +++ b/solutions/2166. Design Bitset/2166.java @@ -0,0 +1,49 @@ +class Bitset { + public Bitset(int size) { + for (int i = 0; i < size; ++i) { + sb.append('0'); + rb.append('1'); + } + } + + public void fix(int idx) { + if (sb.charAt(idx) == '0') + ++cnt; + sb.setCharAt(idx, '1'); + rb.setCharAt(idx, '0'); + } + + public void unfix(int idx) { + if (sb.charAt(idx) == '1') + --cnt; + sb.setCharAt(idx, '0'); + rb.setCharAt(idx, '1'); + } + + public void flip() { + StringBuilder temp = sb; + sb = rb; + rb = temp; + cnt = sb.length() - cnt; + } + + public boolean all() { + return cnt == sb.length(); + } + + public boolean one() { + return cnt > 0; + } + + public int count() { + return cnt; + } + + public String toString() { + return sb.toString(); + } + + private StringBuilder sb = new StringBuilder(); // the original + private StringBuilder rb = new StringBuilder(); // the reversed + private int cnt = 0; +} diff --git a/solutions/2166. Design Bitset/2166.py b/solutions/2166. Design Bitset/2166.py new file mode 100644 index 00000000000..a98102ede24 --- /dev/null +++ b/solutions/2166. Design Bitset/2166.py @@ -0,0 +1,33 @@ +class Bitset: + def __init__(self, size: int): + self.s = ['0'] * size # the original + self.r = ['1'] * size # the reversed + self.cnt = 0 + + def fix(self, idx: int) -> None: + if self.s[idx] == '0': + self.cnt += 1 + self.s[idx] = '1' + self.r[idx] = '0' + + def unfix(self, idx: int) -> None: + if self.s[idx] == '1': + self.cnt -= 1 + self.s[idx] = '0' + self.r[idx] = '1' + + def flip(self) -> None: + self.s, self.r = self.r, self.s + self.cnt = len(self.s) - self.cnt + + def all(self) -> bool: + return self.cnt == len(self.s) + + def one(self) -> bool: + return self.cnt + + def count(self) -> int: + return self.cnt + + def toString(self) -> str: + return ''.join(self.s) diff --git a/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.cpp b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.cpp new file mode 100644 index 00000000000..e4208fba3fa --- /dev/null +++ b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minimumTime(string s) { + const int n = s.length(); + int ans = n; + int left = 0; // the minimum time to remove the illegal cars so far + + for (int i = 0; i < n; ++i) { + left = min(left + (s[i] - '0') * 2, i + 1); + ans = min(ans, left + n - 1 - i); + } + + return ans; + } +}; diff --git a/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.java b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.java new file mode 100644 index 00000000000..24f2a46c594 --- /dev/null +++ b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.java @@ -0,0 +1,14 @@ +class Solution { + public int minimumTime(String s) { + final int n = s.length(); + int ans = n; + int left = 0; // the minimum time to remove the illegal cars so far + + for (int i = 0; i < n; ++i) { + left = Math.min(left + (s.charAt(i) - '0') * 2, i + 1); + ans = Math.min(ans, left + n - 1 - i); + } + + return ans; + } +} diff --git a/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.py b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.py new file mode 100644 index 00000000000..77d6e2ab525 --- /dev/null +++ b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.py @@ -0,0 +1,11 @@ +class Solution: + def minimumTime(self, s: str) -> int: + n = len(s) + ans = n + left = 0 # the minimum time to remove the illegal cars so far + + for i, c in enumerate(s): + left = min(left + (ord(c) - ord('0')) * 2, i + 1) + ans = min(ans, left + n - 1 - i) + + return ans diff --git a/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.cpp b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.cpp new file mode 100644 index 00000000000..2bd191dcb4f --- /dev/null +++ b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minimumTime(string s) { + const int n = s.length(); + // left[i] := the minimum time to remove the illegal cars of s[0..i] + vector left(n); + left[0] = s[0] - '0'; + // dp[i] := the minimum time to remove the illegal cars of s[0..i] optimally + // + the time to remove the illegal cars of s[i + 1..n) consecutively + // Note that the way to remove the illegal cars in the right part + // doesn't need to be optimal since: + // `left | illegal cars | n - 1 - k` will be covered in + // `left' | n - 1 - i` later. + vector dp(n, n); + dp[0] = left[0] + n - 1; + + for (int i = 1; i < n; ++i) { + left[i] = min(left[i - 1] + (s[i] - '0') * 2, i + 1); + dp[i] = min(dp[i], left[i] + n - 1 - i); + } + + return ranges::min(dp); + } +}; diff --git a/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.java b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.java new file mode 100644 index 00000000000..0cf8b397221 --- /dev/null +++ b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.java @@ -0,0 +1,24 @@ +class Solution { + public int minimumTime(String s) { + final int n = s.length(); + // left[i] := the minimum time to remove the illegal cars of s[0..i] + int[] left = new int[n]; + left[0] = s.charAt(0) - '0'; + // dp[i] := the minimum time to remove the illegal cars of s[0..i] optimally + // + the time to remove the illegal cars of s[i + 1..n) consecutively + // Note that the way to remove the illegal cars in the right part + // doesn't need to be optimal since: + // `left | illegal cars | n - 1 - k` will be covered in + // `left' | n - 1 - i` later. + int[] dp = new int[n]; + Arrays.fill(dp, n); + dp[0] = left[0] + n - 1; + + for (int i = 1; i < n; ++i) { + left[i] = Math.min(left[i - 1] + (s.charAt(i) - '0') * 2, i + 1); + dp[i] = Math.min(dp[i], left[i] + n - 1 - i); + } + + return Arrays.stream(dp).min().getAsInt(); + } +} diff --git a/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.py b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.py new file mode 100644 index 00000000000..053b283970f --- /dev/null +++ b/solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.py @@ -0,0 +1,20 @@ +class Solution: + def minimumTime(self, s: str) -> int: + n = len(s) + # left[i] := the minimum time to remove the illegal cars of s[0..i] + left = [0] * n + left[0] = ord(s[0]) - ord('0') + # dp[i] := the minimum time to remove the illegal cars of s[0..i] optimally + # + the time to remove the illegal cars of s[i + 1..n) consecutively + # Note that the way to remove the illegal cars in the right part + # doesn't need to be optimal since: + # `left | illegal cars | n - 1 - k` will be covered in + # `left' | n - 1 - i` later. + dp = [n] * n + dp[0] = left[0] + n - 1 + + for i in range(1, n): + left[i] = min(left[i - 1] + (ord(s[i]) - ord('0')) * 2, i + 1) + dp[i] = min(dp[i], left[i] + n - 1 - i) + + return min(dp) diff --git a/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.cpp b/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.cpp new file mode 100644 index 00000000000..5f471dc88a8 --- /dev/null +++ b/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int equalDigitFrequency(string s) { + const string_view sv(s); + unordered_set seen; + + for (int i = 0; i < s.length(); ++i) + for (int j = i; j < s.length(); ++j) + if (isUnique(sv.substr(i, j - i + 1))) + seen.insert(getRollingHash(sv.substr(i, j - i + 1))); + + return seen.size(); + } + + private: + static constexpr int power = 11; + static constexpr int kMod = 1'000'000'007; + + bool isUnique(const string_view& sv) { + vector count(10); + int unique = 0; + for (const char c : sv) + if (++count[c - '0'] == 1) + ++unique; + const int maxCount = ranges::max(count); + return maxCount * unique == sv.length(); + } + + int getRollingHash(const string_view& sv) { + long hash = 0; + for (const char c : sv) + hash = (hash * power + val(c)) % kMod; + return hash; + } + + constexpr int val(char c) { + return c - '0' + 1; + } +}; diff --git a/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.java b/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.java new file mode 100644 index 00000000000..35dcccd7b5c --- /dev/null +++ b/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.java @@ -0,0 +1,36 @@ +class Solution { + public int equalDigitFrequency(String s) { + Set seen = new HashSet<>(); + + for (int i = 0; i < s.length(); ++i) + for (int j = i; j < s.length(); ++j) + if (isUnique(s, i, j)) + seen.add(getRollingHash(s, i, j)); + + return seen.size(); + } + + private static final int power = 11; + private static final int kMod = 1_000_000_007; + + private boolean isUnique(final String s, int i, int j) { + int[] count = new int[10]; + int unique = 0; + for (int k = i; k <= j; ++k) + if (++count[s.charAt(k) - '0'] == 1) + ++unique; + final int maxCount = Arrays.stream(count).max().getAsInt(); + return maxCount * unique == j - i + 1; + } + + private int getRollingHash(final String s, int i, int j) { + long hash = 0; + for (int k = i; k <= j; ++k) + hash = (hash * power + val(s.charAt(k))) % kMod; + return (int) hash; + } + + private int val(char c) { + return c - '0' + 1; + } +} diff --git a/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.py b/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.py new file mode 100644 index 00000000000..2987e08049b --- /dev/null +++ b/solutions/2168. Unique Substrings With Equal Digit Frequency/2168.py @@ -0,0 +1,31 @@ +class Solution: + def equalDigitFrequency(self, s: str) -> int: + power = 11 + kMod = 1_000_000_007 + seen = set() + + def isUnique(s: str, i: int, j: int) -> bool: + count = [0] * 10 + unique = 0 + for k in range(i, j + 1): + count[ord(s[k]) - ord('0')] += 1 + if count[ord(s[k]) - ord('0')] == 1: + unique += 1 + maxCount = max(count) + return maxCount * unique == j - i + 1 + + def getRollingHash(s: str, i: int, j: int) -> int: + hash = 0 + for k in range(i, j + 1): + hash = (hash * power + val(s[k])) % kMod + return hash + + def val(c: str) -> int: + return ord(c) - ord('0') + 1 + + for i in range(len(s)): + for j in range(i, len(s)): + if isUnique(s, i, j): + seen.add(getRollingHash(s, i, j)) + + return len(seen) diff --git a/solutions/2169. Count Operations to Obtain Zero/2169.cpp b/solutions/2169. Count Operations to Obtain Zero/2169.cpp new file mode 100644 index 00000000000..301b7bfa2d2 --- /dev/null +++ b/solutions/2169. Count Operations to Obtain Zero/2169.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int countOperations(int num1, int num2) { + int ans = 0; + + while (num1 && num2) { + if (num1 < num2) + swap(num1, num2); + ans += num1 / num2; + num1 %= num2; + } + + return ans; + } +}; diff --git a/solutions/2169. Count Operations to Obtain Zero/2169.java b/solutions/2169. Count Operations to Obtain Zero/2169.java new file mode 100644 index 00000000000..3552d462c7b --- /dev/null +++ b/solutions/2169. Count Operations to Obtain Zero/2169.java @@ -0,0 +1,17 @@ +class Solution { + public int countOperations(int num1, int num2) { + int ans = 0; + + while (num1 > 0 && num2 > 0) { + if (num1 < num2) { + final int temp = num1; + num1 = num2; + num2 = temp; + } + ans += num1 / num2; + num1 %= num2; + } + + return ans; + } +} diff --git a/solutions/2169. Count Operations to Obtain Zero/2169.py b/solutions/2169. Count Operations to Obtain Zero/2169.py new file mode 100644 index 00000000000..5f3ae5334a6 --- /dev/null +++ b/solutions/2169. Count Operations to Obtain Zero/2169.py @@ -0,0 +1,11 @@ +class Solution: + def countOperations(self, num1: int, num2: int) -> int: + ans = 0 + + while num1 and num2: + if num1 < num2: + num1, num2 = num2, num1 + ans += num1 // num2 + num1 %= num2 + + return ans diff --git a/solutions/217. Contains Duplicate/217.cpp b/solutions/217. Contains Duplicate/217.cpp new file mode 100644 index 00000000000..dae11f4ce83 --- /dev/null +++ b/solutions/217. Contains Duplicate/217.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool containsDuplicate(vector& nums) { + unordered_set seen; + + for (const int num : nums) + if (!seen.insert(num).second) + return true; + + return false; + } +}; diff --git a/solutions/217. Contains Duplicate/217.java b/solutions/217. Contains Duplicate/217.java new file mode 100644 index 00000000000..b78082a24d4 --- /dev/null +++ b/solutions/217. Contains Duplicate/217.java @@ -0,0 +1,11 @@ +class Solution { + public boolean containsDuplicate(int[] nums) { + Set seen = new HashSet<>(); + + for (final int num : nums) + if (!seen.add(num)) + return true; + + return false; + } +} diff --git a/solutions/217. Contains Duplicate/217.py b/solutions/217. Contains Duplicate/217.py new file mode 100644 index 00000000000..2e7f4294f53 --- /dev/null +++ b/solutions/217. Contains Duplicate/217.py @@ -0,0 +1,3 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) != len(set(nums)) diff --git a/solutions/2170. Minimum Operations to Make the Array Alternating/2170.cpp b/solutions/2170. Minimum Operations to Make the Array Alternating/2170.cpp new file mode 100644 index 00000000000..e3ab7e0211e --- /dev/null +++ b/solutions/2170. Minimum Operations to Make the Array Alternating/2170.cpp @@ -0,0 +1,32 @@ +struct T { + unordered_map count; + int mx = 0; + int secondMax = 0; + int maxFreq = 0; + int secondMaxFreq = 0; +}; + +class Solution { + public: + int minimumOperations(vector& nums) { + // 0 := odd indices, 1 := even indices + vector ts(2); + + for (int i = 0; i < nums.size(); ++i) { + T& t = ts[i % 2]; + const int freq = ++t.count[nums[i]]; + if (freq > t.maxFreq) { + t.maxFreq = freq; + t.mx = nums[i]; + } else if (freq > t.secondMaxFreq) { + t.secondMaxFreq = freq; + t.secondMax = nums[i]; + } + } + + if (ts[0].mx == ts[1].mx) + return nums.size() - max(ts[0].maxFreq + ts[1].secondMaxFreq, + ts[1].maxFreq + ts[0].secondMaxFreq); + return nums.size() - (ts[0].maxFreq + ts[1].maxFreq); + } +}; diff --git a/solutions/2170. Minimum Operations to Make the Array Alternating/2170.java b/solutions/2170. Minimum Operations to Make the Array Alternating/2170.java new file mode 100644 index 00000000000..bdd8ca48ce4 --- /dev/null +++ b/solutions/2170. Minimum Operations to Make the Array Alternating/2170.java @@ -0,0 +1,33 @@ +class T { + public Map count = new HashMap<>(); + public int mx = 0; + public int secondMax = 0; + public int maxFreq = 0; + public int secondMaxFreq = 0; +} + +class Solution { + public int minimumOperations(int[] nums) { + T[] ts = new T[2]; + ts[0] = new T(); + ts[1] = new T(); + + for (int i = 0; i < nums.length; ++i) { + T t = ts[i % 2]; + t.count.merge(nums[i], 1, Integer::sum); + final int freq = t.count.get(nums[i]); + if (freq > t.maxFreq) { + t.maxFreq = freq; + t.mx = nums[i]; + } else if (freq > t.secondMaxFreq) { + t.secondMaxFreq = freq; + t.secondMax = nums[i]; + } + } + + if (ts[0].mx == ts[1].mx) + return nums.length - + Math.max(ts[0].maxFreq + ts[1].secondMaxFreq, ts[1].maxFreq + ts[0].secondMaxFreq); + return nums.length - (ts[0].maxFreq + ts[1].maxFreq); + } +} diff --git a/solutions/2170. Minimum Operations to Make the Array Alternating/2170.py b/solutions/2170. Minimum Operations to Make the Array Alternating/2170.py new file mode 100644 index 00000000000..eff502397fc --- /dev/null +++ b/solutions/2170. Minimum Operations to Make the Array Alternating/2170.py @@ -0,0 +1,29 @@ +class T: + def __init__(self): + self.count = collections.Counter() + self.mx = 0 + self.secondMax = 0 + self.maxFreq = 0 + self.secondMaxFreq = 0 + + +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + # 0 := odd indices, 1 := even indices + ts = [T() for _ in range(2)] + + for i, num in enumerate(nums): + t = ts[i % 2] + t.count[num] += 1 + freq = t.count[num] + if freq > t.maxFreq: + t.maxFreq = freq + t.mx = num + elif freq > t.secondMaxFreq: + t.secondMaxFreq = freq + t.secondMax = num + + if ts[0].mx == ts[1].mx: + return len(nums) - max(ts[0].maxFreq + ts[1].secondMaxFreq, + ts[1].maxFreq + ts[0].secondMaxFreq) + return len(nums) - (ts[0].maxFreq + ts[1].maxFreq) diff --git a/solutions/2171. Removing Minimum Number of Magic Beans/2171.cpp b/solutions/2171. Removing Minimum Number of Magic Beans/2171.cpp new file mode 100644 index 00000000000..2c2f4181b5e --- /dev/null +++ b/solutions/2171. Removing Minimum Number of Magic Beans/2171.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + long long minimumRemoval(vector& beans) { + const long n = beans.size(); + const long sum = accumulate(beans.begin(), beans.end(), 0L); + long ans = LONG_MAX; + + ranges::sort(beans); + + for (int i = 0; i < n; ++i) + ans = min(ans, sum - (n - i) * beans[i]); + + return ans; + } +}; diff --git a/solutions/2171. Removing Minimum Number of Magic Beans/2171.java b/solutions/2171. Removing Minimum Number of Magic Beans/2171.java new file mode 100644 index 00000000000..3c62550a0b4 --- /dev/null +++ b/solutions/2171. Removing Minimum Number of Magic Beans/2171.java @@ -0,0 +1,14 @@ +class Solution { + public long minimumRemoval(int[] beans) { + final long n = beans.length; + final long sum = Arrays.stream(beans).asLongStream().sum(); + long ans = Long.MAX_VALUE; + + Arrays.sort(beans); + + for (int i = 0; i < n; ++i) + ans = Math.min(ans, sum - (n - i) * beans[i]); + + return ans; + } +} diff --git a/solutions/2171. Removing Minimum Number of Magic Beans/2171.py b/solutions/2171. Removing Minimum Number of Magic Beans/2171.py new file mode 100644 index 00000000000..096a8f742dd --- /dev/null +++ b/solutions/2171. Removing Minimum Number of Magic Beans/2171.py @@ -0,0 +1,6 @@ +class Solution: + def minimumRemoval(self, beans: List[int]) -> int: + n = len(beans) + summ = sum(beans) + return min(summ - (n - i) * bean + for i, bean in enumerate(sorted(beans))) diff --git a/solutions/2172. Maximum AND Sum of Array/2172.cpp b/solutions/2172. Maximum AND Sum of Array/2172.cpp new file mode 100644 index 00000000000..d1ff5783c8a --- /dev/null +++ b/solutions/2172. Maximum AND Sum of Array/2172.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maximumANDSum(vector& nums, int numSlots) { + const int n = 2 * numSlots; + const int nSelected = 1 << n; + // dp[i] := the maximum value, where i is the bitmask of the selected + // numbers + vector dp(nSelected); + + nums.resize(n); + + for (unsigned mask = 1; mask < nSelected; ++mask) { + const int selected = popcount(mask); + const int slot = (selected + 1) / 2; // (1, 2) -> 1, (3, 4) -> 2 + for (int i = 0; i < n; ++i) + if (mask >> i & 1) // Assign `nums[i]` to the `slot`-th slot. + dp[mask] = max(dp[mask], dp[mask ^ 1 << i] + (slot & nums[i])); + } + + return dp.back(); + } +}; diff --git a/solutions/2172. Maximum AND Sum of Array/2172.java b/solutions/2172. Maximum AND Sum of Array/2172.java new file mode 100644 index 00000000000..13904529203 --- /dev/null +++ b/solutions/2172. Maximum AND Sum of Array/2172.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumANDSum(int[] nums, int numSlots) { + final int n = 2 * numSlots; + final int nSelected = 1 << n; + // dp[i] := the maximum value, where i is the bitmask of the selected + // numbers + int[] dp = new int[nSelected]; + int[] A = Arrays.copyOf(nums, n); + + for (int mask = 1; mask < nSelected; ++mask) { + final int selected = Integer.bitCount(mask); + final int slot = (selected + 1) / 2; // (1, 2) -> 1, (3, 4) -> 2 + for (int i = 0; i < n; ++i) + if ((mask >> i & 1) == 1) // Assign `A[i]` to the `slot`-th slot. + dp[mask] = Math.max(dp[mask], dp[mask ^ 1 << i] + (slot & A[i])); + } + + return dp[nSelected - 1]; + } +} diff --git a/solutions/2172. Maximum AND Sum of Array/2172.py b/solutions/2172. Maximum AND Sum of Array/2172.py new file mode 100644 index 00000000000..76605b40e70 --- /dev/null +++ b/solutions/2172. Maximum AND Sum of Array/2172.py @@ -0,0 +1,18 @@ +class Solution: + def maximumANDSum(self, nums: List[int], numSlots: int) -> int: + n = 2 * numSlots + nSelected = 1 << n + # dp[i] := the maximum value, where i is the bitmask of the selected + # numbers + dp = [0] * nSelected + + nums += [0] * (n - len(nums)) + + for mask in range(1, nSelected): + selected = mask.bit_count() + slot = (selected + 1) // 2 # (1, 2) -> 1, (3, 4) -> 2 + for i, num in enumerate(nums): + if mask >> i & 1: # Assign `nums[i]` to the `slot`-th slot. + dp[mask] = max(dp[mask], dp[mask ^ 1 << i] + (slot & num)) + + return dp[-1] diff --git a/solutions/2173. Longest Winning Streak/2173.sql b/solutions/2173. Longest Winning Streak/2173.sql new file mode 100644 index 00000000000..e4e7ee617e1 --- /dev/null +++ b/solutions/2173. Longest Winning Streak/2173.sql @@ -0,0 +1,34 @@ +WITH + MatchesWithRowNumberInEachPlayer AS ( + SELECT + *, + ROW_NUMBER() OVER( + PARTITION BY player_id + ORDER BY match_day + ) AS `row_number` + FROM Matches + ), + `Groups` AS ( + SELECT + *, + `row_number` - ROW_NUMBER() OVER( + PARTITION BY player_id + ORDER BY match_day + ) AS group_id + FROM MatchesWithRowNumberInEachPlayer + WHERE result = 'Win' + ), + ConsecCounts AS ( + SELECT + player_id, + COUNT(*) AS consec_count + FROM `Groups` + GROUP BY player_id, group_id + ) +SELECT + Matches.player_id, + IFNULL(MAX(ConsecCounts.consec_count), 0) AS longest_streak +FROM Matches +LEFT JOIN ConsecCounts + USING (player_id) +GROUP BY 1; diff --git a/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.cpp b/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.cpp new file mode 100644 index 00000000000..40790379275 --- /dev/null +++ b/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int removeOnes(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + const int maxMask = 1 << m * n; + // dp[i] := the minimum number of operations to remove all 1s from the grid, + // where `i` is the bitmask of the state of the grid + vector dp(maxMask, INT_MAX / 2); + dp[0] = 0; + + for (int mask = 0; mask < maxMask; ++mask) + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + int nextMask = mask; + // Set the cells in the same row with 0. + for (int k = 0; k < n; ++k) + nextMask &= ~(1 << i * n + k); + // Set the cells in the same column with 0. + for (int k = 0; k < m; ++k) + nextMask &= ~(1 << k * n + j); + dp[mask] = min(dp[mask], 1 + dp[nextMask]); + } + + return dp[encode(grid, m, n)]; + } + + private: + int encode(const vector>& grid, int m, int n) { + int encoded = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j]) + encoded |= 1 << i * n + j; + return encoded; + } +}; diff --git a/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.java b/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.java new file mode 100644 index 00000000000..1406aab29cb --- /dev/null +++ b/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.java @@ -0,0 +1,37 @@ +class Solution { + public int removeOnes(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + final int maxMask = 1 << m * n; + // dp[i] := the minimum number of operations to remove all 1s from the grid, + // where `i` is the bitmask of the state of the grid + int[] dp = new int[1 << m * n]; + Arrays.fill(dp, Integer.MAX_VALUE / 2); + dp[0] = 0; + + for (int mask = 0; mask < maxMask; ++mask) + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + int nextMask = mask; + // Set the cells in the same row with 0. + for (int k = 0; k < n; ++k) + nextMask &= ~(1 << i * n + k); + // Set the cells in the same column with 0. + for (int k = 0; k < m; ++k) + nextMask &= ~(1 << k * n + j); + dp[mask] = Math.min(dp[mask], 1 + dp[nextMask]); + } + + return dp[encode(grid, m, n)]; + } + + private int encode(int[][] grid, int m, int n) { + int encoded = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + encoded |= 1 << i * n + j; + return encoded; + } +} diff --git a/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.py b/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.py new file mode 100644 index 00000000000..2f023fdc905 --- /dev/null +++ b/solutions/2174. Remove All Ones With Row and Column Flips II/2174-2.py @@ -0,0 +1,32 @@ +class Solution: + def removeOnes(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + maxMask = 1 << m * n + # dp[i] := the minimum number of operations to remove all 1s from the grid, + # where `i` is the bitmask of the state of the grid + dp = [math.inf] * maxMask + dp[0] = 0 + + for mask in range(maxMask): + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + nextMask = mask + # Set the cells in the same row with 0. + for k in range(n): + nextMask &= ~(1 << i * n + k) + # Set the cells in the same column with 0. + for k in range(m): + nextMask &= ~(1 << k * n + j) + dp[mask] = min(dp[mask], 1 + dp[nextMask]) + + return dp[self.encode(grid, m, n)] + + def encode(self, grid: List[List[int]], m: int, n: int) -> int: + encoded = 0 + for i in range(m): + for j in range(n): + if grid[i][j]: + encoded |= 1 << i * n + j + return encoded diff --git a/solutions/2174. Remove All Ones With Row and Column Flips II/2174.cpp b/solutions/2174. Remove All Ones With Row and Column Flips II/2174.cpp new file mode 100644 index 00000000000..a23e484fd84 --- /dev/null +++ b/solutions/2174. Remove All Ones With Row and Column Flips II/2174.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int removeOnes(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector mem(1 << m * n, INT_MAX); + return removeOnes(encode(grid, m, n), m, n, mem); + } + + private: + // Returns the minimum number of operations to remove all 1s from the grid, + // where `mask` is the bitmask of the state of the grid. + int removeOnes(int mask, int m, int n, vector& mem) { + if (mask == 0) + return 0; + if (mem[mask] < INT_MAX) + return mem[mask]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mask >> i * n + j & 1) { // grid[i][j] == 1 + int nextMask = mask; + // Set the cells in the same row with 0. + for (int k = 0; k < n; ++k) + nextMask &= ~(1 << i * n + k); + // Set the cells in the same column with 0. + for (int k = 0; k < m; ++k) + nextMask &= ~(1 << k * n + j); + mem[mask] = min(mem[mask], 1 + removeOnes(nextMask, m, n, mem)); + } + + return mem[mask]; + } + + int encode(const vector>& grid, int m, int n) { + int encoded = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j]) + encoded |= 1 << i * n + j; + return encoded; + } +}; diff --git a/solutions/2174. Remove All Ones With Row and Column Flips II/2174.java b/solutions/2174. Remove All Ones With Row and Column Flips II/2174.java new file mode 100644 index 00000000000..0cdf13cd6c5 --- /dev/null +++ b/solutions/2174. Remove All Ones With Row and Column Flips II/2174.java @@ -0,0 +1,42 @@ +class Solution { + public int removeOnes(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[] mem = new int[1 << m * n]; + Arrays.fill(mem, Integer.MAX_VALUE); + return removeOnes(encode(grid, m, n), m, n, mem); + } + + // Returns the minimum number of operations to remove all 1s from the grid, + // where `mask` is the bitmask of the state of the grid. + private int removeOnes(int mask, int m, int n, int[] mem) { + if (mask == 0) + return 0; + if (mem[mask] < Integer.MAX_VALUE) + return mem[mask]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if ((mask >> i * n + j & 1) == 1) { // grid[i][j] == 1 + int nextMask = mask; + // Set the cells in the same row with 0. + for (int k = 0; k < n; ++k) + nextMask &= ~(1 << i * n + k); + // Set the cells in the same column with 0. + for (int k = 0; k < m; ++k) + nextMask &= ~(1 << k * n + j); + mem[mask] = Math.min(mem[mask], 1 + removeOnes(nextMask, m, n, mem)); + } + + return mem[mask]; + } + + private int encode(int[][] grid, int m, int n) { + int encoded = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + encoded |= 1 << i * n + j; + return encoded; + } +} diff --git a/solutions/2174. Remove All Ones With Row and Column Flips II/2174.py b/solutions/2174. Remove All Ones With Row and Column Flips II/2174.py new file mode 100644 index 00000000000..b20a3de3a8c --- /dev/null +++ b/solutions/2174. Remove All Ones With Row and Column Flips II/2174.py @@ -0,0 +1,34 @@ +class Solution: + def removeOnes(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + + @functools.lru_cache(None) + def dp(mask: int) -> int: + """ + Returns the minimum number of operations to remove all 1s from the grid, + where `mask` is the bitmask of the state of the grid. + """ + if mask == 0: + return 0 + ans = math.inf + for i in range(m): + for j in range(n): + if mask >> i * n + j & 1: # grid[i][j] == 1 + nextMask = mask + for k in range(n): # Set the cells in the same row with 0. + nextMask &= ~(1 << i * n + k) + for k in range(m): # Set the cells in the same column with 0. + nextMask &= ~(1 << k * n + j) + ans = min(ans, 1 + dp(nextMask)) + return ans + + return dp(self.encode(grid, m, n)) + + def encode(self, grid: List[List[int]], m: int, n: int) -> int: + encoded = 0 + for i in range(m): + for j in range(n): + if grid[i][j]: + encoded |= 1 << i * n + j + return encoded diff --git a/solutions/2175. The Change in Global Rankings/2175.sql b/solutions/2175. The Change in Global Rankings/2175.sql new file mode 100644 index 00000000000..b1f54850260 --- /dev/null +++ b/solutions/2175. The Change in Global Rankings/2175.sql @@ -0,0 +1,17 @@ +SELECT + TeamPoints.team_id, + TeamPoints.name, + CAST( + RANK() OVER( + ORDER BY TeamPoints.points DESC, TeamPoints.name + ) AS SIGNED + ) - + CAST( + RANK() OVER( + ORDER BY TeamPoints.points + PointsChange.points_change DESC, + TeamPoints.name + ) AS SIGNED + ) AS rank_diff +FROM TeamPoints +INNER JOIN PointsChange + USING (team_id); diff --git a/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.cpp b/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.cpp new file mode 100644 index 00000000000..9d3f4cbe3d3 --- /dev/null +++ b/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int countPairs(vector& nums, int k) { + int ans = 0; + unordered_map> numToIndices; + + for (int i = 0; i < nums.size(); ++i) + numToIndices[nums[i]].push_back(i); + + for (const auto& [_, indices] : numToIndices) { + unordered_map gcds; + for (const int i : indices) { + const int gcd_i = gcd(i, k); + for (const auto& [gcd_j, count] : gcds) + if (gcd_i * gcd_j % k == 0) + ans += count; + ++gcds[gcd_i]; + } + } + + return ans; + } +}; diff --git a/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.java b/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.java new file mode 100644 index 00000000000..977dbf70047 --- /dev/null +++ b/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.java @@ -0,0 +1,28 @@ +class Solution { + public int countPairs(int[] nums, int k) { + int ans = 0; + Map> numToIndices = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + numToIndices.putIfAbsent(nums[i], new ArrayList<>()); + numToIndices.get(nums[i]).add(i); + } + + for (List indices : numToIndices.values()) { + Map gcds = new HashMap<>(); + for (final int i : indices) { + final int gcd_i = gcd(i, k); + for (final int gcd_j : gcds.keySet()) + if (gcd_i * gcd_j % k == 0) + ans += gcds.get(gcd_j); + gcds.merge(gcd_i, 1, Integer::sum); + } + } + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.py b/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.py new file mode 100644 index 00000000000..0f8340cba45 --- /dev/null +++ b/solutions/2176. Count Equal and Divisible Pairs in an Array/2176.py @@ -0,0 +1,18 @@ +class Solution: + def countPairs(self, nums: List[int], k: int) -> int: + ans = 0 + numToIndices = collections.defaultdict(list) + + for i, num in enumerate(nums): + numToIndices[num].append(i) + + for indices in numToIndices.values(): + gcds = collections.Counter() + for i in indices: + gcd_i = math.gcd(i, k) + for gcd_j, count in gcds.items(): + if gcd_i * gcd_j % k == 0: + ans += count + gcds[gcd_i] += 1 + + return ans diff --git a/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.cpp b/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.cpp new file mode 100644 index 00000000000..b9879c7df32 --- /dev/null +++ b/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + vector sumOfThree(long long num) { + if (num % 3) + return {}; + const long x = num / 3; + return {x - 1, x, x + 1}; + } +}; diff --git a/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.java b/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.java new file mode 100644 index 00000000000..a942a45016b --- /dev/null +++ b/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.java @@ -0,0 +1,8 @@ +class Solution { + public long[] sumOfThree(long num) { + if (num % 3 != 0) + return new long[] {}; + final long x = num / 3; + return new long[] {x - 1, x, x + 1}; + } +} diff --git a/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.py b/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.py new file mode 100644 index 00000000000..4a15f67f195 --- /dev/null +++ b/solutions/2177. Find Three Consecutive Integers That Sum to a Given Number/2177.py @@ -0,0 +1,6 @@ +class Solution: + def sumOfThree(self, num: int) -> List[int]: + if num % 3: + return [] + x = num // 3 + return [x - 1, x, x + 1] diff --git a/solutions/2178. Maximum Split of Positive Even Integers/2178.cpp b/solutions/2178. Maximum Split of Positive Even Integers/2178.cpp new file mode 100644 index 00000000000..2aefc0fbe6e --- /dev/null +++ b/solutions/2178. Maximum Split of Positive Even Integers/2178.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector maximumEvenSplit(long long finalSum) { + if (finalSum % 2 == 1) + return {}; + + vector ans; + long needSum = finalSum; + long even = 2; + + while (needSum - even >= even + 2) { + ans.push_back(even); + needSum -= even; + even += 2; + } + + ans.push_back(needSum); + return ans; + } +}; diff --git a/solutions/2178. Maximum Split of Positive Even Integers/2178.java b/solutions/2178. Maximum Split of Positive Even Integers/2178.java new file mode 100644 index 00000000000..e4baf068713 --- /dev/null +++ b/solutions/2178. Maximum Split of Positive Even Integers/2178.java @@ -0,0 +1,19 @@ +class Solution { + public List maximumEvenSplit(long finalSum) { + if (finalSum % 2 == 1) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + long needSum = finalSum; + long even = 2; + + while (needSum - even >= even + 2) { + ans.add(even); + needSum -= even; + even += 2; + } + + ans.add(needSum); + return ans; + } +} diff --git a/solutions/2178. Maximum Split of Positive Even Integers/2178.py b/solutions/2178. Maximum Split of Positive Even Integers/2178.py new file mode 100644 index 00000000000..ab5715541d1 --- /dev/null +++ b/solutions/2178. Maximum Split of Positive Even Integers/2178.py @@ -0,0 +1,15 @@ +class Solution: + def maximumEvenSplit(self, finalSum: int) -> List[int]: + if finalSum % 2 == 1: + return [] + + ans = [] + needSum = finalSum + even = 2 + + while needSum - even >= even + 2: + ans.append(even) + needSum -= even + even += 2 + + return ans + [needSum] diff --git a/solutions/2179. Count Good Triplets in an Array/2179.cpp b/solutions/2179. Count Good Triplets in an Array/2179.cpp new file mode 100644 index 00000000000..09b99515e20 --- /dev/null +++ b/solutions/2179. Count Good Triplets in an Array/2179.cpp @@ -0,0 +1,66 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + long long goodTriplets(vector& nums1, vector& nums2) { + const int n = nums1.size(); + long ans = 0; + unordered_map numToIndex; + vector A; + // leftSmaller[i] := the number of A[j] < A[i], where 0 <= j < i + vector leftSmaller(n); + // rightLarger[i] := the number of A[j] > A[i], where i < j < n + vector rightLarger(n); + FenwickTree tree1(n); // Calculates `leftSmaller`. + FenwickTree tree2(n); // Calculates `rightLarger`. + + for (int i = 0; i < n; ++i) + numToIndex[nums1[i]] = i; + + // Remap each number in `nums2` to the according index in `nums1` as `A`. + // Rephrase the problem as finding the number of increasing tripets in `A`. + for (const int num : nums2) + A.push_back(numToIndex[num]); + + for (int i = 0; i < n; ++i) { + leftSmaller[i] = tree1.get(A[i]); + tree1.add(A[i] + 1, 1); + } + + for (int i = n - 1; i >= 0; --i) { + rightLarger[i] = tree2.get(n) - tree2.get(A[i]); + tree2.add(A[i] + 1, 1); + } + + for (int i = 0; i < n; ++i) + ans += static_cast(leftSmaller[i]) * rightLarger[i]; + + return ans; + } +}; diff --git a/solutions/2179. Count Good Triplets in an Array/2179.java b/solutions/2179. Count Good Triplets in an Array/2179.java new file mode 100644 index 00000000000..bc8e3316a8c --- /dev/null +++ b/solutions/2179. Count Good Triplets in an Array/2179.java @@ -0,0 +1,65 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public long goodTriplets(int[] nums1, int[] nums2) { + final int n = nums1.length; + long ans = 0; + Map numToIndex = new HashMap<>(); + int[] A = new int[n]; + // leftSmaller[i] := the number of A[j] < A[i], where 0 <= j < i + int[] leftSmaller = new int[n]; + // rightLarger[i] := the number of A[j] > A[i], where i < j < n + int[] rightLarger = new int[n]; + FenwickTree tree1 = new FenwickTree(n); // Calculates `leftSmaller`. + FenwickTree tree2 = new FenwickTree(n); // Calculates `rightLarger`. + + for (int i = 0; i < n; ++i) + numToIndex.put(nums1[i], i); + + // Remap each number in `nums2` to the according index in `nums1` as `A`. + // Rephrase the problem as finding the number of increasing tripets in `A`. + for (int i = 0; i < n; ++i) + A[i] = numToIndex.get(nums2[i]); + + for (int i = 0; i < n; ++i) { + leftSmaller[i] = tree1.get(A[i]); + tree1.add(A[i] + 1, 1); + } + + for (int i = n - 1; i >= 0; --i) { + rightLarger[i] = tree2.get(n) - tree2.get(A[i]); + tree2.add(A[i] + 1, 1); + } + + for (int i = 0; i < n; ++i) + ans += (long) leftSmaller[i] * rightLarger[i]; + + return ans; + } +} diff --git a/solutions/2179. Count Good Triplets in an Array/2179.py b/solutions/2179. Count Good Triplets in an Array/2179.py new file mode 100644 index 00000000000..8bfb39a61f5 --- /dev/null +++ b/solutions/2179. Count Good Triplets in an Array/2179.py @@ -0,0 +1,44 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums1) + numToIndex = {num: i for i, num in enumerate(nums1)} + # Remap each number in `nums2` to the according index in `nums1` as `A`. + # Rephrase the problem as finding the number of increasing tripets in `A`. + A = [numToIndex[num] for num in nums2] + # leftSmaller[i] := the number of A[j] < A[i], where 0 <= j < i + leftSmaller = [0] * n + # rightLarger[i] := the number of A[j] > A[i], where i < j < n + rightLarger = [0] * n + tree1 = FenwickTree(n) # Calculates `leftSmaller`. + tree2 = FenwickTree(n) # Calculates `rightLarger`. + + for i, a in enumerate(A): + leftSmaller[i] = tree1.get(a) + tree1.add(a + 1, 1) + + for i, a in reversed(list(enumerate(A))): + rightLarger[i] = tree2.get(n) - tree2.get(a) + tree2.add(a + 1, 1) + + return sum(a * b for a, b in zip(leftSmaller, rightLarger)) diff --git a/solutions/218. The Skyline Problem/218-2.cpp b/solutions/218. The Skyline Problem/218-2.cpp new file mode 100644 index 00000000000..823f524674a --- /dev/null +++ b/solutions/218. The Skyline Problem/218-2.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + vector> getSkyline(vector>& buildings) { + vector> ans; + vector> events; // [(Li, Hi) | (Ri, -Hi)] + + for (const vector& b : buildings) { + events.push_back({b[0], b[2]}); + events.push_back({b[1], -b[2]}); // Minus means leaving. + } + + ranges::sort(events, [](const vector& a, const vector& b) { + return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; + }); + + for (const vector& event : events) { + const int x = event[0]; + const int h = abs(event[1]); + const int isEntering = event[1] > 0; + if (isEntering) { + if (h > maxHeight()) + ans.push_back({x, h}); + set.insert(h); + } else { + set.erase(set.equal_range(h).first); + if (h > maxHeight()) + ans.push_back({x, maxHeight()}); + } + } + + return ans; + } + + private: + multiset set; + + int maxHeight() const { + return set.empty() ? 0 : *set.rbegin(); + } +}; diff --git a/solutions/218. The Skyline Problem/218.cpp b/solutions/218. The Skyline Problem/218.cpp new file mode 100644 index 00000000000..b065b562b57 --- /dev/null +++ b/solutions/218. The Skyline Problem/218.cpp @@ -0,0 +1,58 @@ +class Solution { + public: + vector> getSkyline(const vector>& buildings) { + const int n = buildings.size(); + if (n == 0) + return {}; + if (n == 1) { + const int left = buildings[0][0]; + const int right = buildings[0][1]; + const int height = buildings[0][2]; + return {{left, height}, {right, 0}}; + } + + const vector> left = + getSkyline({buildings.begin(), buildings.begin() + n / 2}); + const vector> right = + getSkyline({buildings.begin() + n / 2, buildings.end()}); + return merge(left, right); + } + + private: + vector> merge(const vector>& left, + const vector>& right) { + vector> ans; + int i = 0; // left's index + int j = 0; // right's index + int leftY = 0; + int rightY = 0; + + while (i < left.size() && j < right.size()) + // Choose the point with the smaller x. + if (left[i][0] < right[j][0]) { + leftY = left[i][1]; // Update the ongoing `leftY`. + addPoint(ans, left[i][0], max(left[i++][1], rightY)); + } else { + rightY = right[j][1]; // Update the ongoing `rightY`. + addPoint(ans, right[j][0], max(right[j++][1], leftY)); + } + + while (i < left.size()) + addPoint(ans, left[i][0], left[i++][1]); + + while (j < right.size()) + addPoint(ans, right[j][0], right[j++][1]); + + return ans; + } + + void addPoint(vector>& ans, int x, int y) { + if (!ans.empty() && ans.back()[0] == x) { + ans.back()[1] = y; + return; + } + if (!ans.empty() && ans.back()[1] == y) + return; + ans.push_back({x, y}); + } +}; diff --git a/solutions/218. The Skyline Problem/218.java b/solutions/218. The Skyline Problem/218.java new file mode 100644 index 00000000000..fa064c6c673 --- /dev/null +++ b/solutions/218. The Skyline Problem/218.java @@ -0,0 +1,56 @@ +class Solution { + public List> getSkyline(int[][] buildings) { + final int n = buildings.length; + if (n == 0) + return new ArrayList<>(); + if (n == 1) { + final int left = buildings[0][0]; + final int right = buildings[0][1]; + final int height = buildings[0][2]; + List> ans = new ArrayList<>(); + ans.add(new ArrayList<>(Arrays.asList(left, height))); + ans.add(new ArrayList<>(Arrays.asList(right, 0))); + return ans; + } + + List> leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, n / 2)); + List> rightSkyline = getSkyline(Arrays.copyOfRange(buildings, n / 2, n)); + return merge(leftSkyline, rightSkyline); + } + + private List> merge(List> left, List> right) { + List> ans = new ArrayList<>(); + int i = 0; // left's index + int j = 0; // right's index + int leftY = 0; + int rightY = 0; + + while (i < left.size() && j < right.size()) + // Choose the point with the smaller x. + if (left.get(i).get(0) < right.get(j).get(0)) { + leftY = left.get(i).get(1); // Update the ongoing `leftY`. + addPoint(ans, left.get(i).get(0), Math.max(left.get(i++).get(1), rightY)); + } else { + rightY = right.get(j).get(1); // Update the ongoing `rightY`. + addPoint(ans, right.get(j).get(0), Math.max(right.get(j++).get(1), leftY)); + } + + while (i < left.size()) + addPoint(ans, left.get(i).get(0), left.get(i++).get(1)); + + while (j < right.size()) + addPoint(ans, right.get(j).get(0), right.get(j++).get(1)); + + return ans; + } + + private void addPoint(List> ans, int x, int y) { + if (!ans.isEmpty() && ans.get(ans.size() - 1).get(0) == x) { + ans.get(ans.size() - 1).set(1, y); + return; + } + if (!ans.isEmpty() && ans.get(ans.size() - 1).get(1) == y) + return; + ans.add(new ArrayList<>(Arrays.asList(x, y))); + } +} diff --git a/solutions/218. The Skyline Problem/218.py b/solutions/218. The Skyline Problem/218.py new file mode 100644 index 00000000000..60102389ff2 --- /dev/null +++ b/solutions/218. The Skyline Problem/218.py @@ -0,0 +1,48 @@ +class Solution: + def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: + n = len(buildings) + if n == 0: + return [] + if n == 1: + left, right, height = buildings[0] + return [[left, height], [right, 0]] + + left = self.getSkyline(buildings[:n // 2]) + right = self.getSkyline(buildings[n // 2:]) + return self._merge(left, right) + + def _merge(self, left: List[List[int]], right: List[List[int]]) -> List[List[int]]: + ans = [] + i = 0 # left's index + j = 0 # right's index + leftY = 0 + rightY = 0 + + while i < len(left) and j < len(right): + # Choose the powith smaller x + if left[i][0] < right[j][0]: + leftY = left[i][1] # Update the ongoing `leftY`. + self._addPoint(ans, left[i][0], max(left[i][1], rightY)) + i += 1 + else: + rightY = right[j][1] # Update the ongoing `rightY`. + self._addPoint(ans, right[j][0], max(right[j][1], leftY)) + j += 1 + + while i < len(left): + self._addPoint(ans, left[i][0], left[i][1]) + i += 1 + + while j < len(right): + self._addPoint(ans, right[j][0], right[j][1]) + j += 1 + + return ans + + def _addPoint(self, ans: List[List[int]], x: int, y: int) -> None: + if ans and ans[-1][0] == x: + ans[-1][1] = y + return + if ans and ans[-1][1] == y: + return + ans.append([x, y]) diff --git a/solutions/2180. Count Integers With Even Digit Sum/2180.cpp b/solutions/2180. Count Integers With Even Digit Sum/2180.cpp new file mode 100644 index 00000000000..f9e56914ac7 --- /dev/null +++ b/solutions/2180. Count Integers With Even Digit Sum/2180.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int countEven(int num) { + return (num - getDigitSum(num) % 2) / 2; + } + + private: + int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +}; diff --git a/solutions/2180. Count Integers With Even Digit Sum/2180.java b/solutions/2180. Count Integers With Even Digit Sum/2180.java new file mode 100644 index 00000000000..30b3701ed8a --- /dev/null +++ b/solutions/2180. Count Integers With Even Digit Sum/2180.java @@ -0,0 +1,16 @@ +class Solution { + public int countEven(int num) { + if (getDigitSum(num) % 2 == 0) + return num / 2; + return (num - 1) / 2; + } + + private int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +} diff --git a/solutions/2180. Count Integers With Even Digit Sum/2180.py b/solutions/2180. Count Integers With Even Digit Sum/2180.py new file mode 100644 index 00000000000..f42f30befba --- /dev/null +++ b/solutions/2180. Count Integers With Even Digit Sum/2180.py @@ -0,0 +1,6 @@ +class Solution: + def countEven(self, num: int) -> int: + return (num - self._getDigitSum(num) % 2) // 2 + + def _getDigitSum(self, num: int) -> int: + return sum(int(digit) for digit in str(num)) diff --git a/solutions/2181. Merge Nodes in Between Zeros/2181-2.cpp b/solutions/2181. Merge Nodes in Between Zeros/2181-2.cpp new file mode 100644 index 00000000000..f2b395e6203 --- /dev/null +++ b/solutions/2181. Merge Nodes in Between Zeros/2181-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + ListNode* mergeNodes(ListNode* head) { + ListNode* curr = head->next; + + while (curr) { + ListNode* running = curr; + int sum = 0; + while (running->val) { + sum += running->val; + running = running->next; + } + curr->val = sum; + curr->next = running->next; + curr = running->next; + } + + return head->next; + } +}; diff --git a/solutions/2181. Merge Nodes in Between Zeros/2181-2.java b/solutions/2181. Merge Nodes in Between Zeros/2181-2.java new file mode 100644 index 00000000000..9dde6a58702 --- /dev/null +++ b/solutions/2181. Merge Nodes in Between Zeros/2181-2.java @@ -0,0 +1,19 @@ +class Solution { + public ListNode mergeNodes(ListNode head) { + ListNode curr = head.next; + + while (curr != null) { + ListNode running = curr; + int sum = 0; + while (running.val > 0) { + sum += running.val; + running = running.next; + } + curr.val = sum; + curr.next = running.next; + curr = running.next; + } + + return head.next; + } +} diff --git a/solutions/2181. Merge Nodes in Between Zeros/2181-2.py b/solutions/2181. Merge Nodes in Between Zeros/2181-2.py new file mode 100644 index 00000000000..04fee1ad371 --- /dev/null +++ b/solutions/2181. Merge Nodes in Between Zeros/2181-2.py @@ -0,0 +1,16 @@ +class Solution: + def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: + curr = head.next + + while curr: + running = curr + summ = 0 + while running.val: + summ += running.val + running = running.next + + curr.val = summ + curr.next = running.next + curr = running.next + + return head.next diff --git a/solutions/2181. Merge Nodes in Between Zeros/2181.cpp b/solutions/2181. Merge Nodes in Between Zeros/2181.cpp new file mode 100644 index 00000000000..7b42576584f --- /dev/null +++ b/solutions/2181. Merge Nodes in Between Zeros/2181.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + ListNode* mergeNodes(ListNode* head) { + if (head == nullptr) + return nullptr; + if (!head->next->val) { + ListNode* node = new ListNode(head->val); + node->next = mergeNodes(head->next->next); + return node; + } + + ListNode* next = mergeNodes(head->next); + next->val += head->val; + return next; + } +}; diff --git a/solutions/2181. Merge Nodes in Between Zeros/2181.java b/solutions/2181. Merge Nodes in Between Zeros/2181.java new file mode 100644 index 00000000000..46a11f866ff --- /dev/null +++ b/solutions/2181. Merge Nodes in Between Zeros/2181.java @@ -0,0 +1,15 @@ +class Solution { + public ListNode mergeNodes(ListNode head) { + if (head == null) + return null; + if (head.next.val == 0) { + ListNode node = new ListNode(head.val); + node.next = mergeNodes(head.next.next); + return node; + } + + ListNode next = mergeNodes(head.next); + next.val += head.val; + return next; + } +} diff --git a/solutions/2181. Merge Nodes in Between Zeros/2181.py b/solutions/2181. Merge Nodes in Between Zeros/2181.py new file mode 100644 index 00000000000..342fcb4e661 --- /dev/null +++ b/solutions/2181. Merge Nodes in Between Zeros/2181.py @@ -0,0 +1,12 @@ +class Solution: + def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head: + return None + if not head.next.val: + node = ListNode(head.val) + node.next = self.mergeNodes(head.next.next) + return node + + next = self.mergeNodes(head.next) + next.val += head.val + return next diff --git a/solutions/2182. Construct String With Repeat Limit/2182.cpp b/solutions/2182. Construct String With Repeat Limit/2182.cpp new file mode 100644 index 00000000000..0d7ef24423c --- /dev/null +++ b/solutions/2182. Construct String With Repeat Limit/2182.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + string repeatLimitedString(string s, int repeatLimit) { + string ans; + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + while (true) { + const bool addOne = !ans.empty() && shouldAddOne(ans, count); + const int i = getLargestChar(ans, count); + if (i == -1) + break; + const int repeats = addOne ? 1 : min(count[i], repeatLimit); + ans += string(repeats, 'a' + i); + count[i] -= repeats; + } + + return ans; + } + + private: + bool shouldAddOne(const string& ans, const vector& count) { + for (int i = 25; i >= 0; --i) + if (count[i]) + return ans.back() == 'a' + i; + return false; + } + + int getLargestChar(const string& ans, const vector& count) { + for (int i = 25; i >= 0; --i) + if (count[i] && (ans.empty() || ans.back() != 'a' + i)) + return i; + return -1; + } +}; diff --git a/solutions/2182. Construct String With Repeat Limit/2182.java b/solutions/2182. Construct String With Repeat Limit/2182.java new file mode 100644 index 00000000000..c34db955c96 --- /dev/null +++ b/solutions/2182. Construct String With Repeat Limit/2182.java @@ -0,0 +1,35 @@ +class Solution { + public String repeatLimitedString(String s, int repeatLimit) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + while (true) { + final boolean addOne = !sb.isEmpty() && shouldAddOne(sb, count); + final int i = getLargestChar(sb, count); + if (i == -1) + break; + final int repeats = addOne ? 1 : Math.min(count[i], repeatLimit); + sb.append(String.valueOf((char) ('a' + i)).repeat(repeats)); + count[i] -= repeats; + } + + return sb.toString(); + } + + private boolean shouldAddOne(StringBuilder sb, int[] count) { + for (int i = 25; i >= 0; --i) + if (count[i] > 0) + return sb.charAt(sb.length() - 1) == 'a' + i; + return false; + } + + private int getLargestChar(StringBuilder sb, int[] count) { + for (int i = 25; i >= 0; --i) + if (count[i] > 0 && (sb.isEmpty() || sb.charAt(sb.length() - 1) != 'a' + i)) + return i; + return -1; + } +} diff --git a/solutions/2182. Construct String With Repeat Limit/2182.py b/solutions/2182. Construct String With Repeat Limit/2182.py new file mode 100644 index 00000000000..d8aa5ba63b1 --- /dev/null +++ b/solutions/2182. Construct String With Repeat Limit/2182.py @@ -0,0 +1,27 @@ +class Solution: + def repeatLimitedString(self, s: str, repeatLimit: int) -> str: + ans = '' + count = collections.Counter(s) + + while True: + addOne = ans and self._shouldAddOne(ans, count) + c = self._getLargestChar(ans, count) + if c == ' ': + break + repeats = 1 if addOne else min(count[c], repeatLimit) + ans += c * repeats + count[c] -= repeats + + return ans + + def _shouldAddOne(self, ans: str, count: collections.Counter) -> bool: + for c in reversed(string.ascii_lowercase): + if count[c]: + return ans[-1] == c + return False + + def _getLargestChar(self, ans: str, count: collections.Counter) -> int: + for c in reversed(string.ascii_lowercase): + if count[c] and (not ans or ans[-1] != c): + return c + return ' ' diff --git a/solutions/2183. Count Array Pairs Divisible by K/2183.cpp b/solutions/2183. Count Array Pairs Divisible by K/2183.cpp new file mode 100644 index 00000000000..8c715e1fafd --- /dev/null +++ b/solutions/2183. Count Array Pairs Divisible by K/2183.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + long long countPairs(vector& nums, int k) { + long ans = 0; + unordered_map gcds; + + for (const int num : nums) { + const int gcd_i = gcd(num, k); + for (const auto& [gcd_j, count] : gcds) + if (static_cast(gcd_i) * gcd_j % k == 0) + ans += count; + ++gcds[gcd_i]; + } + + return ans; + } +}; diff --git a/solutions/2183. Count Array Pairs Divisible by K/2183.java b/solutions/2183. Count Array Pairs Divisible by K/2183.java new file mode 100644 index 00000000000..fccab917a25 --- /dev/null +++ b/solutions/2183. Count Array Pairs Divisible by K/2183.java @@ -0,0 +1,20 @@ +class Solution { + public long countPairs(int[] nums, int k) { + long ans = 0; + Map gcds = new HashMap<>(); + + for (final int num : nums) { + final int gcd_i = gcd(num, k); + for (final int gcd_j : gcds.keySet()) + if ((long) gcd_i * gcd_j % k == 0) + ans += gcds.get(gcd_j); + gcds.merge(gcd_i, 1, Integer::sum); + } + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2183. Count Array Pairs Divisible by K/2183.py b/solutions/2183. Count Array Pairs Divisible by K/2183.py new file mode 100644 index 00000000000..ac3b6b7a7cf --- /dev/null +++ b/solutions/2183. Count Array Pairs Divisible by K/2183.py @@ -0,0 +1,13 @@ +class Solution: + def countPairs(self, nums: List[int], k: int) -> int: + ans = 0 + gcds = collections.Counter() + + for num in nums: + gcd_i = math.gcd(num, k) + for gcd_j, count in gcds.items(): + if gcd_i * gcd_j % k == 0: + ans += count + gcds[gcd_i] += 1 + + return ans diff --git a/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.cpp b/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.cpp new file mode 100644 index 00000000000..cbbcd410bd5 --- /dev/null +++ b/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int buildWall(int height, int width, vector& bricks) { + constexpr int kMod = 1'000'000'007; + // Stores the valid rows in bitmask. + vector rows; + buildRows(width, bricks, 0, rows); + + const int n = rows.size(); + // dp[i] := the number of ways to build `h` height walls with rows[i] in the + // bottom + vector dp(n, 1); + // graph[i] := the valid neighbors of rows[i] + vector> graph(n); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (!(rows[i] & rows[j])) + graph[i].push_back(j); + + for (int h = 2; h <= height; ++h) { + vector newDp(n); + for (int i = 0; i < n; ++i) + for (const int v : graph[i]) { + newDp[i] += dp[v]; + newDp[i] %= kMod; + } + dp = move(newDp); + } + + return accumulate(dp.begin(), dp.end(), 0L) % kMod; + } + + private: + void buildRows(int width, const vector& bricks, int path, + vector& rows) { + for (const int brick : bricks) + if (brick == width) + rows.push_back(path); + else if (brick < width) { + const int newWidth = width - brick; + buildRows(newWidth, bricks, path | 1 << newWidth, rows); + } + } +}; diff --git a/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.java b/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.java new file mode 100644 index 00000000000..7645a7a661e --- /dev/null +++ b/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.java @@ -0,0 +1,46 @@ +class Solution { + public int buildWall(int height, int width, int[] bricks) { + final int kMod = 1_000_000_007; + // Stores the valid rows in bitmask. + List rows = new ArrayList<>(); + buildRows(width, bricks, 0, rows); + + final int n = rows.size(); + // dp[i] := the number of ways to build `h` height walls With rows[i] in the bottom + long[] dp = new long[n]; + // graph[i] := the valid neighbors of rows[i] + List[] graph = new List[n]; + + Arrays.fill(dp, 1); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if ((rows.get(i) & rows.get(j)) == 0) + graph[i].add(j); + + for (int h = 2; h <= height; ++h) { + long[] newDp = new long[n]; + for (int i = 0; i < n; ++i) + for (final int v : graph[i]) { + newDp[i] += dp[v]; + newDp[i] %= kMod; + } + dp = newDp; + } + + return (int) (Arrays.stream(dp).sum() % kMod); + } + + private void buildRows(int width, int[] bricks, int path, List rows) { + for (final int brick : bricks) + if (brick == width) + rows.add(path); + else if (brick < width) { + final int newWidth = width - brick; + buildRows(newWidth, bricks, path | 1 << newWidth, rows); + } + } +} diff --git a/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.py b/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.py new file mode 100644 index 00000000000..04b577ec1b6 --- /dev/null +++ b/solutions/2184. Number of Ways to Build Sturdy Brick Wall/2184.py @@ -0,0 +1,35 @@ +class Solution: + def buildWall(self, height: int, width: int, bricks: List[int]) -> int: + kMod = 1_000_000_007 + # Stores the valid rows in bitmask. + rows = [] + self._buildRows(width, bricks, 0, rows) + + n = len(rows) + # dp[i] := the number of ways to build `h` height walls with rows[i] in the bottom + dp = [1] * n + # graph[i] := the valid neighbors of rows[i] + graph = [[] for _ in range(n)] + + for i, a in enumerate(rows): + for j, b in enumerate(rows): + if not a & b: + graph[i].append(j) + + for _ in range(2, height + 1): + newDp = [0] * n + for i in range(n): + for v in graph[i]: + newDp[i] += dp[v] + newDp[i] %= kMod + dp = newDp + + return sum(dp) % kMod + + def _buildRows(self, width: int, bricks: List[int], path: int, rows: List[int]): + for brick in bricks: + if brick == width: + rows.append(path) + elif brick < width: + newWidth = width - brick + self._buildRows(newWidth, bricks, path | 2 << newWidth, rows) diff --git a/solutions/2185. Counting Words With a Given Prefix/2185.cpp b/solutions/2185. Counting Words With a Given Prefix/2185.cpp new file mode 100644 index 00000000000..6cac0cb1d46 --- /dev/null +++ b/solutions/2185. Counting Words With a Given Prefix/2185.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int prefixCount(vector& words, string pref) { + return ranges::count_if( + words, [&](const string& word) { return word.find(pref) == 0; }); + } +}; diff --git a/solutions/2185. Counting Words With a Given Prefix/2185.java b/solutions/2185. Counting Words With a Given Prefix/2185.java new file mode 100644 index 00000000000..b3ed8f47069 --- /dev/null +++ b/solutions/2185. Counting Words With a Given Prefix/2185.java @@ -0,0 +1,5 @@ +class Solution { + public int prefixCount(String[] words, String pref) { + return (int) Arrays.stream(words).filter(w -> w.startsWith(pref)).count(); + } +} diff --git a/solutions/2185. Counting Words With a Given Prefix/2185.py b/solutions/2185. Counting Words With a Given Prefix/2185.py new file mode 100644 index 00000000000..60675f7fd17 --- /dev/null +++ b/solutions/2185. Counting Words With a Given Prefix/2185.py @@ -0,0 +1,3 @@ +class Solution: + def prefixCount(self, words: List[str], pref: str) -> int: + return sum(word.startswith(pref) for word in words) diff --git a/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.cpp b/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.cpp new file mode 100644 index 00000000000..18b7ee1cd4d --- /dev/null +++ b/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minSteps(string s, string t) { + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + for (const char c : t) + --count[c - 'a']; + + return accumulate(count.begin(), count.end(), 0, + [](int subtotal, int c) { return subtotal + abs(c); }); + } +}; diff --git a/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.java b/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.java new file mode 100644 index 00000000000..7877e99d89e --- /dev/null +++ b/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.java @@ -0,0 +1,8 @@ +class Solution { + public int minSteps(String s, String t) { + int[] count = new int[26]; + s.chars().forEach(c -> ++count[c - 'a']); + t.chars().forEach(c -> --count[c - 'a']); + return Arrays.stream(count).map(Math::abs).sum(); + } +} diff --git a/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.py b/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.py new file mode 100644 index 00000000000..1f831160739 --- /dev/null +++ b/solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.py @@ -0,0 +1,5 @@ +class Solution: + def minSteps(self, s: str, t: str) -> int: + count = collections.Counter(s) + count.subtract(collections.Counter(t)) + return sum([abs(c) for c in count.values()]) diff --git a/solutions/2187. Minimum Time to Complete Trips/2187.cpp b/solutions/2187. Minimum Time to Complete Trips/2187.cpp new file mode 100644 index 00000000000..69ad592997a --- /dev/null +++ b/solutions/2187. Minimum Time to Complete Trips/2187.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + long long minimumTime(vector& time, int totalTrips) { + long l = 1; + long r = static_cast(ranges::min(time)) * totalTrips; + + while (l < r) { + const long m = (l + r) / 2; + if (numTrips(time, m) >= totalTrips) + r = m; + else + l = m + 1; + } + + return l; + } + + long numTrips(const vector& times, long m) { + return accumulate(times.begin(), times.end(), 0L, + [&](long subtotal, int t) { return subtotal + m / t; }); + } +}; diff --git a/solutions/2187. Minimum Time to Complete Trips/2187.java b/solutions/2187. Minimum Time to Complete Trips/2187.java new file mode 100644 index 00000000000..87fbb0ee424 --- /dev/null +++ b/solutions/2187. Minimum Time to Complete Trips/2187.java @@ -0,0 +1,20 @@ +class Solution { + public long minimumTime(int[] time, int totalTrips) { + long l = 1; + long r = Arrays.stream(time).min().getAsInt() * (long) totalTrips; + + while (l < r) { + final long m = (l + r) / 2; + if (numTrips(time, m) >= totalTrips) + r = m; + else + l = m + 1; + } + + return l; + } + + private long numTrips(int[] time, long m) { + return Arrays.stream(time).asLongStream().reduce(0L, (subtotal, t) -> subtotal + m / t); + } +} diff --git a/solutions/2187. Minimum Time to Complete Trips/2187.py b/solutions/2187. Minimum Time to Complete Trips/2187.py new file mode 100644 index 00000000000..4bfee060a3d --- /dev/null +++ b/solutions/2187. Minimum Time to Complete Trips/2187.py @@ -0,0 +1,13 @@ +class Solution: + def minimumTime(self, time: List[int], totalTrips: int) -> int: + l = 1 + r = min(time) * totalTrips + + while l < r: + m = (l + r) // 2 + if sum(m // t for t in time) >= totalTrips: + r = m + else: + l = m + 1 + + return l diff --git a/solutions/2188. Minimum Time to Finish the Race/2188-2.cpp b/solutions/2188. Minimum Time to Finish the Race/2188-2.cpp new file mode 100644 index 00000000000..841b5c3634b --- /dev/null +++ b/solutions/2188. Minimum Time to Finish the Race/2188-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minimumFinishTime(vector>& tires, int changeTime, + int numLaps) { + // dp[i] := the minimum time of the first i laps + vector dp(numLaps + 1, INT_MAX); + + for (const vector& t : tires) + for (int seconds = t[0], secondsSum = t[0], lapCount = 1; + seconds < t[0] + changeTime && lapCount < dp.size(); + seconds *= t[1], ++lapCount, secondsSum += seconds) + dp[lapCount] = min(secondsSum, dp[lapCount]); + + for (int i = 2; i <= numLaps; ++i) + for (int j = 1; j * 2 <= i; ++j) + dp[i] = min(dp[i], dp[j] + dp[i - j] + changeTime); + + return dp[numLaps]; + } +}; diff --git a/solutions/2188. Minimum Time to Finish the Race/2188.cpp b/solutions/2188. Minimum Time to Finish the Race/2188.cpp new file mode 100644 index 00000000000..240271c9fda --- /dev/null +++ b/solutions/2188. Minimum Time to Finish the Race/2188.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int minimumFinishTime(vector>& tires, int changeTime, + int numLaps) { + // singleTire[i] := the minimum time to finish i laps without changing tire + vector singleTire(numLaps + 1, INT_MAX / 2); + // dp[i] := the minimum time to finish i laps + vector dp(numLaps + 1, INT_MAX / 2); + + for (int i = 0; i < tires.size(); ++i) { + const int f = tires[i][0]; + const int r = tires[i][1]; + int sumSecs = 0; + int rPower = 1; + for (int j = 1; j <= numLaps; ++j) { + // the time to use the same tire for the next lap >= + // the time to change a new tire + f + if ((long)f * rPower >= changeTime + f) + break; + sumSecs += f * rPower; + rPower *= r; + singleTire[j] = min(singleTire[j], sumSecs); + } + } + + dp[0] = 0; + for (int i = 1; i <= numLaps; ++i) + for (int j = 1; j <= i; ++j) + dp[i] = min(dp[i], dp[i - j] + changeTime + singleTire[j]); + + return dp[numLaps] - changeTime; + } +}; diff --git a/solutions/2188. Minimum Time to Finish the Race/2188.java b/solutions/2188. Minimum Time to Finish the Race/2188.java new file mode 100644 index 00000000000..55755448220 --- /dev/null +++ b/solutions/2188. Minimum Time to Finish the Race/2188.java @@ -0,0 +1,34 @@ +class Solution { + public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) { + // singleTire[i] := the minimum time to finish i laps without changing tire + int[] singleTire = new int[numLaps + 1]; + // dp[i] := the minimum time to finish i laps + int[] dp = new int[numLaps + 1]; + + Arrays.fill(singleTire, Integer.MAX_VALUE / 2); + Arrays.fill(dp, Integer.MAX_VALUE / 2); + + for (int i = 0; i < tires.length; ++i) { + final int f = tires[i][0]; + final int r = tires[i][1]; + int sumSecs = 0; + int rPower = 1; + for (int j = 1; j <= numLaps; ++j) { + // the time to use the same tire for the next lap >= + // the time to change a new tire + f + if ((long) f * rPower >= changeTime + f) + break; + sumSecs += f * rPower; + rPower *= r; + singleTire[j] = Math.min(singleTire[j], sumSecs); + } + } + + dp[0] = 0; + for (int i = 1; i <= numLaps; ++i) + for (int j = 1; j <= i; ++j) + dp[i] = Math.min(dp[i], dp[i - j] + changeTime + singleTire[j]); + + return dp[numLaps] - changeTime; + } +} diff --git a/solutions/2188. Minimum Time to Finish the Race/2188.py b/solutions/2188. Minimum Time to Finish the Race/2188.py new file mode 100644 index 00000000000..c7251ed72c1 --- /dev/null +++ b/solutions/2188. Minimum Time to Finish the Race/2188.py @@ -0,0 +1,25 @@ +class Solution: + def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int: + # singleTire[i] := the minimum time to finish i laps without changing tire + singleTire = [math.inf] * (numLaps + 1) + # dp[i] := the minimum time to finish i laps + dp = [math.inf] * (numLaps + 1) + + for i, (f, r) in enumerate(tires): + sumSecs = 0 + rPower = 1 + for j in range(1, numLaps + 1): + # the time to use the same tire for the next lap >= + # the time to change a new tire + f + if f * rPower >= changeTime + f: + break + sumSecs += f * rPower + rPower *= r + singleTire[j] = min(singleTire[j], sumSecs) + + dp[0] = 0 + for i in range(1, numLaps + 1): + for j in range(1, i + 1): + dp[i] = min(dp[i], dp[i - j] + changeTime + singleTire[j]) + + return dp[numLaps] - changeTime diff --git a/solutions/2189. Number of Ways to Build House of Cards/2189.cpp b/solutions/2189. Number of Ways to Build House of Cards/2189.cpp new file mode 100644 index 00000000000..8709fdcab05 --- /dev/null +++ b/solutions/2189. Number of Ways to Build House of Cards/2189.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int houseOfCards(int n) { + // dp[i] := the number of valid result for i cards + vector dp(n + 1); + dp[0] = 1; + + for (int baseCards = 2; baseCards <= n; baseCards += 3) + for (int i = n; i >= baseCards; --i) + // Use `baseCards` as the base, so we're left with `i - baseCards` + // cards. + dp[i] += dp[i - baseCards]; + + return dp[n]; + } +}; diff --git a/solutions/2189. Number of Ways to Build House of Cards/2189.java b/solutions/2189. Number of Ways to Build House of Cards/2189.java new file mode 100644 index 00000000000..af5a268165d --- /dev/null +++ b/solutions/2189. Number of Ways to Build House of Cards/2189.java @@ -0,0 +1,14 @@ +class Solution { + public int houseOfCards(int n) { + // dp[i] := the number of valid result for i cards + int[] dp = new int[n + 1]; + dp[0] = 1; + + for (int baseCards = 2; baseCards <= n; baseCards += 3) + for (int i = n; i >= baseCards; --i) + // Use `baseCards` as the base, so we're left with `i - baseCards` cards. + dp[i] += dp[i - baseCards]; + + return dp[n]; + } +} diff --git a/solutions/2189. Number of Ways to Build House of Cards/2189.py b/solutions/2189. Number of Ways to Build House of Cards/2189.py new file mode 100644 index 00000000000..494dac12c87 --- /dev/null +++ b/solutions/2189. Number of Ways to Build House of Cards/2189.py @@ -0,0 +1,11 @@ +class Solution: + def houseOfCards(self, n: int) -> int: + # dp[i] := the number of valid result for i cards + dp = [1] + [0] * n + + for baseCards in range(2, n + 1, 3): + for i in range(n, baseCards - 1, -1): + # Use `baseCards` as the base, so we're left with `i - baseCards` cards. + dp[i] += dp[i - baseCards] + + return dp[n] diff --git a/solutions/219. Contains Duplicate II/219.cpp b/solutions/219. Contains Duplicate II/219.cpp new file mode 100644 index 00000000000..fc4bda946bf --- /dev/null +++ b/solutions/219. Contains Duplicate II/219.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_set seen; + + for (int i = 0; i < nums.size(); ++i) { + if (!seen.insert(nums[i]).second) + return true; + if (i >= k) + seen.erase(nums[i - k]); + } + + return false; + } +}; diff --git a/solutions/219. Contains Duplicate II/219.java b/solutions/219. Contains Duplicate II/219.java new file mode 100644 index 00000000000..3089a0b10a3 --- /dev/null +++ b/solutions/219. Contains Duplicate II/219.java @@ -0,0 +1,14 @@ +class Solution { + public boolean containsNearbyDuplicate(int[] nums, int k) { + Set seen = new HashSet<>(); + + for (int i = 0; i < nums.length; ++i) { + if (!seen.add(nums[i])) + return true; + if (i >= k) + seen.remove(nums[i - k]); + } + + return false; + } +} diff --git a/solutions/219. Contains Duplicate II/219.py b/solutions/219. Contains Duplicate II/219.py new file mode 100644 index 00000000000..1d01e1640c3 --- /dev/null +++ b/solutions/219. Contains Duplicate II/219.py @@ -0,0 +1,12 @@ +class Solution: + def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: + seen = set() + + for i, num in enumerate(nums): + if i > k: + seen.remove(nums[i - k - 1]) + if num in seen: + return True + seen.add(num) + + return False diff --git a/solutions/2190. Most Frequent Number Following Key In an Array/2190.cpp b/solutions/2190. Most Frequent Number Following Key In an Array/2190.cpp new file mode 100644 index 00000000000..ff8200d9313 --- /dev/null +++ b/solutions/2190. Most Frequent Number Following Key In an Array/2190.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int mostFrequent(vector& nums, int key) { + vector count(1001); + + for (int i = 0; i + 1 < nums.size(); ++i) + if (nums[i] == key) + ++count[nums[i + 1]]; + + return ranges::max_element(count) - count.begin(); + } +}; diff --git a/solutions/2190. Most Frequent Number Following Key In an Array/2190.java b/solutions/2190. Most Frequent Number Following Key In an Array/2190.java new file mode 100644 index 00000000000..14135df2ed8 --- /dev/null +++ b/solutions/2190. Most Frequent Number Following Key In an Array/2190.java @@ -0,0 +1,16 @@ +class Solution { + public int mostFrequent(int[] nums, int key) { + int[] count = new int[1001]; + int ans = 0; + + for (int i = 0; i + 1 < nums.length; ++i) + if (nums[i] == key) + ++count[nums[i + 1]]; + + for (int i = 1; i < 1001; ++i) + if (count[i] > count[ans]) + ans = i; + + return ans; + } +} diff --git a/solutions/2190. Most Frequent Number Following Key In an Array/2190.py b/solutions/2190. Most Frequent Number Following Key In an Array/2190.py new file mode 100644 index 00000000000..2807af78cc4 --- /dev/null +++ b/solutions/2190. Most Frequent Number Following Key In an Array/2190.py @@ -0,0 +1,9 @@ +class Solution: + def mostFrequent(self, nums: List[int], key: int) -> int: + count = collections.Counter() + + for a, b in zip(nums, nums[1:]): + if a == key: + count[b] += 1 + + return max(count, key=lambda k: count[k]) diff --git a/solutions/2191. Sort the Jumbled Numbers/2191-2.cpp b/solutions/2191. Sort the Jumbled Numbers/2191-2.cpp new file mode 100644 index 00000000000..b0712522f48 --- /dev/null +++ b/solutions/2191. Sort the Jumbled Numbers/2191-2.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector sortJumbled(vector& mapping, vector& nums) { + vector ans; + map> mappedToOriginalNums; + + for (const int num : nums) + mappedToOriginalNums[getMapped(num, mapping)].push_back(num); + + for (const auto& [_, originalNums] : mappedToOriginalNums) + ans.insert(ans.end(), originalNums.begin(), originalNums.end()); + + return ans; + } + + private: + int getMapped(int num, const vector& mapping) { + string mapped; + for (const char c : to_string(num)) + mapped += to_string(mapping[c - '0']); + return stoi(mapped); + } +}; diff --git a/solutions/2191. Sort the Jumbled Numbers/2191-2.java b/solutions/2191. Sort the Jumbled Numbers/2191-2.java new file mode 100644 index 00000000000..16ebd66c1b1 --- /dev/null +++ b/solutions/2191. Sort the Jumbled Numbers/2191-2.java @@ -0,0 +1,25 @@ + +class Solution { + public int[] sortJumbled(int[] mapping, int[] nums) { + List ans = new ArrayList<>(); + TreeMap> mappedToOriginalNums = new TreeMap<>(); + + for (final int num : nums) { + final int mapped = getMapped(num, mapping); + mappedToOriginalNums.putIfAbsent(mapped, new ArrayList<>()); + mappedToOriginalNums.get(mapped).add(num); + } + + for (List originalNums : mappedToOriginalNums.values()) + ans.addAll(originalNums); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private int getMapped(int num, int[] mapping) { + StringBuilder sb = new StringBuilder(); + for (final char c : String.valueOf(num).toCharArray()) + sb.append(mapping[c - '0']); + return Integer.parseInt(sb.toString()); + } +} diff --git a/solutions/2191. Sort the Jumbled Numbers/2191.cpp b/solutions/2191. Sort the Jumbled Numbers/2191.cpp new file mode 100644 index 00000000000..c94adab7358 --- /dev/null +++ b/solutions/2191. Sort the Jumbled Numbers/2191.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector sortJumbled(vector& mapping, vector& nums) { + vector ans; + vector> A; // (mapped, index, num) + + for (int i = 0; i < nums.size(); ++i) + A.emplace_back(getMapped(nums[i], mapping), i, nums[i]); + + ranges::sort(A); + + for (const auto& [_, i, num] : A) + ans.push_back(num); + + return ans; + } + + private: + int getMapped(int num, const vector& mapping) { + string mapped; + for (const char c : to_string(num)) + mapped += to_string(mapping[c - '0']); + return stoi(mapped); + } +}; diff --git a/solutions/2191. Sort the Jumbled Numbers/2191.java b/solutions/2191. Sort the Jumbled Numbers/2191.java new file mode 100644 index 00000000000..64fb559fbb0 --- /dev/null +++ b/solutions/2191. Sort the Jumbled Numbers/2191.java @@ -0,0 +1,19 @@ +class Solution { + public int[] sortJumbled(int[] mapping, int[] nums) { + int[] ans = new int[nums.length]; + List A = new ArrayList<>(); // (mapped, index, num) + + for (int i = 0; i < nums.length; ++i) + A.add(new int[] {getMapped(nums[i], mapping), i, nums[i]}); + + Collections.sort(A, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + return A.stream().mapToInt(a -> a[2]).toArray(); + } + + private int getMapped(int num, int[] mapping) { + StringBuilder sb = new StringBuilder(); + for (final char c : String.valueOf(num).toCharArray()) + sb.append(mapping[c - '0']); + return Integer.parseInt(sb.toString()); + } +} diff --git a/solutions/2191. Sort the Jumbled Numbers/2191.py b/solutions/2191. Sort the Jumbled Numbers/2191.py new file mode 100644 index 00000000000..d47e7727e59 --- /dev/null +++ b/solutions/2191. Sort the Jumbled Numbers/2191.py @@ -0,0 +1,9 @@ +class Solution: + def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: + def getMapped(num: int) -> int: + mapped = [] + for c in str(num): + mapped.append(str(mapping[ord(c) - ord('0')])) + return int(''.join(mapped)) + A = [(getMapped(num), i, num) for i, num in enumerate(nums)] + return [num for _, i, num in sorted(A)] diff --git a/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.cpp b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.cpp new file mode 100644 index 00000000000..36cf6e07461 --- /dev/null +++ b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + vector> getAncestors(int n, vector>& edges) { + vector> ans; + vector> graph(n); + vector> ancestors(n); // {u: {ancestors}} + vector inDegrees(n); + queue q; + + // Build the graph. + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) { + ancestors[v].insert(u); + std::copy(ancestors[u].begin(), ancestors[u].end(), + std::inserter(ancestors[v], ancestors[v].end())); + if (--inDegrees[v] == 0) + q.push(v); + } + } + } + + for (const set& nodes : ancestors) + ans.push_back({nodes.begin(), nodes.end()}); + + return ans; + } +}; diff --git a/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.java b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.java new file mode 100644 index 00000000000..6daea16a43e --- /dev/null +++ b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.java @@ -0,0 +1,44 @@ +class Solution { + public List> getAncestors(int n, int[][] edges) { + List> ans = new ArrayList<>(); + List[] graph = new List[n]; + TreeSet[] ancestors = new TreeSet[n]; // {u: {ancestors}} + int[] inDegrees = new int[n]; + + for (int i = 0; i < n; ++i) { + graph[i] = new ArrayList<>(); + ancestors[i] = new TreeSet<>(); + } + + // Build the graph. + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + Queue q = IntStream.range(0, n) + .filter(i -> inDegrees[i] == 0) + .boxed() + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.poll(); + for (final int v : graph[u]) { + ancestors[v].add(u); + ancestors[v].addAll(ancestors[u]); + if (--inDegrees[v] == 0) + q.offer(v); + } + } + } + + for (TreeSet nodes : ancestors) + ans.add(new ArrayList<>(nodes)); + + return ans; + } +} diff --git a/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.py b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.py new file mode 100644 index 00000000000..62db54928a1 --- /dev/null +++ b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192-2.py @@ -0,0 +1,25 @@ +class Solution: + def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: + ans = [set() for _ in range(n)] + graph = [[] for _ in range(n)] + inDegrees = [0] * n + + # Build the graph. + for u, v in edges: + graph[u].append(v) + inDegrees[v] += 1 + + # Perform topological sorting. + q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) + + while q: + for _ in range(len(q)): + u = q.popleft() + for v in graph[u]: + ans[v].add(u) + ans[v].update(ans[u]) + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + + return [sorted(nodes) for nodes in ans] diff --git a/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.cpp b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.cpp new file mode 100644 index 00000000000..db46a73b0ba --- /dev/null +++ b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector> getAncestors(int n, vector>& edges) { + vector> ans(n); + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + } + + for (int i = 0; i < n; ++i) + dfs(graph, i, i, vector(n), ans); + + return ans; + } + + private: + void dfs(const vector>& graph, int u, int ancestor, + vector&& seen, vector>& ans) { + seen[u] = true; + for (const int v : graph[u]) { + if (seen[v]) + continue; + ans[v].push_back(ancestor); + dfs(graph, v, ancestor, move(seen), ans); + } + } +}; diff --git a/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.java b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.java new file mode 100644 index 00000000000..c5e6eaf2136 --- /dev/null +++ b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.java @@ -0,0 +1,33 @@ +class Solution { + public List> getAncestors(int n, int[][] edges) { + List> ans = new ArrayList<>(); + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) { + ans.add(new ArrayList<>()); + graph[i] = new ArrayList<>(); + } + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + } + + for (int i = 0; i < n; ++i) + dfs(graph, i, i, new boolean[n], ans); + + return ans; + } + + private void dfs(List[] graph, int u, int ancestor, boolean[] seen, + List> ans) { + seen[u] = true; + for (final int v : graph[u]) { + if (seen[v]) + continue; + ans.get(v).add(ancestor); + dfs(graph, v, ancestor, seen, ans); + } + } +} diff --git a/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.py b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.py new file mode 100644 index 00000000000..499cfe2b32b --- /dev/null +++ b/solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.py @@ -0,0 +1,20 @@ +class Solution: + def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: + ans = [[] for _ in range(n)] + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append(v) + + def dfs(u: int, ancestor: int, seen: Set[int]) -> None: + seen.add(u) + for v in graph[u]: + if v in seen: + continue + ans[v].append(ancestor) + dfs(v, ancestor, seen) + + for i in range(n): + dfs(i, i, set()) + + return ans diff --git a/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.cpp b/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.cpp new file mode 100644 index 00000000000..6a61a972d4a --- /dev/null +++ b/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minMovesToMakePalindrome(string s) { + int ans = 0; + + while (s.length() > 1) { + // Greedily match the last digit. + const int i = s.find(s.back()); + if (i == s.length() - 1) { + // s[i] is the middle letter. + ans += i / 2; + } else { + s.erase(i, 1); + ans += i; // Swap the matched letter to the left. + } + s.pop_back(); + } + + return ans; + } +}; diff --git a/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.java b/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.java new file mode 100644 index 00000000000..0b331ddddfd --- /dev/null +++ b/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.java @@ -0,0 +1,21 @@ +class Solution { + public int minMovesToMakePalindrome(String s) { + int ans = 0; + StringBuilder sb = new StringBuilder(s); + + while (sb.length() > 1) { + // Greedily match the last digit. + final int i = sb.indexOf(sb.substring(sb.length() - 1)); + if (i == sb.length() - 1) { + // s[i] is the middle letter. + ans += i / 2; + } else { + sb.deleteCharAt(i); + ans += i; // Swap the matched letter to the left. + } + sb.deleteCharAt(sb.length() - 1); + } + + return ans; + } +} diff --git a/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.py b/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.py new file mode 100644 index 00000000000..b7a1771b5e8 --- /dev/null +++ b/solutions/2193. Minimum Number of Moves to Make Palindrome/2193.py @@ -0,0 +1,17 @@ +class Solution: + def minMovesToMakePalindrome(self, s: str) -> int: + ans = 0 + chars = list(s) + + while len(chars) > 1: + # Greedily match the last digit. + i = chars.index(chars[-1]) + if i == len(chars) - 1: + # s[i] is the middle letter. + ans += i // 2 + else: + chars.pop(i) + ans += i # Swap the matched letter to the left. + chars.pop() + + return ans diff --git a/solutions/2194. Cells in a Range on an Excel Sheet/2194.cpp b/solutions/2194. Cells in a Range on an Excel Sheet/2194.cpp new file mode 100644 index 00000000000..7aa717a23fd --- /dev/null +++ b/solutions/2194. Cells in a Range on an Excel Sheet/2194.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector cellsInRange(string s) { + vector ans; + const char startCol = s[0]; + const char endCol = s[3]; + const char startRow = s[1]; + const char endRow = s[4]; + + for (char col = startCol; col <= endCol; ++col) + for (char row = startRow; row <= endRow; ++row) + ans.push_back(string(1, col) + row); + + return ans; + } +}; diff --git a/solutions/2194. Cells in a Range on an Excel Sheet/2194.java b/solutions/2194. Cells in a Range on an Excel Sheet/2194.java new file mode 100644 index 00000000000..9059c855258 --- /dev/null +++ b/solutions/2194. Cells in a Range on an Excel Sheet/2194.java @@ -0,0 +1,15 @@ +class Solution { + public List cellsInRange(String s) { + List ans = new ArrayList<>(); + final char startCol = s.charAt(0); + final char endCol = s.charAt(3); + final char startRow = s.charAt(1); + final char endRow = s.charAt(4); + + for (char col = startCol; col <= endCol; ++col) + for (char row = startRow; row <= endRow; ++row) + ans.add("" + col + row); + + return ans; + } +} diff --git a/solutions/2194. Cells in a Range on an Excel Sheet/2194.py b/solutions/2194. Cells in a Range on an Excel Sheet/2194.py new file mode 100644 index 00000000000..58adc917507 --- /dev/null +++ b/solutions/2194. Cells in a Range on an Excel Sheet/2194.py @@ -0,0 +1,10 @@ +class Solution: + def cellsInRange(self, s: str) -> List[str]: + ans = [] + startCol, startRow, _, endCol, endRow = s + + for j in range(ord(startCol), ord(endCol) + 1): + for i in range(int(startRow), int(endRow) + 1): + ans.append(chr(j) + str(i)) + + return ans diff --git a/solutions/2195. Append K Integers With Minimal Sum/2195.cpp b/solutions/2195. Append K Integers With Minimal Sum/2195.cpp new file mode 100644 index 00000000000..55b1aeed23f --- /dev/null +++ b/solutions/2195. Append K Integers With Minimal Sum/2195.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + long long minimalKSum(vector& nums, int k) { + long ans = 0; + nums.push_back(0); + ranges::sort(nums); + + for (int i = 0; i + 1 < nums.size(); ++i) { + if (nums[i] == nums[i + 1]) + continue; + const int l = nums[i] + 1; + const int r = min(nums[i] + k, nums[i + 1] - 1); + ans += static_cast(l + r) * (r - l + 1) / 2; + k -= r - l + 1; + if (k == 0) + return ans; + } + + if (k > 0) { + const int l = nums.back() + 1; + const int r = nums.back() + k; + ans += static_cast(l + r) * (r - l + 1) / 2; + } + + return ans; + } +}; diff --git a/solutions/2195. Append K Integers With Minimal Sum/2195.java b/solutions/2195. Append K Integers With Minimal Sum/2195.java new file mode 100644 index 00000000000..dd1bc558c63 --- /dev/null +++ b/solutions/2195. Append K Integers With Minimal Sum/2195.java @@ -0,0 +1,34 @@ +class Solution { + public long minimalKSum(int[] nums, int k) { + long ans = 0; + Arrays.sort(nums); + + if (nums[0] > 1) { + final int l = 1; + final int r = Math.min(k, nums[0] - 1); + ans += (long) (l + r) * (r - l + 1) / 2; + k -= r - l + 1; + if (k == 0) + return ans; + } + + for (int i = 0; i + 1 < nums.length; ++i) { + if (nums[i] == nums[i + 1]) + continue; + final int l = nums[i] + 1; + final int r = Math.min(nums[i] + k, nums[i + 1] - 1); + ans += (long) (l + r) * (r - l + 1) / 2; + k -= r - l + 1; + if (k == 0) + return ans; + } + + if (k > 0) { + final int l = nums[nums.length - 1] + 1; + final int r = nums[nums.length - 1] + k; + ans += (long) (l + r) * (r - l + 1) / 2; + } + + return ans; + } +} diff --git a/solutions/2195. Append K Integers With Minimal Sum/2195.py b/solutions/2195. Append K Integers With Minimal Sum/2195.py new file mode 100644 index 00000000000..5567d5f0c77 --- /dev/null +++ b/solutions/2195. Append K Integers With Minimal Sum/2195.py @@ -0,0 +1,22 @@ +class Solution: + def minimalKSum(self, nums: List[int], k: int) -> int: + ans = 0 + nums.append(0) + nums.sort() + + for a, b in zip(nums, nums[1:]): + if a == b: + continue + l = a + 1 + r = min(a + k, b - 1) + ans += (l + r) * (r - l + 1) // 2 + k -= r - l + 1 + if k == 0: + return ans + + if k > 0: + l = nums[-1] + 1 + r = nums[-1] + k + ans += (l + r) * (r - l + 1) // 2 + + return ans diff --git a/solutions/2196. Create Binary Tree From Descriptions/2196.cpp b/solutions/2196. Create Binary Tree From Descriptions/2196.cpp new file mode 100644 index 00000000000..ff97c25cd17 --- /dev/null +++ b/solutions/2196. Create Binary Tree From Descriptions/2196.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + TreeNode* createBinaryTree(vector>& descriptions) { + unordered_map childToParent; + unordered_map valToNode; + + for (const vector& d : descriptions) { + const int p = d[0]; + const int c = d[1]; + const bool isLeft = d[2]; + TreeNode* parent = valToNode.contains(p) + ? valToNode[p] + : (valToNode[p] = new TreeNode(p)); + TreeNode* child = valToNode.contains(c) + ? valToNode[c] + : (valToNode[c] = new TreeNode(c)); + childToParent[child] = parent; + if (isLeft) + parent->left = child; + else + parent->right = child; + } + + // Pick a random node and traverse upwardly. + TreeNode* root = childToParent.begin()->second; + while (childToParent.contains(root)) + root = childToParent[root]; + return root; + } +}; diff --git a/solutions/2196. Create Binary Tree From Descriptions/2196.java b/solutions/2196. Create Binary Tree From Descriptions/2196.java new file mode 100644 index 00000000000..511c15b1bd2 --- /dev/null +++ b/solutions/2196. Create Binary Tree From Descriptions/2196.java @@ -0,0 +1,27 @@ +class Solution { + public TreeNode createBinaryTree(int[][] descriptions) { + Map childToParent = new HashMap<>(); + Map valToNode = new HashMap<>(); + + for (int[] d : descriptions) { + final int p = d[0]; + final int c = d[1]; + final int isLeft = d[2]; + TreeNode parent = valToNode.getOrDefault(p, new TreeNode(p)); + TreeNode child = valToNode.getOrDefault(c, new TreeNode(c)); + valToNode.put(p, parent); + valToNode.put(c, child); + childToParent.put(child, parent); + if (isLeft == 1) + parent.left = child; + else + parent.right = child; + } + + // Pick a random node and traverse upwardly. + TreeNode root = childToParent.keySet().iterator().next(); + while (childToParent.containsKey(root)) + root = childToParent.get(root); + return root; + } +} diff --git a/solutions/2196. Create Binary Tree From Descriptions/2196.py b/solutions/2196. Create Binary Tree From Descriptions/2196.py new file mode 100644 index 00000000000..007f4d78cae --- /dev/null +++ b/solutions/2196. Create Binary Tree From Descriptions/2196.py @@ -0,0 +1,16 @@ +class Solution: + def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: + children = set() + valToNode = {} + + for p, c, isLeft in descriptions: + parent = valToNode.setdefault(p, TreeNode(p)) + child = valToNode.setdefault(c, TreeNode(c)) + if isLeft: + parent.left = child + else: + parent.right = child + children.add(c) + + root = (set(valToNode) - set(children)).pop() + return valToNode[root] diff --git a/solutions/2197. Replace Non-Coprime Numbers in Array/2197.cpp b/solutions/2197. Replace Non-Coprime Numbers in Array/2197.cpp new file mode 100644 index 00000000000..74e21c9b590 --- /dev/null +++ b/solutions/2197. Replace Non-Coprime Numbers in Array/2197.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector replaceNonCoprimes(vector& nums) { + vector ans; + + for (int num : nums) { + while (!ans.empty() && std::gcd(ans.back(), num) > 1) + num = std::lcm(ans.back(), num), ans.pop_back(); + ans.push_back(num); + } + + return ans; + } +}; diff --git a/solutions/2197. Replace Non-Coprime Numbers in Array/2197.java b/solutions/2197. Replace Non-Coprime Numbers in Array/2197.java new file mode 100644 index 00000000000..034580d8995 --- /dev/null +++ b/solutions/2197. Replace Non-Coprime Numbers in Array/2197.java @@ -0,0 +1,21 @@ +class Solution { + public List replaceNonCoprimes(int[] nums) { + LinkedList ans = new LinkedList<>(); + + for (int num : nums) { + while (!ans.isEmpty() && gcd(ans.getLast(), num) > 1) + num = lcm(ans.removeLast(), num); + ans.addLast(num); + } + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private int lcm(int a, int b) { + return a * (b / gcd(a, b)); + } +} diff --git a/solutions/2197. Replace Non-Coprime Numbers in Array/2197.py b/solutions/2197. Replace Non-Coprime Numbers in Array/2197.py new file mode 100644 index 00000000000..729bf261132 --- /dev/null +++ b/solutions/2197. Replace Non-Coprime Numbers in Array/2197.py @@ -0,0 +1,10 @@ +class Solution: + def replaceNonCoprimes(self, nums: List[int]) -> List[int]: + ans = [] + + for num in nums: + while ans and math.gcd(ans[-1], num) > 1: + num = math.lcm(ans.pop(), num) + ans.append(num) + + return ans diff --git a/solutions/2198. Number of Single Divisor Triplets/2198.cpp b/solutions/2198. Number of Single Divisor Triplets/2198.cpp new file mode 100644 index 00000000000..47e4716d19d --- /dev/null +++ b/solutions/2198. Number of Single Divisor Triplets/2198.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + long long singleDivisorTriplet(vector& nums) { + constexpr int kMax = 100; + long ans = 0; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int a = 1; a <= kMax; ++a) + for (int b = a; count[a] > 0 && b <= kMax; ++b) + for (int c = b; count[b] > 0 && c <= kMax; ++c) { + const int sum = a + b + c; + if (divisible(sum, a) + divisible(sum, b) + divisible(sum, c) != 1) + continue; + if (a == b) + ans += static_cast(count[a]) * (count[a] - 1) / 2 * count[c]; + else if (b == c) + ans += static_cast(count[b]) * (count[b] - 1) / 2 * count[a]; + else + ans += static_cast(count[a]) * count[b] * count[c]; + } + + return ans * 6; + } + + private: + int divisible(int sum, int num) { + return sum % num == 0; + } +}; diff --git a/solutions/2198. Number of Single Divisor Triplets/2198.java b/solutions/2198. Number of Single Divisor Triplets/2198.java new file mode 100644 index 00000000000..7bfe9ce2ba0 --- /dev/null +++ b/solutions/2198. Number of Single Divisor Triplets/2198.java @@ -0,0 +1,30 @@ +class Solution { + public long singleDivisorTriplet(int[] nums) { + final int kMax = 100; + long ans = 0; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int a = 1; a <= kMax; ++a) + for (int b = a; count[a] > 0 && b <= kMax; ++b) + for (int c = b; count[b] > 0 && c <= kMax; ++c) { + final int sum = a + b + c; + if (divisible(sum, a) + divisible(sum, b) + divisible(sum, c) != 1) + continue; + if (a == b) + ans += (long) count[a] * (count[a] - 1) / 2 * count[c]; + else if (b == c) + ans += (long) count[b] * (count[b] - 1) / 2 * count[a]; + else + ans += (long) count[a] * count[b] * count[c]; + } + + return ans * 6; + } + + private int divisible(int sum, int num) { + return sum % num == 0 ? 1 : 0; + } +} diff --git a/solutions/2198. Number of Single Divisor Triplets/2198.py b/solutions/2198. Number of Single Divisor Triplets/2198.py new file mode 100644 index 00000000000..7c398d949c8 --- /dev/null +++ b/solutions/2198. Number of Single Divisor Triplets/2198.py @@ -0,0 +1,28 @@ +class Solution: + def singleDivisorTriplet(self, nums: List[int]) -> int: + ans = 0 + count = collections.Counter(nums) + + def divisible(summ: int, num: int) -> int: + return summ % num == 0 + + for a in range(1, 101): + if count[a] == 0: + continue + for b in range(a, 101): + if count[b] == 0: + continue + for c in range(b, 101): + if count[c] == 0: + continue + summ = a + b + c + if divisible(summ, a) + divisible(summ, b) + divisible(summ, c) != 1: + continue + if a == b: + ans += count[a] * (count[a] - 1) // 2 * count[c] + elif b == c: + ans += count[b] * (count[b] - 1) // 2 * count[a] + else: + ans += count[a] * count[b] * count[c] + + return ans * 6 diff --git a/solutions/2199. Finding the Topic of Each Post/2199.sql b/solutions/2199. Finding the Topic of Each Post/2199.sql new file mode 100644 index 00000000000..23daacfe8f1 --- /dev/null +++ b/solutions/2199. Finding the Topic of Each Post/2199.sql @@ -0,0 +1,13 @@ +SELECT + Posts.post_id, + IFNULL( + GROUP_CONCAT( + DISTINCT Keywords.topic_id + ORDER BY Keywords.topic_id + ), + 'Ambiguous!' + ) AS topic +FROM Posts +LEFT JOIN Keywords + ON (CONCAT(' ', LOWER(Posts.content), ' ') LIKE CONCAT('% ', LOWER(Keywords.word), ' %')) +GROUP BY 1; diff --git a/solutions/22. Generate Parentheses/22.cpp b/solutions/22. Generate Parentheses/22.cpp new file mode 100644 index 00000000000..9d5fae5fe07 --- /dev/null +++ b/solutions/22. Generate Parentheses/22.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector generateParenthesis(int n) { + vector ans; + dfs(n, n, "", ans); + return ans; + } + + private: + void dfs(int l, int r, string&& path, vector& ans) { + if (l == 0 && r == 0) { + ans.push_back(path); + return; + } + + if (l > 0) { + path.push_back('('); + dfs(l - 1, r, move(path), ans); + path.pop_back(); + } + if (l < r) { + path.push_back(')'); + dfs(l, r - 1, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/22. Generate Parentheses/22.java b/solutions/22. Generate Parentheses/22.java new file mode 100644 index 00000000000..a5887996b56 --- /dev/null +++ b/solutions/22. Generate Parentheses/22.java @@ -0,0 +1,25 @@ +class Solution { + public List generateParenthesis(int n) { + List ans = new ArrayList<>(); + dfs(n, n, new StringBuilder(), ans); + return ans; + } + + private void dfs(int l, int r, StringBuilder sb, List ans) { + if (l == 0 && r == 0) { + ans.add(sb.toString()); + return; + } + + if (l > 0) { + sb.append("("); + dfs(l - 1, r, sb, ans); + sb.deleteCharAt(sb.length() - 1); + } + if (l < r) { + sb.append(")"); + dfs(l, r - 1, sb, ans); + sb.deleteCharAt(sb.length() - 1); + } + } +} diff --git a/solutions/22. Generate Parentheses/22.py b/solutions/22. Generate Parentheses/22.py new file mode 100644 index 00000000000..4ae6e8ff488 --- /dev/null +++ b/solutions/22. Generate Parentheses/22.py @@ -0,0 +1,18 @@ +class Solution: + def generateParenthesis(self, n): + ans = [] + + def dfs(l: int, r: int, s: List[str]) -> None: + if l == 0 and r == 0: + ans.append(''.join(s)) + if l > 0: + s.append('(') + dfs(l - 1, r, s) + s.pop() + if l < r: + s.append(')') + dfs(l, r - 1, s) + s.pop() + + dfs(n, n, []) + return ans diff --git a/solutions/220. Contains Duplicate III/220-2.cpp b/solutions/220. Contains Duplicate III/220-2.cpp new file mode 100644 index 00000000000..aecdf2830d9 --- /dev/null +++ b/solutions/220. Contains Duplicate III/220-2.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + bool containsNearbyAlmostDuplicate(vector& nums, int indexDiff, + int valueDiff) { + if (nums.empty() || indexDiff <= 0 || valueDiff < 0) + return false; + + const long mn = ranges::min(nums); + const long diff = valueDiff + 1L; // In case that `valueDiff` equals 0. + // Use long because the corner case INT_MAX - (-1) will overflow. + unordered_map bucket; + + for (int i = 0; i < nums.size(); ++i) { + const long num = nums[i]; + const long key = getKey(num, mn, diff); + if (bucket.contains(key)) // the current bucket + return true; + if (bucket.contains(key - 1) && + num - bucket[key - 1] < diff) // the left adjacent bucket + return true; + if (bucket.contains(key + 1) && + bucket[key + 1] - num < diff) // the right adjacent bucket + return true; + bucket[key] = num; + if (i >= indexDiff) + bucket.erase(getKey(nums[i - indexDiff], mn, diff)); + } + + return false; + } + + private: + int getKey(long num, long mn, long diff) { + return (num - mn) / diff; + } +}; diff --git a/solutions/220. Contains Duplicate III/220-2.java b/solutions/220. Contains Duplicate III/220-2.java new file mode 100644 index 00000000000..5a9b0c83a8e --- /dev/null +++ b/solutions/220. Contains Duplicate III/220-2.java @@ -0,0 +1,33 @@ +class Solution { + public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) { + if (nums.length == 0 || indexDiff <= 0 || valueDiff < 0) + return false; + + final long mn = Arrays.stream(nums).min().getAsInt(); + final long diff = (long) valueDiff + 1; // In case that `valueDiff` equals 0. + // Use Long because of corner case Integer.MAX_VALUE - (-1) will overflow + HashMap bucket = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + final long num = (long) nums[i]; + final long key = getKey(nums[i], mn, diff); + if (bucket.containsKey(key)) // the current bucket + return true; + if (bucket.containsKey(key - 1) && + num - bucket.get(key - 1) < diff) // the left adjacent bucket + return true; + if (bucket.containsKey(key + 1) && + bucket.get(key + 1) - num < diff) // the right adjacent bucket + return true; + bucket.put(key, num); + if (i >= indexDiff) + bucket.remove(getKey(nums[i - indexDiff], mn, diff)); + } + + return false; + } + + private long getKey(int num, long mn, long diff) { + return ((long) num - mn) / diff; + } +} diff --git a/solutions/220. Contains Duplicate III/220-2.py b/solutions/220. Contains Duplicate III/220-2.py new file mode 100644 index 00000000000..2e1f8fa4598 --- /dev/null +++ b/solutions/220. Contains Duplicate III/220-2.py @@ -0,0 +1,27 @@ +class Solution: + def containsNearbyAlmostDuplicate(self, nums: List[int], indexDiff: int, valueDiff: int) -> bool: + if not nums or indexDiff <= 0 or valueDiff < 0: + return False + + mn = min(nums) + diff = valueDiff + 1 # In case that `valueDiff` equals 0. + bucket = {} + + def getKey(num: int) -> int: + return (num - mn) // diff + + for i, num in enumerate(nums): + key = getKey(num) + if key in bucket: # the current bucket + return True + # the left adjacent bucket + if key - 1 in bucket and num - bucket[key - 1] < diff: + return True + # the right adjacent bucket + if key + 1 in bucket and bucket[key + 1] - num < diff: + return True + bucket[key] = num + if i >= indexDiff: + del bucket[getKey(nums[i - indexDiff])] + + return False diff --git a/solutions/220. Contains Duplicate III/220.cpp b/solutions/220. Contains Duplicate III/220.cpp new file mode 100644 index 00000000000..e5b3eb68a4f --- /dev/null +++ b/solutions/220. Contains Duplicate III/220.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool containsNearbyAlmostDuplicate(vector& nums, int indexDiff, + int valueDiff) { + set window; + + for (int i = 0; i < nums.size(); ++i) { + if (const auto it = + window.lower_bound(static_cast(nums[i]) - valueDiff); + it != window.cend() && *it - nums[i] <= valueDiff) + return true; + window.insert(nums[i]); + if (i >= indexDiff) + window.erase(nums[i - indexDiff]); + } + + return false; + } +}; diff --git a/solutions/220. Contains Duplicate III/220.java b/solutions/220. Contains Duplicate III/220.java new file mode 100644 index 00000000000..48847af7021 --- /dev/null +++ b/solutions/220. Contains Duplicate III/220.java @@ -0,0 +1,20 @@ +class Solution { + public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) { + TreeSet set = new TreeSet<>(); + + for (int i = 0; i < nums.length; ++i) { + final long num = (long) nums[i]; + final Long ceiling = set.ceiling(num); // The smallest num >= nums[i] + if (ceiling != null && ceiling - num <= valueDiff) + return true; + final Long floor = set.floor(num); // The largest num <= nums[i] + if (floor != null && num - floor <= valueDiff) + return true; + set.add(num); + if (i >= indexDiff) + set.remove((long) nums[i - indexDiff]); + } + + return false; + } +} diff --git a/solutions/2200. Find All K-Distant Indices in an Array/2200.cpp b/solutions/2200. Find All K-Distant Indices in an Array/2200.cpp new file mode 100644 index 00000000000..2699b15857d --- /dev/null +++ b/solutions/2200. Find All K-Distant Indices in an Array/2200.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector findKDistantIndices(vector& nums, int key, int k) { + const int n = nums.size(); + vector ans; + + for (int i = 0, j = 0; i < n; ++i) { + // the first index j s.t. nums[j] == key and j >= i - k + while (j < n && (nums[j] != key || j < i - k)) + ++j; + if (j == n) + break; + if (abs(i - j) <= k) + ans.push_back(i); + } + + return ans; + } +}; diff --git a/solutions/2200. Find All K-Distant Indices in an Array/2200.java b/solutions/2200. Find All K-Distant Indices in an Array/2200.java new file mode 100644 index 00000000000..856178d7376 --- /dev/null +++ b/solutions/2200. Find All K-Distant Indices in an Array/2200.java @@ -0,0 +1,18 @@ +class Solution { + public List findKDistantIndices(int[] nums, int key, int k) { + final int n = nums.length; + List ans = new ArrayList<>(); + + for (int i = 0, j = 0; i < n; ++i) { + // the first index j s.t. nums[j] == key and j >= i - k + while (j < n && (nums[j] != key || j < i - k)) + ++j; + if (j == n) + break; + if (Math.abs(i - j) <= k) + ans.add(i); + } + + return ans; + } +} diff --git a/solutions/2200. Find All K-Distant Indices in an Array/2200.py b/solutions/2200. Find All K-Distant Indices in an Array/2200.py new file mode 100644 index 00000000000..41e98c03e5a --- /dev/null +++ b/solutions/2200. Find All K-Distant Indices in an Array/2200.py @@ -0,0 +1,16 @@ +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + n = len(nums) + ans = [] + + j = 0 + for i in range(n): + # the first index j s.t. nums[j] == key and j >= i - k + while j < n and (nums[j] != key or j < i - k): + j += 1 + if j == n: + break + if abs(i - j) <= k: + ans.append(i) + + return ans diff --git a/solutions/2201. Count Artifacts That Can Be Extracted/2201.cpp b/solutions/2201. Count Artifacts That Can Be Extracted/2201.cpp new file mode 100644 index 00000000000..c9bb0eda692 --- /dev/null +++ b/solutions/2201. Count Artifacts That Can Be Extracted/2201.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int digArtifacts(int n, vector>& artifacts, + vector>& dig) { + unordered_set digged; + + for (const vector& d : dig) + digged.insert(hash(d[0], d[1])); + + return ranges::count_if( + artifacts, [&](const auto& a) { return canExtract(a, digged); }); + } + + private: + int hash(int i, int j) { + return i << 16 | j; + } + + bool canExtract(const vector& a, const unordered_set& digged) { + for (int i = a[0]; i <= a[2]; ++i) + for (int j = a[1]; j <= a[3]; ++j) + if (!digged.contains(hash(i, j))) + return false; + return true; + } +}; diff --git a/solutions/2201. Count Artifacts That Can Be Extracted/2201.java b/solutions/2201. Count Artifacts That Can Be Extracted/2201.java new file mode 100644 index 00000000000..7677bb7dfb5 --- /dev/null +++ b/solutions/2201. Count Artifacts That Can Be Extracted/2201.java @@ -0,0 +1,22 @@ +class Solution { + public int digArtifacts(int n, int[][] artifacts, int[][] dig) { + Set digged = new HashSet<>(); + + for (int[] d : dig) + digged.add(hash(d[0], d[1])); + + return (int) Arrays.stream(artifacts).filter(a -> canExtract(a, digged)).count(); + } + + private int hash(int i, int j) { + return i << 16 | j; + } + + private boolean canExtract(int[] a, Set digged) { + for (int i = a[0]; i <= a[2]; ++i) + for (int j = a[1]; j <= a[3]; ++j) + if (!digged.contains(hash(i, j))) + return false; + return true; + } +} diff --git a/solutions/2201. Count Artifacts That Can Be Extracted/2201.py b/solutions/2201. Count Artifacts That Can Be Extracted/2201.py new file mode 100644 index 00000000000..18f4b776241 --- /dev/null +++ b/solutions/2201. Count Artifacts That Can Be Extracted/2201.py @@ -0,0 +1,12 @@ +class Solution: + def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: + digged = set((r, c) for r, c in dig) + + def canExtract(a: List[int]) -> bool: + for i in range(a[0], a[2] + 1): + for j in range(a[1], a[3] + 1): + if (i, j) not in digged: + return False + return True + + return sum(canExtract(a) for a in artifacts) diff --git a/solutions/2202. Maximize the Topmost Element After K Moves/2202.cpp b/solutions/2202. Maximize the Topmost Element After K Moves/2202.cpp new file mode 100644 index 00000000000..3f6e583f95f --- /dev/null +++ b/solutions/2202. Maximize the Topmost Element After K Moves/2202.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maximumTop(vector& nums, int k) { + const int n = nums.size(); + // After taking k elements, if there's something left, then return nums[k]. + // Otherwise, return -1. + if (k == 0 || k == 1) + return n == k ? -1 : nums[k]; + // Remove then add even number of times. + if (n == 1) + return k % 2 == 0 ? nums[0] : -1; + // Take min(n, k - 1) elements and put the largest one back. + const int mx = *max_element(nums.begin(), nums.begin() + min(n, k - 1)); + if (k >= n) + return mx; + return max(mx, nums[k]); + } +}; diff --git a/solutions/2202. Maximize the Topmost Element After K Moves/2202.java b/solutions/2202. Maximize the Topmost Element After K Moves/2202.java new file mode 100644 index 00000000000..57192bce426 --- /dev/null +++ b/solutions/2202. Maximize the Topmost Element After K Moves/2202.java @@ -0,0 +1,24 @@ +class Solution { + public int maximumTop(int[] nums, int k) { + final int n = nums.length; + // After taking k elements, if there's something left, then return nums[k]. + // Otherwise, return -1> + if (k == 0 || k == 1) + return n == k ? -1 : nums[k]; + // Remove then add even number of times. + if (n == 1) + return k % 2 == 0 ? nums[0] : -1; + // Take min(n, k - 1) elements and put the largest one back. + final int mx = firstKMax(nums, k - 1); + if (k >= n) + return mx; + return Math.max(mx, nums[k]); + } + + private int firstKMax(int[] nums, int k) { + int mx = 0; + for (int i = 0; i < nums.length && i < k; ++i) + mx = Math.max(mx, nums[i]); + return mx; + } +} diff --git a/solutions/2202. Maximize the Topmost Element After K Moves/2202.py b/solutions/2202. Maximize the Topmost Element After K Moves/2202.py new file mode 100644 index 00000000000..e5bed15a7d2 --- /dev/null +++ b/solutions/2202. Maximize the Topmost Element After K Moves/2202.py @@ -0,0 +1,15 @@ +class Solution: + def maximumTop(self, nums: List[int], k: int) -> int: + n = len(nums) + # After taking k elements, if we're left something, then we return nums[k] + # Otherwise, return -1. + if k == 0 or k == 1: + return -1 if n == k else nums[k] + # Remove then add even number of times. + if n == 1: + return -1 if k & 1 else nums[0] + # Take min(n, k - 1) elements and put the largest one back. + mx = max(nums[:min(n, k - 1)]) + if k >= n: + return mx + return max(mx, nums[k]) diff --git a/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.cpp b/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.cpp new file mode 100644 index 00000000000..c8603c06076 --- /dev/null +++ b/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.cpp @@ -0,0 +1,55 @@ +class Solution { + public: + long long minimumWeight(int n, vector>& edges, int src1, int src2, + int dest) { + vector>> graph(n); + vector>> reversedGraph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + reversedGraph[v].emplace_back(u, w); + } + + const vector fromSrc1 = dijkstra(graph, src1); + const vector fromSrc2 = dijkstra(graph, src2); + const vector fromDest = dijkstra(reversedGraph, dest); + long ans = kMax; + + for (int i = 0; i < n; ++i) { + if (fromSrc1[i] == kMax || fromSrc2[i] == kMax || fromDest[i] == kMax) + continue; + ans = min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]); + } + + return ans == kMax ? -1 : ans; + } + + private: + static constexpr long kMax = 10'000'000'000; + + vector dijkstra(const vector>>& graph, int src) { + vector dist(graph.size(), kMax); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + } + + return dist; + } +}; diff --git a/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.java b/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.java new file mode 100644 index 00000000000..e727a9fe3ec --- /dev/null +++ b/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.java @@ -0,0 +1,61 @@ +class Solution { + public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) { + List>[] graph = new List[n]; + List>[] reversedGraph = new List[n]; + + for (int i = 0; i < n; ++i) { + graph[i] = new ArrayList<>(); + reversedGraph[i] = new ArrayList<>(); + } + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + reversedGraph[v].add(new Pair<>(u, w)); + } + + long[] fromSrc1 = dijkstra(graph, src1); + long[] fromSrc2 = dijkstra(graph, src2); + long[] fromDest = dijkstra(reversedGraph, dest); + long ans = kMax; + + for (int i = 0; i < n; ++i) { + if (fromSrc1[i] == kMax || fromSrc2[i] == kMax || fromDest[i] == kMax) + continue; + ans = Math.min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]); + } + + return ans == kMax ? -1 : ans; + } + + private static long kMax = (long) 1e10; + + private long[] dijkstra(List>[] graph, int src) { + long[] dist = new long[graph.length]; + Arrays.fill(dist, kMax); + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final long d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + return dist; + } +} diff --git a/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.py b/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.py new file mode 100644 index 00000000000..15a8552bd95 --- /dev/null +++ b/solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.py @@ -0,0 +1,31 @@ +class Solution: + def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: + graph = [[] for _ in range(n)] + reversedGraph = [[] for _ in range(n)] + + for u, v, w in edges: + graph[u].append((v, w)) + reversedGraph[v].append((u, w)) + + fromSrc1 = self._dijkstra(graph, src1) + fromSrc2 = self._dijkstra(graph, src2) + fromDest = self._dijkstra(reversedGraph, dest) + minWeight = min(a + b + c for a, b, c in zip(fromSrc1, fromSrc2, fromDest)) + return -1 if minWeight == math.inf else minWeight + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> List[int]: + dist = [math.inf] * len(graph) + + dist[src] = 0 + minHeap = [(dist[src], src)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + + return dist diff --git a/solutions/2204. Distance to a Cycle in Undirected Graph/2204.cpp b/solutions/2204. Distance to a Cycle in Undirected Graph/2204.cpp new file mode 100644 index 00000000000..ded5e8c202d --- /dev/null +++ b/solutions/2204. Distance to a Cycle in Undirected Graph/2204.cpp @@ -0,0 +1,71 @@ +class Solution { + public: + vector distanceToCycle(int n, vector>& edges) { + vector ans(n); + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + // rank[i] := the minimum node that node i can reach with forward edges + // Initialize with NO_RANK = -2 to indicate not visited. + vector cycle; + getRank(graph, 0, 0, vector(n, NO_RANK), cycle); + + queue q; + vector seen(n); + for (const int u : cycle) { + q.push(u); + seen[u] = true; + } + + int dist = 0; + while (!q.empty()) { + ++dist; + for (int sz = q.size(); sz > 0; --sz) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) { + if (seen[v]) + continue; + q.push(v); + seen[v] = true; + ans[v] = dist; + } + } + } + + return ans; + } + + private: + static constexpr int NO_RANK = -2; + + // The minRank that u can reach with forward edges + int getRank(const vector>& graph, int u, int currRank, + vector&& rank, vector& cycle) { + if (rank[u] != NO_RANK) // The rank is already determined + return rank[u]; + + rank[u] = currRank; + int minRank = currRank; + + for (const int v : graph[u]) { + // Visited || parent (that's why NO_RANK = -2 instead of -1) + if (rank[v] == rank.size() || rank[v] == currRank - 1) + continue; + const int nextRank = getRank(graph, v, currRank + 1, move(rank), cycle); + // NextRank should > currRank if there's no cycle + if (nextRank <= currRank) + cycle.push_back(v); + minRank = min(minRank, nextRank); + } + + rank[u] = rank.size(); // Mark as visited. + return minRank; + } +}; diff --git a/solutions/2204. Distance to a Cycle in Undirected Graph/2204.java b/solutions/2204. Distance to a Cycle in Undirected Graph/2204.java new file mode 100644 index 00000000000..7cdb2db2e92 --- /dev/null +++ b/solutions/2204. Distance to a Cycle in Undirected Graph/2204.java @@ -0,0 +1,70 @@ +class Solution { + public int[] distanceToCycle(int n, int[][] edges) { + int[] ans = new int[n]; + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + // rank[i] := the minimum node that node i can reach with forward edges + // Initialize with NO_RANK = -2 to indicate not visited. + int[] rank = new int[n]; + Arrays.fill(rank, NO_RANK); + List cycle = new ArrayList<>(); + getRank(graph, 0, 0, rank, cycle); + + Queue q = cycle.stream().collect(Collectors.toCollection(ArrayDeque::new)); + boolean[] seen = new boolean[n]; + for (final int u : cycle) + seen[u] = true; + + int dist = 0; + while (!q.isEmpty()) { + ++dist; + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.poll(); + for (final int v : graph[u]) { + if (seen[v]) + continue; + q.offer(v); + seen[v] = true; + ans[v] = dist; + } + } + } + + return ans; + } + + private static final int NO_RANK = -2; + + // The minRank that u can reach with forward edges + private int getRank(List[] graph, int u, int currRank, int[] rank, List cycle) { + if (rank[u] != NO_RANK) // The rank is already determined + return rank[u]; + + rank[u] = currRank; + int minRank = currRank; + + for (final int v : graph[u]) { + // Visited || parent (that's why NO_RANK = -2 instead of -1) + if (rank[u] == rank.length || rank[v] == currRank - 1) + continue; + final int nextRank = getRank(graph, v, currRank + 1, rank, cycle); + // NextRank should > currRank if there's no cycle + if (nextRank <= currRank) + cycle.add(v); + minRank = Math.min(minRank, nextRank); + } + + rank[u] = rank.length; // Mark as visited. + return minRank; + } +} diff --git a/solutions/2204. Distance to a Cycle in Undirected Graph/2204.py b/solutions/2204. Distance to a Cycle in Undirected Graph/2204.py new file mode 100644 index 00000000000..0b84d2dafb2 --- /dev/null +++ b/solutions/2204. Distance to a Cycle in Undirected Graph/2204.py @@ -0,0 +1,53 @@ +class Solution: + def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]: + ans = [0] * n + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + NO_RANK = -2 + + # The minRank that u can reach with forward edges + def getRank(u: int, currRank: int, rank: List[int]) -> int: + if rank[u] != NO_RANK: # The rank is already determined + return rank[u] + + rank[u] = currRank + minRank = currRank + + for v in graph[u]: + # Visited or parent (that's why NO_RANK = -2 instead of -1) + if rank[v] == len(rank) or rank[v] == currRank - 1: + continue + nextRank = getRank(v, currRank + 1, rank) + # NextRank should > currRank if there's no cycle + if nextRank <= currRank: + cycle.append(v) + minRank = min(minRank, nextRank) + + rank[u] = len(rank) # Mark as visited. + return minRank + + # rank[i] := the minimum node that node i can reach with forward edges + # Initialize with NO_RANK = -2 to indicate not visited. + cycle = [] + getRank(0, 0, [NO_RANK] * n) + + q = collections.deque(cycle) + seen = set(cycle) + + dist = 0 + while q: + dist += 1 + for _ in range(len(q)): + u = q.popleft() + for v in graph[u]: + if v in seen: + continue + q.append(v) + seen.add(v) + ans[v] = dist + + return ans diff --git a/solutions/2205. The Number of Users That Are Eligible for Discount/2205.sql b/solutions/2205. The Number of Users That Are Eligible for Discount/2205.sql new file mode 100644 index 00000000000..d90210e463a --- /dev/null +++ b/solutions/2205. The Number of Users That Are Eligible for Discount/2205.sql @@ -0,0 +1,10 @@ +CREATE FUNCTION getUserIDs(startDate DATE, endDate DATE, minAmount INT) RETURNS INT +BEGIN + RETURN ( + SELECT COUNT(DISTINCT user_id) AS user_cnt + FROM Purchases + WHERE + time_stamp BETWEEN startDate AND endDate + AND amount >= minAmount + ); +END diff --git a/solutions/2206. Divide Array Into Equal Pairs/2206.cpp b/solutions/2206. Divide Array Into Equal Pairs/2206.cpp new file mode 100644 index 00000000000..3937065a886 --- /dev/null +++ b/solutions/2206. Divide Array Into Equal Pairs/2206.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool divideArray(vector& nums) { + vector count(501); + + for (const int num : nums) + ++count[num]; + + return ranges::all_of(count, [](int c) { return c % 2 == 0; }); + } +}; diff --git a/solutions/2206. Divide Array Into Equal Pairs/2206.java b/solutions/2206. Divide Array Into Equal Pairs/2206.java new file mode 100644 index 00000000000..2459b9ba25a --- /dev/null +++ b/solutions/2206. Divide Array Into Equal Pairs/2206.java @@ -0,0 +1,10 @@ +class Solution { + public boolean divideArray(int[] nums) { + int[] count = new int[501]; + + for (final int num : nums) + ++count[num]; + + return Arrays.stream(count).allMatch(c -> c % 2 == 0); + } +} diff --git a/solutions/2206. Divide Array Into Equal Pairs/2206.py b/solutions/2206. Divide Array Into Equal Pairs/2206.py new file mode 100644 index 00000000000..ffd328dc2f0 --- /dev/null +++ b/solutions/2206. Divide Array Into Equal Pairs/2206.py @@ -0,0 +1,3 @@ +class Solution: + def divideArray(self, nums: List[int]) -> bool: + return all(value % 2 == 0 for value in collections.Counter(nums).values()) diff --git a/solutions/2207. Maximize Number of Subsequences in a String/2207.cpp b/solutions/2207. Maximize Number of Subsequences in a String/2207.cpp new file mode 100644 index 00000000000..e97851c198b --- /dev/null +++ b/solutions/2207. Maximize Number of Subsequences in a String/2207.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long maximumSubsequenceCount(string text, string pattern) { + long ans = 0; + int count0 = 0; // the count of the letter pattern[0] + int count1 = 0; // the count of the letter pattern[1] + + for (const char c : text) { + if (c == pattern[1]) { + ans += count0; + ++count1; + } + if (c == pattern[0]) + ++count0; + } + + // It is optimal to add pattern[0] at the beginning or add pattern[1] at the + // end of the text. + return ans + max(count0, count1); + } +}; diff --git a/solutions/2207. Maximize Number of Subsequences in a String/2207.java b/solutions/2207. Maximize Number of Subsequences in a String/2207.java new file mode 100644 index 00000000000..f9cae4147e9 --- /dev/null +++ b/solutions/2207. Maximize Number of Subsequences in a String/2207.java @@ -0,0 +1,20 @@ +class Solution { + public long maximumSubsequenceCount(String text, String pattern) { + long ans = 0; + int count0 = 0; // the count of the letter pattern[0] + int count1 = 0; // the count of the letter pattern[1] + + for (final char c : text.toCharArray()) { + if (c == pattern.charAt(1)) { + ans += count0; + ++count1; + } + if (c == pattern.charAt(0)) + ++count0; + } + + // It is optimal to add pattern[0] at the beginning or add pattern[1] at the + // end of the text. + return ans + Math.max(count0, count1); + } +} diff --git a/solutions/2207. Maximize Number of Subsequences in a String/2207.py b/solutions/2207. Maximize Number of Subsequences in a String/2207.py new file mode 100644 index 00000000000..21b6c07ab49 --- /dev/null +++ b/solutions/2207. Maximize Number of Subsequences in a String/2207.py @@ -0,0 +1,16 @@ +class Solution: + def maximumSubsequenceCount(self, text: str, pattern: str) -> int: + ans = 0 + count0 = 0 # the count of the letter pattern[0] + count1 = 0 # the count of the letter pattern[1] + + for c in text: + if c == pattern[1]: + ans += count0 + count1 += 1 + if c == pattern[0]: + count0 += 1 + + # It is optimal to add pattern[0] at the beginning or add pattern[1] at the + # end of the text. + return ans + max(count0, count1) diff --git a/solutions/2208. Minimum Operations to Halve Array Sum/2208.cpp b/solutions/2208. Minimum Operations to Halve Array Sum/2208.cpp new file mode 100644 index 00000000000..1ffe2c993f0 --- /dev/null +++ b/solutions/2208. Minimum Operations to Halve Array Sum/2208.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int halveArray(vector& nums) { + const double halfSum = accumulate(nums.begin(), nums.end(), 0.) / 2; + int ans = 0; + double runningSum = 0; + priority_queue maxHeap{nums.begin(), nums.end()}; + + while (runningSum < halfSum) { + const double maxValue = maxHeap.top() / 2; + runningSum += maxValue, maxHeap.pop(); + maxHeap.push(maxValue); + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2208. Minimum Operations to Halve Array Sum/2208.java b/solutions/2208. Minimum Operations to Halve Array Sum/2208.java new file mode 100644 index 00000000000..1fb1f16a0e6 --- /dev/null +++ b/solutions/2208. Minimum Operations to Halve Array Sum/2208.java @@ -0,0 +1,20 @@ +class Solution { + public int halveArray(int[] nums) { + final double halfSum = Arrays.stream(nums).asDoubleStream().sum() / 2; + int ans = 0; + double runningSum = 0; + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + for (final double num : nums) + maxHeap.offer(num); + + while (runningSum < halfSum) { + final double maxValue = maxHeap.poll() / 2; + runningSum += maxValue; + maxHeap.offer(maxValue); + ++ans; + } + + return ans; + } +} diff --git a/solutions/2208. Minimum Operations to Halve Array Sum/2208.py b/solutions/2208. Minimum Operations to Halve Array Sum/2208.py new file mode 100644 index 00000000000..77524566955 --- /dev/null +++ b/solutions/2208. Minimum Operations to Halve Array Sum/2208.py @@ -0,0 +1,16 @@ +class Solution: + def halveArray(self, nums: List[int]) -> int: + halfSum = sum(nums) / 2 + ans = 0 + runningSum = 0.0 + maxHeap = [-num for num in nums] + + heapq.heapify(maxHeap) + + while runningSum < halfSum: + maxValue = -heapq.heappop(maxHeap) / 2 + runningSum += maxValue + heapq.heappush(maxHeap, -maxValue) + ans += 1 + + return ans diff --git a/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.cpp b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.cpp new file mode 100644 index 00000000000..80035875522 --- /dev/null +++ b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) { + const int n = floor.length(); + // dp[i][j] := the minimum number of visible white tiles of floor[i..n) + // after covering at most j carpets + vector> dp(n + 1, vector(numCarpets + 1)); + + for (int i = n - 1; i >= 0; --i) + dp[i][0] = floor[i] - '0' + dp[i + 1][0]; + + for (int i = n - 1; i >= 0; --i) + for (int j = 1; j <= numCarpets; ++j) { + const int cover = i + carpetLen < n ? dp[i + carpetLen][j - 1] : 0; + const int skip = floor[i] - '0' + dp[i + 1][j]; + dp[i][j] = min(cover, skip); + } + + return dp[0][numCarpets]; + } +}; diff --git a/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.java b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.java new file mode 100644 index 00000000000..1db4d40e79e --- /dev/null +++ b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.java @@ -0,0 +1,20 @@ +class Solution { + public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) { + final int n = floor.length(); + // dp[i][j] := the minimum number of visible white tiles of floor[i..n) + // after covering at most j carpets + int[][] dp = new int[n + 1][numCarpets + 1]; + + for (int i = n - 1; i >= 0; --i) + dp[i][0] = floor.charAt(i) - '0' + dp[i + 1][0]; + + for (int i = n - 1; i >= 0; --i) + for (int j = 1; j <= numCarpets; ++j) { + final int cover = i + carpetLen < n ? dp[i + carpetLen][j - 1] : 0; + final int skip = floor.charAt(i) - '0' + dp[i + 1][j]; + dp[i][j] = Math.min(cover, skip); + } + + return dp[0][numCarpets]; + } +} diff --git a/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.py b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.py new file mode 100644 index 00000000000..b30d5c3f932 --- /dev/null +++ b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209-2.py @@ -0,0 +1,17 @@ +class Solution: + def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: + n = len(floor) + # dp[i][j] := the minimum number of visible white tiles of floor[i..n) + # after covering at most j carpets + dp = [[0] * (numCarpets + 1) for _ in range(n + 1)] + + for i in reversed(range(n)): + dp[i][0] = int(floor[i]) + dp[i + 1][0] + + for i in reversed(range(n)): + for j in range(1, numCarpets + 1): + cover = dp[i + carpetLen][j - 1] if i + carpetLen < n else 0 + skip = int(floor[i]) + dp[i + 1][j] + dp[i][j] = min(cover, skip) + + return dp[0][numCarpets] diff --git a/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.cpp b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.cpp new file mode 100644 index 00000000000..1114efc2c92 --- /dev/null +++ b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) { + vector> mem(floor.length() + 1, + vector(numCarpets + 1, kMax)); + return minimumWhiteTiles(floor, 0, numCarpets, carpetLen, mem); + } + + private: + static constexpr int kMax = 1000; + + // Returns the minimum number of visible white tiles of floor[i..n) after + // covering at most j carpets. + int minimumWhiteTiles(const string& floor, int i, int j, int carpetLen, + vector>& mem) { + if (j < 0) + return kMax; + if (i >= floor.length()) + return 0; + if (mem[i][j] != kMax) + return mem[i][j]; + return mem[i][j] = min( + minimumWhiteTiles(floor, i + carpetLen, j - 1, carpetLen, mem), + minimumWhiteTiles(floor, i + 1, j, carpetLen, mem) + floor[i] - + '0'); + } +}; diff --git a/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.java b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.java new file mode 100644 index 00000000000..ed4f3dc0d5a --- /dev/null +++ b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) { + int[][] mem = new int[floor.length() + 1][numCarpets + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, kMax)); + return minimumWhiteTiles(floor, 0, numCarpets, carpetLen, mem); + } + + private static final int kMax = 1000; + + // Returns the minimum number of visible white tiles of floor[i..n) after + // covering at most j carpets. + int minimumWhiteTiles(final String floor, int i, int j, int carpetLen, int[][] mem) { + if (j < 0) + return kMax; + if (i >= floor.length()) + return 0; + if (mem[i][j] != kMax) + return mem[i][j]; + return mem[i][j] = + Math.min(minimumWhiteTiles(floor, i + carpetLen, j - 1, carpetLen, mem), + minimumWhiteTiles(floor, i + 1, j, carpetLen, mem) + floor.charAt(i) - '0'); + } +} diff --git a/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.py b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.py new file mode 100644 index 00000000000..5906ad0eed5 --- /dev/null +++ b/solutions/2209. Minimum White Tiles After Covering With Carpets/2209.py @@ -0,0 +1,18 @@ +class Solution: + def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: + kMax = 1000 + + @functools.lru_cache(None) + def dp(i: int, j: int) -> int: + """ + Returns the minimum number of visible white tiles of floor[i..n) after + covering at most j carpets. + """ + if j < 0: + return kMax + if i >= len(floor): + return 0 + return min(dp(i + carpetLen, j - 1), + dp(i + 1, j) + int(floor[i])) + + return dp(0, numCarpets) diff --git a/solutions/221. Maximal Square/221-2.cpp b/solutions/221. Maximal Square/221-2.cpp new file mode 100644 index 00000000000..8dc3e5d43ac --- /dev/null +++ b/solutions/221. Maximal Square/221-2.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int maximalSquare(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + vector dp(n); + int maxLength = 0; + int prev = 0; // dp[i - 1][j - 1] + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + const int cache = dp[j]; + if (i == 0 || j == 0 || matrix[i][j] == '0') + dp[j] = matrix[i][j] == '1' ? 1 : 0; + else + dp[j] = min({prev, dp[j], dp[j - 1]}) + 1; + maxLength = max(maxLength, dp[j]); + prev = cache; + } + + return maxLength * maxLength; + } +}; diff --git a/solutions/221. Maximal Square/221-2.java b/solutions/221. Maximal Square/221-2.java new file mode 100644 index 00000000000..01549f8c61a --- /dev/null +++ b/solutions/221. Maximal Square/221-2.java @@ -0,0 +1,22 @@ +class Solution { + public int maximalSquare(char[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + int[] dp = new int[n]; + int maxLength = 0; + int prev = 0; // dp[i - 1][j - 1] + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + final int cache = dp[j]; + if (i == 0 || j == 0 || matrix[i][j] == '0') + dp[j] = matrix[i][j] == '1' ? 1 : 0; + else + dp[j] = Math.min(prev, Math.min(dp[j], dp[j - 1])) + 1; + maxLength = Math.max(maxLength, dp[j]); + prev = cache; + } + + return maxLength * maxLength; + } +} diff --git a/solutions/221. Maximal Square/221-2.py b/solutions/221. Maximal Square/221-2.py new file mode 100644 index 00000000000..0a302e91510 --- /dev/null +++ b/solutions/221. Maximal Square/221-2.py @@ -0,0 +1,19 @@ +class Solution: + def maximalSquare(self, matrix: List[List[chr]]) -> int: + m = len(matrix) + n = len(matrix[0]) + dp = [0] * n + maxLength = 0 + prev = 0 # dp[i - 1][j - 1] + + for i in range(m): + for j in range(n): + cache = dp[j] + if i == 0 or j == 0 or matrix[i][j] == '0': + dp[j] = 1 if matrix[i][j] == '1' else 0 + else: + dp[j] = min([prev, dp[j], dp[j - 1]]) + 1 + maxLength = max(maxLength, dp[j]) + prev = cache + + return maxLength * maxLength diff --git a/solutions/221. Maximal Square/221.cpp b/solutions/221. Maximal Square/221.cpp new file mode 100644 index 00000000000..5b5c5f4cb46 --- /dev/null +++ b/solutions/221. Maximal Square/221.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maximalSquare(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + vector> dp(m, vector(n)); + int maxLength = 0; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (i == 0 || j == 0 || matrix[i][j] == '0') + dp[i][j] = matrix[i][j] == '1' ? 1 : 0; + else + dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1; + maxLength = max(maxLength, dp[i][j]); + } + + return maxLength * maxLength; + } +}; diff --git a/solutions/221. Maximal Square/221.java b/solutions/221. Maximal Square/221.java new file mode 100644 index 00000000000..9febf5f0bc7 --- /dev/null +++ b/solutions/221. Maximal Square/221.java @@ -0,0 +1,19 @@ +class Solution { + public int maximalSquare(char[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + int[][] dp = new int[m][n]; + int maxLength = 0; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (i == 0 || j == 0 || matrix[i][j] == '0') + dp[i][j] = matrix[i][j] == '1' ? 1 : 0; + else + dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; + maxLength = Math.max(maxLength, dp[i][j]); + } + + return maxLength * maxLength; + } +} diff --git a/solutions/221. Maximal Square/221.py b/solutions/221. Maximal Square/221.py new file mode 100644 index 00000000000..3df2de1e5b6 --- /dev/null +++ b/solutions/221. Maximal Square/221.py @@ -0,0 +1,17 @@ +class Solution: + def maximalSquare(self, matrix: List[List[str]]) -> int: + m = len(matrix) + n = len(matrix[0]) + dp = [[0] * n for _ in range(m)] + maxLength = 0 + + for i in range(m): + for j in range(n): + if i == 0 or j == 0 or matrix[i][j] == '0': + dp[i][j] = 1 if matrix[i][j] == '1' else 0 + else: + dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1] + [j], dp[i][j - 1]) + 1 + maxLength = max(maxLength, dp[i][j]) + + return maxLength * maxLength diff --git a/solutions/2210. Count Hills and Valleys in an Array/2210.cpp b/solutions/2210. Count Hills and Valleys in an Array/2210.cpp new file mode 100644 index 00000000000..2de632baaea --- /dev/null +++ b/solutions/2210. Count Hills and Valleys in an Array/2210.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int countthe hillthe valley(vector& nums) { + int ans = 0; + int left = nums[0]; + + for (int i = 1; i + 1 < nums.size(); ++i) + if (left < nums[i] && nums[i] > nums[i + 1] || // the hill + left > nums[i] && nums[i] < nums[i + 1]) { // the valley + ++ans; + left = nums[i]; + } + + return ans; + } +}; diff --git a/solutions/2210. Count Hills and Valleys in an Array/2210.java b/solutions/2210. Count Hills and Valleys in an Array/2210.java new file mode 100644 index 00000000000..24e6d261ed3 --- /dev/null +++ b/solutions/2210. Count Hills and Valleys in an Array/2210.java @@ -0,0 +1,15 @@ +class Solution { + public int countthe hillthe valley(int[] nums) { + int ans = 0; + int left = nums[0]; + + for (int i = 1; i + 1 < nums.length; ++i) + if (left < nums[i] && nums[i] > nums[i + 1] || // the hill + left > nums[i] && nums[i] < nums[i + 1]) { // the valley + ++ans; + left = nums[i]; + } + + return ans; + } +} diff --git a/solutions/2210. Count Hills and Valleys in an Array/2210.py b/solutions/2210. Count Hills and Valleys in an Array/2210.py new file mode 100644 index 00000000000..f504b63a62c --- /dev/null +++ b/solutions/2210. Count Hills and Valleys in an Array/2210.py @@ -0,0 +1,13 @@ +class Solution: + def countthe hillthe valley(self, nums: List[int]) -> int: + ans = 0 + left = nums[0] + + for i in range(1, len(nums) - 1): + # the hill or valley + if left < nums[i] and nums[i] > nums[i + 1] or \ + left > nums[i] and nums[i] < nums[i + 1]: + ans += 1 + left = nums[i] + + return ans diff --git a/solutions/2211. Count Collisions on a Road/2211.cpp b/solutions/2211. Count Collisions on a Road/2211.cpp new file mode 100644 index 00000000000..f5d1dc9dd53 --- /dev/null +++ b/solutions/2211. Count Collisions on a Road/2211.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int countCollisions(string directions) { + int l = 0; + int r = directions.length() - 1; + + while (l < directions.length() && directions[l] == 'L') + ++l; + + while (r >= 0 && directions[r] == 'R') + --r; + + return count_if(directions.begin() + l, directions.begin() + r + 1, + [](char c) { return c != 'S'; }); + } +}; diff --git a/solutions/2211. Count Collisions on a Road/2211.java b/solutions/2211. Count Collisions on a Road/2211.java new file mode 100644 index 00000000000..f8a348ab714 --- /dev/null +++ b/solutions/2211. Count Collisions on a Road/2211.java @@ -0,0 +1,19 @@ +class Solution { + public int countCollisions(String directions) { + int ans = 0; + int l = 0; + int r = directions.length() - 1; + + while (l < directions.length() && directions.charAt(l) == 'L') + ++l; + + while (r >= 0 && directions.charAt(r) == 'R') + --r; + + for (int i = l; i <= r; ++i) + if (directions.charAt(i) != 'S') + ++ans; + + return ans; + } +} diff --git a/solutions/2211. Count Collisions on a Road/2211.py b/solutions/2211. Count Collisions on a Road/2211.py new file mode 100644 index 00000000000..f7594719287 --- /dev/null +++ b/solutions/2211. Count Collisions on a Road/2211.py @@ -0,0 +1,12 @@ +class Solution: + def countCollisions(self, directions: str) -> int: + l = 0 + r = len(directions) - 1 + + while l < len(directions) and directions[l] == 'L': + l += 1 + + while r >= 0 and directions[r] == 'R': + r -= 1 + + return sum(c != 'S' for c in directions[l:r + 1]) diff --git a/solutions/2212. Maximum Points in an Archery Competition/2212.cpp b/solutions/2212. Maximum Points in an Archery Competition/2212.cpp new file mode 100644 index 00000000000..0180c9a3523 --- /dev/null +++ b/solutions/2212. Maximum Points in an Archery Competition/2212.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + vector maximumBobPoints(int numArrows, vector& aliceArrows) { + constexpr int allMask = (1 << 12) - 1; + int maxPoint = 0; + int maxMask = 0; + + for (int mask = 0; mask < allMask; ++mask) { + const auto& [shotable, point] = + getShotableAndPoint(mask, numArrows, aliceArrows); + if (shotable && point > maxPoint) { + maxPoint = point; + maxMask = mask; + } + } + + return getBobsArrows(maxMask, numArrows, aliceArrows); + } + + private: + pair getShotableAndPoint(int mask, int leftArrows, + const vector& aliceArrows) { + int point = 0; + for (int i = 0; i < 12; ++i) + if (mask >> i & 1) { + leftArrows -= aliceArrows[i] + 1; + point += i; + } + return {leftArrows >= 0, point}; + } + + vector getBobsArrows(int mask, int leftArrows, + const vector& aliceArrows) { + vector bobsArrows(12); + for (int i = 0; i < 12; ++i) + if (mask >> i & 1) { + bobsArrows[i] = aliceArrows[i] + 1; + leftArrows -= aliceArrows[i] + 1; + } + bobsArrows[0] = leftArrows; + return bobsArrows; + } +}; diff --git a/solutions/2212. Maximum Points in an Archery Competition/2212.java b/solutions/2212. Maximum Points in an Archery Competition/2212.java new file mode 100644 index 00000000000..77bf274a618 --- /dev/null +++ b/solutions/2212. Maximum Points in an Archery Competition/2212.java @@ -0,0 +1,40 @@ +class Solution { + public int[] maximumBobPoints(int numArrows, int[] aliceArrows) { + final int allMask = (1 << 12) - 1; + int maxPoint = 0; + int maxMask = 0; + + for (int mask = 0; mask < allMask; ++mask) { + Pair pair = getShotableAndPoint(mask, numArrows, aliceArrows); + final boolean shotable = pair.getKey(); + final int point = pair.getValue(); + if (shotable && point > maxPoint) { + maxPoint = point; + maxMask = mask; + } + } + + return getBobsArrows(maxMask, numArrows, aliceArrows); + } + + private Pair getShotableAndPoint(int mask, int leftArrows, int[] aliceArrows) { + int point = 0; + for (int i = 0; i < 12; ++i) + if ((mask >> i & 1) == 1) { + leftArrows -= aliceArrows[i] + 1; + point += i; + } + return new Pair<>(leftArrows >= 0, point); + } + + int[] getBobsArrows(int mask, int leftArrows, int[] aliceArrows) { + int[] bobsArrows = new int[12]; + for (int i = 0; i < 12; ++i) + if ((mask >> i & 1) == 1) { + bobsArrows[i] = aliceArrows[i] + 1; + leftArrows -= aliceArrows[i] + 1; + } + bobsArrows[0] = leftArrows; + return bobsArrows; + } +} diff --git a/solutions/2212. Maximum Points in an Archery Competition/2212.py b/solutions/2212. Maximum Points in an Archery Competition/2212.py new file mode 100644 index 00000000000..fcd1e4baf76 --- /dev/null +++ b/solutions/2212. Maximum Points in an Archery Competition/2212.py @@ -0,0 +1,30 @@ +class Solution: + def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: + allMask = (1 << 12) - 1 + maxPoint = 0 + maxMask = 0 + + def getShotableAndPoint(mask: int, leftArrows: int) -> Tuple[bool, int]: + point = 0 + for i in range(12): + if mask >> i & 1: + leftArrows -= aliceArrows[i] + 1 + point += i + return leftArrows >= 0, point + + for mask in range(allMask): + shotable, point = getShotableAndPoint(mask, numArrows) + if shotable and point > maxPoint: + maxPoint = point + maxMask = mask + + def getBobsArrows(mask: int, leftArrows: int) -> List[int]: + bobsArrows = [0] * 12 + for i in range(12): + if mask >> i & 1: + bobsArrows[i] = aliceArrows[i] + 1 + leftArrows -= aliceArrows[i] + 1 + bobsArrows[0] = leftArrows + return bobsArrows + + return getBobsArrows(maxMask, numArrows) diff --git a/solutions/2213. Longest Substring of One Repeating Character/2213.cpp b/solutions/2213. Longest Substring of One Repeating Character/2213.cpp new file mode 100644 index 00000000000..81240e3102f --- /dev/null +++ b/solutions/2213. Longest Substring of One Repeating Character/2213.cpp @@ -0,0 +1,128 @@ +struct SegmentTreeNode { + int lo; + int hi; + char maxLetter; + char prefixLetter; + char suffixLetter; + int maxLength; + int prefixLength; + int suffixLength; + SegmentTreeNode* left; + SegmentTreeNode* right; + SegmentTreeNode(int lo, int hi, char maxLetter, char prefixLetter, + char suffixLetter, int maxLength, int prefixLength, + int suffixLength, SegmentTreeNode* left = nullptr, + SegmentTreeNode* right = nullptr) + : lo(lo), + hi(hi), + maxLetter(maxLetter), + prefixLetter(prefixLetter), + suffixLetter(suffixLetter), + maxLength(maxLength), + prefixLength(prefixLength), + suffixLength(suffixLength), + left(left), + right(right) {} + ~SegmentTreeNode() { + delete left; + delete right; + left = nullptr; + right = nullptr; + } +}; + +class SegmentTree { + public: + explicit SegmentTree(const string& s) : root(build(s, 0, s.length() - 1)) {} + ~SegmentTree() { + delete root; + } + + void update(int i, char val) { + root = update(root, i, val); + } + + int getMaxLength() { + return root->maxLength; + } + + private: + SegmentTreeNode* root; + + SegmentTreeNode* build(const string& s, int lo, int hi) const { + if (lo == hi) + return new SegmentTreeNode(lo, hi, s[lo], s[lo], s[lo], 1, 1, 1); + const int mid = (lo + hi) / 2; + SegmentTreeNode* left = build(s, lo, mid); + SegmentTreeNode* right = build(s, mid + 1, hi); + return merge(left, right); + } + + SegmentTreeNode* update(SegmentTreeNode* root, int i, char c) { + if (root->lo == i && root->hi == i) { + root->maxLetter = c; + root->prefixLetter = c; + root->suffixLetter = c; + return root; + } + const int mid = (root->lo + root->hi) / 2; + if (i <= mid) { + SegmentTreeNode* updatedLeft = update(root->left, i, c); + return root = merge(updatedLeft, root->right); + } else { + SegmentTreeNode* updatedRight = update(root->right, i, c); + return root = merge(root->left, updatedRight); + } + } + + SegmentTreeNode* merge(SegmentTreeNode* left, SegmentTreeNode* right) const { + // Get `maxLetter` and `maxLength`. + char maxLetter = ' '; + int maxLength = 0; + if (left->maxLength > right->maxLength) { + maxLetter = left->maxLetter; + maxLength = left->maxLength; + } else { + maxLetter = right->maxLetter; + maxLength = right->maxLength; + } + if (left->suffixLetter == right->prefixLetter && + left->suffixLength + right->prefixLength > maxLength) { + maxLetter = left->suffixLetter; + maxLength = left->suffixLength + right->prefixLength; + } + + // Get `prefixLetter` and `prefixLength`. + char prefixLetter = left->prefixLetter; + int prefixLength = left->prefixLength; + if (left->lo + prefixLength == right->lo && + left->prefixLetter == right->prefixLetter) + prefixLength += right->prefixLength; + + // Get `suffixLetter` and `suffixLength`. + char suffixLetter = right->suffixLetter; + int suffixLength = right->suffixLength; + if (right->hi - suffixLength == left->hi && + right->suffixLetter == left->suffixLetter) + suffixLength += left->suffixLength; + return new SegmentTreeNode(left->lo, right->hi, maxLetter, prefixLetter, + suffixLetter, maxLength, prefixLength, + suffixLength, left, right); + } +}; + +class Solution { + public: + vector longestRepeating(string s, string queryLetteracters, + vector& queryIndices) { + vector ans; + SegmentTree tree(s); + + for (int i = 0; i < queryIndices.size(); ++i) { + tree.update(queryIndices[i], queryLetteracters[i]); + ans.push_back(tree.getMaxLength()); + } + + return ans; + } +}; diff --git a/solutions/2214. Minimum Health to Beat Game/2214.cpp b/solutions/2214. Minimum Health to Beat Game/2214.cpp new file mode 100644 index 00000000000..ed6b96a0de4 --- /dev/null +++ b/solutions/2214. Minimum Health to Beat Game/2214.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + long long minimumHealth(vector& damage, int armor) { + const long sum = accumulate(damage.begin(), damage.end(), 0L); + const int maxDamage = ranges::max(damage); + return 1 + sum - min(maxDamage, armor); + } +}; diff --git a/solutions/2214. Minimum Health to Beat Game/2214.java b/solutions/2214. Minimum Health to Beat Game/2214.java new file mode 100644 index 00000000000..c33f48057e2 --- /dev/null +++ b/solutions/2214. Minimum Health to Beat Game/2214.java @@ -0,0 +1,7 @@ +class Solution { + public long minimumHealth(int[] damage, int armor) { + final long sum = Arrays.stream(damage).asLongStream().sum(); + final int maxDamage = Arrays.stream(damage).max().getAsInt(); + return 1 + sum - Math.min(maxDamage, armor); + } +} diff --git a/solutions/2214. Minimum Health to Beat Game/2214.py b/solutions/2214. Minimum Health to Beat Game/2214.py new file mode 100644 index 00000000000..7a70232a1a4 --- /dev/null +++ b/solutions/2214. Minimum Health to Beat Game/2214.py @@ -0,0 +1,3 @@ +class Solution: + def minimumHealth(self, damage: List[int], armor: int) -> int: + return 1 + sum(damage) - min(max(damage), armor) diff --git a/solutions/2215. Find the Difference of Two Arrays/2215.cpp b/solutions/2215. Find the Difference of Two Arrays/2215.cpp new file mode 100644 index 00000000000..fc70fc658d5 --- /dev/null +++ b/solutions/2215. Find the Difference of Two Arrays/2215.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector> findDifference(vector& nums1, vector& nums2) { + const unordered_set set1{nums1.begin(), nums1.end()}; + const unordered_set set2{nums2.begin(), nums2.end()}; + vector> ans(2); + + for (const int num : set1) + if (!set2.contains(num)) + ans[0].push_back(num); + + for (const int num : set2) + if (!set1.contains(num)) + ans[1].push_back(num); + + return ans; + } +}; diff --git a/solutions/2215. Find the Difference of Two Arrays/2215.java b/solutions/2215. Find the Difference of Two Arrays/2215.java new file mode 100644 index 00000000000..a42b9a5fb8b --- /dev/null +++ b/solutions/2215. Find the Difference of Two Arrays/2215.java @@ -0,0 +1,9 @@ +class Solution { + public List> findDifference(int[] nums1, int[] nums2) { + Set set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet()); + Set set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet()); + Arrays.stream(nums1).forEach(set2::remove); + Arrays.stream(nums2).forEach(set1::remove); + return Arrays.asList(new ArrayList<>(set1), new ArrayList<>(set2)); + } +} diff --git a/solutions/2215. Find the Difference of Two Arrays/2215.py b/solutions/2215. Find the Difference of Two Arrays/2215.py new file mode 100644 index 00000000000..aa19edb75ab --- /dev/null +++ b/solutions/2215. Find the Difference of Two Arrays/2215.py @@ -0,0 +1,5 @@ +class Solution: + def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: + set1 = set(nums1) + set2 = set(nums2) + return [set1 - set2, set2 - set1] diff --git a/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.cpp b/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.cpp new file mode 100644 index 00000000000..e8fbcdb6d2e --- /dev/null +++ b/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int minDeletion(vector& nums) { + int ans = 0; + + for (int i = 0; i + 1 < nums.size(); ++i) + // i - ans := the index after deletion + if (nums[i] == nums[i + 1] && (i - ans) % 2 == 0) + ++ans; + + return ans + ((nums.size() - ans) & 1); + } +}; diff --git a/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.java b/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.java new file mode 100644 index 00000000000..6dcd94196fb --- /dev/null +++ b/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.java @@ -0,0 +1,12 @@ +class Solution { + public int minDeletion(int[] nums) { + int ans = 0; + + for (int i = 0; i + 1 < nums.length; ++i) + // i - ans := the index after deletion + if (nums[i] == nums[i + 1] && (i - ans) % 2 == 0) + ++ans; + + return ans + (((nums.length - ans) & 1) == 1 ? 1 : 0); + } +} diff --git a/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.py b/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.py new file mode 100644 index 00000000000..be90c1e8697 --- /dev/null +++ b/solutions/2216. Minimum Deletions to Make Array Beautiful/2216.py @@ -0,0 +1,11 @@ +class Solution: + def minDeletion(self, nums: List[int]) -> int: + ans = 0 + + for i in range(len(nums) - 1): + # i - ans := the index after deletion + if nums[i] == nums[i + 1] and (i - ans) % 2 == 0: + ans += 1 + + # Add one if the length after deletion is odd + return ans + ((len(nums) - ans) & 1) diff --git a/solutions/2217. Find Palindrome With Fixed Length/2217.cpp b/solutions/2217. Find Palindrome With Fixed Length/2217.cpp new file mode 100644 index 00000000000..c9d7982f123 --- /dev/null +++ b/solutions/2217. Find Palindrome With Fixed Length/2217.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector kthPalindrome(vector& queries, int intLength) { + const int start = pow(10, (intLength + 1) / 2 - 1); + const int end = pow(10, (intLength + 1) / 2); + const int mul = pow(10, intLength / 2); + vector ans; + + for (const int query : queries) + if (start + query > end) + ans.push_back(-1); + else + ans.push_back(getKthPalindrome(query, start, mul, intLength)); + + return ans; + } + + private: + long getKthPalindrome(int query, int start, int mul, int intLength) { + const long prefix = start + query - 1; + return prefix * mul + reverse(intLength % 2 == 0 ? prefix : prefix / 10); + } + + long reverse(int num) { + long res = 0; + while (num) { + res = res * 10 + num % 10; + num /= 10; + } + return res; + } +}; diff --git a/solutions/2217. Find Palindrome With Fixed Length/2217.java b/solutions/2217. Find Palindrome With Fixed Length/2217.java new file mode 100644 index 00000000000..ff67d206e11 --- /dev/null +++ b/solutions/2217. Find Palindrome With Fixed Length/2217.java @@ -0,0 +1,30 @@ +class Solution { + public long[] kthPalindrome(int[] queries, int intLength) { + final int start = (int) Math.pow(10, (intLength + 1) / 2 - 1); + final int end = (int) Math.pow(10, (intLength + 1) / 2); + final int mul = (int) Math.pow(10, intLength / 2); + long[] ans = new long[queries.length]; + + for (int i = 0; i < queries.length; ++i) + if (start + queries[i] > end) + ans[i] = -1; + else + ans[i] = getKthPalindrome(queries[i], start, mul, intLength); + + return ans; + } + + private long getKthPalindrome(int q, int start, int mul, int intLength) { + final long prefix = start + q - 1; + return prefix * mul + reverse(intLength % 2 == 0 ? prefix : prefix / 10); + } + + long reverse(long num) { + long res = 0; + while (num > 0) { + res = res * 10 + num % 10; + num /= 10; + } + return res; + } +} diff --git a/solutions/2217. Find Palindrome With Fixed Length/2217.py b/solutions/2217. Find Palindrome With Fixed Length/2217.py new file mode 100644 index 00000000000..326e6d3bf0d --- /dev/null +++ b/solutions/2217. Find Palindrome With Fixed Length/2217.py @@ -0,0 +1,19 @@ +class Solution: + def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]: + start = pow(10, (intLength + 1) // 2 - 1) + end = pow(10, (intLength + 1) // 2) + mul = pow(10, intLength // 2) + + def reverse(num: int) -> int: + res = 0 + while num: + res = res * 10 + num % 10 + num //= 10 + return res + + def getKthPalindrome(query: int) -> int: + prefix = start + query - 1 + return prefix * mul + reverse(prefix if intLength % 2 == 0 else prefix//10) + + return [-1 if start + query > end else getKthPalindrome(query) + for query in queries] diff --git a/solutions/2218. Maximum Value of K Coins From Piles/2218.cpp b/solutions/2218. Maximum Value of K Coins From Piles/2218.cpp new file mode 100644 index 00000000000..eafba340c96 --- /dev/null +++ b/solutions/2218. Maximum Value of K Coins From Piles/2218.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maxValueOfCoins(vector>& piles, int k) { + vector> mem(piles.size(), vector(k + 1)); + return maxValueOfCoins(piles, 0, k, mem); + } + + private: + // Returns the maximum value of picking k coins from piles[i..n) + int maxValueOfCoins(const vector>& piles, int i, size_t k, + vector>& mem) { + if (i == piles.size() || k == 0) + return 0; + if (mem[i][k]) + return mem[i][k]; + + // Pick no coins from the current pile. + int res = maxValueOfCoins(piles, i + 1, k, mem); + int val = 0; // the coins picked from the current pile + + // Try to pick 1, 2, ..., k coins from the current pile. + for (int j = 0; j < min(piles[i].size(), k); ++j) { + val += piles[i][j]; + res = max(res, val + maxValueOfCoins(piles, i + 1, k - j - 1, mem)); + } + + return mem[i][k] = res; + } +}; diff --git a/solutions/2218. Maximum Value of K Coins From Piles/2218.java b/solutions/2218. Maximum Value of K Coins From Piles/2218.java new file mode 100644 index 00000000000..5b814d987c9 --- /dev/null +++ b/solutions/2218. Maximum Value of K Coins From Piles/2218.java @@ -0,0 +1,26 @@ +class Solution { + public int maxValueOfCoins(List> piles, int k) { + Integer[][] mem = new Integer[piles.size()][k + 1]; + return maxValueOfCoins(piles, 0, k, mem); + } + + // Returns the maximum value of picking k coins from piles[i..n) + private int maxValueOfCoins(List> piles, int i, int k, Integer[][] mem) { + if (i == piles.size() || k == 0) + return 0; + if (mem[i][k] != null) + return mem[i][k]; + + // Pick no coins from the current pile. + int res = maxValueOfCoins(piles, i + 1, k, mem); + int val = 0; // the coins picked from the current pile + + // Try to pick 1, 2, ..., k coins from the current pile. + for (int j = 0; j < Math.min(piles.get(i).size(), k); ++j) { + val += piles.get(i).get(j); + res = Math.max(res, val + maxValueOfCoins(piles, i + 1, k - j - 1, mem)); + } + + return mem[i][k] = res; + } +} diff --git a/solutions/2218. Maximum Value of K Coins From Piles/2218.py b/solutions/2218. Maximum Value of K Coins From Piles/2218.py new file mode 100644 index 00000000000..9d928a7b594 --- /dev/null +++ b/solutions/2218. Maximum Value of K Coins From Piles/2218.py @@ -0,0 +1,20 @@ +class Solution: + def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: + @functools.lru_cache(None) + def dp(i: int, k: int) -> int: + """Returns the maximum value of picking k coins from piles[i..n).""" + if i == len(piles) or k == 0: + return 0 + + # Pick no coins from the current pile. + res = dp(i + 1, k) + val = 0 # the coins picked from the current pile + + # Try to pick 1, 2, ..., k coins from the current pile. + for j in range(min(len(piles[i]), k)): + val += piles[i][j] + res = max(res, val + dp(i + 1, k - j - 1)) + + return res + + return dp(0, k) diff --git a/solutions/2219. Maximum Sum Score of Array/2219.cpp b/solutions/2219. Maximum Sum Score of Array/2219.cpp new file mode 100644 index 00000000000..d922ca8f406 --- /dev/null +++ b/solutions/2219. Maximum Sum Score of Array/2219.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + long long maximumSumScore(vector& nums) { + long ans = LONG_MIN; + long prefix = 0; + long sum = accumulate(nums.begin(), nums.end(), 0L); + + for (const int num : nums) { + prefix += num; + ans = max({ans, prefix, sum - prefix + num}); + } + + return ans; + } +}; diff --git a/solutions/2219. Maximum Sum Score of Array/2219.java b/solutions/2219. Maximum Sum Score of Array/2219.java new file mode 100644 index 00000000000..8a5cf19c018 --- /dev/null +++ b/solutions/2219. Maximum Sum Score of Array/2219.java @@ -0,0 +1,14 @@ +class Solution { + public long maximumSumScore(int[] nums) { + long ans = Long.MIN_VALUE; + long prefix = 0; + long sum = Arrays.stream(nums).asLongStream().sum(); + + for (final int num : nums) { + prefix += num; + ans = Math.max(ans, Math.max(prefix, sum - prefix + num)); + } + + return ans; + } +} diff --git a/solutions/2219. Maximum Sum Score of Array/2219.py b/solutions/2219. Maximum Sum Score of Array/2219.py new file mode 100644 index 00000000000..93b52246fb9 --- /dev/null +++ b/solutions/2219. Maximum Sum Score of Array/2219.py @@ -0,0 +1,11 @@ +class Solution: + def maximumSumScore(self, nums: List[int]) -> int: + ans = -math.inf + prefix = 0 + summ = sum(nums) + + for num in nums: + prefix += num + ans = max(ans, prefix, summ - prefix + num) + + return ans diff --git a/solutions/222. Count Complete Tree Nodes/222-2.cpp b/solutions/222. Count Complete Tree Nodes/222-2.cpp new file mode 100644 index 00000000000..8f26742a98a --- /dev/null +++ b/solutions/222. Count Complete Tree Nodes/222-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int countNodes(TreeNode* root) { + if (root == nullptr) + return 0; + + TreeNode* left = root; + TreeNode* right = root; + int heightL = 0; + int heightR = 0; + + while (left != nullptr) { + ++heightL; + left = left->left; + } + + while (right != nullptr) { + ++heightR; + right = right->right; + } + + if (heightL == heightR) // `root` is a complete tree. + return pow(2, heightL) - 1; + return 1 + countNodes(root->left) + countNodes(root->right); + } +}; diff --git a/solutions/222. Count Complete Tree Nodes/222-2.java b/solutions/222. Count Complete Tree Nodes/222-2.java new file mode 100644 index 00000000000..9da87da054b --- /dev/null +++ b/solutions/222. Count Complete Tree Nodes/222-2.java @@ -0,0 +1,25 @@ +class Solution { + public int countNodes(TreeNode root) { + if (root == null) + return 0; + + TreeNode left = root; + TreeNode right = root; + int heightL = 0; + int heightR = 0; + + while (left != null) { + ++heightL; + left = left.left; + } + + while (right != null) { + ++heightR; + right = right.right; + } + + if (heightL == heightR) // `root` is a complete tree. + return (int) Math.pow(2, heightL) - 1; + return 1 + countNodes(root.left) + countNodes(root.right); + } +} diff --git a/solutions/222. Count Complete Tree Nodes/222-2.py b/solutions/222. Count Complete Tree Nodes/222-2.py new file mode 100644 index 00000000000..e1de8344949 --- /dev/null +++ b/solutions/222. Count Complete Tree Nodes/222-2.py @@ -0,0 +1,21 @@ +class Solution: + def countNodes(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + left = root + right = root + heightL = 0 + heightR = 0 + + while left: + heightL += 1 + left = left.left + + while right: + heightR += 1 + right = right.right + + if heightL == heightR: # `root` is a complete tree. + return pow(2, heightL) - 1 + return 1 + self.countNodes(root.left) + self.countNodes(root.right) diff --git a/solutions/222. Count Complete Tree Nodes/222.cpp b/solutions/222. Count Complete Tree Nodes/222.cpp new file mode 100644 index 00000000000..caaf68f73ea --- /dev/null +++ b/solutions/222. Count Complete Tree Nodes/222.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int countNodes(TreeNode* root) { + if (root == nullptr) + return 0; + return 1 + countNodes(root->left) + countNodes(root->right); + } +}; diff --git a/solutions/222. Count Complete Tree Nodes/222.java b/solutions/222. Count Complete Tree Nodes/222.java new file mode 100644 index 00000000000..8119065365a --- /dev/null +++ b/solutions/222. Count Complete Tree Nodes/222.java @@ -0,0 +1,7 @@ +class Solution { + public int countNodes(TreeNode root) { + if (root == null) + return 0; + return 1 + countNodes(root.left) + countNodes(root.right); + } +} diff --git a/solutions/222. Count Complete Tree Nodes/222.py b/solutions/222. Count Complete Tree Nodes/222.py new file mode 100644 index 00000000000..255c6f2db0a --- /dev/null +++ b/solutions/222. Count Complete Tree Nodes/222.py @@ -0,0 +1,5 @@ +class Solution: + def countNodes(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + return 1 + self.countNodes(root.left) + self.countNodes(root.right) diff --git a/solutions/2220. Minimum Bit Flips to Convert Number/2220.cpp b/solutions/2220. Minimum Bit Flips to Convert Number/2220.cpp new file mode 100644 index 00000000000..dfdfa9073ea --- /dev/null +++ b/solutions/2220. Minimum Bit Flips to Convert Number/2220.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int minBitFlips(unsigned start, unsigned goal) { + return popcount(start ^ goal); + } +}; diff --git a/solutions/2220. Minimum Bit Flips to Convert Number/2220.java b/solutions/2220. Minimum Bit Flips to Convert Number/2220.java new file mode 100644 index 00000000000..fb8939cc146 --- /dev/null +++ b/solutions/2220. Minimum Bit Flips to Convert Number/2220.java @@ -0,0 +1,5 @@ +class Solution { + public int minBitFlips(int start, int goal) { + return Integer.bitCount(start ^ goal); + } +} diff --git a/solutions/2220. Minimum Bit Flips to Convert Number/2220.py b/solutions/2220. Minimum Bit Flips to Convert Number/2220.py new file mode 100644 index 00000000000..74852321165 --- /dev/null +++ b/solutions/2220. Minimum Bit Flips to Convert Number/2220.py @@ -0,0 +1,3 @@ +class Solution: + def minBitFlips(self, start: int, goal: int) -> int: + return (start ^ goal).bit_count() diff --git a/solutions/2221. Find Triangular Sum of an Array/2221.cpp b/solutions/2221. Find Triangular Sum of an Array/2221.cpp new file mode 100644 index 00000000000..3e9a9e7436d --- /dev/null +++ b/solutions/2221. Find Triangular Sum of an Array/2221.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int triangularSum(vector& nums) { + for (int sz = nums.size(); sz > 0; --sz) + for (int i = 0; i + 1 < sz; ++i) + nums[i] = (nums[i] + nums[i + 1]) % 10; + return nums[0]; + } +}; diff --git a/solutions/2221. Find Triangular Sum of an Array/2221.java b/solutions/2221. Find Triangular Sum of an Array/2221.java new file mode 100644 index 00000000000..544bc53a51e --- /dev/null +++ b/solutions/2221. Find Triangular Sum of an Array/2221.java @@ -0,0 +1,8 @@ +class Solution { + public int triangularSum(int[] nums) { + for (int sz = nums.length; sz > 0; --sz) + for (int i = 0; i + 1 < sz; ++i) + nums[i] = (nums[i] + nums[i + 1]) % 10; + return nums[0]; + } +} diff --git a/solutions/2221. Find Triangular Sum of an Array/2221.py b/solutions/2221. Find Triangular Sum of an Array/2221.py new file mode 100644 index 00000000000..ab07fe83d0e --- /dev/null +++ b/solutions/2221. Find Triangular Sum of an Array/2221.py @@ -0,0 +1,6 @@ +class Solution: + def triangularSum(self, nums: List[int]) -> int: + for sz in range(len(nums), 0, -1): + for i in range(sz - 1): + nums[i] = (nums[i] + nums[i + 1]) % 10 + return nums[0] diff --git a/solutions/2222. Number of Ways to Select Buildings/2222.cpp b/solutions/2222. Number of Ways to Select Buildings/2222.cpp new file mode 100644 index 00000000000..80871a3e765 --- /dev/null +++ b/solutions/2222. Number of Ways to Select Buildings/2222.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long numberOfWays(string s) { + long ans = 0; + // before[i] := the number of i before the current digit + vector before(2); + // after[i] := the number of i after the current digit + vector after(2); + after[0] = ranges::count(s, '0'); + after[1] = s.length() - after[0]; + + for (const char c : s) { + const int num = c - '0'; + --after[num]; + if (num == 0) + ans += before[1] * after[1]; + else + ans += before[0] * after[0]; + ++before[num]; + } + + return ans; + } +}; diff --git a/solutions/2222. Number of Ways to Select Buildings/2222.java b/solutions/2222. Number of Ways to Select Buildings/2222.java new file mode 100644 index 00000000000..a9c1a87969e --- /dev/null +++ b/solutions/2222. Number of Ways to Select Buildings/2222.java @@ -0,0 +1,23 @@ +class Solution { + public long numberOfWays(String s) { + long ans = 0; + // before[i] := the number of i before the current digit + int[] before = new int[2]; + // after[i] := the number of i after the current digit + int[] after = new int[2]; + after[0] = (int) s.chars().filter(c -> c == '0').count(); + after[1] = s.length() - after[0]; + + for (final char c : s.toCharArray()) { + final int num = c - '0'; + --after[num]; + if (num == 0) + ans += before[1] * after[1]; + else + ans += before[0] * after[0]; + ++before[num]; + } + + return ans; + } +} diff --git a/solutions/2222. Number of Ways to Select Buildings/2222.py b/solutions/2222. Number of Ways to Select Buildings/2222.py new file mode 100644 index 00000000000..a72199c2200 --- /dev/null +++ b/solutions/2222. Number of Ways to Select Buildings/2222.py @@ -0,0 +1,20 @@ +class Solution: + def numberOfWays(self, s: str) -> int: + ans = 0 + # before[i] := the number of i before the current digit + before = [0] * 2 + # after[i] := the number of i after the current digit + after = [0] * 2 + after[0] = s.count('0') + after[1] = len(s) - after[0] + + for c in s: + num = ord(c) - ord('0') + after[num] -= 1 + if num == 0: + ans += before[1] * after[1] + else: + ans += before[0] * after[0] + before[num] += 1 + + return ans diff --git a/solutions/2223. Sum of Scores of Built Strings/2223.cpp b/solutions/2223. Sum of Scores of Built Strings/2223.cpp new file mode 100644 index 00000000000..2a249fb1c96 --- /dev/null +++ b/solutions/2223. Sum of Scores of Built Strings/2223.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long sumScores(string s) { + const int n = s.length(); + // https://cp-algorithms.com/string/z-function.html#implementation + vector z(n); + // [l, r] := the indices of the rightmost segment match + int l = 0; + int r = 0; + + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = min(r - i, z[i - l]); + while (i + z[i] < n && s[z[i]] == s[i + z[i]]) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + + return accumulate(z.begin(), z.end(), 0L) + n; + } +}; diff --git a/solutions/2223. Sum of Scores of Built Strings/2223.java b/solutions/2223. Sum of Scores of Built Strings/2223.java new file mode 100644 index 00000000000..6389e8a762f --- /dev/null +++ b/solutions/2223. Sum of Scores of Built Strings/2223.java @@ -0,0 +1,23 @@ +class Solution { + public long sumScores(String s) { + final int n = s.length(); + // https://cp-algorithms.com/string/z-function.html#implementation + int[] z = new int[n]; + // [l, r] := the indices of the rightmost segment match + int l = 0; + int r = 0; + + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = Math.min(r - i, z[i - l]); + while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + + return Arrays.stream(z).asLongStream().sum() + n; + } +} diff --git a/solutions/2223. Sum of Scores of Built Strings/2223.py b/solutions/2223. Sum of Scores of Built Strings/2223.py new file mode 100644 index 00000000000..272c1b29dad --- /dev/null +++ b/solutions/2223. Sum of Scores of Built Strings/2223.py @@ -0,0 +1,19 @@ +class Solution: + def sumScores(self, s: str) -> int: + n = len(s) + # https://cp-algorithms.com/string/z-function.html#implementation + z = [0] * n + # [l, r] := the indices of the rightmost segment match + l = 0 + r = 0 + + for i in range(1, n): + if i < r: + z[i] = min(r - i, z[i - l]) + while i + z[i] < n and s[z[i]] == s[i + z[i]]: + z[i] += 1 + if i + z[i] > r: + l = i + r = i + z[i] + + return sum(z) + n diff --git a/solutions/2224. Minimum Number of Operations to Convert Time/2224.cpp b/solutions/2224. Minimum Number of Operations to Convert Time/2224.cpp new file mode 100644 index 00000000000..07373c087c5 --- /dev/null +++ b/solutions/2224. Minimum Number of Operations to Convert Time/2224.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int convertTime(string current, string correct) { + const vector ops{60, 15, 5, 1}; + int diff = getMinutes(correct) - getMinutes(current); + int ans = 0; + + for (const int op : ops) { + ans += diff / op; + diff %= op; + } + + return ans; + } + + private: + int getMinutes(const string& s) { + return stoi(s.substr(0, 2)) * 60 + stoi(s.substr(3)); + } +}; diff --git a/solutions/2224. Minimum Number of Operations to Convert Time/2224.java b/solutions/2224. Minimum Number of Operations to Convert Time/2224.java new file mode 100644 index 00000000000..2516b505339 --- /dev/null +++ b/solutions/2224. Minimum Number of Operations to Convert Time/2224.java @@ -0,0 +1,18 @@ +class Solution { + public int convertTime(String current, String correct) { + final int[] ops = {60, 15, 5, 1}; + int diff = getMinutes(correct) - getMinutes(current); + int ans = 0; + + for (final int op : ops) { + ans += diff / op; + diff %= op; + } + + return ans; + } + + private int getMinutes(final String s) { + return Integer.parseInt(s.substring(0, 2)) * 60 + Integer.parseInt(s.substring(3)); + } +} diff --git a/solutions/2224. Minimum Number of Operations to Convert Time/2224.py b/solutions/2224. Minimum Number of Operations to Convert Time/2224.py new file mode 100644 index 00000000000..b630f07b2bf --- /dev/null +++ b/solutions/2224. Minimum Number of Operations to Convert Time/2224.py @@ -0,0 +1,15 @@ +class Solution: + def convertTime(self, current: str, correct: str) -> int: + ops = [60, 15, 5, 1] + + def getMinutes(s: str) -> int: + return int(s[:2]) * 60 + int(s[3:]) + + diff = getMinutes(correct) - getMinutes(current) + ans = 0 + + for op in ops: + ans += diff // op + diff %= op + + return ans diff --git a/solutions/2225. Find Players With Zero or One Losses/2225.cpp b/solutions/2225. Find Players With Zero or One Losses/2225.cpp new file mode 100644 index 00000000000..bcfb9ac7119 --- /dev/null +++ b/solutions/2225. Find Players With Zero or One Losses/2225.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector> findWinners(vector>& matches) { + vector> ans(2); + map lossesCount; + + for (const vector& m : matches) { + const int winner = m[0]; + const int loser = m[1]; + if (!lossesCount.contains(winner)) + lossesCount[winner] = 0; + ++lossesCount[loser]; + } + + for (const auto& [player, nLosses] : lossesCount) + if (nLosses < 2) + ans[nLosses].push_back(player); + + return ans; + } +}; diff --git a/solutions/2225. Find Players With Zero or One Losses/2225.java b/solutions/2225. Find Players With Zero or One Losses/2225.java new file mode 100644 index 00000000000..3b79c052a3e --- /dev/null +++ b/solutions/2225. Find Players With Zero or One Losses/2225.java @@ -0,0 +1,22 @@ +class Solution { + public List> findWinners(int[][] matches) { + List> ans = Arrays.asList(new ArrayList<>(), new ArrayList<>()); + Map lossesCount = new TreeMap<>(); + + for (int[] m : matches) { + final int winner = m[0]; + final int loser = m[1]; + if (!lossesCount.containsKey(winner)) + lossesCount.put(winner, 0); + lossesCount.merge(loser, 1, Integer::sum); + } + + for (final int player : lossesCount.keySet()) { + final int nLosses = lossesCount.get(player); + if (nLosses < 2) + ans.get(nLosses).add(player); + } + + return ans; + } +} diff --git a/solutions/2225. Find Players With Zero or One Losses/2225.py b/solutions/2225. Find Players With Zero or One Losses/2225.py new file mode 100644 index 00000000000..0b415444d42 --- /dev/null +++ b/solutions/2225. Find Players With Zero or One Losses/2225.py @@ -0,0 +1,15 @@ +class Solution: + def findWinners(self, matches: List[List[int]]) -> List[List[int]]: + ans = [[] for _ in range(2)] + lossesCount = collections.Counter() + + for winner, loser in matches: + if winner not in lossesCount: + lossesCount[winner] = 0 + lossesCount[loser] += 1 + + for player, nLosses in lossesCount.items(): + if nLosses < 2: + ans[nLosses].append(player) + + return [sorted(ans[0]), sorted(ans[1])] diff --git a/solutions/2226. Maximum Candies Allocated to K Children/2226.cpp b/solutions/2226. Maximum Candies Allocated to K Children/2226.cpp new file mode 100644 index 00000000000..b21c85fda9c --- /dev/null +++ b/solutions/2226. Maximum Candies Allocated to K Children/2226.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int maximumCandies(vector& candies, long long k) { + int l = 1; + int r = accumulate(candies.begin(), candies.end(), 0L) / k; + + while (l < r) { + const int m = (l + r) / 2; + if (numChildren(candies, m) < k) + r = m; + else + l = m + 1; + } + + return numChildren(candies, l) >= k ? l : l - 1; + } + + private: + long numChildren(const vector& candies, int m) { + return accumulate(candies.begin(), candies.end(), 0L, + [&](long subtotal, int c) { return subtotal + c / m; }); + }; +}; diff --git a/solutions/2226. Maximum Candies Allocated to K Children/2226.java b/solutions/2226. Maximum Candies Allocated to K Children/2226.java new file mode 100644 index 00000000000..1b8e02e3e7f --- /dev/null +++ b/solutions/2226. Maximum Candies Allocated to K Children/2226.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumCandies(int[] candies, long k) { + int l = 1; + int r = (int) (Arrays.stream(candies).asLongStream().sum() / k); + + while (l < r) { + final int m = (l + r) / 2; + if (numChildren(candies, m) < k) + r = m; + else + l = m + 1; + } + + return numChildren(candies, l) >= k ? l : l - 1; + } + + private long numChildren(int[] candies, int m) { + return Arrays.stream(candies).asLongStream().reduce(0L, (subtotal, c) -> subtotal + c / m); + } +} diff --git a/solutions/2226. Maximum Candies Allocated to K Children/2226.py b/solutions/2226. Maximum Candies Allocated to K Children/2226.py new file mode 100644 index 00000000000..a3c245035a7 --- /dev/null +++ b/solutions/2226. Maximum Candies Allocated to K Children/2226.py @@ -0,0 +1,16 @@ +class Solution: + def maximumCandies(self, candies: List[int], k: int) -> int: + l = 1 + r = sum(candies) // k + + def numChildren(m: int) -> bool: + return sum(c // m for c in candies) + + while l < r: + m = (l + r) // 2 + if numChildren(m) < k: + r = m + else: + l = m + 1 + + return l if numChildren(l) >= k else l - 1 diff --git a/solutions/2227. Encrypt and Decrypt Strings/2227-2.cpp b/solutions/2227. Encrypt and Decrypt Strings/2227-2.cpp new file mode 100644 index 00000000000..bc890136951 --- /dev/null +++ b/solutions/2227. Encrypt and Decrypt Strings/2227-2.cpp @@ -0,0 +1,26 @@ +class Encrypter { + public: + Encrypter(vector& keys, vector& values, + vector& dictionary) { + for (int i = 0; i < keys.size(); ++i) + keyToValue[keys[i]] = values[i]; + + for (const string& word : dictionary) + ++encryptedCount[encrypt(word)]; + } + + string encrypt(string word1) { + string ans; + for (const char c : word1) + ans += keyToValue[c]; + return ans; + } + + int decrypt(string word2) { + return encryptedCount[word2]; + } + + private: + unordered_map keyToValue; + unordered_map encryptedCount; +}; diff --git a/solutions/2227. Encrypt and Decrypt Strings/2227-2.java b/solutions/2227. Encrypt and Decrypt Strings/2227-2.java new file mode 100644 index 00000000000..8c317aaeaeb --- /dev/null +++ b/solutions/2227. Encrypt and Decrypt Strings/2227-2.java @@ -0,0 +1,23 @@ +class Encrypter { + public Encrypter(char[] keys, String[] values, String[] dictionary) { + for (int i = 0; i < keys.length; ++i) + keyToValue.put(keys[i], values[i]); + + for (final String word : dictionary) + encryptedCount.merge(encrypt(word), 1, Integer::sum); + } + + public String encrypt(String word1) { + StringBuilder sb = new StringBuilder(); + for (final char c : word1.toCharArray()) + sb.append(keyToValue.get(c)); + return sb.toString(); + } + + public int decrypt(String word2) { + return encryptedCount.getOrDefault(word2, 0); + } + + private Map keyToValue = new HashMap<>(); + private Map encryptedCount = new HashMap<>(); +} diff --git a/solutions/2227. Encrypt and Decrypt Strings/2227-2.py b/solutions/2227. Encrypt and Decrypt Strings/2227-2.py new file mode 100644 index 00000000000..a2a3804cddc --- /dev/null +++ b/solutions/2227. Encrypt and Decrypt Strings/2227-2.py @@ -0,0 +1,8 @@ +class Encrypter: + def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): + self.keyToValue = {k: v for k, v in zip(keys, values)} + self.decrypt = collections.Counter(self.encrypt(word) + for word in dictionary).__getitem__ + + def encrypt(self, word1: str) -> str: + return ''.join(self.keyToValue[c] for c in word1) diff --git a/solutions/2227. Encrypt and Decrypt Strings/2227.cpp b/solutions/2227. Encrypt and Decrypt Strings/2227.cpp new file mode 100644 index 00000000000..b6a4456ca32 --- /dev/null +++ b/solutions/2227. Encrypt and Decrypt Strings/2227.cpp @@ -0,0 +1,70 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class Encrypter { + public: + Encrypter(vector& keys, vector& values, + vector& dictionary) { + for (int i = 0; i < keys.size(); ++i) { + const char key = keys[i]; + const string& value = values[i]; + keyToValue[key] = value; + valueToKeys[value].push_back(key); + } + for (const string& word : dictionary) + insert(word); + } + + string encrypt(string word1) { + string ans; + for (const char c : word1) + ans += keyToValue[c]; + return ans; + } + + int decrypt(string word2) { + return find(word2, 0, root); + } + + private: + unordered_map keyToValue; + unordered_map> valueToKeys; + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->isWord = true; + } + + int find(const string& word, int i, shared_ptr node) { + const string value = word.substr(i, 2); + if (!valueToKeys.contains(value)) + return 0; + + int ans = 0; + if (i + 2 == word.length()) { + for (const char key : valueToKeys[value]) { + const auto& child = node->children[key - 'a']; + ans += child && child->isWord; + } + return ans; + } + + for (const char key : valueToKeys[value]) { + if (!node->children[key - 'a']) + continue; + ans += find(word, i + 2, node->children[key - 'a']); + } + + return ans; + } +}; diff --git a/solutions/2227. Encrypt and Decrypt Strings/2227.java b/solutions/2227. Encrypt and Decrypt Strings/2227.java new file mode 100644 index 00000000000..315ab55f3df --- /dev/null +++ b/solutions/2227. Encrypt and Decrypt Strings/2227.java @@ -0,0 +1,68 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class Encrypter { + public Encrypter(char[] keys, String[] values, String[] dictionary) { + for (int i = 0; i < keys.length; ++i) { + final char key = keys[i]; + final String value = values[i]; + keyToValue.put(key, value); + valueToKeys.putIfAbsent(value, new ArrayList<>()); + valueToKeys.get(value).add(key); + } + for (final String word : dictionary) + insert(word); + } + + public String encrypt(String word1) { + StringBuilder sb = new StringBuilder(); + for (final char c : word1.toCharArray()) + sb.append(keyToValue.get(c)); + return sb.toString(); + } + + public int decrypt(String word2) { + return find(word2, 0, root); + } + + private Map keyToValue = new HashMap<>(); + private Map> valueToKeys = new HashMap<>(); + private TrieNode root = new TrieNode(); + + void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + int find(final String word, int i, TrieNode node) { + final String value = word.substring(i, i + 2); + if (!valueToKeys.containsKey(value)) + return 0; + + int ans = 0; + if (i + 2 == word.length()) { + for (final char key : valueToKeys.get(value)) { + TrieNode child = node.children[key - 'a']; + if (child != null && child.isWord) + ++ans; + } + return ans; + } + + for (final char key : valueToKeys.get(value)) { + if (node.children[key - 'a'] == null) + continue; + ans += find(word, i + 2, node.children[key - 'a']); + } + + return ans; + } +} diff --git a/solutions/2227. Encrypt and Decrypt Strings/2227.py b/solutions/2227. Encrypt and Decrypt Strings/2227.py new file mode 100644 index 00000000000..7b371957a32 --- /dev/null +++ b/solutions/2227. Encrypt and Decrypt Strings/2227.py @@ -0,0 +1,45 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode) + self.isWord = False + + +class Encrypter: + def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): + self.keyToValue = {k: v for k, v in zip(keys, values)} + self.valueToKeys = collections.defaultdict(list) + self.root = TrieNode() + for k, v in zip(keys, values): + self.valueToKeys[v].append(k) + for word in dictionary: + self._insert(word) + + def encrypt(self, word1: str) -> str: + return ''.join(self.keyToValue[c] for c in word1) + + def decrypt(self, word2: str) -> int: + return self._find(word2, 0, self.root) + + def _insert(self, word: str) -> None: + node = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + def _find(self, word: str, i: int, node: TrieNode) -> int: + value = word[i:i + 2] + if value not in self.valueToKeys: + return 0 + + ans = 0 + if i + 2 == len(word): + for key in self.valueToKeys[value]: + ans += node.children[key].isWord + return ans + + for key in self.valueToKeys[value]: + if key not in node.children: + continue + ans += self._find(word, i + 2, node.children[key]) + + return ans diff --git a/solutions/2228. Users With Two Purchases Within Seven Days/2228.sql b/solutions/2228. Users With Two Purchases Within Seven Days/2228.sql new file mode 100644 index 00000000000..071d7d1a637 --- /dev/null +++ b/solutions/2228. Users With Two Purchases Within Seven Days/2228.sql @@ -0,0 +1,9 @@ +SELECT DISTINCT First.user_id +FROM Purchases AS First +INNER JOIN purchases AS Second + USING (user_id) +WHERE + First.purchase_id != Second.purchase_id + AND First.purchase_date <= Second.purchase_date + AND DATEDIFF(Second.purchase_date, First.purchase_date) <= 7 +ORDER BY 1; diff --git a/solutions/2229. Check if an Array Is Consecutive/2229.cpp b/solutions/2229. Check if an Array Is Consecutive/2229.cpp new file mode 100644 index 00000000000..b7aa14c7f00 --- /dev/null +++ b/solutions/2229. Check if an Array Is Consecutive/2229.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + bool isConsecutive(vector& nums) { + const int n = nums.size(); + const int mx = ranges::max(nums); + const int mn = ranges::min(nums); + return mx - mn + 1 == n && + unordered_set{nums.begin(), nums.end()}.size() == n; + } +}; diff --git a/solutions/2229. Check if an Array Is Consecutive/2229.java b/solutions/2229. Check if an Array Is Consecutive/2229.java new file mode 100644 index 00000000000..2efc8f2d37f --- /dev/null +++ b/solutions/2229. Check if an Array Is Consecutive/2229.java @@ -0,0 +1,8 @@ +class Solution { + public boolean isConsecutive(int[] nums) { + final int n = nums.length; + final int mx = Arrays.stream(nums).max().getAsInt(); + final int mn = Arrays.stream(nums).min().getAsInt(); + return mx - mn + 1 == n && Arrays.stream(nums).boxed().collect(Collectors.toSet()).size() == n; + } +} diff --git a/solutions/2229. Check if an Array Is Consecutive/2229.py b/solutions/2229. Check if an Array Is Consecutive/2229.py new file mode 100644 index 00000000000..0e120086192 --- /dev/null +++ b/solutions/2229. Check if an Array Is Consecutive/2229.py @@ -0,0 +1,3 @@ +class Solution: + def isConsecutive(self, nums: List[int]) -> bool: + return max(nums) - min(nums) + 1 == len(set(nums)) == len(nums) diff --git a/solutions/223. Rectangle Area/223.cpp b/solutions/223. Rectangle Area/223.cpp new file mode 100644 index 00000000000..f696bd85a94 --- /dev/null +++ b/solutions/223. Rectangle Area/223.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int computeArea(long A, long B, long C, long D, // + long E, long F, long G, long H) { + const long x = max(A, E) < min(C, G) ? (min(C, G) - max(A, E)) : 0; + const long y = max(B, F) < min(D, H) ? (min(D, H) - max(B, F)) : 0; + return (C - A) * (D - B) + (G - E) * (H - F) - x * y; + } +}; diff --git a/solutions/223. Rectangle Area/223.java b/solutions/223. Rectangle Area/223.java new file mode 100644 index 00000000000..50e55aa533b --- /dev/null +++ b/solutions/223. Rectangle Area/223.java @@ -0,0 +1,7 @@ +class Solution { + public int computeArea(long A, long B, long C, long D, long E, long F, long G, long H) { + final long x = Math.max(A, E) < Math.min(C, G) ? (Math.min(C, G) - Math.max(A, E)) : 0; + final long y = Math.max(B, F) < Math.min(D, H) ? (Math.min(D, H) - Math.max(B, F)) : 0; + return (int) ((C - A) * (D - B) + (G - E) * (H - F) - x * y); + } +} diff --git a/solutions/223. Rectangle Area/223.py b/solutions/223. Rectangle Area/223.py new file mode 100644 index 00000000000..fd6ac77c285 --- /dev/null +++ b/solutions/223. Rectangle Area/223.py @@ -0,0 +1,5 @@ +class Solution: + def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: + x = min(C, G) - max(A, E) if max(A, E) < min(C, G) else 0 + y = min(D, H) - max(B, F) if max(B, F) < min(D, H) else 0 + return (C - A) * (D - B) + (G - E) * (H - F) - x * y diff --git a/solutions/2230. The Users That Are Eligible for Discount/2230.sql b/solutions/2230. The Users That Are Eligible for Discount/2230.sql new file mode 100644 index 00000000000..e8b0033d02e --- /dev/null +++ b/solutions/2230. The Users That Are Eligible for Discount/2230.sql @@ -0,0 +1,9 @@ +CREATE PROCEDURE getUserIDs(startDate DATE, endDate DATE, minAmount INT) +BEGIN + SELECT DISTINCT user_id + FROM Purchases + WHERE + time_stamp BETWEEN startDate AND endDate + AND amount >= minAmount + ORDER BY 1; +END diff --git a/solutions/2231. Largest Number After Digit Swaps by Parity/2231.cpp b/solutions/2231. Largest Number After Digit Swaps by Parity/2231.cpp new file mode 100644 index 00000000000..82540159ec0 --- /dev/null +++ b/solutions/2231. Largest Number After Digit Swaps by Parity/2231.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int largestInteger(int num) { + const string s = to_string(num); + int ans = 0; + // maxHeap[0] := the odd digits + // maxHeap[1] := the even digits + vector> maxHeap(2); + + for (const char c : s) { + const int digit = c - '0'; + maxHeap[digit % 2].push(digit); + } + + for (const char c : s) { + const int i = c - '0' & 1; + ans *= 10; + ans += maxHeap[i].top(), maxHeap[i].pop(); + } + + return ans; + } +}; diff --git a/solutions/2231. Largest Number After Digit Swaps by Parity/2231.java b/solutions/2231. Largest Number After Digit Swaps by Parity/2231.java new file mode 100644 index 00000000000..801be1a89e7 --- /dev/null +++ b/solutions/2231. Largest Number After Digit Swaps by Parity/2231.java @@ -0,0 +1,24 @@ +class Solution { + public int largestInteger(int num) { + final String s = String.valueOf(num); + int ans = 0; + // maxHeap[0] := the odd digits + // maxHeap[1] := the even digits + Queue[] maxHeap = new Queue[2]; + + for (int i = 0; i < 2; ++i) + maxHeap[i] = new PriorityQueue<>(Comparator.reverseOrder()); + + for (final char c : s.toCharArray()) { + final int digit = c - '0'; + maxHeap[digit % 2].offer(digit); + } + + for (final char c : s.toCharArray()) { + final int i = c - '0' & 1; + ans = (ans * 10 + maxHeap[i].poll()); + } + + return ans; + } +} diff --git a/solutions/2231. Largest Number After Digit Swaps by Parity/2231.py b/solutions/2231. Largest Number After Digit Swaps by Parity/2231.py new file mode 100644 index 00000000000..cf13692cab9 --- /dev/null +++ b/solutions/2231. Largest Number After Digit Swaps by Parity/2231.py @@ -0,0 +1,17 @@ +class Solution: + def largestInteger(self, num: int) -> int: + s = str(num) + ans = 0 + # maxHeap[0] := the odd digits + # maxHeap[1] := the even digits + maxHeap = [[] for _ in range(2)] + + for c in s: + digit = ord(c) - ord('0') + heapq.heappush(maxHeap[digit % 2], -digit) + + for c in s: + i = ord(c) - ord('0') & 1 + ans = (ans * 10 - heapq.heappop(maxHeap[i])) + + return ans diff --git a/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.cpp b/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.cpp new file mode 100644 index 00000000000..0e74f152cbe --- /dev/null +++ b/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + string minimizeResult(string expression) { + const int plusIndex = expression.find('+'); + const string left = expression.substr(0, plusIndex); + const string right = expression.substr(plusIndex + 1); + string ans; + int mn = INT_MAX; + + // the expression -> a * (b + c) * d + for (int i = 0; i < left.length(); ++i) + for (int j = 0; j < right.length(); ++j) { + const int a = i == 0 ? 1 : stoi(left.substr(0, i)); + const int b = stoi(left.substr(i)); + const int c = stoi(right.substr(0, j + 1)); + const int d = j == right.length() - 1 ? 1 : stoi(right.substr(j + 1)); + const int val = a * (b + c) * d; + if (val < mn) { + mn = val; + ans = (i == 0 ? "" : to_string(a)) + '(' + to_string(b) + '+' + + to_string(c) + ')' + + (j == right.length() - 1 ? "" : to_string(d)); + } + } + + return ans; + } +}; diff --git a/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.java b/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.java new file mode 100644 index 00000000000..55ea7b95ea4 --- /dev/null +++ b/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.java @@ -0,0 +1,26 @@ +class Solution { + public String minimizeResult(String expression) { + final int plusIndex = expression.indexOf('+'); + final String left = expression.substring(0, plusIndex); + final String right = expression.substring(plusIndex + 1); + String ans = ""; + int mn = Integer.MAX_VALUE; + + // the expression -> a * (b + c) * d + for (int i = 0; i < left.length(); ++i) + for (int j = 0; j < right.length(); ++j) { + final int a = i == 0 ? 1 : Integer.parseInt(left.substring(0, i)); + final int b = Integer.parseInt(left.substring(i)); + final int c = Integer.parseInt(right.substring(0, j + 1)); + final int d = j == right.length() - 1 ? 1 : Integer.parseInt(right.substring(j + 1)); + final int val = a * (b + c) * d; + if (val < mn) { + mn = val; + ans = (i == 0 ? "" : String.valueOf(a)) + '(' + String.valueOf(b) + '+' + + String.valueOf(c) + ')' + (j == right.length() - 1 ? "" : String.valueOf(d)); + } + } + + return ans; + } +} diff --git a/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.py b/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.py new file mode 100644 index 00000000000..4ec90471ae9 --- /dev/null +++ b/solutions/2232. Minimize Result by Adding Parentheses to Expression/2232.py @@ -0,0 +1,23 @@ +class Solution: + def minimizeResult(self, expression: str) -> str: + plusIndex = expression.index('+') + left = expression[:plusIndex] + right = expression[plusIndex + 1:] + ans = '' + mn = math.inf + + # the expression -> a * (b + c) * d + for i in range(len(left)): + for j in range(len(right)): + a = 1 if i == 0 else int(left[:i]) + b = int(left[i:]) + c = int(right[0:j + 1]) + d = 1 if j == len(right) - 1 else int(right[j + 1:]) + val = a * (b + c) * d + if val < mn: + mn = val + ans = ('' if i == 0 else str(a)) + \ + '(' + str(b) + '+' + str(c) + ')' + \ + ('' if j == len(right) - 1 else str(d)) + + return ans diff --git a/solutions/2233. Maximum Product After K Increments/2233.cpp b/solutions/2233. Maximum Product After K Increments/2233.cpp new file mode 100644 index 00000000000..a610f76c17e --- /dev/null +++ b/solutions/2233. Maximum Product After K Increments/2233.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int maximumProduct(vector& nums, int k) { + constexpr int kMod = 1'000'000'007; + long ans = 1; + priority_queue, greater<>> minHeap; + + for (const int num : nums) + minHeap.push(num); + + for (int i = 0; i < k; ++i) { + const int minNum = minHeap.top(); + minHeap.pop(); + minHeap.push(minNum + 1); + } + + while (!minHeap.empty()) { + ans *= minHeap.top(), minHeap.pop(); + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/2233. Maximum Product After K Increments/2233.java b/solutions/2233. Maximum Product After K Increments/2233.java new file mode 100644 index 00000000000..e04be16a746 --- /dev/null +++ b/solutions/2233. Maximum Product After K Increments/2233.java @@ -0,0 +1,22 @@ +class Solution { + public int maximumProduct(int[] nums, int k) { + final int kMod = 1_000_000_007; + long ans = 1; + Queue minHeap = new PriorityQueue<>(); + + for (final int num : nums) + minHeap.offer(num); + + for (int i = 0; i < k; ++i) { + final int minNum = minHeap.poll(); + minHeap.offer(minNum + 1); + } + + while (!minHeap.isEmpty()) { + ans *= minHeap.poll(); + ans %= kMod; + } + + return (int) ans; + } +} diff --git a/solutions/2233. Maximum Product After K Increments/2233.py b/solutions/2233. Maximum Product After K Increments/2233.py new file mode 100644 index 00000000000..b3cb648f6d1 --- /dev/null +++ b/solutions/2233. Maximum Product After K Increments/2233.py @@ -0,0 +1,16 @@ +class Solution: + def maximumProduct(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + ans = 1 + minHeap = nums.copy() + heapq.heapify(minHeap) + + for _ in range(k): + minNum = heapq.heappop(minHeap) + heapq.heappush(minHeap, minNum + 1) + + while minHeap: + ans *= heapq.heappop(minHeap) + ans %= kMod + + return ans diff --git a/solutions/2234. Maximum Total Beauty of the Gardens/2234.cpp b/solutions/2234. Maximum Total Beauty of the Gardens/2234.cpp new file mode 100644 index 00000000000..eb1846d4dc4 --- /dev/null +++ b/solutions/2234. Maximum Total Beauty of the Gardens/2234.cpp @@ -0,0 +1,55 @@ +class Solution { + public: + long long maximumBeauty(vector& flowers, long long newFlowers, + int target, int full, int partial) { + const int n = flowers.size(); + + // If a garden is already complete, clamp it to the target. + for (int& flower : flowers) + flower = min(flower, target); + ranges::sort(flowers); + + // All gardens are complete, so nothing we can do. + if (flowers[0] == target) + return static_cast(n) * full; + + // Having many new flowers maximizes the beauty value. + if (newFlowers >= static_cast(n) * target - + accumulate(flowers.begin(), flowers.end(), 0L)) + return max(static_cast(n) * full, + (n - 1L) * full + (target - 1L) * partial); + + long ans = 0; + long leftFlowers = newFlowers; + // cost[i] := the cost to make flowers[0..i] the same + vector cost(n); + + for (int i = 1; i < n; ++i) + // Plant (flowers[i] - flowers[i - 1]) flowers for flowers[0..i - 1]. + cost[i] = + cost[i - 1] + static_cast(i) * (flowers[i] - flowers[i - 1]); + + int i = n - 1; // flowers' index (flowers[i + 1..n) are complete) + while (flowers[i] == target) + --i; + + for (; leftFlowers >= 0; --i) { + // To maximize the minimum number of incomplete flowers, we find the first + // index j that we can't make flowers[0..j] equal to flowers[j], then we + // know we can make flowers[0..j - 1] equal to flowers[j - 1]. In the + // meantime, evenly increase each of them to seek a bigger minimum value. + const int j = firstGreater(cost, i, leftFlowers); + const long minIncomplete = + flowers[j - 1] + (leftFlowers - cost[j - 1]) / j; + ans = max(ans, (n - 1L - i) * full + minIncomplete * partial); + leftFlowers -= max(0, target - flowers[i]); + } + + return ans; + } + + private: + int firstGreater(const vector& A, int maxIndex, long target) { + return upper_bound(A.begin(), A.begin() + maxIndex + 1, target) - A.begin(); + } +}; diff --git a/solutions/2234. Maximum Total Beauty of the Gardens/2234.java b/solutions/2234. Maximum Total Beauty of the Gardens/2234.java new file mode 100644 index 00000000000..5885f13d3b7 --- /dev/null +++ b/solutions/2234. Maximum Total Beauty of the Gardens/2234.java @@ -0,0 +1,49 @@ +class Solution { + public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) { + final int n = flowers.length; + + // If a garden is already complete, clamp it to the target. + for (int i = 0; i < n; ++i) + flowers[i] = Math.min(flowers[i], target); + Arrays.sort(flowers); + + // All gardens are complete, so nothing we can do. + if (flowers[0] == target) + return (long) n * full; + + // Having many new flowers maximizes the beauty value. + if (newFlowers >= (long) n * target - Arrays.stream(flowers).asLongStream().sum()) + return Math.max((long) n * full, (n - 1L) * full + (target - 1L) * partial); + + long ans = 0; + long leftFlowers = newFlowers; + // cost[i] := the cost to make flowers[0..i] the same + long[] cost = new long[flowers.length]; + + for (int i = 1; i < flowers.length; ++i) + // Plant (flowers[i] - flowers[i - 1]) flowers for flowers[0..i - 1]. + cost[i] = cost[i - 1] + i * (flowers[i] - flowers[i - 1]); + + int i = flowers.length - 1; // flowers' index (flowers[i + 1..n) are complete) + while (flowers[i] == target) + --i; + + for (; leftFlowers >= 0; --i) { + // To maximize the minimum number of incomplete flowers, we find the first + // index j that we can't make flowers[0..j] equal to flowers[j], then we + // know we can make flowers[0..j - 1] equal to flowers[j - 1]. In the + // meantime, evenly increase each of them to seek a bigger minimum value. + final int j = firstGreater(cost, i, leftFlowers); + final long minIncomplete = flowers[j - 1] + (leftFlowers - cost[j - 1]) / j; + ans = Math.max(ans, (n - 1L - i) * full + (long) minIncomplete * partial); + leftFlowers -= Math.max(0, target - flowers[i]); + } + + return ans; + } + + private int firstGreater(long[] A, int maxIndex, long target) { + final int i = Arrays.binarySearch(A, 0, maxIndex + 1, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2234. Maximum Total Beauty of the Gardens/2234.py b/solutions/2234. Maximum Total Beauty of the Gardens/2234.py new file mode 100644 index 00000000000..549fe66fb62 --- /dev/null +++ b/solutions/2234. Maximum Total Beauty of the Gardens/2234.py @@ -0,0 +1,41 @@ +class Solution: + def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int: + n = len(flowers) + + # If a garden is already complete, clamp it to the target. + flowers = [min(flower, target) for flower in flowers] + flowers.sort() + + # All gardens are complete, so nothing we can do. + if flowers[0] == target: + return n * full + + # Having many new flowers maximizes the beauty value. + if newFlowers >= n * target - sum(flowers): + return max(n * full, (n - 1) * full + (target - 1) * partial) + + ans = 0 + leftFlowers = newFlowers + # cost[i] := the cost to make flowers[0..i] the same + cost = [0] * n + + for i in range(1, n): + # Plant (flowers[i] - flowers[i - 1]) flowers for flowers[0..i - 1]. + cost[i] = cost[i - 1] + i * (flowers[i] - flowers[i - 1]) + + i = n - 1 # flowers' index (flowers[i + 1..n) are complete) + while flowers[i] == target: + i -= 1 + + while leftFlowers >= 0: + # To maximize the minimum number of incomplete flowers, we find the first + # index j that we can't make flowers[0..j] equal to flowers[j], then we + # know we can make flowers[0..j - 1] equal to flowers[j - 1]. In the + # meantime, evenly increase each of them to seek a bigger minimum value. + j = min(i + 1, bisect_right(cost, leftFlowers)) + minIncomplete = flowers[j - 1] + (leftFlowers - cost[j - 1]) // j + ans = max(ans, (n - 1 - i) * full + minIncomplete * partial) + leftFlowers -= max(0, target - flowers[i]) + i -= 1 + + return ans diff --git a/solutions/2235. Add Two Integers/2235.cpp b/solutions/2235. Add Two Integers/2235.cpp new file mode 100644 index 00000000000..6f3fb4bb351 --- /dev/null +++ b/solutions/2235. Add Two Integers/2235.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int sum(int num1, int num2) { + return num1 + num2; + } +}; diff --git a/solutions/2235. Add Two Integers/2235.java b/solutions/2235. Add Two Integers/2235.java new file mode 100644 index 00000000000..623e15c6549 --- /dev/null +++ b/solutions/2235. Add Two Integers/2235.java @@ -0,0 +1,5 @@ +class Solution { + public int sum(int num1, int num2) { + return num1 + num2; + } +} diff --git a/solutions/2235. Add Two Integers/2235.py b/solutions/2235. Add Two Integers/2235.py new file mode 100644 index 00000000000..bfd0ca7411f --- /dev/null +++ b/solutions/2235. Add Two Integers/2235.py @@ -0,0 +1,2 @@ +class Solution: + sum = operator.add diff --git a/solutions/2236. Root Equals Sum of Children/2236.cpp b/solutions/2236. Root Equals Sum of Children/2236.cpp new file mode 100644 index 00000000000..5c83d5ef330 --- /dev/null +++ b/solutions/2236. Root Equals Sum of Children/2236.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool checkTree(TreeNode* root) { + return root->val == root->left->val + root->right->val; + } +}; diff --git a/solutions/2236. Root Equals Sum of Children/2236.java b/solutions/2236. Root Equals Sum of Children/2236.java new file mode 100644 index 00000000000..7e7f810aa3f --- /dev/null +++ b/solutions/2236. Root Equals Sum of Children/2236.java @@ -0,0 +1,5 @@ +class Solution { + public boolean checkTree(TreeNode root) { + return root.val == root.left.val + root.right.val; + } +} diff --git a/solutions/2236. Root Equals Sum of Children/2236.py b/solutions/2236. Root Equals Sum of Children/2236.py new file mode 100644 index 00000000000..957214c1962 --- /dev/null +++ b/solutions/2236. Root Equals Sum of Children/2236.py @@ -0,0 +1,3 @@ +class Solution: + def checkTree(self, root: Optional[TreeNode]) -> bool: + return root.val == root.left.val + root.right.val diff --git a/solutions/2237. Count Positions on Street With Required Brightness/2237.cpp b/solutions/2237. Count Positions on Street With Required Brightness/2237.cpp new file mode 100644 index 00000000000..2a7bb9c37c3 --- /dev/null +++ b/solutions/2237. Count Positions on Street With Required Brightness/2237.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int meetRequirement(int n, vector>& lights, + vector& requirement) { + int ans = 0; + int currBrightness = 0; + vector change(n + 1); + + for (const vector& light : lights) { + const int position = light[0]; + const int range = light[1]; + ++change[max(0, position - range)]; + --change[min(n, position + range + 1)]; + } + + for (int i = 0; i < n; ++i) { + currBrightness += change[i]; + if (currBrightness >= requirement[i]) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2237. Count Positions on Street With Required Brightness/2237.java b/solutions/2237. Count Positions on Street With Required Brightness/2237.java new file mode 100644 index 00000000000..cc8c1751ebb --- /dev/null +++ b/solutions/2237. Count Positions on Street With Required Brightness/2237.java @@ -0,0 +1,22 @@ +class Solution { + public int meetRequirement(int n, int[][] lights, int[] requirement) { + int ans = 0; + int currBrightness = 0; + int[] change = new int[n + 1]; + + for (int[] light : lights) { + final int position = light[0]; + final int range = light[1]; + ++change[Math.max(0, position - range)]; + --change[Math.min(n, position + range + 1)]; + } + + for (int i = 0; i < n; ++i) { + currBrightness += change[i]; + if (currBrightness >= requirement[i]) + ++ans; + } + + return ans; + } +} diff --git a/solutions/2237. Count Positions on Street With Required Brightness/2237.py b/solutions/2237. Count Positions on Street With Required Brightness/2237.py new file mode 100644 index 00000000000..3fd9093507f --- /dev/null +++ b/solutions/2237. Count Positions on Street With Required Brightness/2237.py @@ -0,0 +1,16 @@ +class Solution: + def meetRequirement(self, n: int, lights: List[List[int]], requirement: List[int]) -> int: + ans = 0 + currBrightness = 0 + change = [0] * (n + 1) + + for position, rg in lights: + change[max(0, position - rg)] += 1 + change[min(n, position + rg + 1)] -= 1 + + for i in range(n): + currBrightness += change[i] + if currBrightness >= requirement[i]: + ans += 1 + + return ans diff --git a/solutions/2238. Number of Times a Driver Was a Passenger/2238.sql b/solutions/2238. Number of Times a Driver Was a Passenger/2238.sql new file mode 100644 index 00000000000..97aa82912e2 --- /dev/null +++ b/solutions/2238. Number of Times a Driver Was a Passenger/2238.sql @@ -0,0 +1,11 @@ +WITH + DriverIds AS ( + SELECT DISTINCT driver_id FROM Rides + ) +SELECT + DriverIds.driver_id, + COUNT(Rides.passenger_id) AS cnt +FROM DriverIds +LEFT JOIN Rides + ON (DriverIds.driver_id = Rides.passenger_id) +GROUP BY 1; diff --git a/solutions/2239. Find Closest Number to Zero/2239.cpp b/solutions/2239. Find Closest Number to Zero/2239.cpp new file mode 100644 index 00000000000..c833c50a7c3 --- /dev/null +++ b/solutions/2239. Find Closest Number to Zero/2239.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int findClosestNumber(vector& nums) { + return *ranges::min_element(nums, [](const int a, const int b) { + return abs(a) == abs(b) ? a > b : abs(a) < abs(b); + }); + } +}; diff --git a/solutions/2239. Find Closest Number to Zero/2239.java b/solutions/2239. Find Closest Number to Zero/2239.java new file mode 100644 index 00000000000..6f757e5122e --- /dev/null +++ b/solutions/2239. Find Closest Number to Zero/2239.java @@ -0,0 +1,16 @@ +class Solution { + public int findClosestNumber(int[] nums) { + int ans = 0; + int mn = Integer.MAX_VALUE; + + for (final int num : nums) + if (Math.abs(num) < mn) { + mn = Math.abs(num); + ans = num; + } else if (Math.abs(num) == mn && num > ans) { + ans = num; + } + + return ans; + } +} diff --git a/solutions/2239. Find Closest Number to Zero/2239.py b/solutions/2239. Find Closest Number to Zero/2239.py new file mode 100644 index 00000000000..c25957440f5 --- /dev/null +++ b/solutions/2239. Find Closest Number to Zero/2239.py @@ -0,0 +1,4 @@ +class Solution: + def findClosestNumber(self, nums: List[int]) -> int: + nums.sort(key=lambda x: (abs(x), -x)) + return nums[0] diff --git a/solutions/224. Basic Calculator/224.cpp b/solutions/224. Basic Calculator/224.cpp new file mode 100644 index 00000000000..0b9dcee7998 --- /dev/null +++ b/solutions/224. Basic Calculator/224.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int calculate(string s) { + int ans = 0; + int num = 0; + int sign = 1; + stack stack{{sign}}; // stack.top() := the current environment's sign + + for (const char c : s) + if (isdigit(c)) + num = num * 10 + (c - '0'); + else if (c == '(') + stack.push(sign); + else if (c == ')') + stack.pop(); + else if (c == '+' || c == '-') { + ans += sign * num; + sign = (c == '+' ? 1 : -1) * stack.top(); + num = 0; + } + + return ans + sign * num; + } +}; diff --git a/solutions/224. Basic Calculator/224.java b/solutions/224. Basic Calculator/224.java new file mode 100644 index 00000000000..78f5a25b257 --- /dev/null +++ b/solutions/224. Basic Calculator/224.java @@ -0,0 +1,25 @@ +class Solution { + public int calculate(String s) { + int ans = 0; + int num = 0; + int sign = 1; + // stack.peek() := the current environment's sign + Deque stack = new ArrayDeque<>(); + stack.push(sign); + + for (final char c : s.toCharArray()) + if (Character.isDigit(c)) + num = num * 10 + (c - '0'); + else if (c == '(') + stack.push(sign); + else if (c == ')') + stack.pop(); + else if (c == '+' || c == '-') { + ans += sign * num; + sign = (c == '+' ? 1 : -1) * stack.peek(); + num = 0; + } + + return ans + sign * num; + } +} diff --git a/solutions/224. Basic Calculator/224.py b/solutions/224. Basic Calculator/224.py new file mode 100644 index 00000000000..283070ea5a4 --- /dev/null +++ b/solutions/224. Basic Calculator/224.py @@ -0,0 +1,20 @@ +class Solution: + def calculate(self, s: str) -> int: + ans = 0 + num = 0 + sign = 1 + stack = [sign] # stack[-1]: the current environment's sign + + for c in s: + if c.isdigit(): + num = num * 10 + (ord(c) - ord('0')) + elif c == '(': + stack.append(sign) + elif c == ')': + stack.pop() + elif c == '+' or c == '-': + ans += sign * num + sign = (1 if c == '+' else -1) * stack[-1] + num = 0 + + return ans + sign * num diff --git a/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.cpp b/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.cpp new file mode 100644 index 00000000000..a53173269ee --- /dev/null +++ b/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + long long waysToBuyPensPencils(int total, int cost1, int cost2) { + long ans = 0; + const int maxPen = total / cost1; + + for (int i = 0; i <= maxPen; ++i) + ans += (total - i * cost1) / cost2 + 1; + + return ans; + } +}; diff --git a/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.java b/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.java new file mode 100644 index 00000000000..b6b24e7ccbb --- /dev/null +++ b/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.java @@ -0,0 +1,11 @@ +class Solution { + public long waysToBuyPensPencils(int total, int cost1, int cost2) { + long ans = 0; + final int maxPen = total / cost1; + + for (int i = 0; i <= maxPen; ++i) + ans += (total - i * cost1) / cost2 + 1; + + return ans; + } +} diff --git a/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.py b/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.py new file mode 100644 index 00000000000..eaf58123e90 --- /dev/null +++ b/solutions/2240. Number of Ways to Buy Pens and Pencils/2240.py @@ -0,0 +1,5 @@ +class Solution: + def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int: + maxPen = total // cost1 + return sum((total - i * cost1) // cost2 + for i in range(maxPen + 1)) + maxPen + 1 diff --git a/solutions/2241. Design an ATM Machine/2241.cpp b/solutions/2241. Design an ATM Machine/2241.cpp new file mode 100644 index 00000000000..e0b42589d9d --- /dev/null +++ b/solutions/2241. Design an ATM Machine/2241.cpp @@ -0,0 +1,29 @@ +class ATM { + public: + ATM() : bank(5) {} + + void deposit(vector banknotesCount) { + for (int i = 0; i < 5; ++i) + bank[i] += banknotesCount[i]; + } + + vector withdraw(int amount) { + vector withdrew(5); + + for (int i = 4; i >= 0; --i) { + withdrew[i] = min(bank[i], static_cast(amount) / banknotes[i]); + amount -= withdrew[i] * banknotes[i]; + } + + if (amount > 0) + return {-1}; + + for (int i = 0; i < 5; ++i) + bank[i] -= withdrew[i]; + return withdrew; + } + + private: + vector banknotes{20, 50, 100, 200, 500}; + vector bank; +}; diff --git a/solutions/2241. Design an ATM Machine/2241.java b/solutions/2241. Design an ATM Machine/2241.java new file mode 100644 index 00000000000..3d48cabdce6 --- /dev/null +++ b/solutions/2241. Design an ATM Machine/2241.java @@ -0,0 +1,25 @@ +class ATM { + public void deposit(int[] banknotesCount) { + for (int i = 0; i < 5; ++i) + bank[i] += banknotesCount[i]; + } + + public int[] withdraw(int amount) { + int[] withdrew = new int[5]; + + for (int i = 4; i >= 0; --i) { + withdrew[i] = (int) Math.min(bank[i], (long) amount / banknotes[i]); + amount -= withdrew[i] * banknotes[i]; + } + + if (amount > 0) + return new int[] {-1}; + + for (int i = 0; i < 5; ++i) + bank[i] -= withdrew[i]; + return withdrew; + } + + private int[] banknotes = {20, 50, 100, 200, 500}; + private long[] bank = new long[5]; +} diff --git a/solutions/2241. Design an ATM Machine/2241.py b/solutions/2241. Design an ATM Machine/2241.py new file mode 100644 index 00000000000..1d1bbbb0a85 --- /dev/null +++ b/solutions/2241. Design an ATM Machine/2241.py @@ -0,0 +1,22 @@ +class ATM: + def __init__(self): + self.banknotes = [20, 50, 100, 200, 500] + self.bank = [0] * 5 + + def deposit(self, banknotesCount: List[int]) -> None: + for i in range(5): + self.bank[i] += banknotesCount[i] + + def withdraw(self, amount: int) -> List[int]: + withdrew = [0] * 5 + + for i in reversed(range(5)): + withdrew[i] = min(self.bank[i], amount // self.banknotes[i]) + amount -= withdrew[i] * self.banknotes[i] + + if amount: + return [-1] + + for i in range(5): + self.bank[i] -= withdrew[i] + return withdrew diff --git a/solutions/2242. Maximum Score of a Node Sequence/2242.cpp b/solutions/2242. Maximum Score of a Node Sequence/2242.cpp new file mode 100644 index 00000000000..e140898aa4a --- /dev/null +++ b/solutions/2242. Maximum Score of a Node Sequence/2242.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int maximumScore(vector& scores, vector>& edges) { + int ans = -1; + vector>> graph(scores.size()); // {(score, node)} + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].emplace(scores[v], v); + graph[v].emplace(scores[u], u); + if (graph[u].size() > 3) + graph[u].erase(graph[u].begin()); + if (graph[v].size() > 3) + graph[v].erase(graph[v].begin()); + } + + // To find the target sequence: a - u - v - b, enumerate each edge (u, v), + // and find a (u's child) and b (v's child). That's why we find the 3 + // children that have the highest scores because one of the 3 children is + // guaranteed to be valid. + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + for (const auto& [scoreA, a] : graph[u]) + for (const auto& [scoreB, b] : graph[v]) + if (a != b && a != v && b != u) + ans = max(ans, scoreA + scores[u] + scores[v] + scoreB); + } + + return ans; + } +}; diff --git a/solutions/2242. Maximum Score of a Node Sequence/2242.java b/solutions/2242. Maximum Score of a Node Sequence/2242.java new file mode 100644 index 00000000000..3d7f4b035e1 --- /dev/null +++ b/solutions/2242. Maximum Score of a Node Sequence/2242.java @@ -0,0 +1,36 @@ +class Solution { + public int maximumScore(int[] scores, int[][] edges) { + final int n = scores.length; + int ans = -1; + Queue[] graph = new Queue[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new PriorityQueue<>((a, b) -> scores[a] - scores[b]); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].offer(v); + graph[v].offer(u); + if (graph[u].size() > 3) + graph[u].poll(); + if (graph[v].size() > 3) + graph[v].poll(); + } + + // To find the target sequence: a - u - v - b, enumerate each edge (u, v), + // and find a (u's child) and b (v's child). That's why we find the 3 + // children that have the highest scores because one of the 3 children is + // guaranteed to be valid. + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + for (final int a : graph[u]) + for (final int b : graph[v]) + if (a != b && a != v && b != u) + ans = Math.max(ans, scores[a] + scores[u] + scores[v] + scores[b]); + } + + return ans; + } +} diff --git a/solutions/2242. Maximum Score of a Node Sequence/2242.py b/solutions/2242. Maximum Score of a Node Sequence/2242.py new file mode 100644 index 00000000000..a2075e6c3a3 --- /dev/null +++ b/solutions/2242. Maximum Score of a Node Sequence/2242.py @@ -0,0 +1,24 @@ +class Solution: + def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int: + n = len(scores) + ans = -1 + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append((scores[v], v)) + graph[v].append((scores[u], u)) + + for i in range(n): + graph[i] = heapq.nlargest(3, graph[i]) + + # To find the target sequence: a - u - v - b, enumerate each edge (u, v), + # and find a (u's child) and b (v's child). That's why we find the 3 + # children that have the highest scores because one of the 3 children is + # guaranteed to be valid. + for u, v in edges: + for scoreA, a in graph[u]: + for scoreB, b in graph[v]: + if a != b and a != v and b != u: + ans = max(ans, scoreA + scores[u] + scores[v] + scoreB) + + return ans diff --git a/solutions/2243. Calculate Digit Sum of a String/2243.cpp b/solutions/2243. Calculate Digit Sum of a String/2243.cpp new file mode 100644 index 00000000000..152eb8f326b --- /dev/null +++ b/solutions/2243. Calculate Digit Sum of a String/2243.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string digitSum(string s, int k) { + while (s.length() > k) { + string next; + for (int i = 0; i < s.length(); ++i) + next += to_string(accumulate( + s.begin() + i, s.begin() + min(static_cast(s.length()), i + k), + 0, [](int subtotal, char c) { return subtotal + c - '0'; })); + s = move(next); + } + return s; + } +}; diff --git a/solutions/2243. Calculate Digit Sum of a String/2243.java b/solutions/2243. Calculate Digit Sum of a String/2243.java new file mode 100644 index 00000000000..0ec7d6b6ee0 --- /dev/null +++ b/solutions/2243. Calculate Digit Sum of a String/2243.java @@ -0,0 +1,15 @@ +class Solution { + public String digitSum(String s, int k) { + while (s.length() > k) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i += k) { + int sum = 0; + for (int j = i; j < Math.min(s.length(), i + k); ++j) + sum += s.charAt(j) - '0'; + sb.append(sum); + } + s = sb.toString(); + } + return s; + } +} diff --git a/solutions/2243. Calculate Digit Sum of a String/2243.py b/solutions/2243. Calculate Digit Sum of a String/2243.py new file mode 100644 index 00000000000..54c17ef676d --- /dev/null +++ b/solutions/2243. Calculate Digit Sum of a String/2243.py @@ -0,0 +1,11 @@ +class Solution: + def digitSum(self, s: str, k: int) -> str: + while len(s) > k: + next = [] + for i in range(0, len(s), k): + summ = 0 + for j in range(i, min(len(s), i + k)): + summ += ord(s[j]) - ord('0') + next.append(str(summ)) + s = ''.join(next) + return s diff --git a/solutions/2244. Minimum Rounds to Complete All Tasks/2244.cpp b/solutions/2244. Minimum Rounds to Complete All Tasks/2244.cpp new file mode 100644 index 00000000000..a15a492bd61 --- /dev/null +++ b/solutions/2244. Minimum Rounds to Complete All Tasks/2244.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minimumRounds(vector& tasks) { + int ans = 0; + unordered_map count; + + for (const int task : tasks) + ++count[task]; + + // freq = 1 -> it's impossible + // freq = 2 -> needs 1 round + // freq = 3 -> needs 1 round + // freq = 3k -> needs k rounds + // freq = 3k + 1 = 3 * (k - 1) + 2 * 2 -> needs k + 1 rounds + // freq = 3k + 2 = 3 * k + 2 * 1 -> needs k + 1 rounds + for (const auto& [_, freq] : count) + if (freq == 1) + return -1; + else + ans += (freq + 2) / 3; + + return ans; + } +}; diff --git a/solutions/2244. Minimum Rounds to Complete All Tasks/2244.java b/solutions/2244. Minimum Rounds to Complete All Tasks/2244.java new file mode 100644 index 00000000000..6748d9917ba --- /dev/null +++ b/solutions/2244. Minimum Rounds to Complete All Tasks/2244.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumRounds(int[] tasks) { + int ans = 0; + Map count = new HashMap<>(); + + for (final int task : tasks) + count.merge(task, 1, Integer::sum); + + // freq = 1 -> it's impossible + // freq = 2 -> needs 1 round + // freq = 3 -> needs 1 round + // freq = 3k -> needs k rounds + // freq = 3k + 1 = 3 * (k - 1) + 2 * 2 -> needs k + 1 rounds + // freq = 3k + 2 = 3 * k + 2 * 1 -> needs k + 1 rounds + for (final int freq : count.values()) + if (freq == 1) + return -1; + else + ans += (freq + 2) / 3; + + return ans; + } +} diff --git a/solutions/2244. Minimum Rounds to Complete All Tasks/2244.py b/solutions/2244. Minimum Rounds to Complete All Tasks/2244.py new file mode 100644 index 00000000000..c432b832286 --- /dev/null +++ b/solutions/2244. Minimum Rounds to Complete All Tasks/2244.py @@ -0,0 +1,4 @@ +class Solution: + def minimumRounds(self, tasks: List[int]) -> int: + freqs = collections.Counter(tasks).values() + return -1 if 1 in freqs else sum((f + 2) // 3 for f in freqs) diff --git a/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.cpp b/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.cpp new file mode 100644 index 00000000000..60777cbefcc --- /dev/null +++ b/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.cpp @@ -0,0 +1,66 @@ +class Solution { + public: + int maxTrailingZeros(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + // leftPrefix2[i][j] := the number of 2 in grid[i][0..j] + // leftPrefix5[i][j] := the number of 5 in grid[i][0..j] + // topPrefix2[i][j] := the number of 2 in grid[0..i][j] + // topPrefix5[i][j] := the number of 5 in grid[0..i][j] + vector> leftPrefix2(m, vector(n)); + vector> leftPrefix5(m, vector(n)); + vector> topPrefix2(m, vector(n)); + vector> topPrefix5(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + leftPrefix2[i][j] = getCount(grid[i][j], 2); + leftPrefix5[i][j] = getCount(grid[i][j], 5); + if (j > 0) { + leftPrefix2[i][j] += leftPrefix2[i][j - 1]; + leftPrefix5[i][j] += leftPrefix5[i][j - 1]; + } + } + + for (int j = 0; j < n; ++j) + for (int i = 0; i < m; ++i) { + topPrefix2[i][j] = getCount(grid[i][j], 2); + topPrefix5[i][j] = getCount(grid[i][j], 5); + if (i > 0) { + topPrefix2[i][j] += topPrefix2[i - 1][j]; + topPrefix5[i][j] += topPrefix5[i - 1][j]; + } + } + + int ans = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + const int curr2 = getCount(grid[i][j], 2); + const int curr5 = getCount(grid[i][j], 5); + const int l2 = leftPrefix2[i][j]; + const int l5 = leftPrefix5[i][j]; + const int r2 = leftPrefix2[i][n - 1] - (j ? leftPrefix2[i][j - 1] : 0); + const int r5 = leftPrefix5[i][n - 1] - (j ? leftPrefix5[i][j - 1] : 0); + const int t2 = topPrefix2[i][j]; + const int t5 = topPrefix5[i][j]; + const int d2 = topPrefix2[m - 1][j] - (i ? topPrefix2[i - 1][j] : 0); + const int d5 = topPrefix5[m - 1][j] - (i ? topPrefix5[i - 1][j] : 0); + ans = max({ans, min(l2 + t2 - curr2, l5 + t5 - curr5), + min(r2 + t2 - curr2, r5 + t5 - curr5), + min(l2 + d2 - curr2, l5 + d5 - curr5), + min(r2 + d2 - curr2, r5 + d5 - curr5)}); + } + + return ans; + } + + private: + int getCount(int num, int factor) { + int count = 0; + while (num % factor == 0) { + num /= factor; + ++count; + } + return count; + } +}; diff --git a/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.java b/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.java new file mode 100644 index 00000000000..0ba6864575d --- /dev/null +++ b/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.java @@ -0,0 +1,64 @@ +class Solution { + public int maxTrailingZeros(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + // leftPrefix2[i][j] := the number of 2 in grid[i][0..j] + // leftPrefix5[i][j] := the number of 5 in grid[i][0..j] + // topPrefix2[i][j] := the number of 2 in grid[0..i][j] + // topPrefix5[i][j] := the number of 5 in grid[0..i][j] + int[][] leftPrefix2 = new int[m][n]; + int[][] leftPrefix5 = new int[m][n]; + int[][] topPrefix2 = new int[m][n]; + int[][] topPrefix5 = new int[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + leftPrefix2[i][j] = getCount(grid[i][j], 2); + leftPrefix5[i][j] = getCount(grid[i][j], 5); + if (j > 0) { + leftPrefix2[i][j] += leftPrefix2[i][j - 1]; + leftPrefix5[i][j] += leftPrefix5[i][j - 1]; + } + } + + for (int j = 0; j < n; ++j) + for (int i = 0; i < m; ++i) { + topPrefix2[i][j] = getCount(grid[i][j], 2); + topPrefix5[i][j] = getCount(grid[i][j], 5); + if (i > 0) { + topPrefix2[i][j] += topPrefix2[i - 1][j]; + topPrefix5[i][j] += topPrefix5[i - 1][j]; + } + } + + int ans = 0; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + final int curr2 = getCount(grid[i][j], 2); + final int curr5 = getCount(grid[i][j], 5); + final int l2 = leftPrefix2[i][j]; + final int l5 = leftPrefix5[i][j]; + final int r2 = leftPrefix2[i][n - 1] - (j > 0 ? leftPrefix2[i][j - 1] : 0); + final int r5 = leftPrefix5[i][n - 1] - (j > 0 ? leftPrefix5[i][j - 1] : 0); + final int t2 = topPrefix2[i][j]; + final int t5 = topPrefix5[i][j]; + final int d2 = topPrefix2[m - 1][j] - (i > 0 ? topPrefix2[i - 1][j] : 0); + final int d5 = topPrefix5[m - 1][j] - (i > 0 ? topPrefix5[i - 1][j] : 0); + ans = Math.max(ans, Math.max(Math.max(Math.min(l2 + t2 - curr2, l5 + t5 - curr5), + Math.min(r2 + t2 - curr2, r5 + t5 - curr5)), + Math.max(Math.min(l2 + d2 - curr2, l5 + d5 - curr5), + Math.min(r2 + d2 - curr2, r5 + d5 - curr5)))); + } + + return ans; + } + + private int getCount(int num, int factor) { + int count = 0; + while (num % factor == 0) { + num /= factor; + ++count; + } + return count; + } +} diff --git a/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.py b/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.py new file mode 100644 index 00000000000..619e4c2cbf2 --- /dev/null +++ b/solutions/2245. Maximum Trailing Zeros in a Cornered Path/2245.py @@ -0,0 +1,56 @@ +class Solution: + def maxTrailingZeros(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + # leftPrefix2[i][j] := the number of 2 in grid[i][0..j] + # leftPrefix5[i][j] := the number of 5 in grid[i][0..j] + # topPrefix2[i][j] := the number of 2 in grid[0..i][j] + # topPrefix5[i][j] := the number of 5 in grid[0..i][j] + leftPrefix2 = [[0] * n for _ in range(m)] + leftPrefix5 = [[0] * n for _ in range(m)] + topPrefix2 = [[0] * n for _ in range(m)] + topPrefix5 = [[0] * n for _ in range(m)] + + def getCount(num: int, factor: int) -> int: + count = 0 + while num % factor == 0: + num //= factor + count += 1 + return count + + for i in range(m): + for j in range(n): + leftPrefix2[i][j] = getCount(grid[i][j], 2) + leftPrefix5[i][j] = getCount(grid[i][j], 5) + if j: + leftPrefix2[i][j] += leftPrefix2[i][j - 1] + leftPrefix5[i][j] += leftPrefix5[i][j - 1] + + for j in range(n): + for i in range(m): + topPrefix2[i][j] = getCount(grid[i][j], 2) + topPrefix5[i][j] = getCount(grid[i][j], 5) + if i: + topPrefix2[i][j] += topPrefix2[i - 1][j] + topPrefix5[i][j] += topPrefix5[i - 1][j] + + ans = 0 + for i in range(m): + for j in range(n): + curr2 = getCount(grid[i][j], 2) + curr5 = getCount(grid[i][j], 5) + l2 = leftPrefix2[i][j] + l5 = leftPrefix5[i][j] + r2 = leftPrefix2[i][n - 1] - (0 if j == 0 else leftPrefix2[i][j - 1]) + r5 = leftPrefix5[i][n - 1] - (0 if j == 0 else leftPrefix5[i][j - 1]) + t2 = topPrefix2[i][j] + t5 = topPrefix5[i][j] + d2 = topPrefix2[m - 1][j] - (0 if i == 0 else topPrefix2[i - 1][j]) + d5 = topPrefix5[m - 1][j] - (0 if i == 0 else topPrefix5[i - 1][j]) + ans = max(ans, + min(l2 + t2 - curr2, l5 + t5 - curr5), + min(r2 + t2 - curr2, r5 + t5 - curr5), + min(l2 + d2 - curr2, l5 + d5 - curr5), + min(r2 + d2 - curr2, r5 + d5 - curr5)) + + return ans diff --git a/solutions/2246. Longest Path With Different Adjacent Characters/2246.cpp b/solutions/2246. Longest Path With Different Adjacent Characters/2246.cpp new file mode 100644 index 00000000000..46ca0b9e587 --- /dev/null +++ b/solutions/2246. Longest Path With Different Adjacent Characters/2246.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int longestPath(vector& parent, string s) { + const int n = parent.size(); + int ans = 1; + vector> graph(n); + + for (int i = 1; i < n; ++i) + graph[parent[i]].push_back(i); + + longestPathDownFrom(graph, 0, s, ans); + return ans; + } + + private: + int longestPathDownFrom(const vector>& graph, int u, + const string& s, int& ans) { + int max1 = 0; + int max2 = 0; + + for (const int v : graph[u]) { + const int res = longestPathDownFrom(graph, v, s, ans); + if (s[u] == s[v]) + continue; + if (res > max1) { + max2 = max1; + max1 = res; + } else if (res > max2) { + max2 = res; + } + } + + ans = max(ans, 1 + max1 + max2); + return 1 + max1; + } +}; diff --git a/solutions/2246. Longest Path With Different Adjacent Characters/2246.java b/solutions/2246. Longest Path With Different Adjacent Characters/2246.java new file mode 100644 index 00000000000..da0c2561045 --- /dev/null +++ b/solutions/2246. Longest Path With Different Adjacent Characters/2246.java @@ -0,0 +1,37 @@ +class Solution { + public int longestPath(int[] parent, String s) { + final int n = parent.length; + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int i = 1; i < n; ++i) + graph[parent[i]].add(i); + + longestPathDownFrom(graph, 0, s); + return ans; + } + + private int ans = 0; + + private int longestPathDownFrom(List[] graph, int u, final String s) { + int max1 = 0; + int max2 = 0; + + for (final int v : graph[u]) { + final int res = longestPathDownFrom(graph, v, s); + if (s.charAt(u) == s.charAt(v)) + continue; + if (res > max1) { + max2 = max1; + max1 = res; + } else if (res > max2) { + max2 = res; + } + } + + ans = Math.max(ans, 1 + max1 + max2); + return 1 + max1; + } +} diff --git a/solutions/2246. Longest Path With Different Adjacent Characters/2246.py b/solutions/2246. Longest Path With Different Adjacent Characters/2246.py new file mode 100644 index 00000000000..4ef71cf5313 --- /dev/null +++ b/solutions/2246. Longest Path With Different Adjacent Characters/2246.py @@ -0,0 +1,29 @@ +class Solution: + def longestPath(self, parent: List[int], s: str) -> int: + n = len(parent) + ans = 0 + graph = [[] for _ in range(n)] + + for i in range(1, n): + graph[parent[i]].append(i) + + def longestPathDownFrom(u: int) -> int: + nonlocal ans + max1 = 0 + max2 = 0 + + for v in graph[u]: + res = longestPathDownFrom(v) + if s[u] == s[v]: + continue + if res > max1: + max2 = max1 + max1 = res + elif res > max2: + max2 = res + + ans = max(ans, 1 + max1 + max2) + return 1 + max1 + + longestPathDownFrom(0) + return ans diff --git a/solutions/2247. Maximum Cost of Trip With K Highways/2247.cpp b/solutions/2247. Maximum Cost of Trip With K Highways/2247.cpp new file mode 100644 index 00000000000..429404bbde3 --- /dev/null +++ b/solutions/2247. Maximum Cost of Trip With K Highways/2247.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + int maximumCost(int n, vector>& highways, int k) { + if (k + 1 > n) + return -1; + + int ans = -1; + vector> mem(n, vector(1 << n, -1)); + vector>> graph(n); + + for (const vector& h : highways) { + const int u = h[0]; + const int v = h[1]; + const int w = h[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + for (int i = 0; i < n; ++i) + ans = max(ans, maximumCost(graph, i, 1 << i, k, mem)); + + return ans; + } + + private: + // Returns the maximum cost of trip starting from u, where `mask` is the + // bitmask of the visited cities. + int maximumCost(const vector>>& graph, int u, + unsigned mask, int k, vector>& mem) { + if (popcount(mask) == k + 1) + return 0; + if (mem[u][mask] != -1) + return mem[u][mask]; + + int res = -1; + for (const auto& [v, w] : graph[u]) { + if (mask >> v & 1) + continue; + const int nextCost = maximumCost(graph, v, mask | 1 << v, k, mem); + if (nextCost != -1) + res = max(res, w + nextCost); + } + + return mem[u][mask] = res; + } +}; diff --git a/solutions/2247. Maximum Cost of Trip With K Highways/2247.java b/solutions/2247. Maximum Cost of Trip With K Highways/2247.java new file mode 100644 index 00000000000..80da967ae61 --- /dev/null +++ b/solutions/2247. Maximum Cost of Trip With K Highways/2247.java @@ -0,0 +1,49 @@ +class Solution { + public int maximumCost(int n, int[][] highways, int k) { + if (k + 1 > n) + return -1; + + int ans = -1; + Integer[][] mem = new Integer[n][1 << n]; + List>[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] h : highways) { + final int u = h[0]; + final int v = h[1]; + final int w = h[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + for (int i = 0; i < n; ++i) + ans = Math.max(ans, maximumCost(graph, i, 1 << i, k, mem)); + + return ans; + } + + // Returns the maximum cost of trip starting from u, where `mask` is the + // bitmask of the visited cities. + private int maximumCost(List>[] graph, int u, int mask, int k, + Integer[][] mem) { + if (Integer.bitCount(mask) == k + 1) + return 0; + if (mem[u][mask] != null) + return mem[u][mask]; + + int res = -1; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if ((mask >> v & 1) == 1) + continue; + final int nextCost = maximumCost(graph, v, mask | 1 << v, k, mem); + if (nextCost != -1) + res = Math.max(res, w + nextCost); + } + + return mem[u][mask] = res; + } +} diff --git a/solutions/2247. Maximum Cost of Trip With K Highways/2247.py b/solutions/2247. Maximum Cost of Trip With K Highways/2247.py new file mode 100644 index 00000000000..d7ab46d36a5 --- /dev/null +++ b/solutions/2247. Maximum Cost of Trip With K Highways/2247.py @@ -0,0 +1,30 @@ +class Solution: + def maximumCost(self, n: int, highways: List[List[int]], k: int) -> int: + if k + 1 > n: + return -1 + + graph = [[] for _ in range(n)] + + for u, v, w in highways: + graph[u].append((v, w)) + graph[v].append((u, w)) + + @functools.lru_cache(None) + def dp(u: int, mask: int) -> int: + """ + Returns the maximum cost of trip starting from u, where `mask` is the + bitmask of the visited cities. + """ + if mask.bit_count() == k + 1: + return 0 + + res = -1 + for v, w in graph[u]: + if mask >> v & 1: + continue + nextCost = dp(v, mask | 1 << v) + if nextCost != -1: + res = max(res, w + nextCost) + return res + + return max(dp(i, 1 << i) for i in range(n)) diff --git a/solutions/2248. Intersection of Multiple Arrays/2248.cpp b/solutions/2248. Intersection of Multiple Arrays/2248.cpp new file mode 100644 index 00000000000..0fe8da241f7 --- /dev/null +++ b/solutions/2248. Intersection of Multiple Arrays/2248.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector intersection(vector>& nums) { + vector ans; + vector count(1001); + + for (const vector& A : nums) + for (const int a : A) + ++count[a]; + + for (int i = 1; i < 1001; ++i) + if (count[i] == nums.size()) + ans.push_back(i); + + return ans; + } +}; diff --git a/solutions/2248. Intersection of Multiple Arrays/2248.java b/solutions/2248. Intersection of Multiple Arrays/2248.java new file mode 100644 index 00000000000..974a7219ff3 --- /dev/null +++ b/solutions/2248. Intersection of Multiple Arrays/2248.java @@ -0,0 +1,16 @@ +class Solution { + public List intersection(int[][] nums) { + List ans = new ArrayList<>(); + int[] count = new int[1001]; + + for (int[] A : nums) + for (final int a : A) + ++count[a]; + + for (int i = 1; i < 1001; ++i) + if (count[i] == nums.length) + ans.add(i); + + return ans; + } +} diff --git a/solutions/2248. Intersection of Multiple Arrays/2248.py b/solutions/2248. Intersection of Multiple Arrays/2248.py new file mode 100644 index 00000000000..16a22074579 --- /dev/null +++ b/solutions/2248. Intersection of Multiple Arrays/2248.py @@ -0,0 +1,10 @@ +class Solution: + def intersection(self, nums: List[List[int]]) -> List[int]: + count = [0] * 1001 + + for A in nums: + for a in A: + count[a] += 1 + + return [i for i, c in enumerate(count) + if c == len(nums)] diff --git a/solutions/2249. Count Lattice Points Inside a Circle/2249-2.cpp b/solutions/2249. Count Lattice Points Inside a Circle/2249-2.cpp new file mode 100644 index 00000000000..18dd4912584 --- /dev/null +++ b/solutions/2249. Count Lattice Points Inside a Circle/2249-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int countLatticePoints(vector>& circles) { + set> points; + + // dx := relative to x + // dy := relative to y + // So, dx^2 + dy^2 = r^2. + for (const vector& c : circles) { + const int x = c[0]; + const int y = c[1]; + const int r = c[2]; + for (int dx = -r; dx <= r; ++dx) { + const int yMax = sqrt(r * r - dx * dx); + for (int dy = -yMax; dy <= yMax; ++dy) + points.emplace(x + dx, y + dy); + } + } + + return points.size(); + } +}; diff --git a/solutions/2249. Count Lattice Points Inside a Circle/2249-2.java b/solutions/2249. Count Lattice Points Inside a Circle/2249-2.java new file mode 100644 index 00000000000..441ef8c5bb8 --- /dev/null +++ b/solutions/2249. Count Lattice Points Inside a Circle/2249-2.java @@ -0,0 +1,21 @@ +class Solution { + public int countLatticePoints(int[][] circles) { + Set> points = new HashSet<>(); + + // dx := relative to x + // dy := relative to y + // So, dx^2 + dy^2 = r^2. + for (int[] c : circles) { + final int x = c[0]; + final int y = c[1]; + final int r = c[2]; + for (int dx = -r; dx <= r; ++dx) { + final int yMax = (int) Math.sqrt(r * r - dx * dx); + for (int dy = -yMax; dy <= yMax; ++dy) + points.add(new Pair<>(x + dx, y + dy)); + } + } + + return points.size(); + } +} diff --git a/solutions/2249. Count Lattice Points Inside a Circle/2249-2.py b/solutions/2249. Count Lattice Points Inside a Circle/2249-2.py new file mode 100644 index 00000000000..e44fab59b85 --- /dev/null +++ b/solutions/2249. Count Lattice Points Inside a Circle/2249-2.py @@ -0,0 +1,14 @@ +class Solution: + def countLatticePoints(self, circles: List[List[int]]) -> int: + points = set() + + # dx := relative to x + # dy := relative to y + # So, dx^2 + dy^2 = r^2. + for x, y, r in circles: + for dx in range(-r, r + 1): + yMax = int((r**2 - dx**2)**0.5) + for dy in range(-yMax, yMax + 1): + points.add((x + dx, y + dy)) + + return len(points) diff --git a/solutions/2249. Count Lattice Points Inside a Circle/2249.cpp b/solutions/2249. Count Lattice Points Inside a Circle/2249.cpp new file mode 100644 index 00000000000..cde0b38eefe --- /dev/null +++ b/solutions/2249. Count Lattice Points Inside a Circle/2249.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int countLatticePoints(vector>& circles) { + int ans = 0; + + for (int x = 0; x < 201; ++x) + for (int y = 0; y < 201; ++y) + ans += ranges::any_of(circles, [&](const auto& c) { + return (c[0] - x) * (c[0] - x) + (c[1] - y) * (c[1] - y) <= + c[2] * c[2]; + }); + + return ans; + } +}; diff --git a/solutions/2249. Count Lattice Points Inside a Circle/2249.java b/solutions/2249. Count Lattice Points Inside a Circle/2249.java new file mode 100644 index 00000000000..98200c99537 --- /dev/null +++ b/solutions/2249. Count Lattice Points Inside a Circle/2249.java @@ -0,0 +1,15 @@ +class Solution { + public int countLatticePoints(int[][] circles) { + int ans = 0; + + for (int x = 0; x < 201; ++x) + for (int y = 0; y < 201; ++y) + for (int[] c : circles) + if ((c[0] - x) * (c[0] - x) + (c[1] - y) * (c[1] - y) <= c[2] * c[2]) { + ++ans; + break; + } + + return ans; + } +} diff --git a/solutions/2249. Count Lattice Points Inside a Circle/2249.py b/solutions/2249. Count Lattice Points Inside a Circle/2249.py new file mode 100644 index 00000000000..6a9d664dfa8 --- /dev/null +++ b/solutions/2249. Count Lattice Points Inside a Circle/2249.py @@ -0,0 +1,5 @@ +class Solution: + def countLatticePoints(self, circles: List[List[int]]) -> int: + return sum(any((xc - x)**2 + (yc - y)**2 <= r**2 for xc, yc, r in circles) + for x in range(201) + for y in range(201)) diff --git a/solutions/225. Implement Stack using Queues/225.cpp b/solutions/225. Implement Stack using Queues/225.cpp new file mode 100644 index 00000000000..ef624d055ef --- /dev/null +++ b/solutions/225. Implement Stack using Queues/225.cpp @@ -0,0 +1,27 @@ +class MyStack { + public: + void push(int x) { + q.push(x); + for (int i = 0; i < q.size() - 1; ++i) { + q.push(q.front()); + q.pop(); + } + } + + int pop() { + const int val = q.front(); + q.pop(); + return val; + } + + int top() { + return q.front(); + } + + bool empty() { + return q.empty(); + } + + private: + queue q; +}; diff --git a/solutions/225. Implement Stack using Queues/225.java b/solutions/225. Implement Stack using Queues/225.java new file mode 100644 index 00000000000..09c9225d027 --- /dev/null +++ b/solutions/225. Implement Stack using Queues/225.java @@ -0,0 +1,21 @@ +class MyStack { + public void push(int x) { + q.offer(x); + for (int i = 0; i < q.size() - 1; ++i) + q.offer(q.poll()); + } + + public int pop() { + return q.poll(); + } + + public int top() { + return q.peek(); + } + + public boolean empty() { + return q.isEmpty(); + } + + private Queue q = new ArrayDeque<>(); +} diff --git a/solutions/225. Implement Stack using Queues/225.py b/solutions/225. Implement Stack using Queues/225.py new file mode 100644 index 00000000000..c4d61c9d7ad --- /dev/null +++ b/solutions/225. Implement Stack using Queues/225.py @@ -0,0 +1,17 @@ +class MyStack: + def __init__(self): + self.q = collections.deque() + + def push(self, x: int) -> None: + self.q.append(x) + for _ in range(len(self.q) - 1): + self.q.append(self.q.popleft()) + + def pop(self) -> int: + return self.q.popleft() + + def top(self) -> int: + return self.q[0] + + def empty(self) -> bool: + return not self.q diff --git a/solutions/2250. Count Number of Rectangles Containing Each Point/2250.cpp b/solutions/2250. Count Number of Rectangles Containing Each Point/2250.cpp new file mode 100644 index 00000000000..a4de140d82c --- /dev/null +++ b/solutions/2250. Count Number of Rectangles Containing Each Point/2250.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector countRectangles(vector>& rectangles, + vector>& points) { + vector ans; + vector> yToXs(101); + + for (const vector& r : rectangles) + yToXs[r[1]].push_back(r[0]); + + for (auto& xs : yToXs) + ranges::sort(xs); + + for (const vector& p : points) { + int count = 0; + for (int y = p[1]; y < 101; ++y) { + const vector& xs = yToXs[y]; + count += xs.end() - ranges::lower_bound(xs, p[0]); + } + ans.push_back(count); + } + + return ans; + } +}; diff --git a/solutions/2250. Count Number of Rectangles Containing Each Point/2250.java b/solutions/2250. Count Number of Rectangles Containing Each Point/2250.java new file mode 100644 index 00000000000..98185cd5e39 --- /dev/null +++ b/solutions/2250. Count Number of Rectangles Containing Each Point/2250.java @@ -0,0 +1,31 @@ +class Solution { + public int[] countRectangles(int[][] rectangles, int[][] points) { + int[] ans = new int[points.length]; + List[] yToXs = new List[101]; + + for (int i = 0; i < 101; ++i) + yToXs[i] = new ArrayList<>(); + + for (int[] r : rectangles) + yToXs[r[1]].add(r[0]); + + for (List xs : yToXs) + Collections.sort(xs); + + for (int i = 0; i < points.length; ++i) { + int count = 0; + for (int y = points[i][1]; y < 101; ++y) { + List xs = yToXs[y]; + count += xs.size() - firstGreaterEqual(xs, points[i][0]); + } + ans[i] = count; + } + + return ans; + } + + private int firstGreaterEqual(List indices, int target) { + final int i = Collections.binarySearch(indices, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2250. Count Number of Rectangles Containing Each Point/2250.py b/solutions/2250. Count Number of Rectangles Containing Each Point/2250.py new file mode 100644 index 00000000000..88ecb1e3a57 --- /dev/null +++ b/solutions/2250. Count Number of Rectangles Containing Each Point/2250.py @@ -0,0 +1,19 @@ +class Solution: + def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]: + ans = [] + yToXs = [[] for _ in range(101)] + + for l, h in rectangles: + yToXs[h].append(l) + + for xs in yToXs: + xs.sort() + + for xi, yi in points: + count = 0 + for y in range(yi, 101): + xs = yToXs[y] + count += len(xs) - bisect.bisect_left(xs, xi) + ans.append(count) + + return ans diff --git a/solutions/2251. Number of Flowers in Full Bloom/2251.cpp b/solutions/2251. Number of Flowers in Full Bloom/2251.cpp new file mode 100644 index 00000000000..aff8a5f2eb9 --- /dev/null +++ b/solutions/2251. Number of Flowers in Full Bloom/2251.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector fullBloomFlowers(vector>& flowers, + vector& persons) { + vector ans; + vector starts; + vector ends; + + for (const vector& flower : flowers) { + starts.push_back(flower[0]); + ends.push_back(flower[1]); + } + + ranges::sort(starts); + ranges::sort(ends); + + for (const int p : persons) { + const int started = ranges::upper_bound(starts, p) - starts.begin(); + const int ended = ranges::lower_bound(ends, p) - ends.begin(); + ans.push_back(started - ended); + } + + return ans; + } +}; diff --git a/solutions/2251. Number of Flowers in Full Bloom/2251.java b/solutions/2251. Number of Flowers in Full Bloom/2251.java new file mode 100644 index 00000000000..d8cca4b13f6 --- /dev/null +++ b/solutions/2251. Number of Flowers in Full Bloom/2251.java @@ -0,0 +1,49 @@ +class Solution { + public int[] fullBloomFlowers(int[][] flowers, int[] persons) { + int[] ans = new int[persons.length]; + List starts = new ArrayList<>(); + List ends = new ArrayList<>(); + + for (int[] flower : flowers) { + starts.add(flower[0]); + ends.add(flower[1]); + } + + Collections.sort(starts); + Collections.sort(ends); + + for (int i = 0; i < persons.length; ++i) { + final int started = firstGreater(starts, persons[i]); + final int ended = firstGreaterEqual(ends, persons[i]); + ans[i] = started - ended; + } + + return ans; + } + + private int firstGreater(List A, int target) { + int l = 0; + int r = A.size(); + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m) > target) + r = m; + else + l = m + 1; + } + return l; + } + + private int firstGreaterEqual(List A, int target) { + int l = 0; + int r = A.size(); + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m) >= target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/2251. Number of Flowers in Full Bloom/2251.py b/solutions/2251. Number of Flowers in Full Bloom/2251.py new file mode 100644 index 00000000000..b806a15282f --- /dev/null +++ b/solutions/2251. Number of Flowers in Full Bloom/2251.py @@ -0,0 +1,7 @@ +class Solution: + def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: + starts = sorted(s for s, _ in flowers) + ends = sorted(e for _, e in flowers) + return [bisect.bisect_right(starts, person) - + bisect.bisect_left(ends, person) + for person in persons] diff --git a/solutions/2252. Dynamic Pivoting of a Table/2252.sql b/solutions/2252. Dynamic Pivoting of a Table/2252.sql new file mode 100644 index 00000000000..7b61486c146 --- /dev/null +++ b/solutions/2252. Dynamic Pivoting of a Table/2252.sql @@ -0,0 +1,24 @@ +CREATE PROCEDURE PivotProducts() +BEGIN + # Override GROUP_CONCAT length which has a default limit of 1024. + SET SESSION group_concat_max_len = 1000000; + + SELECT GROUP_CONCAT( + DISTINCT CONCAT( + 'SUM(IF(store = "', + store, + '", price, NULL)) AS ', + store + ) + ) INTO @stmt + FROM products; + + SET @query = CONCAT( + 'SELECT product_id, ', @stmt, ' ' + 'FROM Products ' + 'GROUP BY 1'); + + PREPARE final_query FROM @query; + EXECUTE final_query; + DEALLOCATE PREPARE final_query; +END diff --git a/solutions/2253. Dynamic Unpivoting of a Table/2253.sql b/solutions/2253. Dynamic Unpivoting of a Table/2253.sql new file mode 100644 index 00000000000..c80518f588d --- /dev/null +++ b/solutions/2253. Dynamic Unpivoting of a Table/2253.sql @@ -0,0 +1,25 @@ +CREATE PROCEDURE UnpivotProducts() +BEGIN + # Override GROUP_CONCAT length which has a default limit of 1024. + SET SESSION group_concat_max_len = 1000000; + + SELECT GROUP_CONCAT( + CONCAT( + 'SELECT product_id, "', + `column_name`, '" AS store, ', + `column_name`, ' AS price ', + 'FROM products ', + 'WHERE ', + `column_name`, ' IS NOT NULL' + ) SEPARATOR ' UNION ' + ) INTO @stmt + FROM `information_schema`.`columns` + WHERE + `table_schema` = 'test' + AND `table_name` = 'Products' + AND `column_name` != 'product_id'; + + PREPARE final_query FROM @stmt; + EXECUTE final_query; + DEALLOCATE PREPARE final_query; +END diff --git a/solutions/2254. Design Video Sharing Platform/2254.cpp b/solutions/2254. Design Video Sharing Platform/2254.cpp new file mode 100644 index 00000000000..27280f12672 --- /dev/null +++ b/solutions/2254. Design Video Sharing Platform/2254.cpp @@ -0,0 +1,66 @@ +class VideoSharingPlatform { + public: + int upload(string video) { + const int videoId = getVideoId(); + videoIdToVideo[videoId] = video; + return videoId; + } + + void remove(int videoId) { + if (videoIdToVideo.contains(videoId)) { + usedIds.push(videoId); + videoIdToVideo.erase(videoId); + videoIdToViews.erase(videoId); + videoIdToLikes.erase(videoId); + videoIdToDislikes.erase(videoId); + } + } + + string watch(int videoId, int startMinute, int endMinute) { + const auto it = videoIdToVideo.find(videoId); + if (it == videoIdToVideo.cend()) + return "-1"; + ++videoIdToViews[videoId]; + const string video = it->second; + const int duration = + min(endMinute, static_cast(video.length()) - 1) - startMinute + 1; + return video.substr(startMinute, duration); + } + + void like(int videoId) { + if (videoIdToVideo.contains(videoId)) + ++videoIdToLikes[videoId]; + } + + void dislike(int videoId) { + if (videoIdToVideo.contains(videoId)) + ++videoIdToDislikes[videoId]; + } + + vector getLikesAndDislikes(int videoId) { + return videoIdToVideo.contains(videoId) + ? vector{videoIdToLikes[videoId], + videoIdToDislikes[videoId]} + : vector{-1}; + } + + int getViews(int videoId) { + return videoIdToVideo.contains(videoId) ? videoIdToViews[videoId] : -1; + } + + private: + int currVideoId = 0; + priority_queue, greater<>> usedIds; + unordered_map videoIdToVideo; + unordered_map videoIdToViews; + unordered_map videoIdToLikes; + unordered_map videoIdToDislikes; + + int getVideoId() { + if (usedIds.empty()) + return currVideoId++; + const int minUsedId = usedIds.top(); + usedIds.pop(); + return minUsedId; + } +}; diff --git a/solutions/2254. Design Video Sharing Platform/2254.java b/solutions/2254. Design Video Sharing Platform/2254.java new file mode 100644 index 00000000000..e3dddf3521c --- /dev/null +++ b/solutions/2254. Design Video Sharing Platform/2254.java @@ -0,0 +1,59 @@ +class VideoSharingPlatform { + public int upload(String video) { + final int videoId = getVideoId(); + videoIdToVideo.put(videoId, video); + return videoId; + } + + public void remove(int videoId) { + if (videoIdToVideo.containsKey(videoId)) { + usedIds.offer(videoId); + videoIdToVideo.remove(videoId); + videoIdToViews.remove(videoId); + videoIdToLikes.remove(videoId); + videoIdToDislikes.remove(videoId); + } + } + + public String watch(int videoId, int startMinute, int endMinute) { + if (!videoIdToVideo.containsKey(videoId)) + return "-1"; + videoIdToViews.merge(videoId, 1, Integer::sum); + final String video = videoIdToVideo.get(videoId); + return video.substring(startMinute, Math.min(endMinute + 1, video.length())); + } + + public void like(int videoId) { + if (videoIdToVideo.containsKey(videoId)) + videoIdToLikes.merge(videoId, 1, Integer::sum); + } + + public void dislike(int videoId) { + if (videoIdToVideo.containsKey(videoId)) + videoIdToDislikes.merge(videoId, 1, Integer::sum); + } + + public int[] getLikesAndDislikes(int videoId) { + return videoIdToVideo.containsKey(videoId) + ? new int[] {videoIdToLikes.getOrDefault(videoId, 0), + videoIdToDislikes.getOrDefault(videoId, 0)} + : new int[] {-1}; + } + + public int getViews(int videoId) { + return videoIdToVideo.containsKey(videoId) ? videoIdToViews.getOrDefault(videoId, 0) : -1; + } + + private int currVideoId = 0; + private Queue usedIds = new PriorityQueue<>(); + private Map videoIdToVideo = new HashMap<>(); + private Map videoIdToViews = new HashMap<>(); + private Map videoIdToLikes = new HashMap<>(); + private Map videoIdToDislikes = new HashMap<>(); + + private int getVideoId() { + if (usedIds.isEmpty()) + return currVideoId++; + return usedIds.poll(); + } +} diff --git a/solutions/2254. Design Video Sharing Platform/2254.py b/solutions/2254. Design Video Sharing Platform/2254.py new file mode 100644 index 00000000000..5b8bb371f2b --- /dev/null +++ b/solutions/2254. Design Video Sharing Platform/2254.py @@ -0,0 +1,52 @@ +class VideoSharingPlatform: + def __init__(self): + self.currVideoId = 0 + self.usedIds = [] + self.videoIdToVideo = {} + self.videoIdToViews = collections.Counter() + self.videoIdToLikes = collections.Counter() + self.videoIdToDislikes = collections.Counter() + + def upload(self, video: str) -> int: + videoId = self._getVideoId() + self.videoIdToVideo[videoId] = video + return videoId + + def remove(self, videoId: int) -> None: + if videoId in self.videoIdToVideo: + heapq.heappush(self.usedIds, videoId) + del self.videoIdToVideo[videoId] + del self.videoIdToViews[videoId] + del self.videoIdToLikes[videoId] + del self.videoIdToDislikes[videoId] + + def watch(self, videoId: int, startMinute: int, endMinute: int) -> str: + if videoId not in self.videoIdToVideo: + return '-1' + self.videoIdToViews[videoId] += 1 + video = self.videoIdToVideo[videoId] + return video[startMinute:min(endMinute + 1, len(video))] + + def like(self, videoId: int) -> None: + if videoId in self.videoIdToVideo: + self.videoIdToLikes[videoId] += 1 + + def dislike(self, videoId: int) -> None: + if videoId in self.videoIdToVideo: + self.videoIdToDislikes[videoId] += 1 + + def getLikesAndDislikes(self, videoId: int) -> List[int]: + if videoId in self.videoIdToVideo: + return [self.videoIdToLikes[videoId], self.videoIdToDislikes[videoId]] + return [-1] + + def getViews(self, videoId: int) -> int: + if videoId in self.videoIdToVideo: + return self.videoIdToViews[videoId] + return -1 + + def _getVideoId(self) -> int: + if not self.usedIds: + self.currVideoId += 1 + return self.currVideoId - 1 + return heapq.heappop(self.usedIds) diff --git a/solutions/2255. Count Prefixes of a Given String/2255.cpp b/solutions/2255. Count Prefixes of a Given String/2255.cpp new file mode 100644 index 00000000000..caaad890edf --- /dev/null +++ b/solutions/2255. Count Prefixes of a Given String/2255.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int countPrefixes(vector& words, string s) { + return ranges::count_if( + words, [&](const string& word) { return s.find(word) == 0; }); + } +}; diff --git a/solutions/2255. Count Prefixes of a Given String/2255.java b/solutions/2255. Count Prefixes of a Given String/2255.java new file mode 100644 index 00000000000..52438307057 --- /dev/null +++ b/solutions/2255. Count Prefixes of a Given String/2255.java @@ -0,0 +1,5 @@ +class Solution { + public int countPrefixes(String[] words, String s) { + return (int) Arrays.stream(words).filter(word -> s.startsWith(word)).count(); + } +} diff --git a/solutions/2255. Count Prefixes of a Given String/2255.py b/solutions/2255. Count Prefixes of a Given String/2255.py new file mode 100644 index 00000000000..799c69184af --- /dev/null +++ b/solutions/2255. Count Prefixes of a Given String/2255.py @@ -0,0 +1,3 @@ +class Solution: + def countPrefixes(self, words: List[str], s: str) -> int: + return sum(map(s.startswith, words)) diff --git a/solutions/2256. Minimum Average Difference/2256.cpp b/solutions/2256. Minimum Average Difference/2256.cpp new file mode 100644 index 00000000000..bd31104c50b --- /dev/null +++ b/solutions/2256. Minimum Average Difference/2256.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minimumAverageDifference(vector& nums) { + const int n = nums.size(); + int ans = 0; + int minDiff = INT_MAX; + long prefix = 0; + long suffix = accumulate(nums.begin(), nums.end(), 0L); + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i]; + suffix -= nums[i]; + const int prefixAvg = prefix / (i + 1); + const int suffixAvg = (i == n - 1) ? 0 : suffix / (n - 1 - i); + const int diff = abs(prefixAvg - suffixAvg); + if (diff < minDiff) { + ans = i; + minDiff = diff; + } + } + + return ans; + } +}; diff --git a/solutions/2256. Minimum Average Difference/2256.java b/solutions/2256. Minimum Average Difference/2256.java new file mode 100644 index 00000000000..677380a40a7 --- /dev/null +++ b/solutions/2256. Minimum Average Difference/2256.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumAverageDifference(int[] nums) { + final int n = nums.length; + int ans = 0; + int minDiff = Integer.MAX_VALUE; + long prefix = 0; + long suffix = Arrays.stream(nums).asLongStream().sum(); + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i]; + suffix -= nums[i]; + final int prefixAvg = (int) (prefix / (i + 1)); + final int suffixAvg = (i == n - 1) ? 0 : (int) (suffix / (n - 1 - i)); + final int diff = Math.abs(prefixAvg - suffixAvg); + if (diff < minDiff) { + ans = i; + minDiff = diff; + } + } + + return ans; + } +} diff --git a/solutions/2256. Minimum Average Difference/2256.py b/solutions/2256. Minimum Average Difference/2256.py new file mode 100644 index 00000000000..a30ae73e13a --- /dev/null +++ b/solutions/2256. Minimum Average Difference/2256.py @@ -0,0 +1,19 @@ +class Solution: + def minimumAverageDifference(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + minDiff = inf + prefix = 0 + suffix = sum(nums) + + for i, num in enumerate(nums): + prefix += num + suffix -= num + prefixAvg = prefix // (i + 1) + suffixAvg = 0 if i == n - 1 else suffix // (n - 1 - i) + diff = abs(prefixAvg - suffixAvg) + if diff < minDiff: + ans = i + minDiff = diff + + return ans diff --git a/solutions/2257. Count Unguarded Cells in the Grid/2257.cpp b/solutions/2257. Count Unguarded Cells in the Grid/2257.cpp new file mode 100644 index 00000000000..d8c4f8fe067 --- /dev/null +++ b/solutions/2257. Count Unguarded Cells in the Grid/2257.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int countUnguarded(int m, int n, vector>& guards, + vector>& walls) { + int ans = 0; + vector> grid(m, vector(n)); + vector> left(m, vector(n)); + vector> right(m, vector(n)); + vector> up(m, vector(n)); + vector> down(m, vector(n)); + + for (const vector& guard : guards) + grid[guard[0]][guard[1]] = 'G'; + + for (const vector& wall : walls) + grid[wall[0]][wall[1]] = 'W'; + + for (int i = 0; i < m; ++i) { + char lastCell = 0; + for (int j = 0; j < n; ++j) + recordOrFill(grid[i][j], lastCell, left[i][j]); + lastCell = 0; + for (int j = n - 1; j >= 0; --j) + recordOrFill(grid[i][j], lastCell, right[i][j]); + } + + for (int j = 0; j < n; ++j) { + char lastCell = 0; + for (int i = 0; i < m; ++i) + recordOrFill(grid[i][j], lastCell, up[i][j]); + lastCell = 0; + for (int i = m - 1; i >= 0; --i) + recordOrFill(grid[i][j], lastCell, down[i][j]); + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0 && left[i][j] != 'G' && right[i][j] != 'G' && + up[i][j] != 'G' && down[i][j] != 'G') + ++ans; + + return ans; + } + + private: + void recordOrFill(char currCell, char& lastCell, char& infoCell) { + if (currCell == 'G' || currCell == 'W') + lastCell = currCell; + else + infoCell = lastCell; + } +}; diff --git a/solutions/2257. Count Unguarded Cells in the Grid/2257.java b/solutions/2257. Count Unguarded Cells in the Grid/2257.java new file mode 100644 index 00000000000..d6c66306061 --- /dev/null +++ b/solutions/2257. Count Unguarded Cells in the Grid/2257.java @@ -0,0 +1,54 @@ +class Solution { + public int countUnguarded(int m, int n, int[][] guards, int[][] walls) { + int ans = 0; + char[][] grid = new char[m][n]; + char[][] left = new char[m][n]; + char[][] right = new char[m][n]; + char[][] up = new char[m][n]; + char[][] down = new char[m][n]; + + for (int[] guard : guards) + grid[guard[0]][guard[1]] = 'G'; + + for (int[] wall : walls) + grid[wall[0]][wall[1]] = 'W'; + + for (int i = 0; i < m; ++i) { + char lastCell = 0; + for (int j = 0; j < n; ++j) + if (grid[i][j] == 'G' || grid[i][j] == 'W') + lastCell = grid[i][j]; + else + left[i][j] = lastCell; + lastCell = 0; + for (int j = n - 1; j >= 0; --j) + if (grid[i][j] == 'G' || grid[i][j] == 'W') + lastCell = grid[i][j]; + else + right[i][j] = lastCell; + } + + for (int j = 0; j < n; ++j) { + char lastCell = 0; + for (int i = 0; i < m; ++i) + if (grid[i][j] == 'G' || grid[i][j] == 'W') + lastCell = grid[i][j]; + else + up[i][j] = lastCell; + lastCell = 0; + for (int i = m - 1; i >= 0; --i) + if (grid[i][j] == 'G' || grid[i][j] == 'W') + lastCell = grid[i][j]; + else + down[i][j] = lastCell; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0 && left[i][j] != 'G' && right[i][j] != 'G' && up[i][j] != 'G' && + down[i][j] != 'G') + ++ans; + + return ans; + } +} diff --git a/solutions/2257. Count Unguarded Cells in the Grid/2257.py b/solutions/2257. Count Unguarded Cells in the Grid/2257.py new file mode 100644 index 00000000000..cb6da6c8eaf --- /dev/null +++ b/solutions/2257. Count Unguarded Cells in the Grid/2257.py @@ -0,0 +1,50 @@ +class Solution: + def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int: + ans = 0 + grid = [[0] * n for _ in range(m)] + left = [[0] * n for _ in range(m)] + right = [[0] * n for _ in range(m)] + up = [[0] * n for _ in range(m)] + down = [[0] * n for _ in range(m)] + + for row, col in guards: + grid[row][col] = 'G' + + for row, col in walls: + grid[row][col] = 'W' + + for i in range(m): + lastCell = 0 + for j in range(n): + if grid[i][j] == 'G' or grid[i][j] == 'W': + lastCell = grid[i][j] + else: + left[i][j] = lastCell + lastCell = 0 + for j in range(n - 1, -1, -1): + if grid[i][j] == 'G' or grid[i][j] == 'W': + lastCell = grid[i][j] + else: + right[i][j] = lastCell + + for j in range(n): + lastCell = 0 + for i in range(m): + if grid[i][j] == 'G' or grid[i][j] == 'W': + lastCell = grid[i][j] + else: + up[i][j] = lastCell + lastCell = 0 + for i in range(m - 1, -1, -1): + if grid[i][j] == 'G' or grid[i][j] == 'W': + lastCell = grid[i][j] + else: + down[i][j] = lastCell + + for i in range(m): + for j in range(n): + if grid[i][j] == 0 and left[i][j] != 'G' and right[i][j] != 'G' and \ + up[i][j] != 'G' and down[i][j] != 'G': + ans += 1 + + return ans diff --git a/solutions/2258. Escape the Spreading Fire/2258.cpp b/solutions/2258. Escape the Spreading Fire/2258.cpp new file mode 100644 index 00000000000..81c523db16d --- /dev/null +++ b/solutions/2258. Escape the Spreading Fire/2258.cpp @@ -0,0 +1,97 @@ +class Solution { + public: + int maximumMinutes(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int kMax = grid.size() * grid[0].size(); + vector> fireMinute(grid.size(), + vector(grid[0].size(), -1)); + buildFireGrid(grid, fireMinute, dirs); + + int ans = -1; + int l = 0; + int r = kMax; + + while (l <= r) { + const int m = (l + r) / 2; + if (canStayFor(grid, fireMinute, m, dirs)) { + ans = m; + l = m + 1; + } else { + r = m - 1; + } + } + + return ans == kMax ? 1e9 : ans; + } + + private: + void buildFireGrid(const vector>& grid, + vector>& fireMinute, const vector& dirs) { + int minuteFromFire = 0; + queue> q; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == 1) { // the fire + q.emplace(i, j); + fireMinute[i][j] = 0; + } + + while (!q.empty()) { + ++minuteFromFire; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) + continue; + if (grid[x][y] == 2) // the wall + continue; + if (fireMinute[x][y] != -1) + continue; + fireMinute[x][y] = minuteFromFire; + q.emplace(x, y); + } + } + } + } + + bool canStayFor(const vector>& grid, + const vector>& fireMinute, int minute, + const vector& dirs) { + queue> q{{{0, 0}}}; // the start position + vector> seen(grid.size(), vector(grid[0].size())); + seen[0][0] = true; + + while (!q.empty()) { + ++minute; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) + continue; + if (grid[x][y] == 2) // the wall + continue; + if (x == grid.size() - 1 && y == grid[0].size() - 1) { + if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute) + continue; + return true; + } + if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute) + continue; + if (seen[x][y]) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + } + + return false; + } +}; diff --git a/solutions/2258. Escape the Spreading Fire/2258.java b/solutions/2258. Escape the Spreading Fire/2258.java new file mode 100644 index 00000000000..e32838947a1 --- /dev/null +++ b/solutions/2258. Escape the Spreading Fire/2258.java @@ -0,0 +1,93 @@ +class Solution { + public int maximumMinutes(int[][] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int kMax = grid.length * grid[0].length; + int[][] fireMinute = new int[grid.length][grid[0].length]; + Arrays.stream(fireMinute).forEach(A -> Arrays.fill(A, -1)); + buildFireGrid(grid, fireMinute, dirs); + + int ans = -1; + int l = 0; + int r = kMax; + + while (l <= r) { + final int m = (l + r) / 2; + if (canStayFor(grid, fireMinute, m, dirs)) { + ans = m; + l = m + 1; + } else { + r = m - 1; + } + } + + return ans == kMax ? (int) 1e9 : ans; + } + + private void buildFireGrid(int[][] grid, int[][] fireMinute, final int[] dirs) { + int minuteFromFire = 0; + Queue> q = new ArrayDeque<>(); + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 1) { // the fire + q.offer(new Pair<>(i, j)); + fireMinute[i][j] = 0; + } + + while (!q.isEmpty()) { + ++minuteFromFire; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) + continue; + if (grid[x][y] == 2) // the wall + continue; + if (fireMinute[x][y] != -1) + continue; + fireMinute[x][y] = minuteFromFire; + q.offer(new Pair<>(x, y)); + } + } + } + } + + boolean canStayFor(int[][] grid, int[][] fireMinute, int minute, final int[] dirs) { + Queue> q = + new ArrayDeque<>(Arrays.asList(new Pair<>(0, 0))); // the start position + boolean[][] seen = new boolean[grid.length][grid[0].length]; + seen[0][0] = true; + + while (!q.isEmpty()) { + ++minute; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) + continue; + if (grid[x][y] == 2) // the wall + continue; + if (x == grid.length - 1 && y == grid[0].length - 1) { + if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute) + continue; + return true; + } + if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute) + continue; + if (seen[x][y]) + continue; + q.offer(new Pair<>(x, y)); + seen[x][y] = true; + } + } + } + + return false; + } +} diff --git a/solutions/2258. Escape the Spreading Fire/2258.py b/solutions/2258. Escape the Spreading Fire/2258.py new file mode 100644 index 00000000000..a03abf69518 --- /dev/null +++ b/solutions/2258. Escape the Spreading Fire/2258.py @@ -0,0 +1,74 @@ +class Solution: + def maximumMinutes(self, grid: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + kMax = len(grid) * len(grid[0]) + fireGrid = [[-1] * len(grid[0]) for _ in range(len(grid[0]))] + self._buildFireGrid(grid, fireGrid, dirs) + + ans = -1 + l = 0 + r = kMax + + while l <= r: + m = (l + r) // 2 + if self._canStayFor(grid, fireGrid, m, dirs): + ans = m + l = m + 1 + else: + r = m - 1 + + return 1e9 if ans == kMax else ans + + def _buildFireGrid(self, grid: List[List[int]], fireMinute: List[List[int]], dirs: List[int]) -> None: + minuteFromFire = 0 + q = collections.deque() + + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1: # the fire + q.append((i, j)) + fireMinute[i][j] = 0 + + while q: + minuteFromFire += 1 + for _ in range(len(q)): + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]): + continue + if grid[x][y] == 2: # the wall + continue + if fireMinute[x][y] != -1: + continue + fireMinute[x][y] = minuteFromFire + q.append((x, y)) + + def _canStayFor(self, grid: List[List[int]], fireMinute: List[List[int]], minute: int, dirs: List[int]) -> bool: + q = collections.deque([(0, 0)]) # the start position + seen = {(0, 0)} + + while q: + minute += 1 + for _ in range(len(q)): + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]): + continue + if grid[x][y] == 2: # the wall + continue + if x == len(grid) - 1 and y == len(grid[0]) - 1: + if fireMinute[x][y] != -1 and fireMinute[x][y] < minute: + continue + return True + if fireMinute[x][y] != -1 and fireMinute[x][y] <= minute: + continue + if seen[x][y]: + continue + q.append((x, y)) + seen.add((x, y)) + + return False diff --git a/solutions/2259. Remove Digit From Number to Maximize Result/2259.cpp b/solutions/2259. Remove Digit From Number to Maximize Result/2259.cpp new file mode 100644 index 00000000000..ef941627783 --- /dev/null +++ b/solutions/2259. Remove Digit From Number to Maximize Result/2259.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + string removeDigit(string number, char digit) { + for (int i = 0; i + 1 < number.length(); ++i) + if (number[i] == digit && digit < number[i + 1]) + return number.erase(i, 1); + return number.erase(number.rfind(digit), 1); + } +}; diff --git a/solutions/2259. Remove Digit From Number to Maximize Result/2259.java b/solutions/2259. Remove Digit From Number to Maximize Result/2259.java new file mode 100644 index 00000000000..c804b45ab57 --- /dev/null +++ b/solutions/2259. Remove Digit From Number to Maximize Result/2259.java @@ -0,0 +1,8 @@ +class Solution { + public String removeDigit(String number, char digit) { + for (int i = 0; i + 1 < number.length(); ++i) + if (number.charAt(i) == digit && digit < number.charAt(i + 1)) + return new StringBuilder(number).deleteCharAt(i).toString(); + return new StringBuilder(number).deleteCharAt(number.lastIndexOf(digit)).toString(); + } +} diff --git a/solutions/2259. Remove Digit From Number to Maximize Result/2259.py b/solutions/2259. Remove Digit From Number to Maximize Result/2259.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/solutions/226. Invert Binary Tree/226.cpp b/solutions/226. Invert Binary Tree/226.cpp new file mode 100644 index 00000000000..02bcd6a238f --- /dev/null +++ b/solutions/226. Invert Binary Tree/226.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + TreeNode* invertTree(TreeNode* root) { + if (root == nullptr) + return nullptr; + + TreeNode* const left = root->left; + TreeNode* const right = root->right; + root->left = invertTree(right); + root->right = invertTree(left); + return root; + } +}; diff --git a/solutions/226. Invert Binary Tree/226.java b/solutions/226. Invert Binary Tree/226.java new file mode 100644 index 00000000000..296878800a6 --- /dev/null +++ b/solutions/226. Invert Binary Tree/226.java @@ -0,0 +1,12 @@ +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) + return null; + + TreeNode left = root.left; + TreeNode right = root.right; + root.left = invertTree(right); + root.right = invertTree(left); + return root; + } +} diff --git a/solutions/226. Invert Binary Tree/226.py b/solutions/226. Invert Binary Tree/226.py new file mode 100644 index 00000000000..5112bb2ca2c --- /dev/null +++ b/solutions/226. Invert Binary Tree/226.py @@ -0,0 +1,10 @@ +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: + return None + + left = root.left + right = root.right + root.left = self.invertTree(right) + root.right = self.invertTree(left) + return root diff --git a/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.cpp b/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.cpp new file mode 100644 index 00000000000..3623ce78696 --- /dev/null +++ b/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minimumCardPickup(vector& cards) { + int ans = INT_MAX; + unordered_map lastSeen; + + for (int i = 0; i < cards.size(); ++i) { + if (const auto it = lastSeen.find(cards[i]); it != lastSeen.cend()) + ans = min(ans, i - it->second + 1); + lastSeen[cards[i]] = i; + } + + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.java b/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.java new file mode 100644 index 00000000000..6ddbdf20fc4 --- /dev/null +++ b/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.java @@ -0,0 +1,14 @@ +class Solution { + public int minimumCardPickup(int[] cards) { + int ans = Integer.MAX_VALUE; + Map lastSeen = new HashMap<>(); + + for (int i = 0; i < cards.length; ++i) { + if (lastSeen.containsKey(cards[i])) + ans = Math.min(ans, i - lastSeen.get(cards[i]) + 1); + lastSeen.put(cards[i], i); + } + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.py b/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.py new file mode 100644 index 00000000000..b6942f834fa --- /dev/null +++ b/solutions/2260. Minimum Consecutive Cards to Pick Up/2260.py @@ -0,0 +1,11 @@ +class Solution: + def minimumCardPickup(self, cards: List[int]) -> int: + ans = math.inf + lastSeen = {} + + for i, card in enumerate(cards): + if card in lastSeen: + ans = min(ans, i - lastSeen[card] + 1) + lastSeen[card] = i + + return -1 if ans == math.inf else ans diff --git a/solutions/2261. K Divisible Elements Subarrays/2261.cpp b/solutions/2261. K Divisible Elements Subarrays/2261.cpp new file mode 100644 index 00000000000..af36d4010a3 --- /dev/null +++ b/solutions/2261. K Divisible Elements Subarrays/2261.cpp @@ -0,0 +1,29 @@ +struct TrieNode { + unordered_map> children; + int count = 0; +}; + +class Solution { + public: + int countDistinct(vector& nums, int k, int p) { + int ans = 0; + for (int i = 0; i < nums.size(); ++i) + insert(root, nums, i, k, p, ans); + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(shared_ptr node, const vector& nums, int i, int k, + int p, int& ans) { + if (i == nums.size() || k - (nums[i] % p == 0) < 0) + return; + if (!node->children.contains(nums[i])) { + node->children[nums[i]] = make_shared(); + ++ans; + } + insert(node->children[nums[i]], nums, i + 1, k - (nums[i] % p == 0), p, + ans); + } +}; diff --git a/solutions/2261. K Divisible Elements Subarrays/2261.java b/solutions/2261. K Divisible Elements Subarrays/2261.java new file mode 100644 index 00000000000..0186d0b1eaa --- /dev/null +++ b/solutions/2261. K Divisible Elements Subarrays/2261.java @@ -0,0 +1,25 @@ +class TrieNode { + public Map children = new HashMap<>(); + public int count = 0; +} + +class Solution { + public int countDistinct(int[] nums, int k, int p) { + for (int i = 0; i < nums.length; ++i) + insert(root, nums, i, k, p); + return ans; + } + + private int ans = 0; + private TrieNode root = new TrieNode(); + + private void insert(TrieNode node, int[] nums, int i, int k, int p) { + if (i == nums.length || k - (nums[i] % p == 0 ? 1 : 0) < 0) + return; + if (!node.children.containsKey(nums[i])) { + node.children.put(nums[i], new TrieNode()); + ++ans; + } + insert(node.children.get(nums[i]), nums, i + 1, k - (nums[i] % p == 0 ? 1 : 0), p); + } +} diff --git a/solutions/2261. K Divisible Elements Subarrays/2261.py b/solutions/2261. K Divisible Elements Subarrays/2261.py new file mode 100644 index 00000000000..2ff4d449b5a --- /dev/null +++ b/solutions/2261. K Divisible Elements Subarrays/2261.py @@ -0,0 +1,24 @@ +class TrieNode: + def __init__(self): + self.children: Dict[int, TrieNode] = {} + self.count = 0 + + +class Solution: + def countDistinct(self, nums: List[int], k: int, p: int) -> int: + ans = 0 + root = TrieNode() + + def insert(node: TrieNode, i: int, k: int): + nonlocal ans + if i == len(nums) or k - (nums[i] % p == 0) < 0: + return + if nums[i] not in node.children: + node.children[nums[i]] = TrieNode() + ans += 1 + insert(node.children[nums[i]], i + 1, k - (nums[i] % p == 0)) + + for i in range(len(nums)): + insert(root, i, k) + + return ans diff --git a/solutions/2262. Total Appeal of A String/2262-2.cpp b/solutions/2262. Total Appeal of A String/2262-2.cpp new file mode 100644 index 00000000000..2f89c6b0c5b --- /dev/null +++ b/solutions/2262. Total Appeal of A String/2262-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + long long appealSum(string s) { + const int n = s.length(); + long ans = 0; + vector lastSeen(26, -1); + + for (int i = 0; i < n; ++i) { + const int c = s[i] - 'a'; + ans += (i - lastSeen[c]) * (n - i); + lastSeen[c] = i; + } + + return ans; + } +}; diff --git a/solutions/2262. Total Appeal of A String/2262-2.java b/solutions/2262. Total Appeal of A String/2262-2.java new file mode 100644 index 00000000000..cced7b318c6 --- /dev/null +++ b/solutions/2262. Total Appeal of A String/2262-2.java @@ -0,0 +1,16 @@ +class Solution { + public long appealSum(String s) { + final int n = s.length(); + long ans = 0; + int[] lastSeen = new int[26]; + Arrays.fill(lastSeen, -1); + + for (int i = 0; i < n; ++i) { + final int c = s.charAt(i) - 'a'; + ans += (i - lastSeen[c]) * (n - i); + lastSeen[c] = i; + } + + return ans; + } +} diff --git a/solutions/2262. Total Appeal of A String/2262-2.py b/solutions/2262. Total Appeal of A String/2262-2.py new file mode 100644 index 00000000000..641fda194c7 --- /dev/null +++ b/solutions/2262. Total Appeal of A String/2262-2.py @@ -0,0 +1,10 @@ +class Solution: + def appealSum(self, s: str) -> int: + ans = 0 + lastSeen = {} + + for i, c in enumerate(s): + ans += (i - lastSeen.get(c, -1)) * (len(s) - i) + lastSeen[c] = i + + return ans diff --git a/solutions/2262. Total Appeal of A String/2262.cpp b/solutions/2262. Total Appeal of A String/2262.cpp new file mode 100644 index 00000000000..d1c0bbfd240 --- /dev/null +++ b/solutions/2262. Total Appeal of A String/2262.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long appealSum(string s) { + long ans = 0; + // the total appeal of all substrings ending in the index so far + int dp = 0; + vector lastSeen(26, -1); + + for (int i = 0; i < s.length(); ++i) { + // the total appeal of all substrings ending in s[i] + // = the total appeal of all substrings ending in s[i - 1] + // + the number of substrings ending in s[i] that contain only this s[i] + const int c = s[i] - 'a'; + dp += i - lastSeen[c]; + ans += dp; + lastSeen[c] = i; + } + + return ans; + } +}; diff --git a/solutions/2262. Total Appeal of A String/2262.java b/solutions/2262. Total Appeal of A String/2262.java new file mode 100644 index 00000000000..e9282292abd --- /dev/null +++ b/solutions/2262. Total Appeal of A String/2262.java @@ -0,0 +1,21 @@ +class Solution { + public long appealSum(String s) { + long ans = 0; + // the total appeal of all substrings ending in the index so far + int dp = 0; + int[] lastSeen = new int[26]; + Arrays.fill(lastSeen, -1); + + for (int i = 0; i < s.length(); ++i) { + // the total appeal of all substrings ending in s[i] + // = the total appeal of all substrings ending in s[i - 1] + // + the number of substrings ending in s[i] that contain only this s[i] + final int c = s.charAt(i) - 'a'; + dp += i - lastSeen[c]; + ans += dp; + lastSeen[c] = i; + } + + return ans; + } +} diff --git a/solutions/2262. Total Appeal of A String/2262.py b/solutions/2262. Total Appeal of A String/2262.py new file mode 100644 index 00000000000..4025e4ceb1d --- /dev/null +++ b/solutions/2262. Total Appeal of A String/2262.py @@ -0,0 +1,16 @@ +class Solution: + def appealSum(self, s: str) -> int: + ans = 0 + # the total appeal of all substrings ending in the index so far + dp = 0 + lastSeen = {} + + for i, c in enumerate(s): + # the total appeal of all substrings ending in s[i] + # = the total appeal of all substrings ending in s[i - 1] + # + the number of substrings ending in s[i] that contain only this s[i] + dp += i - lastSeen.get(c, -1) + ans += dp + lastSeen[c] = i + + return ans diff --git a/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.cpp b/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.cpp new file mode 100644 index 00000000000..87494ce89e8 --- /dev/null +++ b/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int convertArray(vector& nums) { + return min(cost(nums), cost(negative(nums))); + } + + private: + int cost(const vector& nums) { + int ans = 0; + priority_queue maxHeap; + + // Greedily make `nums` non-decreasing. + for (const int num : nums) { + if (!maxHeap.empty() && maxHeap.top() > num) { + ans += maxHeap.top() - num, maxHeap.pop(); + maxHeap.push(num); + } + maxHeap.push(num); + } + + return ans; + } + + vector negative(const vector& nums) { + vector A(nums); + for (int& a : A) + a *= -1; + return A; + } +}; diff --git a/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.java b/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.java new file mode 100644 index 00000000000..62df5c3fba6 --- /dev/null +++ b/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.java @@ -0,0 +1,28 @@ +class Solution { + public int convertArray(int[] nums) { + return Math.min(cost(nums), cost(negative(nums))); + } + + private int cost(int[] nums) { + int ans = 0; + Queue maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); + + // Greedily make `nums` non-decreasing. + for (final int num : nums) { + if (!maxHeap.isEmpty() && maxHeap.peek() > num) { + ans += maxHeap.poll() - num; + maxHeap.offer(num); + } + maxHeap.offer(num); + } + + return ans; + } + + private int[] negative(int[] nums) { + int[] A = nums.clone(); + for (int i = 0; i < A.length; ++i) + A[i] *= -1; + return A; + } +} diff --git a/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.py b/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.py new file mode 100644 index 00000000000..228120da5c8 --- /dev/null +++ b/solutions/2263. Make Array Non-decreasing or Non-increasing/2263.py @@ -0,0 +1,15 @@ +class Solution: + def convertArray(self, nums: List[int]) -> int: + def cost(nums: List[int]) -> int: + ans = 0 + minHeap = [] + + # Greedily make `nums` non-increasing. + for num in nums: + if minHeap and minHeap[0] < num: + ans += num - heapq.heappushpop(minHeap, num) + heapq.heappush(minHeap, num) + + return ans + + return min(cost(nums), cost([-num for num in nums])) diff --git a/solutions/2264. Largest 3-Same-Digit Number in String/2264.cpp b/solutions/2264. Largest 3-Same-Digit Number in String/2264.cpp new file mode 100644 index 00000000000..f08eabb0643 --- /dev/null +++ b/solutions/2264. Largest 3-Same-Digit Number in String/2264.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + string largestGoodInteger(string num) { + string ans; + + for (int i = 2; i < num.length(); ++i) + if (num[i - 2] == num[i - 1] && num[i - 1] == num[i]) + ans = max(ans, num.substr(i - 2, 3)); + + return ans; + } +}; diff --git a/solutions/2264. Largest 3-Same-Digit Number in String/2264.java b/solutions/2264. Largest 3-Same-Digit Number in String/2264.java new file mode 100644 index 00000000000..8299e610da6 --- /dev/null +++ b/solutions/2264. Largest 3-Same-Digit Number in String/2264.java @@ -0,0 +1,12 @@ +class Solution { + public String largestGoodInteger(String num) { + String ans = ""; + + for (int i = 2; i < num.length(); ++i) + if (num.charAt(i - 2) == num.charAt(i - 1) && num.charAt(i - 1) == num.charAt(i) && + num.substring(i - 2, i + 1).compareTo(ans) > 0) + ans = num.substring(i - 2, i + 1); + + return ans; + } +} diff --git a/solutions/2264. Largest 3-Same-Digit Number in String/2264.py b/solutions/2264. Largest 3-Same-Digit Number in String/2264.py new file mode 100644 index 00000000000..10b8cab72c3 --- /dev/null +++ b/solutions/2264. Largest 3-Same-Digit Number in String/2264.py @@ -0,0 +1,5 @@ +class Solution: + def largestGoodInteger(self, num: str) -> str: + return max(num[i - 2:i + 1] + if num[i] == num[i - 1] == num[i - 2] + else '' for i in range(2, len(num))) diff --git a/solutions/2265. Count Nodes Equal to Average of Subtree/2265.cpp b/solutions/2265. Count Nodes Equal to Average of Subtree/2265.cpp new file mode 100644 index 00000000000..cfc17dff8e0 --- /dev/null +++ b/solutions/2265. Count Nodes Equal to Average of Subtree/2265.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int averageOfSubtree(TreeNode* root) { + int ans = 0; + dfs(root, ans); + return ans; + } + + private: + pair dfs(TreeNode* root, int& ans) { + if (root == nullptr) + return {0, 0}; + const auto [leftSum, leftCount] = dfs(root->left, ans); + const auto [rightSum, rightCount] = dfs(root->right, ans); + const int sum = root->val + leftSum + rightSum; + const int count = 1 + leftCount + rightCount; + if (sum / count == root->val) + ++ans; + return {sum, count}; + } +}; diff --git a/solutions/2265. Count Nodes Equal to Average of Subtree/2265.java b/solutions/2265. Count Nodes Equal to Average of Subtree/2265.java new file mode 100644 index 00000000000..7e9b8301222 --- /dev/null +++ b/solutions/2265. Count Nodes Equal to Average of Subtree/2265.java @@ -0,0 +1,20 @@ +class Solution { + public int averageOfSubtree(TreeNode root) { + dfs(root); + return ans; + } + + private int ans = 0; + + private Pair dfs(TreeNode root) { + if (root == null) + return new Pair<>(0, 0); + Pair left = dfs(root.left); + Pair right = dfs(root.right); + final int sum = root.val + left.getKey() + right.getKey(); + final int count = 1 + left.getValue() + right.getValue(); + if (sum / count == root.val) + ++ans; + return new Pair<>(sum, count); + } +} diff --git a/solutions/2265. Count Nodes Equal to Average of Subtree/2265.py b/solutions/2265. Count Nodes Equal to Average of Subtree/2265.py new file mode 100644 index 00000000000..a8c05bb7834 --- /dev/null +++ b/solutions/2265. Count Nodes Equal to Average of Subtree/2265.py @@ -0,0 +1,18 @@ +class Solution: + def averageOfSubtree(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def dfs(root: Optional[TreeNode]) -> Tuple[int, int]: + nonlocal ans + if not root: + return (0, 0) + leftSum, leftCount = dfs(root.left) + rightSum, rightCount = dfs(root.right) + summ = root.val + leftSum + rightSum + count = 1 + leftCount + rightCount + if summ // count == root.val: + ans += 1 + return (summ, count) + + dfs(root) + return ans diff --git a/solutions/2266. Count Number of Texts/2266.cpp b/solutions/2266. Count Number of Texts/2266.cpp new file mode 100644 index 00000000000..10905357fe0 --- /dev/null +++ b/solutions/2266. Count Number of Texts/2266.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int countTexts(string pressedKeys) { + constexpr int kMod = 1'000'000'007; + const int n = pressedKeys.length(); + // dp[i] := the number of possible text messages of pressedKeys[i..n) + vector dp(n + 1); + dp[n] = 1; // "" + + for (int i = n - 1; i >= 0; --i) { + dp[i] = dp[i + 1]; + if (isSame(pressedKeys, i, 2)) + dp[i] += dp[i + 2]; + if (isSame(pressedKeys, i, 3)) + dp[i] += dp[i + 3]; + if ((pressedKeys[i] == '7' || pressedKeys[i] == '9') && + isSame(pressedKeys, i, 4)) + dp[i] += dp[i + 4]; + dp[i] %= kMod; + } + + return dp[0]; + } + + private: + // Returns true if s[i..i + k) are the same digits. + bool isSame(const string& s, int i, int k) { + if (i + k > s.length()) + return false; + for (int j = i + 1; j < i + k; ++j) + if (s[j] != s[i]) + return false; + return true; + } +}; diff --git a/solutions/2266. Count Number of Texts/2266.java b/solutions/2266. Count Number of Texts/2266.java new file mode 100644 index 00000000000..6c74b6f3a25 --- /dev/null +++ b/solutions/2266. Count Number of Texts/2266.java @@ -0,0 +1,33 @@ +class Solution { + public int countTexts(String pressedKeys) { + final int kMod = 1_000_000_007; + final int n = pressedKeys.length(); + // dp[i] := the number of possible text messages of pressedKeys[i..n) + long[] dp = new long[n + 1]; + dp[n] = 1; // "" + + for (int i = n - 1; i >= 0; --i) { + dp[i] = dp[i + 1]; + if (isSame(pressedKeys, i, 2)) + dp[i] += dp[i + 2]; + if (isSame(pressedKeys, i, 3)) + dp[i] += dp[i + 3]; + if ((pressedKeys.charAt(i) == '7' || pressedKeys.charAt(i) == '9') && + isSame(pressedKeys, i, 4)) + dp[i] += dp[i + 4]; + dp[i] %= kMod; + } + + return (int) dp[0]; + } + + // Returns true if s[i..i + k) are the same digits. + private boolean isSame(final String s, int i, int k) { + if (i + k > s.length()) + return false; + for (int j = i + 1; j < i + k; ++j) + if (s.charAt(j) != s.charAt(i)) + return false; + return true; + } +} diff --git a/solutions/2266. Count Number of Texts/2266.py b/solutions/2266. Count Number of Texts/2266.py new file mode 100644 index 00000000000..44ba42b8243 --- /dev/null +++ b/solutions/2266. Count Number of Texts/2266.py @@ -0,0 +1,28 @@ +class Solution: + def countTexts(self, pressedKeys: str) -> int: + kMod = 1_000_000_007 + n = len(pressedKeys) + # dp[i] := the number of possible text messages of pressedKeys[i..n) + dp = [0] * n + [1] + + def isSame(s: str, i: int, k: int) -> bool: + """Returns True if s[i..i + k) are the same digits.""" + if i + k > len(s): + return False + for j in range(i + 1, i + k): + if s[j] != s[i]: + return False + return True + + for i in reversed(range(n)): + dp[i] = dp[i + 1] + if isSame(pressedKeys, i, 2): + dp[i] += dp[i + 2] + if isSame(pressedKeys, i, 3): + dp[i] += dp[i + 3] + if (pressedKeys[i] == '7' or pressedKeys[i] == '9') and \ + isSame(pressedKeys, i, 4): + dp[i] += dp[i + 4] + dp[i] %= kMod + + return dp[0] diff --git a/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.cpp b/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.cpp new file mode 100644 index 00000000000..bb229e17eb9 --- /dev/null +++ b/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool hasValidPath(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector>> mem( + m, vector>(n, vector(m + n, -1))); + return hasValidPath(grid, 0, 0, 0, mem); + } + + private: + // Returns true if there's a path from grid[i][j] to grid[m - 1][n - 1], where + // the number of '(' - the number of ')' == k. + bool hasValidPath(const vector>& grid, int i, int j, int k, + vector>>& mem) { + if (i == grid.size() || j == grid[0].size()) + return false; + k += grid[i][j] == '(' ? 1 : -1; + if (k < 0) + return false; + if (i == grid.size() - 1 && j == grid[0].size() - 1) + return k == 0; + if (mem[i][j][k] != -1) + return mem[i][j][k]; + return mem[i][j][k] = hasValidPath(grid, i + 1, j, k, mem) | + hasValidPath(grid, i, j + 1, k, mem); + } +}; diff --git a/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.java b/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.java new file mode 100644 index 00000000000..beae75ee07a --- /dev/null +++ b/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.java @@ -0,0 +1,24 @@ +class Solution { + public boolean hasValidPath(char[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + Boolean[][][] mem = new Boolean[m][n][m + n]; + return hasValidPath(grid, 0, 0, 0, mem); + } + + // Returns true if there's a path from grid[i][j] to grid[m - 1][n - 1], where + // the number of '(' - the number of ')' == k. + private boolean hasValidPath(char[][] grid, int i, int j, int k, Boolean[][][] mem) { + if (i == grid.length || j == grid[0].length) + return false; + k += grid[i][j] == '(' ? 1 : -1; + if (k < 0) + return false; + if (i == grid.length - 1 && j == grid[0].length - 1) + return k == 0; + if (mem[i][j][k] != null) + return mem[i][j][k]; + return mem[i][j][k] = hasValidPath(grid, i + 1, j, k, mem) | // + hasValidPath(grid, i, j + 1, k, mem); + } +} diff --git a/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.py b/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.py new file mode 100644 index 00000000000..e937df818a4 --- /dev/null +++ b/solutions/2267. Check if There Is a Valid Parentheses String Path/2267.py @@ -0,0 +1,18 @@ +class Solution: + def hasValidPath(self, grid: List[List[str]]) -> bool: + @functools.lru_cache(None) + def dp(i: int, j: int, k: int) -> bool: + """ + Returns True if there's a path from grid[i][j] to grid[m - 1][n - 1], + where the number of '(' - the number of ')' == k. + """ + if i == len(grid) or j == len(grid[0]): + return False + k += 1 if grid[i][j] == '(' else -1 + if k < 0: + return False + if i == len(grid) - 1 and j == len(grid[0]) - 1: + return k == 0 + return dp(i + 1, j, k) | dp(i, j + 1, k) + + return dp(0, 0, 0) diff --git a/solutions/2268. Minimum Number of Keypresses/2268.cpp b/solutions/2268. Minimum Number of Keypresses/2268.cpp new file mode 100644 index 00000000000..5e6378dde33 --- /dev/null +++ b/solutions/2268. Minimum Number of Keypresses/2268.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minimumKeypresses(string s) { + int ans = 0; + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + ranges::sort(count, greater<>()); + + for (int i = 0; i < 26; ++i) + ans += count[i] * (i / 9 + 1); + + return ans; + } +}; diff --git a/solutions/2268. Minimum Number of Keypresses/2268.java b/solutions/2268. Minimum Number of Keypresses/2268.java new file mode 100644 index 00000000000..a6293282d6b --- /dev/null +++ b/solutions/2268. Minimum Number of Keypresses/2268.java @@ -0,0 +1,17 @@ +class Solution { + public int minimumKeypresses(String s) { + int ans = 0; + Integer[] count = new Integer[26]; + Arrays.fill(count, 0); + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + Arrays.sort(count, (a, b) -> b - a); + + for (int i = 0; i < 26; ++i) + ans += count[i] * (i / 9 + 1); + + return ans; + } +} diff --git a/solutions/2268. Minimum Number of Keypresses/2268.py b/solutions/2268. Minimum Number of Keypresses/2268.py new file mode 100644 index 00000000000..18306dd43ad --- /dev/null +++ b/solutions/2268. Minimum Number of Keypresses/2268.py @@ -0,0 +1,4 @@ +class Solution: + def minimumKeypresses(self, s: str) -> int: + return sum(c * (i // 9 + 1) + for i, c in enumerate(sorted(Counter(s).values(), reverse=True))) diff --git a/solutions/2269. Find the K-Beauty of a Number/2269.cpp b/solutions/2269. Find the K-Beauty of a Number/2269.cpp new file mode 100644 index 00000000000..b729edab9ae --- /dev/null +++ b/solutions/2269. Find the K-Beauty of a Number/2269.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int divisorSubstrings(int num, int k) { + const string s = to_string(num); + int ans = 0; + + for (int i = 0; i + k <= s.length(); ++i) { + const int x = stoi(s.substr(i, k)); + if (x != 0 && num % x == 0) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2269. Find the K-Beauty of a Number/2269.java b/solutions/2269. Find the K-Beauty of a Number/2269.java new file mode 100644 index 00000000000..6e2044b2ea6 --- /dev/null +++ b/solutions/2269. Find the K-Beauty of a Number/2269.java @@ -0,0 +1,14 @@ +class Solution { + public int divisorSubstrings(int num, int k) { + final String s = String.valueOf(num); + int ans = 0; + + for (int i = 0; i + k <= s.length(); ++i) { + final int x = Integer.parseInt(s.substring(i, i + k)); + if (x != 0 && num % x == 0) + ++ans; + } + + return ans; + } +} diff --git a/solutions/2269. Find the K-Beauty of a Number/2269.py b/solutions/2269. Find the K-Beauty of a Number/2269.py new file mode 100644 index 00000000000..eb0cd6df913 --- /dev/null +++ b/solutions/2269. Find the K-Beauty of a Number/2269.py @@ -0,0 +1,11 @@ +class Solution: + def divisorSubstrings(self, num: int, k: int) -> int: + s = str(num) + ans = 0 + + for i in range(len(s) - k + 1): + x = int(s[i:i + k]) + if x != 0 and num % x == 0: + ans += 1 + + return ans diff --git a/solutions/227. Basic Calculator II/227-2.cpp b/solutions/227. Basic Calculator II/227-2.cpp new file mode 100644 index 00000000000..47a2f44ecfa --- /dev/null +++ b/solutions/227. Basic Calculator II/227-2.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int calculate(string s) { + int ans = 0; + int prevNum = 0; + int currNum = 0; + char op = '+'; + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + if (isdigit(c)) + currNum = currNum * 10 + (c - '0'); + if (!isdigit(c) && !isspace(c) || i == s.length() - 1) { + if (op == '+' || op == '-') { + ans += prevNum; + prevNum = op == '+' ? currNum : -currNum; + } else if (op == '*') { + prevNum *= currNum; + } else if (op == '/') { + prevNum /= currNum; + } + op = c; + currNum = 0; + } + } + + return ans + prevNum; + } +}; diff --git a/solutions/227. Basic Calculator II/227-2.java b/solutions/227. Basic Calculator II/227-2.java new file mode 100644 index 00000000000..7673600c604 --- /dev/null +++ b/solutions/227. Basic Calculator II/227-2.java @@ -0,0 +1,28 @@ +class Solution { + public int calculate(String s) { + int ans = 0; + int currNum = 0; + int prevNum = 0; + char op = '+'; + + for (int i = 0; i < s.length(); ++i) { + final char c = s.charAt(i); + if (Character.isDigit(c)) + currNum = currNum * 10 + (c - '0'); + if (!Character.isDigit(c) && c != ' ' || i == s.length() - 1) { + if (op == '+' || op == '-') { + ans += prevNum; + prevNum = op == '+' ? currNum : -currNum; + } else if (op == '*') { + prevNum *= currNum; + } else if (op == '/') { + prevNum /= currNum; + } + op = c; + currNum = 0; + } + } + + return ans + prevNum; + } +} diff --git a/solutions/227. Basic Calculator II/227-2.py b/solutions/227. Basic Calculator II/227-2.py new file mode 100644 index 00000000000..e965b3d250b --- /dev/null +++ b/solutions/227. Basic Calculator II/227-2.py @@ -0,0 +1,22 @@ +class Solution: + def calculate(self, s: str) -> int: + ans = 0 + prevNum = 0 + currNum = 0 + op = '+' + + for i, c in enumerate(s): + if c.isdigit(): + currNum = currNum * 10 + int(c) + if not c.isdigit() and c != ' ' or i == len(s) - 1: + if op == '+' or op == '-': + ans += prevNum + prevNum = (currNum if op == '+' else -currNum) + elif op == '*': + prevNum *= currNum + elif op == '/': + prevNum = int(prevNum / currNum) + op = c + currNum = 0 + + return ans + prevNum diff --git a/solutions/227. Basic Calculator II/227.cpp b/solutions/227. Basic Calculator II/227.cpp new file mode 100644 index 00000000000..b2425c20b40 --- /dev/null +++ b/solutions/227. Basic Calculator II/227.cpp @@ -0,0 +1,60 @@ +class Solution { + public: + int calculate(string s) { + stack nums; + stack ops; + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + if (isdigit(c)) { + int num = c - '0'; + while (i + 1 < s.length() && isdigit(s[i + 1])) { + num = num * 10 + (s[i + 1] - '0'); + ++i; + } + nums.push(num); + } else if (c == '+' || c == '-' || c == '*' || c == '/') { + while (!ops.empty() && compare(ops.top(), c)) + nums.push(calculate(pop(ops), pop(nums), pop(nums))); + ops.push(c); + } + } + + while (!ops.empty()) + nums.push(calculate(pop(ops), pop(nums), pop(nums))); + + return nums.top(); + } + + private: + int calculate(char op, int b, int a) { + switch (op) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + return a / b; + } + throw; + } + + // Returns true if priority(op1) >= priority(op2). + bool compare(char op1, char op2) { + return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-'; + } + + char pop(stack& ops) { + const char op = ops.top(); + ops.pop(); + return op; + } + + int pop(stack& nums) { + const int num = nums.top(); + nums.pop(); + return num; + } +}; diff --git a/solutions/227. Basic Calculator II/227.java b/solutions/227. Basic Calculator II/227.java new file mode 100644 index 00000000000..1ebbbbc84ef --- /dev/null +++ b/solutions/227. Basic Calculator II/227.java @@ -0,0 +1,46 @@ +class Solution { + public int calculate(String s) { + Deque nums = new ArrayDeque<>(); + Deque ops = new ArrayDeque<>(); + + for (int i = 0; i < s.length(); ++i) { + final char c = s.charAt(i); + if (Character.isDigit(c)) { + int num = c - '0'; + while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) { + num = num * 10 + (s.charAt(i + 1) - '0'); + ++i; + } + nums.push(num); + } else if (c == '+' || c == '-' || c == '*' || c == '/') { + while (!ops.isEmpty() && compare(ops.peek(), c)) + nums.push(calculate(ops.pop(), nums.pop(), nums.pop())); + ops.push(c); + } + } + + while (!ops.isEmpty()) + nums.push(calculate(ops.pop(), nums.pop(), nums.pop())); + + return nums.peek(); + } + + private int calculate(char op, int b, int a) { + switch (op) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + return a / b; + } + throw new IllegalArgumentException(); + } + + // Returns true if priority(op1) >= priority(op2). + private boolean compare(char op1, char op2) { + return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-'; + } +} diff --git a/solutions/227. Basic Calculator II/227.py b/solutions/227. Basic Calculator II/227.py new file mode 100644 index 00000000000..8a42e248a57 --- /dev/null +++ b/solutions/227. Basic Calculator II/227.py @@ -0,0 +1,25 @@ +class Solution: + def calculate(self, s: str) -> int: + ans = 0 + prevNum = 0 + currNum = 0 + op = '+' + + for i, c in enumerate(s): + if c.isdigit(): + currNum = currNum * 10 + int(c) + if not c.isdigit() and c != ' ' or i == len(s) - 1: + if op == '+' or op == '-': + ans += prevNum + prevNum = currNum if op == '+' else -currNum + elif op == '*': + prevNum = prevNum * currNum + elif op == '/': + if prevNum < 0: + prevNum = math.ceil(prevNum / currNum) + else: + prevNum = prevNum // currNum + op = c + currNum = 0 + + return ans + prevNum diff --git a/solutions/2270. Number of Ways to Split Array/2270.cpp b/solutions/2270. Number of Ways to Split Array/2270.cpp new file mode 100644 index 00000000000..7d77d6eeaef --- /dev/null +++ b/solutions/2270. Number of Ways to Split Array/2270.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int waysToSplitArray(vector& nums) { + int ans = 0; + long prefix = 0; + long suffix = accumulate(nums.begin(), nums.end(), 0L); + + for (int i = 0; i < nums.size() - 1; ++i) { + prefix += nums[i]; + suffix -= nums[i]; + if (prefix >= suffix) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2270. Number of Ways to Split Array/2270.java b/solutions/2270. Number of Ways to Split Array/2270.java new file mode 100644 index 00000000000..8a3dece6a69 --- /dev/null +++ b/solutions/2270. Number of Ways to Split Array/2270.java @@ -0,0 +1,16 @@ +class Solution { + public int waysToSplitArray(int[] nums) { + int ans = 0; + long prefix = 0; + long suffix = Arrays.stream(nums).asLongStream().sum(); + + for (int i = 0; i < nums.length - 1; ++i) { + prefix += nums[i]; + suffix -= nums[i]; + if (prefix >= suffix) + ++ans; + } + + return ans; + } +} diff --git a/solutions/2270. Number of Ways to Split Array/2270.py b/solutions/2270. Number of Ways to Split Array/2270.py new file mode 100644 index 00000000000..3b4b644abcd --- /dev/null +++ b/solutions/2270. Number of Ways to Split Array/2270.py @@ -0,0 +1,13 @@ +class Solution: + def waysToSplitArray(self, nums: List[int]) -> int: + ans = 0 + prefix = 0 + suffix = sum(nums) + + for i in range(len(nums) - 1): + prefix += nums[i] + suffix -= nums[i] + if prefix >= suffix: + ans += 1 + + return ans diff --git a/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.cpp b/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.cpp new file mode 100644 index 00000000000..a969d1d3a2f --- /dev/null +++ b/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int maximumWhiteTiles(vector>& tiles, int carpetLen) { + if (ranges::any_of(tiles, [&](const auto& tile) { + return tile[1] - tile[0] + 1 >= carpetLen; + })) + return carpetLen; + + int ans = 0; + vector starts; + vector prefix(tiles.size() + 1); + + ranges::sort(tiles); + + for (const vector& tile : tiles) + starts.push_back(tile[0]); + + for (int i = 0; i < tiles.size(); ++i) { + const int length = tiles[i][1] - tiles[i][0] + 1; + prefix[i + 1] = prefix[i] + length; + } + + for (int i = 0; i < tiles.size(); ++i) { + const int s = tiles[i][0]; + const int carpetEnd = s + carpetLen - 1; + const int endIndex = + ranges::upper_bound(starts, carpetEnd) - starts.begin() - 1; + const int notCover = max(0, tiles[endIndex][1] - carpetEnd); + ans = max(ans, prefix[endIndex + 1] - prefix[i] - notCover); + } + + return ans; + } +}; diff --git a/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.java b/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.java new file mode 100644 index 00000000000..5bc2bc702aa --- /dev/null +++ b/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.java @@ -0,0 +1,35 @@ +class Solution { + public int maximumWhiteTiles(int[][] tiles, int carpetLen) { + if (Arrays.stream(tiles).anyMatch(tile -> tile[1] - tile[0] + 1 >= carpetLen)) + return carpetLen; + + int ans = 0; + List starts = new ArrayList<>(); + int[] prefix = new int[tiles.length + 1]; + + Arrays.sort(tiles, (a, b) -> a[0] - b[0]); + + for (int[] tile : tiles) + starts.add(tile[0]); + + for (int i = 0; i < tiles.length; ++i) { + final int length = tiles[i][1] - tiles[i][0] + 1; + prefix[i + 1] = prefix[i] + length; + } + + for (int i = 0; i < tiles.length; ++i) { + final int s = tiles[i][0]; + final int carpetEnd = s + carpetLen - 1; + final int endIndex = firstGreater(starts, carpetEnd) - 1; + final int notCover = Math.max(0, tiles[endIndex][1] - carpetEnd); + ans = Math.max(ans, prefix[endIndex + 1] - prefix[i] - notCover); + } + + return ans; + } + + private int firstGreater(List A, int target) { + final int i = Collections.binarySearch(A, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.py b/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.py new file mode 100644 index 00000000000..94bf92a5a48 --- /dev/null +++ b/solutions/2271. Maximum White Tiles Covered by a Carpet/2271.py @@ -0,0 +1,22 @@ +class Solution: + def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int: + if any(tile[1] - tile[0] + 1 >= carpetLen for tile in tiles): + return carpetLen + + ans = 0 + prefix = [0] * (len(tiles) + 1) + + tiles.sort() + starts = [tile[0] for tile in tiles] + + for i, tile in enumerate(tiles): + length = tile[1] - tile[0] + 1 + prefix[i + 1] = prefix[i] + length + + for i, (s, _) in enumerate(tiles): + carpetEnd = s + carpetLen - 1 + endIndex = bisect_right(starts, carpetEnd) - 1 + notCover = max(0, tiles[endIndex][1] - carpetEnd) + ans = max(ans, prefix[endIndex + 1] - prefix[i] - notCover) + + return ans diff --git a/solutions/2272. Substring With Largest Variance/2272.cpp b/solutions/2272. Substring With Largest Variance/2272.cpp new file mode 100644 index 00000000000..b206b85caed --- /dev/null +++ b/solutions/2272. Substring With Largest Variance/2272.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + int largestVariance(string s) { + int ans = 0; + + for (char a = 'a'; a <= 'z'; ++a) + for (char b = 'a'; b <= 'z'; ++b) + if (a != b) + ans = max(ans, kadane(s, a, b)); + + return ans; + } + + private: + // a := the letter with the higher frequency + // b := the letter with the lower frequency + int kadane(const string& s, char a, char b) { + int ans = 0; + int countA = 0; + int countB = 0; + bool canExtendPrevB = false; + + for (const char c : s) { + if (c != a && c != b) + continue; + if (c == a) + ++countA; + else + ++countB; + if (countB > 0) { + // An interval should contain at least one b. + ans = max(ans, countA - countB); + } else if (countB == 0 && canExtendPrevB) { + // edge case: consider the previous b. + ans = max(ans, countA - 1); + } + // Reset if the number of b > the number of a. + if (countB > countA) { + countA = 0; + countB = 0; + canExtendPrevB = true; + } + } + + return ans; + } +}; diff --git a/solutions/2272. Substring With Largest Variance/2272.java b/solutions/2272. Substring With Largest Variance/2272.java new file mode 100644 index 00000000000..19aaab5ee31 --- /dev/null +++ b/solutions/2272. Substring With Largest Variance/2272.java @@ -0,0 +1,45 @@ +class Solution { + public int largestVariance(String s) { + int ans = 0; + + for (char a = 'a'; a <= 'z'; ++a) + for (char b = 'a'; b <= 'z'; ++b) + if (a != b) + ans = Math.max(ans, kadane(s, a, b)); + + return ans; + } + + // a := the letter with the higher frequency + // b := the letter with the lower frequency + private int kadane(final String s, char a, char b) { + int ans = 0; + int countA = 0; + int countB = 0; + boolean canExtendPrevB = false; + + for (final char c : s.toCharArray()) { + if (c != a && c != b) + continue; + if (c == a) + ++countA; + else + ++countB; + if (countB > 0) { + // An interval should contain at least one b. + ans = Math.max(ans, countA - countB); + } else if (countB == 0 && canExtendPrevB) { + // edge case: consider the previous b + ans = Math.max(ans, countA - 1); + } + // Reset if the number of b > the number of a. + if (countB > countA) { + countA = 0; + countB = 0; + canExtendPrevB = true; + } + } + + return ans; + } +} diff --git a/solutions/2272. Substring With Largest Variance/2272.py b/solutions/2272. Substring With Largest Variance/2272.py new file mode 100644 index 00000000000..582a527005c --- /dev/null +++ b/solutions/2272. Substring With Largest Variance/2272.py @@ -0,0 +1,35 @@ +class Solution: + def largestVariance(self, s: str) -> int: + # a := the letter with the higher frequency + # b := the letter with the lower frequency + def kadane(a: str, b: str) -> int: + ans = 0 + countA = 0 + countB = 0 + canExtendPrevB = False + + for c in s: + if c != a and c != b: + continue + if c == a: + countA += 1 + else: + countB += 1 + if countB > 0: + # An interval should contain at least one b. + ans = max(ans, countA - countB) + elif countB == 0 and canExtendPrevB: + # edge case: consider the previous b. + ans = max(ans, countA - 1) + # Reset if the number of b > the number of a. + if countB > countA: + countA = 0 + countB = 0 + canExtendPrevB = True + + return ans + + return max(kadane(a, b) + for a in string.ascii_lowercase + for b in string.ascii_lowercase + if a != b) diff --git a/solutions/2273. Find Resultant Array After Removing Anagrams/2273.cpp b/solutions/2273. Find Resultant Array After Removing Anagrams/2273.cpp new file mode 100644 index 00000000000..4c1c4b8b7ee --- /dev/null +++ b/solutions/2273. Find Resultant Array After Removing Anagrams/2273.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector removeAnagrams(vector& words) { + vector ans; + + for (int i = 0; i < words.size();) { + int j = i + 1; + while (j < words.size() && isAnagram(words[i], words[j])) + ++j; + ans.push_back(words[i]); + i = j; + } + + return ans; + } + + private: + bool isAnagram(const string& a, const string& b) { + if (a.length() != b.length()) + return false; + + vector count(26); + + for (const char c : a) + ++count[c - 'a']; + + for (const char c : b) + --count[c - 'a']; + + return ranges::all_of(count, [](const int c) { return c == 0; }); + } +}; diff --git a/solutions/2273. Find Resultant Array After Removing Anagrams/2273.java b/solutions/2273. Find Resultant Array After Removing Anagrams/2273.java new file mode 100644 index 00000000000..eadeff0efb7 --- /dev/null +++ b/solutions/2273. Find Resultant Array After Removing Anagrams/2273.java @@ -0,0 +1,30 @@ +class Solution { + public List removeAnagrams(String[] words) { + List ans = new ArrayList<>(); + + for (int i = 0; i < words.length;) { + int j = i + 1; + while (j < words.length && isAnagram(words[i], words[j])) + ++j; + ans.add(words[i]); + i = j; + } + + return ans; + } + + private boolean isAnagram(final String a, final String b) { + if (a.length() != b.length()) + return false; + + int[] count = new int[26]; + + for (final char c : a.toCharArray()) + ++count[c - 'a']; + + for (final char c : b.toCharArray()) + --count[c - 'a']; + + return Arrays.stream(count).allMatch(c -> c == 0); + } +} diff --git a/solutions/2273. Find Resultant Array After Removing Anagrams/2273.py b/solutions/2273. Find Resultant Array After Removing Anagrams/2273.py new file mode 100644 index 00000000000..5d06487e3b4 --- /dev/null +++ b/solutions/2273. Find Resultant Array After Removing Anagrams/2273.py @@ -0,0 +1,18 @@ +class Solution: + def removeAnagrams(self, words: List[str]) -> List[str]: + ans = [] + + def isAnagram(a: str, b: str) -> bool: + count = collections.Counter(a) + count.subtract(collections.Counter(b)) + return all(value == 0 for value in count.values()) + + i = 0 + while i < len(words): + j = i + 1 + while j < len(words) and isAnagram(words[i], words[j]): + j += 1 + ans.append(words[i]) + i = j + + return ans diff --git a/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.cpp b/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.cpp new file mode 100644 index 00000000000..cd09dc157ae --- /dev/null +++ b/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int maxConsecutive(int bottom, int top, vector& special) { + int ans = 0; + + ranges::sort(special); + + for (int i = 1; i < special.size(); ++i) + ans = max(ans, special[i] - special[i - 1] - 1); + + return max({ans, special.front() - bottom, top - special.back()}); + } +}; diff --git a/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.java b/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.java new file mode 100644 index 00000000000..92cd303fb98 --- /dev/null +++ b/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.java @@ -0,0 +1,12 @@ +class Solution { + public int maxConsecutive(int bottom, int top, int[] special) { + int ans = 0; + + Arrays.sort(special); + + for (int i = 1; i < special.length; ++i) + ans = Math.max(ans, special[i] - special[i - 1] - 1); + + return Math.max(ans, Math.max(special[0] - bottom, top - special[special.length - 1])); + } +} diff --git a/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.py b/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.py new file mode 100644 index 00000000000..b764554fd42 --- /dev/null +++ b/solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.py @@ -0,0 +1,10 @@ +class Solution: + def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int: + ans = 0 + + special.sort() + + for a, b in zip(special, special[1:]): + ans = max(ans, b - a - 1) + + return max(ans, special[0] - bottom, top - special[-1]) diff --git a/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.cpp b/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.cpp new file mode 100644 index 00000000000..c98e1371305 --- /dev/null +++ b/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int largestCombination(vector& candidates) { + constexpr int kMaxBit = 24; + int ans = 0; + + for (int i = 0; i < kMaxBit; ++i) { + int count = 0; + for (const int candidate : candidates) + if (candidate >> i & 1) + ++count; + ans = max(ans, count); + } + + return ans; + } +}; diff --git a/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.java b/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.java new file mode 100644 index 00000000000..7c7c96b6fab --- /dev/null +++ b/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.java @@ -0,0 +1,16 @@ +class Solution { + public int largestCombination(int[] candidates) { + final int kMaxBit = 24; + int ans = 0; + + for (int i = 0; i < kMaxBit; ++i) { + int count = 0; + for (final int candidate : candidates) + if ((candidate >> i & 1) == 1) + ++count; + ans = Math.max(ans, count); + } + + return ans; + } +} diff --git a/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.py b/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.py new file mode 100644 index 00000000000..23fc7eafdec --- /dev/null +++ b/solutions/2275. Largest Combination With Bitwise AND Greater Than Zero/2275.py @@ -0,0 +1,3 @@ +class Solution: + def largestCombination(self, candidates: List[int]) -> int: + return max(sum(c >> i & 1 for c in candidates) for i in range(24)) diff --git a/solutions/2276. Count Integers in Intervals/2276.cpp b/solutions/2276. Count Integers in Intervals/2276.cpp new file mode 100644 index 00000000000..964f22db3d9 --- /dev/null +++ b/solutions/2276. Count Integers in Intervals/2276.cpp @@ -0,0 +1,30 @@ +class CountIntervals { + public: + void add(int left, int right) { + while (isOverlapped(left, right)) { + auto it = prev(intervals.upper_bound(right)); + const int l = it->first; + const int r = it->second; + left = min(left, l); + right = max(right, r); + intervals.erase(l); + cnt -= r - l + 1; + } + + intervals[left] = right; + cnt += right - left + 1; + } + + int count() { + return cnt; + } + + private: + map intervals; + int cnt = 0; + + bool isOverlapped(int left, int right) { + auto it = intervals.upper_bound(right); + return it != intervals.begin() && prev(it)->second >= left; + } +}; diff --git a/solutions/2276. Count Integers in Intervals/2276.java b/solutions/2276. Count Integers in Intervals/2276.java new file mode 100644 index 00000000000..767ac1dc4ad --- /dev/null +++ b/solutions/2276. Count Integers in Intervals/2276.java @@ -0,0 +1,28 @@ +class CountIntervals { + public void add(int left, int right) { + while (isOverlapped(left, right)) { + final int l = intervals.floorKey(right); + final int r = intervals.get(l); + left = Math.min(left, l); + right = Math.max(right, r); + intervals.remove(l); + count -= r - l + 1; + } + + intervals.put(left, right); + count += right - left + 1; + } + + public int count() { + return count; + } + + private TreeMap intervals = new TreeMap<>(); + private int count = 0; + + private boolean isOverlapped(int left, int right) { + // L := the maximum number <= end + Integer l = intervals.floorKey(right); + return l != null && intervals.get(l) >= left; + } +} diff --git a/solutions/2276. Count Integers in Intervals/2276.py b/solutions/2276. Count Integers in Intervals/2276.py new file mode 100644 index 00000000000..5d0b35f9d5f --- /dev/null +++ b/solutions/2276. Count Integers in Intervals/2276.py @@ -0,0 +1,25 @@ +from sortedcontainers import SortedDict + + +class CountIntervals: + def __init__(self): + self.intervals = SortedDict() + self.cnt = 0 + + def add(self, left: int, right: int) -> None: + while self._isOverlapped(left, right): + i = self.intervals.bisect_right(right) - 1 + l, r = self.intervals.popitem(i) + left = min(left, l) + right = max(right, r) + self.cnt -= r - l + 1 + + self.intervals[left] = right + self.cnt += right - left + 1 + + def count(self) -> int: + return self.cnt + + def _isOverlapped(self, left: int, right: int) -> bool: + i = self.intervals.bisect_right(right) + return i > 0 and self.intervals.peekitem(i - 1)[1] >= left diff --git a/solutions/2277. Closest Node to Path in Tree/2277.cpp b/solutions/2277. Closest Node to Path in Tree/2277.cpp new file mode 100644 index 00000000000..1d4c5288179 --- /dev/null +++ b/solutions/2277. Closest Node to Path in Tree/2277.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + vector closestNode(int n, vector>& edges, + vector>& query) { + vector ans; + vector> tree(n); + vector> dist(n, vector(n, -1)); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + for (int i = 0; i < n; ++i) + fillDist(tree, i, i, 0, dist); + + for (const vector& q : query) { + const int start = q[0]; + const int end = q[1]; + const int node = q[2]; + ans.push_back(findClosest(tree, dist, start, end, node, start)); + } + + return ans; + } + + private: + void fillDist(const vector>& tree, int start, int u, int d, + vector>& dist) { + dist[start][u] = d; + for (const int v : tree[u]) + if (dist[start][v] == -1) + fillDist(tree, start, v, d + 1, dist); + } + + int findClosest(const vector>& tree, + const vector>& dist, int u, int end, int node, + int ans) { + for (const int v : tree[u]) + if (dist[v][end] < dist[u][end]) + return findClosest(tree, dist, v, end, node, + dist[ans][node] < dist[v][node] ? ans : v); + return ans; + } +}; diff --git a/solutions/2277. Closest Node to Path in Tree/2277.java b/solutions/2277. Closest Node to Path in Tree/2277.java new file mode 100644 index 00000000000..3fc65b3d3cc --- /dev/null +++ b/solutions/2277. Closest Node to Path in Tree/2277.java @@ -0,0 +1,44 @@ +class Solution { + public int[] closestNode(int n, int[][] edges, int[][] query) { + int[] ans = new int[query.length]; + List[] tree = new List[n]; + int[][] dist = new int[n][n]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, -1)); + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + for (int i = 0; i < n; ++i) + fillDist(tree, i, i, 0, dist); + + for (int i = 0; i < query.length; ++i) { + final int start = query[i][0]; + final int end = query[i][1]; + final int node = query[i][2]; + ans[i] = findClosest(tree, dist, start, end, node, start); + } + + return ans; + } + + private void fillDist(List[] tree, int start, int u, int d, int[][] dist) { + dist[start][u] = d; + for (final int v : tree[u]) + if (dist[start][v] == -1) + fillDist(tree, start, v, d + 1, dist); + } + + private int findClosest(List[] tree, int[][] dist, int u, int end, int node, int ans) { + for (final int v : tree[u]) + if (dist[v][end] < dist[u][end]) + return findClosest(tree, dist, v, end, node, dist[ans][node] < dist[v][node] ? ans : v); + return ans; + } +} diff --git a/solutions/2277. Closest Node to Path in Tree/2277.py b/solutions/2277. Closest Node to Path in Tree/2277.py new file mode 100644 index 00000000000..9de1bde6010 --- /dev/null +++ b/solutions/2277. Closest Node to Path in Tree/2277.py @@ -0,0 +1,27 @@ +class Solution: + def closestNode(self, n: int, edges: List[List[int]], query: List[List[int]]) -> List[int]: + ans = [] + tree = [[] for _ in range(n)] + dist = [[-1] * n for _ in range(n)] + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def fillDist(start: int, u: int, d: int) -> None: + dist[start][u] = d + for v in tree[u]: + if dist[start][v] == -1: + fillDist(start, v, d + 1) + + for i in range(n): + fillDist(i, i, 0) + + def findClosest(u: int, end: int, node: int, ans: int) -> int: + for v in tree[u]: + if dist[v][end] < dist[u][end]: + return findClosest(v, end, node, ans if dist[ans][node] < dist[v][node] else v) + return ans + + return [findClosest(start, end, node, start) + for start, end, node in query] diff --git a/solutions/2278. Percentage of Letter in String/2278.cpp b/solutions/2278. Percentage of Letter in String/2278.cpp new file mode 100644 index 00000000000..4e3c447a62a --- /dev/null +++ b/solutions/2278. Percentage of Letter in String/2278.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int percentageLetter(string s, char letter) { + return 100 * ranges::count(s, letter) / s.length(); + } +}; diff --git a/solutions/2278. Percentage of Letter in String/2278.java b/solutions/2278. Percentage of Letter in String/2278.java new file mode 100644 index 00000000000..11d2fea2dd7 --- /dev/null +++ b/solutions/2278. Percentage of Letter in String/2278.java @@ -0,0 +1,5 @@ +class Solution { + public int percentageLetter(String s, char letter) { + return 100 * (int) s.chars().filter(c -> c == letter).count() / s.length(); + } +} diff --git a/solutions/2278. Percentage of Letter in String/2278.py b/solutions/2278. Percentage of Letter in String/2278.py new file mode 100644 index 00000000000..3ef6751ce29 --- /dev/null +++ b/solutions/2278. Percentage of Letter in String/2278.py @@ -0,0 +1,3 @@ +class Solution: + def percentageLetter(self, s: str, letter: str) -> int: + return 100 * s.count(letter) // len(s) diff --git a/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.cpp b/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.cpp new file mode 100644 index 00000000000..dd9030bf774 --- /dev/null +++ b/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maximumBags(vector& capacity, vector& rocks, + int additionalRocks) { + const int n = capacity.size(); + vector diff(n); + + for (int i = 0; i < n; ++i) + diff[i] = capacity[i] - rocks[i]; + + ranges::sort(diff); + + for (int i = 0; i < n; ++i) { + if (diff[i] > additionalRocks) + return i; + additionalRocks -= diff[i]; + } + + return n; + } +}; diff --git a/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.java b/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.java new file mode 100644 index 00000000000..9563513e745 --- /dev/null +++ b/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.java @@ -0,0 +1,19 @@ +class Solution { + public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) { + final int n = capacity.length; + int[] diff = new int[n]; + + for (int i = 0; i < n; ++i) + diff[i] = capacity[i] - rocks[i]; + + Arrays.sort(diff); + + for (int i = 0; i < n; ++i) { + if (diff[i] > additionalRocks) + return i; + additionalRocks -= diff[i]; + } + + return n; + } +} diff --git a/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.py b/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.py new file mode 100644 index 00000000000..b0b1784891a --- /dev/null +++ b/solutions/2279. Maximum Bags With Full Capacity of Rocks/2279.py @@ -0,0 +1,7 @@ +class Solution: + def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int: + for i, d in enumerate(sorted([c - r for c, r in zip(capacity, rocks)])): + if d > additionalRocks: + return i + additionalRocks -= d + return len(capacity) diff --git a/solutions/228. Summary Ranges/228.cpp b/solutions/228. Summary Ranges/228.cpp new file mode 100644 index 00000000000..563d9ceb3fb --- /dev/null +++ b/solutions/228. Summary Ranges/228.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector summaryRanges(vector& nums) { + vector ans; + + for (int i = 0; i < nums.size(); ++i) { + const int begin = nums[i]; + while (i + 1 < nums.size() && nums[i] == nums[i + 1] - 1) + ++i; + const int end = nums[i]; + if (begin == end) + ans.push_back(to_string(begin)); + else + ans.push_back(to_string(begin) + "->" + to_string(end)); + } + + return ans; + } +}; diff --git a/solutions/228. Summary Ranges/228.java b/solutions/228. Summary Ranges/228.java new file mode 100644 index 00000000000..1ceecaecc33 --- /dev/null +++ b/solutions/228. Summary Ranges/228.java @@ -0,0 +1,18 @@ +class Solution { + public List summaryRanges(int[] nums) { + List ans = new ArrayList<>(); + + for (int i = 0; i < nums.length; ++i) { + final int begin = nums[i]; + while (i + 1 < nums.length && nums[i] == nums[i + 1] - 1) + ++i; + final int end = nums[i]; + if (begin == end) + ans.add("" + begin); + else + ans.add("" + begin + "->" + end); + } + + return ans; + } +} diff --git a/solutions/228. Summary Ranges/228.py b/solutions/228. Summary Ranges/228.py new file mode 100644 index 00000000000..eccf562aed3 --- /dev/null +++ b/solutions/228. Summary Ranges/228.py @@ -0,0 +1,17 @@ +class Solution: + def summaryRanges(self, nums: List[int]) -> List[str]: + ans = [] + + i = 0 + while i < len(nums): + begin = nums[i] + while i < len(nums) - 1 and nums[i] == nums[i + 1] - 1: + i += 1 + end = nums[i] + if begin == end: + ans.append(str(begin)) + else: + ans.append(str(begin) + "->" + str(end)) + i += 1 + + return ans diff --git a/solutions/2280. Minimum Lines to Represent a Line Chart/2280.cpp b/solutions/2280. Minimum Lines to Represent a Line Chart/2280.cpp new file mode 100644 index 00000000000..27c37dbf584 --- /dev/null +++ b/solutions/2280. Minimum Lines to Represent a Line Chart/2280.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minimumLines(vector>& stockPrices) { + int ans = 0; + + ranges::sort(stockPrices); + + for (int i = 2; i < stockPrices.size(); ++i) { + const pair a = getSlope(stockPrices[i - 2], stockPrices[i - 1]); + const pair b = getSlope(stockPrices[i - 1], stockPrices[i]); + if (a != b) + ++ans; + } + + return ans + (stockPrices.size() > 1); + } + + private: + pair getSlope(const vector& p, const vector& q) { + const int dx = p[0] - q[0]; + const int dy = p[1] - q[1]; + if (dx == 0) + return {0, p[0]}; + if (dy == 0) + return {p[1], 0}; + const int d = __gcd(dx, dy); + return {dx / d, dy / d}; + } +}; diff --git a/solutions/2280. Minimum Lines to Represent a Line Chart/2280.java b/solutions/2280. Minimum Lines to Represent a Line Chart/2280.java new file mode 100644 index 00000000000..695bd1c4d6e --- /dev/null +++ b/solutions/2280. Minimum Lines to Represent a Line Chart/2280.java @@ -0,0 +1,31 @@ +class Solution { + public int minimumLines(int[][] stockPrices) { + int ans = 0; + + Arrays.sort(stockPrices, (a, b) -> a[0] - b[0]); + + for (int i = 2; i < stockPrices.length; ++i) { + Pair a = getSlope(stockPrices[i - 2], stockPrices[i - 1]); + Pair b = getSlope(stockPrices[i - 1], stockPrices[i]); + if (a.getKey() != b.getKey() || a.getValue() != b.getValue()) + ++ans; + } + + return ans + (stockPrices.length > 1 ? 1 : 0); + } + + private Pair getSlope(int[] p, int[] q) { + final int dx = p[0] - q[0]; + final int dy = p[1] - q[1]; + if (dx == 0) + return new Pair<>(0, p[0]); + if (dy == 0) + return new Pair<>(p[1], 0); + final int d = gcd(dx, dy); + return new Pair<>(dx / d, dy / d); + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2280. Minimum Lines to Represent a Line Chart/2280.py b/solutions/2280. Minimum Lines to Represent a Line Chart/2280.py new file mode 100644 index 00000000000..06bc490a071 --- /dev/null +++ b/solutions/2280. Minimum Lines to Represent a Line Chart/2280.py @@ -0,0 +1,23 @@ +class Solution: + def minimumLines(self, stockPrices: List[List[int]]) -> int: + ans = 0 + + stockPrices.sort() + + def getSlope(p: List[int], q: List[int]) -> Tuple[int, int]: + dx = p[0] - q[0] + dy = p[1] - q[1] + if dx == 0: + return (0, p[0]) + if dy == 0: + return (p[1], 0) + d = gcd(dx, dy) + return (dx // d, dy // d) + + for i in range(2, len(stockPrices)): + a = getSlope(stockPrices[i - 2], stockPrices[i - 1]) + b = getSlope(stockPrices[i - 1], stockPrices[i]) + if a != b: + ans += 1 + + return ans + (len(stockPrices) > 1) diff --git a/solutions/2281. Sum of Total Strength of Wizards/2281.cpp b/solutions/2281. Sum of Total Strength of Wizards/2281.cpp new file mode 100644 index 00000000000..65bce1d37c9 --- /dev/null +++ b/solutions/2281. Sum of Total Strength of Wizards/2281.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + int totalStrength(vector& strength) { + constexpr int kMod = 1'000'000'007; + const int n = strength.size(); + vector prefix(n); + vector prefixOfPrefix(n + 1); + // left[i] := the next index on the left (if any) s.t. + // nums[left[i]] <= nums[i] + vector left(n, -1); + // right[i] := the next index on the right (if any) s.t. + // nums[right[i]] < nums[i] + vector right(n, n); + stack stack; + + for (int i = 0; i < n; ++i) + prefix[i] = i == 0 ? strength[0] : (strength[i] + prefix[i - 1]) % kMod; + + for (int i = 0; i < n; ++i) + prefixOfPrefix[i + 1] = (prefixOfPrefix[i] + prefix[i]) % kMod; + + for (int i = n - 1; i >= 0; --i) { + while (!stack.empty() && strength[stack.top()] >= strength[i]) + left[stack.top()] = i, stack.pop(); + stack.push(i); + } + + stack = std::stack(); + + for (int i = 0; i < n; ++i) { + while (!stack.empty() && strength[stack.top()] > strength[i]) + right[stack.top()] = i, stack.pop(); + stack.push(i); + } + + long ans = 0; + + // For each strength[i] as minimum, calculate sum. + for (int i = 0; i < n; ++i) { + const int l = left[i]; + const int r = right[i]; + const long leftSum = prefixOfPrefix[i] - prefixOfPrefix[max(0, l)]; + const long rightSum = prefixOfPrefix[r] - prefixOfPrefix[i]; + const int leftLen = i - l; + const int rightLen = r - i; + ans += strength[i] * + (rightSum * leftLen % kMod - leftSum * rightLen % kMod + kMod) % + kMod; + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/2281. Sum of Total Strength of Wizards/2281.java b/solutions/2281. Sum of Total Strength of Wizards/2281.java new file mode 100644 index 00000000000..23f2b0e447a --- /dev/null +++ b/solutions/2281. Sum of Total Strength of Wizards/2281.java @@ -0,0 +1,53 @@ +class Solution { + public int totalStrength(int[] strength) { + final int kMod = 1_000_000_007; + final int n = strength.length; + long[] prefix = new long[n]; + long[] prefixOfPrefix = new long[n + 1]; + // left[i] := the next index on the left (if any) + // s.t. nums[left[i]] <= nums[i] + int[] left = new int[n]; + Arrays.fill(left, -1); + // right[i] := the next index on the right (if any) + // s.t. nums[right[i]] < nums[i] + int[] right = new int[n]; + Arrays.fill(right, n); + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < n; ++i) + prefix[i] = i == 0 ? strength[0] : (strength[i] + prefix[i - 1]) % kMod; + + for (int i = 0; i < n; ++i) + prefixOfPrefix[i + 1] = (prefixOfPrefix[i] + prefix[i]) % kMod; + + for (int i = n - 1; i >= 0; --i) { + while (!stack.isEmpty() && strength[stack.peek()] >= strength[i]) + left[stack.pop()] = i; + stack.push(i); + } + + stack.clear(); + + for (int i = 0; i < n; ++i) { + while (!stack.isEmpty() && strength[stack.peek()] > strength[i]) + right[stack.pop()] = i; + stack.push(i); + } + + long ans = 0; + + // For each strength[i] as minimum, calculate sum. + for (int i = 0; i < n; ++i) { + final int l = left[i]; + final int r = right[i]; + final long leftSum = prefixOfPrefix[i] - prefixOfPrefix[Math.max(0, l)]; + final long rightSum = prefixOfPrefix[r] - prefixOfPrefix[i]; + final int leftLen = i - l; + final int rightLen = r - i; + ans += strength[i] * (rightSum * leftLen % kMod - leftSum * rightLen % kMod + kMod) % kMod; + ans %= kMod; + } + + return (int) ans; + } +} diff --git a/solutions/2281. Sum of Total Strength of Wizards/2281.py b/solutions/2281. Sum of Total Strength of Wizards/2281.py new file mode 100644 index 00000000000..6481b706089 --- /dev/null +++ b/solutions/2281. Sum of Total Strength of Wizards/2281.py @@ -0,0 +1,37 @@ +class Solution: + def totalStrength(self, strength: List[int]) -> int: + kMod = 1_000_000_007 + n = len(strength) + # left[i] := the next index on the left (if any) + # s.t. nums[left[i]] <= nums[i] + left = [-1] * n + # right[i] := the next index on the right (if any) + # s.t. nums[right[i]] < nums[i] + right = [n] * n + stack = [] + + for i in reversed(range(n)): + while stack and strength[stack[-1]] >= strength[i]: + left[stack.pop()] = i + stack.append(i) + + stack = [] + + for i in range(n): + while stack and strength[stack[-1]] > strength[i]: + right[stack.pop()] = i + stack.append(i) + + ans = 0 + prefixOfPrefix = list(itertools.accumulate( + itertools.accumulate(strength), initial=0)) + + # For each strength[i] as the minimum, calculate sum. + for i, (l, r) in enumerate(zip(left, right)): + leftSum = prefixOfPrefix[i] - prefixOfPrefix[max(0, l)] + rightSum = prefixOfPrefix[r] - prefixOfPrefix[i] + leftLen = i - l + rightLen = r - i + ans += strength[i] * (rightSum * leftLen - leftSum * rightLen) % kMod + + return ans % kMod diff --git a/solutions/2282. Number of People That Can Be Seen in a Grid/2282.cpp b/solutions/2282. Number of People That Can Be Seen in a Grid/2282.cpp new file mode 100644 index 00000000000..6029d611168 --- /dev/null +++ b/solutions/2282. Number of People That Can Be Seen in a Grid/2282.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + vector> seePeople(vector>& heights) { + const int m = heights.size(); + const int n = heights[0].size(); + vector> ans(m, vector(n)); + + for (int i = 0; i < m; ++i) { + stack stack; + for (int j = 0; j < n; ++j) { + bool hasEqualHeight = false; + while (!stack.empty() && heights[i][stack.top()] <= heights[i][j]) { + if (heights[i][stack.top()] == heights[i][j]) + // edge case: [4, 2, 1, 1, 3] + hasEqualHeight = true; + ++ans[i][stack.top()], stack.pop(); + } + if (!stack.empty() && !hasEqualHeight) + ++ans[i][stack.top()]; + stack.push(j); + } + } + + for (int j = 0; j < n; ++j) { + stack stack; + for (int i = 0; i < m; ++i) { + bool hasEqualHeight = false; + while (!stack.empty() && heights[stack.top()][j] <= heights[i][j]) { + if (heights[stack.top()][j] == heights[i][j]) + hasEqualHeight = true; + ++ans[stack.top()][j], stack.pop(); + } + if (!stack.empty() && !hasEqualHeight) + ++ans[stack.top()][j]; + stack.push(i); + } + } + + return ans; + } +}; diff --git a/solutions/2282. Number of People That Can Be Seen in a Grid/2282.java b/solutions/2282. Number of People That Can Be Seen in a Grid/2282.java new file mode 100644 index 00000000000..241736ea8ca --- /dev/null +++ b/solutions/2282. Number of People That Can Be Seen in a Grid/2282.java @@ -0,0 +1,40 @@ +class Solution { + public int[][] seePeople(int[][] heights) { + final int m = heights.length; + final int n = heights[0].length; + int[][] ans = new int[m][n]; + + for (int i = 0; i < m; ++i) { + Deque stack = new ArrayDeque<>(); + for (int j = 0; j < n; ++j) { + boolean hasEqualHeight = false; + while (!stack.isEmpty() && heights[i][stack.peek()] <= heights[i][j]) { + if (heights[i][stack.peek()] == heights[i][j]) + // edge case: [4, 2, 1, 1, 3] + hasEqualHeight = true; + ++ans[i][stack.pop()]; + } + if (!stack.isEmpty() && !hasEqualHeight) + ++ans[i][stack.peek()]; + stack.push(j); + } + } + + for (int j = 0; j < n; ++j) { + Deque stack = new ArrayDeque<>(); + for (int i = 0; i < m; ++i) { + boolean hasEqualHeight = false; + while (!stack.isEmpty() && heights[stack.peek()][j] <= heights[i][j]) { + if (heights[stack.peek()][j] == heights[i][j]) + hasEqualHeight = true; + ++ans[stack.pop()][j]; + } + if (!stack.isEmpty() && !hasEqualHeight) + ++ans[stack.peek()][j]; + stack.push(i); + } + } + + return ans; + } +} diff --git a/solutions/2282. Number of People That Can Be Seen in a Grid/2282.py b/solutions/2282. Number of People That Can Be Seen in a Grid/2282.py new file mode 100644 index 00000000000..fd3f9ce7449 --- /dev/null +++ b/solutions/2282. Number of People That Can Be Seen in a Grid/2282.py @@ -0,0 +1,32 @@ +class Solution: + def seePeople(self, heights: List[List[int]]) -> List[List[int]]: + m = len(heights) + n = len(heights[0]) + ans = [[0] * n for _ in range(m)] + + for i, row in enumerate(heights): + stack = [] + for j, height in enumerate(row): + hasEqualHeight = False + while stack and row[stack[-1]] <= height: + if row[stack[-1]] == height: + # edge case: [4, 2, 1, 1, 3] + hasEqualHeight = True + ans[i][stack.pop()] += 1 + if stack and not hasEqualHeight: + ans[i][stack[-1]] += 1 + stack.append(j) + + for j, col in enumerate(zip(*heights)): + stack = [] + for i, height in enumerate(col): + hasEqualHeight = False + while stack and col[stack[-1]] <= height: + if col[stack[-1]] == height: + hasEqualHeight = True + ans[stack.pop()][j] += 1 + if stack and not hasEqualHeight: + ans[stack[-1]][j] += 1 + stack.append(i) + + return ans diff --git a/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.cpp b/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.cpp new file mode 100644 index 00000000000..9ddad435b17 --- /dev/null +++ b/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool digitCount(string num) { + vector count(10); + + for (const char c : num) + ++count[c - '0']; + + for (int i = 0; i < num.length(); ++i) + if (count[i] != num[i] - '0') + return false; + + return true; + } +}; diff --git a/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.java b/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.java new file mode 100644 index 00000000000..960c1f34558 --- /dev/null +++ b/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.java @@ -0,0 +1,14 @@ +class Solution { + public boolean digitCount(String num) { + int[] count = new int[10]; + + for (final char c : num.toCharArray()) + ++count[c - '0']; + + for (int i = 0; i < num.length(); ++i) + if (count[i] != num.charAt(i) - '0') + return false; + + return true; + } +} diff --git a/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.py b/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.py new file mode 100644 index 00000000000..15fcb381450 --- /dev/null +++ b/solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.py @@ -0,0 +1,5 @@ +class Solution: + def digitCount(self, num: str) -> bool: + count = collections.Counter(num) + return all(count[str(i)] == int(digit) + for i, digit in enumerate(num)) diff --git a/solutions/2284. Sender With Largest Word Count/2284.cpp b/solutions/2284. Sender With Largest Word Count/2284.cpp new file mode 100644 index 00000000000..c55c5c0c76f --- /dev/null +++ b/solutions/2284. Sender With Largest Word Count/2284.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string largestWordCount(vector& messages, vector& senders) { + const int n = messages.size(); + string ans; + int maxWordsSent = 0; + unordered_map count; // {sender, the number of words sent} + + for (int i = 0; i < n; ++i) { + const string& message = messages[i]; + const string& sender = senders[i]; + const int wordsCount = ranges::count(message, ' ') + 1; + count[sender] += wordsCount; + const int numWordsSent = count[sender]; + if (numWordsSent > maxWordsSent) { + ans = sender; + maxWordsSent = numWordsSent; + } else if (numWordsSent == maxWordsSent && sender > ans) { + ans = sender; + } + } + + return ans; + } +}; diff --git a/solutions/2284. Sender With Largest Word Count/2284.java b/solutions/2284. Sender With Largest Word Count/2284.java new file mode 100644 index 00000000000..abaaacf21bb --- /dev/null +++ b/solutions/2284. Sender With Largest Word Count/2284.java @@ -0,0 +1,23 @@ +class Solution { + public String largestWordCount(String[] messages, String[] senders) { + final int n = messages.length; + String ans = ""; + int maxWordsSent = 0; + Map count = new HashMap<>(); // {sender, the number of words sent} + + for (int i = 0; i < n; ++i) { + final String message = messages[i]; + final String sender = senders[i]; + final int wordsCount = (int) message.chars().filter(c -> c == ' ').count() + 1; + final int numWordsSent = count.merge(sender, wordsCount, Integer::sum); + if (numWordsSent > maxWordsSent) { + ans = sender; + maxWordsSent = numWordsSent; + } else if (numWordsSent == maxWordsSent && sender.compareTo(ans) > 0) { + ans = sender; + } + } + + return ans; + } +} diff --git a/solutions/2284. Sender With Largest Word Count/2284.py b/solutions/2284. Sender With Largest Word Count/2284.py new file mode 100644 index 00000000000..ba637000761 --- /dev/null +++ b/solutions/2284. Sender With Largest Word Count/2284.py @@ -0,0 +1,18 @@ +class Solution: + def largestWordCount(self, messages: List[str], senders: List[str]) -> str: + n = len(messages) + ans = '' + maxWordsSent = 0 + count = collections.Counter() # [sender, # Words sent] + + for message, sender in zip(messages, senders): + wordsCount = message.count(' ') + 1 + count[sender] += wordsCount + numWordsSent = count[sender] + if numWordsSent > maxWordsSent: + ans = sender + maxWordsSent = numWordsSent + elif numWordsSent == maxWordsSent and sender > ans: + ans = sender + + return ans diff --git a/solutions/2285. Maximum Total Importance of Roads/2285.cpp b/solutions/2285. Maximum Total Importance of Roads/2285.cpp new file mode 100644 index 00000000000..808cb1b7f4a --- /dev/null +++ b/solutions/2285. Maximum Total Importance of Roads/2285.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long maximumImportance(int n, vector>& roads) { + long ans = 0; + vector count(n); + + for (const vector& road : roads) { + const int u = road[0]; + const int v = road[1]; + ++count[u]; + ++count[v]; + } + + ranges::sort(count); + + for (int i = 0; i < n; ++i) + ans += (i + 1) * count[i]; + + return ans; + } +}; diff --git a/solutions/2285. Maximum Total Importance of Roads/2285.java b/solutions/2285. Maximum Total Importance of Roads/2285.java new file mode 100644 index 00000000000..188736086f8 --- /dev/null +++ b/solutions/2285. Maximum Total Importance of Roads/2285.java @@ -0,0 +1,20 @@ +class Solution { + public long maximumImportance(int n, int[][] roads) { + long ans = 0; + long[] count = new long[n]; + + for (int[] road : roads) { + final int u = road[0]; + final int v = road[1]; + ++count[u]; + ++count[v]; + } + + Arrays.sort(count); + + for (int i = 0; i < n; ++i) + ans += (i + 1) * count[i]; + + return ans; + } +} diff --git a/solutions/2285. Maximum Total Importance of Roads/2285.py b/solutions/2285. Maximum Total Importance of Roads/2285.py new file mode 100644 index 00000000000..53f6bb7e3ce --- /dev/null +++ b/solutions/2285. Maximum Total Importance of Roads/2285.py @@ -0,0 +1,10 @@ +class Solution: + def maximumImportance(self, n: int, roads: List[List[int]]) -> int: + count = [0] * n + + for u, v in roads: + count[u] += 1 + count[v] += 1 + + count.sort() + return sum((i + 1) * c for i, c in enumerate(count)) diff --git a/solutions/2286. Booking Concert Tickets in Groups/2286.cpp b/solutions/2286. Booking Concert Tickets in Groups/2286.cpp new file mode 100644 index 00000000000..ad0fede2c95 --- /dev/null +++ b/solutions/2286. Booking Concert Tickets in Groups/2286.cpp @@ -0,0 +1,128 @@ +struct SegmentTreeNode { + int lo; + int hi; + unique_ptr left; + unique_ptr right; + int mx; + long sum; + SegmentTreeNode(int lo, int hi, unique_ptr&& left, + unique_ptr&& right, int mx, long sum) + : lo(lo), + hi(hi), + left(move(left)), + right(move(right)), + mx(mx), + sum(sum) {} +}; + +class SegmentTree { + public: + explicit SegmentTree(int n, int m) : m(m), root(move(build(0, n - 1))) {} + + vector maxRange(int k, int maxRow) { + return maxRange(root, k, maxRow); + } + + long sumRange(int maxRow) { + return sumRange(root, 0, maxRow); + } + + // Substracts k from the seats row. + void substract(int row, int k) { + substract(root, row, k); + } + + private: + const int m; + unique_ptr root; + + unique_ptr build(int l, int r) { + if (l == r) + return make_unique(l, r, nullptr, nullptr, m, m); + const int mid = (l + r) / 2; + unique_ptr left = build(l, mid); + unique_ptr right = build(mid + 1, r); + return make_unique(l, r, move(left), move(right), + max(left->mx, right->mx), + left->sum + right->sum); + } + + vector maxRange(unique_ptr& root, int k, int maxRow) { + if (root->lo == root->hi) { + if (root->sum < k || root->lo > maxRow) + return {}; + return {root->lo, m - static_cast(root->sum)}; // {row, col} + } + // Greedily search the left subtree + if (root->left->mx >= k) + return maxRange(root->left, k, maxRow); + return maxRange(root->right, k, maxRow); + } + + long sumRange(unique_ptr& root, int i, int j) { + if (root->lo == i && root->hi == j) + return root->sum; + const int mid = (root->lo + root->hi) / 2; + if (j <= mid) + return sumRange(root->left, i, j); + if (i > mid) + return sumRange(root->right, i, j); + return sumRange(root->left, i, mid) + sumRange(root->right, mid + 1, j); + } + + void substract(unique_ptr& root, int row, int k) { + if (root == nullptr) + return; + if (root->lo == root->hi && root->hi == row) { + root->mx -= k; + root->sum -= k; + return; + } + const int mid = (root->lo + root->hi) / 2; + if (row <= mid) + substract(root->left, row, k); + else + substract(root->right, row, k); + root->mx = max(root->left->mx, root->right->mx); + root->sum = root->left->sum + root->right->sum; + } +}; + +class BookMyShow { + public: + BookMyShow(int n, int m) : tree(n, m), seats(n, m) {} + + vector gather(int k, int maxRow) { + const vector res = tree.maxRange(k, maxRow); + if (res.size() == 2) { + const int row = res[0]; + tree.substract(row, k); + seats[row] -= k; + } + return res; + } + + bool scatter(int k, int maxRow) { + if (tree.sumRange(maxRow) < k) + return false; + + while (k > 0) + if (seats[minVacantRow] >= k) { + tree.substract(minVacantRow, k); + seats[minVacantRow] -= k; + k = 0; + } else { + tree.substract(minVacantRow, seats[minVacantRow]); + k -= seats[minVacantRow]; + seats[minVacantRow] = 0; + ++minVacantRow; + } + + return true; + } + + private: + SegmentTree tree; + vector seats; // the remaining seats at each row + int minVacantRow = 0; +}; diff --git a/solutions/2287. Rearrange Characters to Make Target String/2287.cpp b/solutions/2287. Rearrange Characters to Make Target String/2287.cpp new file mode 100644 index 00000000000..0f4acb3ec6f --- /dev/null +++ b/solutions/2287. Rearrange Characters to Make Target String/2287.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int rearrangeCharacters(string s, string target) { + int ans = s.length(); + vector countS(128); + vector countT(128); + + for (const char c : s) + ++countS[c]; + + for (const char c : target) + ++countT[c]; + + for (const char c : target) + ans = min(ans, countS[c] / countT[c]); + + return ans; + } +}; diff --git a/solutions/2287. Rearrange Characters to Make Target String/2287.java b/solutions/2287. Rearrange Characters to Make Target String/2287.java new file mode 100644 index 00000000000..ad05298f9ef --- /dev/null +++ b/solutions/2287. Rearrange Characters to Make Target String/2287.java @@ -0,0 +1,18 @@ +class Solution { + public int rearrangeCharacters(String s, String target) { + int ans = s.length(); + int[] countS = new int[128]; + int[] countT = new int[128]; + + for (final char c : s.toCharArray()) + ++countS[c]; + + for (final char c : target.toCharArray()) + ++countT[c]; + + for (final char c : target.toCharArray()) + ans = Math.min(ans, countS[c] / countT[c]); + + return ans; + } +} diff --git a/solutions/2287. Rearrange Characters to Make Target String/2287.py b/solutions/2287. Rearrange Characters to Make Target String/2287.py new file mode 100644 index 00000000000..dce0102f86b --- /dev/null +++ b/solutions/2287. Rearrange Characters to Make Target String/2287.py @@ -0,0 +1,5 @@ +class Solution: + def rearrangeCharacters(self, s: str, target: str) -> int: + countS = collections.Counter(s) + countT = collections.Counter(target) + return min(countS[c] // countT[c] for c in target) diff --git a/solutions/2288. Apply Discount to Prices/2288.cpp b/solutions/2288. Apply Discount to Prices/2288.cpp new file mode 100644 index 00000000000..683b9eb6cd4 --- /dev/null +++ b/solutions/2288. Apply Discount to Prices/2288.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string discountPrices(string sentence, int discount) { + constexpr int kPrecision = 2; + string ans; + istringstream iss(sentence); + + for (string word; iss >> word;) + if (word[0] == '$' && word.length() > 1) { + const string digits = word.substr(1); + if (ranges::all_of(digits, + [](const char digit) { return isdigit(digit); })) { + const double val = stold(digits) * (100 - discount) / 100; + const string s = to_string(val); + const string trimmed = s.substr(0, s.find(".") + kPrecision + 1); + ans += "$" + trimmed + " "; + } else { + ans += word + " "; + } + } else { + ans += word + " "; + } + + ans.pop_back(); + return ans; + } +}; diff --git a/solutions/2288. Apply Discount to Prices/2288.java b/solutions/2288. Apply Discount to Prices/2288.java new file mode 100644 index 00000000000..5e99ac3005d --- /dev/null +++ b/solutions/2288. Apply Discount to Prices/2288.java @@ -0,0 +1,24 @@ +class Solution { + public String discountPrices(String sentence, int discount) { + final int kPrecision = 2; + StringBuilder sb = new StringBuilder(); + + for (final String word : sentence.split(" ")) + if (word.charAt(0) == '$' && word.length() > 1) { + final String digits = word.substring(1); + if (digits.chars().allMatch(c -> Character.isDigit(c))) { + final double val = Double.parseDouble(digits) * (100 - discount) / 100; + final String s = String.format("%.2f", val); + final String trimmed = s.substring(0, s.indexOf(".") + kPrecision + 1); + sb.append("$").append(trimmed).append(" "); + } else { + sb.append(word).append(" "); + } + } else { + sb.append(word).append(" "); + } + + sb.deleteCharAt(sb.length() - 1); + return sb.toString(); + } +} diff --git a/solutions/2288. Apply Discount to Prices/2288.py b/solutions/2288. Apply Discount to Prices/2288.py new file mode 100644 index 00000000000..938449ea468 --- /dev/null +++ b/solutions/2288. Apply Discount to Prices/2288.py @@ -0,0 +1,19 @@ +class Solution: + def discountPrices(self, sentence: str, discount: int) -> str: + kPrecision = 2 + ans = [] + + for word in sentence.split(): + if word[0] == '$' and len(word) > 1: + digits = word[1:] + if all(digit.isdigit() for digit in digits): + val = float(digits) * (100 - discount) / 100 + s = f'{val:.2f}' + trimmed = s[:s.index('.') + kPrecision + 1] + ans.append('$' + trimmed) + else: + ans.append(word) + else: + ans.append(word) + + return ' '.join(ans) diff --git a/solutions/2289. Steps to Make Array Non-decreasing/2289.cpp b/solutions/2289. Steps to Make Array Non-decreasing/2289.cpp new file mode 100644 index 00000000000..8f3097a969c --- /dev/null +++ b/solutions/2289. Steps to Make Array Non-decreasing/2289.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int totalSteps(vector& nums) { + // dp[i] := the number of steps to remove nums[i] + vector dp(nums.size()); + stack stack; + + for (int i = 0; i < nums.size(); ++i) { + int step = 1; + while (!stack.empty() && nums[stack.top()] <= nums[i]) + step = max(step, dp[stack.top()] + 1), stack.pop(); + if (!stack.empty()) + dp[i] = step; + stack.push(i); + } + + return ranges::max(dp); + } +}; diff --git a/solutions/2289. Steps to Make Array Non-decreasing/2289.java b/solutions/2289. Steps to Make Array Non-decreasing/2289.java new file mode 100644 index 00000000000..bbc1f0c713b --- /dev/null +++ b/solutions/2289. Steps to Make Array Non-decreasing/2289.java @@ -0,0 +1,18 @@ +class Solution { + public int totalSteps(int[] nums) { + // dp[i] := the number of steps to remove nums[i] + int[] dp = new int[nums.length]; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < nums.length; ++i) { + int step = 1; + while (!stack.isEmpty() && nums[stack.peek()] <= nums[i]) + step = Math.max(step, dp[stack.pop()] + 1); + if (!stack.isEmpty()) + dp[i] = step; + stack.push(i); + } + + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/2289. Steps to Make Array Non-decreasing/2289.py b/solutions/2289. Steps to Make Array Non-decreasing/2289.py new file mode 100644 index 00000000000..d6724fcab5e --- /dev/null +++ b/solutions/2289. Steps to Make Array Non-decreasing/2289.py @@ -0,0 +1,15 @@ +class Solution: + def totalSteps(self, nums: List[int]) -> int: + # dp[i] := the number of steps to remove nums[i] + dp = [0] * len(nums) + stack = [] + + for i, num in enumerate(nums): + step = 1 + while stack and nums[stack[-1]] <= num: + step = max(step, dp[stack.pop()] + 1) + if stack: + dp[i] = step + stack.append(i) + + return max(dp) diff --git a/solutions/229. Majority Element II/229.cpp b/solutions/229. Majority Element II/229.cpp new file mode 100644 index 00000000000..ec59f553922 --- /dev/null +++ b/solutions/229. Majority Element II/229.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector majorityElement(vector& nums) { + vector ans; + int candidate1 = 0; + int candidate2 = 1; // any number different from candidate1 + int countSoFar1 = 0; // the number of candidate1 so far + int countSoFar2 = 0; // the number of candidate2 so far + + for (const int num : nums) + if (num == candidate1) { + ++countSoFar1; + } else if (num == candidate2) { + ++countSoFar2; + } else if (countSoFar1 == 0) { // Assign the new candidate. + candidate1 = num; + ++countSoFar1; + } else if (countSoFar2 == 0) { // Assign the new candidate. + candidate2 = num; + ++countSoFar2; + } else { // Meet a new number, so pair with the previous counts. + --countSoFar1; + --countSoFar2; + } + + const int count1 = ranges::count(nums, candidate1); + const int count2 = ranges::count(nums, candidate2); + + if (count1 > nums.size() / 3) + ans.push_back(candidate1); + if (count2 > nums.size() / 3) + ans.push_back(candidate2); + return ans; + } +}; diff --git a/solutions/229. Majority Element II/229.java b/solutions/229. Majority Element II/229.java new file mode 100644 index 00000000000..6ce45e29dde --- /dev/null +++ b/solutions/229. Majority Element II/229.java @@ -0,0 +1,40 @@ +class Solution { + public List majorityElement(int[] nums) { + List ans = new ArrayList<>(); + int candidate1 = 0; + int candidate2 = 1; // any number different from candidate1 + int countSoFar1 = 0; // the number of candidate1 so far + int countSoFar2 = 0; // the number of candidate2 so far + + for (final int num : nums) + if (num == candidate1) { + ++countSoFar1; + } else if (num == candidate2) { + ++countSoFar2; + } else if (countSoFar1 == 0) { // Assign the new candidate. + candidate1 = num; + ++countSoFar1; + } else if (countSoFar2 == 0) { // Assign the new candidate. + candidate2 = num; + ++countSoFar2; + } else { // Meet a new number, so pair with the previous counts. + --countSoFar1; + --countSoFar2; + } + + int count1 = 0; + int count2 = 0; + + for (final int num : nums) + if (num == candidate1) + ++count1; + else if (num == candidate2) + ++count2; + + if (count1 > nums.length / 3) + ans.add(candidate1); + if (count2 > nums.length / 3) + ans.add(candidate2); + return ans; + } +} diff --git a/solutions/229. Majority Element II/229.py b/solutions/229. Majority Element II/229.py new file mode 100644 index 00000000000..e3226e63f92 --- /dev/null +++ b/solutions/229. Majority Element II/229.py @@ -0,0 +1,23 @@ +class Solution: + def majorityElement(self, nums: List[int]) -> List[int]: + ans1 = 0 + ans2 = 1 + count1 = 0 + count2 = 0 + + for num in nums: + if num == ans1: + count1 += 1 + elif num == ans2: + count2 += 1 + elif count1 == 0: + ans1 = num + count1 = 1 + elif count2 == 0: + ans2 = num + count2 = 1 + else: + count1 -= 1 + count2 -= 1 + + return [ans for ans in (ans1, ans2) if nums.count(ans) > len(nums) // 3] diff --git a/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.cpp b/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.cpp new file mode 100644 index 00000000000..199be0d6c87 --- /dev/null +++ b/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minimumObstacles(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + using T = tuple; // (d, i, j) + priority_queue, greater<>> minHeap; + vector> dist(m, vector(n, INT_MAX)); + + minHeap.emplace(grid[0][0], 0, 0); + dist[0][0] = grid[0][0]; + + while (!minHeap.empty()) { + const auto [d, i, j] = minHeap.top(); + minHeap.pop(); + if (i == m - 1 && j == n - 1) + return d; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + const int newDist = d + grid[i][j]; + if (newDist < dist[x][y]) { + dist[x][y] = newDist; + minHeap.emplace(newDist, x, y); + } + } + } + + return dist[m - 1][n - 1]; + } +}; diff --git a/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.java b/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.java new file mode 100644 index 00000000000..12c5caf9ea7 --- /dev/null +++ b/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.java @@ -0,0 +1,35 @@ +class Solution { + public int minimumObstacles(int[][] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length; + // (d, i, j) + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + int[][] dist = new int[m][n]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + + minHeap.offer(new int[] {grid[0][0], 0, 0}); + dist[0][0] = grid[0][0]; + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek()[0]; + final int i = minHeap.peek()[1]; + final int j = minHeap.poll()[2]; + if (i == m - 1 && j == n - 1) + return d; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + final int newDist = d + grid[i][j]; + if (newDist < dist[x][y]) { + dist[x][y] = newDist; + minHeap.offer(new int[] {newDist, x, y}); + } + } + } + + return dist[m - 1][n - 1]; + } +} diff --git a/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.py b/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.py new file mode 100644 index 00000000000..d3509551417 --- /dev/null +++ b/solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.py @@ -0,0 +1,24 @@ +class Solution: + def minimumObstacles(self, grid: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + minHeap = [(grid[0][0], 0, 0)] # (d, i, j) + dist = [[math.inf] * n for _ in range(m)] + dist[0][0] = grid[0][0] + + while minHeap: + d, i, j = heapq.heappop(minHeap) + if i == m - 1 and j == n - 1: + return d + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + newDist = d + grid[i][j] + if newDist < dist[x][y]: + dist[x][y] = newDist + heapq.heappush(minHeap, (newDist, x, y)) + + return dist[m - 1][n - 1] diff --git a/solutions/2291. Maximum Profit From Trading Stocks/2291-2.cpp b/solutions/2291. Maximum Profit From Trading Stocks/2291-2.cpp new file mode 100644 index 00000000000..4c11859296e --- /dev/null +++ b/solutions/2291. Maximum Profit From Trading Stocks/2291-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maximumProfit(vector& present, vector& future, int budget) { + const int n = present.size(); + // dp[i] := the maximum profit of buying present so far with i budget + vector dp(budget + 1); + + for (int i = 0; i < n; ++i) + for (int j = budget; j >= present[i]; --j) + dp[j] = max(dp[j], future[i] - present[i] + dp[j - present[i]]); + + return dp[budget]; + } +}; diff --git a/solutions/2291. Maximum Profit From Trading Stocks/2291-2.java b/solutions/2291. Maximum Profit From Trading Stocks/2291-2.java new file mode 100644 index 00000000000..1202721af59 --- /dev/null +++ b/solutions/2291. Maximum Profit From Trading Stocks/2291-2.java @@ -0,0 +1,13 @@ +class Solution { + public int maximumProfit(int[] present, int[] future, int budget) { + final int n = present.length; + // dp[i] := the maximum profit of buying present so far with i budget + int[] dp = new int[budget + 1]; + + for (int i = 0; i < n; ++i) + for (int j = budget; j >= present[i]; --j) + dp[j] = Math.max(dp[j], future[i] - present[i] + dp[j - present[i]]); + + return dp[budget]; + } +} diff --git a/solutions/2291. Maximum Profit From Trading Stocks/2291-2.py b/solutions/2291. Maximum Profit From Trading Stocks/2291-2.py new file mode 100644 index 00000000000..d57f17c6177 --- /dev/null +++ b/solutions/2291. Maximum Profit From Trading Stocks/2291-2.py @@ -0,0 +1,11 @@ +class Solution: + def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: + n = len(present) + # dp[i] := the maximum profit of buying present so far with i budget + dp = [0] * (budget + 1) + + for p, f in zip(present, future): + for j in range(budget, p - 1, -1): + dp[j] = max(dp[j], f - p + dp[j - p]) + + return dp[budget] diff --git a/solutions/2291. Maximum Profit From Trading Stocks/2291.cpp b/solutions/2291. Maximum Profit From Trading Stocks/2291.cpp new file mode 100644 index 00000000000..ac8afa46754 --- /dev/null +++ b/solutions/2291. Maximum Profit From Trading Stocks/2291.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maximumProfit(vector& present, vector& future, int budget) { + const int n = present.size(); + // dp[i][j] := the maximum profit of buying present[0..i) with j budget + vector> dp(n + 1, vector(budget + 1)); + + for (int i = 1; i <= n; ++i) { + const int profit = future[i - 1] - present[i - 1]; + for (int j = 0; j <= budget; ++j) + if (j < present[i - 1]) + dp[i][j] = dp[i - 1][j]; + else + dp[i][j] = max(dp[i - 1][j], profit + dp[i - 1][j - present[i - 1]]); + } + + return dp[n][budget]; + } +}; diff --git a/solutions/2291. Maximum Profit From Trading Stocks/2291.java b/solutions/2291. Maximum Profit From Trading Stocks/2291.java new file mode 100644 index 00000000000..90558581298 --- /dev/null +++ b/solutions/2291. Maximum Profit From Trading Stocks/2291.java @@ -0,0 +1,18 @@ +class Solution { + public int maximumProfit(int[] present, int[] future, int budget) { + final int n = present.length; + // dp[i][j] := the maximum profit of buying present[0..i) with j budget + int[][] dp = new int[n + 1][budget + 1]; + + for (int i = 1; i <= n; ++i) { + final int profit = future[i - 1] - present[i - 1]; + for (int j = 0; j <= budget; ++j) + if (j < present[i - 1]) + dp[i][j] = dp[i - 1][j]; + else + dp[i][j] = Math.max(dp[i - 1][j], profit + dp[i - 1][j - present[i - 1]]); + } + + return dp[n][budget]; + } +} diff --git a/solutions/2291. Maximum Profit From Trading Stocks/2291.py b/solutions/2291. Maximum Profit From Trading Stocks/2291.py new file mode 100644 index 00000000000..126621c5aa0 --- /dev/null +++ b/solutions/2291. Maximum Profit From Trading Stocks/2291.py @@ -0,0 +1,15 @@ +class Solution: + def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: + n = len(present) + # dp[i][j] := the maximum profit of buying present[0..i) with j budget + dp = [[0] * (budget + 1) for _ in range(n + 1)] + + for i in range(1, n + 1): + profit = future[i - 1] - present[i - 1] + for j in range(budget + 1): + if j < present[i - 1]: + dp[i][j] = dp[i - 1][j] + else: + dp[i][j] = max(dp[i - 1][j], profit + dp[i - 1][j - present[i - 1]]) + + return dp[n][budget] diff --git a/solutions/2292. Products With Three or More Orders in Two Consecutive Years/2292.sql b/solutions/2292. Products With Three or More Orders in Two Consecutive Years/2292.sql new file mode 100644 index 00000000000..d2e84a278cd --- /dev/null +++ b/solutions/2292. Products With Three or More Orders in Two Consecutive Years/2292.sql @@ -0,0 +1,16 @@ +WITH + OrdersNeighbors AS ( + SELECT + product_id, + YEAR(purchase_date) AS curr_year, + LEAD(YEAR(purchase_date)) OVER( + PARTITION BY product_id + ORDER BY YEAR(purchase_date) + ) AS next_year + FROM orders + GROUP BY 1, 2 + HAVING COUNT(order_id) >= 3 + ) +SELECT DISTINCT product_id +FROM OrdersNeighbors +WHERE curr_year + 1 = next_year; diff --git a/solutions/2293. Min Max Game/2293.cpp b/solutions/2293. Min Max Game/2293.cpp new file mode 100644 index 00000000000..d65b7a08a9a --- /dev/null +++ b/solutions/2293. Min Max Game/2293.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int minMaxGame(vector& nums) { + if (nums.size() == 1) + return nums[0]; + + vector nextNums; + for (int i = 0; i < nums.size() / 2; ++i) + nextNums.push_back(i % 2 == 0 ? min(nums[2 * i], nums[2 * i + 1]) + : max(nums[2 * i], nums[2 * i + 1])); + return minMaxGame(nextNums); + } +}; diff --git a/solutions/2293. Min Max Game/2293.java b/solutions/2293. Min Max Game/2293.java new file mode 100644 index 00000000000..0d83066fec3 --- /dev/null +++ b/solutions/2293. Min Max Game/2293.java @@ -0,0 +1,12 @@ +class Solution { + public int minMaxGame(int[] nums) { + if (nums.length == 1) + return nums[0]; + + int[] nextNums = new int[nums.length / 2]; + for (int i = 0; i < nextNums.length; ++i) + nextNums[i] = i % 2 == 0 ? Math.min(nums[2 * i], nums[2 * i + 1]) + : Math.max(nums[2 * i], nums[2 * i + 1]); + return minMaxGame(nextNums); + } +} diff --git a/solutions/2293. Min Max Game/2293.py b/solutions/2293. Min Max Game/2293.py new file mode 100644 index 00000000000..5f1048d0d86 --- /dev/null +++ b/solutions/2293. Min Max Game/2293.py @@ -0,0 +1,10 @@ +class Solution: + def minMaxGame(self, nums: List[int]) -> int: + if len(nums) == 1: + return nums[0] + + nextNums = [] + for i in range(len(nums) // 2): + nextNums.append(min(nums[2 * i], nums[2 * i + 1]) if i % 2 == 0 else + max(nums[2 * i], nums[2 * i + 1])) + return self.minMaxGame(nextNums) diff --git a/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.cpp b/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.cpp new file mode 100644 index 00000000000..7353d369d8e --- /dev/null +++ b/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int partitionArray(vector& nums, int k) { + ranges::sort(nums); + + int ans = 1; + int mn = nums[0]; + + for (int i = 1; i < nums.size(); ++i) + if (mn + k < nums[i]) { + ++ans; + mn = nums[i]; + } + + return ans; + } +}; diff --git a/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.java b/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.java new file mode 100644 index 00000000000..d1f752ba0f7 --- /dev/null +++ b/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.java @@ -0,0 +1,16 @@ +class Solution { + public int partitionArray(int[] nums, int k) { + Arrays.sort(nums); + + int ans = 1; + int mn = nums[0]; + + for (int i = 1; i < nums.length; ++i) + if (mn + k < nums[i]) { + ++ans; + mn = nums[i]; + } + + return ans; + } +} diff --git a/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.py b/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.py new file mode 100644 index 00000000000..fcc4f9552ae --- /dev/null +++ b/solutions/2294. Partition Array Such That Maximum Difference Is K/2294.py @@ -0,0 +1,13 @@ +class Solution: + def partitionArray(self, nums: List[int], k: int) -> int: + nums.sort() + + ans = 1 + mn = nums[0] + + for i in range(1, len(nums)): + if mn + k < nums[i]: + ans += 1 + mn = nums[i] + + return ans diff --git a/solutions/2295. Replace Elements in an Array/2295.cpp b/solutions/2295. Replace Elements in an Array/2295.cpp new file mode 100644 index 00000000000..f2c99838452 --- /dev/null +++ b/solutions/2295. Replace Elements in an Array/2295.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector arrayChange(vector& nums, vector>& operations) { + unordered_map numToIndex; + + for (int i = 0; i < nums.size(); ++i) + numToIndex[nums[i]] = i; + + for (const vector& o : operations) { + const int original = o[0]; + const int replaced = o[1]; + const int index = numToIndex[original]; + nums[index] = replaced; + numToIndex.erase(original); + numToIndex[replaced] = index; + } + + return nums; + } +}; diff --git a/solutions/2295. Replace Elements in an Array/2295.java b/solutions/2295. Replace Elements in an Array/2295.java new file mode 100644 index 00000000000..9a5295e5276 --- /dev/null +++ b/solutions/2295. Replace Elements in an Array/2295.java @@ -0,0 +1,19 @@ +class Solution { + public int[] arrayChange(int[] nums, int[][] operations) { + Map numToIndex = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) + numToIndex.put(nums[i], i); + + for (int[] o : operations) { + final int original = o[0]; + final int replaced = o[1]; + final int index = numToIndex.get(original); + nums[index] = replaced; + numToIndex.remove(original); + numToIndex.put(replaced, index); + } + + return nums; + } +} diff --git a/solutions/2295. Replace Elements in an Array/2295.py b/solutions/2295. Replace Elements in an Array/2295.py new file mode 100644 index 00000000000..36a04fcb8a8 --- /dev/null +++ b/solutions/2295. Replace Elements in an Array/2295.py @@ -0,0 +1,11 @@ +class Solution: + def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: + numToIndex = {num: i for i, num in enumerate(nums)} + + for original, replaced in operations: + index = numToIndex[original] + nums[index] = replaced + del numToIndex[original] + numToIndex[replaced] = index + + return nums diff --git a/solutions/2296. Design a Text Editor/2296.cpp b/solutions/2296. Design a Text Editor/2296.cpp new file mode 100644 index 00000000000..40cfc1019b2 --- /dev/null +++ b/solutions/2296. Design a Text Editor/2296.cpp @@ -0,0 +1,35 @@ +class TextEditor { + public: + void addText(string text) { + s += text; + } + + int deleteText(int k) { + const int numDeleted = min(k, static_cast(s.length())); + for (int i = 0; i < numDeleted; ++i) + s.pop_back(); + return numDeleted; + } + + string cursorLeft(int k) { + while (!s.empty() && k--) + stack.push(s.back()), s.pop_back(); + return getString(); + } + + string cursorRight(int k) { + while (!stack.empty() && k--) + s += stack.top(), stack.pop(); + return getString(); + } + + string getString() { + if (s.length() < 10) + return s; + return s.substr(s.length() - 10); + } + + private: + string s; + stack stack; +}; diff --git a/solutions/2296. Design a Text Editor/2296.java b/solutions/2296. Design a Text Editor/2296.java new file mode 100644 index 00000000000..dcc8a10ea96 --- /dev/null +++ b/solutions/2296. Design a Text Editor/2296.java @@ -0,0 +1,35 @@ +class TextEditor { + public void addText(String text) { + sb.append(text); + } + + public int deleteText(int k) { + final int numDeleted = Math.min(k, sb.length()); + for (int i = 0; i < numDeleted; ++i) + sb.deleteCharAt(sb.length() - 1); + return numDeleted; + } + + public String cursorLeft(int k) { + while (!sb.isEmpty() && k-- > 0) { + stack.push(sb.charAt(sb.length() - 1)); + sb.deleteCharAt(sb.length() - 1); + } + return getString(); + } + + public String cursorRight(int k) { + while (!stack.isEmpty() && k-- > 0) + sb.append(stack.pop()); + return getString(); + } + + private String getString() { + if (sb.length() < 10) + return sb.toString(); + return sb.substring(sb.length() - 10).toString(); + } + + private StringBuilder sb = new StringBuilder(); + private Deque stack = new ArrayDeque<>(); +} diff --git a/solutions/2296. Design a Text Editor/2296.py b/solutions/2296. Design a Text Editor/2296.py new file mode 100644 index 00000000000..ce68c7e65dc --- /dev/null +++ b/solutions/2296. Design a Text Editor/2296.py @@ -0,0 +1,31 @@ +class TextEditor: + def __init__(self): + self.s = [] + self.stack = [] + + def addText(self, text: str) -> None: + for c in text: + self.s.append(c) + + def deleteText(self, k: int) -> int: + numDeleted = min(k, len(self.s)) + for _ in range(numDeleted): + self.s.pop() + return numDeleted + + def cursorLeft(self, k: int) -> str: + while self.s and k > 0: + self.stack.append(self.s.pop()) + k -= 1 + return self._getString() + + def cursorRight(self, k: int) -> str: + while self.stack and k > 0: + self.s.append(self.stack.pop()) + k -= 1 + return self._getString() + + def _getString(self) -> str: + if len(self.s) < 10: + return ''.join(self.s) + return ''.join(self.s[-10:]) diff --git a/solutions/2297. Jump Game IX/2297.cpp b/solutions/2297. Jump Game IX/2297.cpp new file mode 100644 index 00000000000..f704f7378c3 --- /dev/null +++ b/solutions/2297. Jump Game IX/2297.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long minCost(vector& nums, vector& costs) { + const int n = nums.size(); + // dp[i] := the minimum cost to jump to i + vector dp(n, LONG_MAX); + stack maxStack; + stack minStack; + + dp[0] = 0; + + for (int i = 0; i < n; ++i) { + while (!maxStack.empty() && nums[i] >= nums[maxStack.top()]) + dp[i] = min(dp[i], dp[maxStack.top()] + costs[i]), maxStack.pop(); + while (!minStack.empty() && nums[i] < nums[minStack.top()]) + dp[i] = min(dp[i], dp[minStack.top()] + costs[i]), minStack.pop(); + maxStack.push(i); + minStack.push(i); + } + + return dp.back(); + } +}; diff --git a/solutions/2297. Jump Game IX/2297.java b/solutions/2297. Jump Game IX/2297.java new file mode 100644 index 00000000000..1840af76f7e --- /dev/null +++ b/solutions/2297. Jump Game IX/2297.java @@ -0,0 +1,23 @@ +class Solution { + public long minCost(int[] nums, int[] costs) { + final int n = nums.length; + // dp[i] := the minimum cost to jump to i + long[] dp = new long[n]; + Deque maxStack = new ArrayDeque<>(); + Deque minStack = new ArrayDeque<>(); + + Arrays.fill(dp, Long.MAX_VALUE); + dp[0] = 0; + + for (int i = 0; i < n; ++i) { + while (!maxStack.isEmpty() && nums[i] >= nums[maxStack.peek()]) + dp[i] = Math.min(dp[i], dp[maxStack.pop()] + costs[i]); + while (!minStack.isEmpty() && nums[i] < nums[minStack.peek()]) + dp[i] = Math.min(dp[i], dp[minStack.pop()] + costs[i]); + maxStack.push(i); + minStack.push(i); + } + + return dp[n - 1]; + } +} diff --git a/solutions/2297. Jump Game IX/2297.py b/solutions/2297. Jump Game IX/2297.py new file mode 100644 index 00000000000..c3b3ceec741 --- /dev/null +++ b/solutions/2297. Jump Game IX/2297.py @@ -0,0 +1,18 @@ +class Solution: + def minCost(self, nums: List[int], costs: List[int]) -> int: + # dp[i] := the minimum cost to jump to i + dp = [math.inf] * len(nums) + maxStack = [] + minStack = [] + + dp[0] = 0 + + for i, num in enumerate(nums): + while maxStack and num >= nums[maxStack[-1]]: + dp[i] = min(dp[i], dp[maxStack.pop()] + costs[i]) + while minStack and num < nums[minStack[-1]]: + dp[i] = min(dp[i], dp[minStack.pop()] + costs[i]) + maxStack.append(i) + minStack.append(i) + + return dp[-1] diff --git a/solutions/2298. Tasks Count in the Weekend/2298.sql b/solutions/2298. Tasks Count in the Weekend/2298.sql new file mode 100644 index 00000000000..037964e334b --- /dev/null +++ b/solutions/2298. Tasks Count in the Weekend/2298.sql @@ -0,0 +1,4 @@ +SELECT + SUM(WEEKDAY(submit_date) >= 5) AS weekend_cnt, + SUM(WEEKDAY(submit_date) < 5) AS working_cnt +FROM Tasks; diff --git a/solutions/2299. Strong Password Checker II/2299.cpp b/solutions/2299. Strong Password Checker II/2299.cpp new file mode 100644 index 00000000000..16657ead0d1 --- /dev/null +++ b/solutions/2299. Strong Password Checker II/2299.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + bool strongPasswordCheckerII(string password) { + if (password.length() < 8) + return false; + + const bool hasLowerCase = + ranges::any_of(password, [](const char c) { return islower(c); }); + if (!hasLowerCase) + return false; + + const bool hasUpperCase = + ranges::any_of(password, [](const char c) { return isupper(c); }); + if (!hasUpperCase) + return false; + + const bool hasDigit = + ranges::any_of(password, [](const char c) { return isdigit(c); }); + if (!hasDigit) + return false; + + const bool hasSpecial = ranges::any_of(password, [](const char c) { + return string("!@#$%^&*()-+").find(c) != string::npos; + }); + if (!hasSpecial) + return false; + + for (int i = 1; i < password.length(); ++i) + if (password[i] == password[i - 1]) + return false; + return true; + } +}; diff --git a/solutions/2299. Strong Password Checker II/2299.java b/solutions/2299. Strong Password Checker II/2299.java new file mode 100644 index 00000000000..f4c9b211783 --- /dev/null +++ b/solutions/2299. Strong Password Checker II/2299.java @@ -0,0 +1,27 @@ +class Solution { + public boolean strongPasswordCheckerII(String password) { + if (password.length() < 8) + return false; + + final boolean hasLowerCase = password.chars().anyMatch(c -> Character.isLowerCase(c)); + if (!hasLowerCase) + return false; + + final boolean hasUpperCase = password.chars().anyMatch(c -> Character.isUpperCase(c)); + if (!hasUpperCase) + return false; + + final boolean hasDigit = password.chars().anyMatch(c -> Character.isDigit(c)); + if (!hasDigit) + return false; + + final boolean hasSpecial = password.chars().anyMatch(c -> "!@#$%^&*()-+".indexOf(c) != -1); + if (!hasSpecial) + return false; + + for (int i = 1; i < password.length(); ++i) + if (password.charAt(i) == password.charAt(i - 1)) + return false; + return true; + } +} diff --git a/solutions/2299. Strong Password Checker II/2299.py b/solutions/2299. Strong Password Checker II/2299.py new file mode 100644 index 00000000000..6342efe5d3f --- /dev/null +++ b/solutions/2299. Strong Password Checker II/2299.py @@ -0,0 +1,13 @@ +class Solution: + def strongPasswordCheckerII(self, password: str) -> bool: + if len(password) < 8: + return False + if not any(c.islower() for c in password): + return False + if not any(c.isupper() for c in password): + return False + if not any(c.isdigit() for c in password): + return False + if not any("!@#$%^&*()-+".find(c) != -1 for c in password): + return False + return all(a != b for a, b in zip(password, password[1:])) diff --git a/solutions/23. Merge k Sorted Lists/23.cpp b/solutions/23. Merge k Sorted Lists/23.cpp new file mode 100644 index 00000000000..c53ea40afb3 --- /dev/null +++ b/solutions/23. Merge k Sorted Lists/23.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + ListNode* mergeKLists(vector& lists) { + ListNode dummy(0); + ListNode* curr = &dummy; + auto compare = [](ListNode* a, ListNode* b) { return a->val > b->val; }; + priority_queue, decltype(compare)> minHeap( + compare); + + for (ListNode* list : lists) + if (list != nullptr) + minHeap.push(list); + + while (!minHeap.empty()) { + ListNode* minNode = minHeap.top(); + minHeap.pop(); + if (minNode->next) + minHeap.push(minNode->next); + curr->next = minNode; + curr = curr->next; + } + + return dummy.next; + } +}; diff --git a/solutions/23. Merge k Sorted Lists/23.java b/solutions/23. Merge k Sorted Lists/23.java new file mode 100644 index 00000000000..148d1809a5f --- /dev/null +++ b/solutions/23. Merge k Sorted Lists/23.java @@ -0,0 +1,21 @@ +class Solution { + public ListNode mergeKLists(ListNode[] lists) { + ListNode dummy = new ListNode(0); + ListNode curr = dummy; + Queue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val); + + for (final ListNode list : lists) + if (list != null) + minHeap.offer(list); + + while (!minHeap.isEmpty()) { + ListNode minNode = minHeap.poll(); + if (minNode.next != null) + minHeap.offer(minNode.next); + curr.next = minNode; + curr = curr.next; + } + + return dummy.next; + } +} diff --git a/solutions/23. Merge k Sorted Lists/23.py b/solutions/23. Merge k Sorted Lists/23.py new file mode 100644 index 00000000000..abe295f4a67 --- /dev/null +++ b/solutions/23. Merge k Sorted Lists/23.py @@ -0,0 +1,21 @@ +from queue import PriorityQueue + + +class Solution: + def mergeKLists(self, lists: List[ListNode]) -> ListNode: + dummy = ListNode(0) + curr = dummy + pq = PriorityQueue() + + for i, lst in enumerate(lists): + if lst: + pq.put((lst.val, i, lst)) + + while not pq.empty(): + _, i, minNode = pq.get() + if minNode.next: + pq.put((minNode.next.val, i, minNode.next)) + curr.next = minNode + curr = curr.next + + return dummy.next diff --git a/solutions/230. Kth Smallest Element in a BST/230-2.cpp b/solutions/230. Kth Smallest Element in a BST/230-2.cpp new file mode 100644 index 00000000000..4fa027d5af9 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int kthSmallest(TreeNode* root, int k) { + int ans = -1; + int rank = 0; + traverse(root, k, rank, ans); + return ans; + } + + private: + void traverse(TreeNode* root, int k, int& rank, int& ans) { + if (root == nullptr) + return; + + traverse(root->left, k, rank, ans); + if (++rank == k) { + ans = root->val; + return; + } + traverse(root->right, k, rank, ans); + } +}; diff --git a/solutions/230. Kth Smallest Element in a BST/230-2.java b/solutions/230. Kth Smallest Element in a BST/230-2.java new file mode 100644 index 00000000000..db0a158a383 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230-2.java @@ -0,0 +1,21 @@ +class Solution { + public int kthSmallest(TreeNode root, int k) { + traverse(root, k); + return ans; + } + + private int ans = -1; + private int rank = 0; + + private void traverse(TreeNode root, int k) { + if (root == null) + return; + + traverse(root.left, k); + if (++rank == k) { + ans = root.val; + return; + } + traverse(root.right, k); + } +} diff --git a/solutions/230. Kth Smallest Element in a BST/230-2.py b/solutions/230. Kth Smallest Element in a BST/230-2.py new file mode 100644 index 00000000000..877fceb8130 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230-2.py @@ -0,0 +1,20 @@ +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + rank = 0 + ans = 0 + + def traverse(root: Optional[TreeNode]) -> None: + nonlocal rank + nonlocal ans + if not root: + return + + traverse(root.left) + rank += 1 + if rank == k: + ans = root.val + return + traverse(root.right) + + traverse(root) + return ans diff --git a/solutions/230. Kth Smallest Element in a BST/230-3.cpp b/solutions/230. Kth Smallest Element in a BST/230-3.cpp new file mode 100644 index 00000000000..3bc598bb5e4 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230-3.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int kthSmallest(TreeNode* root, int k) { + stack stack; + + while (root) { + stack.push(root); + root = root->left; + } + + for (int i = 0; i < k - 1; ++i) { + root = stack.top(), stack.pop(); + root = root->right; + while (root) { + stack.push(root); + root = root->left; + } + } + + return stack.top()->val; + } +}; diff --git a/solutions/230. Kth Smallest Element in a BST/230-3.java b/solutions/230. Kth Smallest Element in a BST/230-3.java new file mode 100644 index 00000000000..da7b2231b01 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230-3.java @@ -0,0 +1,21 @@ +class Solution { + public int kthSmallest(TreeNode root, int k) { + Deque stack = new ArrayDeque<>(); + + while (root != null) { + stack.push(root); + root = root.left; + } + + for (int i = 0; i < k - 1; ++i) { + root = stack.pop(); + root = root.right; + while (root != null) { + stack.push(root); + root = root.left; + } + } + + return stack.peek().val; + } +} diff --git a/solutions/230. Kth Smallest Element in a BST/230-3.py b/solutions/230. Kth Smallest Element in a BST/230-3.py new file mode 100644 index 00000000000..63197452dc4 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230-3.py @@ -0,0 +1,16 @@ +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + stack = [] + + while root: + stack.append(root) + root = root.left + + for _ in range(k - 1): + root = stack.pop() + root = root.right + while root: + stack.append(root) + root = root.left + + return stack[-1].val diff --git a/solutions/230. Kth Smallest Element in a BST/230.cpp b/solutions/230. Kth Smallest Element in a BST/230.cpp new file mode 100644 index 00000000000..b0f9fc0efb7 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int kthSmallest(TreeNode* root, int k) { + const int leftCount = countNodes(root->left); + + if (leftCount == k - 1) + return root->val; + if (leftCount >= k) + return kthSmallest(root->left, k); + return kthSmallest(root->right, k - 1 - leftCount); // leftCount < k + } + + private: + int countNodes(TreeNode* root) { + if (root == nullptr) + return 0; + return 1 + countNodes(root->left) + countNodes(root->right); + } +}; diff --git a/solutions/230. Kth Smallest Element in a BST/230.java b/solutions/230. Kth Smallest Element in a BST/230.java new file mode 100644 index 00000000000..6850c39f802 --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230.java @@ -0,0 +1,17 @@ +class Solution { + public int kthSmallest(TreeNode root, int k) { + final int leftCount = countNodes(root.left); + + if (leftCount == k - 1) + return root.val; + if (leftCount >= k) + return kthSmallest(root.left, k); + return kthSmallest(root.right, k - 1 - leftCount); // leftCount < k + } + + private int countNodes(TreeNode root) { + if (root == null) + return 0; + return 1 + countNodes(root.left) + countNodes(root.right); + } +} diff --git a/solutions/230. Kth Smallest Element in a BST/230.py b/solutions/230. Kth Smallest Element in a BST/230.py new file mode 100644 index 00000000000..3dd11381def --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST/230.py @@ -0,0 +1,14 @@ +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + def countNodes(root: Optional[TreeNode]) -> int: + if not root: + return 0 + return 1 + countNodes(root.left) + countNodes(root.right) + + leftCount = countNodes(root.left) + + if leftCount == k - 1: + return root.val + if leftCount >= k: + return self.kthSmallest(root.left, k) + return self.kthSmallest(root.right, k - 1 - leftCount) # leftCount < k diff --git a/solutions/2300. Successful Pairs of Spells and Potions/2300.cpp b/solutions/2300. Successful Pairs of Spells and Potions/2300.cpp new file mode 100644 index 00000000000..218023fcdbd --- /dev/null +++ b/solutions/2300. Successful Pairs of Spells and Potions/2300.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector successfulPairs(vector& spells, vector& potions, + long long success) { + vector ans; + ranges::sort(potions); + + for (const int spell : spells) + ans.push_back(potions.size() - + firstIndexSuccess(spell, potions, success)); + + return ans; + } + + private: + // Returns the first index i s.t. spell * potions[i] >= success. + int firstIndexSuccess(int spell, const vector& potions, long success) { + int l = 0; + int r = potions.size(); + while (l < r) { + const int m = (l + r) / 2; + if (static_cast(spell) * potions[m] >= success) + r = m; + else + l = m + 1; + } + return l; + } +}; diff --git a/solutions/2300. Successful Pairs of Spells and Potions/2300.java b/solutions/2300. Successful Pairs of Spells and Potions/2300.java new file mode 100644 index 00000000000..2d4e912cdb2 --- /dev/null +++ b/solutions/2300. Successful Pairs of Spells and Potions/2300.java @@ -0,0 +1,25 @@ +class Solution { + public int[] successfulPairs(int[] spells, int[] potions, long success) { + int[] ans = new int[spells.length]; + Arrays.sort(potions); + + for (int i = 0; i < spells.length; ++i) + ans[i] = potions.length - firstIndexSuccess(spells[i], potions, success); + + return ans; + } + + // Returns the first index i s.t. spell * potions[i] >= success. + private int firstIndexSuccess(int spell, int[] potions, long success) { + int l = 0; + int r = potions.length; + while (l < r) { + final int m = (l + r) / 2; + if ((long) spell * potions[m] >= success) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/2300. Successful Pairs of Spells and Potions/2300.py b/solutions/2300. Successful Pairs of Spells and Potions/2300.py new file mode 100644 index 00000000000..26a162e4b7e --- /dev/null +++ b/solutions/2300. Successful Pairs of Spells and Potions/2300.py @@ -0,0 +1,17 @@ +class Solution: + def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: + potions.sort() + + def firstIndexSuccess(spell: int): + """Returns the first index i s.t. spell * potions[i] >= success.""" + l = 0 + r = len(potions) + while l < r: + m = (l + r) // 2 + if spell * potions[m] >= success: + r = m + else: + l = m + 1 + return l + + return [len(potions) - firstIndexSuccess(spell) for spell in spells] diff --git a/solutions/2301. Match Substring After Replacement/2301.cpp b/solutions/2301. Match Substring After Replacement/2301.cpp new file mode 100644 index 00000000000..6c38be80332 --- /dev/null +++ b/solutions/2301. Match Substring After Replacement/2301.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + bool matchReplacement(string s, string sub, vector>& mappings) { + vector> isMapped(128, vector(128)); + + for (const vector& m : mappings) { + const char old = m[0]; + const char _new = m[1]; + isMapped[old][_new] = true; + } + + for (int i = 0; i < s.length(); ++i) + if (canTransform(s, i, sub, isMapped)) + return true; + + return false; + } + + private: + bool canTransform(const string& s, int start, const string& sub, + const vector>& isMapped) { + if (start + sub.length() > s.length()) + return false; + + for (int i = 0; i < sub.length(); ++i) { + const char a = sub[i]; + const char b = s[start + i]; + if (a != b && !isMapped[a][b]) + return false; + } + + return true; + } +}; diff --git a/solutions/2301. Match Substring After Replacement/2301.java b/solutions/2301. Match Substring After Replacement/2301.java new file mode 100644 index 00000000000..0e9853fbb35 --- /dev/null +++ b/solutions/2301. Match Substring After Replacement/2301.java @@ -0,0 +1,31 @@ +class Solution { + public boolean matchReplacement(String s, String sub, char[][] mappings) { + boolean[][] isMapped = new boolean[128][128]; + + for (char[] m : mappings) { + final char old = m[0]; + final char _new = m[1]; + isMapped[old][_new] = true; + } + + for (int i = 0; i < s.length(); ++i) + if (canTransform(s, i, sub, isMapped)) + return true; + + return false; + } + + private boolean canTransform(final String s, int start, final String sub, boolean[][] isMapped) { + if (start + sub.length() > s.length()) + return false; + + for (int i = 0; i < sub.length(); ++i) { + final char a = sub.charAt(i); + final char b = s.charAt(start + i); + if (a != b && !isMapped[a][b]) + return false; + } + + return true; + } +} diff --git a/solutions/2301. Match Substring After Replacement/2301.py b/solutions/2301. Match Substring After Replacement/2301.py new file mode 100644 index 00000000000..873005f8288 --- /dev/null +++ b/solutions/2301. Match Substring After Replacement/2301.py @@ -0,0 +1,24 @@ +class Solution: + def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: + isMapped = [[False] * 128 for _ in range(128)] + + for old, new in mappings: + isMapped[ord(old)][ord(new)] = True + + for i in range(len(s)): + if self._canTransform(s, i, sub, isMapped): + return True + + return False + + def _canTransform(self, s: str, start: int, sub: str, isMapped: List[List[bool]]) -> bool: + if start + len(sub) > len(s): + return False + + for i in range(len(sub)): + a = sub[i] + b = s[start + i] + if a != b and not isMapped[ord(a)][ord(b)]: + return False + + return True diff --git a/solutions/2302. Count Subarrays With Score Less Than K/2302.cpp b/solutions/2302. Count Subarrays With Score Less Than K/2302.cpp new file mode 100644 index 00000000000..25782868aac --- /dev/null +++ b/solutions/2302. Count Subarrays With Score Less Than K/2302.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + long long countSubarrays(vector& nums, long long k) { + long ans = 0; + long sum = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + sum += nums[r]; + while (sum * (r - l + 1) >= k) + sum -= nums[l++]; + ans += r - l + 1; + } + + return ans; + } +}; diff --git a/solutions/2302. Count Subarrays With Score Less Than K/2302.java b/solutions/2302. Count Subarrays With Score Less Than K/2302.java new file mode 100644 index 00000000000..e2d5bf17888 --- /dev/null +++ b/solutions/2302. Count Subarrays With Score Less Than K/2302.java @@ -0,0 +1,15 @@ +class Solution { + public long countSubarrays(int[] nums, long k) { + long ans = 0; + long sum = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + sum += nums[r]; + while (sum * (r - l + 1) >= k) + sum -= nums[l++]; + ans += r - l + 1; + } + + return ans; + } +} diff --git a/solutions/2302. Count Subarrays With Score Less Than K/2302.py b/solutions/2302. Count Subarrays With Score Less Than K/2302.py new file mode 100644 index 00000000000..a687853fd7a --- /dev/null +++ b/solutions/2302. Count Subarrays With Score Less Than K/2302.py @@ -0,0 +1,14 @@ +class Solution: + def countSubarrays(self, nums: List[int], k: int) -> int: + ans = 0 + summ = 0 + + l = 0 + for r, num in enumerate(nums): + summ += num + while summ * (r - l + 1) >= k: + summ -= nums[l] + l += 1 + ans += r - l + 1 + + return ans diff --git a/solutions/2303. Calculate Amount Paid in Taxes/2303.cpp b/solutions/2303. Calculate Amount Paid in Taxes/2303.cpp new file mode 100644 index 00000000000..a5c7b4f3cbe --- /dev/null +++ b/solutions/2303. Calculate Amount Paid in Taxes/2303.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + double calculateTax(vector>& brackets, int income) { + double ans = 0; + int prev = 0; + + for (const vector& b : brackets) { + const int upper = b[0]; + const int percent = b[1]; + if (income < upper) + return ans + (income - prev) * percent / 100.0; + ans += (upper - prev) * percent / 100.0; + prev = upper; + } + + return ans; + } +}; diff --git a/solutions/2303. Calculate Amount Paid in Taxes/2303.java b/solutions/2303. Calculate Amount Paid in Taxes/2303.java new file mode 100644 index 00000000000..92bb8b286ea --- /dev/null +++ b/solutions/2303. Calculate Amount Paid in Taxes/2303.java @@ -0,0 +1,17 @@ +class Solution { + public double calculateTax(int[][] brackets, int income) { + double ans = 0; + int prev = 0; + + for (int[] b : brackets) { + final int upper = b[0]; + final int percent = b[1]; + if (income < upper) + return ans + (income - prev) * percent / 100.0; + ans += (upper - prev) * percent / 100.0; + prev = upper; + } + + return ans; + } +} diff --git a/solutions/2303. Calculate Amount Paid in Taxes/2303.py b/solutions/2303. Calculate Amount Paid in Taxes/2303.py new file mode 100644 index 00000000000..13c94a3185c --- /dev/null +++ b/solutions/2303. Calculate Amount Paid in Taxes/2303.py @@ -0,0 +1,12 @@ +class Solution: + def calculateTax(self, brackets: List[List[int]], income: int) -> float: + ans = 0 + prev = 0 + + for upper, percent in brackets: + if income < upper: + return ans + (income - prev) * percent / 100.0 + ans += (upper - prev) * percent / 100.0 + prev = upper + + return ans diff --git a/solutions/2304. Minimum Path Cost in a Grid/2304.cpp b/solutions/2304. Minimum Path Cost in a Grid/2304.cpp new file mode 100644 index 00000000000..92fb1c55421 --- /dev/null +++ b/solutions/2304. Minimum Path Cost in a Grid/2304.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minPathCost(vector>& grid, vector>& moveCost) { + const int m = grid.size(); + const int n = grid[0].size(); + // dp[i][j] := the minimum cost to reach grid[i][j] + vector> dp(m, vector(n, INT_MAX)); + dp[0] = grid[0]; + + for (int i = 1; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int k = 0; k < n; ++k) + dp[i][j] = min(dp[i][j], dp[i - 1][k] + moveCost[grid[i - 1][k]][j] + + grid[i][j]); + + return ranges::min(dp.back()); + } +}; diff --git a/solutions/2304. Minimum Path Cost in a Grid/2304.java b/solutions/2304. Minimum Path Cost in a Grid/2304.java new file mode 100644 index 00000000000..4a0bc63727d --- /dev/null +++ b/solutions/2304. Minimum Path Cost in a Grid/2304.java @@ -0,0 +1,17 @@ +class Solution { + public int minPathCost(int[][] grid, int[][] moveCost) { + final int m = grid.length; + final int n = grid[0].length; + // dp[i][j] := the minimum cost to reach grid[i][j] + int[][] dp = new int[m][n]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + dp[0] = grid[0]; + + for (int i = 1; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int k = 0; k < n; ++k) + dp[i][j] = Math.min(dp[i][j], dp[i - 1][k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); + + return Arrays.stream(dp[m - 1]).min().getAsInt(); + } +} diff --git a/solutions/2304. Minimum Path Cost in a Grid/2304.py b/solutions/2304. Minimum Path Cost in a Grid/2304.py new file mode 100644 index 00000000000..e6664d012e6 --- /dev/null +++ b/solutions/2304. Minimum Path Cost in a Grid/2304.py @@ -0,0 +1,15 @@ +class Solution: + def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + # dp[i][j] := the minimum cost to reach grid[i][j] + dp = [[math.inf] * n for _ in range(m)] + dp[0] = grid[0] + + for i in range(1, m): + for j in range(n): + for k in range(n): + dp[i][j] = min(dp[i][j], dp[i - 1][k] + + moveCost[grid[i - 1][k]][j] + grid[i][j]) + + return min(dp[-1]) diff --git a/solutions/2305. Fair Distribution of Cookies/2305.cpp b/solutions/2305. Fair Distribution of Cookies/2305.cpp new file mode 100644 index 00000000000..fa5753b1a1d --- /dev/null +++ b/solutions/2305. Fair Distribution of Cookies/2305.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int distributeCookies(vector& cookies, int k) { + int ans = INT_MAX; + dfs(cookies, 0, k, vector(k), ans); + return ans; + } + + private: + void dfs(const vector& cookies, int s, int k, vector&& children, + int& ans) { + if (s == cookies.size()) { + ans = min(ans, ranges::max(children)); + return; + } + + for (int i = 0; i < k; ++i) { + children[i] += cookies[s]; + dfs(cookies, s + 1, k, move(children), ans); + children[i] -= cookies[s]; + } + } +}; diff --git a/solutions/2305. Fair Distribution of Cookies/2305.java b/solutions/2305. Fair Distribution of Cookies/2305.java new file mode 100644 index 00000000000..80fd82c5698 --- /dev/null +++ b/solutions/2305. Fair Distribution of Cookies/2305.java @@ -0,0 +1,21 @@ +class Solution { + public int distributeCookies(int[] cookies, int k) { + dfs(cookies, 0, k, new int[k]); + return ans; + } + + private int ans = Integer.MAX_VALUE; + + private void dfs(int[] cookies, int s, int k, int[] children) { + if (s == cookies.length) { + ans = Math.min(ans, Arrays.stream(children).max().getAsInt()); + return; + } + + for (int i = 0; i < k; ++i) { + children[i] += cookies[s]; + dfs(cookies, s + 1, k, children); + children[i] -= cookies[s]; + } + } +} diff --git a/solutions/2305. Fair Distribution of Cookies/2305.py b/solutions/2305. Fair Distribution of Cookies/2305.py new file mode 100644 index 00000000000..d0effb864f8 --- /dev/null +++ b/solutions/2305. Fair Distribution of Cookies/2305.py @@ -0,0 +1,17 @@ +class Solution: + def distributeCookies(self, cookies: List[int], k: int) -> int: + ans = math.inf + + def dfs(s: int, children: List[int]) -> None: + nonlocal ans + if s == len(cookies): + ans = min(ans, max(children)) + return + + for i in range(k): + children[i] += cookies[s] + dfs(s + 1, children) + children[i] -= cookies[s] + + dfs(0, [0] * k) + return ans diff --git a/solutions/2306. Naming a Company/2306.cpp b/solutions/2306. Naming a Company/2306.cpp new file mode 100644 index 00000000000..cefbd437a60 --- /dev/null +++ b/solutions/2306. Naming a Company/2306.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long distinctNames(vector& ideas) { + long ans = 0; + // suffixes[i] := the set of strings omitting the first letter, where the + // first letter is ('a' + i) + vector> suffixes(26); + + for (const string& idea : ideas) + suffixes[idea[0] - 'a'].insert(idea.substr(1)); + + for (int i = 0; i < 25; ++i) + for (int j = i + 1; j < 26; ++j) { + int count = 0; + for (const string& suffix : suffixes[i]) + if (suffixes[j].contains(suffix)) + ++count; + ans += 2 * (suffixes[i].size() - count) * (suffixes[j].size() - count); + } + + return ans; + } +}; diff --git a/solutions/2306. Naming a Company/2306.java b/solutions/2306. Naming a Company/2306.java new file mode 100644 index 00000000000..19042418413 --- /dev/null +++ b/solutions/2306. Naming a Company/2306.java @@ -0,0 +1,25 @@ +class Solution { + public long distinctNames(String[] ideas) { + long ans = 0; + // suffixes[i] := the set of strings omitting the first letter, where the first letter is + // ('a' + i) + Set[] suffixes = new Set[26]; + + for (int i = 0; i < 26; ++i) + suffixes[i] = new HashSet<>(); + + for (final String idea : ideas) + suffixes[idea.charAt(0) - 'a'].add(idea.substring(1)); + + for (int i = 0; i < 25; ++i) + for (int j = i + 1; j < 26; ++j) { + int count = 0; + for (final String suffix : suffixes[i]) + if (suffixes[j].contains(suffix)) + ++count; + ans += 2 * (suffixes[i].size() - count) * (suffixes[j].size() - count); + } + + return ans; + } +} diff --git a/solutions/2306. Naming a Company/2306.py b/solutions/2306. Naming a Company/2306.py new file mode 100644 index 00000000000..dccca475e47 --- /dev/null +++ b/solutions/2306. Naming a Company/2306.py @@ -0,0 +1,16 @@ +class Solution: + def distinctNames(self, ideas: List[str]) -> int: + ans = 0 + # suffixes[i] := the set of strings omitting the first letter, where the + # first letter is ('a' + i) + suffixes = [set() for _ in range(26)] + + for idea in ideas: + suffixes[ord(idea[0]) - ord('a')].add(idea[1:]) + + for i in range(25): + for j in range(i + 1, 26): + count = len(suffixes[i] & suffixes[j]) + ans += 2 * (len(suffixes[i]) - count) * (len(suffixes[j]) - count) + + return ans diff --git a/solutions/2307. Check for Contradictions in Equations/2307.cpp b/solutions/2307. Check for Contradictions in Equations/2307.cpp new file mode 100644 index 00000000000..85d6f35f254 --- /dev/null +++ b/solutions/2307. Check for Contradictions in Equations/2307.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + bool checkContradictions(vector>& equations, + vector& values) { + // Convert `string` to `int` for a better perfermance. + unordered_map strToInt; + + for (const vector& equation : equations) { + const string& u = equation[0]; + const string& v = equation[1]; + if (!strToInt.contains(u)) + strToInt[u] = strToInt.size(); + if (!strToInt.contains(v)) + strToInt[v] = strToInt.size(); + } + + vector>> graph(strToInt.size()); + vector seen(graph.size()); + + for (int i = 0; i < equations.size(); ++i) { + const int u = strToInt.at(equations[i][0]); + const int v = strToInt.at(equations[i][1]); + graph[u].emplace_back(v, values[i]); + graph[v].emplace_back(u, 1 / values[i]); + } + + for (int i = 0; i < graph.size(); ++i) + if (!seen[i] && dfs(graph, i, seen, 1.0)) + return true; + + return false; + } + + private: + bool dfs(const vector>>& graph, int u, + vector& seen, double val) { + if (seen[u]) + return abs(val / seen[u] - 1) > 1e-5; + + seen[u] = val; + for (const auto& [v, w] : graph[u]) + if (dfs(graph, v, seen, val / w)) + return true; + + return false; + } +}; diff --git a/solutions/2307. Check for Contradictions in Equations/2307.java b/solutions/2307. Check for Contradictions in Equations/2307.java new file mode 100644 index 00000000000..d6f42bc759a --- /dev/null +++ b/solutions/2307. Check for Contradictions in Equations/2307.java @@ -0,0 +1,45 @@ +class Solution { + public boolean checkContradictions(List> equations, double[] values) { + // Convert `string` to `int` for a better perfermance. + Map strToInt = new HashMap<>(); + + for (List equation : equations) { + strToInt.putIfAbsent(equation.get(0), strToInt.size()); + strToInt.putIfAbsent(equation.get(1), strToInt.size()); + } + + List>[] graph = new List[strToInt.size()]; + double[] seen = new double[graph.length]; + + for (int i = 0; i < graph.length; ++i) + graph[i] = new ArrayList<>(); + + for (int i = 0; i < equations.size(); ++i) { + final int u = strToInt.get(equations.get(i).get(0)); + final int v = strToInt.get(equations.get(i).get(1)); + graph[u].add(new Pair<>(v, values[i])); + graph[v].add(new Pair<>(u, 1 / values[i])); + } + + for (int i = 0; i < graph.length; ++i) + if (seen[i] != 0.0 && dfs(graph, i, seen, 1.0)) + return true; + + return false; + } + + private boolean dfs(List>[] graph, int u, double[] seen, double val) { + if (seen[u] != 0.0) + return Math.abs(val / seen[u] - 1) > 1e-5; + + seen[u] = val; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final double w = pair.getValue(); + if (dfs(graph, v, seen, val / w)) + return true; + } + + return false; + } +} diff --git a/solutions/2307. Check for Contradictions in Equations/2307.py b/solutions/2307. Check for Contradictions in Equations/2307.py new file mode 100644 index 00000000000..b606fd943fc --- /dev/null +++ b/solutions/2307. Check for Contradictions in Equations/2307.py @@ -0,0 +1,30 @@ +class Solution: + def checkContradictions(self, equations: List[List[str]], values: List[float]) -> bool: + # Convert `string` to `int` for a better perfermance. + strToInt = {} + + for u, v in equations: + strToInt.setdefault(u, len(strToInt)) + strToInt.setdefault(v, len(strToInt)) + + graph = [[] for _ in range(len(strToInt))] + seen = [0.0] * len(graph) + + for i, ((A, B), value) in enumerate(zip(equations, values)): + u = strToInt[A] + v = strToInt[B] + graph[u].append((v, value)) + graph[v].append((u, 1 / value)) + + def dfs(u: int, val: float) -> bool: + if seen[u]: + return abs(val / seen[u] - 1) > 1e-5 + + seen[u] = val + return any(dfs(v, val / w) for v, w in graph[u]) + + for i in range(len(graph)): + if not seen[i] and dfs(i, 1.0): + return True + + return False diff --git a/solutions/2308. Arrange Table by Gender/2308.sql b/solutions/2308. Arrange Table by Gender/2308.sql new file mode 100644 index 00000000000..d9844625834 --- /dev/null +++ b/solutions/2308. Arrange Table by Gender/2308.sql @@ -0,0 +1,9 @@ +SELECT + user_id, + gender +FROM Genders +ORDER BY RANK() OVER( + PARTITION by gender + ORDER BY user_id + ), + LENGTH(gender) DESC; diff --git a/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.cpp b/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.cpp new file mode 100644 index 00000000000..8292c777256 --- /dev/null +++ b/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + string greatestLetter(string s) { + vector seen(128); + + for (const char c : s) + seen[c] = true; + + for (int i = 25; i >= 0; --i) + if (seen['a' + i] && seen['A' + i]) + return string(1, 'A' + i); + + return ""; + } +}; diff --git a/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.java b/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.java new file mode 100644 index 00000000000..8a179b79327 --- /dev/null +++ b/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.java @@ -0,0 +1,14 @@ +class Solution { + public String greatestLetter(String s) { + boolean[] seen = new boolean[128]; + + for (final char c : s.toCharArray()) + seen[c] = true; + + for (int i = 25; i >= 0; --i) + if (seen['a' + i] && seen['A' + i]) + return String.valueOf((char) ('A' + i)); + + return ""; + } +} diff --git a/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.py b/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.py new file mode 100644 index 00000000000..de949ff9d1d --- /dev/null +++ b/solutions/2309. Greatest English Letter in Upper and Lower Case/2309.py @@ -0,0 +1,10 @@ +class Solution: + def greatestLetter(self, s: str) -> str: + seen = set(s) + + for i in range(25, -1, -1): + if chr(ord('a') + i) in seen and \ + chr(ord('A') + i) in seen: + return chr(ord('A') + i) + + return '' diff --git a/solutions/231. Power of Two/231.cpp b/solutions/231. Power of Two/231.cpp new file mode 100644 index 00000000000..be097329e16 --- /dev/null +++ b/solutions/231. Power of Two/231.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool isPowerOfTwo(int n) { + return n >= 0 && __builtin_popcount(n) == 1; + } +}; diff --git a/solutions/231. Power of Two/231.java b/solutions/231. Power of Two/231.java new file mode 100644 index 00000000000..d3938f26b09 --- /dev/null +++ b/solutions/231. Power of Two/231.java @@ -0,0 +1,5 @@ +class Solution { + public boolean isPowerOfTwo(int n) { + return n >= 0 && Integer.bitCount(n) == 1; + } +} diff --git a/solutions/231. Power of Two/231.py b/solutions/231. Power of Two/231.py new file mode 100644 index 00000000000..db8d1fa392b --- /dev/null +++ b/solutions/231. Power of Two/231.py @@ -0,0 +1,3 @@ +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n >= 0 and n.bit_count() == 1 diff --git a/solutions/2310. Sum of Numbers With Units Digit K/2310.cpp b/solutions/2310. Sum of Numbers With Units Digit K/2310.cpp new file mode 100644 index 00000000000..6502a128009 --- /dev/null +++ b/solutions/2310. Sum of Numbers With Units Digit K/2310.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minimumNumbers(int num, int k) { + if (num == 0) + return 0; + + // Assume the size of the set is n, and the numbers in the set are X1, X2, + // ..., Xn. Since the units digit of each number is k, X1 + X2 + ... + Xn = + // N * k + 10 * (x1 + x2 + ... + xn) = num. Therefore, the goal is to find + // the n s.t. n * k % 10 = num % 10 + for (int i = 1; i <= 10 && i * k <= num; ++i) + if (i * k % 10 == num % 10) + return i; + + return -1; + } +}; diff --git a/solutions/2310. Sum of Numbers With Units Digit K/2310.java b/solutions/2310. Sum of Numbers With Units Digit K/2310.java new file mode 100644 index 00000000000..658c9d58983 --- /dev/null +++ b/solutions/2310. Sum of Numbers With Units Digit K/2310.java @@ -0,0 +1,16 @@ +class Solution { + public int minimumNumbers(int num, int k) { + if (num == 0) + return 0; + + // Assume the size of the set is n, and the numbers in the set are X1, X2, + // ..., Xn. Since the units digit of each number is k, X1 + X2 + ... + Xn = + // N * k + 10 * (x1 + x2 + ... + xn) = num. Therefore, the goal is to find + // the n s.t. n * k % 10 = num % 10 + for (int i = 1; i <= 10 && i * k <= num; ++i) + if (i * k % 10 == num % 10) + return i; + + return -1; + } +} diff --git a/solutions/2310. Sum of Numbers With Units Digit K/2310.py b/solutions/2310. Sum of Numbers With Units Digit K/2310.py new file mode 100644 index 00000000000..1af4b0f87c8 --- /dev/null +++ b/solutions/2310. Sum of Numbers With Units Digit K/2310.py @@ -0,0 +1,16 @@ +class Solution: + def minimumNumbers(self, num: int, k: int) -> int: + if num == 0: + return 0 + + # Assume the size of the set is n, and the numbers in the set are X1, X2, + # ..., Xn. Since the units digit of each number is k, X1 + X2 + ... + Xn = + # N * k + 10 * (x1 + x2 + ... + xn) = num. Therefore, the goal is to find + # the n s.t. n * k % 10 = num % 10 + for i in range(1, 11): + if i * k > num + 1: + break + if i * k % 10 == num % 10: + return i + + return -1 diff --git a/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.cpp b/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.cpp new file mode 100644 index 00000000000..e9338f73673 --- /dev/null +++ b/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int longestSubsequence(string s, int k) { + int oneCount = 0; + int num = 0; + int pow = 1; + + // Take as many 1s as possible from the right. + for (int i = s.length() - 1; i >= 0 && num + pow <= k; --i) { + if (s[i] == '1') { + ++oneCount; + num += pow; + } + pow *= 2; + } + + return ranges::count(s, '0') + oneCount; + } +}; diff --git a/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.java b/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.java new file mode 100644 index 00000000000..9681cdafa63 --- /dev/null +++ b/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.java @@ -0,0 +1,18 @@ +class Solution { + public int longestSubsequence(String s, int k) { + int oneCount = 0; + int num = 0; + int pow = 1; + + // Take as many 1s as possible from the right. + for (int i = s.length() - 1; i >= 0 && num + pow <= k; --i) { + if (s.charAt(i) == '1') { + ++oneCount; + num += pow; + } + pow *= 2; + } + + return (int) s.chars().filter(c -> c == '0').count() + oneCount; + } +} diff --git a/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.py b/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.py new file mode 100644 index 00000000000..a55d04b6ce3 --- /dev/null +++ b/solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.py @@ -0,0 +1,16 @@ +class Solution: + def longestSubsequence(self, s: str, k: int) -> int: + oneCount = 0 + num = 0 + pow = 1 + + # Take as many 1s as possible from the right. + for i in reversed(range(len(s))): + if num + pow > k: + break + if s[i] == '1': + oneCount += 1 + num += pow + pow *= 2 + + return s.count('0') + oneCount diff --git a/solutions/2312. Selling Pieces of Wood/2312.cpp b/solutions/2312. Selling Pieces of Wood/2312.cpp new file mode 100644 index 00000000000..23cc7602aa0 --- /dev/null +++ b/solutions/2312. Selling Pieces of Wood/2312.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long sellingWood(int m, int n, vector>& prices) { + // dp[i][j] := the maximum money of cutting i x j piece of wood + vector> dp(m + 1, vector(n + 1)); + + for (const vector& p : prices) { + const int h = p[0]; + const int w = p[1]; + const int price = p[2]; + dp[h][w] = price; + } + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) { + for (int h = 1; h <= i / 2; ++h) + dp[i][j] = max(dp[i][j], dp[h][j] + dp[i - h][j]); + for (int w = 1; w <= j / 2; ++w) + dp[i][j] = max(dp[i][j], dp[i][w] + dp[i][j - w]); + } + + return dp[m][n]; + } +}; diff --git a/solutions/2312. Selling Pieces of Wood/2312.java b/solutions/2312. Selling Pieces of Wood/2312.java new file mode 100644 index 00000000000..7d8a43a15b5 --- /dev/null +++ b/solutions/2312. Selling Pieces of Wood/2312.java @@ -0,0 +1,23 @@ +class Solution { + public long sellingWood(int m, int n, int[][] prices) { + // dp[i][j] := the maximum money of cutting i x j piece of wood + long[][] dp = new long[m + 1][n + 1]; + + for (int[] p : prices) { + final int h = p[0]; + final int w = p[1]; + final int price = p[2]; + dp[h][w] = price; + } + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) { + for (int h = 1; h <= i / 2; ++h) + dp[i][j] = Math.max(dp[i][j], dp[h][j] + dp[i - h][j]); + for (int w = 1; w <= j / 2; ++w) + dp[i][j] = Math.max(dp[i][j], dp[i][w] + dp[i][j - w]); + } + + return dp[m][n]; + } +} diff --git a/solutions/2312. Selling Pieces of Wood/2312.py b/solutions/2312. Selling Pieces of Wood/2312.py new file mode 100644 index 00000000000..54d4aa7e99e --- /dev/null +++ b/solutions/2312. Selling Pieces of Wood/2312.py @@ -0,0 +1,16 @@ +class Solution: + def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: + # dp[i][j] := the maximum money of cutting i x j piece of wood + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for h, w, price in prices: + dp[h][w] = price + + for i in range(1, m + 1): + for j in range(1, n + 1): + for h in range(1, i // 2 + 1): + dp[i][j] = max(dp[i][j], dp[h][j] + dp[i - h][j]) + for w in range(1, j // 2 + 1): + dp[i][j] = max(dp[i][j], dp[i][w] + dp[i][j - w]) + + return dp[m][n] diff --git a/solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.cpp b/solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.cpp new file mode 100644 index 00000000000..d4cc6577eea --- /dev/null +++ b/solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int minimumFlips(TreeNode* root, bool result) { + return dp(root, result); + } + + private: + struct PairHash { + template + std::size_t operator()(const std::pair& p) const { + return std::hash{}(p.first) ^ std::hash{}(p.second); + } + }; + + unordered_map, int, PairHash> mem; + + // Returns the minimum flips to make the subtree become the target. + int dp(TreeNode* root, bool target) { + const pair key{root, target}; + if (const auto it = mem.find(key); it != mem.cend()) + return it->second; + if (root->val == 0 || root->val == 1) // the leaf + return root->val == target ? 0 : 1; + if (root->val == 5) // NOT + return dp(root->left == nullptr ? root->right : root->left, !target); + + vector> nextTargets; + if (root->val == 2) // OR + nextTargets = target ? vector>{{0, 1}, {1, 0}, {1, 1}} + : vector>{{0, 0}}; + else if (root->val == 3) // AND + nextTargets = target ? vector>{{1, 1}} + : vector>{{0, 0}, {0, 1}, {1, 0}}; + else // root.val == 4 (XOR) + nextTargets = target ? vector>{{0, 1}, {1, 0}} + : vector>{{0, 0}, {1, 1}}; + + int ans = INT_MAX; + for (const auto& [leftTarget, rightTarget] : nextTargets) + ans = min(ans, dp(root->left, leftTarget) + dp(root->right, rightTarget)); + return mem[key] = ans; + } +}; diff --git a/solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.py b/solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.py new file mode 100644 index 00000000000..cfa287febd0 --- /dev/null +++ b/solutions/2313. Minimum Flips in Binary Tree to Get Result/2313.py @@ -0,0 +1,19 @@ +class Solution: + def minimumFlips(self, root: Optional[TreeNode], result: bool) -> int: + @functools.lru_cache(None) + def dp(root: Optional[TreeNode], target: bool) -> int: + """Returns the minimum flips to make the subtree root become target.""" + if root.val in (0, 1): # the leaf + return 0 if root.val == target else 1 + if root.val == 5: # NOT + return dp(root.left or root.right, not target) + if root.val == 2: # OR + nextTargets = [(0, 1), (1, 0), (1, 1)] if target else [[0, 0]] + elif root.val == 3: # AND + nextTargets = [(1, 1)] if target else [(0, 0), (0, 1), (1, 0)] + else: # root.val == 4 XOR + nextTargets = [(0, 1), (1, 0)] if target else [(0, 0), (1, 1)] + return min(dp(root.left, leftTarget) + dp(root.right, rightTarget) + for leftTarget, rightTarget in nextTargets) + + return dp(root, result) diff --git a/solutions/2314. The First Day of the Maximum Recorded Degree in Each City/2314.sql b/solutions/2314. The First Day of the Maximum Recorded Degree in Each City/2314.sql new file mode 100644 index 00000000000..e8753b50aee --- /dev/null +++ b/solutions/2314. The First Day of the Maximum Recorded Degree in Each City/2314.sql @@ -0,0 +1,13 @@ +WITH + RankedWeather AS ( + SELECT + *, + RANK() OVER( + PARTITION by city_id + ORDER BY degree DESC, day + ) AS `rank` + FROM Weather + ) +SELECT city_id, day, degree +FROM RankedWeather +WHERE `rank` = 1; diff --git a/solutions/2315. Count Asterisks/2315.cpp b/solutions/2315. Count Asterisks/2315.cpp new file mode 100644 index 00000000000..0cedad9c108 --- /dev/null +++ b/solutions/2315. Count Asterisks/2315.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int countAsterisks(string s) { + int ans = 0; + int bars = 0; + + for (const char c : s) { + if (c == '|') + ++bars; + else if (c == '*' && bars % 2 == 0) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2315. Count Asterisks/2315.java b/solutions/2315. Count Asterisks/2315.java new file mode 100644 index 00000000000..d2532e4b2bd --- /dev/null +++ b/solutions/2315. Count Asterisks/2315.java @@ -0,0 +1,15 @@ +class Solution { + public int countAsterisks(String s) { + int ans = 0; + int bars = 0; + + for (final char c : s.toCharArray()) { + if (c == '|') + ++bars; + else if (c == '*' && bars % 2 == 0) + ++ans; + } + + return ans; + } +} diff --git a/solutions/2315. Count Asterisks/2315.py b/solutions/2315. Count Asterisks/2315.py new file mode 100644 index 00000000000..c4993fdcc35 --- /dev/null +++ b/solutions/2315. Count Asterisks/2315.py @@ -0,0 +1,12 @@ +class Solution: + def countAsterisks(self, s: str) -> int: + ans = 0 + bars = 0 + + for c in s: + if c == '|': + bars += 1 + elif c == '*' and bars % 2 == 0: + ans += 1 + + return ans diff --git a/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.cpp b/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.cpp new file mode 100644 index 00000000000..0dab07cf4fc --- /dev/null +++ b/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + long long countPairs(int n, vector>& edges) { + long ans = 0; + vector> graph(n); + vector seen(n); + int unreached = n; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + for (int i = 0; i < n; ++i) { + const int reached = dfs(graph, i, seen); + unreached -= reached; + ans += static_cast(unreached) * reached; + } + return ans; + } + + private: + int dfs(const vector>& graph, int u, vector& seen) { + if (seen[u]) + return 0; + seen[u] = true; + return accumulate( + graph[u].begin(), graph[u].end(), 1, + [&](int subtotal, int v) { return subtotal + dfs(graph, v, seen); }); + } +}; diff --git a/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.java b/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.java new file mode 100644 index 00000000000..1d42391e26c --- /dev/null +++ b/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.java @@ -0,0 +1,36 @@ +class Solution { + public long countPairs(int n, int[][] edges) { + long ans = 0; + List[] graph = new List[n]; + boolean[] seen = new boolean[n]; + int unreached = n; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + for (int i = 0; i < n; ++i) { + final int reached = dfs(graph, i, seen); + unreached -= reached; + ans += (long) unreached * reached; + } + return ans; + } + + private int dfs(List[] graph, int u, boolean[] seen) { + if (seen[u]) + return 0; + + seen[u] = true; + int ans = 1; + for (final int v : graph[u]) + ans += dfs(graph, v, seen); + return ans; + } +} diff --git a/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.py b/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.py new file mode 100644 index 00000000000..aea02a4e95b --- /dev/null +++ b/solutions/2316. Count Unreachable Pairs of Nodes in an Undirected Graph/2316.py @@ -0,0 +1,27 @@ +class Solution: + def countPairs(self, n: int, edges: List[List[int]]) -> int: + ans = 0 + graph = [0] * n + seen = [0] * n + unreached = n + + for e in edges: + u = e[0] + v = e[1] + graph[u].append(v) + graph[v].append(u) + + for i in range(n): + reached = dfs(graph, i, seen) + unreached -= reached + ans += static_cast < long > (unreached) * reached + + return ans + + def dfs(self, graph: List[List[int]], u: int, seen: List[bool]) -> int: + if seen[u]: + return 0 + seen[u] = True + return accumulate( + begin(graph[u]), end(graph[u]), 1, + [ & ](subtotal, v) [return subtotal + dfs(graph, v, seen)]) diff --git a/solutions/2317. Maximum XOR After Operations/2317.cpp b/solutions/2317. Maximum XOR After Operations/2317.cpp new file mode 100644 index 00000000000..598d8d41b1e --- /dev/null +++ b/solutions/2317. Maximum XOR After Operations/2317.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maximumXOR(vector& nums) { + // 1. nums[i] & (nums[i] ^ x) enables you to turn 1-bit to 0-bit from + // nums[i] since x is arbitrary. + // 2. The i-th bit of the XOR of all the elements is 1 if the i-th bit is 1 + // for an odd number of elements. + // 3. Therefore, the question is equivalent to: if you can convert any digit + // from 1 to 0 for any number, what is the maximum for XOR(nums[i]). + // 4. The maximum we can get is of course to make every digit of the answer + // to be 1 if possible + // 5. Therefore, OR(nums[i]) is an approach. + return reduce(nums.begin(), nums.end(), 0, bit_or()); + } +}; diff --git a/solutions/2317. Maximum XOR After Operations/2317.java b/solutions/2317. Maximum XOR After Operations/2317.java new file mode 100644 index 00000000000..9ac73719e7b --- /dev/null +++ b/solutions/2317. Maximum XOR After Operations/2317.java @@ -0,0 +1,14 @@ +class Solution { + public int maximumXOR(int[] nums) { + // 1. nums[i] & (nums[i] ^ x) enables you to turn 1-bit to 0-bit from + // nums[i] since x is arbitrary. + // 2. The i-th bit of the XOR of all the elements is 1 if the i-th bit is 1 + // for an odd number of elements. + // 3. Therefore, the question is equivalent to: if you can convert any digit + // from 1 to 0 for any number, what is the maximum for XOR(nums[i]). + // 4. The maximum we can get is of course to make every digit of the answer + // to be 1 if possible + // 5. Therefore, OR(nums[i]) is an approach. + return Arrays.stream(nums).reduce(0, (a, b) -> a | b); + } +} diff --git a/solutions/2317. Maximum XOR After Operations/2317.py b/solutions/2317. Maximum XOR After Operations/2317.py new file mode 100644 index 00000000000..447a6175d7f --- /dev/null +++ b/solutions/2317. Maximum XOR After Operations/2317.py @@ -0,0 +1,12 @@ +class Solution: + def maximumXOR(self, nums: List[int]) -> int: + # 1. nums[i] & (nums[i] ^ x) enables you to turn 1-bit to 0-bit from + # nums[i] since x is arbitrary. + # 2. The i-th bit of the XOR of all the elements is 1 if the i-th bit is 1 + # for an odd number of elements. + # 3. Therefore, the question is equivalent to: if you can convert any digit + # from 1 to 0 for any number, what is the maximum for XOR(nums[i]). + # 4. The maximum we can get is of course to make every digit of the answer + # to be 1 if possible + # 5. Therefore, OR(nums[i]) is an approach. + return functools.reduce(operator.ior, nums) diff --git a/solutions/2318. Number of Distinct Roll Sequences/2318.cpp b/solutions/2318. Number of Distinct Roll Sequences/2318.cpp new file mode 100644 index 00000000000..8b680583bfa --- /dev/null +++ b/solutions/2318. Number of Distinct Roll Sequences/2318.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int distinctSequences(int n) { + vector>> mem(n + 1, + vector>(7, vector(7))); + return distinctSequences(n, 0, 0, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of distinct sequences for n dices with `prev` and + // `prevPrev`. + int distinctSequences(int n, int prev, int prevPrev, + vector>>& mem) { + if (n == 0) + return 1; + if (mem[n][prev][prevPrev] > 0) + return mem[n][prev][prevPrev]; + + for (int dice = 1; dice <= 6; ++dice) + if (dice != prev && dice != prevPrev && + (prev == 0 || gcd(dice, prev) == 1)) { + mem[n][prev][prevPrev] += distinctSequences(n - 1, dice, prev, mem); + mem[n][prev][prevPrev] %= kMod; + } + + return mem[n][prev][prevPrev]; + } +}; diff --git a/solutions/2318. Number of Distinct Roll Sequences/2318.java b/solutions/2318. Number of Distinct Roll Sequences/2318.java new file mode 100644 index 00000000000..4ffb6979539 --- /dev/null +++ b/solutions/2318. Number of Distinct Roll Sequences/2318.java @@ -0,0 +1,29 @@ +class Solution { + public int distinctSequences(int n) { + int[][][] mem = new int[n + 1][7][7]; + return distinctSequences(n, 0, 0); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of distinct sequences for n dices with `prev` and + // `prevPrev`. + private int distinctSequences(int n, int prev, int prevPrev, int[][][] mem) { + if (n == 0) + return 1; + if (mem[n][prev][prevPrev] > 0) + return mem[n][prev][prevPrev]; + + for (int dice = 1; dice <= 6; ++dice) + if (dice != prev && dice != prevPrev && (prev == 0 || gcd(dice, prev) == 1)) { + mem[n][prev][prevPrev] += distinctSequences(n - 1, dice, prev, mem); + mem[n][prev][prevPrev] %= kMod; + } + + return mem[n][prev][prevPrev]; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2318. Number of Distinct Roll Sequences/2318.py b/solutions/2318. Number of Distinct Roll Sequences/2318.py new file mode 100644 index 00000000000..1e83ef8d327 --- /dev/null +++ b/solutions/2318. Number of Distinct Roll Sequences/2318.py @@ -0,0 +1,21 @@ +class Solution: + def distinctSequences(self, n: int) -> int: + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def dp(n: int, prev: int, prevPrev: int) -> int: + """ + Returns the number of distinct sequences for n dices with `prev` and + `prevPrev`. + """ + if n == 0: + return 1 + res = 0 + for dice in range(1, 7): + if dice != prev and dice != prevPrev and \ + (prev == 0 or math.gcd(dice, prev) == 1): + res += dp(n - 1, dice, prev) + res %= kMod + return res + + return dp(n, 0, 0) diff --git a/solutions/2319. Check if Matrix Is X-Matrix/2319.cpp b/solutions/2319. Check if Matrix Is X-Matrix/2319.cpp new file mode 100644 index 00000000000..9deeff5d2f8 --- /dev/null +++ b/solutions/2319. Check if Matrix Is X-Matrix/2319.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool checkXMatrix(vector>& grid) { + const int n = grid.size(); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (i == j || i + j == n - 1) { // in diagonal + if (grid[i][j] == 0) + return false; + } else if (grid[i][j]) { // not in diagonal + return false; + } + + return true; + } +}; diff --git a/solutions/2319. Check if Matrix Is X-Matrix/2319.java b/solutions/2319. Check if Matrix Is X-Matrix/2319.java new file mode 100644 index 00000000000..0e09be73cb2 --- /dev/null +++ b/solutions/2319. Check if Matrix Is X-Matrix/2319.java @@ -0,0 +1,16 @@ +class Solution { + public boolean checkXMatrix(int[][] grid) { + final int n = grid.length; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (i == j || i + j == n - 1) { // in diagonal + if (grid[i][j] == 0) + return false; + } else if (grid[i][j] > 0) { // not in diagonal + return false; + } + + return true; + } +} diff --git a/solutions/2319. Check if Matrix Is X-Matrix/2319.py b/solutions/2319. Check if Matrix Is X-Matrix/2319.py new file mode 100644 index 00000000000..b9a59cf4574 --- /dev/null +++ b/solutions/2319. Check if Matrix Is X-Matrix/2319.py @@ -0,0 +1,13 @@ +class Solution: + def checkXMatrix(self, grid: List[List[int]]) -> bool: + n = len(grid) + + for i in range(n): + for j in range(n): + if i == j or i + j == n - 1: # in diagonal + if grid[i][j] == 0: + return False + elif grid[i][j]: # not in diagonal + return False + + return True diff --git a/solutions/232. Implement Queue using Stacks/232.cpp b/solutions/232. Implement Queue using Stacks/232.cpp new file mode 100644 index 00000000000..abcb0578381 --- /dev/null +++ b/solutions/232. Implement Queue using Stacks/232.cpp @@ -0,0 +1,28 @@ +class MyQueue { + public: + void push(int x) { + input.push(x); + } + + int pop() { + peek(); + const int val = output.top(); + output.pop(); + return val; + } + + int peek() { + if (output.empty()) + while (!input.empty()) + output.push(input.top()), input.pop(); + return output.top(); + } + + bool empty() { + return input.empty() && output.empty(); + } + + private: + stack input; + stack output; +}; diff --git a/solutions/232. Implement Queue using Stacks/232.java b/solutions/232. Implement Queue using Stacks/232.java new file mode 100644 index 00000000000..f574f239036 --- /dev/null +++ b/solutions/232. Implement Queue using Stacks/232.java @@ -0,0 +1,24 @@ +class MyQueue { + public void push(int x) { + input.push(x); + } + + public int pop() { + peek(); + return output.pop(); + } + + public int peek() { + if (output.isEmpty()) + while (!input.isEmpty()) + output.push(input.pop()); + return output.peek(); + } + + public boolean empty() { + return input.isEmpty() && output.isEmpty(); + } + + private Deque input = new ArrayDeque<>(); + private Deque output = new ArrayDeque<>(); +} diff --git a/solutions/232. Implement Queue using Stacks/232.py b/solutions/232. Implement Queue using Stacks/232.py new file mode 100644 index 00000000000..5edaa26471c --- /dev/null +++ b/solutions/232. Implement Queue using Stacks/232.py @@ -0,0 +1,20 @@ +class MyQueue: + def __init__(self): + self.input = [] + self.output = [] + + def push(self, x: int) -> None: + self.input.append(x) + + def pop(self) -> int: + self.peek() + return self.output.pop() + + def peek(self) -> int: + if not self.output: + while self.input: + self.output.append(self.input.pop()) + return self.output[-1] + + def empty(self) -> bool: + return not self.input and not self.output diff --git a/solutions/2320. Count Number of Ways to Place Houses/2320.cpp b/solutions/2320. Count Number of Ways to Place Houses/2320.cpp new file mode 100644 index 00000000000..50394c3b736 --- /dev/null +++ b/solutions/2320. Count Number of Ways to Place Houses/2320.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countHousePlacements(int n) { + constexpr int kMod = 1'000'000'007; + int house = 1; // the number of ways ending in a house + int space = 1; // the number of ways ending in a space + int total = house + space; + + for (int i = 2; i <= n; ++i) { + house = space; + space = total; + total = (house + space) % kMod; + } + + return static_cast(total) * total % kMod; + } +}; diff --git a/solutions/2320. Count Number of Ways to Place Houses/2320.java b/solutions/2320. Count Number of Ways to Place Houses/2320.java new file mode 100644 index 00000000000..1e8b0d3785d --- /dev/null +++ b/solutions/2320. Count Number of Ways to Place Houses/2320.java @@ -0,0 +1,16 @@ +class Solution { + public int countHousePlacements(int n) { + final int kMod = 1_000_000_007; + int house = 1; // the number of ways ending in a house + int space = 1; // the number of ways ending in a space + int total = house + space; + + for (int i = 2; i <= n; ++i) { + house = space; + space = total; + total = (house + space) % kMod; + } + + return (int) ((long) total * total % kMod); + } +} diff --git a/solutions/2320. Count Number of Ways to Place Houses/2320.py b/solutions/2320. Count Number of Ways to Place Houses/2320.py new file mode 100644 index 00000000000..1b66f4257e8 --- /dev/null +++ b/solutions/2320. Count Number of Ways to Place Houses/2320.py @@ -0,0 +1,13 @@ +class Solution: + def countHousePlacements(self, n: int) -> int: + kMod = 1_000_000_007 + house = 1 # the number of ways ending in a house + space = 1 # the number of ways ending in a space + total = house + space + + for _ in range(2, n + 1): + house = space + space = total + total = (house + space) % kMod + + return total**2 % kMod diff --git a/solutions/2321. Maximum Score Of Spliced Array/2321.cpp b/solutions/2321. Maximum Score Of Spliced Array/2321.cpp new file mode 100644 index 00000000000..db455e8d70d --- /dev/null +++ b/solutions/2321. Maximum Score Of Spliced Array/2321.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maximumsSplicedArray(vector& nums1, vector& nums2) { + return max(kadane(nums1, nums2), kadane(nums2, nums1)); + } + + private: + // Returns the maximum gain of swapping some numbers in `nums1` with some + // numbers in `nums2`. + int kadane(const vector& nums1, const vector& nums2) { + int gain = 0; + int maxGain = 0; + + for (int i = 0; i < nums1.size(); ++i) { + gain = max(0, gain + nums2[i] - nums1[i]); + maxGain = max(maxGain, gain); + } + + return maxGain + accumulate(nums1.begin(), nums1.end(), 0); + } +}; diff --git a/solutions/2321. Maximum Score Of Spliced Array/2321.java b/solutions/2321. Maximum Score Of Spliced Array/2321.java new file mode 100644 index 00000000000..1215a08803f --- /dev/null +++ b/solutions/2321. Maximum Score Of Spliced Array/2321.java @@ -0,0 +1,18 @@ +class Solution { + public int maximumsSplicedArray(int[] nums1, int[] nums2) { + return Math.max(kadane(nums1, nums2), kadane(nums2, nums1)); + } + + // Returns the maximum gain of swapping some numbers in `nums1` with some numbers in `nums2`. + private int kadane(int[] nums1, int[] nums2) { + int gain = 0; + int maxGain = 0; + + for (int i = 0; i < nums1.length; ++i) { + gain = Math.max(0, gain + nums2[i] - nums1[i]); + maxGain = Math.max(maxGain, gain); + } + + return maxGain + Arrays.stream(nums1).sum(); + } +} diff --git a/solutions/2321. Maximum Score Of Spliced Array/2321.py b/solutions/2321. Maximum Score Of Spliced Array/2321.py new file mode 100644 index 00000000000..5ad9545ef4d --- /dev/null +++ b/solutions/2321. Maximum Score Of Spliced Array/2321.py @@ -0,0 +1,17 @@ +class Solution: + def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int: + def kadane(nums1: List[int], nums2: List[int]) -> int: + """ + Returns the maximum gain of swapping some numbers in `nums1` with some + numbers in `nums2`. + """ + gain = 0 + maxGain = 0 + + for num1, num2 in zip(nums1, nums2): + gain = max(0, gain + num2 - num1) + maxGain = max(maxGain, gain) + + return maxGain + sum(nums1) + + return max(kadane(nums1, nums2), kadane(nums2, nums1)) diff --git a/solutions/2322. Minimum Score After Removals on a Tree/2322.cpp b/solutions/2322. Minimum Score After Removals on a Tree/2322.cpp new file mode 100644 index 00000000000..0fa6d1b5091 --- /dev/null +++ b/solutions/2322. Minimum Score After Removals on a Tree/2322.cpp @@ -0,0 +1,61 @@ +class Solution { + public: + int minimumScore(vector& nums, vector>& edges) { + const int n = nums.size(); + const int xors = reduce(nums.begin(), nums.end(), 0, bit_xor()); + vector subXors(nums); + vector> tree(n); + vector> children(n); + + for (int i = 0; i < n; ++i) + children[i].insert(i); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + dfs(tree, 0, -1, subXors, children); + + int ans = INT_MAX; + + for (int i = 0; i < edges.size(); ++i) { + int a = edges[i][0]; + int b = edges[i][1]; + if (children[a].contains(b)) + swap(a, b); + for (int j = 0; j < i; ++j) { + int c = edges[j][0]; + int d = edges[j][1]; + if (children[c].contains(d)) + swap(c, d); + vector cands; + if (a != c && children[a].contains(c)) + cands = {subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]}; + else if (a != c && children[c].contains(a)) + cands = {subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]}; + else + cands = {subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]}; + ans = min(ans, ranges::max(cands) - ranges::min(cands)); + } + } + + return ans; + } + + private: + pair> dfs(const vector>& tree, int u, + int parent, vector& subXors, + vector>& children) { + for (const int v : tree[u]) { + if (v == parent) + continue; + const auto& [vXor, vChildren] = dfs(tree, v, u, subXors, children); + subXors[u] ^= vXor; + children[u].insert(vChildren.begin(), vChildren.end()); + } + return {subXors[u], children[u]}; + } +}; diff --git a/solutions/2322. Minimum Score After Removals on a Tree/2322.java b/solutions/2322. Minimum Score After Removals on a Tree/2322.java new file mode 100644 index 00000000000..3c2777da83e --- /dev/null +++ b/solutions/2322. Minimum Score After Removals on a Tree/2322.java @@ -0,0 +1,78 @@ +class Solution { + public int minimumScore(int[] nums, int[][] edges) { + final int n = nums.length; + final int xors = getXors(nums); + int[] subXors = nums.clone(); + List[] tree = new List[n]; + Set[] children = new Set[n]; + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int i = 0; i < n; ++i) + children[i] = new HashSet<>(Arrays.asList(i)); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + dfs(tree, 0, -1, subXors, children); + + int ans = Integer.MAX_VALUE; + + for (int i = 0; i < edges.length; ++i) { + int a = edges[i][0]; + int b = edges[i][1]; + if (children[a].contains(b)) { + final int temp = a; + a = b; + b = a; + } + for (int j = 0; j < i; ++j) { + int c = edges[j][0]; + int d = edges[j][1]; + if (children[c].contains(d)) { + final int temp = c; + c = d; + d = temp; + } + int[] cands; + if (a != c && children[a].contains(c)) + cands = new int[] {subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]}; + else if (a != c && children[c].contains(a)) + cands = new int[] {subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]}; + else + cands = new int[] {subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]}; + ans = Math.min(ans, Arrays.stream(cands).max().getAsInt() - + Arrays.stream(cands).min().getAsInt()); + } + } + + return ans; + } + + private Pair> dfs(List[] tree, int u, int parent, int[] subXors, + Set[] children) { + for (final int v : tree[u]) { + if (v == parent) + continue; + final Pair> pair = dfs(tree, v, u, subXors, children); + final int vXor = pair.getKey(); + final Set vChildren = pair.getValue(); + subXors[u] ^= vXor; + for (final int child : vChildren) + children[u].add(child); + } + return new Pair<>(subXors[u], children[u]); + } + + private int getXors(int[] nums) { + int xors = 0; + for (final int num : nums) + xors ^= num; + return xors; + } +} diff --git a/solutions/2322. Minimum Score After Removals on a Tree/2322.py b/solutions/2322. Minimum Score After Removals on a Tree/2322.py new file mode 100644 index 00000000000..2b9aed52773 --- /dev/null +++ b/solutions/2322. Minimum Score After Removals on a Tree/2322.py @@ -0,0 +1,42 @@ +class Solution: + def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int: + n = len(nums) + xors = functools.reduce(operator.xor, nums) + subXors = nums[:] + tree = [[] for _ in range(n)] + children = [{i} for i in range(n)] + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def dfs(u: int, parent: int) -> Tuple[int, Set[int]]: + for v in tree[u]: + if v == parent: + continue + vXor, vChildren = dfs(v, u) + subXors[u] ^= vXor + children[u] |= vChildren + return subXors[u], children[u] + + dfs(0, -1) + + ans = math.inf + for i in range(len(edges)): + a, b = edges[i] + if b in children[a]: + a, b = b, a + for j in range(i): + c, d = edges[j] + if d in children[c]: + c, d = d, c + + if c in children[a] and a != c: + cands = [subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]] + elif a in children[c] and a != c: + cands = [subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]] + else: + cands = [subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]] + ans = min(ans, max(cands) - min(cands)) + + return ans diff --git a/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.cpp b/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.cpp new file mode 100644 index 00000000000..84831f9fca2 --- /dev/null +++ b/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minimumTime(vector& jobs, vector& workers) { + int ans = 0; + + ranges::sort(jobs); + ranges::sort(workers); + + for (int i = 0; i < jobs.size(); ++i) + ans = max(ans, (jobs[i] - 1) / workers[i] + 1); + + return ans; + } +}; diff --git a/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.java b/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.java new file mode 100644 index 00000000000..41fb0be23b0 --- /dev/null +++ b/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.java @@ -0,0 +1,13 @@ +class Solution { + public int minimumTime(int[] jobs, int[] workers) { + int ans = 0; + + Arrays.sort(jobs); + Arrays.sort(workers); + + for (int i = 0; i < jobs.length; ++i) + ans = Math.max(ans, (jobs[i] - 1) / workers[i] + 1); + + return ans; + } +} diff --git a/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.py b/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.py new file mode 100644 index 00000000000..f4522041237 --- /dev/null +++ b/solutions/2323. Find Minimum Time to Finish All Jobs II/2323.py @@ -0,0 +1,11 @@ +class Solution: + def minimumTime(self, jobs: List[int], workers: List[int]) -> int: + ans = 0 + + jobs.sort() + workers.sort() + + for job, worker in zip(jobs, workers): + ans = max(ans, (job - 1) // worker + 1) + + return ans diff --git a/solutions/2324. Product Sales Analysis IV/2324.sql b/solutions/2324. Product Sales Analysis IV/2324.sql new file mode 100644 index 00000000000..d65a028360c --- /dev/null +++ b/solutions/2324. Product Sales Analysis IV/2324.sql @@ -0,0 +1,17 @@ +WITH + RankedSpending AS ( + SELECT + Sales.user_id, + Sales.product_id, + RANK() OVER( + PARTITION by user_id + ORDER BY SUM(Sales.quantity * Product.price) DESC + ) AS `rank` + FROM Sales + INNER JOIN Product + USING (product_id) + GROUP BY 1, 2 + ) +SELECT user_id, product_id +FROM RankedSpending +WHERE `rank` = 1; diff --git a/solutions/2325. Decode the Message/2325.cpp b/solutions/2325. Decode the Message/2325.cpp new file mode 100644 index 00000000000..a9605efbe59 --- /dev/null +++ b/solutions/2325. Decode the Message/2325.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + string decodeMessage(string key, string message) { + vector keyToActual(128); + keyToActual[' '] = ' '; + char currChar = 'a'; + + for (const char c : key) + keyToActual[c] = keyToActual[c] ?: currChar++; + + transform(message.cbegin(), message.cend(), message.begin(), + [&](char c) { return keyToActual[c]; }); + + return message; + } +}; diff --git a/solutions/2325. Decode the Message/2325.java b/solutions/2325. Decode the Message/2325.java new file mode 100644 index 00000000000..745b4698d3a --- /dev/null +++ b/solutions/2325. Decode the Message/2325.java @@ -0,0 +1,17 @@ +class Solution { + public String decodeMessage(String key, String message) { + StringBuilder sb = new StringBuilder(); + char[] keyToActual = new char[128]; + keyToActual[' '] = ' '; + char currChar = 'a'; + + for (final char c : key.toCharArray()) + if (keyToActual[c] == 0) + keyToActual[c] = currChar++; + + for (final char c : message.toCharArray()) + sb.append(keyToActual[c]); + + return sb.toString(); + } +} diff --git a/solutions/2325. Decode the Message/2325.py b/solutions/2325. Decode the Message/2325.py new file mode 100644 index 00000000000..3518dd2e092 --- /dev/null +++ b/solutions/2325. Decode the Message/2325.py @@ -0,0 +1,11 @@ +class Solution: + def decodeMessage(self, key: str, message: str) -> str: + keyToActual = {' ': ' '} + currChar = 'a' + + for c in key: + if c not in keyToActual: + keyToActual[c] = currChar + currChar = chr(ord(currChar) + 1) + + return ''.join(keyToActual[c] for c in message) diff --git a/solutions/2326. Spiral Matrix IV/2326.cpp b/solutions/2326. Spiral Matrix IV/2326.cpp new file mode 100644 index 00000000000..34954fbf504 --- /dev/null +++ b/solutions/2326. Spiral Matrix IV/2326.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector> spiralMatrix(int m, int n, ListNode* head) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + vector> ans(m, vector(n, -1)); + int x = 0; // the current x position + int y = 0; // the current y position + int d = 0; + + for (ListNode* curr = head; curr; curr = curr->next) { + ans[x][y] = curr->val; + if (x + dirs[d] < 0 || x + dirs[d] == m || y + dirs[d + 1] < 0 || + y + dirs[d + 1] == n || ans[x + dirs[d]][y + dirs[d + 1]] != -1) + d = (d + 1) % 4; + x += dirs[d]; + y += dirs[d + 1]; + } + + return ans; + } +}; diff --git a/solutions/2326. Spiral Matrix IV/2326.java b/solutions/2326. Spiral Matrix IV/2326.java new file mode 100644 index 00000000000..fbeb3e37319 --- /dev/null +++ b/solutions/2326. Spiral Matrix IV/2326.java @@ -0,0 +1,21 @@ +class Solution { + public int[][] spiralMatrix(int m, int n, ListNode head) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int[][] ans = new int[m][n]; + Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1)); + int x = 0; // the current x position + int y = 0; // the current y position + int d = 0; + + for (ListNode curr = head; curr != null; curr = curr.next) { + ans[x][y] = curr.val; + if (x + dirs[d] < 0 || x + dirs[d] == m || y + dirs[d + 1] < 0 || y + dirs[d + 1] == n || + ans[x + dirs[d]][y + dirs[d + 1]] != -1) + d = (d + 1) % 4; + x += dirs[d]; + y += dirs[d + 1]; + } + + return ans; + } +} diff --git a/solutions/2326. Spiral Matrix IV/2326.py b/solutions/2326. Spiral Matrix IV/2326.py new file mode 100644 index 00000000000..366642eadb3 --- /dev/null +++ b/solutions/2326. Spiral Matrix IV/2326.py @@ -0,0 +1,19 @@ +class Solution: + def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + ans = [[-1] * n for _ in range(m)] + x = 0 # the current x position + y = 0 # the current y position + d = 0 + + curr = head + while curr: + ans[x][y] = curr.val + if x + dirs[d] < 0 or x + dirs[d] == m or y + dirs[d + 1] < 0 or \ + y + dirs[d + 1] == n or ans[x + dirs[d]][y + dirs[d + 1]] != -1: + d = (d + 1) % 4 + x += dirs[d] + y += dirs[d + 1] + curr = curr.next + + return ans diff --git a/solutions/2327. Number of People Aware of a Secret/2327.cpp b/solutions/2327. Number of People Aware of a Secret/2327.cpp new file mode 100644 index 00000000000..a7bcade599e --- /dev/null +++ b/solutions/2327. Number of People Aware of a Secret/2327.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int peopleAwareOfSecret(int n, int delay, int forget) { + constexpr int kMod = 1'000'000'007; + long share = 0; + // dp[i] := the number of people know the secret at day i + vector dp(n); // Maps day i to i + 1. + dp[0] = 1; + + for (int i = 1; i < n; ++i) { + if (i - delay >= 0) + share += dp[i - delay]; + if (i - forget >= 0) + share -= dp[i - forget]; + share += kMod; + share %= kMod; + dp[i] = share; + } + + // People before day `n - forget - 1` already forget the secret. + return accumulate(dp.end() - forget, dp.end(), 0, [&](int subtotal, int d) { + return (subtotal + d) % kMod; + }); + } +}; diff --git a/solutions/2327. Number of People Aware of a Secret/2327.java b/solutions/2327. Number of People Aware of a Secret/2327.java new file mode 100644 index 00000000000..04f38ef4d96 --- /dev/null +++ b/solutions/2327. Number of People Aware of a Secret/2327.java @@ -0,0 +1,25 @@ +class Solution { + public int peopleAwareOfSecret(int n, int delay, int forget) { + final int kMod = 1_000_000_007; + long share = 0; + // dp[i] := the number of people know the secret at day i + int[] dp = new int[n]; // Maps day i to i + 1. + dp[0] = 1; + + for (int i = 1; i < n; ++i) { + if (i - delay >= 0) + share += dp[i - delay]; + if (i - forget >= 0) + share -= dp[i - forget]; + share += kMod; + share %= kMod; + dp[i] = (int) share; + } + + // People before day `n - forget - 1` already forget the secret. + int ans = 0; + for (int i = n - forget; i < n; ++i) + ans = (ans + dp[i]) % kMod; + return ans; + } +} diff --git a/solutions/2327. Number of People Aware of a Secret/2327.py b/solutions/2327. Number of People Aware of a Secret/2327.py new file mode 100644 index 00000000000..499be073d44 --- /dev/null +++ b/solutions/2327. Number of People Aware of a Secret/2327.py @@ -0,0 +1,19 @@ +class Solution: + def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int: + kMod = 1_000_000_007 + share = 0 + # dp[i] := the number of people know the secret at day i + dp = [0] * n # Maps day i to i + 1. + dp[0] = 1 + + for i in range(1, n): + if i - delay >= 0: + share += dp[i - delay] + if i - forget >= 0: + share -= dp[i - forget] + share += kMod + share %= kMod + dp[i] = share + + # People before day `n - forget - 1` already forget the secret. + return sum(dp[-forget:]) % kMod diff --git a/solutions/2328. Number of Increasing Paths in a Grid/2328.cpp b/solutions/2328. Number of Increasing Paths in a Grid/2328.cpp new file mode 100644 index 00000000000..0cd71149848 --- /dev/null +++ b/solutions/2328. Number of Increasing Paths in a Grid/2328.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int countPaths(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + vector> mem(m, vector(n, -1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + ans += countPaths(grid, i, j, mem); + ans %= kMod; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns the number of increasing paths starting from (i, j). + int countPaths(const vector>& grid, int i, int j, + vector>& mem) { + if (mem[i][j] != -1) + return mem[i][j]; + + mem[i][j] = 1; // The current cell contributes 1 length. + + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) + continue; + if (grid[x][y] <= grid[i][j]) + continue; + mem[i][j] += countPaths(grid, x, y, mem); + mem[i][j] %= kMod; + } + + return mem[i][j]; + } +}; diff --git a/solutions/2328. Number of Increasing Paths in a Grid/2328.java b/solutions/2328. Number of Increasing Paths in a Grid/2328.java new file mode 100644 index 00000000000..defc0776620 --- /dev/null +++ b/solutions/2328. Number of Increasing Paths in a Grid/2328.java @@ -0,0 +1,40 @@ +class Solution { + public int countPaths(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + Integer[][] mem = new Integer[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + ans += countPaths(grid, i, j, mem); + ans %= kMod; + } + + return ans; + } + + private static final int kMod = 1_000_000_007; + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns the number of increasing paths starting from (i, j). + private int countPaths(int[][] grid, int i, int j, Integer[][] mem) { + if (mem[i][j] != null) + return mem[i][j]; + + mem[i][j] = 1; // The current cell contributes 1 length. + + for (int[] dir : dirs) { + int x = i + dir[0]; + int y = j + dir[1]; + if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) + continue; + if (grid[x][y] <= grid[i][j]) + continue; + mem[i][j] += countPaths(grid, x, y, mem); + mem[i][j] %= kMod; + } + + return mem[i][j]; + } +} diff --git a/solutions/2328. Number of Increasing Paths in a Grid/2328.py b/solutions/2328. Number of Increasing Paths in a Grid/2328.py new file mode 100644 index 00000000000..606a5e8d1c9 --- /dev/null +++ b/solutions/2328. Number of Increasing Paths in a Grid/2328.py @@ -0,0 +1,25 @@ +class Solution: + def countPaths(self, grid: List[List[int]]) -> int: + kMod = 1_000_000_007 + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + + @functools.lru_cache(None) + def dp(i: int, j: int) -> int: + """Returns the number of increasing paths starting from (i, j).""" + ans = 1 # The current cell contributes 1 length. + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if grid[x][y] <= grid[i][j]: + continue + ans += dp(x, y) + ans %= kMod + return ans + + return sum(dp(i, j) + for i in range(m) + for j in range(n)) % kMod diff --git a/solutions/2329. Product Sales Analysis V/2329.sql b/solutions/2329. Product Sales Analysis V/2329.sql new file mode 100644 index 00000000000..ef1308c54b5 --- /dev/null +++ b/solutions/2329. Product Sales Analysis V/2329.sql @@ -0,0 +1,8 @@ +SELECT + Sales.user_id, + SUM(Sales.quantity * Product.price) AS spending +FROM Sales +INNER JOIN Product + USING (product_id) +GROUP BY user_id +ORDER BY spending DESC; diff --git a/solutions/233. Number of Digit One/233.cpp b/solutions/233. Number of Digit One/233.cpp new file mode 100644 index 00000000000..19fe1c4eede --- /dev/null +++ b/solutions/233. Number of Digit One/233.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int countDigitOne(int n) { + int ans = 0; + + for (long pow10 = 1; pow10 <= n; pow10 *= 10) { + const long divisor = pow10 * 10; + const int quotient = n / divisor; + const int remainder = n % divisor; + if (quotient > 0) + ans += quotient * pow10; + if (remainder >= pow10) + ans += min(remainder - pow10 + 1, pow10); + } + + return ans; + } +}; diff --git a/solutions/233. Number of Digit One/233.java b/solutions/233. Number of Digit One/233.java new file mode 100644 index 00000000000..62b3739a485 --- /dev/null +++ b/solutions/233. Number of Digit One/233.java @@ -0,0 +1,17 @@ +class Solution { + public int countDigitOne(int n) { + int ans = 0; + + for (long pow10 = 1; pow10 <= n; pow10 *= 10) { + final long divisor = pow10 * 10; + final int quotient = (int) (n / divisor); + final int remainder = (int) (n % divisor); + if (quotient > 0) + ans += quotient * pow10; + if (remainder >= pow10) + ans += Math.min(remainder - pow10 + 1, pow10); + } + + return ans; + } +} diff --git a/solutions/233. Number of Digit One/233.py b/solutions/233. Number of Digit One/233.py new file mode 100644 index 00000000000..8bbabfb84c2 --- /dev/null +++ b/solutions/233. Number of Digit One/233.py @@ -0,0 +1,16 @@ +class Solution: + def countDigitOne(self, n: int) -> int: + ans = 0 + + pow10 = 1 + while pow10 <= n: + divisor = pow10 * 10 + quotient = n // divisor + remainder = n % divisor + if quotient > 0: + ans += quotient * pow10 + if remainder >= pow10: + ans += min(remainder - pow10 + 1, pow10) + pow10 *= 10 + + return ans diff --git a/solutions/2330. Valid Palindrome IV/2330.cpp b/solutions/2330. Valid Palindrome IV/2330.cpp new file mode 100644 index 00000000000..3c075e24483 --- /dev/null +++ b/solutions/2330. Valid Palindrome IV/2330.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool makePalindrome(string s) { + int change = 0; + int l = 0; + int r = s.length() - 1; + + while (l < r) { + if (s[l] != s[r] && ++change > 2) + return false; + ++l; + --r; + } + + return true; + } +}; diff --git a/solutions/2330. Valid Palindrome IV/2330.java b/solutions/2330. Valid Palindrome IV/2330.java new file mode 100644 index 00000000000..1cdf5d114b9 --- /dev/null +++ b/solutions/2330. Valid Palindrome IV/2330.java @@ -0,0 +1,16 @@ +class Solution { + public boolean makePalindrome(String s) { + int change = 0; + int l = 0; + int r = s.length() - 1; + + while (l < r) { + if (s.charAt(l) != s.charAt(r) && ++change > 2) + return false; + ++l; + --r; + } + + return true; + } +} diff --git a/solutions/2330. Valid Palindrome IV/2330.py b/solutions/2330. Valid Palindrome IV/2330.py new file mode 100644 index 00000000000..f89fae25ce6 --- /dev/null +++ b/solutions/2330. Valid Palindrome IV/2330.py @@ -0,0 +1,15 @@ +class Solution: + def makePalindrome(self, s: str) -> bool: + change = 0 + l = 0 + r = len(s) - 1 + + while l < r: + if s[l] != s[r]: + change += 1 + if change > 2: + return False + l += 1 + r -= 1 + + return True diff --git a/solutions/2331. Evaluate Boolean Binary Tree/2331.cpp b/solutions/2331. Evaluate Boolean Binary Tree/2331.cpp new file mode 100644 index 00000000000..ef5805f540d --- /dev/null +++ b/solutions/2331. Evaluate Boolean Binary Tree/2331.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool evaluateTree(TreeNode* root) { + if (root->val < 2) + return root->val; + if (root->val == 2) // OR + return evaluateTree(root->left) || evaluateTree(root->right); + // AND + return evaluateTree(root->left) && evaluateTree(root->right); + } +}; diff --git a/solutions/2331. Evaluate Boolean Binary Tree/2331.java b/solutions/2331. Evaluate Boolean Binary Tree/2331.java new file mode 100644 index 00000000000..d92d03ea060 --- /dev/null +++ b/solutions/2331. Evaluate Boolean Binary Tree/2331.java @@ -0,0 +1,10 @@ +class Solution { + public boolean evaluateTree(TreeNode root) { + if (root.val < 2) + return root.val == 1; + if (root.val == 2) // OR + return evaluateTree(root.left) || evaluateTree(root.right); + // AND + return evaluateTree(root.left) && evaluateTree(root.right); + } +} diff --git a/solutions/2331. Evaluate Boolean Binary Tree/2331.py b/solutions/2331. Evaluate Boolean Binary Tree/2331.py new file mode 100644 index 00000000000..085ae384c81 --- /dev/null +++ b/solutions/2331. Evaluate Boolean Binary Tree/2331.py @@ -0,0 +1,8 @@ +class Solution: + def evaluateTree(self, root: Optional[TreeNode]) -> bool: + if root.val < 2: + return root.val + if root.val == 2: # OR + return self.evaluateTree(root.left) or self.evaluateTree(root.right) + # AND + return self.evaluateTree(root.left) and self.evaluateTree(root.right) diff --git a/solutions/2332. The Latest Time to Catch a Bus/2332.cpp b/solutions/2332. The Latest Time to Catch a Bus/2332.cpp new file mode 100644 index 00000000000..99b59ff55a1 --- /dev/null +++ b/solutions/2332. The Latest Time to Catch a Bus/2332.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int latestTimeCatchTheBus(vector& buses, vector& passengers, + int capacity) { + ranges::sort(buses); + ranges::sort(passengers); + + if (passengers.front() > buses.back()) + return buses.back(); + + int ans = passengers[0] - 1; + int i = 0; // buses' index + int j = 0; // passengers' index + + while (i < buses.size()) { + // Greedily make passengers catch `buses[i]`. + int arrived = 0; + while (arrived < capacity && j < passengers.size() && + passengers[j] <= buses[i]) { + if (j > 0 && passengers[j] != passengers[j - 1] + 1) + ans = passengers[j] - 1; + ++j; + ++arrived; + } + // There's room for `buses[i]` to carry a passenger arriving at + // `buses[i]`. + if (arrived < capacity && j > 0 && passengers[j - 1] != buses[i]) + ans = buses[i]; + ++i; + } + + return ans; + } +}; diff --git a/solutions/2332. The Latest Time to Catch a Bus/2332.java b/solutions/2332. The Latest Time to Catch a Bus/2332.java new file mode 100644 index 00000000000..4b808c6fd35 --- /dev/null +++ b/solutions/2332. The Latest Time to Catch a Bus/2332.java @@ -0,0 +1,31 @@ +class Solution { + public int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) { + Arrays.sort(buses); + Arrays.sort(passengers); + + if (passengers[0] > buses[buses.length - 1]) + return buses[buses.length - 1]; + + int ans = passengers[0] - 1; + int i = 0; // buses' index + int j = 0; // passengers' index + + while (i < buses.length) { + // Greedily make passengers catch `buses[i]`. + int arrived = 0; + while (arrived < capacity && j < passengers.length && passengers[j] <= buses[i]) { + if (j > 0 && passengers[j] != passengers[j - 1] + 1) + ans = passengers[j] - 1; + ++j; + ++arrived; + } + // There's room for `buses[i]` to carry a passenger arriving at the + // `buses[i]`. + if (arrived < capacity && j > 0 && passengers[j - 1] != buses[i]) + ans = buses[i]; + ++i; + } + + return ans; + } +} diff --git a/solutions/2332. The Latest Time to Catch a Bus/2332.py b/solutions/2332. The Latest Time to Catch a Bus/2332.py new file mode 100644 index 00000000000..3d6f9695f6d --- /dev/null +++ b/solutions/2332. The Latest Time to Catch a Bus/2332.py @@ -0,0 +1,27 @@ +class Solution: + def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int: + buses.sort() + passengers.sort() + + if passengers[0] > buses[-1]: + return buses[-1] + + ans = passengers[0] - 1 + i = 0 # buses' index + j = 0 # passengers' index + + while i < len(buses): + # Greedily make passengers catch `buses[i]`. + arrived = 0 + while arrived < capacity and j < len(passengers) and passengers[j] <= buses[i]: + if j > 0 and passengers[j] != passengers[j - 1] + 1: + ans = passengers[j] - 1 + j += 1 + arrived += 1 + # There's room for `buses[i]` to carry a passenger arriving at the + # `buses[i]`. + if arrived < capacity and j > 0 and passengers[j - 1] != buses[i]: + ans = buses[i] + i += 1 + + return ans diff --git a/solutions/2333. Minimum Sum of Squared Difference/2333.cpp b/solutions/2333. Minimum Sum of Squared Difference/2333.cpp new file mode 100644 index 00000000000..344c198d653 --- /dev/null +++ b/solutions/2333. Minimum Sum of Squared Difference/2333.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + long long minSumSquareDiff(vector& nums1, vector& nums2, int k1, + int k2) { + const vector diff = getDiff(nums1, nums2); + int k = k1 + k2; + if (accumulate(diff.begin(), diff.end(), 0L) <= k) + return 0; + + unordered_map count; + priority_queue> maxHeap; // (num, freq) + + for (const int d : diff) + if (d != 0) + ++count[d]; + + for (const auto& [num, freq] : count) + maxHeap.emplace(num, freq); + + while (k > 0) { + const auto [maxNum, maxNumFreq] = maxHeap.top(); + maxHeap.pop(); + // Buck decrease in this turn + const int numDecreased = min(k, maxNumFreq); + k -= numDecreased; + if (maxNumFreq > numDecreased) + maxHeap.emplace(maxNum, maxNumFreq - numDecreased); + if (!maxHeap.empty() && maxHeap.top().first + 1 == maxNum) { + const auto [secondMaxNum, secondMaxNumFreq] = maxHeap.top(); + maxHeap.pop(); + maxHeap.emplace(secondMaxNum, secondMaxNumFreq + numDecreased); + } else if (maxNum > 1) { + maxHeap.emplace(maxNum - 1, numDecreased); + } + } + + long ans = 0; + while (!maxHeap.empty()) { + const auto [num, freq] = maxHeap.top(); + maxHeap.pop(); + ans += static_cast(num) * num * freq; + } + + return ans; + } + + private: + vector getDiff(const vector& nums1, const vector& nums2) { + vector diff; + for (int i = 0; i < nums1.size(); ++i) + diff.push_back(abs(nums1[i] - nums2[i])); + return diff; + } +}; diff --git a/solutions/2333. Minimum Sum of Squared Difference/2333.java b/solutions/2333. Minimum Sum of Squared Difference/2333.java new file mode 100644 index 00000000000..0805f48b30b --- /dev/null +++ b/solutions/2333. Minimum Sum of Squared Difference/2333.java @@ -0,0 +1,55 @@ +class Solution { + public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) { + int[] diff = getDiff(nums1, nums2); + int k = k1 + k2; + if (Arrays.stream(diff).asLongStream().sum() <= k) + return 0; + + Map count = new HashMap<>(); + // (num, freq) + Queue> maxHeap = new PriorityQueue<>((a, b) -> b.getKey() - a.getKey()); + + for (final int d : diff) + if (d != 0) + count.merge(d, 1, Integer::sum); + + for (Map.Entry entry : count.entrySet()) + maxHeap.offer(new Pair<>(entry.getKey(), entry.getValue())); + + while (k > 0) { + Pair pair = maxHeap.poll(); + final int maxNum = pair.getKey(); + final int maxNumFreq = pair.getValue(); + // Buck decrease in this turn + final int numDecreased = Math.min(k, maxNumFreq); + k -= numDecreased; + if (maxNumFreq > numDecreased) + maxHeap.offer(new Pair<>(maxNum, maxNumFreq - numDecreased)); + if (!maxHeap.isEmpty() && maxHeap.peek().getKey() + 1 == maxNum) { + Pair secondNode = maxHeap.poll(); + final int secondMaxNum = secondNode.getKey(); + final int secondMaxNumFreq = secondNode.getValue(); + maxHeap.offer(new Pair<>(secondMaxNum, secondMaxNumFreq + numDecreased)); + } else if (maxNum > 1) { + maxHeap.offer(new Pair<>(maxNum - 1, numDecreased)); + } + } + + long ans = 0; + while (!maxHeap.isEmpty()) { + Pair pair = maxHeap.poll(); + final int num = pair.getKey(); + final int freq = pair.getValue(); + ans += (long) num * num * freq; + } + + return ans; + } + + private int[] getDiff(int[] nums1, int[] nums2) { + int[] diff = new int[nums1.length]; + for (int i = 0; i < nums1.length; ++i) + diff[i] = Math.abs(nums1[i] - nums2[i]); + return diff; + } +} diff --git a/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.cpp b/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.cpp new file mode 100644 index 00000000000..b360715b83e --- /dev/null +++ b/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + // Similar to 907. Sum of Subarray Minimums + int validSubarraySize(vector& nums, int threshold) { + const int n = nums.size(); + // prev[i] := the index k s.t. nums[k] is the previous minimum in nums[0..n) + vector prev(n, -1); + // next[i] := the index k s.t. nums[k] is the next minimum in nums[i + 1..n) + vector next(n, n); + stack stack; + + for (int i = 0; i < n; ++i) { + while (!stack.empty() && nums[stack.top()] > nums[i]) { + const int index = stack.top(); + stack.pop(); + next[index] = i; + } + if (!stack.empty()) + prev[i] = stack.top(); + stack.push(i); + } + + for (int i = 0; i < n; ++i) { + // the number of `nums` in subarray containing nums[i] >= nums[i] + const int k = (i - prev[i]) + (next[i] - i) - 1; + if (nums[i] > threshold / static_cast(k)) + return k; + } + + return -1; + } +}; diff --git a/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.java b/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.java new file mode 100644 index 00000000000..1e02eddc91b --- /dev/null +++ b/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.java @@ -0,0 +1,34 @@ +class Solution { + // Similar to 907. Sum of Subarray Minimums + public int validSubarraySize(int[] nums, int threshold) { + final int n = nums.length; + long ans = 0; + // prev[i] := the index k s.t. nums[k] is the previous minimum in nums[0..n) + int[] prev = new int[n]; + // next[i] := the index k s.t. nums[k] is the next minimum in nums[i + 1..n) + int[] next = new int[n]; + Deque stack = new ArrayDeque<>(); + + Arrays.fill(prev, -1); + Arrays.fill(next, n); + + for (int i = 0; i < nums.length; ++i) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + final int index = stack.pop(); + next[index] = i; + } + if (!stack.isEmpty()) + prev[i] = stack.peek(); + stack.push(i); + } + + for (int i = 0; i < n; ++i) { + // the number of `nums` in subarray containing nums[i] >= nums[i] + final int k = (i - prev[i]) + (next[i] - i) - 1; + if (nums[i] > threshold / (double) k) + return k; + } + + return -1; + } +} diff --git a/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.py b/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.py new file mode 100644 index 00000000000..9096a72edc7 --- /dev/null +++ b/solutions/2334. Subarray With Elements Greater Than Varying Threshold/2334.py @@ -0,0 +1,25 @@ +class Solution: + # Similar to 907. Sum of Subarray Minimums + def validSubarraySize(self, nums: List[int], threshold: int) -> int: + n = len(nums) + ans = 0 + # prev[i] := the index k s.t. nums[k] is the previous minimum in nums[0..n) + prev = [-1] * n + # next[i] := the index k s.t. nums[k] is the next minimum in nums[i + 1..n) + next = [n] * n + stack = [] + + for i, a in enumerate(nums): + while stack and nums[stack[-1]] > a: + index = stack.pop() + next[index] = i + if stack: + prev[i] = stack[-1] + stack.append(i) + + for i, (num, prevIndex, nextIndex) in enumerate(zip(nums, prev, next)): + k = (i - prevIndex) + (nextIndex - i) - 1 + if num > threshold / k: + return k + + return -1 diff --git a/solutions/2335. Minimum Amount of Time to Fill Cups/2335.cpp b/solutions/2335. Minimum Amount of Time to Fill Cups/2335.cpp new file mode 100644 index 00000000000..c15582d587a --- /dev/null +++ b/solutions/2335. Minimum Amount of Time to Fill Cups/2335.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int fillCups(vector& amount) { + const int mx = ranges::max(amount); + const int sum = accumulate(amount.begin(), amount.end(), 0); + return max(mx, (sum + 1) / 2); + } +}; diff --git a/solutions/2335. Minimum Amount of Time to Fill Cups/2335.java b/solutions/2335. Minimum Amount of Time to Fill Cups/2335.java new file mode 100644 index 00000000000..6a0753197dc --- /dev/null +++ b/solutions/2335. Minimum Amount of Time to Fill Cups/2335.java @@ -0,0 +1,7 @@ +class Solution { + public int fillCups(int[] amount) { + final int mx = Arrays.stream(amount).max().getAsInt(); + final int sum = Arrays.stream(amount).sum(); + return Math.max(mx, (sum + 1) / 2); + } +} diff --git a/solutions/2335. Minimum Amount of Time to Fill Cups/2335.py b/solutions/2335. Minimum Amount of Time to Fill Cups/2335.py new file mode 100644 index 00000000000..c95e6ca7beb --- /dev/null +++ b/solutions/2335. Minimum Amount of Time to Fill Cups/2335.py @@ -0,0 +1,3 @@ +class Solution: + def fillCups(self, amount: List[int]) -> int: + return max(max(amount), (sum(amount) + 1) // 2) diff --git a/solutions/2336. Smallest Number in Infinite Set/2336.cpp b/solutions/2336. Smallest Number in Infinite Set/2336.cpp new file mode 100644 index 00000000000..bea68041f4f --- /dev/null +++ b/solutions/2336. Smallest Number in Infinite Set/2336.cpp @@ -0,0 +1,19 @@ +class SmallestInfiniteSet { + public: + int popSmallest() { + if (added.empty()) + return curr++; + const int mn = *added.begin(); + added.erase(added.begin()); + return mn; + } + + void addBack(int num) { + if (num < curr) + added.insert(num); + } + + private: + int curr = 1; + set added; +}; diff --git a/solutions/2336. Smallest Number in Infinite Set/2336.java b/solutions/2336. Smallest Number in Infinite Set/2336.java new file mode 100644 index 00000000000..af3c80aee62 --- /dev/null +++ b/solutions/2336. Smallest Number in Infinite Set/2336.java @@ -0,0 +1,17 @@ +class SmallestInfiniteSet { + public int popSmallest() { + if (added.isEmpty()) + return curr++; + final int mn = added.first(); + added.remove(mn); + return mn; + } + + public void addBack(int num) { + if (num < curr) + added.add(num); + } + + private int curr = 1; + private TreeSet added = new TreeSet<>(); +} diff --git a/solutions/2337. Move Pieces to Obtain a String/2337.cpp b/solutions/2337. Move Pieces to Obtain a String/2337.cpp new file mode 100644 index 00000000000..6b2ba5de998 --- /dev/null +++ b/solutions/2337. Move Pieces to Obtain a String/2337.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + bool canChange(string start, string target) { + const int n = start.length(); + int i = 0; // start's index + int j = 0; // target's index + + while (i <= n && j <= n) { + while (i < n && start[i] == '_') + ++i; + while (j < n && target[j] == '_') + ++j; + if (i == n || j == n) + return i == n && j == n; + if (start[i] != target[j]) + return false; + if (start[i] == 'R' && i > j) + return false; + if (start[i] == 'L' && i < j) + return false; + ++i; + ++j; + } + + return true; + } +}; diff --git a/solutions/2337. Move Pieces to Obtain a String/2337.java b/solutions/2337. Move Pieces to Obtain a String/2337.java new file mode 100644 index 00000000000..7fb766ff1df --- /dev/null +++ b/solutions/2337. Move Pieces to Obtain a String/2337.java @@ -0,0 +1,26 @@ +class Solution { + public boolean canChange(String start, String target) { + final int n = start.length(); + int i = 0; // start's index + int j = 0; // target's index + + while (i <= n && j <= n) { + while (i < n && start.charAt(i) == '_') + ++i; + while (j < n && target.charAt(j) == '_') + ++j; + if (i == n || j == n) + return i == n && j == n; + if (start.charAt(i) != target.charAt(j)) + return false; + if (start.charAt(i) == 'R' && i > j) + return false; + if (start.charAt(i) == 'L' && i < j) + return false; + ++i; + ++j; + } + + return true; + } +} diff --git a/solutions/2337. Move Pieces to Obtain a String/2337.py b/solutions/2337. Move Pieces to Obtain a String/2337.py new file mode 100644 index 00000000000..eac7e66dd12 --- /dev/null +++ b/solutions/2337. Move Pieces to Obtain a String/2337.py @@ -0,0 +1,23 @@ +class Solution: + def canChange(self, start: str, target: str) -> bool: + n = len(start) + i = 0 # start's index + j = 0 # target's index + + while i <= n and j <= n: + while i < n and start[i] == '_': + i += 1 + while j < n and target[j] == '_': + j += 1 + if i == n or j == n: + return i == n and j == n + if start[i] != target[j]: + return False + if start[i] == 'R' and i > j: + return False + if start[i] == 'L' and i < j: + return False + i += 1 + j += 1 + + return True diff --git a/solutions/2338. Count the Number of Ideal Arrays/2338.cpp b/solutions/2338. Count the Number of Ideal Arrays/2338.cpp new file mode 100644 index 00000000000..e29b408ffad --- /dev/null +++ b/solutions/2338. Count the Number of Ideal Arrays/2338.cpp @@ -0,0 +1,63 @@ +class Solution { + public: + int idealArrays(int n, int maxValue) { + // Since 2^14 > 10^4, the longest strictly increasing array is [1, 2, 4, + // ..., 2^13] + const int maxLength = min(14, n); + const vector> factors = getFactors(maxValue); + // dp[i][j] := the number of strictly increasing ideal arrays of length i + // ending in j + // dp[i][j] := sum(dp[i - 1][k]), where j % k == 0 + // dp[i][0] := sum(dp[i][j]) where 1 <= j <= maxValue + vector> dp(maxLength + 1, vector(maxValue + 1)); + vector> mem(n, vector(maxLength, -1)); + long ans = 0; + + for (int j = 1; j <= maxValue; ++j) + dp[1][j] = 1; + + for (int i = 2; i <= maxLength; ++i) + for (int j = 1; j <= maxValue; ++j) + for (const int k : factors[j]) { + dp[i][j] += dp[i - 1][k]; + dp[i][j] %= kMod; + } + + for (int i = 1; i <= maxLength; ++i) + for (int j = 1; j <= maxValue; ++j) { + dp[i][0] += dp[i][j]; + dp[i][0] %= kMod; + } + + for (int i = 1; i <= maxLength; ++i) { + // nCk(n - 1, i - 1) := the number of ways to create an ideal array of + // length n from a strictly increasing array of length i + ans += dp[i][0] * nCk(n - 1, i - 1, mem); + ans %= kMod; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + vector> getFactors(int maxValue) { + vector> factors(maxValue + 1); + for (int i = 1; i <= maxValue; ++i) + // Start from i * 2 because of strictly increasing. + for (int j = i * 2; j <= maxValue; j += i) + factors[j].push_back(i); + return factors; + } + + long nCk(int n, int k, vector>& mem) { + if (k == 0) + return 1; + if (n == k) + return 1; + if (mem[n][k] != -1) + return mem[n][k]; + return mem[n][k] = (nCk(n - 1, k, mem) + nCk(n - 1, k - 1, mem)) % kMod; + } +}; diff --git a/solutions/2339. All the Matches of the League/2339.sql b/solutions/2339. All the Matches of the League/2339.sql new file mode 100644 index 00000000000..d3d39fb88ca --- /dev/null +++ b/solutions/2339. All the Matches of the League/2339.sql @@ -0,0 +1,6 @@ +SELECT + Home.team_name AS home_team, + Away.team_name AS away_team +FROM Teams AS Home +INNER JOIN Teams AS Away +WHERE Home.team_name != Away.team_name; diff --git a/solutions/234. Palindrome Linked List/234.cpp b/solutions/234. Palindrome Linked List/234.cpp new file mode 100644 index 00000000000..a0b552a5639 --- /dev/null +++ b/solutions/234. Palindrome Linked List/234.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + bool isPalindrome(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head; + + while (fast != nullptr && fast->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + } + + if (fast != nullptr) + slow = slow->next; + slow = reverseList(slow); + + while (slow) { + if (slow->val != head->val) + return false; + slow = slow->next; + head = head->next; + } + + return true; + } + + private: + ListNode* reverseList(ListNode* head) { + ListNode* prev = nullptr; + + while (head) { + ListNode* next = head->next; + head->next = prev; + prev = head; + head = next; + } + + return prev; + } +}; diff --git a/solutions/234. Palindrome Linked List/234.java b/solutions/234. Palindrome Linked List/234.java new file mode 100644 index 00000000000..7a343ce2c28 --- /dev/null +++ b/solutions/234. Palindrome Linked List/234.java @@ -0,0 +1,37 @@ +class Solution { + public boolean isPalindrome(ListNode head) { + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + if (fast != null) + slow = slow.next; + slow = reverseList(slow); + + while (slow != null) { + if (slow.val != head.val) + return false; + slow = slow.next; + head = head.next; + } + + return true; + } + + private ListNode reverseList(ListNode head) { + ListNode prev = null; + + while (head != null) { + ListNode next = head.next; + head.next = prev; + prev = head; + head = next; + } + + return prev; + } +} diff --git a/solutions/234. Palindrome Linked List/234.py b/solutions/234. Palindrome Linked List/234.py new file mode 100644 index 00000000000..4d770b0ee39 --- /dev/null +++ b/solutions/234. Palindrome Linked List/234.py @@ -0,0 +1,32 @@ +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + def reverseList(head: ListNode) -> ListNode: + prev = None + curr = head + + while curr: + next = curr.next + curr.next = prev + prev = curr + curr = next + + return prev + + slow = head + fast = head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + if fast: + slow = slow.next + slow = reverseList(slow) + + while slow: + if slow.val != head.val: + return False + slow = slow.next + head = head.next + + return True diff --git a/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.cpp b/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.cpp new file mode 100644 index 00000000000..9b5c741a7a3 --- /dev/null +++ b/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minimumSwaps(vector& nums) { + const int minIndex = getLeftmostMinIndex(nums); + const int maxIndex = getRightmostMaxIndex(nums); + const int swaps = minIndex + (nums.size() - 1 - maxIndex); + return minIndex <= maxIndex ? swaps : swaps - 1; + } + + private: + int getLeftmostMinIndex(const vector& nums) { + int mn = nums.front(); + int minIndex = 0; + for (int i = 1; i < nums.size(); ++i) + if (nums[i] < mn) { + mn = nums[i]; + minIndex = i; + } + return minIndex; + } + + int getRightmostMaxIndex(const vector& nums) { + int mx = nums.back(); + int maxIndex = nums.size() - 1; + for (int i = nums.size() - 2; i >= 0; --i) + if (nums[i] > mx) { + mx = nums[i]; + maxIndex = i; + } + return maxIndex; + } +}; diff --git a/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.java b/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.java new file mode 100644 index 00000000000..5b58030ccb2 --- /dev/null +++ b/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.java @@ -0,0 +1,30 @@ +class Solution { + public int minimumSwaps(int[] nums) { + final int minIndex = getLeftmostMinIndex(nums); + final int maxIndex = getRightmostMaxIndex(nums); + final int swaps = minIndex + (nums.length - 1 - maxIndex); + return minIndex <= maxIndex ? swaps : swaps - 1; + } + + private int getLeftmostMinIndex(int[] nums) { + int mn = nums[0]; + int minIndex = 0; + for (int i = 1; i < nums.length; ++i) + if (nums[i] < mn) { + mn = nums[i]; + minIndex = i; + } + return minIndex; + } + + int getRightmostMaxIndex(int[] nums) { + int mx = nums[nums.length - 1]; + int maxIndex = nums.length - 1; + for (int i = nums.length - 2; i >= 0; --i) + if (nums[i] > mx) { + mx = nums[i]; + maxIndex = i; + } + return maxIndex; + } +} diff --git a/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.py b/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.py new file mode 100644 index 00000000000..56225aa363e --- /dev/null +++ b/solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.py @@ -0,0 +1,24 @@ +class Solution: + def minimumSwaps(self, nums: List[int]) -> int: + minIndex = self._getLeftmostMinIndex(nums) + maxIndex = self._getRightmostMaxIndex(nums) + swaps = minIndex + (len(nums) - 1 - maxIndex) + return swaps if minIndex <= maxIndex else swaps - 1 + + def _getLeftmostMinIndex(self, nums: List[int]) -> int: + mn = nums[0] + minIndex = 0 + for i in range(1, len(nums)): + if nums[i] < mn: + mn = nums[i] + minIndex = i + return minIndex + + def _getRightmostMaxIndex(self, nums: List[int]) -> int: + mx = nums[-1] + maxIndex = len(nums) - 1 + for i in range(len(nums) - 2, -1, -1): + if nums[i] > mx: + mx = nums[i] + maxIndex = i + return maxIndex diff --git a/solutions/2341. Maximum Number of Pairs in Array/2341.cpp b/solutions/2341. Maximum Number of Pairs in Array/2341.cpp new file mode 100644 index 00000000000..3640dca94d0 --- /dev/null +++ b/solutions/2341. Maximum Number of Pairs in Array/2341.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector numberOfPairs(vector& nums) { + constexpr int kMax = 100; + vector ans(2); + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int i = 0; i <= kMax; ++i) { + ans[0] += count[i] / 2; + ans[1] += count[i] & 1; + } + + return ans; + } +}; diff --git a/solutions/2341. Maximum Number of Pairs in Array/2341.java b/solutions/2341. Maximum Number of Pairs in Array/2341.java new file mode 100644 index 00000000000..574ad7da2f7 --- /dev/null +++ b/solutions/2341. Maximum Number of Pairs in Array/2341.java @@ -0,0 +1,18 @@ +class Solution { + public int[] numberOfPairs(int[] nums) { + final int kMax = 100; + int[] ans = new int[2]; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int i = 0; i <= kMax; ++i) { + ans[0] += count[i] / 2; + if (count[i] % 2 == 1) + ++ans[1]; + } + + return ans; + } +} diff --git a/solutions/2341. Maximum Number of Pairs in Array/2341.py b/solutions/2341. Maximum Number of Pairs in Array/2341.py new file mode 100644 index 00000000000..67cd796ce58 --- /dev/null +++ b/solutions/2341. Maximum Number of Pairs in Array/2341.py @@ -0,0 +1,10 @@ +class Solution: + def numberOfPairs(self, nums: List[int]) -> List[int]: + ans = [0] * 2 + count = collections.Counter(nums) + + for i in range(101): + ans[0] += count[i] // 2 + ans[1] += count[i] & 1 + + return ans diff --git a/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.cpp b/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.cpp new file mode 100644 index 00000000000..9ae73948a52 --- /dev/null +++ b/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maximumSum(vector& nums) { + constexpr int kMax = 9 * 9; // 999,999,999 + int ans = -1; + vector> count(kMax + 1); + + for (const int num : nums) + count[getDigitSum(num)].push_back(num); + + for (vector& groupNums : count) { + if (groupNums.size() < 2) + continue; + ranges::sort(groupNums, greater<>()); + ans = max(ans, groupNums[0] + groupNums[1]); + } + + return ans; + } + + private: + int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +}; diff --git a/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.java b/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.java new file mode 100644 index 00000000000..497202f278c --- /dev/null +++ b/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.java @@ -0,0 +1,31 @@ +class Solution { + public int maximumSum(int[] nums) { + final int kMax = 9 * 9; // 999,999,999 + int ans = -1; + List[] count = new List[kMax + 1]; + + for (int i = 0; i <= kMax; ++i) + count[i] = new ArrayList<>(); + + for (final int num : nums) + count[getDigitSum(num)].add(num); + + for (List groupNums : count) { + if (groupNums.size() < 2) + continue; + Collections.sort(groupNums, Collections.reverseOrder()); + ans = Math.max(ans, groupNums.get(0) + groupNums.get(1)); + } + + return ans; + } + + private int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +} diff --git a/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.py b/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.py new file mode 100644 index 00000000000..7941db283a2 --- /dev/null +++ b/solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.py @@ -0,0 +1,19 @@ +class Solution: + def maximumSum(self, nums: List[int]) -> int: + kMax = 9 * 9 # 999,999,999 + ans = -1 + count = [[] for _ in range(kMax + 1)] + + for num in nums: + count[self._getDigitSum(num)].append(num) + + for groupNums in count: + if len(groupNums) < 2: + continue + groupNums.sort(reverse=True) + ans = max(ans, groupNums[0] + groupNums[1]) + + return ans + + def _getDigitSum(self, num: int) -> int: + return sum(int(digit) for digit in str(num)) diff --git a/solutions/2343. Query Kth Smallest Trimmed Number/2343.cpp b/solutions/2343. Query Kth Smallest Trimmed Number/2343.cpp new file mode 100644 index 00000000000..b307197c10b --- /dev/null +++ b/solutions/2343. Query Kth Smallest Trimmed Number/2343.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector smallestTrimmedNumbers(vector& nums, + vector>& queries) { + vector ans; + for (const vector& query : queries) + ans.push_back(getKSmallestIndex(nums, query[0], query[1])); + return ans; + } + + private: + int getKSmallestIndex(const vector& nums, int k, int trim) { + const int startIndex = nums[0].length() - trim; + vector> trimmed; // (num, index) + + for (int i = 0; i < nums.size(); ++i) { + const string& num = nums[i]; + trimmed.push_back({num.substr(startIndex), i}); + } + + ranges::sort(trimmed); + return trimmed[k - 1].second; + } +}; diff --git a/solutions/2344. Minimum Deletions to Make Array Divisible/2344.cpp b/solutions/2344. Minimum Deletions to Make Array Divisible/2344.cpp new file mode 100644 index 00000000000..096ff267af9 --- /dev/null +++ b/solutions/2344. Minimum Deletions to Make Array Divisible/2344.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minOperations(vector& nums, vector& numsDivide) { + const int gcd = getGCD(numsDivide); + + ranges::sort(nums); + + for (int i = 0; i < nums.size(); ++i) + if (gcd % nums[i] == 0) + return i; + + return -1; + } + + private: + int getGCD(const vector& nums) { + int gcd = nums[0]; + for (const int num : nums) + gcd = __gcd(gcd, num); + return gcd; + } +}; diff --git a/solutions/2344. Minimum Deletions to Make Array Divisible/2344.java b/solutions/2344. Minimum Deletions to Make Array Divisible/2344.java new file mode 100644 index 00000000000..55418d28383 --- /dev/null +++ b/solutions/2344. Minimum Deletions to Make Array Divisible/2344.java @@ -0,0 +1,24 @@ +class Solution { + public int minOperations(int[] nums, int[] numsDivide) { + final int gcd = getGCD(numsDivide); + + Arrays.sort(nums); + + for (int i = 0; i < nums.length; ++i) + if (gcd % nums[i] == 0) + return i; + + return -1; + } + + private int getGCD(int[] nums) { + int g = nums[0]; + for (final int num : nums) + g = gcd(g, num); + return g; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2344. Minimum Deletions to Make Array Divisible/2344.py b/solutions/2344. Minimum Deletions to Make Array Divisible/2344.py new file mode 100644 index 00000000000..b2a1cedb8b0 --- /dev/null +++ b/solutions/2344. Minimum Deletions to Make Array Divisible/2344.py @@ -0,0 +1,9 @@ +class Solution: + def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: + gcd = functools.reduce(math.gcd, numsDivide) + + for i, num in enumerate(sorted(nums)): + if gcd % num == 0: + return i + + return -1 diff --git a/solutions/2345. Finding the Number of Visible Mountains/2345-2.cpp b/solutions/2345. Finding the Number of Visible Mountains/2345-2.cpp new file mode 100644 index 00000000000..009d5111bf9 --- /dev/null +++ b/solutions/2345. Finding the Number of Visible Mountains/2345-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int visibleMountains(vector>& peaks) { + ranges::sort(peaks, [](const vector& a, const vector& b) { + const int leftFootA = a[0] - a[1]; + const int leftFootB = b[0] - b[1]; + return leftFootA != leftFootB ? leftFootA < leftFootB : a[0] > b[0]; + }); + + int maxRightFoot = 0; + int result = 0; + + for (int i = 0; i < peaks.size(); ++i) { + const bool overlapWithNext = + i + 1 < peaks.size() && peaks[i] == peaks[i + 1]; + const int currRightFoot = peaks[i][0] + peaks[i][1]; + if (currRightFoot > maxRightFoot) { + if (overlapWithNext == nullptr) + ++result; + maxRightFoot = currRightFoot; + } + } + + return result; + } +}; diff --git a/solutions/2345. Finding the Number of Visible Mountains/2345.cpp b/solutions/2345. Finding the Number of Visible Mountains/2345.cpp new file mode 100644 index 00000000000..4d9fb99d8b4 --- /dev/null +++ b/solutions/2345. Finding the Number of Visible Mountains/2345.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int visibleMountains(vector>& peaks) { + const vector> A = deDuplicates(peaks); + stack stack; + + for (int i = 0; i < A.size(); ++i) { + while (!stack.empty() && isHidden(A[stack.top()], A[i])) + stack.pop(); + if (!stack.empty() && isHidden(A[i], A[stack.top()])) + continue; + stack.push(i); + } + + return stack.size(); + } + + private: + vector> deDuplicates(const vector>& peaks) { + vector> A; + unordered_map, int, PairHash> count; + + for (const vector& peak : peaks) + ++count[{peak[0], peak[1]}]; + + for (const auto& [k, v] : count) + if (v == 1) + A.push_back(k); + + ranges::sort(A); + return A; + } + + bool isHidden(const pair& peak1, const pair& peak2) { + const auto& [x1, y1] = peak1; + const auto& [x2, y2] = peak2; + return x1 - y1 >= x2 - y2 && x1 + y1 <= x2 + y2; + } + + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/2345. Finding the Number of Visible Mountains/2345.java b/solutions/2345. Finding the Number of Visible Mountains/2345.java new file mode 100644 index 00000000000..bbe1727dbfc --- /dev/null +++ b/solutions/2345. Finding the Number of Visible Mountains/2345.java @@ -0,0 +1,39 @@ +class Solution { + public int visibleMountains(int[][] peaks) { + List> A = deDuplicates(peaks); + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < A.size(); ++i) { + while (!stack.isEmpty() && isHidden(A.get(stack.peek()), A.get(i))) + stack.pop(); + if (!stack.isEmpty() && isHidden(A.get(i), A.get(stack.peek()))) + continue; + stack.push(i); + } + + return stack.size(); + } + + private List> deDuplicates(int[][] peaks) { + List> A = new ArrayList<>(); + Map, Integer> count = new HashMap<>(); + + for (int[] peak : peaks) + count.merge(new Pair<>(peak[0], peak[1]), 1, Integer::sum); + + for (Map.Entry, Integer> entry : count.entrySet()) + if (entry.getValue() == 1) + A.add(entry.getKey()); + + Collections.sort(A, Comparator.comparing(Pair::getKey)); + return A; + } + + boolean isHidden(Pair peak1, Pair peak2) { + final int x1 = peak1.getKey(); + final int y1 = peak1.getValue(); + final int x2 = peak2.getKey(); + final int y2 = peak2.getValue(); + return x1 - y1 >= x2 - y2 && x1 + y1 <= x2 + y2; + } +} diff --git a/solutions/2345. Finding the Number of Visible Mountains/2345.py b/solutions/2345. Finding the Number of Visible Mountains/2345.py new file mode 100644 index 00000000000..f3d1de416f8 --- /dev/null +++ b/solutions/2345. Finding the Number of Visible Mountains/2345.py @@ -0,0 +1,20 @@ +class Solution: + def visibleMountains(self, peaks: List[List[int]]) -> int: + count = collections.Counter((x, y) for x, y in peaks) + peaks = sorted([k for k, v in count.items() if v == 1]) + stack = [] + + # Returns True if `peak1` is hidden by `peak2` + def isHidden(peak1: List[int], peak2: List[int]) -> bool: + x1, y1 = peak1 + x2, y2 = peak2 + return x1 - y1 >= x2 - y2 and x1 + y1 <= x2 + y2 + + for i, peak in enumerate(peaks): + while stack and isHidden(peaks[stack[-1]], peak): + stack.pop() + if stack and isHidden(peak, peaks[stack[-1]]): + continue + stack.append(i) + + return len(stack) diff --git a/solutions/2346. Compute the Rank as a Percentage/2346.sql b/solutions/2346. Compute the Rank as a Percentage/2346.sql new file mode 100644 index 00000000000..2950ad76a57 --- /dev/null +++ b/solutions/2346. Compute the Rank as a Percentage/2346.sql @@ -0,0 +1,11 @@ +SELECT + student_id, + department_id, + ROUND( + 100 * PERCENT_RANK() OVER( + PARTITION BY department_id + ORDER BY mark DESC + ), + 2 + ) AS percentage +FROM Students; diff --git a/solutions/2347. Best Poker Hand/2347.cpp b/solutions/2347. Best Poker Hand/2347.cpp new file mode 100644 index 00000000000..ff6eb710626 --- /dev/null +++ b/solutions/2347. Best Poker Hand/2347.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string bestHand(vector& ranks, vector& suits) { + if (ranges::all_of(suits, + [&suits](const char suit) { return suit == suits[0]; })) + return "Flush"; + + constexpr int kMax = 13; + vector count(kMax + 1); + + for (const int rank : ranks) + ++count[rank]; + + const int mx = ranges::max(count); + if (mx > 2) + return "Three of a Kind"; + if (mx == 2) + return "Pair"; + return "High Card"; + } +}; diff --git a/solutions/2347. Best Poker Hand/2347.java b/solutions/2347. Best Poker Hand/2347.java new file mode 100644 index 00000000000..34fbb72462c --- /dev/null +++ b/solutions/2347. Best Poker Hand/2347.java @@ -0,0 +1,19 @@ +class Solution { + public String bestHand(int[] ranks, char[] suits) { + if (new String(suits).chars().allMatch(s -> s == suits[0])) + return "Flush"; + + final int kMax = 13; + int[] count = new int[kMax + 1]; + + for (final int rank : ranks) + ++count[rank]; + + final int mx = Arrays.stream(count).max().getAsInt(); + if (mx > 2) + return "Three of a Kind"; + if (mx == 2) + return "Pair"; + return "High Card"; + } +} diff --git a/solutions/2347. Best Poker Hand/2347.py b/solutions/2347. Best Poker Hand/2347.py new file mode 100644 index 00000000000..7edecd9fd4d --- /dev/null +++ b/solutions/2347. Best Poker Hand/2347.py @@ -0,0 +1,12 @@ +class Solution: + def bestHand(self, ranks: List[int], suits: List[str]) -> str: + if all(suit == suits[0] for suit in suits): + return 'Flush' + + match max(Counter(ranks).values()): + case 5 | 4 | 3: + return 'Three of a Kind' + case 2: + return 'Pair' + case _: + return 'High Card' diff --git a/solutions/2348. Number of Zero-Filled Subarrays/2348.cpp b/solutions/2348. Number of Zero-Filled Subarrays/2348.cpp new file mode 100644 index 00000000000..96c445a6aee --- /dev/null +++ b/solutions/2348. Number of Zero-Filled Subarrays/2348.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + long long zeroFilledSubarray(vector& nums) { + long ans = 0; + int indexBeforeZero = -1; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i]) + indexBeforeZero = i; + else + ans += i - indexBeforeZero; + + return ans; + } +}; diff --git a/solutions/2348. Number of Zero-Filled Subarrays/2348.java b/solutions/2348. Number of Zero-Filled Subarrays/2348.java new file mode 100644 index 00000000000..1740e02e528 --- /dev/null +++ b/solutions/2348. Number of Zero-Filled Subarrays/2348.java @@ -0,0 +1,14 @@ +class Solution { + public long zeroFilledSubarray(int[] nums) { + long ans = 0; + int indexBeforeZero = -1; + + for (int i = 0; i < nums.length; ++i) + if (nums[i] == 0) + ans += i - indexBeforeZero; + else + indexBeforeZero = i; + + return ans; + } +} diff --git a/solutions/2348. Number of Zero-Filled Subarrays/2348.py b/solutions/2348. Number of Zero-Filled Subarrays/2348.py new file mode 100644 index 00000000000..cc1e608dbbf --- /dev/null +++ b/solutions/2348. Number of Zero-Filled Subarrays/2348.py @@ -0,0 +1,12 @@ +class Solution: + def zeroFilledSubarray(self, nums: List[int]) -> int: + ans = 0 + indexBeforeZero = -1 + + for i, num in enumerate(nums): + if num: + indexBeforeZero = i + else: + ans += i - indexBeforeZero + + return ans diff --git a/solutions/2349. Design a Number Container System/2349.cpp b/solutions/2349. Design a Number Container System/2349.cpp new file mode 100644 index 00000000000..93b9ffd0f71 --- /dev/null +++ b/solutions/2349. Design a Number Container System/2349.cpp @@ -0,0 +1,26 @@ +class NumberContainers { + public: + void change(int index, int number) { + const auto it = indexToNumber.find(index); + if (it != indexToNumber.cend()) { + const int originalNumber = it->second; + auto& indices = numberToIndices[originalNumber]; + indices.erase(index); + if (indices.empty()) + numberToIndices.erase(originalNumber); + } + numberToIndices[number].insert(index); + } + + int find(int number) { + const auto it = numberToIndices.find(number); + if (it == numberToIndices.cend()) + return -1; + const auto& indices = it->second; + return *indices.begin(); + } + + private: + unordered_map indexToNumber; + unordered_map> numberToIndices; +}; diff --git a/solutions/2349. Design a Number Container System/2349.java b/solutions/2349. Design a Number Container System/2349.java new file mode 100644 index 00000000000..5e0e838b34d --- /dev/null +++ b/solutions/2349. Design a Number Container System/2349.java @@ -0,0 +1,22 @@ +class NumberContainers { + public void change(int index, int number) { + if (indexToNumbers.containsKey(index)) { + final int originalNumber = indexToNumbers.get(index); + numberToIndices.get(originalNumber).remove(index); + if (numberToIndices.get(originalNumber).isEmpty()) + numberToIndices.remove(originalNumber); + } + indexToNumbers.put(index, number); + numberToIndices.putIfAbsent(number, new TreeSet<>()); + numberToIndices.get(number).add(index); + } + + public int find(int number) { + if (numberToIndices.containsKey(number)) + return numberToIndices.get(number).first(); + return -1; + } + + private Map> numberToIndices = new HashMap<>(); + private Map indexToNumbers = new HashMap<>(); +} diff --git a/solutions/2349. Design a Number Container System/2349.py b/solutions/2349. Design a Number Container System/2349.py new file mode 100644 index 00000000000..ba58721eeae --- /dev/null +++ b/solutions/2349. Design a Number Container System/2349.py @@ -0,0 +1,21 @@ +from sortedcontainers import SortedSet + + +class NumberContainers: + def __init__(self): + self.numberToIndices = collections.defaultdict(SortedSet) + self.indexToNumber = {} + + def change(self, index: int, number: int) -> None: + if index in self.indexToNumber: + originalNumber = self.indexToNumber[index] + self.numberToIndices[originalNumber].remove(index) + if len(self.numberToIndices[originalNumber]) == 0: + del self.numberToIndices[originalNumber] + self.indexToNumber[index] = number + self.numberToIndices[number].add(index) + + def find(self, number: int) -> int: + if number in self.numberToIndices: + return self.numberToIndices[number][0] + return -1 diff --git a/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.cpp b/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.cpp new file mode 100644 index 00000000000..d4cf1403a3f --- /dev/null +++ b/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root->val > max(p->val, q->val)) + return lowestCommonAncestor(root->left, p, q); + if (root->val < min(p->val, q->val)) + return lowestCommonAncestor(root->right, p, q); + return root; + } +}; diff --git a/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.java b/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.java new file mode 100644 index 00000000000..bafccb8ac4f --- /dev/null +++ b/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.java @@ -0,0 +1,9 @@ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root.val > Math.max(p.val, q.val)) + return lowestCommonAncestor(root.left, p, q); + if (root.val < Math.min(p.val, q.val)) + return lowestCommonAncestor(root.right, p, q); + return root; + } +} diff --git a/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.py b/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.py new file mode 100644 index 00000000000..a6c70ba4d0d --- /dev/null +++ b/solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.py @@ -0,0 +1,7 @@ +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if root.val > max(p.val, q.val): + return self.lowestCommonAncestor(root.left, p, q) + if root.val < min(p.val, q.val): + return self.lowestCommonAncestor(root.right, p, q) + return root diff --git a/solutions/2350. Shortest Impossible Sequence of Rolls/2350.cpp b/solutions/2350. Shortest Impossible Sequence of Rolls/2350.cpp new file mode 100644 index 00000000000..7051ea64d8d --- /dev/null +++ b/solutions/2350. Shortest Impossible Sequence of Rolls/2350.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int shortestSequence(vector& rolls, int k) { + int ans = 1; // the the next target length + unordered_set seen; + + for (const int roll : rolls) { + seen.insert(roll); + if (seen.size() == k) { + // Have all combinations that form `ans` length, and we are going to + // extend the sequence to `ans + 1` length. + ++ans; + seen.clear(); + } + } + + return ans; + } +}; diff --git a/solutions/2350. Shortest Impossible Sequence of Rolls/2350.java b/solutions/2350. Shortest Impossible Sequence of Rolls/2350.java new file mode 100644 index 00000000000..c8427aa26f2 --- /dev/null +++ b/solutions/2350. Shortest Impossible Sequence of Rolls/2350.java @@ -0,0 +1,18 @@ +class Solution { + public int shortestSequence(int[] rolls, int k) { + int ans = 1; // the the next target length + Set seen = new HashSet<>(); + + for (final int roll : rolls) { + seen.add(roll); + if (seen.size() == k) { + // Have all combinations that form `ans` length, and we are going to + // extend the sequence to `ans + 1` length. + ++ans; + seen.clear(); + } + } + + return ans; + } +} diff --git a/solutions/2350. Shortest Impossible Sequence of Rolls/2350.py b/solutions/2350. Shortest Impossible Sequence of Rolls/2350.py new file mode 100644 index 00000000000..501cb49eb31 --- /dev/null +++ b/solutions/2350. Shortest Impossible Sequence of Rolls/2350.py @@ -0,0 +1,14 @@ +class Solution: + def shortestSequence(self, rolls: List[int], k: int) -> int: + ans = 1 # the the next target length + seen = set() + + for roll in rolls: + seen.add(roll) + if len(seen) == k: + # Have all combinations that form `ans` length, and we are going to + # extend the sequence to `ans + 1` length. + ans += 1 + seen.clear() + + return ans diff --git a/solutions/2351. First Letter to Appear Twice/2351.cpp b/solutions/2351. First Letter to Appear Twice/2351.cpp new file mode 100644 index 00000000000..0f943d5a259 --- /dev/null +++ b/solutions/2351. First Letter to Appear Twice/2351.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + char repeatedCharacter(string s) { + vector seen(26); + + for (const char c : s) { + if (seen[c - 'a']) + return c; + seen[c - 'a'] = true; + } + + throw; + } +}; diff --git a/solutions/2351. First Letter to Appear Twice/2351.java b/solutions/2351. First Letter to Appear Twice/2351.java new file mode 100644 index 00000000000..77f6e1b1cdd --- /dev/null +++ b/solutions/2351. First Letter to Appear Twice/2351.java @@ -0,0 +1,13 @@ +class Solution { + public char repeatedCharacter(String s) { + boolean[] seen = new boolean[26]; + + for (final char c : s.toCharArray()) { + if (seen[c - 'a']) + return c; + seen[c - 'a'] = true; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2351. First Letter to Appear Twice/2351.py b/solutions/2351. First Letter to Appear Twice/2351.py new file mode 100644 index 00000000000..c054c57418c --- /dev/null +++ b/solutions/2351. First Letter to Appear Twice/2351.py @@ -0,0 +1,8 @@ +class Solution: + def repeatedCharacter(self, s: str) -> str: + seen = [False] * 26 + + for c in s: + if seen[ord(c) - ord('a')]: + return c + seen[ord(c) - ord('a')] = True diff --git a/solutions/2352. Equal Row and Column Pairs/2352.cpp b/solutions/2352. Equal Row and Column Pairs/2352.cpp new file mode 100644 index 00000000000..c534f13f7dc --- /dev/null +++ b/solutions/2352. Equal Row and Column Pairs/2352.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int equalPairs(vector>& grid) { + const int n = grid.size(); + int ans = 0; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + int k = 0; + for (; k < n; ++k) + if (grid[i][k] != grid[k][j]) + break; + if (k == n) // R[i] == C[j] + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2352. Equal Row and Column Pairs/2352.java b/solutions/2352. Equal Row and Column Pairs/2352.java new file mode 100644 index 00000000000..f2b4235f47d --- /dev/null +++ b/solutions/2352. Equal Row and Column Pairs/2352.java @@ -0,0 +1,18 @@ +class Solution { + public int equalPairs(int[][] grid) { + final int n = grid.length; + int ans = 0; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + int k = 0; + for (; k < n; ++k) + if (grid[i][k] != grid[k][j]) + break; + if (k == n) // R[i] == C[j] + ++ans; + } + + return ans; + } +} diff --git a/solutions/2352. Equal Row and Column Pairs/2352.py b/solutions/2352. Equal Row and Column Pairs/2352.py new file mode 100644 index 00000000000..5aee75750d1 --- /dev/null +++ b/solutions/2352. Equal Row and Column Pairs/2352.py @@ -0,0 +1,16 @@ +class Solution: + def equalPairs(self, grid: List[List[int]]) -> int: + n = len(grid) + ans = 0 + + for i in range(n): + for j in range(n): + k = 0 + while k < n: + if grid[i][k] != grid[k][j]: + break + k += 1 + if k == n: # R[i] == C[j] + ans += 1 + + return ans diff --git a/solutions/2353. Design a Food Rating System/2353.cpp b/solutions/2353. Design a Food Rating System/2353.cpp new file mode 100644 index 00000000000..810b52db72e --- /dev/null +++ b/solutions/2353. Design a Food Rating System/2353.cpp @@ -0,0 +1,30 @@ +class FoodRatings { + public: + FoodRatings(vector& foods, vector& cuisines, + vector& ratings) { + for (int i = 0; i < foods.size(); ++i) { + cuisineToRatingAndFoods[cuisines[i]].insert({-ratings[i], foods[i]}); + foodToCuisine[foods[i]] = cuisines[i]; + foodToRating[foods[i]] = ratings[i]; + } + } + + void changeRating(string food, int newRating) { + const string cuisine = foodToCuisine[food]; + const int oldRating = foodToRating[food]; + auto& ratingAndFoods = cuisineToRatingAndFoods[cuisine]; + ratingAndFoods.erase({-oldRating, food}); + ratingAndFoods.insert({-newRating, food}); + foodToRating[food] = newRating; + } + + string highestRated(string cuisine) { + return cuisineToRatingAndFoods[cuisine].begin()->second; + } + + private: + // {cuisine: {(-rating, food)}} stores negative rating for smarter comparison + unordered_map>> cuisineToRatingAndFoods; + unordered_map foodToCuisine; + unordered_map foodToRating; +}; diff --git a/solutions/2353. Design a Food Rating System/2353.java b/solutions/2353. Design a Food Rating System/2353.java new file mode 100644 index 00000000000..1dfdcdbba54 --- /dev/null +++ b/solutions/2353. Design a Food Rating System/2353.java @@ -0,0 +1,32 @@ +class FoodRatings { + public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { + for (int i = 0; i < foods.length; ++i) { + cuisineToRatingAndFoods.putIfAbsent( + cuisines[i], + new TreeSet<>((a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue().compareTo(b.getValue()) + : b.getKey() - a.getKey())); + cuisineToRatingAndFoods.get(cuisines[i]).add(new Pair<>(ratings[i], foods[i])); + foodToCuisine.put(foods[i], cuisines[i]); + foodToRating.put(foods[i], ratings[i]); + } + } + + public void changeRating(String food, int newRating) { + final String cuisine = foodToCuisine.get(food); + final int oldRating = foodToRating.get(food); + TreeSet> ratingAndFoods = cuisineToRatingAndFoods.get(cuisine); + ratingAndFoods.remove(new Pair<>(oldRating, food)); + ratingAndFoods.add(new Pair<>(newRating, food)); + foodToRating.put(food, newRating); + } + + public String highestRated(String cuisine) { + return cuisineToRatingAndFoods.get(cuisine).first().getValue(); + } + + // {cuisine: {(rating, food)}} + Map>> cuisineToRatingAndFoods = new HashMap<>(); + Map foodToCuisine = new HashMap<>(); + Map foodToRating = new HashMap<>(); +} diff --git a/solutions/2353. Design a Food Rating System/2353.py b/solutions/2353. Design a Food Rating System/2353.py new file mode 100644 index 00000000000..0a98c196348 --- /dev/null +++ b/solutions/2353. Design a Food Rating System/2353.py @@ -0,0 +1,25 @@ +from sortedcontainers import SortedSet + + +class FoodRatings: + def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]): + self.cuisineToRatingAndFoods = collections.defaultdict( + lambda: SortedSet(key=lambda x: (-x[0], x[1]))) + self.foodToCuisine = {} + self.foodToRating = {} + + for food, cuisine, rating in zip(foods, cuisines, ratings): + self.cuisineToRatingAndFoods[cuisine].add((rating, food)) + self.foodToCuisine[food] = cuisine + self.foodToRating[food] = rating + + def changeRating(self, food: str, newRating: int) -> None: + cuisine = self.foodToCuisine[food] + oldRating = self.foodToRating[food] + ratingAndFoods = self.cuisineToRatingAndFoods[cuisine] + ratingAndFoods.remove((oldRating, food)) + ratingAndFoods.add((newRating, food)) + self.foodToRating[food] = newRating + + def highestRated(self, cuisine: str) -> str: + return self.cuisineToRatingAndFoods[cuisine][0][1] diff --git a/solutions/2354. Number of Excellent Pairs/2354.cpp b/solutions/2354. Number of Excellent Pairs/2354.cpp new file mode 100644 index 00000000000..cdbd81e0040 --- /dev/null +++ b/solutions/2354. Number of Excellent Pairs/2354.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + long long countExcellentPairs(vector& nums, int k) { + constexpr int kMaxBit = 30; + // bits(num1 | num2) + bits(num1 & num2) = bits(num1) + bits(num2) + long ans = 0; + vector count(kMaxBit); + + for (const unsigned num : unordered_set(nums.begin(), nums.end())) + ++count[popcount(num)]; + + for (int i = 0; i < kMaxBit; ++i) + for (int j = 0; j < kMaxBit; ++j) + if (i + j >= k) + ans += count[i] * count[j]; + + return ans; + } +}; diff --git a/solutions/2354. Number of Excellent Pairs/2354.java b/solutions/2354. Number of Excellent Pairs/2354.java new file mode 100644 index 00000000000..d0426309a24 --- /dev/null +++ b/solutions/2354. Number of Excellent Pairs/2354.java @@ -0,0 +1,18 @@ +class Solution { + public long countExcellentPairs(int[] nums, int k) { + final int kMaxBit = 30; + // bits(num1 | num2) + bits(num1 & num2) = bits(num1) + bits(num2) + long ans = 0; + long[] count = new long[kMaxBit]; + + for (final int num : Arrays.stream(nums).boxed().collect(Collectors.toSet())) + ++count[Integer.bitCount(num)]; + + for (int i = 0; i < kMaxBit; ++i) + for (int j = 0; j < kMaxBit; ++j) + if (i + j >= k) + ans += count[i] * count[j]; + + return ans; + } +} diff --git a/solutions/2354. Number of Excellent Pairs/2354.py b/solutions/2354. Number of Excellent Pairs/2354.py new file mode 100644 index 00000000000..4472d12d042 --- /dev/null +++ b/solutions/2354. Number of Excellent Pairs/2354.py @@ -0,0 +1,7 @@ +class Solution: + def countExcellentPairs(self, nums: List[int], k: int) -> int: + count = collections.Counter(map(int.bit_count, set(nums))) + return sum(count[i] * count[j] + for i in count + for j in count + if i + j >= k) diff --git a/solutions/2355. Maximum Number of Books You Can Take/2355.cpp b/solutions/2355. Maximum Number of Books You Can Take/2355.cpp new file mode 100644 index 00000000000..2efe8dc3b4d --- /dev/null +++ b/solutions/2355. Maximum Number of Books You Can Take/2355.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + long long maximumBooks(vector& books) { + // dp[i] := the maximum number of books we can take from books[0..i] with + // taking all of books[i] + vector dp(books.size()); + stack stack; // the possible indices we can reach + + for (int i = 0; i < books.size(); ++i) { + // We may take all of books[j], where books[j] < books[i] - (i - j). + while (!stack.empty() && + books[stack.top()] >= books[i] - (i - stack.top())) + stack.pop(); + // We can now take books[j + 1..i]. + const int j = stack.empty() ? -1 : stack.top(); + const int lastTook = books[i] - (i - j) + 1; + if (lastTook > 1) + // books[i] + (books[i] - 1) + ... + (books[i] - (i - j) + 1) + dp[i] = static_cast(books[i] + lastTook) * (i - j) / 2; + else + // 1 + 2 + ... + books[i] + dp[i] = static_cast(books[i]) * (books[i] + 1) / 2; + if (j >= 0) + dp[i] += dp[j]; + stack.push(i); + } + + return ranges::max(dp); + } +}; diff --git a/solutions/2355. Maximum Number of Books You Can Take/2355.java b/solutions/2355. Maximum Number of Books You Can Take/2355.java new file mode 100644 index 00000000000..6d67c3c27ec --- /dev/null +++ b/solutions/2355. Maximum Number of Books You Can Take/2355.java @@ -0,0 +1,28 @@ +class Solution { + public long maximumBooks(int[] books) { + // dp[i] := the maximum number of books we can take from books[0..i] with taking all of + // books[i] + long[] dp = new long[books.length]; + Deque stack = new ArrayDeque<>(); // the possible indices we can reach + + for (int i = 0; i < books.length; ++i) { + // We may take all of books[j], where books[j] < books[i] - (i - j). + while (!stack.isEmpty() && books[stack.peek()] >= books[i] - (i - stack.peek())) + stack.pop(); + // We can now take books[j + 1..i]. + final int j = stack.isEmpty() ? -1 : stack.peek(); + final int lastTook = books[i] - (i - j) + 1; + if (lastTook > 1) + // books[i] + (books[i] - 1) + ... + (books[i] - (i - j) + 1) + dp[i] = (long) (books[i] + lastTook) * (i - j) / 2; + else + // 1 + 2 + ... + books[i] + dp[i] = (long) books[i] * (books[i] + 1) / 2; + if (j >= 0) + dp[i] += dp[j]; + stack.push(i); + } + + return Arrays.stream(dp).max().getAsLong(); + } +} diff --git a/solutions/2355. Maximum Number of Books You Can Take/2355.py b/solutions/2355. Maximum Number of Books You Can Take/2355.py new file mode 100644 index 00000000000..ccf931e482c --- /dev/null +++ b/solutions/2355. Maximum Number of Books You Can Take/2355.py @@ -0,0 +1,25 @@ +class Solution: + def maximumBooks(self, books: List[int]) -> int: + # dp[i] := the maximum the number of books we can take from books[0..i] with taking all of + # books[i] + dp = [0] * len(books) + stack = [] # the possible indices we can reach + + for i, book in enumerate(books): + # We may take all of books[j], where books[j] < books[i] - (i - j). + while stack and books[stack[-1]] >= book - (i - stack[-1]): + stack.pop() + # We can now take books[j + 1..i]. + j = stack[-1] if stack else -1 + lastPicked = book - (i - j) + 1 + if lastPicked > 1: + # book + (book - 1) + ... + (book - (i - j) + 1) + dp[i] = (book + lastPicked) * (i - j) // 2 + else: + # 1 + 2 + ... + book + dp[i] = book * (book + 1) // 2 + if j >= 0: + dp[i] += dp[j] + stack.append(i) + + return max(dp) diff --git a/solutions/2356. Number of Unique Subjects Taught by Each Teacher/2356.sql b/solutions/2356. Number of Unique Subjects Taught by Each Teacher/2356.sql new file mode 100644 index 00000000000..1fc8355f2ec --- /dev/null +++ b/solutions/2356. Number of Unique Subjects Taught by Each Teacher/2356.sql @@ -0,0 +1,5 @@ +SELECT + teacher_id, + COUNT(DISTINCT subject_id) AS cnt +FROM Teacher +GROUP BY 1; diff --git a/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.cpp b/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.cpp new file mode 100644 index 00000000000..ef171372f23 --- /dev/null +++ b/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int minimumOperations(vector& nums) { + unordered_set seen(nums.begin(), nums.end()); + return seen.size() - seen.contains(0); + } +}; diff --git a/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.java b/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.java new file mode 100644 index 00000000000..33533a972d9 --- /dev/null +++ b/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.java @@ -0,0 +1,6 @@ +class Solution { + public int minimumOperations(int[] nums) { + Set seen = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + return seen.size() - (seen.contains(0) ? 1 : 0); + } +} diff --git a/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.py b/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.py new file mode 100644 index 00000000000..ac7e2fcf8c4 --- /dev/null +++ b/solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.py @@ -0,0 +1,3 @@ +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + return len(set(nums) - {0}) diff --git a/solutions/2358. Maximum Number of Groups Entering a Competition/2358.cpp b/solutions/2358. Maximum Number of Groups Entering a Competition/2358.cpp new file mode 100644 index 00000000000..34f008b7562 --- /dev/null +++ b/solutions/2358. Maximum Number of Groups Entering a Competition/2358.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maximumGroups(vector& grades) { + // Sort grades, then we can seperate the students into groups of sizes 1, 2, + // 3, ..., k, s.t. the i-th group < the (i + 1)-th group for both sum and + // size. So, we can rephrase the problem into: + // Find the maximum k s.t. 1 + 2 + 3 + ... + k <= n + + // 1 + 2 + 3 + ... + k <= n + // k(k + 1) / 2 <= n + // k^2 + k <= 2n + // (k + 0.5)^2 - 0.25 <= 2n + // (k + 0.5)^2 <= 2n + 0.25 + // k <= sqrt(2n + 0.25) - 0.5 + return sqrt(grades.size() * 2 + 0.25) - 0.5; + } +}; diff --git a/solutions/2358. Maximum Number of Groups Entering a Competition/2358.java b/solutions/2358. Maximum Number of Groups Entering a Competition/2358.java new file mode 100644 index 00000000000..05d33466d74 --- /dev/null +++ b/solutions/2358. Maximum Number of Groups Entering a Competition/2358.java @@ -0,0 +1,16 @@ +class Solution { + public int maximumGroups(int[] grades) { + // Sort grades, then we can seperate the students into groups of sizes 1, 2, + // 3, ..., k, s.t. the i-th group < the (i + 1)-th group for both sum and + // size. So, we can rephrase the problem into: + // Find the maximum k s.t. 1 + 2 + 3 + ... + k <= n + + // 1 + 2 + 3 + ... + k <= n + // k(k + 1) / 2 <= n + // k^2 + k <= 2n + // (k + 0.5)^2 - 0.25 <= 2n + // (k + 0.5)^2 <= 2n + 0.25 + // k <= sqrt(2n + 0.25) - 0.5 + return (int) (Math.sqrt(grades.length * 2 + 0.25) - 0.5); + } +} diff --git a/solutions/2358. Maximum Number of Groups Entering a Competition/2358.py b/solutions/2358. Maximum Number of Groups Entering a Competition/2358.py new file mode 100644 index 00000000000..a0fc0c20315 --- /dev/null +++ b/solutions/2358. Maximum Number of Groups Entering a Competition/2358.py @@ -0,0 +1,14 @@ +class Solution: + def maximumGroups(self, grades: List[int]) -> int: + # Sort grades, then we can seperate the students into groups of sizes 1, 2, + # 3, ..., k, s.t. the i-th group < the (i + 1)-th group for both sum and + # size. So, we can rephrase the problem into: + # Find the maximum k s.t. 1 + 2 + 3 + ... + k <= n + + # 1 + 2 + 3 + ... + k <= n + # k(k + 1) // 2 <= n + # k^2 + k <= 2n + # (k + 0.5)^2 - 0.25 <= 2n + # (k + 0.5)^2 <= 2n + 0.25 + # k <= sqrt(2n + 0.25) - 0.5 + return int(math.sqrt(len(grades) * 2 + 0.25) - 0.5) diff --git a/solutions/2359. Find Closest Node to Given Two Nodes/2359.cpp b/solutions/2359. Find Closest Node to Given Two Nodes/2359.cpp new file mode 100644 index 00000000000..6596792fe8c --- /dev/null +++ b/solutions/2359. Find Closest Node to Given Two Nodes/2359.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int closestMeetingNode(vector& edges, int node1, int node2) { + constexpr int kMax = 10000; + const vector dist1 = getDist(edges, node1); + const vector dist2 = getDist(edges, node2); + int minDist = kMax; + int ans = -1; + + for (int i = 0; i < edges.size(); ++i) + if (min(dist1[i], dist2[i]) >= 0) { + const int maxDist = max(dist1[i], dist2[i]); + if (maxDist < minDist) { + minDist = maxDist; + ans = i; + } + } + + return ans; + } + + private: + vector getDist(const vector& edges, int u) { + vector dist(edges.size(), -1); + int d = 0; + while (u != -1 && dist[u] == -1) { + dist[u] = d++; + u = edges[u]; + } + return dist; + } +}; diff --git a/solutions/2359. Find Closest Node to Given Two Nodes/2359.java b/solutions/2359. Find Closest Node to Given Two Nodes/2359.java new file mode 100644 index 00000000000..b9a5f76ccd8 --- /dev/null +++ b/solutions/2359. Find Closest Node to Given Two Nodes/2359.java @@ -0,0 +1,31 @@ +class Solution { + public int closestMeetingNode(int[] edges, int node1, int node2) { + final int kMax = 10000; + final int[] dist1 = getDist(edges, node1); + final int[] dist2 = getDist(edges, node2); + int minDist = kMax; + int ans = -1; + + for (int i = 0; i < edges.length; ++i) + if (Math.min(dist1[i], dist2[i]) >= 0) { + final int maxDist = Math.max(dist1[i], dist2[i]); + if (maxDist < minDist) { + minDist = maxDist; + ans = i; + } + } + + return ans; + } + + private int[] getDist(int[] edges, int u) { + int[] dist = new int[edges.length]; + Arrays.fill(dist, -1); + int d = 0; + while (u != -1 && dist[u] == -1) { + dist[u] = d++; + u = edges[u]; + } + return dist; + } +} diff --git a/solutions/2359. Find Closest Node to Given Two Nodes/2359.py b/solutions/2359. Find Closest Node to Given Two Nodes/2359.py new file mode 100644 index 00000000000..5fed5d53a2c --- /dev/null +++ b/solutions/2359. Find Closest Node to Given Two Nodes/2359.py @@ -0,0 +1,25 @@ +class Solution: + def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: + kMax = 10000 + dist1 = self._getDist(edges, node1) + dist2 = self._getDist(edges, node2) + minDist = kMax + ans = -1 + + for i, (d1, d2) in enumerate(zip(dist1, dist2)): + if min(d1, d2) >= 0: + maxDist = max(d1, d2) + if maxDist < minDist: + minDist = maxDist + ans = i + + return ans + + def _getDist(self, edges: List[int], u: int) -> List[int]: + dist = [-1] * len(edges) + d = 0 + while u != -1 and dist[u] == -1: + dist[u] = d + d += 1 + u = edges[u] + return dist diff --git a/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.cpp b/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.cpp new file mode 100644 index 00000000000..0d8764457c4 --- /dev/null +++ b/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + queue q_{{root}}; + unordered_map parent{{root, nullptr}}; + unordered_set ancestors; // p's ancestors + + // Iterate until we find both p and q. + while (!parent.contains(p) || !parent.contains(q)) { + root = q_.front(), q_.pop(); + if (root->left) { + parent[root->left] = root; + q_.push(root->left); + } + if (root->right) { + parent[root->right] = root; + q_.push(root->right); + } + } + + // Insert all the p's ancestors. + while (p) { + ancestors.insert(p); + p = parent[p]; // `p` becomes nullptr in the end. + } + + // Go up from q until we meet any of p's ancestors. + while (!ancestors.contains(q)) + q = parent[q]; + + return q; + } +}; diff --git a/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.java b/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.java new file mode 100644 index 00000000000..9e1591e18dc --- /dev/null +++ b/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.java @@ -0,0 +1,33 @@ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + Queue q_ = new ArrayDeque<>(Arrays.asList(root)); + Map parent = new HashMap<>(); + parent.put(root, null); + Set ancestors = new HashSet<>(); // p's ancestors + + // Iterate until we find both p and q. + while (!parent.containsKey(p) || !parent.containsKey(q)) { + root = q_.poll(); + if (root.left != null) { + parent.put(root.left, root); + q_.offer(root.left); + } + if (root.right != null) { + parent.put(root.right, root); + q_.offer(root.right); + } + } + + // Insert all the p's ancestors. + while (p != null) { + ancestors.add(p); + p = parent.get(p); // `p` becomes null in the end. + } + + // Go up from q until we meet any of p's ancestors. + while (!ancestors.contains(q)) + q = parent.get(q); + + return q; + } +} diff --git a/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.py b/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.py new file mode 100644 index 00000000000..ce66e351d2f --- /dev/null +++ b/solutions/236. Lowest Common Ancestor of a Binary Tree/236-2.py @@ -0,0 +1,26 @@ +class Solution: + def lowestCommonAncestor(self, root: Optional[TreeNode], p: Optional[TreeNode], q: Optional[TreeNode]) -> Optional[TreeNode]: + q_ = collections.deque([root]) + parent = {root: None} + ancestors = set() # p's ancestors + + # Iterate until we find both p and q. + while p not in parent or q not in parent: + root = q_.popleft() + if root.left: + parent[root.left] = root + q_.append(root.left) + if root.right: + parent[root.right] = root + q_.append(root.right) + + # Insert all the p's ancestors. + while p: + ancestors.add(p) + p = parent[p] # `p` becomes None in the end. + + # Go up from q until we meet any of p's ancestors. + while q not in ancestors: + q = parent[q] + + return q diff --git a/solutions/236. Lowest Common Ancestor of a Binary Tree/236.cpp b/solutions/236. Lowest Common Ancestor of a Binary Tree/236.cpp new file mode 100644 index 00000000000..608bbeb7306 --- /dev/null +++ b/solutions/236. Lowest Common Ancestor of a Binary Tree/236.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr || root == p || root == q) + return root; + TreeNode* left = lowestCommonAncestor(root->left, p, q); + TreeNode* right = lowestCommonAncestor(root->right, p, q); + if (left != nullptr && right != nullptr) + return root; + return left == nullptr ? right : left; + } +}; diff --git a/solutions/236. Lowest Common Ancestor of a Binary Tree/236.java b/solutions/236. Lowest Common Ancestor of a Binary Tree/236.java new file mode 100644 index 00000000000..094ad2c52f1 --- /dev/null +++ b/solutions/236. Lowest Common Ancestor of a Binary Tree/236.java @@ -0,0 +1,11 @@ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) + return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + if (left != null && right != null) + return root; + return left == null ? right : left; + } +} diff --git a/solutions/236. Lowest Common Ancestor of a Binary Tree/236.py b/solutions/236. Lowest Common Ancestor of a Binary Tree/236.py new file mode 100644 index 00000000000..bf3b300fa02 --- /dev/null +++ b/solutions/236. Lowest Common Ancestor of a Binary Tree/236.py @@ -0,0 +1,9 @@ +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if not root or root == p or root == q: + return root + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + if left and right: + return root + return left or right diff --git a/solutions/2360. Longest Cycle in a Graph/2360.cpp b/solutions/2360. Longest Cycle in a Graph/2360.cpp new file mode 100644 index 00000000000..6b425109dfb --- /dev/null +++ b/solutions/2360. Longest Cycle in a Graph/2360.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int longestCycle(vector& edges) { + int ans = -1; + int time = 1; + vector timeVisited(edges.size()); + + for (int i = 0; i < edges.size(); ++i) { + if (timeVisited[i]) + continue; + const int startTime = time; + int u = i; + while (u != -1 && !timeVisited[u]) { + timeVisited[u] = time++; + u = edges[u]; // Move to the next node. + } + if (u != -1 && timeVisited[u] >= startTime) + ans = max(ans, time - timeVisited[u]); + } + + return ans; + } +}; diff --git a/solutions/2360. Longest Cycle in a Graph/2360.java b/solutions/2360. Longest Cycle in a Graph/2360.java new file mode 100644 index 00000000000..2aff000aa78 --- /dev/null +++ b/solutions/2360. Longest Cycle in a Graph/2360.java @@ -0,0 +1,22 @@ +class Solution { + public int longestCycle(int[] edges) { + int ans = -1; + int time = 1; + int[] timeVisited = new int[edges.length]; + + for (int i = 0; i < edges.length; ++i) { + if (timeVisited[i] > 0) + continue; + final int startTime = time; + int u = i; + while (u != -1 && timeVisited[u] == 0) { + timeVisited[u] = time++; + u = edges[u]; // Move to the next node. + } + if (u != -1 && timeVisited[u] >= startTime) + ans = Math.max(ans, time - timeVisited[u]); + } + + return ans; + } +} diff --git a/solutions/2360. Longest Cycle in a Graph/2360.py b/solutions/2360. Longest Cycle in a Graph/2360.py new file mode 100644 index 00000000000..745d9ffa815 --- /dev/null +++ b/solutions/2360. Longest Cycle in a Graph/2360.py @@ -0,0 +1,19 @@ +class Solution: + def longestCycle(self, edges: List[int]) -> int: + ans = -1 + time = 1 + timeVisited = [0] * len(edges) + + for i, edge in enumerate(edges): + if timeVisited[i]: + continue + startTime = time + u = i + while u != -1 and not timeVisited[u]: + timeVisited[u] = time + time += 1 + u = edges[u] # Move to the next node. + if u != -1 and timeVisited[u] >= startTime: + ans = max(ans, time - timeVisited[u]) + + return ans diff --git a/solutions/2361. Minimum Costs Using the Train Line/2361.cpp b/solutions/2361. Minimum Costs Using the Train Line/2361.cpp new file mode 100644 index 00000000000..7e3e8145631 --- /dev/null +++ b/solutions/2361. Minimum Costs Using the Train Line/2361.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector minimumCosts(vector& regular, vector& express, + int expressCost) { + const int n = regular.size(); + vector ans(n); + // the minimum cost to reach the current stop in a regular route + long dpReg = 0; + // the minimum cost to reach the current stop in an express route + long dpExp = expressCost; + + for (int i = 0; i < n; ++i) { + const long prevReg = dpReg; + const long prevExp = dpExp; + dpReg = min(prevReg + regular[i], prevExp + 0 + regular[i]); + dpExp = min(prevReg + expressCost + express[i], prevExp + express[i]); + ans[i] = min(dpReg, dpExp); + } + + return ans; + } +}; diff --git a/solutions/2361. Minimum Costs Using the Train Line/2361.java b/solutions/2361. Minimum Costs Using the Train Line/2361.java new file mode 100644 index 00000000000..027a9bee5d3 --- /dev/null +++ b/solutions/2361. Minimum Costs Using the Train Line/2361.java @@ -0,0 +1,20 @@ +class Solution { + public long[] minimumCosts(int[] regular, int[] express, int expressCost) { + final int n = regular.length; + long[] ans = new long[n]; + // the minimum cost to reach the current stop in a regular route + long dpReg = 0; + // the minimum cost to reach the current stop in an express route + long dpExp = expressCost; + + for (int i = 0; i < n; ++i) { + final long prevReg = dpReg; + final long prevExp = dpExp; + dpReg = Math.min(prevReg + regular[i], prevExp + 0 + regular[i]); + dpExp = Math.min(prevReg + expressCost + express[i], prevExp + express[i]); + ans[i] = Math.min(dpReg, dpExp); + } + + return ans; + } +} diff --git a/solutions/2361. Minimum Costs Using the Train Line/2361.py b/solutions/2361. Minimum Costs Using the Train Line/2361.py new file mode 100644 index 00000000000..23b4707948d --- /dev/null +++ b/solutions/2361. Minimum Costs Using the Train Line/2361.py @@ -0,0 +1,17 @@ +class Solution: + def minimumCosts(self, regular: List[int], express: List[int], expressCost: int) -> List[int]: + n = len(regular) + ans = [0] * n + # the minimum cost to reach the current stop in a regular route + dpReg = 0 + # the minimum cost to reach the current stop in an express route + dpExp = expressCost + + for i in range(n): + prevReg = dpReg + prevExp = dpExp + dpReg = min(prevReg + regular[i], prevExp + 0 + regular[i]) + dpExp = min(prevReg + expressCost + express[i], prevExp + express[i]) + ans[i] = min(dpReg, dpExp) + + return ans diff --git a/solutions/2362. Generate the Invoice/2362.sql b/solutions/2362. Generate the Invoice/2362.sql new file mode 100644 index 00000000000..f19e8807cac --- /dev/null +++ b/solutions/2362. Generate the Invoice/2362.sql @@ -0,0 +1,21 @@ +WITH + HighestPriceInvoice AS ( + SELECT + Purchases.invoice_id, + SUM(Purchases.quantity * Products.price) AS price + FROM Purchases + INNER JOIN Products + USING (product_id) + GROUP BY 1 + ORDER BY 2 DESC, 1 + LIMIT 1 + ) +SELECT + Products.product_id, + Purchases.quantity, + Purchases.quantity * Products.price AS price +FROM HighestPriceInvoice +INNER JOIN Purchases + USING (invoice_id) +INNER JOIN Products + USING (product_id); \ No newline at end of file diff --git a/solutions/2363. Merge Similar Items/2363.cpp b/solutions/2363. Merge Similar Items/2363.cpp new file mode 100644 index 00000000000..30dca833719 --- /dev/null +++ b/solutions/2363. Merge Similar Items/2363.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector> mergeSimilarItems(vector>& items1, + vector>& items2) { + constexpr int kMax = 1000; + vector> ans; + vector count(kMax + 1); + + for (const vector& item : items1) + count[item[0]] += item[1]; + + for (const vector& item : items2) + count[item[0]] += item[1]; + + for (int i = 1; i <= kMax; ++i) + if (count[i]) + ans.push_back({i, count[i]}); + + return ans; + } +}; diff --git a/solutions/2363. Merge Similar Items/2363.java b/solutions/2363. Merge Similar Items/2363.java new file mode 100644 index 00000000000..048e8273250 --- /dev/null +++ b/solutions/2363. Merge Similar Items/2363.java @@ -0,0 +1,19 @@ +class Solution { + public List> mergeSimilarItems(int[][] items1, int[][] items2) { + final int kMax = 1000; + List> ans = new ArrayList<>(); + int[] count = new int[kMax + 1]; + + for (int[] item : items1) + count[item[0]] += item[1]; + + for (int[] item : items2) + count[item[0]] += item[1]; + + for (int i = 1; i <= kMax; ++i) + if (count[i] > 0) + ans.add(Arrays.asList(i, count[i])); + + return ans; + } +} diff --git a/solutions/2363. Merge Similar Items/2363.py b/solutions/2363. Merge Similar Items/2363.py new file mode 100644 index 00000000000..e9fd729e1a4 --- /dev/null +++ b/solutions/2363. Merge Similar Items/2363.py @@ -0,0 +1,3 @@ +class Solution: + def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: + return sorted((Counter(dict(items1)) + collections.Counter(dict(items2))).items()) diff --git a/solutions/2364. Count Number of Bad Pairs/2364.cpp b/solutions/2364. Count Number of Bad Pairs/2364.cpp new file mode 100644 index 00000000000..ba859e14031 --- /dev/null +++ b/solutions/2364. Count Number of Bad Pairs/2364.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long countBadPairs(vector& nums) { + long ans = 0; + unordered_map count; // (nums[i] - i) + + for (int i = 0; i < nums.size(); ++i) + // count[nums[i] - i] := the number of good pairs + // i - count[nums[i] - i] := the number of bad pairs + ans += i - count[nums[i] - i]++; + + return ans; + } +}; diff --git a/solutions/2364. Count Number of Bad Pairs/2364.java b/solutions/2364. Count Number of Bad Pairs/2364.java new file mode 100644 index 00000000000..aa98aa1355a --- /dev/null +++ b/solutions/2364. Count Number of Bad Pairs/2364.java @@ -0,0 +1,15 @@ +class Solution { + public long countBadPairs(int[] nums) { + long ans = 0; + Map count = new HashMap<>(); // (nums[i] - i) + + for (int i = 0; i < nums.length; ++i) { + // count[nums[i] - i] := the number of good pairs + // i - count[nums[i] - i] := the number of bad pairs + ans += i - count.getOrDefault(nums[i] - i, 0L); + count.merge(nums[i] - i, 1L, Long::sum); + } + + return ans; + } +} diff --git a/solutions/2364. Count Number of Bad Pairs/2364.py b/solutions/2364. Count Number of Bad Pairs/2364.py new file mode 100644 index 00000000000..43e49c7bbcb --- /dev/null +++ b/solutions/2364. Count Number of Bad Pairs/2364.py @@ -0,0 +1,12 @@ +class Solution: + def countBadPairs(self, nums: List[int]) -> int: + ans = 0 + count = collections.Counter() # (nums[i] - i) + + for i, num in enumerate(nums): + # count[nums[i] - i] := the number of good pairs + # i - count[nums[i] - i] := the number of bad pairs + ans += i - count[num - i] + count[num - i] += 1 + + return ans diff --git a/solutions/2365. Task Scheduler II/2365.cpp b/solutions/2365. Task Scheduler II/2365.cpp new file mode 100644 index 00000000000..81969bc69d9 --- /dev/null +++ b/solutions/2365. Task Scheduler II/2365.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long taskSchedulerII(vector& tasks, int space) { + unordered_map taskToNextAvailable; + long ans = 0; + + for (const int task : tasks) { + ans = max(ans + 1, taskToNextAvailable[task]); + taskToNextAvailable[task] = ans + space + 1; + } + + return ans; + } +}; diff --git a/solutions/2365. Task Scheduler II/2365.java b/solutions/2365. Task Scheduler II/2365.java new file mode 100644 index 00000000000..985b329ea6b --- /dev/null +++ b/solutions/2365. Task Scheduler II/2365.java @@ -0,0 +1,13 @@ +class Solution { + public long taskSchedulerII(int[] tasks, int space) { + Map taskToNextAvailable = new HashMap<>(); + long ans = 0; + + for (final int task : tasks) { + ans = Math.max(ans + 1, taskToNextAvailable.getOrDefault(task, 0L)); + taskToNextAvailable.put(task, ans + space + 1); + } + + return ans; + } +} diff --git a/solutions/2365. Task Scheduler II/2365.py b/solutions/2365. Task Scheduler II/2365.py new file mode 100644 index 00000000000..2b4bf384f7e --- /dev/null +++ b/solutions/2365. Task Scheduler II/2365.py @@ -0,0 +1,10 @@ +class Solution: + def taskSchedulerII(self, tasks: List[int], space: int) -> int: + taskToNextAvailable = collections.defaultdict(int) + ans = 0 + + for task in tasks: + ans = max(ans + 1, taskToNextAvailable[task]) + taskToNextAvailable[task] = ans + space + 1 + + return ans diff --git a/solutions/2366. Minimum Replacements to Sort the Array/2366.cpp b/solutions/2366. Minimum Replacements to Sort the Array/2366.cpp new file mode 100644 index 00000000000..4072fc2ab0f --- /dev/null +++ b/solutions/2366. Minimum Replacements to Sort the Array/2366.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + long long minimumReplacement(vector& nums) { + long ans = 0; + int mx = nums.back(); + + for (int i = nums.size() - 2; i >= 0; --i) { + const int ops = (nums[i] - 1) / mx; + ans += ops; + mx = nums[i] / (ops + 1); + } + + return ans; + } +}; diff --git a/solutions/2366. Minimum Replacements to Sort the Array/2366.java b/solutions/2366. Minimum Replacements to Sort the Array/2366.java new file mode 100644 index 00000000000..153984f8293 --- /dev/null +++ b/solutions/2366. Minimum Replacements to Sort the Array/2366.java @@ -0,0 +1,14 @@ +class Solution { + public long minimumReplacement(int[] nums) { + long ans = 0; + int mx = nums[nums.length - 1]; + + for (int i = nums.length - 2; i >= 0; --i) { + final int ops = (nums[i] - 1) / mx; + ans += ops; + mx = nums[i] / (ops + 1); + } + + return ans; + } +} diff --git a/solutions/2366. Minimum Replacements to Sort the Array/2366.py b/solutions/2366. Minimum Replacements to Sort the Array/2366.py new file mode 100644 index 00000000000..15ca47957b1 --- /dev/null +++ b/solutions/2366. Minimum Replacements to Sort the Array/2366.py @@ -0,0 +1,11 @@ +class Solution: + def minimumReplacement(self, nums: List[int]) -> int: + ans = 0 + mx = nums[-1] + + for i in range(len(nums) - 2, -1, -1): + ops = (nums[i] - 1) // mx + ans += ops + mx = nums[i] // (ops + 1) + + return ans diff --git a/solutions/2367. Number of Arithmetic Triplets/2367.cpp b/solutions/2367. Number of Arithmetic Triplets/2367.cpp new file mode 100644 index 00000000000..5017da1fe5c --- /dev/null +++ b/solutions/2367. Number of Arithmetic Triplets/2367.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int arithmeticTriplets(vector& nums, int diff) { + constexpr int kMax = 200; + int ans = 0; + vector count(kMax + 1); + + for (const int num : nums) { + if (num >= 2 * diff && count[num - diff] && count[num - 2 * diff]) + ++ans; + count[num] = true; + } + + return ans; + } +}; diff --git a/solutions/2367. Number of Arithmetic Triplets/2367.java b/solutions/2367. Number of Arithmetic Triplets/2367.java new file mode 100644 index 00000000000..602c8f827b1 --- /dev/null +++ b/solutions/2367. Number of Arithmetic Triplets/2367.java @@ -0,0 +1,15 @@ +class Solution { + public int arithmeticTriplets(int[] nums, int diff) { + final int kMax = 200; + int ans = 0; + boolean[] count = new boolean[kMax + 1]; + + for (final int num : nums) { + if (num >= 2 * diff && count[num - diff] && count[num - 2 * diff]) + ++ans; + count[num] = true; + } + + return ans; + } +} diff --git a/solutions/2367. Number of Arithmetic Triplets/2367.py b/solutions/2367. Number of Arithmetic Triplets/2367.py new file mode 100644 index 00000000000..3a7d84aa5a5 --- /dev/null +++ b/solutions/2367. Number of Arithmetic Triplets/2367.py @@ -0,0 +1,12 @@ +class Solution: + def arithmeticTriplets(self, nums: List[int], diff: int) -> int: + kMax = 200 + ans = 0 + count = [False] * (kMax + 1) + + for num in nums: + if num >= 2 * diff and count[num - diff] and count[num - 2 * diff]: + ans += 1 + count[num] = True + + return ans diff --git a/solutions/2368. Reachable Nodes With Restrictions/2368.cpp b/solutions/2368. Reachable Nodes With Restrictions/2368.cpp new file mode 100644 index 00000000000..d56234ec58a --- /dev/null +++ b/solutions/2368. Reachable Nodes With Restrictions/2368.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int reachableNodes(int n, vector>& edges, + vector& restricted) { + vector> tree(n); + vector seen(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + for (const int r : restricted) + seen[r] = true; + + return dfs(tree, 0, seen); + } + + private: + int dfs(const vector>& tree, int u, vector& seen) { + if (seen[u]) + return 0; + + seen[u] = true; + int ans = 1; + + for (const int v : tree[u]) + ans += dfs(tree, v, seen); + + return ans; + } +}; diff --git a/solutions/2368. Reachable Nodes With Restrictions/2368.java b/solutions/2368. Reachable Nodes With Restrictions/2368.java new file mode 100644 index 00000000000..2be079850f9 --- /dev/null +++ b/solutions/2368. Reachable Nodes With Restrictions/2368.java @@ -0,0 +1,34 @@ +class Solution { + public int reachableNodes(int n, int[][] edges, int[] restricted) { + List[] tree = new List[n]; + boolean[] seen = new boolean[n]; + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + for (final int r : restricted) + seen[r] = true; + + return dfs(tree, 0, seen); + } + + private int dfs(List[] tree, int u, boolean[] seen) { + if (seen[u]) + return 0; + + seen[u] = true; + int ans = 1; + + for (final int v : tree[u]) + ans += dfs(tree, v, seen); + + return ans; + } +} diff --git a/solutions/2368. Reachable Nodes With Restrictions/2368.py b/solutions/2368. Reachable Nodes With Restrictions/2368.py new file mode 100644 index 00000000000..ea21f10ad5d --- /dev/null +++ b/solutions/2368. Reachable Nodes With Restrictions/2368.py @@ -0,0 +1,16 @@ +class Solution: + def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: + tree = [[] for _ in range(n)] + seen = set(restricted) + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def dfs(u: int) -> int: + if u in seen: + return 0 + seen.add(u) + return 1 + sum(dfs(v) for v in tree[u]) + + return dfs(0) diff --git a/solutions/2369. Check if There is a Valid Partition For The Array/2369.cpp b/solutions/2369. Check if There is a Valid Partition For The Array/2369.cpp new file mode 100644 index 00000000000..dbba267f30d --- /dev/null +++ b/solutions/2369. Check if There is a Valid Partition For The Array/2369.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool validPartition(vector& nums) { + const int n = nums.size(); + // dp[i] := true if there's a valid partition for the first i numbers + vector dp(n + 1); + dp[0] = true; + dp[2] = nums[0] == nums[1]; + + for (int i = 3; i <= n; ++i) + dp[i] = (dp[i - 2] && nums[i - 2] == nums[i - 1]) || + (dp[i - 3] && + ((nums[i - 3] == nums[i - 2] && nums[i - 2] == nums[i - 1]) || + (nums[i - 3] + 1 == nums[i - 2] && + nums[i - 2] + 1 == nums[i - 1]))); + + return dp[n]; + } +}; diff --git a/solutions/2369. Check if There is a Valid Partition For The Array/2369.java b/solutions/2369. Check if There is a Valid Partition For The Array/2369.java new file mode 100644 index 00000000000..a9f81171490 --- /dev/null +++ b/solutions/2369. Check if There is a Valid Partition For The Array/2369.java @@ -0,0 +1,16 @@ +class Solution { + public boolean validPartition(int[] nums) { + final int n = nums.length; + // dp[i] := true if there's a valid partition for the first i numbers + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + dp[2] = nums[0] == nums[1]; + + for (int i = 3; i <= n; ++i) + dp[i] = (dp[i - 2] && nums[i - 2] == nums[i - 1]) || + (dp[i - 3] && ((nums[i - 3] == nums[i - 2] && nums[i - 2] == nums[i - 1]) || + (nums[i - 3] + 1 == nums[i - 2] && nums[i - 2] + 1 == nums[i - 1]))); + + return dp[n]; + } +} diff --git a/solutions/2369. Check if There is a Valid Partition For The Array/2369.py b/solutions/2369. Check if There is a Valid Partition For The Array/2369.py new file mode 100644 index 00000000000..9a534999863 --- /dev/null +++ b/solutions/2369. Check if There is a Valid Partition For The Array/2369.py @@ -0,0 +1,14 @@ +class Solution: + def validPartition(self, nums: List[int]) -> bool: + n = len(nums) + # dp[i] := True if there's a valid partition for the first i numbers + dp = [False] * (n + 1) + dp[0] = True + dp[2] = nums[0] == nums[1] + + for i in range(3, n + 1): + dp[i] = (dp[i - 2] and nums[i - 2] == nums[i - 1]) or \ + (dp[i - 3] and ((nums[i - 3] == nums[i - 2] and nums[i - 2] == nums[i - 1]) or + (nums[i - 3] + 1 == nums[i - 2] and nums[i - 2] + 1 == nums[i - 1]))) + + return dp[n] diff --git a/solutions/237. Delete Node in a Linked List/237.cpp b/solutions/237. Delete Node in a Linked List/237.cpp new file mode 100644 index 00000000000..7ff80635e9f --- /dev/null +++ b/solutions/237. Delete Node in a Linked List/237.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + void deleteNode(ListNode* node) { + node->val = node->next->val; + node->next = node->next->next; + } +}; diff --git a/solutions/237. Delete Node in a Linked List/237.java b/solutions/237. Delete Node in a Linked List/237.java new file mode 100644 index 00000000000..057afffafad --- /dev/null +++ b/solutions/237. Delete Node in a Linked List/237.java @@ -0,0 +1,6 @@ +class Solution { + public void deleteNode(ListNode node) { + node.val = node.next.val; + node.next = node.next.next; + } +} diff --git a/solutions/237. Delete Node in a Linked List/237.py b/solutions/237. Delete Node in a Linked List/237.py new file mode 100644 index 00000000000..8a20de9b5d6 --- /dev/null +++ b/solutions/237. Delete Node in a Linked List/237.py @@ -0,0 +1,4 @@ +class Solution: + def deleteNode(self, node): + node.val = node.next.val + node.next = node.next.next diff --git a/solutions/2370. Longest Ideal Subsequence/2370.cpp b/solutions/2370. Longest Ideal Subsequence/2370.cpp new file mode 100644 index 00000000000..6fd64977308 --- /dev/null +++ b/solutions/2370. Longest Ideal Subsequence/2370.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int longestIdealString(string s, int k) { + // dp[i] := the longest subsequence that ends in ('a' + i) + vector dp(26); + + for (const char c : s) { + const int i = c - 'a'; + dp[i] = 1 + getMaxReachable(dp, i, k); + } + + return ranges::max(dp); + } + + private: + int getMaxReachable(const vector& dp, int i, int k) { + const int first = max(0, i - k); + const int last = min(25, i + k); + int maxReachable = 0; + for (int j = first; j <= last; ++j) + maxReachable = max(maxReachable, dp[j]); + return maxReachable; + } +}; diff --git a/solutions/2370. Longest Ideal Subsequence/2370.java b/solutions/2370. Longest Ideal Subsequence/2370.java new file mode 100644 index 00000000000..24dd08477cc --- /dev/null +++ b/solutions/2370. Longest Ideal Subsequence/2370.java @@ -0,0 +1,22 @@ +class Solution { + public int longestIdealString(String s, int k) { + // dp[i] := the longest subsequence that ends in ('a' + i) + int[] dp = new int[26]; + + for (final char c : s.toCharArray()) { + final int i = c - 'a'; + dp[i] = 1 + getMaxReachable(dp, i, k); + } + + return Arrays.stream(dp).max().getAsInt(); + } + + private int getMaxReachable(int[] dp, int i, int k) { + final int first = Math.max(0, i - k); + final int last = Math.min(25, i + k); + int maxReachable = 0; + for (int j = first; j <= last; ++j) + maxReachable = Math.max(maxReachable, dp[j]); + return maxReachable; + } +} diff --git a/solutions/2370. Longest Ideal Subsequence/2370.py b/solutions/2370. Longest Ideal Subsequence/2370.py new file mode 100644 index 00000000000..e63cef8061e --- /dev/null +++ b/solutions/2370. Longest Ideal Subsequence/2370.py @@ -0,0 +1,18 @@ +class Solution: + def longestIdealString(self, s: str, k: int) -> int: + # dp[i] := the longest subsequence that ends in ('a' + i) + dp = [0] * 26 + + for c in s: + i = ord(c) - ord('a') + dp[i] = 1 + self._getMaxReachable(dp, i, k) + + return max(dp) + + def _getMaxReachable(self, dp: List[int], i: int, k: int) -> int: + first = max(0, i - k) + last = min(25, i + k) + maxReachable = 0 + for j in range(first, last + 1): + maxReachable = max(maxReachable, dp[j]) + return maxReachable diff --git a/solutions/2371. Minimize Maximum Value in a Grid/2371.cpp b/solutions/2371. Minimize Maximum Value in a Grid/2371.cpp new file mode 100644 index 00000000000..a26d6d06d5e --- /dev/null +++ b/solutions/2371. Minimize Maximum Value in a Grid/2371.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> minScore(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector> ans(m, vector(n)); + vector> valAndIndices; + vector rows(m); // rows[i] := the maximum used number so far + vector cols(n); // cols[j] := the maximum used number so far + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + valAndIndices.push_back({grid[i][j], i, j}); + + ranges::sort(valAndIndices); + + for (const auto& [_, i, j] : valAndIndices) { + const int nextAvailable = max(rows[i], cols[j]) + 1; + ans[i][j] = nextAvailable; + rows[i] = nextAvailable; + cols[j] = nextAvailable; + } + + return ans; + } +}; diff --git a/solutions/2371. Minimize Maximum Value in a Grid/2371.java b/solutions/2371. Minimize Maximum Value in a Grid/2371.java new file mode 100644 index 00000000000..16fe9e4c024 --- /dev/null +++ b/solutions/2371. Minimize Maximum Value in a Grid/2371.java @@ -0,0 +1,32 @@ +class Solution { + public int[][] minScore(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[][] ans = new int[m][n]; + List valAndIndices = new ArrayList<>(); + int[] rows = new int[m]; // rows[i] := the maximum used number so far + int[] cols = new int[n]; // cols[j] := the maximum used number so far + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + valAndIndices.add(new int[] {grid[i][j], i, j}); + + Collections.sort(valAndIndices, new Comparator() { + @Override + public int compare(int[] a, int[] b) { + return Integer.compare(a[0], b[0]); + } + }); + + for (int[] valAndIndex : valAndIndices) { + final int i = valAndIndex[1]; + final int j = valAndIndex[2]; + final int nextAvailable = Math.max(rows[i], cols[j]) + 1; + ans[i][j] = nextAvailable; + rows[i] = nextAvailable; + cols[j] = nextAvailable; + } + + return ans; + } +} diff --git a/solutions/2371. Minimize Maximum Value in a Grid/2371.py b/solutions/2371. Minimize Maximum Value in a Grid/2371.py new file mode 100644 index 00000000000..fbcc1f98a2d --- /dev/null +++ b/solutions/2371. Minimize Maximum Value in a Grid/2371.py @@ -0,0 +1,22 @@ +class Solution: + def minScore(self, grid: List[List[int]]) -> List[List[int]]: + m = len(grid) + n = len(grid[0]) + ans = [[0] * n for _ in range(m)] + valAndIndices = [] + rows = [0] * m # rows[i] := the maximum used number so far + cols = [0] * n # cols[j] := the maximum used number so far + + for i in range(m): + for j in range(n): + valAndIndices.append((grid[i][j], i, j)) + + valAndIndices.sort() + + for _, i, j in valAndIndices: + nextAvailable = max(rows[i], cols[j]) + 1 + ans[i][j] = nextAvailable + rows[i] = nextAvailable + cols[j] = nextAvailable + + return ans diff --git a/solutions/2372. Calculate the Influence of Each Salesperson/2372.sql b/solutions/2372. Calculate the Influence of Each Salesperson/2372.sql new file mode 100644 index 00000000000..a53d734064c --- /dev/null +++ b/solutions/2372. Calculate the Influence of Each Salesperson/2372.sql @@ -0,0 +1,10 @@ +SELECT + Salesperson.salesperson_id, + Salesperson.name, + SUM(IFNULL(Sales.price, 0)) AS total +FROM Salesperson +LEFT JOIN Customer + USING (salesperson_id) +LEFT JOIN Sales + USING (customer_id) +GROUP BY 1; diff --git a/solutions/2373. Largest Local Values in a Matrix/2373.cpp b/solutions/2373. Largest Local Values in a Matrix/2373.cpp new file mode 100644 index 00000000000..96d110f0453 --- /dev/null +++ b/solutions/2373. Largest Local Values in a Matrix/2373.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector> largestLocal(vector>& grid) { + const int n = grid.size(); + vector> ans(n - 2, vector(n - 2)); + + for (int i = 0; i < n - 2; ++i) + for (int j = 0; j < n - 2; ++j) + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) + ans[i][j] = max(ans[i][j], grid[x][y]); + + return ans; + } +}; diff --git a/solutions/2373. Largest Local Values in a Matrix/2373.java b/solutions/2373. Largest Local Values in a Matrix/2373.java new file mode 100644 index 00000000000..76367c8fcfd --- /dev/null +++ b/solutions/2373. Largest Local Values in a Matrix/2373.java @@ -0,0 +1,14 @@ +class Solution { + public int[][] largestLocal(int[][] grid) { + final int n = grid.length; + int[][] ans = new int[n - 2][n - 2]; + + for (int i = 0; i < n - 2; ++i) + for (int j = 0; j < n - 2; ++j) + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) + ans[i][j] = Math.max(ans[i][j], grid[x][y]); + + return ans; + } +} diff --git a/solutions/2373. Largest Local Values in a Matrix/2373.py b/solutions/2373. Largest Local Values in a Matrix/2373.py new file mode 100644 index 00000000000..9730e6418b9 --- /dev/null +++ b/solutions/2373. Largest Local Values in a Matrix/2373.py @@ -0,0 +1,12 @@ +class Solution: + def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: + n = len(grid) + ans = [[0] * (n - 2) for _ in range(n - 2)] + + for i in range(n - 2): + for j in range(n - 2): + for x in range(i, i + 3): + for y in range(j, j + 3): + ans[i][j] = max(ans[i][j], grid[x][y]) + + return ans diff --git a/solutions/2374. Node With Highest Edge Score/2374.cpp b/solutions/2374. Node With Highest Edge Score/2374.cpp new file mode 100644 index 00000000000..5b0fb0dc6f0 --- /dev/null +++ b/solutions/2374. Node With Highest Edge Score/2374.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int edgeScore(vector& edges) { + vector scores(edges.size()); + for (int i = 0; i < edges.size(); ++i) + scores[edges[i]] += i; + return ranges::max_element(scores) - scores.begin(); + } +}; diff --git a/solutions/2374. Node With Highest Edge Score/2374.java b/solutions/2374. Node With Highest Edge Score/2374.java new file mode 100644 index 00000000000..3749a86048e --- /dev/null +++ b/solutions/2374. Node With Highest Edge Score/2374.java @@ -0,0 +1,15 @@ +class Solution { + public int edgeScore(int[] edges) { + int ans = 0; + long[] scores = new long[edges.length]; + + for (int i = 0; i < edges.length; ++i) + scores[edges[i]] += i; + + for (int i = 1; i < scores.length; ++i) + if (scores[i] > scores[ans]) + ans = i; + + return ans; + } +} diff --git a/solutions/2374. Node With Highest Edge Score/2374.py b/solutions/2374. Node With Highest Edge Score/2374.py new file mode 100644 index 00000000000..97d06332b90 --- /dev/null +++ b/solutions/2374. Node With Highest Edge Score/2374.py @@ -0,0 +1,6 @@ +class Solution: + def edgeScore(self, edges: List[int]) -> int: + scores = [0] * len(edges) + for i, edge in enumerate(edges): + scores[edge] += i + return scores.index(max(scores)) diff --git a/solutions/2375. Construct Smallest Number From DI String/2375.cpp b/solutions/2375. Construct Smallest Number From DI String/2375.cpp new file mode 100644 index 00000000000..d622826c5c6 --- /dev/null +++ b/solutions/2375. Construct Smallest Number From DI String/2375.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + string smallestNumber(string pattern) { + string ans; + stack stack{{'1'}}; + + for (const char c : pattern) { + char maxSorFar = stack.top(); + if (c == 'I') + while (!stack.empty()) { + maxSorFar = max(maxSorFar, stack.top()); + ans += stack.top(), stack.pop(); + } + stack.push(maxSorFar + 1); + } + + while (!stack.empty()) + ans += stack.top(), stack.pop(); + + return ans; + } +}; diff --git a/solutions/2375. Construct Smallest Number From DI String/2375.java b/solutions/2375. Construct Smallest Number From DI String/2375.java new file mode 100644 index 00000000000..234a46e2ed0 --- /dev/null +++ b/solutions/2375. Construct Smallest Number From DI String/2375.java @@ -0,0 +1,21 @@ +class Solution { + public String smallestNumber(String pattern) { + StringBuilder sb = new StringBuilder(); + Deque stack = new ArrayDeque<>(Arrays.asList('1')); + + for (final char c : pattern.toCharArray()) { + char maxSorFar = stack.peek(); + if (c == 'I') + while (!stack.isEmpty()) { + maxSorFar = (char) Math.max(maxSorFar, stack.peek()); + sb.append(stack.pop()); + } + stack.push((char) (maxSorFar + 1)); + } + + while (!stack.isEmpty()) + sb.append(stack.pop()); + + return sb.toString(); + } +} diff --git a/solutions/2375. Construct Smallest Number From DI String/2375.py b/solutions/2375. Construct Smallest Number From DI String/2375.py new file mode 100644 index 00000000000..c96284b3c74 --- /dev/null +++ b/solutions/2375. Construct Smallest Number From DI String/2375.py @@ -0,0 +1,17 @@ +class Solution: + def smallestNumber(self, pattern: str) -> str: + ans = [] + stack = ['1'] + + for c in pattern: + maxSorFar = stack[-1] + if c == 'I': + while stack: + maxSorFar = max(maxSorFar, stack[-1]) + ans.append(stack.pop()) + stack.append(chr(ord(maxSorFar) + 1)) + + while stack: + ans.append(stack.pop()) + + return ''.join(ans) diff --git a/solutions/2376. Count Special Integers/2376.cpp b/solutions/2376. Count Special Integers/2376.cpp new file mode 100644 index 00000000000..2ab9a7ee128 --- /dev/null +++ b/solutions/2376. Count Special Integers/2376.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + // Same as 1012. Numbers With Repeated Digits + int countSpecialNumbers(int n) { + const int digitSize = log10(n) + 1; + vector>> mem( + digitSize + 1, vector>(1 << 10, vector(2, -1))); + return count(to_string(n), 0, 0, true, mem) - 1; // - 0; + } + + private: + // Returns the number of special integers, considering the i-th digit, where + // `used` is the bitmask of the used digits, and `isTight` indicates if the + // current digit is tightly bound. + int count(const string& s, int i, int used, bool isTight, + vector>>& mem) { + if (i == s.length()) + return 1; + if (mem[i][used][isTight] != -1) + return mem[i][used][isTight]; + + int res = 0; + + const int maxDigit = isTight ? s[i] - '0' : 9; + for (int d = 0; d <= maxDigit; ++d) { + // `d` is used. + if (used >> d & 1) + continue; + // Use `d` now. + const bool nextIsTight = isTight && (d == maxDigit); + if (used == 0 && d == 0) // Don't count leading 0s as used. + res += count(s, i + 1, used, nextIsTight, mem); + else + res += count(s, i + 1, used | 1 << d, nextIsTight, mem); + } + + return mem[i][used][isTight] = res; + } +}; diff --git a/solutions/2376. Count Special Integers/2376.java b/solutions/2376. Count Special Integers/2376.java new file mode 100644 index 00000000000..bec613fe3b7 --- /dev/null +++ b/solutions/2376. Count Special Integers/2376.java @@ -0,0 +1,35 @@ +class Solution { + // Same as 1012. Numbers With Repeated Digits + public int countSpecialNumbers(int n) { + final int digitSize = (int) Math.log10(n) + 1; + Integer[][][] mem = new Integer[digitSize + 1][1 << 10][2]; + return count(String.valueOf(n), 0, 0, true, mem) - 1; // - 0; + } + + // Returns the number of special integers, considering the i-th digit, where + // `used` is the bitmask of the used digits, and `isTight` indicates if the + // current digit is tightly bound. + private int count(final String s, int i, int used, boolean isTight, Integer[][][] mem) { + if (i == s.length()) + return 1; + if (mem[i][used][isTight ? 1 : 0] != null) + return mem[i][used][isTight ? 1 : 0]; + + int res = 0; + + final int maxDigit = isTight ? s.charAt(i) - '0' : 9; + for (int d = 0; d <= maxDigit; ++d) { + // `d` is used. + if ((used >> d & 1) == 1) + continue; + // Use `d` now. + final boolean nextIsTight = isTight && (d == maxDigit); + if (used == 0 && d == 0) // Don't count leading 0s as used. + res += count(s, i + 1, used, nextIsTight, mem); + else + res += count(s, i + 1, used | 1 << d, nextIsTight, mem); + } + + return mem[i][used][isTight ? 1 : 0] = res; + } +} diff --git a/solutions/2376. Count Special Integers/2376.py b/solutions/2376. Count Special Integers/2376.py new file mode 100644 index 00000000000..bbdc001daee --- /dev/null +++ b/solutions/2376. Count Special Integers/2376.py @@ -0,0 +1,32 @@ +class Solution: + # Same as 1012. Numbers With Repeated Digits + def countSpecialNumbers(self, n: int) -> int: + s = str(n) + + @functools.lru_cache(None) + def dp(i: int, used: int, isTight: bool) -> int: + """ + Returns the number of special integers, considering the i-th digit, where + `used` is the bitmask of the used digits, and `isTight` indicates if the + current digit is tightly bound. + """ + if i == len(s): + return 1 + + res = 0 + + maxDigit = int(s[i]) if isTight else 9 + for d in range(maxDigit + 1): + # `d` is used. + if used >> d & 1: + continue + # Use `d` now. + nextIsTight = isTight and (d == maxDigit) + if used == 0 and d == 0: # Don't count leading 0s as used. + res += dp(i + 1, used, nextIsTight) + else: + res += dp(i + 1, used | 1 << d, nextIsTight) + + return res + + return dp(0, 0, True) - 1 # - 0 diff --git a/solutions/2377. Sort the Olympic Table/2377.sql b/solutions/2377. Sort the Olympic Table/2377.sql new file mode 100644 index 00000000000..99e1c8e20c4 --- /dev/null +++ b/solutions/2377. Sort the Olympic Table/2377.sql @@ -0,0 +1,11 @@ +SELECT + country, + gold_medals, + silver_medals, + bronze_medals +FROM Olympic +ORDER BY + gold_medals DESC, + silver_medals DESC, + bronze_medals DESC, + country; diff --git a/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.cpp b/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.cpp new file mode 100644 index 00000000000..76f24f23689 --- /dev/null +++ b/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + long long maxScore(vector>& edges) { + const int n = edges.size(); + vector>> graph(n); + + for (int i = 0; i < n; ++i) { + const int parent = edges[i][0]; + const int weight = edges[i][1]; + if (parent != -1) + graph[parent].emplace_back(i, weight); + } + + const auto [takeRoot, notTakeRoot] = dfs(graph, 0); + return max(takeRoot, notTakeRoot); + } + + private: + // Returns (the maximum sum at u if we take one u->v edge, + // the maximum sum at u if we don't take any child edge). + pair dfs(const vector>>& graph, int u) { + long bestEdge = 0; + long notTakeU = 0; + + for (const auto& [v, w] : graph[u]) { + const auto [takeV, notTakeV] = dfs(graph, v); + bestEdge = max(bestEdge, w + notTakeV - takeV); + notTakeU += takeV; + } + + return {bestEdge + notTakeU, notTakeU}; + } +}; diff --git a/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.java b/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.java new file mode 100644 index 00000000000..6a3fc411044 --- /dev/null +++ b/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.java @@ -0,0 +1,40 @@ +class Solution { + public long maxScore(int[][] edges) { + final int n = edges.length; + List>[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int i = 0; i < n; ++i) { + final int parent = edges[i][0]; + final int weight = edges[i][1]; + if (parent != -1) + graph[parent].add(new Pair<>(i, weight)); + } + + Pair pair = dfs(graph, 0); + final long takeRoot = pair.getKey(); + final long notTakeRoot = pair.getValue(); + return Math.max(takeRoot, notTakeRoot); + } + + // Returns (the maximum sum at u if we take one u->v edge, + // the maximum sum at u if we don't take any child edge). + private Pair dfs(List>[] graph, int u) { + long bestEdge = 0; + long notTakeU = 0; + + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + Pair pair = dfs(graph, v); + final long takeV = pair.getKey(); + final long notTakeV = pair.getValue(); + bestEdge = Math.max(bestEdge, w + notTakeV - takeV); + notTakeU += takeV; + } + + return new Pair<>(bestEdge + notTakeU, notTakeU); + } +} diff --git a/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.py b/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.py new file mode 100644 index 00000000000..55d887bea39 --- /dev/null +++ b/solutions/2378. Choose Edges to Maximize Score in a Tree/2378.py @@ -0,0 +1,26 @@ +class Solution: + def maxScore(self, edges: List[List[int]]) -> int: + n = len(edges) + graph = [[] for _ in range(n)] + + for i, (parent, weight) in enumerate(edges): + if parent != -1: + graph[parent].append((i, weight)) + + takeRoot, notTakeRoot = self._dfs(graph, 0) + return max(takeRoot, notTakeRoot) + + def _dfs(self, graph: List[List[int]], u: int) -> Tuple[int, int]: + """ + Returns (the maximum sum at u if we take one u->v edge, + the maximum sum at u if we don't take any child edge). + """ + bestEdge = 0 + notTakeU = 0 + + for v, w in graph[u]: + takeV, notTakeV = self._dfs(graph, v) + bestEdge = max(bestEdge, w + notTakeV - takeV) + notTakeU += takeV + + return (bestEdge + notTakeU, notTakeU) diff --git a/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.cpp b/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.cpp new file mode 100644 index 00000000000..60ec6fb3bb0 --- /dev/null +++ b/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minimumRecolors(string blocks, int k) { + int countB = 0; + int maxCountB = 0; + + for (int i = 0; i < blocks.length(); ++i) { + if (blocks[i] == 'B') + ++countB; + if (i >= k && blocks[i - k] == 'B') + --countB; + maxCountB = max(maxCountB, countB); + } + + return k - maxCountB; + } +}; diff --git a/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.java b/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.java new file mode 100644 index 00000000000..560e22da62e --- /dev/null +++ b/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.java @@ -0,0 +1,16 @@ +class Solution { + public int minimumRecolors(String blocks, int k) { + int countB = 0; + int maxCountB = 0; + + for (int i = 0; i < blocks.length(); ++i) { + if (blocks.charAt(i) == 'B') + ++countB; + if (i >= k && blocks.charAt(i - k) == 'B') + --countB; + maxCountB = Math.max(maxCountB, countB); + } + + return k - maxCountB; + } +} diff --git a/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.py b/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.py new file mode 100644 index 00000000000..d66ef0570ff --- /dev/null +++ b/solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.py @@ -0,0 +1,13 @@ +class Solution: + def minimumRecolors(self, blocks: str, k: int) -> int: + countB = 0 + maxCountB = 0 + + for i, block in enumerate(blocks): + if block == 'B': + countB += 1 + if i >= k and blocks[i - k] == 'B': + countB -= 1 + maxCountB = max(maxCountB, countB) + + return k - maxCountB diff --git a/solutions/238. Product of Array Except Self/238-2.cpp b/solutions/238. Product of Array Except Self/238-2.cpp new file mode 100644 index 00000000000..56b8e382156 --- /dev/null +++ b/solutions/238. Product of Array Except Self/238-2.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector productExceptSelf(vector& nums) { + const int n = nums.size(); + vector ans(n, 1); + + // Use ans as the prefix product array. + for (int i = 1; i < n; ++i) + ans[i] = ans[i - 1] * nums[i - 1]; + + int suffix = 1; // suffix product + for (int i = n - 1; i >= 0; --i) { + ans[i] *= suffix; + suffix *= nums[i]; + } + + return ans; + } +}; diff --git a/solutions/238. Product of Array Except Self/238-2.java b/solutions/238. Product of Array Except Self/238-2.java new file mode 100644 index 00000000000..4a1d3932b26 --- /dev/null +++ b/solutions/238. Product of Array Except Self/238-2.java @@ -0,0 +1,19 @@ +class Solution { + public int[] productExceptSelf(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + ans[0] = 1; + + // Use ans as the prefix product array. + for (int i = 1; i < n; ++i) + ans[i] = ans[i - 1] * nums[i - 1]; + + int suffix = 1; // suffix product + for (int i = n - 1; i >= 0; --i) { + ans[i] *= suffix; + suffix *= nums[i]; + } + + return ans; + } +} diff --git a/solutions/238. Product of Array Except Self/238-2.py b/solutions/238. Product of Array Except Self/238-2.py new file mode 100644 index 00000000000..1fbe220643e --- /dev/null +++ b/solutions/238. Product of Array Except Self/238-2.py @@ -0,0 +1,15 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [1] * n + + # Use ans as the prefix product array. + for i in range(1, n): + ans[i] = ans[i - 1] * nums[i - 1] + + suffix = 1 # suffix product + for i, num in reversed(list(enumerate(nums))): + ans[i] *= suffix + suffix *= num + + return ans diff --git a/solutions/238. Product of Array Except Self/238.cpp b/solutions/238. Product of Array Except Self/238.cpp new file mode 100644 index 00000000000..a67566998da --- /dev/null +++ b/solutions/238. Product of Array Except Self/238.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector productExceptSelf(vector& nums) { + const int n = nums.size(); + vector ans(n); // Can also use `nums` as the ans array. + vector prefix(n, 1); // prefix product + vector suffix(n, 1); // suffix product + + for (int i = 1; i < n; ++i) + prefix[i] = prefix[i - 1] * nums[i - 1]; + + for (int i = n - 2; i >= 0; --i) + suffix[i] = suffix[i + 1] * nums[i + 1]; + + for (int i = 0; i < n; ++i) + ans[i] = prefix[i] * suffix[i]; + + return ans; + } +}; diff --git a/solutions/238. Product of Array Except Self/238.java b/solutions/238. Product of Array Except Self/238.java new file mode 100644 index 00000000000..33434cb929a --- /dev/null +++ b/solutions/238. Product of Array Except Self/238.java @@ -0,0 +1,21 @@ +class Solution { + public int[] productExceptSelf(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; // Can also use `nums` as the ans array. + int[] prefix = new int[n]; // prefix product + int[] suffix = new int[n]; // suffix product + + prefix[0] = 1; + for (int i = 1; i < n; ++i) + prefix[i] = prefix[i - 1] * nums[i - 1]; + + suffix[n - 1] = 1; + for (int i = n - 2; i >= 0; --i) + suffix[i] = suffix[i + 1] * nums[i + 1]; + + for (int i = 0; i < n; ++i) + ans[i] = prefix[i] * suffix[i]; + + return ans; + } +} diff --git a/solutions/238. Product of Array Except Self/238.py b/solutions/238. Product of Array Except Self/238.py new file mode 100644 index 00000000000..bdf7e6ddf88 --- /dev/null +++ b/solutions/238. Product of Array Except Self/238.py @@ -0,0 +1,13 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + prefix = [1] * n # prefix product + suffix = [1] * n # suffix product + + for i in range(1, n): + prefix[i] = prefix[i - 1] * nums[i - 1] + + for i in reversed(range(n - 1)): + suffix[i] = suffix[i + 1] * nums[i + 1] + + return [prefix[i] * suffix[i] for i in range(n)] diff --git a/solutions/2380. Time Needed to Rearrange a Binary String/2380.cpp b/solutions/2380. Time Needed to Rearrange a Binary String/2380.cpp new file mode 100644 index 00000000000..44e5dac308f --- /dev/null +++ b/solutions/2380. Time Needed to Rearrange a Binary String/2380.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int secondsToRemoveOccurrences(string s) { + int ans = 0; + int zeros = 0; + + for (const char c : s) + if (c == '0') + ++zeros; + else if (zeros > 0) // c == '1' + ans = max(ans + 1, zeros); + + return ans; + } +}; diff --git a/solutions/2380. Time Needed to Rearrange a Binary String/2380.java b/solutions/2380. Time Needed to Rearrange a Binary String/2380.java new file mode 100644 index 00000000000..2e4ea919fb7 --- /dev/null +++ b/solutions/2380. Time Needed to Rearrange a Binary String/2380.java @@ -0,0 +1,14 @@ +class Solution { + public int secondsToRemoveOccurrences(String s) { + int ans = 0; + int zeros = 0; + + for (final char c : s.toCharArray()) + if (c == '0') + ++zeros; + else if (zeros > 0) // c == '1' + ans = Math.max(ans + 1, zeros); + + return ans; + } +} diff --git a/solutions/2380. Time Needed to Rearrange a Binary String/2380.py b/solutions/2380. Time Needed to Rearrange a Binary String/2380.py new file mode 100644 index 00000000000..23392331278 --- /dev/null +++ b/solutions/2380. Time Needed to Rearrange a Binary String/2380.py @@ -0,0 +1,12 @@ +class Solution: + def secondsToRemoveOccurrences(self, s: str) -> int: + ans = 0 + zeros = 0 + + for c in s: + if c == '0': + zeros += 1 + elif zeros > 0: # c == '1' + ans = max(ans + 1, zeros) + + return ans diff --git a/solutions/2381. Shifting Letters II/2381.cpp b/solutions/2381. Shifting Letters II/2381.cpp new file mode 100644 index 00000000000..ab283f9178d --- /dev/null +++ b/solutions/2381. Shifting Letters II/2381.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string shiftingLetters(string s, vector>& shifts) { + int currShift = 0; + vector timeline(s.length() + 1); + + for (const vector& shift : shifts) { + const int start = shift[0]; + const int end = shift[1]; + const int direction = shift[2]; + const int diff = direction ? 1 : -1; + timeline[start] += diff; + timeline[end + 1] -= diff; + } + + for (int i = 0; i < s.length(); ++i) { + currShift = (currShift + timeline[i]) % 26; + const int num = (s[i] - 'a' + currShift + 26) % 26; + s[i] = 'a' + num; + } + + return s; + } +}; diff --git a/solutions/2381. Shifting Letters II/2381.java b/solutions/2381. Shifting Letters II/2381.java new file mode 100644 index 00000000000..b047aa194c5 --- /dev/null +++ b/solutions/2381. Shifting Letters II/2381.java @@ -0,0 +1,24 @@ +class Solution { + public String shiftingLetters(String s, int[][] shifts) { + StringBuilder sb = new StringBuilder(); + int currShift = 0; + int[] timeline = new int[s.length() + 1]; + + for (int[] shift : shifts) { + final int start = shift[0]; + final int end = shift[1]; + final int direction = shift[2]; + final int diff = direction == 1 ? 1 : -1; + timeline[start] += diff; + timeline[end + 1] -= diff; + } + + for (int i = 0; i < s.length(); ++i) { + currShift = (currShift + timeline[i]) % 26; + final int num = (s.charAt(i) - 'a' + currShift + 26) % 26; + sb.append((char) ('a' + num)); + } + + return sb.toString(); + } +} diff --git a/solutions/2381. Shifting Letters II/2381.py b/solutions/2381. Shifting Letters II/2381.py new file mode 100644 index 00000000000..5eb4868a8c8 --- /dev/null +++ b/solutions/2381. Shifting Letters II/2381.py @@ -0,0 +1,17 @@ +class Solution: + def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: + ans = [] + currShift = 0 + timeline = [0] * (len(s) + 1) + + for start, end, direction in shifts: + diff = 1 if direction else -1 + timeline[start] += diff + timeline[end + 1] -= diff + + for i, c in enumerate(s): + currShift = (currShift + timeline[i]) % 26 + num = (ord(c) - ord('a') + currShift + 26) % 26 + ans.append(chr(ord('a') + num)) + + return ''.join(ans) diff --git a/solutions/2382. Maximum Segment Sum After Removals/2382.cpp b/solutions/2382. Maximum Segment Sum After Removals/2382.cpp new file mode 100644 index 00000000000..5598b235e21 --- /dev/null +++ b/solutions/2382. Maximum Segment Sum After Removals/2382.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + vector maximumSegmentSum(vector& nums, + vector& removeQueries) { + const int n = nums.size(); + long maxSum = 0; + vector ans(n); + // For the segment [l, r], record its sum in sum[l] and sum[r] + vector sum(n); + // For the segment [l, r], record its count in count[l] and count[r] + vector count(n); + + for (int i = n - 1; i >= 0; --i) { + ans[i] = maxSum; + const int j = removeQueries[i]; + + // Calculate `segmentSum`. + const long leftSum = j > 0 ? sum[j - 1] : 0; + const long rightSum = j + 1 < n ? sum[j + 1] : 0; + const long segmentSum = nums[j] + leftSum + rightSum; + + // Calculate `segmentCount`. + const int leftCount = j > 0 ? count[j - 1] : 0; + const int rightCount = j + 1 < n ? count[j + 1] : 0; + const int segmentCount = 1 + leftCount + rightCount; + + // Update the sum and count of the segment [l, r]. + const int l = j - leftCount; + const int r = j + rightCount; + sum[l] = segmentSum; + sum[r] = segmentSum; + count[l] = segmentCount; + count[r] = segmentCount; + maxSum = max(maxSum, segmentSum); + } + + return ans; + } +}; diff --git a/solutions/2382. Maximum Segment Sum After Removals/2382.java b/solutions/2382. Maximum Segment Sum After Removals/2382.java new file mode 100644 index 00000000000..c3eee75a5f2 --- /dev/null +++ b/solutions/2382. Maximum Segment Sum After Removals/2382.java @@ -0,0 +1,37 @@ +class Solution { + public long[] maximumSegmentSum(int[] nums, int[] removeQueries) { + final int n = nums.length; + long maxSum = 0; + long[] ans = new long[n]; + // For the segment [l, r], record its sum in sum[l] and sum[r] + long[] sum = new long[n]; + // For the segment [l, r], record its count in count[l] and count[r] + int[] count = new int[n]; + + for (int i = n - 1; i >= 0; --i) { + ans[i] = maxSum; + final int j = removeQueries[i]; + + // Calculate `segmentSum`. + final long leftSum = j > 0 ? sum[j - 1] : 0; + final long rightSum = j + 1 < n ? sum[j + 1] : 0; + final long segmentSum = nums[j] + leftSum + rightSum; + + // Calculate `segmentCount`. + final int leftCount = j > 0 ? count[j - 1] : 0; + final int rightCount = j + 1 < n ? count[j + 1] : 0; + final int segmentCount = 1 + leftCount + rightCount; + + // Update the sum and count of the segment [l, r]. + final int l = j - leftCount; + final int r = j + rightCount; + sum[l] = segmentSum; + sum[r] = segmentSum; + count[l] = segmentCount; + count[r] = segmentCount; + maxSum = Math.max(maxSum, segmentSum); + } + + return ans; + } +} diff --git a/solutions/2382. Maximum Segment Sum After Removals/2382.py b/solutions/2382. Maximum Segment Sum After Removals/2382.py new file mode 100644 index 00000000000..1665b7929b7 --- /dev/null +++ b/solutions/2382. Maximum Segment Sum After Removals/2382.py @@ -0,0 +1,34 @@ +class Solution: + def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: + n = len(nums) + maxSum = 0 + ans = [0] * n + # For the segment [l, r], record its sum in summ[l] and summ[r] + summ = [0] * n + # For the segment [l, r], record its count in count[l] and count[r] + count = [0] * n + + for i in reversed(range(n)): + ans[i] = maxSum + j = removeQueries[i] + + # Calculate `segmentSum`. + leftSum = summ[j - 1] if j > 0 else 0 + rightSum = summ[j + 1] if j + 1 < n else 0 + segmentSum = nums[j] + leftSum + rightSum + + # Calculate `segmentCount`. + leftCount = count[j - 1] if j > 0 else 0 + rightCount = count[j + 1] if j + 1 < n else 0 + segmentCount = 1 + leftCount + rightCount + + # Update `summ` and `count` of the segment [l, r]. + l = j - leftCount + r = j + rightCount + summ[l] = segmentSum + summ[r] = segmentSum + count[l] = segmentCount + count[r] = segmentCount + maxSum = max(maxSum, segmentSum) + + return ans diff --git a/solutions/2383. Minimum Hours of Training to Win a Competition/2383.cpp b/solutions/2383. Minimum Hours of Training to Win a Competition/2383.cpp new file mode 100644 index 00000000000..183d173e54a --- /dev/null +++ b/solutions/2383. Minimum Hours of Training to Win a Competition/2383.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int minNumberOfHours(int initialEnergy, int initialExperience, + vector& energy, vector& experience) { + return getRequiredEnergy(initialEnergy, energy) + + getRequiredExperience(initialExperience, experience); + } + + private: + int getRequiredEnergy(int initialEnergy, const vector& energy) { + return max(0, + accumulate(energy.begin(), energy.end(), 0) + 1 - initialEnergy); + } + + int getRequiredExperience(int currentExperience, + const vector& experience) { + int requiredExperience = 0; + for (const int e : experience) { + if (e >= currentExperience) { + requiredExperience += e + 1 - currentExperience; + currentExperience += e + 1 - currentExperience; + } + currentExperience += e; + } + return requiredExperience; + } +}; diff --git a/solutions/2383. Minimum Hours of Training to Win a Competition/2383.java b/solutions/2383. Minimum Hours of Training to Win a Competition/2383.java new file mode 100644 index 00000000000..b85d3e47554 --- /dev/null +++ b/solutions/2383. Minimum Hours of Training to Win a Competition/2383.java @@ -0,0 +1,23 @@ +class Solution { + public int minNumberOfHours(int initialEnergy, int initialExperience, int[] energy, + int[] experience) { + return getRequiredEnergy(initialEnergy, energy) + + getRequiredExperience(initialExperience, experience); + } + + private int getRequiredEnergy(int initialEnergy, int[] energy) { + return Math.max(0, Arrays.stream(energy).sum() + 1 - initialEnergy); + } + + private int getRequiredExperience(int currentExperience, int[] experience) { + int requiredExperience = 0; + for (final int e : experience) { + if (e >= currentExperience) { + requiredExperience += e + 1 - currentExperience; + currentExperience += e + 1 - currentExperience; + } + currentExperience += e; + } + return requiredExperience; + } +} diff --git a/solutions/2383. Minimum Hours of Training to Win a Competition/2383.py b/solutions/2383. Minimum Hours of Training to Win a Competition/2383.py new file mode 100644 index 00000000000..c55ccffdd70 --- /dev/null +++ b/solutions/2383. Minimum Hours of Training to Win a Competition/2383.py @@ -0,0 +1,16 @@ +class Solution: + def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int: + return self._getRequiredEnergy(initialEnergy, energy) + \ + self._getRequiredExperience(initialExperience, experience) + + def _getRequiredEnergy(self, initialEnergy: int, energy: List[int]) -> int: + return max(0, sum(energy) + 1 - initialEnergy) + + def _getRequiredExperience(self, currentExperience: int, experience: List[int]) -> int: + requiredExperience = 0 + for e in experience: + if e >= currentExperience: + requiredExperience += e + 1 - currentExperience + currentExperience += e + 1 - currentExperience + currentExperience += e + return requiredExperience diff --git a/solutions/2384. Largest Palindromic Number/2384.cpp b/solutions/2384. Largest Palindromic Number/2384.cpp new file mode 100644 index 00000000000..fd420d7d294 --- /dev/null +++ b/solutions/2384. Largest Palindromic Number/2384.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + string largestPalindromic(string num) { + unordered_map count; + + for (const char c : num) + ++count[c]; + + const string firstHalf = getFirstHalf(count); + const string mid = getMid(count); + const string ans = firstHalf + mid + reversed(firstHalf); + return ans.empty() ? "0" : ans; + } + + private: + string getFirstHalf(const unordered_map& count) { + string firstHalf; + for (char c = '9'; c >= '0'; --c) { + const auto it = count.find(c); + if (it == count.cend()) + continue; + const int freq = it->second; + firstHalf += string(freq / 2, c); + } + const int index = firstHalf.find_first_not_of('0'); + return index == string::npos ? "" : firstHalf.substr(index); + } + + string getMid(const unordered_map& count) { + for (char c = '9'; c >= '0'; --c) { + const auto it = count.find(c); + if (it == count.cend()) + continue; + const int freq = it->second; + if (freq % 2 == 1) + return string(1, c); + } + return ""; + } + + string reversed(const string& s) { + return {s.rbegin(), s.rend()}; + } +}; diff --git a/solutions/2384. Largest Palindromic Number/2384.java b/solutions/2384. Largest Palindromic Number/2384.java new file mode 100644 index 00000000000..ea66b6268c4 --- /dev/null +++ b/solutions/2384. Largest Palindromic Number/2384.java @@ -0,0 +1,44 @@ +class Solution { + public String largestPalindromic(String num) { + Map count = new HashMap<>(); + + for (final char c : num.toCharArray()) + count.merge(c, 1, Integer::sum); + + final String firstHalf = getFirstHalf(count); + final String mid = getMid(count); + final String ans = firstHalf + mid + reversed(firstHalf); + return ans.isEmpty() ? "0" : ans; + } + + private String getFirstHalf(Map count) { + StringBuilder sb = new StringBuilder(); + for (char c = '9'; c >= '0'; --c) { + final int freq = count.getOrDefault(c, 0); + sb.append(String.valueOf(c).repeat(freq / 2)); + } + final int index = firstNotZeroIndex(sb); + return index == -1 ? "" : sb.substring(index); + } + + private int firstNotZeroIndex(StringBuilder sb) { + for (int i = 0; i < sb.length(); ++i) + if (sb.charAt(i) != '0') + return i; + return -1; + } + + private String getMid(Map count) { + StringBuilder sb = new StringBuilder(); + for (char c = '9'; c >= '0'; --c) { + final int freq = count.getOrDefault(c, 0); + if (freq % 2 == 1) + return String.valueOf(c); + } + return ""; + } + + private String reversed(final String s) { + return new StringBuilder(s).reverse().toString(); + } +} diff --git a/solutions/2384. Largest Palindromic Number/2384.py b/solutions/2384. Largest Palindromic Number/2384.py new file mode 100644 index 00000000000..4926e816668 --- /dev/null +++ b/solutions/2384. Largest Palindromic Number/2384.py @@ -0,0 +1,12 @@ +class Solution: + def largestPalindromic(self, num: str) -> str: + count = collections.Counter(num) + firstHalf = ''.join(count[i] // 2 * i for i in '9876543210').lstrip('0') + mid = self._getMid(count) + return (firstHalf + mid + firstHalf[::-1]) or '0' + + def _getMid(self, count: Dict[str, int]) -> str: + for c in '9876543210': + if count[c] & 1: + return c + return '' diff --git a/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.cpp b/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.cpp new file mode 100644 index 00000000000..c0da0a4c128 --- /dev/null +++ b/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + int amountOfTime(TreeNode* root, int start) { + int ans = -1; + const unordered_map> graph = getGraph(root); + queue q{{start}}; + unordered_set seen{start}; + + for (; !q.empty(); ++ans) { + for (int sz = q.size(); sz > 0; --sz) { + const int u = q.front(); + q.pop(); + if (!graph.contains(u)) + continue; + for (const int v : graph.at(u)) { + if (seen.contains(v)) + continue; + q.push(v); + seen.insert(v); + } + } + } + + return ans; + } + + private: + unordered_map> getGraph(TreeNode* root) { + unordered_map> graph; + queue> q{{{root, -1}}}; // (node, parent) + + while (!q.empty()) { + const auto [node, parent] = q.front(); + q.pop(); + if (parent != -1) { + graph[parent].push_back(node->val); + graph[node->val].push_back(parent); + } + if (node->left) + q.emplace(node->left, node->val); + if (node->right) + q.emplace(node->right, node->val); + } + + return graph; + } +}; diff --git a/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.java b/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.java new file mode 100644 index 00000000000..23a37edd0d6 --- /dev/null +++ b/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.java @@ -0,0 +1,48 @@ +class Solution { + public int amountOfTime(TreeNode root, int start) { + int ans = -1; + Map> graph = getGraph(root); + Queue q = new ArrayDeque<>(Arrays.asList(start)); + Set seen = new HashSet<>(Arrays.asList(start)); + + for (; !q.isEmpty(); ++ans) { + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.poll(); + if (!graph.containsKey(u)) + continue; + for (final int v : graph.get(u)) { + if (seen.contains(v)) + continue; + q.offer(v); + seen.add(v); + } + } + } + + return ans; + } + + private Map> getGraph(TreeNode root) { + Map> graph = new HashMap<>(); + // (node, parent) + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(root, -1))); + + while (!q.isEmpty()) { + Pair pair = q.poll(); + TreeNode node = pair.getKey(); + final int parent = pair.getValue(); + if (parent != -1) { + graph.putIfAbsent(parent, new ArrayList<>()); + graph.putIfAbsent(node.val, new ArrayList<>()); + graph.get(parent).add(node.val); + graph.get(node.val).add(parent); + } + if (node.left != null) + q.add(new Pair<>(node.left, node.val)); + if (node.right != null) + q.add(new Pair<>(node.right, node.val)); + } + + return graph; + } +} diff --git a/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.py b/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.py new file mode 100644 index 00000000000..d0da30f1026 --- /dev/null +++ b/solutions/2385. Amount of Time for Binary Tree to Be Infected/2385.py @@ -0,0 +1,36 @@ +class Solution: + def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: + ans = -1 + graph = self._getGraph(root) + q = collections.deque([start]) + seen = {start} + + while q: + ans += 1 + for _ in range(len(q)): + u = q.popleft() + if u not in graph: + continue + for v in graph[u]: + if v in seen: + continue + q.append(v) + seen.add(v) + + return ans + + def _getGraph(self, root: Optional[TreeNode]) -> Dict[int, List[int]]: + graph = collections.defaultdict(list) + q = collections.deque([(root, -1)]) # (node, parent) + + while q: + node, parent = q.popleft() + if parent != -1: + graph[parent].append(node.val) + graph[node.val].append(parent) + if node.left: + q.append((node.left, node.val)) + if node.right: + q.append((node.right, node.val)) + + return graph diff --git a/solutions/2386. Find the K-Sum of an Array/2386.cpp b/solutions/2386. Find the K-Sum of an Array/2386.cpp new file mode 100644 index 00000000000..0b228bf53d8 --- /dev/null +++ b/solutions/2386. Find the K-Sum of an Array/2386.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + long long kSum(vector& nums, int k) { + const long long maxSum = getMaxSum(nums); + const vector absNums = getAbsNums(nums); + long long ans = maxSum; + // (the next maximum sum, the next index i) + using P = pair; + priority_queue

maxHeap; + maxHeap.emplace(maxSum - absNums[0], 0); + + for (int j = 0; j < k - 1; ++j) { + const auto [nextMaxSum, i] = maxHeap.top(); + maxHeap.pop(); + ans = nextMaxSum; + if (i + 1 < absNums.size()) { + maxHeap.emplace(nextMaxSum - absNums[i + 1], i + 1); + maxHeap.emplace(nextMaxSum - absNums[i + 1] + absNums[i], i + 1); + } + } + + return ans; + } + + private: + long long getMaxSum(const vector& nums) { + long long maxSum = 0; + for (const int num : nums) + if (num > 0) + maxSum += num; + return maxSum; + } + + vector getAbsNums(const vector& nums) { + vector absNums; + for (const int num : nums) + absNums.push_back(abs(num)); + ranges::sort(absNums); + return absNums; + } +}; diff --git a/solutions/2386. Find the K-Sum of an Array/2386.java b/solutions/2386. Find the K-Sum of an Array/2386.java new file mode 100644 index 00000000000..e4693f8c0eb --- /dev/null +++ b/solutions/2386. Find the K-Sum of an Array/2386.java @@ -0,0 +1,39 @@ +class Solution { + public long kSum(int[] nums, int k) { + final long maxSum = getMaxSum(nums); + final int[] absNums = getAbsNums(nums); + long ans = maxSum; + // (the next maximum sum, the next index i) + Queue> maxHeap = + new PriorityQueue<>((a, b) -> Long.compare(b.getKey(), a.getKey())); + maxHeap.offer(new Pair<>(maxSum - absNums[0], 0)); + + for (int j = 0; j < k - 1; ++j) { + Pair pair = maxHeap.poll(); + final long nextMaxSum = pair.getKey(); + final int i = pair.getValue(); + ans = nextMaxSum; + if (i + 1 < absNums.length) { + maxHeap.offer(new Pair<>(nextMaxSum - absNums[i + 1], i + 1)); + maxHeap.offer(new Pair<>(nextMaxSum - absNums[i + 1] + absNums[i], i + 1)); + } + } + + return ans; + } + + private long getMaxSum(int[] nums) { + long maxSum = 0; + for (final int num : nums) + if (num > 0) + maxSum += num; + return maxSum; + } + + private int[] getAbsNums(int[] nums) { + for (int i = 0; i < nums.length; ++i) + nums[i] = Math.abs(nums[i]); + Arrays.sort(nums); + return nums; + } +} diff --git a/solutions/2386. Find the K-Sum of an Array/2386.py b/solutions/2386. Find the K-Sum of an Array/2386.py new file mode 100644 index 00000000000..01cad6f2445 --- /dev/null +++ b/solutions/2386. Find the K-Sum of an Array/2386.py @@ -0,0 +1,17 @@ +class Solution: + def kSum(self, nums: List[int], k: int) -> int: + maxSum = sum(num for num in nums if num > 0) + absNums = sorted(abs(num) for num in nums) + # (the next maximum sum, the next index i) + maxHeap = [(-(maxSum - absNums[0]), 0)] + nextMaxSum = maxSum + + for _ in range(k - 1): + nextMaxSum, i = heapq.heappop(maxHeap) + nextMaxSum *= -1 + if i + 1 < len(absNums): + heapq.heappush(maxHeap, (-(nextMaxSum - absNums[i + 1]), i + 1)) + heapq.heappush( + maxHeap, (-(nextMaxSum - absNums[i + 1] + absNums[i]), i + 1)) + + return nextMaxSum diff --git a/solutions/2387. Median of a Row Wise Sorted Matrix/2387.cpp b/solutions/2387. Median of a Row Wise Sorted Matrix/2387.cpp new file mode 100644 index 00000000000..bcb0d1a4d4b --- /dev/null +++ b/solutions/2387. Median of a Row Wise Sorted Matrix/2387.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int matrixMedian(vector>& grid) { + const int noGreaterThanMedianCount = grid.size() * grid[0].size() / 2 + 1; + int l = 1; + int r = 1e6; + + while (l < r) { + const int m = (l + r) / 2; + if (numsNoGreaterThan(grid, m) >= noGreaterThanMedianCount) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int numsNoGreaterThan(const vector>& grid, int m) { + int count = 0; + for (const vector& row : grid) + count += ranges::upper_bound(row, m) - row.begin(); + return count; + } +}; diff --git a/solutions/2387. Median of a Row Wise Sorted Matrix/2387.java b/solutions/2387. Median of a Row Wise Sorted Matrix/2387.java new file mode 100644 index 00000000000..ba77ab74451 --- /dev/null +++ b/solutions/2387. Median of a Row Wise Sorted Matrix/2387.java @@ -0,0 +1,37 @@ +class Solution { + public int matrixMedian(int[][] grid) { + final int noGreaterThanMedianCount = grid.length * grid[0].length / 2 + 1; + int l = 1; + int r = (int) 1e6; + + while (l < r) { + final int m = (l + r) / 2; + if (numsNoGreaterThan(grid, m) >= noGreaterThanMedianCount) + r = m; + else + l = m + 1; + } + + return l; + } + + private int numsNoGreaterThan(int[][] grid, int m) { + int count = 0; + for (int[] row : grid) + count += firstGreater(row, m); + return count; + } + + private int firstGreater(int[] A, int target) { + int l = 0; + int r = A.length; + while (l < r) { + final int m = (l + r) / 2; + if (A[m] > target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/2387. Median of a Row Wise Sorted Matrix/2387.py b/solutions/2387. Median of a Row Wise Sorted Matrix/2387.py new file mode 100644 index 00000000000..314d32d7940 --- /dev/null +++ b/solutions/2387. Median of a Row Wise Sorted Matrix/2387.py @@ -0,0 +1,15 @@ +class Solution: + def matrixMedian(self, grid: List[List[int]]) -> int: + noGreaterThanMedianCount = len(grid) * len(grid[0]) // 2 + 1 + l = 1 + r = int(1e6) + + while l < r: + m = (l + r) // 2 + if sum(bisect_right(row, m) for row in grid) >= \ + noGreaterThanMedianCount: + r = m + else: + l = m + 1 + + return l diff --git a/solutions/2388. Change Null Values in a Table to the Previous Value/2388.sql b/solutions/2388. Change Null Values in a Table to the Previous Value/2388.sql new file mode 100644 index 00000000000..ef38629578b --- /dev/null +++ b/solutions/2388. Change Null Values in a Table to the Previous Value/2388.sql @@ -0,0 +1,20 @@ +WITH + CoffeeShoptWithRowNumber AS ( + SELECT *, ROW_NUMBER() OVER() AS `row_number` + FROM CoffeeShop + ), + CoffeeShoptWithRowNumberAndGroupId AS ( + SELECT + *, + SUM(drink IS NOT NULL) OVER( + ORDER BY `row_number` + ) AS group_id + FROM CoffeeShoptWithRowNumber + ) +SELECT + id, + FIRST_VALUE(drink) OVER( + PARTITION by group_id + ORDER BY `row_number` + ) AS drink +FROM CoffeeShoptWithRowNumberAndGroupId; diff --git a/solutions/2389. Longest Subsequence With Limited Sum/2389.cpp b/solutions/2389. Longest Subsequence With Limited Sum/2389.cpp new file mode 100644 index 00000000000..167631d7cae --- /dev/null +++ b/solutions/2389. Longest Subsequence With Limited Sum/2389.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector answerQueries(vector& nums, vector& queries) { + vector ans; + + ranges::sort(nums); + + for (const int query : queries) + ans.push_back(numOfElementsLessThan(nums, query)); + + return ans; + } + + private: + int numOfElementsLessThan(const vector& nums, int query) { + int sum = 0; + for (int i = 0; i < nums.size(); ++i) { + sum += nums[i]; + if (sum > query) + return i; + } + return nums.size(); + } +}; diff --git a/solutions/2389. Longest Subsequence With Limited Sum/2389.java b/solutions/2389. Longest Subsequence With Limited Sum/2389.java new file mode 100644 index 00000000000..155016f866f --- /dev/null +++ b/solutions/2389. Longest Subsequence With Limited Sum/2389.java @@ -0,0 +1,22 @@ +class Solution { + public int[] answerQueries(int[] nums, int[] queries) { + int[] ans = new int[queries.length]; + + Arrays.sort(nums); + + for (int i = 0; i < queries.length; ++i) + ans[i] = numOfElementsLessThan(nums, queries[i]); + + return ans; + } + + private int numOfElementsLessThan(int[] nums, int query) { + int sum = 0; + for (int i = 0; i < nums.length; ++i) { + sum += nums[i]; + if (sum > query) + return i; + } + return nums.length; + } +} diff --git a/solutions/2389. Longest Subsequence With Limited Sum/2389.py b/solutions/2389. Longest Subsequence With Limited Sum/2389.py new file mode 100644 index 00000000000..b66f6971ff7 --- /dev/null +++ b/solutions/2389. Longest Subsequence With Limited Sum/2389.py @@ -0,0 +1,13 @@ +class Solution: + def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: + nums.sort() + + def numOfElementsLessThan(query: int) -> int: + summ = 0 + for i, num in enumerate(nums): + summ += num + if summ > query: + return i + return len(nums) + + return [numOfElementsLessThan(query) for query in queries] diff --git a/solutions/239. Sliding Window Maximum/239.cpp b/solutions/239. Sliding Window Maximum/239.cpp new file mode 100644 index 00000000000..171d4c4c145 --- /dev/null +++ b/solutions/239. Sliding Window Maximum/239.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector maxSlidingWindow(vector& nums, int k) { + vector ans; + deque maxQ; + + for (int i = 0; i < nums.size(); ++i) { + while (!maxQ.empty() && maxQ.back() < nums[i]) + maxQ.pop_back(); + maxQ.push_back(nums[i]); + if (i >= k && nums[i - k] == maxQ.front()) // out-of-bounds + maxQ.pop_front(); + if (i >= k - 1) + ans.push_back(maxQ.front()); + } + + return ans; + } +}; diff --git a/solutions/239. Sliding Window Maximum/239.java b/solutions/239. Sliding Window Maximum/239.java new file mode 100644 index 00000000000..dd67649af9e --- /dev/null +++ b/solutions/239. Sliding Window Maximum/239.java @@ -0,0 +1,18 @@ +class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + int[] ans = new int[nums.length - k + 1]; + Deque maxQ = new ArrayDeque<>(); + + for (int i = 0; i < nums.length; ++i) { + while (!maxQ.isEmpty() && maxQ.peekLast() < nums[i]) + maxQ.pollLast(); + maxQ.offerLast(nums[i]); + if (i >= k && nums[i - k] == maxQ.peekFirst()) // out-of-bounds + maxQ.pollFirst(); + if (i >= k - 1) + ans[i - k + 1] = maxQ.peekFirst(); + } + + return ans; + } +} diff --git a/solutions/239. Sliding Window Maximum/239.py b/solutions/239. Sliding Window Maximum/239.py new file mode 100644 index 00000000000..09d9cc3d9b8 --- /dev/null +++ b/solutions/239. Sliding Window Maximum/239.py @@ -0,0 +1,15 @@ +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + ans = [] + maxQ = collections.deque() + + for i, num in enumerate(nums): + while maxQ and maxQ[-1] < num: + maxQ.pop() + maxQ.append(num) + if i >= k and nums[i - k] == maxQ[0]: # out-of-bounds + maxQ.popleft() + if i >= k - 1: + ans.append(maxQ[0]) + + return ans diff --git a/solutions/2390. Removing Stars From a String/2390.cpp b/solutions/2390. Removing Stars From a String/2390.cpp new file mode 100644 index 00000000000..ec825a04289 --- /dev/null +++ b/solutions/2390. Removing Stars From a String/2390.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + string removeStars(string s) { + string ans; + for (const char c : s) + if (c == '*') + ans.pop_back(); + else + ans.push_back(c); + return ans; + } +}; diff --git a/solutions/2390. Removing Stars From a String/2390.java b/solutions/2390. Removing Stars From a String/2390.java new file mode 100644 index 00000000000..aba45eb1e9e --- /dev/null +++ b/solutions/2390. Removing Stars From a String/2390.java @@ -0,0 +1,11 @@ +class Solution { + public String removeStars(String s) { + StringBuilder sb = new StringBuilder(); + for (final char c : s.toCharArray()) + if (c == '*') + sb.deleteCharAt(sb.length() - 1); + else + sb.append(c); + return sb.toString(); + } +} diff --git a/solutions/2390. Removing Stars From a String/2390.py b/solutions/2390. Removing Stars From a String/2390.py new file mode 100644 index 00000000000..f70d391e579 --- /dev/null +++ b/solutions/2390. Removing Stars From a String/2390.py @@ -0,0 +1,9 @@ +class Solution: + def removeStars(self, s: str) -> str: + ans = [] + for c in s: + if c == '*': + ans.pop() + else: + ans.append(c) + return ''.join(ans) diff --git a/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.cpp b/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.cpp new file mode 100644 index 00000000000..5c5fbad5da1 --- /dev/null +++ b/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int garbageCollection(vector& garbage, vector& travel) { + vector prefix(travel.size()); + partial_sum(travel.begin(), travel.end(), prefix.begin()); + const int timeM = getTime(garbage, prefix, 'M'); + const int timeP = getTime(garbage, prefix, 'P'); + const int timeG = getTime(garbage, prefix, 'G'); + return timeM + timeP + timeG; + } + + private: + int getTime(const vector& garbage, const vector& prefix, + char c) { + int characterCount = 0; + int lastIndex = -1; + for (int i = 0; i < garbage.size(); ++i) { + const string& s = garbage[i]; + if (ranges::any_of(s, [c](const char g) { return g == c; })) + lastIndex = i; + characterCount += std::ranges::count(s, c); + } + return characterCount + (lastIndex <= 0 ? 0 : prefix[lastIndex - 1]); + } +}; diff --git a/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.java b/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.java new file mode 100644 index 00000000000..086500b6d11 --- /dev/null +++ b/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.java @@ -0,0 +1,24 @@ +class Solution { + public int garbageCollection(String[] garbage, int[] travel) { + int[] prefix = new int[travel.length]; + prefix[0] = travel[0]; + for (int i = 1; i < prefix.length; ++i) + prefix[i] += prefix[i - 1] + travel[i]; + final int timeM = getTime(garbage, prefix, 'M'); + final int timeP = getTime(garbage, prefix, 'P'); + final int timeG = getTime(garbage, prefix, 'G'); + return timeM + timeP + timeG; + } + + private int getTime(String[] garbage, int[] prefix, char c) { + int characterCount = 0; + int lastIndex = -1; + for (int i = 0; i < garbage.length; ++i) { + final String s = garbage[i]; + if (s.chars().anyMatch(g -> g == c)) + lastIndex = i; + characterCount += (int) s.chars().filter(g -> g == c).count(); + } + return characterCount + (lastIndex <= 0 ? 0 : prefix[lastIndex - 1]); + } +} diff --git a/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.py b/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.py new file mode 100644 index 00000000000..22821f6ab91 --- /dev/null +++ b/solutions/2391. Minimum Amount of Time to Collect Garbage/2391.py @@ -0,0 +1,14 @@ +class Solution: + def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: + prefix = list(itertools.accumulate(travel)) + + def getTime(c: str) -> int: + characterCount = 0 + lastIndex = -1 + for i, s in enumerate(garbage): + if any(g == c for g in s): + lastIndex = i + characterCount += s.count(c) + return characterCount + (0 if lastIndex <= 0 else prefix[lastIndex - 1]) + + return getTime('M') + getTime('P') + getTime('G') diff --git a/solutions/2392. Build a Matrix With Conditions/2392.cpp b/solutions/2392. Build a Matrix With Conditions/2392.cpp new file mode 100644 index 00000000000..5d98f21c34f --- /dev/null +++ b/solutions/2392. Build a Matrix With Conditions/2392.cpp @@ -0,0 +1,59 @@ +class Solution { + public: + vector> buildMatrix(int k, vector>& rowConditions, + vector>& colConditions) { + const vector rowOrder = topologicalSort(rowConditions, k); + if (rowOrder.empty()) + return {}; + + const vector colOrder = topologicalSort(colConditions, k); + if (colOrder.empty()) + return {}; + + vector> ans(k, vector(k)); + vector nodeToRowIndex(k + 1); + + for (int i = 0; i < k; ++i) + nodeToRowIndex[rowOrder[i]] = i; + + for (int j = 0; j < k; ++j) { + const int node = colOrder[j]; + const int i = nodeToRowIndex[node]; + ans[i][j] = node; + } + + return ans; + } + + private: + vector topologicalSort(const vector>& conditions, int n) { + vector order; + vector> graph(n + 1); + vector inDegrees(n + 1); + queue q; + + // Build the graph. + for (const vector& condition : conditions) { + const int u = condition[0]; + const int v = condition[1]; + graph[u].push_back(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + for (int i = 1; i <= n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + order.push_back(u); + for (const int v : graph[u]) + if (--inDegrees[v] == 0) + q.push(v); + } + + return order.size() == n ? order : vector(); + } +}; diff --git a/solutions/2392. Build a Matrix With Conditions/2392.java b/solutions/2392. Build a Matrix With Conditions/2392.java new file mode 100644 index 00000000000..bd0ff777c01 --- /dev/null +++ b/solutions/2392. Build a Matrix With Conditions/2392.java @@ -0,0 +1,58 @@ +class Solution { + public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) { + List rowOrder = topologicalSort(rowConditions, k); + if (rowOrder.isEmpty()) + return new int[][] {}; + + List colOrder = topologicalSort(colConditions, k); + if (colOrder.isEmpty()) + return new int[][] {}; + + int[][] ans = new int[k][k]; + int[] nodeToRowIndex = new int[k + 1]; + + for (int i = 0; i < k; ++i) + nodeToRowIndex[rowOrder.get(i)] = i; + + for (int j = 0; j < k; ++j) { + final int node = colOrder[j]; + final int i = nodeToRowIndex[node]; + ans[i][j] = node; + } + + return ans; + } + + private List topologicalSort(int[][] conditions, int n) { + List order = new ArrayList<>(); + List[] graph = new List[n + 1]; + int[] inDegrees = new int[n + 1]; + Queue q = new ArrayDeque<>(); + + for (int i = 1; i <= n; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph. + for (int[] condition : conditions) { + final int u = condition[0]; + final int v = condition[1]; + graph[u].add(v); + ++inDegrees[v]; + } + + // Perform topological sorting. + for (int i = 1; i <= n; ++i) + if (inDegrees[i] == 0) + q.offer(i); + + while (!q.isEmpty()) { + final int u = q.poll(); + order.add(u); + for (final int v : graph[u]) + if (--inDegrees[v] == 0) + q.offer(v); + } + + return order.size() == n ? order : new ArrayList<>(); + } +} diff --git a/solutions/2392. Build a Matrix With Conditions/2392.py b/solutions/2392. Build a Matrix With Conditions/2392.py new file mode 100644 index 00000000000..764b4c6dfbf --- /dev/null +++ b/solutions/2392. Build a Matrix With Conditions/2392.py @@ -0,0 +1,44 @@ +class Solution: + def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: + rowOrder = self._topologicalSort(rowConditions, k) + if not rowOrder: + return [] + + colOrder = self._topologicalSort(colConditions, k) + if not colOrder: + return [] + + ans = [[0] * k for _ in range(k)] + nodeToRowIndex = [0] * (k + 1) + + for i, node in enumerate(rowOrder): + nodeToRowIndex[node] = i + + for j, node in enumerate(colOrder): + i = nodeToRowIndex[node] + ans[i][j] = node + + return ans + + def _topologicalSort(self, conditions: List[List[int]], n: int) -> List[int]: + order = [] + graph = [[] for _ in range(n + 1)] + inDegrees = [0] * (n + 1) + + # Build the graph. + for u, v in conditions: + graph[u].append(v) + inDegrees[v] += 1 + + # Perform topological sorting. + q = collections.deque([i for i in range(1, n + 1) if inDegrees[i] == 0]) + + while q: + u = q.popleft() + order.append(u) + for v in graph[u]: + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + + return order if len(order) == n else [] diff --git a/solutions/2393. Count Strictly Increasing Subarrays/2393.cpp b/solutions/2393. Count Strictly Increasing Subarrays/2393.cpp new file mode 100644 index 00000000000..56d60d47939 --- /dev/null +++ b/solutions/2393. Count Strictly Increasing Subarrays/2393.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long countSubarrays(vector& nums) { + long long ans = 0; + + for (int i = 0, j = -1; i < nums.size(); ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + j = i - 1; + ans += i - j; + } + + return ans; + } +}; diff --git a/solutions/2393. Count Strictly Increasing Subarrays/2393.java b/solutions/2393. Count Strictly Increasing Subarrays/2393.java new file mode 100644 index 00000000000..ae33535f584 --- /dev/null +++ b/solutions/2393. Count Strictly Increasing Subarrays/2393.java @@ -0,0 +1,13 @@ +class Solution { + public long countSubarrays(int[] nums) { + long ans = 0; + + for (int i = 0, j = -1; i < nums.length; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + j = i - 1; + ans += i - j; + } + + return ans; + } +} diff --git a/solutions/2393. Count Strictly Increasing Subarrays/2393.py b/solutions/2393. Count Strictly Increasing Subarrays/2393.py new file mode 100644 index 00000000000..bcf6f152e01 --- /dev/null +++ b/solutions/2393. Count Strictly Increasing Subarrays/2393.py @@ -0,0 +1,11 @@ +class Solution: + def countSubarrays(self, nums: List[int]) -> int: + ans = 0 + + j = -1 + for i, num in enumerate(nums): + if i > 0 and num <= nums[i - 1]: + j = i - 1 + ans += i - j + + return ans diff --git a/solutions/2394. Employees With Deductions/2394.sql b/solutions/2394. Employees With Deductions/2394.sql new file mode 100644 index 00000000000..07fcb122846 --- /dev/null +++ b/solutions/2394. Employees With Deductions/2394.sql @@ -0,0 +1,15 @@ +SELECT Employees.employee_id +FROM Employees +LEFT JOIN Logs + USING (employee_id) +GROUP BY Employees.employee_id, Employees.needed_hours +HAVING ( + SUM( + CEIL( + IFNULL( + TIMESTAMPDIFF(SECOND, LOGS.in_time, LOGS.out_time), + 0 + ) / 60 + ) + ) / 60 + ) < Employees.needed_hours; diff --git a/solutions/2395. Find Subarrays With Equal Sum/2395.cpp b/solutions/2395. Find Subarrays With Equal Sum/2395.cpp new file mode 100644 index 00000000000..dbf6dc700af --- /dev/null +++ b/solutions/2395. Find Subarrays With Equal Sum/2395.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool findSubarrays(vector& nums) { + unordered_set seen; + + for (int i = 1; i < nums.size(); ++i) + if (!seen.insert(nums[i - 1] + nums[i]).second) + return true; + + return false; + } +}; diff --git a/solutions/2395. Find Subarrays With Equal Sum/2395.java b/solutions/2395. Find Subarrays With Equal Sum/2395.java new file mode 100644 index 00000000000..54118792870 --- /dev/null +++ b/solutions/2395. Find Subarrays With Equal Sum/2395.java @@ -0,0 +1,14 @@ +class Solution { + public boolean findSubarrays(int[] nums) { + Set seen = new HashSet<>(); + + for (int i = 1; i < nums.length; ++i) { + final int sum = nums[i - 1] + nums[i]; + if (seen.contains(sum)) + return true; + seen.add(sum); + } + + return false; + } +} diff --git a/solutions/2395. Find Subarrays With Equal Sum/2395.py b/solutions/2395. Find Subarrays With Equal Sum/2395.py new file mode 100644 index 00000000000..03a69f24229 --- /dev/null +++ b/solutions/2395. Find Subarrays With Equal Sum/2395.py @@ -0,0 +1,11 @@ +class Solution: + def findSubarrays(self, nums: List[int]) -> bool: + seen = set() + + for a, b in zip(nums, nums[1:]): + summ = a + b + if summ in seen: + return True + seen.add(summ) + + return False diff --git a/solutions/2396. Strictly Palindromic Number/2396.cpp b/solutions/2396. Strictly Palindromic Number/2396.cpp new file mode 100644 index 00000000000..51be697d299 --- /dev/null +++ b/solutions/2396. Strictly Palindromic Number/2396.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool isStrictlyPalindromic(int n) { + return false; + } +}; diff --git a/solutions/2396. Strictly Palindromic Number/2396.java b/solutions/2396. Strictly Palindromic Number/2396.java new file mode 100644 index 00000000000..ab01b960544 --- /dev/null +++ b/solutions/2396. Strictly Palindromic Number/2396.java @@ -0,0 +1,5 @@ +class Solution { + public boolean isStrictlyPalindromic(int n) { + return false; + } +} diff --git a/solutions/2396. Strictly Palindromic Number/2396.py b/solutions/2396. Strictly Palindromic Number/2396.py new file mode 100644 index 00000000000..6599afb3e4b --- /dev/null +++ b/solutions/2396. Strictly Palindromic Number/2396.py @@ -0,0 +1,3 @@ +class Solution: + def isStrictlyPalindromic(self, n: int) -> bool: + return False diff --git a/solutions/2397. Maximum Rows Covered by Columns/2397.cpp b/solutions/2397. Maximum Rows Covered by Columns/2397.cpp new file mode 100644 index 00000000000..e1e57be471b --- /dev/null +++ b/solutions/2397. Maximum Rows Covered by Columns/2397.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int maximumRows(vector>& matrix, int numSelect) { + int ans = 0; + dfs(matrix, /*colIndex=*/0, numSelect, /*mask=*/0, ans); + return ans; + } + + private: + void dfs(const vector>& matrix, int colIndex, int leftColsCount, + int mask, int& ans) { + if (leftColsCount == 0) { + ans = max(ans, getAllZerosRowCount(matrix, mask)); + return; + } + if (colIndex == matrix[0].size()) + return; + + // Choose this column. + dfs(matrix, colIndex + 1, leftColsCount - 1, mask | 1 << colIndex, ans); + // Don't choose this column. + dfs(matrix, colIndex + 1, leftColsCount, mask, ans); + } + + int getAllZerosRowCount(const vector>& matrix, int mask) { + int count = 0; + for (const vector& row : matrix) { + bool isAllZeros = true; + for (int i = 0; i < row.size(); ++i) { + if (row[i] == 1 && (mask >> i & 1) == 0) { + isAllZeros = false; + break; + } + } + if (isAllZeros) + ++count; + } + return count; + } +}; diff --git a/solutions/2397. Maximum Rows Covered by Columns/2397.java b/solutions/2397. Maximum Rows Covered by Columns/2397.java new file mode 100644 index 00000000000..9d5f79ae666 --- /dev/null +++ b/solutions/2397. Maximum Rows Covered by Columns/2397.java @@ -0,0 +1,38 @@ +class Solution { + public int maximumRows(int[][] matrix, int numSelect) { + dfs(matrix, /*colIndex=*/0, numSelect, /*mask=*/0); + return ans; + } + + private int ans = 0; + + private void dfs(int[][] matrix, int colIndex, int leftColsCount, int mask) { + if (leftColsCount == 0) { + ans = Math.max(ans, getAllZerosRowCount(matrix, mask)); + return; + } + if (colIndex == matrix[0].length) + return; + + // Choose this column. + dfs(matrix, colIndex + 1, leftColsCount - 1, mask | 1 << colIndex); + // Don't choose this column. + dfs(matrix, colIndex + 1, leftColsCount, mask); + } + + int getAllZerosRowCount(int[][] matrix, int mask) { + int count = 0; + for (int[] row : matrix) { + boolean isAllZeros = true; + for (int i = 0; i < row.length; ++i) { + if (row[i] == 1 && (mask >> i & 1) == 0) { + isAllZeros = false; + break; + } + } + if (isAllZeros) + ++count; + } + return count; + } +} diff --git a/solutions/2397. Maximum Rows Covered by Columns/2397.py b/solutions/2397. Maximum Rows Covered by Columns/2397.py new file mode 100644 index 00000000000..cf68f93a688 --- /dev/null +++ b/solutions/2397. Maximum Rows Covered by Columns/2397.py @@ -0,0 +1,32 @@ +class Solution: + def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int: + ans = 0 + + def dfs(colIndex: int, leftColsCount: int, mask: int): + nonlocal ans + if leftColsCount == 0: + ans = max(ans, self._getAllZerosRowCount(matrix, mask)) + return + + if colIndex == len(matrix[0]): + return + + # Choose this column. + dfs(colIndex + 1, leftColsCount - 1, mask | 1 << colIndex) + # Don't choose this column. + dfs(colIndex + 1, leftColsCount, mask) + + dfs(0, numSelect, 0) + return ans + + def _getAllZerosRowCount(self, matrix: List[List[int]], mask: int) -> int: + count = 0 + for row in matrix: + isAllZeros = True + for i, cell in enumerate(row): + if cell == 1 and (mask >> i & 1) == 0: + isAllZeros = False + break + if isAllZeros: + count += 1 + return count diff --git a/solutions/2398. Maximum Number of Robots Within Budget/2398.cpp b/solutions/2398. Maximum Number of Robots Within Budget/2398.cpp new file mode 100644 index 00000000000..9f26c8a1247 --- /dev/null +++ b/solutions/2398. Maximum Number of Robots Within Budget/2398.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int maximumRobots(vector& chargeTimes, vector& runningCosts, + long long budget) { + long cost = 0; + deque maxQ; // Stores `chargeTimes[i]`. + + int j = 0; // window's range := [i..j], so k = i - j + 1 + for (int i = 0; i < chargeTimes.size(); ++i) { + cost += runningCosts[i]; + while (!maxQ.empty() && maxQ.back() < chargeTimes[i]) + maxQ.pop_back(); + maxQ.push_back(chargeTimes[i]); + if (maxQ.front() + (i - j + 1) * cost > budget) { + if (maxQ.front() == chargeTimes[j]) + maxQ.pop_front(); + cost -= runningCosts[j++]; + } + } + + return chargeTimes.size() - j; + } +}; diff --git a/solutions/2398. Maximum Number of Robots Within Budget/2398.java b/solutions/2398. Maximum Number of Robots Within Budget/2398.java new file mode 100644 index 00000000000..83fb7d04593 --- /dev/null +++ b/solutions/2398. Maximum Number of Robots Within Budget/2398.java @@ -0,0 +1,22 @@ +class Solution { + public int maximumRobots(int[] chargeTimes, int[] runningCosts, long budget) { + long cost = 0; + // Stores `chargeTimes[i]`. + Deque maxQ = new ArrayDeque<>(); + + int j = 0; // window's range := [i..j], so k = i - j + 1 + for (int i = 0; i < chargeTimes.length; ++i) { + cost += runningCosts[i]; + while (!maxQ.isEmpty() && maxQ.peekLast() < chargeTimes[i]) + maxQ.pollLast(); + maxQ.offerLast(chargeTimes[i]); + if (maxQ.peekFirst() + (i - j + 1) * cost > budget) { + if (maxQ.peekFirst() == chargeTimes[j]) + maxQ.pollFirst(); + cost -= runningCosts[j++]; + } + } + + return chargeTimes.length - j; + } +} diff --git a/solutions/2398. Maximum Number of Robots Within Budget/2398.py b/solutions/2398. Maximum Number of Robots Within Budget/2398.py new file mode 100644 index 00000000000..cfd784c7742 --- /dev/null +++ b/solutions/2398. Maximum Number of Robots Within Budget/2398.py @@ -0,0 +1,18 @@ +class Solution: + def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: + cost = 0 + maxQ = collections.deque() # Stores `chargeTimes[i]`. + + j = 0 # window's range := [i..j], so k = i - j + 1 + for i, (chargeTime, runningCost) in enumerate(zip(chargeTimes, runningCosts)): + cost += runningCost + while maxQ and maxQ[-1] < chargeTime: + maxQ.pop() + maxQ.append(chargeTime) + if maxQ[0] + (i - j + 1) * cost > budget: + if maxQ[0] == chargeTimes[j]: + maxQ.popleft() + cost -= runningCosts[j] + j += 1 + + return len(chargeTimes) - j diff --git a/solutions/2399. Check Distances Between Same Letters/2399.cpp b/solutions/2399. Check Distances Between Same Letters/2399.cpp new file mode 100644 index 00000000000..d9ee746c6e1 --- /dev/null +++ b/solutions/2399. Check Distances Between Same Letters/2399.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool checkDistances(string s, vector& distance) { + vector firstSeenIndex(26, -1); + + for (int i = 0; i < s.length(); ++i) { + const int j = s[i] - 'a'; + int& prevIndex = firstSeenIndex[j]; + if (prevIndex != -1 && i - prevIndex - 1 != distance[j]) + return false; + prevIndex = i; + } + + return true; + } +}; diff --git a/solutions/2399. Check Distances Between Same Letters/2399.java b/solutions/2399. Check Distances Between Same Letters/2399.java new file mode 100644 index 00000000000..79278aff335 --- /dev/null +++ b/solutions/2399. Check Distances Between Same Letters/2399.java @@ -0,0 +1,16 @@ +class Solution { + public boolean checkDistances(String s, int[] distance) { + int[] firstSeenIndex = new int[26]; + Arrays.fill(firstSeenIndex, -1); + + for (int i = 0; i < s.length(); ++i) { + final int j = s.charAt(i) - 'a'; + final int prevIndex = firstSeenIndex[j]; + if (prevIndex != -1 && i - prevIndex - 1 != distance[j]) + return false; + firstSeenIndex[j] = i; + } + + return true; + } +} diff --git a/solutions/2399. Check Distances Between Same Letters/2399.py b/solutions/2399. Check Distances Between Same Letters/2399.py new file mode 100644 index 00000000000..e34669871a3 --- /dev/null +++ b/solutions/2399. Check Distances Between Same Letters/2399.py @@ -0,0 +1,12 @@ +class Solution: + def checkDistances(self, s: str, distance: List[int]) -> bool: + firstSeenIndex = [-1] * 26 + + for i, c in enumerate(s): + j = ord(c) - ord('a') + prevIndex = firstSeenIndex[j] + if prevIndex != -1 and i - prevIndex - 1 != distance[j]: + return False + firstSeenIndex[j] = i + + return True diff --git a/solutions/24. Swap Nodes in Pairs/24.cpp b/solutions/24. Swap Nodes in Pairs/24.cpp new file mode 100644 index 00000000000..cd598cdb97a --- /dev/null +++ b/solutions/24. Swap Nodes in Pairs/24.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + ListNode* swapPairs(ListNode* head) { + const int length = getLength(head); + ListNode dummy(0, head); + ListNode* prev = &dummy; + ListNode* curr = head; + + for (int i = 0; i < length / 2; ++i) { + ListNode* next = curr->next; + curr->next = next->next; + next->next = prev->next; + prev->next = next; + prev = curr; + curr = curr->next; + } + + return dummy.next; + } + + private: + int getLength(ListNode* head) { + int length = 0; + for (ListNode* curr = head; curr; curr = curr->next) + ++length; + return length; + } +}; diff --git a/solutions/24. Swap Nodes in Pairs/24.java b/solutions/24. Swap Nodes in Pairs/24.java new file mode 100644 index 00000000000..e06fab3c53c --- /dev/null +++ b/solutions/24. Swap Nodes in Pairs/24.java @@ -0,0 +1,26 @@ +class Solution { + public ListNode swapPairs(ListNode head) { + final int length = getLength(head); + ListNode dummy = new ListNode(0, head); + ListNode prev = dummy; + ListNode curr = head; + + for (int i = 0; i < length / 2; ++i) { + ListNode next = curr.next; + curr.next = next.next; + next.next = curr; + prev.next = next; + prev = curr; + curr = curr.next; + } + + return dummy.next; + } + + private int getLength(ListNode head) { + int length = 0; + for (ListNode curr = head; curr != null; curr = curr.next) + ++length; + return length; + } +} diff --git a/solutions/24. Swap Nodes in Pairs/24.py b/solutions/24. Swap Nodes in Pairs/24.py new file mode 100644 index 00000000000..2a875cac990 --- /dev/null +++ b/solutions/24. Swap Nodes in Pairs/24.py @@ -0,0 +1,23 @@ +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + def getLength(head: ListNode) -> int: + length = 0 + while head: + length += 1 + head = head.next + return length + + length = getLength(head) + dummy = ListNode(0, head) + prev = dummy + curr = head + + for _ in range(length // 2): + next = curr.next + curr.next = next.next + next.next = prev.next + prev.next = next + prev = curr + curr = curr.next + + return dummy.next diff --git a/solutions/240. Search a 2D Matrix II/240.cpp b/solutions/240. Search a 2D Matrix II/240.cpp new file mode 100644 index 00000000000..3fd5f8d2696 --- /dev/null +++ b/solutions/240. Search a 2D Matrix II/240.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool searchMatrix(vector>& matrix, int target) { + int r = 0; + int c = matrix[0].size() - 1; + + while (r < matrix.size() && c >= 0) { + if (matrix[r][c] == target) + return true; + if (matrix[r][c] > target) + --c; + else + ++r; + } + + return false; + } +}; diff --git a/solutions/240. Search a 2D Matrix II/240.java b/solutions/240. Search a 2D Matrix II/240.java new file mode 100644 index 00000000000..e92cb5fa4fd --- /dev/null +++ b/solutions/240. Search a 2D Matrix II/240.java @@ -0,0 +1,17 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int r = 0; + int c = matrix[0].length - 1; + + while (r <= matrix.length && c >= 0) { + if (matrix[r][c] == target) + return true; + if (matrix[r][c] > target) + --c; + else + ++r; + } + + return false; + } +} diff --git a/solutions/240. Search a 2D Matrix II/240.py b/solutions/240. Search a 2D Matrix II/240.py new file mode 100644 index 00000000000..3ad108e5310 --- /dev/null +++ b/solutions/240. Search a 2D Matrix II/240.py @@ -0,0 +1,14 @@ +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + r = 0 + c = len(matrix[0]) - 1 + + while r < len(matrix) and c >= 0: + if matrix[r][c] == target: + return True + if target < matrix[r][c]: + c -= 1 + else: + r += 1 + + return False diff --git a/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.cpp b/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.cpp new file mode 100644 index 00000000000..66396c21e06 --- /dev/null +++ b/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int numberOfWays(int startPos, int endPos, int k) { + // leftStep + rightStep = k + // rightStep - leftStep = endPos - startPos + // 2 * rightStep = k + endPos - startPos + // rightStep = (k + endPos - startPos) / 2 + const int val = k + endPos - startPos; + if (val < 0 || val % 2 == 1) + return 0; + const int rightStep = val / 2; + const int leftStep = k - rightStep; + if (leftStep < 0) + return 0; + return nCk(leftStep + rightStep, min(leftStep, rightStep)); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // C(n, k) = C(n - 1, k) + C(n - 1, k - 1) + int nCk(int n, int k) { + // dp[i] := C(n so far, i) + vector dp(k + 1); + dp[0] = 1; + + while (n-- > 0) // Calculate n times. + for (int j = k; j > 0; --j) { + dp[j] += dp[j - 1]; + dp[j] %= kMod; + } + + return dp[k]; + } +}; diff --git a/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.java b/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.java new file mode 100644 index 00000000000..df837813c4e --- /dev/null +++ b/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.java @@ -0,0 +1,32 @@ +class Solution { + public int numberOfWays(int startPos, int endPos, int k) { + // leftStep + rightStep = k + // rightStep - leftStep = endPos - startPos + // 2 * rightStep = k + endPos - startPos + // rightStep = (k + endPos - startPos) / 2 + final int val = k + endPos - startPos; + if (val < 0 || val % 2 == 1) + return 0; + final int rightStep = val / 2; + final int leftStep = k - rightStep; + if (leftStep < 0) + return 0; + return nCk(leftStep + rightStep, Math.min(leftStep, rightStep)); + } + + // C(n, k) = C(n - 1, k) + C(n - 1, k - 1) + private int nCk(int n, int k) { + final int kMod = 1_000_000_007; + // dp[i] := C(n so far, i) + int[] dp = new int[k + 1]; + dp[0] = 1; + + while (n-- > 0) // Calculate n times. + for (int j = k; j > 0; --j) { + dp[j] += dp[j - 1]; + dp[j] %= kMod; + } + + return dp[k]; + } +} diff --git a/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.py b/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.py new file mode 100644 index 00000000000..68fb1fdb813 --- /dev/null +++ b/solutions/2400. Number of Ways to Reach a Position After Exactly k Steps/2400.py @@ -0,0 +1,27 @@ +class Solution: + def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: + # leftStep + rightStep = k + # rightStep - leftStep = endPos - startPos + # 2 * rightStep = k + endPos - startPos + # rightStep = (k + endPos - startPos) // 2 + val = k + endPos - startPos + if val < 0 or val % 2 == 1: + return 0 + rightStep = val // 2 + leftStep = k - rightStep + if leftStep < 0: + return 0 + return self._nCk(leftStep + rightStep, min(leftStep, rightStep)) + + # C(n, k) = C(n - 1, k) + C(n - 1, k - 1) + def _nCk(self, n: int, k: int) -> int: + kMod = 1_000_000_007 + # dp[i] := C(n so far, i) + dp = [1] + [0] * k + + for _ in range(n): # Calculate n times. + for j in range(k, 0, -1): + dp[j] += dp[j - 1] + dp[j] %= kMod + + return dp[k] diff --git a/solutions/2401. Longest Nice Subarray/2401.cpp b/solutions/2401. Longest Nice Subarray/2401.cpp new file mode 100644 index 00000000000..de57eefbf84 --- /dev/null +++ b/solutions/2401. Longest Nice Subarray/2401.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int longestNiceSubarray(vector& nums) { + int ans = 0; + int used = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + while (used & nums[r]) + used ^= nums[l++]; + used |= nums[r]; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/2401. Longest Nice Subarray/2401.java b/solutions/2401. Longest Nice Subarray/2401.java new file mode 100644 index 00000000000..000ffbf3bcc --- /dev/null +++ b/solutions/2401. Longest Nice Subarray/2401.java @@ -0,0 +1,15 @@ +class Solution { + public int longestNiceSubarray(int[] nums) { + int ans = 0; + int used = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + while ((used & nums[r]) > 0) + used ^= nums[l++]; + used |= nums[r]; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/2401. Longest Nice Subarray/2401.py b/solutions/2401. Longest Nice Subarray/2401.py new file mode 100644 index 00000000000..4643cac2196 --- /dev/null +++ b/solutions/2401. Longest Nice Subarray/2401.py @@ -0,0 +1,14 @@ +class Solution: + def longestNiceSubarray(self, nums: List[int]) -> int: + ans = 0 + used = 0 + + l = 0 + for r, num in enumerate(nums): + while used & num: + used ^= nums[l] + l += 1 + used |= num + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/2402. Meeting Rooms III/2402.cpp b/solutions/2402. Meeting Rooms III/2402.cpp new file mode 100644 index 00000000000..187b91fd08e --- /dev/null +++ b/solutions/2402. Meeting Rooms III/2402.cpp @@ -0,0 +1,45 @@ +struct T { + long endTime; + int roomId; +}; + +class Solution { + public: + int mostBooked(int n, vector>& meetings) { + vector count(n); + + ranges::sort(meetings); + + auto compare = [](const T& a, const T& b) { + return a.endTime == b.endTime ? a.roomId > b.roomId + : a.endTime > b.endTime; + }; + priority_queue, decltype(compare)> occupied(compare); + priority_queue, greater<>> availableRoomIds; + + for (int i = 0; i < n; ++i) + availableRoomIds.push(i); + + for (const vector& meeting : meetings) { + const int start = meeting[0]; + const int end = meeting[1]; + // Push meetings ending before this `meeting` in occupied to the + // `availableRoomsIds`. + while (!occupied.empty() && occupied.top().endTime <= start) + availableRoomIds.push(occupied.top().roomId), occupied.pop(); + if (availableRoomIds.empty()) { + const auto [newStart, roomId] = occupied.top(); + occupied.pop(); + ++count[roomId]; + occupied.push({newStart + (end - start), roomId}); + } else { + const int roomId = availableRoomIds.top(); + availableRoomIds.pop(); + ++count[roomId]; + occupied.push({end, roomId}); + } + } + + return ranges::max_element(count) - count.begin(); + } +}; diff --git a/solutions/2402. Meeting Rooms III/2402.java b/solutions/2402. Meeting Rooms III/2402.java new file mode 100644 index 00000000000..fc8ba7ccda8 --- /dev/null +++ b/solutions/2402. Meeting Rooms III/2402.java @@ -0,0 +1,49 @@ +class T { + public long endTime; + public int roomId; + public T(long endTime, int roomId) { + this.endTime = endTime; + this.roomId = roomId; + } +} + +class Solution { + public int mostBooked(int n, int[][] meetings) { + int[] count = new int[n]; + + Arrays.sort(meetings, (a, b) -> a[0] - b[0]); + + Queue occupied = + new PriorityQueue<>((a, b) + -> a.endTime == b.endTime ? Integer.compare(a.roomId, b.roomId) + : Long.compare(a.endTime, b.endTime)); + Queue availableRoomIds = new PriorityQueue<>(); + + for (int i = 0; i < n; ++i) + availableRoomIds.offer(i); + + for (int[] meeting : meetings) { + final int start = meeting[0]; + final int end = meeting[1]; + // Push meetings ending before this `meeting` in occupied to the + // `availableRoomsIds`. + while (!occupied.isEmpty() && occupied.peek().endTime <= start) + availableRoomIds.offer(occupied.poll().roomId); + if (availableRoomIds.isEmpty()) { + T t = occupied.poll(); + ++count[t.roomId]; + occupied.offer(new T(t.endTime + (end - start), t.roomId)); + } else { + final int roomId = availableRoomIds.poll(); + ++count[roomId]; + occupied.offer(new T(end, roomId)); + } + } + + int maxIndex = 0; + for (int i = 0; i < n; ++i) + if (count[i] > count[maxIndex]) + maxIndex = i; + return maxIndex; + } +} diff --git a/solutions/2402. Meeting Rooms III/2402.py b/solutions/2402. Meeting Rooms III/2402.py new file mode 100644 index 00000000000..d83f4284f1a --- /dev/null +++ b/solutions/2402. Meeting Rooms III/2402.py @@ -0,0 +1,25 @@ +class Solution: + def mostBooked(self, n: int, meetings: List[List[int]]) -> int: + count = [0] * n + + meetings.sort() + + occupied = [] # (endTime, roomId) + availableRoomIds = [i for i in range(n)] + heapq.heapify(availableRoomIds) + + for start, end in meetings: + # Push meetings ending before this `meeting` in occupied to the + # `availableRoomsIds`. + while occupied and occupied[0][0] <= start: + heapq.heappush(availableRoomIds, heapq.heappop(occupied)[1]) + if availableRoomIds: + roomId = heapq.heappop(availableRoomIds) + count[roomId] += 1 + heapq.heappush(occupied, (end, roomId)) + else: + newStart, roomId = heapq.heappop(occupied) + count[roomId] += 1 + heapq.heappush(occupied, (newStart + (end - start), roomId)) + + return count.index(max(count)) diff --git a/solutions/2403. Minimum Time to Kill All Monsters/2403.cpp b/solutions/2403. Minimum Time to Kill All Monsters/2403.cpp new file mode 100644 index 00000000000..c61e5fb0ac0 --- /dev/null +++ b/solutions/2403. Minimum Time to Kill All Monsters/2403.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long minimumTime(vector& power) { + const int n = power.size(); + const int maxMask = 1 << n; + // dp[i] := the minimum number of days needed to defeat the monsters, where + // i is the bitmask of the monsters + vector dp(maxMask, LONG_MAX); + dp[0] = 0; + + for (unsigned mask = 1; mask < maxMask; ++mask) { + const int currentGain = popcount(mask); + for (int i = 0; i < n; ++i) + if (mask >> i & 1) + dp[mask] = + min(dp[mask], + dp[mask & ~(1 << i)] + + static_cast(ceil(power[i] * 1.0 / currentGain))); + } + + return dp.back(); + } +}; diff --git a/solutions/2403. Minimum Time to Kill All Monsters/2403.java b/solutions/2403. Minimum Time to Kill All Monsters/2403.java new file mode 100644 index 00000000000..303b220177a --- /dev/null +++ b/solutions/2403. Minimum Time to Kill All Monsters/2403.java @@ -0,0 +1,21 @@ +class Solution { + public long minimumTime(int[] power) { + final int n = power.length; + final int maxMask = 1 << n; + // dp[i] := the minimum number of days needed to defeat the monsters, where + // i is the bitmask of the monsters + long[] dp = new long[maxMask]; + Arrays.fill(dp, Long.MAX_VALUE); + dp[0] = 0; + + for (int mask = 1; mask < maxMask; ++mask) { + final int currentGain = Integer.bitCount(mask); + for (int i = 0; i < n; ++i) + if ((mask >> i & 1) == 1) + dp[mask] = Math.min(dp[mask], dp[mask & ~(1 << i)] + + (int) (Math.ceil(power[i] * 1.0 / currentGain))); + } + + return dp[maxMask - 1]; + } +} diff --git a/solutions/2403. Minimum Time to Kill All Monsters/2403.py b/solutions/2403. Minimum Time to Kill All Monsters/2403.py new file mode 100644 index 00000000000..4ee2ded2aa4 --- /dev/null +++ b/solutions/2403. Minimum Time to Kill All Monsters/2403.py @@ -0,0 +1,17 @@ +class Solution: + def minimumTime(self, power: List[int]) -> int: + n = len(power) + maxMask = 1 << n + # dp[i] := the minimum number of days needed to defeat the monsters, where + # i is the bitmask of the monsters + dp = [math.inf] * maxMask + dp[0] = 0 + + for mask in range(1, maxMask): + currentGain = mask.bit_count() + for i in range(n): + if mask >> i & 1: + dp[mask] = min(dp[mask], dp[mask & ~(1 << i)] + + int(math.ceil(power[i] / currentGain))) + + return dp[-1] diff --git a/solutions/2404. Most Frequent Even Element/2404.cpp b/solutions/2404. Most Frequent Even Element/2404.cpp new file mode 100644 index 00000000000..efef7efc71c --- /dev/null +++ b/solutions/2404. Most Frequent Even Element/2404.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int mostFrequentEven(vector& nums) { + int ans = -1; + unordered_map count; + + for (const int num : nums) { + if (num % 2 == 1) + continue; + const int newCount = ++count[num]; + const int maxCount = count[ans]; + if (newCount > maxCount || newCount == maxCount && num < ans) + ans = num; + } + + return ans; + } +}; diff --git a/solutions/2404. Most Frequent Even Element/2404.java b/solutions/2404. Most Frequent Even Element/2404.java new file mode 100644 index 00000000000..d08e9b4af9f --- /dev/null +++ b/solutions/2404. Most Frequent Even Element/2404.java @@ -0,0 +1,17 @@ +class Solution { + public int mostFrequentEven(int[] nums) { + int ans = -1; + Map count = new HashMap<>(); + + for (final int num : nums) { + if (num % 2 == 1) + continue; + final int newCount = count.merge(num, 1, Integer::sum); + final int maxCount = count.getOrDefault(ans, 0); + if (newCount > maxCount || newCount == maxCount && num < ans) + ans = num; + } + + return ans; + } +} diff --git a/solutions/2404. Most Frequent Even Element/2404.py b/solutions/2404. Most Frequent Even Element/2404.py new file mode 100644 index 00000000000..f154308ee3e --- /dev/null +++ b/solutions/2404. Most Frequent Even Element/2404.py @@ -0,0 +1,15 @@ +class Solution: + def mostFrequentEven(self, nums: List[int]) -> int: + ans = -1 + count = collections.Counter() + + for num in nums: + if num % 2 == 1: + continue + count[num] += 1 + newCount = count[num] + maxCount = count[ans] + if newCount > maxCount or newCount == maxCount and num < ans: + ans = num + + return ans diff --git a/solutions/2405. Optimal Partition of String/2405.cpp b/solutions/2405. Optimal Partition of String/2405.cpp new file mode 100644 index 00000000000..40fdcd56381 --- /dev/null +++ b/solutions/2405. Optimal Partition of String/2405.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int partitionString(string s) { + int ans = 1; + int used = 0; + + for (const char c : s) { + const int i = c - 'a'; + if (used >> i & 1) { + used = 1 << i; + ++ans; + } else { + used |= 1 << i; + } + } + + return ans; + } +}; diff --git a/solutions/2405. Optimal Partition of String/2405.java b/solutions/2405. Optimal Partition of String/2405.java new file mode 100644 index 00000000000..602ba34b527 --- /dev/null +++ b/solutions/2405. Optimal Partition of String/2405.java @@ -0,0 +1,18 @@ +class Solution { + public int partitionString(String s) { + int ans = 1; + int used = 0; + + for (final char c : s.toCharArray()) { + final int i = c - 'a'; + if ((used >> i & 1) == 1) { + used = 1 << i; + ++ans; + } else { + used |= 1 << i; + } + } + + return ans; + } +} diff --git a/solutions/2405. Optimal Partition of String/2405.py b/solutions/2405. Optimal Partition of String/2405.py new file mode 100644 index 00000000000..955ff1e659e --- /dev/null +++ b/solutions/2405. Optimal Partition of String/2405.py @@ -0,0 +1,14 @@ +class Solution: + def partitionString(self, s: str) -> int: + ans = 1 + used = 0 + + for c in s: + i = ord(c) - ord('a') + if used >> i & 1: + used = 1 << i + ans += 1 + else: + used |= 1 << i + + return ans diff --git a/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.cpp b/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.cpp new file mode 100644 index 00000000000..62bbab38c93 --- /dev/null +++ b/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + // Similar to 253. Meeting Rooms II + int minGroups(vector>& intervals) { + // Stores `right`s. + priority_queue, greater<>> minHeap; + + ranges::sort(intervals); + + for (const vector& interval : intervals) { + if (!minHeap.empty() && interval[0] > minHeap.top()) + minHeap.pop(); // There is no overlaps, so we can reuse the same group. + minHeap.push(interval[1]); + } + + return minHeap.size(); + } +}; diff --git a/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.java b/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.java new file mode 100644 index 00000000000..8cf1405dca4 --- /dev/null +++ b/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.java @@ -0,0 +1,17 @@ +class Solution { + // Similar to 253. Meeting Rooms II + public int minGroups(int[][] intervals) { + // Stores `right`s. + Queue minHeap = new PriorityQueue<>((a, b) -> a - b); + + Arrays.sort(intervals, (a, b) -> (a[0] - b[0])); + + for (int[] interval : intervals) { + if (!minHeap.isEmpty() && interval[0] > minHeap.peek()) + minHeap.poll(); // There is no overlaps, so we can reuse the same group. + minHeap.offer(interval[1]); + } + + return minHeap.size(); + } +} diff --git a/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.py b/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.py new file mode 100644 index 00000000000..389e13add76 --- /dev/null +++ b/solutions/2406. Divide Intervals Into Minimum Number of Groups/2406.py @@ -0,0 +1,12 @@ +class Solution: + # Similar to 253. Meeting Rooms II + def minGroups(self, intervals: List[List[int]]) -> int: + minHeap = [] # Stores `right`s. + + for left, right in sorted(intervals): + if minHeap and left > minHeap[0]: + # There is no overlaps, so we can reuse the same group. + heapq.heappop(minHeap) + heapq.heappush(minHeap, right) + + return len(minHeap) diff --git a/solutions/2407. Longest Increasing Subsequence II/2407.cpp b/solutions/2407. Longest Increasing Subsequence II/2407.cpp new file mode 100644 index 00000000000..bddad980981 --- /dev/null +++ b/solutions/2407. Longest Increasing Subsequence II/2407.cpp @@ -0,0 +1,89 @@ +struct SegmentTreeNode { + int lo; + int hi; + int maxLength; + unique_ptr left; + unique_ptr right; + // maxLength := the maximum length of LIS ending in [lo..hi] + SegmentTreeNode(int lo, int hi, int maxLength, + unique_ptr left = nullptr, + unique_ptr right = nullptr) + : lo(lo), + hi(hi), + maxLength(maxLength), + left(move(left)), + right(move(right)) {} +}; + +class SegmentTree { + public: + explicit SegmentTree() : root(make_unique(0, 1e5 + 1, 0)) {} + + void updateRange(int i, int j, int maxLength) { + update(root, i, j, maxLength); + } + + // queryRange(i, j) := the maximum length of LIS ending in [i..j] + int queryRange(int i, int j) { + return query(root, i, j); + } + + private: + std::unique_ptr root; + + void update(unique_ptr& root, int i, int j, int maxLength) { + if (root->lo == i && root->hi == j) { + root->maxLength = maxLength; + root->left = nullptr; + root->right = nullptr; + return; + } + const int mid = root->lo + (root->hi - root->lo) / 2; + if (root->left == nullptr) { + root->left = make_unique(root->lo, mid, root->maxLength); + root->right = + make_unique(mid + 1, root->hi, root->maxLength); + } + if (j <= mid) + update(root->left, i, j, maxLength); + else if (i > mid) + update(root->right, i, j, maxLength); + else { + update(root->left, i, mid, maxLength); + update(root->right, mid + 1, j, maxLength); + } + root->maxLength = max(root->left->maxLength, root->right->maxLength); + } + + int query(unique_ptr& root, int i, int j) { + if (root->left == nullptr) + return root->maxLength; + if (root->lo == i && root->hi == j) + return root->maxLength; + const int mid = root->lo + (root->hi - root->lo) / 2; + if (j <= mid) + return query(root->left, i, j); + if (i > mid) + return query(root->right, i, j); + return max(query(root->left, i, mid), query(root->right, mid + 1, j)); + } +}; + +class Solution { + public: + int lengthOfLIS(vector& nums, int k) { + int ans = 1; + SegmentTree tree; + + for (const int num : nums) { + const int left = max(1, num - k); + const int right = num - 1; + // the maximum length of LIS ending in [left..right] + the current number + const int maxLength = tree.queryRange(left, right) + 1; + ans = std::max(ans, maxLength); + tree.updateRange(num, num, maxLength); + } + + return ans; + } +}; diff --git a/solutions/2408. Design SQL/2408.cpp b/solutions/2408. Design SQL/2408.cpp new file mode 100644 index 00000000000..de23114c7c5 --- /dev/null +++ b/solutions/2408. Design SQL/2408.cpp @@ -0,0 +1,15 @@ +class SQL { + public: + void insertRow(string name, vector row) { + db[name].push_back(row); + } + + void deleteRow(string name, int rowId) {} + + string selectCell(string name, int rowId, int columnId) { + return db[name][rowId - 1][columnId - 1]; + } + + private: + unordered_map>> db; +}; diff --git a/solutions/2408. Design SQL/2408.java b/solutions/2408. Design SQL/2408.java new file mode 100644 index 00000000000..e53626d19e8 --- /dev/null +++ b/solutions/2408. Design SQL/2408.java @@ -0,0 +1,16 @@ +class SQL { + public SQL(List names, List columns) {} + + public void insertRow(String name, List row) { + db.putIfAbsent(name, new ArrayList<>()); + db.get(name).add(row); + } + + public void deleteRow(String name, int rowId) {} + + public String selectCell(String name, int rowId, int columnId) { + return db.get(name).get(rowId - 1).get(columnId - 1); + } + + private Map>> db = new HashMap<>(); +} diff --git a/solutions/2408. Design SQL/2408.py b/solutions/2408. Design SQL/2408.py new file mode 100644 index 00000000000..1826a3d0ff8 --- /dev/null +++ b/solutions/2408. Design SQL/2408.py @@ -0,0 +1,12 @@ +class SQL: + def __init__(self, names: List[str], columns: List[int]): + self.db: Dict[str, List[List[str]]] = collections.defaultdict(list) + + def insertRow(self, name: str, row: List[str]) -> None: + self.db[name].append(row) + + def deleteRow(self, name: str, rowId: int) -> None: + pass + + def selectCell(self, name: str, rowId: int, columnId: int) -> str: + return self.db[name][rowId - 1][columnId - 1] diff --git a/solutions/2409. Count Days Spent Together/2409.cpp b/solutions/2409. Count Days Spent Together/2409.cpp new file mode 100644 index 00000000000..64c195f7fa1 --- /dev/null +++ b/solutions/2409. Count Days Spent Together/2409.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, + string leaveBob) { + const int arriveA = toDays(arriveAlice); + const int leaveA = toDays(leaveAlice); + const int arriveB = toDays(arriveBob); + const int leaveB = toDays(leaveBob); + int ans = 0; + + for (int day = 1; day <= 365; ++day) + if (arriveA <= day && day <= leaveA && arriveB <= day && day <= leaveB) + ++ans; + + return ans; + } + + private: + const vector days{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + int toDays(const string& s) { + const int month = (s[0] - '0') * 10 + (s[1] - '0'); + const int day = (s[3] - '0') * 10 + (s[4] - '0'); + int prevDays = 0; + for (int m = 1; m < month; ++m) + prevDays += days[m]; + return prevDays + day; + } +}; diff --git a/solutions/2409. Count Days Spent Together/2409.java b/solutions/2409. Count Days Spent Together/2409.java new file mode 100644 index 00000000000..e79669fcd14 --- /dev/null +++ b/solutions/2409. Count Days Spent Together/2409.java @@ -0,0 +1,27 @@ +class Solution { + public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob, + String leaveBob) { + final int arriveA = toDays(arriveAlice); + final int leaveA = toDays(leaveAlice); + final int arriveB = toDays(arriveBob); + final int leaveB = toDays(leaveBob); + int ans = 0; + + for (int day = 1; day <= 365; ++day) + if (arriveA <= day && day <= leaveA && arriveB <= day && day <= leaveB) + ++ans; + + return ans; + } + + private final int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + private int toDays(final String s) { + final int month = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); + final int day = (s.charAt(3) - '0') * 10 + (s.charAt(4) - '0'); + int prevDays = 0; + for (int m = 1; m < month; ++m) + prevDays += days[m]; + return prevDays + day; + } +} diff --git a/solutions/2409. Count Days Spent Together/2409.py b/solutions/2409. Count Days Spent Together/2409.py new file mode 100644 index 00000000000..46719964d22 --- /dev/null +++ b/solutions/2409. Count Days Spent Together/2409.py @@ -0,0 +1,23 @@ +class Solution: + def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int: + days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + def toDays(s: str) -> int: + month = int(s[:2]) + day = int(s[3:]) + prevDays = 0 + for m in range(1, month): + prevDays += days[m] + return prevDays + day + + arriveA = toDays(arriveAlice) + leaveA = toDays(leaveAlice) + arriveB = toDays(arriveBob) + leaveB = toDays(leaveBob) + ans = 0 + + for day in range(1, 366): + if arriveA <= day and day <= leaveA and arriveB <= day and day <= leaveB: + ans += 1 + + return ans diff --git a/solutions/241. Different Ways to Add Parentheses/241.cpp b/solutions/241. Different Ways to Add Parentheses/241.cpp new file mode 100644 index 00000000000..087085841c1 --- /dev/null +++ b/solutions/241. Different Ways to Add Parentheses/241.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector diffWaysToCompute(string expression) { + return ways(expression, {}); + } + + private: + vector ways(const string& s, unordered_map>&& mem) { + if (const auto it = mem.find(s); it != mem.cend()) + return it->second; + + vector ans; + + for (int i = 0; i < s.length(); ++i) + if (ispunct(s[i])) + for (const int a : ways(s.substr(0, i), move(mem))) + for (const int b : ways(s.substr(i + 1), move(mem))) + if (s[i] == '+') + ans.push_back(a + b); + else if (s[i] == '-') + ans.push_back(a - b); + else + ans.push_back(a * b); + + return mem[s] = (ans.empty() ? vector{stoi(s)} : ans); + } +}; diff --git a/solutions/241. Different Ways to Add Parentheses/241.java b/solutions/241. Different Ways to Add Parentheses/241.java new file mode 100644 index 00000000000..b42323c51c6 --- /dev/null +++ b/solutions/241. Different Ways to Add Parentheses/241.java @@ -0,0 +1,30 @@ +class Solution { + public List diffWaysToCompute(String expression) { + return ways(expression, new HashMap<>()); + } + + private List ways(final String s, Map> mem) { + if (mem.containsKey(s)) + return mem.get(s); + + List ans = new ArrayList<>(); + + for (int i = 0; i < s.length(); ++i) + if (!Character.isDigit(s.charAt(i))) + for (final int a : ways(s.substring(0, i), mem)) + for (final int b : ways(s.substring(i + 1), mem)) + if (s.charAt(i) == '+') + ans.add(a + b); + else if (s.charAt(i) == '-') + ans.add(a - b); + else + ans.add(a * b); + + if (ans.isEmpty()) { // Single number + mem.put(s, Arrays.asList(Integer.parseInt(s))); + return mem.get(s); + } + mem.put(s, ans); + return ans; + } +} diff --git a/solutions/241. Different Ways to Add Parentheses/241.py b/solutions/241. Different Ways to Add Parentheses/241.py new file mode 100644 index 00000000000..0ba047fa217 --- /dev/null +++ b/solutions/241. Different Ways to Add Parentheses/241.py @@ -0,0 +1,12 @@ +class Solution: + @functools.lru_cache(None) + def diffWaysToCompute(self, expression: str) -> List[int]: + ans = [] + + for i, c in enumerate(expression): + if c in '+-*': + for a in self.diffWaysToCompute(expression[:i]): + for b in self.diffWaysToCompute(expression[i + 1:]): + ans.append(eval(str(a) + c + str(b))) + + return ans or [int(expression)] diff --git a/solutions/2410. Maximum Matching of Players With Trainers/2410.cpp b/solutions/2410. Maximum Matching of Players With Trainers/2410.cpp new file mode 100644 index 00000000000..0b568454118 --- /dev/null +++ b/solutions/2410. Maximum Matching of Players With Trainers/2410.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int matchPlayersAndTrainers(vector& players, vector& trainers) { + int ans = 0; + + ranges::sort(players); + ranges::sort(trainers); + + for (int i = 0; i < trainers.size(); ++i) + if (players[ans] <= trainers[i] && ++ans == players.size()) + return ans; + + return ans; + } +}; diff --git a/solutions/2410. Maximum Matching of Players With Trainers/2410.java b/solutions/2410. Maximum Matching of Players With Trainers/2410.java new file mode 100644 index 00000000000..d73b81ffbac --- /dev/null +++ b/solutions/2410. Maximum Matching of Players With Trainers/2410.java @@ -0,0 +1,14 @@ +class Solution { + public int matchPlayersAndTrainers(int[] players, int[] trainers) { + int ans = 0; + + Arrays.sort(players); + Arrays.sort(trainers); + + for (int i = 0; i < trainers.length; ++i) + if (players[ans] <= trainers[i] && ++ans == players.length) + return ans; + + return ans; + } +} diff --git a/solutions/2410. Maximum Matching of Players With Trainers/2410.py b/solutions/2410. Maximum Matching of Players With Trainers/2410.py new file mode 100644 index 00000000000..37ad0270ea1 --- /dev/null +++ b/solutions/2410. Maximum Matching of Players With Trainers/2410.py @@ -0,0 +1,16 @@ +class Solution: + def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int: + ans = 0 + + players.sort() + trainers.sort() + + for i, trainer in enumerate(trainers): + if players[ans] <= trainers[i]: + ans += 1 + if ans == len(players): + return ans + + return ans + + diff --git a/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.cpp b/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.cpp new file mode 100644 index 00000000000..d367ab4ebf5 --- /dev/null +++ b/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector smallestSubarrays(vector& nums) { + constexpr int kMaxBit = 30; + vector ans(nums.size(), 1); + // closest[j] := the closest index i s.t. the j-th bit of nums[i] is 1 + vector closest(kMaxBit); + + for (int i = nums.size() - 1; i >= 0; --i) + for (int j = 0; j < kMaxBit; ++j) { + if (nums[i] >> j & 1) + closest[j] = i; + ans[i] = max(ans[i], closest[j] - i + 1); + } + + return ans; + } +}; diff --git a/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.java b/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.java new file mode 100644 index 00000000000..31de60044b6 --- /dev/null +++ b/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.java @@ -0,0 +1,19 @@ +class Solution { + public int[] smallestSubarrays(int[] nums) { + final int kMaxBit = 30; + int[] ans = new int[nums.length]; + // closest[j] := the closest index i s.t. the j-th bit of nums[i] is 1 + int[] closest = new int[kMaxBit]; + + Arrays.fill(ans, 1); + + for (int i = nums.length - 1; i >= 0; --i) + for (int j = 0; j < kMaxBit; ++j) { + if ((nums[i] >> j & 1) == 1) + closest[j] = i; + ans[i] = Math.max(ans[i], closest[j] - i + 1); + } + + return ans; + } +} diff --git a/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.py b/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.py new file mode 100644 index 00000000000..678ac577da8 --- /dev/null +++ b/solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.py @@ -0,0 +1,14 @@ +class Solution: + def smallestSubarrays(self, nums: List[int]) -> List[int]: + kMaxBit = 30 + ans = [1] * len(nums) + # closest[j] := the closest index i s.t. the j-th bit of nums[i] is 1 + closest = [0] * kMaxBit + + for i in reversed(range(len(nums))): + for j in range(kMaxBit): + if nums[i] >> j & 1: + closest[j] = i + ans[i] = max(ans[i], closest[j] - i + 1) + + return ans diff --git a/solutions/2412. Minimum Money Required Before Transactions/2412.cpp b/solutions/2412. Minimum Money Required Before Transactions/2412.cpp new file mode 100644 index 00000000000..a0b667a754b --- /dev/null +++ b/solutions/2412. Minimum Money Required Before Transactions/2412.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + long long minimumMoney(vector>& transactions) { + long ans = 0; + long losses = 0; + + // Before picking the final transaction, perform any transaction that raises + // the required money. + for (const vector& t : transactions) { + const int cost = t[0]; + const int cashback = t[1]; + losses += max(0, cost - cashback); + } + + // Now, pick a transaction to be the final one. + for (const vector& t : transactions) { + const int cost = t[0]; + const int cashback = t[1]; + if (cost > cashback) + // The losses except this transaction: losses - (cost - cashback), so + // add the cost of this transaction = losses - (cost - cashback) + cost. + ans = max(ans, losses + cashback); + else + // The losses except this transaction: losses, so add the cost of this + // transaction = losses + cost. + ans = max(ans, losses + cost); + } + + return ans; + } +}; diff --git a/solutions/2412. Minimum Money Required Before Transactions/2412.java b/solutions/2412. Minimum Money Required Before Transactions/2412.java new file mode 100644 index 00000000000..722739a68d8 --- /dev/null +++ b/solutions/2412. Minimum Money Required Before Transactions/2412.java @@ -0,0 +1,30 @@ +class Solution { + public long minimumMoney(int[][] transactions) { + long ans = 0; + long losses = 0; + + // Before picking the final transaction, perform any transaction that raises + // the required money. + for (int[] t : transactions) { + final int cost = t[0]; + final int cashback = t[1]; + losses += Math.max(0, cost - cashback); + } + + // Now, pick a transaction to be the final one. + for (int[] t : transactions) { + final int cost = t[0]; + final int cashback = t[1]; + if (cost > cashback) + // The losses except this transaction: losses - (cost - cashback), so + // add the cost of this transaction = losses - (cost - cashback) + cost. + ans = Math.max(ans, losses + cashback); + else + // The losses except this transaction: losses, so add the cost of this + // transaction = losses + cost. + ans = Math.max(ans, losses + cost); + } + + return ans; + } +} diff --git a/solutions/2412. Minimum Money Required Before Transactions/2412.py b/solutions/2412. Minimum Money Required Before Transactions/2412.py new file mode 100644 index 00000000000..77623f0a1af --- /dev/null +++ b/solutions/2412. Minimum Money Required Before Transactions/2412.py @@ -0,0 +1,22 @@ +class Solution: + def minimumMoney(self, transactions: List[List[int]]) -> int: + ans = 0 + losses = 0 + + # Before picking the final transaction, perform any transaction that raises + # the required money. + for cost, cashback in transactions: + losses += max(0, cost - cashback) + + # Now, pick a transaction to be the final one. + for cost, cashback in transactions: + if cost > cashback: + # The losses except this transaction: losses - (cost - cashback), so + # add the cost of this transaction = losses - (cost - cashback) + cost. + ans = max(ans, losses + cashback) + else: + # The losses except this transaction: losses, so add the cost of this + # transaction = losses + cost. + ans = max(ans, losses + cost) + + return ans diff --git a/solutions/2413. Smallest Even Multiple/2413.cpp b/solutions/2413. Smallest Even Multiple/2413.cpp new file mode 100644 index 00000000000..0b4b4bd31d2 --- /dev/null +++ b/solutions/2413. Smallest Even Multiple/2413.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int smallestEvenMultiple(int n) { + return n * (n % 2 + 1); + } +}; diff --git a/solutions/2413. Smallest Even Multiple/2413.java b/solutions/2413. Smallest Even Multiple/2413.java new file mode 100644 index 00000000000..440fe6801e7 --- /dev/null +++ b/solutions/2413. Smallest Even Multiple/2413.java @@ -0,0 +1,5 @@ +class Solution { + public int smallestEvenMultiple(int n) { + return n * (n % 2 + 1); + } +} diff --git a/solutions/2413. Smallest Even Multiple/2413.py b/solutions/2413. Smallest Even Multiple/2413.py new file mode 100644 index 00000000000..5758c7fd57c --- /dev/null +++ b/solutions/2413. Smallest Even Multiple/2413.py @@ -0,0 +1,3 @@ +class Solution: + def smallestEvenMultiple(self, n: int) -> int: + return n * (n % 2 + 1) diff --git a/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.cpp b/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.cpp new file mode 100644 index 00000000000..2f0b0bad183 --- /dev/null +++ b/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int longestContinuousSubstring(string s) { + int ans = 1; + int runningLen = 1; + + for (int i = 1; i < s.length(); ++i) + if (s[i] == s[i - 1] + 1) + ans = max(ans, ++runningLen); + else + runningLen = 1; + + return ans; + } +}; diff --git a/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.java b/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.java new file mode 100644 index 00000000000..cfa53176a96 --- /dev/null +++ b/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.java @@ -0,0 +1,14 @@ +class Solution { + public int longestContinuousSubstring(String s) { + int ans = 1; + int runningLen = 1; + + for (int i = 1; i < s.length(); ++i) + if (s.charAt(i) == s.charAt(i - 1) + 1) + ans = Math.max(ans, ++runningLen); + else + runningLen = 1; + + return ans; + } +} diff --git a/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.py b/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.py new file mode 100644 index 00000000000..1016c5a1d11 --- /dev/null +++ b/solutions/2414. Length of the Longest Alphabetical Continuous Substring/2414.py @@ -0,0 +1,13 @@ +class Solution: + def longestContinuousSubstring(self, s: str) -> int: + ans = 1 + runningLen = 1 + + for a, b in zip(s, s[1:]): + if ord(a) + 1 == ord(b): + runningLen += 1 + ans = max(ans, runningLen) + else: + runningLen = 1 + + return ans diff --git a/solutions/2415. Reverse Odd Levels of Binary Tree/2415.cpp b/solutions/2415. Reverse Odd Levels of Binary Tree/2415.cpp new file mode 100644 index 00000000000..0655644f4f1 --- /dev/null +++ b/solutions/2415. Reverse Odd Levels of Binary Tree/2415.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + TreeNode* reverseOddLevels(TreeNode* root) { + dfs(root->left, root->right, true); + return root; + } + + private: + void dfs(TreeNode* left, TreeNode* right, bool isOddLevel) { + if (left == nullptr) + return; + if (isOddLevel) + swap(left->val, right->val); + dfs(left->left, right->right, !isOddLevel); + dfs(left->right, right->left, !isOddLevel); + } +}; diff --git a/solutions/2415. Reverse Odd Levels of Binary Tree/2415.java b/solutions/2415. Reverse Odd Levels of Binary Tree/2415.java new file mode 100644 index 00000000000..1d1cd362c3f --- /dev/null +++ b/solutions/2415. Reverse Odd Levels of Binary Tree/2415.java @@ -0,0 +1,18 @@ +class Solution { + public TreeNode reverseOddLevels(TreeNode root) { + dfs(root.left, root.right, true); + return root; + } + + private void dfs(TreeNode left, TreeNode right, boolean isOddLevel) { + if (left == null) + return; + if (isOddLevel) { + final int val = left.val; + left.val = right.val; + right.val = val; + } + dfs(left.left, right.right, !isOddLevel); + dfs(left.right, right.left, !isOddLevel); + } +} diff --git a/solutions/2415. Reverse Odd Levels of Binary Tree/2415.py b/solutions/2415. Reverse Odd Levels of Binary Tree/2415.py new file mode 100644 index 00000000000..a0715637c04 --- /dev/null +++ b/solutions/2415. Reverse Odd Levels of Binary Tree/2415.py @@ -0,0 +1,12 @@ +class Solution: + def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + def dfs(left: Optional[TreeNode], right: Optional[TreeNode], isOddLevel: bool) -> None: + if not left: + return + if isOddLevel: + left.val, right.val = right.val, left.val + dfs(left.left, right.right, not isOddLevel) + dfs(left.right, right.left, not isOddLevel) + + dfs(root.left, root.right, True) + return root diff --git a/solutions/2416. Sum of Prefix Scores of Strings/2416.cpp b/solutions/2416. Sum of Prefix Scores of Strings/2416.cpp new file mode 100644 index 00000000000..a6ab29241d9 --- /dev/null +++ b/solutions/2416. Sum of Prefix Scores of Strings/2416.cpp @@ -0,0 +1,44 @@ +struct TrieNode { + vector> children; + int count = 0; + TrieNode() : children(26) {} +}; + +class Solution { + public: + vector sumPrefixScores(vector& words) { + vector ans; + + for (const string& word : words) + insert(word); + + for (const string& word : words) + ans.push_back(getScore(word)); + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + ++node->count; + } + } + + int getScore(const string& word) { + shared_ptr node = root; + int score = 0; + for (const char c : word) { + node = node->children[c - 'a']; + score += node->count; + } + return score; + } +}; diff --git a/solutions/2416. Sum of Prefix Scores of Strings/2416.java b/solutions/2416. Sum of Prefix Scores of Strings/2416.java new file mode 100644 index 00000000000..d397b07d903 --- /dev/null +++ b/solutions/2416. Sum of Prefix Scores of Strings/2416.java @@ -0,0 +1,41 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int count = 0; +} + +class Solution { + public int[] sumPrefixScores(String[] words) { + int[] ans = new int[words.length]; + + for (final String word : words) + insert(word); + + for (int i = 0; i < words.length; ++i) + ans[i] = getScore(words[i]); + + return ans; + } + + private TrieNode root = new TrieNode(); + + private void insert(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + ++node.count; + } + } + + private int getScore(String word) { + TrieNode node = root; + int score = 0; + for (final char c : word.toCharArray()) { + node = node.children[c - 'a']; + score += node.count; + } + return score; + } +} diff --git a/solutions/2416. Sum of Prefix Scores of Strings/2416.py b/solutions/2416. Sum of Prefix Scores of Strings/2416.py new file mode 100644 index 00000000000..1dd8791b125 --- /dev/null +++ b/solutions/2416. Sum of Prefix Scores of Strings/2416.py @@ -0,0 +1,28 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.count = 0 + + +class Solution: + def sumPrefixScores(self, words: List[str]) -> List[int]: + root = TrieNode() + + def insert(word: str) -> None: + node: TrieNode = root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.count += 1 + + for word in words: + insert(word) + + def getScore(word: str) -> int: + node: TrieNode = root + score = 0 + for c in word: + node = node.children[c] + score += node.count + return score + + return [getScore(word) for word in words] diff --git a/solutions/2417. Closest Fair Integer/2417.cpp b/solutions/2417. Closest Fair Integer/2417.cpp new file mode 100644 index 00000000000..ee5c1d42a7d --- /dev/null +++ b/solutions/2417. Closest Fair Integer/2417.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int closestFair(int n) { + const int digitsCount = to_string(n).length(); + return digitsCount % 2 == 0 ? getEvenDigits(n) : getOddDigits(digitsCount); + } + + private: + long getOddDigits(int digitsCount) { + const int zeros = (digitsCount + 1) / 2; + const int ones = (digitsCount - 1) / 2; + return stoi('1' + string(zeros, '0') + string(ones, '1')); + } + + int getEvenDigits(int n) { + const int digitsCount = to_string(n).length(); + const long maxNum = stol('1' + string(digitsCount, '0')); + for (long num = n; num < maxNum; ++num) + if (isValidNum(num)) + return num; + return getOddDigits(digitsCount + 1); + } + + bool isValidNum(long num) { + int count = 0; + for (const char c : to_string(num)) + count += (c - '0') % 2 == 0 ? 1 : -1; + return count == 0; + } +}; diff --git a/solutions/2417. Closest Fair Integer/2417.java b/solutions/2417. Closest Fair Integer/2417.java new file mode 100644 index 00000000000..7648b931de5 --- /dev/null +++ b/solutions/2417. Closest Fair Integer/2417.java @@ -0,0 +1,28 @@ +class Solution { + public int closestFair(int n) { + final int digitsCount = String.valueOf(n).length(); + return digitsCount % 2 == 0 ? getEvenDigits(n) : (int) getOddDigits(digitsCount); + } + + private long getOddDigits(int digitsCount) { + final int zeros = (digitsCount + 1) / 2; + final int ones = (digitsCount - 1) / 2; + return Integer.valueOf('1' + "0".repeat(zeros) + "1".repeat(ones)); + } + + private int getEvenDigits(int n) { + final int digitsCount = String.valueOf(n).length(); + final long maxNum = Long.valueOf('1' + "0".repeat(digitsCount)); + for (long num = n; num < maxNum; ++num) + if (isValidNum(num)) + return (int) num; + return (int) getOddDigits(digitsCount + 1); + } + + private boolean isValidNum(long num) { + int count = 0; + for (final char c : String.valueOf(num).toCharArray()) + count += (c - '0') % 2 == 0 ? 1 : -1; + return count == 0; + } +} diff --git a/solutions/2417. Closest Fair Integer/2417.py b/solutions/2417. Closest Fair Integer/2417.py new file mode 100644 index 00000000000..4ee7437016c --- /dev/null +++ b/solutions/2417. Closest Fair Integer/2417.py @@ -0,0 +1,24 @@ +class Solution: + def closestFair(self, n: int) -> int: + digitsCount = len(str(n)) + return self._getEvenDigits(n) if digitsCount % 2 == 0 \ + else self._getOddDigits(digitsCount) + + def _getOddDigits(self, digitsCount: int) -> int: + zeros = (digitsCount + 1) // 2 + ones = (digitsCount - 1) // 2 + return int('1' + '0' * zeros + '1' * ones) + + def _getEvenDigits(self, n: int) -> int: + digitsCount = len(str(n)) + maxNum = int('1' + '0' * digitsCount) + for num in range(n, maxNum): + if self._isValidNum(num): + return num + return self._getOddDigits(digitsCount + 1) + + def _isValidNum(self, num: int) -> bool: + count = 0 + for c in str(num): + count += 1 if (ord(c) - ord('0')) % 2 == 0 else -1 + return count == 0 diff --git a/solutions/2418. Sort the People/2418.cpp b/solutions/2418. Sort the People/2418.cpp new file mode 100644 index 00000000000..b5145589487 --- /dev/null +++ b/solutions/2418. Sort the People/2418.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector sortPeople(vector& names, vector& heights) { + vector ans; + vector> heightAndNames; + + for (int i = 0; i < names.size(); ++i) + heightAndNames.emplace_back(heights[i], names[i]); + + ranges::sort(heightAndNames, greater<>()); + + for (const auto& [_, name] : heightAndNames) + ans.push_back(name); + + return ans; + } +}; diff --git a/solutions/2418. Sort the People/2418.java b/solutions/2418. Sort the People/2418.java new file mode 100644 index 00000000000..a8d925335a2 --- /dev/null +++ b/solutions/2418. Sort the People/2418.java @@ -0,0 +1,15 @@ +class Solution { + public String[] sortPeople(String[] names, int[] heights) { + List> heightAndNames = new ArrayList<>(); + + for (int i = 0; i < names.length; ++i) + heightAndNames.add(new Pair<>(heights[i], names[i])); + + Collections.sort(heightAndNames, (a, b) -> b.getKey() - a.getKey()); + + for (int i = 0; i < heightAndNames.size(); ++i) + names[i] = heightAndNames.get(i).getValue(); + + return names; + } +} diff --git a/solutions/2418. Sort the People/2418.py b/solutions/2418. Sort the People/2418.py new file mode 100644 index 00000000000..eec2c7ec488 --- /dev/null +++ b/solutions/2418. Sort the People/2418.py @@ -0,0 +1,4 @@ +class Solution: + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: + return [height for _, height in + sorted([(height, name) for name, height in zip(names, heights)], reverse=True)] diff --git a/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.cpp b/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.cpp new file mode 100644 index 00000000000..0b5f7278dd4 --- /dev/null +++ b/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int longestSubarray(vector& nums) { + int ans = 0; + int maxIndex = 0; + int sameNumLength = 0; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == nums[maxIndex]) { + ans = max(ans, ++sameNumLength); + } else if (nums[i] > nums[maxIndex]) { + maxIndex = i; + sameNumLength = 1; + ans = 1; + } else { + sameNumLength = 0; + } + + return ans; + } +}; diff --git a/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.java b/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.java new file mode 100644 index 00000000000..0cac61b973b --- /dev/null +++ b/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.java @@ -0,0 +1,20 @@ +class Solution { + public int longestSubarray(int[] nums) { + int ans = 0; + int maxIndex = 0; + int sameNumLength = 0; + + for (int i = 0; i < nums.length; ++i) + if (nums[i] == nums[maxIndex]) { + ans = Math.max(ans, ++sameNumLength); + } else if (nums[i] > nums[maxIndex]) { + maxIndex = i; + sameNumLength = 1; + ans = 1; + } else { + sameNumLength = 0; + } + + return ans; + } +} diff --git a/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.py b/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.py new file mode 100644 index 00000000000..ee935b1aa76 --- /dev/null +++ b/solutions/2419. Longest Subarray With Maximum Bitwise AND/2419.py @@ -0,0 +1,18 @@ +class Solution: + def longestSubarray(self, nums: List[int]) -> int: + ans = 0 + maxIndex = 0 + sameNumLength = 0 + + for i, num in enumerate(nums): + if nums[i] == nums[maxIndex]: + sameNumLength += 1 + ans = max(ans, sameNumLength) + elif nums[i] > nums[maxIndex]: + maxIndex = i + sameNumLength = 1 + ans = 1 + else: + sameNumLength = 0 + + return ans diff --git a/solutions/242. Valid Anagram/242.cpp b/solutions/242. Valid Anagram/242.cpp new file mode 100644 index 00000000000..9dd5832766f --- /dev/null +++ b/solutions/242. Valid Anagram/242.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) + return false; + + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + for (const char c : t) { + if (count[c - 'a'] == 0) + return false; + --count[c - 'a']; + } + + return true; + } +}; diff --git a/solutions/242. Valid Anagram/242.java b/solutions/242. Valid Anagram/242.java new file mode 100644 index 00000000000..c49261b37e3 --- /dev/null +++ b/solutions/242. Valid Anagram/242.java @@ -0,0 +1,19 @@ +class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) + return false; + + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (final char c : t.toCharArray()) { + if (count[c - 'a'] == 0) + return false; + --count[c - 'a']; + } + + return true; + } +} diff --git a/solutions/242. Valid Anagram/242.py b/solutions/242. Valid Anagram/242.py new file mode 100644 index 00000000000..dfb6080ffa1 --- /dev/null +++ b/solutions/242. Valid Anagram/242.py @@ -0,0 +1,8 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + count = collections.Counter(s) + count.subtract(collections.Counter(t)) + return all(freq == 0 for freq in count.values()) diff --git a/solutions/2420. Find All Good Indices/2420.cpp b/solutions/2420. Find All Good Indices/2420.cpp new file mode 100644 index 00000000000..295ad3af750 --- /dev/null +++ b/solutions/2420. Find All Good Indices/2420.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + // Same as 2100. Find Good Days to Rob the Bank + vector goodIndices(vector& nums, int k) { + const int n = nums.size(); + vector ans; + // dec[i] := 1 + the number of continuous decreasing numbers before i + vector dec(n, 1); + // inc[i] := 1 + the number of continuous increasing numbers after i + vector inc(n, 1); + + for (int i = 1; i < n; ++i) + if (nums[i - 1] >= nums[i]) + dec[i] = dec[i - 1] + 1; + + for (int i = n - 2; i >= 0; --i) + if (nums[i] <= nums[i + 1]) + inc[i] = inc[i + 1] + 1; + + for (int i = k; i < n - k; ++i) + if (dec[i - 1] >= k && inc[i + 1] >= k) + ans.push_back(i); + + return ans; + } +}; diff --git a/solutions/2420. Find All Good Indices/2420.java b/solutions/2420. Find All Good Indices/2420.java new file mode 100644 index 00000000000..9563803136d --- /dev/null +++ b/solutions/2420. Find All Good Indices/2420.java @@ -0,0 +1,28 @@ +class Solution { + // Same as 2100. Find Good Days to Rob the Bank + public List goodIndices(int[] nums, int k) { + final int n = nums.length; + List ans = new ArrayList<>(); + // dec[i] := 1 + the number of continuous decreasing numbers before i + int[] dec = new int[n]; + // inc[i] := 1 + the number of continuous increasing numbers after i + int[] inc = new int[n]; + + Arrays.fill(dec, 1); + Arrays.fill(inc, 1); + + for (int i = 1; i < n; ++i) + if (nums[i - 1] >= nums[i]) + dec[i] = dec[i - 1] + 1; + + for (int i = n - 2; i >= 0; --i) + if (nums[i] <= nums[i + 1]) + inc[i] = inc[i + 1] + 1; + + for (int i = k; i < n - k; ++i) + if (dec[i - 1] >= k && inc[i + 1] >= k) + ans.add(i); + + return ans; + } +} diff --git a/solutions/2420. Find All Good Indices/2420.py b/solutions/2420. Find All Good Indices/2420.py new file mode 100644 index 00000000000..3a8eaabe594 --- /dev/null +++ b/solutions/2420. Find All Good Indices/2420.py @@ -0,0 +1,17 @@ +class Solution: + # Same as 2100. Find Good Days to Rob the Bank + def goodIndices(self, nums: List[int], k: int) -> List[int]: + n = len(nums) + dec = [1] * n # 1 + the number of continuous decreasing numbers before i + inc = [1] * n # 1 + the number of continuous increasing numbers after i + + for i in range(1, n): + if nums[i - 1] >= nums[i]: + dec[i] = dec[i - 1] + 1 + + for i in range(n - 2, -1, -1): + if nums[i] <= nums[i + 1]: + inc[i] = inc[i + 1] + 1 + + return [i for i in range(k, n - k) + if dec[i - 1] >= k and inc[i + 1] >= k] diff --git a/solutions/2421. Number of Good Paths/2421.cpp b/solutions/2421. Number of Good Paths/2421.cpp new file mode 100644 index 00000000000..1a0ce55aedd --- /dev/null +++ b/solutions/2421. Number of Good Paths/2421.cpp @@ -0,0 +1,66 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + int numberOfGoodPaths(vector& vals, vector>& edges) { + const int n = vals.size(); + int ans = n; + UnionFind uf(n); + vector> tree(n); + map> valToNodes; + + for (int i = 0; i < vals.size(); ++i) + valToNodes[vals[i]].push_back(i); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + if (vals[v] <= vals[u]) + tree[u].push_back(v); + if (vals[u] <= vals[v]) + tree[v].push_back(u); + } + + for (const auto& [val, nodes] : valToNodes) { + for (const int u : nodes) + for (const int v : tree[u]) + uf.unionByRank(u, v); + unordered_map rootCount; + for (const int u : nodes) + ++rootCount[uf.find(u)]; + // For each group, C(count, 2) := count * (count - 1) / 2 + for (const auto& [_, count] : rootCount) + ans += count * (count - 1) / 2; + } + + return ans; + } +}; diff --git a/solutions/2421. Number of Good Paths/2421.java b/solutions/2421. Number of Good Paths/2421.java new file mode 100644 index 00000000000..ed8fef67d0c --- /dev/null +++ b/solutions/2421. Number of Good Paths/2421.java @@ -0,0 +1,73 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public int numberOfGoodPaths(int[] vals, int[][] edges) { + final int n = vals.length; + int ans = n; + UnionFind uf = new UnionFind(n); + List[] tree = new List[n]; + Map> valToNodes = new TreeMap<>(); + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + if (vals[v] <= vals[u]) + tree[u].add(v); + if (vals[u] <= vals[v]) + tree[v].add(u); + } + + for (int i = 0; i < vals.length; ++i) { + valToNodes.putIfAbsent(vals[i], new ArrayList<>()); + valToNodes.get(vals[i]).add(i); + } + + for (Map.Entry> entry : valToNodes.entrySet()) { + final int val = entry.getKey(); + List nodes = entry.getValue(); + for (final int u : nodes) + for (final int v : tree[u]) + uf.unionByRank(u, v); + Map rootCount = new HashMap<>(); + for (final int u : nodes) + rootCount.merge(uf.find(u), 1, Integer::sum); + // For each group, C(count, 2) := count * (count - 1) / 2 + for (final int count : rootCount.values()) + ans += count * (count - 1) / 2; + } + + return ans; + } +} diff --git a/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.cpp b/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.cpp new file mode 100644 index 00000000000..b433b9c594e --- /dev/null +++ b/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minimumOperations(vector& nums) { + int ans = 0; + int l = 0; + int r = nums.size() - 1; + long leftSum = nums.front(); + long rightSum = nums.back(); + + while (l < r) + if (leftSum < rightSum) { + leftSum += nums[++l]; + ++ans; + } else if (leftSum > rightSum) { + rightSum += nums[--r]; + ++ans; + } else { // leftSum == rightSum + leftSum = nums[++l]; + rightSum = nums[--r]; + } + + return ans; + } +}; diff --git a/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.java b/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.java new file mode 100644 index 00000000000..7d167769217 --- /dev/null +++ b/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumOperations(int[] nums) { + int ans = 0; + int l = 0; + int r = nums.length - 1; + long leftSum = nums[l]; + long rightSum = nums[r]; + + while (l < r) + if (leftSum < rightSum) { + leftSum += nums[++l]; + ++ans; + } else if (leftSum > rightSum) { + rightSum += nums[--r]; + ++ans; + } else { // LeftSum == rightSum + leftSum = nums[++l]; + rightSum = nums[--r]; + } + + return ans; + } +} diff --git a/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.py b/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.py new file mode 100644 index 00000000000..33e16c14be4 --- /dev/null +++ b/solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.py @@ -0,0 +1,24 @@ +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + ans = 0 + l = 0 + r = len(nums) - 1 + leftSum = nums[0] + rightSum = nums[-1] + + while l < r: + if leftSum < rightSum: + l += 1 + leftSum += nums[l] + ans += 1 + elif leftSum > rightSum: + r -= 1 + rightSum += nums[r] + ans += 1 + else: # leftSum == rightSum + l += 1 + r -= 1 + leftSum = nums[l] + rightSum = nums[r] + + return ans diff --git a/solutions/2423. Remove Letter To Equalize Frequency/2423.cpp b/solutions/2423. Remove Letter To Equalize Frequency/2423.cpp new file mode 100644 index 00000000000..636bb097585 --- /dev/null +++ b/solutions/2423. Remove Letter To Equalize Frequency/2423.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + bool equalFrequency(string word) { + vector count(26); + + for (const char c : word) + ++count[c - 'a']; + + // Try to remove each letter, then check if the frequency of all the letters + // in `word` are equal. + for (const char c : word) { + --count[c - 'a']; + if (equalFreq(count)) + return true; + ++count[c - 'a']; + } + + return false; + } + + private: + static constexpr int kMax = 101; + + bool equalFreq(const vector& count) { + int minfreq = kMax; + int maxfreq = 0; + for (const int freq : count) + if (freq > 0) { + minfreq = min(minfreq, freq); + maxfreq = max(maxfreq, freq); + } + return minfreq == maxfreq; + } +}; diff --git a/solutions/2423. Remove Letter To Equalize Frequency/2423.java b/solutions/2423. Remove Letter To Equalize Frequency/2423.java new file mode 100644 index 00000000000..bc6195ae4c5 --- /dev/null +++ b/solutions/2423. Remove Letter To Equalize Frequency/2423.java @@ -0,0 +1,32 @@ +class Solution { + public boolean equalFrequency(String word) { + int[] count = new int[26]; + + for (final char c : word.toCharArray()) + ++count[c - 'a']; + + // Try to remove each letter, then check if the frequency of all the letters + // in `word` are equal. + for (final char c : word.toCharArray()) { + --count[c - 'a']; + if (equalFreq(count)) + return true; + ++count[c - 'a']; + } + + return false; + } + + private static final int kMax = 101; + + private boolean equalFreq(int[] count) { + int minfreq = kMax; + int maxfreq = 0; + for (final int freq : count) + if (freq > 0) { + minfreq = Math.min(minfreq, freq); + maxfreq = Math.max(maxfreq, freq); + } + return minfreq == maxfreq; + } +} diff --git a/solutions/2423. Remove Letter To Equalize Frequency/2423.py b/solutions/2423. Remove Letter To Equalize Frequency/2423.py new file mode 100644 index 00000000000..82cd049f4d2 --- /dev/null +++ b/solutions/2423. Remove Letter To Equalize Frequency/2423.py @@ -0,0 +1,15 @@ +class Solution: + def equalFrequency(self, word: str) -> bool: + count = collections.Counter(word) + + # Try to remove each letter, then check if the frequency of all the letters + # in `word` are equal. + for c in word: + count[c] -= 1 + if count[c] == 0: + del count[c] + if min(count.values()) == max(count.values()): + return True + count[c] += 1 + + return False diff --git a/solutions/2424. Longest Uploaded Prefix/2424.cpp b/solutions/2424. Longest Uploaded Prefix/2424.cpp new file mode 100644 index 00000000000..37b43b0f4fa --- /dev/null +++ b/solutions/2424. Longest Uploaded Prefix/2424.cpp @@ -0,0 +1,18 @@ +class LUPrefix { + public: + LUPrefix(int n) {} + + void upload(int video) { + seen.insert(video); + while (seen.contains(longestPrefix + 1)) + ++longestPrefix; + } + + int longest() { + return longestPrefix; + } + + private: + unordered_set seen; + int longestPrefix = 0; +}; diff --git a/solutions/2424. Longest Uploaded Prefix/2424.java b/solutions/2424. Longest Uploaded Prefix/2424.java new file mode 100644 index 00000000000..11a4aeb716c --- /dev/null +++ b/solutions/2424. Longest Uploaded Prefix/2424.java @@ -0,0 +1,16 @@ +class LUPrefix { + public LUPrefix(int n) {} + + public void upload(int video) { + seen.add(video); + while (seen.contains(longestPrefix + 1)) + ++longestPrefix; + } + + public int longest() { + return longestPrefix; + } + + private Set seen = new HashSet<>(); + private int longestPrefix = 0; +} diff --git a/solutions/2424. Longest Uploaded Prefix/2424.py b/solutions/2424. Longest Uploaded Prefix/2424.py new file mode 100644 index 00000000000..7d4b13bcf63 --- /dev/null +++ b/solutions/2424. Longest Uploaded Prefix/2424.py @@ -0,0 +1,12 @@ +class LUPrefix: + def __init__(self, n: int): + self.seen = set() + self.longestPrefix = 0 + + def upload(self, video: int) -> None: + self.seen.add(video) + while self.longestPrefix + 1 in self.seen: + self.longestPrefix += 1 + + def longest(self) -> int: + return self.longestPrefix diff --git a/solutions/2425. Bitwise XOR of All Pairings/2425.cpp b/solutions/2425. Bitwise XOR of All Pairings/2425.cpp new file mode 100644 index 00000000000..40d76090013 --- /dev/null +++ b/solutions/2425. Bitwise XOR of All Pairings/2425.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int xorAllNums(vector& nums1, vector& nums2) { + // If the size of nums1 is m and the size of nums2 is n, then each number in + // nums1 is repeated n times and each number in nums2 is repeated m times. + const int xors1 = accumulate(nums1.begin(), nums1.end(), 0, bit_xor<>()); + const int xors2 = accumulate(nums2.begin(), nums2.end(), 0, bit_xor<>()); + return (nums1.size() % 2 * xors2) ^ (nums2.size() % 2 * xors1); + } +}; diff --git a/solutions/2425. Bitwise XOR of All Pairings/2425.java b/solutions/2425. Bitwise XOR of All Pairings/2425.java new file mode 100644 index 00000000000..d26900a746d --- /dev/null +++ b/solutions/2425. Bitwise XOR of All Pairings/2425.java @@ -0,0 +1,9 @@ +class Solution { + public int xorAllNums(int[] nums1, int[] nums2) { + // If the size of nums1 is m and the size of nums2 is n, then each number in + // nums1 is repeated n times and each number in nums2 is repeated m times. + final int xors1 = Arrays.stream(nums1).reduce((a, b) -> a ^ b).getAsInt(); + final int xors2 = Arrays.stream(nums2).reduce((a, b) -> a ^ b).getAsInt(); + return (nums1.length % 2 * xors2) ^ (nums2.length % 2 * xors1); + } +} diff --git a/solutions/2425. Bitwise XOR of All Pairings/2425.py b/solutions/2425. Bitwise XOR of All Pairings/2425.py new file mode 100644 index 00000000000..ff3b479e029 --- /dev/null +++ b/solutions/2425. Bitwise XOR of All Pairings/2425.py @@ -0,0 +1,7 @@ +class Solution: + def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int: + xors1 = functools.reduce(operator.xor, nums1) + xors2 = functools.reduce(operator.xor, nums2) + # If the size of nums1 is m and the size of nums2 is n, then each number in + # nums1 is repeated n times and each number in nums2 is repeated m times. + return (len(nums1) % 2 * xors2) ^ (len(nums2) % 2 * xors1) diff --git a/solutions/2426. Number of Pairs Satisfying Inequality/2426.cpp b/solutions/2426. Number of Pairs Satisfying Inequality/2426.cpp new file mode 100644 index 00000000000..fe059d6d5aa --- /dev/null +++ b/solutions/2426. Number of Pairs Satisfying Inequality/2426.cpp @@ -0,0 +1,60 @@ +class Solution { + public: + long long numberOfPairs(vector& nums1, vector& nums2, int diff) { + // nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff + // nums1[i] - nums2[i] <= nums1[j] - nums2[j] + diff + // Define A[i] := nums1[i] - nums2[i] -> A[i] <= A[j] + diff + vector A; + + for (int i = 0; i < nums1.size(); ++i) + A.push_back(nums1[i] - nums2[i]); + + long ans = 0; + mergeSort(A, 0, A.size() - 1, diff, ans); + return ans; + } + + private: + void mergeSort(vector& A, int l, int r, int diff, long& ans) { + if (l >= r) + return; + + const int m = (l + r) / 2; + mergeSort(A, l, m, diff, ans); + mergeSort(A, m + 1, r, diff, ans); + merge(A, l, m, r, diff, ans); + } + + void merge(vector& A, int l, int m, int r, int diff, long& ans) { + const int lo = m + 1; + int hi = m + 1; // the first index s.t. A[i] <= A[hi] + diff + + // For each index i in the range [l, m], add `r - hi + 1` to `ans`. + for (int i = l; i <= m; ++i) { + while (hi <= r && A[i] > A[hi] + diff) + ++hi; + ans += r - hi + 1; + } + + vector sorted(r - l + 1); + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + + while (i <= m && j <= r) + if (A[i] < A[j]) + sorted[k++] = A[i++]; + else + sorted[k++] = A[j++]; + + // Put the possible remaining left part into the sorted array. + while (i <= m) + sorted[k++] = A[i++]; + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = A[j++]; + + copy(sorted.begin(), sorted.end(), A.begin() + l); + } +}; diff --git a/solutions/2427. Number of Common Factors/2427.cpp b/solutions/2427. Number of Common Factors/2427.cpp new file mode 100644 index 00000000000..edf7be7f44c --- /dev/null +++ b/solutions/2427. Number of Common Factors/2427.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int commonFactors(int a, int b) { + int ans = 1; + const int gcd = __gcd(a, b); + for (int i = 2; i <= gcd; ++i) + if (a % i == 0 && b % i == 0) + ++ans; + return ans; + } +}; diff --git a/solutions/2427. Number of Common Factors/2427.java b/solutions/2427. Number of Common Factors/2427.java new file mode 100644 index 00000000000..46cecd450ff --- /dev/null +++ b/solutions/2427. Number of Common Factors/2427.java @@ -0,0 +1,14 @@ +class Solution { + public int commonFactors(int a, int b) { + int ans = 1; + final int gcd = gcd(a, b); + for (int i = 2; i <= gcd; ++i) + if (a % i == 0 && b % i == 0) + ++ans; + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2427. Number of Common Factors/2427.py b/solutions/2427. Number of Common Factors/2427.py new file mode 100644 index 00000000000..3185ad1b42b --- /dev/null +++ b/solutions/2427. Number of Common Factors/2427.py @@ -0,0 +1,6 @@ +class Solution: + def commonFactors(self, a: int, b: int) -> int: + gcd = math.gcd(a, b) + return sum(a % i == 0 and b % i == 0 + for i in range(1, gcd + 1)) + \ No newline at end of file diff --git a/solutions/2428. Maximum Sum of an Hourglass/2428.cpp b/solutions/2428. Maximum Sum of an Hourglass/2428.cpp new file mode 100644 index 00000000000..d4d3ec5283c --- /dev/null +++ b/solutions/2428. Maximum Sum of an Hourglass/2428.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxSum(vector>& grid) { + int ans = 0; + + for (int i = 1; i + 1 < grid.size(); ++i) + for (int j = 1; j + 1 < grid[0].size(); ++j) + ans = + max(ans, grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + + grid[i][j] + grid[i + 1][j - 1] + grid[i + 1][j] + + grid[i + 1][j + 1]); + + return ans; + } +}; diff --git a/solutions/2428. Maximum Sum of an Hourglass/2428.java b/solutions/2428. Maximum Sum of an Hourglass/2428.java new file mode 100644 index 00000000000..5dc845de5f3 --- /dev/null +++ b/solutions/2428. Maximum Sum of an Hourglass/2428.java @@ -0,0 +1,12 @@ +public class Solution { + public int maxSum(int[][] grid) { + int ans = 0; + + for (int i = 1; i + 1 < grid.length; ++i) + for (int j = 1; j + 1 < grid[0].length; ++j) + ans = Math.max(ans, grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i][j] + + grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1]); + + return ans; + } +} diff --git a/solutions/2428. Maximum Sum of an Hourglass/2428.py b/solutions/2428. Maximum Sum of an Hourglass/2428.py new file mode 100644 index 00000000000..450cd4fda86 --- /dev/null +++ b/solutions/2428. Maximum Sum of an Hourglass/2428.py @@ -0,0 +1,6 @@ +class Solution: + def maxSum(self, grid: List[List[int]]) -> int: + return max(grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i][j] + + grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1] + for i in range(1, len(grid) - 1) + for j in range(1, len(grid[0]) - 1)) diff --git a/solutions/2429. Minimize XOR/2429.cpp b/solutions/2429. Minimize XOR/2429.cpp new file mode 100644 index 00000000000..3172bbe6f09 --- /dev/null +++ b/solutions/2429. Minimize XOR/2429.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int minimizeXor(unsigned num1, unsigned num2) { + constexpr int kMaxBit = 30; + int bits = popcount(num2); + // Can turn off all the bits in `num1`. + if (popcount(num1) == bits) + return num1; + + int ans = 0; + + // Turn off the MSB if we have `bits` quota. + for (int i = kMaxBit; i >= 0; --i) + if (num1 >> i & 1) { + ans |= 1 << i; + if (--bits == 0) + return ans; + } + + // Turn on the LSB if we still have `bits`. + for (int i = 0; i < kMaxBit; ++i) + if ((num1 >> i & 1) == 0) { + ans |= 1 << i; + if (--bits == 0) + return ans; + } + + return ans; + } +}; diff --git a/solutions/2429. Minimize XOR/2429.java b/solutions/2429. Minimize XOR/2429.java new file mode 100644 index 00000000000..b2fdc6cf7b0 --- /dev/null +++ b/solutions/2429. Minimize XOR/2429.java @@ -0,0 +1,29 @@ +class Solution { + public int minimizeXor(int num1, int num2) { + final int kMaxBit = 30; + int bits = Integer.bitCount(num2); + // Can turn off all the bits in `num1`. + if (Integer.bitCount(num1) == bits) + return num1; + + int ans = 0; + + // Turn off the MSB if we have `bits` quota. + for (int i = kMaxBit - 1; i >= 0; --i) + if ((num1 >> i & 1) == 1) { + ans |= 1 << i; + if (--bits == 0) + return ans; + } + + // Turn on the LSB if we still have `bits`. + for (int i = 0; i < kMaxBit; ++i) + if ((num1 >> i & 1) == 0) { + ans |= 1 << i; + if (--bits == 0) + return ans; + } + + return ans; + } +} diff --git a/solutions/2429. Minimize XOR/2429.py b/solutions/2429. Minimize XOR/2429.py new file mode 100644 index 00000000000..895005048b1 --- /dev/null +++ b/solutions/2429. Minimize XOR/2429.py @@ -0,0 +1,27 @@ +class Solution: + def minimizeXor(self, num1: int, num2: int) -> int: + kMaxBit = 30 + bits = num2.bit_count() + # Can turn off all the bits in `num1`. + if num1.bit_count() == bits: + return num1 + + ans = 0 + + # Turn off the MSB if we have `bits` quota. + for i in reversed(range(kMaxBit)): + if num1 >> i & 1: + ans |= 1 << i + bits -= 1 + if bits == 0: + return ans + + # Turn on the LSB if we still have `bits`. + for i in range(kMaxBit): + if (num1 >> i & 1) == 0: + ans |= 1 << i + bits -= 1 + if bits == 0: + return ans + + return ans diff --git a/solutions/243. Shortest Word Distance/243.cpp b/solutions/243. Shortest Word Distance/243.cpp new file mode 100644 index 00000000000..f904ded4ba6 --- /dev/null +++ b/solutions/243. Shortest Word Distance/243.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int shortestDistance(vector& wordsDict, string word1, string word2) { + int ans = wordsDict.size(); + int index1 = -1; // wordsDict[index1] == word1 + int index2 = -1; // wordsDict[index2] == word2 + + for (int i = 0; i < wordsDict.size(); ++i) { + if (wordsDict[i] == word1) { + index1 = i; + if (index2 != -1) + ans = min(ans, index1 - index2); + } + if (wordsDict[i] == word2) { + index2 = i; + if (index1 != -1) + ans = min(ans, index2 - index1); + } + } + + return ans; + } +}; diff --git a/solutions/243. Shortest Word Distance/243.java b/solutions/243. Shortest Word Distance/243.java new file mode 100644 index 00000000000..270a85c9d8a --- /dev/null +++ b/solutions/243. Shortest Word Distance/243.java @@ -0,0 +1,22 @@ +class Solution { + public int shortestDistance(String[] wordsDict, String word1, String word2) { + int ans = wordsDict.length; + int index1 = -1; // wordsDict[index1] == word1 + int index2 = -1; // wordsDict[index2] == word2 + + for (int i = 0; i < wordsDict.length; ++i) { + if (wordsDict[i].equals(word1)) { + index1 = i; + if (index2 != -1) + ans = Math.min(ans, index1 - index2); + } + if (wordsDict[i].equals(word2)) { + index2 = i; + if (index1 != -1) + ans = Math.min(ans, index2 - index1); + } + } + + return ans; + } +} diff --git a/solutions/243. Shortest Word Distance/243.py b/solutions/243. Shortest Word Distance/243.py new file mode 100644 index 00000000000..926445c8376 --- /dev/null +++ b/solutions/243. Shortest Word Distance/243.py @@ -0,0 +1,17 @@ +class Solution: + def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: + ans = len(wordsDict) + index1 = -1 # wordsDict[index1] == word1 + index2 = -1 # wordsDict[index2] == word2 + + for i, word in enumerate(wordsDict): + if word == word1: + index1 = i + if index2 != -1: + ans = min(ans, index1 - index2) + if word == word2: + index2 = i + if index1 != -1: + ans = min(ans, index2 - index1) + + return ans diff --git a/solutions/2430. Maximum Deletions on a String/2430.cpp b/solutions/2430. Maximum Deletions on a String/2430.cpp new file mode 100644 index 00000000000..90092425faa --- /dev/null +++ b/solutions/2430. Maximum Deletions on a String/2430.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int deleteString(string s) { + const int n = s.length(); + // lcs[i][j] := the number of the same letters of s[i..n) and s[j..n) + vector> lcs(n + 1, vector(n + 1)); + // dp[i] := the maximum number of operations needed to delete s[i..n) + vector dp(n, 1); + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j < n; ++j) { + if (s[i] == s[j]) + lcs[i][j] = lcs[i + 1][j + 1] + 1; + if (lcs[i][j] >= j - i) + dp[i] = max(dp[i], dp[j] + 1); + } + + return dp[0]; + } +}; diff --git a/solutions/2430. Maximum Deletions on a String/2430.java b/solutions/2430. Maximum Deletions on a String/2430.java new file mode 100644 index 00000000000..26a8d0ceaac --- /dev/null +++ b/solutions/2430. Maximum Deletions on a String/2430.java @@ -0,0 +1,20 @@ +class Solution { + public int deleteString(String s) { + final int n = s.length(); + // lcs[i][j] := the number of the same letters of s[i..n) and s[j..n) + int[][] lcs = new int[n + 1][n + 1]; + // dp[i] := the maximum number of operations needed to delete s[i..n) + int[] dp = new int[n]; + Arrays.fill(dp, 1); + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) + lcs[i][j] = lcs[i + 1][j + 1] + 1; + if (lcs[i][j] >= j - i) + dp[i] = Math.max(dp[i], dp[j] + 1); + } + + return dp[0]; + } +} diff --git a/solutions/2430. Maximum Deletions on a String/2430.py b/solutions/2430. Maximum Deletions on a String/2430.py new file mode 100644 index 00000000000..2627d15b3b5 --- /dev/null +++ b/solutions/2430. Maximum Deletions on a String/2430.py @@ -0,0 +1,16 @@ +class Solution: + def deleteString(self, s: str) -> int: + n = len(s) + # lcs[i][j] := the number of the same letters of s[i..n) and s[j..n) + lcs = [[0] * (n + 1) for _ in range(n + 1)] + # dp[i] := the maximum number of operations needed to delete s[i..n) + dp = [1] * n + + for i in reversed(range(n)): + for j in range(i + 1, n): + if s[i] == s[j]: + lcs[i][j] = lcs[i + 1][j + 1] + 1 + if lcs[i][j] >= j - i: + dp[i] = max(dp[i], dp[j] + 1) + + return dp[0] diff --git a/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.cpp b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.cpp new file mode 100644 index 00000000000..447cac43ecb --- /dev/null +++ b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maxTastiness(vector& price, vector& tastiness, int maxAmount, + int maxCoupons) { + // dp[j][k] := the maximum tastiness of price so far with j amount of money + // and k coupons + vector> dp(maxAmount + 1, vector(maxCoupons + 1)); + + for (int i = 0; i < price.size(); ++i) + for (int j = maxAmount; j >= price[i] / 2; --j) + for (int k = maxCoupons; k >= 0; --k) { + const int buyWithCoupon = + k == 0 ? 0 : dp[j - price[i] / 2][k - 1] + tastiness[i]; + const int buyWithoutCoupon = + j < price[i] ? 0 : dp[j - price[i]][k] + tastiness[i]; + dp[j][k] = max({dp[j][k], buyWithCoupon, buyWithoutCoupon}); + } + + return dp[maxAmount][maxCoupons]; + } +}; diff --git a/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.java b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.java new file mode 100644 index 00000000000..2f5d3df268c --- /dev/null +++ b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.java @@ -0,0 +1,17 @@ +class Solution { + public int maxTastiness(int[] price, int[] tastiness, int maxAmount, int maxCoupons) { + // dp[j][k] := the maximum tastiness of price so far with j amount of money and k + // coupons + int[][] dp = new int[maxAmount + 1][maxCoupons + 1]; + + for (int i = 0; i < price.length; ++i) + for (int j = maxAmount; j >= price[i] / 2; --j) + for (int k = maxCoupons; k >= 0; --k) { + final int buyWithCoupon = k == 0 ? 0 : dp[j - price[i] / 2][k - 1] + tastiness[i]; + final int buyWithoutCoupon = j < price[i] ? 0 : dp[j - price[i]][k] + tastiness[i]; + dp[j][k] = Math.max(dp[j][k], Math.max(buyWithCoupon, buyWithoutCoupon)); + } + + return dp[maxAmount][maxCoupons]; + } +} diff --git a/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.py b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.py new file mode 100644 index 00000000000..a6b3cd30d87 --- /dev/null +++ b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.py @@ -0,0 +1,13 @@ +class Solution: + def maxTastiness(self, price: List[int], tastiness: List[int], maxAmount: int, maxCoupons: int) -> int: + # dp[j][k] := the maximum tastiness of price so far with j amount of money and k coupons + dp = [[0] * (maxCoupons + 1) for _ in range(maxAmount + 1)] + + for p, t in zip(price, tastiness): + for j in range(maxAmount, p // 2 - 1, -1): + for k in range(maxCoupons, -1, -1): + buyWithCoupon = 0 if k == 0 else dp[j - p // 2][k - 1] + t + buyWithoutCoupon = 0 if j < p else dp[j - p][k] + t + dp[j][k] = max(dp[j][k], buyWithCoupon, buyWithoutCoupon) + + return dp[maxAmount][maxCoupons] diff --git a/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.cpp b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.cpp new file mode 100644 index 00000000000..dccda970db7 --- /dev/null +++ b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int maxTastiness(vector& price, vector& tastiness, int maxAmount, + int maxCoupons) { + const int n = price.size(); + // dp[i][j][k] := the maximum tastiness of first i price with j amount of + // money and k coupons + vector>> dp( + n + 1, vector>(maxAmount + 1, vector(maxCoupons + 1))); + + for (int i = 1; i <= n; ++i) { + // 1-indexed + const int currPrice = price[i - 1]; + const int currTastiness = tastiness[i - 1]; + for (int amount = 0; amount <= maxAmount; ++amount) { + for (int coupon = 0; coupon <= maxCoupons; ++coupon) { + // 1. Don't buy, the tastiness will be the same as the first i - 1 + // price. + dp[i][amount][coupon] = dp[i - 1][amount][coupon]; + + // 2. Buy without coupon if have enough money. + if (amount >= currPrice) + dp[i][amount][coupon] = + max(dp[i][amount][coupon], + dp[i - 1][amount - currPrice][coupon] + currTastiness); + + // 3. Buy with coupon if have coupon and enough money. + if (coupon > 0 && amount >= currPrice / 2) + dp[i][amount][coupon] = max( + dp[i][amount][coupon], + dp[i - 1][amount - currPrice / 2][coupon - 1] + currTastiness); + } + } + } + + return dp[n][maxAmount][maxCoupons]; + } +}; diff --git a/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.java b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.java new file mode 100644 index 00000000000..42ce17da256 --- /dev/null +++ b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.java @@ -0,0 +1,33 @@ +class Solution { + public int maxTastiness(int[] price, int[] tastiness, int maxAmount, int maxCoupons) { + final int n = price.length; + // dp[i][j][k] := the maximum tastiness of first i price with j amount of money and k coupons + int[][][] dp = new int[price.length + 1][maxAmount + 1][maxCoupons + 1]; + + for (int i = 1; i <= n; ++i) { + // 1-indexed + final int currPrice = price[i - 1]; + final int currTastiness = tastiness[i - 1]; + for (int amount = 0; amount <= maxAmount; ++amount) { + for (int coupon = 0; coupon <= maxCoupons; ++coupon) { + // 1. Don't buy, the tastiness will be the same as the first i - 1 + // price. + dp[i][amount][coupon] = dp[i - 1][amount][coupon]; + + // 2. Buy without coupon if have enough money. + if (amount >= currPrice) + dp[i][amount][coupon] = Math.max(dp[i][amount][coupon], + dp[i - 1][amount - currPrice][coupon] + currTastiness); + + // 3. Buy with coupon if have coupon and enough money. + if (coupon > 0 && amount >= currPrice / 2) + dp[i][amount][coupon] = + Math.max(dp[i][amount][coupon], + dp[i - 1][amount - currPrice / 2][coupon - 1] + currTastiness); + } + } + } + + return dp[n][maxAmount][maxCoupons]; + } +} diff --git a/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.py b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.py new file mode 100644 index 00000000000..e695b42d5e1 --- /dev/null +++ b/solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.py @@ -0,0 +1,31 @@ +class Solution: + def maxTastiness(self, price: List[int], tastiness: List[int], maxAmount: int, maxCoupons: int) -> int: + n = len(price) + # dp[i][j][k] := the maximum tastiness of first i price with j amount of money and k coupons + dp = [[[0] * (maxCoupons + 1) + for j in range(maxAmount + 1)] + for i in range(n + 1)] + + for i in range(1, n + 1): + # 1-indexed + currPrice = price[i - 1] + currTastiness = tastiness[i - 1] + for amount in range(maxAmount + 1): + for coupon in range(maxCoupons + 1): + # 1. Don't buy, the tastiness will be the same as the first i - 1 + # price. + dp[i][amount][coupon] = dp[i - 1][amount][coupon] + + # 2. Buy without coupon if have enough money. + if amount >= currPrice: + dp[i][amount][coupon] = max( + dp[i][amount][coupon], + dp[i - 1][amount - currPrice][coupon] + currTastiness) + + # 3. Buy with coupon if have coupon and enough money. + if coupon > 0 and amount >= currPrice // 2: + dp[i][amount][coupon] = max( + dp[i][amount][coupon], + dp[i - 1][amount - currPrice // 2][coupon - 1] + currTastiness) + + return dp[n][maxAmount][maxCoupons] diff --git a/solutions/2432. The Employee That Worked on the Longest Task/2432.cpp b/solutions/2432. The Employee That Worked on the Longest Task/2432.cpp new file mode 100644 index 00000000000..2875a0ff965 --- /dev/null +++ b/solutions/2432. The Employee That Worked on the Longest Task/2432.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int hardestWorker(int n, vector>& logs) { + int ans = logs[0][0]; + int maxWorkingTime = logs[0][1]; + + for (int i = 1; i < logs.size(); ++i) { + const int id = logs[i][0]; + const int workingTime = logs[i][1] - logs[i - 1][1]; + if (workingTime > maxWorkingTime) { + ans = id; + maxWorkingTime = workingTime; + } else if (workingTime == maxWorkingTime) { + ans = min(ans, id); + } + } + + return ans; + } +}; diff --git a/solutions/2432. The Employee That Worked on the Longest Task/2432.java b/solutions/2432. The Employee That Worked on the Longest Task/2432.java new file mode 100644 index 00000000000..e111ffaa729 --- /dev/null +++ b/solutions/2432. The Employee That Worked on the Longest Task/2432.java @@ -0,0 +1,19 @@ +class Solution { + public int hardestWorker(int n, int[][] logs) { + int ans = logs[0][0]; + int maxWorkingTime = logs[0][1]; + + for (int i = 1; i < logs.length; ++i) { + final int id = logs[i][0]; + final int workingTime = logs[i][1] - logs[i - 1][1]; + if (workingTime > maxWorkingTime) { + ans = id; + maxWorkingTime = workingTime; + } else if (workingTime == maxWorkingTime) { + ans = Math.min(ans, id); + } + } + + return ans; + } +} diff --git a/solutions/2432. The Employee That Worked on the Longest Task/2432.py b/solutions/2432. The Employee That Worked on the Longest Task/2432.py new file mode 100644 index 00000000000..e7de3cf972b --- /dev/null +++ b/solutions/2432. The Employee That Worked on the Longest Task/2432.py @@ -0,0 +1,14 @@ +class Solution: + def hardestWorker(self, n: int, logs: List[List[int]]) -> int: + ans = logs[0][0] + maxWorkingTime = logs[0][1] + + for (_, prevLeaveTime), (id, leaveTime) in zip(logs, logs[1:]): + workingTime = leaveTime - prevLeaveTime + if workingTime > maxWorkingTime: + ans = id + maxWorkingTime = workingTime + elif workingTime == maxWorkingTime: + ans = min(ans, id) + + return ans diff --git a/solutions/2433. Find The Original Array of Prefix Xor/2433.cpp b/solutions/2433. Find The Original Array of Prefix Xor/2433.cpp new file mode 100644 index 00000000000..53af4dee28f --- /dev/null +++ b/solutions/2433. Find The Original Array of Prefix Xor/2433.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector findArray(vector& pref) { + vector ans(pref.size()); + + ans[0] = pref[0]; + for (int i = 1; i < ans.size(); ++i) + ans[i] = pref[i] ^ pref[i - 1]; + + return ans; + } +}; diff --git a/solutions/2433. Find The Original Array of Prefix Xor/2433.java b/solutions/2433. Find The Original Array of Prefix Xor/2433.java new file mode 100644 index 00000000000..fde3070607e --- /dev/null +++ b/solutions/2433. Find The Original Array of Prefix Xor/2433.java @@ -0,0 +1,11 @@ +class Solution { + public int[] findArray(int[] pref) { + int[] ans = new int[pref.length]; + + ans[0] = pref[0]; + for (int i = 1; i < ans.length; ++i) + ans[i] = pref[i] ^ pref[i - 1]; + + return ans; + } +} diff --git a/solutions/2433. Find The Original Array of Prefix Xor/2433.py b/solutions/2433. Find The Original Array of Prefix Xor/2433.py new file mode 100644 index 00000000000..25ab584f81c --- /dev/null +++ b/solutions/2433. Find The Original Array of Prefix Xor/2433.py @@ -0,0 +1,9 @@ +class Solution: + def findArray(self, pref: List[int]) -> List[int]: + ans = [0] * len(pref) + + ans[0] = pref[0] + for i in range(1, len(ans)): + ans[i] = pref[i] ^ pref[i - 1] + + return ans diff --git a/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.cpp b/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.cpp new file mode 100644 index 00000000000..e2255945af9 --- /dev/null +++ b/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + string robotWithString(string s) { + string ans; + vector count(26); + stack stack; + + for (const char c : s) + ++count[c - 'a']; + + for (const char c : s) { + stack.push(c); + --count[c - 'a']; + const char minChar = getMinChar(count); + while (!stack.empty() && stack.top() <= minChar) + ans += stack.top(), stack.pop(); + } + + while (!stack.empty()) + ans += stack.top(), stack.pop(); + + return ans; + } + + private: + char getMinChar(const vector& count) { + for (int i = 0; i < 26; ++i) + if (count[i]) + return 'a' + i; + return 'a'; + } +}; diff --git a/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.java b/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.java new file mode 100644 index 00000000000..aa4be7ae2ff --- /dev/null +++ b/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.java @@ -0,0 +1,30 @@ +class Solution { + public String robotWithString(String s) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[26]; + Deque stack = new ArrayDeque<>(); + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (final char c : s.toCharArray()) { + stack.push(c); + --count[c - 'a']; + final char minChar = getMinChar(count); + while (!stack.isEmpty() && stack.peek() <= minChar) + sb.append(stack.pop()); + } + + while (!stack.isEmpty()) + sb.append(stack.pop()); + + return sb.toString(); + } + + private char getMinChar(int[] count) { + for (int i = 0; i < 26; ++i) + if (count[i] > 0) + return (char) ('a' + i); + return 'a'; + } +} diff --git a/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.py b/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.py new file mode 100644 index 00000000000..3e8f95d7400 --- /dev/null +++ b/solutions/2434. Using a Robot to Print the Lexicographically Smallest String/2434.py @@ -0,0 +1,20 @@ +class Solution: + def robotWithString(self, s: str) -> str: + ans = [] + count = collections.Counter(s) + stack = [] + + for c in s: + stack.append(c) + count[c] -= 1 + minChar = self._getMinChar(count) + while stack and stack[-1] <= minChar: + ans.append(stack.pop()) + + return ''.join(ans + stack[::-1]) + + def _getMinChar(self, count: List[int]) -> str: + for c in string.ascii_lowercase: + if count[c]: + return c + return 'a' diff --git a/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.cpp b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.cpp new file mode 100644 index 00000000000..ed8d3e25f2c --- /dev/null +++ b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int numberOfPaths(vector>& grid, int k) { + constexpr int kMod = 1'000'000'007; + const int m = grid.size(); + const int n = grid[0].size(); + // dp[i][j][sum] : = the number of paths to(i, j), where the sum / k == sum + vector>> dp(m, vector>(n, vector(k))); + dp[0][0][grid[0][0] % k] = 1; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int sum = 0; sum < k; ++sum) { + const int newSum = (sum + grid[i][j]) % k; + if (i > 0) + dp[i][j][newSum] += dp[i - 1][j][sum]; + if (j > 0) + dp[i][j][newSum] += dp[i][j - 1][sum]; + dp[i][j][newSum] %= kMod; + } + + return dp[m - 1][n - 1][0]; + } +}; diff --git a/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.java b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.java new file mode 100644 index 00000000000..5aa7d792b14 --- /dev/null +++ b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.java @@ -0,0 +1,23 @@ +class Solution { + public int numberOfPaths(int[][] grid, int k) { + final int kMod = 1_000_000_007; + final int m = grid.length; + final int n = grid[0].length; + // dp[i][j][sum] : = the number of paths to(i, j), where the sum / k == sum + int[][][] dp = new int[m][n][k]; + dp[0][0][grid[0][0] % k] = 1; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int sum = 0; sum < k; ++sum) { + final int newSum = (sum + grid[i][j]) % k; + if (i > 0) + dp[i][j][newSum] += dp[i - 1][j][sum]; + if (j > 0) + dp[i][j][newSum] += dp[i][j - 1][sum]; + dp[i][j][newSum] %= kMod; + } + + return dp[m - 1][n - 1][0]; + } +} diff --git a/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.py b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.py new file mode 100644 index 00000000000..09b91ae5dd0 --- /dev/null +++ b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435-2.py @@ -0,0 +1,20 @@ +class Solution: + def numberOfPaths(self, grid: List[List[int]], k: int) -> int: + kMod = 1_000_000_007 + m = len(grid) + n = len(grid[0]) + # dp[i][j][sum] := the number of paths to (i, j), where the sum / k == sum + dp = [[[0] * k for j in range(n)] for i in range(m)] + dp[0][0][grid[0][0] % k] = 1 + + for i in range(m): + for j in range(n): + for summ in range(k): + newSum = (summ + grid[i][j]) % k + if i > 0: + dp[i][j][newSum] += dp[i - 1][j][summ] + if j > 0: + dp[i][j][newSum] += dp[i][j - 1][summ] + dp[i][j][newSum] %= kMod + + return dp[m - 1][n - 1][0] diff --git a/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.cpp b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.cpp new file mode 100644 index 00000000000..bd3bd6ff513 --- /dev/null +++ b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int numberOfPaths(vector>& grid, int k) { + vector>> mem( + grid.size(), vector>(grid[0].size(), vector(k, -1))); + return numberOfPaths(grid, 0, 0, 0, k, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of paths to (i, j), where the sum / k == `sum`. + int numberOfPaths(const vector>& grid, int i, int j, int sum, + int k, vector>>& mem) { + if (i == grid.size() || j == grid[0].size()) + return 0; + if (i == grid.size() - 1 && j == grid[0].size() - 1) + return (sum + grid[i][j]) % k == 0; + if (mem[i][j][sum] != -1) + return mem[i][j][sum]; + const int newSum = (sum + grid[i][j]) % k; + return mem[i][j][sum] = (numberOfPaths(grid, i + 1, j, newSum, k, mem) + + numberOfPaths(grid, i, j + 1, newSum, k, mem)) % + kMod; + } +}; diff --git a/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.java b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.java new file mode 100644 index 00000000000..57df780c29c --- /dev/null +++ b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.java @@ -0,0 +1,22 @@ +class Solution { + public int numberOfPaths(int[][] grid, int k) { + Integer[][][] mem = new Integer[grid.length][grid[0].length][k]; + return numberOfPaths(grid, 0, 0, 0, k, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of paths to (i, j), where the sum / k == `sum`. + private int numberOfPaths(int[][] grid, int i, int j, int sum, int k, Integer[][][] mem) { + if (i == grid.length || j == grid[0].length) + return 0; + if (i == grid.length - 1 && j == grid[0].length - 1) + return (sum + grid[i][j]) % k == 0 ? 1 : 0; + if (mem[i][j][sum] != null) + return mem[i][j][sum]; + final int newSum = (sum + grid[i][j]) % k; + return mem[i][j][sum] = (numberOfPaths(grid, i + 1, j, newSum, k, mem) + + numberOfPaths(grid, i, j + 1, newSum, k, mem)) % + kMod; + } +} diff --git a/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.py b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.py new file mode 100644 index 00000000000..ef6fd0af0a7 --- /dev/null +++ b/solutions/2435. Paths in Matrix Whose Sum Is Divisible by K/2435.py @@ -0,0 +1,19 @@ +class Solution: + def numberOfPaths(self, grid: List[List[int]], k: int) -> int: + kMod = 1_000_000_007 + m = len(grid) + n = len(grid[0]) + + @functools.lru_cache(None) + def dp(i: int, j: int, summ: int) -> int: + """ + Returns the number of paths to (i, j), where the sum / k == `summ`. + """ + if i == m or j == n: + return 0 + if i == m - 1 and j == n - 1: + return 1 if (summ + grid[i][j]) % k == 0 else 0 + newSum = (summ + grid[i][j]) % k + return (dp(i + 1, j, newSum) + dp(i, j + 1, newSum)) % kMod + + return dp(0, 0, 0) diff --git a/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.cpp b/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.cpp new file mode 100644 index 00000000000..1ac3ece6a9c --- /dev/null +++ b/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minimumSplits(vector& nums) { + int ans = 1; + int gcd = nums[0]; + + for (const int num : nums) { + const int newGcd = __gcd(gcd, num); + if (newGcd > 1) { + gcd = newGcd; + } else { + gcd = num; + ++ans; + } + } + + return ans; + } +}; diff --git a/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.java b/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.java new file mode 100644 index 00000000000..a12637deb48 --- /dev/null +++ b/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.java @@ -0,0 +1,22 @@ +class Solution { + public int minimumSplits(int[] nums) { + int ans = 1; + int gcd = nums[0]; + + for (final int num : nums) { + final int newGcd = gcd(gcd, num); + if (newGcd > 1) { + gcd = newGcd; + } else { + gcd = num; + ++ans; + } + } + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.py b/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.py new file mode 100644 index 00000000000..f33a7df268d --- /dev/null +++ b/solutions/2436. Minimum Split Into Subarrays With GCD Greater Than One/2436.py @@ -0,0 +1,14 @@ +class Solution: + def minimumSplits(self, nums: List[int]) -> int: + ans = 1 + gcd = nums[0] + + for num in nums: + newGcd = math.gcd(gcd, num) + if newGcd > 1: + gcd = newGcd + else: + gcd = num + ans += 1 + + return ans diff --git a/solutions/2437. Number of Valid Clock Times/2437.cpp b/solutions/2437. Number of Valid Clock Times/2437.cpp new file mode 100644 index 00000000000..730f4163f16 --- /dev/null +++ b/solutions/2437. Number of Valid Clock Times/2437.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int countTime(string time) { + int ans = 1; + if (time[3] == '?') + ans *= 6; + if (time[4] == '?') + ans *= 10; + + if (time[0] == '?' && time[1] == '?') + return ans * 24; + if (time[0] == '?') + return time[1] < '4' ? ans * 3 : ans * 2; + if (time[1] == '?') + return time[0] == '2' ? ans * 4 : ans * 10; + return ans; + } +}; diff --git a/solutions/2437. Number of Valid Clock Times/2437.java b/solutions/2437. Number of Valid Clock Times/2437.java new file mode 100644 index 00000000000..4aa47dc87c2 --- /dev/null +++ b/solutions/2437. Number of Valid Clock Times/2437.java @@ -0,0 +1,17 @@ +class Solution { + public int countTime(String time) { + int ans = 1; + if (time.charAt(3) == '?') + ans *= 6; + if (time.charAt(4) == '?') + ans *= 10; + + if (time.charAt(0) == '?' && time.charAt(1) == '?') + return ans * 24; + if (time.charAt(0) == '?') + return time.charAt(1) < '4' ? ans * 3 : ans * 2; + if (time.charAt(1) == '?') + return time.charAt(0) == '2' ? ans * 4 : ans * 10; + return ans; + } +} diff --git a/solutions/2437. Number of Valid Clock Times/2437.py b/solutions/2437. Number of Valid Clock Times/2437.py new file mode 100644 index 00000000000..ecb948d5003 --- /dev/null +++ b/solutions/2437. Number of Valid Clock Times/2437.py @@ -0,0 +1,15 @@ +class Solution: + def countTime(self, time: str) -> int: + ans = 1 + if time[3] == '?': + ans *= 6 + if time[4] == '?': + ans *= 10 + + if time[0] == '?' and time[1] == '?': + return ans * 24 + if time[0] == '?': + return ans * 3 if time[1] < '4' else ans * 2 + if time[1] == '?': + return ans * 4 if time[0] == '2' else ans * 10 + return ans diff --git a/solutions/2438. Range Product Queries of Powers/2438.cpp b/solutions/2438. Range Product Queries of Powers/2438.cpp new file mode 100644 index 00000000000..9d94aac5441 --- /dev/null +++ b/solutions/2438. Range Product Queries of Powers/2438.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector productQueries(int n, vector>& queries) { + constexpr int kMod = 1'000'000'007; + constexpr int kMaxBit = 30; + vector ans; + vector powers; + + for (int i = 0; i < kMaxBit; ++i) + if (n >> i & 1) + powers.push_back(1 << i); + + for (const vector& query : queries) { + const int left = query[0]; + const int right = query[1]; + long prod = 1; + for (int i = left; i <= right; ++i) { + prod *= powers[i]; + prod %= kMod; + } + ans.push_back(prod); + } + + return ans; + } +}; diff --git a/solutions/2438. Range Product Queries of Powers/2438.java b/solutions/2438. Range Product Queries of Powers/2438.java new file mode 100644 index 00000000000..19226f1e997 --- /dev/null +++ b/solutions/2438. Range Product Queries of Powers/2438.java @@ -0,0 +1,25 @@ +class Solution { + public int[] productQueries(int n, int[][] queries) { + final int kMod = 1_000_000_007; + final int kMaxBit = 30; + int[] ans = new int[queries.length]; + List powers = new ArrayList<>(); + + for (int i = 0; i < kMaxBit; ++i) + if ((n >> i & 1) == 1) + powers.add(1 << i); + + for (int i = 0; i < queries.length; ++i) { + final int left = queries[i][0]; + final int right = queries[i][1]; + long prod = 1; + for (int j = left; j <= right; ++j) { + prod *= powers.get(j); + prod %= kMod; + } + ans[i] = (int) prod; + } + + return ans; + } +} diff --git a/solutions/2438. Range Product Queries of Powers/2438.py b/solutions/2438. Range Product Queries of Powers/2438.py new file mode 100644 index 00000000000..5068a4ad581 --- /dev/null +++ b/solutions/2438. Range Product Queries of Powers/2438.py @@ -0,0 +1,15 @@ +class Solution: + def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: + kMod = 1_000_000_007 + kMaxBit = 30 + ans = [] + powers = [1 << i for i in range(kMaxBit) if n >> i & 1] + + for left, right in queries: + prod = 1 + for i in range(left, right + 1): + prod *= powers[i] + prod %= kMod + ans.append(prod) + + return ans diff --git a/solutions/2439. Minimize Maximum of Array/2439.cpp b/solutions/2439. Minimize Maximum of Array/2439.cpp new file mode 100644 index 00000000000..5d64fb65b3d --- /dev/null +++ b/solutions/2439. Minimize Maximum of Array/2439.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minimizeArrayValue(vector& nums) { + long ans = 0; + long prefix = 0; + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i]; + const long prefixAvg = ceil(prefix / static_cast(i + 1)); + ans = max(ans, prefixAvg); + } + + return ans; + } +}; diff --git a/solutions/2439. Minimize Maximum of Array/2439.java b/solutions/2439. Minimize Maximum of Array/2439.java new file mode 100644 index 00000000000..25ef587e327 --- /dev/null +++ b/solutions/2439. Minimize Maximum of Array/2439.java @@ -0,0 +1,14 @@ +class Solution { + public int minimizeArrayValue(int[] nums) { + long ans = 0; + long prefix = 0; + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i]; + final long prefixAvg = (long) Math.ceil(prefix / (double) (i + 1)); + ans = Math.max(ans, prefixAvg); + } + + return (int) ans; + } +} diff --git a/solutions/2439. Minimize Maximum of Array/2439.py b/solutions/2439. Minimize Maximum of Array/2439.py new file mode 100644 index 00000000000..4d678f5833c --- /dev/null +++ b/solutions/2439. Minimize Maximum of Array/2439.py @@ -0,0 +1,11 @@ +class Solution: + def minimizeArrayValue(self, nums: List[int]) -> int: + ans = 0 + prefix = 0 + + for i, num in enumerate(nums): + prefix += num + prefixAvg = math.ceil(prefix / (i + 1)) + ans = max(ans, prefixAvg) + + return ans diff --git a/solutions/244. Shortest Word Distance II/244.cpp b/solutions/244. Shortest Word Distance II/244.cpp new file mode 100644 index 00000000000..9bb1dab38f9 --- /dev/null +++ b/solutions/244. Shortest Word Distance II/244.cpp @@ -0,0 +1,26 @@ +class WordDistance { + public: + WordDistance(vector& words) { + for (int i = 0; i < words.size(); ++i) + wordToIndices[words[i]].push_back(i); + } + + int shortest(string word1, string word2) { + const vector indices1 = wordToIndices[word1]; + const vector indices2 = wordToIndices[word2]; + int ans = INT_MAX; + + for (int i = 0, j = 0; i < indices1.size() && j < indices2.size();) { + ans = min(ans, abs(indices1[i] - indices2[j])); + if (indices1[i] < indices2[j]) + ++i; + else + ++j; + } + + return ans; + } + + private: + unordered_map> wordToIndices; +}; diff --git a/solutions/244. Shortest Word Distance II/244.java b/solutions/244. Shortest Word Distance II/244.java new file mode 100644 index 00000000000..5939f7d8b51 --- /dev/null +++ b/solutions/244. Shortest Word Distance II/244.java @@ -0,0 +1,26 @@ +class WordDistance { + public WordDistance(String[] words) { + for (int i = 0; i < words.length; ++i) { + wordToIndices.putIfAbsent(words[i], new ArrayList<>()); + wordToIndices.get(words[i]).add(i); + } + } + + public int shortest(String word1, String word2) { + List indices1 = wordToIndices.get(word1); + List indices2 = wordToIndices.get(word2); + int ans = Integer.MAX_VALUE; + + for (int i = 0, j = 0; i < indices1.size() && j < indices2.size();) { + ans = Math.min(ans, Math.abs(indices1.get(i) - indices2.get(j))); + if (indices1.get(i) < indices2.get(j)) + ++i; + else + ++j; + } + + return ans; + } + + private Map> wordToIndices = new HashMap<>(); +} diff --git a/solutions/244. Shortest Word Distance II/244.py b/solutions/244. Shortest Word Distance II/244.py new file mode 100644 index 00000000000..026af61eea4 --- /dev/null +++ b/solutions/244. Shortest Word Distance II/244.py @@ -0,0 +1,21 @@ +class WordDistance: + def __init__(self, wordsDict: List[str]): + self.wordToIndices = collections.defaultdict(list) + for i, word in enumerate(wordsDict): + self.wordToIndices[word].append(i) + + def shortest(self, word1: str, word2: str) -> int: + indices1 = self.wordToIndices[word1] + indices2 = self.wordToIndices[word2] + ans = math.inf + + i = 0 + j = 0 + while i < len(indices1) and j < len(indices2): + ans = min(ans, abs(indices1[i] - indices2[j])) + if indices1[i] < indices2[j]: + i += 1 + else: + j += 1 + + return ans diff --git a/solutions/2440. Create Components With Same Value/2440.cpp b/solutions/2440. Create Components With Same Value/2440.cpp new file mode 100644 index 00000000000..d196a289f5d --- /dev/null +++ b/solutions/2440. Create Components With Same Value/2440.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + int componentValue(vector& nums, vector>& edges) { + const int n = nums.size(); + const int sum = accumulate(nums.begin(), nums.end(), 0); + vector> tree(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + for (int i = n; i > 1; --i) + // Split the tree into i parts, i.e. delete (i - 1) edges. + if (sum % i == 0 && dfs(nums, tree, 0, sum / i, vector(n)) == 0) + return i - 1; + + return 0; + } + + private: + static constexpr int kMax = 1'000'000'000; + + // Returns the sum of the subtree rooted at u substracting the sum of the + // deleted subtrees. + int dfs(const vector& nums, const vector>& tree, int u, + int target, vector&& seen) { + int sum = nums[u]; + seen[u] = true; + + for (const int v : tree[u]) { + if (seen[v]) + continue; + sum += dfs(nums, tree, v, target, move(seen)); + if (sum > target) + return kMax; + } + + // Delete the tree that has sum == target. + if (sum == target) + return 0; + return sum; + } +}; diff --git a/solutions/2440. Create Components With Same Value/2440.java b/solutions/2440. Create Components With Same Value/2440.java new file mode 100644 index 00000000000..22d851067ea --- /dev/null +++ b/solutions/2440. Create Components With Same Value/2440.java @@ -0,0 +1,45 @@ +class Solution { + public int componentValue(int[] nums, int[][] edges) { + final int n = nums.length; + final int sum = Arrays.stream(nums).sum(); + List[] tree = new List[n]; + + for (int i = 0; i < tree.length; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + for (int i = n; i > 1; --i) + // Split the tree into i parts, i.e. delete (i - 1) edges. + if (sum % i == 0 && dfs(nums, tree, 0, sum / i, new boolean[n]) == 0) + return i - 1; + + return 0; + } + + private static final int kMax = 1_000_000_000; + + // Returns the sum of the subtree rooted at u substracting the sum of the deleted subtrees. + private int dfs(int[] nums, List[] tree, int u, int target, boolean[] seen) { + int sum = nums[u]; + seen[u] = true; + + for (final int v : tree[u]) { + if (seen[v]) + continue; + sum += dfs(nums, tree, v, target, seen); + if (sum > target) + return kMax; + } + + // Delete the tree that has sum == target. + if (sum == target) + return 0; + return sum; + } +} diff --git a/solutions/2440. Create Components With Same Value/2440.py b/solutions/2440. Create Components With Same Value/2440.py new file mode 100644 index 00000000000..70368f28ac5 --- /dev/null +++ b/solutions/2440. Create Components With Same Value/2440.py @@ -0,0 +1,37 @@ +class Solution: + def componentValue(self, nums: List[int], edges: List[List[int]]) -> int: + kMax = 1_000_000_000 + n = len(nums) + summ = sum(nums) + tree = [[] for _ in range(n)] + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def dfs(u: int, target: int, seen: Set[bool]) -> int: + """ + Returns the sum of the subtree rooted at u substracting the sum of the + deleted subtrees. + """ + summ = nums[u] + seen.add(u) + + for v in tree[u]: + if v in seen: + continue + summ += dfs(v, target, seen) + if summ > target: + return kMax + + # Delete the tree that has sum == target. + if summ == target: + return 0 + return summ + + for i in range(n, 1, -1): + # Split the tree into i parts, i.e. delete (i - 1) edges. + if summ % i == 0 and dfs(0, summ // i, set()) == 0: + return i - 1 + + return 0 diff --git a/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.cpp b/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.cpp new file mode 100644 index 00000000000..18319972b0a --- /dev/null +++ b/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int findMaxK(vector& nums) { + int ans = -1; + unordered_set seen; + + for (const int num : nums) + if (seen.contains(-num)) + ans = max(ans, abs(num)); + else + seen.insert(num); + + return ans; + } +}; diff --git a/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.java b/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.java new file mode 100644 index 00000000000..7562eb82950 --- /dev/null +++ b/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.java @@ -0,0 +1,14 @@ +public class Solution { + public int findMaxK(int[] nums) { + int ans = -1; + Set seen = new HashSet<>(); + + for (final int num : nums) + if (seen.contains(-num)) + ans = Math.max(ans, Math.abs(num)); + else + seen.add(num); + + return ans; + } +} diff --git a/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.py b/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.py new file mode 100644 index 00000000000..b111af4ef8c --- /dev/null +++ b/solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.py @@ -0,0 +1,12 @@ +class Solution: + def findMaxK(self, nums: List[int]) -> int: + ans = -1 + seen = set() + + for num in nums: + if -num in seen: + ans = max(ans, abs(num)) + else: + seen.add(num) + + return ans diff --git a/solutions/2442. Count Number of Distinct Integers After Reverse Operations/2442.cpp b/solutions/2442. Count Number of Distinct Integers After Reverse Operations/2442.cpp new file mode 100644 index 00000000000..dc4879380ae --- /dev/null +++ b/solutions/2442. Count Number of Distinct Integers After Reverse Operations/2442.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countDistinctIntegers(vector& nums) { + unordered_set numsSet{nums.begin(), nums.end()}; + + for (const int num : nums) + numsSet.insert(reversed(num)); + + return numsSet.size(); + } + + private: + int reversed(int num) { + int ans = 0; + while (num > 0) { + ans = ans * 10 + num % 10; + num /= 10; + } + return ans; + } +}; diff --git a/solutions/2443. Sum of Number and Its Reverse/2443.cpp b/solutions/2443. Sum of Number and Its Reverse/2443.cpp new file mode 100644 index 00000000000..f195f58b4f8 --- /dev/null +++ b/solutions/2443. Sum of Number and Its Reverse/2443.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool sumOfNumberAndReverse(int num) { + for (int i = num / 2; i <= num; ++i) + if (num == i + reversed(i)) + return true; + return false; + } + + private: + int reversed(int num) { + int ans = 0; + while (num > 0) { + ans = ans * 10 + num % 10; + num /= 10; + } + return ans; + } +}; diff --git a/solutions/2444. Count Subarrays With Fixed Bounds/2444.cpp b/solutions/2444. Count Subarrays With Fixed Bounds/2444.cpp new file mode 100644 index 00000000000..6ed6b223a14 --- /dev/null +++ b/solutions/2444. Count Subarrays With Fixed Bounds/2444.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long countSubarrays(vector& nums, int minK, int maxK) { + long ans = 0; + int j = -1; + int prevMinKIndex = -1; + int prevMaxKIndex = -1; + + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] < minK || nums[i] > maxK) + j = i; + if (nums[i] == minK) + prevMinKIndex = i; + if (nums[i] == maxK) + prevMaxKIndex = i; + // Any index k in [j + 1, min(prevMinKIndex, prevMaxKIndex)] can be the + // start of the subarray s.t. nums[k..i] satisfies the conditions. + ans += max(0, min(prevMinKIndex, prevMaxKIndex) - j); + } + + return ans; + } +}; diff --git a/solutions/2444. Count Subarrays With Fixed Bounds/2444.java b/solutions/2444. Count Subarrays With Fixed Bounds/2444.java new file mode 100644 index 00000000000..bb48d8a7329 --- /dev/null +++ b/solutions/2444. Count Subarrays With Fixed Bounds/2444.java @@ -0,0 +1,22 @@ +class Solution { + public long countSubarrays(int[] nums, int minK, int maxK) { + long ans = 0; + int j = -1; + int prevMinKIndex = -1; + int prevMaxKIndex = -1; + + for (int i = 0; i < nums.length; ++i) { + if (nums[i] < minK || nums[i] > maxK) + j = i; + if (nums[i] == minK) + prevMinKIndex = i; + if (nums[i] == maxK) + prevMaxKIndex = i; + // Any index k in [j + 1, min(prevMinKIndex, prevMaxKIndex)] can be the + // start of the subarray s.t. nums[k..i] satisfies the conditions. + ans += Math.max(0, Math.min(prevMinKIndex, prevMaxKIndex) - j); + } + + return ans; + } +} diff --git a/solutions/2444. Count Subarrays With Fixed Bounds/2444.py b/solutions/2444. Count Subarrays With Fixed Bounds/2444.py new file mode 100644 index 00000000000..c4b33cea3f9 --- /dev/null +++ b/solutions/2444. Count Subarrays With Fixed Bounds/2444.py @@ -0,0 +1,19 @@ +class Solution: + def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int: + ans = 0 + j = -1 + prevMinKIndex = -1 + prevMaxKIndex = -1 + + for i, num in enumerate(nums): + if num < minK or num > maxK: + j = i + if num == minK: + prevMinKIndex = i + if num == maxK: + prevMaxKIndex = i + # Any index k in [j + 1, min(prevMinKIndex, prevMaxKIndex)] can be the + # start of the subarray s.t. nums[k..i] satisfies the conditions. + ans += max(0, min(prevMinKIndex, prevMaxKIndex) - j) + + return ans diff --git a/solutions/2445. Number of Nodes With Value One/2445.cpp b/solutions/2445. Number of Nodes With Value One/2445.cpp new file mode 100644 index 00000000000..e642017da4e --- /dev/null +++ b/solutions/2445. Number of Nodes With Value One/2445.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int numberOfNodes(int n, vector& queries) { + // flipped[i] := true if we should flip all the values in the subtree rooted + // at i + vector flipped(n + 1); + + for (const int query : queries) + flipped[query] = flipped[query] ^ true; + + return dfs(1, 0, n, flipped); + } + + private: + int dfs(int label, int value, int n, const vector& flipped) { + if (label > n) + return 0; + value ^= flipped[label]; + return value + // + dfs(label * 2, value, n, flipped) + + dfs(label * 2 + 1, value, n, flipped); + } +}; diff --git a/solutions/2445. Number of Nodes With Value One/2445.java b/solutions/2445. Number of Nodes With Value One/2445.java new file mode 100644 index 00000000000..77379df7f4c --- /dev/null +++ b/solutions/2445. Number of Nodes With Value One/2445.java @@ -0,0 +1,21 @@ +class Solution { + public int numberOfNodes(int n, int[] queries) { + // flipped[i] := true if we should flip all the values in the subtree rooted + // at i + boolean[] flipped = new boolean[n + 1]; + + for (final int query : queries) + flipped[query] = flipped[query] ^ true; + + return dfs(1, 0, n, flipped); + } + + private int dfs(int label, int value, int n, boolean[] flipped) { + if (label > n) + return 0; + value ^= flipped[label] ? 1 : 0; + return value + // + dfs(label * 2, value, n, flipped) + // + dfs(label * 2 + 1, value, n, flipped); + } +} diff --git a/solutions/2445. Number of Nodes With Value One/2445.py b/solutions/2445. Number of Nodes With Value One/2445.py new file mode 100644 index 00000000000..522ba044d4d --- /dev/null +++ b/solutions/2445. Number of Nodes With Value One/2445.py @@ -0,0 +1,16 @@ +class Solution: + def numberOfNodes(self, n: int, queries: List[int]) -> int: + # flipped[i] := True if we should flip all the values in the subtree rooted + # at i + flipped = [False] * (n + 1) + + for query in queries: + flipped[query] = flipped[query] ^ True + + def dfs(label: int, value: int) -> int: + if label > n: + return 0 + value ^= flipped[label] + return value + dfs(label * 2, value) + dfs(label * 2 + 1, value) + + return dfs(1, 0) diff --git a/solutions/2446. Determine if Two Events Have Conflict/2446.cpp b/solutions/2446. Determine if Two Events Have Conflict/2446.cpp new file mode 100644 index 00000000000..f670b26093a --- /dev/null +++ b/solutions/2446. Determine if Two Events Have Conflict/2446.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool haveConflict(vector& event1, vector& event2) { + return event1[0] <= event2[1] && event2[0] <= event1[1]; + } +}; diff --git a/solutions/2446. Determine if Two Events Have Conflict/2446.java b/solutions/2446. Determine if Two Events Have Conflict/2446.java new file mode 100644 index 00000000000..743b0bd7d52 --- /dev/null +++ b/solutions/2446. Determine if Two Events Have Conflict/2446.java @@ -0,0 +1,5 @@ +class Solution { + public boolean haveConflict(String[] event1, String[] event2) { + return event1[0].compareTo(event2[1]) <= 0 && event2[0].compareTo(event1[1]) <= 0; + } +} diff --git a/solutions/2446. Determine if Two Events Have Conflict/2446.py b/solutions/2446. Determine if Two Events Have Conflict/2446.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/solutions/2447. Number of Subarrays With GCD Equal to K/2447.cpp b/solutions/2447. Number of Subarrays With GCD Equal to K/2447.cpp new file mode 100644 index 00000000000..d7eaf9df9cf --- /dev/null +++ b/solutions/2447. Number of Subarrays With GCD Equal to K/2447.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int subarrayGCD(vector& nums, int k) { + int ans = 0; + unordered_map gcds; + + for (const int num : nums) + if (num % k == 0) { + unordered_map nextGcds{{num, 1}}; + for (const auto& [prevGcd, count] : gcds) + nextGcds[gcd(prevGcd, num)] += count; + ans += nextGcds[k]; + gcds = move(nextGcds); + } else { + // The GCD streak stops, so fresh start from the next number. + gcds.clear(); + } + + return ans; + } +}; diff --git a/solutions/2447. Number of Subarrays With GCD Equal to K/2447.java b/solutions/2447. Number of Subarrays With GCD Equal to K/2447.java new file mode 100644 index 00000000000..67290ada31b --- /dev/null +++ b/solutions/2447. Number of Subarrays With GCD Equal to K/2447.java @@ -0,0 +1,28 @@ +class Solution { + public int subarrayGCD(int[] nums, int k) { + int ans = 0; + Map gcds = new HashMap<>(); + + for (final int num : nums) + if (num % k == 0) { + Map nextGcds = new HashMap<>(); + nextGcds.put(num, 1); + for (Map.Entry entry : gcds.entrySet()) { + final int prevGcd = entry.getKey(); + final int count = entry.getValue(); + nextGcds.merge(gcd(prevGcd, num), count, Integer::sum); + } + ans += nextGcds.getOrDefault(k, 0); + gcds = nextGcds; + } else { + // The GCD streak stops, so fresh start from the next number. + gcds.clear(); + } + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2447. Number of Subarrays With GCD Equal to K/2447.py b/solutions/2447. Number of Subarrays With GCD Equal to K/2447.py new file mode 100644 index 00000000000..aa4917c62b0 --- /dev/null +++ b/solutions/2447. Number of Subarrays With GCD Equal to K/2447.py @@ -0,0 +1,18 @@ +class Solution: + def subarrayGCD(self, nums: List[int], k: int) -> int: + ans = 0 + gcds = collections.Counter() + + for num in nums: + if num % k == 0: + nextGcds = collections.defaultdict(int) + nextGcds[num] += 1 + for prevGcd, count in gcds.items(): + nextGcds[math.gcd(prevGcd, num)] += count + ans += nextGcds.get(k, 0) + gcds = nextGcds + else: + # The GCD streak stops, so fresh start from the next number. + gcds.clear() + + return ans diff --git a/solutions/2448. Minimum Cost to Make Array Equal/2448.cpp b/solutions/2448. Minimum Cost to Make Array Equal/2448.cpp new file mode 100644 index 00000000000..052a706a54f --- /dev/null +++ b/solutions/2448. Minimum Cost to Make Array Equal/2448.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + long long minCost(vector& nums, vector& cost) { + long ans = 0; + int l = ranges::min(nums); + int r = ranges::max(nums); + + while (l < r) { + const int m = (l + r) / 2; + const long cost1 = getCost(nums, cost, m); + const long cost2 = getCost(nums, cost, m + 1); + ans = min(cost1, cost2); + if (cost1 < cost2) + r = m; + else + l = m + 1; + } + + return ans; + } + + private: + long getCost(const vector& nums, const vector& cost, int target) { + long res = 0; + for (int i = 0; i < nums.size(); ++i) + res += static_cast(abs(nums[i] - target)) * cost[i]; + return res; + } +}; diff --git a/solutions/2448. Minimum Cost to Make Array Equal/2448.java b/solutions/2448. Minimum Cost to Make Array Equal/2448.java new file mode 100644 index 00000000000..f0cf017fce2 --- /dev/null +++ b/solutions/2448. Minimum Cost to Make Array Equal/2448.java @@ -0,0 +1,27 @@ +class Solution { + public long minCost(int[] nums, int[] cost) { + long ans = 0; + int l = Arrays.stream(nums).min().getAsInt(); + int r = Arrays.stream(nums).max().getAsInt(); + + while (l < r) { + final int m = (l + r) / 2; + final long cost1 = getCost(nums, cost, m); + final long cost2 = getCost(nums, cost, m + 1); + ans = Math.min(cost1, cost2); + if (cost1 < cost2) + r = m; + else + l = m + 1; + } + + return ans; + } + + private long getCost(int[] nums, int[] cost, int target) { + long res = 0; + for (int i = 0; i < nums.length; ++i) + res += Math.abs(nums[i] - target) * (long) cost[i]; + return res; + } +} diff --git a/solutions/2448. Minimum Cost to Make Array Equal/2448.py b/solutions/2448. Minimum Cost to Make Array Equal/2448.py new file mode 100644 index 00000000000..77592de0bae --- /dev/null +++ b/solutions/2448. Minimum Cost to Make Array Equal/2448.py @@ -0,0 +1,20 @@ +class Solution: + def minCost(self, nums: List[int], cost: List[int]) -> int: + ans = 0 + l = min(nums) + r = max(nums) + + def getCost(target: int) -> int: + return sum(abs(num - target) * c for num, c in zip(nums, cost)) + + while l < r: + m = (l + r) // 2 + cost1 = getCost(m) + cost2 = getCost(m + 1) + ans = min(cost1, cost2) + if cost1 < cost2: + r = m + else: + l = m + 1 + + return ans diff --git a/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.cpp b/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.cpp new file mode 100644 index 00000000000..853072846c8 --- /dev/null +++ b/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + long long makeSimilar(vector& nums, vector& target) { + long ans = 0; + vector> A(2); // A[0] := even nums, A[1] := odd nums + vector> B(2); // B[0] := even target, B[1] := odd nums + + for (const int num : nums) + A[num % 2].push_back(num); + + for (const int num : target) + B[num % 2].push_back(num); + + ranges::sort(A[0]); + ranges::sort(A[1]); + ranges::sort(B[0]); + ranges::sort(B[1]); + + for (int i = 0; i < 2; ++i) + for (int j = 0; j < A[i].size(); ++j) + ans += abs(A[i][j] - B[i][j]) / 2; + + return ans / 2; + } +}; diff --git a/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.java b/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.java new file mode 100644 index 00000000000..8abbd47f424 --- /dev/null +++ b/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.java @@ -0,0 +1,26 @@ +class Solution { + public long makeSimilar(int[] nums, int[] target) { + long ans = 0; + // A[0] := even nums, A[1] := odd nums + List[] A = new List[] {new ArrayList<>(), new ArrayList<>()}; + // B[0] := even target, B[1] := odd nums + List[] B = new List[] {new ArrayList<>(), new ArrayList<>()}; + + for (final int num : nums) + A[num % 2].add(num); + + for (final int num : target) + B[num % 2].add(num); + + Collections.sort(A[0]); + Collections.sort(A[1]); + Collections.sort(B[0]); + Collections.sort(B[1]); + + for (int i = 0; i < 2; ++i) + for (int j = 0; j < A[i].size(); ++j) + ans += Math.abs(A[i].get(j) - B[i].get(j)) / 2; + + return ans / 2; + } +} diff --git a/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.py b/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.py new file mode 100644 index 00000000000..a65fb7a00b1 --- /dev/null +++ b/solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.py @@ -0,0 +1,5 @@ +class Solution: + def makeSimilar(self, nums: List[int], target: List[int]) -> int: + nums.sort(key=lambda x: (x % 2, x)) + target.sort(key=lambda x: (x % 2, x)) + return sum(abs(a - b) for a, b in zip(nums, target)) // 4 diff --git a/solutions/245. Shortest Word Distance III/245.cpp b/solutions/245. Shortest Word Distance III/245.cpp new file mode 100644 index 00000000000..def57e4bfb4 --- /dev/null +++ b/solutions/245. Shortest Word Distance III/245.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int shortestWordDistance(vector& words, string word1, string word2) { + const bool isSame = word1 == word2; + int ans = INT_MAX; + // If word1 == word2, index1 is the newest index. + int index1 = words.size(); + // If word1 == word2, index2 is the previous index. + int index2 = -words.size(); + + for (int i = 0; i < words.size(); ++i) { + if (words[i] == word1) { + if (isSame) + index2 = index1; + index1 = i; + } else if (words[i] == word2) { + index2 = i; + } + ans = min(ans, abs(index1 - index2)); + } + + return ans; + } +}; diff --git a/solutions/245. Shortest Word Distance III/245.java b/solutions/245. Shortest Word Distance III/245.java new file mode 100644 index 00000000000..473c63c27da --- /dev/null +++ b/solutions/245. Shortest Word Distance III/245.java @@ -0,0 +1,21 @@ +class Solution { + public int shortestWordDistance(String[] words, String word1, String word2) { + final boolean isSame = word1.equals(word2); + int ans = Integer.MAX_VALUE; + int index1 = words.length; // If word1 == word2, index1 is the newest index. + int index2 = -words.length; // If word1 == word2, index2 is the previous index. + + for (int i = 0; i < words.length; ++i) { + if (words[i].equals(word1)) { + if (isSame) + index2 = index1; + index1 = i; + } else if (words[i].equals(word2)) { + index2 = i; + } + ans = Math.min(ans, Math.abs(index1 - index2)); + } + + return ans; + } +} diff --git a/solutions/245. Shortest Word Distance III/245.py b/solutions/245. Shortest Word Distance III/245.py new file mode 100644 index 00000000000..3788da11cb2 --- /dev/null +++ b/solutions/245. Shortest Word Distance III/245.py @@ -0,0 +1,19 @@ +class Solution: + def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: + isSame = word1 == word2 + ans = math.inf + # If word1 == word2, index1 is the newest index. + index1 = len(wordsDict) + # If word1 == word2, index2 is the previous index. + index2 = -len(wordsDict) + + for i, word in enumerate(wordsDict): + if word == word1: + if isSame: + index2 = index1 + index1 = i + elif word == word2: + index2 = i + ans = min(ans, abs(index1 - index2)) + + return ans diff --git a/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.cpp b/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.cpp new file mode 100644 index 00000000000..a1c1370d46b --- /dev/null +++ b/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countDistinctStrings(string s, int k) { + // Since the content of `s` doesn't matter, for each i in [0, n - k], we can + // flip s[i..i + k] or don't flip it. Therefore, there's 2^(n - k + 1) ways. + return modPow(2, s.length() - k + 1); + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.java b/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.java new file mode 100644 index 00000000000..4f44125777d --- /dev/null +++ b/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.java @@ -0,0 +1,17 @@ +class Solution { + public int countDistinctStrings(String s, int k) { + // Since the content of `s` doesn't matter, for each i in [0, n - k], we can + // flip s[i..i + k] or don't flip it. Therefore, there's 2^(n - k + 1) ways. + return (int) modPow(2, s.length() - k + 1); + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } +} diff --git a/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.py b/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.py new file mode 100644 index 00000000000..9f44c199b7b --- /dev/null +++ b/solutions/2450. Number of Distinct Binary Strings After Applying Operations/2450.py @@ -0,0 +1,5 @@ +class Solution: + def countDistinctStrings(self, s: str, k: int) -> int: + # Since the content of `s` doesn't matter, for each i in [0, n - k], we can + # flip s[i..i + k] or don't flip it. Therefore, there's 2^(n - k + 1) ways. + return pow(2, len(s) - k + 1, 1_000_000_007) diff --git a/solutions/2451. Odd String Difference/2451.cpp b/solutions/2451. Odd String Difference/2451.cpp new file mode 100644 index 00000000000..f4ec3391721 --- /dev/null +++ b/solutions/2451. Odd String Difference/2451.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + string oddString(vector& words) { + const vector> wordAndDiffStrs = + getWordAndDiffStrs(words); + unordered_map diffStrCount; + + for (const auto& [_, diffStr] : wordAndDiffStrs) + ++diffStrCount[diffStr]; + + for (const auto& [word, diffStr] : wordAndDiffStrs) + if (diffStrCount[diffStr] == 1) + return word; + + throw; + } + + private: + // Returns the pairs of the word and its corresponding difference string. + // e.g. [("adc", "3#-1#"), ("wzy", "3#-1#"), ("abc", "1#1#")] + vector> getWordAndDiffStrs(const vector& words) { + vector> wordAndDiffStrs; + for (const string& word : words) + wordAndDiffStrs.emplace_back(word, getDiffStr(word)); + return wordAndDiffStrs; + } + + // Returns the difference string of `s`. + // e.g. getDiffStr("adc") -> "3#-1#" + string getDiffStr(const string& s) { + string diffStr; + for (int i = 1; i < s.length(); ++i) + diffStr += to_string(s[i] - s[i - 1]) + "#"; + return diffStr; + } +}; diff --git a/solutions/2451. Odd String Difference/2451.java b/solutions/2451. Odd String Difference/2451.java new file mode 100644 index 00000000000..cec32d95c6f --- /dev/null +++ b/solutions/2451. Odd String Difference/2451.java @@ -0,0 +1,33 @@ +class Solution { + public String oddString(String[] words) { + List> wordAndHashCodes = getWordAndHashCodes(words); + Map hashCodeCount = new HashMap<>(); + + for (Pair wordAndHashCode : wordAndHashCodes) + hashCodeCount.merge(wordAndHashCode.getValue(), 1, Integer::sum); + + for (Pair wordAndHashCode : wordAndHashCodes) + if (hashCodeCount.get(wordAndHashCode.getValue()) == 1) + return wordAndHashCode.getKey(); + + throw new IllegalArgumentException(); + } + + // Returns the pairs of the word and its corresponding difference string. + // e.g. [("adc", "3#-1#"), ("wzy", "3#-1#"), ("abc", "1#1#")] + private List> getWordAndHashCodes(String[] words) { + List> wordAndHashCodes = new ArrayList<>(); + for (final String word : words) + wordAndHashCodes.add(new Pair<>(word, getDiffStr(word).hashCode())); + return wordAndHashCodes; + } + + // Returns the difference string of `s`. + // e.g. getDiffStr("adc") -> "3#-1#" + private String getDiffStr(final String s) { + StringBuilder sb = new StringBuilder(); + for (int i = 1; i < s.length(); ++i) + sb.append(s.charAt(i) - s.charAt(i - 1)).append("#"); + return sb.toString(); + } +} diff --git a/solutions/2451. Odd String Difference/2451.py b/solutions/2451. Odd String Difference/2451.py new file mode 100644 index 00000000000..5c00f09a884 --- /dev/null +++ b/solutions/2451. Odd String Difference/2451.py @@ -0,0 +1,14 @@ +class Solution: + def oddString(self, words: List[str]) -> str: + def getDiff(s: str) -> List[int]: + return [ord(b) - ord(a) for a, b in zip(s, s[1:])] + + wordAndDiffTuples = [(word, tuple(getDiff(word))) for word in words] + diffTupleCount = collections.Counter() + + for _, diffTuple in wordAndDiffTuples: + diffTupleCount[diffTuple] += 1 + + for word, diffTuple in wordAndDiffTuples: + if diffTupleCount[diffTuple] == 1: + return word diff --git a/solutions/2452. Words Within Two Edits of Dictionary/2452.cpp b/solutions/2452. Words Within Two Edits of Dictionary/2452.cpp new file mode 100644 index 00000000000..4a72c64686c --- /dev/null +++ b/solutions/2452. Words Within Two Edits of Dictionary/2452.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector twoEditWords(vector& queries, + vector& dictionary) { + vector ans; + + for (const string& query : queries) + for (const string& word : dictionary) + if (inner_product(query.begin(), query.end(), word.begin(), 0, plus<>(), + not_equal_to()) < 3) { + ans.push_back(q); + break; + } + + return ans; + } +}; diff --git a/solutions/2452. Words Within Two Edits of Dictionary/2452.java b/solutions/2452. Words Within Two Edits of Dictionary/2452.java new file mode 100644 index 00000000000..5d0bf7792e5 --- /dev/null +++ b/solutions/2452. Words Within Two Edits of Dictionary/2452.java @@ -0,0 +1,22 @@ +class Solution { + public List twoEditWords(String[] queries, String[] dictionary) { + List ans = new ArrayList<>(); + + for (final String query : queries) + for (final String word : dictionary) + if (getDiff(query, word) < 3) { + ans.add(query); + break; + } + + return ans; + } + + private int getDiff(final String query, final String word) { + int diff = 0; + for (int i = 0; i < query.length(); ++i) + if (query.charAt(i) != word.charAt(i)) + ++diff; + return diff; + } +} diff --git a/solutions/2452. Words Within Two Edits of Dictionary/2452.py b/solutions/2452. Words Within Two Edits of Dictionary/2452.py new file mode 100644 index 00000000000..9769340dff8 --- /dev/null +++ b/solutions/2452. Words Within Two Edits of Dictionary/2452.py @@ -0,0 +1,5 @@ +class Solution: + def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]: + return [query for query in queries + if any(sum(a != b for a, b in zip(query, word)) < 3 + for word in dictionary)] diff --git a/solutions/2453. Destroy Sequential Targets/2453-2.cpp b/solutions/2453. Destroy Sequential Targets/2453-2.cpp new file mode 100644 index 00000000000..afb3873078c --- /dev/null +++ b/solutions/2453. Destroy Sequential Targets/2453-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int destroyTargets(vector& nums, int space) { + unordered_map count; + + for (const int num : nums) + ++count[num % space]; + + return *ranges::max_element(nums, [&count, space](int a, int b) { + const int countA = count[a % space]; + const int countB = count[b % space]; + return countA == countB ? a > b : countA < countB; + }); + } +}; diff --git a/solutions/2453. Destroy Sequential Targets/2453.cpp b/solutions/2453. Destroy Sequential Targets/2453.cpp new file mode 100644 index 00000000000..c52f9c4610b --- /dev/null +++ b/solutions/2453. Destroy Sequential Targets/2453.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int destroyTargets(vector& nums, int space) { + int ans = INT_MAX; + int maxCount = 0; + unordered_map count; + + for (const int num : nums) + maxCount = max(maxCount, ++count[num % space]); + + for (const int num : nums) + if (count[num % space] == maxCount) + ans = min(ans, num); + + return ans; + } +}; diff --git a/solutions/2453. Destroy Sequential Targets/2453.java b/solutions/2453. Destroy Sequential Targets/2453.java new file mode 100644 index 00000000000..800b5ff8ad1 --- /dev/null +++ b/solutions/2453. Destroy Sequential Targets/2453.java @@ -0,0 +1,16 @@ +class Solution { + public int destroyTargets(int[] nums, int space) { + int ans = Integer.MAX_VALUE; + int maxCount = 0; + Map count = new HashMap<>(); + + for (final int num : nums) + maxCount = Math.max(maxCount, count.merge(num % space, 1, Integer::sum)); + + for (final int num : nums) + if (count.get(num % space) == maxCount) + ans = Math.min(ans, num); + + return ans; + } +} diff --git a/solutions/2453. Destroy Sequential Targets/2453.py b/solutions/2453. Destroy Sequential Targets/2453.py new file mode 100644 index 00000000000..1a83c79b22c --- /dev/null +++ b/solutions/2453. Destroy Sequential Targets/2453.py @@ -0,0 +1,5 @@ +class Solution: + def destroyTargets(self, nums: List[int], space: int) -> int: + count = collections.Counter([num % space for num in nums]) + maxCount = max(count.values()) + return min(num for num in nums if count[num % space] == maxCount) diff --git a/solutions/2454. Next Greater Element IV/2454.cpp b/solutions/2454. Next Greater Element IV/2454.cpp new file mode 100644 index 00000000000..f95e44cdf57 --- /dev/null +++ b/solutions/2454. Next Greater Element IV/2454.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector secondGreaterElement(vector& nums) { + vector ans(nums.size(), -1); + // a decreasing stack that stores indices that met the first greater number + stack prevStack; + // a decreasing stack that stores indices + stack currStack; + + for (int i = 0; i < nums.size(); ++i) { + // Indices in `prevStack` meet the second greater number. + while (!prevStack.empty() && nums[prevStack.top()] < nums[i]) + ans[prevStack.top()] = nums[i], prevStack.pop(); + // Push indices that meet the first greater number from `currStack` to + // `prevStack`. We need a temporary array to make the indices in the + // `prevStack` increasing. + stack decreasingIndices; + while (!currStack.empty() && nums[currStack.top()] < nums[i]) + decreasingIndices.push(currStack.top()), currStack.pop(); + while (!decreasingIndices.empty()) + prevStack.push(decreasingIndices.top()), decreasingIndices.pop(); + currStack.push(i); + } + + return ans; + } +}; diff --git a/solutions/2454. Next Greater Element IV/2454.java b/solutions/2454. Next Greater Element IV/2454.java new file mode 100644 index 00000000000..66349730b84 --- /dev/null +++ b/solutions/2454. Next Greater Element IV/2454.java @@ -0,0 +1,27 @@ +class Solution { + public int[] secondGreaterElement(int[] nums) { + int[] ans = new int[nums.length]; + Arrays.fill(ans, -1); + // a decreasing stack that stores indices that met the first greater number + Deque prevStack = new ArrayDeque<>(); + // a decreasing stack that stores indices + Deque currStack = new ArrayDeque<>(); + + for (int i = 0; i < nums.length; ++i) { + // Indices in prevStack meet the second greater num. + while (!prevStack.isEmpty() && nums[prevStack.peek()] < nums[i]) + ans[prevStack.poll()] = nums[i]; + // Push indices that meet the first greater number from `currStack` to + // `prevStack`. We need a temporary array to make the indices in the + // `prevStack` increasing. + Deque decreasingIndices = new ArrayDeque<>(); + while (!currStack.isEmpty() && nums[currStack.peek()] < nums[i]) + decreasingIndices.push(currStack.poll()); + while (!decreasingIndices.isEmpty()) + prevStack.push(decreasingIndices.poll()); + currStack.push(i); + } + + return ans; + } +} diff --git a/solutions/2454. Next Greater Element IV/2454.py b/solutions/2454. Next Greater Element IV/2454.py new file mode 100644 index 00000000000..ff66edb5ce5 --- /dev/null +++ b/solutions/2454. Next Greater Element IV/2454.py @@ -0,0 +1,23 @@ +class Solution: + def secondGreaterElement(self, nums: List[int]) -> List[int]: + ans = [-1] * len(nums) + # a decreasing stack that stores indices that met the first greater number. + prevStack = [] + # a decreasing stack that stores indices. + currStack = [] + + for i, num in enumerate(nums): + # Indices in prevStack meet the second greater num. + while prevStack and nums[prevStack[-1]] < num: + ans[prevStack.pop()] = num + # Push indices that meet the first greater number from `currStack` to + # `prevStack`. We need a temporary array to make the indices in the + # `prevStack` increasing. + decreasingIndices = [] + while currStack and nums[currStack[-1]] < num: + decreasingIndices.append(currStack.pop()) + while decreasingIndices: + prevStack.append(decreasingIndices.pop()) + currStack.append(i) + + return ans diff --git a/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.cpp b/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.cpp new file mode 100644 index 00000000000..a03822d9fde --- /dev/null +++ b/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int averageValue(vector& nums) { + int sum = 0; + int count = 0; + + for (const int num : nums) + if (num % 6 == 0) { + sum += num; + ++count; + } + + return count == 0 ? 0 : sum / count; + } +}; diff --git a/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.java b/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.java new file mode 100644 index 00000000000..eb4fd1bccf8 --- /dev/null +++ b/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.java @@ -0,0 +1,14 @@ +class Solution { + public int averageValue(int[] nums) { + int sum = 0; + int count = 0; + + for (final int num : nums) + if (num % 6 == 0) { + sum += num; + ++count; + } + + return count == 0 ? 0 : sum / count; + } +} diff --git a/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.py b/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.py new file mode 100644 index 00000000000..4c66263f931 --- /dev/null +++ b/solutions/2455. Average Value of Even Numbers That Are Divisible by Three/2455.py @@ -0,0 +1,11 @@ +class Solution: + def averageValue(self, nums: List[int]) -> int: + summ = 0 + count = 0 + + for num in nums: + if num % 6 == 0: + summ += num + count += 1 + + return 0 if count == 0 else summ // count diff --git a/solutions/2456. Most Popular Video Creator/2456.cpp b/solutions/2456. Most Popular Video Creator/2456.cpp new file mode 100644 index 00000000000..b02ef81fd03 --- /dev/null +++ b/solutions/2456. Most Popular Video Creator/2456.cpp @@ -0,0 +1,42 @@ +struct Creator { + long popularity; // the popularity sum + string videoId; // the video id that has the maximum view + int maxView; // the maximum view of the creator +}; + +class Solution { + public: + vector> mostPopularCreator(vector& creators, + vector& ids, + vector& views) { + vector> ans; + unordered_map nameToCreator; + long maxPopularity = 0; + + for (int i = 0; i < creators.size(); ++i) { + if (!nameToCreator.contains(creators[i])) { + nameToCreator[creators[i]] = Creator{ + .popularity = views[i], + .videoId = ids[i], + .maxView = views[i], + }; + maxPopularity = max(maxPopularity, static_cast(views[i])); + continue; + } + Creator& creator = nameToCreator[creators[i]]; + creator.popularity += views[i]; + maxPopularity = max(maxPopularity, static_cast(creator.popularity)); + if (creator.maxView < views[i] || + creator.maxView == views[i] && creator.videoId > ids[i]) { + creator.videoId = ids[i]; + creator.maxView = views[i]; + } + } + + for (const auto& [name, creator] : nameToCreator) + if (creator.popularity == maxPopularity) + ans.push_back({name, creator.videoId}); + + return ans; + } +}; diff --git a/solutions/2456. Most Popular Video Creator/2456.java b/solutions/2456. Most Popular Video Creator/2456.java new file mode 100644 index 00000000000..fe805393b0c --- /dev/null +++ b/solutions/2456. Most Popular Video Creator/2456.java @@ -0,0 +1,40 @@ +class Creator { + public long popularity; // the popularity sum + public String videoId; // the video id that has the maximum view + public int maxView; // the maximum view of the creator + public Creator(long popularity, String videoId, int maxView) { + this.popularity = popularity; + this.videoId = videoId; + this.maxView = maxView; + } +} + +class Solution { + public List> mostPopularCreator(String[] creators, String[] ids, int[] views) { + List> ans = new ArrayList<>(); + Map nameToCreator = new HashMap<>(); + long maxPopularity = 0; + + for (int i = 0; i < creators.length; ++i) { + if (!nameToCreator.containsKey(creators[i])) { + nameToCreator.put(creators[i], new Creator(views[i], ids[i], views[i])); + maxPopularity = Math.max(maxPopularity, (long) views[i]); + continue; + } + Creator creator = nameToCreator.get(creators[i]); + creator.popularity += views[i]; + maxPopularity = Math.max(maxPopularity, (long) creator.popularity); + if (creator.maxView < views[i] || + creator.maxView == views[i] && creator.videoId.compareTo(ids[i]) > 0) { + creator.videoId = ids[i]; + creator.maxView = views[i]; + } + } + + for (Map.Entry entry : nameToCreator.entrySet()) + if (entry.getValue().popularity == maxPopularity) + ans.add(Arrays.asList(entry.getKey(), entry.getValue().videoId)); + + return ans; + } +} diff --git a/solutions/2456. Most Popular Video Creator/2456.py b/solutions/2456. Most Popular Video Creator/2456.py new file mode 100644 index 00000000000..dd25f23dd17 --- /dev/null +++ b/solutions/2456. Most Popular Video Creator/2456.py @@ -0,0 +1,31 @@ +class Creator: + def __init__(self, popularity: int, videoId: str, maxView: int): + self.popularity = popularity # the popularity sum + self.videoId = videoId # the video id that has the maximum view + self.maxView = maxView # the maximum view of the creator + + +class Solution: + def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]: + ans = [] + maxPopularity = 0 + nameToCreator = {} + + for name, id, view in zip(creators, ids, views): + if name not in nameToCreator: + nameToCreator[name] = Creator(view, id, view) + maxPopularity = max(maxPopularity, view) + continue + creator = nameToCreator[name] + creator.popularity += view + maxPopularity = max(maxPopularity, creator.popularity) + if creator.maxView < view or \ + creator.maxView == view and creator.videoId > id: + creator.videoId = id + creator.maxView = view + + for name, creator in nameToCreator.items(): + if creator.popularity == maxPopularity: + ans.append([name, creator.videoId]) + + return ans diff --git a/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.cpp b/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.cpp new file mode 100644 index 00000000000..8278d0fadf7 --- /dev/null +++ b/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + long long makeIntegerBeautiful(long long n, int target) { + long ans = 0; + long power = 1; + + // e.g. n = 123. After tunning off the last bit by adding 7, n = 130. + // Effectively, we can think n as 13. That's why we do n = (n / 10) + 1. + while (sum(n) > target) { + // the cost to turn off the last digit + ans += power * (10 - n % 10); + n = n / 10 + 1; + power *= 10; + } + + return ans; + } + + private: + int sum(long n) { + int res = 0; + while (n > 0) { + res += n % 10; + n /= 10; + } + return res; + } +}; diff --git a/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.java b/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.java new file mode 100644 index 00000000000..beeaa517d8b --- /dev/null +++ b/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.java @@ -0,0 +1,26 @@ +class Solution { + public long makeIntegerBeautiful(long n, int target) { + long ans = 0; + long power = 1; + + // e.g. n = 123. After tunning off the last bit by adding 7, n = 130. + // Effectively, we can think n as 13. That's why we do n = (n / 10) + 1. + while (sum(n) > target) { + // the cost to turn off the last digit + ans += power * (10 - n % 10); + n = n / 10 + 1; + power *= 10; + } + + return ans; + } + + private int sum(long n) { + int res = 0; + while (n > 0) { + res += n % 10; + n /= 10; + } + return res; + } +} diff --git a/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.py b/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.py new file mode 100644 index 00000000000..221575bcff0 --- /dev/null +++ b/solutions/2457. Minimum Addition to Make Integer Beautiful/2457.py @@ -0,0 +1,14 @@ +class Solution: + def makeIntegerBeautiful(self, n: int, target: int) -> int: + ans = 0 + power = 1 + + # e.g. n = 123. After tunning off the last bit by adding 7, n = 130. + # Effectively, we can think n as 13. That's why we do n = (n / 10) + 1. + while sum(map(int, str(n))) > target: + # the cost to turn off the last digit + ans += power * (10 - n % 10) + n = n // 10 + 1 + power *= 10 + + return ans diff --git a/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.cpp b/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.cpp new file mode 100644 index 00000000000..d5ac6af4483 --- /dev/null +++ b/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + vector treeQueries(TreeNode* root, vector& queries) { + vector ans; + + dfs(root, 0, 0); + + for (const int query : queries) + ans.push_back(valToMaxHeight[query]); + + return ans; + } + + private: + // valToMaxHeight[val] := the maximum height without the node with `val` + unordered_map valToMaxHeight; + // valToHeight[val] := the height of the node with `val` + unordered_map valToHeight; + + int height(TreeNode* root) { + if (root == nullptr) + return 0; + if (const auto it = valToHeight.find(root->val); it != valToHeight.cend()) + return it->second; + return valToHeight[root->val] = + (1 + max(height(root->left), height(root->right))); + } + + // maxHeight := the maximum height without the current node `root` + void dfs(TreeNode* root, int depth, int maxHeight) { + if (root == nullptr) + return; + valToMaxHeight[root->val] = maxHeight; + dfs(root->left, depth + 1, max(maxHeight, depth + height(root->right))); + dfs(root->right, depth + 1, max(maxHeight, depth + height(root->left))); + } +}; diff --git a/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.java b/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.java new file mode 100644 index 00000000000..dacfa45ec9e --- /dev/null +++ b/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.java @@ -0,0 +1,36 @@ +class Solution { + public int[] treeQueries(TreeNode root, int[] queries) { + int[] ans = new int[queries.length]; + + dfs(root, 0, 0); + + for (int i = 0; i < queries.length; ++i) + ans[i] = valToMaxHeight.get(queries[i]); + + return ans; + } + + // valToMaxHeight[val] := the maximum height without the node with `val` + private Map valToMaxHeight = new HashMap<>(); + // valToHeight[val] := the height of the node with `val` + private Map valToHeight = new HashMap<>(); + + private int height(TreeNode root) { + if (root == null) + return 0; + if (valToHeight.containsKey(root.val)) + return valToHeight.get(root.val); + final int h = 1 + Math.max(height(root.left), height(root.right)); + valToHeight.put(root.val, h); + return h; + } + + // maxHeight := the maximum height without the current node `root` + private void dfs(TreeNode root, int depth, int maxHeight) { + if (root == null) + return; + valToMaxHeight.put(root.val, maxHeight); + dfs(root.left, depth + 1, Math.max(maxHeight, depth + height(root.right))); + dfs(root.right, depth + 1, Math.max(maxHeight, depth + height(root.left))); + } +} diff --git a/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.py b/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.py new file mode 100644 index 00000000000..771b15faa3b --- /dev/null +++ b/solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.py @@ -0,0 +1,21 @@ +class Solution: + def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]: + @lru_cache(None) + def height(root: Optional[TreeNode]) -> int: + if not root: + return 0 + return 1 + max(height(root.left), height(root.right)) + + # valToMaxHeight[val] := the maximum height without the node with `val` + valToMaxHeight = {} + + # maxHeight := the maximum height without the current node `root` + def dfs(root: Optional[TreeNode], depth: int, maxHeight: int) -> None: + if not root: + return + valToMaxHeight[root.val] = maxHeight + dfs(root.left, depth + 1, max(maxHeight, depth + height(root.right))) + dfs(root.right, depth + 1, max(maxHeight, depth + height(root.left))) + + dfs(root, 0, 0) + return [valToMaxHeight[query] for query in queries] diff --git a/solutions/2459. Sort Array by Moving Items to Empty Space/2459.py b/solutions/2459. Sort Array by Moving Items to Empty Space/2459.py new file mode 100644 index 00000000000..b62a307d7e7 --- /dev/null +++ b/solutions/2459. Sort Array by Moving Items to Empty Space/2459.py @@ -0,0 +1,33 @@ +class Solution: + def sortArray(self, nums: List[int]) -> int: + n = len(nums) + numToIndex = [0] * n + + for i, num in enumerate(nums): + numToIndex[num] = i + + def minOps(numToIndex: List[int], zeroInBeginning: bool) -> int: + ops = 0 + num = 1 + # If zeroInBeginning, the correct index of each num is num. + # If not zeroInBeginning, the correct index of each num is num - 1. + offset = 0 if zeroInBeginning else 1 + while num < n: + # 0 is in the correct index, so swap 0 with the first `numInWrongIndex`. + if zeroInBeginning and numToIndex[0] == 0 or \ + not zeroInBeginning and numToIndex[0] == n - 1: + while numToIndex[num] == num - offset: # num is in correct position + num += 1 + if num == n: + return ops + numInWrongIndex = num + # 0 is in the wrong index. e.g. numToIndex[0] == 2, that means 2 is not + # in nums[2] because nums[2] == 0. + else: + numInWrongIndex = numToIndex[0] + offset + numToIndex[0], numToIndex[numInWrongIndex] = \ + numToIndex[numInWrongIndex], numToIndex[0] + ops += 1 + + return min(minOps(numToIndex.copy(), True), + minOps(numToIndex.copy(), False)) diff --git a/solutions/246. Strobogrammatic Number/246.cpp b/solutions/246. Strobogrammatic Number/246.cpp new file mode 100644 index 00000000000..804a6bb38b7 --- /dev/null +++ b/solutions/246. Strobogrammatic Number/246.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool isStrobogrammatic(string num) { + const vector rotated{'0', '1', 'x', 'x', 'x', + 'x', '9', 'x', '8', '6'}; + int l = 0; + int r = num.length() - 1; + + while (l <= r) + if (num[l++] != rotated[num[r--] - '0']) + return false; + + return true; + } +}; diff --git a/solutions/246. Strobogrammatic Number/246.java b/solutions/246. Strobogrammatic Number/246.java new file mode 100644 index 00000000000..13f1f55cbb9 --- /dev/null +++ b/solutions/246. Strobogrammatic Number/246.java @@ -0,0 +1,13 @@ +class Solution { + public boolean isStrobogrammatic(String num) { + final char[] rotated = {'0', '1', 'x', 'x', 'x', 'x', '9', 'x', '8', '6'}; + int l = 0; + int r = num.length() - 1; + + while (l <= r) + if (num.charAt(l++) != rotated[num.charAt(r--) - '0']) + return false; + + return true; + } +} diff --git a/solutions/246. Strobogrammatic Number/246.py b/solutions/246. Strobogrammatic Number/246.py new file mode 100644 index 00000000000..751c882d375 --- /dev/null +++ b/solutions/246. Strobogrammatic Number/246.py @@ -0,0 +1,15 @@ +class Solution: + def isStrobogrammatic(self, num: str) -> bool: + rotated = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'} + l = 0 + r = len(num) - 1 + + while l <= r: + if num[r] not in rotated: + return False + if num[l] != rotated[num[r]]: + return False + l += 1 + r -= 1 + + return True diff --git a/solutions/2460. Apply Operations to an Array/2460-2.cpp b/solutions/2460. Apply Operations to an Array/2460-2.cpp new file mode 100644 index 00000000000..4e93bd9b34c --- /dev/null +++ b/solutions/2460. Apply Operations to an Array/2460-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector applyOperations(vector& nums) { + for (int i = 0, j = 0; i < nums.size(); ++i) { + if (i + 1 < nums.size() && nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + if (nums[i] > 0) + swap(nums[i], nums[j++]); + } + return nums; + } +}; diff --git a/solutions/2460. Apply Operations to an Array/2460-2.java b/solutions/2460. Apply Operations to an Array/2460-2.java new file mode 100644 index 00000000000..08cced8d001 --- /dev/null +++ b/solutions/2460. Apply Operations to an Array/2460-2.java @@ -0,0 +1,20 @@ +class Solution { + public int[] applyOperations(int[] nums) { + for (int i = 0, j = 0; i < nums.length; ++i) { + if (i + 1 < nums.length && nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + if (nums[i] > 0) { + swap(nums, i, j++); + } + } + return nums; + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/2460. Apply Operations to an Array/2460-2.py b/solutions/2460. Apply Operations to an Array/2460-2.py new file mode 100644 index 00000000000..4fd85c2860d --- /dev/null +++ b/solutions/2460. Apply Operations to an Array/2460-2.py @@ -0,0 +1,11 @@ +class Solution: + def applyOperations(self, nums: List[int]) -> List[int]: + j = 0 + for i in range(len(nums)): + if i + 1 < len(nums) and nums[i] == nums[i + 1]: + nums[i] *= 2 + nums[i + 1] = 0 + if nums[i] > 0: + nums[i], nums[j] = nums[j], nums[i] + j += 1 + return nums diff --git a/solutions/2460. Apply Operations to an Array/2460.cpp b/solutions/2460. Apply Operations to an Array/2460.cpp new file mode 100644 index 00000000000..3d2426ea68e --- /dev/null +++ b/solutions/2460. Apply Operations to an Array/2460.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector applyOperations(vector& nums) { + vector ans(nums.size()); + + for (int i = 0; i + 1 < nums.size(); ++i) + if (nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + + int i = 0; + for (const int num : nums) + if (num > 0) + ans[i++] = num; + + return ans; + } +}; diff --git a/solutions/2460. Apply Operations to an Array/2460.java b/solutions/2460. Apply Operations to an Array/2460.java new file mode 100644 index 00000000000..a9f9ba4a7da --- /dev/null +++ b/solutions/2460. Apply Operations to an Array/2460.java @@ -0,0 +1,18 @@ +class Solution { + public int[] applyOperations(int[] nums) { + int[] ans = new int[nums.length]; + + for (int i = 0; i + 1 < nums.length; ++i) + if (nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + + int i = 0; + for (final int num : nums) + if (num > 0) + ans[i++] = num; + + return ans; + } +} diff --git a/solutions/2460. Apply Operations to an Array/2460.py b/solutions/2460. Apply Operations to an Array/2460.py new file mode 100644 index 00000000000..b96dde83d52 --- /dev/null +++ b/solutions/2460. Apply Operations to an Array/2460.py @@ -0,0 +1,16 @@ +class Solution: + def applyOperations(self, nums: List[int]) -> List[int]: + ans = [0] * len(nums) + + for i in range(len(nums) - 1): + if nums[i] == nums[i + 1]: + nums[i] *= 2 + nums[i + 1] = 0 + + i = 0 + for num in nums: + if num > 0: + ans[i] = num + i += 1 + + return ans diff --git a/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.cpp b/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.cpp new file mode 100644 index 00000000000..3b5d5049fc7 --- /dev/null +++ b/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long maximumSubarraySum(vector& nums, int k) { + long ans = 0; + long sum = 0; + int distinct = 0; + unordered_map count; + + for (int i = 0; i < nums.size(); ++i) { + sum += nums[i]; + if (++count[nums[i]] == 1) + ++distinct; + if (i >= k) { + if (--count[nums[i - k]] == 0) + --distinct; + sum -= nums[i - k]; + } + if (i >= k - 1 && distinct == k) + ans = max(ans, sum); + } + + return ans; + } +}; diff --git a/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.java b/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.java new file mode 100644 index 00000000000..59f5e82e338 --- /dev/null +++ b/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.java @@ -0,0 +1,23 @@ +class Solution { + public long maximumSubarraySum(int[] nums, int k) { + long ans = 0; + long sum = 0; + int distinct = 0; + Map count = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + sum += nums[i]; + if (count.merge(nums[i], 1, Integer::sum) == 1) + ++distinct; + if (i >= k) { + if (count.merge(nums[i - k], -1, Integer::sum) == 0) + --distinct; + sum -= nums[i - k]; + } + if (i >= k - 1 && distinct == k) + ans = Math.max(ans, sum); + } + + return ans; + } +} diff --git a/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.py b/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.py new file mode 100644 index 00000000000..a83e281627b --- /dev/null +++ b/solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.py @@ -0,0 +1,21 @@ +class Solution: + def maximumSubarraySum(self, nums: List[int], k: int) -> int: + ans = 0 + summ = 0 + distinct = 0 + count = collections.Counter() + + for i, num in enumerate(nums): + summ += num + count[num] += 1 + if count[num] == 1: + distinct += 1 + if i >= k: + count[nums[i - k]] -= 1 + if count[nums[i - k]] == 0: + distinct -= 1 + summ -= nums[i - k] + if i >= k - 1 and distinct == k: + ans = max(ans, summ) + + return ans diff --git a/solutions/2462. Total Cost to Hire K Workers/2462.cpp b/solutions/2462. Total Cost to Hire K Workers/2462.cpp new file mode 100644 index 00000000000..1fc728d9380 --- /dev/null +++ b/solutions/2462. Total Cost to Hire K Workers/2462.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + long long totalCost(vector& costs, int k, int candidates) { + long ans = 0; + int i = 0; + int j = costs.size() - 1; + priority_queue, greater<>> minHeapL; + priority_queue, greater<>> minHeapR; + + for (int hired = 0; hired < k; ++hired) { + while (minHeapL.size() < candidates && i <= j) + minHeapL.push(costs[i++]); + while (minHeapR.size() < candidates && i <= j) + minHeapR.push(costs[j--]); + if (minHeapL.empty()) + ans += minHeapR.top(), minHeapR.pop(); + else if (minHeapR.empty()) + ans += minHeapL.top(), minHeapL.pop(); + // Both `minHeapL` and `minHeapR` are not empty. + else if (minHeapL.top() <= minHeapR.top()) + ans += minHeapL.top(), minHeapL.pop(); + else + ans += minHeapR.top(), minHeapR.pop(); + } + + return ans; + } +}; diff --git a/solutions/2462. Total Cost to Hire K Workers/2462.java b/solutions/2462. Total Cost to Hire K Workers/2462.java new file mode 100644 index 00000000000..2d59321d1c5 --- /dev/null +++ b/solutions/2462. Total Cost to Hire K Workers/2462.java @@ -0,0 +1,27 @@ +class Solution { + public long totalCost(int[] costs, int k, int candidates) { + long ans = 0; + int i = 0; + int j = costs.length - 1; + Queue minHeapL = new PriorityQueue<>(); + Queue minHeapR = new PriorityQueue<>(); + + for (int hired = 0; hired < k; ++hired) { + while (minHeapL.size() < candidates && i <= j) + minHeapL.offer(costs[i++]); + while (minHeapR.size() < candidates && i <= j) + minHeapR.offer(costs[j--]); + if (minHeapL.isEmpty()) + ans += minHeapR.poll(); + else if (minHeapR.isEmpty()) + ans += minHeapL.poll(); + // Both `minHeapL` and `minHeapR` are not empty. + else if (minHeapL.peek() <= minHeapR.peek()) + ans += minHeapL.poll(); + else + ans += minHeapR.poll(); + } + + return ans; + } +} diff --git a/solutions/2462. Total Cost to Hire K Workers/2462.py b/solutions/2462. Total Cost to Hire K Workers/2462.py new file mode 100644 index 00000000000..20c8696500b --- /dev/null +++ b/solutions/2462. Total Cost to Hire K Workers/2462.py @@ -0,0 +1,26 @@ +class Solution: + def totalCost(self, costs: List[int], k: int, candidates: int) -> int: + ans = 0 + i = 0 + j = len(costs) - 1 + minHeapL = [] # First half + minHeapR = [] # Second half + + for _ in range(k): + while len(minHeapL) < candidates and i <= j: + heapq.heappush(minHeapL, costs[i]) + i += 1 + while len(minHeapR) < candidates and i <= j: + heapq.heappush(minHeapR, costs[j]) + j -= 1 + if not minHeapL: + ans += heapq.heappop(minHeapR) + elif not minHeapR: + ans += heapq.heappop(minHeapL) + # Both `minHeapL` and `minHeapR` are not empty. + elif minHeapL[0] <= minHeapR[0]: + ans += heapq.heappop(minHeapL) + else: + ans += heapq.heappop(minHeapR) + + return ans diff --git a/solutions/2463. Minimum Total Distance Traveled/2463.cpp b/solutions/2463. Minimum Total Distance Traveled/2463.cpp new file mode 100644 index 00000000000..317e8fa8ced --- /dev/null +++ b/solutions/2463. Minimum Total Distance Traveled/2463.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + long long minimumTotalDistance(vector& robot, + vector>& factory) { + ranges::sort(robot); + ranges::sort(factory); + vector>> mem( + robot.size(), + vector>(factory.size(), vector(robot.size()))); + return minimumTotalDistance(robot, factory, 0, 0, 0, mem); + } + + private: + // Returns the minimum distance to fix robot[i..n) with factory[j..n), where + // factory[j] already fixed k robots. + long minimumTotalDistance(const vector& robot, + const vector>& factory, int i, int j, + int k, vector>>& mem) { + if (i == robot.size()) + return 0; + if (j == factory.size()) + return LONG_MAX; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + const long skipFactory = + minimumTotalDistance(robot, factory, i, j + 1, 0, mem); + const int position = factory[j][0]; + const int limit = factory[j][1]; + const long useFactory = + limit > k ? minimumTotalDistance(robot, factory, i + 1, j, k + 1, mem) + + abs(robot[i] - position) + : LONG_MAX / 2; + return mem[i][j][k] = min(skipFactory, useFactory); + } +}; diff --git a/solutions/2463. Minimum Total Distance Traveled/2463.java b/solutions/2463. Minimum Total Distance Traveled/2463.java new file mode 100644 index 00000000000..a0c917d0b65 --- /dev/null +++ b/solutions/2463. Minimum Total Distance Traveled/2463.java @@ -0,0 +1,25 @@ +class Solution { + public long minimumTotalDistance(List robot, int[][] factory) { + Collections.sort(robot); + Arrays.sort(factory, (a, b) -> (a[0] - b[0])); + long[][][] mem = new long[robot.size()][factory.length][robot.size()]; + return minimumTotalDistance(robot, factory, 0, 0, 0, mem); + } + + private long minimumTotalDistance(List robot, int[][] factory, int i, int j, int k, + long[][][] mem) { + if (i == robot.size()) + return 0; + if (j == factory.length) + return Long.MAX_VALUE; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + final long skipFactory = minimumTotalDistance(robot, factory, i, j + 1, 0, mem); + final int position = factory[j][0]; + final int limit = factory[j][1]; + final long useFactory = limit > k ? minimumTotalDistance(robot, factory, i + 1, j, k + 1, mem) + + Math.abs(robot.get(i) - position) + : Long.MAX_VALUE / 2; + return mem[i][j][k] = Math.min(skipFactory, useFactory); + } +} diff --git a/solutions/2463. Minimum Total Distance Traveled/2463.py b/solutions/2463. Minimum Total Distance Traveled/2463.py new file mode 100644 index 00000000000..0b5862bf5af --- /dev/null +++ b/solutions/2463. Minimum Total Distance Traveled/2463.py @@ -0,0 +1,22 @@ +class Solution: + def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: + robot.sort() + factory.sort() + + @functools.lru_cache(None) + def dp(i: int, j: int, k: int) -> int: + """ + Returns the minimum distance to fix robot[i..n) with factory[j..n), where + factory[j] already fixed k robots. + """ + if i == len(robot): + return 0 + if j == len(factory): + return math.inf + skipFactory = dp(i, j + 1, 0) + position, limit = factory[j] + useFactory = dp(i + 1, j, k + 1) + abs(robot[i] - position) \ + if limit > k else math.inf + return min(skipFactory, useFactory) + + return dp(0, 0, 0) diff --git a/solutions/2464. Minimum Subarrays in a Valid Split/2464.cpp b/solutions/2464. Minimum Subarrays in a Valid Split/2464.cpp new file mode 100644 index 00000000000..312aff147e7 --- /dev/null +++ b/solutions/2464. Minimum Subarrays in a Valid Split/2464.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int validSubarraySplit(vector& nums) { + constexpr int kMax = INT_MAX / 2; + // dp[i] := the minimum number of subarrays to validly split nums[0..i] + vector dp(nums.size(), kMax); + + for (int i = 0; i < nums.size(); ++i) + for (int j = 0; j <= i; ++j) + if (__gcd(nums[j], nums[i]) > 1) + dp[i] = min(dp[i], j == 0 ? 1 : dp[j - 1] + 1); + + return dp.back() == kMax ? -1 : dp.back(); + } +}; diff --git a/solutions/2464. Minimum Subarrays in a Valid Split/2464.java b/solutions/2464. Minimum Subarrays in a Valid Split/2464.java new file mode 100644 index 00000000000..83b9b2436d6 --- /dev/null +++ b/solutions/2464. Minimum Subarrays in a Valid Split/2464.java @@ -0,0 +1,20 @@ +class Solution { + public int validSubarraySplit(int[] nums) { + final int kMax = Integer.MAX_VALUE / 2; + final int n = nums.length; + // dp[i] := the minimum number of subarrays to validly split nums[0..i] + int[] dp = new int[n]; + Arrays.fill(dp, kMax); + + for (int i = 0; i < n; ++i) + for (int j = 0; j <= i; ++j) + if (gcd(nums[j], nums[i]) > 1) + dp[i] = Math.min(dp[i], j == 0 ? 1 : dp[j - 1] + 1); + + return dp[n - 1] == kMax ? -1 : dp[n - 1]; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2464. Minimum Subarrays in a Valid Split/2464.py b/solutions/2464. Minimum Subarrays in a Valid Split/2464.py new file mode 100644 index 00000000000..7dce5e2d5cd --- /dev/null +++ b/solutions/2464. Minimum Subarrays in a Valid Split/2464.py @@ -0,0 +1,11 @@ +class Solution: + def validSubarraySplit(self, nums: List[int]) -> int: + # dp[i] := the minimum number of subarrays to validly split nums[0..i] + dp = [math.inf] * len(nums) + + for i, num in enumerate(nums): + for j in range(i + 1): + if math.gcd(nums[j], num) > 1: + dp[i] = min(dp[i], 1 if j == 0 else dp[j - 1] + 1) + + return -1 if dp[-1] == math.inf else dp[-1] diff --git a/solutions/2465. Number of Distinct Averages/2465.cpp b/solutions/2465. Number of Distinct Averages/2465.cpp new file mode 100644 index 00000000000..33e0c621cf9 --- /dev/null +++ b/solutions/2465. Number of Distinct Averages/2465.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int distinctAverages(vector& nums) { + const int n = nums.size(); + unordered_set sums; + + ranges::sort(nums); + + for (int i = 0; i < n / 2; ++i) + sums.insert(nums[i] + nums[n - 1 - i]); + + return sums.size(); + } +}; diff --git a/solutions/2465. Number of Distinct Averages/2465.java b/solutions/2465. Number of Distinct Averages/2465.java new file mode 100644 index 00000000000..6b6dd5aebd4 --- /dev/null +++ b/solutions/2465. Number of Distinct Averages/2465.java @@ -0,0 +1,13 @@ +class Solution { + public int distinctAverages(int[] nums) { + final int n = nums.length; + Set sums = new HashSet<>(); + + Arrays.sort(nums); + + for (int i = 0; i < n / 2; ++i) + sums.add(nums[i] + nums[n - 1 - i]); + + return sums.size(); + } +} diff --git a/solutions/2465. Number of Distinct Averages/2465.py b/solutions/2465. Number of Distinct Averages/2465.py new file mode 100644 index 00000000000..be771bfd7f7 --- /dev/null +++ b/solutions/2465. Number of Distinct Averages/2465.py @@ -0,0 +1,11 @@ +class Solution: + def distinctAverages(self, nums: List[int]) -> int: + n = len(nums) + sums = set() + + nums.sort() + + for i in range(n // 2): + sums.add(nums[i] + nums[n - 1 - i]) + + return len(sums) diff --git a/solutions/2466. Count Ways To Build Good Strings/2466.cpp b/solutions/2466. Count Ways To Build Good Strings/2466.cpp new file mode 100644 index 00000000000..37d2a6fbf71 --- /dev/null +++ b/solutions/2466. Count Ways To Build Good Strings/2466.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int countGoodStrings(int low, int high, int zero, int one) { + constexpr int kMod = 1'000'000'007; + int ans = 0; + // dp[i] := the number of good strings with length i + vector dp(high + 1); + dp[0] = 1; + + for (int i = 1; i <= high; ++i) { + if (i >= zero) + dp[i] = (dp[i] + dp[i - zero]) % kMod; + if (i >= one) + dp[i] = (dp[i] + dp[i - one]) % kMod; + if (i >= low) + ans = (ans + dp[i]) % kMod; + } + + return ans; + } +}; diff --git a/solutions/2466. Count Ways To Build Good Strings/2466.java b/solutions/2466. Count Ways To Build Good Strings/2466.java new file mode 100644 index 00000000000..883a8980a76 --- /dev/null +++ b/solutions/2466. Count Ways To Build Good Strings/2466.java @@ -0,0 +1,20 @@ +class Solution { + public int countGoodStrings(int low, int high, int zero, int one) { + final int kMod = 1_000_000_007; + int ans = 0; + // dp[i] := the number of good strings with length i + int[] dp = new int[high + 1]; + dp[0] = 1; + + for (int i = 1; i <= high; ++i) { + if (i >= zero) + dp[i] = (dp[i] + dp[i - zero]) % kMod; + if (i >= one) + dp[i] = (dp[i] + dp[i - one]) % kMod; + if (i >= low) + ans = (ans + dp[i]) % kMod; + } + + return ans; + } +} diff --git a/solutions/2466. Count Ways To Build Good Strings/2466.py b/solutions/2466. Count Ways To Build Good Strings/2466.py new file mode 100644 index 00000000000..7d78cb0f352 --- /dev/null +++ b/solutions/2466. Count Ways To Build Good Strings/2466.py @@ -0,0 +1,16 @@ +class Solution: + def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: + kMod = 1_000_000_007 + ans = 0 + # dp[i] := the number of good strings with length i + dp = [1] + [0] * high + + for i in range(1, high + 1): + if i >= zero: + dp[i] = (dp[i] + dp[i - zero]) % kMod + if i >= one: + dp[i] = (dp[i] + dp[i - one]) % kMod + if i >= low: + ans = (ans + dp[i]) % kMod + + return ans diff --git a/solutions/2467. Most Profitable Path in a Tree/2467.cpp b/solutions/2467. Most Profitable Path in a Tree/2467.cpp new file mode 100644 index 00000000000..a690185410a --- /dev/null +++ b/solutions/2467. Most Profitable Path in a Tree/2467.cpp @@ -0,0 +1,57 @@ +class Solution { + public: + int mostProfitablePath(vector>& edges, int bob, + vector& amount) { + const int n = amount.size(); + vector> tree(n); + vector parent(n); + vector aliceDist(n, -1); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + dfs(tree, 0, -1, 0, parent, aliceDist); + + // Modify the amount along the path from node Bob to node 0. + // For each node, + // 1. If Bob reaches earlier than Alice does, change the amount to 0. + // 2. If Bob and Alice reach simultaneously, devide the amount by 2. + for (int u = bob, bobDist = 0; u != 0; u = parent[u], ++bobDist) + if (bobDist < aliceDist[u]) + amount[u] = 0; + else if (bobDist == aliceDist[u]) + amount[u] /= 2; + + return getMoney(tree, 0, -1, amount); + } + + private: + // Fills `parent` and `dist`. + void dfs(const vector>& tree, int u, int prev, int d, + vector& parent, vector& dist) { + parent[u] = prev; + dist[u] = d; + for (const int v : tree[u]) { + if (dist[v] == -1) + dfs(tree, v, u, d + 1, parent, dist); + } + } + + int getMoney(const vector>& tree, int u, int prev, + const vector& amount) { + // a leaf node + if (tree[u].size() == 1 && tree[u][0] == prev) + return amount[u]; + + int maxPath = INT_MIN; + for (const int v : tree[u]) + if (v != prev) + maxPath = max(maxPath, getMoney(tree, v, u, amount)); + + return amount[u] + maxPath; + } +}; diff --git a/solutions/2467. Most Profitable Path in a Tree/2467.java b/solutions/2467. Most Profitable Path in a Tree/2467.java new file mode 100644 index 00000000000..6e04dd07c7a --- /dev/null +++ b/solutions/2467. Most Profitable Path in a Tree/2467.java @@ -0,0 +1,56 @@ +class Solution { + public int mostProfitablePath(int[][] edges, int bob, int[] amount) { + final int n = amount.length; + List[] tree = new List[n]; + int[] parent = new int[n]; + int[] aliceDist = new int[n]; + Arrays.fill(aliceDist, -1); + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + dfs(tree, 0, -1, 0, parent, aliceDist); + + // Modify the amount along the path from node Bob to node 0. + // For each node, + // 1. If Bob reaches earlier than Alice does, change the amount to 0. + // 2. If Bob and Alice reach simultaneously, devide the amount by 2. + for (int u = bob, bobDist = 0; u != 0; u = parent[u], ++bobDist) + if (bobDist < aliceDist[u]) + amount[u] = 0; + else if (bobDist == aliceDist[u]) + amount[u] /= 2; + + return getMoney(tree, 0, -1, amount); + } + + // Fills `parent` and `dist`. + private void dfs(List[] tree, int u, int prev, int d, int[] parent, int[] dist) { + parent[u] = prev; + dist[u] = d; + for (final int v : tree[u]) { + if (dist[v] == -1) + dfs(tree, v, u, d + 1, parent, dist); + } + } + + private int getMoney(List[] tree, int u, int prev, int[] amount) { + // a leaf node + if (tree[u].size() == 1 && tree[u].get(0) == prev) + return amount[u]; + + int maxPath = Integer.MIN_VALUE; + for (final int v : tree[u]) + if (v != prev) + maxPath = Math.max(maxPath, getMoney(tree, v, u, amount)); + + return amount[u] + maxPath; + } +} diff --git a/solutions/2467. Most Profitable Path in a Tree/2467.py b/solutions/2467. Most Profitable Path in a Tree/2467.py new file mode 100644 index 00000000000..2e250588d28 --- /dev/null +++ b/solutions/2467. Most Profitable Path in a Tree/2467.py @@ -0,0 +1,48 @@ +class Solution: + def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: + n = len(amount) + tree = [[] for _ in range(n)] + parent = [0] * n + aliceDist = [-1] * n + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + # Fills `parent` and `aliceDist`. + def dfs(u: int, prev: int, d: int) -> None: + parent[u] = prev + aliceDist[u] = d + for v in tree[u]: + if aliceDist[v] == -1: + dfs(v, u, d + 1) + + dfs(0, -1, 0) + + # Modify amount athe path from node bob to node 0. + # For each node, + # 1. If Bob reaches earlier than Alice does, change the amount to 0. + # 2. If Bob and Alice reach simultaneously, devide the amount by 2. + u = bob + bobDist = 0 + while u != 0: + if bobDist < aliceDist[u]: + amount[u] = 0 + elif bobDist == aliceDist[u]: + amount[u] //= 2 + u = parent[u] + bobDist += 1 + + return self._getMoney(tree, 0, -1, amount) + + def _getMoney(self, tree: List[List[int]], u: int, prev: int, amount: List[int]) -> int: + # a leaf node + if len(tree[u]) == 1 and tree[u][0] == prev: + return amount[u] + + maxPath = -math.inf + for v in tree[u]: + if v != prev: + maxPath = max(maxPath, self._getMoney(tree, v, u, amount)) + + return amount[u] + maxPath diff --git a/solutions/2468. Split Message Based on Limit/2468.cpp b/solutions/2468. Split Message Based on Limit/2468.cpp new file mode 100644 index 00000000000..e8b54c04e13 --- /dev/null +++ b/solutions/2468. Split Message Based on Limit/2468.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector splitMessage(string message, int limit) { + const int kMessageLength = message.length(); + int b = 1; + // the total length of a: initialized with the length of "1" + int aLength = sz(1); + + // the total length of b := b * sz(b) + // The total length of "" := b * 3 + while (b * limit < b * (sz(b) + 3) + aLength + kMessageLength) { + // If the length of the last suffix "" := sz(b) * 2 + 3 >= limit, + // then it's impossible that the length of "*" <= limit. + if (sz(b) * 2 + 3 >= limit) + return {}; + aLength += sz(++b); + } + + vector ans; + + for (int i = 0, a = 1; a <= b; ++a) { + // the length of "" := sz(a) + sz(b) + 3 + const int j = limit - (sz(a) + sz(b) + 3); + ans.push_back(message.substr(i, j) + "<" + to_string(a) + "/" + + to_string(b) + ">"); + i += j; + } + + return ans; + } + + private: + int sz(int num) { + return to_string(num).length(); + } +}; diff --git a/solutions/2468. Split Message Based on Limit/2468.java b/solutions/2468. Split Message Based on Limit/2468.java new file mode 100644 index 00000000000..6d9748a244e --- /dev/null +++ b/solutions/2468. Split Message Based on Limit/2468.java @@ -0,0 +1,34 @@ +class Solution { + public String[] splitMessage(String message, int limit) { + final int kMessageLength = message.length(); + int b = 1; + // the total length of a: initialized with the length of "1" + int aLength = sz(1); + + // the total length of b := b * sz(b) + // The total length of "" := b * 3 + while (b * limit < b * (sz(b) + 3) + aLength + kMessageLength) { + // If the length of the last suffix "" := sz(b) * 2 + 3 >= limit, + // then it's impossible that the length of "*" <= limit. + if (sz(b) * 2 + 3 >= limit) + return new String[] {}; + aLength += sz(++b); + } + + String[] ans = new String[b]; + + for (int i = 0, a = 1; a <= b; ++a) { + // the length of "" := sz(a) + sz(b) + 3 + final int j = limit - (sz(a) + sz(b) + 3); + ans[a - 1] = message.substring(i, Math.min(message.length(), i + j)) + "<" + + String.valueOf(a) + "/" + String.valueOf(b) + ">"; + i += j; + } + + return ans; + } + + private int sz(int num) { + return String.valueOf(num).length(); + } +} diff --git a/solutions/2468. Split Message Based on Limit/2468.py b/solutions/2468. Split Message Based on Limit/2468.py new file mode 100644 index 00000000000..df3777b2691 --- /dev/null +++ b/solutions/2468. Split Message Based on Limit/2468.py @@ -0,0 +1,31 @@ +class Solution: + def splitMessage(self, message: str, limit: int) -> List[str]: + kMessageLength = len(message) + + def sz(num: int): + return len(str(num)) + + b = 1 + # the total length of a: initialized with the length of "1" + aLength = sz(1) + + # the total length of b := b * sz(b) + # The total length of "" := b * 3 + while b * limit < b * (sz(b) + 3) + aLength + kMessageLength: + # If the length of the last suffix "" := sz(b) * 2 + 3 >= limit, + # then it's impossible that the length of "*" <= limit. + if sz(b) * 2 + 3 >= limit: + return [] + b += 1 + aLength += sz(b) + + ans = [] + + i = 0 + for a in range(1, b + 1): + # the length of "" := sz(a) + sz(b) + 3 + j = limit - (sz(a) + sz(b) + 3) + ans.append(f'{message[i:i + j]}<{a}/{b}>') + i += j + + return ans diff --git a/solutions/2469. Convert the Temperature/2469.cpp b/solutions/2469. Convert the Temperature/2469.cpp new file mode 100644 index 00000000000..b26430a0efc --- /dev/null +++ b/solutions/2469. Convert the Temperature/2469.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + vector convertTemperature(double celsius) { + return {celsius + 273.15, celsius * 1.8 + 32}; + } +}; diff --git a/solutions/2469. Convert the Temperature/2469.java b/solutions/2469. Convert the Temperature/2469.java new file mode 100644 index 00000000000..1bfddcf9b27 --- /dev/null +++ b/solutions/2469. Convert the Temperature/2469.java @@ -0,0 +1,5 @@ +class Solution { + public double[] convertTemperature(double celsius) { + return new double[] {celsius + 273.15, celsius * 1.8 + 32}; + } +} diff --git a/solutions/2469. Convert the Temperature/2469.py b/solutions/2469. Convert the Temperature/2469.py new file mode 100644 index 00000000000..8bbe237567a --- /dev/null +++ b/solutions/2469. Convert the Temperature/2469.py @@ -0,0 +1,3 @@ +class Solution: + def convertTemperature(self, celsius: float) -> List[float]: + return [celsius + 273.15, celsius * 1.8 + 32] diff --git a/solutions/247. Strobogrammatic Number II/247.cpp b/solutions/247. Strobogrammatic Number II/247.cpp new file mode 100644 index 00000000000..68738f88b91 --- /dev/null +++ b/solutions/247. Strobogrammatic Number II/247.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector findStrobogrammatic(int n) { + return helper(n, n); + } + + private: + vector helper(int n, int k) { + if (n == 0) + return {""}; + if (n == 1) + return {"0", "1", "8"}; + + vector ans; + + for (const string& inner : helper(n - 2, k)) { + if (n < k) + ans.push_back("0" + inner + "0"); + ans.push_back("1" + inner + "1"); + ans.push_back("6" + inner + "9"); + ans.push_back("8" + inner + "8"); + ans.push_back("9" + inner + "6"); + } + + return ans; + } +}; diff --git a/solutions/247. Strobogrammatic Number II/247.java b/solutions/247. Strobogrammatic Number II/247.java new file mode 100644 index 00000000000..8e6a9b4b85b --- /dev/null +++ b/solutions/247. Strobogrammatic Number II/247.java @@ -0,0 +1,25 @@ +class Solution { + public List findStrobogrammatic(int n) { + return helper(n, n); + } + + private List helper(int n, int k) { + if (n == 0) + return new ArrayList<>(Arrays.asList("")); + if (n == 1) + return new ArrayList<>(Arrays.asList("0", "1", "8")); + + List ans = new ArrayList<>(); + + for (final String inner : helper(n - 2, k)) { + if (n < k) + ans.add("0" + inner + "0"); + ans.add("1" + inner + "1"); + ans.add("6" + inner + "9"); + ans.add("8" + inner + "8"); + ans.add("9" + inner + "6"); + } + + return ans; + } +} diff --git a/solutions/247. Strobogrammatic Number II/247.py b/solutions/247. Strobogrammatic Number II/247.py new file mode 100644 index 00000000000..3fb71f318e0 --- /dev/null +++ b/solutions/247. Strobogrammatic Number II/247.py @@ -0,0 +1,21 @@ +class Solution: + def findStrobogrammatic(self, n: int) -> List[str]: + def helper(n: int, k: int) -> List[str]: + if n == 0: + return [''] + if n == 1: + return ['0', '1', '8'] + + ans = [] + + for inner in helper(n - 2, k): + if n < k: + ans.append('0' + inner + '0') + ans.append('1' + inner + '1') + ans.append('6' + inner + '9') + ans.append('8' + inner + '8') + ans.append('9' + inner + '6') + + return ans + + return helper(n, n) diff --git a/solutions/2470. Number of Subarrays With LCM Equal to K/2470.cpp b/solutions/2470. Number of Subarrays With LCM Equal to K/2470.cpp new file mode 100644 index 00000000000..0ef76f05128 --- /dev/null +++ b/solutions/2470. Number of Subarrays With LCM Equal to K/2470.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int subarrayLCM(vector& nums, int k) { + int ans = 0; + + for (int i = 0; i < nums.size(); ++i) { + int runningLcm = nums[i]; + for (int j = i; j < nums.size(); ++j) { + runningLcm = std::lcm(runningLcm, nums[j]); + if (runningLcm > k) + break; + if (runningLcm == k) + ++ans; + } + } + + return ans; + } +}; diff --git a/solutions/2470. Number of Subarrays With LCM Equal to K/2470.java b/solutions/2470. Number of Subarrays With LCM Equal to K/2470.java new file mode 100644 index 00000000000..de868892d05 --- /dev/null +++ b/solutions/2470. Number of Subarrays With LCM Equal to K/2470.java @@ -0,0 +1,26 @@ +class Solution { + public int subarrayLCM(int[] nums, int k) { + int ans = 0; + + for (int i = 0; i < nums.length; ++i) { + int runningLcm = nums[i]; + for (int j = i; j < nums.length; ++j) { + runningLcm = lcm(runningLcm, nums[j]); + if (runningLcm > k) + break; + if (runningLcm == k) + ++ans; + } + } + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private int lcm(int a, int b) { + return a * (b / gcd(a, b)); + } +} diff --git a/solutions/2470. Number of Subarrays With LCM Equal to K/2470.py b/solutions/2470. Number of Subarrays With LCM Equal to K/2470.py new file mode 100644 index 00000000000..12bc8bce5ef --- /dev/null +++ b/solutions/2470. Number of Subarrays With LCM Equal to K/2470.py @@ -0,0 +1,13 @@ +class Solution: + def subarrayLCM(self, nums: List[int], k: int) -> int: + ans = 0 + + for i, runningLcm in enumerate(nums): + for j in range(i, len(nums)): + runningLcm = math.lcm(runningLcm, nums[j]) + if runningLcm > k: + break + if runningLcm == k: + ans += 1 + + return ans diff --git a/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.cpp b/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.cpp new file mode 100644 index 00000000000..6671a6efe49 --- /dev/null +++ b/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minimumOperations(TreeNode* root) { + int ans = 0; + queue q{{root}}; + + // e.g. vals = [7, 6, 8, 5] + // [2, 1, 3, 0]: Initialize the ids based on the order of vals. + // [3, 1, 2, 0]: Swap 2 with 3, so 2 is in the right place (i == ids[i]). + // [0, 1, 2, 3]: Swap 3 with 0, so 3 is in the right place. + while (!q.empty()) { + vector vals; + vector ids(q.size()); + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + vals.push_back(node->val); + if (node->left != nullptr) + q.push(node->left); + if (node->right != nullptr) + q.push(node->right); + } + iota(ids.begin(), ids.end(), 0); + ranges::sort(ids, [&vals](int i, int j) { return vals[i] < vals[j]; }); + for (int i = 0; i < ids.size(); ++i) + for (; ids[i] != i; ++ans) + swap(ids[i], ids[ids[i]]); + } + + return ans; + } +}; diff --git a/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.java b/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.java new file mode 100644 index 00000000000..af94cbabc51 --- /dev/null +++ b/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.java @@ -0,0 +1,37 @@ +class Solution { + public int minimumOperations(TreeNode root) { + int ans = 0; + Queue q = new LinkedList<>(Arrays.asList(root)); + + // e.g. vals = [7, 6, 8, 5] + // [2, 1, 3, 0]: Initialize the ids based on the order of vals. + // [3, 1, 2, 0]: Swap 2 with 3, so 2 is in the right place (i == ids[i]). + // [0, 1, 2, 3]: Swap 3 with 0, so 3 is in the right place. + while (!q.isEmpty()) { + List vals = new ArrayList<>(); + List ids = new ArrayList<>(); + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + vals.add(node.val); + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + for (int i = 0; i < vals.size(); ++i) + ids.add(i); + Collections.sort(ids, (i, j) -> vals.get(i) - vals.get(j)); + for (int i = 0; i < ids.size(); ++i) + for (; ids.get(i) != i; ++ans) + swap(ids, i, ids.get(i)); + } + + return ans; + } + + private void swap(List ids, int i, int j) { + final int temp = ids.get(i); + ids.set(i, ids.get(j)); + ids.set(j, temp); + } +} diff --git a/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.py b/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.py new file mode 100644 index 00000000000..2dd0b192a75 --- /dev/null +++ b/solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.py @@ -0,0 +1,28 @@ +class Solution: + def minimumOperations(self, root: Optional[TreeNode]) -> int: + ans = 0 + q = collections.deque([root]) + + # e.g. vals = [7, 6, 8, 5] + # [2, 1, 3, 0]: Initialize the ids based on the order of vals. + # [3, 1, 2, 0]: Swap 2 with 3, so 2 is in the right place (i == ids[i]). + # [0, 1, 2, 3]: Swap 3 with 0, so 3 is in the right place. + while q: + vals = [] + for _ in range(len(q)): + node = q.popleft() + vals.append(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + # O(n^2logn), which is not great and leads to TLE. + ids = [sorted(vals).index(val) for val in vals] + for i in range(len(ids)): + while ids[i] != i: + j = ids[i] + ids[i] = ids[j] + ids[j] = j + ans += 1 + + return ans diff --git a/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.cpp b/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.cpp new file mode 100644 index 00000000000..42be55e1431 --- /dev/null +++ b/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int maxPalindromes(string s, int k) { + const int n = s.length(); + // dp[i] := the maximum number of substrings in the first i chars of s + vector dp(n + 1); + + // If a palindrome is a substring of another palindrome, then considering + // the longer palindrome won't increase the number of non-overlapping + // palindromes. So, we only need to consider the shorter one. Also, + // considering palindromes with both k length and k + 1 length ensures that + // we look for both even and odd length palindromes. + for (int i = k; i <= n; ++i) { + dp[i] = dp[i - 1]; + // Consider palindrome with length k. + if (isPalindrome(s, i - k, i - 1)) + dp[i] = max(dp[i], 1 + dp[i - k]); + // Consider palindrome with length k + 1. + if (isPalindrome(s, i - k - 1, i - 1)) + dp[i] = max(dp[i], 1 + dp[i - k - 1]); + } + + return dp[n]; + } + + private: + // Returns true is s[i..j) is a palindrome. + bool isPalindrome(const string& s, int l, int r) { + if (l < 0) + return false; + while (l < r) + if (s[l++] != s[r--]) + return false; + return true; + } +}; diff --git a/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.java b/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.java new file mode 100644 index 00000000000..b6baf28aac2 --- /dev/null +++ b/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.java @@ -0,0 +1,34 @@ +class Solution { + public int maxPalindromes(String s, int k) { + final int n = s.length(); + // dp[i] := the maximum number of substrings in the first i chars of s + int[] dp = new int[n + 1]; + + // If a palindrome is a subString of another palindrome, then considering + // the longer palindrome won't increase the number of non-overlapping + // palindromes. So, we only need to consider the shorter one. Also, + // considering palindromes with both k length and k + 1 length ensures that + // we look for both even and odd length palindromes. + for (int i = k; i <= n; ++i) { + dp[i] = dp[i - 1]; + // Consider palindrome with length k. + if (isPalindrome(s, i - k, i - 1)) + dp[i] = Math.max(dp[i], 1 + dp[i - k]); + // Consider palindrome with length k + 1. + if (isPalindrome(s, i - k - 1, i - 1)) + dp[i] = Math.max(dp[i], 1 + dp[i - k - 1]); + } + + return dp[n]; + } + + // Returns true is s[i..j) is a palindrome. + private boolean isPalindrome(String s, int l, int r) { + if (l < 0) + return false; + while (l < r) + if (s.charAt(l++) != s.charAt(r--)) + return false; + return true; + } +} diff --git a/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.py b/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.py new file mode 100644 index 00000000000..df5645fcc60 --- /dev/null +++ b/solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.py @@ -0,0 +1,32 @@ +class Solution: + def maxPalindromes(self, s: str, k: int) -> int: + n = len(s) + # dp[i] := the maximum number of substrings in the first i chars of s + dp = [0] * (n + 1) + + def isPalindrome(l: int, r: int) -> bool: + """Returns True is s[i..j) is a palindrome.""" + if l < 0: + return False + while l < r: + if s[l] != s[r]: + return False + l += 1 + r -= 1 + return True + + # If a palindrome is a subof another palindrome, then considering + # the longer palindrome won't increase the number of non-overlapping + # palindromes. So, we only need to consider the shorter one. Also, + # considering palindromes with both k length and k + 1 length ensures that + # we look for both even and odd length palindromes. + for i in range(k, n + 1): + dp[i] = dp[i - 1] + # Consider palindrome with length k. + if isPalindrome(i - k, i - 1): + dp[i] = max(dp[i], 1 + dp[i - k]) + # Consider palindrome with length k + 1. + if isPalindrome(i - k - 1, i - 1): + dp[i] = max(dp[i], 1 + dp[i - k - 1]) + + return dp[n] diff --git a/solutions/2473. Minimum Cost to Buy Apples/2473.cpp b/solutions/2473. Minimum Cost to Buy Apples/2473.cpp new file mode 100644 index 00000000000..476d6948c4a --- /dev/null +++ b/solutions/2473. Minimum Cost to Buy Apples/2473.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + vector minCost(int n, vector>& roads, + vector& appleCost, int k) { + vector ans; + vector>> graph(n); + + for (const vector& road : roads) { + const int u = road[0] - 1; + const int v = road[1] - 1; + const int w = road[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + for (int i = 0; i < n; ++i) + ans.push_back(dijkstra(graph, i, appleCost, k)); + + return ans; + } + + private: + long dijkstra(const vector>>& graph, int i, + const vector& appleCost, int k) { + vector forwardCost(graph.size(), LONG_MAX); + vector totalCost(graph.size(), LONG_MAX); + forwardCost[i] = 0; + queue q{{i}}; + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const auto& [v, w] : graph[u]) { + const long nextCost = forwardCost[u] + w; + if (nextCost >= forwardCost[v]) + continue; + forwardCost[v] = nextCost; + // Take apple at city v and return back to city i. + totalCost[v] = (k + 1) * nextCost + appleCost[v]; + q.push(v); + } + } + + return min(static_cast(appleCost[i]), ranges::min(totalCost)); + } +}; diff --git a/solutions/2473. Minimum Cost to Buy Apples/2473.java b/solutions/2473. Minimum Cost to Buy Apples/2473.java new file mode 100644 index 00000000000..c0ec03d40ba --- /dev/null +++ b/solutions/2473. Minimum Cost to Buy Apples/2473.java @@ -0,0 +1,48 @@ +class Solution { + public long[] minCost(int n, int[][] roads, int[] appleCost, int k) { + long[] ans = new long[n]; + List>[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] road : roads) { + final int u = road[0] - 1; + final int v = road[1] - 1; + final int w = road[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + for (int i = 0; i < n; ++i) + ans[i] = dijkstra(graph, i, appleCost, k); + + return ans; + } + + private long dijkstra(List>[] graph, int i, int[] appleCost, int k) { + long[] forwardCost = new long[graph.length]; + long[] totalCost = new long[graph.length]; + Arrays.fill(forwardCost, Long.MAX_VALUE); + Arrays.fill(totalCost, Long.MAX_VALUE); + forwardCost[i] = 0; + Queue q = new LinkedList<>(Arrays.asList(i)); + + while (!q.isEmpty()) { + final int u = q.poll(); + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + final long nextCost = forwardCost[u] + w; + if (nextCost >= forwardCost[v]) + continue; + forwardCost[v] = nextCost; + // Take apple at city v and return back to city i. + totalCost[v] = (k + 1) * nextCost + appleCost[v]; + q.offer(v); + } + } + + return Math.min(appleCost[i], Arrays.stream(totalCost).min().getAsLong()); + } +} diff --git a/solutions/2473. Minimum Cost to Buy Apples/2473.py b/solutions/2473. Minimum Cost to Buy Apples/2473.py new file mode 100644 index 00000000000..11eacbbb499 --- /dev/null +++ b/solutions/2473. Minimum Cost to Buy Apples/2473.py @@ -0,0 +1,28 @@ +class Solution: + def minCost(self, n: int, roads: List[List[int]], appleCost: List[int], k: int) -> List[int]: + graph = [[] for _ in range(n)] + + for u, v, w in roads: + graph[u - 1].append((v - 1, w)) + graph[v - 1].append((u - 1, w)) + + def dijkstra(i: int) -> int: + forwardCost = [math.inf] * n + totalCost = [math.inf] * n + forwardCost[i] = 0 + q = collections.deque([i]) + + while q: + u = q.popleft() + for v, w in graph[u]: + nextCost = forwardCost[u] + w + if nextCost >= forwardCost[v]: + continue + forwardCost[v] = nextCost + # Take apple at city v and return back to city i. + totalCost[v] = (k + 1) * nextCost + appleCost[v] + q.append(v) + + return min(appleCost[i], min(totalCost)) + + return [dijkstra(i) for i in range(n)] diff --git a/solutions/2474. Customers With Strictly Increasing Purchases/2474.sql b/solutions/2474. Customers With Strictly Increasing Purchases/2474.sql new file mode 100644 index 00000000000..fbdaaa7b883 --- /dev/null +++ b/solutions/2474. Customers With Strictly Increasing Purchases/2474.sql @@ -0,0 +1,18 @@ +WITH + YearlyOrders AS ( + SELECT + customer_id, + YEAR(order_date) AS year, + SUM(price) AS price + FROM Orders + GROUP BY 1, 2 + ) +SELECT CurrYear.customer_id +FROM YearlyOrders AS CurrYear +LEFT JOIN YearlyOrders AS NextYear + ON ( + CurrYear.customer_id = NextYear.customer_id + AND CurrYear.year + 1 = NextYear.year + AND CurrYear.price < NextYear.price) +GROUP BY 1 +HAVING COUNT(*) - COUNT(NextYear.customer_id) = 1; diff --git a/solutions/2475. Number of Unequal Triplets in Array/2475.cpp b/solutions/2475. Number of Unequal Triplets in Array/2475.cpp new file mode 100644 index 00000000000..345eea54a9e --- /dev/null +++ b/solutions/2475. Number of Unequal Triplets in Array/2475.cpp @@ -0,0 +1,37 @@ +// Assume that we have 4 kinds of numbers a, b, c, and d in the count map. +// +// What we want is: +// cnt[a] * cnt[b] * cnt[c] +// cnt[a] * cnt[b] * cnt[d] +// cnt[a] * cnt[c] * cnt[d] +// cnt[b] * cnt[c] * cnt[d] +// +// The above combinations can be reduced as: +// +// prev | curr | next +// ---------------------------------------------------------------- +// (0) * cnt[a] * (cnt[b] + cnt[c] + cnt[d]) +// (cnt[a]) * cnt[b] * (cnt[c] + cnt[d]) +// (cnt[a] + cnt[b]) * cnt[c] * (cnt[d]) +// (cnt[a] + cnt[b] + cnt[c]) * cnt[d] * (0) + +class Solution { + public: + int unequalTriplets(vector& nums) { + int ans = 0; + int prev = 0; + int next = nums.size(); + unordered_map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [_, freq] : count) { + next -= freq; + ans += prev * freq * next; + prev += freq; + } + + return ans; + } +}; diff --git a/solutions/2475. Number of Unequal Triplets in Array/2475.java b/solutions/2475. Number of Unequal Triplets in Array/2475.java new file mode 100644 index 00000000000..ab6abed3450 --- /dev/null +++ b/solutions/2475. Number of Unequal Triplets in Array/2475.java @@ -0,0 +1,36 @@ +// Assume that we have 4 kinds of numbers a, b, c, and d in the count map. +// +// What we want is: +// cnt[a] * cnt[b] * cnt[c] +// cnt[a] * cnt[b] * cnt[d] +// cnt[a] * cnt[c] * cnt[d] +// cnt[b] * cnt[c] * cnt[d] +// +// The above combinations can be reduced as: +// +// prev | curr | next +// ---------------------------------------------------------------- +// (0) * cnt[a] * (cnt[b] + cnt[c] + cnt[d]) +// (cnt[a]) * cnt[b] * (cnt[c] + cnt[d]) +// (cnt[a] + cnt[b]) * cnt[c] * (cnt[d]) +// (cnt[a] + cnt[b] + cnt[c]) * cnt[d] * (0) + +class Solution { + public int unequalTriplets(int[] nums) { + int ans = 0; + int prev = 0; + int next = nums.length; + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int freq : count.values()) { + next -= freq; + ans += prev * freq * next; + prev += freq; + } + + return ans; + } +} diff --git a/solutions/2475. Number of Unequal Triplets in Array/2475.py b/solutions/2475. Number of Unequal Triplets in Array/2475.py new file mode 100644 index 00000000000..80b638e536e --- /dev/null +++ b/solutions/2475. Number of Unequal Triplets in Array/2475.py @@ -0,0 +1,29 @@ +# Assume that we have 4 kinds of numbers a, b, c, and d in the count map. +# +# What we want is: +# cnt[a] * cnt[b] * cnt[c] +# cnt[a] * cnt[b] * cnt[d] +# cnt[a] * cnt[c] * cnt[d] +# cnt[b] * cnt[c] * cnt[d] +# +# The above combinations can be reduced as: +# +# prev | curr | next +# +# (0) * cnt[a] * (cnt[b] + cnt[c] + cnt[d]) +# (cnt[a]) * cnt[b] * (cnt[c] + cnt[d]) +# (cnt[a] + cnt[b]) * cnt[c] * (cnt[d]) +# (cnt[a] + cnt[b] + cnt[c]) * cnt[d] * (0) + +class Solution: + def unequalTriplets(self, nums: List[int]) -> int: + ans = 0 + prev = 0 + next = len(nums) + + for freq in collections.Counter(nums).values(): + next -= freq + ans += prev * freq * next + prev += freq + + return ans diff --git a/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.cpp b/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.cpp new file mode 100644 index 00000000000..9d419bf3f67 --- /dev/null +++ b/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector> closestNodes(TreeNode* root, vector& queries) { + vector> ans; + vector sortedVals; + + inorder(root, sortedVals); + + for (const int query : queries) { + const auto it = ranges::lower_bound(sortedVals, query); + // query is presented in the tree, so just use {query, query}. + if (it != sortedVals.cend() && *it == query) + ans.push_back({query, query}); + // query isn't presented in the tree, so find the cloest one if possible. + else + ans.push_back({it == sortedVals.cbegin() ? -1 : *prev(it), + it == sortedVals.cend() ? -1 : *it}); + } + + return ans; + } + + private: + // Walks the BST to collect the sorted numbers. + void inorder(TreeNode* root, vector& sortedVals) { + if (root == nullptr) + return; + inorder(root->left, sortedVals); + sortedVals.push_back(root->val); + inorder(root->right, sortedVals); + } +}; diff --git a/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.java b/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.java new file mode 100644 index 00000000000..3f50b829180 --- /dev/null +++ b/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.java @@ -0,0 +1,35 @@ +class Solution { + public List> closestNodes(TreeNode root, List queries) { + List> ans = new ArrayList<>(); + List sortedVals = new ArrayList<>(); + + inorder(root, sortedVals); + + for (final int query : queries) { + final int i = firstGreaterEqual(sortedVals, query); + // query is presented in the tree, so just use {query, query}. + if (i != sortedVals.size() && sortedVals.get(i) == query) + ans.add(Arrays.asList(query, query)); + // query isn't presented in the tree, so find the cloest one if possible. + else + ans.add(Arrays.asList(i == 0 ? -1 : sortedVals.get(i - 1), + i == sortedVals.size() ? -1 : sortedVals.get(i))); + } + + return ans; + } + + // Walks the BST to collect the sorted numbers. + private void inorder(TreeNode root, List sortedVals) { + if (root == null) + return; + inorder(root.left, sortedVals); + sortedVals.add(root.val); + inorder(root.right, sortedVals); + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.py b/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.py new file mode 100644 index 00000000000..1e249be5eab --- /dev/null +++ b/solutions/2476. Closest Nodes Queries in a Binary Search Tree/2476.py @@ -0,0 +1,23 @@ +class Solution: + def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: + sortedVals = [] + self._inorder(root, sortedVals) + + def getClosestPair(query: int) -> List[int]: + i = bisect_left(sortedVals, query) + # query is presented in the tree, so just use [query, query]. + if i != len(sortedVals) and sortedVals[i] == query: + return [query, query] + # query isn't presented in the tree, so find the cloest one if possible. + return [-1 if i == 0 else sortedVals[i - 1], + -1 if i == len(sortedVals) else sortedVals[i]] + + return [getClosestPair(query) for query in queries] + + def _inorder(self, root: Optional[TreeNode], sortedVals: List[int]) -> None: + """Walks the BST to collect the sorted numbers.""" + if not root: + return + self._inorder(root.left, sortedVals) + sortedVals.append(root.val) + self._inorder(root.right, sortedVals) diff --git a/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.cpp b/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.cpp new file mode 100644 index 00000000000..11534e7a1d0 --- /dev/null +++ b/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + long long minimumFuelCost(vector>& roads, int seats) { + long ans = 0; + vector> tree(roads.size() + 1); + + for (const vector& road : roads) { + const int u = road[0]; + const int v = road[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + dfs(tree, 0, -1, seats, ans); + return ans; + } + + private: + int dfs(const vector>& tree, int u, int prev, int seats, + long& ans) { + int people = 1; + for (const int v : tree[u]) { + if (v == prev) + continue; + people += dfs(tree, v, u, seats, ans); + } + if (u > 0) + // the number of cars needed = ceil(people / seats) + ans += (people + seats - 1) / seats; + return people; + } +}; diff --git a/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.java b/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.java new file mode 100644 index 00000000000..ef89448ab0c --- /dev/null +++ b/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.java @@ -0,0 +1,33 @@ +class Solution { + public long minimumFuelCost(int[][] roads, int seats) { + List[] tree = new List[roads.length + 1]; + + for (int i = 0; i < tree.length; ++i) + tree[i] = new ArrayList<>(); + + for (int[] road : roads) { + final int u = road[0]; + final int v = road[1]; + tree[u].add(v); + tree[v].add(u); + } + + dfs(tree, 0, -1, seats); + return ans; + } + + private long ans = 0; + + private int dfs(List[] tree, int u, int prev, int seats) { + int people = 1; + for (final int v : tree[u]) { + if (v == prev) + continue; + people += dfs(tree, v, u, seats); + } + if (u > 0) + // the number of cars needed = ceil(people / seats) + ans += (people + seats - 1) / seats; + return people; + } +} diff --git a/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.py b/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.py new file mode 100644 index 00000000000..5bad778b224 --- /dev/null +++ b/solutions/2477. Minimum Fuel Cost to Report to the Capital/2477.py @@ -0,0 +1,23 @@ +class Solution: + def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: + ans = 0 + tree = [[] for _ in range(len(roads) + 1)] + + for u, v in roads: + tree[u].append(v) + tree[v].append(u) + + def dfs(u: int, prev: int) -> int: + nonlocal ans + people = 1 + for v in tree[u]: + if v == prev: + continue + people += dfs(v, u) + if u > 0: + # the number of cars needed + ans += int(math.ceil(people / seats)) + return people + + dfs(0, -1) + return ans diff --git a/solutions/2478. Number of Beautiful Partitions/2478.cpp b/solutions/2478. Number of Beautiful Partitions/2478.cpp new file mode 100644 index 00000000000..3a2310d4a1f --- /dev/null +++ b/solutions/2478. Number of Beautiful Partitions/2478.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int beautifulPartitions(string s, int k, int minLength) { + if (!isPrime(s.front()) || isPrime(s.back())) + return 0; + vector> mem(s.length(), vector(k, -1)); + return beautifulPartitions(s, minLength, k - 1, minLength, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of beautiful partitions of s[i..n) with k bars (|) left. + int beautifulPartitions(const string& s, int i, int k, int minLength, + vector>& mem) { + if (i <= s.length() && k == 0) + return 1; + if (i >= s.length()) + return 0; + if (mem[i][k] != -1) + return mem[i][k]; + + // Don't split between s[i - 1] and s[i]. + int res = beautifulPartitions(s, i + 1, k, minLength, mem) % kMod; + + // Split between s[i - 1] and s[i]. + if (isPrime(s[i]) && !isPrime(s[i - 1])) + res += beautifulPartitions(s, i + minLength, k - 1, minLength, mem); + + return mem[i][k] = res % kMod; + } + + bool isPrime(char c) { + return c == '2' || c == '3' || c == '5' || c == '7'; + } +}; diff --git a/solutions/2478. Number of Beautiful Partitions/2478.java b/solutions/2478. Number of Beautiful Partitions/2478.java new file mode 100644 index 00000000000..0a054e6f1fd --- /dev/null +++ b/solutions/2478. Number of Beautiful Partitions/2478.java @@ -0,0 +1,33 @@ +class Solution { + public int beautifulPartitions(String s, int k, int minLength) { + if (!isPrime(s.charAt(0)) || isPrime(s.charAt(s.length() - 1))) + return 0; + Integer[][] mem = new Integer[s.length()][k]; + return beautifulPartitions(s, minLength, k - 1, minLength, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of beautiful partitions of s[i..n) with k bars (|) left. + private int beautifulPartitions(final String s, int i, int k, int minLength, Integer[][] mem) { + if (i <= s.length() && k == 0) + return 1; + if (i >= s.length()) + return 0; + if (mem[i][k] != null) + return mem[i][k]; + + // Don't split between s[i - 1] and s[i]. + int ans = beautifulPartitions(s, i + 1, k, minLength, mem) % kMod; + + // Split between s[i - 1] and s[i]. + if (isPrime(s.charAt(i)) && !isPrime(s.charAt(i - 1))) + ans += beautifulPartitions(s, i + minLength, k - 1, minLength, mem); + + return mem[i][k] = ans % kMod; + } + + private boolean isPrime(char c) { + return c == '2' || c == '3' || c == '5' || c == '7'; + } +} diff --git a/solutions/2478. Number of Beautiful Partitions/2478.py b/solutions/2478. Number of Beautiful Partitions/2478.py new file mode 100644 index 00000000000..8e289d797fb --- /dev/null +++ b/solutions/2478. Number of Beautiful Partitions/2478.py @@ -0,0 +1,31 @@ +class Solution: + def beautifulPartitions(self, s: str, k: int, minLength: int) -> int: + def isPrime(c: str) -> bool: + return c in '2357' + + if not isPrime(s[0]) or isPrime(s[-1]): + return 0 + + kMod = 1_000_000_007 + + @lru_cache(None) + def dp(i: int, k: int) -> int: + """ + Returns the number of beautiful partitions of s[i..n) with k bars (|) + left. + """ + if i <= len(s) and k == 0: + return 1 + if i >= len(s): + return 0 + + # Don't split between s[i - 1] and s[i]. + ans = dp(i + 1, k) % kMod + + # Split between s[i - 1] and s[i]. + if isPrime(s[i]) and not isPrime(s[i - 1]): + ans += dp(i + minLength, k - 1) + + return ans % kMod + + return dp(minLength, k - 1) diff --git a/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.cpp b/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.cpp new file mode 100644 index 00000000000..fb7d311be2b --- /dev/null +++ b/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.cpp @@ -0,0 +1,93 @@ +struct TrieNode { + vector> children; + TrieNode() : children(2) {} +}; + +class BitTrie { + public: + BitTrie(int maxBit) : maxBit(maxBit) {} + + void insert(long num) { + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + if (node->children[bit] == nullptr) + node->children[bit] = make_shared(); + node = node->children[bit]; + } + } + + long getMaxXor(long num) { + long maxXor = 0; + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + const int toggleBit = bit ^ 1; + if (node->children[toggleBit] != nullptr) { + maxXor = maxXor | 1L << i; + node = node->children[toggleBit]; + } else if (node->children[bit] != nullptr) { + node = node->children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private: + const int maxBit; + shared_ptr root = make_shared(); +}; + +class Solution { + public: + long long maxXor(int n, vector>& edges, vector& values) { + long ans = 0; + vector> tree(n); + vector treeSums(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + getTreeSum(tree, 0, -1, treeSums, values); + const long maxSubTreeSum = + *max_element(treeSums.begin() + 1, treeSums.end()); + const int maxBit = static_cast(log2(maxSubTreeSum)); + // Similar to 421. Maximum XOR of Two Numbers in an Array + dfs(tree, 0, -1, treeSums, BitTrie(maxBit), ans); + return ans; + } + + private: + // Gets the tree sum rooted at node u. + long getTreeSum(const vector>& tree, int u, int prev, + vector& treeSums, const vector& values) { + long treeSum = values[u]; + for (const int v : tree[u]) { + if (v == prev) + continue; + treeSum += getTreeSum(tree, v, u, treeSums, values); + } + treeSums[u] = treeSum; + return treeSum; + } + + void dfs(const vector>& tree, int u, int prev, + const vector& treeSums, BitTrie&& bitTrie, long& ans) { + for (const int v : tree[u]) { + if (v == prev) + continue; + // Preorder to get the ans. + ans = max(ans, bitTrie.getMaxXor(treeSums[v])); + // Recursively call on the subtree rooted at node v. + dfs(tree, v, u, treeSums, move(bitTrie), ans); + // Postorder insert the tree sum rooted at node v. + bitTrie.insert(treeSums[v]); + } + } +}; diff --git a/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.java b/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.java new file mode 100644 index 00000000000..1f6e1769e5b --- /dev/null +++ b/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.java @@ -0,0 +1,98 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[2]; +} + +class BitTrie { + public BitTrie(int maxBit) { + this.maxBit = maxBit; + } + + public void insert(long num) { + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + if (node.children[bit] == null) + node.children[bit] = new TrieNode(); + node = node.children[bit]; + } + } + + public long getMaxXor(long num) { + long maxXor = 0; + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + final int toggleBit = bit ^ 1; + if (node.children[toggleBit] != null) { + maxXor = maxXor | 1L << i; + node = node.children[toggleBit]; + } else if (node.children[bit] != null) { + node = node.children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private int maxBit; + private TrieNode root = new TrieNode(); +} + +class Solution { + public long maxXor(int n, int[][] edges, int[] values) { + List[] tree = new List[n]; + long[] treeSums = new long[n]; + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + getTreeSum(tree, 0, -1, treeSums, values); + final long maxSubTreeSum = getMaxSubTreeSum(treeSums); + final int maxBit = (int) (Math.log(maxSubTreeSum) / Math.log(2)); + // Similar to 421. Maximum XOR of Two Numbers in an Array + dfs(tree, 0, -1, treeSums, new BitTrie(maxBit)); + return ans; + } + + private long ans = 0; + + // Gets the tree sum rooted at node u. + private long getTreeSum(List[] tree, int u, int prev, long[] treeSums, int[] values) { + long treeSum = values[u]; + for (final int v : tree[u]) { + if (v == prev) + continue; + treeSum += getTreeSum(tree, v, u, treeSums, values); + } + treeSums[u] = treeSum; + return treeSum; + } + + private long getMaxSubTreeSum(long[] treeSums) { + long maxSubTreeSum = 0; + for (int i = 1; i < treeSums.length; ++i) + maxSubTreeSum = Math.max(maxSubTreeSum, treeSums[i]); + return maxSubTreeSum; + } + + private void dfs(List[] tree, int u, int prev, long[] treeSums, BitTrie bitTrie) { + for (final int v : tree[u]) { + if (v == prev) + continue; + // Preorder to get the ans. + ans = Math.max(ans, bitTrie.getMaxXor(treeSums[v])); + // Recursively call on the subtree rooted at node v. + dfs(tree, v, u, treeSums, bitTrie); + // Postorder to insert the tree sum rooted at node v. + bitTrie.insert(treeSums[v]); + } + } +} diff --git a/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.py b/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.py new file mode 100644 index 00000000000..f32c5305977 --- /dev/null +++ b/solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.py @@ -0,0 +1,71 @@ +class TrieNode: + def __init__(self): + self.children: List[Optional[TrieNode]] = [None] * 2 + + +class BitTrie: + def __init__(self, maxBit: int): + self.maxBit = maxBit + self.root = TrieNode() + + def insert(self, num: int) -> None: + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + if not node.children[bit]: + node.children[bit] = TrieNode() + node = node.children[bit] + + def getMaxXor(self, num: int) -> int: + maxXor = 0 + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + toggleBit = bit ^ 1 + if node.children[toggleBit]: + maxXor = maxXor | 1 << i + node = node.children[toggleBit] + elif node.children[bit]: + node = node.children[bit] + else: # There's nothing in the Bit Trie. + return 0 + return maxXor + + +class Solution: + def maxXor(self, n: int, edges: List[List[int]], values: List[int]) -> int: + ans = 0 + tree = [[] for _ in range(n)] + treeSums = [0] * n + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + # Gets the tree sum rooted at node u. + def getTreeSum(u: int, prev: int) -> int: + treeSum = values[u] + for v in tree[u]: + if v == prev: + continue + treeSum += getTreeSum(v, u) + treeSums[u] = treeSum + return treeSum + + def dfs(u: int, prev: int, bitTrie: BitTrie) -> None: + nonlocal ans + for v in tree[u]: + if v == prev: + continue + # Preorder to get the ans. + ans = max(ans, bitTrie.getMaxXor(treeSums[v])) + # Recursively call on the subtree rooted at node v. + dfs(v, u, bitTrie) + # Postorder to insert the tree sum rooted at node v. + bitTrie.insert(treeSums[v]) + + getTreeSum(0, -1) + maxBit = int(math.log2(max(treeSums[1:]))) + # Similar to 421. Maximum XOR of Two Numbers in an Array + dfs(0, -1, BitTrie(maxBit)) + return ans diff --git a/solutions/248. Strobogrammatic Number III/248.cpp b/solutions/248. Strobogrammatic Number III/248.cpp new file mode 100644 index 00000000000..98d4c60ce76 --- /dev/null +++ b/solutions/248. Strobogrammatic Number III/248.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int strobogrammaticInRange(string low, string high) { + int ans = 0; + + for (int n = low.length(); n <= high.length(); ++n) { + string s(n, ' '); + dfs(low, high, s, 0, n - 1, ans); + } + + return ans; + } + + private: + const vector> pairs{ + {'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}}; + + void dfs(const string& low, const string& high, string& s, int l, int r, + int& ans) { + if (l > r) { + if (s.length() == low.length() && s < low) + return; + if (s.length() == high.length() && s > high) + return; + ++ans; + return; + } + + for (const auto& [leftDigit, rightDigit] : pairs) { + if (l == r && leftDigit != rightDigit) + continue; + s[l] = leftDigit; + s[r] = rightDigit; + if (s.length() > 1 && s[0] == '0') + continue; + dfs(low, high, s, l + 1, r - 1, ans); + } + } +}; diff --git a/solutions/248. Strobogrammatic Number III/248.java b/solutions/248. Strobogrammatic Number III/248.java new file mode 100644 index 00000000000..829be3da2fb --- /dev/null +++ b/solutions/248. Strobogrammatic Number III/248.java @@ -0,0 +1,37 @@ +class Solution { + public int strobogrammaticInRange(String low, String high) { + for (int n = low.length(); n <= high.length(); ++n) { + char[] c = new char[n]; + dfs(low, high, c, 0, n - 1); + } + + return ans; + } + + private int ans = 0; + + private static final char[][] pairs = { + {'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}}; + + private void dfs(final String low, final String high, char[] c, int l, int r) { + if (l > r) { + final String s = new String(c); + if (s.length() == low.length() && s.compareTo(low) < 0) + return; + if (s.length() == high.length() && s.compareTo(high) > 0) + return; + ++ans; + return; + } + + for (char[] pair : pairs) { + if (l == r && pair[0] != pair[1]) + continue; + c[l] = pair[0]; + c[r] = pair[1]; + if (c.length > 1 && c[0] == '0') + continue; + dfs(low, high, c, l + 1, r - 1); + } + } +} diff --git a/solutions/248. Strobogrammatic Number III/248.py b/solutions/248. Strobogrammatic Number III/248.py new file mode 100644 index 00000000000..922bf59beaa --- /dev/null +++ b/solutions/248. Strobogrammatic Number III/248.py @@ -0,0 +1,28 @@ +class Solution: + def strobogrammaticInRange(self, low: str, high: str) -> int: + pairs = [['0', '0'], ['1', '1'], ['6', '9'], ['8', '8'], ['9', '6']] + ans = 0 + + def dfs(s: List[chr], l: int, r: int) -> None: + nonlocal ans + if l > r: + if len(s) == len(low) and ''.join(s) < low: + return + if len(s) == len(high) and ''.join(s) > high: + return + ans += 1 + return + + for leftDigit, rightDigit in pairs: + if l == r and leftDigit != rightDigit: + continue + s[l] = leftDigit + s[r] = rightDigit + if len(s) > 1 and s[0] == '0': + continue + dfs(s, l + 1, r - 1) + + for n in range(len(low), len(high) + 1): + dfs([' '] * n, 0, n - 1) + + return ans diff --git a/solutions/2480. Form a Chemical Bond/2480.sql b/solutions/2480. Form a Chemical Bond/2480.sql new file mode 100644 index 00000000000..953bd908a7a --- /dev/null +++ b/solutions/2480. Form a Chemical Bond/2480.sql @@ -0,0 +1,7 @@ +SELECT + A.symbol AS metal, + B.symbol AS nonmetal +FROM Elements AS A, Elements AS B +WHERE + A.type = 'Metal' + AND B.type = 'Nonmetal' diff --git a/solutions/2481. Minimum Cuts to Divide a Circle/2481.cpp b/solutions/2481. Minimum Cuts to Divide a Circle/2481.cpp new file mode 100644 index 00000000000..a6bae15218c --- /dev/null +++ b/solutions/2481. Minimum Cuts to Divide a Circle/2481.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int numberOfCuts(int n) { + if (n == 1) + return 0; + return n % 2 == 0 ? n / 2 : n; + } +}; diff --git a/solutions/2481. Minimum Cuts to Divide a Circle/2481.java b/solutions/2481. Minimum Cuts to Divide a Circle/2481.java new file mode 100644 index 00000000000..1fd52197b29 --- /dev/null +++ b/solutions/2481. Minimum Cuts to Divide a Circle/2481.java @@ -0,0 +1,7 @@ +class Solution { + public int numberOfCuts(int n) { + if (n == 1) + return 0; + return n % 2 == 0 ? n / 2 : n; + } +} diff --git a/solutions/2481. Minimum Cuts to Divide a Circle/2481.py b/solutions/2481. Minimum Cuts to Divide a Circle/2481.py new file mode 100644 index 00000000000..7414778cc37 --- /dev/null +++ b/solutions/2481. Minimum Cuts to Divide a Circle/2481.py @@ -0,0 +1,5 @@ +class Solution: + def numberOfCuts(self, n: int) -> int: + if n == 1: + return 0 + return n // 2 if n % 2 == 0 else n diff --git a/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.cpp b/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.cpp new file mode 100644 index 00000000000..9a67720b6b2 --- /dev/null +++ b/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector> onesMinusZeros(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector> ans(m, vector(n)); + vector onesRow; + vector onesCol; + + for (const vector& row : grid) + onesRow.push_back(ranges::count(row, 1)); + + for (int j = 0; j < n; ++j) { + int ones = 0; + for (int i = 0; i < m; ++i) + ones += grid[i][j]; + onesCol.push_back(ones); + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + ans[i][j] = + onesRow[i] + onesCol[j] - (n - onesRow[i]) - (m - onesCol[j]); + + return ans; + } +}; diff --git a/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.java b/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.java new file mode 100644 index 00000000000..ecadbdf207f --- /dev/null +++ b/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.java @@ -0,0 +1,25 @@ +class Solution { + public int[][] onesMinusZeros(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[][] ans = new int[m][n]; + int[] onesRow = new int[m]; + int[] onesCol = new int[n]; + + for (int i = 0; i < m; ++i) + onesRow[i] = (int) Arrays.stream(grid[i]).filter(a -> a == 1).count(); + + for (int j = 0; j < n; ++j) { + int ones = 0; + for (int i = 0; i < m; ++i) + ones += grid[i][j]; + onesCol[j] = ones; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + ans[i][j] = onesRow[i] + onesCol[j] - (n - onesRow[i]) - (m - onesCol[j]); + + return ans; + } +} diff --git a/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.py b/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.py new file mode 100644 index 00000000000..2390623f0e2 --- /dev/null +++ b/solutions/2482. Difference Between Ones and Zeros in Row and Column/2482.py @@ -0,0 +1,14 @@ +class Solution: + def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]: + m = len(grid) + n = len(grid[0]) + ans = [[0] * n for _ in range(m)] + onesRow = [row.count(1) for row in grid] + onesCol = [col.count(1) for col in zip(*grid)] + + for i in range(m): + for j in range(n): + ans[i][j] = onesRow[i] + onesCol[j] - \ + (n - onesRow[i]) - (m - onesCol[j]) + + return ans diff --git a/solutions/2483. Minimum Penalty for a Shop/2483.cpp b/solutions/2483. Minimum Penalty for a Shop/2483.cpp new file mode 100644 index 00000000000..7a73e335616 --- /dev/null +++ b/solutions/2483. Minimum Penalty for a Shop/2483.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int bestClosingTime(string customers) { + // Instead of computing the minimum penalty, we can compute the maximum + // profit. + int ans = 0; + int profit = 0; + int maxProfit = 0; + + for (int i = 0; i < customers.length(); ++i) { + profit += customers[i] == 'Y' ? 1 : -1; + if (profit > maxProfit) { + maxProfit = profit; + ans = i + 1; + } + } + + return ans; + } +}; diff --git a/solutions/2483. Minimum Penalty for a Shop/2483.java b/solutions/2483. Minimum Penalty for a Shop/2483.java new file mode 100644 index 00000000000..4a1f746db80 --- /dev/null +++ b/solutions/2483. Minimum Penalty for a Shop/2483.java @@ -0,0 +1,18 @@ +class Solution { + public int bestClosingTime(String customers) { + // Instead of computing the minimum penalty, we can compute the maximum profit. + int ans = 0; + int profit = 0; + int maxProfit = 0; + + for (int i = 0; i < customers.length(); ++i) { + profit += customers.charAt(i) == 'Y' ? 1 : -1; + if (profit > maxProfit) { + maxProfit = profit; + ans = i + 1; + } + } + + return ans; + } +} diff --git a/solutions/2483. Minimum Penalty for a Shop/2483.py b/solutions/2483. Minimum Penalty for a Shop/2483.py new file mode 100644 index 00000000000..8199bb45691 --- /dev/null +++ b/solutions/2483. Minimum Penalty for a Shop/2483.py @@ -0,0 +1,14 @@ +class Solution: + def bestClosingTime(self, customers: str) -> int: + # Instead of computing the minimum penalty, we can compute the maximum profit. + ans = 0 + profit = 0 + maxProfit = 0 + + for i, customer in enumerate(customers): + profit += 1 if customer == 'Y' else -1 + if profit > maxProfit: + maxProfit = profit + ans = i + 1 + + return ans diff --git a/solutions/2484. Count Palindromic Subsequences/2484.cpp b/solutions/2484. Count Palindromic Subsequences/2484.cpp new file mode 100644 index 00000000000..9912feee190 --- /dev/null +++ b/solutions/2484. Count Palindromic Subsequences/2484.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int countPalindromes(string s) { + constexpr int kMod = 1'000'000'007; + constexpr int kPatternSize = 5; + long ans = 0; + + for (char a = '0'; a <= '9'; ++a) + for (char b = '0'; b <= '9'; ++b) { + const vector pattern{a, b, '.', b, a}; + // dp[i] := the number of subsequences of pattern[i..n) in s, where + // pattern[2] can be any character + vector dp(kPatternSize + 1); + dp.back() = 1; + for (const char c : s) + for (int i = 0; i < kPatternSize; ++i) + if (pattern[i] == '.' || pattern[i] == c) + dp[i] += dp[i + 1]; + ans += dp[0]; + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/2484. Count Palindromic Subsequences/2484.java b/solutions/2484. Count Palindromic Subsequences/2484.java new file mode 100644 index 00000000000..348e0d18546 --- /dev/null +++ b/solutions/2484. Count Palindromic Subsequences/2484.java @@ -0,0 +1,24 @@ +class Solution { + public int countPalindromes(String s) { + final int kMod = 1_000_000_007; + final int kPatternSize = 5; + long ans = 0; + + for (char a = '0'; a <= '9'; ++a) + for (char b = '0'; b <= '9'; ++b) { + char[] pattern = {a, b, '.', b, a}; + // dp[i] := the number of subsequences of pattern[i..n) in s, where + // pattern[2] can be any character + long[] dp = new long[kPatternSize + 1]; + dp[kPatternSize] = 1; + for (final char c : s.toCharArray()) + for (int i = 0; i < kPatternSize; ++i) + if (pattern[i] == '.' || pattern[i] == c) + dp[i] += dp[i + 1]; + ans += dp[0]; + ans %= kMod; + } + + return (int) ans; + } +} diff --git a/solutions/2484. Count Palindromic Subsequences/2484.py b/solutions/2484. Count Palindromic Subsequences/2484.py new file mode 100644 index 00000000000..77992693e04 --- /dev/null +++ b/solutions/2484. Count Palindromic Subsequences/2484.py @@ -0,0 +1,19 @@ +class Solution: + def countPalindromes(self, s: str) -> int: + kMod = 1_000_000_007 + ans = 0 + + for a in range(10): + for b in range(10): + pattern = f'{a}{b}.{b}{a}' + # dp[i] := the number of subsequences of pattern[i..n) in s, where + # pattern[2] can be any character + dp = [0] * 5 + [1] + for c in s: + for i, p in enumerate(pattern): + if p == '.' or p == c: + dp[i] += dp[i + 1] + ans += dp[0] + ans %= kMod + + return ans diff --git a/solutions/2485. Find the Pivot Integer/2485.cpp b/solutions/2485. Find the Pivot Integer/2485.cpp new file mode 100644 index 00000000000..78f2178bd40 --- /dev/null +++ b/solutions/2485. Find the Pivot Integer/2485.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int pivotInteger(int n) { + // 1 + 2 + ... + x = x + ... + n + // (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2 + // x + x^2 = nx - x^2 + x + n^2 - nx + n + // 2 * x^2 = n^2 + n + // x = sqrt((n^2 + n) / 2) + const int y = (n * n + n) / 2; + const int x = sqrt(y); + return x * x == y ? x : -1; + } +}; diff --git a/solutions/2485. Find the Pivot Integer/2485.java b/solutions/2485. Find the Pivot Integer/2485.java new file mode 100644 index 00000000000..06b809de8dd --- /dev/null +++ b/solutions/2485. Find the Pivot Integer/2485.java @@ -0,0 +1,12 @@ +class Solution { + public int pivotInteger(int n) { + // 1 + 2 + ... + x = x + ... + n + // (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2 + // x + x^2 = nx - x^2 + x + n^2 - nx + n + // 2 * x^2 = n^2 + n + // x = sqrt((n^2 + n) / 2) + final int y = (n * n + n) / 2; + final int x = (int) Math.sqrt(y); + return x * x == y ? x : -1; + } +} diff --git a/solutions/2485. Find the Pivot Integer/2485.py b/solutions/2485. Find the Pivot Integer/2485.py new file mode 100644 index 00000000000..55ea69c65c3 --- /dev/null +++ b/solutions/2485. Find the Pivot Integer/2485.py @@ -0,0 +1,10 @@ +class Solution: + def pivotInteger(self, n: int) -> int: + # 1 + 2 + ... + x = x + ... + n + # (1 + x) * x // 2 = (x + n) * (n - x + 1) // 2 + # x + x^2 = nx - x^2 + x + n^2 - nx + n + # 2 * x^2 = n^2 + n + # x = sqrt((n^2 + n) // 2) + y = (n * n + n) // 2 + x = math.isqrt(y) + return x if x * x == y else -1 diff --git a/solutions/2486. Append Characters to String to Make Subsequence/2486.cpp b/solutions/2486. Append Characters to String to Make Subsequence/2486.cpp new file mode 100644 index 00000000000..cee80ec8f16 --- /dev/null +++ b/solutions/2486. Append Characters to String to Make Subsequence/2486.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int appendCharacters(string s, string t) { + int i = 0; // t's index + + for (const char c : s) + if (c == t[i]) + if (++i == t.length()) + return 0; + + return t.length() - i; + } +}; diff --git a/solutions/2486. Append Characters to String to Make Subsequence/2486.java b/solutions/2486. Append Characters to String to Make Subsequence/2486.java new file mode 100644 index 00000000000..afac39f8a30 --- /dev/null +++ b/solutions/2486. Append Characters to String to Make Subsequence/2486.java @@ -0,0 +1,12 @@ +class Solution { + public int appendCharacters(String s, String t) { + int i = 0; // t's index + + for (final char c : s.toCharArray()) + if (c == t.charAt(i)) + if (++i == t.length()) + return 0; + + return t.length() - i; + } +} diff --git a/solutions/2486. Append Characters to String to Make Subsequence/2486.py b/solutions/2486. Append Characters to String to Make Subsequence/2486.py new file mode 100644 index 00000000000..624e6771f1f --- /dev/null +++ b/solutions/2486. Append Characters to String to Make Subsequence/2486.py @@ -0,0 +1,11 @@ +class Solution: + def appendCharacters(self, s: str, t: str) -> int: + i = 0 # t's index + + for c in s: + if c == t[i]: + i += 1 + if i == len(t): + return 0 + + return len(t) - i diff --git a/solutions/2487. Remove Nodes From Linked List/2487.cpp b/solutions/2487. Remove Nodes From Linked List/2487.cpp new file mode 100644 index 00000000000..7c38f3a36a2 --- /dev/null +++ b/solutions/2487. Remove Nodes From Linked List/2487.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + ListNode* removeNodes(ListNode* head) { + if (head == nullptr) + return nullptr; + head->next = removeNodes(head->next); + return head->next != nullptr && head->val < head->next->val ? head->next + : head; + } +}; diff --git a/solutions/2487. Remove Nodes From Linked List/2487.java b/solutions/2487. Remove Nodes From Linked List/2487.java new file mode 100644 index 00000000000..c6bf2405c41 --- /dev/null +++ b/solutions/2487. Remove Nodes From Linked List/2487.java @@ -0,0 +1,8 @@ +class Solution { + public ListNode removeNodes(ListNode head) { + if (head == null) + return null; + head.next = removeNodes(head.next); + return head.next != null && head.val < head.next.val ? head.next : head; + } +} diff --git a/solutions/2487. Remove Nodes From Linked List/2487.py b/solutions/2487. Remove Nodes From Linked List/2487.py new file mode 100644 index 00000000000..921b2fbfc86 --- /dev/null +++ b/solutions/2487. Remove Nodes From Linked List/2487.py @@ -0,0 +1,6 @@ +class Solution: + def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head: + return None + head.next = self.removeNodes(head.next) + return head.next if head.next and head.val < head.next.val else head diff --git a/solutions/2488. Count Subarrays With Median K/2488.cpp b/solutions/2488. Count Subarrays With Median K/2488.cpp new file mode 100644 index 00000000000..e76b64027e0 --- /dev/null +++ b/solutions/2488. Count Subarrays With Median K/2488.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int countSubarrays(vector& nums, int k) { + const int kIndex = find(nums.begin(), nums.end(), k) - nums.begin(); + int ans = 0; + unordered_map count; + + for (int i = kIndex, balance = 0; i >= 0; --i) { + if (nums[i] < k) + --balance; + else if (nums[i] > k) + ++balance; + ++count[balance]; + } + + for (int i = kIndex, balance = 0; i < nums.size(); ++i) { + if (nums[i] < k) + --balance; + else if (nums[i] > k) + ++balance; + // The subarray that has balance == 0 or 1 having median equal to k. + // So, add count[0 - balance] and count[1 - balance] to `ans`. + ans += count[-balance] + count[1 - balance]; + } + + return ans; + } +}; diff --git a/solutions/2488. Count Subarrays With Median K/2488.java b/solutions/2488. Count Subarrays With Median K/2488.java new file mode 100644 index 00000000000..99e6aa4c389 --- /dev/null +++ b/solutions/2488. Count Subarrays With Median K/2488.java @@ -0,0 +1,34 @@ +class Solution { + public int countSubarrays(int[] nums, int k) { + final int kIndex = find(nums, k); + int ans = 0; + Map count = new HashMap<>(); + + for (int i = kIndex, balance = 0; i >= 0; --i) { + if (nums[i] < k) + --balance; + else if (nums[i] > k) + ++balance; + count.merge(balance, 1, Integer::sum); + } + + for (int i = kIndex, balance = 0; i < nums.length; ++i) { + if (nums[i] < k) + --balance; + else if (nums[i] > k) + ++balance; + // The subarray that has balance == 0 or 1 having median equal to k. + // So, add count[0 - balance] and count[1 - balance] to `ans`. + ans += count.getOrDefault(-balance, 0) + count.getOrDefault(1 - balance, 0); + } + + return ans; + } + + private int find(int[] nums, int k) { + for (int i = 0; i < nums.length; ++i) + if (nums[i] == k) + return i; + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2488. Count Subarrays With Median K/2488.py b/solutions/2488. Count Subarrays With Median K/2488.py new file mode 100644 index 00000000000..58ed3db0cbf --- /dev/null +++ b/solutions/2488. Count Subarrays With Median K/2488.py @@ -0,0 +1,25 @@ +class Solution: + def countSubarrays(self, nums: List[int], k: int) -> int: + kIndex = nums.index(k) + ans = 0 + count = collections.Counter() + + balance = 0 + for i in range(kIndex, -1, -1): + if nums[i] < k: + balance -= 1 + elif nums[i] > k: + balance += 1 + count[balance] += 1 + + balance = 0 + for i in range(kIndex, len(nums)): + if nums[i] < k: + balance -= 1 + elif nums[i] > k: + balance += 1 + # The subarray that has balance == 0 or 1 having median equal to k. + # So, add count[0 - balance] and count[1 - balance] to `ans`. + ans += count[-balance] + count[1 - balance] + + return ans diff --git a/solutions/2489. Number of Substrings With Fixed Ratio/2489.cpp b/solutions/2489. Number of Substrings With Fixed Ratio/2489.cpp new file mode 100644 index 00000000000..bb9517242c9 --- /dev/null +++ b/solutions/2489. Number of Substrings With Fixed Ratio/2489.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + long long fixedRatio(string s, int num1, int num2) { + // Let x := the number of 0s and y := the number of 1s in the subarray. + // We want x : y = num1 : num2, so our goal is to find number of subarrays + // with x * num2 - y * num1 = 0. To achieve this, we can use a prefix count + // map to record the count of the running x * num2 - y * num1. If the + // running x * num2 - y * num1 = prefix, then add count[prefix] to the + // `ans`. + long ans = 0; + long prefix = 0; + unordered_map prefixCount{{0, 1}}; + + for (const char c : s) { + if (c == '0') + prefix += num2; + else // c == '1' + prefix -= num1; + ans += prefixCount[prefix]; + ++prefixCount[prefix]; + } + + return ans; + } +}; diff --git a/solutions/2489. Number of Substrings With Fixed Ratio/2489.java b/solutions/2489. Number of Substrings With Fixed Ratio/2489.java new file mode 100644 index 00000000000..04148026453 --- /dev/null +++ b/solutions/2489. Number of Substrings With Fixed Ratio/2489.java @@ -0,0 +1,25 @@ +class Solution { + public long fixedRatio(String s, int num1, int num2) { + // Let x := the number of 0s and y := the number of 1s in the subarray. + // We want x : y = num1 : num2, so our goal is to find number of subarrays + // with x * num2 - y * num1 = 0. To achieve this, we can use a prefix count + // map to record the count of the running x * num2 - y * num1. If the + // running x * num2 - y * num1 = prefix, then add count[prefix] to the + // `ans`. + long ans = 0; + long prefix = 0; + Map prefixCount = new HashMap<>(); + prefixCount.put(0L, 1); + + for (final char c : s.toCharArray()) { + if (c == '0') + prefix += num2; + else // c == '1' + prefix -= num1; + ans += prefixCount.getOrDefault(prefix, 0); + prefixCount.merge(prefix, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/2489. Number of Substrings With Fixed Ratio/2489.py b/solutions/2489. Number of Substrings With Fixed Ratio/2489.py new file mode 100644 index 00000000000..ec425b8bd95 --- /dev/null +++ b/solutions/2489. Number of Substrings With Fixed Ratio/2489.py @@ -0,0 +1,21 @@ +class Solution: + def fixedRatio(self, s: str, num1: int, num2: int) -> int: + # Let x := the number of 0s and y := the number of 1s in the subarray. + # We want x : y = num1 : num2, so our goal is to find number of subarrays + # with x * num2 - y * num1 = 0. To achieve this, we can use a prefix count + # map to record the count of the running x * num2 - y * num1. If the + # running x * num2 - y * num1 = prefix, then add count[prefix] to the + # `ans`. + ans = 0 + prefix = 0 + prefixCount = collections.Counter({0: 1}) + + for c in s: + if c == '0': + prefix += num2 + else: # c == '1' + prefix -= num1 + ans += prefixCount[prefix] + prefixCount[prefix] += 1 + + return ans diff --git a/solutions/249. Group Shifted Strings/249.cpp b/solutions/249. Group Shifted Strings/249.cpp new file mode 100644 index 00000000000..7432d30efaf --- /dev/null +++ b/solutions/249. Group Shifted Strings/249.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector> groupStrings(vector& strings) { + vector> ans; + unordered_map> keyToStrings; + + for (const string& s : strings) + keyToStrings[getKey(s)].push_back(s); + + for (const auto& [_, strings] : keyToStrings) + ans.push_back(strings); + + return ans; + } + + private: + // Returns the key of 's' by pairwise calculation of differences. + // e.g. getKey("abc") -> "1,1" because diff(a, b) = 1 and diff(b, c) = 1. + string getKey(const string& s) { + string key; + + for (int i = 1; i < s.length(); ++i) { + const int diff = (s[i] - s[i - 1] + 26) % 26; + key += to_string(diff) + ","; + } + + return key; + } +}; diff --git a/solutions/249. Group Shifted Strings/249.java b/solutions/249. Group Shifted Strings/249.java new file mode 100644 index 00000000000..8f95722f9b4 --- /dev/null +++ b/solutions/249. Group Shifted Strings/249.java @@ -0,0 +1,23 @@ +class Solution { + public List> groupStrings(String[] strings) { + Map> keyToStrings = new HashMap<>(); + + for (final String s : strings) + keyToStrings.computeIfAbsent(getKey(s), k -> new ArrayList<>()).add(s); + + return new ArrayList<>(keyToStrings.values()); + } + + // Returns the key of 's' by pairwise calculation of differences. + // e.g. getKey("abc") -> "1,1" because diff(a, b) = 1 and diff(b, c) = 1. + private String getKey(final String s) { + StringBuilder sb = new StringBuilder(); + + for (int i = 1; i < s.length(); ++i) { + final int diff = (s.charAt(i) - s.charAt(i - 1) + 26) % 26; + sb.append(diff).append(","); + } + + return sb.toString(); + } +} diff --git a/solutions/249. Group Shifted Strings/249.py b/solutions/249. Group Shifted Strings/249.py new file mode 100644 index 00000000000..a8a9e7a12b5 --- /dev/null +++ b/solutions/249. Group Shifted Strings/249.py @@ -0,0 +1,21 @@ +class Solution: + def groupStrings(self, strings: List[str]) -> List[List[str]]: + keyToStrings = collections.defaultdict(list) + + def getKey(s: str) -> str: + """ + Returns the key of 's' by pairwise calculation of differences. + e.g. getKey("abc") -> "1,1" because diff(a, b) = 1 and diff(b, c) = 1. + """ + diffs = [] + + for i in range(1, len(s)): + diff = (ord(s[i]) - ord(s[i - 1]) + 26) % 26 + diffs.append(str(diff)) + + return ','.join(diffs) + + for s in strings: + keyToStrings[getKey(s)].append(s) + + return keyToStrings.values() diff --git a/solutions/2490. Circular Sentence/2490.cpp b/solutions/2490. Circular Sentence/2490.cpp new file mode 100644 index 00000000000..2b77af328bf --- /dev/null +++ b/solutions/2490. Circular Sentence/2490.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + bool isCircularSentence(string sentence) { + for (int i = 0; i < sentence.length(); ++i) + if (sentence[i] == ' ' && sentence[i - 1] != sentence[i + 1]) + return false; + return sentence.front() == sentence.back(); + } +}; diff --git a/solutions/2490. Circular Sentence/2490.java b/solutions/2490. Circular Sentence/2490.java new file mode 100644 index 00000000000..89c0e623a0c --- /dev/null +++ b/solutions/2490. Circular Sentence/2490.java @@ -0,0 +1,8 @@ +class Solution { + public boolean isCircularSentence(String sentence) { + for (int i = 0; i < sentence.length(); ++i) + if (sentence.charAt(i) == ' ' && sentence.charAt(i - 1) != sentence.charAt(i + 1)) + return false; + return sentence.charAt(0) == sentence.charAt(sentence.length() - 1); + } +} diff --git a/solutions/2490. Circular Sentence/2490.py b/solutions/2490. Circular Sentence/2490.py new file mode 100644 index 00000000000..b0e4ced7cfc --- /dev/null +++ b/solutions/2490. Circular Sentence/2490.py @@ -0,0 +1,6 @@ +class Solution: + def isCircularSentence(self, sentence: str) -> bool: + for i, c in enumerate(sentence): + if c == ' ' and sentence[i - 1] != sentence[i + 1]: + return False + return sentence[0] == sentence[-1] diff --git a/solutions/2491. Divide Players Into Teams of Equal Skill/2491.cpp b/solutions/2491. Divide Players Into Teams of Equal Skill/2491.cpp new file mode 100644 index 00000000000..dabc1a35b5f --- /dev/null +++ b/solutions/2491. Divide Players Into Teams of Equal Skill/2491.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + long long dividePlayers(vector& skill) { + const int n = skill.size(); + const int teamSkill = accumulate(skill.begin(), skill.end(), 0) / (n / 2); + long ans = 0; + unordered_map count; + + for (const int s : skill) + ++count[s]; + + for (const auto& [s, freq] : count) { + const int requiredSkill = teamSkill - s; + if (const auto it = count.find(requiredSkill); + it == count.cend() || it->second != freq) + return -1; + ans += static_cast(s) * requiredSkill * freq; + } + + return ans / 2; + } +}; diff --git a/solutions/2491. Divide Players Into Teams of Equal Skill/2491.java b/solutions/2491. Divide Players Into Teams of Equal Skill/2491.java new file mode 100644 index 00000000000..971ac78d4c6 --- /dev/null +++ b/solutions/2491. Divide Players Into Teams of Equal Skill/2491.java @@ -0,0 +1,22 @@ +class Solution { + public long dividePlayers(int[] skill) { + final int n = skill.length; + final int teamSkill = Arrays.stream(skill).sum() / (n / 2); + long ans = 0; + Map count = new HashMap<>(); + + for (final int s : skill) + count.merge(s, 1, Integer::sum); + + for (Map.Entry entry : count.entrySet()) { + final int s = entry.getKey(); + final int freq = entry.getValue(); + final int requiredSkill = teamSkill - s; + if (count.getOrDefault(requiredSkill, 0) != freq) + return -1; + ans += (long) s * requiredSkill * freq; + } + + return ans / 2; + } +} diff --git a/solutions/2491. Divide Players Into Teams of Equal Skill/2491.py b/solutions/2491. Divide Players Into Teams of Equal Skill/2491.py new file mode 100644 index 00000000000..936db871e06 --- /dev/null +++ b/solutions/2491. Divide Players Into Teams of Equal Skill/2491.py @@ -0,0 +1,14 @@ +class Solution: + def dividePlayers(self, skill: List[int]) -> int: + n = len(skill) + teamSkill = sum(skill) // (n // 2) + ans = 0 + count = collections.Counter(skill) + + for s, freq in count.items(): + requiredSkill = teamSkill - s + if count[requiredSkill] != freq: + return -1 + ans += s * requiredSkill * freq + + return ans // 2 diff --git a/solutions/2492. Minimum Score of a Path Between Two Cities/2492.cpp b/solutions/2492. Minimum Score of a Path Between Two Cities/2492.cpp new file mode 100644 index 00000000000..b4b52b4cc82 --- /dev/null +++ b/solutions/2492. Minimum Score of a Path Between Two Cities/2492.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minScore(int n, vector>& roads) { + int ans = INT_MAX; + vector>> graph(n); // graph[u] := [(v, distance)] + queue q{{0}}; + vector seen(n); + seen[0] = true; + + for (const vector& r : roads) { + const int u = r[0] - 1; + const int v = r[1] - 1; + const int distance = r[2]; + graph[u].emplace_back(v, distance); + graph[v].emplace_back(u, distance); + } + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const auto& [v, d] : graph[u]) { + ans = min(ans, d); + if (seen[v]) + continue; + q.push(v); + seen[v] = true; + } + } + + return ans; + } +}; diff --git a/solutions/2492. Minimum Score of a Path Between Two Cities/2492.java b/solutions/2492. Minimum Score of a Path Between Two Cities/2492.java new file mode 100644 index 00000000000..32d1c2b3625 --- /dev/null +++ b/solutions/2492. Minimum Score of a Path Between Two Cities/2492.java @@ -0,0 +1,35 @@ +class Solution { + public int minScore(int n, int[][] roads) { + int ans = Integer.MAX_VALUE; + List>[] graph = new List[n]; // graph[u] := [(v, distance)] + Queue q = new ArrayDeque<>(Arrays.asList(0)); + boolean[] seen = new boolean[n]; + seen[0] = true; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (final int[] r : roads) { + final int u = r[0] - 1; + final int v = r[1] - 1; + final int distance = r[2]; + graph[u].add(new Pair<>(v, distance)); + graph[v].add(new Pair<>(u, distance)); + } + + while (!q.isEmpty()) { + final int u = q.poll(); + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int d = pair.getValue(); + ans = Math.min(ans, d); + if (seen[v]) + continue; + q.offer(v); + seen[v] = true; + } + } + + return ans; + } +} diff --git a/solutions/2492. Minimum Score of a Path Between Two Cities/2492.py b/solutions/2492. Minimum Score of a Path Between Two Cities/2492.py new file mode 100644 index 00000000000..8f343d66485 --- /dev/null +++ b/solutions/2492. Minimum Score of a Path Between Two Cities/2492.py @@ -0,0 +1,21 @@ +class Solution: + def minScore(self, n: int, roads: List[List[int]]) -> int: + ans = math.inf + graph = [[] for _ in range(n + 1)] # graph[u] := [(v, distance)] + q = collections.deque([1]) + seen = {1} + + for u, v, distance in roads: + graph[u].append((v, distance)) + graph[v].append((u, distance)) + + while q: + u = q.popleft() + for v, d in graph[u]: + ans = min(ans, d) + if v in seen: + continue + q.append(v) + seen.add(v) + + return ans diff --git a/solutions/2493. Divide Nodes Into the Maximum Number of Groups/2493.cpp b/solutions/2493. Divide Nodes Into the Maximum Number of Groups/2493.cpp new file mode 100644 index 00000000000..8ce961afcee --- /dev/null +++ b/solutions/2493. Divide Nodes Into the Maximum Number of Groups/2493.cpp @@ -0,0 +1,87 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + int magnificentSets(int n, vector>& edges) { + vector> graph(n); + UnionFind uf(n); + unordered_map rootToGroupSize; + + for (const vector& edge : edges) { + const int u = edge[0] - 1; + const int v = edge[1] - 1; + graph[u].push_back(v); + graph[v].push_back(u); + uf.unionByRank(u, v); + } + + for (int i = 0; i < n; ++i) { + const int newGroupSize = bfs(graph, i); + if (newGroupSize == -1) + return -1; + const int root = uf.find(i); + auto& groupSize = rootToGroupSize[root]; + groupSize = max(groupSize, newGroupSize); + } + + int ans = 0; + for (const auto& [_, groupSize] : rootToGroupSize) + ans += groupSize; + + return ans; + } + + private: + int bfs(const vector>& graph, int u) { + int step = 0; + queue q{{u}}; + unordered_map nodeToStep{{u, 1}}; + + while (!q.empty()) { + ++step; + for (int sz = q.size(); sz > 0; --sz) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) { + if (!nodeToStep.contains(v)) { + q.push(v); + nodeToStep[v] = step + 1; + } else if (nodeToStep[v] == step) { + // There is an odd number of edges in the cycle. + return -1; + } + } + } + } + + return step; + } +}; diff --git a/solutions/2494. Merge Overlapping Events in the Same Hall/2494.sql b/solutions/2494. Merge Overlapping Events in the Same Hall/2494.sql new file mode 100644 index 00000000000..52a5196edbf --- /dev/null +++ b/solutions/2494. Merge Overlapping Events in the Same Hall/2494.sql @@ -0,0 +1,33 @@ +WITH + HallEventsWithIsNewEvent AS ( + SELECT + hall_id, + start_day, + end_day, + IFNULL( + start_day > MAX(end_day) OVER( + PARTITION BY hall_id + ORDER BY start_day, + end_day DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING + ), + 1 + ) AS is_new_event + FROM HallEvents + ), + HallEventsWithGroupId AS ( + SELECT + hall_id, + start_day, + end_day, + SUM(is_new_event) OVER( + PARTITION BY hall_id + ORDER BY start_day, end_day DESC + ) AS group_id + FROM HallEventsWithIsNewEvent + ) +SELECT + hall_id, + MIN(start_day) AS start_day, + MAX(end_day) AS end_day +FROM HallEventsWithGroupId +GROUP BY hall_id, group_id; diff --git a/solutions/2495. Number of Subarrays Having Even Product/2495.cpp b/solutions/2495. Number of Subarrays Having Even Product/2495.cpp new file mode 100644 index 00000000000..2fe92a7fefb --- /dev/null +++ b/solutions/2495. Number of Subarrays Having Even Product/2495.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + long long evenProduct(vector& nums) { + long ans = 0; + int numsBeforeEven = 0; // inclusively + + // e.g. nums = [1, 0, 1, 1, 0]. + // After meeting the first 0, set `numsBeforeEven` to 2. So, the number + // between index 1 to index 3 (the one before next 0) will contribute 2 to + // `ans`. + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] % 2 == 0) + numsBeforeEven = i + 1; + ans += numsBeforeEven; + } + + return ans; + } +}; diff --git a/solutions/2495. Number of Subarrays Having Even Product/2495.java b/solutions/2495. Number of Subarrays Having Even Product/2495.java new file mode 100644 index 00000000000..3111dd31468 --- /dev/null +++ b/solutions/2495. Number of Subarrays Having Even Product/2495.java @@ -0,0 +1,18 @@ +class Solution { + public long evenProduct(int[] nums) { + long ans = 0; + int numsBeforeEven = 0; // inclusively + + // e.g. nums = [1, 0, 1, 1, 0]. + // After meeting the first 0, set `numsBeforeEven` to 2. So, the number + // between index 1 to index 3 (the one before next 0) will contribute 2 to + // `ans`. + for (int i = 0; i < nums.length; ++i) { + if (nums[i] % 2 == 0) + numsBeforeEven = i + 1; + ans += numsBeforeEven; + } + + return ans; + } +} diff --git a/solutions/2495. Number of Subarrays Having Even Product/2495.py b/solutions/2495. Number of Subarrays Having Even Product/2495.py new file mode 100644 index 00000000000..52c04b2c146 --- /dev/null +++ b/solutions/2495. Number of Subarrays Having Even Product/2495.py @@ -0,0 +1,15 @@ +class Solution: + def evenProduct(self, nums: List[int]) -> int: + ans = 0 + numsBeforeEven = 0 # inclusively + + # e.g. nums = [1, 0, 1, 1, 0]. + # After meeting the first 0, set `numsBeforeEven` to 2. So, the number + # between index 1 to index 3 (the one before next 0) will contribute 2 to + # `ans`. + for i, num in enumerate(nums): + if num % 2 == 0: + numsBeforeEven = i + 1 + ans += numsBeforeEven + + return ans diff --git a/solutions/2496. Maximum Value of a String in an Array/2496.cpp b/solutions/2496. Maximum Value of a String in an Array/2496.cpp new file mode 100644 index 00000000000..2b3ccc07770 --- /dev/null +++ b/solutions/2496. Maximum Value of a String in an Array/2496.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int maximumValue(vector& strs) { + int ans = 0; + for (const string& s : strs) + ans = max(ans, ranges::any_of(s, [](char c) { return isalpha(c); }) + ? static_cast(s.length()) + : stoi(s)); + return ans; + } +}; diff --git a/solutions/2496. Maximum Value of a String in an Array/2496.java b/solutions/2496. Maximum Value of a String in an Array/2496.java new file mode 100644 index 00000000000..6b4030c64ee --- /dev/null +++ b/solutions/2496. Maximum Value of a String in an Array/2496.java @@ -0,0 +1,9 @@ +class Solution { + public int maximumValue(String[] strs) { + int ans = 0; + for (final String s : strs) + ans = Math.max(ans, s.chars().anyMatch(c -> Character.isAlphabetic(c)) ? s.length() + : Integer.valueOf(s)); + return ans; + } +} diff --git a/solutions/2496. Maximum Value of a String in an Array/2496.py b/solutions/2496. Maximum Value of a String in an Array/2496.py new file mode 100644 index 00000000000..7193c8e2c44 --- /dev/null +++ b/solutions/2496. Maximum Value of a String in an Array/2496.py @@ -0,0 +1,4 @@ +class Solution: + def maximumValue(self, strs: List[str]) -> int: + return max(len(s) if any(c.isalpha() for c in s) else int(s) + for s in strs) diff --git a/solutions/2497. Maximum Star Sum of a Graph/2497.cpp b/solutions/2497. Maximum Star Sum of a Graph/2497.cpp new file mode 100644 index 00000000000..e9bd967c39c --- /dev/null +++ b/solutions/2497. Maximum Star Sum of a Graph/2497.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int maxStarSum(vector& vals, vector>& edges, int k) { + const int n = vals.size(); + int ans = INT_MIN; + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].emplace_back(v, vals[v]); + graph[v].emplace_back(u, vals[u]); + } + + for (int i = 0; i < n; ++i) { + priority_queue maxHeap; + for (const auto& [_, val] : graph[i]) + if (val > 0) + maxHeap.push(val); + int starSum = vals[i]; + for (int j = 0; j < k && !maxHeap.empty(); ++j) + starSum += maxHeap.top(), maxHeap.pop(); + ans = max(ans, starSum); + } + + return ans; + } +}; diff --git a/solutions/2497. Maximum Star Sum of a Graph/2497.java b/solutions/2497. Maximum Star Sum of a Graph/2497.java new file mode 100644 index 00000000000..6da23be315b --- /dev/null +++ b/solutions/2497. Maximum Star Sum of a Graph/2497.java @@ -0,0 +1,32 @@ +class Solution { + public int maxStarSum(int[] vals, int[][] edges, int k) { + final int n = vals.length; + int ans = Integer.MIN_VALUE; + List>[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(new Pair<>(v, vals[v])); + graph[v].add(new Pair<>(u, vals[u])); + } + + for (int i = 0; i < n; ++i) { + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + for (Pair pair : graph[i]) { + final int val = pair.getValue(); + if (val > 0) + maxHeap.offer(val); + } + int starSum = vals[i]; + for (int j = 0; j < k && !maxHeap.isEmpty(); ++j) + starSum += maxHeap.poll(); + ans = Math.max(ans, starSum); + } + + return ans; + } +} diff --git a/solutions/2497. Maximum Star Sum of a Graph/2497.py b/solutions/2497. Maximum Star Sum of a Graph/2497.py new file mode 100644 index 00000000000..de7141de7a5 --- /dev/null +++ b/solutions/2497. Maximum Star Sum of a Graph/2497.py @@ -0,0 +1,22 @@ +class Solution: + def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int: + n = len(vals) + ans = -math.inf + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append((v, vals[v])) + graph[v].append((u, vals[u])) + + for i, starSum in enumerate(vals): + maxHeap = [] + for _, val in graph[i]: + if val > 0: + heapq.heappush(maxHeap, -val) + j = 0 + while j < k and maxHeap: + starSum -= heapq.heappop(maxHeap) + j += 1 + ans = max(ans, starSum) + + return ans diff --git a/solutions/2498. Frog Jump II/2498.cpp b/solutions/2498. Frog Jump II/2498.cpp new file mode 100644 index 00000000000..7e63c50071f --- /dev/null +++ b/solutions/2498. Frog Jump II/2498.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int maxJump(vector& stones) { + // Let's denote the forwarding path as F and the backwarding path as B. + // "F1 B2 B1 F2" is no better than "F1 B2 F2 B1" since the distance between + // F1 and F2 increase, resulting a larger `ans`. + int ans = stones[1] - stones[0]; // If there're only two stones. + for (int i = 2; i < stones.size(); ++i) + ans = max(ans, stones[i] - stones[i - 2]); + return ans; + } +}; diff --git a/solutions/2498. Frog Jump II/2498.java b/solutions/2498. Frog Jump II/2498.java new file mode 100644 index 00000000000..679f5c7c54c --- /dev/null +++ b/solutions/2498. Frog Jump II/2498.java @@ -0,0 +1,11 @@ +class Solution { + public int maxJump(int[] stones) { + // Let's denote the forwarding path as F and the backwarding path as B. + // "F1 B2 B1 F2" is no better than "F1 B2 F2 B1" since the distance between + // F1 and F2 increase, resulting a larger `ans`. + int ans = stones[1] - stones[0]; // If there're only two stones. + for (int i = 2; i < stones.length; ++i) + ans = Math.max(ans, stones[i] - stones[i - 2]); + return ans; + } +} diff --git a/solutions/2498. Frog Jump II/2498.py b/solutions/2498. Frog Jump II/2498.py new file mode 100644 index 00000000000..bb0e90988f5 --- /dev/null +++ b/solutions/2498. Frog Jump II/2498.py @@ -0,0 +1,9 @@ +class Solution: + def maxJump(self, stones: List[int]) -> int: + # Let's denote the forwarding path as F and the backwarding path as B. + # 'F1 B2 B1 F2' is no better than 'F1 B2 F2 B1' since the distance between + # F1 and F2 increase, resulting a larger `ans`. + if len(stones) == 2: + return stones[1] - stones[0] + return max(stones[i] - stones[i - 2] + for i in range(2, len(stones))) diff --git a/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.cpp b/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.cpp new file mode 100644 index 00000000000..7f6008cb432 --- /dev/null +++ b/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + long long minimumTotalCost(vector& nums1, vector& nums2) { + const int n = nums1.size(); + long ans = 0; + int maxFreq = 0; + int maxFreqNum = 0; + int shouldBeSwapped = 0; + vector conflictedNumCount(n + 1); + + // Collect the indices i s.t. nums1[i] == nums2[i] and record their + // `maxFreq` and `maxFreqNum`. + for (int i = 0; i < n; ++i) + if (nums1[i] == nums2[i]) { + const int conflictedNum = nums1[i]; + if (++conflictedNumCount[conflictedNum] > maxFreq) { + maxFreq = conflictedNumCount[conflictedNum]; + maxFreqNum = conflictedNum; + } + ++shouldBeSwapped; + ans += i; + } + + // Collect the indices with nums1[i] != nums2[i] that contribute less cost. + // This can be greedily achieved by iterating from 0 to n - 1. + for (int i = 0; i < n; ++i) { + // Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be + // successfully distributed, so no need to collectextra spaces. + if (maxFreq * 2 <= shouldBeSwapped) + break; + if (nums1[i] == nums2[i]) + continue; + // The numbers == `maxFreqNum` worsen the result since they increase the + // `maxFreq`. + if (nums1[i] == maxFreqNum || nums2[i] == maxFreqNum) + continue; + ++shouldBeSwapped; + ans += i; + } + + return maxFreq * 2 > shouldBeSwapped ? -1 : ans; + } +}; diff --git a/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.java b/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.java new file mode 100644 index 00000000000..4e9eb107224 --- /dev/null +++ b/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.java @@ -0,0 +1,42 @@ +class Solution { + public long minimumTotalCost(int[] nums1, int[] nums2) { + final int n = nums1.length; + long ans = 0; + int maxFreq = 0; + int maxFreqNum = 0; + int shouldBeSwapped = 0; + int[] conflictedNumCount = new int[n + 1]; + + // Collect the indices i s.t. nums1[i] == nums2[i] and record their `maxFreq` + // and `maxFreqNum`. + for (int i = 0; i < n; ++i) + if (nums1[i] == nums2[i]) { + final int conflictedNum = nums1[i]; + if (++conflictedNumCount[conflictedNum] > maxFreq) { + maxFreq = conflictedNumCount[conflictedNum]; + maxFreqNum = conflictedNum; + } + ++shouldBeSwapped; + ans += i; + } + + // Collect the indices with nums1[i] != nums2[i] that contribute less cost. + // This can be greedily achieved by iterating from 0 to n - 1. + for (int i = 0; i < n; ++i) { + // Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be + // successfully distributed, so no need to collectextra spaces. + if (maxFreq * 2 <= shouldBeSwapped) + break; + if (nums1[i] == nums2[i]) + continue; + // The numbers == `maxFreqNum` worsen the result since they increase the + // `maxFreq`. + if (nums1[i] == maxFreqNum || nums2[i] == maxFreqNum) + continue; + ++shouldBeSwapped; + ans += i; + } + + return maxFreq * 2 > shouldBeSwapped ? -1 : ans; + } +} diff --git a/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.py b/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.py new file mode 100644 index 00000000000..0d883b99b3f --- /dev/null +++ b/solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.py @@ -0,0 +1,38 @@ +class Solution: + def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums1) + ans = 0 + maxFreq = 0 + maxFreqNum = 0 + shouldBeSwapped = 0 + conflictedNumCount = [0] * (n + 1) + + # Collect the indices i s.t. num1 == num2 and record their `maxFreq` + # and `maxFreqNum`. + for i, (num1, num2) in enumerate(zip(nums1, nums2)): + if num1 == num2: + conflictedNum = num1 + conflictedNumCount[conflictedNum] += 1 + if conflictedNumCount[conflictedNum] > maxFreq: + maxFreq = conflictedNumCount[conflictedNum] + maxFreqNum = conflictedNum + shouldBeSwapped += 1 + ans += i + + # Collect the indices with num1 != num2 that contribute less cost. + # This can be greedily achieved by iterating from 0 to n - 1. + for i, (num1, num2) in enumerate(zip(nums1, nums2)): + # Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be + # successfully distributed, so no need to collectextra spaces. + if maxFreq * 2 <= shouldBeSwapped: + break + if num1 == num2: + continue + # The numbers == `maxFreqNum` worsen the result since they increase the + # `maxFreq`. + if num1 == maxFreqNum or num2 == maxFreqNum: + continue + shouldBeSwapped += 1 + ans += i + + return -1 if maxFreq * 2 > shouldBeSwapped else ans diff --git a/solutions/25. Reverse Nodes in k-Group/25-2.cpp b/solutions/25. Reverse Nodes in k-Group/25-2.cpp new file mode 100644 index 00000000000..4a982f6c6b7 --- /dev/null +++ b/solutions/25. Reverse Nodes in k-Group/25-2.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + ListNode* reverseKGroup(ListNode* head, int k) { + if (!head || k == 1) + return head; + + const int length = getLength(head); + ListNode dummy(0, head); + ListNode* prev = &dummy; + ListNode* curr = head; + + for (int i = 0; i < length / k; ++i) { + for (int j = 0; j < k - 1; ++j) { + ListNode* next = curr->next; + curr->next = next->next; + next->next = prev->next; + prev->next = next; + } + prev = curr; + curr = curr->next; + } + + return dummy.next; + } + + private: + int getLength(ListNode* head) { + int length = 0; + for (ListNode* curr = head; curr; curr = curr->next) + ++length; + return length; + } +}; diff --git a/solutions/25. Reverse Nodes in k-Group/25-2.java b/solutions/25. Reverse Nodes in k-Group/25-2.java new file mode 100644 index 00000000000..8ba27da5bcc --- /dev/null +++ b/solutions/25. Reverse Nodes in k-Group/25-2.java @@ -0,0 +1,31 @@ +class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + if (head == null || k == 1) + return head; + + final int length = getLength(head); + ListNode dummy = new ListNode(0, head); + ListNode prev = dummy; + ListNode curr = head; + + for (int i = 0; i < length / k; ++i) { + for (int j = 0; j < k - 1; ++j) { + ListNode next = curr.next; + curr.next = next.next; + next.next = prev.next; + prev.next = next; + } + prev = curr; + curr = curr.next; + } + + return dummy.next; + } + + private int getLength(ListNode head) { + int length = 0; + for (ListNode curr = head; curr != null; curr = curr.next) + ++length; + return length; + } +} diff --git a/solutions/25. Reverse Nodes in k-Group/25-2.py b/solutions/25. Reverse Nodes in k-Group/25-2.py new file mode 100644 index 00000000000..32d3a907f21 --- /dev/null +++ b/solutions/25. Reverse Nodes in k-Group/25-2.py @@ -0,0 +1,27 @@ +class Solution: + def reverseKGroup(self, head: ListNode, k: int) -> ListNode: + if not head or k == 1: + return head + + def getLength(head: ListNode) -> int: + length = 0 + while head: + length += 1 + head = head.next + return length + + length = getLength(head) + dummy = ListNode(0, head) + prev = dummy + curr = head + + for _ in range(length // k): + for _ in range(k - 1): + next = curr.next + curr.next = next.next + next.next = prev.next + prev.next = next + prev = curr + curr = curr.next + + return dummy.next diff --git a/solutions/25. Reverse Nodes in k-Group/25.cpp b/solutions/25. Reverse Nodes in k-Group/25.cpp new file mode 100644 index 00000000000..74d94558412 --- /dev/null +++ b/solutions/25. Reverse Nodes in k-Group/25.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + ListNode* reverseKGroup(ListNode* head, int k) { + if (head == nullptr) + return nullptr; + + ListNode* tail = head; + + for (int i = 0; i < k; ++i) { + // There are less than k nodes in the list, do nothing. + if (tail == nullptr) + return head; + tail = tail->next; + } + + ListNode* newHead = reverse(head, tail); + head->next = reverseKGroup(tail, k); + return newHead; + } + + private: + // Reverses [head, tail). + ListNode* reverse(ListNode* head, ListNode* tail) { + ListNode* prev = nullptr; + ListNode* curr = head; + while (curr != tail) { + ListNode* next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + return prev; + } +}; diff --git a/solutions/25. Reverse Nodes in k-Group/25.java b/solutions/25. Reverse Nodes in k-Group/25.java new file mode 100644 index 00000000000..c4608abfb05 --- /dev/null +++ b/solutions/25. Reverse Nodes in k-Group/25.java @@ -0,0 +1,32 @@ +class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + if (head == null) + return null; + + ListNode tail = head; + + for (int i = 0; i < k; ++i) { + // There are less than k nodes in the list, do nothing. + if (tail == null) + return head; + tail = tail.next; + } + + ListNode newHead = reverse(head, tail); + head.next = reverseKGroup(tail, k); + return newHead; + } + + // Reverses [head, tail). + private ListNode reverse(ListNode head, ListNode tail) { + ListNode prev = null; + ListNode curr = head; + while (curr != tail) { + ListNode next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + } + return prev; + } +} diff --git a/solutions/25. Reverse Nodes in k-Group/25.py b/solutions/25. Reverse Nodes in k-Group/25.py new file mode 100644 index 00000000000..ea3b4c5e8ae --- /dev/null +++ b/solutions/25. Reverse Nodes in k-Group/25.py @@ -0,0 +1,27 @@ +class Solution: + def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: + if not head: + return None + + tail = head + + for _ in range(k): + # There are less than k nodes in the list, do nothing. + if not tail: + return head + tail = tail.next + + newHead = self._reverse(head, tail) + head.next = self.reverseKGroup(tail, k) + return newHead + + def _reverse(self, head: Optional[ListNode], tail: Optional[ListNode]) -> Optional[ListNode]: + """Reverses [head, tail).""" + prev = None + curr = head + while curr != tail: + next = curr.next + curr.next = prev + prev = curr + curr = next + return prev diff --git a/solutions/250. Count Univalue Subtrees/250.cpp b/solutions/250. Count Univalue Subtrees/250.cpp new file mode 100644 index 00000000000..3b4b9b0ba8d --- /dev/null +++ b/solutions/250. Count Univalue Subtrees/250.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int countUnivalSubtrees(TreeNode* root) { + int ans = 0; + isUnival(root, INT_MAX, ans); + return ans; + } + + private: + bool isUnival(TreeNode* root, int val, int& ans) { + if (root == nullptr) + return true; + + if (isUnival(root->left, root->val, ans) & + isUnival(root->right, root->val, ans)) { + ++ans; + return root->val == val; + } + + return false; + } +}; diff --git a/solutions/250. Count Univalue Subtrees/250.java b/solutions/250. Count Univalue Subtrees/250.java new file mode 100644 index 00000000000..6f01c7a2a66 --- /dev/null +++ b/solutions/250. Count Univalue Subtrees/250.java @@ -0,0 +1,20 @@ +class Solution { + public int countUnivalSubtrees(TreeNode root) { + isUnival(root, Integer.MAX_VALUE); + return ans; + } + + private int ans = 0; + + private boolean isUnival(TreeNode root, int val) { + if (root == null) + return true; + + if (isUnival(root.left, root.val) & isUnival(root.right, root.val)) { + ++ans; + return root.val == val; + } + + return false; + } +} diff --git a/solutions/250. Count Univalue Subtrees/250.py b/solutions/250. Count Univalue Subtrees/250.py new file mode 100644 index 00000000000..ad303ef59a8 --- /dev/null +++ b/solutions/250. Count Univalue Subtrees/250.py @@ -0,0 +1,17 @@ +class Solution: + def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def isUnival(root: Optional[TreeNode], val: int) -> bool: + nonlocal ans + if not root: + return True + + if isUnival(root.left, root.val) & isUnival(root.right, root.val): + ans += 1 + return root.val == val + + return False + + isUnival(root, math.inf) + return ans diff --git a/solutions/2500. Delete Greatest Value in Each Row/2500.cpp b/solutions/2500. Delete Greatest Value in Each Row/2500.cpp new file mode 100644 index 00000000000..55e4df5cbb9 --- /dev/null +++ b/solutions/2500. Delete Greatest Value in Each Row/2500.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int deleteGreatestValue(vector>& grid) { + int ans = 0; + + for (vector& row : grid) + ranges::sort(row); + + for (int j = 0; j < grid[0].size(); ++j) { + int maxOfColumn = 0; + for (int i = 0; i < grid.size(); ++i) + maxOfColumn = max(maxOfColumn, grid[i][j]); + ans += maxOfColumn; + } + + return ans; + } +}; diff --git a/solutions/2500. Delete Greatest Value in Each Row/2500.java b/solutions/2500. Delete Greatest Value in Each Row/2500.java new file mode 100644 index 00000000000..30d8a289f6d --- /dev/null +++ b/solutions/2500. Delete Greatest Value in Each Row/2500.java @@ -0,0 +1,17 @@ +class Solution { + public int deleteGreatestValue(int[][] grid) { + int ans = 0; + + for (int[] row : grid) + Arrays.sort(row); + + for (int j = 0; j < grid[0].length; ++j) { + int maxOfColumn = 0; + for (int i = 0; i < grid.length; ++i) + maxOfColumn = Math.max(maxOfColumn, grid[i][j]); + ans += maxOfColumn; + } + + return ans; + } +} diff --git a/solutions/2500. Delete Greatest Value in Each Row/2500.py b/solutions/2500. Delete Greatest Value in Each Row/2500.py new file mode 100644 index 00000000000..70a1d08cd20 --- /dev/null +++ b/solutions/2500. Delete Greatest Value in Each Row/2500.py @@ -0,0 +1,5 @@ +class Solution: + def deleteGreatestValue(self, grid: List[List[int]]) -> int: + for row in grid: + row.sort() + return sum(max(col) for col in zip(*grid)) diff --git a/solutions/2501. Longest Square Streak in an Array/2501.cpp b/solutions/2501. Longest Square Streak in an Array/2501.cpp new file mode 100644 index 00000000000..2247ec4f756 --- /dev/null +++ b/solutions/2501. Longest Square Streak in an Array/2501.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int longestSquareStreak(vector& nums) { + nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); + ranges::sort(nums, greater<>()); + + const int maxNum = ranges::max(nums); + // dp[i] := the longest square streak starts with i + vector dp(maxNum + 1); + + for (const int num : nums) { + dp[num] = 1; + const long squaredNum = static_cast(num) * num; + if (squaredNum <= maxNum) + dp[num] += dp[squaredNum]; + } + + const int ans = ranges::max(dp); + return ans < 2 ? -1 : ans; + } +}; diff --git a/solutions/2502. Design Memory Allocator/2502.cpp b/solutions/2502. Design Memory Allocator/2502.cpp new file mode 100644 index 00000000000..97b98279358 --- /dev/null +++ b/solutions/2502. Design Memory Allocator/2502.cpp @@ -0,0 +1,32 @@ +class Allocator { + public: + Allocator(int n) : memory(n), mIDToIndices(1001) {} + + int allocate(int size, int mID) { + int consecutiveFree = 0; + for (int i = 0; i < memory.size(); ++i) { + consecutiveFree = memory[i] == 0 ? consecutiveFree + 1 : 0; + if (consecutiveFree == size) { + for (int j = i - consecutiveFree + 1; j <= i; ++j) { + memory[j] = mID; + mIDToIndices[mID].push_back(j); + } + return i - consecutiveFree + 1; + } + } + return -1; + } + + int free(int mID) { + vector& indices = mIDToIndices[mID]; + const int freedUnits = indices.size(); + for (const int index : indices) + memory[index] = 0; + indices.clear(); + return freedUnits; + } + + private: + vector memory; + vector> mIDToIndices; +}; diff --git a/solutions/2502. Design Memory Allocator/2502.java b/solutions/2502. Design Memory Allocator/2502.java new file mode 100644 index 00000000000..46b1b3b24f0 --- /dev/null +++ b/solutions/2502. Design Memory Allocator/2502.java @@ -0,0 +1,35 @@ +class Allocator { + public Allocator(int n) { + memory = new int[n]; + mIDToIndices = new List[1001]; + for (int i = 1; i <= 1000; ++i) + mIDToIndices[i] = new ArrayList<>(); + } + + public int allocate(int size, int mID) { + int consecutiveFree = 0; + for (int i = 0; i < memory.length; ++i) { + consecutiveFree = memory[i] == 0 ? consecutiveFree + 1 : 0; + if (consecutiveFree == size) { + for (int j = i - consecutiveFree + 1; j <= i; ++j) { + memory[j] = mID; + mIDToIndices[mID].add(j); + } + return i - consecutiveFree + 1; + } + } + return -1; + } + + public int free(int mID) { + List indices = mIDToIndices[mID]; + final int freedUnits = indices.size(); + for (final int index : indices) + memory[index] = 0; + indices.clear(); + return freedUnits; + } + + private int[] memory; + private List[] mIDToIndices; +} diff --git a/solutions/2502. Design Memory Allocator/2502.py b/solutions/2502. Design Memory Allocator/2502.py new file mode 100644 index 00000000000..31364688c6f --- /dev/null +++ b/solutions/2502. Design Memory Allocator/2502.py @@ -0,0 +1,23 @@ +class Allocator: + def __init__(self, n: int): + self.memory = [0] * n + self.mIDToIndices = [[] for _ in range(1001)] + + def allocate(self, size: int, mID: int) -> int: + consecutiveFree = 0 + for i, m in enumerate(self.memory): + consecutiveFree = consecutiveFree + 1 if m == 0 else 0 + if consecutiveFree == size: + for j in range(i - consecutiveFree + 1, i + 1): + self.memory[j] = mID + self.mIDToIndices[mID].append(j) + return i - consecutiveFree + 1 + return -1 + + def free(self, mID: int) -> int: + indices = self.mIDToIndices[mID] + freedUnits = len(indices) + for index in indices: + self.memory[index] = 0 + indices.clear() + return freedUnits diff --git a/solutions/2503. Maximum Number of Points From Grid Queries/2503.cpp b/solutions/2503. Maximum Number of Points From Grid Queries/2503.cpp new file mode 100644 index 00000000000..87fe6e2f38e --- /dev/null +++ b/solutions/2503. Maximum Number of Points From Grid Queries/2503.cpp @@ -0,0 +1,67 @@ +struct IndexedQuery { + int queryIndex; + int query; +}; + +struct T { + int i; + int j; + int val; // grid[i][j] + T(int i, int j, int val) : i(i), j(j), val(val) {} +}; + +class Solution { + public: + vector maxPoints(vector>& grid, vector& queries) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + vector ans(queries.size()); + auto compare = [](const T& a, const T& b) { return a.val > b.val; }; + priority_queue, decltype(compare)> minHeap(compare); + vector> seen(m, vector(n)); + + minHeap.emplace(0, 0, grid[0][0]); + seen[0][0] = true; + int accumulate = 0; + + for (const auto& [queryIndex, query] : getIndexedQueries(queries)) { + while (!minHeap.empty()) { + const auto [i, j, val] = minHeap.top(); + minHeap.pop(); + if (val >= query) { + // The smallest neighbor is still larger than `query`, so no need to + // keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`. + minHeap.emplace(i, j, val); + break; + } + ++accumulate; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + minHeap.emplace(x, y, grid[x][y]); + seen[x][y] = true; + } + } + ans[queryIndex] = accumulate; + } + + return ans; + } + + private: + vector getIndexedQueries(const vector& queries) { + vector indexedQueries; + for (int i = 0; i < queries.size(); ++i) + indexedQueries.push_back({i, queries[i]}); + ranges::sort(indexedQueries, + [](const IndexedQuery& a, const IndexedQuery& b) { + return a.query < b.query; + }); + return indexedQueries; + } +}; diff --git a/solutions/2503. Maximum Number of Points From Grid Queries/2503.java b/solutions/2503. Maximum Number of Points From Grid Queries/2503.java new file mode 100644 index 00000000000..a47529fa348 --- /dev/null +++ b/solutions/2503. Maximum Number of Points From Grid Queries/2503.java @@ -0,0 +1,65 @@ +class T { + public int i; + public int j; + public int val; // grid[i][j] + public T(int i, int j, int val) { + this.i = i; + this.j = j; + this.val = val; + } +} + +class Solution { + public int[] maxPoints(int[][] grid, int[] queries) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length; + int[] ans = new int[queries.length]; + Queue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val); + boolean[][] seen = new boolean[m][n]; + + minHeap.offer(new T(0, 0, grid[0][0])); + seen[0][0] = true; + int accumulate = 0; + + for (IndexedQuery indexedQuery : getIndexedQueries(queries)) { + final int queryIndex = indexedQuery.queryIndex; + final int query = indexedQuery.query; + while (!minHeap.isEmpty()) { + final int i = minHeap.peek().i; + final int j = minHeap.peek().j; + final int val = minHeap.poll().val; + if (val >= query) { + // The smallest neighbor is still larger than `query`, so no need to + // keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`. + minHeap.offer(new T(i, j, val)); + break; + } + ++accumulate; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + minHeap.offer(new T(x, y, grid[x][y])); + seen[x][y] = true; + } + } + ans[queryIndex] = accumulate; + } + + return ans; + } + + private record IndexedQuery(int queryIndex, int query){}; + + private IndexedQuery[] getIndexedQueries(int[] queries) { + IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; + for (int i = 0; i < queries.length; ++i) + indexedQueries[i] = new IndexedQuery(i, queries[i]); + Arrays.sort(indexedQueries, (a, b) -> a.query - b.query); + return indexedQueries; + } +} diff --git a/solutions/2503. Maximum Number of Points From Grid Queries/2503.py b/solutions/2503. Maximum Number of Points From Grid Queries/2503.py new file mode 100644 index 00000000000..f66d8a1437d --- /dev/null +++ b/solutions/2503. Maximum Number of Points From Grid Queries/2503.py @@ -0,0 +1,43 @@ +class IndexedQuery: + def __init__(self, queryIndex: int, query: int): + self.queryIndex = queryIndex + self.query = query + + def __iter__(self): + yield self.queryIndex + yield self.query + + +class Solution: + def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + ans = [0] * len(queries) + minHeap = [(grid[0][0], 0, 0)] # (grid[i][j], i, j) + seen = {(0, 0)} + accumulate = 0 + + for queryIndex, query in sorted([IndexedQuery(i, query) + for i, query in enumerate(queries)], + key=lambda iq: iq.query): + while minHeap: + val, i, j = heapq.heappop(minHeap) + if val >= query: + # The smallest neighbor is still larger than `query`, so no need to + # keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`. + heapq.heappush(minHeap, (val, i, j)) + break + accumulate += 1 + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if (x, y) in seen: + continue + heapq.heappush(minHeap, (grid[x][y], x, y)) + seen.add((x, y)) + ans[queryIndex] = accumulate + + return ans diff --git a/solutions/2504. Concatenate the Name and the Profession/2504.sql b/solutions/2504. Concatenate the Name and the Profession/2504.sql new file mode 100644 index 00000000000..54567034b34 --- /dev/null +++ b/solutions/2504. Concatenate the Name and the Profession/2504.sql @@ -0,0 +1,5 @@ +SELECT + person_id, + CONCAT(name, '(', LEFT(profession, 1), ')') name +FROM Person +ORDER BY 1 DESC; diff --git a/solutions/2505. Bitwise OR of All Subsequence Sums/2505.cpp b/solutions/2505. Bitwise OR of All Subsequence Sums/2505.cpp new file mode 100644 index 00000000000..25e32a43686 --- /dev/null +++ b/solutions/2505. Bitwise OR of All Subsequence Sums/2505.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long subsequenceSumOr(vector& nums) { + long ans = 0; + long prefix = 0; + + for (const int num : nums) { + prefix += num; + ans |= num | prefix; + } + + return ans; + } +}; diff --git a/solutions/2505. Bitwise OR of All Subsequence Sums/2505.java b/solutions/2505. Bitwise OR of All Subsequence Sums/2505.java new file mode 100644 index 00000000000..31f33165b0f --- /dev/null +++ b/solutions/2505. Bitwise OR of All Subsequence Sums/2505.java @@ -0,0 +1,13 @@ +class Solution { + public long subsequenceSumOr(int[] nums) { + long ans = 0; + long prefix = 0; + + for (final int num : nums) { + prefix += num; + ans |= num | prefix; + } + + return ans; + } +} diff --git a/solutions/2505. Bitwise OR of All Subsequence Sums/2505.py b/solutions/2505. Bitwise OR of All Subsequence Sums/2505.py new file mode 100644 index 00000000000..e2c29f88b2b --- /dev/null +++ b/solutions/2505. Bitwise OR of All Subsequence Sums/2505.py @@ -0,0 +1,10 @@ +class Solution: + def subsequenceSumOr(self, nums: List[int]) -> int: + ans = 0 + prefix = 0 + + for num in nums: + prefix += num + ans |= num | prefix + + return ans diff --git a/solutions/2506. Count Pairs Of Similar Strings/2506-2.py b/solutions/2506. Count Pairs Of Similar Strings/2506-2.py new file mode 100644 index 00000000000..47dc1f3740e --- /dev/null +++ b/solutions/2506. Count Pairs Of Similar Strings/2506-2.py @@ -0,0 +1,5 @@ +class Solution: + def similarPairs(self, words: List[str]) -> int: + return sum(set(words[i]) == set(words[j]) + for i in range(len(words)) + for j in range(i + 1, len(words))) diff --git a/solutions/2506. Count Pairs Of Similar Strings/2506.cpp b/solutions/2506. Count Pairs Of Similar Strings/2506.cpp new file mode 100644 index 00000000000..a59d281e801 --- /dev/null +++ b/solutions/2506. Count Pairs Of Similar Strings/2506.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int similarPairs(vector& words) { + int ans = 0; + vector masks; + + for (const string& word : words) + masks.push_back(getMask(word)); + + for (int i = 0; i < masks.size(); ++i) + for (int j = i + 1; j < masks.size(); ++j) + if (masks[i] == masks[j]) + ++ans; + + return ans; + } + + private: + int getMask(const string& word) { + int mask = 0; + for (const char c : word) + mask |= 1 << c - 'a'; + return mask; + } +}; diff --git a/solutions/2506. Count Pairs Of Similar Strings/2506.java b/solutions/2506. Count Pairs Of Similar Strings/2506.java new file mode 100644 index 00000000000..cd2fcc522ea --- /dev/null +++ b/solutions/2506. Count Pairs Of Similar Strings/2506.java @@ -0,0 +1,23 @@ +class Solution { + public int similarPairs(String[] words) { + int ans = 0; + int[] masks = new int[words.length]; + + for (int i = 0; i < words.length; ++i) + masks[i] = getMask(words[i]); + + for (int i = 0; i < masks.length; ++i) + for (int j = i + 1; j < masks.length; ++j) + if (masks[i] == masks[j]) + ++ans; + + return ans; + } + + private int getMask(final String word) { + int mask = 0; + for (const char c : word.toCharArray()) + mask |= 1 << c - 'a'; + return mask; + } +} diff --git a/solutions/2506. Count Pairs Of Similar Strings/2506.py b/solutions/2506. Count Pairs Of Similar Strings/2506.py new file mode 100644 index 00000000000..25471a903e3 --- /dev/null +++ b/solutions/2506. Count Pairs Of Similar Strings/2506.py @@ -0,0 +1,18 @@ +class Solution: + def similarPairs(self, words: List[str]) -> int: + ans = 0 + + def getMask(word: str) -> int: + mask = 0 + for c in word: + mask |= 1 << ord(c) - ord('a') + return mask + + masks = [getMask(word) for word in words] + + for i in range(len(masks)): + for j in range(i + 1, len(masks)): + if masks[i] == masks[j]: + ans += 1 + + return ans diff --git a/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.cpp b/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.cpp new file mode 100644 index 00000000000..9f9642c0adb --- /dev/null +++ b/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int smallestValue(int n) { + int primeSum = getPrimeSum(n); + while (n != primeSum) { + n = primeSum; + primeSum = getPrimeSum(n); + } + return n; + } + + private: + int getPrimeSum(int n) { + int primeSum = 0; + for (int i = 2; i <= n; ++i) + while (n % i == 0) { + n /= i; + primeSum += i; + } + return primeSum; + } +}; diff --git a/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.java b/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.java new file mode 100644 index 00000000000..1a52ccaa90a --- /dev/null +++ b/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.java @@ -0,0 +1,20 @@ +class Solution { + public int smallestValue(int n) { + int primeSum = getPrimeSum(n); + while (n != primeSum) { + n = primeSum; + primeSum = getPrimeSum(n); + } + return n; + } + + private int getPrimeSum(int n) { + int primeSum = 0; + for (int i = 2; i <= n; ++i) + while (n % i == 0) { + n /= i; + primeSum += i; + } + return primeSum; + } +} diff --git a/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.py b/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.py new file mode 100644 index 00000000000..e4881788f76 --- /dev/null +++ b/solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.py @@ -0,0 +1,15 @@ +class Solution: + def smallestValue(self, n: int) -> int: + def getPrimeSum(n: int) -> int: + primeSum = 0 + for i in range(2, n + 1): + while n % i == 0: + n //= i + primeSum += i + return primeSum + + primeSum = getPrimeSum(n) + while n != primeSum: + n = primeSum + primeSum = getPrimeSum(n) + return n diff --git a/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.cpp b/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.cpp new file mode 100644 index 00000000000..a51584cd2f3 --- /dev/null +++ b/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + bool isPossible(int n, vector>& edges) { + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0] - 1; + const int v = edge[1] - 1; + graph[u].insert(v); + graph[v].insert(u); + } + + const vector oddNodes = getOddNodes(graph); + if (oddNodes.empty()) + return true; + if (oddNodes.size() == 2) { + const int a = oddNodes[0]; + const int b = oddNodes[1]; + for (int i = 0; i < n; ++i) + // Can connect i with a and i with b. + if (!graph[i].contains(a) && !graph[i].contains(b)) + return true; + } + if (oddNodes.size() == 4) { + const int a = oddNodes[0]; + const int b = oddNodes[1]; + const int c = oddNodes[2]; + const int d = oddNodes[3]; + return (!graph[a].contains(b) && !graph[c].contains(d)) || + (!graph[a].contains(c) && !graph[b].contains(d)) || + (!graph[a].contains(d) && !graph[b].contains(c)); + } + return false; + } + + private: + vector getOddNodes(const vector>& graph) { + vector oddNodes; + for (int i = 0; i < graph.size(); ++i) + if (graph[i].size() % 2 == 1) + oddNodes.push_back(i); + return oddNodes; + } +}; diff --git a/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.java b/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.java new file mode 100644 index 00000000000..0fdb3c3e31b --- /dev/null +++ b/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.java @@ -0,0 +1,45 @@ +class Solution { + public boolean isPossible(int n, List> edges) { + Set[] graph = new Set[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new HashSet<>(); + + for (List edge : edges) { + final int u = edge.get(0) - 1; + final int v = edge.get(1) - 1; + graph[u].add(v); + graph[v].add(u); + } + + List oddNodes = getOddNodes(graph); + if (oddNodes.isEmpty()) + return true; + if (oddNodes.size() == 2) { + final int a = oddNodes.get(0); + final int b = oddNodes.get(1); + for (int i = 0; i < n; ++i) + // Can connect i with a and i with b. + if (!graph[i].contains(a) && !graph[i].contains(b)) + return true; + } + if (oddNodes.size() == 4) { + final int a = oddNodes.get(0); + final int b = oddNodes.get(1); + final int c = oddNodes.get(2); + final int d = oddNodes.get(3); + return (!graph[a].contains(b) && !graph[c].contains(d)) || + (!graph[a].contains(c) && !graph[b].contains(d)) || + (!graph[a].contains(d) && !graph[b].contains(c)); + } + return false; + } + + private List getOddNodes(Set[] graph) { + List oddNodes = new ArrayList<>(); + for (int i = 0; i < graph.length; ++i) + if (graph[i].size() % 2 == 1) + oddNodes.add(i); + return oddNodes; + } +} diff --git a/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.py b/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.py new file mode 100644 index 00000000000..5513d6e03ab --- /dev/null +++ b/solutions/2508. Add Edges to Make Degrees of All Nodes Even/2508.py @@ -0,0 +1,21 @@ +class Solution: + def isPossible(self, n: int, edges: List[List[int]]) -> bool: + graph = [set() for _ in range(n)] + + for u, v in edges: + graph[u - 1].add(v - 1) + graph[v - 1].add(u - 1) + + oddNodes = [i for i, neighbor in enumerate( + graph) if len(neighbor) % 2 == 1] + if not oddNodes: + return True + if len(oddNodes) == 2: + a, b = oddNodes + return any(a not in graph[i] and b not in graph[i] for i in range(n)) + if len(oddNodes) == 4: + a, b, c, d = oddNodes + return (b not in graph[a] and d not in graph[c]) or \ + (c not in graph[a] and d not in graph[b]) or \ + (d not in graph[a] and c not in graph[b]) + return False diff --git a/solutions/2509. Cycle Length Queries in a Tree/2509.cpp b/solutions/2509. Cycle Length Queries in a Tree/2509.cpp new file mode 100644 index 00000000000..dd29bb2cbde --- /dev/null +++ b/solutions/2509. Cycle Length Queries in a Tree/2509.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector cycleLengthQueries(int n, vector>& queries) { + vector ans; + + for (const vector& query : queries) { + ans.push_back(1); + int a = query[0]; + int b = query[1]; + while (a != b) { + if (a > b) + a /= 2; + else + b /= 2; + ++ans.back(); + } + } + + return ans; + } +}; diff --git a/solutions/2509. Cycle Length Queries in a Tree/2509.java b/solutions/2509. Cycle Length Queries in a Tree/2509.java new file mode 100644 index 00000000000..1856f59efce --- /dev/null +++ b/solutions/2509. Cycle Length Queries in a Tree/2509.java @@ -0,0 +1,20 @@ +class Solution { + public int[] cycleLengthQueries(int n, int[][] queries) { + int[] ans = new int[queries.length]; + + for (int i = 0; i < queries.length; ++i) { + ++ans[i]; + int a = queries[i][0]; + int b = queries[i][1]; + while (a != b) { + if (a > b) + a /= 2; + else + b /= 2; + ++ans[i]; + } + } + + return ans; + } +} diff --git a/solutions/2509. Cycle Length Queries in a Tree/2509.py b/solutions/2509. Cycle Length Queries in a Tree/2509.py new file mode 100644 index 00000000000..d04bf2b6490 --- /dev/null +++ b/solutions/2509. Cycle Length Queries in a Tree/2509.py @@ -0,0 +1,13 @@ +class Solution: + def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]: + def getCycleLength(a: int, b: int): + cycleLength = 1 + while a != b: + if a > b: + a //= 2 + else: + b //= 2 + cycleLength += 1 + return cycleLength + + return [getCycleLength(*query) for query in queries] diff --git a/solutions/251. Flatten 2D Vector/251-2.cpp b/solutions/251. Flatten 2D Vector/251-2.cpp new file mode 100644 index 00000000000..0f49e0e3f76 --- /dev/null +++ b/solutions/251. Flatten 2D Vector/251-2.cpp @@ -0,0 +1,27 @@ +class Vector2D { + public: + Vector2D(vector>& v) { + i = v.begin(); + iEnd = v.end(); + } + + int next() { + moveIterator(); + return (*i)[j++]; + } + + bool hasNext() { + moveIterator(); + return i != iEnd; + } + + private: + // (*i)[j] := the current pointed value + vector>::iterator i, iEnd; + int j = 0; + + void moveIterator() { + while (i != iEnd && j == (*i).size()) + ++i, j = 0; + } +}; diff --git a/solutions/251. Flatten 2D Vector/251.cpp b/solutions/251. Flatten 2D Vector/251.cpp new file mode 100644 index 00000000000..6e4c394a8c3 --- /dev/null +++ b/solutions/251. Flatten 2D Vector/251.cpp @@ -0,0 +1,20 @@ +class Vector2D { + public: + Vector2D(vector>& vec) { + for (const vector& A : vec) + for (const int a : A) + this->vec.push_back(a); + } + + int next() { + return vec[i++]; + } + + bool hasNext() { + return i < vec.size(); + } + + private: + vector vec; + int i = 0; +}; diff --git a/solutions/251. Flatten 2D Vector/251.java b/solutions/251. Flatten 2D Vector/251.java new file mode 100644 index 00000000000..70d4ffd7b3c --- /dev/null +++ b/solutions/251. Flatten 2D Vector/251.java @@ -0,0 +1,18 @@ +class Vector2D { + public Vector2D(int[][] vec) { + for (int[] A : vec) + for (final int a : A) + this.vec.add(a); + } + + public int next() { + return vec.get(i++); + } + + public boolean hasNext() { + return i < vec.size(); + } + + private List vec = new ArrayList<>(); + private int i = 0; +} diff --git a/solutions/251. Flatten 2D Vector/251.py b/solutions/251. Flatten 2D Vector/251.py new file mode 100644 index 00000000000..bef70b8c014 --- /dev/null +++ b/solutions/251. Flatten 2D Vector/251.py @@ -0,0 +1,15 @@ +class Vector2D: + def __init__(self, vec: List[List[int]]): + self.vec = [] + self.i = 0 + + for A in vec: + self.vec += A + + def next(self) -> int: + ans = self.vec[self.i] + self.i += 1 + return ans + + def hasNext(self) -> bool: + return self.i < len(self.vec) diff --git a/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.cpp b/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.cpp new file mode 100644 index 00000000000..7dbf0eeea87 --- /dev/null +++ b/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + bool isThereAPath(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + // Map negative (the number of 0s - the number of 1s) to non-negative one. + const int cells = m + n - 1; + if (cells % 2 == 1) + return false; + vector>> mem( + m, vector>(n, vector(cells * 2 + 1, -1))); + return isThereAPath(grid, 0, 0, 0, cells, mem); + } + + private: + // Returns 1 if there's a path to grid[i][j] + // s.t. `sum` = (the number of 0s - the number of 1s). + bool isThereAPath(const vector>& grid, int i, int j, int sum, + const int& cells, vector>>& mem) { + if (i == grid.size() || j == grid[0].size()) + return false; + sum += grid[i][j] == 0 ? 1 : -1; + if (i == grid.size() - 1 && j == grid[0].size() - 1) + return sum == 0; + const int k = cells + sum; + if (mem[i][j][k] != -1) + return mem[i][j][k]; + return mem[i][j][k] = isThereAPath(grid, i + 1, j, sum, cells, mem) || + isThereAPath(grid, i, j + 1, sum, cells, mem); + } +}; diff --git a/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.java b/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.java new file mode 100644 index 00000000000..3db50773961 --- /dev/null +++ b/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.java @@ -0,0 +1,28 @@ +class Solution { + public boolean isThereAPath(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + // Map negative (the number of 0s - the number of 1s) to non-negative one. + final int cells = m + n - 1; + if (cells % 2 == 1) + return false; + Boolean[][][] mem = new Boolean[m][n][cells * 2 + 1]; + return isThereAPath(grid, 0, 0, 0, cells, mem); + } + + // Returns 1 if there's a path to grid[i][j] + // s.t. `sum` = (the number of 0s - the number of 1s). + private boolean isThereAPath(int[][] grid, int i, int j, int sum, final int cells, + Boolean[][][] mem) { + if (i == grid.length || j == grid[0].length) + return false; + sum += grid[i][j] == 0 ? 1 : -1; + if (i == grid.length - 1 && j == grid[0].length - 1) + return sum == 0; + final int k = cells + sum; + if (mem[i][j][k] != null) + return mem[i][j][k]; + return mem[i][j][k] = isThereAPath(grid, i + 1, j, sum, cells, mem) || + isThereAPath(grid, i, j + 1, sum, cells, mem); + } +} diff --git a/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.py b/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.py new file mode 100644 index 00000000000..eee9ce7bdf7 --- /dev/null +++ b/solutions/2510. Check if There is a Path With Equal Number of 0's And 1's/2510.py @@ -0,0 +1,21 @@ +class Solution: + def isThereAPath(self, grid: List[List[int]]) -> bool: + m = len(grid) + n = len(grid[0]) + if m + n - 1 & 1: + return False + + @functools.lru_cache(None) + def dp(i: int, j: int, summ: int) -> bool: + """ + Returns 1 if there's a path to grid[i][j] s.t. + `summ` = (the number of 0s - the number of 1s). + """ + if i == m or j == n: + return False + summ += 1 if grid[i][j] == 0 else -1 + if i == m - 1 and j == n - 1: + return summ == 0 + return dp(i + 1, j, summ) or dp(i, j + 1, summ) + + return dp(0, 0, 0) diff --git a/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.cpp b/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.cpp new file mode 100644 index 00000000000..286940dd32d --- /dev/null +++ b/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int captureForts(vector& forts) { + int ans = 0; + + for (int i = 0, j = 0; i < forts.size(); ++i) + if (forts[i] != 0) { // -1 or 1 + if (forts[i] == -forts[j]) + ans = max(ans, i - j - 1); + j = i; + } + + return ans; + } +}; diff --git a/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.java b/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.java new file mode 100644 index 00000000000..d7ac5b235c3 --- /dev/null +++ b/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.java @@ -0,0 +1,14 @@ +class Solution { + public int captureForts(int[] forts) { + int ans = 0; + + for (int i = 0, j = 0; i < forts.length; ++i) + if (forts[i] != 0) { // -1 or 1 + if (forts[i] == -forts[j]) + ans = Math.max(ans, i - j - 1); + j = i; + } + + return ans; + } +} diff --git a/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.py b/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.py new file mode 100644 index 00000000000..70a942793be --- /dev/null +++ b/solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.py @@ -0,0 +1,12 @@ +class Solution: + def captureForts(self, forts: List[int]) -> int: + ans = 0 + + j = 0 + for i, fort in enumerate(forts): + if fort != 0: # -1 or 1 + if fort == -forts[j]: + ans = max(ans, i - j - 1) + j = i + + return ans diff --git a/solutions/2512. Reward Top K Students/2512.cpp b/solutions/2512. Reward Top K Students/2512.cpp new file mode 100644 index 00000000000..b50802e67bb --- /dev/null +++ b/solutions/2512. Reward Top K Students/2512.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector topStudents(vector& positive_feedback, + vector& negative_feedback, + vector& report, vector& student_id, + int k) { + vector ans; + vector> scoreAndIds; + unordered_set pos{positive_feedback.begin(), + positive_feedback.end()}; + unordered_set neg{negative_feedback.begin(), + negative_feedback.end()}; + + for (int i = 0; i < report.size(); ++i) { + int score = 0; + istringstream iss(report[i]); + for (string word; iss >> word;) { + if (pos.contains(word)) + score += 3; + if (neg.contains(word)) + score -= 1; + } + scoreAndIds.emplace_back(-score, student_id[i]); + } + + partial_sort(scoreAndIds.begin(), scoreAndIds.begin() + k, + scoreAndIds.end()); + transform( + scoreAndIds.begin(), scoreAndIds.begin() + k, back_inserter(ans), + [](const pair& scoreAndId) { return scoreAndId.second; }); + return ans; + } +}; diff --git a/solutions/2512. Reward Top K Students/2512.java b/solutions/2512. Reward Top K Students/2512.java new file mode 100644 index 00000000000..12d75b5a88d --- /dev/null +++ b/solutions/2512. Reward Top K Students/2512.java @@ -0,0 +1,29 @@ +class Solution { + public List topStudents(String[] positive_feedback, String[] negative_feedback, + String[] report, int[] student_id, int k) { + List ans = new ArrayList<>(); + Pair[] scoreAndIds = new Pair[report.length]; + Set pos = Arrays.stream(positive_feedback).collect(Collectors.toSet()); + Set neg = Arrays.stream(negative_feedback).collect(Collectors.toSet()); + + for (int i = 0; i < report.length; ++i) { + int score = 0; + for (final String word : report[i].split(" ")) { + if (pos.contains(word)) + score += 3; + if (neg.contains(word)) + score -= 1; + } + scoreAndIds[i] = new Pair<>(score, student_id[i]); + } + + Arrays.sort(scoreAndIds, + (a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue() - b.getValue() + : b.getKey() - a.getKey()); + + for (int i = 0; i < k; ++i) + ans.add(scoreAndIds[i].getValue()); + return ans; + } +} diff --git a/solutions/2512. Reward Top K Students/2512.py b/solutions/2512. Reward Top K Students/2512.py new file mode 100644 index 00000000000..e581522c133 --- /dev/null +++ b/solutions/2512. Reward Top K Students/2512.py @@ -0,0 +1,16 @@ +class Solution: + def topStudents(self, positive_feedback: List[str], negative_feedback: List[str], report: List[str], student_id: List[int], k: int) -> List[int]: + scoreAndIds = [] + pos = set(positive_feedback) + neg = set(negative_feedback) + + for sid, r in zip(student_id, report): + score = 0 + for word in r.split(): + if word in pos: + score += 3 + if word in neg: + score -= 1 + scoreAndIds.append((-score, sid)) + + return [sid for _, sid in sorted(scoreAndIds)[:k]] diff --git a/solutions/2513. Minimize the Maximum of Two Arrays/2513.cpp b/solutions/2513. Minimize the Maximum of Two Arrays/2513.cpp new file mode 100644 index 00000000000..de35dc2eb6a --- /dev/null +++ b/solutions/2513. Minimize the Maximum of Two Arrays/2513.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) { + const long divisorLcm = std::lcm(static_cast(divisor1), divisor2); + long l = 0; + long r = INT_MAX; + + while (l < r) { + const long m = (l + r) / 2; + if (isPossible(m, divisorLcm, divisor1, divisor2, uniqueCnt1, uniqueCnt2)) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Returns true if we can take uniqueCnt1 integers from [1..m] to arr1 and + // take uniqueCnt2 integers from [1..m] to arr2. + bool isPossible(long m, long divisorLcm, int divisor1, int divisor2, + int uniqueCnt1, int uniqueCnt2) { + const long cnt1 = m - m / divisor1; + const long cnt2 = m - m / divisor2; + const long totalCnt = m - m / divisorLcm; + return cnt1 >= uniqueCnt1 && cnt2 >= uniqueCnt2 && + totalCnt >= uniqueCnt1 + uniqueCnt2; + } +}; diff --git a/solutions/2513. Minimize the Maximum of Two Arrays/2513.java b/solutions/2513. Minimize the Maximum of Two Arrays/2513.java new file mode 100644 index 00000000000..84a7dbafb27 --- /dev/null +++ b/solutions/2513. Minimize the Maximum of Two Arrays/2513.java @@ -0,0 +1,35 @@ +class Solution { + public int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) { + final long divisorLcm = lcm(divisor1, divisor2); + long l = 0; + long r = Integer.MAX_VALUE; + + while (l < r) { + final long m = (l + r) / 2; + if (isPossible(m, divisorLcm, divisor1, divisor2, uniqueCnt1, uniqueCnt2)) + r = m; + else + l = m + 1; + } + + return (int) l; + } + + // Returns true if we can take uniqueCnt1 integers from [1..m] to arr1 and + // take uniqueCnt2 integers from [1..m] to arr2. + private boolean isPossible(long m, long divisorLcm, int divisor1, int divisor2, int uniqueCnt1, + int uniqueCnt2) { + final long cnt1 = m - m / divisor1; + final long cnt2 = m - m / divisor2; + final long totalCnt = m - m / divisorLcm; + return cnt1 >= uniqueCnt1 && cnt2 >= uniqueCnt2 && totalCnt >= uniqueCnt1 + uniqueCnt2; + } + + private long gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private long lcm(int a, int b) { + return a * (b / gcd(a, b)); + } +} diff --git a/solutions/2513. Minimize the Maximum of Two Arrays/2513.py b/solutions/2513. Minimize the Maximum of Two Arrays/2513.py new file mode 100644 index 00000000000..f15e32b6bbd --- /dev/null +++ b/solutions/2513. Minimize the Maximum of Two Arrays/2513.py @@ -0,0 +1,23 @@ +class Solution: + def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int: + divisorLcm = math.lcm(divisor1, divisor2) + l = 0 + r = 2**31 - 1 + + # True if we can take uniqueCnt1 integers from [1..m] to arr1 and take + # uniqueCnt2 integers from [1..m] to arr2. + def isPossible(m: int) -> bool: + cnt1 = m - m // divisor1 + cnt2 = m - m // divisor2 + totalCnt = m - m // divisorLcm + return cnt1 >= uniqueCnt1 and cnt2 >= uniqueCnt2 and \ + totalCnt >= uniqueCnt1 + uniqueCnt2 + + while l < r: + m = (l + r) // 2 + if isPossible(m): + r = m + else: + l = m + 1 + + return l diff --git a/solutions/2514. Count Anagrams/2514.cpp b/solutions/2514. Count Anagrams/2514.cpp new file mode 100644 index 00000000000..558b807453c --- /dev/null +++ b/solutions/2514. Count Anagrams/2514.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int countAnagrams(string s) { + const int n = s.length(); + const auto [fact, invFact] = getFactAndInvFact(n); + int ans = 1; + istringstream iss(s); + + for (string word; iss >> word;) { + ans = ans * fact[word.length()] % kMod; + vector count(26); + for (const char c : word) + ++count[c - 'a']; + for (const int freq : count) + ans = ans * invFact[freq] % kMod; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + pair, vector> getFactAndInvFact(int n) { + vector fact(n + 1); + vector invFact(n + 1); + vector inv(n + 1); + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return {fact, invFact}; + } +}; diff --git a/solutions/2514. Count Anagrams/2514.java b/solutions/2514. Count Anagrams/2514.java new file mode 100644 index 00000000000..3d78a8eafaf --- /dev/null +++ b/solutions/2514. Count Anagrams/2514.java @@ -0,0 +1,37 @@ +class Solution { + public int countAnagrams(String s) { + final int n = s.length(); + final long[][] factAndInvFact = getFactAndInvFact(n); + final long[] fact = factAndInvFact[0]; + final long[] invFact = factAndInvFact[1]; + long ans = 1; + + for (final String word : s.split(" ")) { + ans = ans * fact[word.length()] % kMod; + int[] count = new int[26]; + for (final char c : word.toCharArray()) + ++count[c - 'a']; + for (final int freq : count) + ans = ans * invFact[freq] % kMod; + } + + return (int) ans; + } + + private static final int kMod = 1_000_000_007; + + private long[][] getFactAndInvFact(int n) { + long[] fact = new long[n + 1]; + long[] invFact = new long[n + 1]; + long[] inv = new long[n + 1]; + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return new long[][] {fact, invFact}; + } +} diff --git a/solutions/2514. Count Anagrams/2514.py b/solutions/2514. Count Anagrams/2514.py new file mode 100644 index 00000000000..9998d57e3fe --- /dev/null +++ b/solutions/2514. Count Anagrams/2514.py @@ -0,0 +1,11 @@ +class Solution: + def countAnagrams(self, s: str) -> int: + ans = 1 + + for word in s.split(): + ans = ans * math.factorial(len(word)) + count = collections.Counter(word) + for freq in count.values(): + ans //= math.factorial(freq) + + return ans % 1_000_000_007 diff --git a/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.cpp b/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.cpp new file mode 100644 index 00000000000..5e2903947b0 --- /dev/null +++ b/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int closetTarget(vector& words, string target, int startIndex) { + const int n = words.size(); + + for (int i = 0; i < n; ++i) { + if (words[(startIndex + i + n) % n] == target) + return i; + if (words[(startIndex - i + n) % n] == target) + return i; + } + + return -1; + } +}; diff --git a/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.java b/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.java new file mode 100644 index 00000000000..bb06a7c3718 --- /dev/null +++ b/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.java @@ -0,0 +1,14 @@ +class Solution { + public int closetTarget(String[] words, String target, int startIndex) { + final int n = words.length; + + for (int i = 0; i < n; ++i) { + if (words[(startIndex + i + n) % n].equals(target)) + return i; + if (words[(startIndex - i + n) % n].equals(target)) + return i; + } + + return -1; + } +} diff --git a/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.py b/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.py new file mode 100644 index 00000000000..2a3f9b47b46 --- /dev/null +++ b/solutions/2515. Shortest Distance to Target String in a Circular Array/2515.py @@ -0,0 +1,11 @@ +class Solution: + def closetTarget(self, words: List[str], target: str, startIndex: int) -> int: + n = len(words) + + for i in range(n): + if words[(startIndex + i + n) % n] == target: + return i + if words[(startIndex - i + n) % n] == target: + return i + + return -1 diff --git a/solutions/2516. Take K of Each Character From Left and Right/2516.cpp b/solutions/2516. Take K of Each Character From Left and Right/2516.cpp new file mode 100644 index 00000000000..cfc1a892d2c --- /dev/null +++ b/solutions/2516. Take K of Each Character From Left and Right/2516.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int takeCharacters(string s, int k) { + const int n = s.length(); + int ans = n; + vector count(3); + + for (const char c : s) + ++count[c - 'a']; + + if (count[0] < k || count[1] < k || count[2] < k) + return -1; + + for (int l = 0, r = 0; r < n; ++r) { + --count[s[r] - 'a']; + while (count[s[r] - 'a'] < k) + ++count[s[l++] - 'a']; + ans = min(ans, n - (r - l + 1)); + } + + return ans; + } +}; diff --git a/solutions/2516. Take K of Each Character From Left and Right/2516.java b/solutions/2516. Take K of Each Character From Left and Right/2516.java new file mode 100644 index 00000000000..fbdcab5cb81 --- /dev/null +++ b/solutions/2516. Take K of Each Character From Left and Right/2516.java @@ -0,0 +1,22 @@ +class Solution { + public int takeCharacters(String s, int k) { + final int n = s.length(); + int ans = n; + int[] count = new int[3]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + if (count[0] < k || count[1] < k || count[2] < k) + return -1; + + for (int l = 0, r = 0; r < n; ++r) { + --count[s.charAt(r) - 'a']; + while (count[s.charAt(r) - 'a'] < k) + ++count[s.charAt(l++) - 'a']; + ans = Math.min(ans, n - (r - l + 1)); + } + + return ans; + } +} diff --git a/solutions/2516. Take K of Each Character From Left and Right/2516.py b/solutions/2516. Take K of Each Character From Left and Right/2516.py new file mode 100644 index 00000000000..60384c133b6 --- /dev/null +++ b/solutions/2516. Take K of Each Character From Left and Right/2516.py @@ -0,0 +1,17 @@ +class Solution: + def takeCharacters(self, s: str, k: int) -> int: + n = len(s) + ans = n + count = collections.Counter(s) + if any(count[c] < k for c in 'abc'): + return -1 + + l = 0 + for r, c in enumerate(s): + count[c] -= 1 + while count[c] < k: + count[s[l]] += 1 + l += 1 + ans = min(ans, n - (r - l + 1)) + + return ans diff --git a/solutions/2517. Maximum Tastiness of Candy Basket/2517.cpp b/solutions/2517. Maximum Tastiness of Candy Basket/2517.cpp new file mode 100644 index 00000000000..0c7494647a4 --- /dev/null +++ b/solutions/2517. Maximum Tastiness of Candy Basket/2517.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int maximumTastiness(vector& price, int k) { + ranges::sort(price); + + int l = 0; + int r = ranges::max(price) - ranges::min(price) + 1; + + while (l < r) { + const int m = (l + r) / 2; + if (numBaskets(price, m) >= k) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + private: + // Returns the number of baskets we can pick for m tastiness. + int numBaskets(const vector& price, int m) { + int baskets = 0; + int prevPrice = -m; + for (const int p : price) + if (p >= prevPrice + m) { + prevPrice = p; + ++baskets; + } + return baskets; + } +}; diff --git a/solutions/2517. Maximum Tastiness of Candy Basket/2517.java b/solutions/2517. Maximum Tastiness of Candy Basket/2517.java new file mode 100644 index 00000000000..a17b93ae872 --- /dev/null +++ b/solutions/2517. Maximum Tastiness of Candy Basket/2517.java @@ -0,0 +1,30 @@ +class Solution { + public int maximumTastiness(int[] price, int k) { + Arrays.sort(price); + + int l = 0; + int r = Arrays.stream(price).max().getAsInt() - Arrays.stream(price).min().getAsInt() + 1; + + while (l < r) { + final int m = (l + r) / 2; + if (numBaskets(price, m) >= k) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + // Returns the number of baskets we can pick for m tastiness. + private int numBaskets(int[] price, int m) { + int baskets = 0; + int prevPrice = -m; + for (final int p : price) + if (p >= prevPrice + m) { + prevPrice = p; + ++baskets; + } + return baskets; + } +} diff --git a/solutions/2517. Maximum Tastiness of Candy Basket/2517.py b/solutions/2517. Maximum Tastiness of Candy Basket/2517.py new file mode 100644 index 00000000000..5a0b5a5397e --- /dev/null +++ b/solutions/2517. Maximum Tastiness of Candy Basket/2517.py @@ -0,0 +1,17 @@ +class Solution: + def maximumTastiness(self, price: List[int], k: int) -> int: + price.sort() + + def cantPick(m: int) -> bool: + """Returns True if we can't pick k distinct candies for m tastiness.""" + baskets = 0 + prevPrice = -m + for p in price: + if p >= prevPrice + m: + prevPrice = p + baskets += 1 + return baskets < k + + l = bisect.bisect_left(range(max(price) - min(price) + 1), True, + key=lambda m: cantPick(m)) + return l - 1 diff --git a/solutions/2518. Number of Great Partitions/2518.cpp b/solutions/2518. Number of Great Partitions/2518.cpp new file mode 100644 index 00000000000..91a69a7d271 --- /dev/null +++ b/solutions/2518. Number of Great Partitions/2518.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int countPartitions(vector& nums, int k) { + const long sum = accumulate(nums.begin(), nums.end(), 0L); + long ans = modPow(2, nums.size()); + vector dp(k + 1); + dp[0] = 1; + + for (const int num : nums) + for (int i = k; i >= num; --i) { + dp[i] += dp[i - num]; + dp[i] %= kMod; + } + + // Substract the cases that're not satisfied. + for (int i = 0; i < k; ++i) + if (sum - i < k) // Both group1 and group2 < k. + ans -= dp[i]; + else + ans -= dp[i] * 2; + + return (ans % kMod + kMod) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/2518. Number of Great Partitions/2518.java b/solutions/2518. Number of Great Partitions/2518.java new file mode 100644 index 00000000000..6094b381fef --- /dev/null +++ b/solutions/2518. Number of Great Partitions/2518.java @@ -0,0 +1,31 @@ +class Solution { + public int countPartitions(int[] nums, int k) { + final int kMod = 1_000_000_007; + final long sum = Arrays.stream(nums).asLongStream().sum(); + long ans = modPow(2, nums.length, kMod); // 2^n % kMod + long[] dp = new long[k + 1]; + dp[0] = 1; + + for (final int num : nums) + for (int i = k; i >= num; --i) { + dp[i] += dp[i - num]; + dp[i] %= kMod; + } + + // Substract the cases that're not satisfied. + for (int i = 0; i < k; ++i) + if (sum - i < k) // Both group1 and group2 < k. + ans -= dp[i]; + else + ans -= dp[i] * 2; + + return (int) ((ans % kMod + kMod) % kMod); + } + + private int modPow(int x, int n, int kMod) { + int res = 1; + for (int i = 0; i < n; ++i) + res = res * x % kMod; + return res; + } +} diff --git a/solutions/2518. Number of Great Partitions/2518.py b/solutions/2518. Number of Great Partitions/2518.py new file mode 100644 index 00000000000..04a9969216e --- /dev/null +++ b/solutions/2518. Number of Great Partitions/2518.py @@ -0,0 +1,20 @@ +class Solution: + def countPartitions(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + summ = sum(nums) + ans = pow(2, len(nums), kMod) # 2^n % kMod + dp = [1] + [0] * k + + for num in nums: + for i in range(k, num - 1, -1): + dp[i] += dp[i - num] + dp[i] %= kMod + + # Substract the cases that're not satisfied. + for i in range(k): + if summ - i < k: # Both group1 and group2 < k. + ans -= dp[i] + else: + ans -= dp[i] * 2 + + return ans % kMod diff --git a/solutions/2519. Count the Number of K-Big Indices/2519.cpp b/solutions/2519. Count the Number of K-Big Indices/2519.cpp new file mode 100644 index 00000000000..d3781d8be3d --- /dev/null +++ b/solutions/2519. Count the Number of K-Big Indices/2519.cpp @@ -0,0 +1,57 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + int kBigIndices(vector& nums, int k) { + const int n = nums.size(); + int ans = 0; + FenwickTree leftTree(n); + FenwickTree rightTree(n); + // left[i] := the number of `nums` < nums[i] with index < i + vector left(n); + // right[i] := the number of `nums` < nums[i] with index > i + vector right(n); + + for (int i = 0; i < n; ++i) { + left[i] = leftTree.get(nums[i] - 1); + leftTree.add(nums[i], 1); + } + + for (int i = n - 1; i >= 0; --i) { + right[i] = rightTree.get(nums[i] - 1); + rightTree.add(nums[i], 1); + } + + for (int i = 0; i < n; ++i) + if (left[i] >= k && right[i] >= k) + ++ans; + + return ans; + } +}; diff --git a/solutions/2519. Count the Number of K-Big Indices/2519.java b/solutions/2519. Count the Number of K-Big Indices/2519.java new file mode 100644 index 00000000000..84a3de36b70 --- /dev/null +++ b/solutions/2519. Count the Number of K-Big Indices/2519.java @@ -0,0 +1,56 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public int kBigIndices(int[] nums, int k) { + final int n = nums.length; + int ans = 0; + FenwickTree leftTree = new FenwickTree(n); + FenwickTree rightTree = new FenwickTree(n); + // left[i] := the number of `nums` < nums[i] with index < i + int[] left = new int[n]; + // right[i] := the number of `nums` < nums[i] with index > i + int[] right = new int[n]; + + for (int i = 0; i < n; ++i) { + left[i] = leftTree.get(nums[i] - 1); + leftTree.add(nums[i], 1); + } + + for (int i = n - 1; i >= 0; --i) { + right[i] = rightTree.get(nums[i] - 1); + rightTree.add(nums[i], 1); + } + + for (int i = 0; i < n; ++i) + if (left[i] >= k && right[i] >= k) + ++ans; + + return ans; + } +} diff --git a/solutions/2519. Count the Number of K-Big Indices/2519.py b/solutions/2519. Count the Number of K-Big Indices/2519.py new file mode 100644 index 00000000000..b3612f7f2a5 --- /dev/null +++ b/solutions/2519. Count the Number of K-Big Indices/2519.py @@ -0,0 +1,40 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def kBigIndices(self, nums: List[int], k: int) -> int: + n = len(nums) + leftTree = FenwickTree(n) + rightTree = FenwickTree(n) + # left[i] := the number of `nums` < nums[i] with index < i + left = [0] * n + # right[i] := the number of `nums` < nums[i] with index > i + right = [0] * n + + for i, num in enumerate(nums): + left[i] = leftTree.get(num - 1) + leftTree.add(num, 1) + + for i in range(n - 1, -1, -1): + right[i] = rightTree.get(nums[i] - 1) + rightTree.add(nums[i], 1) + + return sum(l >= k and r >= k for l, r in zip(left, right)) diff --git a/solutions/252. Meeting Rooms/252.cpp b/solutions/252. Meeting Rooms/252.cpp new file mode 100644 index 00000000000..6e8943c154e --- /dev/null +++ b/solutions/252. Meeting Rooms/252.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool canAttendMeetings(vector>& intervals) { + ranges::sort(intervals); + + for (int i = 1; i < intervals.size(); ++i) + if (intervals[i - 1][1] > intervals[i][0]) + return false; + + return true; + } +}; diff --git a/solutions/252. Meeting Rooms/252.java b/solutions/252. Meeting Rooms/252.java new file mode 100644 index 00000000000..9c40bc0bc12 --- /dev/null +++ b/solutions/252. Meeting Rooms/252.java @@ -0,0 +1,11 @@ +class Solution { + public boolean canAttendMeetings(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + + for (int i = 1; i < intervals.length; ++i) + if (intervals[i - 1][1] > intervals[i][0]) + return false; + + return true; + } +} diff --git a/solutions/252. Meeting Rooms/252.py b/solutions/252. Meeting Rooms/252.py new file mode 100644 index 00000000000..ff5f023d41b --- /dev/null +++ b/solutions/252. Meeting Rooms/252.py @@ -0,0 +1,9 @@ +class Solution: + def canAttendMeetings(self, intervals: List[List[int]]) -> bool: + intervals.sort() + + for i in range(1, len(intervals)): + if intervals[i - 1][1] > intervals[i][0]: + return False + + return True diff --git a/solutions/2520. Count the Digits That Divide a Number/2520.cpp b/solutions/2520. Count the Digits That Divide a Number/2520.cpp new file mode 100644 index 00000000000..15f63c05be9 --- /dev/null +++ b/solutions/2520. Count the Digits That Divide a Number/2520.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int countDigits(int num) { + int ans = 0; + + for (int n = num; n > 0; n /= 10) + if (num % (n % 10) == 0) + ++ans; + + return ans; + } +}; diff --git a/solutions/2520. Count the Digits That Divide a Number/2520.java b/solutions/2520. Count the Digits That Divide a Number/2520.java new file mode 100644 index 00000000000..4994f990cd3 --- /dev/null +++ b/solutions/2520. Count the Digits That Divide a Number/2520.java @@ -0,0 +1,11 @@ +class Solution { + public int countDigits(int num) { + int ans = 0; + + for (int n = num; n > 0; n /= 10) + if (num % (n % 10) == 0) + ++ans; + + return ans; + } +} diff --git a/solutions/2520. Count the Digits That Divide a Number/2520.py b/solutions/2520. Count the Digits That Divide a Number/2520.py new file mode 100644 index 00000000000..6a787cd76d7 --- /dev/null +++ b/solutions/2520. Count the Digits That Divide a Number/2520.py @@ -0,0 +1,3 @@ +class Solution: + def countDigits(self, num: int) -> int: + return sum(num % int(d) == 0 for d in str(num)) diff --git a/solutions/2521. Distinct Prime Factors of Product of Array/2521.cpp b/solutions/2521. Distinct Prime Factors of Product of Array/2521.cpp new file mode 100644 index 00000000000..976219521e3 --- /dev/null +++ b/solutions/2521. Distinct Prime Factors of Product of Array/2521.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int distinctPrimeFactors(vector& nums) { + unordered_set primes; + + for (const int num : nums) + addPrimeFactors(primes, num); + + return primes.size(); + } + + private: + void addPrimeFactors(unordered_set& primes, int num) { + for (int divisor = 2; divisor <= num; ++divisor) + if (num % divisor == 0) { + primes.insert(divisor); + while (num % divisor == 0) + num /= divisor; + } + } +}; diff --git a/solutions/2521. Distinct Prime Factors of Product of Array/2521.java b/solutions/2521. Distinct Prime Factors of Product of Array/2521.java new file mode 100644 index 00000000000..ad91444706e --- /dev/null +++ b/solutions/2521. Distinct Prime Factors of Product of Array/2521.java @@ -0,0 +1,19 @@ +class Solution { + public int distinctPrimeFactors(int[] nums) { + Set primes = new HashSet<>(); + + for (final int num : nums) + addPrimeFactors(primes, num); + + return primes.size(); + } + + private void addPrimeFactors(Set primes, int num) { + for (int divisor = 2; divisor <= num; ++divisor) + if (num % divisor == 0) { + primes.add(divisor); + while (num % divisor == 0) + num /= divisor; + } + } +} diff --git a/solutions/2521. Distinct Prime Factors of Product of Array/2521.py b/solutions/2521. Distinct Prime Factors of Product of Array/2521.py new file mode 100644 index 00000000000..e94c39ca5f6 --- /dev/null +++ b/solutions/2521. Distinct Prime Factors of Product of Array/2521.py @@ -0,0 +1,15 @@ +class Solution: + def distinctPrimeFactors(self, nums: List[int]) -> int: + primes = set() + + for num in nums: + self._addPrimeFactors(primes, num) + + return len(primes) + + def _addPrimeFactors(self, primes: Set[int], num: int) -> None: + for divisor in range(2, num + 1): + if num % divisor == 0: + primes.add(divisor) + while num % divisor == 0: + num //= divisor diff --git a/solutions/2522. Partition String Into Substrings With Values at Most K/2522.cpp b/solutions/2522. Partition String Into Substrings With Values at Most K/2522.cpp new file mode 100644 index 00000000000..6bd7bab1daa --- /dev/null +++ b/solutions/2522. Partition String Into Substrings With Values at Most K/2522.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minimumPartition(string s, int k) { + int ans = 1; + long curr = 0; + + for (const char c : s) { + curr = curr * 10 + c - '0'; + if (curr > k) { + curr = c - '0'; + ++ans; + } + if (curr > k) + return -1; + } + + return ans; + } +}; diff --git a/solutions/2522. Partition String Into Substrings With Values at Most K/2522.java b/solutions/2522. Partition String Into Substrings With Values at Most K/2522.java new file mode 100644 index 00000000000..e5b1eeb7846 --- /dev/null +++ b/solutions/2522. Partition String Into Substrings With Values at Most K/2522.java @@ -0,0 +1,18 @@ +class Solution { + public int minimumPartition(String s, int k) { + int ans = 1; + long curr = 0; + + for (final char c : s.toCharArray()) { + curr = curr * 10 + c - '0'; + if (curr > k) { + curr = c - '0'; + ++ans; + } + if (curr > k) + return -1; + } + + return ans; + } +} diff --git a/solutions/2522. Partition String Into Substrings With Values at Most K/2522.py b/solutions/2522. Partition String Into Substrings With Values at Most K/2522.py new file mode 100644 index 00000000000..4d136bfb9bf --- /dev/null +++ b/solutions/2522. Partition String Into Substrings With Values at Most K/2522.py @@ -0,0 +1,14 @@ +class Solution: + def minimumPartition(self, s: str, k: int) -> int: + ans = 1 + curr = 0 + + for c in s: + curr = curr * 10 + int(c) + if curr > k: + curr = int(c) + ans += 1 + if curr > k: + return -1 + + return ans diff --git a/solutions/2523. Closest Prime Numbers in Range/2523.cpp b/solutions/2523. Closest Prime Numbers in Range/2523.cpp new file mode 100644 index 00000000000..ec232e74557 --- /dev/null +++ b/solutions/2523. Closest Prime Numbers in Range/2523.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + vector closestPrimes(int left, int right) { + const vector isPrime = sieveEratosthenes(right + 1); + vector primes; + + for (int i = left; i <= right; ++i) + if (isPrime[i]) + primes.push_back(i); + + if (primes.size() < 2) + return {-1, -1}; + + int minDiff = INT_MAX; + int num1 = -1; + int num2 = -1; + + for (int i = 1; i < primes.size(); ++i) { + const int diff = primes[i] - primes[i - 1]; + if (diff < minDiff) { + minDiff = diff; + num1 = primes[i - 1]; + num2 = primes[i]; + } + } + + return {num1, num2}; + } + + private: + vector sieveEratosthenes(int n) { + vector isPrime(n, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +}; diff --git a/solutions/2523. Closest Prime Numbers in Range/2523.java b/solutions/2523. Closest Prime Numbers in Range/2523.java new file mode 100644 index 00000000000..3ca7f2feab6 --- /dev/null +++ b/solutions/2523. Closest Prime Numbers in Range/2523.java @@ -0,0 +1,40 @@ +class Solution { + public int[] closestPrimes(int left, int right) { + final boolean[] isPrime = sieveEratosthenes(right + 1); + List primes = new ArrayList<>(); + + for (int i = left; i <= right; ++i) + if (isPrime[i]) + primes.add(i); + + if (primes.size() < 2) + return new int[] {-1, -1}; + + int minDiff = Integer.MAX_VALUE; + int num1 = -1; + int num2 = -1; + + for (int i = 1; i < primes.size(); ++i) { + final int diff = prime.get(i) - prime.get(i - 1); + if (diff < minDiff) { + minDiff = diff; + num1 = prime.get(i - 1); + num2 = prime.get(i); + } + } + + return new int[] {num1, num2}; + } + + private boolean[] sieveEratosthenes(int n) { + boolean[] isPrime = new boolean[n]; + Arrays.fill(isPrime, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +} diff --git a/solutions/2523. Closest Prime Numbers in Range/2523.py b/solutions/2523. Closest Prime Numbers in Range/2523.py new file mode 100644 index 00000000000..b375b19080f --- /dev/null +++ b/solutions/2523. Closest Prime Numbers in Range/2523.py @@ -0,0 +1,30 @@ +class Solution: + def closestPrimes(self, left: int, right: int) -> List[int]: + isPrime = self._sieveEratosthenes(right + 1) + primes = [i for i in range(left, right + 1) if isPrime[i]] + + if len(primes) < 2: + return [-1, -1] + + minDiff = math.inf + num1 = -1 + num2 = -1 + + for a, b in zip(primes, primes[1:]): + diff = b - a + if diff < minDiff: + minDiff = diff + num1 = a + num2 = b + + return [num1, num2] + + def _sieveEratosthenes(self, n: int) -> List[bool]: + isPrime = [True] * n + isPrime[0] = False + isPrime[1] = False + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n, i): + isPrime[j] = False + return isPrime diff --git a/solutions/2524. Maximum Frequency Score of a Subarray/2524.cpp b/solutions/2524. Maximum Frequency Score of a Subarray/2524.cpp new file mode 100644 index 00000000000..6caa7525ca0 --- /dev/null +++ b/solutions/2524. Maximum Frequency Score of a Subarray/2524.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + int maxFrequencyScore(vector& nums, int k) { + unordered_map count; + + for (int i = 0; i < k; ++i) + ++count[nums[i]]; + + int sum = getInitialSum(count); + int ans = sum; + + for (int i = k; i < nums.size(); ++i) { + // Remove the leftmost number that's out-of-window. + const int leftNum = nums[i - k]; + sum = (sum - modPow(leftNum, count[leftNum]) + kMod) % kMod; + // After decreasing its frequency, if it's still > 0, then add it back. + if (--count[leftNum] > 0) + sum = (sum + modPow(leftNum, count[leftNum])) % kMod; + // Otherwise, remove it from the count map. + else + count.erase(leftNum); + // Add the current number. Similarly, remove the current score like above. + const int rightNum = nums[i]; + if (count[rightNum] > 0) + sum = (sum - modPow(rightNum, count[rightNum]) + kMod) % kMod; + sum = (sum + modPow(rightNum, ++count[rightNum])) % kMod; + ans = max(ans, sum); + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + int getInitialSum(const unordered_map& count) { + long sum = 0; + for (const auto& [num, freq] : count) + sum = (sum + modPow(num, freq)) % kMod; + return sum; + } + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/2524. Maximum Frequency Score of a Subarray/2524.java b/solutions/2524. Maximum Frequency Score of a Subarray/2524.java new file mode 100644 index 00000000000..b75d6702272 --- /dev/null +++ b/solutions/2524. Maximum Frequency Score of a Subarray/2524.java @@ -0,0 +1,51 @@ +class Solution { + public int maxFrequencyScore(int[] nums, int k) { + Map count = new HashMap<>(); + + for (int i = 0; i < k; ++i) + count.merge(nums[i], 1, Integer::sum); + + int sum = getInitialSum(count); + int ans = sum; + + for (int i = k; i < nums.length; ++i) { + // Remove the leftmost number that's out-of-window. + final int leftNum = nums[i - k]; + sum = (sum - modPow(leftNum, count.get(leftNum)) + kMod) % kMod; + // After decreasing its frequency, if it's still > 0, then add it back. + if (count.merge(leftNum, -1, Integer::sum) > 0) + sum = (sum + modPow(leftNum, count.get(leftNum))) % kMod; + // Otherwise, remove it from the count map. + else + count.remove(leftNum); + // Add the current number. Similarly, remove the current score like above. + final int rightNum = nums[i]; + if (count.getOrDefault(rightNum, 0) > 0) + sum = (sum - modPow(rightNum, count.get(rightNum)) + kMod) % kMod; + sum = (sum + modPow(rightNum, count.merge(rightNum, 1, Integer::sum))) % kMod; + ans = Math.max(ans, sum); + } + + return ans; + } + + private static final int kMod = 1_000_000_007; + + private int getInitialSum(Map count) { + int sum = 0; + for (Map.Entry entry : count.entrySet()) { + final int num = entry.getKey(); + final int freq = entry.getValue(); + sum = (sum + modPow(num, freq)) % kMod; + } + return sum; + } + + private int modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return (int) (x * modPow(x % kMod, (n - 1)) % kMod); + return modPow(x * x % kMod, (n / 2)) % kMod; + } +} diff --git a/solutions/2524. Maximum Frequency Score of a Subarray/2524.py b/solutions/2524. Maximum Frequency Score of a Subarray/2524.py new file mode 100644 index 00000000000..98c7feee12a --- /dev/null +++ b/solutions/2524. Maximum Frequency Score of a Subarray/2524.py @@ -0,0 +1,33 @@ +class Solution: + def maxFrequencyScore(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + count = collections.Counter(nums[:k]) + summ = self._getInitialSumm(count, kMod) + ans = summ + + for i in range(k, len(nums)): + # Remove the leftmost number that's out-of-window. + leftNum = nums[i - k] + summ = (summ - pow(leftNum, count[leftNum], kMod) + kMod) % kMod + # After decreasing its frequency, if it's still > 0, then add it back. + count[leftNum] -= 1 + if count[leftNum] > 0: + summ = (summ + pow(leftNum, count[leftNum], kMod)) % kMod + # Otherwise, remove it from the count map. + else: + del count[leftNum] + # Add the current number. Similarly, remove the current score like above. + rightNum = nums[i] + if count[rightNum] > 0: + summ = (summ - pow(rightNum, count[rightNum], kMod) + kMod) % kMod + count[rightNum] += 1 + summ = (summ + pow(rightNum, count[rightNum], kMod)) % kMod + ans = max(ans, summ) + + return ans + + def _getInitialSumm(self, count: Dict[int, int], kMod: int) -> int: + summ = 0 + for num, freq in count.items(): + summ = (summ + pow(num, freq, kMod)) % kMod + return summ diff --git a/solutions/2525. Categorize Box According to Criteria/2525.cpp b/solutions/2525. Categorize Box According to Criteria/2525.cpp new file mode 100644 index 00000000000..c686b04d993 --- /dev/null +++ b/solutions/2525. Categorize Box According to Criteria/2525.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + string categorizeBox(int length, int width, int height, int mass) { + const bool isBulky = + length >= 10000 || width >= 10000 || height >= 10000 || + static_cast(length) * width * height >= 1'000'000'000; + const bool isHeavy = mass >= 100; + if (isBulky && isHeavy) + return "Both"; + if (isBulky) + return "Bulky"; + if (isHeavy) + return "Heavy"; + return "Neither"; + } +}; diff --git a/solutions/2525. Categorize Box According to Criteria/2525.java b/solutions/2525. Categorize Box According to Criteria/2525.java new file mode 100644 index 00000000000..b32187e7794 --- /dev/null +++ b/solutions/2525. Categorize Box According to Criteria/2525.java @@ -0,0 +1,14 @@ +class Solution { + public String categorizeBox(int length, int width, int height, int mass) { + final boolean isBulky = length >= 10000 || width >= 10000 || height >= 10000 || + (long) length * width * height >= 1_000_000_000; + final boolean isHeavy = mass >= 100; + if (isBulky && isHeavy) + return "Both"; + if (isBulky) + return "Bulky"; + if (isHeavy) + return "Heavy"; + return "Neither"; + } +} diff --git a/solutions/2525. Categorize Box According to Criteria/2525.py b/solutions/2525. Categorize Box According to Criteria/2525.py new file mode 100644 index 00000000000..9bdf708ef49 --- /dev/null +++ b/solutions/2525. Categorize Box According to Criteria/2525.py @@ -0,0 +1,12 @@ +class Solution: + def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: + isBulky = length >= 10000 or width >= 10000 or height >= 10000 or length * \ + width * height >= 1_000_000_000 + isHeavy = mass >= 100 + if isBulky and isHeavy: + return 'Both' + if isBulky: + return 'Bulky' + if isHeavy: + return 'Heavy' + return 'Neither' diff --git a/solutions/2526. Find Consecutive Integers from a Data Stream/2526.cpp b/solutions/2526. Find Consecutive Integers from a Data Stream/2526.cpp new file mode 100644 index 00000000000..5622b7dff94 --- /dev/null +++ b/solutions/2526. Find Consecutive Integers from a Data Stream/2526.cpp @@ -0,0 +1,22 @@ +class DataStream { + public: + DataStream(int value, int k) : value(value), k(k) {} + + bool consec(int num) { + if (q.size() == k) { + if (q.front() == value) + --count; + q.pop(); + } + if (num == value) + ++count; + q.push(num); + return count == k; + } + + private: + const int value; + const int k; + queue q; + int count = 0; +}; diff --git a/solutions/2526. Find Consecutive Integers from a Data Stream/2526.java b/solutions/2526. Find Consecutive Integers from a Data Stream/2526.java new file mode 100644 index 00000000000..9eb11b38966 --- /dev/null +++ b/solutions/2526. Find Consecutive Integers from a Data Stream/2526.java @@ -0,0 +1,20 @@ +class DataStream { + public DataStream(int value, int k) { + this.value = value; + this.k = k; + } + + public boolean consec(int num) { + if (q.size() == k && q.poll() == value) + --count; + if (num == value) + ++count; + q.offer(num); + return count == k; + } + + private int value; + private int k; + private Queue q = new ArrayDeque<>(); + private int count = 0; +} diff --git a/solutions/2526. Find Consecutive Integers from a Data Stream/2526.py b/solutions/2526. Find Consecutive Integers from a Data Stream/2526.py new file mode 100644 index 00000000000..8676a0a8647 --- /dev/null +++ b/solutions/2526. Find Consecutive Integers from a Data Stream/2526.py @@ -0,0 +1,14 @@ +class DataStream: + def __init__(self, value: int, k: int): + self.value = value + self.k = k + self.q = deque() + self.count = 0 + + def consec(self, num: int) -> bool: + if len(self.q) == self.k and self.q.popleft() == self.value: + self.count -= 1 + if num == self.value: + self.count += 1 + self.q.append(num) + return self.count == self.k diff --git a/solutions/2527. Find Xor-Beauty of Array/2527.cpp b/solutions/2527. Find Xor-Beauty of Array/2527.cpp new file mode 100644 index 00000000000..a2a734755ff --- /dev/null +++ b/solutions/2527. Find Xor-Beauty of Array/2527.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int xorBeauty(vector& nums) { + return accumulate(nums.begin(), nums.end(), 0, bit_xor<>()); + } +}; diff --git a/solutions/2527. Find Xor-Beauty of Array/2527.java b/solutions/2527. Find Xor-Beauty of Array/2527.java new file mode 100644 index 00000000000..a1bbff8f069 --- /dev/null +++ b/solutions/2527. Find Xor-Beauty of Array/2527.java @@ -0,0 +1,5 @@ +class Solution { + public int xorBeauty(int[] nums) { + return Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt(); + } +} diff --git a/solutions/2527. Find Xor-Beauty of Array/2527.py b/solutions/2527. Find Xor-Beauty of Array/2527.py new file mode 100644 index 00000000000..88d7a91227b --- /dev/null +++ b/solutions/2527. Find Xor-Beauty of Array/2527.py @@ -0,0 +1,3 @@ +class Solution: + def xorBeauty(self, nums: List[int]) -> int: + return functools.reduce(operator.xor, nums) diff --git a/solutions/2528. Maximize the Minimum Powered City/2528.cpp b/solutions/2528. Maximize the Minimum Powered City/2528.cpp new file mode 100644 index 00000000000..9098f21962d --- /dev/null +++ b/solutions/2528. Maximize the Minimum Powered City/2528.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + long long maxPower(vector& stations, int r, int k) { + long left = ranges::min(stations); + long right = accumulate(stations.begin(), stations.end(), 0L) + k + 1; + + while (left < right) { + const long mid = (left + right) / 2; + if (check(stations, r, k, mid)) + left = mid + 1; + else + right = mid; + } + + return left - 1; + } + + private: + // Returns true if each city can have at least `minPower`. + bool check(vector stations, int r, int additionalStations, + long minPower) { + const int n = stations.size(); + // Initilaize `power` as the 0-th city's power - stations[r]. + long power = accumulate(stations.begin(), stations.begin() + r, 0L); + + for (int i = 0; i < n; ++i) { + if (i + r < n) + power += stations[i + r]; // `power` = sum(stations[i - r..i + r]). + if (power < minPower) { + const long requiredPower = minPower - power; + // There're not enough stations to plant. + if (requiredPower > additionalStations) + return false; + // Greedily plant `requiredPower` power stations in the farthest place + // to cover as many cities as possible. + stations[min(n - 1, i + r)] += requiredPower; + additionalStations -= requiredPower; + power += requiredPower; + } + if (i - r >= 0) + power -= stations[i - r]; + } + + return true; + } +}; diff --git a/solutions/2528. Maximize the Minimum Powered City/2528.java b/solutions/2528. Maximize the Minimum Powered City/2528.java new file mode 100644 index 00000000000..a94d7c4dbe0 --- /dev/null +++ b/solutions/2528. Maximize the Minimum Powered City/2528.java @@ -0,0 +1,46 @@ +class Solution { + public long maxPower(int[] stations, int r, int k) { + long left = Arrays.stream(stations).min().getAsInt(); + long right = Arrays.stream(stations).asLongStream().sum() + k + 1; + + while (left < right) { + final long mid = (left + right) / 2; + if (check(stations.clone(), r, k, mid)) + left = mid + 1; + else + right = mid; + } + + return left - 1; + } + + // Returns true if each city can have at least `minPower`. + boolean check(int[] stations, int r, int additionalStations, long minPower) { + final int n = stations.length; + // Initilaize `power` as the 0-th city's power - stations[r]. + long power = 0; + + for (int i = 0; i < r; ++i) + power += stations[i]; + + for (int i = 0; i < n; ++i) { + if (i + r < n) + power += stations[i + r]; // `power` = sum(stations[i - r..i + r]). + if (power < minPower) { + final long requiredPower = minPower - power; + // There're not enough stations to plant. + if (requiredPower > additionalStations) + return false; + // Greedily plant `requiredPower` power stations in the farthest place + // to cover as many cities as possible. + stations[Math.min(n - 1, i + r)] += requiredPower; + additionalStations -= requiredPower; + power += requiredPower; + } + if (i - r >= 0) + power -= stations[i - r]; + } + + return true; + } +} diff --git a/solutions/2528. Maximize the Minimum Powered City/2528.py b/solutions/2528. Maximize the Minimum Powered City/2528.py new file mode 100644 index 00000000000..53414ab8adf --- /dev/null +++ b/solutions/2528. Maximize the Minimum Powered City/2528.py @@ -0,0 +1,37 @@ +class Solution: + def maxPower(self, stations: List[int], r: int, k: int) -> int: + n = len(stations) + left = min(stations) + right = sum(stations) + k + 1 + + def check(stations: List[int], additionalStations: int, minPower: int) -> bool: + """Returns True if each city can have at least `minPower`.""" + # Initilaize `power` as the 0-th city's power - stations[r]. + power = sum(stations[:r]) + + for i in range(n): + if i + r < n: + power += stations[i + r] # `power` = sum(stations[i - r..i + r]). + if power < minPower: + requiredPower = minPower - power + # There're not enough stations to plant. + if requiredPower > additionalStations: + return False + # Greedily plant `requiredPower` power stations in the farthest place + # to cover as many cities as possible. + stations[min(n - 1, i + r)] += requiredPower + additionalStations -= requiredPower + power += requiredPower + if i - r >= 0: + power -= stations[i - r] + + return True + + while left < right: + mid = (left + right) // 2 + if check(stations.copy(), k, mid): + left = mid + 1 + else: + right = mid + + return left - 1 diff --git a/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.cpp b/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.cpp new file mode 100644 index 00000000000..dd00e81af36 --- /dev/null +++ b/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int maximumCount(vector& nums) { + return max(ranges::count_if(nums, [](int num) { return num > 0; }), + ranges::count_if(nums, [](int num) { return num < 0; })); + } +}; diff --git a/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.java b/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.java new file mode 100644 index 00000000000..ed54ea5c48c --- /dev/null +++ b/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.java @@ -0,0 +1,6 @@ +class Solution { + public int maximumCount(int[] nums) { + return (int) Math.max(Arrays.stream(nums).filter(num -> num > 0).count(), + Arrays.stream(nums).filter(num -> num < 0).count()); + } +} diff --git a/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.py b/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.py new file mode 100644 index 00000000000..ee45ea08a7e --- /dev/null +++ b/solutions/2529. Maximum Count of Positive Integer and Negative Integer/2529.py @@ -0,0 +1,3 @@ +class Solution: + def maximumCount(self, nums: List[int]) -> int: + return max(sum(num > 0 for num in nums), sum(num < 0 for num in nums)) diff --git a/solutions/253. Meeting Rooms II/253-2.cpp b/solutions/253. Meeting Rooms II/253-2.cpp new file mode 100644 index 00000000000..ba8cf992844 --- /dev/null +++ b/solutions/253. Meeting Rooms II/253-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minMeetingRooms(vector>& intervals) { + const int n = intervals.size(); + int ans = 0; + vector starts; + vector ends; + + for (const vector& interval : intervals) { + starts.push_back(interval[0]); + ends.push_back(interval[1]); + } + + ranges::sort(starts); + ranges::sort(ends); + + for (int i = 0, j = 0; i < n; ++i) + if (starts[i] < ends[j]) + ++ans; + else + ++j; + + return ans; + } +}; diff --git a/solutions/253. Meeting Rooms II/253-2.java b/solutions/253. Meeting Rooms II/253-2.java new file mode 100644 index 00000000000..07b5bdbc909 --- /dev/null +++ b/solutions/253. Meeting Rooms II/253-2.java @@ -0,0 +1,25 @@ +class Solution { + public int minMeetingRooms(int[][] intervals) { + final int n = intervals.length; + int ans = 0; + int[] starts = new int[n]; + int[] ends = new int[n]; + + for (int i = 0; i < n; ++i) { + starts[i] = intervals[i][0]; + ends[i] = intervals[i][1]; + } + + Arrays.sort(starts); + Arrays.sort(ends); + + // J points to ends + for (int i = 0, j = 0; i < n; ++i) + if (starts[i] < ends[j]) + ++ans; + else + ++j; + + return ans; + } +} diff --git a/solutions/253. Meeting Rooms II/253-2.py b/solutions/253. Meeting Rooms II/253-2.py new file mode 100644 index 00000000000..61a668b0f6f --- /dev/null +++ b/solutions/253. Meeting Rooms II/253-2.py @@ -0,0 +1,22 @@ +class Solution: + def minMeetingRooms(self, intervals: List[List[int]]) -> int: + n = len(intervals) + ans = 0 + starts = [] + ends = [] + + for start, end in intervals: + starts.append(start) + ends.append(end) + + starts.sort() + ends.sort() + + j = 0 + for i in range(n): + if starts[i] < ends[j]: + ans += 1 + else: + j += 1 + + return ans diff --git a/solutions/253. Meeting Rooms II/253.cpp b/solutions/253. Meeting Rooms II/253.cpp new file mode 100644 index 00000000000..77f4dca56ee --- /dev/null +++ b/solutions/253. Meeting Rooms II/253.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minMeetingRooms(vector>& intervals) { + ranges::sort(intervals); + + // Store the end times of each room. + priority_queue, greater<>> minHeap; + + for (const vector& interval : intervals) { + // There's no overlap, so we can reuse the same room. + if (!minHeap.empty() && interval[0] >= minHeap.top()) + minHeap.pop(); + minHeap.push(interval[1]); + } + + return minHeap.size(); + } +}; diff --git a/solutions/253. Meeting Rooms II/253.java b/solutions/253. Meeting Rooms II/253.java new file mode 100644 index 00000000000..35fbdcb8f5a --- /dev/null +++ b/solutions/253. Meeting Rooms II/253.java @@ -0,0 +1,17 @@ +class Solution { + public int minMeetingRooms(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> (a[0] - b[0])); + + // Store the end times of each room. + Queue minHeap = new PriorityQueue<>(); + + for (int[] interval : intervals) { + // There's no overlap, so we can reuse the same room. + if (!minHeap.isEmpty() && interval[0] >= minHeap.peek()) + minHeap.poll(); + minHeap.offer(interval[1]); + } + + return minHeap.size(); + } +} diff --git a/solutions/253. Meeting Rooms II/253.py b/solutions/253. Meeting Rooms II/253.py new file mode 100644 index 00000000000..fb4256cd79c --- /dev/null +++ b/solutions/253. Meeting Rooms II/253.py @@ -0,0 +1,11 @@ +class Solution: + def minMeetingRooms(self, intervals: List[List[int]]) -> int: + minHeap = [] # Store the end times of each room. + + for start, end in sorted(intervals): + # There's no overlap, so we can reuse the same room. + if minHeap and start >= minHeap[0]: + heapq.heappop(minHeap) + heapq.heappush(minHeap, end) + + return len(minHeap) diff --git a/solutions/2530. Maximal Score After Applying K Operations/2530.cpp b/solutions/2530. Maximal Score After Applying K Operations/2530.cpp new file mode 100644 index 00000000000..bfeef4ed2d1 --- /dev/null +++ b/solutions/2530. Maximal Score After Applying K Operations/2530.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + long long maxKelements(vector& nums, int k) { + long ans = 0; + priority_queue maxHeap; + + for (const int num : nums) + maxHeap.push(num); + + for (int i = 0; i < k; ++i) { + const int num = maxHeap.top(); + maxHeap.pop(); + ans += num; + maxHeap.push((num + 2) / 3); + } + + return ans; + } +}; diff --git a/solutions/2530. Maximal Score After Applying K Operations/2530.java b/solutions/2530. Maximal Score After Applying K Operations/2530.java new file mode 100644 index 00000000000..54540b812f2 --- /dev/null +++ b/solutions/2530. Maximal Score After Applying K Operations/2530.java @@ -0,0 +1,17 @@ +class Solution { + public long maxKelements(int[] nums, int k) { + long ans = 0; + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + for (final int num : nums) + maxHeap.offer(num); + + for (int i = 0; i < k; ++i) { + final int num = maxHeap.poll(); + ans += num; + maxHeap.offer((num + 2) / 3); + } + + return ans; + } +} diff --git a/solutions/2530. Maximal Score After Applying K Operations/2530.py b/solutions/2530. Maximal Score After Applying K Operations/2530.py new file mode 100644 index 00000000000..351c716110f --- /dev/null +++ b/solutions/2530. Maximal Score After Applying K Operations/2530.py @@ -0,0 +1,12 @@ +class Solution: + def maxKelements(self, nums: List[int], k: int) -> int: + ans = 0 + maxHeap = [-num for num in nums] + heapq.heapify(maxHeap) + + for _ in range(k): + num = -heapq.heappop(maxHeap) + ans += num + heapq.heappush(maxHeap, -math.ceil(num / 3)) + + return ans diff --git a/solutions/2531. Make Number of Distinct Characters Equal/2531.cpp b/solutions/2531. Make Number of Distinct Characters Equal/2531.cpp new file mode 100644 index 00000000000..1f349e06144 --- /dev/null +++ b/solutions/2531. Make Number of Distinct Characters Equal/2531.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + bool isItPossible(string word1, string word2) { + const vector count1 = getCount(word1); + const vector count2 = getCount(word2); + const int distinct1 = getDistinct(count1); + const int distinct2 = getDistinct(count2); + + for (int i = 0; i < 26; ++i) + for (int j = 0; j < 26; ++j) { + if (count1[i] == 0 || count2[j] == 0) + continue; + if (i == j) { + // Swapping the same letters won't change the number of distinct + // letters in each string, so just check if `distinct1 == distinct2`. + if (distinct1 == distinct2) + return true; + continue; + } + // The calculation is meaningful only when i != j. + // Swap ('a' + i) in word1 with ('a' + j) in word2. + const int distinctAfterSwap1 = + distinct1 - (count1[i] == 1) + (count1[j] == 0); + const int distinctAfterSwap2 = + distinct2 - (count2[j] == 1) + (count2[i] == 0); + if (distinctAfterSwap1 == distinctAfterSwap2) + return true; + } + + return false; + } + + private: + vector getCount(const string& s) { + vector count(26); + for (const char c : s) + ++count[c - 'a']; + return count; + } + + int getDistinct(const vector& count) { + return ranges::count_if(count, [](const int c) { return c > 0; }); + } +}; diff --git a/solutions/2531. Make Number of Distinct Characters Equal/2531.java b/solutions/2531. Make Number of Distinct Characters Equal/2531.java new file mode 100644 index 00000000000..0c7301c2563 --- /dev/null +++ b/solutions/2531. Make Number of Distinct Characters Equal/2531.java @@ -0,0 +1,42 @@ +class Solution { + public boolean isItPossible(String word1, String word2) { + final int[] count1 = getCount(word1); + final int[] count2 = getCount(word2); + final int distinct1 = getDistinct(count1); + final int distinct2 = getDistinct(count2); + + for (int i = 0; i < 26; ++i) + for (int j = 0; j < 26; ++j) { + if (count1[i] == 0 || count2[j] == 0) + continue; + if (i == j) { + // Swapping the same letters won't change the number of distinct + // letters in each string, so just check if `distinct1 == distinct2`. + if (distinct1 == distinct2) + return true; + continue; + } + // The calculation is meaningful only when i != j. + // Swap ('a' + i) in word1 with ('a' + j) in word2. + final int distinctAfterSwap1 = + distinct1 - (count1[i] == 1 ? 1 : 0) + (count1[j] == 0 ? 1 : 0); + final int distinctAfterSwap2 = + distinct2 - (count2[j] == 1 ? 1 : 0) + (count2[i] == 0 ? 1 : 0); + if (distinctAfterSwap1 == distinctAfterSwap2) + return true; + } + + return false; + } + + private int[] getCount(final String s) { + int[] count = new int[26]; + for (final char c : s.toCharArray()) + ++count[c - 'a']; + return count; + } + + private int getDistinct(int[] count) { + return (int) Arrays.stream(count).filter(c -> c > 0).count(); + } +} diff --git a/solutions/2531. Make Number of Distinct Characters Equal/2531.py b/solutions/2531. Make Number of Distinct Characters Equal/2531.py new file mode 100644 index 00000000000..5e7b995814c --- /dev/null +++ b/solutions/2531. Make Number of Distinct Characters Equal/2531.py @@ -0,0 +1,23 @@ +class Solution: + def isItPossible(self, word1: str, word2: str) -> bool: + count1 = collections.Counter(word1) + count2 = collections.Counter(word2) + distinct1 = len(count1) + distinct2 = len(count2) + + for a in count1: + for b in count2: + if a == b: + # Swapping the same letters won't change the number of distinct + # letters in each string, so just check if `distinct1 == distinct2`. + if distinct1 == distinct2: + return True + continue + # The calculation is meaningful only when a != b + # Swap a in word1 with b in word2. + distinctAfterSwap1 = distinct1 - (count1[a] == 1) + (count1[b] == 0) + distinctAfterSwap2 = distinct2 - (count2[b] == 1) + (count2[a] == 0) + if distinctAfterSwap1 == distinctAfterSwap2: + return True + + return False diff --git a/solutions/2532. Time to Cross a Bridge/2532.cpp b/solutions/2532. Time to Cross a Bridge/2532.cpp new file mode 100644 index 00000000000..95d1261f3bc --- /dev/null +++ b/solutions/2532. Time to Cross a Bridge/2532.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + int findCrossingTime(int n, int k, vector>& time) { + int ans = 0; + using P = pair; + // (leftToRight + rightToLeft, i) + priority_queue

leftBridgeQueue; + priority_queue

rightBridgeQueue; + // (time to be idle, i) + priority_queue, greater<>> leftWorkers; + priority_queue, greater<>> rightWorkers; + + for (int i = 0; i < k; ++i) + leftBridgeQueue.emplace( + /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i); + + while (n > 0 || !rightBridgeQueue.empty() || !rightWorkers.empty()) { + // Idle left workers get on the left bridge. + while (!leftWorkers.empty() && leftWorkers.top().first <= ans) { + const int i = leftWorkers.top().second; + leftWorkers.pop(); + leftBridgeQueue.emplace( + /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i); + } + // Idle right workers get on the right bridge. + while (!rightWorkers.empty() && rightWorkers.top().first <= ans) { + const int i = rightWorkers.top().second; + rightWorkers.pop(); + rightBridgeQueue.emplace( + /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i); + } + + if (!rightBridgeQueue.empty()) { + // If the bridge is free, the worker waiting on the right side of the + // bridge gets to cross the bridge. If more than one worker is waiting + // on the right side, the one with the lowest efficiency crosses first. + const int i = rightBridgeQueue.top().second; + rightBridgeQueue.pop(); + ans += /*rightToLeft*/ time[i][2]; + leftWorkers.emplace(ans + /*putNew*/ time[i][3], i); + } else if (!leftBridgeQueue.empty() && n > 0) { + // If the bridge is free and no worker is waiting on the right side, and + // at least one box remains at the old warehouse, the worker on the left + // side of the river gets to cross the bridge. If more than one worker + // is waiting on the left side, the one with the lowest efficiency + // crosses first. + const int i = leftBridgeQueue.top().second; + leftBridgeQueue.pop(); + ans += /*leftToRight*/ time[i][0]; + rightWorkers.emplace(ans + /*pickOld*/ time[i][1], i); + --n; + } else { + // Advance the time of the last crossing worker. + ans = min( + !leftWorkers.empty() && n > 0 ? leftWorkers.top().first : INT_MAX, + !rightWorkers.empty() ? rightWorkers.top().first : INT_MAX); + } + } + + return ans; + } +}; diff --git a/solutions/2532. Time to Cross a Bridge/2532.java b/solutions/2532. Time to Cross a Bridge/2532.java new file mode 100644 index 00000000000..311530713cf --- /dev/null +++ b/solutions/2532. Time to Cross a Bridge/2532.java @@ -0,0 +1,68 @@ +class Solution { + public int findCrossingTime(int n, int k, int[][] time) { + int ans = 0; + // (leftToRight + rightToLeft, i) + Queue> leftBridgeQueue = createMaxHeap(); + Queue> rightBridgeQueue = createMaxHeap(); + // (time to be idle, i) + Queue> leftWorkers = createMinHeap(); + Queue> rightWorkers = createMinHeap(); + + for (int i = 0; i < k; ++i) + leftBridgeQueue.offer(new Pair<>( + /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i)); + + while (n > 0 || !rightBridgeQueue.isEmpty() || !rightWorkers.isEmpty()) { + // Idle left workers get on the left bridge. + while (!leftWorkers.isEmpty() && leftWorkers.peek().getKey() <= ans) { + final int i = leftWorkers.poll().getValue(); + leftBridgeQueue.offer(new Pair<>( + /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i)); + } + // Idle right workers get on the right bridge. + while (!rightWorkers.isEmpty() && rightWorkers.peek().getKey() <= ans) { + final int i = rightWorkers.poll().getValue(); + rightBridgeQueue.offer(new Pair<>( + /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i)); + } + + if (!rightBridgeQueue.isEmpty()) { + // If the bridge is free, the worker waiting on the right side of the + // bridge gets to cross the bridge. If more than one worker is waiting + // on the right side, the one with the lowest efficiency crosses first. + final int i = rightBridgeQueue.poll().getValue(); + ans += /*rightToLeft*/ time[i][2]; + leftWorkers.offer(new Pair<>(ans + /*putNew*/ time[i][3], i)); + } else if (!leftBridgeQueue.isEmpty() && n > 0) { + // If the bridge is free and no worker is waiting on the right side, and + // at least one box remains at the old warehouse, the worker on the left + // side of the river gets to cross the bridge. If more than one worker + // is waiting on the left side, the one with the lowest efficiency + // crosses first. + final int i = leftBridgeQueue.poll().getValue(); + ans += /*leftToRight*/ time[i][0]; + rightWorkers.offer(new Pair<>(ans + /*pickOld*/ time[i][1], i)); + --n; + } else { + // Advance the time of the last crossing worker. + ans = Math.min(!leftWorkers.isEmpty() && n > 0 ? leftWorkers.peek().getKey() + : Integer.MAX_VALUE, + !rightWorkers.isEmpty() ? rightWorkers.peek().getKey() : Integer.MAX_VALUE); + } + } + + return ans; + } + + private Queue> createMaxHeap() { + return new PriorityQueue<>((a, b) + -> a.getKey().equals(b.getKey()) ? b.getValue() - a.getValue() + : b.getKey() - a.getKey()); + } + + private Queue> createMinHeap() { + return new PriorityQueue<>((a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue() - b.getValue() + : a.getKey() - b.getKey()); + } +} diff --git a/solutions/2532. Time to Cross a Bridge/2532.py b/solutions/2532. Time to Cross a Bridge/2532.py new file mode 100644 index 00000000000..f581a7c105c --- /dev/null +++ b/solutions/2532. Time to Cross a Bridge/2532.py @@ -0,0 +1,46 @@ +class Solution: + def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int: + ans = 0 + # (leftToRight + rightToLeft, i) + leftBridgeQueue = [(-leftToRight - rightToLeft, -i) + for i, (leftToRight, pickOld, rightToLeft, pickNew) in enumerate(time)] + rightBridgeQueue = [] + # (time to be idle, i) + leftWorkers = [] + rightWorkers = [] + + heapq.heapify(leftBridgeQueue) + + while n > 0 or rightBridgeQueue or rightWorkers: + # Idle left workers get on the left bridge. + while leftWorkers and leftWorkers[0][0] <= ans: + i = heapq.heappop(leftWorkers)[1] + leftWorkers.pop() + heapq.heappush(leftBridgeQueue, (-time[i][0] - time[i][2], -i)) + # Idle right workers get on the right bridge. + while rightWorkers and rightWorkers[0][0] <= ans: + i = heapq.heappop(rightWorkers)[1] + heapq.heappush(rightBridgeQueue, (-time[i][0] - time[i][2], -i)) + if rightBridgeQueue: + # If the bridge is free, the worker waiting on the right side of the + # bridge gets to cross the bridge. If more than one worker is waiting + # on the right side, the one with the lowest efficiency crosses first. + i = -heapq.heappop(rightBridgeQueue)[1] + ans += time[i][2] + heapq.heappush(leftWorkers, (ans + time[i][3], i)) + elif leftBridgeQueue and n > 0: + # If the bridge is free and no worker is waiting on the right side, and + # at least one box remains at the old warehouse, the worker on the left + # side of the river gets to cross the bridge. If more than one worker + # is waiting on the left side, the one with the lowest efficiency + # crosses first. + i = -heapq.heappop(leftBridgeQueue)[1] + ans += time[i][0] + heapq.heappush(rightWorkers, (ans + time[i][1], i)) + n -= 1 + else: + # Advance the time of the last crossing worker. + ans = min(leftWorkers[0][0] if leftWorkers and n > 0 else math.inf, + rightWorkers[0][0] if rightWorkers else math.inf) + + return ans diff --git a/solutions/2533. Number of Good Binary Strings/2533.cpp b/solutions/2533. Number of Good Binary Strings/2533.cpp new file mode 100644 index 00000000000..a80a34651c8 --- /dev/null +++ b/solutions/2533. Number of Good Binary Strings/2533.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int goodBinaryStrings(int minLength, int maxLength, int oneGroup, + int zeroGroup) { + constexpr int kMod = 1'000'000'007; + // dp[i] := the number of good binary strings with length i + vector dp(maxLength + 1); + dp[0] = 1; // "" + + for (int i = 0; i <= maxLength; ++i) + // There are good binary strings with length i, so we can append + // consecutive 0s or 1s after it. + if (dp[i] > 0) { + const int appendZeros = i + zeroGroup; + if (appendZeros <= maxLength) { + dp[appendZeros] += dp[i]; + dp[appendZeros] %= kMod; + } + const int appendOnes = i + oneGroup; + if (appendOnes <= maxLength) { + dp[appendOnes] += dp[i]; + dp[appendOnes] %= kMod; + } + } + + return accumulate(dp.begin() + minLength, dp.end(), 0L) % kMod; + } +}; diff --git a/solutions/2533. Number of Good Binary Strings/2533.java b/solutions/2533. Number of Good Binary Strings/2533.java new file mode 100644 index 00000000000..5d232e87c7d --- /dev/null +++ b/solutions/2533. Number of Good Binary Strings/2533.java @@ -0,0 +1,31 @@ +class Solution { + public int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) { + final int kMod = 1_000_000_007; + // dp[i] := the number of good binary strings with length i + int[] dp = new int[maxLength + 1]; + dp[0] = 1; // "" + + for (int i = 0; i <= maxLength; ++i) + // There are good binary strings with length i, so we can append + // consecutive 0s or 1s after it. + if (dp[i] > 0) { + final int appendZeros = i + zeroGroup; + if (appendZeros <= maxLength) { + dp[appendZeros] += dp[i]; + dp[appendZeros] %= kMod; + } + final int appendOnes = i + oneGroup; + if (appendOnes <= maxLength) { + dp[appendOnes] += dp[i]; + dp[appendOnes] %= kMod; + } + } + + int ans = 0; + for (int i = minLength; i <= maxLength; ++i) { + ans += dp[i]; + ans %= kMod; + } + return ans; + } +} diff --git a/solutions/2533. Number of Good Binary Strings/2533.py b/solutions/2533. Number of Good Binary Strings/2533.py new file mode 100644 index 00000000000..fd175fd9c74 --- /dev/null +++ b/solutions/2533. Number of Good Binary Strings/2533.py @@ -0,0 +1,20 @@ +class Solution: + def goodBinaryStrings(self, minLength: int, maxLength: int, oneGroup: int, zeroGroup: int) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of good binary strings with length i + dp = [1] + [0] * maxLength + + for i in range(maxLength + 1): + # There are good binary strings with length i, so we can append + # consecutive 0s or 1s after it. + if dp[i] > 0: + appendZeros = i + zeroGroup + if appendZeros <= maxLength: + dp[appendZeros] += dp[i] + dp[appendZeros] %= kMod + appendOnes = i + oneGroup + if appendOnes <= maxLength: + dp[appendOnes] += dp[i] + dp[appendOnes] %= kMod + + return sum(dp[minLength:]) % kMod diff --git a/solutions/2534. Time Taken to Cross the Door/2534.cpp b/solutions/2534. Time Taken to Cross the Door/2534.cpp new file mode 100644 index 00000000000..4a71b381973 --- /dev/null +++ b/solutions/2534. Time Taken to Cross the Door/2534.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector timeTaken(vector& arrival, vector& state) { + const int n = arrival.size(); + vector ans(n); + // qs[0] := enter, qs[1] := exit + vector> qs(2); + int time = 0; + int d = 1; + + for (int i = 0; i < n; ++i) { + popQueues(time, d, arrival[i], qs, ans); + // If the door was not used in the previous second, then the person who + // wants to exit goes first. + if (arrival[i] > time) { + time = arrival[i]; // Forward `time` to now. + d = 1; + } + qs[state[i]].push(i); + } + + popQueues(time, d, 200'000, qs, ans); + return ans; + } + + private: + void popQueues(int& time, int& d, int arrivalTime, vector>& qs, + vector& ans) { + while (arrivalTime > time && (!qs[0].empty() || !qs[1].empty())) { + if (qs[d].empty()) + d ^= 1; + ans[qs[d].front()] = time, qs[d].pop(); + ++time; + } + } +}; diff --git a/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.cpp b/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.cpp new file mode 100644 index 00000000000..41d0f2630fe --- /dev/null +++ b/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int differenceOfSum(vector& nums) { + const int elementSum = accumulate(nums.begin(), nums.end(), 0); + const int allDigitSum = getAllDigitSum(nums); + return abs(elementSum - allDigitSum); + } + + private: + int getAllDigitSum(const vector& nums) { + int allDigitSum = 0; + for (const int num : nums) + allDigitSum += getDigitSum(num); + return allDigitSum; + } + + int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +}; diff --git a/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.java b/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.java new file mode 100644 index 00000000000..bae127f6ff7 --- /dev/null +++ b/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.java @@ -0,0 +1,23 @@ +class Solution { + public int differenceOfSum(int[] nums) { + final int elementSum = Arrays.stream(nums).sum(); + final int allDigitSum = getAllDigitSum(nums); + return Math.abs(elementSum - allDigitSum); + } + + private int getAllDigitSum(int[] nums) { + int allDigitSum = 0; + for (final int num : nums) + allDigitSum += getDigitSum(num); + return allDigitSum; + } + + private int getDigitSum(int num) { + int digitSum = 0; + while (num > 0) { + digitSum += num % 10; + num /= 10; + } + return digitSum; + } +} diff --git a/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.py b/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.py new file mode 100644 index 00000000000..b84de08efc9 --- /dev/null +++ b/solutions/2535. Difference Between Element Sum and Digit Sum of an Array/2535.py @@ -0,0 +1,11 @@ +class Solution: + def differenceOfSum(self, nums: List[int]) -> int: + elementSum = sum(nums) + digitSum = self._getAllDigitSum(nums) + return abs(elementSum - digitSum) + + def _getAllDigitSum(self, nums: List[int]) -> int: + return sum(self._getDigitSum(num) for num in nums) + + def _getDigitSum(self, num: int) -> int: + return sum(int(digit) for digit in str(num)) diff --git a/solutions/2536. Increment Submatrices by One/2536.cpp b/solutions/2536. Increment Submatrices by One/2536.cpp new file mode 100644 index 00000000000..57667726cab --- /dev/null +++ b/solutions/2536. Increment Submatrices by One/2536.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector> rangeAddQueries(int n, vector>& queries) { + vector> ans(n, vector(n)); + vector> prefix(n, vector(n + 1)); + + for (const vector& query : queries) { + const int row1 = query[0]; + const int col1 = query[1]; + const int row2 = query[2]; + const int col2 = query[3]; + for (int i = row1; i <= row2; ++i) { + ++prefix[i][col1]; + --prefix[i][col2 + 1]; + } + } + + for (int i = 0; i < n; ++i) { + int sum = 0; + for (int j = 0; j < n; ++j) { + sum += prefix[i][j]; + ans[i][j] = sum; + } + } + + return ans; + } +}; diff --git a/solutions/2537. Count the Number of Good Subarrays/2537.cpp b/solutions/2537. Count the Number of Good Subarrays/2537.cpp new file mode 100644 index 00000000000..c79bcac742c --- /dev/null +++ b/solutions/2537. Count the Number of Good Subarrays/2537.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long countGood(vector& nums, int k) { + long ans = 0; + int pairs = 0; + unordered_map count; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + // Since there're count[r] nums[r]s, including nums[r] to the window will + // increase the number of good subarrays by count[r]. + pairs += count[nums[r]]++; + while (pairs >= k) + pairs -= --count[nums[l++]]; + // nums[0..r], nums[1..r], ..., nums[l - 1..r] are good subarrays, so add + // l to `ans`. + ans += l; + } + + return ans; + } +}; diff --git a/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.cpp b/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.cpp new file mode 100644 index 00000000000..b89c91ecdb8 --- /dev/null +++ b/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + long long maxOutput(int n, vector>& edges, vector& price) { + int ans = 0; + vector> tree(n); + // maxSums[i] := the maximum the sum of path rooted at i + vector maxSums(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + // Precalculate `maxSums`. + maxSum(tree, 0, /*prev=*/-1, maxSums, price); + reroot(tree, 0, /*prev=*/-1, /*parentSum=*/0, maxSums, price, ans); + return ans; + } + + private: + int maxSum(const vector>& tree, int u, int prev, + vector& maxSums, const vector& price) { + int maxChildSum = 0; + for (const int v : tree[u]) + if (prev != v) + maxChildSum = max(maxChildSum, maxSum(tree, v, u, maxSums, price)); + return maxSums[u] = price[u] + maxChildSum; + } + + void reroot(const vector>& tree, int u, int prev, int parentSum, + const vector& maxSums, const vector& price, int& ans) { + // Get the top two subtree sums and the top one node index. + int maxSubtreeSum1 = 0; + int maxSubtreeSum2 = 0; + int maxNode = -1; + for (const int v : tree[u]) { + if (v == prev) + continue; + if (maxSums[v] > maxSubtreeSum1) { + maxSubtreeSum2 = maxSubtreeSum1; + maxSubtreeSum1 = maxSums[v]; + maxNode = v; + } else if (maxSums[v] > maxSubtreeSum2) { + maxSubtreeSum2 = maxSums[v]; + } + } + + if (tree[u].size() == 1) + ans = max({ans, parentSum, maxSubtreeSum1}); + + for (const int v : tree[u]) { + if (v == prev) + continue; + const int nextParentSum = + (v == maxNode ? price[u] + max(parentSum, maxSubtreeSum2) + : price[u] + max(parentSum, maxSubtreeSum1)); + reroot(tree, v, u, nextParentSum, maxSums, price, ans); + } + } +}; diff --git a/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.java b/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.java new file mode 100644 index 00000000000..34126c73e39 --- /dev/null +++ b/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.java @@ -0,0 +1,62 @@ +class Solution { + public long maxOutput(int n, int[][] edges, int[] price) { + List[] tree = new List[n]; + // maxSums[i] := the maximum the sum of path rooted at i + int[] maxSums = new int[n]; + + for (int i = 0; i < n; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + // Precalculate `maxSums`. + maxSum(tree, 0, /*prev=*/-1, maxSums, price); + reroot(tree, 0, /*prev=*/-1, /*parentSum=*/0, maxSums, price); + return (long) ans; + } + + private int ans = 0; + + private int maxSum(List[] tree, int u, int prev, int[] maxSums, int[] price) { + int maxChildSum = 0; + for (final int v : tree[u]) + if (prev != v) + maxChildSum = Math.max(maxChildSum, maxSum(tree, v, u, maxSums, price)); + return maxSums[u] = price[u] + maxChildSum; + } + + private void reroot(List[] tree, int u, int prev, int parentSum, int[] maxSums, + int[] price) { + // Get top two sums and top one node index. + int maxSubtreeSum1 = 0; + int maxSubtreeSum2 = 0; + int maxNode = -1; + for (final int v : tree[u]) { + if (v == prev) + continue; + if (maxSums[v] > maxSubtreeSum1) { + maxSubtreeSum2 = maxSubtreeSum1; + maxSubtreeSum1 = maxSums[v]; + maxNode = v; + } else if (maxSums[v] > maxSubtreeSum2) { + maxSubtreeSum2 = maxSums[v]; + } + } + + if (tree[u].size() == 1) + ans = Math.max(ans, Math.max(parentSum, maxSubtreeSum1)); + + for (final int v : tree[u]) { + if (v == prev) + continue; + final int nextParentSum = (v == maxNode ? price[u] + Math.max(parentSum, maxSubtreeSum2) + : price[u] + Math.max(parentSum, maxSubtreeSum1)); + reroot(tree, v, u, nextParentSum, maxSums, price); + } + } +} diff --git a/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.py b/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.py new file mode 100644 index 00000000000..2ba8d6d2828 --- /dev/null +++ b/solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.py @@ -0,0 +1,50 @@ +class Solution: + def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int: + ans = 0 + tree = [[] for _ in range(n)] + maxSums = [0] * n # maxSums[i] := the maximum the sum of path rooted at i + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def maxSum(u: int, prev: int) -> int: + maxChildSum = 0 + for v in tree[u]: + if prev != v: + maxChildSum = max(maxChildSum, maxSum(v, u)) + maxSums[u] = price[u] + maxChildSum + return maxSums[u] + + # Precalculate `maxSums`. + maxSum(0, -1) + + def reroot(u: int, prev: int, parentSum: int) -> None: + nonlocal ans + # Get the top two subtree sums and the top one node index. + maxSubtreeSum1 = 0 + maxSubtreeSum2 = 0 + maxNode = -1 + for v in tree[u]: + if v == prev: + continue + if maxSums[v] > maxSubtreeSum1: + maxSubtreeSum2 = maxSubtreeSum1 + maxSubtreeSum1 = maxSums[v] + maxNode = v + elif maxSums[v] > maxSubtreeSum2: + maxSubtreeSum2 = maxSums[v] + + if len(tree[u]) == 1: + ans = max(ans, parentSum, maxSubtreeSum1) + + for v in tree[u]: + if v == prev: + continue + nextParentSum = \ + price[u] + max(parentSum, maxSubtreeSum2) if v == maxNode else \ + price[u] + max(parentSum, maxSubtreeSum1) + reroot(v, u, nextParentSum) + + reroot(0, -1, 0) + return ans diff --git a/solutions/2539. Count the Number of Good Subsequences/2539.cpp b/solutions/2539. Count the Number of Good Subsequences/2539.cpp new file mode 100644 index 00000000000..2b0604f242d --- /dev/null +++ b/solutions/2539. Count the Number of Good Subsequences/2539.cpp @@ -0,0 +1,65 @@ +class Solution { + public: + int countGoodSubsequences(string s) { + // For each frequency f in [1, max(freq)], start with "" and calculate how + // many subsequences can be constructed with each letter's frequency = f. + // + // e.g. s = "abb", so f = max(freq) = 2. + // + // For f = 1, with 1 way to build "", choose any 'a' to construct a good + // subseq, so # of good subsequences = 1 + 1 * (1, 1) = 2 ("", "a"). Next, + // add 'b' and # of good subsequences = 2 + 2 * (2, 1) = 6 ("", "a", "b1", + // "b2", "ab1", "ab2"). So, the number of good subsequences for f = 1 is 5 + // since we need to exclude "". + // + // For f = 2, with 1 way to build "", choose any two 'b's to construct a + // good subseq, so # of good subsequences = 1 + 1 * (2, 2) is 2 ("", "bb"). + // So, the number of good subsequences for f = 2 = 1 since we need to + // exclude "". + // + // Therefore, the number of good subsequences for "aab" = 5 + 1 = 6. + int ans = 0; + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + const int maxFreq = ranges::max(count); + const auto [fact, invFact] = getFactAndInvFact(maxFreq); + + for (int freq = 1; freq <= maxFreq; ++freq) { + long numSubseqs = 1; // "" + for (const int charFreq : count) + if (charFreq >= freq) + numSubseqs = (numSubseqs + // + numSubseqs * nCk(charFreq, freq, fact, invFact)) % + kMod; + ans += numSubseqs - 1; // Minus "". + ans %= kMod; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + pair, vector> getFactAndInvFact(int n) { + vector fact(n + 1); + vector invFact(n + 1); + vector inv(n + 1); + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return {fact, invFact}; + } + + int nCk(int n, int k, const vector& fact, const vector& invFact) { + return fact[n] * invFact[k] % kMod * invFact[n - k] % kMod; + } +}; diff --git a/solutions/2539. Count the Number of Good Subsequences/2539.java b/solutions/2539. Count the Number of Good Subsequences/2539.java new file mode 100644 index 00000000000..d56e6d625cd --- /dev/null +++ b/solutions/2539. Count the Number of Good Subsequences/2539.java @@ -0,0 +1,65 @@ +class Solution { + public int countGoodSubsequences(String s) { + // For each frequency f in [1, max(freq)], start with "" and calculate how + // many subsequences can be finalructed with each letter's frequency = f. + // + // e.g. s = "abb", so f = max(freq) = 2. + // + // For f = 1, with 1 way to build "", choose any 'a' to finalruct a good + // subseq, so # of good subsequences = 1 + 1 * (1, 1) = 2 ("", "a"). Next, add + // 'b' and # of good subsequences = 2 + 2 * (2, 1) = 6 ("", "a", "b1", "b2", + // "ab1", "ab2"). So, the number of good subsequences for f = 1 is 5 since we need to + // exclude "". + // + // For f = 2, with 1 way to build "", choose any two 'b's to finalruct a + // good subseq, so # of good subsequences = 1 + 1 * (2, 2) is 2 ("", "bb"). So, + // the number of good subsequences for f = 2 = 1 since we need to exclude "". + // + // Therefore, the number of good subsequences for "aab" = 5 + 1 = 6. + final int kMod = 1_000_000_007; + int ans = 0; + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + final int maxFreq = Arrays.stream(count).max().getAsInt(); + final long[][] factAndInvFact = getFactAndInvFact(maxFreq); + final long[] fact = factAndInvFact[0]; + final long[] invFact = factAndInvFact[1]; + + for (int freq = 1; freq <= maxFreq; ++freq) { + long numSubseqs = 1; // "" + for (final int charFreq : count) + if (charFreq >= freq) + numSubseqs = (numSubseqs + // + numSubseqs * nCk(charFreq, freq, fact, invFact)) % + kMod; + ans += numSubseqs - 1; // Minus "". + ans %= kMod; + } + + return ans; + } + + private static final int kMod = 1_000_000_007; + + private long[][] getFactAndInvFact(int n) { + long[] fact = new long[n + 1]; + long[] invFact = new long[n + 1]; + long[] inv = new long[n + 1]; + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return new long[][] {fact, invFact}; + } + + private int nCk(int n, int k, long[] fact, long[] invFact) { + return (int) (fact[n] * invFact[k] % kMod * invFact[n - k] % kMod); + } +} diff --git a/solutions/2539. Count the Number of Good Subsequences/2539.py b/solutions/2539. Count the Number of Good Subsequences/2539.py new file mode 100644 index 00000000000..6b4d373ae53 --- /dev/null +++ b/solutions/2539. Count the Number of Good Subsequences/2539.py @@ -0,0 +1,27 @@ +class Solution: + def countGoodSubsequences(self, s: str) -> int: + kMod = 1_000_000_007 + ans = 0 + count = collections.Counter(s) + + @functools.lru_cache(None) + def fact(i: int) -> int: + return 1 if i <= 1 else i * fact(i - 1) % kMod + + @functools.lru_cache(None) + def inv(i: int) -> int: + return pow(i, kMod - 2, kMod) + + @functools.lru_cache(None) + def nCk(n: int, k: int) -> int: + return fact(n) * inv(fact(k)) * inv(fact(n - k)) % kMod + + for freq in range(1, max(count.values()) + 1): + numSubseqs = 1 # "" + for charFreq in count.values(): + if charFreq >= freq: + numSubseqs = numSubseqs * (1 + nCk(charFreq, freq)) % kMod + ans += numSubseqs - 1 # Minus "". + ans %= kMod + + return ans diff --git a/solutions/254. Factor Combinations/254.cpp b/solutions/254. Factor Combinations/254.cpp new file mode 100644 index 00000000000..dd29f934f55 --- /dev/null +++ b/solutions/254. Factor Combinations/254.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector> getFactors(int n) { + vector> ans; + dfs(n, 2, {}, ans); // The minimum factor is 2. + return ans; + } + + private: + void dfs(int n, int s, vector&& path, vector>& ans) { + if (n <= 1) { + if (path.size() > 1) + ans.push_back(path); + return; + } + + for (int i = s; i <= n; ++i) + if (n % i == 0) { + path.push_back(i); + dfs(n / i, i, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/254. Factor Combinations/254.java b/solutions/254. Factor Combinations/254.java new file mode 100644 index 00000000000..65bc9191c01 --- /dev/null +++ b/solutions/254. Factor Combinations/254.java @@ -0,0 +1,22 @@ +class Solution { + public List> getFactors(int n) { + List> ans = new ArrayList<>(); + dfs(n, 2, new ArrayList<>(), ans); // The minimum factor is 2. + return ans; + } + + private void dfs(int n, int s, List path, List> ans) { + if (n == 1) { + if (path.size() > 1) + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = s; i <= n; ++i) + if (n % i == 0) { + path.add(i); + dfs(n / i, i, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/254. Factor Combinations/254.py b/solutions/254. Factor Combinations/254.py new file mode 100644 index 00000000000..9fefc4043fc --- /dev/null +++ b/solutions/254. Factor Combinations/254.py @@ -0,0 +1,18 @@ +class Solution: + def getFactors(self, n: int) -> List[List[int]]: + ans = [] + + def dfs(n: int, s: int, path: List[int]) -> None: + if n <= 1: + if len(path) > 1: + ans.append(path.copy()) + return + + for i in range(s, n + 1): + if n % i == 0: + path.append(i) + dfs(n // i, i, path) + path.pop() + + dfs(n, 2, []) # The minimum factor is 2. + return ans diff --git a/solutions/2540. Minimum Common Value/2540.cpp b/solutions/2540. Minimum Common Value/2540.cpp new file mode 100644 index 00000000000..5219f61f7ed --- /dev/null +++ b/solutions/2540. Minimum Common Value/2540.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int getCommon(vector& nums1, vector& nums2) { + int i = 0; // nums1's index + int j = 0; // nums2's index + + while (i < nums1.size() && j < nums2.size()) { + if (nums1[i] == nums2[j]) + return nums1[i]; + if (nums1[i] < nums2[j]) + ++i; + else + ++j; + } + + return -1; + } +}; diff --git a/solutions/2540. Minimum Common Value/2540.java b/solutions/2540. Minimum Common Value/2540.java new file mode 100644 index 00000000000..a019d02befa --- /dev/null +++ b/solutions/2540. Minimum Common Value/2540.java @@ -0,0 +1,17 @@ +class Solution { + public int getCommon(int[] nums1, int[] nums2) { + int i = 0; // nums1's index + int j = 0; // nums2's index + + while (i < nums1.length && j < nums1.length) { + if (nums1[i] == nums2[j]) + return nums1[i]; + if (nums1[i] < nums2[j]) + ++i; + else + ++j; + } + + return -1; + } +} diff --git a/solutions/2540. Minimum Common Value/2540.py b/solutions/2540. Minimum Common Value/2540.py new file mode 100644 index 00000000000..68b7af63a65 --- /dev/null +++ b/solutions/2540. Minimum Common Value/2540.py @@ -0,0 +1,14 @@ +class Solution: + def getCommon(self, nums1: List[int], nums2: List[int]) -> int: + i = 0 # nums1's index + j = 0 # nums2's index + + while i < len(nums1) and j < len(nums2): + if nums1[i] == nums2[j]: + return nums1[i] + if nums1[i] < nums2[j]: + i += 1 + else: + j += 1 + + return -1 diff --git a/solutions/2541. Minimum Operations to Make Array Equal II/2541.cpp b/solutions/2541. Minimum Operations to Make Array Equal II/2541.cpp new file mode 100644 index 00000000000..0f19781d839 --- /dev/null +++ b/solutions/2541. Minimum Operations to Make Array Equal II/2541.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long minOperations(vector& nums1, vector& nums2, int k) { + if (k == 0) + return nums1 == nums2 ? 0 : -1; + + long ans = 0; + // the number of increments - the number of decrements + long opsDiff = 0; + + for (int i = 0; i < nums1.size(); ++i) { + const int diff = nums1[i] - nums2[i]; + if (diff == 0) + continue; + if (diff % k != 0) + return -1; + const int ops = diff / k; + opsDiff += ops; + ans += abs(ops); + } + + return opsDiff == 0 ? ans / 2 : -1; + } +}; diff --git a/solutions/2541. Minimum Operations to Make Array Equal II/2541.java b/solutions/2541. Minimum Operations to Make Array Equal II/2541.java new file mode 100644 index 00000000000..76e305238e5 --- /dev/null +++ b/solutions/2541. Minimum Operations to Make Array Equal II/2541.java @@ -0,0 +1,22 @@ +class Solution { + public long minOperations(int[] nums1, int[] nums2, int k) { + if (k == 0) + return Arrays.equals(nums1, nums2) ? 0 : -1; + + long ans = 0; + long opsDiff = 0; // the number of increments - the number of decrements + + for (int i = 0; i < nums1.length; ++i) { + final int diff = nums1[i] - nums2[i]; + if (diff == 0) + continue; + if (diff % k != 0) + return -1; + final int ops = diff / k; + opsDiff += ops; + ans += Math.abs(ops); + } + + return opsDiff == 0 ? ans / 2 : -1; + } +} diff --git a/solutions/2541. Minimum Operations to Make Array Equal II/2541.py b/solutions/2541. Minimum Operations to Make Array Equal II/2541.py new file mode 100644 index 00000000000..fcae122d3f2 --- /dev/null +++ b/solutions/2541. Minimum Operations to Make Array Equal II/2541.py @@ -0,0 +1,19 @@ +class Solution: + def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int: + if k == 0: + return 0 if nums1 == nums2 else -1 + + ans = 0 + opsDiff = 0 # the number of increments - number of decrements + + for num1, num2 in zip(nums1, nums2): + diff = num1 - num2 + if diff == 0: + continue + if diff % k != 0: + return -1 + ops = diff // k + opsDiff += ops + ans += abs(ops) + + return ans // 2 if opsDiff == 0 else -1 diff --git a/solutions/2542. Maximum Subsequence Score/2542.cpp b/solutions/2542. Maximum Subsequence Score/2542.cpp new file mode 100644 index 00000000000..88c6458acd9 --- /dev/null +++ b/solutions/2542. Maximum Subsequence Score/2542.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + // Same as 1383. Maximum Performance of a Team + long long maxScore(vector& nums1, vector& nums2, int k) { + long ans = 0; + long sum = 0; + // (nums2[i], nums1[i]) sorted by nums2[i] in descending order + vector> A; + priority_queue, greater<>> minHeap; + + for (int i = 0; i < nums1.size(); ++i) + A.emplace_back(nums2[i], nums1[i]); + + ranges::sort(A, greater<>()); + + for (const auto& [num2, num1] : A) { + minHeap.push(num1); + sum += num1; + if (minHeap.size() > k) + sum -= minHeap.top(), minHeap.pop(); + if (minHeap.size() == k) + ans = max(ans, sum * num2); + } + + return ans; + } +}; diff --git a/solutions/2542. Maximum Subsequence Score/2542.java b/solutions/2542. Maximum Subsequence Score/2542.java new file mode 100644 index 00000000000..2cbe18cce6f --- /dev/null +++ b/solutions/2542. Maximum Subsequence Score/2542.java @@ -0,0 +1,28 @@ +class Solution { + // Same as 1383. Maximum Performance of a Team + public long maxScore(int[] nums1, int[] nums2, int k) { + long ans = 0; + long sum = 0; + // (nums2[i], nums1[i]) sorted by nums2[i] in descending order + Pair[] A = new Pair[nums1.length]; + Queue minHeap = new PriorityQueue<>(); + + for (int i = 0; i < nums1.length; ++i) + A[i] = new Pair<>(nums2[i], nums1[i]); + + Arrays.sort(A, (a, b) -> Integer.compare(b.getKey(), a.getKey())); + + for (Pair a : A) { + final int num2 = a.getKey(); + final int num1 = a.getValue(); + minHeap.offer(num1); + sum += num1; + if (minHeap.size() > k) + sum -= minHeap.poll(); + if (minHeap.size() == k) + ans = Math.max(ans, sum * num2); + } + + return ans; + } +} diff --git a/solutions/2542. Maximum Subsequence Score/2542.py b/solutions/2542. Maximum Subsequence Score/2542.py new file mode 100644 index 00000000000..41c391a09cb --- /dev/null +++ b/solutions/2542. Maximum Subsequence Score/2542.py @@ -0,0 +1,19 @@ +class Solution: + # Same as 1383. Maximum Performance of a Team + def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int: + ans = 0 + summ = 0 + # (nums2[i], nums1[i]) sorted by nums2[i] in descending order + A = sorted([(num2, num1) + for num1, num2 in zip(nums1, nums2)], reverse=True) + minHeap = [] + + for num2, num1 in A: + heapq.heappush(minHeap, num1) + summ += num1 + if len(minHeap) > k: + summ -= heapq.heappop(minHeap) + if len(minHeap) == k: + ans = max(ans, summ * num2) + + return ans diff --git a/solutions/2543. Check if Point Is Reachable/2543.cpp b/solutions/2543. Check if Point Is Reachable/2543.cpp new file mode 100644 index 00000000000..65f9c0db6b4 --- /dev/null +++ b/solutions/2543. Check if Point Is Reachable/2543.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool isReachable(unsigned targetX, unsigned targetY) { + return popcount(gcd(targetX, targetY)) == 1; + } +}; diff --git a/solutions/2543. Check if Point Is Reachable/2543.java b/solutions/2543. Check if Point Is Reachable/2543.java new file mode 100644 index 00000000000..1019d139263 --- /dev/null +++ b/solutions/2543. Check if Point Is Reachable/2543.java @@ -0,0 +1,9 @@ +class Solution { + public boolean isReachable(int targetX, int targetY) { + return Integer.bitCount(gcd(targetX, targetY)) == 1; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2543. Check if Point Is Reachable/2543.py b/solutions/2543. Check if Point Is Reachable/2543.py new file mode 100644 index 00000000000..0c4a2eb78a5 --- /dev/null +++ b/solutions/2543. Check if Point Is Reachable/2543.py @@ -0,0 +1,3 @@ +class Solution: + def isReachable(self, targetX: int, targetY: int) -> bool: + return math.gcd(targetX, targetY).bit_count() == 1 diff --git a/solutions/2544. Alternating Digit Sum/2544.cpp b/solutions/2544. Alternating Digit Sum/2544.cpp new file mode 100644 index 00000000000..ee9c0df2808 --- /dev/null +++ b/solutions/2544. Alternating Digit Sum/2544.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int alternateDigitSum(int n) { + int ans = 0; + int sign = 1; + + for (; n > 0; n /= 10) { + sign *= -1; + ans += sign * n % 10; + } + + return sign * ans; + } +}; diff --git a/solutions/2544. Alternating Digit Sum/2544.java b/solutions/2544. Alternating Digit Sum/2544.java new file mode 100644 index 00000000000..9c9cdb9a6d2 --- /dev/null +++ b/solutions/2544. Alternating Digit Sum/2544.java @@ -0,0 +1,13 @@ +class Solution { + public int alternateDigitSum(int n) { + int ans = 0; + int sign = 1; + + for (; n > 0; n /= 10) { + sign *= -1; + ans += sign * n % 10; + } + + return sign * ans; + } +} diff --git a/solutions/2544. Alternating Digit Sum/2544.py b/solutions/2544. Alternating Digit Sum/2544.py new file mode 100644 index 00000000000..bcd71d4b106 --- /dev/null +++ b/solutions/2544. Alternating Digit Sum/2544.py @@ -0,0 +1,11 @@ +class Solution: + def alternateDigitSum(self, n: int) -> int: + ans = 0 + sign = 1 + + while n > 0: + sign *= -1 + ans += n % 10 * sign + n //= 10 + + return sign * ans diff --git a/solutions/2545. Sort the Students by Their Kth Score/2545.cpp b/solutions/2545. Sort the Students by Their Kth Score/2545.cpp new file mode 100644 index 00000000000..eac68af328d --- /dev/null +++ b/solutions/2545. Sort the Students by Their Kth Score/2545.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + vector> sortTheStudents(vector>& score, int k) { + ranges::sort(score, [k](const vector& a, const vector& b) { + return a[k] > b[k]; + }); + return score; + } +}; diff --git a/solutions/2545. Sort the Students by Their Kth Score/2545.java b/solutions/2545. Sort the Students by Their Kth Score/2545.java new file mode 100644 index 00000000000..7c0a741647e --- /dev/null +++ b/solutions/2545. Sort the Students by Their Kth Score/2545.java @@ -0,0 +1,6 @@ +class Solution { + public int[][] sortTheStudents(int[][] score, int k) { + Arrays.sort(score, (a, b) -> b[k] - a[k]); + return score; + } +} diff --git a/solutions/2545. Sort the Students by Their Kth Score/2545.py b/solutions/2545. Sort the Students by Their Kth Score/2545.py new file mode 100644 index 00000000000..c8c0ad21557 --- /dev/null +++ b/solutions/2545. Sort the Students by Their Kth Score/2545.py @@ -0,0 +1,3 @@ +class Solution: + def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]: + return sorted(score, key=lambda a: -a[k]) diff --git a/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.cpp b/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.cpp new file mode 100644 index 00000000000..e2bd94c3bde --- /dev/null +++ b/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool makeStringsEqual(string s, string target) { + return (s.find('1') != string::npos) == (target.find('1') != string::npos); + } +}; diff --git a/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.java b/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.java new file mode 100644 index 00000000000..36c4916c1f0 --- /dev/null +++ b/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.java @@ -0,0 +1,5 @@ +class Solution { + public boolean makeStringsEqual(String s, String target) { + return s.contains("1") == target.contains("1"); + } +} diff --git a/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.py b/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.py new file mode 100644 index 00000000000..161dac1799f --- /dev/null +++ b/solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.py @@ -0,0 +1,3 @@ +class Solution: + def makeStringsEqual(self, s: str, target: str) -> bool: + return ('1' in s) == ('1' in target) diff --git a/solutions/2547. Minimum Cost to Split an Array/2547.cpp b/solutions/2547. Minimum Cost to Split an Array/2547.cpp new file mode 100644 index 00000000000..81b5c71dd6f --- /dev/null +++ b/solutions/2547. Minimum Cost to Split an Array/2547.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int minCost(vector& nums, int k) { + constexpr int kMax = 1001; + const int n = nums.size(); + // trimmedLength[i][j] := trimmed(nums[i..j]).length + vector> trimmedLength(n, vector(n)); + // dp[i] := the minimum cost to split nums[i..n) + vector dp(n + 1, INT_MAX / 2); + + for (int i = 0; i < n; ++i) { + int length = 0; + vector count(kMax); + for (int j = i; j < n; ++j) { + if (++count[nums[j]] == 2) + length += 2; + else if (count[nums[j]] > 2) + ++length; + trimmedLength[i][j] = length; + } + } + + dp[n] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = i; j < n; ++j) + dp[i] = min(dp[i], k + trimmedLength[i][j] + dp[j + 1]); + + return dp[0]; + } +}; diff --git a/solutions/2547. Minimum Cost to Split an Array/2547.java b/solutions/2547. Minimum Cost to Split an Array/2547.java new file mode 100644 index 00000000000..3d6ef7f19ea --- /dev/null +++ b/solutions/2547. Minimum Cost to Split an Array/2547.java @@ -0,0 +1,31 @@ +class Solution { + public int minCost(int[] nums, int k) { + final int kMax = 1001; + final int n = nums.length; + // trimmedLength[i][j] := trimmed(nums[i..j]).length + int[][] trimmedLength = new int[n][n]; + // dp[i] := the minimum cost to split nums[i..n) + int[] dp = new int[n + 1]; + Arrays.fill(dp, Integer.MAX_VALUE / 2); + + for (int i = 0; i < n; ++i) { + int length = 0; + int[] count = new int[kMax]; + for (int j = i; j < n; ++j) { + if (++count[nums[j]] == 2) + length += 2; + else if (count[nums[j]] > 2) + ++length; + trimmedLength[i][j] = length; + } + } + + dp[n] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = i; j < n; ++j) + dp[i] = Math.min(dp[i], k + trimmedLength[i][j] + dp[j + 1]); + + return dp[0]; + } +} diff --git a/solutions/2547. Minimum Cost to Split an Array/2547.py b/solutions/2547. Minimum Cost to Split an Array/2547.py new file mode 100644 index 00000000000..2add2241166 --- /dev/null +++ b/solutions/2547. Minimum Cost to Split an Array/2547.py @@ -0,0 +1,27 @@ +class Solution: + def minCost(self, nums: List[int], k: int) -> int: + kMax = 1001 + n = len(nums) + # trimmedLength[i][j] := trimmed(nums[i..j]).length + trimmedLength = [[0] * n for _ in range(n)] + # dp[i] := the minimum cost to split nums[i..n) + dp = [math.inf] * n + [0] + + for i in range(n): + length = 0 + count = [0] * kMax + for j in range(i, n): + count[nums[j]] += 1 + if count[nums[j]] == 2: + length += 2 + elif count[nums[j]] > 2: + length += 1 + trimmedLength[i][j] = length + + dp[n] = 0 + + for i in range(n - 1, -1, -1): + for j in range(i, n): + dp[i] = min(dp[i], k + trimmedLength[i][j] + dp[j + 1]) + + return dp[0] diff --git a/solutions/2548. Maximum Price to Fill a Bag/2548.cpp b/solutions/2548. Maximum Price to Fill a Bag/2548.cpp new file mode 100644 index 00000000000..42c1c534d17 --- /dev/null +++ b/solutions/2548. Maximum Price to Fill a Bag/2548.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + double maxPrice(vector>& items, int capacity) { + double ans = 0; + + // Sort items based on price/weight. + ranges::sort(items, [](const vector& a, const vector& b) { + return static_cast(a[0]) / a[1] > + static_cast(b[0]) / b[1]; + }); + + for (const vector& item : items) { + const int price = item[0]; + const int weight = item[1]; + // The bag is filled. + if (capacity <= weight) + return ans + price * capacity / static_cast(weight); + ans += price; + capacity -= weight; + } + + return -1; + } +}; diff --git a/solutions/2548. Maximum Price to Fill a Bag/2548.java b/solutions/2548. Maximum Price to Fill a Bag/2548.java new file mode 100644 index 00000000000..a23ab88746d --- /dev/null +++ b/solutions/2548. Maximum Price to Fill a Bag/2548.java @@ -0,0 +1,25 @@ +class Solution { + public double maxPrice(int[][] items, int capacity) { + double ans = 0; + + // Sort items based on price/weight. + Arrays.sort(items, new Comparator() { + @Override + public int compare(int[] a, int[] b) { + return Double.compare((double) b[0] / b[1], (double) a[0] / a[1]); + } + }); + + for (int[] item : items) { + final int price = item[0]; + final int weight = item[1]; + // The bag is filled. + if (capacity <= weight) + return ans + price * capacity / (double) weight; + ans += price; + capacity -= weight; + } + + return -1; + } +} diff --git a/solutions/2548. Maximum Price to Fill a Bag/2548.py b/solutions/2548. Maximum Price to Fill a Bag/2548.py new file mode 100644 index 00000000000..c4953f6dbf1 --- /dev/null +++ b/solutions/2548. Maximum Price to Fill a Bag/2548.py @@ -0,0 +1,13 @@ +class Solution: + def maxPrice(self, items: List[List[int]], capacity: int) -> float: + ans = 0 + + # Sort items based on price//weight. + for price, weight in sorted(items, key=lambda x: -x[0] / x[1]): + # The bag is filled. + if capacity <= weight: + return ans + price * capacity / weight + ans += price + capacity -= weight + + return -1 diff --git a/solutions/2549. Count Distinct Numbers on Board/2549.cpp b/solutions/2549. Count Distinct Numbers on Board/2549.cpp new file mode 100644 index 00000000000..dd1db476ef8 --- /dev/null +++ b/solutions/2549. Count Distinct Numbers on Board/2549.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int distinctIntegers(int n) { + return max(n - 1, 1); + } +}; diff --git a/solutions/2549. Count Distinct Numbers on Board/2549.java b/solutions/2549. Count Distinct Numbers on Board/2549.java new file mode 100644 index 00000000000..3bf45b7878d --- /dev/null +++ b/solutions/2549. Count Distinct Numbers on Board/2549.java @@ -0,0 +1,5 @@ +class Solution { + public int distinctIntegers(int n) { + return Math.max(n - 1, 1); + } +} diff --git a/solutions/2549. Count Distinct Numbers on Board/2549.py b/solutions/2549. Count Distinct Numbers on Board/2549.py new file mode 100644 index 00000000000..66d156beecc --- /dev/null +++ b/solutions/2549. Count Distinct Numbers on Board/2549.py @@ -0,0 +1,3 @@ +class Solution: + def distinctIntegers(self, n: int) -> int: + return max(n - 1, 1) diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.cpp b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.cpp new file mode 100644 index 00000000000..b67a2293708 --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool verifyPreorder(vector& preorder) { + int low = INT_MIN; + stack stack; + + for (const int p : preorder) { + if (p < low) + return false; + while (!stack.empty() && stack.top() < p) + low = stack.top(), stack.pop(); + stack.push(p); + } + + return true; + } +}; diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.java b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.java new file mode 100644 index 00000000000..5b72961a06d --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.java @@ -0,0 +1,16 @@ +class Solution { + public boolean verifyPreorder(int[] preorder) { + int low = Integer.MIN_VALUE; + Deque stack = new ArrayDeque<>(); + + for (final int p : preorder) { + if (p < low) + return false; + while (!stack.isEmpty() && stack.peek() < p) + low = stack.pop(); + stack.push(p); + } + + return true; + } +} diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.py b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.py new file mode 100644 index 00000000000..ebee86a92cf --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-2.py @@ -0,0 +1,13 @@ +class Solution: + def verifyPreorder(self, preorder: List[int]) -> List[int]: + low = -math.inf + stack = [] + + for p in preorder: + if p < low: + return False + while stack and stack[-1] < p: + low = stack.pop() + stack.append(p) + + return True diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.cpp b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.cpp new file mode 100644 index 00000000000..6367bbed48a --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool verifyPreorder(vector& preorder) { + int low = INT_MIN; + int i = -1; + + for (const int p : preorder) { + if (p < low) + return false; + while (i >= 0 && preorder[i] < p) + low = preorder[i--]; + preorder[++i] = p; + } + + return true; + } +}; diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.java b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.java new file mode 100644 index 00000000000..296e070c6e1 --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.java @@ -0,0 +1,16 @@ +class Solution { + public boolean verifyPreorder(int[] preorder) { + int low = Integer.MIN_VALUE; + int i = -1; + + for (final int p : preorder) { + if (p < low) + return false; + while (i >= 0 && preorder[i] < p) + low = preorder[i--]; + preorder[++i] = p; + } + + return true; + } +} diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.py b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.py new file mode 100644 index 00000000000..13da28e6782 --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.py @@ -0,0 +1,15 @@ +class Solution: + def verifyPreorder(self, preorder: List[int]) -> bool: + low = -math.inf + i = -1 + + for p in preorder: + if p < low: + return False + while i >= 0 and preorder[i] < p: + low = preorder[i] + i -= 1 + i += 1 + preorder[i] = p + + return True diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.cpp b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.cpp new file mode 100644 index 00000000000..314d1fbcd5c --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool verifyPreorder(vector& preorder) { + int i = 0; + dfs(preorder, i, INT_MIN, INT_MAX); + return i == preorder.size(); + } + + private: + void dfs(const vector& preorder, int& i, int min, int max) { + if (i == preorder.size()) + return; + if (preorder[i] < min || preorder[i] > max) + return; + + const int val = preorder[i++]; + dfs(preorder, i, min, val); + dfs(preorder, i, val, max); + } +}; diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.java b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.java new file mode 100644 index 00000000000..2ce90cff326 --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.java @@ -0,0 +1,19 @@ +class Solution { + public boolean verifyPreorder(int[] preorder) { + dfs(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE); + return i == preorder.length; + } + + private int i = 0; + + private void dfs(int[] preorder, int mn, int mx) { + if (i == preorder.length) + return; + if (preorder[i] < mn || preorder[i] > mx) + return; + + final int val = preorder[i++]; + dfs(preorder, mn, val); + dfs(preorder, val, mx); + } +} diff --git a/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.py b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.py new file mode 100644 index 00000000000..c1e9b414e99 --- /dev/null +++ b/solutions/255. Verify Preorder Sequence in Binary Search Tree/255.py @@ -0,0 +1,18 @@ +class Solution: + def verifyPreorder(self, preorder: List[int]) -> bool: + i = 0 + + def dfs(min: int, max: int) -> None: + nonlocal i + if i == len(preorder): + return + if preorder[i] < min or preorder[i] > max: + return + + val = preorder[i] + i += 1 + dfs(min, val) + dfs(val, max) + + dfs(-math.inf, math.inf) + return i == len(preorder) diff --git a/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.cpp b/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.cpp new file mode 100644 index 00000000000..9748d9d93c9 --- /dev/null +++ b/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int monkeyMove(int n) { + const int res = modPow(2, n) - 2; + return res < 0 ? res + kMod : res; + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.java b/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.java new file mode 100644 index 00000000000..c1575212329 --- /dev/null +++ b/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.java @@ -0,0 +1,16 @@ +class Solution { + public int monkeyMove(int n) { + final int res = (int) modPow(2, n) - 2; + return res < 0 ? res + kMod : res; + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } +} diff --git a/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.py b/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.py new file mode 100644 index 00000000000..2c129346427 --- /dev/null +++ b/solutions/2550. Count Collisions of Monkeys on a Polygon/2550.py @@ -0,0 +1,5 @@ +class Solution: + def monkeyMove(self, n: int) -> int: + kMod = 1_000_000_007 + res = pow(2, n, kMod) - 2 + return res + kMod if res < 0 else res diff --git a/solutions/2551. Put Marbles in Bags/2551.cpp b/solutions/2551. Put Marbles in Bags/2551.cpp new file mode 100644 index 00000000000..0f15342cc26 --- /dev/null +++ b/solutions/2551. Put Marbles in Bags/2551.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + long long putMarbles(vector& weights, int k) { + // To distribute marbles into k bags, there will be k - 1 cuts. If there's a + // cut after weights[i], then weights[i] and weights[i + 1] will be added to + // the cost. Also, no matter how we cut, weights[0] and weights[n - 1] will + // be counted. So, the goal is to find the max/min k - 1 weights[i] + + // weights[i + 1]. + vector A; // weights[i] + weights[i + 1] + long mn = 0; + long mx = 0; + + for (int i = 0; i + 1 < weights.size(); ++i) + A.push_back(weights[i] + weights[i + 1]); + + ranges::sort(A); + + for (int i = 0; i < k - 1; ++i) { + mn += A[i]; + mx += A[A.size() - 1 - i]; + } + + return mx - mn; + } +}; diff --git a/solutions/2551. Put Marbles in Bags/2551.java b/solutions/2551. Put Marbles in Bags/2551.java new file mode 100644 index 00000000000..bbed37a254a --- /dev/null +++ b/solutions/2551. Put Marbles in Bags/2551.java @@ -0,0 +1,24 @@ +class Solution { + public long putMarbles(int[] weights, int k) { + // To distribute marbles into k bags, there will be k - 1 cuts. If there's a + // cut after weights[i], then weights[i] and weights[i + 1] will be added to + // the cost. Also, no matter how we cut, weights[0] and weights[n - 1] will + // be counted. So, the goal is to find the max/min k - 1 weights[i] + + // weights[i + 1]. + int[] A = new int[weights.length - 1]; // weights[i] + weights[i + 1] + long mn = 0; + long mx = 0; + + for (int i = 0; i < A.length; ++i) + A[i] = weights[i] + weights[i + 1]; + + Arrays.sort(A); + + for (int i = 0; i < k - 1; ++i) { + mn += A[i]; + mx += A[A.length - 1 - i]; + } + + return mx - mn; + } +} diff --git a/solutions/2551. Put Marbles in Bags/2551.py b/solutions/2551. Put Marbles in Bags/2551.py new file mode 100644 index 00000000000..7790b22bef6 --- /dev/null +++ b/solutions/2551. Put Marbles in Bags/2551.py @@ -0,0 +1,11 @@ +class Solution: + def putMarbles(self, weights: List[int], k: int) -> int: + # To distribute marbles into k bags, there will be k - 1 cuts. If there's a + # cut after weights[i], then weights[i] and weights[i + 1] will be added to + # the cost. Also, no matter how we cut, weights[0] and weights[n - 1] will + # be counted. So, the goal is to find the max//min k - 1 weights[i] + + # weights[i + 1]. + + # weights[i] + weights[i + 1] + A = [a + b for a, b in itertools.pairwise(weights)] + return sum(heapq.nlargest(k - 1, A)) - sum(heapq.nsmallest(k - 1, A)) diff --git a/solutions/2552. Count Increasing Quadruplets/2552.cpp b/solutions/2552. Count Increasing Quadruplets/2552.cpp new file mode 100644 index 00000000000..6076d5cebff --- /dev/null +++ b/solutions/2552. Count Increasing Quadruplets/2552.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + long long countQuadruplets(vector& nums) { + long ans = 0; + // dp[j] := the number of triplets (i, j, k) where i < j < k and nums[i] < + // nums[k] < nums[j]. Keep this information for l to use later. + vector dp(nums.size()); + + // k can be treated as l. + for (int k = 2; k < nums.size(); ++k) + // j can be treated as i. + for (int j = 0, numLessThanK = 0; j < k; ++j) + if (nums[j] < nums[k]) { + ++numLessThanK; // nums[i] < nums[k] + // nums[j] < nums[l], so we should add dp[j] since we find a new + // quadruplets for (i, j, k, l). + ans += dp[j]; + + } else if (nums[j] > nums[k]) { + dp[j] += numLessThanK; + } + + return ans; + } +}; diff --git a/solutions/2552. Count Increasing Quadruplets/2552.java b/solutions/2552. Count Increasing Quadruplets/2552.java new file mode 100644 index 00000000000..6d5e19da0a2 --- /dev/null +++ b/solutions/2552. Count Increasing Quadruplets/2552.java @@ -0,0 +1,23 @@ +class Solution { + public long countQuadruplets(int[] nums) { + long ans = 0; + // dp[j] := the number of triplets (i, j, k) where i < j < k and nums[i] < nums[k] < + // nums[j]. Keep this information for l to use later. + int[] dp = new int[nums.size()]; + + // k can be treated as l. + for (int k = 2; k < nums.length; ++k) + // j can be treated as i. + for (int j = 0, numLessThanK = 0; j < k; ++j) + if (nums[j] < nums[k]) { + ++numLessThanK; // nums[i] < nums[k] + // nums[j] < nums[l], so we should add dp[j] since we find a new + // quadruplets for (i, j, k, l). + ans += dp[j]; + } else if (nums[j] > nums[k]) { + dp[j] += numLessThanK; + } + + return ans; + } +} diff --git a/solutions/2552. Count Increasing Quadruplets/2552.py b/solutions/2552. Count Increasing Quadruplets/2552.py new file mode 100644 index 00000000000..2eab02fb761 --- /dev/null +++ b/solutions/2552. Count Increasing Quadruplets/2552.py @@ -0,0 +1,21 @@ +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + ans = 0 + # dp[j] := the number of triplets (i, j, k) where i < j < k and nums[i] < nums[k] < + # nums[j]. Keep this information for l to use later. + dp = [0] * len(nums) + + # k can be treated as l. + for k in range(2, len(nums)): + numLessThanK = 0 + # j can be treated as i. + for j in range(k): + if nums[j] < nums[k]: + numLessThanK += 1 # nums[i] < nums[k] + # nums[j] < nums[l], so we should add dp[j] since we find a new + # quadruplets for (i, j, k, l). + ans += dp[j] + elif nums[j] > nums[k]: + dp[j] += numLessThanK + + return ans diff --git a/solutions/2553. Separate the Digits in an Array/2553.cpp b/solutions/2553. Separate the Digits in an Array/2553.cpp new file mode 100644 index 00000000000..81326f243f6 --- /dev/null +++ b/solutions/2553. Separate the Digits in an Array/2553.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector separateDigits(vector& nums) { + vector ans; + + for (const int num : nums) + for (const char c : to_string(num)) + ans.push_back(c - '0'); + + return ans; + } +}; diff --git a/solutions/2553. Separate the Digits in an Array/2553.java b/solutions/2553. Separate the Digits in an Array/2553.java new file mode 100644 index 00000000000..10ce697d792 --- /dev/null +++ b/solutions/2553. Separate the Digits in an Array/2553.java @@ -0,0 +1,11 @@ +class Solution { + public int[] separateDigits(int[] nums) { + List ans = new ArrayList<>(); + + for (final int num : nums) + for (final char c : String.valueOf(num).toCharArray()) + ans.add(c - '0'); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/2553. Separate the Digits in an Array/2553.py b/solutions/2553. Separate the Digits in an Array/2553.py new file mode 100644 index 00000000000..222099e9849 --- /dev/null +++ b/solutions/2553. Separate the Digits in an Array/2553.py @@ -0,0 +1,3 @@ +class Solution: + def separateDigits(self, nums: List[int]) -> List[int]: + return [int(c) for num in nums for c in str(num)] diff --git a/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.cpp b/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.cpp new file mode 100644 index 00000000000..f49fd3c6682 --- /dev/null +++ b/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxCount(vector& banned, int n, int maxSum) { + int ans = 0; + int sum = 0; + const unordered_set bannedSet{banned.begin(), banned.end()}; + + for (int i = 1; i <= n; ++i) + if (!bannedSet.contains(i) && sum + i <= maxSum) { + ++ans; + sum += i; + } + + return ans; + } +}; diff --git a/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.java b/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.java new file mode 100644 index 00000000000..a5062174384 --- /dev/null +++ b/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.java @@ -0,0 +1,15 @@ +class Solution { + public int maxCount(int[] banned, int n, int maxSum) { + int ans = 0; + int sum = 0; + Set bannedSet = Arrays.stream(banned).boxed().collect(Collectors.toSet()); + + for (int i = 1; i <= n; ++i) + if (!bannedSet.contains(i) && sum + i <= maxSum) { + ++ans; + sum += i; + } + + return ans; + } +} diff --git a/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.py b/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.py new file mode 100644 index 00000000000..d2ef1ccb9db --- /dev/null +++ b/solutions/2554. Maximum Number of Integers to Choose From a Range I/2554.py @@ -0,0 +1,12 @@ +class Solution: + def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: + ans = 0 + summ = 0 + bannedSet = set(banned) + + for i in range(1, n + 1): + if i not in bannedSet and summ + i <= maxSum: + ans += 1 + summ += i + + return ans diff --git a/solutions/2555. Maximize Win From Two Segments/2555.cpp b/solutions/2555. Maximize Win From Two Segments/2555.cpp new file mode 100644 index 00000000000..f363c2fb348 --- /dev/null +++ b/solutions/2555. Maximize Win From Two Segments/2555.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maximizeWin(vector& prizePositions, int k) { + int ans = 0; + // dp[i] := the maximum number of prizes to choose the first i + // `prizePositions` + vector dp(prizePositions.size() + 1); + + for (int i = 0, j = 0; i < prizePositions.size(); ++i) { + while (prizePositions[i] - prizePositions[j] > k) + ++j; + const int covered = i - j + 1; + dp[i + 1] = max(dp[i], covered); + ans = max(ans, dp[j] + covered); + } + + return ans; + } +}; diff --git a/solutions/2555. Maximize Win From Two Segments/2555.java b/solutions/2555. Maximize Win From Two Segments/2555.java new file mode 100644 index 00000000000..04de1b135bb --- /dev/null +++ b/solutions/2555. Maximize Win From Two Segments/2555.java @@ -0,0 +1,18 @@ +class Solution { + public int maximizeWin(int[] prizePositions, int k) { + int ans = 0; + // dp[i] := the maximum number of prizes to choose the first i + // `prizePositions` + int[] dp = new int[prizePositions.length + 1]; + + for (int i = 0, j = 0; i < prizePositions.length; ++i) { + while (prizePositions[i] - prizePositions[j] > k) + ++j; + final int covered = i - j + 1; + dp[i + 1] = Math.max(dp[i], covered); + ans = Math.max(ans, dp[j] + covered); + } + + return ans; + } +} diff --git a/solutions/2555. Maximize Win From Two Segments/2555.py b/solutions/2555. Maximize Win From Two Segments/2555.py new file mode 100644 index 00000000000..bc3fd3f0a25 --- /dev/null +++ b/solutions/2555. Maximize Win From Two Segments/2555.py @@ -0,0 +1,16 @@ +class Solution: + def maximizeWin(self, prizePositions: List[int], k: int) -> int: + ans = 0 + # dp[i] := the maximum number of prizes to choose the first i + # `prizePositions` + dp = [0] * (len(prizePositions) + 1) + + j = 0 + for i, prizePosition in enumerate(prizePositions): + while prizePosition - prizePositions[j] > k: + j += 1 + covered = i - j + 1 + dp[i + 1] = max(dp[i], covered) + ans = max(ans, dp[j] + covered) + + return ans diff --git a/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.cpp b/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.cpp new file mode 100644 index 00000000000..0d00a9bcd49 --- /dev/null +++ b/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + bool isPossibleToCutPath(vector>& grid) { + if (!hasPath(grid, 0, 0)) + return true; + // Reassign (0, 0) as 1. + grid[0][0] = 1; + return !hasPath(grid, 0, 0); + } + + private: + // Returns true is there's a path from (0, 0) to (m - 1, n - 1). + // Also marks the visited path as 0 except (m - 1, n - 1). + bool hasPath(vector>& grid, int i, int j) { + if (i == grid.size() || j == grid[0].size()) + return false; + if (i == grid.size() - 1 && j == grid[0].size() - 1) + return true; + if (grid[i][j] == 0) + return false; + + grid[i][j] = 0; + // Go down first. Since we use OR logic, we'll only mark one path. + return hasPath(grid, i + 1, j) || hasPath(grid, i, j + 1); + } +}; diff --git a/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.java b/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.java new file mode 100644 index 00000000000..390718ba75b --- /dev/null +++ b/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.java @@ -0,0 +1,24 @@ +class Solution { + public boolean isPossibleToCutPath(int[][] grid) { + if (!hasPath(grid, 0, 0)) + return true; + // Reassign (0, 0) as 1. + grid[0][0] = 1; + return !hasPath(grid, 0, 0); + } + + // Returns true is there's a path from (0, 0) to (m - 1, n - 1). + // Also marks the visited path as 0 except (m - 1, n - 1). + private boolean hasPath(int[][] grid, int i, int j) { + if (i == grid.length || j == grid[0].length) + return false; + if (i == grid.length - 1 && j == grid[0].length - 1) + return true; + if (grid[i][j] == 0) + return false; + + grid[i][j] = 0; + // Go down first. Since we use OR logic, we'll only mark one path. + return hasPath(grid, i + 1, j) || hasPath(grid, i, j + 1); + } +} diff --git a/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.py b/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.py new file mode 100644 index 00000000000..30f1f4beb2f --- /dev/null +++ b/solutions/2556. Disconnect Path in a Binary Matrix by at Most One Flip/2556.py @@ -0,0 +1,21 @@ +class Solution: + def isPossibleToCutPath(self, grid: List[List[int]]) -> bool: + # Returns True is there's a path from (0, 0) to (m - 1, n - 1). + # Also marks the visited path as 0 except (m - 1, n - 1). + def hasPath(i: int, j: int) -> bool: + if i == len(grid) or j == len(grid[0]): + return False + if i == len(grid) - 1 and j == len(grid[0]) - 1: + return True + if grid[i][j] == 0: + return False + + grid[i][j] = 0 + # Go down first. Since we use OR logic, we'll only mark one path. + return hasPath(i + 1, j) or hasPath(i, j + 1) + + if not hasPath(0, 0): + return True + # Reassign (0, 0) as 1. + grid[0][0] = 1 + return not hasPath(0, 0) diff --git a/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.cpp b/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.cpp new file mode 100644 index 00000000000..db1ffbe037e --- /dev/null +++ b/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int maxCount(vector& banned, int n, long long maxSum) { + const unordered_set bannedSet{banned.begin(), banned.end()}; + int l = 1; + int r = n; + + while (l < r) { + const int m = (l + r + 1) / 2; + if (getSum(bannedSet, m) > maxSum) + r = m - 1; + else + l = m; + } + + return l - ranges::count_if(bannedSet, [l](const int b) { return b <= l; }); + } + + private: + // Returns sum([1..m]) - sum(bannedSet). + long getSum(const unordered_set& bannedSet, long m) { + long sum = m * (m + 1) / 2; // sum([1..m]) + for (const int b : bannedSet) + if (b <= m) + sum -= b; + return sum; + } +}; diff --git a/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.java b/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.java new file mode 100644 index 00000000000..ca8cd64813e --- /dev/null +++ b/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.java @@ -0,0 +1,30 @@ +class Solution { + public int maxCount(int[] banned, int n, long maxSum) { + Set bannedSet = Arrays.stream(banned).boxed().collect(Collectors.toSet()); + int l = 1; + int r = n; + + while (l < r) { + final int m = (l + r + 1) / 2; + if (getSum(bannedSet, m) > maxSum) + r = m - 1; + else + l = m; + } + + int ans = l; + for (final int b : bannedSet) + if (b <= l) + --ans; + return ans; + } + + // Returns sum([1..m]) - sum(bannedSet). + private long getSum(Set bannedSet, long m) { + long sum = m * (m + 1) / 2; // sum([1..m]) + for (final int b : bannedSet) + if (b <= m) + sum -= b; + return sum; + } +} diff --git a/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.py b/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.py new file mode 100644 index 00000000000..2cdfb19f6d9 --- /dev/null +++ b/solutions/2557. Maximum Number of Integers to Choose From a Range II/2557.py @@ -0,0 +1,18 @@ +class Solution: + def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: + bannedSet = set(banned) + l = 1 + r = n + + while l < r: + m = (l + r + 1) // 2 + if self._getSum(bannedSet, m) > maxSum: + r = m - 1 + else: + l = m + + return l - sum(b <= l for b in banned) + + # Returns sum([1..m]) - sum(bannedSet). + def _getSum(self, bannedSet: Set[int], m: int) -> int: + return m * (m + 1) // 2 - sum(b for b in bannedSet if b <= m) diff --git a/solutions/2558. Take Gifts From the Richest Pile/2558.cpp b/solutions/2558. Take Gifts From the Richest Pile/2558.cpp new file mode 100644 index 00000000000..dca32b3cf33 --- /dev/null +++ b/solutions/2558. Take Gifts From the Richest Pile/2558.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long pickGifts(vector& gifts, int k) { + long ans = 0; + priority_queue maxHeap; + + for (const int gift : gifts) + maxHeap.push(gift); + + for (int i = 0; i < k; ++i) { + const int squaredMax = sqrt(maxHeap.top()); + maxHeap.pop(); + maxHeap.push(squaredMax); + } + + while (!maxHeap.empty()) + ans += maxHeap.top(), maxHeap.pop(); + + return ans; + } +}; diff --git a/solutions/2558. Take Gifts From the Richest Pile/2558.java b/solutions/2558. Take Gifts From the Richest Pile/2558.java new file mode 100644 index 00000000000..513c9dd7e6e --- /dev/null +++ b/solutions/2558. Take Gifts From the Richest Pile/2558.java @@ -0,0 +1,19 @@ +class Solution { + public long pickGifts(int[] gifts, int k) { + long ans = 0; + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + for (final int gift : gifts) + maxHeap.offer(gift); + + for (int i = 0; i < k; ++i) { + final int squaredMax = (int) Math.sqrt(maxHeap.poll()); + maxHeap.offer(squaredMax); + } + + while (!maxHeap.isEmpty()) + ans += maxHeap.poll(); + + return ans; + } +} diff --git a/solutions/2558. Take Gifts From the Richest Pile/2558.py b/solutions/2558. Take Gifts From the Richest Pile/2558.py new file mode 100644 index 00000000000..8cac95b187c --- /dev/null +++ b/solutions/2558. Take Gifts From the Richest Pile/2558.py @@ -0,0 +1,10 @@ +class Solution: + def pickGifts(self, gifts: List[int], k: int) -> int: + maxHeap = [-gift for gift in gifts] + heapq.heapify(maxHeap) + + for _ in range(k): + squaredMax = math.isqrt(-heapq.heappop(maxHeap)) + heapq.heappush(maxHeap, -squaredMax) + + return -sum(maxHeap) diff --git a/solutions/2559. Count Vowel Strings in Ranges/2559.cpp b/solutions/2559. Count Vowel Strings in Ranges/2559.cpp new file mode 100644 index 00000000000..9bfa1af7476 --- /dev/null +++ b/solutions/2559. Count Vowel Strings in Ranges/2559.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector vowelStrings(vector& words, + vector>& queries) { + vector ans; + // prefix[i] := the number of the first i words that start with and end in a + // vowel + vector prefix(words.size() + 1); + + for (int i = 0; i < words.size(); ++i) + prefix[i + 1] += prefix[i] + startsAndEndsWithVowel(words[i]); + + for (const vector& query : queries) { + const int l = query[0]; + const int r = query[1]; + ans.push_back(prefix[r + 1] - prefix[l]); + } + + return ans; + } + + private: + bool startsAndEndsWithVowel(const string& word) { + return isVowel(word.front()) && isVowel(word.back()); + } + + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiou"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/2559. Count Vowel Strings in Ranges/2559.java b/solutions/2559. Count Vowel Strings in Ranges/2559.java new file mode 100644 index 00000000000..64132ecf0b7 --- /dev/null +++ b/solutions/2559. Count Vowel Strings in Ranges/2559.java @@ -0,0 +1,26 @@ +class Solution { + public int[] vowelStrings(String[] words, int[][] queries) { + int[] ans = new int[queries.length]; + // prefix[i] := the number of the first i words that start with and end in a vowel + int[] prefix = new int[words.length + 1]; + + for (int i = 0; i < words.length; ++i) + prefix[i + 1] += prefix[i] + (startsAndEndsWithVowel(words[i]) ? 1 : 0); + + for (int i = 0; i < queries.length; ++i) { + final int l = queries[i][0]; + final int r = queries[i][1]; + ans[i] = prefix[r + 1] - prefix[l]; + } + + return ans; + } + + private boolean startsAndEndsWithVowel(final String word) { + return isVowel(word.charAt(0)) && isVowel(word.charAt(word.length() - 1)); + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(c) != -1; + } +} diff --git a/solutions/2559. Count Vowel Strings in Ranges/2559.py b/solutions/2559. Count Vowel Strings in Ranges/2559.py new file mode 100644 index 00000000000..2a07fa92754 --- /dev/null +++ b/solutions/2559. Count Vowel Strings in Ranges/2559.py @@ -0,0 +1,11 @@ +class Solution: + def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: + kVowels = 'aeiou' + # prefix[i] := the number of the first i words that start with and end in a vowel + prefix = [0] * (len(words) + 1) + + for i, word in enumerate(words): + prefix[i + 1] += prefix[i] + (word[0] in kVowels and word[-1] in kVowels) + + return [prefix[r + 1] - prefix[l] + for l, r in queries] diff --git a/solutions/256. Paint House/256.cpp b/solutions/256. Paint House/256.cpp new file mode 100644 index 00000000000..3805588cad9 --- /dev/null +++ b/solutions/256. Paint House/256.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int minCost(vector>& costs) { + for (int i = 1; i < costs.size(); ++i) { + costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]); + costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]); + costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]); + } + + return ranges::min(costs.back()); + } +}; diff --git a/solutions/256. Paint House/256.java b/solutions/256. Paint House/256.java new file mode 100644 index 00000000000..4aff55558b7 --- /dev/null +++ b/solutions/256. Paint House/256.java @@ -0,0 +1,13 @@ +class Solution { + public int minCost(int[][] costs) { + final int n = costs.length; + + for (int i = 1; i < n; ++i) { + costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]); + costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]); + costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]); + } + + return Math.min(costs[n - 1][0], Math.min(costs[n - 1][1], costs[n - 1][2])); + } +} diff --git a/solutions/256. Paint House/256.py b/solutions/256. Paint House/256.py new file mode 100644 index 00000000000..75d91582c91 --- /dev/null +++ b/solutions/256. Paint House/256.py @@ -0,0 +1,8 @@ +class Solution: + def minCost(self, costs: List[List[int]]) -> List[List[int]]: + for i in range(1, len(costs)): + costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]) + costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]) + costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]) + + return min(costs[-1]) diff --git a/solutions/2560. House Robber IV/2560.cpp b/solutions/2560. House Robber IV/2560.cpp new file mode 100644 index 00000000000..584bf208e3f --- /dev/null +++ b/solutions/2560. House Robber IV/2560.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int minCapability(vector& nums, int k) { + int l = ranges::min(nums); + int r = ranges::max(nums); + + while (l < r) { + const int m = (l + r) / 2; + if (numStolenHouses(nums, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int numStolenHouses(const vector& nums, int capacity) { + int stolenHouses = 0; + for (int i = 0; i < nums.size(); ++i) + if (nums[i] <= capacity) { + ++stolenHouses; + ++i; + } + return stolenHouses; + } +}; diff --git a/solutions/2560. House Robber IV/2560.java b/solutions/2560. House Robber IV/2560.java new file mode 100644 index 00000000000..980c3da742e --- /dev/null +++ b/solutions/2560. House Robber IV/2560.java @@ -0,0 +1,26 @@ +class Solution { + public int minCapability(int[] nums, int k) { + int l = Arrays.stream(nums).min().getAsInt(); + int r = Arrays.stream(nums).max().getAsInt(); + + while (l < r) { + final int m = (l + r) / 2; + if (numStolenHouses(nums, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private int numStolenHouses(int[] nums, int capacity) { + int stolenHouses = 0; + for (int i = 0; i < nums.length; ++i) + if (nums[i] <= capacity) { + ++stolenHouses; + ++i; + } + return stolenHouses; + } +} diff --git a/solutions/2560. House Robber IV/2560.py b/solutions/2560. House Robber IV/2560.py new file mode 100644 index 00000000000..3e5b3aa1564 --- /dev/null +++ b/solutions/2560. House Robber IV/2560.py @@ -0,0 +1,14 @@ +class Solution: + def minCapability(self, nums: List[int], k: int) -> int: + def numStolenHouses(capacity: int) -> int: + stolenHouses = 0 + i = 0 + while i < len(nums): + if nums[i] <= capacity: + stolenHouses += 1 + i += 1 + i += 1 + return stolenHouses + + return bisect.bisect_left(range(max(nums)), k, + key=lambda m: numStolenHouses(m)) diff --git a/solutions/2561. Rearranging Fruits/2561.cpp b/solutions/2561. Rearranging Fruits/2561.cpp new file mode 100644 index 00000000000..d7965278fb2 --- /dev/null +++ b/solutions/2561. Rearranging Fruits/2561.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + long long minCost(vector& basket1, vector& basket2) { + vector swapped; + unordered_map count; + + for (const int b : basket1) + ++count[b]; + + for (const int b : basket2) + --count[b]; + + for (const auto& [num, freq] : count) { + if (freq % 2 != 0) + return -1; + for (int i = 0; i < abs(freq) / 2; ++i) + swapped.push_back(num); + } + + const int minNum = min(ranges::min(basket1), ranges::min(basket2)); + const auto midIt = swapped.begin() + swapped.size() / 2; + nth_element(swapped.begin(), midIt, swapped.end()); + return accumulate(swapped.begin(), midIt, 0L, + [minNum](long subtotal, int num) { + return subtotal + min(2 * minNum, num); + }); + } +}; diff --git a/solutions/2561. Rearranging Fruits/2561.java b/solutions/2561. Rearranging Fruits/2561.java new file mode 100644 index 00000000000..931029d04d1 --- /dev/null +++ b/solutions/2561. Rearranging Fruits/2561.java @@ -0,0 +1,30 @@ +class Solution { + public long minCost(int[] basket1, int[] basket2) { + long ans = 0; + List swapped = new ArrayList<>(); + Map count = new HashMap<>(); + + for (final int b : basket1) + count.merge(b, 1, Integer::sum); + + for (final int b : basket2) + count.merge(b, -1, Integer::sum); + + for (Map.Entry entry : count.entrySet()) { + final Integer num = entry.getKey(); + final Integer freq = entry.getValue(); + if (freq % 2 != 0) + return -1; + for (int i = 0; i < Math.abs(freq) / 2; ++i) + swapped.add(num); + } + + final int minNum = + Math.min(Arrays.stream(basket1).min().getAsInt(), Arrays.stream(basket2).min().getAsInt()); + Collections.sort(swapped); + + for (int i = 0; i < swapped.size() / 2; ++i) + ans += Math.min(minNum * 2, swapped.get(i)); + return ans; + } +} diff --git a/solutions/2561. Rearranging Fruits/2561.py b/solutions/2561. Rearranging Fruits/2561.py new file mode 100644 index 00000000000..9070bd04275 --- /dev/null +++ b/solutions/2561. Rearranging Fruits/2561.py @@ -0,0 +1,18 @@ +class Solution: + def minCost(self, basket1: List[int], basket2: List[int]) -> int: + swapped = [] + count = collections.Counter(basket1) + count.subtract(collections.Counter(basket2)) + + for num, freq in count.items(): + if freq % 2 != 0: + return -1 + swapped += [num] * abs(freq // 2) + + swapped.sort() + minNum = min(min(basket1), min(basket2)) + # Other than directly swap basket1[i] and basket2[j], we can swap basket1[i] + # with `minNum` first then swap `minNum` with basket2[j], and vice versa. + # That's why we take min(2 * minNum, num) in the below. + return sum(min(2 * minNum, num) for num in swapped[0:len(swapped) // 2]) + \ No newline at end of file diff --git a/solutions/2562. Find the Array Concatenation Value/2562.cpp b/solutions/2562. Find the Array Concatenation Value/2562.cpp new file mode 100644 index 00000000000..372577b6c05 --- /dev/null +++ b/solutions/2562. Find the Array Concatenation Value/2562.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long findTheArrayConcVal(vector& nums) { + long ans = 0; + + for (int i = 0, j = nums.size() - 1; i <= j; ++i, --j) { + ans += nums[j]; + if (i < j) + ans += nums[i] * pow(10, static_cast(log10(nums[j])) + 1); + } + + return ans; + } +}; diff --git a/solutions/2563. Count the Number of Fair Pairs/2563.cpp b/solutions/2563. Count the Number of Fair Pairs/2563.cpp new file mode 100644 index 00000000000..fa1ebef8878 --- /dev/null +++ b/solutions/2563. Count the Number of Fair Pairs/2563.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + long long countFairPairs(vector& nums, int lower, int upper) { + // nums[i] + nums[j] == nums[j] + nums[i], so the condition that i < j + // degrades to i != j and we can sort the array. + ranges::sort(nums); + return countLess(nums, upper) - countLess(nums, lower - 1); + } + + private: + long countLess(const vector& nums, int sum) { + long res = 0; + for (int i = 0, j = nums.size() - 1; i < j; ++i) { + while (i < j && nums[i] + nums[j] > sum) + --j; + res += j - i; + } + return res; + } +}; diff --git a/solutions/2563. Count the Number of Fair Pairs/2563.java b/solutions/2563. Count the Number of Fair Pairs/2563.java new file mode 100644 index 00000000000..7d2850825b3 --- /dev/null +++ b/solutions/2563. Count the Number of Fair Pairs/2563.java @@ -0,0 +1,18 @@ +class Solution { + public long countFairPairs(int[] nums, int lower, int upper) { + // nums[i] + nums[j] == nums[j] + nums[i], so the condition that i < j + // degrades to i != j and we can sort the array. + Arrays.sort(nums); + return countLess(nums, upper) - countLess(nums, lower - 1); + } + + private long countLess(int[] nums, int sum) { + long res = 0; + for (int i = 0, j = nums.length - 1; i < j; ++i) { + while (i < j && nums[i] + nums[j] > sum) + --j; + res += j - i; + } + return res; + } +} diff --git a/solutions/2563. Count the Number of Fair Pairs/2563.py b/solutions/2563. Count the Number of Fair Pairs/2563.py new file mode 100644 index 00000000000..2e9c41d2ded --- /dev/null +++ b/solutions/2563. Count the Number of Fair Pairs/2563.py @@ -0,0 +1,18 @@ +class Solution: + def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: + # nums[i] + nums[j] == nums[j] + nums[i], so the condition that i < j + # degrades to i != j and we can sort the array. + nums.sort() + + def countLess(summ: int) -> int: + res = 0 + i = 0 + j = len(nums) - 1 + while i < j: + while i < j and nums[i] + nums[j] > summ: + j -= 1 + res += j - i + i += 1 + return res + + return countLess(upper) - countLess(lower - 1) diff --git a/solutions/2564. Substring XOR Queries/2564.cpp b/solutions/2564. Substring XOR Queries/2564.cpp new file mode 100644 index 00000000000..dec0b805490 --- /dev/null +++ b/solutions/2564. Substring XOR Queries/2564.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + vector> substringXorQueries(string s, + vector>& queries) { + constexpr int kMaxBit = 30; + vector> ans; + // {val: (left, right)} := s[left..right]'s decimal value = val + unordered_map> valToLeftAndRight; + + for (int left = 0; left < s.length(); ++left) { + int val = 0; + if (s[left] == '0') { + // edge case: Save the index of the first 0. + if (!valToLeftAndRight.contains(0)) + valToLeftAndRight[0] = {left, left}; + continue; + } + const int maxRight = min(static_cast(s.length()), left + kMaxBit); + for (int right = left; right < maxRight; ++right) { + val = val * 2 + s[right] - '0'; + if (!valToLeftAndRight.contains(val)) + valToLeftAndRight[val] = {left, right}; + } + } + + for (const vector& query : queries) { + const int first = query[0]; + const int second = query[1]; + const int val = first ^ second; + const auto it = valToLeftAndRight.find(val); + if (it == valToLeftAndRight.cend()) { + ans.push_back({-1, -1}); + } else { + const auto [left, right] = it->second; + ans.push_back({left, right}); + } + } + + return ans; + } +}; diff --git a/solutions/2564. Substring XOR Queries/2564.java b/solutions/2564. Substring XOR Queries/2564.java new file mode 100644 index 00000000000..60feb4c56d2 --- /dev/null +++ b/solutions/2564. Substring XOR Queries/2564.java @@ -0,0 +1,40 @@ +class Solution { + public int[][] substringXorQueries(String s, int[][] queries) { + final int kMaxBit = 30; + int[][] ans = new int[queries.length][2]; + // {val: (left, right)} := s[left..right]'s decimal value = val + Map> valToLeftAndRight = new HashMap<>(); + + for (int left = 0; left < s.length(); ++left) { + int val = 0; + if (s.charAt(left) == '0') { + // edge case: Save the index of the first 0. + if (!valToLeftAndRight.containsKey(0)) + valToLeftAndRight.put(val, new Pair<>(left, left)); + continue; + } + final int maxRight = Math.min(s.length(), left + kMaxBit); + for (int right = left; right < maxRight; ++right) { + val = val * 2 + s.charAt(right) - '0'; + if (!valToLeftAndRight.containsKey(val)) + valToLeftAndRight.put(val, new Pair<>(left, right)); + } + } + + for (int i = 0; i < queries.length; ++i) { + final int first = queries[i][0]; + final int second = queries[i][1]; + final int val = first ^ second; + Pair leftAndRight = valToLeftAndRight.get(val); + if (leftAndRight == null) { + ans[i] = new int[] {-1, -1}; + } else { + final int left = leftAndRight.getKey(); + final int right = leftAndRight.getValue(); + ans[i] = new int[] {left, right}; + } + } + + return ans; + } +} diff --git a/solutions/2564. Substring XOR Queries/2564.py b/solutions/2564. Substring XOR Queries/2564.py new file mode 100644 index 00000000000..82be4f92a50 --- /dev/null +++ b/solutions/2564. Substring XOR Queries/2564.py @@ -0,0 +1,20 @@ +class Solution: + def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]: + kMaxBit = 30 + # {val: [left, right]} := s[left..right]'s decimal value = val + valToLeftAndRight = collections.defaultdict(lambda: [-1, -1]) + + for left, c in enumerate(s): + val = 0 + if c == '0': + # edge case: Save the index of the first 0. + if 0 not in valToLeftAndRight: + valToLeftAndRight[0] = [left, left] + continue + for right in range(left, min(len(s), left + kMaxBit)): + val = val * 2 + int(s[right]) + if val not in valToLeftAndRight: + valToLeftAndRight[val] = [left, right] + + return [valToLeftAndRight[first, right] + for first, right in queries] diff --git a/solutions/2565. Subsequence With the Minimum Score/2565.py b/solutions/2565. Subsequence With the Minimum Score/2565.py new file mode 100644 index 00000000000..ff089c7109e --- /dev/null +++ b/solutions/2565. Subsequence With the Minimum Score/2565.py @@ -0,0 +1,46 @@ +class Solution: + def minimumScore(self, s: str, t: str) -> int: + # leftmost[j] := the minimum index i s.t. t[0..j] is a subsequence of s[0..i]. + # -1 := impossible + leftmost = [-1] * len(t) + # rightmost[j] := the maximum index i s.t. t[j:] is a subsequence of s[i..n). + # -1 := impossible + rightmost = [-1] * len(t) + + j = 0 # t's index + for i in range(len(s)): + if s[i] == t[j]: + leftmost[j] = i + j += 1 + if j == len(t): + break + + j = len(t) - 1 # t's index + for i in reversed(range(len(s))): + if s[i] == t[j]: + rightmost[j] = i + j -= 1 + if j == -1: + break + + # The worst case is to delete t[0:j] since t[j:] is a subsequence of s. (deduced + # from the above loop). + ans = j + 1 + + j = 0 + for i in range(len(t)): + # It's impossible that t[0..i] is a subsequence of s. So, stop the loop since + # no need to consider any larger i. + if leftmost[i] == -1: + break + # While t[0..i] + t[j:] is not a subsequence of s, increase j. + while j < len(t) and leftmost[i] >= rightmost[j]: + j += 1 + # Now, leftmost[i] < rightmost[j], so t[0..i] + t[j:n] is a subsequence of s. + # If i == j that means t is a subsequence of s, so just return 0. + if i == j: + return 0 + # Delete t[i + 1..j - 1] and that's a total of j - i - 1 letters. + ans = min(ans, j - i - 1) + + return ans diff --git a/solutions/2566. Maximum Difference by Remapping a Digit/2566.cpp b/solutions/2566. Maximum Difference by Remapping a Digit/2566.cpp new file mode 100644 index 00000000000..efe65dcecd3 --- /dev/null +++ b/solutions/2566. Maximum Difference by Remapping a Digit/2566.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int minMaxDifference(int num) { + const string s = to_string(num); + const char to9 = s[firstNotNineIndex(s)]; + const char to0 = s[0]; + return getMax(s, to9) - getMin(s, to0); + } + + private: + int firstNotNineIndex(const string& s) { + for (int i = 0; i < s.length(); ++i) + if (s[i] != '9') + return i; + return 0; + } + + int getMax(string s, char to9) { + for (char& c : s) + if (c == to9) + c = '9'; + return stoi(s); + } + + int getMin(string s, char to0) { + for (char& c : s) + if (c == to0) + c = '0'; + return stoi(s); + } +}; diff --git a/solutions/2566. Maximum Difference by Remapping a Digit/2566.java b/solutions/2566. Maximum Difference by Remapping a Digit/2566.java new file mode 100644 index 00000000000..79775a4c01d --- /dev/null +++ b/solutions/2566. Maximum Difference by Remapping a Digit/2566.java @@ -0,0 +1,29 @@ +class Solution { + public int minMaxDifference(int num) { + final String s = String.valueOf(num); + final char to9 = s.charAt(firstNotNineIndex(s)); + final char to0 = s.charAt(0); + return getMax(new StringBuilder(s), to9) - getMin(new StringBuilder(s), to0); + } + + private int firstNotNineIndex(final String s) { + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) != '9') + return i; + return 0; + } + + private int getMax(StringBuilder sb, char to9) { + for (int i = 0; i < sb.length(); ++i) + if (sb.charAt(i) == to9) + sb.setCharAt(i, '9'); + return Integer.parseInt(sb.toString()); + } + + private int getMin(StringBuilder sb, char to0) { + for (int i = 0; i < sb.length(); ++i) + if (sb.charAt(i) == to0) + sb.setCharAt(i, '0'); + return Integer.parseInt(sb.toString()); + } +} diff --git a/solutions/2566. Maximum Difference by Remapping a Digit/2566.py b/solutions/2566. Maximum Difference by Remapping a Digit/2566.py new file mode 100644 index 00000000000..c2867eec320 --- /dev/null +++ b/solutions/2566. Maximum Difference by Remapping a Digit/2566.py @@ -0,0 +1,12 @@ +class Solution: + def minMaxDifference(self, num: int) -> int: + s = str(num) + to9 = s[self._firstNotNineIndex(s)] + to0 = s[0] + return int(s.replace(to9, '9')) - int(s.replace(to0, '0')) + + def _firstNotNineIndex(self, s: str) -> int: + for i, c in enumerate(s): + if c != '9': + return i + return 0 diff --git a/solutions/2567. Minimum Score by Changing Two Elements/2567.cpp b/solutions/2567. Minimum Score by Changing Two Elements/2567.cpp new file mode 100644 index 00000000000..2733b984a7a --- /dev/null +++ b/solutions/2567. Minimum Score by Changing Two Elements/2567.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minimizeSum(vector& nums) { + ranges::sort(nums); + // Can always change the number to any other number in `nums`, so `low` + // becomes 0. Thus, rephrase the problem as finding the minimum `high`. + const int n = nums.size(); + const int highOfChangingTwoMins = nums.back() - nums[2]; + const int highOfChangingTwoMaxs = nums[n - 3] - nums[0]; + const int highOfChangingMinAndMax = nums[n - 2] - nums[1]; + return min({highOfChangingTwoMins, highOfChangingTwoMaxs, + highOfChangingMinAndMax}); + } +}; diff --git a/solutions/2567. Minimum Score by Changing Two Elements/2567.java b/solutions/2567. Minimum Score by Changing Two Elements/2567.java new file mode 100644 index 00000000000..d7febf8169d --- /dev/null +++ b/solutions/2567. Minimum Score by Changing Two Elements/2567.java @@ -0,0 +1,13 @@ +class Solution { + public int minimizeSum(int[] nums) { + Arrays.sort(nums); + // Can always change the number to any other number in `nums`, so `low` becomes 0. + // Thus, rephrase the problem as finding the minimum `high`. + final int n = nums.length; + final int highOfChangingTwoMins = nums[n - 1] - nums[2]; + final int highOfChangingTwoMaxs = nums[n - 3] - nums[0]; + final int highOfChangingMinAndMax = nums[n - 2] - nums[1]; + return Math.min(Math.min(highOfChangingTwoMins, highOfChangingTwoMaxs), + highOfChangingMinAndMax); + } +} diff --git a/solutions/2567. Minimum Score by Changing Two Elements/2567.py b/solutions/2567. Minimum Score by Changing Two Elements/2567.py new file mode 100644 index 00000000000..86ae2f8170a --- /dev/null +++ b/solutions/2567. Minimum Score by Changing Two Elements/2567.py @@ -0,0 +1,10 @@ +class Solution: + def minimizeSum(self, nums: List[int]) -> int: + nums.sort() + # Can always change the number to any other number in `nums`, so `low` becomes 0. + # Thus, rephrase the problem as finding the minimum `high`. + highOfChangingTwoMins = nums[-1] - nums[2] + highOfChangingTwoMaxs = nums[-3] - nums[0] + highOfChangingMinAndMax = nums[-2] - nums[1] + return min(highOfChangingTwoMins, highOfChangingTwoMaxs, + highOfChangingMinAndMax) diff --git a/solutions/2568. Minimum Impossible OR/2568.cpp b/solutions/2568. Minimum Impossible OR/2568.cpp new file mode 100644 index 00000000000..d5f32896594 --- /dev/null +++ b/solutions/2568. Minimum Impossible OR/2568.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int minImpossibleOR(vector& nums) { + int ans = 1; + const unordered_set numsSet{nums.begin(), nums.end()}; + + while (numsSet.contains(ans)) + ans <<= 1; + + return ans; + } +}; diff --git a/solutions/2568. Minimum Impossible OR/2568.java b/solutions/2568. Minimum Impossible OR/2568.java new file mode 100644 index 00000000000..e49bea36073 --- /dev/null +++ b/solutions/2568. Minimum Impossible OR/2568.java @@ -0,0 +1,11 @@ +class Solution { + public int minImpossibleOR(int[] nums) { + int ans = 1; + Set numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + + while (numsSet.contains(ans)) + ans <<= 1; + + return ans; + } +} diff --git a/solutions/2568. Minimum Impossible OR/2568.py b/solutions/2568. Minimum Impossible OR/2568.py new file mode 100644 index 00000000000..aadedca8333 --- /dev/null +++ b/solutions/2568. Minimum Impossible OR/2568.py @@ -0,0 +1,9 @@ +class Solution: + def minImpossibleOR(self, nums: List[int]) -> int: + ans = 1 + numsSet = set(nums) + + while ans in numsSet: + ans <<= 1 + + return ans diff --git a/solutions/2569. Handling Sum Queries After Update/2569.cpp b/solutions/2569. Handling Sum Queries After Update/2569.cpp new file mode 100644 index 00000000000..5ef1799762e --- /dev/null +++ b/solutions/2569. Handling Sum Queries After Update/2569.cpp @@ -0,0 +1,84 @@ +class LazySegmentTree { + public: + explicit LazySegmentTree(const vector& nums) { + const int n = nums.size(); + tree.resize(4 * n); + lazy.resize(4 * n); + build(nums, 0, 0, n - 1); + } + + // i := index of the current node + // [start, end] := range of the current node + // [l, r] := range of the query + void updateRange(int i, int start, int end, int l, int r) { + if (lazy[i]) + propogate(i, start, end); + if (start > r || end < l) + return; + if (start >= l && end <= r) { + flip(i, start, end); + return; + } + const int mid = (start + end) / 2; + updateRange(i * 2 + 1, start, mid, l, r); + updateRange(i * 2 + 2, mid + 1, end, l, r); + tree[i] = tree[2 * i + 1] + tree[2 * i + 2]; + } + + int getTreeSum() const { + return tree[0]; + } + + private: + vector tree; + vector lazy; + + void build(const vector& nums, int i, int start, int end) { + if (start == end) { + tree[i] = nums[start]; + return; + } + const int mid = (start + end) / 2; + build(nums, 2 * i + 1, start, mid); + build(nums, 2 * i + 2, mid + 1, end); + tree[i] = tree[2 * i + 1] + tree[2 * i + 2]; + } + + void propogate(int i, int start, int end) { + flip(i, start, end); + lazy[i] = false; + } + + void flip(int i, int start, int end) { + tree[i] = (end - start + 1) - tree[i]; // Flip 0/1. + if (start < end) { + lazy[2 * i + 1] = !lazy[2 * i + 1]; + lazy[2 * i + 2] = !lazy[2 * i + 2]; + } + } +}; + +class Solution { + public: + vector handleQuery(vector& nums1, vector& nums2, + vector>& queries) { + vector ans; + LazySegmentTree tree(nums1); + long sumNums2 = accumulate(nums2.begin(), nums2.end(), 0L); + + for (const vector& query : queries) { + const int type = query[0]; + const int l = query[1]; + const int r = query[2]; + if (type == 1) { + tree.updateRange(0, 0, nums1.size() - 1, l, r); + } else if (type == 2) { + sumNums2 += static_cast(l) * tree.getTreeSum(); + } else { // type == 3 + ans.push_back(sumNums2); + } + } + + return ans; + } +}; diff --git a/solutions/257. Binary Tree Paths/257.cpp b/solutions/257. Binary Tree Paths/257.cpp new file mode 100644 index 00000000000..ead8b4b5988 --- /dev/null +++ b/solutions/257. Binary Tree Paths/257.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector binaryTreePaths(TreeNode* root) { + vector ans; + dfs(root, {}, ans); + return ans; + } + + private: + void dfs(TreeNode* root, vector&& path, vector& ans) { + if (root == nullptr) + return; + if (root->left == nullptr && root->right == nullptr) { + ans.push_back(join(path) + to_string(root->val)); + return; + } + + path.push_back(to_string(root->val) + "->"); + dfs(root->left, move(path), ans); + dfs(root->right, move(path), ans); + path.pop_back(); + } + + string join(const vector& path) { + string joined; + for (const string& s : path) + joined += s; + return joined; + } +}; diff --git a/solutions/257. Binary Tree Paths/257.java b/solutions/257. Binary Tree Paths/257.java new file mode 100644 index 00000000000..b09d333ef35 --- /dev/null +++ b/solutions/257. Binary Tree Paths/257.java @@ -0,0 +1,22 @@ +class Solution { + public List binaryTreePaths(TreeNode root) { + List ans = new ArrayList<>(); + dfs(root, new StringBuilder(), ans); + return ans; + } + + private void dfs(TreeNode root, StringBuilder sb, List ans) { + if (root == null) + return; + if (root.left == null && root.right == null) { + ans.add(sb.append(root.val).toString()); + return; + } + + final int length = sb.length(); + dfs(root.left, sb.append(root.val).append("->"), ans); + sb.setLength(length); + dfs(root.right, sb.append(root.val).append("->"), ans); + sb.setLength(length); + } +} diff --git a/solutions/257. Binary Tree Paths/257.py b/solutions/257. Binary Tree Paths/257.py new file mode 100644 index 00000000000..e467253b8d0 --- /dev/null +++ b/solutions/257. Binary Tree Paths/257.py @@ -0,0 +1,18 @@ +class Solution: + def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: + ans = [] + + def dfs(root: Optional[TreeNode], path: List[str]) -> None: + if not root: + return + if not root.left and not root.right: + ans.append(''.join(path) + str(root.val)) + return + + path.append(str(root.val) + '->') + dfs(root.left, path) + dfs(root.right, path) + path.pop() + + dfs(root, []) + return ans diff --git a/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.cpp b/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.cpp new file mode 100644 index 00000000000..ae52a66e643 --- /dev/null +++ b/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector> mergeArrays(vector>& nums1, + vector>& nums2) { + constexpr int kMax = 1000; + vector> ans; + vector count(kMax + 1); + + addCount(nums1, count); + addCount(nums2, count); + + for (int i = 1; i <= kMax; ++i) + if (count[i] > 0) + ans.push_back({i, count[i]}); + + return ans; + } + + private: + void addCount(const vector>& nums, vector& count) { + for (const vector& idAndVal : nums) { + const int id = idAndVal[0]; + const int val = idAndVal[1]; + count[id] += val; + } + } +}; diff --git a/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.java b/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.java new file mode 100644 index 00000000000..04ad4af2056 --- /dev/null +++ b/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.java @@ -0,0 +1,24 @@ +class Solution { + public int[][] mergeArrays(int[][] nums1, int[][] nums2) { + final int kMax = 1000; + List ans = new ArrayList<>(); + int[] count = new int[kMax + 1]; + + addCount(nums1, count); + addCount(nums2, count); + + for (int i = 1; i <= kMax; ++i) + if (count[i] > 0) + ans.add(new int[] {i, count[i]}); + + return ans.stream().toArray(int[][] ::new); + } + + private void addCount(int[][] nums, int[] count) { + for (int[] idAndVal : nums) { + final int id = idAndVal[0]; + final int val = idAndVal[1]; + count[id] += val; + } + } +} diff --git a/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.py b/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.py new file mode 100644 index 00000000000..22ae0618ec5 --- /dev/null +++ b/solutions/2570. Merge Two 2D Arrays by Summing Values/2570.py @@ -0,0 +1,10 @@ +class Solution: + def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]: + count = [0] * (1001) + self._addCount(nums1, count) + self._addCount(nums2, count) + return [[i, c] for i, c in enumerate(count) if c > 0] + + def _addCount(self, nums: List[List[int]], count: List[int]) -> None: + for id_, val in nums: + count[id_] += val diff --git a/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.cpp b/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.cpp new file mode 100644 index 00000000000..bbab548f8ee --- /dev/null +++ b/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int minOperations(int n) { + // The strategy is that when the end of n is + // 1. consecutive 1s, add 1 (2^0). + // 2. single 1, substract 1 (2^0). + // 3. 0, substract 2^k to omit the last 1. Equivalently, n >> 1. + // + // e.g. + // + // n = 0b101 + // n -= 2^0 -> 0b100 + // n -= 2^2 -> 0b0 + // n = 0b1011 + // n += 2^0 -> 0b1100 + // n -= 2^2 -> 0b1000 + // n -= 2^3 -> 0b0 + int ans = 0; + + while (n > 0) + if ((n & 3) == 3) { + ++n; + ++ans; + } else if (n % 2 == 1) { + --n; + ++ans; + } else { + n >>= 1; + } + + return ans; + } +}; diff --git a/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.java b/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.java new file mode 100644 index 00000000000..522013c6799 --- /dev/null +++ b/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.java @@ -0,0 +1,32 @@ +class Solution { + public int minOperations(int n) { + // The strategy is that when the end of n is + // 1. consecutive 1s, add 1 (2^0). + // 2. single 1, substract 1 (2^0). + // 3. 0, substract 2^k to omit the last 1. Equivalently, n >> 1. + // + // e.g. + // + // n = 0b101 + // n -= 2^0 -> 0b100 + // n -= 2^2 -> 0b0 + // n = 0b1011 + // n += 2^0 -> 0b1100 + // n -= 2^2 -> 0b1000 + // n -= 2^3 -> 0b0 + int ans = 0; + + while (n > 0) + if ((n & 3) == 3) { + ++n; + ++ans; + } else if (n % 2 == 1) { + --n; + ++ans; + } else { + n >>= 1; + } + + return ans; + } +} diff --git a/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.py b/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.py new file mode 100644 index 00000000000..b6d55be76a8 --- /dev/null +++ b/solutions/2571. Minimum Operations to Reduce an Integer to 0/2571.py @@ -0,0 +1,29 @@ +class Solution: + def minOperations(self, n: int) -> int: + # The strategy is that when the end of n is + # 1. consecutive 1s, add 1 (2^0). + # 2. single 1, substract 1 (2^0). + # 3. 0, substract 2^k to omit the last 1. Equivalently, n >> 1. + # + # e.g. + # + # n = 0b101 + # n -= 2^0 -> 0b100 + # n -= 2^2 -> 0b0 + # n = 0b1011 + # n += 2^0 -> 0b1100 + # n -= 2^2 -> 0b1000 + # n -= 2^3 -> 0b0 + ans = 0 + + while n > 0: + if (n & 3) == 3: + n += 1 + ans += 1 + elif n % 2 == 1: + n -= 1 + ans += 1 + else: + n >>= 1 + + return ans diff --git a/solutions/2572. Count the Number of Square-Free Subsets/2572.cpp b/solutions/2572. Count the Number of Square-Free Subsets/2572.cpp new file mode 100644 index 00000000000..409b5445c8c --- /dev/null +++ b/solutions/2572. Count the Number of Square-Free Subsets/2572.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int squareFreeSubsets(vector& nums) { + vector> mem(nums.size(), + vector(1 << (kPrimesCount + 1), -1)); + vector masks; + + for (const int num : nums) + masks.push_back(getMask(num)); + + // -1 means that we take no number. + // `used` is initialized to 1 so that -1 & 1 = 1 instead of 0. + return (squareFreeSubsets(masks, 0, /*used=*/1, mem) - 1 + kMod) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + static constexpr int kPrimesCount = 10; + static constexpr int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + + int squareFreeSubsets(const vector& masks, int i, int used, + vector>& mem) { + if (i == masks.size()) + return 1; + if (mem[i][used] != -1) + return mem[i][used]; + const int pick = (masks[i] & used) == 0 + ? squareFreeSubsets(masks, i + 1, used | masks[i], mem) + : 0; + const int skip = squareFreeSubsets(masks, i + 1, used, mem); + return mem[i][used] = (pick + skip) % kMod; + } + + // e.g. num = 10 = 2 * 5, so mask = 0b101 -> 0b1010 (append a 0) + // num = 15 = 3 * 5, so mask = 0b110 -> 0b1100 (append a 0) + // num = 25 = 5 * 5, so mask = 0b-1 -> 0b1..1 (invalid) + int getMask(int num) { + int mask = 0; + for (int i = 0; i < sizeof(primes) / sizeof(int); ++i) { + int rootCount = 0; + while (num % primes[i] == 0) { + num /= primes[i]; + ++rootCount; + } + if (rootCount >= 2) + return -1; + if (rootCount == 1) + mask |= 1 << i; + } + return mask << 1; + } +}; diff --git a/solutions/2572. Count the Number of Square-Free Subsets/2572.java b/solutions/2572. Count the Number of Square-Free Subsets/2572.java new file mode 100644 index 00000000000..dc58cebf3e5 --- /dev/null +++ b/solutions/2572. Count the Number of Square-Free Subsets/2572.java @@ -0,0 +1,47 @@ +class Solution { + public int squareFreeSubsets(int[] nums) { + Integer[][] mem = new Integer[nums.length][1 << (kPrimesCount + 1)]; + int[] masks = new int[nums.length]; + + for (int i = 0; i < nums.length; ++i) + masks[i] = getMask(nums[i]); + + // -1 means that we take no number. + // `used` is initialized to 1 so that -1 & 1 = 1 instead of 0. + return (squareFreeSubsets(masks, 0, /*used=*/1, mem) - 1 + kMod) % kMod; + } + + private static final int kMod = 1_000_000_007; + private static final int kPrimesCount = 10; + private static final int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + + private int squareFreeSubsets(int[] masks, int i, int used, Integer[][] mem) { + if (i == masks.length) + return 1; + if (mem[i][used] != null) + return mem[i][used]; + final int pick = + (masks[i] & used) == 0 ? squareFreeSubsets(masks, i + 1, used | masks[i], mem) : 0; + final int skip = squareFreeSubsets(masks, i + 1, used, mem); + return mem[i][used] = (pick + skip) % kMod; + } + + // e.g. num = 10 = 2 * 5, so mask = 0b101 -> 0b1010 (append a 0) + // num = 15 = 3 * 5, so mask = 0b110 -> 0b1100 (append a 0) + // num = 25 = 5 * 5, so mask = 0b-1 -> 0b1..1 (invalid) + private int getMask(int num) { + int mask = 0; + for (int i = 0; i < primes.length; ++i) { + int rootCount = 0; + while (num % primes[i] == 0) { + num /= primes[i]; + ++rootCount; + } + if (rootCount >= 2) + return -1; + if (rootCount == 1) + mask |= 1 << i; + } + return mask << 1; + } +} diff --git a/solutions/2572. Count the Number of Square-Free Subsets/2572.py b/solutions/2572. Count the Number of Square-Free Subsets/2572.py new file mode 100644 index 00000000000..39528fbb353 --- /dev/null +++ b/solutions/2572. Count the Number of Square-Free Subsets/2572.py @@ -0,0 +1,36 @@ +class Solution: + def squareFreeSubsets(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + def getMask(num: int) -> int: + """ + e.g. num = 10 = 2 * 5, so mask = 0b101 . 0b1010 (append a 0) + num = 15 = 3 * 5, so mask = 0b110 . 0b1100 (append a 0) + num = 25 = 5 * 5, so mask = (-1)2 . (1..1)2 (invalid) + """ + mask = 0 + for i, prime in enumerate(primes): + rootCount = 0 + while num % prime == 0: + num //= prime + rootCount += 1 + if rootCount >= 2: + return -1 + if rootCount == 1: + mask |= 1 << i + return mask << 1 + + masks = [getMask(num) for num in nums] + + @functools.lru_cache(None) + def dp(i: int, used: int) -> int: + if i == len(masks): + return 1 + pick = dp(i + 1, used | masks[i]) if (masks[i] & used) == 0 else 0 + skip = dp(i + 1, used) + return (pick + skip) % kMod + + # -1 means that we take no number. + # `used` is initialized to 1 so that -1 & 1 = 1 instead of 0. + return (dp(0, 1) - 1 + kMod) % kMod diff --git a/solutions/2573. Find the String with LCP/2573.cpp b/solutions/2573. Find the String with LCP/2573.cpp new file mode 100644 index 00000000000..ac8b5505598 --- /dev/null +++ b/solutions/2573. Find the String with LCP/2573.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + string findTheString(vector>& lcp) { + const int n = lcp.size(); + constexpr char nonLetter = 'a' - 1; + char c = nonLetter; + vector word(n, nonLetter); + + for (int i = 0; i < n; ++i) { + if (word[i] != nonLetter) // There's a candidate already. + continue; + if (++c > 'z') // Run out of letters, so return "". + return ""; + // No need to consider [0..i - 1] since they were considered. + for (int j = i; j < n; ++j) + if (lcp[i][j] > 0) + word[j] = c; + } + + // Check if `word` is valid. + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + const int nextLcp = i + 1 < n && j + 1 < n ? lcp[i + 1][j + 1] : 0; + const int currLcp = word[i] == word[j] ? 1 + nextLcp : 0; + if (lcp[i][j] != currLcp) + return ""; + } + + string ans; + for (const char c : word) + ans += c; + return ans; + } +}; diff --git a/solutions/2574. Left and Right Sum Differences/2574-2.cpp b/solutions/2574. Left and Right Sum Differences/2574-2.cpp new file mode 100644 index 00000000000..9bca97070bc --- /dev/null +++ b/solutions/2574. Left and Right Sum Differences/2574-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector leftRigthDifference(vector& nums) { + vector ans; + int leftSum = 0; + int rightSum = accumulate(nums.begin(), nums.end(), 0); + + for (const int num : nums) { + rightSum -= num; + ans.push_back(abs(leftSum - rightSum)); + leftSum += num; + } + + return ans; + } +}; diff --git a/solutions/2574. Left and Right Sum Differences/2574-2.java b/solutions/2574. Left and Right Sum Differences/2574-2.java new file mode 100644 index 00000000000..3ca278235fe --- /dev/null +++ b/solutions/2574. Left and Right Sum Differences/2574-2.java @@ -0,0 +1,15 @@ +class Solution { + public int[] leftRigthDifference(int[] nums) { + int[] ans = new int[nums.length]; + int leftSum = 0; + int rightSum = Arrays.stream(nums).sum(); + + for (int i = 0; i < nums.length; ++i) { + rightSum -= nums[i]; + ans[i] = Math.abs(leftSum - rightSum); + leftSum += nums[i]; + } + + return ans; + } +} diff --git a/solutions/2574. Left and Right Sum Differences/2574-2.py b/solutions/2574. Left and Right Sum Differences/2574-2.py new file mode 100644 index 00000000000..235bec998ee --- /dev/null +++ b/solutions/2574. Left and Right Sum Differences/2574-2.py @@ -0,0 +1,12 @@ +class Solution: + def leftRigthDifference(self, nums: List[int]) -> List[int]: + ans = [] + leftSum = 0 + rightSum = sum(nums) + + for num in nums: + rightSum -= num + ans.append(abs(leftSum - rightSum)) + leftSum += num + + return ans diff --git a/solutions/2574. Left and Right Sum Differences/2574.cpp b/solutions/2574. Left and Right Sum Differences/2574.cpp new file mode 100644 index 00000000000..bb367583ced --- /dev/null +++ b/solutions/2574. Left and Right Sum Differences/2574.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector leftRigthDifference(vector& nums) { + const int n = nums.size(); + vector ans(n); + vector leftSum(n); + vector rightSum(n); + int prefix = 0; + int suffix = 0; + + for (int i = 0; i < n; ++i) { + if (i > 0) + prefix += nums[i - 1]; + leftSum[i] = prefix; + } + + for (int i = n - 1; i >= 0; --i) { + if (i + 1 < n) + suffix += nums[i + 1]; + rightSum[i] = suffix; + } + + for (int i = 0; i < n; ++i) + ans[i] = abs(leftSum[i] - rightSum[i]); + + return ans; + } +}; diff --git a/solutions/2574. Left and Right Sum Differences/2574.java b/solutions/2574. Left and Right Sum Differences/2574.java new file mode 100644 index 00000000000..76dd2228543 --- /dev/null +++ b/solutions/2574. Left and Right Sum Differences/2574.java @@ -0,0 +1,27 @@ +class Solution { + public int[] leftRigthDifference(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + int[] leftSum = new int[n]; + int[] rightSum = new int[n]; + int prefix = 0; + int suffix = 0; + + for (int i = 0; i < n; ++i) { + if (i > 0) + prefix += nums[i - 1]; + leftSum[i] = prefix; + } + + for (int i = n - 1; i >= 0; --i) { + if (i + 1 < n) + suffix += nums[i + 1]; + rightSum[i] = suffix; + } + + for (int i = 0; i < n; ++i) + ans[i] = Math.abs(leftSum[i] - rightSum[i]); + + return ans; + } +} diff --git a/solutions/2574. Left and Right Sum Differences/2574.py b/solutions/2574. Left and Right Sum Differences/2574.py new file mode 100644 index 00000000000..03c52541a3a --- /dev/null +++ b/solutions/2574. Left and Right Sum Differences/2574.py @@ -0,0 +1,19 @@ +class Solution: + def leftRigthDifference(self, nums: List[int]) -> List[int]: + n = len(nums) + leftSum = [0] * n + rightSum = [0] * n + prefix = 0 + suffix = 0 + + for i in range(n): + if i > 0: + prefix += nums[i - 1] + leftSum[i] = prefix + + for i in range(n - 1, -1, -1): + if i + 1 < n: + suffix += nums[i + 1] + rightSum[i] = suffix + + return [abs(l - r) for l, r in zip(leftSum, rightSum)] diff --git a/solutions/2575. Find the Divisibility Array of a String/2575.cpp b/solutions/2575. Find the Divisibility Array of a String/2575.cpp new file mode 100644 index 00000000000..006815cb9e0 --- /dev/null +++ b/solutions/2575. Find the Divisibility Array of a String/2575.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector divisibilityArray(string word, int m) { + vector ans; + long prevRemainder = 0; + + for (const char c : word) { + const long remainder = (prevRemainder * 10 + (c - '0')) % m; + ans.push_back(remainder == 0 ? 1 : 0); + prevRemainder = remainder; + } + + return ans; + } +}; diff --git a/solutions/2575. Find the Divisibility Array of a String/2575.java b/solutions/2575. Find the Divisibility Array of a String/2575.java new file mode 100644 index 00000000000..fba71d3afd9 --- /dev/null +++ b/solutions/2575. Find the Divisibility Array of a String/2575.java @@ -0,0 +1,14 @@ +class Solution { + public int[] divisibilityArray(String word, int m) { + int[] ans = new int[word.length()]; + long prevRemainder = 0; + + for (int i = 0; i < word.length(); ++i) { + final long remainder = (prevRemainder * 10 + (word.charAt(i) - '0')) % m; + ans[i] = remainder == 0 ? 1 : 0; + prevRemainder = remainder; + } + + return ans; + } +} diff --git a/solutions/2575. Find the Divisibility Array of a String/2575.py b/solutions/2575. Find the Divisibility Array of a String/2575.py new file mode 100644 index 00000000000..66ea7b8c472 --- /dev/null +++ b/solutions/2575. Find the Divisibility Array of a String/2575.py @@ -0,0 +1,11 @@ +class Solution: + def divisibilityArray(self, word: str, m: int) -> List[int]: + ans = [] + prevRemainder = 0 + + for c in word: + remainder = (prevRemainder * 10 + int(c)) % m + ans.append(1 if remainder == 0 else 0) + prevRemainder = remainder + + return ans diff --git a/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.cpp b/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.cpp new file mode 100644 index 00000000000..23641055f32 --- /dev/null +++ b/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int maxNumOfMarkedIndices(vector& nums) { + ranges::sort(nums); + + int i = 0; + for (int j = nums.size() / 2; j < nums.size(); ++j) + if (2 * nums[i] <= nums[j] && ++i == nums.size() / 2) + break; + + return i * 2; + } +}; diff --git a/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.java b/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.java new file mode 100644 index 00000000000..9767b52adde --- /dev/null +++ b/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.java @@ -0,0 +1,12 @@ +class Solution { + public int maxNumOfMarkedIndices(int[] nums) { + Arrays.sort(nums); + + int i = 0; + for (int j = nums.length / 2; j < nums.length; ++j) + if (2 * nums[i] <= nums[j] && ++i == nums.length / 2) + break; + + return i * 2; + } +} diff --git a/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.py b/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.py new file mode 100644 index 00000000000..2479d620cf2 --- /dev/null +++ b/solutions/2576. Find the Maximum Number of Marked Indices/2576-2.py @@ -0,0 +1,12 @@ +class Solution: + def maxNumOfMarkedIndices(self, nums: List[int]) -> int: + nums.sort() + + i = 0 + for j in range(len(nums) // 2, len(nums)): + if 2 * nums[i] <= nums[j]: + i += 1 + if i == len(nums) // 2: + break + + return i * 2 diff --git a/solutions/2576. Find the Maximum Number of Marked Indices/2576.cpp b/solutions/2576. Find the Maximum Number of Marked Indices/2576.cpp new file mode 100644 index 00000000000..47e6570b78d --- /dev/null +++ b/solutions/2576. Find the Maximum Number of Marked Indices/2576.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxNumOfMarkedIndices(vector& nums) { + ranges::sort(nums); + + int l = 0; + int r = nums.size() / 2 + 1; + + while (l < r) { + const int m = (l + r) / 2; + if (isPossible(nums, m)) + l = m + 1; + else + r = m; + } + + return (l - 1) * 2; + } + + private: + bool isPossible(const vector& nums, int m) { + for (int i = 0; i < m; ++i) + if (2 * nums[i] > nums[nums.size() - m + i]) + return false; + return true; + } +}; diff --git a/solutions/2576. Find the Maximum Number of Marked Indices/2576.java b/solutions/2576. Find the Maximum Number of Marked Indices/2576.java new file mode 100644 index 00000000000..b796e6b46e0 --- /dev/null +++ b/solutions/2576. Find the Maximum Number of Marked Indices/2576.java @@ -0,0 +1,25 @@ +class Solution { + public int maxNumOfMarkedIndices(int[] nums) { + Arrays.sort(nums); + + int l = 0; + int r = nums.length / 2 + 1; + + while (l < r) { + final int m = (l + r) / 2; + if (isPossible(nums, m)) + l = m + 1; + else + r = m; + } + + return (l - 1) * 2; + } + + private boolean isPossible(int[] nums, int m) { + for (int i = 0; i < m; ++i) + if (2 * nums[i] > nums[nums.length - m + i]) + return false; + return true; + } +} diff --git a/solutions/2576. Find the Maximum Number of Marked Indices/2576.py b/solutions/2576. Find the Maximum Number of Marked Indices/2576.py new file mode 100644 index 00000000000..8996de0b969 --- /dev/null +++ b/solutions/2576. Find the Maximum Number of Marked Indices/2576.py @@ -0,0 +1,13 @@ +class Solution: + def maxNumOfMarkedIndices(self, nums: List[int]) -> int: + nums.sort() + + def isPossible(m: int) -> bool: + for i in range(m): + if 2 * nums[i] > nums[-m + i]: + return False + return True + + l = bisect.bisect_left(range(len(nums) // 2 + 1), True, + key=lambda m: not isPossible(m)) + return (l - 1) * 2 diff --git a/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.cpp b/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.cpp new file mode 100644 index 00000000000..f7ce480fe84 --- /dev/null +++ b/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int minimumTime(vector>& grid) { + if (grid[0][1] > 1 && grid[1][0] > 1) + return -1; + + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + using T = tuple; // (time, i, j) + priority_queue, greater<>> minHeap; + vector> seen(m, vector(n)); + + minHeap.emplace(0, 0, 0); + seen[0][0] = true; + + while (!minHeap.empty()) { + const auto [time, i, j] = minHeap.top(); + minHeap.pop(); + if (i == m - 1 && j == n - 1) + return time; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + const int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0; + const int nextTime = max(time + 1, grid[x][y] + extraWait); + minHeap.emplace(nextTime, x, y); + seen[x][y] = true; + } + } + + throw; + } +}; diff --git a/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.java b/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.java new file mode 100644 index 00000000000..87f74ef36cd --- /dev/null +++ b/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.java @@ -0,0 +1,38 @@ +class Solution { + public int minimumTime(int[][] grid) { + if (grid[0][1] > 1 && grid[1][0] > 1) + return -1; + + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length; + // (time, i, j) + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + boolean[][] seen = new boolean[m][n]; + + minHeap.offer(new int[] {0, 0, 0}); + seen[0][0] = true; + + while (!minHeap.isEmpty()) { + final int time = minHeap.peek()[0]; + final int i = minHeap.peek()[1]; + final int j = minHeap.poll()[2]; + if (i == m - 1 && j == n - 1) + return time; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + final int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0; + final int nextTime = Math.max(time + 1, grid[x][y] + extraWait); + minHeap.offer(new int[] {nextTime, x, y}); + seen[x][y] = true; + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.py b/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.py new file mode 100644 index 00000000000..9845e7a147b --- /dev/null +++ b/solutions/2577. Minimum Time to Visit a Cell In a Grid/2577.py @@ -0,0 +1,26 @@ +class Solution: + def minimumTime(self, grid: List[List[int]]) -> int: + if grid[0][1] > 1 and grid[1][0] > 1: + return -1 + + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + minHeap = [(0, 0, 0)] # (time, i, j) + seen = {(0, 0)} + + while minHeap: + time, i, j = heapq.heappop(minHeap) + if i == m - 1 and j == n - 1: + return time + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if (x, y) in seen: + continue + extraWait = 1 if (grid[x][y] - time) % 2 == 0 else 0 + nextTime = max(time + 1, grid[x][y] + extraWait) + heapq.heappush(minHeap, (nextTime, x, y)) + seen.add((x, y)) diff --git a/solutions/2578. Split With Minimum Sum/2578.cpp b/solutions/2578. Split With Minimum Sum/2578.cpp new file mode 100644 index 00000000000..bd13d074d5e --- /dev/null +++ b/solutions/2578. Split With Minimum Sum/2578.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int splitNum(int num) { + string num1; + string num2; + string s = to_string(num); + + ranges::sort(s); + + for (int i = 0; i < s.length(); ++i) + if (i % 2 == 0) + num1 += s[i]; + else + num2 += s[i]; + + return stoi(num1) + stoi(num2); + } +}; diff --git a/solutions/2578. Split With Minimum Sum/2578.java b/solutions/2578. Split With Minimum Sum/2578.java new file mode 100644 index 00000000000..582b379eb08 --- /dev/null +++ b/solutions/2578. Split With Minimum Sum/2578.java @@ -0,0 +1,17 @@ +class Solution { + public int splitNum(int num) { + StringBuilder sb1 = new StringBuilder(); + StringBuilder sb2 = new StringBuilder(); + char[] chars = String.valueOf(num).toCharArray(); + + Arrays.sort(chars); + + for (int i = 0; i < chars.length; ++i) + if (i % 2 == 0) + sb1.append(chars[i]); + else + sb2.append(chars[i]); + + return Integer.parseInt(sb1.toString()) + Integer.parseInt(sb2.toString()); + } +} diff --git a/solutions/2578. Split With Minimum Sum/2578.py b/solutions/2578. Split With Minimum Sum/2578.py new file mode 100644 index 00000000000..c09db09cc0a --- /dev/null +++ b/solutions/2578. Split With Minimum Sum/2578.py @@ -0,0 +1,4 @@ +class Solution: + def splitNum(self, num: int) -> int: + s = ''.join(sorted(str(num))) + return sum(map(int, (s[::2], s[1::2]))) diff --git a/solutions/2579. Count Total Number of Colored Cells/2579.cpp b/solutions/2579. Count Total Number of Colored Cells/2579.cpp new file mode 100644 index 00000000000..a7f92c2f80f --- /dev/null +++ b/solutions/2579. Count Total Number of Colored Cells/2579.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + long long coloredCells(int n) { + return static_cast(n) * n + static_cast(n - 1) * (n - 1); + } +}; diff --git a/solutions/2579. Count Total Number of Colored Cells/2579.java b/solutions/2579. Count Total Number of Colored Cells/2579.java new file mode 100644 index 00000000000..00452cbcb64 --- /dev/null +++ b/solutions/2579. Count Total Number of Colored Cells/2579.java @@ -0,0 +1,5 @@ +class Solution { + public long coloredCells(int n) { + return 1L * n * n + 1L * (n - 1) * (n - 1); + } +} diff --git a/solutions/2579. Count Total Number of Colored Cells/2579.py b/solutions/2579. Count Total Number of Colored Cells/2579.py new file mode 100644 index 00000000000..3e62aaa6427 --- /dev/null +++ b/solutions/2579. Count Total Number of Colored Cells/2579.py @@ -0,0 +1,3 @@ +class Solution: + def coloredCells(self, n: int) -> int: + return n**2 + (n - 1)**2 diff --git a/solutions/258. Add Digits/258.cpp b/solutions/258. Add Digits/258.cpp new file mode 100644 index 00000000000..ac7d1f9bbec --- /dev/null +++ b/solutions/258. Add Digits/258.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int addDigits(int num) { + return 1 + (num - 1) % 9; + } +}; diff --git a/solutions/258. Add Digits/258.java b/solutions/258. Add Digits/258.java new file mode 100644 index 00000000000..ce984f09f2a --- /dev/null +++ b/solutions/258. Add Digits/258.java @@ -0,0 +1,5 @@ +class Solution { + public int addDigits(int num) { + return 1 + (num - 1) % 9; + } +} diff --git a/solutions/258. Add Digits/258.py b/solutions/258. Add Digits/258.py new file mode 100644 index 00000000000..6c73ee47cd1 --- /dev/null +++ b/solutions/258. Add Digits/258.py @@ -0,0 +1,3 @@ +class Solution: + def addDigits(self, num: int) -> int: + return 0 if num == 0 else 1 + (num - 1) % 9 diff --git a/solutions/2580. Count Ways to Group Overlapping Ranges/2580.cpp b/solutions/2580. Count Ways to Group Overlapping Ranges/2580.cpp new file mode 100644 index 00000000000..0eb19c3c98c --- /dev/null +++ b/solutions/2580. Count Ways to Group Overlapping Ranges/2580.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int countWays(vector>& ranges) { + constexpr int kMod = 1'000'000'007; + int ans = 1; + int prevEnd = -1; + + ranges::sort(ranges); + + for (const vector& range : ranges) { + const int start = range[0]; + const int end = range[1]; + if (start > prevEnd) + ans = ans * 2 % kMod; + prevEnd = max(prevEnd, end); + } + + return ans; + } +}; diff --git a/solutions/2580. Count Ways to Group Overlapping Ranges/2580.java b/solutions/2580. Count Ways to Group Overlapping Ranges/2580.java new file mode 100644 index 00000000000..9ef61d62baf --- /dev/null +++ b/solutions/2580. Count Ways to Group Overlapping Ranges/2580.java @@ -0,0 +1,19 @@ +class Solution { + public int countWays(int[][] ranges) { + final int kMod = 1_000_000_007; + int ans = 1; + int prevEnd = -1; + + Arrays.sort(ranges, (a, b) -> a[0] - b[0]); + + for (int[] range : ranges) { + final int start = range[0]; + final int end = range[1]; + if (start > prevEnd) + ans = ans * 2 % kMod; + prevEnd = Math.max(prevEnd, end); + } + + return ans; + } +} diff --git a/solutions/2580. Count Ways to Group Overlapping Ranges/2580.py b/solutions/2580. Count Ways to Group Overlapping Ranges/2580.py new file mode 100644 index 00000000000..2684dbd191c --- /dev/null +++ b/solutions/2580. Count Ways to Group Overlapping Ranges/2580.py @@ -0,0 +1,12 @@ +class Solution: + def countWays(self, ranges: List[List[int]]) -> int: + kMod = 1_000_000_007 + ans = 1 + prevEnd = -1 + + for start, end in sorted(ranges): + if start > prevEnd: + ans = ans * 2 % kMod + prevEnd = max(prevEnd, end) + + return ans diff --git a/solutions/2581. Count Number of Possible Root Nodes/2581.cpp b/solutions/2581. Count Number of Possible Root Nodes/2581.cpp new file mode 100644 index 00000000000..a39668dabd9 --- /dev/null +++ b/solutions/2581. Count Number of Possible Root Nodes/2581.cpp @@ -0,0 +1,65 @@ +class Solution { + public: + int rootCount(vector>& edges, vector>& guesses, + int k) { + int ans = 0; + const int n = edges.size() + 1; + vector> graph(n); + vector> guessGraph(n); + vector parent(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + for (const vector& guess : guesses) { + const int u = guess[0]; + const int v = guess[1]; + guessGraph[u].insert(v); + } + + // Precalculate `parent`. + dfs(graph, 0, /*prev=*/-1, parent); + + // Calculate `correctGuess` for tree rooted at 0. + int correctGuess = 0; + for (int i = 1; i < n; ++i) + if (guessGraph[parent[i]].contains(i)) + ++correctGuess; + + reroot(graph, 0, /*prev=*/-1, correctGuess, guessGraph, k, ans); + return ans; + } + + private: + void dfs(const vector>& graph, int u, int prev, + vector& parent) { + parent[u] = prev; + for (const int v : graph[u]) + if (v != prev) + dfs(graph, v, u, parent); + } + + void reroot(const vector>& graph, int u, int prev, + int correctGuess, const vector>& guessGraph, + const int& k, int& ans) { + if (u != 0) { + // The tree is rooted at u, so a guess edge (u, prev) will match the new + // `parent` relationship. + if (guessGraph[u].contains(prev)) + ++correctGuess; + // A guess edge (prev, u) matching the old `parent` relationship will no + // longer be true. + if (guessGraph[prev].contains(u)) + --correctGuess; + } + if (correctGuess >= k) + ++ans; + for (const int v : graph[u]) + if (v != prev) + reroot(graph, v, u, correctGuess, guessGraph, k, ans); + } +}; diff --git a/solutions/2581. Count Number of Possible Root Nodes/2581.java b/solutions/2581. Count Number of Possible Root Nodes/2581.java new file mode 100644 index 00000000000..f796a13336f --- /dev/null +++ b/solutions/2581. Count Number of Possible Root Nodes/2581.java @@ -0,0 +1,66 @@ +class Solution { + public int rootCount(int[][] edges, int[][] guesses, int k) { + final int n = edges.length + 1; + List[] graph = new List[n]; + Set[] guessGraph = new Set[n]; + int[] parent = new int[n]; + + for (int i = 0; i < n; ++i) { + graph[i] = new ArrayList<>(); + guessGraph[i] = new HashSet<>(); + } + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + for (int[] guess : guesses) { + final int u = guess[0]; + final int v = guess[1]; + guessGraph[u].add(v); + } + + // Precalculate `parent`. + dfs(graph, 0, /*prev=*/-1, parent); + + // Calculate `correctGuess` for tree rooted at 0. + int correctGuess = 0; + for (int i = 1; i < n; ++i) + if (guessGraph[parent[i]].contains(i)) + ++correctGuess; + + reroot(graph, 0, /*prev=*/-1, correctGuess, guessGraph, k); + return ans; + } + + private int ans = 0; + + private void dfs(List[] graph, int u, int prev, int[] parent) { + parent[u] = prev; + for (final int v : graph[u]) + if (v != prev) + dfs(graph, v, u, parent); + } + + private void reroot(List[] graph, int u, int prev, int correctGuess, + Set[] guessGraph, int k) { + if (u != 0) { + // The tree is rooted at u, so a guess edge (u, prev) will match the new + // `parent` relationship. + if (guessGraph[u].contains(prev)) + ++correctGuess; + // A guess edge (prev, u) matching the old `parent` relationship will no + // longer be true. + if (guessGraph[prev].contains(u)) + --correctGuess; + } + if (correctGuess >= k) + ++ans; + for (final int v : graph[u]) + if (v != prev) + reroot(graph, v, u, correctGuess, guessGraph, k); + } +} diff --git a/solutions/2581. Count Number of Possible Root Nodes/2581.py b/solutions/2581. Count Number of Possible Root Nodes/2581.py new file mode 100644 index 00000000000..d938935ff37 --- /dev/null +++ b/solutions/2581. Count Number of Possible Root Nodes/2581.py @@ -0,0 +1,46 @@ +class Solution: + def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int: + ans = 0 + n = len(edges) + 1 + graph = [[] for _ in range(n)] + guessGraph = [set() for _ in range(n)] + parent = [0] * n + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + for u, v in guesses: + guessGraph[u].add(v) + + def dfs(u: int, prev: int) -> None: + parent[u] = prev + for v in graph[u]: + if v != prev: + dfs(v, u) + + # Precalculate `parent`. + dfs(0, -1) + + # Calculate `correctGuess` for tree rooted at 0. + correctGuess = sum(i in guessGraph[parent[i]] for i in range(1, n)) + + def reroot(u: int, prev: int, correctGuess: int) -> None: + nonlocal ans + if u != 0: + # The tree is rooted at u, so a guess edge (u, prev) will match the new + # `parent` relationship. + if prev in guessGraph[u]: + correctGuess += 1 + # A guess edge (prev, u) matching the old `parent` relationship will no + # longer be True. + if u in guessGraph[prev]: + correctGuess -= 1 + if correctGuess >= k: + ans += 1 + for v in graph[u]: + if v != prev: + reroot(v, u, correctGuess) + + reroot(0, -1, correctGuess) + return ans diff --git a/solutions/2582. Pass the Pillow/2582.cpp b/solutions/2582. Pass the Pillow/2582.cpp new file mode 100644 index 00000000000..88dc8399faf --- /dev/null +++ b/solutions/2582. Pass the Pillow/2582.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int passThePillow(int n, int time) { + // Repeat every (n - 1) * 2 seconds. + time %= (n - 1) * 2; + if (time < n) // Go forward from 1. + return 1 + time; + return n - (time - (n - 1)); // Go backward from n. + } +}; diff --git a/solutions/2582. Pass the Pillow/2582.java b/solutions/2582. Pass the Pillow/2582.java new file mode 100644 index 00000000000..f0b4814649e --- /dev/null +++ b/solutions/2582. Pass the Pillow/2582.java @@ -0,0 +1,9 @@ +class Solution { + public int passThePillow(int n, int time) { + // Repeat every (n - 1) * 2 seconds. + time %= (n - 1) * 2; + if (time < n) // Go forward from 1. + return 1 + time; + return n - (time - (n - 1)); // Go backward from n. + } +} diff --git a/solutions/2582. Pass the Pillow/2582.py b/solutions/2582. Pass the Pillow/2582.py new file mode 100644 index 00000000000..14dc2d516ba --- /dev/null +++ b/solutions/2582. Pass the Pillow/2582.py @@ -0,0 +1,7 @@ +class Solution: + def passThePillow(self, n: int, time: int) -> int: + # Repeat every (n - 1) * 2 seconds. + time %= (n - 1) * 2 + if time < n: # Go forward from 1. + return 1 + time + return n - (time - (n - 1)) # Go backward from n. diff --git a/solutions/2583. Kth Largest Sum in a Binary Tree/2583.cpp b/solutions/2583. Kth Largest Sum in a Binary Tree/2583.cpp new file mode 100644 index 00000000000..1da4387ecae --- /dev/null +++ b/solutions/2583. Kth Largest Sum in a Binary Tree/2583.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long kthLargestLevelSum(TreeNode* root, int k) { + vector levelSums; + dfs(root, 0, levelSums); + if (levelSums.size() < k) + return -1; + + nth_element(levelSums.begin(), levelSums.begin() + k - 1, levelSums.end(), + greater<>()); + return levelSums[k - 1]; + } + + private: + void dfs(TreeNode* root, int level, vector& levelSums) { + if (root == nullptr) + return; + if (levelSums.size() == level) + levelSums.push_back(0); + levelSums[level] += root->val; + dfs(root->left, level + 1, levelSums); + dfs(root->right, level + 1, levelSums); + } +}; diff --git a/solutions/2583. Kth Largest Sum in a Binary Tree/2583.java b/solutions/2583. Kth Largest Sum in a Binary Tree/2583.java new file mode 100644 index 00000000000..a22aff5e5b3 --- /dev/null +++ b/solutions/2583. Kth Largest Sum in a Binary Tree/2583.java @@ -0,0 +1,21 @@ +class Solution { + public long kthLargestLevelSum(TreeNode root, int k) { + List levelSums = new ArrayList<>(); + dfs(root, 0, levelSums); + if (levelSums.size() < k) + return -1; + + Collections.sort(levelSums, Collections.reverseOrder()); + return levelSums.get(k - 1); + } + + private void dfs(TreeNode root, int level, List levelSums) { + if (root == null) + return; + if (levelSums.size() == level) + levelSums.add(0L); + levelSums.set(level, levelSums.get(level) + root.val); + dfs(root.left, level + 1, levelSums); + dfs(root.right, level + 1, levelSums); + } +} diff --git a/solutions/2583. Kth Largest Sum in a Binary Tree/2583.py b/solutions/2583. Kth Largest Sum in a Binary Tree/2583.py new file mode 100644 index 00000000000..e84dee17aca --- /dev/null +++ b/solutions/2583. Kth Largest Sum in a Binary Tree/2583.py @@ -0,0 +1,18 @@ +class Solution: + def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int: + levelSums = [] + + def dfs(root: Optional[TreeNode], level: int) -> None: + if not root: + return + if len(levelSums) == level: + levelSums.append(0) + levelSums[level] += root.val + dfs(root.left, level + 1) + dfs(root.right, level + 1) + + dfs(root, 0) + if len(levelSums) < k: + return -1 + + return sorted(levelSums, reverse=True)[k - 1] diff --git a/solutions/2584. Split the Array to Make Coprime Products/2584.cpp b/solutions/2584. Split the Array to Make Coprime Products/2584.cpp new file mode 100644 index 00000000000..61a98eec889 --- /dev/null +++ b/solutions/2584. Split the Array to Make Coprime Products/2584.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int findValidSplit(vector& nums) { + unordered_map leftPrimeFactors; + unordered_map rightPrimeFactors; + + for (const int num : nums) + for (const int primeFactor : getPrimeFactors(num)) + ++rightPrimeFactors[primeFactor]; + + for (int i = 0; i < nums.size() - 1; ++i) { + for (const int primeFactor : getPrimeFactors(nums[i])) { + if (--rightPrimeFactors[primeFactor] == 0) { + // rightPrimeFactors[primeFactor] == 0, so no need to track + // leftPrimeFactors[primeFactor]. + rightPrimeFactors.erase(primeFactor); + leftPrimeFactors.erase(primeFactor); + } else { + // Otherwise, need to track leftPrimeFactors[primeFactor]. + ++leftPrimeFactors[primeFactor]; + } + } + if (leftPrimeFactors.empty()) + return i; + } + + return -1; + } + + private: + // Gets the prime factors under sqrt(10^6). + vector getPrimeFactors(int num) { + vector primeFactors; + for (int divisor = 2; divisor <= min(1000, num); ++divisor) + if (num % divisor == 0) { + primeFactors.push_back(divisor); + while (num % divisor == 0) + num /= divisor; + } + // Handle the case that `num` contains a prime factor > 1000. + if (num > 1) + primeFactors.push_back(num); + return primeFactors; + } +}; diff --git a/solutions/2584. Split the Array to Make Coprime Products/2584.java b/solutions/2584. Split the Array to Make Coprime Products/2584.java new file mode 100644 index 00000000000..e4d7bccae2e --- /dev/null +++ b/solutions/2584. Split the Array to Make Coprime Products/2584.java @@ -0,0 +1,44 @@ +class Solution { + public int findValidSplit(int[] nums) { + Map leftPrimeFactors = new HashMap<>(); + Map rightPrimeFactors = new HashMap<>(); + + for (final int num : nums) + for (final int primeFactor : getPrimeFactors(num)) + rightPrimeFactors.merge(primeFactor, 1, Integer::sum); + + for (int i = 0; i < nums.length - 1; ++i) { + for (final int primeFactor : getPrimeFactors(nums[i])) { + rightPrimeFactors.merge(primeFactor, -1, Integer::sum); + if (rightPrimeFactors.get(primeFactor) == 0) { + // rightPrimeFactors[primeFactor] == 0, so no need to track + // leftPrimeFactors[primeFactor]. + rightPrimeFactors.remove(primeFactor); + leftPrimeFactors.remove(primeFactor); + } else { + // Otherwise, need to track leftPrimeFactors[primeFactor]. + leftPrimeFactors.merge(primeFactor, 1, Integer::sum); + } + } + if (leftPrimeFactors.isEmpty()) + return i; + } + + return -1; + } + + // Gets the prime factors under sqrt(10^6). + private List getPrimeFactors(int num) { + List primeFactors = new ArrayList<>(); + for (int divisor = 2; divisor <= Math.min(1000, num); ++divisor) + if (num % divisor == 0) { + primeFactors.add(divisor); + while (num % divisor == 0) + num /= divisor; + } + // Handle the case that `num` contains a prime factor > 1000. + if (num > 1) + primeFactors.add(num); + return primeFactors; + } +} diff --git a/solutions/2584. Split the Array to Make Coprime Products/2584.py b/solutions/2584. Split the Array to Make Coprime Products/2584.py new file mode 100644 index 00000000000..66906c3eaf8 --- /dev/null +++ b/solutions/2584. Split the Array to Make Coprime Products/2584.py @@ -0,0 +1,37 @@ +class Solution: + def findValidSplit(self, nums: List[int]) -> int: + leftPrimeFactors = collections.Counter() + rightPrimeFactors = collections.Counter() + + def getPrimeFactors(num: int) -> List[int]: + """Gets the prime factors under sqrt(10^6).""" + primeFactors = [] + for divisor in range(2, min(1000, num) + 1): + if num % divisor == 0: + primeFactors.append(divisor) + while num % divisor == 0: + num //= divisor + # Handle the case that `num` contains a prime factor > 1000. + if num > 1: + primeFactors.append(num) + return primeFactors + + for num in nums: + for primeFactor in getPrimeFactors(num): + rightPrimeFactors[primeFactor] += 1 + + for i in range(len(nums) - 1): + for primeFactor in getPrimeFactors(nums[i]): + rightPrimeFactors[primeFactor] -= 1 + if rightPrimeFactors[primeFactor] == 0: + # rightPrimeFactors[primeFactor] == 0, so no need to track + # leftPrimeFactors[primeFactor]. + del rightPrimeFactors[primeFactor] + del leftPrimeFactors[primeFactor] + else: + # Otherwise, need to track leftPrimeFactors[primeFactor]. + leftPrimeFactors[primeFactor] += 1 + if not leftPrimeFactors: + return i + + return -1 diff --git a/solutions/2585. Number of Ways to Earn Points/2585-2.cpp b/solutions/2585. Number of Ways to Earn Points/2585-2.cpp new file mode 100644 index 00000000000..35861d1331a --- /dev/null +++ b/solutions/2585. Number of Ways to Earn Points/2585-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int waysToReachTarget(int target, vector>& types) { + constexpr int kMod = 1'000'000'007; + // dp[j] := the number of ways to earn j points with the types so far + vector dp(target + 1); + dp[0] = 1; + + for (const vector& type : types) { + const int count = type[0]; + const int mark = type[1]; + for (int j = target; j >= 0; --j) + for (int solved = 1; solved <= count; ++solved) + if (j - solved * mark >= 0) { + dp[j] += dp[j - solved * mark]; + dp[j] %= kMod; + } + } + + return dp[target]; + } +}; diff --git a/solutions/2585. Number of Ways to Earn Points/2585-2.java b/solutions/2585. Number of Ways to Earn Points/2585-2.java new file mode 100644 index 00000000000..8d36c1d1408 --- /dev/null +++ b/solutions/2585. Number of Ways to Earn Points/2585-2.java @@ -0,0 +1,21 @@ +class Solution { + public int waysToReachTarget(int target, int[][] types) { + final int kMod = 1_000_000_007; + // dp[j] := the number of ways to earn j points with the types so far + int[] dp = new int[target + 1]; + dp[0] = 1; + + for (int[] type : types) { + final int count = type[0]; + final int mark = type[1]; + for (int j = target; j >= 0; --j) + for (int solved = 1; solved <= count; ++solved) + if (j - solved * mark >= 0) { + dp[j] += dp[j - solved * mark]; + dp[j] %= kMod; + } + } + + return dp[target]; + } +} diff --git a/solutions/2585. Number of Ways to Earn Points/2585-2.py b/solutions/2585. Number of Ways to Earn Points/2585-2.py new file mode 100644 index 00000000000..bb68e9a9fc8 --- /dev/null +++ b/solutions/2585. Number of Ways to Earn Points/2585-2.py @@ -0,0 +1,14 @@ +class Solution: + def waysToReachTarget(self, target: int, types: List[List[int]]) -> int: + kMod = 1_000_000_007 + # dp[j] := the number of ways to earn j points with the types so far + dp = [1] + [0] * target + + for count, mark in types: + for j in range(target, -1, -1): + for solved in range(1, count + 1): + if j - solved * mark >= 0: + dp[j] += dp[j - solved * mark] + dp[j] %= kMod + + return dp[target] diff --git a/solutions/2585. Number of Ways to Earn Points/2585.cpp b/solutions/2585. Number of Ways to Earn Points/2585.cpp new file mode 100644 index 00000000000..75fc7978342 --- /dev/null +++ b/solutions/2585. Number of Ways to Earn Points/2585.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int waysToReachTarget(int target, vector>& types) { + constexpr int kMod = 1'000'000'007; + // dp[i][j] := the number of ways to earn j points with the first i types + vector> dp(types.size() + 1, vector(target + 1)); + dp[0][0] = 1; + + for (int i = 1; i <= types.size(); ++i) { + const int count = types[i - 1][0]; + const int mark = types[i - 1][1]; + for (int j = 0; j <= target; ++j) + for (int solved = 0; solved <= count; ++solved) + if (j - solved * mark >= 0) { + dp[i][j] += dp[i - 1][j - solved * mark]; + dp[i][j] %= kMod; + } + } + + return dp[types.size()][target]; + } +}; diff --git a/solutions/2585. Number of Ways to Earn Points/2585.java b/solutions/2585. Number of Ways to Earn Points/2585.java new file mode 100644 index 00000000000..43125eca9c5 --- /dev/null +++ b/solutions/2585. Number of Ways to Earn Points/2585.java @@ -0,0 +1,21 @@ +class Solution { + public int waysToReachTarget(int target, int[][] types) { + final int kMod = 1_000_000_007; + // dp[i][j] := the number of ways to earn j points with the first i types + int[][] dp = new int[types.length + 1][target + 1]; + dp[0][0] = 1; + + for (int i = 1; i <= types.length; ++i) { + final int count = types[i - 1][0]; + final int mark = types[i - 1][1]; + for (int j = 0; j <= target; ++j) + for (int solved = 0; solved <= count; ++solved) + if (j - solved * mark >= 0) { + dp[i][j] += dp[i - 1][j - solved * mark]; + dp[i][j] %= kMod; + } + } + + return dp[types.length][target]; + } +} diff --git a/solutions/2585. Number of Ways to Earn Points/2585.py b/solutions/2585. Number of Ways to Earn Points/2585.py new file mode 100644 index 00000000000..d3e5330ce18 --- /dev/null +++ b/solutions/2585. Number of Ways to Earn Points/2585.py @@ -0,0 +1,17 @@ +class Solution: + def waysToReachTarget(self, target: int, types: List[List[int]]) -> int: + kMod = 1_000_000_007 + # dp[i][j] := the number of ways to earn j points with the first i types + dp = [[0] * (target + 1) for _ in range(len(types) + 1)] + dp[0][0] = 1 + + for i in range(1, len(types) + 1): + count = types[i - 1][0] + mark = types[i - 1][1] + for j in range(target + 1): + for solved in range(count + 1): + if j - solved * mark >= 0: + dp[i][j] += dp[i - 1][j - solved * mark] + dp[i][j] %= kMod + + return dp[len(types)][target] diff --git a/solutions/2586. Count the Number of Vowel Strings in Range/2586.cpp b/solutions/2586. Count the Number of Vowel Strings in Range/2586.cpp new file mode 100644 index 00000000000..2e209ea4e06 --- /dev/null +++ b/solutions/2586. Count the Number of Vowel Strings in Range/2586.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int vowelStrings(vector& words, int left, int right) { + return count_if(words.begin() + left, words.begin() + right + 1, + [=](const string& word) { + return isVowel(word.front()) && isVowel(word.back()); + }); + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiou"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/2586. Count the Number of Vowel Strings in Range/2586.java b/solutions/2586. Count the Number of Vowel Strings in Range/2586.java new file mode 100644 index 00000000000..530b1140c6d --- /dev/null +++ b/solutions/2586. Count the Number of Vowel Strings in Range/2586.java @@ -0,0 +1,13 @@ +class Solution { + public int vowelStrings(String[] words, int left, int right) { + return (int) Arrays.asList(words) + .subList(left, right + 1) + .stream() + .filter(word -> isVowel(word.charAt(0)) && isVowel(word.charAt(word.length() - 1))) + .count(); + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(c) != -1; + } +} diff --git a/solutions/2586. Count the Number of Vowel Strings in Range/2586.py b/solutions/2586. Count the Number of Vowel Strings in Range/2586.py new file mode 100644 index 00000000000..577c92feb68 --- /dev/null +++ b/solutions/2586. Count the Number of Vowel Strings in Range/2586.py @@ -0,0 +1,5 @@ +class Solution: + def vowelStrings(self, words: List[str], left: int, right: int) -> int: + kVowels = 'aeiou' + return sum(word[0] in kVowels and word[-1] in kVowels + for word in words[left:right + 1]) diff --git a/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.cpp b/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.cpp new file mode 100644 index 00000000000..1d1a7cf1ca2 --- /dev/null +++ b/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxScore(vector& nums) { + long prefix = 0; + + ranges::sort(nums, greater<>()); + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i]; + if (prefix <= 0) + return i; + } + + return nums.size(); + } +}; diff --git a/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.java b/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.java new file mode 100644 index 00000000000..77841872419 --- /dev/null +++ b/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.java @@ -0,0 +1,19 @@ +class Solution { + public int maxScore(int[] nums) { + long prefix = 0; + + nums = Arrays.stream(nums) + .boxed() + .sorted(Collections.reverseOrder()) + .mapToInt(Integer::intValue) + .toArray(); + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i]; + if (prefix <= 0) + return i; + } + + return nums.length; + } +} diff --git a/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.py b/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.py new file mode 100644 index 00000000000..05d88fa7c47 --- /dev/null +++ b/solutions/2587. Rearrange Array to Maximize Prefix Score/2587.py @@ -0,0 +1,4 @@ +class Solution: + def maxScore(self, nums: List[int]) -> int: + return sum(num > 0 + for num in itertools.accumulate(sorted(nums, reverse=True))) diff --git a/solutions/2588. Count the Number of Beautiful Subarrays/2588.cpp b/solutions/2588. Count the Number of Beautiful Subarrays/2588.cpp new file mode 100644 index 00000000000..9a06b3cd337 --- /dev/null +++ b/solutions/2588. Count the Number of Beautiful Subarrays/2588.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + long long beautifulSubarrays(vector& nums) { + // A subarray is beautiful if xor(subarray) = 0. + long ans = 0; + int prefix = 0; + unordered_map prefixCount{{0, 1}}; + + for (const int num : nums) { + prefix ^= num; + ans += prefixCount[prefix]++; + } + + return ans; + } +}; diff --git a/solutions/2588. Count the Number of Beautiful Subarrays/2588.java b/solutions/2588. Count the Number of Beautiful Subarrays/2588.java new file mode 100644 index 00000000000..3a588e118c3 --- /dev/null +++ b/solutions/2588. Count the Number of Beautiful Subarrays/2588.java @@ -0,0 +1,17 @@ +class Solution { + public long beautifulSubarrays(int[] nums) { + // A subarray is beautiful if xor(subarray) = 0. + long ans = 0; + int prefix = 0; + Map prefixCount = new HashMap<>(); + prefixCount.put(0, 1); + + for (final int num : nums) { + prefix ^= num; + ans += prefixCount.getOrDefault(prefix, 0); + prefixCount.merge(prefix, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/2588. Count the Number of Beautiful Subarrays/2588.py b/solutions/2588. Count the Number of Beautiful Subarrays/2588.py new file mode 100644 index 00000000000..b08ee4aaf9d --- /dev/null +++ b/solutions/2588. Count the Number of Beautiful Subarrays/2588.py @@ -0,0 +1,13 @@ +class Solution: + def beautifulSubarrays(self, nums: List[int]) -> int: + # A subarray is beautiful if xor(subarray) = 0. + ans = 0 + prefix = 0 + prefixCount = collections.Counter({0: 1}) + + for num in nums: + prefix ^= num + ans += prefixCount[prefix] + prefixCount[prefix] += 1 + + return ans diff --git a/solutions/2589. Minimum Time to Complete All Tasks/2589.cpp b/solutions/2589. Minimum Time to Complete All Tasks/2589.cpp new file mode 100644 index 00000000000..976ac59b037 --- /dev/null +++ b/solutions/2589. Minimum Time to Complete All Tasks/2589.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int findMinimumTime(vector>& tasks) { + constexpr int kMax = 2000; + vector running(kMax + 1); + + // Sort tasks by end. + sort( + tasks.begin(), tasks.end(), + [](const vector& a, const vector& b) { return a[1] < b[1]; }); + + for (const vector& task : tasks) { + const int start = task[0]; + const int end = task[1]; + const int duration = task[2]; + int neededDuration = duration - count(running.begin() + start, + running.begin() + end + 1, true); + // Greedily run the task as late as possible so that later tasks can run + // simultaneously. + for (int i = end; neededDuration > 0; --i) { + if (!running[i]) { + running[i] = true; + --neededDuration; + } + } + } + + return ranges::count(running, true); + } +}; diff --git a/solutions/2589. Minimum Time to Complete All Tasks/2589.java b/solutions/2589. Minimum Time to Complete All Tasks/2589.java new file mode 100644 index 00000000000..7d8b1472ec2 --- /dev/null +++ b/solutions/2589. Minimum Time to Complete All Tasks/2589.java @@ -0,0 +1,32 @@ +class Solution { + public int findMinimumTime(int[][] tasks) { + final int kMax = 2000; + boolean[] running = new boolean[kMax + 1]; + + // Sort tasks by end. + Arrays.sort(tasks, (a, b) -> a[1] - b[1]); + + for (int[] task : tasks) { + final int start = task[0]; + final int end = task[1]; + final int duration = task[2]; + int neededDuration = duration; + for (int i = start; i <= end; ++i) + if (running[i]) + --neededDuration; + // Greedily run the task as late as possible so that later tasks can run + // simultaneously. + for (int i = end; neededDuration > 0; --i) { + if (!running[i]) { + running[i] = true; + --neededDuration; + } + } + } + + return (int) IntStream.range(0, running.length) + .mapToObj(i -> running[i]) + .filter(r -> r) + .count(); + } +} diff --git a/solutions/2589. Minimum Time to Complete All Tasks/2589.py b/solutions/2589. Minimum Time to Complete All Tasks/2589.py new file mode 100644 index 00000000000..5e88a8dd9cf --- /dev/null +++ b/solutions/2589. Minimum Time to Complete All Tasks/2589.py @@ -0,0 +1,19 @@ +class Solution: + def findMinimumTime(self, tasks: List[List[int]]) -> int: + kMax = 2000 + running = [False] * (kMax + 1) + + # Sort tasks by end. + for start, end, duration in sorted(tasks, key=lambda x: x[1]): + neededDuration = duration - \ + sum(running[i] for i in range(start, end + 1)) + # Greedily run the task as late as possible so that later tasks can run + # simultaneously. + i = end + while neededDuration > 0: + if not running[i]: + running[i] = True + neededDuration -= 1 + i -= 1 + + return sum(running) diff --git a/solutions/259. 3Sum Smaller/259.cpp b/solutions/259. 3Sum Smaller/259.cpp new file mode 100644 index 00000000000..0f1f17ab832 --- /dev/null +++ b/solutions/259. 3Sum Smaller/259.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int threeSumSmaller(vector& nums, int target) { + if (nums.size() < 3) + return 0; + + int ans = 0; + + ranges::sort(nums); + + for (int i = 0; i + 2 < nums.size(); ++i) { + int l = i + 1; + int r = nums.size() - 1; + while (l < r) + if (nums[i] + nums[l] + nums[r] < target) { + // (nums[i], nums[l], nums[r]) + // (nums[i], nums[l], nums[r - 1]) + // ..., + // (nums[i], nums[l], nums[l + 1]) + ans += r - l; + ++l; + } else { + --r; + } + } + + return ans; + } +}; diff --git a/solutions/259. 3Sum Smaller/259.java b/solutions/259. 3Sum Smaller/259.java new file mode 100644 index 00000000000..133a0f757d5 --- /dev/null +++ b/solutions/259. 3Sum Smaller/259.java @@ -0,0 +1,28 @@ +class Solution { + public int threeSumSmaller(int[] nums, int target) { + if (nums.length < 3) + return 0; + + int ans = 0; + + Arrays.sort(nums); + + for (int i = 0; i + 2 < nums.length; ++i) { + int l = i + 1; + int r = nums.length - 1; + while (l < r) + if (nums[i] + nums[l] + nums[r] < target) { + // (nums[i], nums[l], nums[r]) + // (nums[i], nums[l], nums[r - 1]) + // ..., + // (nums[i], nums[l], nums[l + 1]) + ans += r - l; + ++l; + } else { + --r; + } + } + + return ans; + } +} diff --git a/solutions/259. 3Sum Smaller/259.py b/solutions/259. 3Sum Smaller/259.py new file mode 100644 index 00000000000..35474ec85d2 --- /dev/null +++ b/solutions/259. 3Sum Smaller/259.py @@ -0,0 +1,24 @@ +class Solution: + def threeSumSmaller(self, nums: List[int], target: int) -> int: + if len(nums) < 3: + return 0 + + ans = 0 + + nums.sort() + + for i in range(len(nums) - 2): + l = i + 1 + r = len(nums) - 1 + while l < r: + if nums[i] + nums[l] + nums[r] < target: + # (nums[i], nums[l], nums[r]) + # (nums[i], nums[l], nums[r - 1]) + # ..., + # (nums[i], nums[l], nums[l + 1]) + ans += r - l + l += 1 + else: + r -= 1 + + return ans diff --git a/solutions/2590. Design a Todo List/2590.cpp b/solutions/2590. Design a Todo List/2590.cpp new file mode 100644 index 00000000000..859c278573b --- /dev/null +++ b/solutions/2590. Design a Todo List/2590.cpp @@ -0,0 +1,66 @@ +struct Task { + // int taskId; + string taskDescription; + int dueDate; + unordered_set tags; + + bool operator<(const Task& other) const { + return dueDate < other.dueDate; + } +}; + +class TodoList { + public: + int addTask(int userId, string taskDescription, int dueDate, + vector tags) { + userIdToTaskIdToTasks[userId][++taskId] = + Task{.taskDescription = taskDescription, + .dueDate = dueDate, + .tags = {tags.begin(), tags.end()}}; + taskIds.insert(taskId); + return taskId; + } + + vector getAllTasks(int userId) { + vector res; + for (const Task& task : getTasksSortedByDueDate(userId)) + res.push_back(task.taskDescription); + return res; + } + + vector getTasksForTag(int userId, string tag) { + vector res; + for (const Task& task : getTasksSortedByDueDate(userId)) + if (task.tags.contains(tag)) + res.push_back(task.taskDescription); + return res; + } + + void completeTask(int userId, int taskId) { + if (!taskIds.contains(taskId)) + return; + const auto it = userIdToTaskIdToTasks.find(userId); + if (it == userIdToTaskIdToTasks.cend()) + return; + auto& taskIdToTasks = it->second; + if (!taskIdToTasks.contains(taskId)) + return; + taskIdToTasks.erase(taskId); + } + + private: + int taskId = 0; + unordered_set taskIds; + // {userId: {taskId: tasks}} + unordered_map> userIdToTaskIdToTasks; + + vector getTasksSortedByDueDate(int userId) { + const auto it = userIdToTaskIdToTasks.find(userId); + if (it == userIdToTaskIdToTasks.cend()) + return {}; + set tasks; + for (const auto& [_, task] : it->second) + tasks.insert(task); + return {tasks.begin(), tasks.end()}; + } +}; diff --git a/solutions/2590. Design a Todo List/2590.java b/solutions/2590. Design a Todo List/2590.java new file mode 100644 index 00000000000..136919bd0cf --- /dev/null +++ b/solutions/2590. Design a Todo List/2590.java @@ -0,0 +1,49 @@ +class TodoList { + public int addTask(int userId, String taskDescription, int dueDate, List tags) { + userIdToTaskIdToTasks.putIfAbsent(userId, new HashMap<>()); + userIdToTaskIdToTasks.get(userId).put(++taskId, new Task(taskDescription, dueDate, tags)); + taskIds.add(taskId); + return taskId; + } + + public List getAllTasks(int userId) { + List res = new ArrayList<>(); + for (Task task : getTasksSortedByDueDate(userId)) + res.add(task.taskDescription); + return res; + } + + public List getTasksForTag(int userId, String tag) { + List res = new ArrayList<>(); + for (Task task : getTasksSortedByDueDate(userId)) + if (task.tags.contains(tag)) + res.add(task.taskDescription); + return res; + } + + public void completeTask(int userId, int taskId) { + if (!taskIds.contains(taskId)) + return; + if (!userIdToTaskIdToTasks.containsKey(userId)) + return; + Map taskIdToTasks = userIdToTaskIdToTasks.get(userId); + if (!taskIdToTasks.containsKey(taskId)) + return; + taskIdToTasks.remove(taskId); + } + + private record Task(String taskDescription, int dueDate, List tags) {} + private int taskId = 0; + private Set taskIds = new HashSet<>(); + // {userId: {taskId: tasks}} + private Map> userIdToTaskIdToTasks = new HashMap<>(); + + private List getTasksSortedByDueDate(int userId) { + if (!userIdToTaskIdToTasks.containsKey(userId)) + return new ArrayList<>(); + TreeSet tasks = new TreeSet<>((a, b) -> a.dueDate - b.dueDate); + for (Task task : userIdToTaskIdToTasks.get(userId).values()) + tasks.add(task); + return new ArrayList<>(tasks); + } +} diff --git a/solutions/2590. Design a Todo List/2590.py b/solutions/2590. Design a Todo List/2590.py new file mode 100644 index 00000000000..38e20163e7e --- /dev/null +++ b/solutions/2590. Design a Todo List/2590.py @@ -0,0 +1,47 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Task: + taskDescription: str + dueDate: int + tags: List[str] + + +class TodoList: + def __init__(self): + self.taskId = 0 + self.taskIds = set() + self.userIdToTaskIdToTasks: Dict[int, Dict[int, List[Task]]] = {} + + def addTask(self, userId: int, taskDescription: str, dueDate: int, tags: List[str]) -> int: + self.taskId += 1 + taskIdToTasks = self.userIdToTaskIdToTasks.setdefault(userId, {}) + taskIdToTasks[self.taskId] = Task(taskDescription, dueDate, tags) + self.taskIds.add(self.taskId) + return self.taskId + + def getAllTasks(self, userId: int) -> List[str]: + return [task.taskDescription + for task in self._getTasksSortedByDueDate(userId)] + + def getTasksForTag(self, userId: int, tag: str) -> List[str]: + return [task.taskDescription + for task in self._getTasksSortedByDueDate(userId) + if tag in task.tags] + + def completeTask(self, userId: int, taskId: int) -> None: + if taskId not in self.taskIds: + return + if userId not in self.userIdToTaskIdToTasks: + return + taskIdToTasks = self.userIdToTaskIdToTasks[userId] + if taskId not in taskIdToTasks: + return + del taskIdToTasks[taskId] + + def _getTasksSortedByDueDate(self, userId: int) -> List[Task]: + if userId not in self.userIdToTaskIdToTasks: + return [] + taskIdToTasks = self.userIdToTaskIdToTasks[userId] + return sorted([task for task in taskIdToTasks.values()], key=lambda x: x.dueDate) diff --git a/solutions/2591. Distribute Money to Maximum Children/2591.cpp b/solutions/2591. Distribute Money to Maximum Children/2591.cpp new file mode 100644 index 00000000000..c7630f283bd --- /dev/null +++ b/solutions/2591. Distribute Money to Maximum Children/2591.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int distMoney(int money, int children) { + // Everyone must receive at least 1 dollar. + money -= children; + if (money < 0) + return -1; + + const int count7 = money / 7; + const int remaining = money % 7; + + // Distribute 8 dollars to every child. + if (count7 == children && remaining == 0) + return count7; + + // Need to move 1 dollar from the last child with 4 dollars to one of other + // children. That's why we need to substract 1. + if (count7 == children - 1 && remaining == 3) + return count7 - 1; + + // Though there might be child with 4 dollars, since count7 < children - 1, + // we have "extra" spot to move money to if needed. + return min(children - 1, count7); + } +}; diff --git a/solutions/2591. Distribute Money to Maximum Children/2591.java b/solutions/2591. Distribute Money to Maximum Children/2591.java new file mode 100644 index 00000000000..5ee00f60060 --- /dev/null +++ b/solutions/2591. Distribute Money to Maximum Children/2591.java @@ -0,0 +1,24 @@ +class Solution { + public int distMoney(int money, int children) { + // Everyone must receive at least 1 dollar. + money -= children; + if (money < 0) + return -1; + + final int count7 = money / 7; + final int remaining = money % 7; + + // Distribute 8 dollars to every child. + if (count7 == children && remaining == 0) + return count7; + + // Need to move 1 dollar from the last child with 4 dollars to one of other + // children. That's why we need to substract 1. + if (count7 == children - 1 && remaining == 3) + return count7 - 1; + + // Though there might be child with 4 dollars, since count7 < children - 1, + // we have "extra" spot to move money to if needed. + return Math.min(children - 1, count7); + } +} diff --git a/solutions/2591. Distribute Money to Maximum Children/2591.py b/solutions/2591. Distribute Money to Maximum Children/2591.py new file mode 100644 index 00000000000..6a94cf3b6e9 --- /dev/null +++ b/solutions/2591. Distribute Money to Maximum Children/2591.py @@ -0,0 +1,22 @@ +class Solution: + def distMoney(self, money: int, children: int) -> int: + # Everyone must receive at least 1 dollar. + money -= children + if money < 0: + return -1 + + count7 = money // 7 + remaining = money % 7 + + # Distribute 8 dollars to every child. + if count7 == children and remaining == 0: + return count7 + + # Need to move 1 dollar from the last child with 4 dollars to one of other + # children. That's why we need to substract 1. + if count7 == children - 1 and remaining == 3: + return count7 - 1 + + # Though there might be child with 4 dollars, since count7 < children - 1, + # we have 'extra' spot to move money to if needed. + return min(children - 1, count7) diff --git a/solutions/2592. Maximize Greatness of an Array/2592.cpp b/solutions/2592. Maximize Greatness of an Array/2592.cpp new file mode 100644 index 00000000000..b36ebf9a52d --- /dev/null +++ b/solutions/2592. Maximize Greatness of an Array/2592.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maximizeGreatness(vector& nums) { + int ans = 0; + + ranges::sort(nums); + + for (const int num : nums) + if (num > nums[ans]) + ++ans; + + return ans; + } +}; diff --git a/solutions/2592. Maximize Greatness of an Array/2592.java b/solutions/2592. Maximize Greatness of an Array/2592.java new file mode 100644 index 00000000000..e7446cd3157 --- /dev/null +++ b/solutions/2592. Maximize Greatness of an Array/2592.java @@ -0,0 +1,13 @@ +class Solution { + public int maximizeGreatness(int[] nums) { + int ans = 0; + + Arrays.sort(nums); + + for (final int num : nums) + if (num > nums[ans]) + ++ans; + + return ans; + } +} diff --git a/solutions/2592. Maximize Greatness of an Array/2592.py b/solutions/2592. Maximize Greatness of an Array/2592.py new file mode 100644 index 00000000000..ad2e9907c5d --- /dev/null +++ b/solutions/2592. Maximize Greatness of an Array/2592.py @@ -0,0 +1,11 @@ +class Solution: + def maximizeGreatness(self, nums: List[int]) -> int: + ans = 0 + + nums.sort() + + for num in nums: + if num > nums[ans]: + ans += 1 + + return ans diff --git a/solutions/2593. Find Score of an Array After Marking All Elements/2593.cpp b/solutions/2593. Find Score of an Array After Marking All Elements/2593.cpp new file mode 100644 index 00000000000..129aa128b7f --- /dev/null +++ b/solutions/2593. Find Score of an Array After Marking All Elements/2593.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long findScore(vector& nums) { + long ans = 0; + set> numAndIndices; + vector seen(nums.size()); + + for (int i = 0; i < nums.size(); ++i) + numAndIndices.insert({nums[i], i}); + + for (const auto& [num, i] : numAndIndices) { + if (seen[i]) + continue; + if (i > 0) + seen[i - 1] = true; + if (i + 1 < nums.size()) + seen[i + 1] = true; + seen[i] = true; + ans += num; + } + + return ans; + } +}; diff --git a/solutions/2593. Find Score of an Array After Marking All Elements/2593.java b/solutions/2593. Find Score of an Array After Marking All Elements/2593.java new file mode 100644 index 00000000000..5106bef22b5 --- /dev/null +++ b/solutions/2593. Find Score of an Array After Marking All Elements/2593.java @@ -0,0 +1,28 @@ +class Solution { + public long findScore(int[] nums) { + long ans = 0; + TreeSet> numAndIndices = + new TreeSet<>((a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue() - b.getValue() + : a.getKey() - b.getKey()); + boolean[] seen = new boolean[nums.length]; + + for (int i = 0; i < nums.length; ++i) + numAndIndices.add(new Pair<>(nums[i], i)); + + for (Pair pair : numAndIndices) { + final int num = pair.getKey(); + final int i = pair.getValue(); + if (seen[i]) + continue; + if (i > 0) + seen[i - 1] = true; + if (i + 1 < nums.length) + seen[i + 1] = true; + seen[i] = true; + ans += num; + } + + return ans; + } +} diff --git a/solutions/2593. Find Score of an Array After Marking All Elements/2593.py b/solutions/2593. Find Score of an Array After Marking All Elements/2593.py new file mode 100644 index 00000000000..be70ee6ceb5 --- /dev/null +++ b/solutions/2593. Find Score of an Array After Marking All Elements/2593.py @@ -0,0 +1,14 @@ +class Solution: + def findScore(self, nums: List[int]) -> int: + ans = 0 + seen = set() + + for num, i in sorted([(num, i) for i, num in enumerate(nums)]): + if i in seen: + continue + seen.add(i - 1) + seen.add(i + 1) + seen.add(i) + ans += num + + return ans diff --git a/solutions/2594. Minimum Time to Repair Cars/2594.cpp b/solutions/2594. Minimum Time to Repair Cars/2594.cpp new file mode 100644 index 00000000000..f9ce51060dd --- /dev/null +++ b/solutions/2594. Minimum Time to Repair Cars/2594.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + long long repairCars(vector& ranks, int cars) { + long l = 0; + long r = static_cast(ranges::min(ranks)) * cars * cars; + + while (l < r) { + const long m = (l + r) / 2; + if (numCarsFixed(ranks, m) >= cars) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + long numCarsFixed(const vector& ranks, long minutes) { + long carsFixed = 0; + // r * n^2 = minutes + // -> n = sqrt(minutes / r) + for (const int rank : ranks) + carsFixed += sqrt(minutes / rank); + return carsFixed; + } +}; diff --git a/solutions/2594. Minimum Time to Repair Cars/2594.java b/solutions/2594. Minimum Time to Repair Cars/2594.java new file mode 100644 index 00000000000..3171373342d --- /dev/null +++ b/solutions/2594. Minimum Time to Repair Cars/2594.java @@ -0,0 +1,25 @@ +class Solution { + public long repairCars(int[] ranks, int cars) { + long l = 0; + long r = (long) Arrays.stream(ranks).min().getAsInt() * cars * cars; + + while (l < r) { + final long m = (l + r) / 2; + if (numCarsFixed(ranks, m) >= cars) + r = m; + else + l = m + 1; + } + + return l; + } + + private long numCarsFixed(int[] ranks, long minutes) { + long carsFixed = 0; + // r * n^2 = minutes + // -> n = sqrt(minutes / r) + for (final int rank : ranks) + carsFixed += Math.sqrt(minutes / rank); + return carsFixed; + } +} diff --git a/solutions/2594. Minimum Time to Repair Cars/2594.py b/solutions/2594. Minimum Time to Repair Cars/2594.py new file mode 100644 index 00000000000..97171e890dd --- /dev/null +++ b/solutions/2594. Minimum Time to Repair Cars/2594.py @@ -0,0 +1,10 @@ +class Solution: + def repairCars(self, ranks: List[int], cars: int) -> int: + def numCarsFixed(minutes: int) -> int: + # r * n^2 = minutes + # -> n = sqrt(minutes / r) + return sum(math.isqrt(minutes // rank) for rank in ranks) + + return bisect.bisect_left( + range(0, min(ranks) * cars**2), cars, + key=lambda m: numCarsFixed(m)) diff --git a/solutions/2595. Number of Even and Odd Bits/2595.cpp b/solutions/2595. Number of Even and Odd Bits/2595.cpp new file mode 100644 index 00000000000..aed66823687 --- /dev/null +++ b/solutions/2595. Number of Even and Odd Bits/2595.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector evenOddBit(int n) { + vector ans(2); + int i = 0; // 0 := even, 1 := odd + + while (n > 0) { + ans[i] += n & 1; + n >>= 1; + i ^= 1; + } + + return ans; + } +}; diff --git a/solutions/2595. Number of Even and Odd Bits/2595.java b/solutions/2595. Number of Even and Odd Bits/2595.java new file mode 100644 index 00000000000..dd2d82e965f --- /dev/null +++ b/solutions/2595. Number of Even and Odd Bits/2595.java @@ -0,0 +1,14 @@ +class Solution { + public int[] evenOddBit(int n) { + int[] ans = new int[2]; + int i = 0; // 0 := even, 1 := odd + + while (n > 0) { + ans[i] += n & 1; + n >>= 1; + i ^= 1; + } + + return ans; + } +} diff --git a/solutions/2595. Number of Even and Odd Bits/2595.py b/solutions/2595. Number of Even and Odd Bits/2595.py new file mode 100644 index 00000000000..5b84ec319f8 --- /dev/null +++ b/solutions/2595. Number of Even and Odd Bits/2595.py @@ -0,0 +1,11 @@ +class Solution: + def evenOddBit(self, n: int) -> List[int]: + ans = [0] * 2 + i = 0 # 0 := even, 1 := odd + + while n > 0: + ans[i] += n & 1 + n >>= 1 + i ^= 1 + + return ans diff --git a/solutions/2596. Check Knight Tour Configuration/2596.cpp b/solutions/2596. Check Knight Tour Configuration/2596.cpp new file mode 100644 index 00000000000..d201c1794a6 --- /dev/null +++ b/solutions/2596. Check Knight Tour Configuration/2596.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + bool checkValidGrid(vector>& grid) { + const int n = grid.size(); + int i = 0; + int j = 0; + + for (int target = 1; target < n * n; ++target) { + const auto [x, y] = nextGrid(grid, i, j, target); + if (x == -1 && y == -1) + return false; + // Move (x, y) to (i, j). + i = x; + j = y; + } + + return true; + } + + private: + const vector> dirs{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, + {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + + // Returns (x, y), where grid[x][y] == target if (i, j) can reach target. + pair nextGrid(const vector>& grid, int i, int j, + int target) { + const int n = grid.size(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x >= n || y < 0 || y >= n) + continue; + if (grid[x][y] == target) + return {x, y}; + } + return {-1, -1}; + } +}; diff --git a/solutions/2596. Check Knight Tour Configuration/2596.java b/solutions/2596. Check Knight Tour Configuration/2596.java new file mode 100644 index 00000000000..11e12d33346 --- /dev/null +++ b/solutions/2596. Check Knight Tour Configuration/2596.java @@ -0,0 +1,37 @@ +class Solution { + public boolean checkValidGrid(int[][] grid) { + final int n = grid.length; + int i = 0; + int j = 0; + + for (int target = 1; target < n * n; ++target) { + Pair pair = nextGrid(grid, i, j, target); + final int x = pair.getKey(); + final int y = pair.getValue(); + if (x == -1 && y == -1) + return false; + // Move (x, y) to (i, j). + i = x; + j = y; + } + + return true; + } + + private static final int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, + {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + + // Returns (x, y), where grid[x][y] == target if (i, j) can reach target. + private Pair nextGrid(int[][] grid, int i, int j, int target) { + final int n = grid.length; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x >= n || y < 0 || y >= n) + continue; + if (grid[x][y] == target) + return new Pair<>(x, y); + } + return new Pair<>(-1, -1); + } +} diff --git a/solutions/2596. Check Knight Tour Configuration/2596.py b/solutions/2596. Check Knight Tour Configuration/2596.py new file mode 100644 index 00000000000..8413b5155c6 --- /dev/null +++ b/solutions/2596. Check Knight Tour Configuration/2596.py @@ -0,0 +1,30 @@ +class Solution: + def checkValidGrid(self, grid: List[List[int]]) -> bool: + dirs = ((1, 2), (2, 1), (2, -1), (1, -2), + (-1, -2), (-2, -1), (-2, 1), (-1, 2)) + n = len(grid) + i = 0 + j = 0 + + def nextGrid(i: int, j: int, target: int) -> Tuple[int, int]: + """ + Returns (x, y), where grid[x][y] == target if (i, j) can reach target. + """ + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x >= n or y < 0 or y >= n: + continue + if grid[x][y] == target: + return (x, y) + return (-1, -1) + + for target in range(1, n * n): + x, y = nextGrid(i, j, target) + if x == -1 and y == -1: + return False + # Move (x, y) to (i, j). + i = x + j = y + + return True diff --git a/solutions/2597. The Number of Beautiful Subsets/2597.cpp b/solutions/2597. The Number of Beautiful Subsets/2597.cpp new file mode 100644 index 00000000000..c4377e73d86 --- /dev/null +++ b/solutions/2597. The Number of Beautiful Subsets/2597.cpp @@ -0,0 +1,59 @@ +// e.g. nums = [2, 3, 4, 4], k = 2 +// +// subset[0] = [2, 4, 4'] +// subset[1] = [1] +// count = {2: 1, 4: 2, 1: 1} +// +// Initially, skip = len([]) = 0, pick = len([]) = 0 +// +// * For values in subset[0]: +// After 2: +// skip = skip + pick = len([]) = 0 +// pick = (2^count[2] - 1) * (1 + skip + pick) +// = len([[2]]) * len([[]]) +// = len([[2]]) = 1 +// After 4: +// skip = skip + pick = len([[2]]) = 1 +// pick = (2^count[4] - 1) * (1 + skip) +// = len([[4], [4'], [4, 4']]) * len([[]]) +// = len([[4], [4'], [4, 4']]) = 3 +// +// * For values in subset[1]: +// After 1: +// skip = skip + pick +// = len([[2], [4], [4'], [4, 4']]) = 4 +// pick = (2^count[1] - 1) * (1 + skip + pick) +// = len([[1]]) * len([[], [2], [4], [4'], [4, 4']]) +// = len([[1], [1, 2], [1, 4], [1, 4'], [1, 4, 4']]) = 5 +// +// So, ans = skip + pick = 9 + +class Solution { + public: + int beautifulSubsets(vector& nums, int k) { + constexpr int kMaxNum = 1000; + vector count(kMaxNum + 1); + unordered_map> modToSubset; + + for (const int num : nums) { + ++count[num]; + modToSubset[num % k].insert(num); + } + + int prevNum = -k; + int skip = 0; + int pick = 0; + + for (const auto& [_, subset] : modToSubset) + for (const int num : subset) { + const int nonEmptyCount = pow(2, count[num]) - 1; + const int cacheSkip = skip; + skip += pick; + pick = + nonEmptyCount * (1 + cacheSkip + (num - prevNum == k ? 0 : pick)); + prevNum = num; + } + + return skip + pick; + } +}; diff --git a/solutions/2597. The Number of Beautiful Subsets/2597.java b/solutions/2597. The Number of Beautiful Subsets/2597.java new file mode 100644 index 00000000000..7f0d8e7ac38 --- /dev/null +++ b/solutions/2597. The Number of Beautiful Subsets/2597.java @@ -0,0 +1,58 @@ +// e.g. nums = [2, 3, 4, 4], k = 2 +// +// subset[0] = [2, 4, 4'] +// subset[1] = [1] +// count = {2: 1, 4: 2, 1: 1} +// +// Initially, skip = len([]) = 0, pick = len([]) = 0 +// +// * For values in subset[0]: +// After 2: +// skip = skip + pick = len([]) = 0 +// pick = (2^count[2] - 1) * (1 + skip + pick) +// = len([[2]]) * len([[]]) +// = len([[2]]) = 1 +// After 4: +// skip = skip + pick = len([[2]]) = 1 +// pick = (2^count[4] - 1) * (1 + skip) +// = len([[4], [4'], [4, 4']]) * len([[]]) +// = len([[4], [4'], [4, 4']]) = 3 +// +// * For values in subset[1]: +// After 1: +// skip = skip + pick +// = len([[2], [4], [4'], [4, 4']]) = 4 +// pick = (2^count[1] - 1) * (1 + skip + pick) +// = len([[1]]) * len([[], [2], [4], [4'], [4, 4']]) +// = len([[1], [1, 2], [1, 4], [1, 4'], [1, 4, 4']]) = 5 +// +// So, ans = skip + pick = 9 + +class Solution { + public int beautifulSubsets(int[] nums, int k) { + final int kMaxNum = 1000; + int[] count = new int[kMaxNum + 1]; + Map> modToSubset = new HashMap<>(); + + for (final int num : nums) { + ++count[num]; + modToSubset.putIfAbsent(num % k, new TreeSet<>()); + modToSubset.get(num % k).add(num); + } + + int prevNum = -k; + int skip = 0; + int pick = 0; + + for (Set subset : modToSubset.values()) + for (final int num : subset) { + final int nonEmptyCount = (int) Math.pow(2, count[num]) - 1; + final int cacheSkip = skip; + skip += pick; + pick = nonEmptyCount * (1 + cacheSkip + (num - prevNum == k ? 0 : pick)); + prevNum = num; + } + + return skip + pick; + } +} diff --git a/solutions/2597. The Number of Beautiful Subsets/2597.py b/solutions/2597. The Number of Beautiful Subsets/2597.py new file mode 100644 index 00000000000..1bc10edb3be --- /dev/null +++ b/solutions/2597. The Number of Beautiful Subsets/2597.py @@ -0,0 +1,50 @@ +# e.g. nums = [2, 3, 4, 4], k = 2 +# +# subset[0] = [2, 4, 4'] +# subset[1] = [1] +# count = {2: 1, 4: 2, 1: 1} +# +# Initially, skip = len([]) = 0, pick = len([]) = 0 +# +# * For values in subset[0]: +# After 2: +# skip = skip + pick = len([]) = 0 +# pick = (2^count[2] - 1) * (1 + skip + pick) +# = len([[2]]) * len([[]]) +# = len([[2]]) = 1 +# After 4: +# skip = skip + pick = len([[2]]) = 1 +# pick = (2^count[4] - 1) * (1 + skip) +# = len([[4], [4'], [4, 4']]) * len([[]]) +# = len([[4], [4'], [4, 4']]) = 3 +# +# * For values in subset[1]: +# After 1: +# skip = skip + pick +# = len([[2], [4], [4'], [4, 4']]) = 4 +# pick = (2^count[1] - 1) * (1 + skip + pick) +# = len([[1]]) * len([[], [2], [4], [4'], [4, 4']]) +# = len([[1], [1, 2], [1, 4], [1, 4'], [1, 4, 4']]) = 5 +# +# So, ans = skip + pick = 9 + +class Solution: + def beautifulSubsets(self, nums: List[int], k: int) -> int: + count = collections.Counter(nums) + modToSubset = collections.defaultdict(set) + + for num in nums: + modToSubset[num % k].add(num) + + prevNum = -k + skip = 0 + pick = 0 + + for subset in modToSubset.values(): + for num in sorted(subset): + nonEmptyCount = 2**count[num] - 1 + skip, pick = skip + pick, nonEmptyCount * \ + (1 + skip + (0 if num - prevNum == k else pick)) + prevNum = num + + return skip + pick diff --git a/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.cpp b/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.cpp new file mode 100644 index 00000000000..cf5d448ee2c --- /dev/null +++ b/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int findSmallestInteger(vector& nums, int value) { + unordered_map count; + + for (const int num : nums) + ++count[(num % value + value) % value]; + + for (int i = 0; i < nums.size(); ++i) + if (--count[i % value] < 0) + return i; + + return nums.size(); + } +}; diff --git a/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.java b/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.java new file mode 100644 index 00000000000..bb0f194f6bc --- /dev/null +++ b/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.java @@ -0,0 +1,16 @@ +class Solution { + public int findSmallestInteger(int[] nums, int value) { + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge((num % value + value) % value, 1, Integer::sum); + + for (int i = 0; i < nums.length; ++i) { + if (count.getOrDefault(i % value, 0) == 0) + return i; + count.merge(i % value, -1, Integer::sum); + } + + return nums.length; + } +} diff --git a/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.py b/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.py new file mode 100644 index 00000000000..7baf255dd1c --- /dev/null +++ b/solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.py @@ -0,0 +1,10 @@ +class Solution: + def findSmallestInteger(self, nums: List[int], value: int) -> int: + count = collections.Counter([num % value for num in nums]) + + for i in range(len(nums)): + if count[i % value] == 0: + return i + count[i % value] -= 1 + + return len(nums) diff --git a/solutions/2599. Make the Prefix Sum Non-negative/2599.cpp b/solutions/2599. Make the Prefix Sum Non-negative/2599.cpp new file mode 100644 index 00000000000..cc72b85f440 --- /dev/null +++ b/solutions/2599. Make the Prefix Sum Non-negative/2599.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int makePrefSumNonNegative(vector& nums) { + int ans = 0; + long prefix = 0; + priority_queue, greater<>> minHeap; + + for (const int num : nums) { + prefix += num; + if (num < 0) + minHeap.push(num); + while (prefix < 0) { + prefix -= minHeap.top(), minHeap.pop(); + ++ans; + } + } + + return ans; + } +}; diff --git a/solutions/2599. Make the Prefix Sum Non-negative/2599.java b/solutions/2599. Make the Prefix Sum Non-negative/2599.java new file mode 100644 index 00000000000..aa4353825e7 --- /dev/null +++ b/solutions/2599. Make the Prefix Sum Non-negative/2599.java @@ -0,0 +1,19 @@ +class Solution { + public int makePrefSumNonNegative(int[] nums) { + int ans = 0; + long prefix = 0; + Queue minHeap = new PriorityQueue<>(); + + for (final int num : nums) { + prefix += num; + if (num < 0) + minHeap.offer(num); + while (prefix < 0) { + prefix -= minHeap.poll(); + ++ans; + } + } + + return ans; + } +} diff --git a/solutions/2599. Make the Prefix Sum Non-negative/2599.py b/solutions/2599. Make the Prefix Sum Non-negative/2599.py new file mode 100644 index 00000000000..18bd8613762 --- /dev/null +++ b/solutions/2599. Make the Prefix Sum Non-negative/2599.py @@ -0,0 +1,15 @@ +class Solution: + def makePrefSumNonNegative(self, nums: List[int]) -> int: + ans = 0 + prefix = 0 + minHeap = [] + + for num in nums: + prefix += num + if num < 0: + heapq.heappush(minHeap, num) + while prefix < 0: + prefix -= heapq.heappop(minHeap) + ans += 1 + + return ans diff --git a/solutions/26. Remove Duplicates from Sorted Array/26.cpp b/solutions/26. Remove Duplicates from Sorted Array/26.cpp new file mode 100644 index 00000000000..f1e113ad799 --- /dev/null +++ b/solutions/26. Remove Duplicates from Sorted Array/26.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int removeDuplicates(vector& nums) { + int i = 0; + + for (const int num : nums) + if (i < 1 || num > nums[i - 1]) + nums[i++] = num; + + return i; + } +}; diff --git a/solutions/26. Remove Duplicates from Sorted Array/26.java b/solutions/26. Remove Duplicates from Sorted Array/26.java new file mode 100644 index 00000000000..1e3a7e9a933 --- /dev/null +++ b/solutions/26. Remove Duplicates from Sorted Array/26.java @@ -0,0 +1,11 @@ +class Solution { + public int removeDuplicates(int[] nums) { + int i = 0; + + for (final int num : nums) + if (i < 1 || num > nums[i - 1]) + nums[i++] = num; + + return i; + } +} diff --git a/solutions/26. Remove Duplicates from Sorted Array/26.py b/solutions/26. Remove Duplicates from Sorted Array/26.py new file mode 100644 index 00000000000..0359fbdfe2e --- /dev/null +++ b/solutions/26. Remove Duplicates from Sorted Array/26.py @@ -0,0 +1,10 @@ +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + i = 0 + + for num in nums: + if i < 1 or num > nums[i - 1]: + nums[i] = num + i += 1 + + return i diff --git a/solutions/260. Single Number III/260.cpp b/solutions/260. Single Number III/260.cpp new file mode 100644 index 00000000000..427c64d552f --- /dev/null +++ b/solutions/260. Single Number III/260.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector singleNumber(vector& nums) { + const int xors = accumulate(nums.begin(), nums.end(), 0, bit_xor<>()); + const int lowbit = xors & -xors; + vector ans(2); + + // Seperate `nums` into two groups by `lowbit`. + for (const int num : nums) + if (num & lowbit) + ans[0] ^= num; + else + ans[1] ^= num; + + return ans; + } +}; diff --git a/solutions/260. Single Number III/260.java b/solutions/260. Single Number III/260.java new file mode 100644 index 00000000000..c6da7799487 --- /dev/null +++ b/solutions/260. Single Number III/260.java @@ -0,0 +1,16 @@ +class Solution { + public int[] singleNumber(int[] nums) { + final int xors = Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt(); + final int lowbit = xors & -xors; + int[] ans = new int[2]; + + // Seperate `nums` into two groups by `lowbit`. + for (final int num : nums) + if ((num & lowbit) > 0) + ans[0] ^= num; + else + ans[1] ^= num; + + return ans; + } +} diff --git a/solutions/260. Single Number III/260.py b/solutions/260. Single Number III/260.py new file mode 100644 index 00000000000..c58e343b08e --- /dev/null +++ b/solutions/260. Single Number III/260.py @@ -0,0 +1,14 @@ +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + xors = functools.reduce(operator.xor, nums) + lowbit = xors & -xors + ans = [0, 0] + + # Seperate `nums` into two groups by `lowbit`. + for num in nums: + if num & lowbit: + ans[0] ^= num + else: + ans[1] ^= num + + return ans diff --git a/solutions/2600. K Items With the Maximum Sum/2600.cpp b/solutions/2600. K Items With the Maximum Sum/2600.cpp new file mode 100644 index 00000000000..8aa8634bdd6 --- /dev/null +++ b/solutions/2600. K Items With the Maximum Sum/2600.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (k <= numOnes) + return k; + if (k <= numOnes + numZeros) + return numOnes; + return numOnes - (k - numOnes - numZeros); + } +}; diff --git a/solutions/2600. K Items With the Maximum Sum/2600.java b/solutions/2600. K Items With the Maximum Sum/2600.java new file mode 100644 index 00000000000..5d5035422eb --- /dev/null +++ b/solutions/2600. K Items With the Maximum Sum/2600.java @@ -0,0 +1,9 @@ +class Solution { + public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (k <= numOnes) + return k; + if (k <= numOnes + numZeros) + return numOnes; + return numOnes - (k - numOnes - numZeros); + } +} diff --git a/solutions/2600. K Items With the Maximum Sum/2600.py b/solutions/2600. K Items With the Maximum Sum/2600.py new file mode 100644 index 00000000000..7ca76c6806f --- /dev/null +++ b/solutions/2600. K Items With the Maximum Sum/2600.py @@ -0,0 +1,7 @@ +class Solution: + def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int: + if k <= numOnes: + return k + if k <= numOnes + numZeros: + return numOnes + return numOnes - (k - numOnes - numZeros) diff --git a/solutions/2601. Prime Subtraction Operation/2601.cpp b/solutions/2601. Prime Subtraction Operation/2601.cpp new file mode 100644 index 00000000000..8c15dd2acfe --- /dev/null +++ b/solutions/2601. Prime Subtraction Operation/2601.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + bool primeSubOperation(vector& nums) { + constexpr int kMax = 1000; + const vector primes = sieveEratosthenes(kMax); + + int prevNum = 0; + for (int num : nums) { + // Make nums[i] the smallest as possible and still > nums[i - 1]. + const auto it = ranges::lower_bound(primes, num - prevNum); + if (it != primes.begin()) + num -= *prev(it); + if (num <= prevNum) + return false; + prevNum = num; + } + + return true; + } + + vector sieveEratosthenes(int n) { + vector primes; + vector isPrime(n, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + for (int i = 2; i < n; ++i) + if (isPrime[i]) + primes.push_back(i); + return primes; + } +}; diff --git a/solutions/2601. Prime Subtraction Operation/2601.java b/solutions/2601. Prime Subtraction Operation/2601.java new file mode 100644 index 00000000000..b90bd240371 --- /dev/null +++ b/solutions/2601. Prime Subtraction Operation/2601.java @@ -0,0 +1,40 @@ +class Solution { + public boolean primeSubOperation(int[] nums) { + final int kMax = 1000; + final List primes = sieveEratosthenes(kMax); + + int prevNum = 0; + for (int num : nums) { + // Make nums[i] the smallest as possible and still > nums[i - 1]. + final int i = firstGreaterEqual(primes, num - prevNum); + if (i > 0) + num -= primes.get(i - 1); + if (num <= prevNum) + return false; + prevNum = num; + } + + return true; + } + + private List sieveEratosthenes(int n) { + List primes = new ArrayList<>(); + boolean[] isPrime = new boolean[n]; + Arrays.fill(isPrime, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + for (int i = 2; i < n; ++i) + if (isPrime[i]) + primes.add(i); + return primes; + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2601. Prime Subtraction Operation/2601.py b/solutions/2601. Prime Subtraction Operation/2601.py new file mode 100644 index 00000000000..e63bae879de --- /dev/null +++ b/solutions/2601. Prime Subtraction Operation/2601.py @@ -0,0 +1,26 @@ +class Solution: + def primeSubOperation(self, nums: List[int]) -> bool: + kMax = 1000 + primes = self._sieveEratosthenes(kMax) + + prevNum = 0 + for num in nums: + # Make nums[i] the smallest as possible and still > nums[i - 1]. + i = bisect.bisect_left(primes, num - prevNum) + if i > 0: + num -= primes[i - 1] + if num <= prevNum: + return False + prevNum = num + + return True + + def _sieveEratosthenes(self, n: int) -> List[int]: + isPrime = [True] * n + isPrime[0] = False + isPrime[1] = False + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n, i): + isPrime[j] = False + return [i for i in range(n) if isPrime[i]] diff --git a/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.cpp b/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.cpp new file mode 100644 index 00000000000..13d4488916b --- /dev/null +++ b/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector minOperations(vector& nums, vector& queries) { + const int n = nums.size(); + vector ans; + vector prefix{0}; + + ranges::sort(nums); + + for (int i = 0; i < n; ++i) + prefix.push_back(prefix.back() + nums[i]); + + for (const long query : queries) { + const int i = ranges::upper_bound(nums, query) - nums.begin(); + // Since nums[0..i) <= query, nums[i..n) > `query`, we should + // - increase each num in nums[0..i) to `query` and + // - decrease each num in nums[i..n) to `query`. + const long inc = query * i - prefix[i]; + const long dec = prefix[n] - prefix[i] - query * (n - i); + ans.push_back(inc + dec); + } + + return ans; + } +}; diff --git a/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.java b/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.java new file mode 100644 index 00000000000..d13675b8773 --- /dev/null +++ b/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.java @@ -0,0 +1,27 @@ +class Solution { + public List minOperations(int[] nums, int[] queries) { + final int n = nums.length; + List ans = new ArrayList<>(); + long[] prefix = new long[n + 1]; + + Arrays.sort(nums); + + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + nums[i]; + + for (final int query : queries) { + int i = Arrays.binarySearch(nums, query); + if (i < 0) + i = -i - 1; + + // Since nums[0..i) <= query, nums[i..n) > `query`, we should + // - increase each num in nums[0..i) to `query` and + // - decrease each num in nums[i..n) to `query`. + final long inc = (long) query * i - prefix[i]; + final long dec = prefix[n] - prefix[i] - (long) query * (n - i); + ans.add(inc + dec); + } + + return ans; + } +} diff --git a/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.py b/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.py new file mode 100644 index 00000000000..35a5e4c8223 --- /dev/null +++ b/solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.py @@ -0,0 +1,9 @@ +class Solution: + def minOperations(self, nums: List[int], queries: List[int]) -> List[int]: + n = len(nums) + nums.sort() + prefix = [0] + list(itertools.accumulate(nums)) + splits = [(query, bisect.bisect_right(nums, query)) for query in queries] + return [(query * i - prefix[i]) + + (prefix[-1] - prefix[i] - query * (n - i)) + for query, i in splits] diff --git a/solutions/2603. Collect Coins in a Tree/2603.cpp b/solutions/2603. Collect Coins in a Tree/2603.cpp new file mode 100644 index 00000000000..c77639132ca --- /dev/null +++ b/solutions/2603. Collect Coins in a Tree/2603.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + int collectTheCoins(vector& coins, vector>& edges) { + const int n = coins.size(); + vector> tree(n); + queue leavesToBeRemoved; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].insert(v); + tree[v].insert(u); + } + + for (int i = 0; i < n; ++i) { + int u = i; + // Remove the leaves that don't have coins. + while (tree[u].size() == 1 && coins[u] == 0) { + const int v = *tree[u].begin(); + tree[u].clear(); + tree[v].erase(u); + u = v; // Walk up to its parent. + } + // After trimming leaves without coins, leaves with coins may satisfy + // `leavesToBeRemoved`. + if (tree[u].size() == 1) + leavesToBeRemoved.push(u); + } + + // Remove each remaining leaf node and its parent. The remaining nodes are + // the ones that must be visited. + for (int i = 0; i < 2; ++i) + for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) { + const int u = leavesToBeRemoved.front(); + leavesToBeRemoved.pop(); + if (!tree[u].empty()) { + const int v = *tree[u].begin(); + tree[u].clear(); + tree[v].erase(u); + if (tree[v].size() == 1) + leavesToBeRemoved.push(v); + } + } + + return accumulate(tree.begin(), tree.end(), 0, + [](int subtotal, const unordered_set& children) { + return subtotal + children.size(); + }); + } +}; diff --git a/solutions/2603. Collect Coins in a Tree/2603.java b/solutions/2603. Collect Coins in a Tree/2603.java new file mode 100644 index 00000000000..9b68a94c435 --- /dev/null +++ b/solutions/2603. Collect Coins in a Tree/2603.java @@ -0,0 +1,48 @@ +class Solution { + public int collectTheCoins(int[] coins, int[][] edges) { + final int n = coins.length; + Set[] tree = new Set[n]; + Deque leavesToBeRemoved = new ArrayDeque<>(); + + for (int i = 0; i < n; ++i) + tree[i] = new HashSet<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + for (int i = 0; i < n; ++i) { + int u = i; + // Remove the leaves that don't have coins. + while (tree[u].size() == 1 && coins[u] == 0) { + final int v = tree[u].iterator().next(); + tree[u].clear(); + tree[v].remove(u); + u = v; // Walk up to its parent. + } + // After trimming leaves without coins, leaves with coins may satisfy + // `leavesToBeRemoved`. + if (tree[u].size() == 1) + leavesToBeRemoved.offer(u); + } + + // Remove each remaining leaf node and its parent. The remaining nodes are + // the ones that must be visited. + for (int i = 0; i < 2; ++i) + for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) { + final int u = leavesToBeRemoved.poll(); + if (!tree[u].isEmpty()) { + final int v = tree[u].iterator().next(); + tree[u].clear(); + tree[v].remove(u); + if (tree[v].size() == 1) + leavesToBeRemoved.offer(v); + } + } + + return Arrays.stream(tree).mapToInt(children -> children.size()).sum(); + } +} diff --git a/solutions/2603. Collect Coins in a Tree/2603.py b/solutions/2603. Collect Coins in a Tree/2603.py new file mode 100644 index 00000000000..06dad336151 --- /dev/null +++ b/solutions/2603. Collect Coins in a Tree/2603.py @@ -0,0 +1,33 @@ +class Solution: + def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int: + n = len(coins) + tree = [set() for _ in range(n)] + leavesToBeRemoved = collections.deque() + + for u, v in edges: + tree[u].add(v) + tree[v].add(u) + + for u in range(n): + # Remove the leaves that don't have coins. + while len(tree[u]) == 1 and coins[u] == 0: + v = tree[u].pop() + tree[v].remove(u) + u = v # Walk up to its parent. + # After trimming leaves without coins, leaves with coins may satisfy + # `leavesToBeRemoved`. + if len(tree[u]) == 1: # coins[u] must be 1. + leavesToBeRemoved.append(u) + + # Remove each remaining leaf node and its parent. The remaining nodes are + # the ones that must be visited. + for _ in range(2): + for _ in range(len(leavesToBeRemoved)): + u = leavesToBeRemoved.popleft() + if tree[u]: + v = tree[u].pop() + tree[v].remove(u) + if len(tree[v]) == 1: # It's a leaf. + leavesToBeRemoved.append(v) + + return sum(len(children) for children in tree) diff --git a/solutions/2604. Minimum Time to Eat All Grains/2604.cpp b/solutions/2604. Minimum Time to Eat All Grains/2604.cpp new file mode 100644 index 00000000000..a3f6e77c87f --- /dev/null +++ b/solutions/2604. Minimum Time to Eat All Grains/2604.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + int minimumTime(vector& hens, vector& grains) { + ranges::sort(hens); + ranges::sort(grains); + + const int maxPosition = max(ranges::max(hens), ranges::max(grains)); + const int minPosition = min(ranges::min(hens), ranges::min(grains)); + int l = 0; + int r = 1.5 * (maxPosition - minPosition); + + while (l < r) { + const int m = (l + static_cast(r)) / 2; + if (canEat(hens, grains, m)) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Returns true if `hens` can eat all `grains` within `time`. + bool canEat(const vector& hens, const vector& grains, int time) { + int i = 0; // grains[i] := next grain to be ate + for (const int hen : hens) { + int moves = time; + if (grains[i] < hen) { + // `hen` needs go back to eat `grains[i]`. + const int leftMoves = hen - grains[i]; + if (leftMoves > time) + return false; + const int leftThenRight = time - 2 * leftMoves; + const int rightThenLeft = (time - leftMoves) / 2; + moves = max({0, leftThenRight, rightThenLeft}); + } + i = ranges::upper_bound(grains, hen + moves) - grains.begin(); + if (i == grains.size()) + return true; + } + return false; + } +}; diff --git a/solutions/2604. Minimum Time to Eat All Grains/2604.java b/solutions/2604. Minimum Time to Eat All Grains/2604.java new file mode 100644 index 00000000000..96b3369f7d8 --- /dev/null +++ b/solutions/2604. Minimum Time to Eat All Grains/2604.java @@ -0,0 +1,49 @@ +class Solution { + public int minimumTime(int[] hens, int[] grains) { + Arrays.sort(hens); + Arrays.sort(grains); + + final int maxPosition = Math.max(Arrays.stream(hens).max().getAsInt(), // + Arrays.stream(grains).max().getAsInt()); + final int minPosition = Math.min(Arrays.stream(hens).min().getAsInt(), // + Arrays.stream(grains).min().getAsInt()); + int l = 0; + int r = (int) (1.5 * (maxPosition - minPosition)); + + while (l < r) { + final int m = (int) ((l + (long) r) / 2); + if (canEat(hens, grains, m)) + r = m; + else + l = m + 1; + } + + return (int) l; + } + + // Returns true if `hens` can eat all `grains` within `time`. + private boolean canEat(int[] hens, int[] grains, int time) { + int i = 0; // grains[i] := next grain to be ate + for (final int hen : hens) { + int rightMoves = time; + if (grains[i] < hen) { + // `hen` needs go back to eat `grains[i]`. + final int leftMoves = hen - grains[i]; + if (leftMoves > time) + return false; + final int leftThenRight = time - 2 * leftMoves; + final int rightThenLeft = (time - leftMoves) / 2; + rightMoves = Math.max(0, Math.max(leftThenRight, rightThenLeft)); + } + i = firstGreater(grains, hen + rightMoves); + if (i == grains.length) + return true; + } + return false; + } + + private int firstGreater(int[] A, int target) { + final int i = Arrays.binarySearch(A, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2604. Minimum Time to Eat All Grains/2604.py b/solutions/2604. Minimum Time to Eat All Grains/2604.py new file mode 100644 index 00000000000..298b86d7937 --- /dev/null +++ b/solutions/2604. Minimum Time to Eat All Grains/2604.py @@ -0,0 +1,25 @@ +class Solution: + def minimumTime(self, hens: List[int], grains: List[int]) -> int: + hens.sort() + grains.sort() + + def canEat(time: int) -> bool: + """Returns True if `hens` can eat all `grains` within `time`.""" + i = 0 # grains[i] := next grain to be ate + for hen in hens: + rightMoves = time + if grains[i] < hen: + # `hen` needs go back to eat `grains[i]`. + leftMoves = hen - grains[i] + if leftMoves > time: + return False + leftThenRight = time - 2 * leftMoves + rightThenLeft = (time - leftMoves) // 2 + rightMoves = max(0, leftThenRight, rightThenLeft) + i = bisect.bisect_right(grains, hen + rightMoves) + if i == len(grains): + return True + return False + + maxMoves = int(1.5 * (max(hens + grains) - min(hens + grains))) + return bisect.bisect_left(range(maxMoves), True, key=lambda m: canEat(m)) diff --git a/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.cpp b/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.cpp new file mode 100644 index 00000000000..aa076c39160 --- /dev/null +++ b/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int minNumber(vector& nums1, vector& nums2) { + int ans = 89; // the largest num we can have + for (const int a : nums1) + for (const int b : nums2) + ans = min(ans, a == b ? a : min(a, b) * 10 + max(a, b)); + return ans; + } +}; diff --git a/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.java b/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.java new file mode 100644 index 00000000000..b02cab6f585 --- /dev/null +++ b/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.java @@ -0,0 +1,9 @@ +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int ans = 89; // the largest num we can have + for (final int a : nums1) + for (final int b : nums2) + ans = Math.min(ans, a == b ? a : Math.min(a, b) * 10 + Math.max(a, b)); + return ans; + } +} diff --git a/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.py b/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.py new file mode 100644 index 00000000000..de06896348b --- /dev/null +++ b/solutions/2605. Form Smallest Number From Two Digit Arrays/2605.py @@ -0,0 +1,5 @@ +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + return min(a if a == b else min(a, b) * 10 + max(a, b) + for a in nums1 + for b in nums2) diff --git a/solutions/2606. Find the Substring With Maximum Cost/2606.cpp b/solutions/2606. Find the Substring With Maximum Cost/2606.cpp new file mode 100644 index 00000000000..4522a25f5ed --- /dev/null +++ b/solutions/2606. Find the Substring With Maximum Cost/2606.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maximumCostSubstring(string s, string chars, vector& vals) { + int ans = 0; + int cost = 0; + vector costs(26); // costs[i] := the cost of 'a' + i + + iota(costs.begin(), costs.end(), 1); + + for (int i = 0; i < chars.size(); ++i) + costs[chars[i] - 'a'] = vals[i]; + + for (const char c : s) { + cost = max(0, cost + costs[c - 'a']); + ans = max(ans, cost); + } + + return ans; + } +}; diff --git a/solutions/2606. Find the Substring With Maximum Cost/2606.java b/solutions/2606. Find the Substring With Maximum Cost/2606.java new file mode 100644 index 00000000000..178d1441b9b --- /dev/null +++ b/solutions/2606. Find the Substring With Maximum Cost/2606.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumCostSubstring(String s, String chars, int[] vals) { + int ans = 0; + int cost = 0; + int[] costs = new int[26]; // costs[i] := the cost of 'a' + i + + for (int i = 0; i < 26; ++i) + costs[i] = i + 1; + + for (int i = 0; i < chars.length(); ++i) + costs[chars.charAt(i) - 'a'] = vals[i]; + + for (final char c : s.toCharArray()) { + cost = Math.max(0, cost + costs[c - 'a']); + ans = Math.max(ans, cost); + } + + return ans; + } +} diff --git a/solutions/2606. Find the Substring With Maximum Cost/2606.py b/solutions/2606. Find the Substring With Maximum Cost/2606.py new file mode 100644 index 00000000000..23ac4184ae5 --- /dev/null +++ b/solutions/2606. Find the Substring With Maximum Cost/2606.py @@ -0,0 +1,14 @@ +class Solution: + def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: + ans = 0 + cost = 0 + costs = [i for i in range(1, 27)] # costs[i] := the cost of 'a' + i + + for c, val in zip(chars, vals): + costs[ord(c) - ord('a')] = val + + for c in s: + cost = max(0, cost + costs[ord(c) - ord('a')]) + ans = max(ans, cost) + + return ans diff --git a/solutions/2607. Make K-Subarray Sums Equal/2607.cpp b/solutions/2607. Make K-Subarray Sums Equal/2607.cpp new file mode 100644 index 00000000000..0f6c32aa5f8 --- /dev/null +++ b/solutions/2607. Make K-Subarray Sums Equal/2607.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + long long makeSubKSumEqual(vector& arr, int k) { + // If the sum of each subarray of length k is equal, then `arr` must have a + // repeated pattern of size k. e.g. arr = [1, 2, 3, ...] and k = 3, to have + // sum([1, 2, 3)] == sum([2, 3, x]), x must be 1. Therefore, arr[i] == + // arr[(i + k) % n] for every i. + const int n = arr.size(); + long ans = 0; + vector seen(n); + + for (int i = 0; i < n; ++i) { + vector groups; + int j = i; + while (!seen[j]) { + groups.push_back(arr[j]); + seen[j] = true; + j = (j + k) % n; + } + nth_element(groups.begin(), groups.begin() + groups.size() / 2, + groups.end()); + for (const int num : groups) + ans += abs(num - groups[groups.size() / 2]); + } + + return ans; + } +}; diff --git a/solutions/2607. Make K-Subarray Sums Equal/2607.java b/solutions/2607. Make K-Subarray Sums Equal/2607.java new file mode 100644 index 00000000000..8881b8761e2 --- /dev/null +++ b/solutions/2607. Make K-Subarray Sums Equal/2607.java @@ -0,0 +1,26 @@ +class Solution { + public long makeSubKSumEqual(int[] arr, int k) { + // If the sum of each subarray of length k is equal, then `arr` must have a + // repeated pattern of size k. e.g. arr = [1, 2, 3, ...] and k = 3, to have + // sum([1, 2, 3)] == sum([2, 3, x]), x must be 1. Therefore, arr[i] == + // arr[(i + k) % n] for every i. + final int n = arr.length; + long ans = 0; + boolean[] seen = new boolean[n]; + + for (int i = 0; i < n; ++i) { + List groups = new ArrayList<>(); + int j = i; + while (!seen[j]) { + groups.add(arr[j]); + seen[j] = true; + j = (j + k) % n; + } + Collections.sort(groups); + for (final int num : groups) + ans += Math.abs(num - groups.get(groups.size() / 2)); + } + + return ans; + } +} diff --git a/solutions/2607. Make K-Subarray Sums Equal/2607.py b/solutions/2607. Make K-Subarray Sums Equal/2607.py new file mode 100644 index 00000000000..cf7db4640cc --- /dev/null +++ b/solutions/2607. Make K-Subarray Sums Equal/2607.py @@ -0,0 +1,22 @@ +class Solution: + def makeSubKSumEqual(self, arr: List[int], k: int) -> int: + # If the sum of each subarray of length k is equal, then `arr` must have a + # repeated pattern of size k. e.g. arr = [1, 2, 3, ...] and k = 3, to have + # sum([1, 2, 3)] == sum([2, 3, x]), x must be 1. Therefore, arr[i] == + # arr[(i + k) % n] for every i. + n = len(arr) + ans = 0 + seen = [0] * n + + for i in range(n): + groups = [] + j = i + while not seen[j]: + groups.append(arr[j]) + seen[j] = True + j = (j + k) % n + groups.sort() + for num in groups: + ans += abs(num - groups[len(groups) // 2]) + + return ans diff --git a/solutions/2608. Shortest Cycle in a Graph/2608.cpp b/solutions/2608. Shortest Cycle in a Graph/2608.cpp new file mode 100644 index 00000000000..79d88e73958 --- /dev/null +++ b/solutions/2608. Shortest Cycle in a Graph/2608.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int findShortestCycle(int n, vector>& edges) { + int ans = kInf; + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + for (int i = 0; i < n; ++i) + ans = min(ans, bfs(graph, i)); + + return ans == kInf ? -1 : ans; + } + + private: + static constexpr int kInf = 1001; + + // Returns the length of the minimum cycle by starting BFS from node `i`. + // Returns `kInf` if there's no cycle. + int bfs(const vector>& graph, int i) { + vector dist(graph.size(), kInf); + queue q{{i}}; + dist[i] = 0; + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) { + if (dist[v] == kInf) { + dist[v] = dist[u] + 1; + q.push(v); + } else if (dist[v] + 1 != dist[u]) { // v is not a parent u. + return dist[v] + dist[u] + 1; + } + } + } + return kInf; + } +}; diff --git a/solutions/2608. Shortest Cycle in a Graph/2608.java b/solutions/2608. Shortest Cycle in a Graph/2608.java new file mode 100644 index 00000000000..02c73f509b3 --- /dev/null +++ b/solutions/2608. Shortest Cycle in a Graph/2608.java @@ -0,0 +1,44 @@ +class Solution { + public int findShortestCycle(int n, int[][] edges) { + int ans = kInf; + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + for (int i = 0; i < n; ++i) + ans = Math.min(ans, bfs(graph, i)); + + return ans == kInf ? -1 : ans; + } + + private static final int kInf = 1001; + + // Returns the length of the minimum cycle by starting BFS from node `i`. + // Returns `kInf` if there's no cycle. + private int bfs(List[] graph, int i) { + int[] dist = new int[graph.length]; + Arrays.fill(dist, kInf); + Queue q = new ArrayDeque<>(Arrays.asList(i)); + dist[i] = 0; + while (!q.isEmpty()) { + final int u = q.poll(); + for (final int v : graph[u]) { + if (dist[v] == kInf) { + dist[v] = dist[u] + 1; + q.offer(v); + } else if (dist[v] + 1 != dist[u]) { // v is not a parent u. + return dist[v] + dist[u] + 1; + } + } + } + return kInf; + } +} diff --git a/solutions/2608. Shortest Cycle in a Graph/2608.py b/solutions/2608. Shortest Cycle in a Graph/2608.py new file mode 100644 index 00000000000..9a36bf1bcf0 --- /dev/null +++ b/solutions/2608. Shortest Cycle in a Graph/2608.py @@ -0,0 +1,30 @@ +class Solution: + def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: + kInf = 1001 + ans = kInf + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + def bfs(i: int) -> int: + """Returns the length of the minimum cycle by starting BFS from node `i`. + + Returns `kInf` if there's no cycle. + """ + dist = [kInf] * n + q = collections.deque([i]) + dist[i] = 0 + while q: + u = q.popleft() + for v in graph[u]: + if dist[v] == kInf: + dist[v] = dist[u] + 1 + q.append(v) + elif dist[v] + 1 != dist[u]: # v is not a parent u. + return dist[v] + dist[u] + 1 + return kInf + + ans = min(map(bfs, range(n))) + return -1 if ans == kInf else ans diff --git a/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.cpp b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.cpp new file mode 100644 index 00000000000..b873e3590c7 --- /dev/null +++ b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int findTheLongestBalancedSubstring(string s) { + int ans = 0; + int count0 = 0; + int count1 = 0; + + for (const char c : s) { + if (c == '0') { + count0 = count1 > 0 ? 1 : count0 + 1; + count1 = 0; + } else { // c == '1' + ++count1; + } + if (count0 >= count1) + ans = max(ans, count1); + } + + return ans * 2; + } +}; diff --git a/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.java b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.java new file mode 100644 index 00000000000..9b9c1f5963c --- /dev/null +++ b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.java @@ -0,0 +1,20 @@ +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int ans = 0; + int zeros = 0; + int ones = 0; + + for (final char c : s.toCharArray()) { + if (c == '0') { + zeros = ones > 0 ? 1 : zeros + 1; + ones = 0; + } else { // c == '1' + ++ones; + } + if (zeros >= ones) + ans = Math.max(ans, ones); + } + + return ans * 2; + } +} diff --git a/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.py b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.py new file mode 100644 index 00000000000..2d809a281f4 --- /dev/null +++ b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609-2.py @@ -0,0 +1,16 @@ +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + ans = 0 + zeros = 0 + ones = 0 + + for c in s: + if c == '0': + zeros = 1 if ones > 0 else zeros + 1 + ones = 0 + else: # c == '1' + ones += 1 + if zeros >= ones: + ans = max(ans, ones) + + return ans * 2 diff --git a/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.cpp b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.cpp new file mode 100644 index 00000000000..4096226a3d1 --- /dev/null +++ b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int findTheLongestBalancedSubstring(string s) { + int ans = 0; + + for (int i = 0; i < s.length();) { + int zeros = 0; + int ones = 0; + while (i < s.length() && s[i] == '0') { + ++zeros; + ++i; + } + while (i < s.length() && s[i] == '1') { + ++ones; + ++i; + } + ans = max(ans, min(zeros, ones)); + } + + return ans * 2; + } +}; diff --git a/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.java b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.java new file mode 100644 index 00000000000..7139c15d4ab --- /dev/null +++ b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.java @@ -0,0 +1,21 @@ +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int ans = 0; + + for (int i = 0; i < s.length();) { + int zeros = 0; + int ones = 0; + while (i < s.length() && s.charAt(i) == '0') { + ++zeros; + ++i; + } + while (i < s.length() && s.charAt(i) == '1') { + ++ones; + ++i; + } + ans = Math.max(ans, Math.min(zeros, ones)); + } + + return ans * 2; + } +} diff --git a/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.py b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.py new file mode 100644 index 00000000000..ed761c48a8b --- /dev/null +++ b/solutions/2609. Find the Longest Balanced Substring of a Binary String/2609.py @@ -0,0 +1,17 @@ +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + ans = 0 + + i = 0 + while i < len(s): + zeros = 0 + ones = 0 + while i < len(s) and s[i] == '0': + zeros += 1 + i += 1 + while i < len(s) and s[i] == '1': + ones += 1 + i += 1 + ans = max(ans, min(zeros, ones)) + + return ans * 2 diff --git a/solutions/261. Graph Valid Tree/261-2.cpp b/solutions/261. Graph Valid Tree/261-2.cpp new file mode 100644 index 00000000000..91c3b1a4a09 --- /dev/null +++ b/solutions/261. Graph Valid Tree/261-2.cpp @@ -0,0 +1,53 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + bool validTree(int n, vector>& edges) { + if (n == 0 || edges.size() != n - 1) + return false; + + UnionFind uf(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + uf.unionByRank(u, v); + } + + return uf.getCount() == 1; + } +}; diff --git a/solutions/261. Graph Valid Tree/261-2.java b/solutions/261. Graph Valid Tree/261-2.java new file mode 100644 index 00000000000..58b6078e64a --- /dev/null +++ b/solutions/261. Graph Valid Tree/261-2.java @@ -0,0 +1,54 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + public int getCount() { + return count; + } + + private int count; + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public boolean validTree(int n, int[][] edges) { + if (n == 0 || edges.length != n - 1) + return false; + + UnionFind uf = new UnionFind(n); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + uf.unionByRank(u, v); + } + + return uf.getCount() == 1; + } +} diff --git a/solutions/261. Graph Valid Tree/261-2.py b/solutions/261. Graph Valid Tree/261-2.py new file mode 100644 index 00000000000..f65e6305946 --- /dev/null +++ b/solutions/261. Graph Valid Tree/261-2.py @@ -0,0 +1,37 @@ +class UnionFind: + def __init__(self, n: int): + self.count = n + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self._find(u) + j = self._find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + self.count -= 1 + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def validTree(self, n: int, edges: List[List[int]]) -> bool: + if n == 0 or len(edges) != n - 1: + return False + + uf = UnionFind(n) + + for u, v in edges: + uf.unionByRank(u, v) + + return uf.count == 1 diff --git a/solutions/261. Graph Valid Tree/261.cpp b/solutions/261. Graph Valid Tree/261.cpp new file mode 100644 index 00000000000..7242d53029a --- /dev/null +++ b/solutions/261. Graph Valid Tree/261.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool validTree(int n, vector>& edges) { + if (n == 0 || edges.size() != n - 1) + return false; + + vector> graph(n); + queue q{{0}}; + unordered_set seen{{0}}; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) + if (!seen.contains(v)) { + q.push(v); + seen.insert(v); + } + } + + return seen.size() == n; + } +}; diff --git a/solutions/261. Graph Valid Tree/261.java b/solutions/261. Graph Valid Tree/261.java new file mode 100644 index 00000000000..e436431babe --- /dev/null +++ b/solutions/261. Graph Valid Tree/261.java @@ -0,0 +1,31 @@ +class Solution { + public boolean validTree(int n, int[][] edges) { + if (n == 0 || edges.length != n - 1) + return false; + + List[] graph = new List[n]; + Queue q = new ArrayDeque<>(Arrays.asList(0)); + Set seen = new HashSet<>(Arrays.asList(0)); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + while (!q.isEmpty()) { + final int u = q.poll(); + for (final int v : graph[u]) + if (!seen.contains(v)) { + q.offer(v); + seen.add(v); + } + } + + return seen.size() == n; + } +} diff --git a/solutions/261. Graph Valid Tree/261.py b/solutions/261. Graph Valid Tree/261.py new file mode 100644 index 00000000000..db53184ce16 --- /dev/null +++ b/solutions/261. Graph Valid Tree/261.py @@ -0,0 +1,21 @@ +class Solution: + def validTree(self, n: int, edges: List[List[int]]) -> bool: + if n == 0 or len(edges) != n - 1: + return False + + graph = [[] for _ in range(n)] + q = collections.deque([0]) + seen = {0} + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + while q: + u = q.popleft() + for v in graph[u]: + if v not in seen: + q.append(v) + seen.add(v) + + return len(seen) == n diff --git a/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.cpp b/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.cpp new file mode 100644 index 00000000000..4ec2c61de45 --- /dev/null +++ b/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector> findMatrix(vector& nums) { + // The number of rows we need equals the maximum frequency. + vector> ans; + vector count(nums.size() + 1); + + for (const int num : nums) { + // Construct `ans` on demand. + if (++count[num] > ans.size()) + ans.push_back({}); + ans[count[num] - 1].push_back(num); + } + + return ans; + } +}; diff --git a/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.java b/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.java new file mode 100644 index 00000000000..46b032cf918 --- /dev/null +++ b/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.java @@ -0,0 +1,16 @@ +class Solution { + public List> findMatrix(int[] nums) { + // The number of rows we need equals the maximum frequency. + List> ans = new ArrayList<>(); + int[] count = new int[nums.length + 1]; + + for (final int num : nums) { + // Construct `ans` on demand. + if (++count[num] > ans.size()) + ans.add(new ArrayList<>()); + ans.get(count[num] - 1).add(num); + } + + return ans; + } +} diff --git a/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.py b/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.py new file mode 100644 index 00000000000..f3f49282250 --- /dev/null +++ b/solutions/2610. Convert an Array Into a 2D Array With Conditions/2610.py @@ -0,0 +1,14 @@ +class Solution: + def findMatrix(self, nums: List[int]) -> List[List[int]]: + # The number of rows we need equals the maximum frequency. + ans = [] + count = [0] * (len(nums) + 1) + + for num in nums: + count[num] += 1 + # Construct `ans` on demand. + if count[num] > len(ans): + ans.append([]) + ans[count[num] - 1].append(num) + + return ans diff --git a/solutions/2611. Mice and Cheese/2611.cpp b/solutions/2611. Mice and Cheese/2611.cpp new file mode 100644 index 00000000000..87964182593 --- /dev/null +++ b/solutions/2611. Mice and Cheese/2611.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + // diffs[i] := reward1[i] - reward2[i]. + vector diffs; + + for (int i = 0; i < reward1.size(); ++i) + diffs.push_back(reward1[i] - reward2[i]); + + nth_element(diffs.begin(), diffs.begin() + k, diffs.end(), greater<>()); + return accumulate(reward2.begin(), reward2.end(), 0) + + accumulate(diffs.begin(), diffs.begin() + k, 0); + } +}; diff --git a/solutions/2611. Mice and Cheese/2611.java b/solutions/2611. Mice and Cheese/2611.java new file mode 100644 index 00000000000..20223a8add3 --- /dev/null +++ b/solutions/2611. Mice and Cheese/2611.java @@ -0,0 +1,13 @@ +class Solution { + public int miceAndCheese(int[] reward1, int[] reward2, int k) { + Queue minHeap = new PriorityQueue<>(); + + for (int i = 0; i < reward1.length; ++i) { + minHeap.offer(reward1[i] - reward2[i]); + if (minHeap.size() == k + 1) + minHeap.poll(); + } + + return Arrays.stream(reward2).sum() + minHeap.stream().mapToInt(Integer::intValue).sum(); + } +} diff --git a/solutions/2611. Mice and Cheese/2611.py b/solutions/2611. Mice and Cheese/2611.py new file mode 100644 index 00000000000..bddaf272e40 --- /dev/null +++ b/solutions/2611. Mice and Cheese/2611.py @@ -0,0 +1,3 @@ +class Solution: + def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: + return sum(reward2) + sum(heapq.nlargest(k, (a - b for a, b in zip(reward1, reward2)))) diff --git a/solutions/2612. Minimum Reverse Operations/2612.cpp b/solutions/2612. Minimum Reverse Operations/2612.cpp new file mode 100644 index 00000000000..7fdeaa36675 --- /dev/null +++ b/solutions/2612. Minimum Reverse Operations/2612.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector minReverseOperations(int n, int p, vector& banned, int k) { + const unordered_set bannedSet{banned.begin(), banned.end()}; + vector ans(n, -1); + // unseen[i] := the unseen numbers that % 2 == i + vector> unseen(2); + + for (int num = 0; num < n; ++num) + if (num != p && !bannedSet.contains(num)) + unseen[num % 2].insert(num); + + // Perform BFS from `p`. + queue q{{p}}; + ans[p] = 0; + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + const int lo = max(u - k + 1, k - 1 - u); + const int hi = min(u + k - 1, n - 1 - (u - (n - k))); + // Choose the correct set of numbers. + set& nums = unseen[lo % 2]; + for (auto it = nums.lower_bound(lo); it != nums.end() && *it <= hi;) { + ans[*it] = ans[u] + 1; + q.push(*it); + it = nums.erase(it); + } + } + + return ans; + } +}; diff --git a/solutions/2612. Minimum Reverse Operations/2612.java b/solutions/2612. Minimum Reverse Operations/2612.java new file mode 100644 index 00000000000..6b1b334c96b --- /dev/null +++ b/solutions/2612. Minimum Reverse Operations/2612.java @@ -0,0 +1,35 @@ +class Solution { + public int[] minReverseOperations(int n, int p, int[] banned, int k) { + Set bannedSet = Arrays.stream(banned).boxed().collect(Collectors.toSet()); + int[] ans = new int[n]; + Arrays.fill(ans, -1); + // unseen[i] := the unseen numbers that % 2 == i + TreeSet[] unseen = new TreeSet[2]; + unseen[0] = new TreeSet<>(); + unseen[1] = new TreeSet<>(); + + for (int num = 0; num < n; ++num) + if (num != p && !bannedSet.contains(num)) + unseen[num % 2].add(num); + + // Perform BFS from `p`. + Queue q = new ArrayDeque<>(Arrays.asList(p)); + ans[p] = 0; + + while (!q.isEmpty()) { + final int u = q.poll(); + final int lo = Math.max(u - k + 1, k - 1 - u); + final int hi = Math.min(u + k - 1, n - 1 - (u - (n - k))); + // Choose the correct set of numbers. + TreeSet nums = unseen[lo % 2]; + for (Integer num = nums.ceiling(lo); num != null && num <= hi;) { + ans[num] = ans[u] + 1; + q.offer(num); + nums.remove(num); + num = nums.higher(num); + } + } + + return ans; + } +} diff --git a/solutions/2612. Minimum Reverse Operations/2612.py b/solutions/2612. Minimum Reverse Operations/2612.py new file mode 100644 index 00000000000..6a0c35cedaf --- /dev/null +++ b/solutions/2612. Minimum Reverse Operations/2612.py @@ -0,0 +1,32 @@ +from sortedcontainers import SortedList + + +class Solution: + def minReverseOperations(self, n: int, p: int, banned: List[int], k: int) -> List[int]: + bannedSet = set(banned) + ans = [-1] * n + # unseen[i] := the unseen numbers that % 2 == i + unseen = [SortedList(), SortedList()] + + for num in range(n): + if num != p and num not in bannedSet: + unseen[num % 2].add(num) + + # Perform BFS from `p`. + q = collections.deque([p]) + ans[p] = 0 + + while q: + u = q.popleft() + lo = max(u - k + 1, k - 1 - u) + hi = min(u + k - 1, n - 1 - (u - (n - k))) + # Choose the correct set of numbers. + nums = unseen[lo % 2] + i = nums.bisect_left(lo) + while i < len(nums) and nums[i] <= hi: + num = nums[i] + ans[num] = ans[u] + 1 + q.append(num) + nums.pop(i) + + return ans diff --git a/solutions/2613. Beautiful Pairs/2613.cpp b/solutions/2613. Beautiful Pairs/2613.cpp new file mode 100644 index 00000000000..012c169d6ae --- /dev/null +++ b/solutions/2613. Beautiful Pairs/2613.cpp @@ -0,0 +1,135 @@ +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) + : maxNum(nums.size()), nums(move(nums)), tree(4 * maxNum, -1) {} + + // Updates the value of the node to be the index of the smaller number between + // the old value stored at the node and the new value `index`, where `i` is + // the index of the element in the `nums` array. + void update(int i, int numIndex) { + update(0, 0, maxNum, i, numIndex); + } + + // Returns the index k s.t. `nums[k]` is maximum number in the range [i, j]. + int query(int i, int j) const { + return query(0, 0, maxNum, i, j); + } + + private: + // default node value for non-overlapping queries + static constexpr int kDefaultValue = -1; + const int maxNum; + const vector nums; // nums2 + nums1 or nums2 - nums1 + vector tree; // tree[i] := the minimum index stored in this node + + void update(int treeIndex, int lo, int hi, int i, int numIndex) { + if (lo == hi) { + tree[treeIndex] = merge(tree[treeIndex], numIndex); + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + update(2 * treeIndex + 1, lo, mid, i, numIndex); + else + update(2 * treeIndex + 2, mid + 1, hi, i, numIndex); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + int query(int treeIndex, int lo, int hi, int i, int j) const { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return kDefaultValue; + const int mid = (lo + hi) / 2; + return merge(query(2 * treeIndex + 1, lo, mid, i, j), + query(2 * treeIndex + 2, mid + 1, hi, i, j)); + } + + // Returns the better index. Index i is better than index j if + // (nums[i] > nums[j]) or (nums[i] == nums[j] && i < j). + int merge(const int& i, const int& j) const { + if (i == -1) + return j; + if (j == -1) + return i; + if (nums[i] > nums[j]) + return i; + if (nums[j] > nums[i]) + return j; + return min(i, j); + } +}; + +class Solution { + public: + vector beautifulPair(vector& nums1, vector& nums2) { + // The goal is to find the lexicographically smallest beautiful pair (i, j) + // s.t. |nums1[i] - nums1[j]| + |nums2[i] - nums2[j]| is the smallest. + // + // Sort `nums2` and store the order in `indices`. + // To minimize |nums1[i] - nums1[j]| + |nums2[i] - nums2[j]|, since we + // already have sorted `nums2`, we can always have nums2[i] > nums2[j] while + // iterating the array. So we only need to consider the following 2 cases: + // + // * nums1[i] >= nums1[j]: + // The value will be nums1[i] - nums1[j] + nums2[i] - nums2[j] + // = (nums2[i] + nums1[i]) - (nums2[j] + nums1[j]) + // Just find max (nums2[j] + nums1[j]) s.t. 0 <= nums1[j] <= nums1[i]. + // + // * nums1[i] <= nums1[j]: + // The value will be nums1[j] - nums1[i] + nums2[i] - nums2[j] + // = (nums2[i] - nums1[i]) - (nums2[j] - nums1[j]) + // Just find max (nums2[j] - nums1[j]) s.t. nums1[i] <= nums1[j] <= n. + constexpr int kInf = 1'000'000'000; + const int n = nums1.size(); + vector ans(2, n); + vector nums2PlusNums1; + vector nums2MinusNums1; + vector indices; + int minBeauty = INT_MAX; + + for (int i = 0; i < n; ++i) { + nums2PlusNums1.push_back(nums2[i] + nums1[i]); + nums2MinusNums1.push_back(nums2[i] - nums1[i]); + indices.push_back(i); + } + + ranges::sort(indices, + [&nums2](int i, int j) { return nums2[i] < nums2[j]; }); + + SegmentTree tree1(nums2PlusNums1); + SegmentTree tree2(nums2MinusNums1); + + for (const int i : indices) { + const int num = nums1[i]; + // For case nums1[i] >= nums1[j], find index j s.t. (nums2[j] + nums1[j]) + // is the maximum in the range [0, nums1[i]]. + int j = tree1.query(0, num); + if (j >= 0) + updateAns(nums2PlusNums1, i, j, minBeauty, ans); + tree1.update(num, i); + // For case nums1[i] <= nums1[j], find index j s.t. (nums2[j] - nums1[j]) + // is the maximum in the range [nums1[i], n]. + j = tree2.query(num, n); + if (j >= 0) + updateAns(nums2MinusNums1, i, j, minBeauty, ans); + tree2.update(num, i); + } + + return ans; + } + + private: + void updateAns(const vector& nums, int i, int j, int& minBeauty, + vector& ans) { + // beauty := |nums1[i] - nums1[j]| + |nums2[i] - nums2[j]| + const int beauty = nums[i] - nums[j]; + const vector nextAns = {min(i, j), max(i, j)}; + if (beauty < minBeauty) { + minBeauty = beauty; + ans = nextAns; + } else if (beauty == minBeauty) { + ans = min(ans, nextAns); + } + } +}; diff --git a/solutions/2614. Prime In Diagonal/2614.cpp b/solutions/2614. Prime In Diagonal/2614.cpp new file mode 100644 index 00000000000..3914c5a28d8 --- /dev/null +++ b/solutions/2614. Prime In Diagonal/2614.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int diagonalPrime(vector>& nums) { + int ans = 0; + for (int i = 0; i < nums.size(); ++i) { + const int a = nums[i][i]; + const int b = nums[i][nums.size() - i - 1]; + if (isPrime(a)) + ans = max(ans, a); + if (isPrime(b)) + ans = max(ans, b); + } + return ans; + } + + private: + bool isPrime(int n) { + if (n <= 1) + return false; + for (int i = 2; i * i <= n; ++i) + if (n % i == 0) + return false; + return true; + } +}; diff --git a/solutions/2614. Prime In Diagonal/2614.java b/solutions/2614. Prime In Diagonal/2614.java new file mode 100644 index 00000000000..64478cdd6dd --- /dev/null +++ b/solutions/2614. Prime In Diagonal/2614.java @@ -0,0 +1,23 @@ +class Solution { + public int diagonalPrime(int[][] nums) { + int ans = 0; + for (int i = 0; i < nums.length; ++i) { + final int a = nums[i][i]; + final int b = nums[i][nums.length - i - 1]; + if (isPrime(a)) + ans = Math.max(ans, a); + if (isPrime(b)) + ans = Math.max(ans, b); + } + return ans; + } + + private boolean isPrime(int n) { + if (n <= 1) + return false; + for (int i = 2; i * i <= n; ++i) + if (n % i == 0) + return false; + return true; + } +} diff --git a/solutions/2614. Prime In Diagonal/2614.py b/solutions/2614. Prime In Diagonal/2614.py new file mode 100644 index 00000000000..e773a7e0af2 --- /dev/null +++ b/solutions/2614. Prime In Diagonal/2614.py @@ -0,0 +1,16 @@ +class Solution: + def diagonalPrime(self, nums: List[List[int]]) -> int: + def isPrime(n: int) -> bool: + if n <= 1: + return False + for i in range(2, int(n**0.5) + 1): + if n % i == 0: + return False + return True + + primes1 = [row[i] + for i, row in enumerate(nums) if isPrime(row[i])] + primes2 = [row[-i - 1] + for i, row in enumerate(nums) if isPrime(row[-i - 1])] + return max(max(primes1) if primes1 else 0, + max(primes2) if primes2 else 0) diff --git a/solutions/2615. Sum of Distances/2615.cpp b/solutions/2615. Sum of Distances/2615.cpp new file mode 100644 index 00000000000..e769d8e9484 --- /dev/null +++ b/solutions/2615. Sum of Distances/2615.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector distance(vector& nums) { + vector ans(nums.size()); + unordered_map> numToIndices; + + for (int i = 0; i < nums.size(); ++i) + numToIndices[nums[i]].push_back(i); + + for (const auto& [_, indices] : numToIndices) { + const int n = indices.size(); + if (n == 1) + continue; + long sumSoFar = accumulate(indices.begin(), indices.end(), 0L); + int prevIndex = 0; + for (int i = 0; i < n; ++i) { + sumSoFar += (i - 1) * (indices[i] - prevIndex); + sumSoFar -= (n - 1 - i) * (indices[i] - prevIndex); + ans[indices[i]] = sumSoFar; + prevIndex = indices[i]; + } + } + + return ans; + } +}; diff --git a/solutions/2615. Sum of Distances/2615.java b/solutions/2615. Sum of Distances/2615.java new file mode 100644 index 00000000000..70528bf8363 --- /dev/null +++ b/solutions/2615. Sum of Distances/2615.java @@ -0,0 +1,28 @@ +public class Solution { + public long[] distance(int[] nums) { + long[] ans = new long[nums.length]; + Map> numToIndices = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + numToIndices.putIfAbsent(nums[i], new ArrayList<>()); + numToIndices.get(nums[i]).add(i); + } + + for (List indices : numToIndices.values()) { + final int n = indices.size(); + if (n == 1) { + continue; + } + long sumSoFar = indices.stream().mapToLong(Integer::intValue).sum(); + int prevIndex = 0; + for (int i = 0; i < n; ++i) { + sumSoFar += (i - 1) * (indices.get(i) - prevIndex); + sumSoFar -= (n - 1 - i) * (indices.get(i) - prevIndex); + ans[indices.get(i)] = sumSoFar; + prevIndex = indices.get(i); + } + } + + return ans; + } +} diff --git a/solutions/2615. Sum of Distances/2615.py b/solutions/2615. Sum of Distances/2615.py new file mode 100644 index 00000000000..a06c9c5cb24 --- /dev/null +++ b/solutions/2615. Sum of Distances/2615.py @@ -0,0 +1,21 @@ +class Solution: + def distance(self, nums: List[int]) -> List[int]: + ans = [0] * len(nums) + numToIndices = collections.defaultdict(list) + + for i, num in enumerate(nums): + numToIndices[num].append(i) + + for indices in numToIndices.values(): + n = len(indices) + if n == 1: + continue + sumSoFar = sum(indices) + prevIndex = 0 + for i in range(n): + sumSoFar += (i - 1) * (indices[i] - prevIndex) + sumSoFar -= (n - 1 - i) * (indices[i] - prevIndex) + ans[indices[i]] = sumSoFar + prevIndex = indices[i] + + return ans diff --git a/solutions/2616. Minimize the Maximum Difference of Pairs/2616.cpp b/solutions/2616. Minimize the Maximum Difference of Pairs/2616.cpp new file mode 100644 index 00000000000..a48c7aef5e7 --- /dev/null +++ b/solutions/2616. Minimize the Maximum Difference of Pairs/2616.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int minimizeMax(vector& nums, int p) { + ranges::sort(nums); + + int l = 0; + int r = nums.back() - nums.front(); + + while (l < r) { + const int m = (l + r) / 2; + if (numPairs(nums, m) >= p) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Returns the number of pairs that can be obtained if the difference between + // each pair <= `maxDiff`. + int numPairs(const vector& nums, int maxDiff) { + int pairs = 0; + for (int i = 1; i < nums.size(); ++i) + // Greedily pair nums[i] with nums[i - 1]. + if (nums[i] - nums[i - 1] <= maxDiff) { + ++pairs; + ++i; + } + return pairs; + } +}; diff --git a/solutions/2616. Minimize the Maximum Difference of Pairs/2616.java b/solutions/2616. Minimize the Maximum Difference of Pairs/2616.java new file mode 100644 index 00000000000..7b42cc96a5e --- /dev/null +++ b/solutions/2616. Minimize the Maximum Difference of Pairs/2616.java @@ -0,0 +1,31 @@ +class Solution { + public int minimizeMax(int[] nums, int p) { + Arrays.sort(nums); + + int l = 0; + int r = nums[nums.length - 1] - nums[0]; + + while (l < r) { + final int m = (l + r) / 2; + if (numPairs(nums, m) >= p) + r = m; + else + l = m + 1; + } + + return l; + } + + // Returns the number of pairs that can be obtained if the difference between each + // pair <= `maxDiff`. + private int numPairs(int[] nums, int maxDiff) { + int pairs = 0; + for (int i = 1; i < nums.length; ++i) + // Greedily pair nums[i] with nums[i - 1]. + if (nums[i] - nums[i - 1] <= maxDiff) { + ++pairs; + ++i; + } + return pairs; + } +} diff --git a/solutions/2616. Minimize the Maximum Difference of Pairs/2616.py b/solutions/2616. Minimize the Maximum Difference of Pairs/2616.py new file mode 100644 index 00000000000..2c80fafb95d --- /dev/null +++ b/solutions/2616. Minimize the Maximum Difference of Pairs/2616.py @@ -0,0 +1,23 @@ +class Solution: + def minimizeMax(self, nums: List[int], p: int) -> int: + nums.sort() + + def numPairs(maxDiff: int) -> int: + """ + Returns the number of pairs that can be obtained if the difference between + each pair <= `maxDiff`. + """ + pairs = 0 + i = 1 + while i < len(nums): + # Greedily pair nums[i] with nums[i - 1]. + if nums[i] - nums[i - 1] <= maxDiff: + pairs += 1 + i += 2 + else: + i += 1 + return pairs + + return bisect.bisect_left( + range(0, nums[-1] - nums[0]), p, + key=lambda m: numPairs(m)) diff --git a/solutions/2617. Minimum Number of Visited Cells in a Grid/2617.cpp b/solutions/2617. Minimum Number of Visited Cells in a Grid/2617.cpp new file mode 100644 index 00000000000..84f91e16c7b --- /dev/null +++ b/solutions/2617. Minimum Number of Visited Cells in a Grid/2617.cpp @@ -0,0 +1,78 @@ +class SegmentTree { + public: + explicit SegmentTree(int n, int kInf) : kInf(kInf), n(n), tree(4 * n, kInf) {} + + // Updates nums[i] to val. + void update(int i, int val) { + update(0, 0, n - 1, i, val); + } + + // Returns min(nums[i..j]). + int query(int i, int j) { + return query(0, 0, n - 1, i, j); + } + + private: + const int kInf; // the invalid value + const int n; // the size of the input array + vector tree; // the segment tree + + void update(int treeIndex, int lo, int hi, int i, int val) { + if (lo == hi) { + tree[treeIndex] = val; + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + update(2 * treeIndex + 1, lo, mid, i, val); + else + update(2 * treeIndex + 2, mid + 1, hi, i, val); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + int query(int treeIndex, int lo, int hi, int i, int j) { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return kInf; + const int mid = (lo + hi) / 2; + return merge(query(treeIndex * 2 + 1, lo, mid, i, j), + query(treeIndex * 2 + 2, mid + 1, hi, i, j)); + } + + // Merges the result of the left node and the right node. + int merge(int a, int b) { + return min(a, b); + } +}; + +class Solution { + public: + int minimumVisitedCells(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + const int kInf = (m + n) * 2 - 1; + vector rows(m, SegmentTree(n, kInf)); + vector cols(n, SegmentTree(m, kInf)); + + // The min # cells to visit (m - 1, n - 1) from (m - 1, n - 1) is 1. + rows[m - 1].update(n - 1, 1); + cols[n - 1].update(m - 1, 1); + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) { + // There's no k s.t. j < k <= 0 + j. + // There's no k s.t. i < k <= 0 + i. + if (grid[i][j] == 0) + continue; + const int moveRight = rows[i].query(j + 1, grid[i][j] + j); + const int moveDown = cols[j].query(i + 1, grid[i][j] + i); + const int minMove = min(kInf, min(moveRight, moveDown) + 1); + rows[i].update(j, minMove); + cols[j].update(i, minMove); + } + + const int res = rows[0].query(0, 0); + return res == kInf ? -1 : res; + } +}; diff --git a/solutions/2618. Check if Object Instance of Class/2618.ts b/solutions/2618. Check if Object Instance of Class/2618.ts new file mode 100644 index 00000000000..e865d5799d0 --- /dev/null +++ b/solutions/2618. Check if Object Instance of Class/2618.ts @@ -0,0 +1,9 @@ +function checkIfInstanceOf(obj: any, classFunction: any): boolean { + while (obj != null) { + if (obj.constructor === classFunction) { + return true; + } + obj = Object.getPrototypeOf(obj); + } + return false; +} diff --git a/solutions/2619. Array Prototype Last/2619.ts b/solutions/2619. Array Prototype Last/2619.ts new file mode 100644 index 00000000000..ba6235005b7 --- /dev/null +++ b/solutions/2619. Array Prototype Last/2619.ts @@ -0,0 +1,11 @@ +declare global { + interface Array { + last(): T | -1; + } +} + +Array.prototype.last = function () { + return this.length === 0 ? -1 : this[this.length - 1]; +}; + +export {}; diff --git a/solutions/262. Trips and Users/262.sql b/solutions/262. Trips and Users/262.sql new file mode 100644 index 00000000000..28cc9b92559 --- /dev/null +++ b/solutions/262. Trips and Users/262.sql @@ -0,0 +1,12 @@ +SELECT + Trips.request_at AS Day, + ROUND(SUM(Trips.status != 'completed') / COUNT(*), 2) AS 'Cancellation Rate' +FROM Trips +INNER JOIN Users AS Clients + ON (Trips.client_id = Clients.users_id) +INNER JOIN Users AS Drivers + ON (Trips.driver_id = Drivers.users_id) +WHERE Clients.banned = 'No' + AND Drivers.banned = 'No' + AND Trips.request_at BETWEEN '2013-10-01' AND '2013-10-03' +GROUP BY 1; diff --git a/solutions/2620. Counter/2620.ts b/solutions/2620. Counter/2620.ts new file mode 100644 index 00000000000..e5a129957e1 --- /dev/null +++ b/solutions/2620. Counter/2620.ts @@ -0,0 +1,5 @@ +function createCounter(n: number): () => number { + return function () { + return n++; + }; +} diff --git a/solutions/2621. Sleep/2621.ts b/solutions/2621. Sleep/2621.ts new file mode 100644 index 00000000000..8f1e12214c4 --- /dev/null +++ b/solutions/2621. Sleep/2621.ts @@ -0,0 +1,5 @@ +async function sleep(millis: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, millis); + }); +} diff --git a/solutions/2622. Cache With Time Limit/2622-2.ts b/solutions/2622. Cache With Time Limit/2622-2.ts new file mode 100644 index 00000000000..27a0e04c522 --- /dev/null +++ b/solutions/2622. Cache With Time Limit/2622-2.ts @@ -0,0 +1,28 @@ +interface TTLValue { + value: number; + timer: ReturnType; +} + +class TimeLimitedCache { + private cache = new Map(); + + set(key: number, value: number, duration: number): boolean { + const exists = this.cache.has(key); + if (exists) { + clearTimeout(this.cache.get(key).timer); + } + this.cache.set(key, { + value, + timer: setTimeout(() => this.cache.delete(key), duration), + }); + return exists; + } + + get(key: number): number { + return this.cache.has(key) ? this.cache.get(key).value : -1; + } + + count(): number { + return this.cache.size; + } +} diff --git a/solutions/2622. Cache With Time Limit/2622.ts b/solutions/2622. Cache With Time Limit/2622.ts new file mode 100644 index 00000000000..2ed12bc92eb --- /dev/null +++ b/solutions/2622. Cache With Time Limit/2622.ts @@ -0,0 +1,34 @@ +interface Value { + value: number; + expiredAt: number; +} + +class TimeLimitedCache { + private cache = new Map(); + + set(key: number, value: number, duration: number): boolean { + const now = Date.now(); + const exists = this.getValue(now, key) !== undefined; + this.cache.set(key, { value, expiredAt: now + duration }); + return exists; + } + + get(key: number): number { + const val = this.getValue(Date.now(), key); + return val === undefined ? -1 : val.value; + } + + count(): number { + const now = Date.now(); + for (const key of this.cache.keys()) + if (this.getValue(now, key) === undefined) { + this.cache.delete(key); + } + return this.cache.size; + } + + private getValue(now: number, key: number): Value | undefined { + const val = this.cache.get(key); + return val && now <= val.expiredAt ? val : undefined; + } +} diff --git a/solutions/2623. Memoize/2623.ts b/solutions/2623. Memoize/2623.ts new file mode 100644 index 00000000000..db179accd91 --- /dev/null +++ b/solutions/2623. Memoize/2623.ts @@ -0,0 +1,9 @@ +type Fn = (...params: number[]) => number; + +function memoize(fn: Fn): Fn { + const cache: Record = {}; + return function (...args) { + const key = args.join(' '); + return cache[key] === undefined ? (cache[key] = fn(...args)) : cache[key]; + }; +} diff --git a/solutions/2624. Snail Traversal/2624.ts b/solutions/2624. Snail Traversal/2624.ts new file mode 100644 index 00000000000..17e0526ad00 --- /dev/null +++ b/solutions/2624. Snail Traversal/2624.ts @@ -0,0 +1,24 @@ +declare global { + interface Array { + snail(rowsCount: number, colsCount: number): number[][]; + } +} + +Array.prototype.snail = function ( + rowsCount: number, + colsCount: number +): number[][] { + if (rowsCount * colsCount != this.length) { + return []; + } + const ans: number[][] = []; + for (let i = 0; i < rowsCount; ++i) { + ans.push([]); + } + for (let i = 0; i < rowsCount; ++i) + for (let j = 0; j < colsCount; ++j) { + const k = j * rowsCount + (j % 2 == 0 ? i : rowsCount - 1 - i); + ans[i][j] = this[k]; + } + return ans; +}; diff --git a/solutions/2625. Flatten Deeply Nested Array/2625.ts b/solutions/2625. Flatten Deeply Nested Array/2625.ts new file mode 100644 index 00000000000..deee6e029f4 --- /dev/null +++ b/solutions/2625. Flatten Deeply Nested Array/2625.ts @@ -0,0 +1,23 @@ +type MultiDimensionalArray = (number | MultiDimensionalArray)[]; + +var flat = function ( + arr: MultiDimensionalArray, + n: number +): MultiDimensionalArray { + function dfs(arr: number | MultiDimensionalArray, n: number) { + if (typeof arr === 'number') { + ans.push(arr); + } else if (n === 0) { + for (const element of arr) { + ans.push(element); + } + } else { + for (const element of arr) { + dfs(element, n - 1); + } + } + } + const ans: MultiDimensionalArray = []; + dfs(arr, n); + return ans; +}; diff --git a/solutions/2626. Array Reduce Transformation/2626.ts b/solutions/2626. Array Reduce Transformation/2626.ts new file mode 100644 index 00000000000..2cdfca950dc --- /dev/null +++ b/solutions/2626. Array Reduce Transformation/2626.ts @@ -0,0 +1,9 @@ +type Fn = (accum: number, curr: number) => number; + +function reduce(nums: number[], fn: Fn, init: number): number { + let ans = init; + for (const num of nums) { + ans = fn(ans, num); + } + return ans; +} diff --git a/solutions/2627. Debounce/2627.ts b/solutions/2627. Debounce/2627.ts new file mode 100644 index 00000000000..9aa6f2c81d9 --- /dev/null +++ b/solutions/2627. Debounce/2627.ts @@ -0,0 +1,9 @@ +type F = (...args: number[]) => void; + +function debounce(fn: F, t: number): F { + let timeout: ReturnType | undefined; + return function (...args) { + clearTimeout(timeout); + timeout = setTimeout(() => fn(...args), t); + }; +} diff --git a/solutions/2628. JSON Deep Equal/2628.ts b/solutions/2628. JSON Deep Equal/2628.ts new file mode 100644 index 00000000000..7668515e63c --- /dev/null +++ b/solutions/2628. JSON Deep Equal/2628.ts @@ -0,0 +1,31 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +function areDeeplyEqual(o1: JSONValue, o2: JSONValue): boolean { + if (o1 === o2) { + return true; + } + if (o1 === null || o1 === undefined || o2 === null || o2 === undefined) { + return false; + } + if (typeof o1 !== 'object' || typeof o2 !== 'object') { + return false; + } + if (Array.isArray(o1) !== Array.isArray(o2)) { + return false; + } + if (Object.keys(o1).length != Object.keys(o2).length) { + return false; + } + for (const key in o1) { + if (!areDeeplyEqual(o1[key], o2[key])) { + return false; + } + } + return true; +} diff --git a/solutions/2629. Function Composition/2629.ts b/solutions/2629. Function Composition/2629.ts new file mode 100644 index 00000000000..59cbdc192c0 --- /dev/null +++ b/solutions/2629. Function Composition/2629.ts @@ -0,0 +1,7 @@ +type F = (x: number) => number; + +function compose(functions: F[]): F { + return function (x) { + return functions.reduceRight((val, f) => f(val), x); + }; +} diff --git a/solutions/263. Ugly Number/263.cpp b/solutions/263. Ugly Number/263.cpp new file mode 100644 index 00000000000..6246d6dd9be --- /dev/null +++ b/solutions/263. Ugly Number/263.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool isUgly(int n) { + if (n == 0) + return false; + + for (const int prime : {2, 3, 5}) + while (n % prime == 0) + n /= prime; + + return n == 1; + } +}; diff --git a/solutions/263. Ugly Number/263.java b/solutions/263. Ugly Number/263.java new file mode 100644 index 00000000000..3402b1dc9d2 --- /dev/null +++ b/solutions/263. Ugly Number/263.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isUgly(int n) { + if (n == 0) + return false; + + for (final int prime : new int[] {2, 3, 5}) + while (n % prime == 0) + n /= prime; + + return n == 1; + } +} diff --git a/solutions/263. Ugly Number/263.py b/solutions/263. Ugly Number/263.py new file mode 100644 index 00000000000..ed20b8d1b01 --- /dev/null +++ b/solutions/263. Ugly Number/263.py @@ -0,0 +1,10 @@ +class Solution: + def isUgly(self, n: int) -> bool: + if n == 0: + return False + + for prime in 2, 3, 5: + while n % prime == 0: + n //= prime + + return n == 1 diff --git a/solutions/2630. Memoize II/2630.ts b/solutions/2630. Memoize II/2630.ts new file mode 100644 index 00000000000..681d53d6d6e --- /dev/null +++ b/solutions/2630. Memoize II/2630.ts @@ -0,0 +1,23 @@ +type Fn = (...params: any) => any; + +function memoize(fn: Fn): Fn { + const root = new Map(); // trie + const ansKey = {}; + return function (...params) { + let node = root; + for (const param of params) { + let next = node.get(param); + if (next === undefined) { + next = new Map(); + node.set(param, next); + } + node = next; + } + + // Check if `ansKey` has been set. + if (node.has(ansKey)) return node.get(ansKey); + const ans = fn(...params); + node.set(ansKey, ans); + return ans; + }; +} diff --git a/solutions/2631. Group By/2631.ts b/solutions/2631. Group By/2631.ts new file mode 100644 index 00000000000..953b33123b1 --- /dev/null +++ b/solutions/2631. Group By/2631.ts @@ -0,0 +1,17 @@ +declare global { + interface Array { + groupBy(fn: (item: T) => string): Record; + } +} + +Array.prototype.groupBy = function (fn) { + const ans: Record = {}; + for (const item of this) { + const key = fn(item); + if (ans[key] === undefined) { + ans[key] = []; + } + ans[key].push(item); + } + return ans; +}; diff --git a/solutions/2632. Curry/2632.ts b/solutions/2632. Curry/2632.ts new file mode 100644 index 00000000000..9f87300eeac --- /dev/null +++ b/solutions/2632. Curry/2632.ts @@ -0,0 +1,7 @@ +function curry(fn: Function): Function { + return function curried(...args: any[]): any { + return args.length >= fn.length + ? fn.apply(this, args) + : curried.bind(this, ...args); + }; +} diff --git a/solutions/2633. Convert Object to JSON String/2633.ts b/solutions/2633. Convert Object to JSON String/2633.ts new file mode 100644 index 00000000000..673f91995d3 --- /dev/null +++ b/solutions/2633. Convert Object to JSON String/2633.ts @@ -0,0 +1,28 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +function jsonStringify(object: JSONValue): string { + if (object === null) { + return 'null'; + } + if (typeof object === 'boolean' || typeof object === 'number') { + return String(object); + } + if (typeof object === 'string') { + return `"${object}"`; + } + if (Array.isArray(object)) { + const elems = object.map((elem) => jsonStringify(elem)); + return `[${elems.join(',')}]`; + } + // typeof object === 'object' + const pairs = Object.keys(object).map( + (key) => `"${key}":${jsonStringify(object[key])}` + ); + return `{${pairs.join(',')}}`; +} diff --git a/solutions/2634. Filter Elements from Array/2634.ts b/solutions/2634. Filter Elements from Array/2634.ts new file mode 100644 index 00000000000..4477acaf049 --- /dev/null +++ b/solutions/2634. Filter Elements from Array/2634.ts @@ -0,0 +1,11 @@ +type Fn = (n: number, i: number) => any; + +function filter(arr: number[], fn: Fn): number[] { + const ans: number[] = []; + arr.forEach((a, index) => { + if (fn(a, index)) { + ans.push(a); + } + }); + return ans; +} diff --git a/solutions/2635. Apply Transform Over Each Element in Array/2635.ts b/solutions/2635. Apply Transform Over Each Element in Array/2635.ts new file mode 100644 index 00000000000..2d19b5840d2 --- /dev/null +++ b/solutions/2635. Apply Transform Over Each Element in Array/2635.ts @@ -0,0 +1,7 @@ +function map(arr: number[], fn: (n: number, i: number) => number): number[] { + const ans: number[] = []; + arr.forEach((a, index) => { + ans.push(fn(a, index)); + }); + return ans; +} diff --git a/solutions/2636. Promise Pool/2636.ts b/solutions/2636. Promise Pool/2636.ts new file mode 100644 index 00000000000..a915df918bb --- /dev/null +++ b/solutions/2636. Promise Pool/2636.ts @@ -0,0 +1,6 @@ +type F = () => Promise; + +function promisePool(functions: F[], n: number): Promise { + const next = () => functions[n++]?.().then(next); + return Promise.all(functions.slice(0, n).map((f) => f().then(next))); +} diff --git a/solutions/2637. Promise Time Limit/2637.ts b/solutions/2637. Promise Time Limit/2637.ts new file mode 100644 index 00000000000..55b5c3b9ad4 --- /dev/null +++ b/solutions/2637. Promise Time Limit/2637.ts @@ -0,0 +1,11 @@ +type Fn = (...params: any[]) => Promise; + +function timeLimit(fn: Fn, t: number): Fn { + return async function (...args) { + const p1 = new Promise((_, reject) => { + setTimeout(() => reject('Time Limit Exceeded'), t); + }); + const p2 = fn(...args); + return Promise.race([p1, p2]); + }; +} diff --git a/solutions/2638. Count the Number of K-Free Subsets/2638.cpp b/solutions/2638. Count the Number of K-Free Subsets/2638.cpp new file mode 100644 index 00000000000..5aa9fbc471f --- /dev/null +++ b/solutions/2638. Count the Number of K-Free Subsets/2638.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + // Similar to 2597. The Number of Beautiful Subsets + long long countTheNumOfKFreeSubsets(vector& nums, int k) { + unordered_map> modToSubset; + + for (const int num : nums) + modToSubset[num % k].insert(num); + + int prevNum = -k; + long skip = 0; + long pick = 0; + + for (const auto& [_, subset] : modToSubset) + for (const int num : subset) { + const long cacheSkip = skip; + skip += pick; + pick = 1 + cacheSkip + (num - prevNum == k ? 0 : pick); + prevNum = num; + } + + return 1 + skip + pick; + } +}; diff --git a/solutions/2638. Count the Number of K-Free Subsets/2638.java b/solutions/2638. Count the Number of K-Free Subsets/2638.java new file mode 100644 index 00000000000..5feb5cd240a --- /dev/null +++ b/solutions/2638. Count the Number of K-Free Subsets/2638.java @@ -0,0 +1,24 @@ +class Solution { + public long countTheNumOfKFreeSubsets(int[] nums, int k) { + Map> modToSubset = new HashMap<>(); + + for (final int num : nums) { + modToSubset.putIfAbsent(num % k, new TreeSet<>()); + modToSubset.get(num % k).add(num); + } + + int prevNum = -k; + long skip = 0; + long pick = 0; + + for (Set subset : modToSubset.values()) + for (final int num : subset) { + final long cacheSkip = skip; + skip += pick; + pick = 1 + cacheSkip + (num - prevNum == k ? 0 : pick); + prevNum = num; + } + + return 1 + skip + pick; + } +} diff --git a/solutions/2638. Count the Number of K-Free Subsets/2638.py b/solutions/2638. Count the Number of K-Free Subsets/2638.py new file mode 100644 index 00000000000..48e8f652aff --- /dev/null +++ b/solutions/2638. Count the Number of K-Free Subsets/2638.py @@ -0,0 +1,18 @@ +class Solution: + def countTheNumOfKFreeSubsets(self, nums: List[int], k: int) -> int: + modToSubset = collections.defaultdict(set) + + for num in nums: + modToSubset[num % k].add(num) + + prevNum = -k + skip = 0 + pick = 0 + + for subset in modToSubset.values(): + for num in sorted(subset): + skip, pick = skip + pick, \ + 1 + skip + (0 if num - prevNum == k else pick) + prevNum = num + + return 1 + skip + pick diff --git a/solutions/2639. Find the Width of Columns of a Grid/2639.cpp b/solutions/2639. Find the Width of Columns of a Grid/2639.cpp new file mode 100644 index 00000000000..d43f83b1c65 --- /dev/null +++ b/solutions/2639. Find the Width of Columns of a Grid/2639.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector findColumnWidth(vector>& grid) { + vector ans; + + for (int j = 0; j < grid[0].size(); ++j) { + ans.push_back(0); + for (int i = 0; i < grid.size(); ++i) + ans[j] = max(ans[j], static_cast(to_string(grid[i][j]).length())); + } + + return ans; + } +}; diff --git a/solutions/2639. Find the Width of Columns of a Grid/2639.java b/solutions/2639. Find the Width of Columns of a Grid/2639.java new file mode 100644 index 00000000000..c17bc9164b5 --- /dev/null +++ b/solutions/2639. Find the Width of Columns of a Grid/2639.java @@ -0,0 +1,13 @@ +class Solution { + public int[] findColumnWidth(int[][] grid) { + int[] ans = new int[grid[0].length]; + + for (int j = 0; j < grid[0].length; ++j) { + ans[j] = 0; + for (int i = 0; i < grid.length; ++i) + ans[j] = Math.max(ans[j], String.valueOf(grid[i][j]).length()); + } + + return ans; + } +} diff --git a/solutions/2639. Find the Width of Columns of a Grid/2639.py b/solutions/2639. Find the Width of Columns of a Grid/2639.py new file mode 100644 index 00000000000..fcd259b2ee9 --- /dev/null +++ b/solutions/2639. Find the Width of Columns of a Grid/2639.py @@ -0,0 +1,3 @@ +class Solution: + def findColumnWidth(self, grid: List[List[int]]) -> List[int]: + return [max(map(len, map(str, col))) for col in zip(*grid)] diff --git a/solutions/264. Ugly Number II/264.cpp b/solutions/264. Ugly Number II/264.cpp new file mode 100644 index 00000000000..cb72651a91c --- /dev/null +++ b/solutions/264. Ugly Number II/264.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int nthUglyNumber(int n) { + vector uglyNums{1}; + int i2 = 0; + int i3 = 0; + int i5 = 0; + + while (uglyNums.size() < n) { + const int next2 = uglyNums[i2] * 2; + const int next3 = uglyNums[i3] * 3; + const int next5 = uglyNums[i5] * 5; + const int next = min({next2, next3, next5}); + if (next == next2) + ++i2; + if (next == next3) + ++i3; + if (next == next5) + ++i5; + uglyNums.push_back(next); + } + + return uglyNums.back(); + } +}; diff --git a/solutions/264. Ugly Number II/264.java b/solutions/264. Ugly Number II/264.java new file mode 100644 index 00000000000..bae10f00e4c --- /dev/null +++ b/solutions/264. Ugly Number II/264.java @@ -0,0 +1,25 @@ +class Solution { + public int nthUglyNumber(int n) { + List uglyNums = new ArrayList<>(); + uglyNums.add(1); + int i2 = 0; + int i3 = 0; + int i5 = 0; + + while (uglyNums.size() < n) { + final int next2 = uglyNums.get(i2) * 2; + final int next3 = uglyNums.get(i3) * 3; + final int next5 = uglyNums.get(i5) * 5; + final int next = Math.min(next2, Math.min(next3, next5)); + if (next == next2) + ++i2; + if (next == next3) + ++i3; + if (next == next5) + ++i5; + uglyNums.add(next); + } + + return uglyNums.get(uglyNums.size() - 1); + } +} diff --git a/solutions/264. Ugly Number II/264.py b/solutions/264. Ugly Number II/264.py new file mode 100644 index 00000000000..858a8ad5211 --- /dev/null +++ b/solutions/264. Ugly Number II/264.py @@ -0,0 +1,21 @@ +class Solution: + def nthUglyNumber(self, n: int) -> int: + nums = [1] + i2 = 0 + i3 = 0 + i5 = 0 + + while len(nums) < n: + next2 = nums[i2] * 2 + next3 = nums[i3] * 3 + next5 = nums[i5] * 5 + next = min(next2, next3, next5) + if next == next2: + i2 += 1 + if next == next3: + i3 += 1 + if next == next5: + i5 += 1 + nums.append(next) + + return nums[-1] diff --git a/solutions/2640. Find the Score of All Prefixes of an Array/2640.cpp b/solutions/2640. Find the Score of All Prefixes of an Array/2640.cpp new file mode 100644 index 00000000000..87446a8228e --- /dev/null +++ b/solutions/2640. Find the Score of All Prefixes of an Array/2640.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector findPrefixScore(vector& nums) { + vector ans; + long prefix = 0; + int mx = 0; + + for (const int num : nums) { + mx = max(mx, num); + prefix += num + mx; + ans.push_back(prefix); + } + + return ans; + } +}; diff --git a/solutions/2640. Find the Score of All Prefixes of an Array/2640.java b/solutions/2640. Find the Score of All Prefixes of an Array/2640.java new file mode 100644 index 00000000000..9743b949a1f --- /dev/null +++ b/solutions/2640. Find the Score of All Prefixes of an Array/2640.java @@ -0,0 +1,15 @@ +class Solution { + public long[] findPrefixScore(int[] nums) { + long[] ans = new long[nums.length]; + long prefix = 0; + int mx = 0; + + for (int i = 0; i < nums.length; i++) { + mx = Math.max(mx, nums[i]); + prefix += nums[i] + mx; + ans[i] = prefix; + } + + return ans; + } +} diff --git a/solutions/2640. Find the Score of All Prefixes of an Array/2640.py b/solutions/2640. Find the Score of All Prefixes of an Array/2640.py new file mode 100644 index 00000000000..c9d48d34120 --- /dev/null +++ b/solutions/2640. Find the Score of All Prefixes of an Array/2640.py @@ -0,0 +1,10 @@ +class Solution: + def findPrefixScore(self, nums: List[int]) -> List[int]: + conver = [] + mx = 0 + + for num in nums: + mx = max(mx, num) + conver.append(num + mx) + + return itertools.accumulate(conver) diff --git a/solutions/2641. Cousins in Binary Tree II/2641.cpp b/solutions/2641. Cousins in Binary Tree II/2641.cpp new file mode 100644 index 00000000000..cb9ad4545e8 --- /dev/null +++ b/solutions/2641. Cousins in Binary Tree II/2641.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + TreeNode* replaceValueInTree(TreeNode* root) { + vector levelSums; + dfs(root, 0, levelSums); + return replace(root, 0, new TreeNode(0), levelSums); + } + + private: + void dfs(TreeNode* root, int level, vector& levelSums) { + if (root == nullptr) + return; + if (levelSums.size() == level) + levelSums.push_back(0); + levelSums[level] += root->val; + dfs(root->left, level + 1, levelSums); + dfs(root->right, level + 1, levelSums); + } + + TreeNode* replace(TreeNode* root, int level, TreeNode* curr, + const vector& levelSums) { + const int nextLevel = level + 1; + const int nextLevelCousinsSum = + nextLevel >= levelSums.size() + ? 0 + : levelSums[nextLevel] - + (root->left == nullptr ? 0 : root->left->val) - + (root->right == nullptr ? 0 : root->right->val); + if (root->left != nullptr) { + curr->left = new TreeNode(nextLevelCousinsSum); + replace(root->left, level + 1, curr->left, levelSums); + } + if (root->right != nullptr) { + curr->right = new TreeNode(nextLevelCousinsSum); + replace(root->right, level + 1, curr->right, levelSums); + } + return curr; + } +}; diff --git a/solutions/2641. Cousins in Binary Tree II/2641.java b/solutions/2641. Cousins in Binary Tree II/2641.java new file mode 100644 index 00000000000..0f8061fa737 --- /dev/null +++ b/solutions/2641. Cousins in Binary Tree II/2641.java @@ -0,0 +1,35 @@ +class Solution { + public TreeNode replaceValueInTree(TreeNode root) { + List levelSums = new ArrayList<>(); + dfs(root, 0, levelSums); + return replace(root, 0, new TreeNode(0), levelSums); + } + + private void dfs(TreeNode root, int level, List levelSums) { + if (root == null) + return; + if (levelSums.size() == level) + levelSums.add(0); + levelSums.set(level, levelSums.get(level) + root.val); + dfs(root.left, level + 1, levelSums); + dfs(root.right, level + 1, levelSums); + } + + private TreeNode replace(TreeNode root, int level, TreeNode curr, List levelSums) { + final int nextLevel = level + 1; + final int nextLevelCousinsSum = nextLevel >= levelSums.size() + ? 0 + : levelSums.get(nextLevel) - + (root.left == null ? 0 : root.left.val) - + (root.right == null ? 0 : root.right.val); + if (root.left != null) { + curr.left = new TreeNode(nextLevelCousinsSum); + replace(root.left, level + 1, curr.left, levelSums); + } + if (root.right != null) { + curr.right = new TreeNode(nextLevelCousinsSum); + replace(root.right, level + 1, curr.right, levelSums); + } + return curr; + } +} diff --git a/solutions/2641. Cousins in Binary Tree II/2641.py b/solutions/2641. Cousins in Binary Tree II/2641.py new file mode 100644 index 00000000000..d310a507b73 --- /dev/null +++ b/solutions/2641. Cousins in Binary Tree II/2641.py @@ -0,0 +1,28 @@ +class Solution: + def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + levelSums = [] + + def dfs(root: Optional[TreeNode], level: int) -> None: + if not root: + return + if len(levelSums) == level: + levelSums.append(0) + levelSums[level] += root.val + dfs(root.left, level + 1) + dfs(root.right, level + 1) + + def replace(root: Optional[TreeNode], level: int, curr: Optional[TreeNode]) -> Optional[TreeNode]: + nextLevel = level + 1 + nextLevelCousinsSum = (levelSums[nextLevel] if nextLevel < len(levelSums) else 0) - \ + (root.left.val if root.left else 0) - \ + (root.right.val if root.right else 0) + if root.left: + curr.left = TreeNode(nextLevelCousinsSum) + replace(root.left, level + 1, curr.left) + if root.right: + curr.right = TreeNode(nextLevelCousinsSum) + replace(root.right, level + 1, curr.right) + return curr + + dfs(root, 0) + return replace(root, 0, TreeNode(0)) diff --git a/solutions/2642. Design Graph With Shortest Path Calculator/2642.cpp b/solutions/2642. Design Graph With Shortest Path Calculator/2642.cpp new file mode 100644 index 00000000000..5f4e54996a2 --- /dev/null +++ b/solutions/2642. Design Graph With Shortest Path Calculator/2642.cpp @@ -0,0 +1,41 @@ +class Graph { + public: + Graph(int n, vector>& edges) { + graph.resize(n); + for (const vector& edge : edges) + addEdge(edge); + } + + void addEdge(vector edge) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + } + + int shortestPath(int node1, int node2) { + vector dist(graph.size(), INT_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[node1] = 0; + minHeap.emplace(dist[node1], node1); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (u == node2) + return d; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + } + + return -1; + } + + private: + vector>> graph; +}; diff --git a/solutions/2642. Design Graph With Shortest Path Calculator/2642.java b/solutions/2642. Design Graph With Shortest Path Calculator/2642.java new file mode 100644 index 00000000000..4460478a31b --- /dev/null +++ b/solutions/2642. Design Graph With Shortest Path Calculator/2642.java @@ -0,0 +1,45 @@ +class Graph { + public Graph(int n, int[][] edges) { + graph = new List[n]; + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + for (int[] edge : edges) + addEdge(edge); + } + + public void addEdge(int[] edge) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + } + + public int shortestPath(int node1, int node2) { + int[] dist = new int[graph.length]; + Arrays.fill(dist, Integer.MAX_VALUE); + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + dist[node1] = 0; + minHeap.offer(new Pair<>(dist[node1], node1)); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (u == node2) + return d; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + return -1; + } + + private List>[] graph; +} diff --git a/solutions/2642. Design Graph With Shortest Path Calculator/2642.py b/solutions/2642. Design Graph With Shortest Path Calculator/2642.py new file mode 100644 index 00000000000..42a12762e75 --- /dev/null +++ b/solutions/2642. Design Graph With Shortest Path Calculator/2642.py @@ -0,0 +1,26 @@ +class Graph: + def __init__(self, n: int, edges: List[List[int]]): + self.graph = [[] for _ in range(n)] + for edge in edges: + self.addEdge(edge) + + def addEdge(self, edge: List[int]): + u, v, w = edge + self.graph[u].append((v, w)) + + def shortestPath(self, node1: int, node2: int) -> int: + dist = [math.inf] * len(self.graph) + + dist[node1] = 0 + minHeap = [(dist[node1], node1)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + if u == node2: + return d + for v, w in self.graph[u]: + if d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + + return -1 diff --git a/solutions/2643. Row With Maximum Ones/2643.cpp b/solutions/2643. Row With Maximum Ones/2643.cpp new file mode 100644 index 00000000000..6de0736f3e6 --- /dev/null +++ b/solutions/2643. Row With Maximum Ones/2643.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector rowAndMaximumOnes(vector>& mat) { + vector ans{0, 0}; + + for (int i = 0; i < mat.size(); ++i) { + const int ones = ranges::count(mat[i], 1); + if (ones > ans[1]) { + ans[0] = i; + ans[1] = ones; + } + } + + return ans; + } +}; diff --git a/solutions/2643. Row With Maximum Ones/2643.java b/solutions/2643. Row With Maximum Ones/2643.java new file mode 100644 index 00000000000..a03601f49a8 --- /dev/null +++ b/solutions/2643. Row With Maximum Ones/2643.java @@ -0,0 +1,15 @@ +class Solution { + public int[] rowAndMaximumOnes(int[][] mat) { + int[] ans = new int[2]; + + for (int i = 0; i < mat.length; ++i) { + final int ones = (int) Arrays.stream(mat[i]).filter(a -> a == 1).count(); + if (ones > ans[1]) { + ans[0] = i; + ans[1] = ones; + } + } + + return ans; + } +} diff --git a/solutions/2643. Row With Maximum Ones/2643.py b/solutions/2643. Row With Maximum Ones/2643.py new file mode 100644 index 00000000000..0b43d9a2ed9 --- /dev/null +++ b/solutions/2643. Row With Maximum Ones/2643.py @@ -0,0 +1,11 @@ +class Solution: + def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]: + ans = [0, 0] + + for i, row in enumerate(mat): + ones = row.count(1) + if ones > ans[1]: + ans[0] = i + ans[1] = ones + + return ans diff --git a/solutions/2644. Find the Maximum Divisibility Score/2644.cpp b/solutions/2644. Find the Maximum Divisibility Score/2644.cpp new file mode 100644 index 00000000000..34ab69f40cc --- /dev/null +++ b/solutions/2644. Find the Maximum Divisibility Score/2644.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxDivScore(vector& nums, vector& divisors) { + int ans = -1; + int maxScore = -1; + + for (const int divisor : divisors) { + const int score = ranges::count_if( + nums, [divisor](const int num) { return num % divisor == 0; }); + if (score > maxScore) { + ans = divisor; + maxScore = score; + } else if (score == maxScore) { + ans = min(ans, divisor); + } + } + + return ans; + } +}; diff --git a/solutions/2644. Find the Maximum Divisibility Score/2644.java b/solutions/2644. Find the Maximum Divisibility Score/2644.java new file mode 100644 index 00000000000..8867af1c5e9 --- /dev/null +++ b/solutions/2644. Find the Maximum Divisibility Score/2644.java @@ -0,0 +1,18 @@ +class Solution { + public int maxDivScore(int[] nums, int[] divisors) { + int ans = -1; + int maxScore = -1; + + for (final int divisor : divisors) { + final int score = (int) Arrays.stream(nums).filter(num -> num % divisor == 0).count(); + if (score > maxScore) { + ans = divisor; + maxScore = score; + } else if (score == maxScore) { + ans = Math.min(ans, divisor); + } + } + + return ans; + } +} diff --git a/solutions/2644. Find the Maximum Divisibility Score/2644.py b/solutions/2644. Find the Maximum Divisibility Score/2644.py new file mode 100644 index 00000000000..8fb00598e4a --- /dev/null +++ b/solutions/2644. Find the Maximum Divisibility Score/2644.py @@ -0,0 +1,14 @@ +class Solution: + def maxDivScore(self, nums: List[int], divisors: List[int]) -> int: + ans = -1 + maxScore = -1 + + for divisor in divisors: + score = sum([1 for num in nums if num % divisor == 0]) + if score > maxScore: + ans = divisor + maxScore = score + elif score == maxScore: + ans = min(ans, divisor) + + return ans diff --git a/solutions/2645. Minimum Additions to Make Valid String/2645.cpp b/solutions/2645. Minimum Additions to Make Valid String/2645.cpp new file mode 100644 index 00000000000..06d50e6e87b --- /dev/null +++ b/solutions/2645. Minimum Additions to Make Valid String/2645.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int addMinimum(string word) { + const string letters = "abc"; + int ans = 0; + int i = 0; + + while (i < word.length()) + for (const char c : letters) { + if (i < word.length() && word[i] == c) + ++i; + else + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2645. Minimum Additions to Make Valid String/2645.java b/solutions/2645. Minimum Additions to Make Valid String/2645.java new file mode 100644 index 00000000000..79e12a154cc --- /dev/null +++ b/solutions/2645. Minimum Additions to Make Valid String/2645.java @@ -0,0 +1,17 @@ +class Solution { + public int addMinimum(String word) { + final char[] letters = new char[] {'a', 'b', 'c'}; + int ans = 0; + int i = 0; + + while (i < word.length()) + for (final char c : letters) { + if (i < word.length() && word.charAt(i) == c) + ++i; + else + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2645. Minimum Additions to Make Valid String/2645.py b/solutions/2645. Minimum Additions to Make Valid String/2645.py new file mode 100644 index 00000000000..20e5fd1f93d --- /dev/null +++ b/solutions/2645. Minimum Additions to Make Valid String/2645.py @@ -0,0 +1,14 @@ +class Solution: + def addMinimum(self, word: str) -> int: + letters = ['a', 'b', 'c'] + ans = 0 + i = 0 + + while i < len(word): + for c in letters: + if i < len(word) and word[i] == c: + i += 1 + else: + ans += 1 + + return ans diff --git a/solutions/2646. Minimize the Total Price of the Trips/2646.cpp b/solutions/2646. Minimize the Total Price of the Trips/2646.cpp new file mode 100644 index 00000000000..26cc64b0f73 --- /dev/null +++ b/solutions/2646. Minimize the Total Price of the Trips/2646.cpp @@ -0,0 +1,66 @@ +class Solution { + public: + int minimumTotalPrice(int n, vector>& edges, vector& price, + vector>& trips) { + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + // count[i] := the number of times node i is traversed + vector count(n); + + for (const vector& trip : trips) { + const int start = trip[0]; + const int end = trip[1]; + vector path; + dfsCount(graph, start, /*prev=*/-1, end, count, path); + } + + vector> mem(n, vector(2, -1)); + return dfs(graph, 0, -1, price, count, false, mem); + } + + private: + void dfsCount(const vector>& graph, int u, int prev, int end, + vector& count, vector& path) { + path.push_back(u); + if (u == end) { + for (const int i : path) + ++count[i]; + return; + } + for (const int v : graph[u]) + if (v != prev) + dfsCount(graph, v, u, end, count, path); + path.pop_back(); + } + + // Returns the minimum price sum for the i-th node, where its parent is + // halved parent or not halved not. + int dfs(const vector>& graph, int u, int prev, + const vector& price, const vector& count, int parentHalved, + vector>& mem) { + if (mem[u][parentHalved] != -1) + return mem[u][parentHalved]; + + int sumWithFullNode = price[u] * count[u]; + for (const int v : graph[u]) + if (v != prev) + sumWithFullNode += dfs(graph, v, u, price, count, false, mem); + + if (parentHalved) // Can't halve this node if its parent was halved. + return mem[u][parentHalved] = sumWithFullNode; + + int sumWithHalvedNode = (price[u] / 2) * count[u]; + for (const int v : graph[u]) + if (v != prev) + sumWithHalvedNode += dfs(graph, v, u, price, count, true, mem); + + return mem[u][parentHalved] = min(sumWithFullNode, sumWithHalvedNode); + } +}; diff --git a/solutions/2646. Minimize the Total Price of the Trips/2646.java b/solutions/2646. Minimize the Total Price of the Trips/2646.java new file mode 100644 index 00000000000..c734abd02f1 --- /dev/null +++ b/solutions/2646. Minimize the Total Price of the Trips/2646.java @@ -0,0 +1,63 @@ +class Solution { + public int minimumTotalPrice(int n, int[][] edges, int[] price, int[][] trips) { + List[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + // count[i] := the number of times node i is traversed + int[] count = new int[n]; + for (int[] trip : trips) { + final int start = trip[0]; + final int end = trip[1]; + dfsCount(graph, start, -1, end, count, /*path=*/new ArrayList<>()); + } + + Integer[][] mem = new Integer[n][2]; + return dfs(graph, 0, -1, price, count, false, mem); + } + + private void dfsCount(List[] graph, int u, int prev, int end, int[] count, + List path) { + path.add(u); + if (u == end) { + for (final int i : path) + ++count[i]; + return; + } + for (final int v : graph[u]) + if (v != prev) + dfsCount(graph, v, u, end, count, path); + path.remove(path.size() - 1); + } + + // Returns the minimum price sum for the i-th node, where its parent is + // halved parent or not halved not. + private int dfs(List[] graph, int u, int prev, int[] price, int[] count, + boolean parentHalved, Integer[][] mem) { + if (mem[u][parentHalved ? 1 : 0] != null) + return mem[u][parentHalved ? 1 : 0]; + + int sumWithFullNode = price[u] * count[u]; + for (final int v : graph[u]) + if (v != prev) + sumWithFullNode += dfs(graph, v, u, price, count, false, mem); + + if (parentHalved) // Can't halve this node if its parent was halved. + return mem[u][1] = sumWithFullNode; + + int sumWithHalvedNode = (price[u] / 2) * count[u]; + for (int v : graph[u]) + if (v != prev) + sumWithHalvedNode += dfs(graph, v, u, price, count, true, mem); + + return mem[u][parentHalved ? 1 : 0] = Math.min(sumWithFullNode, sumWithHalvedNode); + } +} diff --git a/solutions/2646. Minimize the Total Price of the Trips/2646.py b/solutions/2646. Minimize the Total Price of the Trips/2646.py new file mode 100644 index 00000000000..8a885f0b90b --- /dev/null +++ b/solutions/2646. Minimize the Total Price of the Trips/2646.py @@ -0,0 +1,43 @@ +class Solution: + def minimumTotalPrice(self, n: int, edges: List[List[int]], price: List[int], + trips: List[List[int]]) -> int: + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + # count[i] := the number of times i is traversed + count = [0] * n + + def dfsCount(u: int, prev: int, end: int, path: List[int]) -> None: + path.append(u) + if u == end: + for i in path: + count[i] += 1 + return + for v in graph[u]: + if v != prev: + dfsCount(v, u, end, path) + path.pop() + + for start, end in trips: + dfsCount(start, -1, end, []) + + @functools.lru_cache(None) + def dfs(u: int, prev: int, parentHalved: bool) -> int: + """ + Returns the minimum price sum for the i-th node, where its parent is + halved parent or not halved not. + """ + sumWithFullNode = price[u] * count[u] + sum(dfs(v, u, False) + for v in graph[u] + if v != prev) + if parentHalved: # Can't halve this node if its parent was halved. + return sumWithFullNode + sumWithHalvedNode = (price[u] // 2) * count[u] + sum(dfs(v, u, True) + for v in graph[u] + if v != prev) + return min(sumWithFullNode, sumWithHalvedNode) + + return dfs(0, -1, False) diff --git a/solutions/2647. Color the Triangle Red/2647.cpp b/solutions/2647. Color the Triangle Red/2647.cpp new file mode 100644 index 00000000000..d25ed9a1e4c --- /dev/null +++ b/solutions/2647. Color the Triangle Red/2647.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector> colorRed(int n) { + vector> ans; + const int tipSize = n % 4; + + // The tip of the triangle is always painted red. + if (tipSize >= 1) + ans.push_back({1, 1}); + + // Paint the rightmost and the leftmost elements at the following rows. + for (int i = 2; i <= tipSize; ++i) { + ans.push_back({i, 1}); + ans.push_back({i, 2 * i - 1}); + } + + // Paint the 4-row chunks. + for (int i = tipSize + 1; i < n; i += 4) { + // Fill the first row of the chunk. + ans.push_back({i, 1}); + // Fill the second row. + for (int j = 1; j <= i; ++j) + ans.push_back({i + 1, 2 * j + 1}); + // Fill the third row. + ans.push_back({i + 2, 2}); + // Fill the fourth row. + for (int j = 0; j <= i + 2; ++j) + ans.push_back({i + 3, 2 * j + 1}); + } + + return ans; + } +}; diff --git a/solutions/2647. Color the Triangle Red/2647.java b/solutions/2647. Color the Triangle Red/2647.java new file mode 100644 index 00000000000..8aedf835d9a --- /dev/null +++ b/solutions/2647. Color the Triangle Red/2647.java @@ -0,0 +1,31 @@ +class Solution { + public int[][] colorRed(int n) { + List ans = new ArrayList<>(); + final int tipSize = n % 4; + // The tip of the triangle is always painted red. + if (tipSize >= 1) + ans.add(new int[] {1, 1}); + + // Paint the rightmost and the leftmost elements at the following rows. + for (int i = 2; i <= tipSize; ++i) { + ans.add(new int[] {i, 1}); + ans.add(new int[] {i, 2 * i - 1}); + } + + // Paint the 4-row chunks. + for (int i = tipSize + 1; i < n; i += 4) { + // Fill the first row of the chunk. + ans.add(new int[] {i, 1}); + // Fill the second row. + for (int j = 1; j <= i; ++j) + ans.add(new int[] {i + 1, 2 * j + 1}); + // Fill the third row. + ans.add(new int[] {i + 2, 2}); + // Fill the fourth row. + for (int j = 0; j <= i + 2; ++j) + ans.add(new int[] {i + 3, 2 * j + 1}); + } + + return ans.stream().toArray(int[][] ::new); + } +} diff --git a/solutions/2647. Color the Triangle Red/2647.py b/solutions/2647. Color the Triangle Red/2647.py new file mode 100644 index 00000000000..014b88bc4b6 --- /dev/null +++ b/solutions/2647. Color the Triangle Red/2647.py @@ -0,0 +1,28 @@ +class Solution: + def colorRed(self, n: int) -> List[List[int]]: + ans = [] + tipSize = n % 4 + + # The tip of the triangle is always painted red. + if tipSize >= 1: + ans.append([1, 1]) + + # Pamost right and most left elements at the following rows. + for i in range(2, tipSize + 1): + ans.append([i, 1]) + ans.append([i, 2 * i - 1]) + + # Pa4-row chunks. + for i in range(tipSize + 1, n, 4): + # Fill the first row of the chunk. + ans.append([i, 1]) + # Fill the second row. + for j in range(1, i + 1): + ans.append([i + 1, 2 * j + 1]) + # Fill the third row. + ans.append([i + 2, 2]) + # Fill the fourth row. + for j in range(i + 2 + 1): + ans.append([i + 3, 2 * j + 1]) + + return ans diff --git a/solutions/2648. Generate Fibonacci Sequence/2648.ts b/solutions/2648. Generate Fibonacci Sequence/2648.ts new file mode 100644 index 00000000000..bda69c76d70 --- /dev/null +++ b/solutions/2648. Generate Fibonacci Sequence/2648.ts @@ -0,0 +1,9 @@ +function* fibGenerator(): Generator { + const arr = [0, 0, 1]; + while (true) { + yield arr[1]; + arr[0] = arr[1]; + arr[1] = arr[2]; + arr[2] = arr[0] + arr[1]; + } +} diff --git a/solutions/2649. Nested Array Generator/2649.ts b/solutions/2649. Nested Array Generator/2649.ts new file mode 100644 index 00000000000..d56c60aaab7 --- /dev/null +++ b/solutions/2649. Nested Array Generator/2649.ts @@ -0,0 +1,13 @@ +type MultidimensionalArray = (MultidimensionalArray | number)[]; + +function* inorderTraversal( + arr: MultidimensionalArray +): Generator { + for (const item of arr) { + if (typeof item === 'number') { + yield item; + } else { + yield* inorderTraversal(item); + } + } +} diff --git a/solutions/265. Paint House II/265.cpp b/solutions/265. Paint House II/265.cpp new file mode 100644 index 00000000000..1ff5fffd922 --- /dev/null +++ b/solutions/265. Paint House II/265.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int minCostII(vector>& costs) { + int prevIndex = -1; // the previous minimum index + int prevMin1 = 0; // the minimum cost so far + int prevMin2 = 0; // the second minimum cost so far + + for (const vector& cost : costs) { // O(n) + // the painted index that will achieve the minimum cost after painting the + // current house + int index = -1; + // the minimum cost after painting the current house + int min1 = INT_MAX; + // the second minimum cost after painting the current house + int min2 = INT_MAX; + for (int i = 0; i < cost.size(); ++i) { // O(k) + const int theCost = cost[i] + (i == prevIndex ? prevMin2 : prevMin1); + if (theCost < min1) { + index = i; + min2 = min1; + min1 = theCost; + } else if (theCost < min2) { // min1 <= theCost < min2 + min2 = theCost; + } + } + prevIndex = index; + prevMin1 = min1; + prevMin2 = min2; + } + + return prevMin1; + } +}; diff --git a/solutions/265. Paint House II/265.java b/solutions/265. Paint House II/265.java new file mode 100644 index 00000000000..4b16f2367c3 --- /dev/null +++ b/solutions/265. Paint House II/265.java @@ -0,0 +1,32 @@ +class Solution { + public int minCostII(int[][] costs) { + int prevIndex = -1; // the previous minimum index + int prevMin1 = 0; // the minimum cost so far + int prevMin2 = 0; // the second minimum cost so far + + for (int[] cost : costs) { // O(n) + // the painted index that will achieve the minimum cost after painting the + // current house + int index = -1; + // the minimum cost after painting the current house + int min1 = Integer.MAX_VALUE; + // the second minimum cost after painting the current house + int min2 = Integer.MAX_VALUE; + for (int i = 0; i < cost.length; ++i) { // O(k) + final int theCost = cost[i] + (i == prevIndex ? prevMin2 : prevMin1); + if (theCost < min1) { + index = i; + min2 = min1; + min1 = theCost; + } else if (theCost < min2) { // min1 <= theCost < min2 + min2 = theCost; + } + } + prevIndex = index; + prevMin1 = min1; + prevMin2 = min2; + } + + return prevMin1; + } +} diff --git a/solutions/265. Paint House II/265.py b/solutions/265. Paint House II/265.py new file mode 100644 index 00000000000..ecf1d1fede1 --- /dev/null +++ b/solutions/265. Paint House II/265.py @@ -0,0 +1,28 @@ +class Solution: + def minCostII(self, costs: List[List[int]]) -> int: + prevIndex = -1 # the previous minimum index + prevMin1 = 0 # the minimum cost so far + prevMin2 = 0 # the second minimum cost so far + + for cost in costs: # O(n) + # the painted index that will achieve the minimum cost after painting the + # current house + index = -1 + # the minimum cost after painting the current house + min1 = math.inf + # the second minimum cost after painting the current house + min2 = math.inf + for i, cst in enumerate(cost): # O(k) + theCost = cst + (prevMin2 if i == prevIndex else prevMin1) + if theCost < min1: + index = i + min2 = min1 + min1 = theCost + elif theCost < min2: # min1 <= theCost < min2 + min2 = theCost + + prevIndex = index + prevMin1 = min1 + prevMin2 = min2 + + return prevMin1 diff --git a/solutions/2650. Design Cancellable Function/2650.ts b/solutions/2650. Design Cancellable Function/2650.ts new file mode 100644 index 00000000000..b3ea574b216 --- /dev/null +++ b/solutions/2650. Design Cancellable Function/2650.ts @@ -0,0 +1,22 @@ +function cancellable( + generator: Generator, T, unknown> +): [() => void, Promise] { + let cancel = () => {}; + const cancelPromise = new Promise((_, reject) => { + cancel = () => reject('Cancelled'); + }); + + const promise = (async (): Promise => { + let next = generator.next(); + while (!next.done) { + try { + next = generator.next(await Promise.race([next.value, cancelPromise])); + } catch (e) { + next = generator.throw(e); + } + } + return next.value; + })(); + + return [cancel, promise]; +} diff --git a/solutions/2651. Calculate Delayed Arrival Time/2651.cpp b/solutions/2651. Calculate Delayed Arrival Time/2651.cpp new file mode 100644 index 00000000000..c4c46abe751 --- /dev/null +++ b/solutions/2651. Calculate Delayed Arrival Time/2651.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int findDelayedArrivalTime(int arrivalTime, int delayedTime) { + return (arrivalTime + delayedTime) % 24; + } +}; diff --git a/solutions/2651. Calculate Delayed Arrival Time/2651.java b/solutions/2651. Calculate Delayed Arrival Time/2651.java new file mode 100644 index 00000000000..7a9e6a39529 --- /dev/null +++ b/solutions/2651. Calculate Delayed Arrival Time/2651.java @@ -0,0 +1,5 @@ +class Solution { + public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { + return (arrivalTime + delayedTime) % 24; + } +} diff --git a/solutions/2651. Calculate Delayed Arrival Time/2651.py b/solutions/2651. Calculate Delayed Arrival Time/2651.py new file mode 100644 index 00000000000..68ac252dda2 --- /dev/null +++ b/solutions/2651. Calculate Delayed Arrival Time/2651.py @@ -0,0 +1,3 @@ +class Solution: + def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int: + return (arrivalTime + delayedTime) % 24 diff --git a/solutions/2652. Sum Multiples/2652-2.cpp b/solutions/2652. Sum Multiples/2652-2.cpp new file mode 100644 index 00000000000..9a94f676ce6 --- /dev/null +++ b/solutions/2652. Sum Multiples/2652-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int sumOfMultiples(int n) { + // Returns the sum of multiples of value in [1, n]. + auto sumOfMultiples = [n](int value) { + const int lo = value; + const int hi = n / value * value; + const int count = (hi - lo) / value + 1; + return (lo + hi) * count / 2; + }; + return sumOfMultiples(3) + sumOfMultiples(5) + sumOfMultiples(7) - + (sumOfMultiples(15) + sumOfMultiples(21) + sumOfMultiples(35)) + + sumOfMultiples(105); + } +}; diff --git a/solutions/2652. Sum Multiples/2652-2.java b/solutions/2652. Sum Multiples/2652-2.java new file mode 100644 index 00000000000..605e22a2f45 --- /dev/null +++ b/solutions/2652. Sum Multiples/2652-2.java @@ -0,0 +1,15 @@ +public class Solution { + public int sumOfMultiples(int n) { + return sumOfMultiples(n, 3) + sumOfMultiples(n, 5) + sumOfMultiples(n, 7) - + (sumOfMultiples(n, 15) + sumOfMultiples(n, 21) + sumOfMultiples(n, 35)) + + sumOfMultiples(n, 105); + } + + // Returns the sum of multiples of value in [1, n]. + private int sumOfMultiples(int n, int value) { + final int lo = value; + final int hi = n / value * value; + final int count = (hi - lo) / value + 1; + return (lo + hi) * count / 2; + } +} diff --git a/solutions/2652. Sum Multiples/2652-2.py b/solutions/2652. Sum Multiples/2652-2.py new file mode 100644 index 00000000000..2fabf80a3ad --- /dev/null +++ b/solutions/2652. Sum Multiples/2652-2.py @@ -0,0 +1,12 @@ +class Solution: + def sumOfMultiples(self, n: int) -> int: + # Returns the sum of multiples of value in [1, n]. + def sumOfMultiples(value: int) -> int: + lo = value + hi = (n // value) * value + count = (hi - lo) // value + 1 + return (lo + hi) * count // 2 + + return sumOfMultiples(3) + sumOfMultiples(5) + sumOfMultiples(7) \ + - (sumOfMultiples(15) + sumOfMultiples(21) + sumOfMultiples(35)) \ + + sumOfMultiples(105) diff --git a/solutions/2652. Sum Multiples/2652.cpp b/solutions/2652. Sum Multiples/2652.cpp new file mode 100644 index 00000000000..e695024bc17 --- /dev/null +++ b/solutions/2652. Sum Multiples/2652.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int sumOfMultiples(int n) { + int ans = 0; + for (int i = 1; i <= n; ++i) + if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0) + ans += i; + return ans; + } +}; diff --git a/solutions/2652. Sum Multiples/2652.java b/solutions/2652. Sum Multiples/2652.java new file mode 100644 index 00000000000..1077aea540b --- /dev/null +++ b/solutions/2652. Sum Multiples/2652.java @@ -0,0 +1,9 @@ +class Solution { + public int sumOfMultiples(int n) { + int ans = 0; + for (int i = 1; i <= n; ++i) + if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0) + ans += i; + return ans; + } +} diff --git a/solutions/2652. Sum Multiples/2652.py b/solutions/2652. Sum Multiples/2652.py new file mode 100644 index 00000000000..f20bd948cef --- /dev/null +++ b/solutions/2652. Sum Multiples/2652.py @@ -0,0 +1,7 @@ +class Solution: + def sumOfMultiples(self, n: int) -> int: + ans = 0 + for i in range(1, n + 1): + if i % 3 == 0 or i % 5 == 0 or i % 7 == 0: + ans += i + return ans diff --git a/solutions/2653. Sliding Subarray Beauty/2653.cpp b/solutions/2653. Sliding Subarray Beauty/2653.cpp new file mode 100644 index 00000000000..88684193adf --- /dev/null +++ b/solutions/2653. Sliding Subarray Beauty/2653.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector getSubarrayBeauty(vector& nums, int k, int x) { + vector ans; + vector count(50); // count[i] := the frequency of (i + 50) + + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] < 0) + ++count[nums[i] + 50]; + if (i - k >= 0 && nums[i - k] < 0) + --count[nums[i - k] + 50]; + if (i + 1 >= k) + ans.push_back(getXthSmallestNum(count, x)); + } + + return ans; + } + + private: + int getXthSmallestNum(const vector& count, int x) { + int prefix = 0; + for (int i = 0; i < 50; ++i) { + prefix += count[i]; + if (prefix >= x) + return i - 50; + } + return 0; + } +}; diff --git a/solutions/2653. Sliding Subarray Beauty/2653.java b/solutions/2653. Sliding Subarray Beauty/2653.java new file mode 100644 index 00000000000..0196ad81cf9 --- /dev/null +++ b/solutions/2653. Sliding Subarray Beauty/2653.java @@ -0,0 +1,27 @@ +class Solution { + public int[] getSubarrayBeauty(int[] nums, int k, int x) { + int[] ans = new int[nums.length - k + 1]; + int[] count = new int[50]; // count[i] := the frequency of (i + 50) + + for (int i = 0; i < nums.length; ++i) { + if (nums[i] < 0) + ++count[nums[i] + 50]; + if (i - k >= 0 && nums[i - k] < 0) + --count[nums[i - k] + 50]; + if (i + 1 >= k) + ans[i - k + 1] = getXthSmallestNum(count, x); + } + + return ans; + } + + private int getXthSmallestNum(int[] count, int x) { + int prefix = 0; + for (int i = 0; i < 50; ++i) { + prefix += count[i]; + if (prefix >= x) + return i - 50; + } + return 0; + } +} diff --git a/solutions/2653. Sliding Subarray Beauty/2653.py b/solutions/2653. Sliding Subarray Beauty/2653.py new file mode 100644 index 00000000000..fda8f66c70c --- /dev/null +++ b/solutions/2653. Sliding Subarray Beauty/2653.py @@ -0,0 +1,22 @@ +class Solution: + def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: + ans = [] + count = [0] * 50 # count[i] := the frequency of (i + 50) + + for i, num in enumerate(nums): + if num < 0: + count[num + 50] += 1 + if i - k >= 0 and nums[i - k] < 0: + count[nums[i - k] + 50] -= 1 + if i + 1 >= k: + ans.append(self._getXthSmallestNum(count, x)) + + return ans + + def _getXthSmallestNum(self, count: List[int], x: int) -> int: + prefix = 0 + for i in range(50): + prefix += count[i] + if prefix >= x: + return i - 50 + return 0 diff --git a/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.cpp b/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.cpp new file mode 100644 index 00000000000..eaa09ccad79 --- /dev/null +++ b/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int minOperations(vector& nums) { + const int n = nums.size(); + const int ones = ranges::count(nums, 1); + if (ones > 0) + return n - ones; + + // the minimum operations to make the shortest subarray with a gcd == 1 + int minOps = INT_MAX; + + for (int i = 0; i < n; ++i) { + int g = nums[i]; + for (int j = i + 1; j < n; ++j) { + g = __gcd(g, nums[j]); + if (g == 1) { // gcd(nums[i..j]) == 1 + minOps = min(minOps, j - i); + break; + } + } + } + + // After making the shortest subarray with `minOps`, need additional n - 1 + // operations to make the other numbers to 1. + return minOps == INT_MAX ? -1 : minOps + n - 1; + } +}; diff --git a/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.java b/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.java new file mode 100644 index 00000000000..7c3c7b4cdd7 --- /dev/null +++ b/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.java @@ -0,0 +1,30 @@ +class Solution { + public int minOperations(int[] nums) { + final int n = nums.length; + final int ones = (int) Arrays.stream(nums).filter(num -> num == 1).count(); + if (ones > 0) + return n - ones; + + // the minimum operations to make the shortest subarray with a gcd == 1 + int minOps = Integer.MAX_VALUE; + + for (int i = 0; i < n; ++i) { + int g = nums[i]; + for (int j = i + 1; j < n; ++j) { + g = gcd(g, nums[j]); + if (g == 1) { // gcd(nums[i..j]) == 1 + minOps = Math.min(minOps, j - i); + break; + } + } + } + + // After making the shortest subarray with `minOps`, need additional n - 1 + // operations to make the other numbers to 1. + return minOps == Integer.MAX_VALUE ? -1 : minOps + n - 1; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.py b/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.py new file mode 100644 index 00000000000..33cbf7dcb4f --- /dev/null +++ b/solutions/2654. Minimum Number of Operations to Make All Array Elements Equal to 1/2654.py @@ -0,0 +1,20 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + n = len(nums) + ones = nums.count(1) + if ones > 0: + return n - ones + + # the minimum operations to make the shortest subarray with a gcd == 1 + minOps = math.inf + + for i, g in enumerate(nums): + for j in range(i + 1, n): + g = math.gcd(g, nums[j]) + if g == 1: # gcd(nums[i..j]:== 1 + minOps = min(minOps, j - i) + break + + # After making the shortest subarray with `minOps`, need additional n - 1 + # operations to make the other numbers to 1. + return -1 if minOps == math.inf else minOps + n - 1 diff --git a/solutions/2655. Find Maximal Uncovered Ranges/2655.cpp b/solutions/2655. Find Maximal Uncovered Ranges/2655.cpp new file mode 100644 index 00000000000..da4306fe34f --- /dev/null +++ b/solutions/2655. Find Maximal Uncovered Ranges/2655.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector> findMaximalUncoveredRanges(int n, + vector>& ranges) { + vector> ans; + int start = 0; + + ranges::sort(ranges); + + for (const vector& range : ranges) { + const int l = range[0]; + const int r = range[1]; + if (start < l) + ans.push_back({start, l - 1}); + if (start <= r) + start = r + 1; + } + + if (start < n) + ans.push_back({start, n - 1}); + + return ans; + } +}; diff --git a/solutions/2655. Find Maximal Uncovered Ranges/2655.java b/solutions/2655. Find Maximal Uncovered Ranges/2655.java new file mode 100644 index 00000000000..208d7380a3c --- /dev/null +++ b/solutions/2655. Find Maximal Uncovered Ranges/2655.java @@ -0,0 +1,22 @@ +class Solution { + public int[][] findMaximalUncoveredRanges(int n, int[][] ranges) { + List ans = new ArrayList<>(); + int start = 0; + + Arrays.sort(ranges, (a, b) -> a[0] - b[0]); + + for (int[] range : ranges) { + final int l = range[0]; + final int r = range[1]; + if (start < l) + ans.add(new int[] {start, l - 1}); + if (start <= r) + start = r + 1; + } + + if (start < n) + ans.add(new int[] {start, n - 1}); + + return ans.stream().toArray(int[][] ::new); + } +} diff --git a/solutions/2655. Find Maximal Uncovered Ranges/2655.py b/solutions/2655. Find Maximal Uncovered Ranges/2655.py new file mode 100644 index 00000000000..fb1c35a1b02 --- /dev/null +++ b/solutions/2655. Find Maximal Uncovered Ranges/2655.py @@ -0,0 +1,15 @@ +class Solution: + def findMaximalUncoveredRanges(self, n: int, ranges: List[List[int]]) -> List[List[int]]: + ans = [] + start = 0 + + for l, r in sorted(ranges): + if start < l: + ans.append([start, l - 1]) + if start <= r: + start = r + 1 + + if start < n: + ans.append([start, n - 1]) + + return ans diff --git a/solutions/2656. Maximum Sum With Exactly K Elements/2656.cpp b/solutions/2656. Maximum Sum With Exactly K Elements/2656.cpp new file mode 100644 index 00000000000..55f258f1e0e --- /dev/null +++ b/solutions/2656. Maximum Sum With Exactly K Elements/2656.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int maximizeSum(vector& nums, int k) { + // If x = max(nums), ans = x + (x + 1) + .. + (x + k - 1). + const int x = ranges::max(nums); + return x * k + k * (k - 1) / 2; + } +}; diff --git a/solutions/2656. Maximum Sum With Exactly K Elements/2656.java b/solutions/2656. Maximum Sum With Exactly K Elements/2656.java new file mode 100644 index 00000000000..6afc4bf5fae --- /dev/null +++ b/solutions/2656. Maximum Sum With Exactly K Elements/2656.java @@ -0,0 +1,7 @@ +class Solution { + public int maximizeSum(int[] nums, int k) { + // If x = max(nums), ans = x + (x + 1) + .. + (x + k - 1). + final int x = Arrays.stream(nums).max().getAsInt(); + return x * k + k * (k - 1) / 2; + } +} diff --git a/solutions/2656. Maximum Sum With Exactly K Elements/2656.py b/solutions/2656. Maximum Sum With Exactly K Elements/2656.py new file mode 100644 index 00000000000..3a52363e53a --- /dev/null +++ b/solutions/2656. Maximum Sum With Exactly K Elements/2656.py @@ -0,0 +1,3 @@ +class Solution: + def maximizeSum(self, nums: List[int], k: int) -> int: + return max(nums) * k + k * (k - 1) // 2 diff --git a/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.cpp b/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.cpp new file mode 100644 index 00000000000..b2dcd2844e7 --- /dev/null +++ b/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector findThePrefixCommonArray(vector& A, vector& B) { + const int n = A.size(); + int prefixCommon = 0; + vector ans; + vector count(n + 1); + + for (int i = 0; i < A.size(); ++i) { + if (++count[A[i]] == 2) + ++prefixCommon; + if (++count[B[i]] == 2) + ++prefixCommon; + ans.push_back(prefixCommon); + } + + return ans; + } +}; diff --git a/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.java b/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.java new file mode 100644 index 00000000000..387b0d693a4 --- /dev/null +++ b/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.java @@ -0,0 +1,18 @@ +class Solution { + public int[] findThePrefixCommonArray(int[] A, int[] B) { + final int n = A.length; + int prefixCommon = 0; + int[] ans = new int[n]; + int[] count = new int[n + 1]; + + for (int i = 0; i < A.length; ++i) { + if (++count[A[i]] == 2) + ++prefixCommon; + if (++count[B[i]] == 2) + ++prefixCommon; + ans[i] = prefixCommon; + } + + return ans; + } +} diff --git a/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.py b/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.py new file mode 100644 index 00000000000..9f588dd4fd4 --- /dev/null +++ b/solutions/2657. Find the Prefix Common Array of Two Arrays/2657.py @@ -0,0 +1,17 @@ +class Solution: + def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: + n = len(A) + prefixCommon = 0 + ans = [] + count = [0] * (n + 1) + + for a, b in zip(A, B): + count[a] += 1 + if count[a] == 2: + prefixCommon += 1 + count[b] += 1 + if count[b] == 2: + prefixCommon += 1 + ans.append(prefixCommon) + + return ans diff --git a/solutions/2658. Maximum Number of Fish in a Grid/2658.cpp b/solutions/2658. Maximum Number of Fish in a Grid/2658.cpp new file mode 100644 index 00000000000..2537e32a4c8 --- /dev/null +++ b/solutions/2658. Maximum Number of Fish in a Grid/2658.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int findMaxFish(vector>& grid) { + int ans = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] > 0) + ans = max(ans, dfs(grid, i, j)); + + return ans; + } + + private: + int dfs(vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return 0; + if (grid[i][j] == 0) + return 0; + int caughtFish = grid[i][j]; + grid[i][j] = 0; // Mark 0 as visited + return caughtFish + // + dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + // + dfs(grid, i, j + 1) + dfs(grid, i, j - 1); + } +}; diff --git a/solutions/2658. Maximum Number of Fish in a Grid/2658.java b/solutions/2658. Maximum Number of Fish in a Grid/2658.java new file mode 100644 index 00000000000..86dd2faf524 --- /dev/null +++ b/solutions/2658. Maximum Number of Fish in a Grid/2658.java @@ -0,0 +1,24 @@ +class Solution { + public int findMaxFish(int[][] grid) { + int ans = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] > 0) + ans = Math.max(ans, dfs(grid, i, j)); + + return ans; + } + + private int dfs(int[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid.length) + return 0; + if (grid[i][j] == 0) + return 0; + int caughtFish = grid[i][j]; + grid[i][j] = 0; // Mark 0 as visited + return caughtFish + // + dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + // + dfs(grid, i, j + 1) + dfs(grid, i, j - 1); + } +} diff --git a/solutions/2658. Maximum Number of Fish in a Grid/2658.py b/solutions/2658. Maximum Number of Fish in a Grid/2658.py new file mode 100644 index 00000000000..a3a84864dc0 --- /dev/null +++ b/solutions/2658. Maximum Number of Fish in a Grid/2658.py @@ -0,0 +1,16 @@ +class Solution: + def findMaxFish(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]): + return 0 + if grid[i][j] == 0: + return 0 + caughtFish = grid[i][j] + grid[i][j] = 0 # Mark 0 as visited + return caughtFish + \ + dfs(i + 1, j) + dfs(i - 1, j) + \ + dfs(i, j + 1) + dfs(i, j - 1) + + return max(dfs(i, j) + for i in range(len(grid)) + for j in range(len(grid[0]))) diff --git a/solutions/2659. Make Array Empty/2659.cpp b/solutions/2659. Make Array Empty/2659.cpp new file mode 100644 index 00000000000..8adb2c2a901 --- /dev/null +++ b/solutions/2659. Make Array Empty/2659.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long countOperationsToEmptyArray(vector& nums) { + const int n = nums.size(); + long ans = n; + unordered_map numToIndex; + + for (int i = 0; i < n; ++i) + numToIndex[nums[i]] = i; + + ranges::sort(nums); + + for (int i = 1; i < n; ++i) + // On the i-th step we've already removed the i - 1 smallest numbers and + // can ignore them. If an element nums[i] has smaller index in origin + // array than nums[i - 1], we should rotate the whole left array n - i + // times to set nums[i] element on the first position. + if (numToIndex[nums[i]] < numToIndex[nums[i - 1]]) + ans += n - i; + + return ans; + } +}; diff --git a/solutions/2659. Make Array Empty/2659.java b/solutions/2659. Make Array Empty/2659.java new file mode 100644 index 00000000000..cd29aa856cd --- /dev/null +++ b/solutions/2659. Make Array Empty/2659.java @@ -0,0 +1,22 @@ +class Solution { + public long countOperationsToEmptyArray(int[] nums) { + final int n = nums.length; + long ans = n; + Map numToIndex = new HashMap<>(); + + for (int i = 0; i < n; ++i) + numToIndex.put(nums[i], i); + + Arrays.sort(nums); + + for (int i = 1; i < n; ++i) + // On the i-th step we've already removed the i - 1 smallest numbers and + // can ignore them. If an element nums[i] has smaller index in origin + // array than nums[i - 1], we should rotate the whole left array n - i + // times to set nums[i] element on the first position. + if (numToIndex.get(nums[i]) < numToIndex.get(nums[i - 1])) + ans += n - i; + + return ans; + } +} diff --git a/solutions/2659. Make Array Empty/2659.py b/solutions/2659. Make Array Empty/2659.py new file mode 100644 index 00000000000..2a2394416e2 --- /dev/null +++ b/solutions/2659. Make Array Empty/2659.py @@ -0,0 +1,20 @@ +class Solution: + def countOperationsToEmptyArray(self, nums: List[int]) -> int: + n = len(nums) + ans = n + numToIndex = {} + + for i, num in enumerate(nums): + numToIndex[num] = i + + nums.sort() + + for i in range(1, n): + # On the i-th step we've already removed the i - 1 smallest numbers and + # can ignore them. If an element nums[i] has smaller index in origin + # array than nums[i - 1], we should rotate the whole left array n - i + # times to set nums[i] element on the first position. + if numToIndex[nums[i]] < numToIndex[nums[i - 1]]: + ans += n - i + + return ans diff --git a/solutions/266. Palindrome Permutation/266.cpp b/solutions/266. Palindrome Permutation/266.cpp new file mode 100644 index 00000000000..59505fcf841 --- /dev/null +++ b/solutions/266. Palindrome Permutation/266.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool canPermutePalindrome(string s) { + unordered_set seen; + + for (const char c : s) + if (!seen.insert(c).second) + seen.erase(c); + + return seen.size() <= 1; + } +}; diff --git a/solutions/266. Palindrome Permutation/266.java b/solutions/266. Palindrome Permutation/266.java new file mode 100644 index 00000000000..583e3d5d9d9 --- /dev/null +++ b/solutions/266. Palindrome Permutation/266.java @@ -0,0 +1,11 @@ +class Solution { + public boolean canPermutePalindrome(String s) { + Set seen = new HashSet<>(); + + for (final char c : s.toCharArray()) + if (!seen.add(c)) + seen.remove(c); + + return seen.size() <= 1; + } +} diff --git a/solutions/266. Palindrome Permutation/266.py b/solutions/266. Palindrome Permutation/266.py new file mode 100644 index 00000000000..31b7724909e --- /dev/null +++ b/solutions/266. Palindrome Permutation/266.py @@ -0,0 +1,11 @@ +class Solution: + def canPermutePalindrome(self, s: str) -> bool: + seen = set() + + for c in s: + if c in seen: + seen.remove(c) + else: + seen.add(c) + + return len(seen) <= 1 diff --git a/solutions/2660. Determine the Winner of a Bowling Game/2660.cpp b/solutions/2660. Determine the Winner of a Bowling Game/2660.cpp new file mode 100644 index 00000000000..0f07e22f1d1 --- /dev/null +++ b/solutions/2660. Determine the Winner of a Bowling Game/2660.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int isWinner(vector& player1, vector& player2) { + const int score1 = getScore(player1); + const int score2 = getScore(player2); + if (score1 > score2) + return 1; + if (score2 > score1) + return 2; + return 0; + } + + private: + int getScore(const vector& player) { + constexpr int kInvalid = -3; + int score = 0; + int last10 = kInvalid; + for (int i = 0; i < player.size(); ++i) { + score += i - last10 > 2 ? player[i] : player[i] * 2; + if (player[i] == 10) + last10 = i; + } + return score; + } +}; diff --git a/solutions/2660. Determine the Winner of a Bowling Game/2660.java b/solutions/2660. Determine the Winner of a Bowling Game/2660.java new file mode 100644 index 00000000000..d9587bae378 --- /dev/null +++ b/solutions/2660. Determine the Winner of a Bowling Game/2660.java @@ -0,0 +1,23 @@ +class Solution { + public int isWinner(int[] player1, int[] player2) { + final int score1 = getScore(player1); + final int score2 = getScore(player2); + if (score1 > score2) + return 1; + if (score2 > score1) + return 2; + return 0; + } + + private int getScore(int[] player) { + final int kInvalid = -3; + int score = 0; + int last10 = kInvalid; + for (int i = 0; i < player.length; ++i) { + score += i - last10 > 2 ? player[i] : player[i] * 2; + if (player[i] == 10) + last10 = i; + } + return score; + } +} diff --git a/solutions/2660. Determine the Winner of a Bowling Game/2660.py b/solutions/2660. Determine the Winner of a Bowling Game/2660.py new file mode 100644 index 00000000000..2dfbb152c64 --- /dev/null +++ b/solutions/2660. Determine the Winner of a Bowling Game/2660.py @@ -0,0 +1,19 @@ +class Solution: + def isWinner(self, player1: List[int], player2: List[int]) -> int: + def getScore(player: List[int]) -> int: + kInvalid = -3 + score = 0 + last10 = kInvalid + for i, p in enumerate(player): + score += p if i - last10 > 2 else p * 2 + if p == 10: + last10 = i + return score + + score1 = getScore(player1) + score2 = getScore(player2) + if score1 > score2: + return 1 + if score2 > score1: + return 2 + return 0 diff --git a/solutions/2661. First Completely Painted Row or Column/2661.cpp b/solutions/2661. First Completely Painted Row or Column/2661.cpp new file mode 100644 index 00000000000..eac2990f46f --- /dev/null +++ b/solutions/2661. First Completely Painted Row or Column/2661.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int firstCompleteIndex(vector& arr, vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + // rows[i] := the number of painted grid in the i-th row + vector rows(m); + // cols[j] := the number of painted grid in the j-th column + vector cols(n); + // numToRow[num] := the i-th row of `num` in `mat` + vector numToRow(m * n + 1); + // numToCol[num] := the j-th column of `num` in `mat` + vector numToCol(m * n + 1); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + numToRow[mat[i][j]] = i; + numToCol[mat[i][j]] = j; + } + + for (int i = 0; i < arr.size(); ++i) { + if (++rows[numToRow[arr[i]]] == n) + return i; + if (++cols[numToCol[arr[i]]] == m) + return i; + } + + throw; + } +}; diff --git a/solutions/2661. First Completely Painted Row or Column/2661.java b/solutions/2661. First Completely Painted Row or Column/2661.java new file mode 100644 index 00000000000..7abfd49c805 --- /dev/null +++ b/solutions/2661. First Completely Painted Row or Column/2661.java @@ -0,0 +1,29 @@ +class Solution { + public int firstCompleteIndex(int[] arr, int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + // rows[i] := the number of painted grid in the i-th row + int[] rows = new int[m]; + // cols[j] := the number of painted grid in the j-th column + int[] cols = new int[n]; + // numToRow[num] := the i-th row of `num` in `mat` + int[] numToRow = new int[m * n + 1]; + // numToCol[num] := the j-th column of `num` in `mat` + int[] numToCol = new int[m * n + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + numToRow[mat[i][j]] = i; + numToCol[mat[i][j]] = j; + } + + for (int i = 0; i < arr.length; ++i) { + if (++rows[numToRow[arr[i]]] == n) + return i; + if (++cols[numToCol[arr[i]]] == m) + return i; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2661. First Completely Painted Row or Column/2661.py b/solutions/2661. First Completely Painted Row or Column/2661.py new file mode 100644 index 00000000000..38561b63bfa --- /dev/null +++ b/solutions/2661. First Completely Painted Row or Column/2661.py @@ -0,0 +1,25 @@ +class Solution: + def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int: + m = len(mat) + n = len(mat[0]) + # rows[i] := the number of painted grid in the i-th row + rows = [0] * m + # cols[j] := the number of painted grid in the j-th column + cols = [0] * n + # numToRow[num] := the i-th row of `num` in `mat` + numToRow = [0] * (m * n + 1) + # numToCol[num] := the j-th column of `num` in `mat` + numToCol = [0] * (m * n + 1) + + for i, row in enumerate(mat): + for j, num in enumerate(row): + numToRow[num] = i + numToCol[num] = j + + for i, a in enumerate(arr): + rows[numToRow[a]] += 1 + if rows[numToRow[a]] == n: + return i + cols[numToCol[a]] += 1 + if cols[numToCol[a]] == m: + return i diff --git a/solutions/2662. Minimum Cost of a Path With Special Roads/2662.cpp b/solutions/2662. Minimum Cost of a Path With Special Roads/2662.cpp new file mode 100644 index 00000000000..05cedb7c9e4 --- /dev/null +++ b/solutions/2662. Minimum Cost of a Path With Special Roads/2662.cpp @@ -0,0 +1,59 @@ +class Solution { + public: + int minimumCost(vector& start, vector& target, + vector>& specialRoads) { + return dijkstra(specialRoads, start[0], start[1], target[0], target[1]); + } + + private: + int dijkstra(const vector>& specialRoads, int srcX, int srcY, + int dstX, int dstY) { + const int n = specialRoads.size(); + // dist[i] := the minimum distance of (srcX, srcY) to + // specialRoads[i](x2, y2) + vector dist(specialRoads.size(), INT_MAX); + using P = pair; // (d, u), where u := the i-th specialRoads + priority_queue, greater<>> minHeap; + + // (srcX, srcY) -> (x1, y1) to cost -> (x2, y2) + for (int u = 0; u < n; ++u) { + const int x1 = specialRoads[u][0]; + const int y1 = specialRoads[u][1]; + const int cost = specialRoads[u][4]; + const int d = abs(x1 - srcX) + abs(y1 - srcY) + cost; + dist[u] = d; + minHeap.emplace(dist[u], u); + } + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + const int ux2 = specialRoads[u][2]; + const int uy2 = specialRoads[u][3]; + for (int v = 0; v < n; ++v) { + if (v == u) + continue; + const int vx1 = specialRoads[v][0]; + const int vy1 = specialRoads[v][1]; + const int vcost = specialRoads[v][4]; + // (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2) + const int newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost; + if (newDist < dist[v]) { + dist[v] = newDist; + minHeap.emplace(dist[v], v); + } + } + } + + int ans = abs(dstX - srcX) + abs(dstY - srcY); + for (int u = 0; u < n; ++u) { + const int x2 = specialRoads[u][2]; + const int y2 = specialRoads[u][3]; + // (srcX, srcY) -> (x2, y2) -> (dstX, dstY). + ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2)); + } + return ans; + } +}; diff --git a/solutions/2662. Minimum Cost of a Path With Special Roads/2662.java b/solutions/2662. Minimum Cost of a Path With Special Roads/2662.java new file mode 100644 index 00000000000..3a9de6f3836 --- /dev/null +++ b/solutions/2662. Minimum Cost of a Path With Special Roads/2662.java @@ -0,0 +1,56 @@ +class Solution { + public int minimumCost(int[] start, int[] target, int[][] specialRoads) { + return dijkstra(specialRoads, start[0], start[1], target[0], target[1]); + } + + private int dijkstra(int[][] specialRoads, int srcX, int srcY, int dstX, int dstY) { + final int n = specialRoads.length; + // dist[i] := the minimum distance of (srcX, srcY) to + // specialRoads[i](x2, y2) + int[] dist = new int[n]; + Arrays.fill(dist, Integer.MAX_VALUE); + // (d, u), where u := the i-th specialRoads + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + // (srcX, srcY) -> (x1, y1) to cost -> (x2, y2) + for (int u = 0; u < n; ++u) { + final int x1 = specialRoads[u][0]; + final int y1 = specialRoads[u][1]; + final int cost = specialRoads[u][4]; + final int d = Math.abs(x1 - srcX) + Math.abs(y1 - srcY) + cost; + dist[u] = d; + minHeap.offer(new Pair<>(dist[u], u)); + } + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + final int ux2 = specialRoads[u][2]; + final int uy2 = specialRoads[u][3]; + for (int v = 0; v < n; ++v) { + if (v == u) + continue; + final int vx1 = specialRoads[v][0]; + final int vy1 = specialRoads[v][1]; + final int vcost = specialRoads[v][4]; + // (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2) + final int newDist = d + Math.abs(vx1 - ux2) + Math.abs(vy1 - uy2) + vcost; + if (newDist < dist[v]) { + dist[v] = newDist; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + int ans = Math.abs(dstX - srcX) + Math.abs(dstY - srcY); + for (int u = 0; u < n; ++u) { + final int x2 = specialRoads[u][2]; + final int y2 = specialRoads[u][3]; + // (srcX, srcY) -> (x2, y2) -> (dstX, dstY). + ans = Math.min(ans, dist[u] + Math.abs(dstX - x2) + Math.abs(dstY - y2)); + } + return ans; + } +} diff --git a/solutions/2662. Minimum Cost of a Path With Special Roads/2662.py b/solutions/2662. Minimum Cost of a Path With Special Roads/2662.py new file mode 100644 index 00000000000..ba78e0e6ead --- /dev/null +++ b/solutions/2662. Minimum Cost of a Path With Special Roads/2662.py @@ -0,0 +1,38 @@ +class Solution: + def minimumCost(self, start: List[int], target: List[int], specialRoads: List[List[int]]) -> int: + return self.dijkstra(specialRoads, *start, *target) + + def dijkstra(self, specialRoads: List[List[int]], srcX: int, srcY: int, dstX: int, dstY: int) -> int: + n = len(specialRoads) + # dist[i] := the minimum distance of (srcX, srcY) to specialRoads[i](x2, y2) + dist = [math.inf] * n + minHeap = [] # (d, u),(d, u), where u := the i-th specialRoads + + # (srcX, srcY) -> (x1, y1) to cost -> (x2, y2) + for u, (x1, y1, _, _, cost) in enumerate(specialRoads): + d = abs(x1 - srcX) + abs(y1 - srcY) + cost + dist[u] = d + heapq.heappush(minHeap, (dist[u], u)) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + _, _, ux2, uy2, _ = specialRoads[u] + for v in range(n): + if v == u: + continue + vx1, vy1, _, _, vcost = specialRoads[v] + # (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2) + newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost + if newDist < dist[v]: + dist[v] = newDist + heapq.heappush(minHeap, (dist[v], v)) + + ans = abs(dstX - srcX) + abs(dstY - srcY) + for u in range(n): + _, _, x2, y2, _ = specialRoads[u] + # (srcX, srcY) -> (x2, y2) -> (dstX, dstY). + ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2)) + + return ans diff --git a/solutions/2663. Lexicographically Smallest Beautiful String/2663.cpp b/solutions/2663. Lexicographically Smallest Beautiful String/2663.cpp new file mode 100644 index 00000000000..9f1cbb33cbc --- /dev/null +++ b/solutions/2663. Lexicographically Smallest Beautiful String/2663.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + string smallestBeautifulString(string s, int k) { + for (int i = s.length() - 1; i >= 0; --i) { + do { + ++s[i]; + } while (containsPalindrome(s, i)); + if (s[i] < 'a' + k) + // If s[i] is among the first k letters, then change the letters after + // s[i] to the smallest ones that don't form any palindrome substring. + return changeSuffix(s, i + 1); + } + + return ""; + } + + private: + // Returns true if s[0..i] contains any palindrome. + bool containsPalindrome(const string& s, int i) { + return (i > 0 && s[i] == s[i - 1]) || (i > 1 && s[i] == s[i - 2]); + } + + // Returns a string, where replacing s[i..n) with the smallest possible + // letters don't form any palindrome substring. + string changeSuffix(string& s, int i) { + for (int j = i; j < s.length(); ++j) + for (s[j] = 'a'; containsPalindrome(s, j); ++s[j]) + ; + return s; + } +}; diff --git a/solutions/2663. Lexicographically Smallest Beautiful String/2663.java b/solutions/2663. Lexicographically Smallest Beautiful String/2663.java new file mode 100644 index 00000000000..238cfdb9993 --- /dev/null +++ b/solutions/2663. Lexicographically Smallest Beautiful String/2663.java @@ -0,0 +1,33 @@ +public class Solution { + public String smallestBeautifulString(String s, int k) { + StringBuilder sb = new StringBuilder(s); + + for (int i = s.length() - 1; i >= 0; --i) { + do { + sb.setCharAt(i, (char) (sb.charAt(i) + 1)); + } while (containsPalindrome(sb, i)); + if (sb.charAt(i) < 'a' + k) + // If sb[i] is among the first k letters, then change the letters after + // sb[i] to the smallest ones that don't form any palindrome substring. + return changeSuffix(sb, i + 1); + } + + return ""; + } + + // Returns true if sb[0..i] contains any palindrome. + private boolean containsPalindrome(StringBuilder sb, int i) { + return (i > 0 && sb.charAt(i) == sb.charAt(i - 1)) || + (i > 1 && sb.charAt(i) == sb.charAt(i - 2)); + } + + // Returns a string, where replacing sb[i..n) with the smallest possible + // letters don't form any palindrome substring. + private String changeSuffix(StringBuilder sb, int i) { + for (int j = i; j < sb.length(); ++j) + for (sb.setCharAt(j, 'a'); containsPalindrome(sb, j); + sb.setCharAt(j, (char) (sb.charAt(j) + 1))) + ; + return sb.toString(); + } +} diff --git a/solutions/2663. Lexicographically Smallest Beautiful String/2663.py b/solutions/2663. Lexicographically Smallest Beautiful String/2663.py new file mode 100644 index 00000000000..02e92f6bdd6 --- /dev/null +++ b/solutions/2663. Lexicographically Smallest Beautiful String/2663.py @@ -0,0 +1,30 @@ +class Solution: + def smallestBeautifulString(self, s: str, k: int) -> str: + chars = list(s) + + for i in reversed(range(len(chars))): + chars[i] = chr(ord(chars[i]) + 1) + while self._containsPalindrome(chars, i): + chars[i] = chr(ord(chars[i]) + 1) + if chars[i] < chr(ord('a') + k): + # If s[i] is among the first k letters, then change the letters after + # s[i] to the smallest ones that don't form any palindrome substring. + return self._changeSuffix(chars, i + 1) + + return '' + + def _containsPalindrome(self, chars: List[str], i: int) -> bool: + """Returns True if chars[0..i] contains palindrome.""" + return (i > 0 and chars[i] == chars[i - 1]) or \ + (i > 1 and chars[i] == chars[i - 2]) + + def _changeSuffix(self, chars: List[str], i: int) -> str: + """ + Returns a string, where replacing sb[i..n) with the smallest possible + letters don't form any palindrome substring. + """ + for j in range(i, len(chars)): + chars[j] = 'a' + while self._containsPalindrome(chars, j): + chars[j] = chr(ord(chars[j]) + 1) + return ''.join(chars) diff --git "a/solutions/2664. The Knight\342\200\231s Tour/2664.cpp" "b/solutions/2664. The Knight\342\200\231s Tour/2664.cpp" new file mode 100644 index 00000000000..268e387b9ee --- /dev/null +++ "b/solutions/2664. The Knight\342\200\231s Tour/2664.cpp" @@ -0,0 +1,27 @@ +class Solution { + public: + vector> tourOfKnight(int m, int n, int r, int c) { + vector> ans(m, vector(n, -1)); + dfs(m, n, r, c, 0, ans); + return ans; + } + + private: + static constexpr int dirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, + {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; + + bool dfs(int m, int n, int i, int j, int step, vector>& ans) { + if (step == m * n) + return true; + if (i < 0 || i >= m || j < 0 || j >= n) + return false; + if (ans[i][j] != -1) + return false; + ans[i][j] = step; + for (const auto& [dx, dy] : dirs) + if (dfs(m, n, i + dx, j + dy, step + 1, ans)) + return true; + ans[i][j] = -1; + return false; + } +}; diff --git "a/solutions/2664. The Knight\342\200\231s Tour/2664.java" "b/solutions/2664. The Knight\342\200\231s Tour/2664.java" new file mode 100644 index 00000000000..6e32e91615b --- /dev/null +++ "b/solutions/2664. The Knight\342\200\231s Tour/2664.java" @@ -0,0 +1,26 @@ +class Solution { + public int[][] tourOfKnight(int m, int n, int r, int c) { + int[][] ans = new int[m][n]; + Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1)); + dfs(m, n, r, c, 0, ans); + return ans; + } + + private static final int[][] dirs = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, + {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; + + private boolean dfs(int m, int n, int i, int j, int step, int[][] ans) { + if (step == m * n) + return true; + if (i < 0 || i >= m || j < 0 || j >= n) + return false; + if (ans[i][j] != -1) + return false; + ans[i][j] = step; + for (int[] dir : dirs) + if (dfs(m, n, i + dir[0], j + dir[1], step + 1, ans)) + return true; + ans[i][j] = -1; + return false; + } +} diff --git "a/solutions/2664. The Knight\342\200\231s Tour/2664.py" "b/solutions/2664. The Knight\342\200\231s Tour/2664.py" new file mode 100644 index 00000000000..316f3e18700 --- /dev/null +++ "b/solutions/2664. The Knight\342\200\231s Tour/2664.py" @@ -0,0 +1,22 @@ +class Solution: + def tourOfKnight(self, m: int, n: int, r: int, c: int) -> List[List[int]]: + dirs = ((1, 2), (2, 1), (2, -1), (1, -2), + (-1, -2), (-2, -1), (-2, 1), (-1, 2)) + ans = [[-1] * n for _ in range(m)] + + def dfs(i: int, j: int, step: int) -> bool: + if step == m * n: + return True + if i < 0 or i >= m or j < 0 or j >= n: + return False + if ans[i][j] != -1: + return False + ans[i][j] = step + for dx, dy in dirs: + if dfs(i + dx, j + dy, step + 1): + return True + ans[i][j] = -1 + return False + + dfs(r, c, 0) + return ans diff --git a/solutions/2665. Counter II/2665.ts b/solutions/2665. Counter II/2665.ts new file mode 100644 index 00000000000..44d9b74cfc5 --- /dev/null +++ b/solutions/2665. Counter II/2665.ts @@ -0,0 +1,14 @@ +type ReturnObj = { + increment: () => number; + decrement: () => number; + reset: () => number; +}; + +function createCounter(init: number): ReturnObj { + let cur = init; + return { + increment: () => ++cur, + decrement: () => --cur, + reset: () => (cur = init), + }; +} diff --git a/solutions/2666. Allow One Function Call/2666.ts b/solutions/2666. Allow One Function Call/2666.ts new file mode 100644 index 00000000000..930206e6123 --- /dev/null +++ b/solutions/2666. Allow One Function Call/2666.ts @@ -0,0 +1,19 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type OnceFn = (...args: JSONValue[]) => JSONValue | undefined; + +function once(fn: Function): OnceFn { + let isCalled = false; + return function (...args) { + if (isCalled) { + return; + } + isCalled = true; + return fn(...args); + }; +} diff --git a/solutions/2667. Create Hello World Function/2667.ts b/solutions/2667. Create Hello World Function/2667.ts new file mode 100644 index 00000000000..830e287386b --- /dev/null +++ b/solutions/2667. Create Hello World Function/2667.ts @@ -0,0 +1,5 @@ +function createHelloWorld() { + return function (..._): string { + return 'Hello World'; + }; +} diff --git a/solutions/2668. Find Latest Salaries/2668.sql b/solutions/2668. Find Latest Salaries/2668.sql new file mode 100644 index 00000000000..740bb62d1d1 --- /dev/null +++ b/solutions/2668. Find Latest Salaries/2668.sql @@ -0,0 +1,9 @@ +SELECT + emp_id, + firstname, + lastname, + MAX(salary) AS salary, + department_id +FROM Salary +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2669. Count Artist Occurrences On Spotify Ranking List/2669.sql b/solutions/2669. Count Artist Occurrences On Spotify Ranking List/2669.sql new file mode 100644 index 00000000000..2c1823ecf06 --- /dev/null +++ b/solutions/2669. Count Artist Occurrences On Spotify Ranking List/2669.sql @@ -0,0 +1,6 @@ +SELECT + artist, + COUNT(id) AS occurrences +FROM Spotify +GROUP BY 1 +ORDER BY 2 DESC, 1; diff --git a/solutions/267. Palindrome Permutation II/267.cpp b/solutions/267. Palindrome Permutation II/267.cpp new file mode 100644 index 00000000000..018d92ee966 --- /dev/null +++ b/solutions/267. Palindrome Permutation II/267.cpp @@ -0,0 +1,59 @@ +class Solution { + public: + vector generatePalindromes(string s) { + int odd = 0; + unordered_map count; + + for (const char c : s) + ++count[c]; + + // Count odd ones. + for (const auto& [_, value] : count) + if (value % 2 == 1) + ++odd; + + // Can't form any palindrome. + if (odd > 1) + return {}; + + vector ans; + vector candidates; + string mid; + + // Get the mid and the candidates characters. + for (const auto& [key, value] : count) { + if (value % 2 == 1) + mid += key; + for (int i = 0; i < value / 2; ++i) + candidates.push_back(key); + } + + // Backtrack to generate the ans strings. + dfs(candidates, mid, vector(candidates.size()), "", ans); + return ans; + } + + private: + // Generates all the unique palindromes from the candidates. + void dfs(const vector& candidates, const string& mid, + vector&& used, string&& path, vector& ans) { + if (path.length() == candidates.size()) { + string secondHalf = path; + reverse(secondHalf.begin(), secondHalf.end()); + ans.push_back(path + mid + secondHalf); + return; + } + + for (int i = 0; i < candidates.size(); ++i) { + if (used[i]) + continue; + if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) + continue; + used[i] = true; + path.push_back(candidates[i]); + dfs(candidates, mid, move(used), move(path), ans); + path.pop_back(); + used[i] = false; + } + } +}; diff --git a/solutions/267. Palindrome Permutation II/267.java b/solutions/267. Palindrome Permutation II/267.java new file mode 100644 index 00000000000..e56959db8fd --- /dev/null +++ b/solutions/267. Palindrome Permutation II/267.java @@ -0,0 +1,58 @@ +class Solution { + public List generatePalindromes(String s) { + int odd = 0; + Map count = new HashMap<>(); + + for (final char c : s.toCharArray()) + count.merge(c, 1, Integer::sum); + + // Count odd ones. + for (Map.Entry entry : count.entrySet()) + if (entry.getValue() % 2 == 1) + ++odd; + + // Can't form any palindrome. + if (odd > 1) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + List candidates = new ArrayList<>(); + StringBuilder mid = new StringBuilder(); + + // Get the mid and the candidates characters. + for (Map.Entry entry : count.entrySet()) { + final char key = entry.getKey(); + final int value = entry.getValue(); + if (value % 2 == 1) + mid.append(key); + for (int i = 0; i < value / 2; ++i) + candidates.add(key); + } + + // Backtrack to generate the ans strings. + dfs(candidates, mid, new boolean[candidates.size()], new StringBuilder(), ans); + return ans; + } + + // Generates all the unique palindromes from the candidates. + private void dfs(List candidates, StringBuilder mid, boolean[] used, StringBuilder sb, + List ans) { + if (sb.length() == candidates.size()) { + ans.add(sb.toString() + mid + sb.reverse().toString()); + sb.reverse(); + return; + } + + for (int i = 0; i < candidates.size(); ++i) { + if (used[i]) + continue; + if (i > 0 && candidates.get(i) == candidates.get(i - 1) && !used[i - 1]) + continue; + used[i] = true; + sb.append(candidates.get(i)); + dfs(candidates, mid, used, sb, ans); + sb.deleteCharAt(sb.length() - 1); + used[i] = false; + } + } +} diff --git a/solutions/267. Palindrome Permutation II/267.py b/solutions/267. Palindrome Permutation II/267.py new file mode 100644 index 00000000000..40f0438eded --- /dev/null +++ b/solutions/267. Palindrome Permutation II/267.py @@ -0,0 +1,42 @@ +class Solution: + def generatePalindromes(self, s: str) -> List[str]: + count = collections.Counter(s) + + # Count odd ones. + odd = sum(value & 1 for value in count.values()) + + # Can't form any palindrome. + if odd > 1: + return [] + + ans = [] + candidates = [] + mid = '' + + # Get the mid and the candidates characters. + for key, value in count.items(): + if value % 2 == 1: + mid += key + for _ in range(value // 2): + candidates.append(key) + + def dfs(used: List[bool], path: List[chr]) -> None: + """Generates all the unique palindromes from the candidates.""" + if len(path) == len(candidates): + ans.append(''.join(path) + mid + ''.join(reversed(path))) + return + + for i, candidate in enumerate(candidates): + if used[i]: + continue + if i > 0 and candidate == candidates[i - 1] and not used[i - 1]: + continue + used[i] = True + path.append(candidate) + dfs(used, path) + path.pop() + used[i] = False + + # Backtrack to generate the ans strings. + dfs([False] * len(candidates), []) + return ans diff --git a/solutions/2670. Find the Distinct Difference Array/2670.cpp b/solutions/2670. Find the Distinct Difference Array/2670.cpp new file mode 100644 index 00000000000..0c739d06c03 --- /dev/null +++ b/solutions/2670. Find the Distinct Difference Array/2670.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector distinctDifferenceArray(vector& nums) { + constexpr int kMax = 50; + vector ans; + vector prefixCount(kMax + 1); + vector suffixCount(kMax + 1); + int distinctPrefix = 0; + int distinctSuffix = 0; + + for (const int num : nums) + if (++suffixCount[num] == 1) + ++distinctSuffix; + + for (const int num : nums) { + if (++prefixCount[num] == 1) + ++distinctPrefix; + if (--suffixCount[num] == 0) + --distinctSuffix; + ans.push_back(distinctPrefix - distinctSuffix); + } + + return ans; + } +}; diff --git a/solutions/2670. Find the Distinct Difference Array/2670.java b/solutions/2670. Find the Distinct Difference Array/2670.java new file mode 100644 index 00000000000..f3ffe3e0f2e --- /dev/null +++ b/solutions/2670. Find the Distinct Difference Array/2670.java @@ -0,0 +1,24 @@ +class Solution { + public int[] distinctDifferenceArray(int[] nums) { + final int kMax = 50; + int[] ans = new int[nums.length]; + int[] prefixCount = new int[kMax + 1]; + int[] suffixCount = new int[kMax + 1]; + int distinctPrefix = 0; + int distinctSuffix = 0; + + for (final int num : nums) + if (++suffixCount[num] == 1) + ++distinctSuffix; + + for (int i = 0; i < nums.length; ++i) { + if (++prefixCount[nums[i]] == 1) + ++distinctPrefix; + if (--suffixCount[nums[i]] == 0) + --distinctSuffix; + ans[i] = distinctPrefix - distinctSuffix; + } + + return ans; + } +} diff --git a/solutions/2670. Find the Distinct Difference Array/2670.py b/solutions/2670. Find the Distinct Difference Array/2670.py new file mode 100644 index 00000000000..4509d468d27 --- /dev/null +++ b/solutions/2670. Find the Distinct Difference Array/2670.py @@ -0,0 +1,24 @@ +class Solution: + def distinctDifferenceArray(self, nums: List[int]) -> List[int]: + kMax = 50 + ans = [] + prefixCount = [0] * (kMax + 1) + suffixCount = [0] * (kMax + 1) + distinctPrefix = 0 + distinctSuffix = 0 + + for num in nums: + if suffixCount[num] == 0: + distinctSuffix += 1 + suffixCount[num] += 1 + + for num in nums: + if prefixCount[num] == 0: + distinctPrefix += 1 + prefixCount[num] += 1 + if suffixCount[num] == 1: + distinctSuffix -= 1 + suffixCount[num] -= 1 + ans.append(distinctPrefix - distinctSuffix) + + return ans diff --git a/solutions/2671. Frequency Tracker/2671.cpp b/solutions/2671. Frequency Tracker/2671.cpp new file mode 100644 index 00000000000..4da9063e863 --- /dev/null +++ b/solutions/2671. Frequency Tracker/2671.cpp @@ -0,0 +1,25 @@ +class FrequencyTracker { + public: + void add(int number) { + if (count[number] > 0) + --freqCount[count[number]]; + ++count[number]; + ++freqCount[count[number]]; + } + + void deleteOne(int number) { + if (count[number] == 0) + return; + --freqCount[count[number]]; + --count[number]; + ++freqCount[count[number]]; + } + + bool hasFrequency(int frequency) { + return freqCount[frequency] > 0; + } + + private: + unordered_map count; + unordered_map freqCount; +}; diff --git a/solutions/2671. Frequency Tracker/2671.java b/solutions/2671. Frequency Tracker/2671.java new file mode 100644 index 00000000000..a43601b5a2f --- /dev/null +++ b/solutions/2671. Frequency Tracker/2671.java @@ -0,0 +1,23 @@ +class FrequencyTracker { + public void add(int number) { + if (count[number] > 0) + --freqCount[count[number]]; + ++count[number]; + ++freqCount[count[number]]; + } + + public void deleteOne(int number) { + if (count[number] == 0) + return; + --freqCount[count[number]]; + --count[number]; + ++freqCount[count[number]]; + } + + public boolean hasFrequency(int frequency) { + return freqCount[frequency] > 0; + } + + private int[] freqCount = new int[100_001]; + private int[] count = new int[100_001]; +} diff --git a/solutions/2671. Frequency Tracker/2671.py b/solutions/2671. Frequency Tracker/2671.py new file mode 100644 index 00000000000..45181480b51 --- /dev/null +++ b/solutions/2671. Frequency Tracker/2671.py @@ -0,0 +1,20 @@ +class FrequencyTracker: + def __init__(self): + self.count = collections.Counter() + self.freqCount = collections.Counter() + + def add(self, number: int) -> None: + if self.count[number] > 0: + self.freqCount[self.count[number]] -= 1 + self.count[number] += 1 + self.freqCount[self.count[number]] += 1 + + def deleteOne(self, number: int) -> None: + if self.count[number] == 0: + return + self.freqCount[self.count[number]] -= 1 + self.count[number] -= 1 + self.freqCount[self.count[number]] += 1 + + def hasFrequency(self, frequency: int) -> bool: + return self.freqCount[frequency] > 0 diff --git a/solutions/2672. Number of Adjacent Elements With the Same Color/2672.cpp b/solutions/2672. Number of Adjacent Elements With the Same Color/2672.cpp new file mode 100644 index 00000000000..3d89857de30 --- /dev/null +++ b/solutions/2672. Number of Adjacent Elements With the Same Color/2672.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector colorTheArray(int n, vector>& queries) { + vector ans; + vector arr(n); + int sameColors = 0; + + for (const vector& query : queries) { + const int i = query[0]; + const int color = query[1]; + if (i + 1 < n) { + if (arr[i + 1] > 0 && arr[i + 1] == arr[i]) + --sameColors; + if (arr[i + 1] == color) + ++sameColors; + } + if (i > 0) { + if (arr[i - 1] > 0 && arr[i - 1] == arr[i]) + --sameColors; + if (arr[i - 1] == color) + ++sameColors; + } + arr[i] = color; + ans.push_back(sameColors); + } + + return ans; + } +}; diff --git a/solutions/2672. Number of Adjacent Elements With the Same Color/2672.java b/solutions/2672. Number of Adjacent Elements With the Same Color/2672.java new file mode 100644 index 00000000000..64006d7ef37 --- /dev/null +++ b/solutions/2672. Number of Adjacent Elements With the Same Color/2672.java @@ -0,0 +1,28 @@ +class Solution { + public int[] colorTheArray(int n, int[][] queries) { + int[] ans = new int[queries.length]; + int[] arr = new int[n]; + int sameColors = 0; + + for (int i = 0; i < queries.length; ++i) { + final int j = queries[i][0]; + final int color = queries[i][1]; + if (j + 1 < n) { + if (arr[j + 1] > 0 && arr[j + 1] == arr[j]) + --sameColors; + if (arr[j + 1] == color) + ++sameColors; + } + if (j > 0) { + if (arr[j - 1] > 0 && arr[j - 1] == arr[j]) + --sameColors; + if (arr[j - 1] == color) + ++sameColors; + } + arr[j] = color; + ans[i] = sameColors; + } + + return ans; + } +} diff --git a/solutions/2672. Number of Adjacent Elements With the Same Color/2672.py b/solutions/2672. Number of Adjacent Elements With the Same Color/2672.py new file mode 100644 index 00000000000..c4fbd471e68 --- /dev/null +++ b/solutions/2672. Number of Adjacent Elements With the Same Color/2672.py @@ -0,0 +1,21 @@ +class Solution: + def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]: + ans = [] + arr = [0] * n + sameColors = 0 + + for i, color in queries: + if i + 1 < n: + if arr[i + 1] > 0 and arr[i + 1] == arr[i]: + sameColors -= 1 + if arr[i + 1] == color: + sameColors += 1 + if i > 0: + if arr[i - 1] > 0 and arr[i - 1] == arr[i]: + sameColors -= 1 + if arr[i - 1] == color: + sameColors += 1 + arr[i] = color + ans.append(sameColors) + + return ans diff --git a/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.cpp b/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.cpp new file mode 100644 index 00000000000..f63ba159a44 --- /dev/null +++ b/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minIncrements(int n, vector& cost) { + int ans = 0; + + for (int i = n / 2 - 1; i >= 0; --i) { + const int l = i * 2 + 1; + const int r = i * 2 + 2; + ans += abs(cost[l] - cost[r]); + // Record the information in the parent from the children. So, there's + // need to actually update the values in the children. + cost[i] += max(cost[l], cost[r]); + } + + return ans; + } +}; diff --git a/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.java b/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.java new file mode 100644 index 00000000000..3d0512e6d54 --- /dev/null +++ b/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.java @@ -0,0 +1,16 @@ +class Solution { + public int minIncrements(int n, int[] cost) { + int ans = 0; + + for (int i = n / 2 - 1; i >= 0; --i) { + final int l = i * 2 + 1; + final int r = i * 2 + 2; + ans += Math.abs(cost[l] - cost[r]); + // Record the information in the parent from the children. So, there's need to actually + // update the values in the children. + cost[i] += Math.max(cost[l], cost[r]); + } + + return ans; + } +} diff --git a/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.py b/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.py new file mode 100644 index 00000000000..0e0735fee98 --- /dev/null +++ b/solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.py @@ -0,0 +1,13 @@ +class Solution: + def minIncrements(self, n: int, cost: List[int]) -> int: + ans = 0 + + for i in range(n // 2 - 1, -1, -1): + l = i * 2 + 1 + r = i * 2 + 2 + ans += abs(cost[l] - cost[r]) + # Record the information in the parent from the children. So, there's need to actually + # update the values in the children. + cost[i] += max(cost[l], cost[r]) + + return ans diff --git a/solutions/2674. Split a Circular Linked List/2674.cpp b/solutions/2674. Split a Circular Linked List/2674.cpp new file mode 100644 index 00000000000..8ca264d811b --- /dev/null +++ b/solutions/2674. Split a Circular Linked List/2674.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector splitCircularLinkedList(ListNode* list) { + ListNode* slow = list; + ListNode* fast = list; + + // Point `slow` to the last node in the first half. + while (fast->next != list && fast->next->next != list) { + slow = slow->next; + fast = fast->next->next; + } + + // Circle back the second half. + ListNode* secondHead = slow->next; + if (fast->next == list) + fast->next = secondHead; + else + fast->next->next = secondHead; + + // Circle back the first half. + slow->next = list; + + return {list, secondHead}; + } +}; diff --git a/solutions/2674. Split a Circular Linked List/2674.java b/solutions/2674. Split a Circular Linked List/2674.java new file mode 100644 index 00000000000..39d63a1c9af --- /dev/null +++ b/solutions/2674. Split a Circular Linked List/2674.java @@ -0,0 +1,24 @@ +class Solution { + public ListNode[] splitCircularLinkedList(ListNode list) { + ListNode slow = list; + ListNode fast = list; + + // Point `slow` to the last node in the first half. + while (fast.next != list && fast.next.next != list) { + slow = slow.next; + fast = fast.next.next; + } + + // Circle back the second half. + ListNode secondHead = slow.next; + if (fast.next == list) + fast.next = secondHead; + else + fast.next.next = secondHead; + + // Circle back the first half. + slow.next = list; + + return new ListNode[] {list, secondHead}; + } +} diff --git a/solutions/2674. Split a Circular Linked List/2674.py b/solutions/2674. Split a Circular Linked List/2674.py new file mode 100644 index 00000000000..136d1b00cce --- /dev/null +++ b/solutions/2674. Split a Circular Linked List/2674.py @@ -0,0 +1,21 @@ +class Solution: + def splitCircularLinkedList(self, list: Optional[ListNode]) -> List[Optional[ListNode]]: + slow = list + fast = list + + # Point `slow` to the last node in the first half. + while fast.next != list and fast.next.next != list: + slow = slow.next + fast = fast.next.next + + # Circle back the second half. + secondHead = slow.next + if fast.next == list: + fast.next = secondHead + else: + fast.next.next = secondHead + + # Circle back the first half. + slow.next = list + + return [list, secondHead] diff --git a/solutions/2675. Array of Objects to Matrix/2675.ts b/solutions/2675. Array of Objects to Matrix/2675.ts new file mode 100644 index 00000000000..2368feb1671 --- /dev/null +++ b/solutions/2675. Array of Objects to Matrix/2675.ts @@ -0,0 +1,51 @@ +function jsonToMatrix(arr: any[]): (string | number | boolean | null)[][] { + const isObject = (o: any) => o !== null && typeof o === 'object'; + + // Returns the keys of a JSON-like object by recursively unwrapping the nests. + const getKeys = (json: any): string[] => { + if (!isObject(json)) { + return ['']; + } + return Object.keys(json).reduce((acc: string[], currKey: string) => { + return ( + acc.push( + ...getKeys(json[currKey]).map((nextKey: string) => + nextKey === '' ? currKey : `${currKey}.${nextKey}` + ) + ), + acc + ); + }, []); + }; + + const sortedKeys: string[] = [ + ...arr.reduce((acc: Set, curr: any) => { + getKeys(curr).forEach((key: string) => acc.add(key)); + return acc; + }, new Set()), + ].sort(); + + // Returns the value of `obj` keyed by `nestedKey`. + const getValue = ( + obj: any, + nestedKey: string + ): string | number | boolean | null => { + let value: any = obj; + for (const key of nestedKey.split('.')) { + if (!isObject(value) || !(key in value)) { + return ''; + } + value = value[key]; + } + return isObject(value) ? '' : value; + }; + + const matrix: (string | number | boolean | null)[][] = [sortedKeys]; + arr.forEach((obj: any) => { + matrix.push( + sortedKeys.map((nestedKey: string) => getValue(obj, nestedKey)) + ); + }); + + return matrix; +} diff --git a/solutions/2676. Throttle/2676.ts b/solutions/2676. Throttle/2676.ts new file mode 100644 index 00000000000..e5904e3c4d1 --- /dev/null +++ b/solutions/2676. Throttle/2676.ts @@ -0,0 +1,14 @@ +type F = (...args: any[]) => void; + +function throttle(fn: F, t: number): F { + let timeout: ReturnType | undefined; + let nextTimeToCallFn = 0; + return function (...args) { + const delay = Math.max(0, nextTimeToCallFn - Date.now()); + clearTimeout(timeout); + timeout = setTimeout(() => { + fn(...args); + nextTimeToCallFn = Date.now() + t; + }, delay); + }; +} diff --git a/solutions/2677. Chunk Array/2677.ts b/solutions/2677. Chunk Array/2677.ts new file mode 100644 index 00000000000..a23715454e0 --- /dev/null +++ b/solutions/2677. Chunk Array/2677.ts @@ -0,0 +1,16 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Obj = Record | Array; + +function chunk(arr: Obj[], size: number): Obj[][] { + const ans: Obj[][] = []; + for (let i = 0; i < arr.length; i += size) { + ans.push(arr.slice(i, i + size)); + } + return ans; +} diff --git a/solutions/2678. Number of Senior Citizens/2678.cpp b/solutions/2678. Number of Senior Citizens/2678.cpp new file mode 100644 index 00000000000..6c23e296e96 --- /dev/null +++ b/solutions/2678. Number of Senior Citizens/2678.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int countSeniors(vector& details) { + return ranges::count_if(details, [](const string& detail) { + return stoi(detail.substr(11, 2)) > 60; + }); + } +}; diff --git a/solutions/2678. Number of Senior Citizens/2678.java b/solutions/2678. Number of Senior Citizens/2678.java new file mode 100644 index 00000000000..df6b3f5f116 --- /dev/null +++ b/solutions/2678. Number of Senior Citizens/2678.java @@ -0,0 +1,7 @@ +class Solution { + public int countSeniors(String[] details) { + return (int) Arrays.stream(details) + .filter(detail -> Integer.parseInt(detail.substring(11, 13)) > 60) + .count(); + } +} diff --git a/solutions/2678. Number of Senior Citizens/2678.py b/solutions/2678. Number of Senior Citizens/2678.py new file mode 100644 index 00000000000..71402ed87a4 --- /dev/null +++ b/solutions/2678. Number of Senior Citizens/2678.py @@ -0,0 +1,3 @@ +class Solution: + def countSeniors(self, details: List[str]) -> int: + return sum(int(detail[11:13]) > 60 for detail in details) diff --git a/solutions/2679. Sum in a Matrix/2679.cpp b/solutions/2679. Sum in a Matrix/2679.cpp new file mode 100644 index 00000000000..7c28c94c01e --- /dev/null +++ b/solutions/2679. Sum in a Matrix/2679.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int matrixSum(vector>& nums) { + int ans = 0; + + for (vector& row : nums) + ranges::sort(row); + + for (int j = 0; j < nums[0].size(); ++j) { + int mx = 0; + for (int i = 0; i < nums.size(); ++i) + mx = max(mx, nums[i][j]); + ans += mx; + } + + return ans; + } +}; diff --git a/solutions/2679. Sum in a Matrix/2679.java b/solutions/2679. Sum in a Matrix/2679.java new file mode 100644 index 00000000000..43eab28f9e6 --- /dev/null +++ b/solutions/2679. Sum in a Matrix/2679.java @@ -0,0 +1,17 @@ +class Solution { + public int matrixSum(int[][] nums) { + int ans = 0; + + for (int[] row : nums) + Arrays.sort(row); + + for (int j = 0; j < nums[0].length; ++j) { + int mx = 0; + for (int i = 0; i < nums.length; ++i) + mx = Math.max(mx, nums[i][j]); + ans += mx; + } + + return ans; + } +} diff --git a/solutions/2679. Sum in a Matrix/2679.py b/solutions/2679. Sum in a Matrix/2679.py new file mode 100644 index 00000000000..6d452086627 --- /dev/null +++ b/solutions/2679. Sum in a Matrix/2679.py @@ -0,0 +1,6 @@ +class Solution: + def matrixSum(self, nums: List[List[int]]) -> int: + for row in nums: + row.sort() + + return sum(max(col) for col in zip(*nums)) diff --git a/solutions/268. Missing Number/268.cpp b/solutions/268. Missing Number/268.cpp new file mode 100644 index 00000000000..7d2dfb00953 --- /dev/null +++ b/solutions/268. Missing Number/268.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int missingNumber(vector& nums) { + int ans = nums.size(); + + for (int i = 0; i < nums.size(); ++i) + ans ^= i ^ nums[i]; + + return ans; + } +}; diff --git a/solutions/268. Missing Number/268.java b/solutions/268. Missing Number/268.java new file mode 100644 index 00000000000..a745dc0f609 --- /dev/null +++ b/solutions/268. Missing Number/268.java @@ -0,0 +1,10 @@ +class Solution { + public int missingNumber(int[] nums) { + int ans = nums.length; + + for (int i = 0; i < nums.length; ++i) + ans ^= i ^ nums[i]; + + return ans; + } +} diff --git a/solutions/268. Missing Number/268.py b/solutions/268. Missing Number/268.py new file mode 100644 index 00000000000..81f92ee1ecd --- /dev/null +++ b/solutions/268. Missing Number/268.py @@ -0,0 +1,8 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + ans = len(nums) + + for i, num in enumerate(nums): + ans ^= i ^ num + + return ans diff --git a/solutions/2680. Maximum OR/2680.cpp b/solutions/2680. Maximum OR/2680.cpp new file mode 100644 index 00000000000..0f14f7782d1 --- /dev/null +++ b/solutions/2680. Maximum OR/2680.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long maximumOr(vector& nums, int k) { + const int n = nums.size(); + long ans = 0; + // prefix[i] := nums[0] | nums[1] | ... | nums[i - 1] + vector prefix(n); + // suffix[i] := nums[i + 1] | nums[i + 2] | ... nums[n - 1] + vector suffix(n); + + for (int i = 1; i < n; ++i) + prefix[i] = prefix[i - 1] | nums[i - 1]; + + for (int i = n - 2; i >= 0; --i) + suffix[i] = suffix[i + 1] | nums[i + 1]; + + // For each num, greedily shift it left by k bits. + for (int i = 0; i < n; ++i) + ans = max(ans, prefix[i] | static_cast(nums[i]) << k | suffix[i]); + + return ans; + } +}; diff --git a/solutions/2680. Maximum OR/2680.java b/solutions/2680. Maximum OR/2680.java new file mode 100644 index 00000000000..cb0b419795a --- /dev/null +++ b/solutions/2680. Maximum OR/2680.java @@ -0,0 +1,23 @@ +class Solution { + public long maximumOr(int[] nums, int k) { + final int n = nums.length; + long ans = 0; + // prefix[i] := nums[0] | nums[1] | ... | nums[i - 1] + long[] prefix = new long[n]; + // suffix[i] := nums[i + 1] | nums[i + 2] | ... nums[n - 1] + long[] suffix = new long[n]; + + for (int i = 1; i < n; ++i) + prefix[i] = prefix[i - 1] | nums[i - 1]; + + for (int i = n - 2; i >= 0; --i) + suffix[i] = suffix[i + 1] | nums[i + 1]; + + // For each num, greedily shift it left by k bits. The bitwise or value is + // prefix[i] | nums[i] << k | suffix[i] + for (int i = 0; i < n; ++i) + ans = Math.max(ans, prefix[i] | (long) nums[i] << k | suffix[i]); + + return ans; + } +} diff --git a/solutions/2680. Maximum OR/2680.py b/solutions/2680. Maximum OR/2680.py new file mode 100644 index 00000000000..682ecc90748 --- /dev/null +++ b/solutions/2680. Maximum OR/2680.py @@ -0,0 +1,16 @@ +class Solution: + def maximumOr(self, nums: List[int], k: int) -> int: + n = len(nums) + # prefix[i] := nums[0] | nums[1] | ... | nums[i - 1] + prefix = [0] * n + # suffix[i] := nums[i + 1] | nums[i + 2] | ... nums[n - 1] + suffix = [0] * n + + for i in range(1, n): + prefix[i] = prefix[i - 1] | nums[i - 1] + + for i in range(n - 2, -1, -1): + suffix[i] = suffix[i + 1] | nums[i + 1] + + # For each num, greedily shift it left by k bits. + return max(p | num << k | s for num, p, s in zip(nums, prefix, suffix)) diff --git a/solutions/2681. Power of Heroes/2681.cpp b/solutions/2681. Power of Heroes/2681.cpp new file mode 100644 index 00000000000..de8789fcaf1 --- /dev/null +++ b/solutions/2681. Power of Heroes/2681.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int sumOfPower(vector& nums) { + constexpr int kMod = 1'000'000'007; + long ans = 0; + long sum = 0; + + ranges::sort(nums); + + for (const int num : nums) { + ans = (ans + (num + sum) * num % kMod * num % kMod) % kMod; + sum = (sum * 2 + num) % kMod; + } + + return ans; + } +}; diff --git a/solutions/2681. Power of Heroes/2681.java b/solutions/2681. Power of Heroes/2681.java new file mode 100644 index 00000000000..d05a230c125 --- /dev/null +++ b/solutions/2681. Power of Heroes/2681.java @@ -0,0 +1,16 @@ +class Solution { + public int sumOfPower(int[] nums) { + final int kMod = 1_000_000_007; + long ans = 0; + long sum = 0; + + Arrays.sort(nums); + + for (final int num : nums) { + ans = (ans + (num + sum) * num % kMod * num % kMod) % kMod; + sum = (sum * 2 + num) % kMod; + } + + return (int) ans; + } +} diff --git a/solutions/2681. Power of Heroes/2681.py b/solutions/2681. Power of Heroes/2681.py new file mode 100644 index 00000000000..fcab09d39e5 --- /dev/null +++ b/solutions/2681. Power of Heroes/2681.py @@ -0,0 +1,12 @@ +class Solution: + def sumOfPower(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + ans = 0 + summ = 0 + + for num in sorted(nums): + ans += (num + summ) * num**2 + ans %= kMod + summ = (summ * 2 + num) % kMod + + return ans diff --git a/solutions/2682. Find the Losers of the Circular Game/2682.cpp b/solutions/2682. Find the Losers of the Circular Game/2682.cpp new file mode 100644 index 00000000000..44c8cdecbc4 --- /dev/null +++ b/solutions/2682. Find the Losers of the Circular Game/2682.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector circularGameLosers(int n, int k) { + vector ans; + vector seen(n); + + for (int friendIndex = 0, turn = 1; !seen[friendIndex];) { + seen[friendIndex] = true; + friendIndex += turn++ * k; + friendIndex %= n; + } + + for (int friendIndex = 0; friendIndex < n; ++friendIndex) + if (!seen[friendIndex]) + ans.push_back(friendIndex + 1); + + return ans; + } +}; diff --git a/solutions/2682. Find the Losers of the Circular Game/2682.java b/solutions/2682. Find the Losers of the Circular Game/2682.java new file mode 100644 index 00000000000..6c033271511 --- /dev/null +++ b/solutions/2682. Find the Losers of the Circular Game/2682.java @@ -0,0 +1,18 @@ +class Solution { + public int[] circularGameLosers(int n, int k) { + List ans = new ArrayList<>(); + boolean[] seen = new boolean[n]; + + for (int friendIndex = 0, turn = 1; !seen[friendIndex];) { + seen[friendIndex] = true; + friendIndex += turn++ * k; + friendIndex %= n; + } + + for (int friendIndex = 0; friendIndex < n; ++friendIndex) + if (!seen[friendIndex]) + ans.add(friendIndex + 1); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/2682. Find the Losers of the Circular Game/2682.py b/solutions/2682. Find the Losers of the Circular Game/2682.py new file mode 100644 index 00000000000..5dc1f768bd6 --- /dev/null +++ b/solutions/2682. Find the Losers of the Circular Game/2682.py @@ -0,0 +1,15 @@ +class Solution: + def circularGameLosers(self, n: int, k: int) -> List[int]: + seen = [False] * n + friendIndex = 0 + turn = 1 + + while not seen[friendIndex]: + seen[friendIndex] = True + friendIndex += turn * k + friendIndex %= n + turn += 1 + + return [friendIndex + 1 + for friendIndex in range(n) + if not seen[friendIndex]] diff --git a/solutions/2683. Neighboring Bitwise XOR/2683.cpp b/solutions/2683. Neighboring Bitwise XOR/2683.cpp new file mode 100644 index 00000000000..f08122b1ff9 --- /dev/null +++ b/solutions/2683. Neighboring Bitwise XOR/2683.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + bool doesValidArrayExist(vector& derived) { + // original = [O[0], O[1], ..., O[n - 1]] + // derived = [O[0]^O[1], O[1]^O[2], ..., O[n - 1]^O[0]] + // XOR(derivedd) = 0 + return accumulate(derived.begin(), derived.end(), 0, bit_xor<>()) == 0; + } +}; diff --git a/solutions/2683. Neighboring Bitwise XOR/2683.java b/solutions/2683. Neighboring Bitwise XOR/2683.java new file mode 100644 index 00000000000..d7812655c4d --- /dev/null +++ b/solutions/2683. Neighboring Bitwise XOR/2683.java @@ -0,0 +1,8 @@ +class Solution { + public boolean doesValidArrayExist(int[] derived) { + // original = [O[0], O[1], ..., O[n - 1]] + // derived = [O[0]^O[1], O[1]^O[2], ..., O[n - 1]^O[0]] + // XOR(derivedd) = 0 + return Arrays.stream(derived).reduce((a, b) -> a ^ b).getAsInt() == 0; + } +} diff --git a/solutions/2683. Neighboring Bitwise XOR/2683.py b/solutions/2683. Neighboring Bitwise XOR/2683.py new file mode 100644 index 00000000000..ae1d4e3890b --- /dev/null +++ b/solutions/2683. Neighboring Bitwise XOR/2683.py @@ -0,0 +1,3 @@ +class Solution: + def doesValidArrayExist(self, derived: List[int]) -> bool: + return functools.reduce(operator.xor, derived) == 0 diff --git a/solutions/2684. Maximum Number of Moves in a Grid/2684.cpp b/solutions/2684. Maximum Number of Moves in a Grid/2684.cpp new file mode 100644 index 00000000000..8089c1f8d3b --- /dev/null +++ b/solutions/2684. Maximum Number of Moves in a Grid/2684.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int maxMoves(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + // dp[i][j] := the maximum number of moves you can perform from (i, j) + vector> dp(m, vector(n)); + + for (int j = n - 2; j >= 0; --j) + for (int i = 0; i < m; ++i) { + if (grid[i][j + 1] > grid[i][j]) + dp[i][j] = 1 + dp[i][j + 1]; + if (i > 0 && grid[i - 1][j + 1] > grid[i][j]) + dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1]); + if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j]) + dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1]); + } + + for (int i = 0; i < m; ++i) + ans = max(ans, dp[i][0]); + + return ans; + } +}; diff --git a/solutions/2684. Maximum Number of Moves in a Grid/2684.java b/solutions/2684. Maximum Number of Moves in a Grid/2684.java new file mode 100644 index 00000000000..99a5a443ae0 --- /dev/null +++ b/solutions/2684. Maximum Number of Moves in a Grid/2684.java @@ -0,0 +1,24 @@ +class Solution { + public int maxMoves(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + // dp[i][j] := the maximum number of moves you can perform from (i, j) + int[][] dp = new int[m][n]; + + for (int j = n - 2; j >= 0; --j) + for (int i = 0; i < m; ++i) { + if (grid[i][j + 1] > grid[i][j]) + dp[i][j] = 1 + dp[i][j + 1]; + if (i > 0 && grid[i - 1][j + 1] > grid[i][j]) + dp[i][j] = Math.max(dp[i][j], 1 + dp[i - 1][j + 1]); + if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j]) + dp[i][j] = Math.max(dp[i][j], 1 + dp[i + 1][j + 1]); + } + + for (int i = 0; i < m; ++i) + ans = Math.max(ans, dp[i][0]); + + return ans; + } +} diff --git a/solutions/2684. Maximum Number of Moves in a Grid/2684.py b/solutions/2684. Maximum Number of Moves in a Grid/2684.py new file mode 100644 index 00000000000..47f83e5c2f5 --- /dev/null +++ b/solutions/2684. Maximum Number of Moves in a Grid/2684.py @@ -0,0 +1,17 @@ +class Solution: + def maxMoves(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + # dp[i][j] := the maximum number of moves you can perform from (i, j) + dp = [[0] * n for _ in range(m)] + + for j in range(n - 2, -1, -1): + for i in range(m): + if grid[i][j + 1] > grid[i][j]: + dp[i][j] = 1 + dp[i][j + 1] + if i > 0 and grid[i - 1][j + 1] > grid[i][j]: + dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1]) + if i + 1 < m and grid[i + 1][j + 1] > grid[i][j]: + dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1]) + + return max(dp[i][0] for i in range(m)) diff --git a/solutions/2685. Count the Number of Complete Components/2685.cpp b/solutions/2685. Count the Number of Complete Components/2685.cpp new file mode 100644 index 00000000000..281b0930315 --- /dev/null +++ b/solutions/2685. Count the Number of Complete Components/2685.cpp @@ -0,0 +1,65 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n), nodeCount(n, 1), edgeCount(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + ++edgeCount[i]; + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + edgeCount[j] += edgeCount[i]; + nodeCount[j] += nodeCount[i]; + } else if (rank[i] > rank[j]) { + id[j] = i; + edgeCount[i] += edgeCount[j]; + nodeCount[i] += nodeCount[j]; + } else { + id[i] = j; + edgeCount[j] += edgeCount[i]; + nodeCount[j] += nodeCount[i]; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + bool isComplete(int u) { + return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u]; + } + + private: + vector id; + vector rank; + vector nodeCount; + vector edgeCount; +}; + +class Solution { + public: + int countCompleteComponents(int n, vector>& edges) { + int ans = 0; + UnionFind uf(n); + unordered_set parents; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + uf.unionByRank(u, v); + } + + for (int i = 0; i < n; ++i) { + const int parent = uf.find(i); + if (parents.insert(parent).second && uf.isComplete(parent)) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2685. Count the Number of Complete Components/2685.java b/solutions/2685. Count the Number of Complete Components/2685.java new file mode 100644 index 00000000000..f6e441cbfec --- /dev/null +++ b/solutions/2685. Count the Number of Complete Components/2685.java @@ -0,0 +1,69 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + nodeCount = new int[n]; + edgeCount = new int[n]; + for (int i = 0; i < n; ++i) { + id[i] = i; + nodeCount[i] = 1; + } + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + ++edgeCount[i]; + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + edgeCount[j] += edgeCount[i]; + nodeCount[j] += nodeCount[i]; + } else if (rank[i] > rank[j]) { + id[j] = i; + edgeCount[i] += edgeCount[j]; + nodeCount[i] += nodeCount[j]; + } else { + id[i] = j; + edgeCount[j] += edgeCount[i]; + nodeCount[j] += nodeCount[i]; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + public boolean isComplete(int u) { + return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u]; + } + + private int[] id; + private int[] rank; + private int[] nodeCount; + private int[] edgeCount; +} + +class Solution { + public int countCompleteComponents(int n, int[][] edges) { + int ans = 0; + UnionFind uf = new UnionFind(n); + Set parents = new HashSet<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + uf.unionByRank(u, v); + } + + for (int i = 0; i < n; ++i) { + final int parent = uf.find(i); + if (parents.add(parent) && uf.isComplete(parent)) + ++ans; + } + + return ans; + } +} diff --git a/solutions/2685. Count the Number of Complete Components/2685.py b/solutions/2685. Count the Number of Complete Components/2685.py new file mode 100644 index 00000000000..c29d602ffa1 --- /dev/null +++ b/solutions/2685. Count the Number of Complete Components/2685.py @@ -0,0 +1,52 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + self.nodeCount = [1] * n + self.edgeCount = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + self.edgeCount[i] += 1 + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + self.edgeCount[j] += self.edgeCount[i] + self.nodeCount[j] += self.nodeCount[i] + elif self.rank[i] > self.rank[j]: + self.id[j] = i + self.edgeCount[i] += self.edgeCount[j] + self.nodeCount[i] += self.nodeCount[j] + else: + self.id[i] = j + self.edgeCount[j] += self.edgeCount[i] + self.nodeCount[j] += self.nodeCount[i] + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + def isComplete(self, u): + return self.nodeCount[u] * (self.nodeCount[u] - 1) // 2 == self.edgeCount[u] + + +class Solution: + def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int: + ans = 0 + uf = UnionFind(n) + parents = set() + + for u, v in edges: + uf.unionByRank(u, v) + + for i in range(n): + parent = uf.find(i) + if parent not in parents and uf.isComplete(parent): + ans += 1 + parents.add(parent) + + return ans diff --git a/solutions/2686. Immediate Food Delivery III/2686.sql b/solutions/2686. Immediate Food Delivery III/2686.sql new file mode 100644 index 00000000000..07c31989de2 --- /dev/null +++ b/solutions/2686. Immediate Food Delivery III/2686.sql @@ -0,0 +1,9 @@ +SELECT + order_date, + ROUND( + AVG(order_date = customer_pref_delivery_date) * 100, + 2 + ) AS immediate_percentage +FROM Delivery +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2687. Bikes Last Time Used/2687.sql b/solutions/2687. Bikes Last Time Used/2687.sql new file mode 100644 index 00000000000..5b16e4c5db3 --- /dev/null +++ b/solutions/2687. Bikes Last Time Used/2687.sql @@ -0,0 +1,3 @@ +SELECT bike_number, MAX(end_time) AS end_time +FROM Bikes +GROUP BY 1; diff --git a/solutions/2688. Find Active Users/2688.sql b/solutions/2688. Find Active Users/2688.sql new file mode 100644 index 00000000000..9b8d9653afa --- /dev/null +++ b/solutions/2688. Find Active Users/2688.sql @@ -0,0 +1,14 @@ +WITH + UsersWithRowNumber AS ( + SELECT + *, + ROW_NUMBER() OVER(ORDER BY created_at) AS `row_number` + FROM Users + ) +SELECT DISTINCT(First.user_id) +FROM UsersWithRowNumber AS First +INNER JOIN UsersWithRowNumber AS Second + USING (user_id) +WHERE + First.`row_number` < Second.`row_number` + AND DATEDIFF(Second.created_at, First.created_at) <= 7 diff --git a/solutions/2689. Extract Kth Character From The Rope Tree/2589-2.py b/solutions/2689. Extract Kth Character From The Rope Tree/2589-2.py new file mode 100644 index 00000000000..3d2b7556050 --- /dev/null +++ b/solutions/2689. Extract Kth Character From The Rope Tree/2589-2.py @@ -0,0 +1,12 @@ +class Solution: + def getKthCharacter(self, root: Optional[object], k: int) -> str: + """:type root: Optional[RopeTreeNode]""" + while root.len > 0: + leftLen = 0 if root.left is None \ + else max(root.left.len, len(root.left.val)) + if leftLen >= k: + root = root.left + else: + root = root.right + k -= leftLen + return root.val[k - 1] diff --git a/solutions/2689. Extract Kth Character From The Rope Tree/2689-2.cpp b/solutions/2689. Extract Kth Character From The Rope Tree/2689-2.cpp new file mode 100644 index 00000000000..a6fd700f2ec --- /dev/null +++ b/solutions/2689. Extract Kth Character From The Rope Tree/2689-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + char getKthCharacter(RopeTreeNode* root, int k) { + while (root->len > 0) { + const int leftLen = root->left == nullptr + ? 0 + : max(root->left->len, + static_cast(root->left->val.length())); + if (leftLen >= k) { + root = root->left; + } else { + root = root->right; + k -= leftLen; + } + } + return root->val[k - 1]; + } +}; diff --git a/solutions/2689. Extract Kth Character From The Rope Tree/2689-2.java b/solutions/2689. Extract Kth Character From The Rope Tree/2689-2.java new file mode 100644 index 00000000000..0ed877448b0 --- /dev/null +++ b/solutions/2689. Extract Kth Character From The Rope Tree/2689-2.java @@ -0,0 +1,14 @@ +class Solution { + public char getKthCharacter(RopeTreeNode root, int k) { + while (root.len > 0) { + final int leftLen = root.left == null ? 0 : Math.max(root.left.len, root.left.val.length()); + if (leftLen >= k) { + root = root.left; + } else { + root = root.right; + k -= leftLen; + } + } + return root.val.charAt(k - 1); + } +} diff --git a/solutions/2689. Extract Kth Character From The Rope Tree/2689.cpp b/solutions/2689. Extract Kth Character From The Rope Tree/2689.cpp new file mode 100644 index 00000000000..8a418833370 --- /dev/null +++ b/solutions/2689. Extract Kth Character From The Rope Tree/2689.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + char getKthCharacter(RopeTreeNode* root, int k) { + if (root->len == 0) + return root->val[k - 1]; + const int leftLen = + root->left == nullptr + ? 0 + : max(root->left->len, static_cast(root->left->val.length())); + return leftLen >= k ? getKthCharacter(root->left, k) + : getKthCharacter(root->right, k - leftLen); + } +}; diff --git a/solutions/2689. Extract Kth Character From The Rope Tree/2689.java b/solutions/2689. Extract Kth Character From The Rope Tree/2689.java new file mode 100644 index 00000000000..456965572d6 --- /dev/null +++ b/solutions/2689. Extract Kth Character From The Rope Tree/2689.java @@ -0,0 +1,8 @@ +class Solution { + public char getKthCharacter(RopeTreeNode root, int k) { + if (root.len == 0) + return root.val.charAt(k - 1); + final int leftLen = root.left == null ? 0 : Math.max(root.left.len, root.left.val.length()); + return leftLen >= k ? getKthCharacter(root.left, k) : getKthCharacter(root.right, k - leftLen); + } +} diff --git a/solutions/2689. Extract Kth Character From The Rope Tree/2689.py b/solutions/2689. Extract Kth Character From The Rope Tree/2689.py new file mode 100644 index 00000000000..a3633f2302d --- /dev/null +++ b/solutions/2689. Extract Kth Character From The Rope Tree/2689.py @@ -0,0 +1,10 @@ +class Solution: + def getKthCharacter(self, root: Optional[object], k: int) -> str: + """:type root: Optional[RopeTreeNode]""" + if root.len == 0: + return root.val[k - 1] + leftLen = 0 if root.left is None \ + else max(root.left.len, len(root.left.val)) + if leftLen >= k: + return self.getKthCharacter(root.left, k) + return self.getKthCharacter(root.right, k - leftLen) diff --git a/solutions/269. Alien Dictionary/269.cpp b/solutions/269. Alien Dictionary/269.cpp new file mode 100644 index 00000000000..97a1d527650 --- /dev/null +++ b/solutions/269. Alien Dictionary/269.cpp @@ -0,0 +1,63 @@ +class Solution { + public: + string alienOrder(vector& words) { + unordered_map> graph; + vector inDegrees(26); + buildGraph(graph, words, inDegrees); + return topology(graph, inDegrees); + } + + private: + void buildGraph(unordered_map>& graph, + const vector& words, vector& inDegrees) { + // Create a node for each character in each word. + for (const string& word : words) + for (const char c : word) + if (!graph.contains(c)) + graph[c] = unordered_set(); + + for (int i = 1; i < words.size(); ++i) { + const string& first = words[i - 1]; + const string& second = words[i]; + const int length = min(first.length(), second.length()); + for (int j = 0; j < length; ++j) { + const char u = first[j]; + const char v = second[j]; + if (u != v) { + if (!graph[u].contains(v)) { + graph[u].insert(v); + ++inDegrees[v - 'a']; + } + break; // The order of characters after this are meaningless. + } + // e.g. first = "ab", second = "a" -> invalid + if (j == length - 1 && first.length() > second.length()) { + graph.clear(); + return; + } + } + } + } + + string topology(unordered_map>& graph, + vector& inDegrees) { + string s; + queue q; + + for (const auto& [c, _] : graph) + if (inDegrees[c - 'a'] == 0) + q.push(c); + + while (!q.empty()) { + const char u = q.front(); + q.pop(); + s += u; + for (const char v : graph[u]) + if (--inDegrees[v - 'a'] == 0) + q.push(v); + } + + // e.g. words = ["z", "x", "y", "x"] + return s.length() == graph.size() ? s : ""; + } +}; diff --git a/solutions/269. Alien Dictionary/269.java b/solutions/269. Alien Dictionary/269.java new file mode 100644 index 00000000000..d3037238b71 --- /dev/null +++ b/solutions/269. Alien Dictionary/269.java @@ -0,0 +1,56 @@ +class Solution { + public String alienOrder(String[] words) { + Map> graph = new HashMap<>(); + int[] inDegrees = new int[26]; + buildGraph(graph, words, inDegrees); + return topology(graph, inDegrees); + } + + private void buildGraph(Map> graph, String[] words, int[] inDegrees) { + // Create a node for each character in each word. + for (final String word : words) + for (final char c : word.toCharArray()) + graph.putIfAbsent(c, new HashSet<>()); + + for (int i = 1; i < words.length; ++i) { + final String first = words[i - 1]; + final String second = words[i]; + final int length = Math.min(first.length(), second.length()); + for (int j = 0; j < length; ++j) { + final char u = first.charAt(j); + final char v = second.charAt(j); + if (u != v) { + if (!graph.get(u).contains(v)) { + graph.get(u).add(v); + ++inDegrees[v - 'a']; + } + break; // The order of characters after this are meaningless. + } + // e.g. first = "ab", second = "a" -> invalid + if (j == length - 1 && first.length() > second.length()) { + graph.clear(); + return; + } + } + } + } + + private String topology(Map> graph, int[] inDegrees) { + StringBuilder sb = new StringBuilder(); + Queue q = graph.keySet() + .stream() + .filter(c -> inDegrees[c - 'a'] == 0) + .collect(Collectors.toCollection(ArrayDeque::new)); + + while (!q.isEmpty()) { + final char u = q.poll(); + sb.append(u); + for (final char v : graph.get(u)) + if (--inDegrees[v - 'a'] == 0) + q.offer(v); + } + + // e.g. words = ["z", "x", "y", "x"] + return sb.length() == graph.size() ? sb.toString() : ""; + } +} diff --git a/solutions/269. Alien Dictionary/269.py b/solutions/269. Alien Dictionary/269.py new file mode 100644 index 00000000000..ba03d055a7f --- /dev/null +++ b/solutions/269. Alien Dictionary/269.py @@ -0,0 +1,48 @@ +class Solution: + def alienOrder(self, words: List[str]) -> str: + graph = {} + inDegrees = [0] * 26 + + self._buildGraph(graph, words, inDegrees) + return self._topology(graph, inDegrees) + + def _buildGraph(self, graph: Dict[chr, Set[chr]], words: List[str], inDegrees: List[int]) -> None: + # Create a node for each character in each word. + for word in words: + for c in word: + if c not in graph: + graph[c] = set() + + for first, second in zip(words, words[1:]): + length = min(len(first), len(second)) + for j in range(length): + u = first[j] + v = second[j] + if u != v: + if v not in graph[u]: + graph[u].add(v) + inDegrees[ord(v) - ord('a')] += 1 + break # The order of characters after this are meaningless. + # First = 'ab', second = 'a' . invalid + if j == length - 1 and len(first) > len(second): + graph.clear() + return + + def _topology(self, graph: Dict[chr, Set[chr]], inDegrees: List[int]) -> str: + s = '' + q = collections.deque() + + for c in graph: + if inDegrees[ord(c) - ord('a')] == 0: + q.append(c) + + while q: + u = q.pop() + s += u + for v in graph[u]: + inDegrees[ord(v) - ord('a')] -= 1 + if inDegrees[ord(v) - ord('a')] == 0: + q.append(v) + + # Words = ['z', 'x', 'y', 'x'] + return s if len(s) == len(graph) else '' diff --git a/solutions/2690. Infinite Method Object/2690.ts b/solutions/2690. Infinite Method Object/2690.ts new file mode 100644 index 00000000000..72d91fea993 --- /dev/null +++ b/solutions/2690. Infinite Method Object/2690.ts @@ -0,0 +1,8 @@ +function createInfiniteObject(): Record string> { + return new Proxy( + {}, + { + get: (_, prop: string) => () => prop, + } + ); +} diff --git a/solutions/2691. Immutability Helper/2691.ts b/solutions/2691. Immutability Helper/2691.ts new file mode 100644 index 00000000000..53fef07a4a7 --- /dev/null +++ b/solutions/2691. Immutability Helper/2691.ts @@ -0,0 +1,114 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type InputObj = Record | Array; + +type RecursiveHandler = { + set: (target: any, prop: string, value: any) => boolean; + get: (target: any, prop: string) => unknown; +}; + +const isObject = (o: any) => o !== null && typeof o === 'object'; + +// Access history of properties +class AccessHistory { + value: JSONValue | null = null; + props: Map = new Map(); +} + +class ImmutableHelper { + private obj: InputObj; + + constructor(obj: InputObj) { + this.obj = obj; + } + + produce(mutator: (obj: InputObj) => void): InputObj { + // Creates a proxied object to track property access history. + function createProxiedObj( + obj: InputObj, + accessHistory: AccessHistory + ): InputObj { + const handler: RecursiveHandler = { + // 'set' trap intercepts property assignment. + set(_, prop, value) { + if (!accessHistory.props.has(prop)) { + accessHistory.props.set(prop, new AccessHistory()); + } + accessHistory.props.get(prop)!.value = value; + return true; + }, + // 'get' trap intercepts property access. + get(_, prop) { + if (accessHistory.value !== null) { + return accessHistory.value; + } + if (!accessHistory.props.has(prop)) { + accessHistory.props.set(prop, new AccessHistory()); + } + if (accessHistory.props.get(prop)!.value !== null) { + return accessHistory.props.get(prop)!.value; + } + if (isObject(obj[prop])) { + // Recursively create a proxed object for object property. + return createProxiedObj( + obj[prop] as InputObj, + accessHistory.props.get(prop)! as AccessHistory + ); + } + return obj[prop]; + }, + }; + return new Proxy(obj, handler); + } + + // Returns true if there are mutated properties in the access history; + // otherwise, returns false and deletes the unnecessary properties. + function deleteUnmutatedProps(accessHistory: AccessHistory): boolean { + if (accessHistory.value !== null) { + return true; + } + let hasMutation = false; + for (const [prop, childAccessHistory] of [...accessHistory.props]) { + if (deleteUnmutatedProps(childAccessHistory)) { + hasMutation = true; + } else { + accessHistory.props.delete(prop); + } + } + return hasMutation; + } + + // Function to transform the original object based on the access history + function transform(obj: InputObj, accessHistory: AccessHistory): InputObj { + if (accessHistory.value !== null) { + return accessHistory.value as InputObj; + } + if (accessHistory.props.size === 0) { + return obj; + } + if (!isObject(obj)) { + return obj; + } + let clone = Array.isArray(obj) ? [...obj] : { ...obj }; + for (const [prop, childAccessHistory] of [...accessHistory.props]) { + clone[prop] = transform(obj[prop] as InputObj, childAccessHistory); + } + return clone; + } + + const accessHistory = new AccessHistory(); + const proxiedObj = createProxiedObj(this.obj, accessHistory); + // Apply the mutator function on the proxied object. This will also record + // the property access history in `accessHistory`. + mutator(proxiedObj); + // Simplify the access history. + deleteUnmutatedProps(accessHistory); + // Transform the original object based on the simplified access history. + return transform(this.obj, accessHistory); + } +} diff --git a/solutions/2692. Make Object Immutable/2692.ts b/solutions/2692. Make Object Immutable/2692.ts new file mode 100644 index 00000000000..0f08a03c796 --- /dev/null +++ b/solutions/2692. Make Object Immutable/2692.ts @@ -0,0 +1,49 @@ +type RecursiveHandler = { + set: (target: T, prop: string, value: any) => boolean; + get: (target: T, prop: string) => any; + apply: (target: T, thisArg: any, argArray?: any) => any; +}; + +function makeImmutable(obj: T): T { + // a set of mutating array methods + const methods = new Set([ + 'pop', + 'push', + 'shift', + 'unshift', + 'splice', + 'sort', + 'reverse', + ]); + + const handler: RecursiveHandler = { + // 'set' trap prevents modifications of the object properties. + set(target, prop, _) { + throw Array.isArray(target) + ? `Error Modifying Index: ${String(prop)}` + : `Error Modifying: ${String(prop)}`; + }, + // 'get' trap returns object properties or creates new proxies for nested + // objects or functions + get(target, prop) { + // If the property is 'prototype', null, or not an object/function, return + // it directly. We exclude 'prototype' to avoid potential issues with + // inheritance Objects and functions are wrapped in a new proxy to + // preserve immutability at all depths. + const key = prop as keyof typeof target; + return prop === 'prototype' || + target[key] === null || + (typeof target[key] !== 'object' && typeof target[key] !== 'function') + ? target[key] + : new Proxy(target[key], this); + }, + // 'apply' trap prevents call of mutating methods and apply function calls. + apply(target, thisArg, argumentsList) { + if (methods.has((target as any).name)) + throw `Error Calling Method: ${(target as any).name}`; + return target.apply(thisArg, argumentsList); + }, + }; + + return new Proxy(obj, handler) as T; +} diff --git a/solutions/2693. Call Function with Custom Context/2693.ts b/solutions/2693. Call Function with Custom Context/2693.ts new file mode 100644 index 00000000000..4360e6dd52f --- /dev/null +++ b/solutions/2693. Call Function with Custom Context/2693.ts @@ -0,0 +1,27 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +declare global { + interface Function { + callPolyfill( + context: Record, + ...args: JSONValue[] + ): JSONValue; + } +} + +Function.prototype.callPolyfill = function (context, ...args): JSONValue { + const fn = this; + Object.defineProperty(context, '__fn__', { + value: fn, + enumerable: false, + }); + const ans = (context.__fn__ as any)(...args); + delete context.__fn__; + return typeof ans !== 'undefined' ? ans : undefined; +}; diff --git a/solutions/2694. Event Emitter/2694.ts b/solutions/2694. Event Emitter/2694.ts new file mode 100644 index 00000000000..570e87545a3 --- /dev/null +++ b/solutions/2694. Event Emitter/2694.ts @@ -0,0 +1,37 @@ +type Callback = (...args: any[]) => any; +type Subscription = { + unsubscribe: () => void; +}; + +class EventEmitter { + private eventToCallbacks: Map; + + constructor() { + this.eventToCallbacks = new Map(); + } + + subscribe(eventName: string, callback: Callback): Subscription { + if (!this.eventToCallbacks.has(eventName)) + this.eventToCallbacks.set(eventName, []); + + const callbacks = this.eventToCallbacks.get(eventName); + callbacks?.push(callback); + + return { + unsubscribe: () => { + const index = callbacks?.indexOf(callback); + if (index !== undefined && index !== -1) { + callbacks?.splice(index, 1); + } + }, + }; + } + + emit(eventName: string, args: any[] = []): any[] { + const callbacks = this.eventToCallbacks.get(eventName); + if (callbacks === undefined) { + return []; + } + return callbacks.map((callback) => callback(...args)); + } +} diff --git a/solutions/2695. Array Wrapper/2695.ts b/solutions/2695. Array Wrapper/2695.ts new file mode 100644 index 00000000000..9e3806d6dc5 --- /dev/null +++ b/solutions/2695. Array Wrapper/2695.ts @@ -0,0 +1,15 @@ +class ArrayWrapper { + private nums: number[]; + + constructor(nums: number[]) { + this.nums = nums; + } + + valueOf(): number { + return this.nums.reduce((sum, num) => sum + num, 0); + } + + toString(): string { + return '[' + this.nums.join(',') + ']'; + } +} diff --git a/solutions/2696. Minimum String Length After Removing Substrings/2696.cpp b/solutions/2696. Minimum String Length After Removing Substrings/2696.cpp new file mode 100644 index 00000000000..178e16887f1 --- /dev/null +++ b/solutions/2696. Minimum String Length After Removing Substrings/2696.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minLength(string s) { + stack stack; + + for (const char c : s) + if (c == 'B' && match(stack, 'A')) + stack.pop(); + else if (c == 'D' && match(stack, 'C')) + stack.pop(); + else + stack.push(c); + + return stack.size(); + } + + private: + bool match(const stack& stack, int c) { + return !stack.empty() && stack.top() == c; + } +}; diff --git a/solutions/2696. Minimum String Length After Removing Substrings/2696.java b/solutions/2696. Minimum String Length After Removing Substrings/2696.java new file mode 100644 index 00000000000..2afa3ec650a --- /dev/null +++ b/solutions/2696. Minimum String Length After Removing Substrings/2696.java @@ -0,0 +1,19 @@ +class Solution { + public int minLength(String s) { + Deque stack = new ArrayDeque<>(); + + for (final char c : s.toCharArray()) + if (c == 'B' && match(stack, 'A')) + stack.pop(); + else if (c == 'D' && match(stack, 'C')) + stack.pop(); + else + stack.push(c); + + return stack.size(); + } + + private boolean match(Deque stack, char c) { + return !stack.isEmpty() && stack.peek() == c; + } +} diff --git a/solutions/2696. Minimum String Length After Removing Substrings/2696.py b/solutions/2696. Minimum String Length After Removing Substrings/2696.py new file mode 100644 index 00000000000..e3913b07ab4 --- /dev/null +++ b/solutions/2696. Minimum String Length After Removing Substrings/2696.py @@ -0,0 +1,16 @@ +class Solution: + def minLength(self, s: str) -> int: + stack = [] + + def match(c: str) -> bool: + return stack and stack[-1] == c + + for c in s: + if c == 'B' and match('A'): + stack.pop() + elif c == 'D' and match('C'): + stack.pop() + else: + stack.append(c) + + return len(stack) diff --git a/solutions/2697. Lexicographically Smallest Palindrome/2697.cpp b/solutions/2697. Lexicographically Smallest Palindrome/2697.cpp new file mode 100644 index 00000000000..c7bdf0ec560 --- /dev/null +++ b/solutions/2697. Lexicographically Smallest Palindrome/2697.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + string makeSmallestPalindrome(string s) { + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + const int minChar = min(s[i], s[j]); + s[i] = minChar; + s[j] = minChar; + } + return s; + } +}; diff --git a/solutions/2697. Lexicographically Smallest Palindrome/2697.java b/solutions/2697. Lexicographically Smallest Palindrome/2697.java new file mode 100644 index 00000000000..1c95d5b46a9 --- /dev/null +++ b/solutions/2697. Lexicographically Smallest Palindrome/2697.java @@ -0,0 +1,11 @@ +class Solution { + public String makeSmallestPalindrome(String s) { + char[] chars = s.toCharArray(); + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + final char minChar = (char) Math.min(chars[i], chars[j]); + chars[i] = minChar; + chars[j] = minChar; + } + return new String(chars); + } +} diff --git a/solutions/2697. Lexicographically Smallest Palindrome/2697.py b/solutions/2697. Lexicographically Smallest Palindrome/2697.py new file mode 100644 index 00000000000..ef79f4d4973 --- /dev/null +++ b/solutions/2697. Lexicographically Smallest Palindrome/2697.py @@ -0,0 +1,14 @@ +class Solution: + def makeSmallestPalindrome(self, s: str) -> str: + chars = list(s) + i = 0 + j = len(s) - 1 + + while i < j: + minChar = min(chars[i], chars[j]) + chars[i] = minChar + chars[j] = minChar + i += 1 + j -= 1 + + return ''.join(chars) diff --git a/solutions/2698. Find the Punishment Number of an Integer/2698.cpp b/solutions/2698. Find the Punishment Number of an Integer/2698.cpp new file mode 100644 index 00000000000..c410af61553 --- /dev/null +++ b/solutions/2698. Find the Punishment Number of an Integer/2698.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int punishmentNumber(int n) { + int ans = 0; + for (int i = 1; i <= n; ++i) + if (isPossible(0, 0, to_string(i * i), 0, i)) + ans += i * i; + return ans; + } + + private: + // Returns true if the sum of any split of `numChars` equals to the target. + bool isPossible(int accumulate, int running, const string& numChars, int s, + int target) { + if (s == numChars.length()) + return target == accumulate + running; + const int d = numChars[s] - '0'; + return isPossible(accumulate, running * 10 + d, numChars, s + 1, target) || + isPossible(accumulate + running, d, numChars, s + 1, target); + } +}; diff --git a/solutions/2698. Find the Punishment Number of an Integer/2698.java b/solutions/2698. Find the Punishment Number of an Integer/2698.java new file mode 100644 index 00000000000..faf844a532d --- /dev/null +++ b/solutions/2698. Find the Punishment Number of an Integer/2698.java @@ -0,0 +1,19 @@ +public class Solution { + public int punishmentNumber(int n) { + int ans = 0; + for (int i = 1; i <= n; ++i) + if (isPossible(0, 0, String.valueOf(i * i), 0, i)) + ans += i * i; + + return ans; + } + + // Returns true if the sum of any split of `numChars` equals to the target. + private boolean isPossible(int accumulate, int running, String numChars, int s, int target) { + if (s == numChars.length()) + return target == accumulate + running; + final int d = numChars.charAt(s) - '0'; + return isPossible(accumulate, running * 10 + d, numChars, s + 1, target) || + isPossible(accumulate + running, d, numChars, s + 1, target); + } +} diff --git a/solutions/2698. Find the Punishment Number of an Integer/2698.py b/solutions/2698. Find the Punishment Number of an Integer/2698.py new file mode 100644 index 00000000000..a75a96a214d --- /dev/null +++ b/solutions/2698. Find the Punishment Number of an Integer/2698.py @@ -0,0 +1,19 @@ +class Solution: + def punishmentNumber(self, n: int) -> int: + def isPossible(accumulate: int, running: int, numChars: List[str], s: int, target: int) -> bool: + """ + Returns True if the sum of any split of `numChars` equals to the target. + """ + if s == len(numChars): + return target == accumulate + running + d = int(numChars[s]) + return ( + # Keep growing `running`. + isPossible(accumulate, running * 10 + d, numChars, s + 1, target) or + # Start a new `running`. + isPossible(accumulate + running, d, numChars, s + 1, target) + ) + + return sum(i * i + for i in range(1, n + 1) + if isPossible(0, 0, str(i * i), 0, i)) diff --git a/solutions/2699. Modify Graph Edge Weights/2699.cpp b/solutions/2699. Modify Graph Edge Weights/2699.cpp new file mode 100644 index 00000000000..9941bff3651 --- /dev/null +++ b/solutions/2699. Modify Graph Edge Weights/2699.cpp @@ -0,0 +1,76 @@ +class Solution { + public: + vector> modifiedGraphEdges(int n, vector>& edges, + int source, int destination, + int target) { + constexpr int kMax = 2'000'000'000; + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + if (w == -1) + continue; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + int distToDestination = dijkstra(graph, source, destination); + if (distToDestination < target) + return {}; + if (distToDestination == target) { + // Change the weights of negative edges to an impossible value. + for (vector& edge : edges) + if (edge[2] == -1) + edge[2] = kMax; + return edges; + } + + for (int i = 0; i < edges.size(); ++i) { + const int u = edges[i][0]; + const int v = edges[i][1]; + int& w = edges[i][2]; + if (w != -1) + continue; + w = 1; + graph[u].emplace_back(v, 1); + graph[v].emplace_back(u, 1); + distToDestination = dijkstra(graph, source, destination); + if (distToDestination <= target) { + w += target - distToDestination; + // Change the weights of negative edges to an impossible value. + for (int j = i + 1; j < edges.size(); ++j) + if (edges[j][2] == -1) + edges[j][2] = kMax; + return edges; + } + } + + return {}; + } + + private: + int dijkstra(const vector>>& graph, int src, int dst) { + vector dist(graph.size(), INT_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + } + + return dist[dst]; + } +}; diff --git a/solutions/2699. Modify Graph Edge Weights/2699.java b/solutions/2699. Modify Graph Edge Weights/2699.java new file mode 100644 index 00000000000..86b90feed18 --- /dev/null +++ b/solutions/2699. Modify Graph Edge Weights/2699.java @@ -0,0 +1,79 @@ +class Solution { + public int[][] modifiedGraphEdges(int n, int[][] edges, int source, int destination, int target) { + final int kMax = 2_000_000_000; + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + if (w == -1) + continue; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + int distToDestination = dijkstra(graph, source, destination); + if (distToDestination < target) + return new int[0][]; + if (distToDestination == target) { + // Change the weights of negative edges to an impossible value. + for (int[] edge : edges) + if (edge[2] == -1) + edge[2] = kMax; + return edges; + } + + for (int i = 0; i < edges.length; ++i) { + final int u = edges[i][0]; + final int v = edges[i][1]; + final int w = edges[i][2]; + if (w != -1) + continue; + edges[i][2] = 1; + graph[u].add(new Pair<>(v, 1)); + graph[v].add(new Pair<>(u, 1)); + distToDestination = dijkstra(graph, source, destination); + if (distToDestination <= target) { + edges[i][2] += target - distToDestination; + // Change the weights of negative edges to an impossible value. + for (int j = i + 1; j < edges.length; ++j) + if (edges[j][2] == -1) + edges[j][2] = kMax; + return edges; + } + } + + return new int[0][]; + } + + private int dijkstra(List>[] graph, int src, int dst) { + int[] dist = new int[graph.length]; + Arrays.fill(dist, Integer.MAX_VALUE); + // (d, u) + Queue> minHeap = new PriorityQueue<>((a, b) -> a.getKey() - b.getKey()); + + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + return dist[dst]; + } +} diff --git a/solutions/2699. Modify Graph Edge Weights/2699.py b/solutions/2699. Modify Graph Edge Weights/2699.py new file mode 100644 index 00000000000..df20700a1dc --- /dev/null +++ b/solutions/2699. Modify Graph Edge Weights/2699.py @@ -0,0 +1,56 @@ + +class Solution: + def modifiedGraphEdges(self, n: int, edges: List[List[int]], source: int, destination: int, target: int) -> List[List[int]]: + kMax = 2_000_000_000 + graph = [[] for _ in range(n)] + + for u, v, w in edges: + if w == -1: + continue + graph[u].append((v, w)) + graph[v].append((u, w)) + + distToDestination = self._dijkstra(graph, source, destination) + if distToDestination < target: + return [] + if distToDestination == target: + # Change the weights of negative edges to an impossible value. + for edge in edges: + if edge[2] == -1: + edge[2] = kMax + return edges + + for i, (u, v, w) in enumerate(edges): + if w != -1: + continue + edges[i][2] = 1 + graph[u].append((v, 1)) + graph[v].append((u, 1)) + distToDestination = self._dijkstra(graph, source, destination) + if distToDestination <= target: + edges[i][2] += target - distToDestination + # Change the weights of negative edges to an impossible value. + for j in range(i + 1, len(edges)): + if edges[j][2] == -1: + edges[j][2] = kMax + return edges + + return [] + + def _dijkstra(self, graph: List[List[int]], src: int, dst: int) -> int: + dist = [math.inf] * len(graph) + minHeap = [] # (d, u) + + dist[src] = 0 + heapq.heappush(minHeap, (dist[src], src)) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + + return dist[dst] diff --git a/solutions/27. Remove Element/27.cpp b/solutions/27. Remove Element/27.cpp new file mode 100644 index 00000000000..c3e54f64899 --- /dev/null +++ b/solutions/27. Remove Element/27.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int removeElement(vector& nums, int val) { + int i = 0; + + for (const int num : nums) + if (num != val) + nums[i++] = num; + + return i; + } +}; diff --git a/solutions/27. Remove Element/27.java b/solutions/27. Remove Element/27.java new file mode 100644 index 00000000000..a50a336b6bb --- /dev/null +++ b/solutions/27. Remove Element/27.java @@ -0,0 +1,11 @@ +class Solution { + public int removeElement(int[] nums, int val) { + int i = 0; + + for (final int num : nums) + if (num != val) + nums[i++] = num; + + return i; + } +} diff --git a/solutions/27. Remove Element/27.py b/solutions/27. Remove Element/27.py new file mode 100644 index 00000000000..9700bb7cce1 --- /dev/null +++ b/solutions/27. Remove Element/27.py @@ -0,0 +1,10 @@ +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + i = 0 + + for num in nums: + if num != val: + nums[i] = num + i += 1 + + return i diff --git a/solutions/270. Closest Binary Search Tree Value/270.cpp b/solutions/270. Closest Binary Search Tree Value/270.cpp new file mode 100644 index 00000000000..39b1c75de32 --- /dev/null +++ b/solutions/270. Closest Binary Search Tree Value/270.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int closestValue(TreeNode* root, double target) { + // If target < root->val, search the left subtree. + if (target < root->val && root->left) { + const int left = closestValue(root->left, target); + if (abs(left - target) <= abs(root->val - target)) + return left; + } + + // If target > root->val, search the right subtree. + if (target > root->val && root->right) { + const int right = closestValue(root->right, target); + if (abs(right - target) < abs(root->val - target)) + return right; + } + + return root->val; + } +}; diff --git a/solutions/270. Closest Binary Search Tree Value/270.java b/solutions/270. Closest Binary Search Tree Value/270.java new file mode 100644 index 00000000000..028857bad5b --- /dev/null +++ b/solutions/270. Closest Binary Search Tree Value/270.java @@ -0,0 +1,19 @@ +class Solution { + public int closestValue(TreeNode root, double target) { + // If target < root.val, search the left subtree. + if (target < root.val && root.left != null) { + final int left = closestValue(root.left, target); + if (Math.abs(left - target) <= Math.abs(root.val - target)) + return left; + } + + // If target > root.val, search the right subtree. + if (target > root.val && root.right != null) { + final int right = closestValue(root.right, target); + if (Math.abs(right - target) < Math.abs(root.val - target)) + return right; + } + + return root.val; + } +} diff --git a/solutions/270. Closest Binary Search Tree Value/270.py b/solutions/270. Closest Binary Search Tree Value/270.py new file mode 100644 index 00000000000..5fad40b1977 --- /dev/null +++ b/solutions/270. Closest Binary Search Tree Value/270.py @@ -0,0 +1,15 @@ +class Solution: + def closestValue(self, root: Optional[TreeNode], target: float) -> int: + # If target < root.val, search the left subtree. + if target < root.val and root.left: + left = self.closestValue(root.left, target) + if abs(left - target) <= abs(root.val - target): + return left + + # If target > root.val, search the right subtree. + if target > root.val and root.right: + right = self.closestValue(root.right, target) + if abs(right - target) < abs(root.val - target): + return right + + return root.val diff --git a/solutions/2700. Differences Between Two Objects/2700.ts b/solutions/2700. Differences Between Two Objects/2700.ts new file mode 100644 index 00000000000..d082832aec9 --- /dev/null +++ b/solutions/2700. Differences Between Two Objects/2700.ts @@ -0,0 +1,33 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Obj = Record | Array; + +function objDiff(obj1: Obj, obj2: Obj): Obj { + if (obj1 === obj2) { + return {}; + } + if (obj1 === null || obj2 === null) { + return [obj1, obj2]; + } + if (typeof obj1 !== 'object' || typeof obj2 !== 'object') { + return [obj1, obj2]; + } + if (Array.isArray(obj1) !== Array.isArray(obj2)) { + return [obj1, obj2]; + } + const ans = {}; + for (const key in obj1) { + if (key in obj2) { + const subDiff = objDiff(obj1[key], obj2[key]); + if (Object.keys(subDiff).length > 0) { + ans[key] = subDiff; + } + } + } + return ans; +} diff --git a/solutions/2701. Consecutive Transactions with Increasing Amounts/2701.sql b/solutions/2701. Consecutive Transactions with Increasing Amounts/2701.sql new file mode 100644 index 00000000000..0ad442cb61c --- /dev/null +++ b/solutions/2701. Consecutive Transactions with Increasing Amounts/2701.sql @@ -0,0 +1,36 @@ +WITH + IncreasingTransactions AS ( + SELECT + Curr.customer_id, + Curr.transaction_date + FROM Transactions AS Curr + LEFT JOIN Transactions AS Next + USING (customer_id) + WHERE + Curr.amount < Next.amount + AND DATEDIFF(Next.transaction_date, Curr.transaction_date) = 1 + ), + IncreasingTransactionsWithGroupId AS ( + SELECT + *, + TO_DAYS(transaction_date) - ROW_NUMBER() OVER( + PARTITION BY customer_id + ORDER BY transaction_date + ) AS group_id + FROM IncreasingTransactions + ), + IncreasingTransactionsWithCountDays AS ( + SELECT + customer_id, + MIN(transaction_date) AS consecutive_start, + COUNT(*) AS count_days + FROM IncreasingTransactionsWithGroupId + GROUP BY customer_id, group_id + ) +SELECT + customer_id, + consecutive_start, + DATE_ADD(consecutive_start, INTERVAL count_days DAY) AS consecutive_end +FROM IncreasingTransactionsWithCountDays +WHERE count_days >= 2 +ORDER BY 1; diff --git a/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.cpp b/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.cpp new file mode 100644 index 00000000000..21525dbc485 --- /dev/null +++ b/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minOperations(vector& nums, int x, int y) { + int l = 0; + int r = ranges::max(nums); + + while (l < r) { + const int m = (l + r) / 2; + if (isPossible(nums, x, y, m)) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Returns true if it's possible to make all `nums` <= 0 using m operations. + bool isPossible(const vector& nums, int x, int y, int m) { + long additionalOps = 0; + // If we want m operations, first decrease all the numbers by y * m. Then, + // we have m operations to select indices to decrease them by x - y. + for (const int num : nums) + additionalOps += + max(0L, (num - static_cast(y) * m + x - y - 1) / (x - y)); + return additionalOps <= m; + } +}; diff --git a/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.java b/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.java new file mode 100644 index 00000000000..92686f70890 --- /dev/null +++ b/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.java @@ -0,0 +1,26 @@ +class Solution { + public int minOperations(int[] nums, int x, int y) { + int l = 0; + int r = Arrays.stream(nums).max().getAsInt(); + + while (l < r) { + final int m = (l + r) / 2; + if (isPossible(nums, x, y, m)) + r = m; + else + l = m + 1; + } + + return l; + } + + // Returns true if it's possible to make all `nums` <= 0 using m operations. + private boolean isPossible(int[] nums, int x, int y, int m) { + long additionalOps = 0; + // If we want m operations, first decrease all the numbers by y * m. Then, + // we have m operations to select indices to decrease them by x - y. + for (final int num : nums) + additionalOps += Math.max(0L, (num - 1L * y * m + x - y - 1) / (x - y)); + return additionalOps <= m; + } +} diff --git a/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.py b/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.py new file mode 100644 index 00000000000..bf597516830 --- /dev/null +++ b/solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.py @@ -0,0 +1,13 @@ +class Solution: + def minOperations(self, nums: list[int], x: int, y: int) -> int: + def isPossible(m: int) -> bool: + """ + Returns True if it's possible to make all `nums` <= 0 using m operations. + """ + # If we want m operations, first decrease all the numbers by y * m. Then + # we have m operations to select indices to decrease them by x - y. + return sum(max(0, math.ceil((num - y * m) / (x - y))) + for num in nums) <= m + + return bisect.bisect_left(range(max(nums)), True, + key=isPossible) diff --git a/solutions/2703. Return Length of Arguments Passed/2703.ts b/solutions/2703. Return Length of Arguments Passed/2703.ts new file mode 100644 index 00000000000..715170f1662 --- /dev/null +++ b/solutions/2703. Return Length of Arguments Passed/2703.ts @@ -0,0 +1,11 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +function argumentsLength(...args: JSONValue[]): number { + return args.length; +} diff --git a/solutions/2704. To Be Or Not To Be/2704.ts b/solutions/2704. To Be Or Not To Be/2704.ts new file mode 100644 index 00000000000..eaceaac1ddf --- /dev/null +++ b/solutions/2704. To Be Or Not To Be/2704.ts @@ -0,0 +1,21 @@ +type ToBeOrNotToBe = { + toBe: (val: any) => boolean; + notToBe: (val: any) => boolean; +}; + +function expect(val: any): ToBeOrNotToBe { + return { + toBe: function (val2: any) { + if (val === val2) { + return true; + } + throw 'Not Equal'; + }, + notToBe: function (val2: any) { + if (val !== val2) { + return true; + } + throw 'Equal'; + }, + }; +} diff --git a/solutions/2705. Compact Object/2705.ts b/solutions/2705. Compact Object/2705.ts new file mode 100644 index 00000000000..5b0bda9cd8b --- /dev/null +++ b/solutions/2705. Compact Object/2705.ts @@ -0,0 +1,31 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Obj = Record | Array; + +function compactObject(obj: Obj): Obj { + return dfs(obj) as Obj; +} + +function dfs(value: JSONValue): JSONValue { + if (value === null) { + return null; + } + if (Array.isArray(value)) { + return value.filter(Boolean).map(dfs); + } + if (typeof value === 'object') { + for (const key of Object.keys(value)) { + if (Boolean(value[key])) { + value[key] = dfs(value[key]); + } else { + delete value[key]; + } + } + } + return value; +} diff --git a/solutions/2706. Buy Two Chocolates/2706.cpp b/solutions/2706. Buy Two Chocolates/2706.cpp new file mode 100644 index 00000000000..dc9db241998 --- /dev/null +++ b/solutions/2706. Buy Two Chocolates/2706.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int buyChoco(vector& prices, int money) { + int min1 = INT_MAX; + int min2 = INT_MAX; + + for (const int price : prices) + if (price <= min1) { + min2 = min1; + min1 = price; + } else if (price < min2) { + min2 = price; + } + + const int minCost = min1 + min2; + return minCost > money ? money : money - minCost; + } +}; diff --git a/solutions/2706. Buy Two Chocolates/2706.java b/solutions/2706. Buy Two Chocolates/2706.java new file mode 100644 index 00000000000..65ad047e6f6 --- /dev/null +++ b/solutions/2706. Buy Two Chocolates/2706.java @@ -0,0 +1,17 @@ +class Solution { + public int buyChoco(int[] prices, int money) { + int min1 = Integer.MAX_VALUE; + int min2 = Integer.MAX_VALUE; + + for (final int price : prices) + if (price <= min1) { + min2 = min1; + min1 = price; + } else if (price < min2) { + min2 = price; + } + + final int minCost = min1 + min2; + return minCost > money ? money : money - minCost; + } +} diff --git a/solutions/2706. Buy Two Chocolates/2706.py b/solutions/2706. Buy Two Chocolates/2706.py new file mode 100644 index 00000000000..db98bce87ec --- /dev/null +++ b/solutions/2706. Buy Two Chocolates/2706.py @@ -0,0 +1,14 @@ +class Solution: + def buyChoco(self, prices: List[int], money: int) -> int: + min1 = math.inf + min2 = math.inf + + for price in prices: + if price <= min1: + min2 = min1 + min1 = price + elif price < min2: + min2 = price + + minCost = min1 + min2 + return money if minCost > money else money - minCost diff --git a/solutions/2707. Extra Characters in a String/2707.cpp b/solutions/2707. Extra Characters in a String/2707.cpp new file mode 100644 index 00000000000..e599813569e --- /dev/null +++ b/solutions/2707. Extra Characters in a String/2707.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + // Similar to 139. Word Break + int minExtraChar(string s, vector& dictionary) { + const int n = s.length(); + const unordered_set dictionarySet{dictionary.begin(), + dictionary.end()}; + // dp[i] := the minimum extra letters if breaking up s[0..i) optimally + vector dp(n + 1, n); + dp[0] = 0; + + for (int i = 1; i <= n; ++i) + for (int j = 0; j < i; ++j) + // s[j..i) is in `dictionarySet`. + if (dictionarySet.contains(s.substr(j, i - j))) + dp[i] = min(dp[i], dp[j]); + // s[j..i) are extra letters. + else + dp[i] = min(dp[i], dp[j] + i - j); + + return dp[n]; + } +}; diff --git a/solutions/2707. Extra Characters in a String/2707.java b/solutions/2707. Extra Characters in a String/2707.java new file mode 100644 index 00000000000..9c123555361 --- /dev/null +++ b/solutions/2707. Extra Characters in a String/2707.java @@ -0,0 +1,22 @@ +class Solution { + // Similar to 139. Word Break + public int minExtraChar(String s, String[] dictionary) { + final int n = s.length(); + Set dictionarySet = new HashSet<>(Arrays.asList(dictionary)); + // dp[i] := the minimum extra letters if breaking up s[0..i) optimally + int[] dp = new int[n + 1]; + Arrays.fill(dp, n); + dp[0] = 0; + + for (int i = 1; i <= n; i++) + for (int j = 0; j < i; j++) + // s[j..i) is in `dictionarySet`. + if (dictionarySet.contains(s.substring(j, i))) + dp[i] = Math.min(dp[i], dp[j]); + // s[j..i) are extra letters. + else + dp[i] = Math.min(dp[i], dp[j] + i - j); + + return dp[n]; + } +} diff --git a/solutions/2707. Extra Characters in a String/2707.py b/solutions/2707. Extra Characters in a String/2707.py new file mode 100644 index 00000000000..b12b92ec1b2 --- /dev/null +++ b/solutions/2707. Extra Characters in a String/2707.py @@ -0,0 +1,16 @@ +class Solution: + # Similar to 139. Word Break + def minExtraChar(self, s: str, dictionary: List[str]) -> int: + n = len(s) + dictionarySet = set(dictionary) + # dp[i] := the minimum extra letters if breaking up s[0..i) optimally + dp = [0] + [n] * n + + for i in range(1, n + 1): + for j in range(i): + if s[j:i] in dictionarySet: + dp[i] = min(dp[i], dp[j]) + else: + dp[i] = min(dp[i], dp[j] + i - j) + + return dp[n] diff --git a/solutions/2708. Maximum Strength of a Group/2708.cpp b/solutions/2708. Maximum Strength of a Group/2708.cpp new file mode 100644 index 00000000000..58773985cb2 --- /dev/null +++ b/solutions/2708. Maximum Strength of a Group/2708.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + long long maxStrength(vector& nums) { + long posProd = 1; + long negProd = 1; + int maxNeg = INT_MIN; + int negCount = 0; + bool hasPos = false; + bool hasZero = false; + + for (const int num : nums) + if (num > 0) { + posProd *= num; + hasPos = true; + } else if (num < 0) { + negProd *= num; + maxNeg = max(maxNeg, num); + ++negCount; + } else { // num == 0 + hasZero = true; + } + + if (negCount == 0 && !hasPos) + return 0; + if (negCount % 2 == 0) + return negProd * posProd; + if (negCount >= 3) + return negProd / maxNeg * posProd; + if (hasPos) + return posProd; + if (hasZero) + return 0; + return maxNeg; + } +}; diff --git a/solutions/2708. Maximum Strength of a Group/2708.java b/solutions/2708. Maximum Strength of a Group/2708.java new file mode 100644 index 00000000000..3d1d4f25592 --- /dev/null +++ b/solutions/2708. Maximum Strength of a Group/2708.java @@ -0,0 +1,34 @@ +class Solution { + public long maxStrength(int[] nums) { + long posProd = 1; + long negProd = 1; + int maxNeg = Integer.MIN_VALUE; + int negCount = 0; + boolean hasPos = false; + boolean hasZero = false; + + for (final int num : nums) + if (num > 0) { + posProd *= num; + hasPos = true; + } else if (num < 0) { + negProd *= num; + maxNeg = Math.max(maxNeg, num); + ++negCount; + } else { // num == 0 + hasZero = true; + } + + if (negCount == 0 && !hasPos) + return 0; + if (negCount % 2 == 0) + return negProd * posProd; + if (negCount >= 3) + return negProd / maxNeg * posProd; + if (hasPos) + return posProd; + if (hasZero) + return 0; + return maxNeg; + } +} diff --git a/solutions/2708. Maximum Strength of a Group/2708.py b/solutions/2708. Maximum Strength of a Group/2708.py new file mode 100644 index 00000000000..b001ed4eb8b --- /dev/null +++ b/solutions/2708. Maximum Strength of a Group/2708.py @@ -0,0 +1,31 @@ +class Solution: + def maxStrength(self, nums: List[int]) -> int: + posProd = 1 + negProd = 1 + maxNeg = -math.inf + negCount = 0 + hasPos = False + hasZero = False + + for num in nums: + if num > 0: + posProd *= num + hasPos = True + elif num < 0: + negProd *= num + maxNeg = max(maxNeg, num) + negCount += 1 + else: # num == 0 + hasZero = True + + if negCount == 0 and not hasPos: + return 0 + if negCount % 2 == 0: + return negProd * posProd + if negCount >= 3: + return negProd // maxNeg * posProd + if hasPos: + return posProd + if hasZero: + return 0 + return maxNeg diff --git a/solutions/2709. Greatest Common Divisor Traversal/2709.cpp b/solutions/2709. Greatest Common Divisor Traversal/2709.cpp new file mode 100644 index 00000000000..a8923bc2e41 --- /dev/null +++ b/solutions/2709. Greatest Common Divisor Traversal/2709.cpp @@ -0,0 +1,81 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), sz(n, 1) { + iota(id.begin(), id.end(), 0); + } + + void unionBySize(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (sz[i] < sz[j]) { + sz[j] += sz[i]; + id[i] = j; + } else { + sz[i] += sz[j]; + id[j] = i; + } + } + + int getSize(int i) { + return sz[i]; + } + + private: + vector id; + vector sz; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + bool canTraverseAllPairs(vector& nums) { + const int n = nums.size(); + const int maxNum = ranges::max(nums); + const vector minPrimeFactors = sieveEratosthenes(maxNum + 1); + unordered_map primeToFirstIndex; + UnionFind uf(n); + + for (int i = 0; i < n; ++i) + for (const int primeFactor : getPrimeFactors(nums[i], minPrimeFactors)) + // `primeFactor` already appeared in the previous indices. + if (const auto it = primeToFirstIndex.find(primeFactor); + it != primeToFirstIndex.cend()) + uf.unionBySize(it->second, i); + else + primeToFirstIndex[primeFactor] = i; + + for (int i = 0; i < n; ++i) + if (uf.getSize(i) == n) + return true; + + return false; + } + + private: + // Gets the minimum prime factor of i, where 1 < i <= n. + vector sieveEratosthenes(int n) { + vector minPrimeFactors(n + 1); + iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + vector getPrimeFactors(int num, const vector& minPrimeFactors) { + vector primeFactors; + while (num > 1) { + const int divisor = minPrimeFactors[num]; + primeFactors.push_back(divisor); + while (num % divisor == 0) + num /= divisor; + } + return primeFactors; + } +}; diff --git a/solutions/2709. Greatest Common Divisor Traversal/2709.java b/solutions/2709. Greatest Common Divisor Traversal/2709.java new file mode 100644 index 00000000000..cd67b9c84a9 --- /dev/null +++ b/solutions/2709. Greatest Common Divisor Traversal/2709.java @@ -0,0 +1,81 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + sz = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + for (int i = 0; i < n; ++i) + sz[i] = 1; + } + + public void unionBySize(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (sz[i] < sz[j]) { + sz[j] += sz[i]; + id[i] = j; + } else { + sz[i] += sz[j]; + id[j] = i; + } + } + + public int getSize(int i) { + return sz[i]; + } + + private int[] id; + private int[] sz; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public boolean canTraverseAllPairs(int[] nums) { + final int n = nums.length; + final int maxNum = Arrays.stream(nums).max().getAsInt(); + final int[] minPrimeFactors = sieveEratosthenes(maxNum + 1); + Map primeToFirstIndex = new HashMap<>(); + UnionFind uf = new UnionFind(n); + + for (int i = 0; i < n; ++i) + for (final int primeFactor : getPrimeFactors(nums[i], minPrimeFactors)) + // `primeFactor` already appeared in the previous indices. + if (primeToFirstIndex.containsKey(primeFactor)) + uf.unionBySize(primeToFirstIndex.get(primeFactor), i); + else + primeToFirstIndex.put(primeFactor, i); + + for (int i = 0; i < n; ++i) + if (uf.getSize(i) == n) + return true; + return false; + } + + // Gets the minimum prime factor of i, where 1 < i <= n. + private int[] sieveEratosthenes(int n) { + int[] minPrimeFactors = new int[n + 1]; + for (int i = 2; i <= n; ++i) + minPrimeFactors[i] = i; + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + private List getPrimeFactors(int num, int[] minPrimeFactors) { + List primeFactors = new ArrayList<>(); + while (num > 1) { + final int divisor = minPrimeFactors[num]; + primeFactors.add(divisor); + while (num % divisor == 0) + num /= divisor; + } + return primeFactors; + } +} diff --git a/solutions/2709. Greatest Common Divisor Traversal/2709.py b/solutions/2709. Greatest Common Divisor Traversal/2709.py new file mode 100644 index 00000000000..edc2bfadf8d --- /dev/null +++ b/solutions/2709. Greatest Common Divisor Traversal/2709.py @@ -0,0 +1,60 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.sz = [1] * n + + def unionBySize(self, u: int, v: int) -> None: + i = self._find(u) + j = self._find(v) + if i == j: + return + if self.sz[i] < self.sz[j]: + self.sz[j] += self.sz[i] + self.id[i] = j + else: + self.sz[i] += self.sz[j] + self.id[j] = i + + def getSize(self, i: int) -> int: + return self.sz[i] + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def canTraverseAllPairs(self, nums: List[int]) -> bool: + n = len(nums) + max_num = max(nums) + maxPrimeFactor = self._sieveEratosthenes(max_num + 1) + primeToFirstIndex = collections.defaultdict(int) + uf = UnionFind(n) + + for i, num in enumerate(nums): + for prime_factor in self._getPrimeFactors(num, maxPrimeFactor): + if prime_factor in primeToFirstIndex: + uf.unionBySize(primeToFirstIndex[prime_factor], i) + else: + primeToFirstIndex[prime_factor] = i + + return any(uf.getSize(i) == n for i in range(n)) + + def _sieveEratosthenes(self, n: int) -> List[int]: + """Gets the minimum prime factor of i, where 1 < i <= n.""" + minPrimeFactors = [i for i in range(n + 1)] + for i in range(2, int(n**0.5) + 1): + if minPrimeFactors[i] == i: # `i` is prime. + for j in range(i * i, n, i): + minPrimeFactors[j] = min(minPrimeFactors[j], i) + return minPrimeFactors + + def _getPrimeFactors(self, num: int, minPrimeFactors: List[int]) -> List[int]: + primeFactors = [] + while num > 1: + divisor = minPrimeFactors[num] + primeFactors.append(divisor) + while num % divisor == 0: + num //= divisor + return primeFactors diff --git a/solutions/271. Encode and Decode Strings/271.cpp b/solutions/271. Encode and Decode Strings/271.cpp new file mode 100644 index 00000000000..6b2c2d10904 --- /dev/null +++ b/solutions/271. Encode and Decode Strings/271.cpp @@ -0,0 +1,26 @@ +class Codec { + public: + // Encodes a list of strings to a single string. + string encode(vector& strs) { + string encoded; + + for (const string& s : strs) + encoded += to_string(s.length()) + '/' + s; + + return encoded; + } + + // Decodes a single string to a list of strings. + vector decode(string s) { + vector decoded; + + for (int i = 0; i < s.length();) { + const int slash = s.find('/', i); + const int length = stoi(s.substr(i, slash - i)); + i = slash + length + 1; + decoded.push_back(s.substr(slash + 1, i - slash - 1)); + } + + return decoded; + } +}; diff --git a/solutions/271. Encode and Decode Strings/271.java b/solutions/271. Encode and Decode Strings/271.java new file mode 100644 index 00000000000..627d55600ff --- /dev/null +++ b/solutions/271. Encode and Decode Strings/271.java @@ -0,0 +1,25 @@ +public class Codec { + // Encodes a list of strings to a single string. + public String encode(List strs) { + StringBuilder encoded = new StringBuilder(); + + for (final String s : strs) + encoded.append(s.length()).append('/').append(s); + + return encoded.toString(); + } + + // Decodes a single string to a list of strings. + public List decode(String s) { + List decoded = new ArrayList<>(); + + for (int i = 0; i < s.length();) { + final int slash = s.indexOf('/', i); + final int length = Integer.parseInt(s.substring(i, slash)); + i = slash + length + 1; + decoded.add(s.substring(slash + 1, i)); + } + + return decoded; + } +} diff --git a/solutions/271. Encode and Decode Strings/271.py b/solutions/271. Encode and Decode Strings/271.py new file mode 100644 index 00000000000..6419f663d7f --- /dev/null +++ b/solutions/271. Encode and Decode Strings/271.py @@ -0,0 +1,17 @@ +class Codec: + def encode(self, strs: List[str]) -> str: + """Encodes a list of strings to a single string.""" + return ''.join(str(len(s)) + '/' + s for s in strs) + + def decode(self, s: str) -> List[str]: + """Decodes a single string to a list of strings.""" + decoded = [] + + i = 0 + while i < len(s): + slash = s.find('/', i) + length = int(s[i:slash]) + i = slash + length + 1 + decoded.append(s[slash + 1:i]) + + return decoded diff --git a/solutions/2710. Remove Trailing Zeros From a String/2710.cpp b/solutions/2710. Remove Trailing Zeros From a String/2710.cpp new file mode 100644 index 00000000000..d4b4bd26a0a --- /dev/null +++ b/solutions/2710. Remove Trailing Zeros From a String/2710.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + string removeTrailingZeros(string num) { + return regex_replace(num, regex("0+$"), ""); + } +}; diff --git a/solutions/2710. Remove Trailing Zeros From a String/2710.java b/solutions/2710. Remove Trailing Zeros From a String/2710.java new file mode 100644 index 00000000000..1cd05494673 --- /dev/null +++ b/solutions/2710. Remove Trailing Zeros From a String/2710.java @@ -0,0 +1,5 @@ +class Solution { + public String removeTrailingZeros(String num) { + return num.replaceAll("0+$", ""); + } +} diff --git a/solutions/2710. Remove Trailing Zeros From a String/2710.py b/solutions/2710. Remove Trailing Zeros From a String/2710.py new file mode 100644 index 00000000000..2c78f4813f6 --- /dev/null +++ b/solutions/2710. Remove Trailing Zeros From a String/2710.py @@ -0,0 +1,3 @@ +class Solution: + def removeTrailingZeros(self, num: str) -> str: + return num.rstrip('0') diff --git a/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.cpp b/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.cpp new file mode 100644 index 00000000000..224eda54ea3 --- /dev/null +++ b/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + vector> differenceOfDistinctValues(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector> ans(m, vector(n)); + + for (int i = 0; i < m; ++i) + fillInDiagonal(grid, i, 0, ans); + + for (int j = 1; j < n; ++j) + fillInDiagonal(grid, 0, j, ans); + + return ans; + } + + private: + void fillInDiagonal(const vector>& grid, int i, int j, + vector>& ans) { + unordered_set topLeft; + unordered_set bottomRight; + + // Fill in the diagonal from the top-left to the bottom-right. + while (i < grid.size() && j < grid[0].size()) { + ans[i][j] = topLeft.size(); + // Post-addition, so this information can be utilized in subsequent cells. + topLeft.insert(grid[i++][j++]); + } + + --i; + --j; + + // Fill in the diagonal from the bottom-right to the top-left. + while (i >= 0 && j >= 0) { + ans[i][j] = abs(ans[i][j] - static_cast(bottomRight.size())); + // Post-addition, so this information can be utilized in subsequent cells. + bottomRight.insert(grid[i--][j--]); + } + } +}; diff --git a/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.java b/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.java new file mode 100644 index 00000000000..1e61c26fb4b --- /dev/null +++ b/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.java @@ -0,0 +1,37 @@ +class Solution { + public int[][] differenceOfDistinctValues(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[][] ans = new int[m][n]; + + for (int i = 0; i < m; ++i) + fillInDiagonal(grid, i, 0, ans); + + for (int j = 1; j < n; ++j) + fillInDiagonal(grid, 0, j, ans); + + return ans; + } + + private void fillInDiagonal(int[][] grid, int i, int j, int[][] ans) { + Set topLeft = new HashSet<>(); + Set bottomRight = new HashSet<>(); + + // Fill in the diagonal from the top-left to the bottom-right. + while (i < grid.length && j < grid[0].length) { + ans[i][j] = topLeft.size(); + // Post-addition, so this information can be utilized in subsequent cells. + topLeft.add(grid[i++][j++]); + } + + --i; + --j; + + // Fill in the diagonal from the bottom-right to the top-left. + while (i >= 0 && j >= 0) { + ans[i][j] = Math.abs(ans[i][j] - bottomRight.size()); + // Post-addition, so this information can be utilized in subsequent cells. + bottomRight.add(grid[i--][j--]); + } + } +} diff --git a/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.py b/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.py new file mode 100644 index 00000000000..0a151e14d78 --- /dev/null +++ b/solutions/2711. Difference of Number of Distinct Values on Diagonals/2711.py @@ -0,0 +1,36 @@ +class Solution: + def differenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]: + m = len(grid) + n = len(grid[0]) + ans = [[0] * n for _ in range(m)] + + def fillInDiagonal(i: int, j: int) -> None: + topLeft = set() + bottomRight = set() + + # Fill in the diagonal from the top-left to the bottom-right. + while i < len(grid) and j < len(grid[0]): + ans[i][j] = len(topLeft) + # Post-addition, so this information can be utilized in subsequent cells. + topLeft.add(grid[i][j]) + i += 1 + j += 1 + + i -= 1 + j -= 1 + + # Fill in the diagonal from the bottom-right to the top-left. + while i >= 0 and j >= 0: + ans[i][j] = abs(ans[i][j] - len(bottomRight)) + # Post-addition, so this information can be utilized in subsequent cells. + bottomRight.add(grid[i][j]) + i -= 1 + j -= 1 + + for i in range(m): + fillInDiagonal(i, 0) + + for j in range(1, n): + fillInDiagonal(0, j) + + return ans diff --git a/solutions/2712. Minimum Cost to Make All Characters Equal/2712.cpp b/solutions/2712. Minimum Cost to Make All Characters Equal/2712.cpp new file mode 100644 index 00000000000..6cae1473aee --- /dev/null +++ b/solutions/2712. Minimum Cost to Make All Characters Equal/2712.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long minimumCost(string s) { + const int n = s.length(); + long ans = 0; + + for (int i = 1; i < n; ++i) + if (s[i] != s[i - 1]) + // Invert s[0..i - 1] or s[i..n - 1]. + ans += min(i, n - i); + + return ans; + } +}; diff --git a/solutions/2712. Minimum Cost to Make All Characters Equal/2712.java b/solutions/2712. Minimum Cost to Make All Characters Equal/2712.java new file mode 100644 index 00000000000..83741fcf178 --- /dev/null +++ b/solutions/2712. Minimum Cost to Make All Characters Equal/2712.java @@ -0,0 +1,13 @@ +class Solution { + public long minimumCost(String s) { + final int n = s.length(); + long ans = 0; + + for (int i = 1; i < n; ++i) + if (s.charAt(i) != s.charAt(i - 1)) + // Invert s[0..i - 1] or s[i..n - 1]. + ans += Math.min(i, n - i); + + return ans; + } +} diff --git a/solutions/2712. Minimum Cost to Make All Characters Equal/2712.py b/solutions/2712. Minimum Cost to Make All Characters Equal/2712.py new file mode 100644 index 00000000000..859c9805921 --- /dev/null +++ b/solutions/2712. Minimum Cost to Make All Characters Equal/2712.py @@ -0,0 +1,11 @@ +class Solution: + def minimumCost(self, s: str) -> int: + n = len(s) + ans = 0 + + for i in range(1, n): + if s[i] != s[i - 1]: + # Invert s[0..i - 1] or s[i..n - 1]. + ans += min(i, n - i) + + return ans diff --git a/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.cpp b/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.cpp new file mode 100644 index 00000000000..6c8e23c21ea --- /dev/null +++ b/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int maxIncreasingCells(vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + // rows[i] := the maximum path length for the i-th row + vector rows(m); + // cols[j] := the maximum path length for the j-th column + vector cols(n); + unordered_map>> valToIndices; + // maxPathLength[i][j] := the maximum path length from mat[i][j] + vector> maxPathLength(m, vector(n)); + // Sort all the unique values in the matrix in non-increasing order. + set> decreasingSet; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + valToIndices[mat[i][j]].emplace_back(i, j); + decreasingSet.insert(mat[i][j]); + } + + for (const int val : decreasingSet) { + for (const auto& [i, j] : valToIndices[val]) + maxPathLength[i][j] = max(rows[i], cols[j]) + 1; + for (const auto& [i, j] : valToIndices[val]) { + rows[i] = max(rows[i], maxPathLength[i][j]); + cols[j] = max(cols[j], maxPathLength[i][j]); + } + } + + return max(ranges::max(rows), ranges::max(cols)); + } +}; diff --git a/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.java b/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.java new file mode 100644 index 00000000000..510df2f6075 --- /dev/null +++ b/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.java @@ -0,0 +1,40 @@ +class Solution { + public int maxIncreasingCells(int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + // rows[i] := the maximum path length for the i-th row + int[] rows = new int[m]; + // cols[j] := the maximum path length for the j-th column + int[] cols = new int[n]; + Map>> valToIndices = new HashMap<>(); + // maxPathLength[i][j] := the maximum path length from mat[i][j] + int[][] maxPathLength = new int[m][n]; + // Sort all the unique values in the matrix in non-increasing order. + TreeSet decreasingSet = new TreeSet<>(Comparator.reverseOrder()); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + final int val = mat[i][j]; + valToIndices.putIfAbsent(val, new ArrayList<>()); + valToIndices.get(val).add(new Pair<>(i, j)); + decreasingSet.add(val); + } + + for (final int val : decreasingSet) { + for (Pair pair : valToIndices.get(val)) { + final int i = pair.getKey(); + final int j = pair.getValue(); + maxPathLength[i][j] = Math.max(rows[i], cols[j]) + 1; + } + for (Pair pair : valToIndices.get(val)) { + final int i = pair.getKey(); + final int j = pair.getValue(); + rows[i] = Math.max(rows[i], maxPathLength[i][j]); + cols[j] = Math.max(cols[j], maxPathLength[i][j]); + } + } + + return Math.max(Arrays.stream(rows).max().getAsInt(), // + Arrays.stream(cols).max().getAsInt()); + } +} diff --git a/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.py b/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.py new file mode 100644 index 00000000000..749789bf0a7 --- /dev/null +++ b/solutions/2713. Maximum Strictly Increasing Cells in a Matrix/2713.py @@ -0,0 +1,26 @@ +class Solution: + def maxIncreasingCells(self, mat: List[List[int]]) -> int: + m = len(mat) + n = len(mat[0]) + rows = [0] * m # rows[i] := the maximum path length for the i-th row + cols = [0] * n # cols[j] := the maximum path length for the j-th column + valToIndices = collections.defaultdict(list) + # maxPathLength[i][j] := the maximum path length from mat[i][j] + maxPathLength = [[0] * n for _ in range(m)] + # Sort all the unique values in the matrix in non-increasing order. + decreasingSet = set() + + for i in range(m): + for j in range(n): + val = mat[i][j] + valToIndices[val].append((i, j)) + decreasingSet.add(val) + + for val in sorted(decreasingSet, reverse=True): + for i, j in valToIndices[val]: + maxPathLength[i][j] = max(rows[i], cols[j]) + 1 + for i, j in valToIndices[val]: + rows[i] = max(rows[i], maxPathLength[i][j]) + cols[j] = max(cols[j], maxPathLength[i][j]) + + return max(max(rows), max(cols)) diff --git a/solutions/2714. Find Shortest Path with K Hops/2714.cpp b/solutions/2714. Find Shortest Path with K Hops/2714.cpp new file mode 100644 index 00000000000..e0a41748f2a --- /dev/null +++ b/solutions/2714. Find Shortest Path with K Hops/2714.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + // Similar to 787. Cheapest Flights Within K Stops + int shortestPathWithHops(int n, vector>& edges, int s, int d, + int k) { + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + return dijkstra(graph, s, d, k); + } + + private: + int dijkstra(const vector>>& graph, int src, int dst, + int k) { + vector> dist(graph.size(), vector(k + 1, INT_MAX)); + using T = tuple; // (d, u, hops) + priority_queue, greater<>> minHeap; + + dist[src][k] = 0; + minHeap.emplace(dist[src][k], src, k); + + while (!minHeap.empty()) { + const auto [d, u, hops] = minHeap.top(); + minHeap.pop(); + if (u == dst) + return d; + if (dist[u][hops] > d) + continue; + for (const auto& [v, w] : graph[u]) { + // Go from u -> v with w cost. + if (d + w < dist[v][hops]) { + dist[v][hops] = d + w; + minHeap.emplace(dist[v][hops], v, hops); + } + // Hop from u -> v with 0 cost. + if (hops > 0 && d < dist[v][hops - 1]) { + dist[v][hops - 1] = d; + minHeap.emplace(dist[v][hops - 1], v, hops - 1); + } + } + } + + throw; + } +}; diff --git a/solutions/2714. Find Shortest Path with K Hops/2714.java b/solutions/2714. Find Shortest Path with K Hops/2714.java new file mode 100644 index 00000000000..8e954cf7ff6 --- /dev/null +++ b/solutions/2714. Find Shortest Path with K Hops/2714.java @@ -0,0 +1,55 @@ +class Solution { + // Similar to 787. Cheapest Flights Within K Stops + public int shortestPathWithHops(int n, int[][] edges, int s, int d, int k) { + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + return dijkstra(graph, s, d, k); + } + + private int dijkstra(List>[] graph, int src, int dst, int k) { + int[][] dist = new int[graph.length][k + 1]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + // (d, u, hops) + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + + dist[src][k] = 0; + minHeap.offer(new int[] {dist[src][k], src, k}); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek()[0]; + final int u = minHeap.peek()[1]; + final int hops = minHeap.poll()[2]; + if (u == dst) + return d; + if (dist[u][hops] > d) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + // Go from u -> v with w cost. + if (d + w < dist[v][hops]) { + dist[v][hops] = d + w; + minHeap.offer(new int[] {dist[v][hops], v, hops}); + } + // Hop from u -> v with 0 cost. + if (hops > 0 && d < dist[v][hops - 1]) { + dist[v][hops - 1] = d; + minHeap.offer(new int[] {dist[v][hops - 1], v, hops - 1}); + } + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2714. Find Shortest Path with K Hops/2714.py b/solutions/2714. Find Shortest Path with K Hops/2714.py new file mode 100644 index 00000000000..b92834a2f63 --- /dev/null +++ b/solutions/2714. Find Shortest Path with K Hops/2714.py @@ -0,0 +1,32 @@ +class Solution: + # Similar to 787. Cheapest Flights Within K Stops + def shortestPathWithHops(self, n: int, edges: List[List[int]], s: int, d: int, k: int) -> int: + graph = [[] for _ in range(n)] + + for u, v, w in edges: + graph[u].append((v, w)) + graph[v].append((u, w)) + + return self._dijkstra(graph, s, d, k) + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int, k: int) -> int: + dist = [[math.inf for _ in range(k + 1)] for _ in range(len(graph))] + + dist[src][k] = 0 + minHeap = [(dist[src][k], src, k)] # (d, u, hops) + + while minHeap: + d, u, hops = heapq.heappop(minHeap) + if u == dst: + return d + if dist[u][hops] > d: + continue + for v, w in graph[u]: + # Go from u -> v with w cost. + if d + w < dist[v][hops]: + dist[v][hops] = d + w + heapq.heappush(minHeap, (dist[v][hops], v, hops)) + # Hop from u -> v with 0 cost. + if hops > 0 and d < dist[v][hops - 1]: + dist[v][hops - 1] = d + heapq.heappush(minHeap, (dist[v][hops - 1], v, hops - 1)) diff --git a/solutions/2715. Timeout Cancellation/2715.ts b/solutions/2715. Timeout Cancellation/2715.ts new file mode 100644 index 00000000000..022c755a05f --- /dev/null +++ b/solutions/2715. Timeout Cancellation/2715.ts @@ -0,0 +1,15 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Fn = (...args: JSONValue[]) => void; + +function cancellable(fn: Fn, args: JSONValue[], t: number): Function { + const timer = setTimeout(() => fn(...args), t); + return function () { + clearTimeout(timer); + }; +} diff --git a/solutions/2716. Minimize String Length/2716.cpp b/solutions/2716. Minimize String Length/2716.cpp new file mode 100644 index 00000000000..c4adbb25937 --- /dev/null +++ b/solutions/2716. Minimize String Length/2716.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int minimizedStringLength(string s) { + return unordered_set(s.begin(), s.end()).size(); + } +}; diff --git a/solutions/2716. Minimize String Length/2716.java b/solutions/2716. Minimize String Length/2716.java new file mode 100644 index 00000000000..9be846c5f31 --- /dev/null +++ b/solutions/2716. Minimize String Length/2716.java @@ -0,0 +1,5 @@ +class Solution { + public int minimizedStringLength(String s) { + return new HashSet<>(Arrays.asList(s.split(""))).size(); + } +} diff --git a/solutions/2716. Minimize String Length/2716.py b/solutions/2716. Minimize String Length/2716.py new file mode 100644 index 00000000000..12788444209 --- /dev/null +++ b/solutions/2716. Minimize String Length/2716.py @@ -0,0 +1,3 @@ +class Solution: + def minimizedStringLength(self, s: str) -> int: + return len({*s}) diff --git a/solutions/2717. Semi-Ordered Permutation/2717.cpp b/solutions/2717. Semi-Ordered Permutation/2717.cpp new file mode 100644 index 00000000000..2ef32e4ebe3 --- /dev/null +++ b/solutions/2717. Semi-Ordered Permutation/2717.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int semiOrderedPermutation(vector& nums) { + const int n = nums.size(); + const int index1 = find(nums.begin(), nums.end(), 1) - nums.begin(); + const int indexN = find(nums.begin(), nums.end(), n) - nums.begin(); + return index1 + (n - 1 - indexN) - (index1 > indexN ? 1 : 0); + } +}; diff --git a/solutions/2717. Semi-Ordered Permutation/2717.java b/solutions/2717. Semi-Ordered Permutation/2717.java new file mode 100644 index 00000000000..35579bbafe1 --- /dev/null +++ b/solutions/2717. Semi-Ordered Permutation/2717.java @@ -0,0 +1,14 @@ +class Solution { + public int semiOrderedPermutation(int[] nums) { + final int n = nums.length; + int index1 = -1; + int indexN = -1; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == 1) + index1 = i; + else if (nums[i] == n) + indexN = i; + } + return index1 + (n - 1 - indexN) - (index1 > indexN ? 1 : 0); + } +} diff --git a/solutions/2717. Semi-Ordered Permutation/2717.py b/solutions/2717. Semi-Ordered Permutation/2717.py new file mode 100644 index 00000000000..75ea131f50a --- /dev/null +++ b/solutions/2717. Semi-Ordered Permutation/2717.py @@ -0,0 +1,6 @@ +class Solution: + def semiOrderedPermutation(self, nums: List[int]) -> int: + n = len(nums) + index1 = nums.index(1) + indexN = nums.index(n) + return index1 + (n - 1 - indexN) - int(index1 > indexN) diff --git a/solutions/2718. Sum of Matrix After Queries/2718.cpp b/solutions/2718. Sum of Matrix After Queries/2718.cpp new file mode 100644 index 00000000000..d3af6ee9dcb --- /dev/null +++ b/solutions/2718. Sum of Matrix After Queries/2718.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long matrixSumQueries(int n, vector>& queries) { + long ans = 0; + // seen[0] := row, seen[1] := col + vector> seen(2, vector(n)); + // notSet[0] = row, notSet[1] := col + vector notSet(2, n); + + // Later queries dominate. + for (int i = queries.size() - 1; i >= 0; --i) { + const int type = queries[i][0]; + const int index = queries[i][1]; + const int val = queries[i][2]; + if (!seen[type][index]) { + ans += val * notSet[type ^ 1]; + seen[type][index] = true; + --notSet[type]; + } + } + + return ans; + } +}; diff --git a/solutions/2718. Sum of Matrix After Queries/2718.java b/solutions/2718. Sum of Matrix After Queries/2718.java new file mode 100644 index 00000000000..80be4e806ce --- /dev/null +++ b/solutions/2718. Sum of Matrix After Queries/2718.java @@ -0,0 +1,24 @@ +class Solution { + public long matrixSumQueries(int n, int[][] queries) { + long ans = 0; + // seen[0] := row, seen[1] := col + boolean[][] seen = new boolean[2][n]; + // notSet[0] = row, notSet[1] := col + int[] notSet = new int[2]; + Arrays.fill(notSet, n); + + // Late queries dominate. + for (int i = queries.length - 1; i >= 0; --i) { + final int type = queries[i][0]; + final int index = queries[i][1]; + final int val = queries[i][2]; + if (!seen[type][index]) { + ans += val * notSet[type ^ 1]; + seen[type][index] = true; + --notSet[type]; + } + } + + return ans; + } +} diff --git a/solutions/2718. Sum of Matrix After Queries/2718.py b/solutions/2718. Sum of Matrix After Queries/2718.py new file mode 100644 index 00000000000..97239354293 --- /dev/null +++ b/solutions/2718. Sum of Matrix After Queries/2718.py @@ -0,0 +1,16 @@ +class Solution: + def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int: + ans = 0 + # seen[0] := row, seen[1] := col + seen = [[False] * n for _ in range(2)] + # notSet[0] = row, notSet[1] := col + notSet = [n] * 2 + + # Late queries dominate. + for type, index, val in reversed(queries): + if not seen[type][index]: + ans += val * notSet[type ^ 1] + seen[type][index] = True + notSet[type] -= 1 + + return ans diff --git a/solutions/2719. Count of Integers/2719.cpp b/solutions/2719. Count of Integers/2719.cpp new file mode 100644 index 00000000000..9ca82eb1cf1 --- /dev/null +++ b/solutions/2719. Count of Integers/2719.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + int count(string num1, string num2, int min_sum, int max_sum) { + const string num1WithLeadingZeros = + string(num2.length() - num1.length(), '0') + num1; + vector>>> mem( + num2.length(), + vector>>( + max_sum + 1, vector>(2, vector(2, -1)))); + return (count(num1WithLeadingZeros, num2, 0, max_sum, true, true, mem) - + count(num1WithLeadingZeros, num2, 0, min_sum - 1, true, true, mem) + + kMod) % + kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of valid integers, considering the i-th digit, where + // `sum` is the maximum digit sum, `isTight1` indicates if the current digit + // is tightly bound for `num1` and `isTight2` indicates if the current digit + // is tightly bound for `num2` + int count(const string& num1, const string& num2, int i, int sum, + bool isTight1, bool isTight2, + vector>>>& mem) { + if (sum < 0) + return 0; + if (i == num2.length()) + return 1; + if (mem[i][sum][isTight1][isTight2] != -1) + return mem[i][sum][isTight1][isTight2]; + + int res = 0; + + const int minDigit = isTight1 ? num1[i] - '0' : 0; + const int maxDigit = isTight2 ? num2[i] - '0' : 9; + for (int d = minDigit; d <= maxDigit; ++d) { + const bool nextIsTight1 = isTight1 && (d == minDigit); + const bool nextIsTight2 = isTight2 && (d == maxDigit); + res += count(num1, num2, i + 1, sum - d, nextIsTight1, nextIsTight2, mem); + res %= kMod; + } + + return mem[i][sum][isTight1][isTight2] = res; + } +}; diff --git a/solutions/272. Closest Binary Search Tree Value II/272.cpp b/solutions/272. Closest Binary Search Tree Value II/272.cpp new file mode 100644 index 00000000000..fa7d17f62bc --- /dev/null +++ b/solutions/272. Closest Binary Search Tree Value II/272.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector closestKValues(TreeNode* root, double target, int k) { + deque dq; + + inorder(root, dq); + + while (dq.size() > k) + if (abs(dq.front() - target) > abs(dq.back() - target)) + dq.pop_front(); + else + dq.pop_back(); + + return {dq.begin(), dq.end()}; + } + + private: + void inorder(TreeNode* root, deque& dq) { + if (root == nullptr) + return; + + inorder(root->left, dq); + dq.push_back(root->val); + inorder(root->right, dq); + } +}; diff --git a/solutions/272. Closest Binary Search Tree Value II/272.java b/solutions/272. Closest Binary Search Tree Value II/272.java new file mode 100644 index 00000000000..2b1ec726e27 --- /dev/null +++ b/solutions/272. Closest Binary Search Tree Value II/272.java @@ -0,0 +1,24 @@ +class Solution { + public List closestKValues(TreeNode root, double target, int k) { + Deque dq = new ArrayDeque<>(); + + inorder(root, dq); + + while (dq.size() > k) + if (Math.abs(dq.peekFirst() - target) > Math.abs(dq.peekLast() - target)) + dq.pollFirst(); + else + dq.pollLast(); + + return new ArrayList<>(dq); + } + + private void inorder(TreeNode root, Deque dq) { + if (root == null) + return; + + inorder(root.left, dq); + dq.offerLast(root.val); + inorder(root.right, dq); + } +} diff --git a/solutions/272. Closest Binary Search Tree Value II/272.py b/solutions/272. Closest Binary Search Tree Value II/272.py new file mode 100644 index 00000000000..d01554ca159 --- /dev/null +++ b/solutions/272. Closest Binary Search Tree Value II/272.py @@ -0,0 +1,21 @@ +class Solution: + def closestKValues(self, root: Optional[TreeNode], target: float, k: int) -> List[int]: + dq = collections.deque() + + def inorder(root: Optional[TreeNode]) -> None: + if not root: + return + + inorder(root.left) + dq.append(root.val) + inorder(root.right) + + inorder(root) + + while len(dq) > k: + if abs(dq[0] - target) > abs(dq[-1] - target): + dq.popleft() + else: + dq.pop() + + return list(dq) diff --git a/solutions/2720. Popularity Percentage/2720.sql b/solutions/2720. Popularity Percentage/2720.sql new file mode 100644 index 00000000000..421a393ee19 --- /dev/null +++ b/solutions/2720. Popularity Percentage/2720.sql @@ -0,0 +1,15 @@ +WITH + TwoWayFriends AS ( + SELECT user1, user2 FROM Friends + UNION ALL + SELECT user2, user1 FROM Friends + ) +SELECT + user1, + ROUND( + 100 * (COUNT(DISTINCT user2) / (COUNT(*) OVER())), + 2 + ) AS percentage_popularity +FROM TwoWayFriends +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2721. Execute Asynchronous Functions in Parallel/2721.ts b/solutions/2721. Execute Asynchronous Functions in Parallel/2721.ts new file mode 100644 index 00000000000..e3ace932043 --- /dev/null +++ b/solutions/2721. Execute Asynchronous Functions in Parallel/2721.ts @@ -0,0 +1,20 @@ +type Fn = () => Promise; + +function promiseAll(functions: Fn[]): Promise { + return new Promise((resolve, reject) => { + const ans: T[] = []; + let resolveCount = 0; + functions.forEach((fn, index) => { + fn() + .then((val) => { + ans[index] = val; + if (++resolveCount === functions.length) { + resolve(ans); + } + }) + .catch((error) => { + reject(error); + }); + }); + }); +} diff --git a/solutions/2722. Join Two Arrays by ID/2722.ts b/solutions/2722. Join Two Arrays by ID/2722.ts new file mode 100644 index 00000000000..3c69f9e7bac --- /dev/null +++ b/solutions/2722. Join Two Arrays by ID/2722.ts @@ -0,0 +1,31 @@ +type JSONValue = + | {} + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +type Item = { [key: string]: JSONValue } & { + id: number; +}; + +function join(arr1: Item[], arr2: Item[]): Item[] { + const idToObj: { [key: number]: Item } = {}; + for (const item of arr1) { + idToObj[item.id] = item; + } + for (const item of arr2) { + if (idToObj[item.id] === undefined) { + idToObj[item.id] = item; + } else { + for (const key of Object.keys(item)) { + idToObj[item.id][key] = item[key]; + } + } + } + const ans = Object.values(idToObj); + ans.sort((a, b) => a.id - b.id); + return ans; +} diff --git a/solutions/2723. Add Two Promises/2723.ts b/solutions/2723. Add Two Promises/2723.ts new file mode 100644 index 00000000000..6c87384bc54 --- /dev/null +++ b/solutions/2723. Add Two Promises/2723.ts @@ -0,0 +1,6 @@ +type P = Promise; + +async function addTwoPromises(promise1: P, promise2: P): P { + const results = await Promise.all([promise1, promise2]); + return results[0] + results[1]; +} diff --git a/solutions/2724. Sort By/2724.ts b/solutions/2724. Sort By/2724.ts new file mode 100644 index 00000000000..477789276c5 --- /dev/null +++ b/solutions/2724. Sort By/2724.ts @@ -0,0 +1,13 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Fn = (value: JSONValue) => number; + +function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] { + arr.sort((a, b) => fn(a) - fn(b)); + return arr; +} diff --git a/solutions/2725. Interval Cancellation/2725.ts b/solutions/2725. Interval Cancellation/2725.ts new file mode 100644 index 00000000000..abd452830c4 --- /dev/null +++ b/solutions/2725. Interval Cancellation/2725.ts @@ -0,0 +1,16 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Fn = (...args: JSONValue[]) => void; + +function cancellable(fn: Fn, args: JSONValue[], t: number): Function { + fn(...args); + const timer = setInterval(() => fn(...args), t); + return function () { + clearInterval(timer); + }; +} diff --git a/solutions/2726. Calculator with Method Chaining/2726.ts b/solutions/2726. Calculator with Method Chaining/2726.ts new file mode 100644 index 00000000000..0130d911c14 --- /dev/null +++ b/solutions/2726. Calculator with Method Chaining/2726.ts @@ -0,0 +1,37 @@ +class Calculator { + private cur: number; + + constructor(value: number) { + this.cur = value; + } + + add(value: number): Calculator { + this.cur += value; + return this; + } + + subtract(value: number): Calculator { + this.cur -= value; + return this; + } + + multiply(value: number): Calculator { + this.cur *= value; + return this; + } + + divide(value: number): Calculator { + if (value === 0) throw new Error('Division by zero is not allowed'); + this.cur /= value; + return this; + } + + power(value: number): Calculator { + this.cur **= value; + return this; + } + + getResult(): number { + return this.cur; + } +} diff --git a/solutions/2727. Is Object Empty/2727.ts b/solutions/2727. Is Object Empty/2727.ts new file mode 100644 index 00000000000..a29133195cb --- /dev/null +++ b/solutions/2727. Is Object Empty/2727.ts @@ -0,0 +1,15 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Obj = Record | JSONValue[]; + +function isEmpty(obj: Obj): boolean { + if (Array.isArray(obj)) { + return obj.length === 0; + } + return Object.keys(obj).length === 0; +} diff --git a/solutions/2728. Count Houses in a Circular Street/2728.cpp b/solutions/2728. Count Houses in a Circular Street/2728.cpp new file mode 100644 index 00000000000..2d8f434b10a --- /dev/null +++ b/solutions/2728. Count Houses in a Circular Street/2728.cpp @@ -0,0 +1,32 @@ +/** + * Definition for a street. + * class Street { + * public: + * Street(vector doors); + * void openDoor(); + * void closeDoor(); + * bool isDoorOpen(); + * void moveRight(); + * void moveLeft(); + * }; + */ + +class Solution { + public: + int houseCount(Street* street, int k) { + for (int i = 0; i < k; ++i) { + if (street->isDoorOpen()) + street->closeDoor(); + street->moveRight(); + } + + for (int ans = 0;; ++ans) { + if (street->isDoorOpen()) + return ans; + street->openDoor(); + street->moveRight(); + } + + throw; + } +}; diff --git a/solutions/2728. Count Houses in a Circular Street/2728.java b/solutions/2728. Count Houses in a Circular Street/2728.java new file mode 100644 index 00000000000..b3ff131c550 --- /dev/null +++ b/solutions/2728. Count Houses in a Circular Street/2728.java @@ -0,0 +1,28 @@ +/** + * Definition for a street. + * class Street { + * public Street(int[] doors); + * public void openDoor(); + * public void closeDoor(); + * public boolean isDoorOpen(); + * public void moveRight(); + * public void moveLeft(); + * } + */ + +class Solution { + public int houseCount(Street street, int k) { + for (int i = 0; i < k; ++i) { + if (street.isDoorOpen()) + street.closeDoor(); + street.moveRight(); + } + + for (int ans = 0;; ++ans) { + if (street.isDoorOpen()) + return ans; + street.openDoor(); + street.moveRight(); + } + } +} diff --git a/solutions/2728. Count Houses in a Circular Street/2728.py b/solutions/2728. Count Houses in a Circular Street/2728.py new file mode 100644 index 00000000000..f639de71483 --- /dev/null +++ b/solutions/2728. Count Houses in a Circular Street/2728.py @@ -0,0 +1,25 @@ +# Definition for a street. +# class Street: +# def openDoor(self): +# pass +# def closeDoor(self): +# pass +# def isDoorOpen(self): +# pass +# def moveRight(self): +# pass +# def moveLeft(self): +# pass + +class Solution: + def houseCount(self, street: Optional['Street'], k: int) -> int: + for _ in range(k): + if street.isDoorOpen(): + street.closeDoor() + street.moveRight() + + for ans in range(k + 1): + if street.isDoorOpen(): + return ans + street.openDoor() + street.moveRight() diff --git a/solutions/2729. Check if The Number is Fascinating/2729.cpp b/solutions/2729. Check if The Number is Fascinating/2729.cpp new file mode 100644 index 00000000000..cf1a2657663 --- /dev/null +++ b/solutions/2729. Check if The Number is Fascinating/2729.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + bool isFascinating(int n) { + string s = to_string(n) + to_string(2 * n) + to_string(3 * n); + ranges::sort(s); + return s == "123456789"; + } +}; diff --git a/solutions/2729. Check if The Number is Fascinating/2729.java b/solutions/2729. Check if The Number is Fascinating/2729.java new file mode 100644 index 00000000000..88e2b3f931c --- /dev/null +++ b/solutions/2729. Check if The Number is Fascinating/2729.java @@ -0,0 +1,8 @@ +class Solution { + public boolean isFascinating(int n) { + String s = Integer.toString(n) + Integer.toString(2 * n) + Integer.toString(3 * n); + char[] charArray = s.toCharArray(); + Arrays.sort(charArray); + return new String(charArray).equals("123456789"); + } +} diff --git a/solutions/2729. Check if The Number is Fascinating/2729.py b/solutions/2729. Check if The Number is Fascinating/2729.py new file mode 100644 index 00000000000..b4522dd1b38 --- /dev/null +++ b/solutions/2729. Check if The Number is Fascinating/2729.py @@ -0,0 +1,4 @@ +class Solution: + def isFascinating(self, n): + s = str(n) + str(2 * n) + str(3 * n) + return ''.join(sorted(s)) == '123456789' diff --git a/solutions/273. Integer to English Words/273.cpp b/solutions/273. Integer to English Words/273.cpp new file mode 100644 index 00000000000..e17ae7a1f83 --- /dev/null +++ b/solutions/273. Integer to English Words/273.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + string numberToWords(int num) { + if (num == 0) + return "Zero"; + return helper(num); + } + + private: + const vector belowTwenty{ + "", "One", "Two", "Three", "Four", + "Five", "Six", "Seven", "Eight", "Nine", + "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", + "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; + const vector tens{"", "", "Twenty", "Thirty", "Forty", + "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; + + string helper(int num) { + string s; + + if (num < 20) + s = belowTwenty.at(num); + else if (num < 100) + s = tens.at(num / 10) + " " + belowTwenty.at(num % 10); + else if (num < 1000) + s = helper(num / 100) + " Hundred " + helper(num % 100); + else if (num < 1000000) + s = helper(num / 1000) + " Thousand " + helper(num % 1000); + else if (num < 1000000000) + s = helper(num / 1000000) + " Million " + helper(num % 1000000); + else + s = helper(num / 1000000000) + " Billion " + helper(num % 1000000000); + + trim(s); + return s; + } + + void trim(string& s) { + s.erase(0, s.find_first_not_of(' ')); + s.erase(s.find_last_not_of(' ') + 1); + } +}; diff --git a/solutions/273. Integer to English Words/273.java b/solutions/273. Integer to English Words/273.java new file mode 100644 index 00000000000..33bcbda4cc1 --- /dev/null +++ b/solutions/273. Integer to English Words/273.java @@ -0,0 +1,31 @@ +class Solution { + public String numberToWords(int num) { + return num == 0 ? "Zero" : helper(num); + } + + private final String[] belowTwenty = {"", "One", "Two", "Three", "Four", + "Five", "Six", "Seven", "Eight", "Nine", + "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", + "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; + private final String[] tens = {"", "", "Twenty", "Thirty", "Forty", + "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; + + private String helper(int num) { + StringBuilder s = new StringBuilder(); + + if (num < 20) + s.append(belowTwenty[num]); + else if (num < 100) + s.append(tens[num / 10]).append(" ").append(belowTwenty[num % 10]); + else if (num < 1000) + s.append(helper(num / 100)).append(" Hundred ").append(helper(num % 100)); + else if (num < 1000000) + s.append(helper(num / 1000)).append(" Thousand ").append(helper(num % 1000)); + else if (num < 1000000000) + s.append(helper(num / 1000000)).append(" Million ").append(helper(num % 1000000)); + else + s.append(helper(num / 1000000000)).append(" Billion ").append(helper(num % 1000000000)); + + return s.toString().trim(); + } +} diff --git a/solutions/273. Integer to English Words/273.py b/solutions/273. Integer to English Words/273.py new file mode 100644 index 00000000000..101beb7b3b0 --- /dev/null +++ b/solutions/273. Integer to English Words/273.py @@ -0,0 +1,32 @@ +class Solution: + def numberToWords(self, num: int) -> str: + if num == 0: + return "Zero" + + belowTwenty = ["", "One", "Two", "Three", + "Four", "Five", "Six", "Seven", + "Eight", "Nine", "Ten", "Eleven", + "Twelve", "Thirteen", "Fourteen", "Fifteen", + "Sixteen", "Seventeen", "Eighteen", "Nineteen"] + tens = ["", "Ten", "Twenty", "Thirty", "Forty", + "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] + + def helper(num: int) -> str: + if num < 20: + s = belowTwenty[num] + elif num < 100: + s = tens[num // 10] + " " + belowTwenty[num % 10] + elif num < 1000: + s = helper(num // 100) + " Hundred " + helper(num % 100) + elif num < 1000000: + s = helper(num // 1000) + " Thousand " + helper(num % 1000) + elif num < 1000000000: + s = helper(num // 1000000) + " Million " + \ + helper(num % 1000000) + else: + s = helper(num // 1000000000) + " Billion " + \ + helper(num % 1000000000) + + return s.strip() + + return helper(num) diff --git a/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.cpp b/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.cpp new file mode 100644 index 00000000000..f9c53a90532 --- /dev/null +++ b/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int longestSemiRepetitiveSubstring(string s) { + int ans = 1; + int prevStart = 0; + int start = 0; + + for (int i = 1; i < s.length(); ++i) { + if (s[i] == s[i - 1]) { + if (prevStart > 0) + start = prevStart; + prevStart = i; + } + ans = max(ans, i - start + 1); + } + + return ans; + } +}; diff --git a/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.java b/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.java new file mode 100644 index 00000000000..0bf84ef0f8c --- /dev/null +++ b/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.java @@ -0,0 +1,18 @@ +class Solution { + public int longestSemiRepetitiveSubstring(String s) { + int ans = 1; + int prevStart = 0; + int start = 0; + + for (int i = 1; i < s.length(); ++i) { + if (s.charAt(i) == s.charAt(i - 1)) { + if (prevStart > 0) + start = prevStart; + prevStart = i; + } + ans = Math.max(ans, i - start + 1); + } + + return ans; + } +} diff --git a/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.py b/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.py new file mode 100644 index 00000000000..5e0159db18a --- /dev/null +++ b/solutions/2730. Find the Longest Semi-Repetitive Substring/2730.py @@ -0,0 +1,14 @@ +class Solution: + def longestSemiRepetitiveSubstring(self, s: str) -> int: + ans = 1 + prevStart = 0 + start = 0 + + for i in range(1, len(s)): + if s[i] == s[i - 1]: + if prevStart > 0: + start = prevStart + prevStart = i + ans = max(ans, i - start + 1) + + return ans diff --git a/solutions/2731. Movement of Robots/2731.cpp b/solutions/2731. Movement of Robots/2731.cpp new file mode 100644 index 00000000000..949835105d6 --- /dev/null +++ b/solutions/2731. Movement of Robots/2731.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int sumDistance(vector& nums, string s, int d) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + int prefix = 0; + vector pos; + + for (int i = 0; i < nums.size(); ++i) + if (s[i] == 'L') + pos.push_back(nums[i] - d); + else + pos.push_back(nums[i] + d); + + ranges::sort(pos); + + for (int i = 0; i < n; ++i) { + ans = + ((ans + static_cast(i) * pos[i] - prefix) % kMod + kMod) % kMod; + prefix = ((0L + prefix + pos[i]) % kMod + kMod) % kMod; + } + + return ans; + } +}; diff --git a/solutions/2731. Movement of Robots/2731.java b/solutions/2731. Movement of Robots/2731.java new file mode 100644 index 00000000000..dd70189aa12 --- /dev/null +++ b/solutions/2731. Movement of Robots/2731.java @@ -0,0 +1,24 @@ +class Solution { + public int sumDistance(int[] nums, String s, int d) { + final int kMod = 1_000_000_007; + final int n = nums.length; + int ans = 0; + int prefix = 0; + int[] pos = new int[n]; + + for (int i = 0; i < n; ++i) + if (s.charAt(i) == 'L') + pos[i] = nums[i] - d; + else + pos[i] = nums[i] + d; + + Arrays.sort(pos); + + for (int i = 0; i < n; ++i) { + ans = (int) (((ans + 1L * i * pos[i] - prefix) % kMod + kMod) % kMod); + prefix = (int) (((0L + prefix + pos[i]) % kMod + kMod) % kMod); + } + + return ans; + } +} diff --git a/solutions/2731. Movement of Robots/2731.py b/solutions/2731. Movement of Robots/2731.py new file mode 100644 index 00000000000..a76af26c5b0 --- /dev/null +++ b/solutions/2731. Movement of Robots/2731.py @@ -0,0 +1,13 @@ +class Solution: + def sumDistance(self, nums: List[int], s: str, d: int) -> int: + kMod = 1_000_000_007 + ans = 0 + prefix = 0 + pos = sorted([num - d if c == 'L' else num + d + for num, c in zip(nums, s)]) + + for i, p in enumerate(pos): + ans = ((ans + i * p - prefix) % kMod + kMod) % kMod + prefix = ((prefix + p) % kMod + kMod) % kMod + + return ans diff --git a/solutions/2732. Find a Good Subset of the Matrix/2732.cpp b/solutions/2732. Find a Good Subset of the Matrix/2732.cpp new file mode 100644 index 00000000000..0f270da7593 --- /dev/null +++ b/solutions/2732. Find a Good Subset of the Matrix/2732.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector goodSubsetofBinaryMatrix(vector>& grid) { + constexpr int kMaxBit = 30; + unordered_map maskToIndex; + + for (int i = 0; i < grid.size(); ++i) { + const int mask = getMask(grid[i]); + if (mask == 0) + return {i}; + for (int prevMask = 1; prevMask < kMaxBit; ++prevMask) + if ((mask & prevMask) == 0 && maskToIndex.contains(prevMask)) + return {maskToIndex[prevMask], i}; + maskToIndex[mask] = i; + } + + return {}; + } + + private: + int getMask(const vector& row) { + int mask = 0; + for (int i = 0; i < row.size(); ++i) + if (row[i] == 1) + mask |= 1 << i; + return mask; + } +}; diff --git a/solutions/2732. Find a Good Subset of the Matrix/2732.java b/solutions/2732. Find a Good Subset of the Matrix/2732.java new file mode 100644 index 00000000000..b7208f09c3d --- /dev/null +++ b/solutions/2732. Find a Good Subset of the Matrix/2732.java @@ -0,0 +1,26 @@ +class Solution { + public List goodSubsetofBinaryMatrix(int[][] grid) { + final int kMaxBit = 30; + Map maskToIndex = new HashMap<>(); + + for (int i = 0; i < grid.length; ++i) { + final int mask = getMask(grid[i]); + if (mask == 0) + return List.of(i); + for (int prevMask = 1; prevMask < kMaxBit; ++prevMask) + if ((mask & prevMask) == 0 && maskToIndex.containsKey(prevMask)) + return List.of(maskToIndex.get(prevMask), i); + maskToIndex.put(mask, i); + } + + return new ArrayList<>(); + } + + private int getMask(int[] row) { + int mask = 0; + for (int i = 0; i < row.length; ++i) + if (row[i] == 1) + mask |= 1 << i; + return mask; + } +} diff --git a/solutions/2732. Find a Good Subset of the Matrix/2732.py b/solutions/2732. Find a Good Subset of the Matrix/2732.py new file mode 100644 index 00000000000..8726547cd3e --- /dev/null +++ b/solutions/2732. Find a Good Subset of the Matrix/2732.py @@ -0,0 +1,22 @@ +class Solution: + def goodSubsetofBinaryMatrix(self, grid: List[List[int]]) -> List[int]: + kMaxBit = 30 + maskToIndex = {} + + def getMask(row: List[int]) -> int: + mask = 0 + for i, num in enumerate(row): + if num == 1: + mask |= 1 << i + return mask + + for i, row in enumerate(grid): + mask = getMask(row) + if mask == 0: + return [i] + for prevMask in range(1, kMaxBit): + if (mask & prevMask) == 0 and prevMask in maskToIndex: + return [maskToIndex[prevMask], i] + maskToIndex[mask] = i + + return [] diff --git a/solutions/2733. Neither Minimum nor Maximum/2733.cpp b/solutions/2733. Neither Minimum nor Maximum/2733.cpp new file mode 100644 index 00000000000..2d3bcab4d4c --- /dev/null +++ b/solutions/2733. Neither Minimum nor Maximum/2733.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int findNonMinOrMax(vector& nums) { + if (nums.size() < 3) + return -1; + sort(nums.begin(), nums.begin() + 3); + return nums[1]; + } +}; diff --git a/solutions/2733. Neither Minimum nor Maximum/2733.java b/solutions/2733. Neither Minimum nor Maximum/2733.java new file mode 100644 index 00000000000..fd09a55e9d7 --- /dev/null +++ b/solutions/2733. Neither Minimum nor Maximum/2733.java @@ -0,0 +1,8 @@ +class Solution { + public int findNonMinOrMax(int[] nums) { + if (nums.length < 3) + return -1; + Arrays.sort(nums, 0, 3); + return nums[1]; + } +} diff --git a/solutions/2733. Neither Minimum nor Maximum/2733.py b/solutions/2733. Neither Minimum nor Maximum/2733.py new file mode 100644 index 00000000000..7f2c6ad5951 --- /dev/null +++ b/solutions/2733. Neither Minimum nor Maximum/2733.py @@ -0,0 +1,3 @@ +class Solution: + def findNonMinOrMax(self, nums: List[int]) -> int: + return -1 if len(nums) < 3 else sorted(nums[:3])[1] diff --git a/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.cpp b/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.cpp new file mode 100644 index 00000000000..4452120d020 --- /dev/null +++ b/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + string smallestString(string s) { + const int n = s.length(); + int i = 0; + + while (i < n && s[i] == 'a') + ++i; + if (i == n) { + s[n - 1] = 'z'; + return s; + } + + while (i < n && s[i] != 'a') + --s[i++]; + + return s; + } +}; diff --git a/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.java b/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.java new file mode 100644 index 00000000000..086a704e96f --- /dev/null +++ b/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.java @@ -0,0 +1,19 @@ +public class Solution { + public String smallestString(String s) { + char[] charArray = s.toCharArray(); + final int n = s.length(); + int i = 0; + + while (i < n && charArray[i] == 'a') + ++i; + if (i == n) { + charArray[n - 1] = 'z'; + return new String(charArray); + } + + while (i < n && charArray[i] != 'a') + --charArray[i++]; + + return new String(charArray); + } +} diff --git a/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.py b/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.py new file mode 100644 index 00000000000..2cea2d857a2 --- /dev/null +++ b/solutions/2734. Lexicographically Smallest String After Substring Operation/2734.py @@ -0,0 +1,17 @@ +class Solution: + def smallestString(self, s: str) -> str: + chars = list(s) + n = len(s) + i = 0 + + while i < n and chars[i] == 'a': + i += 1 + if i == n: + chars[-1] = 'z' + return ''.join(chars) + + while i < n and s[i] != 'a': + chars[i] = chr(ord(chars[i]) - 1) + i += 1 + + return ''.join(chars) diff --git a/solutions/2735. Collecting Chocolates/2735.cpp b/solutions/2735. Collecting Chocolates/2735.cpp new file mode 100644 index 00000000000..24123f947a7 --- /dev/null +++ b/solutions/2735. Collecting Chocolates/2735.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long long minCost(vector& nums, long long x) { + const int n = nums.size(); + long ans = LONG_MAX; + // minCost[i] := the minimum cost to collect the i-th type + vector minCost(n, INT_MAX); + + for (int rotate = 0; rotate < n; ++rotate) { + for (int i = 0; i < n; ++i) + minCost[i] = min(minCost[i], nums[(i - rotate + n) % n]); + ans = + min(ans, accumulate(minCost.begin(), minCost.end(), 0L) + rotate * x); + } + + return ans; + } +}; diff --git a/solutions/2735. Collecting Chocolates/2735.java b/solutions/2735. Collecting Chocolates/2735.java new file mode 100644 index 00000000000..221b19a4a10 --- /dev/null +++ b/solutions/2735. Collecting Chocolates/2735.java @@ -0,0 +1,17 @@ +public class Solution { + public long minCost(int[] nums, long x) { + int n = nums.length; + long ans = Long.MAX_VALUE; + // minCost[i] := the minimum cost to collect the i-th type + int[] minCost = new int[n]; + Arrays.fill(minCost, Integer.MAX_VALUE); + + for (int rotate = 0; rotate < n; ++rotate) { + for (int i = 0; i < n; ++i) + minCost[i] = Math.min(minCost[i], nums[(i - rotate + n) % n]); + ans = Math.min(ans, Arrays.stream(minCost).asLongStream().sum() + rotate * x); + } + + return ans; + } +} diff --git a/solutions/2735. Collecting Chocolates/2735.py b/solutions/2735. Collecting Chocolates/2735.py new file mode 100644 index 00000000000..4a778966220 --- /dev/null +++ b/solutions/2735. Collecting Chocolates/2735.py @@ -0,0 +1,13 @@ +class Solution: + def minCost(self, nums: List[int], x: int) -> int: + n = len(nums) + ans = math.inf + # minCost[i] := the minimum cost to collect the i-th type + minCost = [math.inf] * n + + for rotate in range(n): + for i in range(n): + minCost[i] = min(minCost[i], nums[(i - rotate + n) % n]) + ans = min(ans, sum(minCost) + rotate * x) + + return ans diff --git a/solutions/2736. Maximum Sum Queries/2736.cpp b/solutions/2736. Maximum Sum Queries/2736.cpp new file mode 100644 index 00000000000..2ff83b559d8 --- /dev/null +++ b/solutions/2736. Maximum Sum Queries/2736.cpp @@ -0,0 +1,58 @@ +struct Pair { + int x; + int y; +}; + +struct IndexedQuery { + int queryIndex; + int minX; + int minY; +}; + +class Solution { + public: + vector maximumSumQueries(vector& nums1, vector& nums2, + vector>& queries) { + const vector pairs = getPairs(nums1, nums2); + vector ans(queries.size()); + vector> stack; // [(y, x + y)] + + int pairsIndex = 0; + for (const auto& [queryIndex, minX, minY] : getIndexedQueries(queries)) { + while (pairsIndex < pairs.size() && pairs[pairsIndex].x >= minX) { + const auto [x, y] = pairs[pairsIndex++]; + // x + y is a better candidate. Given that x is decreasing, the + // condition "x + y >= stack.back().second" suggests that y is + // relatively larger, thereby making it a better candidate. + while (!stack.empty() && x + y >= stack.back().second) + stack.pop_back(); + if (stack.empty() || y > stack.back().first) + stack.emplace_back(y, x + y); + } + const auto it = ranges::lower_bound(stack, pair{minY, INT_MIN}); + ans[queryIndex] = it == stack.end() ? -1 : it->second; + } + + return ans; + } + + private: + vector getPairs(const vector& nums1, const vector& nums2) { + vector pairs; + for (int i = 0; i < nums1.size(); ++i) + pairs.push_back({nums1[i], nums2[i]}); + ranges::sort(pairs, [](const Pair& a, const Pair& b) { return a.x > b.x; }); + return pairs; + } + + vector getIndexedQueries(const vector>& queries) { + vector indexedQueries; + for (int i = 0; i < queries.size(); ++i) + indexedQueries.push_back({i, queries[i][0], queries[i][1]}); + ranges::sort(indexedQueries, + [](const IndexedQuery& a, const IndexedQuery& b) { + return a.minX > b.minX; + }); + return indexedQueries; + } +}; diff --git a/solutions/2736. Maximum Sum Queries/2736.java b/solutions/2736. Maximum Sum Queries/2736.java new file mode 100644 index 00000000000..d248164de63 --- /dev/null +++ b/solutions/2736. Maximum Sum Queries/2736.java @@ -0,0 +1,63 @@ +class Solution { + public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] queries) { + MyPair[] pairs = getPairs(nums1, nums2); + IndexedQuery[] indexedQueries = getIndexedQueries(queries); + int[] ans = new int[queries.length]; + List> stack = new ArrayList<>(); // [(y, x + y)] + + int pairsIndex = 0; + for (IndexedQuery indexedQuery : indexedQueries) { + final int queryIndex = indexedQuery.queryIndex; + final int minX = indexedQuery.minX; + final int minY = indexedQuery.minY; + while (pairsIndex < pairs.length && pairs[pairsIndex].x >= minX) { + MyPair pair = pairs[pairsIndex++]; + // x + y is a better candidate. Given that x is decreasing, the + // condition "x + y >= stack.get(stack.size() - 1).getValue()" suggests + // that y is relatively larger, thereby making it a better candidate. + final int x = pair.x; + final int y = pair.y; + while (!stack.isEmpty() && x + y >= stack.get(stack.size() - 1).getValue()) + stack.remove(stack.size() - 1); + if (stack.isEmpty() || y > stack.get(stack.size() - 1).getKey()) + stack.add(new Pair<>(y, x + y)); + } + final int j = firstGreaterEqual(stack, minY); + ans[queryIndex] = j == stack.size() ? -1 : stack.get(j).getValue(); + } + + return ans; + } + + private record MyPair(int x, int y){}; + private record IndexedQuery(int queryIndex, int minX, int minY){}; + + private int firstGreaterEqual(List> A, int target) { + int l = 0; + int r = A.size(); + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m).getKey() >= target) + r = m; + else + l = m + 1; + } + return l; + } + + private MyPair[] getPairs(int[] nums1, int[] nums2) { + MyPair[] pairs = new MyPair[nums1.length]; + for (int i = 0; i < nums1.length; ++i) + pairs[i] = new MyPair(nums1[i], nums2[i]); + Arrays.sort(pairs, (a, b) -> b.x - a.x); + return pairs; + } + + private IndexedQuery[] getIndexedQueries(int[][] queries) { + IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; + for (int i = 0; i < queries.length; ++i) + indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]); + Arrays.sort(indexedQueries, (a, b) -> b.minX - a.minX); + return indexedQueries; + } +} diff --git a/solutions/2736. Maximum Sum Queries/2736.py b/solutions/2736. Maximum Sum Queries/2736.py new file mode 100644 index 00000000000..97f757577ca --- /dev/null +++ b/solutions/2736. Maximum Sum Queries/2736.py @@ -0,0 +1,58 @@ +class Pair: + def __init__(self, x: int, y: int): + self.x = x + self.y = y + + def __iter__(self): + yield self.x + yield self.y + + +class IndexedQuery: + def __init__(self, queryIndex: int, minX: int, minY: int): + self.queryIndex = queryIndex + self.minX = minX + self.minY = minY + + def __iter__(self): + yield self.queryIndex + yield self.minX + yield self.minY + + +class Solution: + def maximumSumQueries(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]: + pairs = sorted([Pair(nums1[i], nums2[i]) + for i in range(len(nums1))], key=lambda p: p.x, reverse=True) + ans = [0] * len(queries) + stack = [] # [(y, x + y)] + + pairsIndex = 0 + for queryIndex, minX, minY in sorted([IndexedQuery(i, query[0], query[1]) + for i, query in enumerate(queries)], + key=lambda iq: -iq.minX): + while pairsIndex < len(pairs) and pairs[pairsIndex].x >= minX: + # x + y is a better candidate. Given that x is decreasing, the + # condition "x + y >= stack[-1][1]" suggests that y is relatively + # larger, thereby making it a better candidate. + x, y = pairs[pairsIndex] + while stack and x + y >= stack[-1][1]: + stack.pop() + if not stack or y > stack[-1][0]: + stack.append((y, x + y)) + pairsIndex += 1 + j = self._firstGreaterEqual(stack, minY) + ans[queryIndex] = -1 if j == len(stack) else stack[j][1] + + return ans + + def _firstGreaterEqual(self, A: List[Tuple[int, int]], target: int) -> int: + l = 0 + r = len(A) + while l < r: + m = (l + r) // 2 + if A[m][0] >= target: + r = m + else: + l = m + 1 + return l diff --git a/solutions/2737. Find the Closest Marked Node/2737.cpp b/solutions/2737. Find the Closest Marked Node/2737.cpp new file mode 100644 index 00000000000..31a0545d521 --- /dev/null +++ b/solutions/2737. Find the Closest Marked Node/2737.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + int minimumDistance(int n, vector>& edges, int s, + vector& marked) { + int ans = INT_MAX; + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + } + + const vector dist = dijkstra(graph, s); + + for (const int u : marked) + ans = min(ans, dist[u]); + + return ans == INT_MAX ? -1 : ans; + } + + private: + vector dijkstra(const vector>>& graph, int src) { + vector dist(graph.size(), INT_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + } + + return dist; + } +}; diff --git a/solutions/2737. Find the Closest Marked Node/2737.java b/solutions/2737. Find the Closest Marked Node/2737.java new file mode 100644 index 00000000000..4e2183839b5 --- /dev/null +++ b/solutions/2737. Find the Closest Marked Node/2737.java @@ -0,0 +1,50 @@ +class Solution { + public int minimumDistance(int n, List> edges, int s, int[] marked) { + int ans = Integer.MAX_VALUE; + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (List edge : edges) { + final int u = edge.get(0); + final int v = edge.get(1); + final int w = edge.get(2); + graph[u].add(new Pair<>(v, w)); + } + + int[] dist = dijkstra(graph, s); + + for (final int u : marked) + ans = Math.min(ans, dist[u]); + + return ans == Integer.MAX_VALUE ? -1 : ans; + } + + private int[] dijkstra(List>[] graph, int src) { + int[] dist = new int[graph.length]; + Arrays.fill(dist, Integer.MAX_VALUE); + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + return dist; + } +} diff --git a/solutions/2737. Find the Closest Marked Node/2737.py b/solutions/2737. Find the Closest Marked Node/2737.py new file mode 100644 index 00000000000..b863ec36416 --- /dev/null +++ b/solutions/2737. Find the Closest Marked Node/2737.py @@ -0,0 +1,27 @@ +class Solution: + def minimumDistance(self, n: int, edges: List[List[int]], s: int, marked: List[int]) -> int: + graph = [[] for _ in range(n)] + + for u, v, w in edges: + graph[u].append((v, w)) + + dist = self._dijkstra(graph, s) + ans = min(dist[u] for u in marked) + return -1 if ans == math.inf else ans + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> List[int]: + dist = [math.inf] * len(graph) + + dist[src] = 0 + minHeap = [(dist[src], src)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + + return dist diff --git a/solutions/2738. Count Occurrences in Text/2738.sql b/solutions/2738. Count Occurrences in Text/2738.sql new file mode 100644 index 00000000000..3e1fcba47eb --- /dev/null +++ b/solutions/2738. Count Occurrences in Text/2738.sql @@ -0,0 +1,5 @@ +SELECT 'bull' AS word, SUM(content LIKE '% bull %') AS count +FROM Files +UNION ALL +SELECT 'bear' AS word, SUM(content LIKE '% bear %') AS count +FROM Files; diff --git a/solutions/2739. Total Distance Traveled/2739.cpp b/solutions/2739. Total Distance Traveled/2739.cpp new file mode 100644 index 00000000000..9813d79e0af --- /dev/null +++ b/solutions/2739. Total Distance Traveled/2739.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int distanceTraveled(int mainTank, int additionalTank) { + // M M M M M A M M M M A + // 1 [2 3 4 5] 6 [7 8 9 10] 11 + return (mainTank + min((mainTank - 1) / 4, additionalTank)) * 10; + } +}; diff --git a/solutions/2739. Total Distance Traveled/2739.java b/solutions/2739. Total Distance Traveled/2739.java new file mode 100644 index 00000000000..e929cc7f822 --- /dev/null +++ b/solutions/2739. Total Distance Traveled/2739.java @@ -0,0 +1,7 @@ +class Solution { + public int distanceTraveled(int mainTank, int additionalTank) { + // M M M M M A M M M M A + // 1 [2 3 4 5] 6 [7 8 9 10] 11 + return (mainTank + Math.min((mainTank - 1) / 4, additionalTank)) * 10; + } +} diff --git a/solutions/2739. Total Distance Traveled/2739.py b/solutions/2739. Total Distance Traveled/2739.py new file mode 100644 index 00000000000..2b788ce8906 --- /dev/null +++ b/solutions/2739. Total Distance Traveled/2739.py @@ -0,0 +1,5 @@ +class Solution: + def distanceTraveled(self, mainTank: int, additionalTank: int) -> int: + # M M M M M A M M M M A + # 1 [2 3 4 5] 6 [7 8 9 10] 11 + return (mainTank + min((mainTank - 1) // 4, additionalTank)) * 10 diff --git a/solutions/274. H-Index/274-2.cpp b/solutions/274. H-Index/274-2.cpp new file mode 100644 index 00000000000..7da16bc89d2 --- /dev/null +++ b/solutions/274. H-Index/274-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int hIndex(vector& citations) { + const int n = citations.size(); + + ranges::sort(citations); + + for (int i = 0; i < n; ++i) + if (citations[i] >= n - i) + return n - i; + + return 0; + } +}; diff --git a/solutions/274. H-Index/274-2.java b/solutions/274. H-Index/274-2.java new file mode 100644 index 00000000000..09d66bcf972 --- /dev/null +++ b/solutions/274. H-Index/274-2.java @@ -0,0 +1,13 @@ +class Solution { + public int hIndex(int[] citations) { + final int n = citations.length; + + Arrays.sort(citations); + + for (int i = 0; i < n; ++i) + if (citations[i] >= n - i) + return n - i; + + return 0; + } +} diff --git a/solutions/274. H-Index/274-2.py b/solutions/274. H-Index/274-2.py new file mode 100644 index 00000000000..0787cbd3874 --- /dev/null +++ b/solutions/274. H-Index/274-2.py @@ -0,0 +1,11 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + + citations.sort() + + for i, citation in enumerate(citations): + if citation >= n - i: + return n - i + + return 0 diff --git a/solutions/274. H-Index/274.cpp b/solutions/274. H-Index/274.cpp new file mode 100644 index 00000000000..cd09a522a43 --- /dev/null +++ b/solutions/274. H-Index/274.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int hIndex(vector& citations) { + const int n = citations.size(); + int accumulate = 0; + vector count(n + 1); + + for (const int citation : citations) + ++count[min(citation, n)]; + + // To find the maximum h-index, loop from the back to the front. + // i := the candidate's h-index + for (int i = n; i >= 0; --i) { + accumulate += count[i]; + if (accumulate >= i) + return i; + } + + throw; + } +}; diff --git a/solutions/274. H-Index/274.java b/solutions/274. H-Index/274.java new file mode 100644 index 00000000000..c72db14727a --- /dev/null +++ b/solutions/274. H-Index/274.java @@ -0,0 +1,20 @@ +class Solution { + public int hIndex(int[] citations) { + final int n = citations.length; + int accumulate = 0; + int[] count = new int[n + 1]; + + for (final int citation : citations) + ++count[Math.min(citation, n)]; + + // To find the maximum h-index, loop from the back to the front. + // i := the candidate's h-index + for (int i = n; i >= 0; --i) { + accumulate += count[i]; + if (accumulate >= i) + return i; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/274. H-Index/274.py b/solutions/274. H-Index/274.py new file mode 100644 index 00000000000..707e3a57292 --- /dev/null +++ b/solutions/274. H-Index/274.py @@ -0,0 +1,15 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + accumulate = 0 + count = [0] * (n + 1) + + for citation in citations: + count[min(citation, n)] += 1 + + # To find the maximum h-index, loop from the back to the front. + # i := the candidate's h-index + for i, c in reversed(list(enumerate(count))): + accumulate += c + if accumulate >= i: + return i diff --git a/solutions/2740. Find the Value of the Partition/2740.cpp b/solutions/2740. Find the Value of the Partition/2740.cpp new file mode 100644 index 00000000000..e03a27d88cc --- /dev/null +++ b/solutions/2740. Find the Value of the Partition/2740.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int findValueOfPartition(vector& nums) { + int ans = INT_MAX; + + sort(begin(nums), end(nums)); + + for (int i = 1; i < nums.size(); ++i) + ans = min(ans, nums[i] - nums[i - 1]); + + return ans; + } +}; diff --git a/solutions/2740. Find the Value of the Partition/2740.java b/solutions/2740. Find the Value of the Partition/2740.java new file mode 100644 index 00000000000..6a6f091cb7c --- /dev/null +++ b/solutions/2740. Find the Value of the Partition/2740.java @@ -0,0 +1,12 @@ +class Solution { + public int findValueOfPartition(int[] nums) { + int ans = Integer.MAX_VALUE; + + Arrays.sort(nums); + + for (int i = 1; i < nums.length; ++i) + ans = Math.min(ans, nums[i] - nums[i - 1]); + + return ans; + } +} diff --git a/solutions/2740. Find the Value of the Partition/2740.py b/solutions/2740. Find the Value of the Partition/2740.py new file mode 100644 index 00000000000..aa4b6ea2c0c --- /dev/null +++ b/solutions/2740. Find the Value of the Partition/2740.py @@ -0,0 +1,3 @@ +class Solution: + def findValueOfPartition(self, nums: List[int]) -> int: + return min(b - a for a, b in itertools.pairwise(sorted(nums))) diff --git a/solutions/2741. Special Permutations/2741.cpp b/solutions/2741. Special Permutations/2741.cpp new file mode 100644 index 00000000000..1203f82f81f --- /dev/null +++ b/solutions/2741. Special Permutations/2741.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int specialPerm(vector& nums) { + const int n = nums.size(); + const int maxMask = 1 << n; + int ans = 0; + vector> mem(n, vector(maxMask)); + + for (int i = 0; i < n; ++i) { + ans += specialPerm(nums, i, 1 << i, maxMask, mem); + ans %= kMod; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of special permutations, where the previous number is + // nums[i] and `mask` is the bitmask of the used numbers. + int specialPerm(const vector& nums, int prev, int mask, + const int& maxMask, vector>& mem) { + if (mask == maxMask - 1) + return 1; + if (mem[prev][mask] > 0) + return mem[prev][mask]; + + int res = 0; + + for (int i = 0; i < nums.size(); ++i) { + if (mask >> i & 1) + continue; + if (nums[i] % nums[prev] == 0 || nums[prev] % nums[i] == 0) { + res += specialPerm(nums, i, mask | 1 << i, maxMask, mem); + res %= kMod; + } + } + + return mem[prev][mask] = res; + } +}; diff --git a/solutions/2741. Special Permutations/2741.java b/solutions/2741. Special Permutations/2741.java new file mode 100644 index 00000000000..0ca483d26ab --- /dev/null +++ b/solutions/2741. Special Permutations/2741.java @@ -0,0 +1,39 @@ +class Solution { + public int specialPerm(int[] nums) { + final int n = nums.length; + final int maxMask = 1 << n; + int ans = 0; + int[][] mem = new int[n][maxMask]; + + for (int i = 0; i < n; ++i) { + ans += specialPerm(nums, i, 1 << i, maxMask, mem); + ans %= kMod; + } + + return ans; + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of special permutations, where the previous number is + // nums[i] and `mask` is the bitmask of the used numbers. + private int specialPerm(int[] nums, int prev, int mask, int maxMask, int[][] mem) { + if (mask == maxMask - 1) + return 1; + if (mem[prev][mask] != 0) + return mem[prev][mask]; + + int res = 0; + + for (int i = 0; i < nums.length; ++i) { + if ((mask >> i & 1) == 1) + continue; + if (nums[i] % nums[prev] == 0 || nums[prev] % nums[i] == 0) { + res += specialPerm(nums, i, mask | 1 << i, maxMask, mem); + res %= kMod; + } + } + + return mem[prev][mask] = res; + } +} diff --git a/solutions/2741. Special Permutations/2741.py b/solutions/2741. Special Permutations/2741.py new file mode 100644 index 00000000000..8a9fc705bfc --- /dev/null +++ b/solutions/2741. Special Permutations/2741.py @@ -0,0 +1,27 @@ +class Solution: + def specialPerm(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + maxMask = 1 << len(nums) + + @functools.lru_cache(None) + def dp(prev: int, mask: int) -> int: + """ + Returns the number of special permutations, where the previous number is + nums[i] and `mask` is the bitmask of the used numbers. + """ + if mask == maxMask - 1: + return 1 + + res = 0 + + for i, num in enumerate(nums): + if mask >> i & 1: + continue + if num % nums[prev] == 0 or nums[prev] % num == 0: + res += dp(i, mask | 1 << i) + res %= kMod + + return res + + return sum(dp(i, 1 << i) + for i in range(len(nums))) % kMod diff --git a/solutions/2742. Painting the Walls/2742-2.cpp b/solutions/2742. Painting the Walls/2742-2.cpp new file mode 100644 index 00000000000..dd1b72decc1 --- /dev/null +++ b/solutions/2742. Painting the Walls/2742-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int paintWalls(vector& cost, vector& time) { + constexpr int kMax = 500'000'000; + const int n = cost.size(); + // dp[i] := the minimum cost to paint i walls by the painters so far + vector dp(n + 1, kMax); + dp[0] = 0; + + for (int i = 0; i < n; ++i) + for (int walls = n; walls > 0; --walls) + dp[walls] = min(dp[walls], dp[max(walls - time[i] - 1, 0)] + cost[i]); + + return dp[n]; + } +}; diff --git a/solutions/2742. Painting the Walls/2742-2.java b/solutions/2742. Painting the Walls/2742-2.java new file mode 100644 index 00000000000..a29053e1f25 --- /dev/null +++ b/solutions/2742. Painting the Walls/2742-2.java @@ -0,0 +1,16 @@ +class Solution { + public int paintWalls(int[] cost, int[] time) { + final int kMax = 500_000_000; + final int n = cost.length; + // dp[i] := the minimum cost to paint i walls by the painters so far + int[] dp = new int[n + 1]; + Arrays.fill(dp, kMax); + dp[0] = 0; + + for (int i = 0; i < n; ++i) + for (int walls = n; walls > 0; --walls) + dp[walls] = Math.min(dp[walls], dp[Math.max(walls - time[i] - 1, 0)] + cost[i]); + + return dp[n]; + } +} diff --git a/solutions/2742. Painting the Walls/2742-2.py b/solutions/2742. Painting the Walls/2742-2.py new file mode 100644 index 00000000000..7d813e66c1f --- /dev/null +++ b/solutions/2742. Painting the Walls/2742-2.py @@ -0,0 +1,12 @@ +class Solution: + def paintWalls(self, cost: List[int], time: List[int]) -> int: + kMax = 500_000_000 + n = len(cost) + # dp[i] := the minimum cost to paint i walls by the painters so far + dp = [0] + [kMax] * n + + for c, t in zip(cost, time): + for walls in range(n, 0, -1): + dp[walls] = min(dp[walls], dp[max(walls - t - 1, 0)] + c) + + return dp[n] diff --git a/solutions/2742. Painting the Walls/2742.cpp b/solutions/2742. Painting the Walls/2742.cpp new file mode 100644 index 00000000000..b659038d7fc --- /dev/null +++ b/solutions/2742. Painting the Walls/2742.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int paintWalls(vector& cost, vector& time) { + const int n = cost.size(); + vector> mem(n, vector(n + 1)); + return paintWalls(cost, time, 0, time.size(), mem); + } + + private: + static constexpr int kMax = 500'000'000; + + // Returns the minimum cost to paint j walls by painters[i..n). + int paintWalls(const vector& cost, const vector& time, int i, + int walls, vector>& mem) { + if (walls <= 0) + return 0; + if (i == cost.size()) + return kMax; + if (mem[i][walls] > 0) + return mem[i][walls]; + const int pick = + cost[i] + paintWalls(cost, time, i + 1, walls - time[i] - 1, mem); + const int skip = paintWalls(cost, time, i + 1, walls, mem); + return mem[i][walls] = min(pick, skip); + } +}; diff --git a/solutions/2742. Painting the Walls/2742.java b/solutions/2742. Painting the Walls/2742.java new file mode 100644 index 00000000000..3866b31047b --- /dev/null +++ b/solutions/2742. Painting the Walls/2742.java @@ -0,0 +1,22 @@ +class Solution { + public int paintWalls(int[] cost, int[] time) { + final int n = cost.length; + int[][] mem = new int[n][n + 1]; + return paintWalls(cost, time, 0, time.length, mem); + } + + private static final int kMax = 500_000_000; + + // Returns the minimum cost to paint j walls by painters[i..n). + private int paintWalls(int[] cost, int[] time, int i, int walls, int[][] mem) { + if (walls <= 0) + return 0; + if (i == cost.length) + return kMax; + if (mem[i][walls] > 0) + return mem[i][walls]; + final int pick = cost[i] + paintWalls(cost, time, i + 1, walls - time[i] - 1, mem); + final int skip = paintWalls(cost, time, i + 1, walls, mem); + return mem[i][walls] = Math.min(pick, skip); + } +} diff --git a/solutions/2742. Painting the Walls/2742.py b/solutions/2742. Painting the Walls/2742.py new file mode 100644 index 00000000000..5be2c323d91 --- /dev/null +++ b/solutions/2742. Painting the Walls/2742.py @@ -0,0 +1,16 @@ +class Solution: + def paintWalls(self, cost: List[int], time: List[int]) -> int: + n = len(cost) + + @functools.lru_cache(None) + def dp(i: int, walls: int) -> int: + """Returns the minimum cost to paint j walls by painters[i..n).""" + if walls <= 0: + return 0 + if i == n: + return math.inf + pick = cost[i] + dp(i + 1, walls - time[i] - 1) + skip = dp(i + 1, walls) + return min(pick, skip) + + return dp(0, n) diff --git a/solutions/2743. Count Substrings Without Repeating Character/2743.cpp b/solutions/2743. Count Substrings Without Repeating Character/2743.cpp new file mode 100644 index 00000000000..d1f148b191c --- /dev/null +++ b/solutions/2743. Count Substrings Without Repeating Character/2743.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int numberOfSpecialSubstrings(string s) { + int ans = 0; + vector count(26); + + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s[r] - 'a']; + while (count[s[r] - 'a'] == 2) + --count[s[l++] - 'a']; + ans += r - l + 1; + } + + return ans; + } +}; diff --git a/solutions/2743. Count Substrings Without Repeating Character/2743.java b/solutions/2743. Count Substrings Without Repeating Character/2743.java new file mode 100644 index 00000000000..cec8036718a --- /dev/null +++ b/solutions/2743. Count Substrings Without Repeating Character/2743.java @@ -0,0 +1,15 @@ +class Solution { + public int numberOfSpecialSubstrings(String s) { + int ans = 0; + int[] count = new int[26]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s.charAt(r) - 'a']; + while (count[s.charAt(r) - 'a'] == 2) + --count[s.charAt(l++) - 'a']; + ans += r - l + 1; + } + + return ans; + } +} diff --git a/solutions/2743. Count Substrings Without Repeating Character/2743.py b/solutions/2743. Count Substrings Without Repeating Character/2743.py new file mode 100644 index 00000000000..58ae9500703 --- /dev/null +++ b/solutions/2743. Count Substrings Without Repeating Character/2743.py @@ -0,0 +1,14 @@ +class Solution: + def numberOfSpecialSubstrings(self, s: str) -> int: + ans = 0 + count = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + while count[c] == 2: + count[s[l]] -= 1 + l += 1 + ans += r - l + 1 + + return ans diff --git a/solutions/2744. Find Maximum Number of String Pairs/2744.cpp b/solutions/2744. Find Maximum Number of String Pairs/2744.cpp new file mode 100644 index 00000000000..0e4cb60f4aa --- /dev/null +++ b/solutions/2744. Find Maximum Number of String Pairs/2744.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maximumNumberOfStringPairs(vector& words) { + int ans = 0; + vector seen(26 * 26); + + for (const string& word : words) { + if (seen[val(word[1]) * 26 + val(word[0])]) + ++ans; + seen[val(word[0]) * 26 + val(word[1])] = true; + } + + return ans; + } + + private: + constexpr int val(char c) { + return c - 'a'; + } +}; diff --git a/solutions/2744. Find Maximum Number of String Pairs/2744.java b/solutions/2744. Find Maximum Number of String Pairs/2744.java new file mode 100644 index 00000000000..f8581822d74 --- /dev/null +++ b/solutions/2744. Find Maximum Number of String Pairs/2744.java @@ -0,0 +1,18 @@ +class Solution { + public int maximumNumberOfStringPairs(String[] words) { + int ans = 0; + boolean[] seen = new boolean[26 * 26]; + + for (final String word : words) { + if (seen[val(word.charAt(1)) * 26 + val(word.charAt(0))]) + ++ans; + seen[val(word.charAt(0)) * 26 + val(word.charAt(1))] = true; + } + + return ans; + } + + private final int val(char c) { + return c - 'a'; + } +} diff --git a/solutions/2744. Find Maximum Number of String Pairs/2744.py b/solutions/2744. Find Maximum Number of String Pairs/2744.py new file mode 100644 index 00000000000..1d8a504951a --- /dev/null +++ b/solutions/2744. Find Maximum Number of String Pairs/2744.py @@ -0,0 +1,14 @@ +class Solution: + def maximumNumberOfStringPairs(self, words: List[str]) -> int: + ans = 0 + seen = [False] * (26 * 26) + + def val(c: str) -> int: + return ord(c) - ord('a') + + for word in words: + if seen[val(word[1]) * 26 + val(word[0])]: + ans += 1 + seen[val(word[0]) * 26 + val(word[1])] = True + + return ans diff --git a/solutions/2745. Construct the Longest New String/2745.cpp b/solutions/2745. Construct the Longest New String/2745.cpp new file mode 100644 index 00000000000..0af1181f88a --- /dev/null +++ b/solutions/2745. Construct the Longest New String/2745.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int longestString(int x, int y, int z) { + //"AB" can always be easily appended within the string. + // Alternating "AA" and "BB" can be appended, creating a pattern like "AABB" + // If x == y, we repeat the pattern "AABBAABB...AABB". + // If x != y, the pattern becomes "AABBAABB...AABBAA" or "BBAABBAABB...AABB" + const int mn = min(x, y); + if (x == y) + return (mn * 2 + z) * 2; + return (mn * 2 + 1 + z) * 2; + } +}; diff --git a/solutions/2745. Construct the Longest New String/2745.java b/solutions/2745. Construct the Longest New String/2745.java new file mode 100644 index 00000000000..e51b3c3108d --- /dev/null +++ b/solutions/2745. Construct the Longest New String/2745.java @@ -0,0 +1,8 @@ +class Solution { + public int longestString(int x, int y, int z) { + final int mn = Math.min(x, y); + if (x == y) + return (mn * 2 + z) * 2; + return (mn * 2 + 1 + z) * 2; + } +} diff --git a/solutions/2745. Construct the Longest New String/2745.py b/solutions/2745. Construct the Longest New String/2745.py new file mode 100644 index 00000000000..0bac0adec70 --- /dev/null +++ b/solutions/2745. Construct the Longest New String/2745.py @@ -0,0 +1,10 @@ +class Solution: + def longestString(self, x: int, y: int, z: int) -> int: + # 'AB' can always be easily appended within the string. + # Alternating 'AA' and 'BB' can be appended, creating a pattern like 'AABB' + # If x == y, we repeat the pattern 'AABBAABB...AABB'. + # If x != y, the pattern becomes 'AABBAABB...AABBAA' or 'BBAABBAABB...AABB' + mn = min(x, y) + if x == y: + return (mn * 2 + z) * 2 + return (mn * 2 + 1 + z) * 2 diff --git a/solutions/2746. Decremental String Concatenation/2746.cpp b/solutions/2746. Decremental String Concatenation/2746.cpp new file mode 100644 index 00000000000..c0a127e93e0 --- /dev/null +++ b/solutions/2746. Decremental String Concatenation/2746.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minimizeConcatenatedLength(vector& words) { + vector>> mem(words.size(), + vector>(26, vector(26))); + return words[0].length() + minimizeConcatenatedLength(words, 1, + words[0].front(), + words[0].back(), mem); + } + + private: + // Returns the minimum concatenated length of the first i words starting with + // `first` and ending in `last`. + int minimizeConcatenatedLength(const vector& words, int i, char first, + char last, vector>>& mem) { + if (i == words.size()) + return 0; + const int j = first - 'a'; + const int k = last - 'a'; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + const char nextFirst = words[i].front(); + const char nextLast = words[i].back(); + return mem[i][j][k] = // + words[i].length() + + min( + // join(words[i - 1], words[i]) + minimizeConcatenatedLength(words, i + 1, first, nextLast, mem) - + (last == nextFirst ? 1 : 0), + // join(words[i], words[i - 1]) + minimizeConcatenatedLength(words, i + 1, nextFirst, last, mem) - + (first == nextLast ? 1 : 0)); + } +}; diff --git a/solutions/2746. Decremental String Concatenation/2746.java b/solutions/2746. Decremental String Concatenation/2746.java new file mode 100644 index 00000000000..c37624125b7 --- /dev/null +++ b/solutions/2746. Decremental String Concatenation/2746.java @@ -0,0 +1,29 @@ +class Solution { + public int minimizeConcatenatedLength(String[] words) { + int[][][] mem = new int[words.length][26][26]; + return words[0].length() + minimizeConcatenatedLength(words, 1, words[0].charAt(0), + words[0].charAt(words[0].length() - 1), + mem); + } + + private int minimizeConcatenatedLength(String[] words, int i, char first, char last, + int[][][] mem) { + if (i == words.length) + return 0; + final int j = first - 'a'; + final int k = last - 'a'; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + final char nextFirst = words[i].charAt(0); + final char nextLast = words[i].charAt(words[i].length() - 1); + return mem[i][j][k] = // + words[i].length() + // + Math.min( + // join(words[i - 1], words[i]) + minimizeConcatenatedLength(words, i + 1, first, nextLast, mem) - + (last == nextFirst ? 1 : 0), + // join(words[i], words[i - 1]) + minimizeConcatenatedLength(words, i + 1, nextFirst, last, mem) - + (first == nextLast ? 1 : 0)); + } +} diff --git a/solutions/2746. Decremental String Concatenation/2746.py b/solutions/2746. Decremental String Concatenation/2746.py new file mode 100644 index 00000000000..1fa1a3ad078 --- /dev/null +++ b/solutions/2746. Decremental String Concatenation/2746.py @@ -0,0 +1,20 @@ +class Solution: + def minimizeConcatenatedLength(self, words: List[str]) -> int: + @functools.lru_cache(None) + def dp(i: int, first: str, last: str) -> int: + """ + Returns the minimum concatenated length of the first i words starting with + `first` and ending in `last`. + """ + if i == len(words): + return 0 + nextFirst = words[i][0] + nextLast = words[i][-1] + return len(words[i]) + min( + # join(words[i - 1], words[i]) + dp(i + 1, first, nextLast) - (last == nextFirst), + # join(words[i], words[i - 1]) + dp(i + 1, nextFirst, last) - (first == nextLast) + ) + + return len(words[0]) + dp(1, words[0][0], words[0][-1]) diff --git a/solutions/2747. Count Zero Request Servers/2747.cpp b/solutions/2747. Count Zero Request Servers/2747.cpp new file mode 100644 index 00000000000..1451c96f36e --- /dev/null +++ b/solutions/2747. Count Zero Request Servers/2747.cpp @@ -0,0 +1,46 @@ +struct IndexedQuery { + int queryIndex; + int query; +}; + +class Solution { + public: + vector countServers(int n, vector>& logs, int x, + vector& queries) { + vector ans(queries.size()); + vector count(n + 1); + + ranges::sort(logs, [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + + int i = 0; + int j = 0; + int servers = 0; + + // For each query, we care about logs[i..j]. + for (const auto& [queryIndex, query] : getIndexedQueries(queries)) { + for (; j < logs.size() && logs[j][1] <= query; ++j) + if (++count[logs[j][0]] == 1) + ++servers; + for (; i < logs.size() && logs[i][1] < query - x; ++i) + if (--count[logs[i][0]] == 0) + --servers; + ans[queryIndex] = n - servers; + } + + return ans; + } + + private: + vector getIndexedQueries(const vector& queries) { + vector indexedQueries; + for (int i = 0; i < queries.size(); ++i) + indexedQueries.push_back({i, queries[i]}); + ranges::sort(indexedQueries, + [](const IndexedQuery& a, const IndexedQuery& b) { + return a.query < b.query; + }); + return indexedQueries; + } +}; diff --git a/solutions/2747. Count Zero Request Servers/2747.java b/solutions/2747. Count Zero Request Servers/2747.java new file mode 100644 index 00000000000..ce6360f05f4 --- /dev/null +++ b/solutions/2747. Count Zero Request Servers/2747.java @@ -0,0 +1,37 @@ +class Solution { + public int[] countServers(int n, int[][] logs, int x, int[] queries) { + int[] ans = new int[queries.length]; + int[] count = new int[n + 1]; + + Arrays.sort(logs, (a, b) -> Integer.compare(a[1], b[1])); + + int i = 0; + int j = 0; + int servers = 0; + + // For each query, we care about logs[i..j]. + for (IndexedQuery indexedQuery : getIndexedQueries(queries)) { + final int queryIndex = indexedQuery.queryIndex; + final int query = indexedQuery.query; + for (; j < logs.length && logs[j][1] <= query; ++j) + if (++count[logs[j][0]] == 1) + ++servers; + for (; i < logs.length && logs[i][1] < query - x; ++i) + if (--count[logs[i][0]] == 0) + --servers; + ans[queryIndex] = n - servers; + } + + return ans; + } + + private record IndexedQuery(int queryIndex, int query){}; + + private IndexedQuery[] getIndexedQueries(int[] queries) { + IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; + for (int i = 0; i < queries.length; ++i) + indexedQueries[i] = new IndexedQuery(i, queries[i]); + Arrays.sort(indexedQueries, (a, b) -> a.query - b.query); + return indexedQueries; + } +} diff --git a/solutions/2747. Count Zero Request Servers/2747.py b/solutions/2747. Count Zero Request Servers/2747.py new file mode 100644 index 00000000000..0722b14b01c --- /dev/null +++ b/solutions/2747. Count Zero Request Servers/2747.py @@ -0,0 +1,38 @@ +class IndexedQuery: + def __init__(self, queryIndex: int, query: int): + self.queryIndex = queryIndex + self.query = query + + def __iter__(self): + yield self.queryIndex + yield self.query + + +class Solution: + def countServers(self, n: int, logs: List[List[int]], x: int, queries: List[int]) -> List[int]: + ans = [0] * len(queries) + count = [0] * (n + 1) + + logs.sort(key=lambda log: log[1]) + + i = 0 + j = 0 + servers = 0 + + # For each query, we care about logs[i..j]. + for queryIndex, query in sorted([IndexedQuery(i, query) + for i, query in enumerate(queries)], + key=lambda iq: iq.query): + while j < len(logs) and logs[j][1] <= query: + count[logs[j][0]] += 1 + if count[logs[j][0]] == 1: + servers += 1 + j += 1 + while i < len(logs) and logs[i][1] < query - x: + count[logs[i][0]] -= 1 + if count[logs[i][0]] == 0: + servers -= 1 + i += 1 + ans[queryIndex] = n - servers + + return ans diff --git a/solutions/2748. Number of Beautiful Pairs/2748.cpp b/solutions/2748. Number of Beautiful Pairs/2748.cpp new file mode 100644 index 00000000000..5f55acabf19 --- /dev/null +++ b/solutions/2748. Number of Beautiful Pairs/2748.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int countBeautifulPairs(vector& nums) { + int ans = 0; + + for (int i = 0; i < nums.size(); ++i) + for (int j = i + 1; j < nums.size(); ++j) + if (__gcd(firstDigit(nums[i]), lastDigit(nums[j])) == 1) + ++ans; + + return ans; + } + + private: + int firstDigit(int num) { + return to_string(num)[0] - '0'; + } + + int lastDigit(int num) { + return num % 10; + } +}; diff --git a/solutions/2748. Number of Beautiful Pairs/2748.java b/solutions/2748. Number of Beautiful Pairs/2748.java new file mode 100644 index 00000000000..6427f3b02f8 --- /dev/null +++ b/solutions/2748. Number of Beautiful Pairs/2748.java @@ -0,0 +1,24 @@ +class Solution { + public int countBeautifulPairs(int[] nums) { + int ans = 0; + + for (int i = 0; i < nums.length; ++i) + for (int j = i + 1; j < nums.length; ++j) + if (gcd(firstDigit(nums[i]), lastDigit(nums[j])) == 1) + ++ans; + + return ans; + } + + private int firstDigit(int num) { + return Integer.parseInt(Integer.toString(num).substring(0, 1)); + } + + private int lastDigit(int num) { + return num % 10; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2748. Number of Beautiful Pairs/2748.py b/solutions/2748. Number of Beautiful Pairs/2748.py new file mode 100644 index 00000000000..36a1ab36ec2 --- /dev/null +++ b/solutions/2748. Number of Beautiful Pairs/2748.py @@ -0,0 +1,11 @@ +class Solution: + def countBeautifulPairs(self, nums: List[int]) -> int: + def firstDigit(num: int) -> int: + return int(str(num)[0]) + + def lastDigit(num: int) -> int: + return num % 10 + + return sum(math.gcd(firstDigit(nums[i]), lastDigit(nums[j])) == 1 + for i in range(len(nums)) + for j in range(i + 1, len(nums))) diff --git a/solutions/2749. Minimum Operations to Make the Integer Zero/2749.cpp b/solutions/2749. Minimum Operations to Make the Integer Zero/2749.cpp new file mode 100644 index 00000000000..49eda2d3e53 --- /dev/null +++ b/solutions/2749. Minimum Operations to Make the Integer Zero/2749.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int makeTheIntegerZero(int num1, int num2) { + // If k operations are used, num1 - [(num2 + 2^{i_1}) + (num2 + 2^{i_2}) + + // ... + (num2 + 2^{i_k})] = 0. So, num1 - k * num2 = (2^{i_1} + 2^{i_2} + + // ... + 2^{i_k}), where i_1, i_2, ..., i_k are in the range [0, 60]. + // Note that for any number x, we can use "x's bit count" operations to make + // x equal to 0. Additionally, we can also use x operations to deduct x by + // 2^0 (x times), which also results in 0. + + for (long ops = 0; ops <= 60; ++ops) { + const long target = num1 - ops * num2; + if (__builtin_popcountl(target) <= ops && ops <= target) + return ops; + } + + return -1; + } +}; diff --git a/solutions/2749. Minimum Operations to Make the Integer Zero/2749.java b/solutions/2749. Minimum Operations to Make the Integer Zero/2749.java new file mode 100644 index 00000000000..5a54399da13 --- /dev/null +++ b/solutions/2749. Minimum Operations to Make the Integer Zero/2749.java @@ -0,0 +1,18 @@ +class Solution { + public int makeTheIntegerZero(int num1, int num2) { + // If k operations are used, num1 - [(num2 + 2^{i_1}) + (num2 + 2^{i_2}) + + // ... + (num2 + 2^{i_k})] = 0. So, num1 - k * num2 = (2^{i_1} + 2^{i_2} + + // ... + 2^{i_k}), where i_1, i_2, ..., i_k are in the range [0, 60]. + // Note that for any number x, we can use "x's bit count" operations to make + // x equal to 0. Additionally, we can also use x operations to deduct x by + // 2^0 (x times), which also results in 0. + + for (long ops = 0; ops <= 60; ++ops) { + long target = num1 - ops * num2; + if (Long.bitCount(target) <= ops && ops <= target) + return (int) ops; + } + + return -1; + } +} diff --git a/solutions/2749. Minimum Operations to Make the Integer Zero/2749.py b/solutions/2749. Minimum Operations to Make the Integer Zero/2749.py new file mode 100644 index 00000000000..ec1f19e4c9e --- /dev/null +++ b/solutions/2749. Minimum Operations to Make the Integer Zero/2749.py @@ -0,0 +1,15 @@ +class Solution: + def makeTheIntegerZero(self, num1: int, num2: int) -> int: + # If k operations are used, num1 - [(num2 + 2^{i_1}) + (num2 + 2^{i_2}) + + # ... + (num2 + 2^{i_k})] = 0. So, num1 - k * num2 = (2^{i_1} + 2^{i_2} + + # ... + 2^{i_k}), where i_1, i_2, ..., i_k are in the range [0, 60]. + # Note that for any number x, we can use "x's bit count" operations to make + # x equal to 0. Additionally, we can also use x operations to deduct x by + # 2^0 (x times), which also results in 0. + + for ops in range(61): + target = num1 - ops * num2 + if target.bit_count() <= ops <= target: + return ops + + return -1 diff --git a/solutions/275. H-Index II/275.cpp b/solutions/275. H-Index II/275.cpp new file mode 100644 index 00000000000..58874384131 --- /dev/null +++ b/solutions/275. H-Index II/275.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int hIndex(vector& citations) { + const int n = citations.size(); + int l = 0; + int r = n; + + while (l < r) { + const int m = (l + r) / 2; + if (citations[m] >= n - m) + r = m; + else + l = m + 1; + } + + return n - l; + } +}; diff --git a/solutions/275. H-Index II/275.java b/solutions/275. H-Index II/275.java new file mode 100644 index 00000000000..3fe0dec18fb --- /dev/null +++ b/solutions/275. H-Index II/275.java @@ -0,0 +1,17 @@ +class Solution { + public int hIndex(int[] citations) { + final int n = citations.length; + int l = 0; + int r = n; + + while (l < r) { + final int m = (l + r) / 2; + if (citations[m] >= n - m) + r = m; + else + l = m + 1; + } + + return n - l; + } +} diff --git a/solutions/275. H-Index II/275.py b/solutions/275. H-Index II/275.py new file mode 100644 index 00000000000..8ac43f1b707 --- /dev/null +++ b/solutions/275. H-Index II/275.py @@ -0,0 +1,5 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + return n - bisect.bisect_left(range(n), n, + key=lambda m: citations[m] + m) diff --git a/solutions/2750. Ways to Split Array Into Good Subarrays/2750.cpp b/solutions/2750. Ways to Split Array Into Good Subarrays/2750.cpp new file mode 100644 index 00000000000..2b01896b728 --- /dev/null +++ b/solutions/2750. Ways to Split Array Into Good Subarrays/2750.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int numberOfGoodSubarraySplits(vector& nums) { + if (ranges::count(nums, 1) == 0) + return 0; + + constexpr int kMod = 1'000'000'007; + int prev = -1; // the previous index of 1 + int ans = 1; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == 1) { + if (prev != -1) + ans = ans * static_cast(i - prev) % kMod; + prev = i; + } + + return ans; + } +}; diff --git a/solutions/2750. Ways to Split Array Into Good Subarrays/2750.java b/solutions/2750. Ways to Split Array Into Good Subarrays/2750.java new file mode 100644 index 00000000000..373cdb61491 --- /dev/null +++ b/solutions/2750. Ways to Split Array Into Good Subarrays/2750.java @@ -0,0 +1,19 @@ +class Solution { + public int numberOfGoodSubarraySplits(int[] nums) { + if (Arrays.stream(nums).filter(num -> num == 1).count() == 0) + return 0; + + final int kMod = 1_000_000_007; + int prev = -1; // the previous index of 1 + int ans = 1; + + for (int i = 0; i < nums.length; ++i) + if (nums[i] == 1) { + if (prev != -1) + ans = (int) ((long) ans * (i - prev) % kMod); + prev = i; + } + + return ans; + } +} diff --git a/solutions/2750. Ways to Split Array Into Good Subarrays/2750.py b/solutions/2750. Ways to Split Array Into Good Subarrays/2750.py new file mode 100644 index 00000000000..bf6ac6be447 --- /dev/null +++ b/solutions/2750. Ways to Split Array Into Good Subarrays/2750.py @@ -0,0 +1,17 @@ +class Solution: + def numberOfGoodSubarraySplits(self, nums: List[int]) -> int: + if 1 not in nums: + return 0 + + kMod = 1_000_000_007 + prev = -1 # the previous index of 1 + ans = 1 + + for i, num in enumerate(nums): + if num == 1: + if prev != -1: + ans *= i - prev + ans %= kMod + prev = i + + return ans diff --git a/solutions/2751. Robot Collisions/2751.cpp b/solutions/2751. Robot Collisions/2751.cpp new file mode 100644 index 00000000000..fe5ee795cfe --- /dev/null +++ b/solutions/2751. Robot Collisions/2751.cpp @@ -0,0 +1,55 @@ +struct Robot { + int index; + int position; + int health; + char direction; +}; + +class Solution { + public: + vector survivedRobotsHealths(vector& positions, + vector& healths, string directions) { + vector ans; + vector robots; + vector stack; // the runnnig robots + + for (int i = 0; i < positions.size(); ++i) + robots.push_back(Robot{i, positions[i], healths[i], directions[i]}); + + ranges::sort(robots, [](const Robot& a, const Robot& b) { + return a.position < b.position; + }); + + for (Robot& robot : robots) { + if (robot.direction == 'R') { + stack.push_back(robot); + continue; + } + // Collide with robots going right if any. + while (!stack.empty() && stack.back().direction == 'R' && + robot.health > 0) { + if (stack.back().health == robot.health) { + stack.pop_back(); + robot.health = 0; + } else if (stack.back().health < robot.health) { + stack.pop_back(); + robot.health -= 1; + } else { // stack.back().health > robot.health + stack.back().health -= 1; + robot.health = 0; + } + } + if (robot.health > 0) + stack.push_back(robot); + } + + ranges::sort(stack, [](const Robot& a, const Robot& b) { + return a.index < b.index; + }); + + for (const Robot& robot : stack) + ans.push_back(robot.health); + + return ans; + } +}; diff --git a/solutions/2751. Robot Collisions/2751.java b/solutions/2751. Robot Collisions/2751.java new file mode 100644 index 00000000000..68acb36731b --- /dev/null +++ b/solutions/2751. Robot Collisions/2751.java @@ -0,0 +1,54 @@ +class Robot { + public int index; + public int position; + public int health; + public char direction; + public Robot(int index, int position, int health, char direction) { + this.index = index; + this.position = position; + this.health = health; + this.direction = direction; + } +} + +class Solution { + public List survivedRobotsHealths(int[] positions, int[] healths, String directions) { + List ans = new ArrayList<>(); + Robot[] robots = new Robot[positions.length]; + List stack = new ArrayList<>(); // running robots + + for (int i = 0; i < positions.length; ++i) + robots[i] = new Robot(i, positions[i], healths[i], directions.charAt(i)); + + Arrays.sort(robots, (a, b) -> a.position - b.position); + + for (Robot robot : robots) { + if (robot.direction == 'R') { + stack.add(robot); + continue; + } + // Collide with robots going right if any. + while (!stack.isEmpty() && stack.get(stack.size() - 1).direction == 'R' && robot.health > 0) { + if (stack.get(stack.size() - 1).health == robot.health) { + stack.remove(stack.size() - 1); + robot.health = 0; + } else if (stack.get(stack.size() - 1).health < robot.health) { + stack.remove(stack.size() - 1); + robot.health -= 1; + } else { // stack[-1].health > robot.health + stack.get(stack.size() - 1).health -= 1; + robot.health = 0; + } + } + if (robot.health > 0) + stack.add(robot); + } + + stack.sort((a, b) -> a.index - b.index); + + for (Robot robot : stack) + ans.add(robot.health); + + return ans; + } +} diff --git a/solutions/2751. Robot Collisions/2751.py b/solutions/2751. Robot Collisions/2751.py new file mode 100644 index 00000000000..839cf55d4f6 --- /dev/null +++ b/solutions/2751. Robot Collisions/2751.py @@ -0,0 +1,36 @@ +@dataclass +class Robot: + index: int + position: int + health: int + direction: str + + +class Solution: + def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]: + robots = sorted([Robot(index, position, health, direction) + for index, (position, health, direction) in + enumerate(zip(positions, healths, directions))], + key=lambda robot: robot.position) + stack: List[Robot] = [] # running robots + + for robot in robots: + if robot.direction == 'R': + stack.append(robot) + continue + # Collide with robots going right if any. + while stack and stack[-1].direction == 'R' and robot.health > 0: + if stack[-1].health == robot.health: + stack.pop() + robot.health = 0 + elif stack[-1].health < robot.health: + stack.pop() + robot.health -= 1 + else: # stack[-1].health > robot.health + stack[-1].health -= 1 + robot.health = 0 + if robot.health > 0: + stack.append(robot) + + stack.sort(key=lambda robot: robot.index) + return [robot.health for robot in stack] diff --git a/solutions/2752. Customers with Maximum Number of Transactions on Consecutive Days/2752.sql b/solutions/2752. Customers with Maximum Number of Transactions on Consecutive Days/2752.sql new file mode 100644 index 00000000000..e8a54494845 --- /dev/null +++ b/solutions/2752. Customers with Maximum Number of Transactions on Consecutive Days/2752.sql @@ -0,0 +1,21 @@ +WITH + TransactionsWithGroupId AS ( + SELECT + customer_id, + TO_DAYS(transaction_date) - ROW_NUMBER() OVER( + PARTITION BY customer_id + ORDER BY transaction_date + ) AS group_id + FROM Transactions + ), + RankedCustomers AS ( + SELECT + customer_id, + RANK() OVER(ORDER BY COUNT(*) DESC) AS `rank` + FROM TransactionsWithGroupId + GROUP BY customer_id, group_id + ) +SELECT customer_id +FROM RankedCustomers +WHERE `rank` = 1 +ORDER BY 1; diff --git a/solutions/2753. Count Houses in a Circular Street II/2753.cpp b/solutions/2753. Count Houses in a Circular Street II/2753.cpp new file mode 100644 index 00000000000..a6a3c1d24b7 --- /dev/null +++ b/solutions/2753. Count Houses in a Circular Street II/2753.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a street. + * class Street { + * public: + * Street(vector doors); + * void closeDoor(); + * bool isDoorOpen(); + * void moveRight(); + * }; + */ +class Solution { + public: + int houseCount(Street* street, int k) { + int ans = 0; + + // Go to the first open door. + while (!street->isDoorOpen()) + street->moveRight(); + + street->moveRight(); + + for (int count = 1; count <= k; ++count) { + // Each time we encounter an open door, there's a possibility that it's + // the first open door we intentionally left open. + if (street->isDoorOpen()) { + ans = count; + street->closeDoor(); + } + street->moveRight(); + } + + return ans; + } +}; diff --git a/solutions/2753. Count Houses in a Circular Street II/2753.java b/solutions/2753. Count Houses in a Circular Street II/2753.java new file mode 100644 index 00000000000..20dfc301a11 --- /dev/null +++ b/solutions/2753. Count Houses in a Circular Street II/2753.java @@ -0,0 +1,32 @@ +/** + * Definition for a street. + * class Street { + * public Street(int[] doors); + * public void closeDoor(); + * public boolean isDoorOpen(); + * public void moveRight(); + * } + */ +class Solution { + public int houseCount(Street street, int k) { + int ans = 0; + + // Go to the first open door. + while (!street.isDoorOpen()) + street.moveRight(); + + street.moveRight(); + + for (int count = 1; count <= k; ++count) { + // Each time we encounter an open door, there's a possibility that it's + // the first open door we intentionally left open. + if (street.isDoorOpen()) { + ans = count; + street.closeDoor(); + } + street.moveRight(); + } + + return ans; + } +} diff --git a/solutions/2753. Count Houses in a Circular Street II/2753.py b/solutions/2753. Count Houses in a Circular Street II/2753.py new file mode 100644 index 00000000000..dd7f4bb17ce --- /dev/null +++ b/solutions/2753. Count Houses in a Circular Street II/2753.py @@ -0,0 +1,27 @@ +# Definition for a street. +# class Street: +# def closeDoor(self): +# pass +# def isDoorOpen(self): +# pass +# def moveRight(self): +# pass +class Solution: + def houseCount(self, street: Optional['Street'], k: int) -> int: + ans = 0 + + # Go to the first open door. + while not street.isDoorOpen(): + street.moveRight() + + street.moveRight() + + for count in range(k): + # Each time we encounter an open door, there's a possibility that it's the + # first open door we intentionally left open. + if street.isDoorOpen(): + ans = count + 1 + street.closeDoor() + street.moveRight() + + return ans diff --git a/solutions/2754. Bind Function to Context/2754.ts b/solutions/2754. Bind Function to Context/2754.ts new file mode 100644 index 00000000000..19e9b4c9933 --- /dev/null +++ b/solutions/2754. Bind Function to Context/2754.ts @@ -0,0 +1,11 @@ +type Fn = (...args) => any; + +declare global { + interface Function { + bindPolyfill(obj: Record): Fn; + } +} + +Function.prototype.bindPolyfill = function (obj): Fn { + return (...newArgs) => this.call(obj, ...newArgs); +}; diff --git a/solutions/2755. Deep Merge of Two Objects/2755.ts b/solutions/2755. Deep Merge of Two Objects/2755.ts new file mode 100644 index 00000000000..100fe5b66f6 --- /dev/null +++ b/solutions/2755. Deep Merge of Two Objects/2755.ts @@ -0,0 +1,28 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +function deepMerge(obj1: JSONValue, obj2: JSONValue): JSONValue { + if (typeof obj1 !== 'object' || typeof obj2 !== 'object') { + return obj2; + } + if (obj1 === null || obj2 === null) { + return obj2; + } + if (Array.isArray(obj1) !== Array.isArray(obj2)) { + return obj2; + } + const ans = obj1; + for (const key in obj2) { + if (key in ans) { + ans[key] = deepMerge(ans[key], obj2[key]); + } else { + ans[key] = obj2[key]; + } + } + return ans; +} diff --git a/solutions/2756. Query Batching/2756.ts b/solutions/2756. Query Batching/2756.ts new file mode 100644 index 00000000000..1d106fe8a99 --- /dev/null +++ b/solutions/2756. Query Batching/2756.ts @@ -0,0 +1,53 @@ +type QueryMultipleFn = (keys: string[]) => Promise; + +type ThrottledRequest = { + key: string; + resolve: (result: string) => void; +}; + +class QueryBatcher { + private readonly queryMultiple: QueryMultipleFn; + private readonly throttleTime: number; + private isThrottling: boolean; + private throttledRequests: ThrottledRequest[]; + + constructor(queryMultiple: QueryMultipleFn, t: number) { + this.queryMultiple = queryMultiple; + this.throttleTime = t; + this.isThrottling = false; + this.throttledRequests = []; + } + + async getValue(key: string): Promise { + if (this.throttleTime === 0) { + const results = await this.queryMultiple([key]); + return results[0]; + } + if (this.isThrottling) { + return new Promise((resolve) => { + this.throttledRequests.push({ key, resolve }); + }); + } + this.isThrottling = true; + setTimeout(() => this.deThrottle(), this.throttleTime); + const results = await this.queryMultiple([key]); + return results[0]; + } + + // De-throttles and processes any pending requests. + private deThrottle(): void { + const throttledRequests = this.throttledRequests; + if (throttledRequests.length === 0) { + this.isThrottling = false; + } else { + const keys = throttledRequests.map((req) => req.key); + this.queryMultiple(keys).then((results) => { + results.forEach((result, index) => { + throttledRequests[index].resolve(result); + }); + }); + setTimeout(() => this.deThrottle(), this.throttleTime); + this.throttledRequests = []; + } + } +} diff --git a/solutions/2757. Generate Circular Array Values/2757.ts b/solutions/2757. Generate Circular Array Values/2757.ts new file mode 100644 index 00000000000..b523e90d290 --- /dev/null +++ b/solutions/2757. Generate Circular Array Values/2757.ts @@ -0,0 +1,11 @@ +function* cycleGenerator( + arr: number[], + startIndex: number +): Generator { + const n = arr.length; + let index = startIndex; + while (true) { + const jump = yield arr[index]; + index = (index + (jump % n) + n) % n; + } +} diff --git a/solutions/2758. Next Day/2758.ts b/solutions/2758. Next Day/2758.ts new file mode 100644 index 00000000000..a2dbec81dcd --- /dev/null +++ b/solutions/2758. Next Day/2758.ts @@ -0,0 +1,11 @@ +declare global { + interface Date { + nextDay(): string; + } +} + +Date.prototype.nextDay = function () { + const today = new Date(this.getTime()); + today.setDate(today.getDate() + 1); + return today.toISOString().split('T')[0]; +}; diff --git a/solutions/2759. Convert JSON String to Object/2759.ts b/solutions/2759. Convert JSON String to Object/2759.ts new file mode 100644 index 00000000000..8cddbf2c0cd --- /dev/null +++ b/solutions/2759. Convert JSON String to Object/2759.ts @@ -0,0 +1,141 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +class JSONParser { + private str: string; + private i: number; + + constructor(str: string) { + this.str = str; + this.i = 0; + } + + public parse(): JSONValue { + return this.parseValue(); + } + + private parseValue(): JSONValue { + switch (this.str[this.i]) { + case '{': + return this.parseObject(); + case '[': + return this.parseArray(); + case 't': // true + case 'f': // false + case 'n': // null + return this.parseLiteral(); + case '"': + return this.parseString(); + default: + return this.parseNumber(); + } + } + + private parseObject(): JSONValue { + ++this.i; + + const ans: JSONValue = {}; + + while (this.i < this.str.length && this.str[this.i] !== '}') { + const key = this.parseString(); + this.expectChar(':'); + const value = this.parseValue(); + + ans[key] = value; + if (this.str[this.i] === ',') { + ++this.i; + } + } + + ++this.i; + return ans; + } + + private parseArray(): JSONValue[] { + ++this.i; + + const ans: JSONValue[] = []; + + while (this.i < this.str.length && this.str[this.i] !== ']') { + const value = this.parseValue(); + ans.push(value); + if (this.str[this.i] === ',') { + ++this.i; + } + } + + ++this.i; + return ans; + } + + private parseLiteral(): boolean | null { + if (this.str.startsWith('true', this.i)) { + this.i += 4; + return true; + } + if (this.str.startsWith('false', this.i)) { + this.i += 5; + return false; + } + if (this.str.startsWith('null', this.i)) { + this.i += 4; + return null; + } + throw new Error(`Unexpected token at position ${this.i}`); + } + + private parseString(): string { + let ans = ''; + ++this.i; + + while (this.i < this.str.length && this.str[this.i] !== '"') { + ans += this.str[this.i]; + ++this.i; + } + + ++this.i; + return ans; + } + + private parseNumber(): number { + let start = this.i; + + if (this.str[this.i] === '-') { + ++this.i; + } + + while (this.i < this.str.length && this.isDigit(this.str[this.i])) { + ++this.i; + } + + if (this.str[this.i] === '.') { + ++this.i; + while (this.i < this.str.length && this.isDigit(this.str[this.i])) { + ++this.i; + } + } + + return Number(this.str.slice(start, this.i)); + } + + private isDigit(n: string): boolean { + return n >= '0' && n <= '9'; + } + + private expectChar(char: string): void { + if (this.str[this.i] !== char) { + throw new Error(`Expected '${char}' at position ${this.i}`); + } + ++this.i; + } +} + +function jsonParse(str: string): JSONValue { + const parser = new JSONParser(str); + return parser.parse(); +} diff --git a/solutions/276. Paint Fence/276.cpp b/solutions/276. Paint Fence/276.cpp new file mode 100644 index 00000000000..41abf26c3c1 --- /dev/null +++ b/solutions/276. Paint Fence/276.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int numWays(int n, int k) { + if (n == 0) + return 0; + if (n == 1) + return k; + if (n == 2) + return k * k; + + // dp[i] := the number of ways to paint n posts with k colors + vector dp(n + 1); + dp[0] = 0; + dp[1] = k; + dp[2] = k * k; + + for (int i = 3; i <= n; ++i) + dp[i] = (dp[i - 1] + dp[i - 2]) * (k - 1); + + return dp[n]; + } +}; diff --git a/solutions/276. Paint Fence/276.java b/solutions/276. Paint Fence/276.java new file mode 100644 index 00000000000..5781439bff3 --- /dev/null +++ b/solutions/276. Paint Fence/276.java @@ -0,0 +1,21 @@ +class Solution { + public int numWays(int n, int k) { + if (n == 0) + return 0; + if (n == 1) + return k; + if (n == 2) + return k * k; + + // dp[i] := the number of ways to paint n posts with k colors + int[] dp = new int[n + 1]; + dp[0] = 0; + dp[1] = k; + dp[2] = k * k; + + for (int i = 3; i <= n; ++i) + dp[i] = (dp[i - 1] + dp[i - 2]) * (k - 1); + + return dp[n]; + } +} diff --git a/solutions/276. Paint Fence/276.py b/solutions/276. Paint Fence/276.py new file mode 100644 index 00000000000..736b641664f --- /dev/null +++ b/solutions/276. Paint Fence/276.py @@ -0,0 +1,19 @@ +class Solution: + def numWays(self, n: int, k: int) -> int: + if n == 0: + return 0 + if n == 1: + return k + if n == 2: + return k * k + + # dp[i] := the number of ways to pan posts with k colors + dp = [0] * (n + 1) + dp[0] = 0 + dp[1] = k + dp[2] = k * k + + for i in range(3, n + 1): + dp[i] = (dp[i - 1] + dp[i - 2]) * (k - 1) + + return dp[n] diff --git a/solutions/2760. Longest Even Odd Subarray With Threshold/2760.cpp b/solutions/2760. Longest Even Odd Subarray With Threshold/2760.cpp new file mode 100644 index 00000000000..f0f7d63d2f4 --- /dev/null +++ b/solutions/2760. Longest Even Odd Subarray With Threshold/2760.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int longestAlternatingSubarray(vector& nums, int threshold) { + int ans = 0; + int dp = 0; + + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] > threshold) + dp = 0; + else if (i > 0 && dp > 0 && isOddEven(nums[i - 1], nums[i])) + // Increase the size of the subarray. + ++dp; + else + // Start a new subarray if the start is valid. + dp = nums[i] % 2 == 0 ? 1 : 0; + ans = max(ans, dp); + } + + return ans; + } + + private: + bool isOddEven(int a, int b) { + return a % 2 != b % 2; + } +}; diff --git a/solutions/2760. Longest Even Odd Subarray With Threshold/2760.java b/solutions/2760. Longest Even Odd Subarray With Threshold/2760.java new file mode 100644 index 00000000000..0146e5dd019 --- /dev/null +++ b/solutions/2760. Longest Even Odd Subarray With Threshold/2760.java @@ -0,0 +1,24 @@ +class Solution { + public int longestAlternatingSubarray(int[] nums, int threshold) { + int ans = 0; + int dp = 0; + + for (int i = 0; i < nums.length; ++i) { + if (nums[i] > threshold) + dp = 0; + else if (i > 0 && dp > 0 && isOddEven(nums[i - 1], nums[i])) + // Increase the size of the subarray. + ++dp; + else + // Start a new subarray if the start is valid. + dp = nums[i] % 2 == 0 ? 1 : 0; + ans = Math.max(ans, dp); + } + + return ans; + } + + private boolean isOddEven(int a, int b) { + return a % 2 != b % 2; + } +} diff --git a/solutions/2760. Longest Even Odd Subarray With Threshold/2760.py b/solutions/2760. Longest Even Odd Subarray With Threshold/2760.py new file mode 100644 index 00000000000..104b6a11d1f --- /dev/null +++ b/solutions/2760. Longest Even Odd Subarray With Threshold/2760.py @@ -0,0 +1,20 @@ +class Solution: + def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: + ans = 0 + dp = 0 + + def isOddEven(a: int, b: int) -> bool: + return a % 2 != b % 2 + + for i, num in enumerate(nums): + if num > threshold: + dp = 0 + elif i > 0 and dp > 0 and isOddEven(nums[i - 1], num): + # Increase the size of the subarray. + dp += 1 + else: + # Start a new subarray if the start is valid. + dp = 1 if num % 2 == 0 else 0 + ans = max(ans, dp) + + return ans diff --git a/solutions/2761. Prime Pairs With Target Sum/2761.cpp b/solutions/2761. Prime Pairs With Target Sum/2761.cpp new file mode 100644 index 00000000000..67d9db5f803 --- /dev/null +++ b/solutions/2761. Prime Pairs With Target Sum/2761.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector> findPrimePairs(int n) { + const vector isPrime = sieveEratosthenes(n + 1); + vector> ans; + + for (int i = 2; i <= n / 2; ++i) + if (isPrime[i] && isPrime[n - i]) + ans.push_back({i, n - i}); + + return ans; + } + + private: + vector sieveEratosthenes(int n) { + vector isPrime(n, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +}; diff --git a/solutions/2761. Prime Pairs With Target Sum/2761.java b/solutions/2761. Prime Pairs With Target Sum/2761.java new file mode 100644 index 00000000000..738bae04b5a --- /dev/null +++ b/solutions/2761. Prime Pairs With Target Sum/2761.java @@ -0,0 +1,24 @@ +class Solution { + public List> findPrimePairs(int n) { + boolean[] isPrime = sieveEratosthenes(n + 1); + List> ans = new ArrayList<>(); + + for (int i = 2; i <= n / 2; ++i) + if (isPrime[i] && isPrime[n - i]) + ans.add(List.of(i, n - i)); + + return ans; + } + + private boolean[] sieveEratosthenes(int n) { + boolean[] isPrime = new boolean[n]; + Arrays.fill(isPrime, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +} diff --git a/solutions/2761. Prime Pairs With Target Sum/2761.py b/solutions/2761. Prime Pairs With Target Sum/2761.py new file mode 100644 index 00000000000..ca4516887d0 --- /dev/null +++ b/solutions/2761. Prime Pairs With Target Sum/2761.py @@ -0,0 +1,16 @@ +class Solution: + def findPrimePairs(self, n: int) -> List[List[int]]: + isPrime = self._sieveEratosthenes(n + 1) + return [[i, n - i] for i in range(2, n // 2 + 1) + if isPrime[i] and isPrime[n - i]] + + def _sieveEratosthenes(self, n: int) -> List[bool]: + isPrime = [True] * n + isPrime[0] = False + isPrime[1] = False + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n, i): + isPrime[j] = False + return isPrime +j diff --git a/solutions/2762. Continuous Subarrays/2762.cpp b/solutions/2762. Continuous Subarrays/2762.cpp new file mode 100644 index 00000000000..ee972a9e8e0 --- /dev/null +++ b/solutions/2762. Continuous Subarrays/2762.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + long long continuousSubarrays(vector& nums) { + long ans = 1; // [nums[0]] + int left = nums[0] - 2; + int right = nums[0] + 2; + int l = 0; + + // nums[l..r] is a valid window with range in [left, right]. + for (int r = 1; r < nums.size(); r++) { + if (left <= nums[r] && nums[r] <= right) { + left = max(left, nums[r] - 2); + right = min(right, nums[r] + 2); + } else { + // nums[r] is out-of-bounds, so reconstruct the window. + left = nums[r] - 2; + right = nums[r] + 2; + l = r; + // If we consistently move leftward in each iteration, it implies that + // the entire left subarray satisfies the given condition. For every + // subarray with l in the range [0, r], the condition is met, preventing + // the code from reaching the final "else" condition. Instead, it stops + // at the "if" condition. + while (nums[r] - 2 <= nums[l] && nums[l] <= nums[r] + 2) { + left = max(left, nums[l] - 2); + right = min(right, nums[l] + 2); + --l; + } + ++l; + } + // nums[l..r], nums[l + 1..r], ..., nums[r] + ans += r - l + 1; + } + + return ans; + } +}; diff --git a/solutions/2762. Continuous Subarrays/2762.java b/solutions/2762. Continuous Subarrays/2762.java new file mode 100644 index 00000000000..2c7e0584cfa --- /dev/null +++ b/solutions/2762. Continuous Subarrays/2762.java @@ -0,0 +1,36 @@ +class Solution { + public long continuousSubarrays(int[] nums) { + long ans = 1; // [nums[0]] + int left = nums[0] - 2; + int right = nums[0] + 2; + int l = 0; + + // nums[l..r] is a valid window with range in [left, right]. + for (int r = 1; r < nums.length; r++) { + if (left <= nums[r] && nums[r] <= right) { + left = Math.max(left, nums[r] - 2); + right = Math.min(right, nums[r] + 2); + } else { + // nums[r] is out-of-bounds, so reconstruct the window. + left = nums[r] - 2; + right = nums[r] + 2; + l = r; + // If we consistently move leftward in each iteration, it implies that + // the entire left subarray satisfies the given condition. For every + // subarray with l in the range [0, r], the condition is met, preventing + // the code from reaching the final "else" condition. Instead, it stops + // at the "if" condition. + while (nums[r] - 2 <= nums[l] && nums[l] <= nums[r] + 2) { + left = Math.max(left, nums[l] - 2); + right = Math.min(right, nums[l] + 2); + --l; + } + ++l; + } + // nums[l..r], nums[l + 1..r], ..., nums[r] + ans += r - l + 1; + } + + return ans; + } +} diff --git a/solutions/2762. Continuous Subarrays/2762.py b/solutions/2762. Continuous Subarrays/2762.py new file mode 100644 index 00000000000..793fa3356d0 --- /dev/null +++ b/solutions/2762. Continuous Subarrays/2762.py @@ -0,0 +1,31 @@ +class Solution: + def continuousSubarrays(self, nums: List[int]) -> int: + ans = 1 # [nums[0]] + left = nums[0] - 2 + right = nums[0] + 2 + l = 0 + + # nums[l..r] is a valid window. + for r in range(1, len(nums)): + if left <= nums[r] <= right: + left = max(left, nums[r] - 2) + right = min(right, nums[r] + 2) + else: + # nums[r] is out-of-bounds, so reconstruct the window. + left = nums[r] - 2 + right = nums[r] + 2 + l = r + # If we consistently move leftward in each iteration, it implies that + # the entire left subarray satisfies the given condition. For every + # subarray with l in the range [0, r], the condition is met, preventing + # the code from reaching the final "else" condition. Instead, it stops + # at the "if" condition. + while nums[r] - 2 <= nums[l] <= nums[r] + 2: + left = max(left, nums[l] - 2) + right = min(right, nums[l] + 2) + l -= 1 + l += 1 + # nums[l..r], num[l + 1..r], ..., nums[r] + ans += r - l + 1 + + return ans diff --git a/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.cpp b/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.cpp new file mode 100644 index 00000000000..59553f0df74 --- /dev/null +++ b/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + // If sorted(nums)[i + 1] - sorted(nums)[i] > 1, then there's a gap. Instead + // of determining the number of gaps in each subarray, let's find out how many + // subarrays contain each gap. + int sumImbalanceNumbers(vector& nums) { + const int n = nums.size(); + int ans = 0; + // Note that to avoid double counting, only `left` needs to check nums[i]. + // This adjustment ensures that i represents the position of the leftmost + // element of nums[i] within the subarray. + + // left[i] := the maximum index l s.t. nums[l] = nums[i] or nums[i] + 1 + vector left(n); + // right[i] := the minimum index r s.t. nums[r] = nums[i] + vector right(n); + + vector numToIndex(n + 2, -1); + for (int i = 0; i < n; ++i) { + left[i] = max(numToIndex[nums[i]], numToIndex[nums[i] + 1]); + numToIndex[nums[i]] = i; + } + + fill(numToIndex.begin(), numToIndex.end(), n); + for (int i = n - 1; i >= 0; --i) { + right[i] = numToIndex[nums[i] + 1]; + numToIndex[nums[i]] = i; + } + + // The gap above nums[i] persists until encountering nums[i] or nums[i] + 1. + // Consider subarrays nums[l..r] with l <= i <= r, where l in [left[i], i] + // and r in [i, right[i] - 1]. There are (i - left[i]) * (right[i] - i) + // subarrays satisfying this condition. + for (int i = 0; i < n; ++i) + ans += (i - left[i]) * (right[i] - i); + + // Subtract n * (n + 1) / 2 to account for the overcounting of elements + // initially assumed to have a gap. This adjustment is necessary as the + // maximum element of every subarray does not have a gap. + return ans - n * (n + 1) / 2; + } +}; diff --git a/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.java b/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.java new file mode 100644 index 00000000000..ccb0a2e464b --- /dev/null +++ b/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.java @@ -0,0 +1,42 @@ +class Solution { + // If sorted(nums)[i + 1] - sorted(nums)[i] > 1, then there's a gap. Instead + // of determining the number of gaps in each subarray, let's find out how many + // subarrays contain each gap. + public int sumImbalanceNumbers(int[] nums) { + final int n = nums.length; + int ans = 0; + // Note that to avoid double counting, only `left` needs to check nums[i]. + // This adjustment ensures that i represents the position of the leftmost + // element of nums[i] within the subarray. + + // left[i] := the maximum index l s.t. nums[l] = nums[i] or nums[i] + 1 + int[] left = new int[n]; + // right[i] := the minimum index r s.t. nums[r] = nums[i] + int[] right = new int[n]; + int[] numToIndex = new int[n + 2]; + + Arrays.fill(numToIndex, -1); + for (int i = 0; i < n; ++i) { + left[i] = Math.max(numToIndex[nums[i]], numToIndex[nums[i] + 1]); + numToIndex[nums[i]] = i; + } + + Arrays.fill(numToIndex, n); + for (int i = n - 1; i >= 0; --i) { + right[i] = numToIndex[nums[i] + 1]; + numToIndex[nums[i]] = i; + } + + // The gap above nums[i] persists until encountering nums[i] or nums[i] + 1. + // Consider subarrays nums[l..r] with l <= i <= r, where l in [left[i], i] + // and r in [i, right[i] - 1]. There are (i - left[i]) * (right[i] - i) + // subarrays satisfying this condition. + for (int i = 0; i < n; ++i) + ans += (i - left[i]) * (right[i] - i); + + // Subtract n * (n + 1) / 2 to account for the overcounting of elements + // initially assumed to have a gap. This adjustment is necessary as the + // maximum element of every subarray does not have a gap. + return ans - n * (n + 1) / 2; + } +} diff --git a/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.py b/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.py new file mode 100644 index 00000000000..506862551d5 --- /dev/null +++ b/solutions/2763. Sum of Imbalance Numbers of All Subarrays/2763-2.py @@ -0,0 +1,35 @@ +class Solution: + # If sorted(nums)[i + 1] - sorted(nums)[i] > 1, then there's a gap. Instead + # of determining the number of gaps in each subarray, let's find out how many + # subarrays contain each gap. + def sumImbalanceNumbers(self, nums: List[int]) -> int: + n = len(nums) + # Note that to avoid double counting, only `left` needs to check nums[i]. + # This adjustment ensures that i represents the position of the leftmost + # element of nums[i] within the subarray. + + # left[i] := the maximum index l s.t. nums[l] = nums[i] or nums[i] + 1 + left = [0] * n + # right[i] := the minimum index r s.t. nums[r] = nums[i] + right = [0] * n + + numToIndex = [-1] * (n + 2) + for i, num in enumerate(nums): + left[i] = max(numToIndex[num], numToIndex[num + 1]) + numToIndex[num] = i + + numToIndex = [n] * (n + 2) + for i in range(n - 1, -1, -1): + right[i] = numToIndex[nums[i] + 1] + numToIndex[nums[i]] = i + + # The gap above nums[i] persists until encountering nums[i] or nums[i] + 1. + # Consider subarrays nums[l..r] with l <= i <= r, where l in [left[i], i] + # and r in [i, right[i] - 1]. There are (i - left[i]) * (right[i] - i) + # subarrays satisfying this condition. + # + # Subtract n * (n + 1) / 2 to account for the overcounting of elements + # initially assumed to have a gap. This adjustment is necessary as the + # maximum element of every subarray does not have a gap. + return sum((i - left[i]) * (right[i] - i) + for i in range(n)) - n * (n + 1) // 2 diff --git "a/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.cpp" "b/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.cpp" new file mode 100644 index 00000000000..e69bf4b4704 --- /dev/null +++ "b/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.cpp" @@ -0,0 +1,22 @@ +class Solution { + public: + bool isPreorder(vector>& nodes) { + stack stack; // Stores `id`s. + + for (const vector& node : nodes) { + const int id = node[0]; + const int parentId = node[1]; + if (parentId == -1) { + stack.push(id); + continue; + } + while (!stack.empty() && stack.top() != parentId) + stack.pop(); + if (stack.empty()) + return false; + stack.push(id); + } + + return true; + } +}; diff --git "a/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.java" "b/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.java" new file mode 100644 index 00000000000..b41d3871028 --- /dev/null +++ "b/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.java" @@ -0,0 +1,21 @@ +class Solution { + public boolean isPreorder(List> nodes) { + Deque stack = new ArrayDeque<>(); // Stores `id`s. + + for (List node : nodes) { + final int id = node.get(0); + final int parentId = node.get(1); + if (parentId == -1) { + stack.push(id); + continue; + } + while (!stack.isEmpty() && stack.peek() != parentId) + stack.pop(); + if (stack.isEmpty()) + return false; + stack.push(id); + } + + return true; + } +} diff --git "a/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.py" "b/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.py" new file mode 100644 index 00000000000..3cf68be355f --- /dev/null +++ "b/solutions/2764. is Array a Preorder of Some \342\200\214Binary Tree/2764.py" @@ -0,0 +1,15 @@ +class Solution: + def isPreorder(self, nodes: List[List[int]]) -> bool: + stack = [] # Stores `id`s. + + for id, parentId in nodes: + if parentId == -1: + stack.append(id) + continue + while stack and stack[-1] != parentId: + stack.pop() + if not stack: + return False + stack.append(id) + + return True diff --git a/solutions/2765. Longest Alternating Subarray/2765.cpp b/solutions/2765. Longest Alternating Subarray/2765.cpp new file mode 100644 index 00000000000..4a7b871dc18 --- /dev/null +++ b/solutions/2765. Longest Alternating Subarray/2765.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int alternatingSubarray(vector& nums) { + int ans = 1; + int dp = 1; + + for (int i = 1; i < nums.size(); ++i) { + const int targetDiff = dp % 2 == 0 ? -1 : 1; + // Append nums[i] to the current alternating subarray. + if (nums[i] - nums[i - 1] == targetDiff) + ++dp; + // Reset the alternating subarray to nums[i - 1..i]. + else if (nums[i] - nums[i - 1] == 1) + dp = 2; + // Reset the alternating subarray to nums[i]. + else + dp = 1; + ans = max(ans, dp); + } + + return ans == 1 ? -1 : ans; + } +}; diff --git a/solutions/2765. Longest Alternating Subarray/2765.java b/solutions/2765. Longest Alternating Subarray/2765.java new file mode 100644 index 00000000000..18554b538bd --- /dev/null +++ b/solutions/2765. Longest Alternating Subarray/2765.java @@ -0,0 +1,22 @@ +class Solution { + public int alternatingSubarray(int[] nums) { + int ans = 1; + int dp = 1; + + for (int i = 1; i < nums.length; ++i) { + final int targetDiff = dp % 2 == 0 ? -1 : 1; + // Append nums[i] to the current alternating subarray. + if (nums[i] - nums[i - 1] == targetDiff) + ++dp; + // Reset the alternating subarray to nums[i - 1..i]. + else if (nums[i] - nums[i - 1] == 1) + dp = 2; + // Reset the alternating subarray to nums[i]. + else + dp = 1; + ans = Math.max(ans, dp); + } + + return ans == 1 ? -1 : ans; + } +} diff --git a/solutions/2765. Longest Alternating Subarray/2765.py b/solutions/2765. Longest Alternating Subarray/2765.py new file mode 100644 index 00000000000..70ee11c4673 --- /dev/null +++ b/solutions/2765. Longest Alternating Subarray/2765.py @@ -0,0 +1,19 @@ +class Solution: + def alternatingSubarray(self, nums: List[int]) -> int: + ans = 1 + dp = 1 + + for i in range(1, len(nums)): + targetDiff = -1 if dp % 2 == 0 else 1 + # Append nums[i] to the current alternating subarray. + if nums[i] - nums[i - 1] == targetDiff: + dp += 1 + # Reset the alternating subarray to nums[i - 1..i]. + elif nums[i] - nums[i - 1] == 1: + dp = 2 + # Reset the alternating subarray to nums[i]. + else: + dp = 1 + ans = max(ans, dp) + + return -1 if ans == 1 else ans diff --git a/solutions/2766. Relocate Marbles/2766.cpp b/solutions/2766. Relocate Marbles/2766.cpp new file mode 100644 index 00000000000..b85dda83ac8 --- /dev/null +++ b/solutions/2766. Relocate Marbles/2766.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector relocateMarbles(vector& nums, vector& moveFrom, + vector& moveTo) { + set numsSet{nums.begin(), nums.end()}; + + for (int i = 0; i < moveFrom.size(); ++i) { + numsSet.erase(numsSet.find(moveFrom[i])); + numsSet.insert(moveTo[i]); + } + + return {numsSet.begin(), numsSet.end()}; + } +}; diff --git a/solutions/2766. Relocate Marbles/2766.java b/solutions/2766. Relocate Marbles/2766.java new file mode 100644 index 00000000000..f8d2e5769af --- /dev/null +++ b/solutions/2766. Relocate Marbles/2766.java @@ -0,0 +1,12 @@ +class Solution { + public List relocateMarbles(int[] nums, int[] moveFrom, int[] moveTo) { + Set numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + + for (int i = 0; i < moveFrom.length; ++i) { + numsSet.remove(moveFrom[i]); + numsSet.add(moveTo[i]); + } + + return numsSet.stream().sorted().toList(); + } +} diff --git a/solutions/2766. Relocate Marbles/2766.py b/solutions/2766. Relocate Marbles/2766.py new file mode 100644 index 00000000000..f8705b371a4 --- /dev/null +++ b/solutions/2766. Relocate Marbles/2766.py @@ -0,0 +1,9 @@ +class Solution: + def relocateMarbles(self, nums: List[int], moveFrom: List[int], moveTo: List[int]) -> List[int]: + numsSet = set(nums) + + for f, t in zip(moveFrom, moveTo): + numsSet.remove(f) + numsSet.add(t) + + return sorted(numsSet) diff --git a/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.cpp b/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.cpp new file mode 100644 index 00000000000..e13bf8c53c8 --- /dev/null +++ b/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minimumBeautifulSubstrings(string s) { + const int n = s.length(); + // dp[i] := the minimum number of beautiful substrings for the first i chars + vector dp(n + 1, n + 1); + dp[0] = 0; + + for (int i = 1; i <= n; ++i) { + if (s[i - 1] == '0') + continue; + int num = 0; // num of s[i - 1..j - 1] + for (int j = i; j <= n; ++j) { + num = (num << 1) + s[j - 1] - '0'; + if (isPowerOfFive(num)) + dp[j] = min(dp[j], dp[i - 1] + 1); + } + } + + return dp[n] == n + 1 ? -1 : dp[n]; + } + + private: + bool isPowerOfFive(int num) { + while (num % 5 == 0) + num /= 5; + return num == 1; + } +}; diff --git a/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.java b/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.java new file mode 100644 index 00000000000..556e46cd7c1 --- /dev/null +++ b/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.java @@ -0,0 +1,28 @@ +class Solution { + public int minimumBeautifulSubstrings(String s) { + final int n = s.length(); + // dp[i] := the minimum number of beautiful substrings for the first i chars + int[] dp = new int[n + 1]; + Arrays.fill(dp, n + 1); + dp[0] = 0; + + for (int i = 1; i <= n; ++i) { + if (s.charAt(i - 1) == '0') + continue; + int num = 0; // num of s[i - 1..j - 1] + for (int j = i; j <= n; ++j) { + num = (num << 1) + s.charAt(j - 1) - '0'; + if (isPowerOfFive(num)) + dp[j] = Math.min(dp[j], dp[i - 1] + 1); + } + } + + return dp[n] == n + 1 ? -1 : dp[n]; + } + + private boolean isPowerOfFive(int num) { + while (num % 5 == 0) + num /= 5; + return num == 1; + } +} diff --git a/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.py b/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.py new file mode 100644 index 00000000000..b0100a0f398 --- /dev/null +++ b/solutions/2767. Partition String Into Minimum Beautiful Substrings/2767.py @@ -0,0 +1,21 @@ +class Solution: + def minimumBeautifulSubstrings(self, s: str) -> int: + n = len(s) + # dp[i] := the minimum number of beautiful substrings for the first i chars + dp = [0] + [n + 1] * n + + for i in range(1, n + 1): + if s[i - 1] == '0': + continue + num = 0 # the number of s[i - 1..j - 1] + for j in range(i, n + 1): + num = (num << 1) + int(s[j - 1]) + if self._isPowerOfFive(num): + dp[j] = min(dp[j], dp[i - 1] + 1) + + return -1 if dp[n] == n + 1 else dp[n] + + def _isPowerOfFive(self, num: int) -> bool: + while num % 5 == 0: + num //= 5 + return num == 1 diff --git a/solutions/2768. Number of Black Blocks/2768.cpp b/solutions/2768. Number of Black Blocks/2768.cpp new file mode 100644 index 00000000000..e70b26cb980 --- /dev/null +++ b/solutions/2768. Number of Black Blocks/2768.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector countBlackBlocks(int m, int n, + vector>& coordinates) { + vector ans(5); + // count[i * n + j] := the number of black cells in + // (i - 1, j - 1), (i - 1, j), (i, j - 1), (i, j) + unordered_map count; + + for (const vector& coordinate : coordinates) { + const int x = coordinate[0]; + const int y = coordinate[1]; + for (long i = x; i < x + 2; ++i) + for (long j = y; j < y + 2; ++j) + // 2 x 2 submatrix with right-bottom conner being (i, j) contains the + // current black cell (x, y). + if (i - 1 >= 0 && i < m && j - 1 >= 0 && j < n) + ++count[i * n + j]; + } + + for (const auto& [_, freq] : count) + ++ans[freq]; + + ans[0] = (m - 1L) * (n - 1) - accumulate(ans.begin(), ans.end(), 0L); + return ans; + } +}; diff --git a/solutions/2768. Number of Black Blocks/2768.java b/solutions/2768. Number of Black Blocks/2768.java new file mode 100644 index 00000000000..c9cf9be21ea --- /dev/null +++ b/solutions/2768. Number of Black Blocks/2768.java @@ -0,0 +1,25 @@ +class Solution { + public long[] countBlackBlocks(int m, int n, int[][] coordinates) { + long[] ans = new long[5]; + // count[i * n + j] := the number of black cells in + // (i - 1, j - 1), (i - 1, j), (i, j - 1), (i, j) + Map count = new HashMap<>(); + + for (int[] coordinate : coordinates) { + final int x = coordinate[0]; + final int y = coordinate[1]; + for (long i = x; i < x + 2; ++i) + for (long j = y; j < y + 2; ++j) + // 2 x 2 submatrix with right-bottom conner being (i, j) contains the + // current black cell (x, y). + if (i - 1 >= 0 && i < m && j - 1 >= 0 && j < n) + count.merge(i * n + j, 1, Integer::sum); + } + + for (final int freq : count.values()) + ++ans[freq]; + + ans[0] = (m - 1L) * (n - 1) - Arrays.stream(ans).sum(); + return ans; + } +} diff --git a/solutions/2768. Number of Black Blocks/2768.py b/solutions/2768. Number of Black Blocks/2768.py new file mode 100644 index 00000000000..f2add9473f0 --- /dev/null +++ b/solutions/2768. Number of Black Blocks/2768.py @@ -0,0 +1,20 @@ +class Solution: + def countBlackBlocks(self, m: int, n: int, coordinates: List[List[int]]) -> List[int]: + ans = [0] * 5 + # count[i * n + j] := the number of black cells in + # (i - 1, j - 1), (i - 1, j), (i, j - 1), (i, j) + count = collections.Counter() + + for x, y in coordinates: + for i in range(x, x + 2): + for j in range(y, y + 2): + # 2 x 2 submatrix with right-bottom conner being (i, j) contains the + # current black cell (x, y). + if 0 < i < m and 0 < j < n: + count[(i, j)] += 1 + + for freq in count.values(): + ans[freq] += 1 + + ans[0] = (m - 1) * (n - 1) - sum(ans) + return ans diff --git a/solutions/2769. Find the Maximum Achievable Number/2769.cpp b/solutions/2769. Find the Maximum Achievable Number/2769.cpp new file mode 100644 index 00000000000..c08aaf7fd98 --- /dev/null +++ b/solutions/2769. Find the Maximum Achievable Number/2769.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int theMaximumAchievableX(int num, int t) { + return num + 2 * t; + } +}; diff --git a/solutions/2769. Find the Maximum Achievable Number/2769.java b/solutions/2769. Find the Maximum Achievable Number/2769.java new file mode 100644 index 00000000000..3a07eacbbd9 --- /dev/null +++ b/solutions/2769. Find the Maximum Achievable Number/2769.java @@ -0,0 +1,5 @@ +class Solution { + public int theMaximumAchievableX(int num, int t) { + return num + 2 * t; + } +} diff --git a/solutions/2769. Find the Maximum Achievable Number/2769.py b/solutions/2769. Find the Maximum Achievable Number/2769.py new file mode 100644 index 00000000000..dc87402c01a --- /dev/null +++ b/solutions/2769. Find the Maximum Achievable Number/2769.py @@ -0,0 +1,3 @@ +class Solution: + def theMaximumAchievableX(self, num: int, t: int) -> int: + return num + 2 * t diff --git a/solutions/277. Find the Celebrity/277.cpp b/solutions/277. Find the Celebrity/277.cpp new file mode 100644 index 00000000000..5292bc8ed36 --- /dev/null +++ b/solutions/277. Find the Celebrity/277.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int findCelebrity(int n) { + int candidate = 0; + + // Everyone knows the celebrity. + for (int i = 1; i < n; ++i) + if (knows(candidate, i)) + candidate = i; + + // The candidate knows nobody and everyone knows the celebrity. + for (int i = 0; i < n; ++i) { + if (i < candidate && knows(candidate, i) || !knows(i, candidate)) + return -1; + if (i > candidate && !knows(i, candidate)) + return -1; + } + + return candidate; + } +}; diff --git a/solutions/277. Find the Celebrity/277.java b/solutions/277. Find the Celebrity/277.java new file mode 100644 index 00000000000..d5b1c75b13e --- /dev/null +++ b/solutions/277. Find the Celebrity/277.java @@ -0,0 +1,20 @@ +public class Solution extends Relation { + public int findCelebrity(int n) { + int candidate = 0; + + // Everyone knows the celebrity. + for (int i = 1; i < n; ++i) + if (knows(candidate, i)) + candidate = i; + + // The candidate knows nobody and everyone knows the celebrity. + for (int i = 0; i < n; ++i) { + if (i < candidate && knows(candidate, i) || !knows(i, candidate)) + return -1; + if (i > candidate && !knows(i, candidate)) + return -1; + } + + return candidate; + } +} diff --git a/solutions/277. Find the Celebrity/277.py b/solutions/277. Find the Celebrity/277.py new file mode 100644 index 00000000000..26a208c9120 --- /dev/null +++ b/solutions/277. Find the Celebrity/277.py @@ -0,0 +1,22 @@ +# The knows API is already defined for you. +# Returns a bool, whether a knows b +# Def knows(a: int, b: int) -> bool: + + +class Solution: + def findCelebrity(self, n: int) -> int: + candidate = 0 + + # Everyone knows the celebrity. + for i in range(1, n): + if knows(candidate, i): + candidate = i + + # The candidate knows nobody and everyone knows the celebrity. + for i in range(n): + if i < candidate and knows(candidate, i) or not knows(i, candidate): + return -1 + if i > candidate and not knows(i, candidate): + return -1 + + return candidate diff --git a/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.cpp b/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.cpp new file mode 100644 index 00000000000..f15af03151a --- /dev/null +++ b/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maximumJumps(vector& nums, int target) { + const int n = nums.size(); + // dp[i] := the maximum number of jumps to reach i from 0 + vector dp(n, -1); + dp[0] = 0; + + for (int j = 1; j < n; ++j) + for (int i = 0; i < j; ++i) + if (dp[i] != -1 && abs(nums[j] - nums[i]) <= target) + dp[j] = max(dp[j], dp[i] + 1); + + return dp[n - 1]; + } +}; diff --git a/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.java b/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.java new file mode 100644 index 00000000000..5a1de1d32de --- /dev/null +++ b/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.java @@ -0,0 +1,16 @@ +class Solution { + public int maximumJumps(int[] nums, int target) { + final int n = nums.length; + // dp[i] := the maximum number of jumps to reach i from 0 + int[] dp = new int[n]; + Arrays.fill(dp, -1); + dp[0] = 0; + + for (int j = 1; j < n; ++j) + for (int i = 0; i < j; ++i) + if (dp[i] != -1 && Math.abs(nums[j] - nums[i]) <= target) + dp[j] = Math.max(dp[j], dp[i] + 1); + + return dp[n - 1]; + } +} diff --git a/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.py b/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.py new file mode 100644 index 00000000000..84c8fa28039 --- /dev/null +++ b/solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.py @@ -0,0 +1,13 @@ +class Solution: + def maximumJumps(self, nums: List[int], target: int) -> int: + n = len(nums) + # dp[i] := the maximum number of jumps to reach i from 0 + dp = [-1] * n + dp[0] = 0 + + for j in range(1, n): + for i in range(j): + if dp[i] != -1 and abs(nums[j] - nums[i]) <= target: + dp[j] = max(dp[j], dp[i] + 1) + + return dp[-1] diff --git a/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.cpp b/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.cpp new file mode 100644 index 00000000000..4dd4820379a --- /dev/null +++ b/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxNonDecreasingLength(vector& nums1, vector& nums2) { + int ans = 1; + int dp1 = 1; // the longest subarray that ends in nums1[i] so far + int dp2 = 1; // the longest subarray that ends in nums2[i] so far + + for (int i = 1; i < nums1.size(); ++i) { + const int dp11 = nums1[i - 1] <= nums1[i] ? dp1 + 1 : 1; + const int dp21 = nums2[i - 1] <= nums1[i] ? dp2 + 1 : 1; + const int dp12 = nums1[i - 1] <= nums2[i] ? dp1 + 1 : 1; + const int dp22 = nums2[i - 1] <= nums2[i] ? dp2 + 1 : 1; + dp1 = max(dp11, dp21); + dp2 = max(dp12, dp22); + ans = max({ans, dp1, dp2}); + } + + return ans; + } +}; diff --git a/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.java b/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.java new file mode 100644 index 00000000000..7113a5b55d8 --- /dev/null +++ b/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.java @@ -0,0 +1,19 @@ +class Solution { + public int maxNonDecreasingLength(int[] nums1, int[] nums2) { + int ans = 1; + int dp1 = 1; // the longest subarray that ends in nums1[i] so far + int dp2 = 1; // the longest subarray that ends in nums2[i] so far + + for (int i = 1; i < nums1.length; ++i) { + final int dp11 = nums1[i - 1] <= nums1[i] ? dp1 + 1 : 1; + final int dp21 = nums2[i - 1] <= nums1[i] ? dp2 + 1 : 1; + final int dp12 = nums1[i - 1] <= nums2[i] ? dp1 + 1 : 1; + final int dp22 = nums2[i - 1] <= nums2[i] ? dp2 + 1 : 1; + dp1 = Math.max(dp11, dp21); + dp2 = Math.max(dp12, dp22); + ans = Math.max(ans, Math.max(dp1, dp2)); + } + + return ans; + } +} diff --git a/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.py b/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.py new file mode 100644 index 00000000000..d1884a1a2ea --- /dev/null +++ b/solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.py @@ -0,0 +1,16 @@ +class Solution: + def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: + ans = 1 + dp1 = 1 # the longest subarray that ends in nums1[i] so far + dp2 = 1 # the longest subarray that ends in nums2[i] so far + + for i in range(1, len(nums1)): + dp11 = dp1 + 1 if nums1[i - 1] <= nums1[i] else 1 + dp21 = dp2 + 1 if nums2[i - 1] <= nums1[i] else 1 + dp12 = dp1 + 1 if nums1[i - 1] <= nums2[i] else 1 + dp22 = dp2 + 1 if nums2[i - 1] <= nums2[i] else 1 + dp1 = max(dp11, dp21) + dp2 = max(dp12, dp22) + ans = max(ans, dp1, dp2) + + return ans diff --git a/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.cpp b/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.cpp new file mode 100644 index 00000000000..5cef5223770 --- /dev/null +++ b/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool checkArray(vector& nums, int k) { + if (k == 1) + return true; + + int needDecrease = 0; + // Store nums[i - k + 1..i] with decreasing nums[i - k + 1]. + deque dq; + + for (int i = 0; i < nums.size(); ++i) { + if (i >= k) { + needDecrease -= dq.front(); + dq.pop_front(); + } + if (nums[i] < needDecrease) + return false; + const int decreasedNum = nums[i] - needDecrease; + dq.push_back(decreasedNum); + needDecrease += decreasedNum; + } + + return dq.back() == 0; + } +}; diff --git a/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.java b/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.java new file mode 100644 index 00000000000..84b928fdd6a --- /dev/null +++ b/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.java @@ -0,0 +1,22 @@ +class Solution { + public boolean checkArray(int[] nums, int k) { + if (k == 1) + return true; + + int needDecrease = 0; + // Store nums[i - k + 1..i] with decreasing nums[i - k + 1]. + Deque dq = new ArrayDeque<>(); + + for (int i = 0; i < nums.length; ++i) { + if (i >= k) + needDecrease -= dq.pollFirst(); + if (nums[i] < needDecrease) + return false; + final int decreasedNum = nums[i] - needDecrease; + dq.offerLast(decreasedNum); + needDecrease += decreasedNum; + } + + return dq.getLast() == 0; + } +} diff --git a/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.py b/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.py new file mode 100644 index 00000000000..5e2562994ca --- /dev/null +++ b/solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.py @@ -0,0 +1,19 @@ +class Solution: + def checkArray(self, nums: List[int], k: int) -> bool: + if k == 1: + return True + + needDecrease = 0 + # Store nums[i - k + 1..i] with decreasing nums[i - k + 1]. + dq = collections.deque() + + for i, num in enumerate(nums): + if i >= k: + needDecrease -= dq.popleft() + if nums[i] < needDecrease: + return False + decreasedNum = nums[i] - needDecrease + dq.append(decreasedNum) + needDecrease += decreasedNum + + return dq[-1] == 0 diff --git a/solutions/2773. Height of Special Binary Tree/2773.cpp b/solutions/2773. Height of Special Binary Tree/2773.cpp new file mode 100644 index 00000000000..b096c684315 --- /dev/null +++ b/solutions/2773. Height of Special Binary Tree/2773.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int heightOfTree(TreeNode* root) { + if (root == nullptr) + return 0; + // a leaf node + if (root->left != nullptr && root->left->right == root) + return 0; + return 1 + max(heightOfTree(root->left), heightOfTree(root->right)); + } +}; diff --git a/solutions/2773. Height of Special Binary Tree/2773.java b/solutions/2773. Height of Special Binary Tree/2773.java new file mode 100644 index 00000000000..cb301001999 --- /dev/null +++ b/solutions/2773. Height of Special Binary Tree/2773.java @@ -0,0 +1,10 @@ +class Solution { + public int heightOfTree(TreeNode root) { + if (root == null) + return 0; + // a leaf node + if (root.left != null && root.left.right == root) + return 0; + return 1 + Math.max(heightOfTree(root.left), heightOfTree(root.right)); + } +} diff --git a/solutions/2773. Height of Special Binary Tree/2773.py b/solutions/2773. Height of Special Binary Tree/2773.py new file mode 100644 index 00000000000..eb8aaa43c19 --- /dev/null +++ b/solutions/2773. Height of Special Binary Tree/2773.py @@ -0,0 +1,8 @@ +class Solution: + def heightOfTree(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + # a leaf node + if root.left and root.left.right == root: + return 0 + return 1 + max(self.heightOfTree(root.left), self.heightOfTree(root.right)) diff --git a/solutions/2774. Array Upper Bound/2774.ts b/solutions/2774. Array Upper Bound/2774.ts new file mode 100644 index 00000000000..37d71dfbb20 --- /dev/null +++ b/solutions/2774. Array Upper Bound/2774.ts @@ -0,0 +1,19 @@ +declare global { + interface Array { + upperBound(target: number): number; + } +} + +Array.prototype.upperBound = function (target): number { + let l = 0; + let r = this.length - 1; + while (l < r) { + const m = (l + r + 1) >> 1; + if (this[m] > target) { + r = m - 1; + } else { + l = m; + } + } + return this[l] == target ? l : -1; +}; diff --git a/solutions/2775. Undefined to Null/2775-2.ts b/solutions/2775. Undefined to Null/2775-2.ts new file mode 100644 index 00000000000..39c46b37b30 --- /dev/null +++ b/solutions/2775. Undefined to Null/2775-2.ts @@ -0,0 +1,39 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Value = + | undefined + | null + | boolean + | number + | string + | Value[] + | { [key: string]: Value }; + +type Obj1 = Record | Array; +type Obj2 = Record | Array; + +function undefinedToNull(obj: Obj1): Obj2 { + if (obj === undefined || obj === null) { + return null; + } + if ( + typeof obj === 'boolean' || + typeof obj === 'number' || + typeof obj === 'string' + ) { + return obj; + } + if (Array.isArray(obj)) { + return (obj as Obj1[]).map(undefinedToNull); + } + let ans = {}; + for (const key in obj) { + ans[key] = undefinedToNull(obj[key] as Obj1); + } + return ans; +} diff --git a/solutions/2775. Undefined to Null/2775.ts b/solutions/2775. Undefined to Null/2775.ts new file mode 100644 index 00000000000..6b34d2a04d8 --- /dev/null +++ b/solutions/2775. Undefined to Null/2775.ts @@ -0,0 +1,35 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Value = + | undefined + | null + | boolean + | number + | string + | Value[] + | { [key: string]: Value }; + +type Obj1 = Record | Array; +type Obj2 = Record | Array; + +function undefinedToNull(obj: Obj1): Obj2 { + if (obj === undefined || obj === null) { + return null; + } + if ( + typeof obj === 'boolean' || + typeof obj === 'number' || + typeof obj === 'string' + ) { + return obj; + } + for (const key in obj) { + obj[key] = undefinedToNull(obj[key]); + } + return obj; +} diff --git a/solutions/2776. Convert Callback Based Function to Promise Based Function/2776.ts b/solutions/2776. Convert Callback Based Function to Promise Based Function/2776.ts new file mode 100644 index 00000000000..ba34e6ff5fe --- /dev/null +++ b/solutions/2776. Convert Callback Based Function to Promise Based Function/2776.ts @@ -0,0 +1,13 @@ +type CallbackFn = ( + next: (data: number, error: string) => void, + ...args: number[] +) => void; +type Promisified = (...args: number[]) => Promise; + +function promisify(fn: CallbackFn): Promisified { + return async function (...args: number[]): Promise { + return new Promise((resolve, reject) => + fn((data, err) => (err ? reject(err) : resolve(data)), ...args) + ); + }; +} diff --git a/solutions/2777. Date Range Generator/2777.ts b/solutions/2777. Date Range Generator/2777.ts new file mode 100644 index 00000000000..28cf2ace68b --- /dev/null +++ b/solutions/2777. Date Range Generator/2777.ts @@ -0,0 +1,14 @@ +// Similar to 2758. Next Day +function* dateRangeGenerator( + start: string, + end: string, + step: number +): Generator { + const startDate = new Date(start); + const endDate = new Date(end); + let currentDate = startDate; + while (currentDate <= endDate) { + yield currentDate.toISOString().split('T')[0]; + currentDate.setDate(currentDate.getDate() + step); + } +} diff --git a/solutions/2778. Sum of Squares of Special Elements/2778.cpp b/solutions/2778. Sum of Squares of Special Elements/2778.cpp new file mode 100644 index 00000000000..4db25103d9f --- /dev/null +++ b/solutions/2778. Sum of Squares of Special Elements/2778.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int sumOfSquares(vector& nums) { + const int n = nums.size(); + int ans = 0; + + for (int i = 0; i < n; ++i) + if (n % (i + 1) == 0) + ans += nums[i] * nums[i]; + + return ans; + } +}; diff --git a/solutions/2778. Sum of Squares of Special Elements/2778.java b/solutions/2778. Sum of Squares of Special Elements/2778.java new file mode 100644 index 00000000000..c4ee961a604 --- /dev/null +++ b/solutions/2778. Sum of Squares of Special Elements/2778.java @@ -0,0 +1,12 @@ +class Solution { + public int sumOfSquares(int[] nums) { + final int n = nums.length; + int ans = 0; + + for (int i = 0; i < n; ++i) + if (n % (i + 1) == 0) + ans += nums[i] * nums[i]; + + return ans; + } +} diff --git a/solutions/2778. Sum of Squares of Special Elements/2778.py b/solutions/2778. Sum of Squares of Special Elements/2778.py new file mode 100644 index 00000000000..b1eef001640 --- /dev/null +++ b/solutions/2778. Sum of Squares of Special Elements/2778.py @@ -0,0 +1,4 @@ +class Solution: + def sumOfSquares(self, nums: List[int]) -> int: + return sum(num**2 for i, num in enumerate(nums) + if len(nums) % (i + 1) == 0) diff --git a/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.cpp b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.cpp new file mode 100644 index 00000000000..ba99eaf6ec4 --- /dev/null +++ b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maximumBeauty(vector& nums, int k) { + // l and r track the maximum window instead of the valid window. + int l = 0; + int r = 0; + + ranges::sort(nums); + + for (r = 0; r < nums.size(); ++r) + if (nums[r] - nums[l] > 2 * k) + ++l; + + return r - l; + } +}; diff --git a/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.java b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.java new file mode 100644 index 00000000000..7bc02fc1897 --- /dev/null +++ b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.java @@ -0,0 +1,15 @@ +class Solution { + public int maximumBeauty(int[] nums, int k) { + // l and r track the maximum window instead of the valid window. + int l = 0; + int r = 0; + + Arrays.sort(nums); + + for (r = 0; r < nums.length; ++r) + if (nums[r] - nums[l] > 2 * k) + ++l; + + return r - l; + } +} diff --git a/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.py b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.py new file mode 100644 index 00000000000..58ca8cd4db6 --- /dev/null +++ b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779-2.py @@ -0,0 +1,11 @@ +class Solution: + def maximumBeauty(self, nums: List[int], k: int) -> int: + nums.sort() + + # l and r track the maximum window instead of the valid window. + l = 0 + for r in range(len(nums)): + if nums[r] - nums[l] > 2 * k: + l += 1 + + return r - l + 1 diff --git a/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.cpp b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.cpp new file mode 100644 index 00000000000..9ffddb06960 --- /dev/null +++ b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maximumBeauty(vector& nums, int k) { + int ans = 0; + + ranges::sort(nums); + + for (int l = 0, r = 0; r < nums.size(); ++r) { + while (nums[r] - nums[l] > 2 * k) + ++l; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.java b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.java new file mode 100644 index 00000000000..79a8c037afa --- /dev/null +++ b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.java @@ -0,0 +1,15 @@ +class Solution { + public int maximumBeauty(int[] nums, int k) { + int ans = 0; + + Arrays.sort(nums); + + for (int l = 0, r = 0; r < nums.length; ++r) { + while (nums[r] - nums[l] > 2 * k) + ++l; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.py b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.py new file mode 100644 index 00000000000..f14bf31a0c0 --- /dev/null +++ b/solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.py @@ -0,0 +1,13 @@ +class Solution: + def maximumBeauty(self, nums: List[int], k: int) -> int: + ans = 0 + + nums.sort() + + l = 0 + for r in range(len(nums)): + while nums[r] - nums[l] > 2 * k: + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/278. First Bad Version/278.cpp b/solutions/278. First Bad Version/278.cpp new file mode 100644 index 00000000000..9faca5000d2 --- /dev/null +++ b/solutions/278. First Bad Version/278.cpp @@ -0,0 +1,19 @@ +bool isBadVersion(int version); + +class Solution { + public: + int firstBadVersion(int n) { + int l = 1; + int r = n; + + while (l < r) { + const int m = l + (r - l) / 2; + if (isBadVersion(m)) + r = m; + else + l = m + 1; + } + + return l; + } +}; diff --git a/solutions/278. First Bad Version/278.java b/solutions/278. First Bad Version/278.java new file mode 100644 index 00000000000..89b5cf09751 --- /dev/null +++ b/solutions/278. First Bad Version/278.java @@ -0,0 +1,16 @@ +public class Solution extends VersionControl { + public int firstBadVersion(int n) { + int l = 1; + int r = n; + + while (l < r) { + final int m = l + (r - l) / 2; + if (isBadVersion(m)) + r = m; + else + l = m + 1; + } + + return l; + } +} diff --git a/solutions/278. First Bad Version/278.py b/solutions/278. First Bad Version/278.py new file mode 100644 index 00000000000..541ef1fda51 --- /dev/null +++ b/solutions/278. First Bad Version/278.py @@ -0,0 +1,13 @@ +class Solution: + def firstBadVersion(self, n: int) -> int: + l = 1 + r = n + + while l < r: + m = (l + r) >> 1 + if isBadVersion(m): + r = m + else: + l = m + 1 + + return l diff --git a/solutions/2780. Minimum Index of a Valid Split/2780.cpp b/solutions/2780. Minimum Index of a Valid Split/2780.cpp new file mode 100644 index 00000000000..244867c225a --- /dev/null +++ b/solutions/2780. Minimum Index of a Valid Split/2780.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minimumIndex(vector& nums) { + const int n = nums.size(); + unordered_map count1; + unordered_map count2; + + for (const int num : nums) + ++count2[num]; + + for (int i = 0; i < n; ++i) { + const int freq1 = ++count1[nums[i]]; + const int freq2 = --count2[nums[i]]; + if (freq1 * 2 > i + 1 && freq2 * 2 > n - 1 - i) + return i; + } + + return -1; + } +}; diff --git a/solutions/2780. Minimum Index of a Valid Split/2780.java b/solutions/2780. Minimum Index of a Valid Split/2780.java new file mode 100644 index 00000000000..ec9a95611f2 --- /dev/null +++ b/solutions/2780. Minimum Index of a Valid Split/2780.java @@ -0,0 +1,19 @@ +class Solution { + public int minimumIndex(List nums) { + final int n = nums.size(); + Map count1 = new HashMap<>(); + Map count2 = new HashMap<>(); + + for (final int num : nums) + count2.merge(num, 1, Integer::sum); + + for (int i = 0; i < n; ++i) { + final int freq1 = count1.merge(nums.get(i), 1, Integer::sum); + final int freq2 = count2.merge(nums.get(i), -1, Integer::sum); + if (freq1 * 2 > i + 1 && freq2 * 2 > n - 1 - i) + return i; + } + + return -1; + } +} diff --git a/solutions/2780. Minimum Index of a Valid Split/2780.py b/solutions/2780. Minimum Index of a Valid Split/2780.py new file mode 100644 index 00000000000..f98917f103f --- /dev/null +++ b/solutions/2780. Minimum Index of a Valid Split/2780.py @@ -0,0 +1,12 @@ +class Solution: + def minimumIndex(self, nums: List[int]) -> int: + count1 = collections.Counter() + count2 = collections.Counter(nums) + + for i, num in enumerate(nums): + count1[num] = count1[num] + 1 + count2[num] = count2[num] - 1 + if count1[num] * 2 > i + 1 and count2[num] * 2 > len(nums) - i - 1: + return i + + return -1 diff --git a/solutions/2781. Length of the Longest Valid Substring/2781-2.cpp b/solutions/2781. Length of the Longest Valid Substring/2781-2.cpp new file mode 100644 index 00000000000..e7fc10b7fcc --- /dev/null +++ b/solutions/2781. Length of the Longest Valid Substring/2781-2.cpp @@ -0,0 +1,56 @@ +struct TrieNode { + public: + unordered_map> children; + bool isWord = false; +}; + +class Trie { + public: + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + if (node->children[c] == nullptr) + node->children[c] = make_shared(); + node = node->children[c]; + } + node->isWord = true; + } + + bool search(const string& word, int l, int r) { + shared_ptr node = root; + for (int j = l; j <= r; ++j) { + const char c = word[j]; + if (node->children[c] == nullptr) + return false; + node = node->children[c]; + } + return node->isWord; + } + + private: + shared_ptr root = make_shared(); +}; + +class Solution { + public: + int longestValidSubstring(string word, vector& forbidden) { + int ans = 0; + Trie trie; + + for (const string& s : forbidden) + trie.insert(s); + + // r is the rightmost index to make word[l..r] a valid substring. + int r = word.length() - 1; + for (int l = word.length() - 1; l >= 0; --l) { + for (int end = l; end < min(l + 10, r + 1); ++end) + if (trie.search(word, l, end)) { + r = end - 1; + break; + } + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/2781. Length of the Longest Valid Substring/2781-2.java b/solutions/2781. Length of the Longest Valid Substring/2781-2.java new file mode 100644 index 00000000000..5aae246cc80 --- /dev/null +++ b/solutions/2781. Length of the Longest Valid Substring/2781-2.java @@ -0,0 +1,53 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class Trie { + public void insert(String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + public boolean search(String word, int l, int r) { + TrieNode node = root; + for (int j = l; j <= r; ++j) { + final int i = word.charAt(j) - 'a'; + if (node.children[i] == null) + return false; + node = node.children[i]; + } + return node.isWord; + } + + private TrieNode root = new TrieNode(); +} + +class Solution { + public int longestValidSubstring(String word, List forbidden) { + int ans = 0; + Trie trie = new Trie(); + + for (final String s : forbidden) + trie.insert(s); + + // r is the rightmost index to make word[l..r] a valid substring. + int r = word.length() - 1; + for (int l = word.length() - 1; l >= 0; --l) { + for (int end = l; end < Math.min(l + 10, r + 1); ++end) + if (trie.search(word, l, end)) { + r = end - 1; + break; + } + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/2781. Length of the Longest Valid Substring/2781-2.py b/solutions/2781. Length of the Longest Valid Substring/2781-2.py new file mode 100644 index 00000000000..305887afcea --- /dev/null +++ b/solutions/2781. Length of the Longest Valid Substring/2781-2.py @@ -0,0 +1,43 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.isWord = False + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> None: + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + def search(self, word: str, l: int, r: int) -> bool: + node: TrieNode = self.root + for i in range(l, r): + if word[i] not in node.children: + return False + node = node.children[word[i]] + return node.isWord + + +class Solution: + def longestValidSubstring(self, word: str, forbidden: List[str]) -> int: + ans = 0 + trie = Trie() + + for s in forbidden: + trie.insert(s) + + # r is the rightmost index to make word[l..r] a valid substring. + r = len(word) - 1 + for l in range(len(word) - 1, -1, -1): + for end in range(l, min(l + 10, r + 1)): + if trie.search(word, l, end + 1): + r = end - 1 + break + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/2781. Length of the Longest Valid Substring/2781.cpp b/solutions/2781. Length of the Longest Valid Substring/2781.cpp new file mode 100644 index 00000000000..f7d844dfc55 --- /dev/null +++ b/solutions/2781. Length of the Longest Valid Substring/2781.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int longestValidSubstring(string word, vector& forbidden) { + int ans = 0; + unordered_set forbiddenSet{forbidden.begin(), forbidden.end()}; + + // r is the rightmost index to make word[l..r] a valid substring. + int r = word.length() - 1; + for (int l = word.length() - 1; l >= 0; --l) { + for (int end = l; end < min(l + 10, r + 1); ++end) + if (forbiddenSet.contains(word.substr(l, end - l + 1))) { + r = end - 1; + break; + } + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/2781. Length of the Longest Valid Substring/2781.java b/solutions/2781. Length of the Longest Valid Substring/2781.java new file mode 100644 index 00000000000..3707655f596 --- /dev/null +++ b/solutions/2781. Length of the Longest Valid Substring/2781.java @@ -0,0 +1,19 @@ +class Solution { + public int longestValidSubstring(String word, List forbidden) { + int ans = 0; + Set forbiddenSet = new HashSet<>(forbidden); + + // r is the rightmost index to make word[l..r] a valid substring. + int r = word.length() - 1; + for (int l = word.length() - 1; l >= 0; --l) { + for (int end = l; end < Math.min(l + 10, r + 1); ++end) + if (forbiddenSet.contains(word.substring(l, end + 1))) { + r = end - 1; + break; + } + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/2781. Length of the Longest Valid Substring/2781.py b/solutions/2781. Length of the Longest Valid Substring/2781.py new file mode 100644 index 00000000000..fd110db46ad --- /dev/null +++ b/solutions/2781. Length of the Longest Valid Substring/2781.py @@ -0,0 +1,14 @@ +class Solution: + def longestValidSubstring(self, word: str, forbidden: List[str]) -> int: + forbiddenSet = set(forbidden) + ans = 0 + r = len(word) - 1 # rightmost index of the valid substring + + for l in range(len(word) - 1, -1, -1): + for end in range(l, min(l + 10, r + 1)): + if word[l:end + 1] in forbiddenSet: + r = end - 1 + break + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/2782. Number of Unique Categories/2782.cpp b/solutions/2782. Number of Unique Categories/2782.cpp new file mode 100644 index 00000000000..c046e83bb4a --- /dev/null +++ b/solutions/2782. Number of Unique Categories/2782.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a category handler. + * class CategoryHandler { + * public: + * CategoryHandler(vector categories); + * bool haveSameCategory(int a, int b); + * }; + */ + +class Solution { + public: + int numberOfCategories(int n, CategoryHandler* categoryHandler) { + int ans = 0; + + for (int i = 0; i < n; ++i) + if (!haveSameCategoryPreviously(i, n, categoryHandler)) + ++ans; + + return ans; + } + + private: + bool haveSameCategoryPreviously(int i, int n, + CategoryHandler* categoryHandler) { + for (int j = 0; j < i; ++j) + if (categoryHandler->haveSameCategory(i, j)) + return true; + return false; + } +}; diff --git a/solutions/2782. Number of Unique Categories/2782.java b/solutions/2782. Number of Unique Categories/2782.java new file mode 100644 index 00000000000..2ce2dec9dca --- /dev/null +++ b/solutions/2782. Number of Unique Categories/2782.java @@ -0,0 +1,24 @@ +/** + * Definition for a category handler. + * class CategoryHandler { + * public CategoryHandler(int[] categories); + * public boolean haveSameCategory(int a, int b); + * }; + */ + +class Solution { + public int numberOfCategories(int n, CategoryHandler categoryHandler) { + int ans = 0; + for (int i = 0; i < n; ++i) + if (!haveSameCategoryPreviously(i, n, categoryHandler)) + ++ans; + return ans; + } + + private boolean haveSameCategoryPreviously(int i, int n, CategoryHandler categoryHandler) { + for (int j = 0; j < i; ++j) + if (categoryHandler.haveSameCategory(i, j)) + return true; + return false; + } +} diff --git a/solutions/2782. Number of Unique Categories/2782.py b/solutions/2782. Number of Unique Categories/2782.py new file mode 100644 index 00000000000..17f051c8729 --- /dev/null +++ b/solutions/2782. Number of Unique Categories/2782.py @@ -0,0 +1,14 @@ +# Definition for a category handler. +# class CategoryHandler: +# def haveSameCategory(self, a: int, b: int) -> bool: +# pass + +class Solution: + def numberOfCategories(self, n: int, categoryHandler: Optional['CategoryHandler']) -> int: + ans = 0 + + for i in range(n): + if not any(categoryHandler.haveSameCategory(i, j) for j in range(i)): + ans += 1 + + return ans diff --git a/solutions/2783. Flight Occupancy and Waitlist Analysis/2783.sql b/solutions/2783. Flight Occupancy and Waitlist Analysis/2783.sql new file mode 100644 index 00000000000..1c76a4fdfac --- /dev/null +++ b/solutions/2783. Flight Occupancy and Waitlist Analysis/2783.sql @@ -0,0 +1,9 @@ +SELECT + Flights.flight_id, + LEAST(Flights.capacity, COUNT(Passengers.flight_id)) AS booked_cnt, + GREATEST(0, COUNT(Passengers.flight_id) - Flights.capacity) AS waitlist_cnt +FROM Flights +LEFT JOIN Passengers + USING (flight_id) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2784. Check if Array is Good/2784.cpp b/solutions/2784. Check if Array is Good/2784.cpp new file mode 100644 index 00000000000..246b71ae224 --- /dev/null +++ b/solutions/2784. Check if Array is Good/2784.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool isGood(vector& nums) { + constexpr int kMax = 200; + const int n = nums.size() - 1; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + return all_of(count.begin() + 1, count.begin() + n, [](int c) { + return c == 1; + }) && count[n] == 2; + } +}; diff --git a/solutions/2784. Check if Array is Good/2784.java b/solutions/2784. Check if Array is Good/2784.java new file mode 100644 index 00000000000..4653105d7f4 --- /dev/null +++ b/solutions/2784. Check if Array is Good/2784.java @@ -0,0 +1,12 @@ +public class Solution { + public boolean isGood(int[] nums) { + final int kMax = 200; + final int n = nums.length - 1; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + return (n == 0 || Arrays.stream(count, 1, n).allMatch(c -> c == 1)) && count[n] == 2; + } +} diff --git a/solutions/2784. Check if Array is Good/2784.py b/solutions/2784. Check if Array is Good/2784.py new file mode 100644 index 00000000000..4d72ccb12bc --- /dev/null +++ b/solutions/2784. Check if Array is Good/2784.py @@ -0,0 +1,5 @@ +class Solution: + def isGood(self, nums: List[int]) -> bool: + n = len(nums) - 1 + count = collections.Counter(nums) + return all(count[i] == 1 for i in range(1, n)) and count[n] == 2 diff --git a/solutions/2785. Sort Vowels in a String/2785.cpp b/solutions/2785. Sort Vowels in a String/2785.cpp new file mode 100644 index 00000000000..719c5397c6c --- /dev/null +++ b/solutions/2785. Sort Vowels in a String/2785.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string sortVowels(string s) { + string ans; + vector vowels; + + for (const char c : s) + if (isVowel(c)) + vowels.push_back(c); + + ranges::sort(vowels); + + int i = 0; // vowels' index + for (const char c : s) + ans += isVowel(c) ? vowels[i++] : c; + + return ans; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/2785. Sort Vowels in a String/2785.java b/solutions/2785. Sort Vowels in a String/2785.java new file mode 100644 index 00000000000..d3274e48af0 --- /dev/null +++ b/solutions/2785. Sort Vowels in a String/2785.java @@ -0,0 +1,22 @@ +class Solution { + public String sortVowels(String s) { + StringBuilder sb = new StringBuilder(); + List vowels = new ArrayList<>(); + + for (final char c : s.toCharArray()) + if (isVowel(c)) + vowels.add(c); + + Collections.sort(vowels); + + int i = 0; // vowels' index + for (final char c : s.toCharArray()) + sb.append(isVowel(c) ? vowels.get(i++) : c); + + return sb.toString(); + } + + private boolean isVowel(char c) { + return "aeiouAEIOU".indexOf(c) != -1; + } +} diff --git a/solutions/2785. Sort Vowels in a String/2785.py b/solutions/2785. Sort Vowels in a String/2785.py new file mode 100644 index 00000000000..9a40c69ea15 --- /dev/null +++ b/solutions/2785. Sort Vowels in a String/2785.py @@ -0,0 +1,15 @@ +class Solution: + def sortVowels(self, s: str) -> str: + kVowels = 'aeiouAEIOU' + ans = [] + vowels = sorted([c for c in s if c in kVowels]) + + i = 0 # vowels' index + for c in s: + if c in kVowels: + ans.append(vowels[i]) + i += 1 + else: + ans.append(c) + + return ''.join(ans) diff --git a/solutions/2786. Visit Array Positions to Maximize Score/2786.cpp b/solutions/2786. Visit Array Positions to Maximize Score/2786.cpp new file mode 100644 index 00000000000..e2a7994006d --- /dev/null +++ b/solutions/2786. Visit Array Positions to Maximize Score/2786.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + long long maxScore(vector& nums, int x) { + // Note that we always need to take nums[0], so the initial definition might + // not hold true. + + // dp0 := the maximum score so far with `nums` ending in an even number + long dp0 = nums[0] - (nums[0] % 2 == 1 ? x : 0); + // dp1 := the maximum score so far with `nums` ending in an odd number + long dp1 = nums[0] - (nums[0] % 2 == 0 ? x : 0); + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] % 2 == 0) + dp0 = nums[i] + max(dp0, dp1 - x); + else + dp1 = nums[i] + max(dp1, dp0 - x); + + return max(dp0, dp1); + } +}; diff --git a/solutions/2786. Visit Array Positions to Maximize Score/2786.java b/solutions/2786. Visit Array Positions to Maximize Score/2786.java new file mode 100644 index 00000000000..88283e99c2e --- /dev/null +++ b/solutions/2786. Visit Array Positions to Maximize Score/2786.java @@ -0,0 +1,19 @@ +class Solution { + public long maxScore(int[] nums, int x) { + // Note that we always need to take nums[0], so the initial definition might + // not hold true. + + // dp0 := the maximum score so far with `nums` ending in an even number + long dp0 = nums[0] - (nums[0] % 2 == 1 ? x : 0); + // dp1 := the maximum score so far with `nums` ending in an odd number + long dp1 = nums[0] - (nums[0] % 2 == 0 ? x : 0); + + for (int i = 1; i < nums.length; ++i) + if (nums[i] % 2 == 0) + dp0 = nums[i] + Math.max(dp0, dp1 - x); + else + dp1 = nums[i] + Math.max(dp1, dp0 - x); + + return Math.max(dp0, dp1); + } +} diff --git a/solutions/2786. Visit Array Positions to Maximize Score/2786.py b/solutions/2786. Visit Array Positions to Maximize Score/2786.py new file mode 100644 index 00000000000..2e09e164d0e --- /dev/null +++ b/solutions/2786. Visit Array Positions to Maximize Score/2786.py @@ -0,0 +1,17 @@ +class Solution: + def maxScore(self, nums: List[int], x: int) -> int: + # Note that we always need to take nums[0], so the initial definition might + # not hold true. + + # dp0 := the maximum score so far with `nums` ending in an even number + dp0 = nums[0] - (x if nums[0] % 2 == 1 else 0) + # dp0 := the maximum score so far with `nums` ending in an odd number + dp1 = nums[0] - (x if nums[0] % 2 == 0 else 0) + + for i in range(1, len(nums)): + if nums[i] % 2 == 0: + dp0 = nums[i] + max(dp0, dp1 - x) + else: + dp1 = nums[i] + max(dp1, dp0 - x) + + return max(dp0, dp1) diff --git a/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.cpp b/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.cpp new file mode 100644 index 00000000000..de07ac961c2 --- /dev/null +++ b/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int numberOfWays(int n, int x) { + constexpr int kMod = 1'000'000'007; + // dp[i] := the number of ways to express i + vector dp(n + 1); + int ax; // a^x + + dp[0] = 1; + + for (int a = 1; (ax = pow(a, x)) <= n; ++a) + for (int i = n; i >= ax; --i) { + dp[i] += dp[i - ax]; + dp[i] %= kMod; + } + + return dp[n]; + } +}; diff --git a/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.java b/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.java new file mode 100644 index 00000000000..909df6c76d5 --- /dev/null +++ b/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.java @@ -0,0 +1,18 @@ +class Solution { + public int numberOfWays(int n, int x) { + final int kMod = 1_000_000_007; + // dp[i] := the number of ways to express i + int[] dp = new int[n + 1]; + int ax; // a^x + + dp[0] = 1; + + for (int a = 1; (ax = (int) Math.pow(a, x)) <= n; ++a) + for (int i = n; i >= ax; --i) { + dp[i] += dp[i - ax]; + dp[i] %= kMod; + } + + return dp[n]; + } +} diff --git a/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.py b/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.py new file mode 100644 index 00000000000..3e7cc0bf5fa --- /dev/null +++ b/solutions/2787. Ways to Express an Integer as Sum of Powers/2787.py @@ -0,0 +1,15 @@ +class Solution: + def numberOfWays(self, n: int, x: int) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of ways to express i + dp = [1] + [0] * n + + for a in range(1, n + 1): + ax = a**x + if ax > n: + break + for i in range(n, ax - 1, -1): + dp[i] += dp[i - ax] + dp[i] %= kMod + + return dp[n] diff --git a/solutions/2788. Split Strings by Separator/2788.cpp b/solutions/2788. Split Strings by Separator/2788.cpp new file mode 100644 index 00000000000..53c1d9ffd0f --- /dev/null +++ b/solutions/2788. Split Strings by Separator/2788.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector splitWordsBySeparator(vector& words, char separator) { + vector ans; + + for (const string& word : words) { + istringstream iss(word); + for (string word; getline(iss, word, separator);) + if (!word.empty()) + ans.push_back(word); + } + + return ans; + } +}; diff --git a/solutions/2788. Split Strings by Separator/2788.java b/solutions/2788. Split Strings by Separator/2788.java new file mode 100644 index 00000000000..fb5116af964 --- /dev/null +++ b/solutions/2788. Split Strings by Separator/2788.java @@ -0,0 +1,8 @@ +public class Solution { + public List splitWordsBySeparator(List words, char separator) { + return words.stream() + .flatMap(word -> Arrays.stream(word.split("\\" + separator))) + .filter(word -> !word.isEmpty()) + .collect(Collectors.toList()); + } +} diff --git a/solutions/2788. Split Strings by Separator/2788.py b/solutions/2788. Split Strings by Separator/2788.py new file mode 100644 index 00000000000..5b271150bc5 --- /dev/null +++ b/solutions/2788. Split Strings by Separator/2788.py @@ -0,0 +1,6 @@ +class Solution: + def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]: + return [splitWord + for word in words + for splitWord in word.split(separator) + if splitWord] diff --git a/solutions/2789. Largest Element in an Array after Merge Operations/2789.cpp b/solutions/2789. Largest Element in an Array after Merge Operations/2789.cpp new file mode 100644 index 00000000000..da38833d18f --- /dev/null +++ b/solutions/2789. Largest Element in an Array after Merge Operations/2789.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long maxArrayValue(vector& nums) { + long ans = nums.back(); + + for (int i = nums.size() - 2; i >= 0; --i) + if (nums[i] > ans) + ans = nums[i]; + else + ans += nums[i]; + + return ans; + } +}; diff --git a/solutions/2789. Largest Element in an Array after Merge Operations/2789.java b/solutions/2789. Largest Element in an Array after Merge Operations/2789.java new file mode 100644 index 00000000000..8626e78b5ab --- /dev/null +++ b/solutions/2789. Largest Element in an Array after Merge Operations/2789.java @@ -0,0 +1,13 @@ +class Solution { + public long maxArrayValue(int[] nums) { + long ans = nums[nums.length - 1]; + + for (int i = nums.length - 2; i >= 0; --i) + if (nums[i] > ans) + ans = nums[i]; + else + ans += nums[i]; + + return ans; + } +} diff --git a/solutions/2789. Largest Element in an Array after Merge Operations/2789.py b/solutions/2789. Largest Element in an Array after Merge Operations/2789.py new file mode 100644 index 00000000000..530f9249664 --- /dev/null +++ b/solutions/2789. Largest Element in an Array after Merge Operations/2789.py @@ -0,0 +1,11 @@ +class Solution: + def maxArrayValue(self, nums: List[int]) -> int: + ans = nums[-1] + + for i in range(len(nums) - 2, -1, -1): + if nums[i] > ans: + ans = nums[i] + else: + ans += nums[i] + + return ans diff --git a/solutions/279. Perfect Squares/279.cpp b/solutions/279. Perfect Squares/279.cpp new file mode 100644 index 00000000000..23cf4633b02 --- /dev/null +++ b/solutions/279. Perfect Squares/279.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int numSquares(int n) { + vector dp(n + 1, n); // 1^2 x n + dp[0] = 0; // no way + dp[1] = 1; // 1^2 + + for (int i = 2; i <= n; ++i) + for (int j = 1; j * j <= i; ++j) + dp[i] = min(dp[i], dp[i - j * j] + 1); + + return dp[n]; + } +}; diff --git a/solutions/279. Perfect Squares/279.java b/solutions/279. Perfect Squares/279.java new file mode 100644 index 00000000000..fad0ca19b44 --- /dev/null +++ b/solutions/279. Perfect Squares/279.java @@ -0,0 +1,14 @@ +class Solution { + public int numSquares(int n) { + int[] dp = new int[n + 1]; + Arrays.fill(dp, n); // 1^2 x n + dp[0] = 0; // no way + dp[1] = 1; // 1^2 + + for (int i = 2; i <= n; ++i) + for (int j = 1; j * j <= i; ++j) + dp[i] = Math.min(dp[i], dp[i - j * j] + 1); + + return dp[n]; + } +} diff --git a/solutions/279. Perfect Squares/279.py b/solutions/279. Perfect Squares/279.py new file mode 100644 index 00000000000..4c4ddafd39c --- /dev/null +++ b/solutions/279. Perfect Squares/279.py @@ -0,0 +1,13 @@ +class Solution: + def numSquares(self, n: int) -> int: + dp = [n] * (n + 1) # 1^2 x n + dp[0] = 0 # no way + dp[1] = 1 # 1^2 + + for i in range(2, n + 1): + j = 1 + while j * j <= i: + dp[i] = min(dp[i], dp[i - j * j] + 1) + j += 1 + + return dp[n] diff --git a/solutions/2790. Maximum Number of Groups With Increasing Length/2790.cpp b/solutions/2790. Maximum Number of Groups With Increasing Length/2790.cpp new file mode 100644 index 00000000000..113c4ba7695 --- /dev/null +++ b/solutions/2790. Maximum Number of Groups With Increasing Length/2790.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxIncreasingGroups(vector& usageLimits) { + int ans = 1; // the next target length + long availableLimits = 0; + + ranges::sort(usageLimits); + + for (const int usageLimit : usageLimits) { + availableLimits += usageLimit; + // Can create groups 1, 2, ..., ans. + if (availableLimits >= ans * static_cast(ans + 1) / 2) + ++ans; + } + + return ans - 1; + } +}; diff --git a/solutions/2790. Maximum Number of Groups With Increasing Length/2790.java b/solutions/2790. Maximum Number of Groups With Increasing Length/2790.java new file mode 100644 index 00000000000..0698db5c357 --- /dev/null +++ b/solutions/2790. Maximum Number of Groups With Increasing Length/2790.java @@ -0,0 +1,17 @@ +class Solution { + public int maxIncreasingGroups(List usageLimits) { + int ans = 1; // the next target length + long availableLimits = 0; + + Collections.sort(usageLimits); + + for (final int usageLimit : usageLimits) { + availableLimits += usageLimit; + // Can create groups 1, 2, ..., ans. + if (availableLimits >= ans * (long) (ans + 1) / 2) + ++ans; + } + + return ans - 1; + } +} diff --git a/solutions/2790. Maximum Number of Groups With Increasing Length/2790.py b/solutions/2790. Maximum Number of Groups With Increasing Length/2790.py new file mode 100644 index 00000000000..526fcf580f1 --- /dev/null +++ b/solutions/2790. Maximum Number of Groups With Increasing Length/2790.py @@ -0,0 +1,12 @@ +class Solution: + def maxIncreasingGroups(self, usageLimits: List[int]) -> int: + ans = 1 # the next target length + availableLimits = 0 + + for usageLimit in sorted(usageLimits): + availableLimits += usageLimit + # Can create groups 1, 2, ..., ans. + if availableLimits >= ans * (ans + 1) // 2: + ans += 1 + + return ans - 1 diff --git a/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.cpp b/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.cpp new file mode 100644 index 00000000000..7f931434684 --- /dev/null +++ b/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + long long countPalindromePaths(vector& parent, string s) { + // A valid (u, v) has at most 1 letter with odd frequency on its path. The + // frequency of a letter on the u-v path is equal to the sum of its + // frequencies on the root-u and root-v paths substract twice of its + // frequency on the root-LCA(u, v) path. Considering only the parity + // (even/odd), the part involving root-LCA(u, v) can be ignored, making it + // possible to calculate both parts easily using a simple DFS. + vector> tree(parent.size()); + + for (int i = 1; i < parent.size(); ++i) + tree[parent[i]].push_back(i); + + return dfs(tree, 0, 0, s, {{0, 1}}); + } + + private: + // mask := 26 bits that represent the parity of each character in the alphabet + // on the path from node 0 to node u + long dfs(const vector>& tree, int u, int mask, const string& s, + unordered_map&& maskToCount) { + long res = 0; + if (u > 0) { + mask ^= 1 << (s[u] - 'a'); + // Consider any u-v path with 1 bit set. + for (int i = 0; i < 26; ++i) + if (const auto it = maskToCount.find(mask ^ (1 << i)); + it != maskToCount.cend()) + res += it->second; + // Consider u-v path with 0 bit set. + res += maskToCount[mask ^ 0]++; + } + for (const int v : tree[u]) + res += dfs(tree, v, mask, s, move(maskToCount)); + return res; + } +}; diff --git a/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.java b/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.java new file mode 100644 index 00000000000..7e211b37df9 --- /dev/null +++ b/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.java @@ -0,0 +1,39 @@ +class Solution { + public long countPalindromePaths(List parent, String s) { + // A valid (u, v) has at most 1 letter with odd frequency on its path. The + // frequency of a letter on the u-v path is equal to the sum of its + // frequencies on the root-u and root-v paths substract twice of its + // frequency on the root-LCA(u, v) path. Considering only the parity + // (even/odd), the part involving root-LCA(u, v) can be ignored, making it + // possible to calculate both parts easily using a simple DFS. + List[] tree = new List[parent.size()]; + + for (int i = 0; i < parent.size(); ++i) + tree[i] = new ArrayList<>(); + + for (int i = 1; i < parent.size(); ++i) + tree[parent.get(i)].add(i); + + return dfs(tree, 0, 0, s, new HashMap<>(Map.of(0, 1))); + } + + // mask := 26 bits that represent the parity of each character in the alphabet + // on the path from node 0 to node u + private long dfs(List[] tree, int u, int mask, String s, + Map maskToCount) { + long res = 0; + if (u > 0) { + mask ^= 1 << (s.charAt(u) - 'a'); + // Consider any u-v path with 1 bit set. + for (int i = 0; i < 26; ++i) + if (maskToCount.containsKey(mask ^ (1 << i))) + res += maskToCount.get(mask ^ (1 << i)); + // Consider u-v path with 0 bit set. + res += maskToCount.getOrDefault(mask ^ 0, 0); + maskToCount.merge(mask, 1, Integer::sum); + } + for (final int v : tree[u]) + res += dfs(tree, v, mask, s, maskToCount); + return res; + } +} diff --git a/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.py b/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.py new file mode 100644 index 00000000000..2e73f3224f4 --- /dev/null +++ b/solutions/2791. Count Paths That Can Form a Palindrome in a Tree/2791.py @@ -0,0 +1,31 @@ +class Solution: + def countPalindromePaths(self, parent: List[int], s: str) -> int: + # A valid (u, v) has at most 1 letter with odd frequency on its path. The + # frequency of a letter on the u-v path is equal to the sum of its + # frequencies on the root-u and root-v paths substract twice of its + # frequency on the root-LCA(u, v) path. Considering only the parity + # (even/odd), the part involving root-LCA(u, v) can be ignored, making it + # possible to calculate both parts easily using a simple DFS. + tree = collections.defaultdict(list) + maskToCount = collections.Counter({0: 1}) + + for i in range(1, len(parent)): + tree[parent[i]].append(i) + + # mask := 26 bits that represent the parity of each character in the alphabet + # on the path from node 0 to node u + def dfs(u: int, mask: int) -> int: + res = 0 + if u > 0: + mask ^= 1 << (ord(s[u]) - ord('a')) + # Consider any u-v path with 1 bit set. + for i in range(26): + res += maskToCount[mask ^ (1 << i)] + # Consider u-v path with 0 bit set. + res += maskToCount[mask ^ 0] + maskToCount[mask] += 1 + for v in tree[u]: + res += dfs(v, mask) + return res + + return dfs(0, 0) diff --git a/solutions/2792. Count Nodes That Are Great Enough/2792.cpp b/solutions/2792. Count Nodes That Are Great Enough/2792.cpp new file mode 100644 index 00000000000..5802f6039d7 --- /dev/null +++ b/solutions/2792. Count Nodes That Are Great Enough/2792.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int countGreatEnoughNodes(TreeNode* root, int k) { + int ans = 0; + dfs(root, k, ans); + return ans; + } + + private: + multiset dfs(TreeNode* root, int k, int& ans) { + if (root == nullptr) + return {}; + + multiset kSmallest = dfs(root->left, k, ans); + multiset kSmallestRight = dfs(root->right, k, ans); + kSmallest.merge(kSmallestRight); + + if (kSmallest.size() > k) + kSmallest.erase(next(kSmallest.begin(), k), kSmallest.end()); + if (kSmallest.size() == k && root->val > *kSmallest.rbegin()) + ++ans; + + kSmallest.insert(root->val); + return kSmallest; + } +}; diff --git a/solutions/2792. Count Nodes That Are Great Enough/2792.java b/solutions/2792. Count Nodes That Are Great Enough/2792.java new file mode 100644 index 00000000000..2799ea89734 --- /dev/null +++ b/solutions/2792. Count Nodes That Are Great Enough/2792.java @@ -0,0 +1,25 @@ +class Solution { + public int countGreatEnoughNodes(TreeNode root, int k) { + dfs(root, k); + return ans; + } + + private int ans = 0; + + private Queue dfs(TreeNode root, int k) { + if (root == null) + return new PriorityQueue<>(Collections.reverseOrder()); + + Queue kSmallest = dfs(root.left, k); + Queue kSmallestRight = dfs(root.right, k); + kSmallest.addAll(kSmallestRight); + + while (kSmallest.size() > k) + kSmallest.poll(); + if (kSmallest.size() == k && root.val > kSmallest.peek()) + ++ans; + + kSmallest.offer(root.val); + return kSmallest; + } +} diff --git a/solutions/2792. Count Nodes That Are Great Enough/2792.py b/solutions/2792. Count Nodes That Are Great Enough/2792.py new file mode 100644 index 00000000000..7e79c9b4024 --- /dev/null +++ b/solutions/2792. Count Nodes That Are Great Enough/2792.py @@ -0,0 +1,17 @@ +class Solution: + def countGreatEnoughNodes(self, root: Optional[TreeNode], k: int) -> int: + ans = 0 + + def dfs(root: Optional[TreeNode]) -> List[int]: + nonlocal ans + if not root: + return [] + + kSmallest = sorted(dfs(root.left) + dfs(root.right))[:k] + if len(kSmallest) == k and root.val > kSmallest[-1]: + ans += 1 + + return kSmallest + [root.val] + + dfs(root) + return ans diff --git a/solutions/2793. Status of Flight Tickets/2793.sql b/solutions/2793. Status of Flight Tickets/2793.sql new file mode 100644 index 00000000000..25bab180b85 --- /dev/null +++ b/solutions/2793. Status of Flight Tickets/2793.sql @@ -0,0 +1,14 @@ +SELECT + Passengers.passenger_id, + IF( + RANK() OVER( + PARTITION BY Passengers.flight_id + ORDER BY Passengers.booking_time + ) <= Flights.capacity, + 'Confirmed', + 'Waitlist' + ) AS status +FROM Passengers +INNER JOIN Flights + USING (flight_id) +ORDER BY 1; diff --git a/solutions/2794. Create Object from Two Arrays/2794.ts b/solutions/2794. Create Object from Two Arrays/2794.ts new file mode 100644 index 00000000000..2c0d975dfbf --- /dev/null +++ b/solutions/2794. Create Object from Two Arrays/2794.ts @@ -0,0 +1,21 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; + +function createObject( + keysArr: JSONValue[], + valuesArr: JSONValue[] +): Record { + let ans: Record = {}; + keysArr.forEach((key, index) => { + let stringKey: string = typeof key === 'string' ? key : String(key); + if (!(stringKey in ans)) { + ans[stringKey] = valuesArr[index]; + } + }); + return ans; +} diff --git a/solutions/2795. Parallel Execution of Promises for Individual Results Retrieval/2795.ts b/solutions/2795. Parallel Execution of Promises for Individual Results Retrieval/2795.ts new file mode 100644 index 00000000000..645ff5c3dff --- /dev/null +++ b/solutions/2795. Parallel Execution of Promises for Individual Results Retrieval/2795.ts @@ -0,0 +1,30 @@ +type FulfilledObj = { + status: 'fulfilled'; + value: string; +}; +type RejectedObj = { + status: 'rejected'; + reason: string; +}; +type Obj = FulfilledObj | RejectedObj; + +function promiseAllSettled(functions: Function[]): Promise { + return new Promise((resolve) => { + const results: Obj[] = Array.from({ length: functions.length }); + let count = 0; + functions.forEach((fn, index) => { + fn() + .then((value) => { + results[index] = { status: 'fulfilled', value }; + }) + .catch((reason) => { + results[index] = { status: 'rejected', reason }; + }) + .finally(() => { + if (++count === functions.length) { + resolve(results); + } + }); + }); + }); +} diff --git a/solutions/2796. Repeat String/2796.ts b/solutions/2796. Repeat String/2796.ts new file mode 100644 index 00000000000..f89ff92161c --- /dev/null +++ b/solutions/2796. Repeat String/2796.ts @@ -0,0 +1,9 @@ +declare global { + interface String { + replicate(times: number): string; + } +} + +String.prototype.replicate = function (times): string { + return Array(times).fill(this).join(''); +}; diff --git a/solutions/2797. Partial Function with Placeholders/2797.ts b/solutions/2797. Partial Function with Placeholders/2797.ts new file mode 100644 index 00000000000..3b3f01a1d5b --- /dev/null +++ b/solutions/2797. Partial Function with Placeholders/2797.ts @@ -0,0 +1,18 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Fn = (...args: JSONValue[]) => JSONValue; + +function partial(fn: Fn, args: JSONValue[]): Fn { + return function (...restArgs) { + return fn( + ...args + .map((arg) => (arg === '_' ? restArgs.shift() : arg)) + .concat(restArgs) + ); + }; +} diff --git a/solutions/2798. Number of Employees Who Met the Target/2798.cpp b/solutions/2798. Number of Employees Who Met the Target/2798.cpp new file mode 100644 index 00000000000..f88690a2d37 --- /dev/null +++ b/solutions/2798. Number of Employees Who Met the Target/2798.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int numberOfEmployeesWhoMetTarget(vector& hours, int target) { + return ranges::count_if(hours, + [target](int hour) { return hour >= target; }); + } +}; diff --git a/solutions/2798. Number of Employees Who Met the Target/2798.java b/solutions/2798. Number of Employees Who Met the Target/2798.java new file mode 100644 index 00000000000..a77a776d2ba --- /dev/null +++ b/solutions/2798. Number of Employees Who Met the Target/2798.java @@ -0,0 +1,5 @@ +class Solution { + public int numberOfEmployeesWhoMetTarget(int[] hours, int target) { + return (int) Arrays.stream(hours).filter(hour -> hour >= target).count(); + } +} diff --git a/solutions/2798. Number of Employees Who Met the Target/2798.py b/solutions/2798. Number of Employees Who Met the Target/2798.py new file mode 100644 index 00000000000..f233028ecc6 --- /dev/null +++ b/solutions/2798. Number of Employees Who Met the Target/2798.py @@ -0,0 +1,3 @@ +class Solution: + def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int: + return sum(hour >= target for hour in hours) diff --git a/solutions/2799. Count Complete Subarrays in an Array/2799.cpp b/solutions/2799. Count Complete Subarrays in an Array/2799.cpp new file mode 100644 index 00000000000..6f2e2b85bfb --- /dev/null +++ b/solutions/2799. Count Complete Subarrays in an Array/2799.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int countCompleteSubarrays(vector& nums) { + constexpr int kMax = 2000; + const int totalDistinct = + unordered_set(nums.begin(), nums.end()).size(); + int ans = 0; + int distinct = 0; + vector count(kMax + 1); + + int l = 0; + for (const int num : nums) { + if (++count[num] == 1) + ++distinct; + while (distinct == totalDistinct) + if (--count[nums[l++]] == 0) + --distinct; + // Assume nums[r] = num, + // nums[0..r], nums[1..r], ..., nums[l - 1..r] have k different values. + ans += l; + } + + return ans; + } +}; diff --git a/solutions/2799. Count Complete Subarrays in an Array/2799.java b/solutions/2799. Count Complete Subarrays in an Array/2799.java new file mode 100644 index 00000000000..603b7551f35 --- /dev/null +++ b/solutions/2799. Count Complete Subarrays in an Array/2799.java @@ -0,0 +1,23 @@ +class Solution { + public int countCompleteSubarrays(int[] nums) { + final int kMax = 2000; + final int totalDistinct = Arrays.stream(nums).boxed().collect(Collectors.toSet()).size(); + int ans = 0; + int distinct = 0; + int[] count = new int[kMax + 1]; + + int l = 0; + for (final int num : nums) { + if (++count[num] == 1) + ++distinct; + while (distinct == totalDistinct) + if (--count[nums[l++]] == 0) + --distinct; + // Assume nums[r] = num, + // nums[0..r], nums[1..r], ..., nums[l - 1..r] have k different values. + ans += l; + } + + return ans; + } +} diff --git a/solutions/2799. Count Complete Subarrays in an Array/2799.py b/solutions/2799. Count Complete Subarrays in an Array/2799.py new file mode 100644 index 00000000000..2d6fbde073c --- /dev/null +++ b/solutions/2799. Count Complete Subarrays in an Array/2799.py @@ -0,0 +1,19 @@ +class Solution: + def countCompleteSubarrays(self, nums: List[int]) -> int: + ans = 0 + distinct = len(set(nums)) + count = collections.Counter() + + l = 0 + for num in nums: + count[num] += 1 + while len(count) == distinct: + count[nums[l]] -= 1 + if count[nums[l]] == 0: + del count[nums[l]] + l += 1 + # Assume nums[r] = num, + # nums[0..r], nums[1..r], ..., nums[l - 1..r] have k different values. + ans += l + + return ans diff --git a/solutions/28. Implement strStr()/28.cpp b/solutions/28. Implement strStr()/28.cpp new file mode 100644 index 00000000000..93e172d90fb --- /dev/null +++ b/solutions/28. Implement strStr()/28.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int strStr(string haystack, string needle) { + const int m = haystack.length(); + const int n = needle.length(); + + for (int i = 0; i < m - n + 1; i++) + if (haystack.substr(i, n) == needle) + return i; + + return -1; + } +}; diff --git a/solutions/28. Implement strStr()/28.java b/solutions/28. Implement strStr()/28.java new file mode 100644 index 00000000000..8ebcc1e24d6 --- /dev/null +++ b/solutions/28. Implement strStr()/28.java @@ -0,0 +1,12 @@ +class Solution { + public int strStr(String haystack, String needle) { + final int m = haystack.length(); + final int n = needle.length(); + + for (int i = 0; i < m - n + 1; ++i) + if (haystack.substring(i, i + n).equals(needle)) + return i; + + return -1; + } +} diff --git a/solutions/28. Implement strStr()/28.py b/solutions/28. Implement strStr()/28.py new file mode 100644 index 00000000000..888b4663a6a --- /dev/null +++ b/solutions/28. Implement strStr()/28.py @@ -0,0 +1,10 @@ +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + m = len(haystack) + n = len(needle) + + for i in range(m - n + 1): + if haystack[i:i + n] == needle: + return i + + return -1 diff --git a/solutions/280. Wiggle Sort/280.cpp b/solutions/280. Wiggle Sort/280.cpp new file mode 100644 index 00000000000..372800b59e5 --- /dev/null +++ b/solutions/280. Wiggle Sort/280.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + void wiggleSort(vector& nums) { + // 1. If i is even, then nums[i] <= nums[i - 1]. + // 2. If i is odd, then nums[i] >= nums[i - 1]. + for (int i = 1; i < nums.size(); ++i) + if (i % 2 == 0 && nums[i] > nums[i - 1] || + i % 2 == 1 && nums[i] < nums[i - 1]) + swap(nums[i], nums[i - 1]); + } +}; diff --git a/solutions/280. Wiggle Sort/280.java b/solutions/280. Wiggle Sort/280.java new file mode 100644 index 00000000000..078cc5db43e --- /dev/null +++ b/solutions/280. Wiggle Sort/280.java @@ -0,0 +1,16 @@ +class Solution { + public void wiggleSort(int[] nums) { + // 1. If i is even, then nums[i] <= nums[i - 1]. + // 2. If i is odd, then nums[i] >= nums[i - 1]. + for (int i = 1; i < nums.length; ++i) + if (i % 2 == 0 && nums[i] > nums[i - 1] || // + i % 2 == 1 && nums[i] < nums[i - 1]) + swap(nums, i, i - 1); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/280. Wiggle Sort/280.py b/solutions/280. Wiggle Sort/280.py new file mode 100644 index 00000000000..e4ff916bebb --- /dev/null +++ b/solutions/280. Wiggle Sort/280.py @@ -0,0 +1,8 @@ +class Solution: + def wiggleSort(self, nums: List[int]) -> None: + # 1. If i is even, then nums[i] <= nums[i - 1]. + # 2. If i is odd, then nums[i] >= nums[i - 1]. + for i in range(1, len(nums)): + if i % 2 == 0 and nums[i] > nums[i - 1] or \ + i % 2 == 1 and nums[i] < nums[i - 1]: + nums[i], nums[i - 1] = nums[i - 1], nums[i] diff --git a/solutions/2800. Shortest String That Contains Three Strings/2800.cpp b/solutions/2800. Shortest String That Contains Three Strings/2800.cpp new file mode 100644 index 00000000000..075af794d51 --- /dev/null +++ b/solutions/2800. Shortest String That Contains Three Strings/2800.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + string minimumString(string a, string b, string c) { + const string abc = merge(a, merge(b, c)); + const string acb = merge(a, merge(c, b)); + const string bac = merge(b, merge(a, c)); + const string bca = merge(b, merge(c, a)); + const string cab = merge(c, merge(a, b)); + const string cba = merge(c, merge(b, a)); + return getMin({abc, acb, bac, bca, cab, cba}); + } + + private: + // Merges a and b. + string merge(const string& a, const string& b) { + if (b.find(a) != string::npos) // a is a substring of b. + return b; + for (int i = 0; i < a.length(); ++i) { + const string aSuffix = a.substr(i); + const string bPrefix = b.substr(0, min(b.length(), aSuffix.length())); + if (aSuffix == bPrefix) + return a + b.substr(bPrefix.length()); + } + return a + b; + } + + // Returns the lexicographically smallest string. + string getMin(const vector& words) { + string res = words[0]; + for (int i = 1; i < words.size(); ++i) + res = getMin(res, words[i]); + return res; + } + + // Returns the lexicographically smaller string. + string getMin(const string& a, const string& b) { + return (a.length() < b.length() || (a.length() == b.length() && a < b)) ? a + : b; + } +}; diff --git a/solutions/2800. Shortest String That Contains Three Strings/2800.java b/solutions/2800. Shortest String That Contains Three Strings/2800.java new file mode 100644 index 00000000000..d7ccc0f2dbc --- /dev/null +++ b/solutions/2800. Shortest String That Contains Three Strings/2800.java @@ -0,0 +1,37 @@ +public class Solution { + public String minimumString(String a, String b, String c) { + final String abc = merge(a, merge(b, c)); + final String acb = merge(a, merge(c, b)); + final String bac = merge(b, merge(a, c)); + final String bca = merge(b, merge(c, a)); + final String cab = merge(c, merge(a, b)); + final String cba = merge(c, merge(b, a)); + return getMin(Arrays.asList(abc, acb, bac, bca, cab, cba)); + } + + // Merges a and b. + private String merge(String a, String b) { + if (b.contains(a)) // a is a substring of b. + return b; + for (int i = 0; i < a.length(); ++i) { + final String aSuffix = a.substring(i); + final String bPrefix = b.substring(0, Math.min(b.length(), aSuffix.length())); + if (aSuffix.equals(bPrefix)) + return a + b.substring(bPrefix.length()); + } + return a + b; + } + + // Returns the lexicographically smallest string. + private String getMin(List words) { + String res = words.get(0); + for (int i = 1; i < words.size(); ++i) + res = getMin(res, words.get(i)); + return res; + } + + // Returns the lexicographically smaller string. + private String getMin(String a, String b) { + return (a.length() < b.length() || (a.length() == b.length() && a.compareTo(b) < 0)) ? a : b; + } +} diff --git a/solutions/2800. Shortest String That Contains Three Strings/2800.py b/solutions/2800. Shortest String That Contains Three Strings/2800.py new file mode 100644 index 00000000000..bfa7dacf80e --- /dev/null +++ b/solutions/2800. Shortest String That Contains Three Strings/2800.py @@ -0,0 +1,32 @@ +class Solution: + def minimumString(self, a: str, b: str, c: str) -> str: + def merge(a: str, b: str) -> str: + """Merges a and b.""" + if a in b: # a is a substring of b. + return b + for i in range(len(a)): + aSuffix = a[i:] + bPrefix = b[:len(aSuffix)] + if aSuffix == bPrefix: + return a + b[len(bPrefix):] + return a + b + + abc = merge(a, merge(b, c)) + acb = merge(a, merge(c, b)) + bac = merge(b, merge(a, c)) + bca = merge(b, merge(c, a)) + cab = merge(c, merge(a, b)) + cba = merge(c, merge(b, a)) + return self._getMin([abc, acb, bac, bca, cab, cba]) + + def _getMin(self, words: List[str]) -> str: + """Returns the lexicographically smallest string.""" + + def getMin(a: str, b: str) -> str: + """Returns the lexicographically smaller string.""" + return a if len(a) < len(b) or (len(a) == len(b) and a < b) else b + + res = words[0] + for i in range(1, len(words)): + res = getMin(res, words[i]) + return res diff --git a/solutions/2801. Count Stepping Numbers in Range/2801.cpp b/solutions/2801. Count Stepping Numbers in Range/2801.cpp new file mode 100644 index 00000000000..0bdf3f168ff --- /dev/null +++ b/solutions/2801. Count Stepping Numbers in Range/2801.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int countSteppingNumbers(string low, string high) { + const string lowWithLeadingZeros = + string(high.length() - low.length(), '0') + low; + vector>>> mem( + high.length(), vector>>( + 11, vector>(2, vector(2, -1)))); + return count(lowWithLeadingZeros, high, 0, 10, /*isLeadingZero=*/true, true, + true, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of valid integers, considering the i-th digit, where + // `prevDigit` is the previous digit, `isTight1` indicates if the current + // digit is tightly bound for `low`, and `isTight2` indicates if the current + // digit is tightly bound for `high`. + int count(const string& low, const string& high, int i, int prevDigit, + bool isLeadingZero, bool isTight1, bool isTight2, + vector>>>& mem) { + if (i == high.length()) + return 1; + if (mem[i][prevDigit][isTight1][isTight2] != -1) + return mem[i][prevDigit][isTight1][isTight2]; + + int res = 0; + const int minDigit = isTight1 ? low[i] - '0' : 0; + const int maxDigit = isTight2 ? high[i] - '0' : 9; + + for (int d = minDigit; d <= maxDigit; ++d) { + const bool nextIsTight1 = isTight1 && (d == minDigit); + const bool nextIsTight2 = isTight2 && (d == maxDigit); + if (isLeadingZero) + // Can place any digit in [minDigit, maxDigit]. + res += count(low, high, i + 1, d, isLeadingZero && d == 0, nextIsTight1, + nextIsTight2, mem); + else if (abs(d - prevDigit) == 1) + // Can only place prevDigit - 1 or prevDigit + 1. + res += + count(low, high, i + 1, d, false, nextIsTight1, nextIsTight2, mem); + res %= kMod; + } + + return mem[i][prevDigit][isTight1][isTight2] = res; + } +}; diff --git a/solutions/2801. Count Stepping Numbers in Range/2801.java b/solutions/2801. Count Stepping Numbers in Range/2801.java new file mode 100644 index 00000000000..a1ab30c486e --- /dev/null +++ b/solutions/2801. Count Stepping Numbers in Range/2801.java @@ -0,0 +1,41 @@ +class Solution { + public int countSteppingNumbers(String low, String high) { + final String lowWithLeadingZeros = + String.valueOf('0').repeat(high.length() - low.length()) + low; + Integer[][][][] mem = new Integer[high.length()][11][2][2]; + return count(lowWithLeadingZeros, high, 0, 10, /*isLeadingZero=*/true, true, true, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of valid integers, considering the i-th digit, where + // `prevDigit` is the previous digit, `isTight1` indicates if the current + // digit is tightly bound for `low`, and `isTight2` indicates if the current + // digit is tightly bound for `high`. + private int count(final String low, final String high, int i, int prevDigit, + boolean isLeadingZero, boolean isTight1, boolean isTight2, + Integer[][][][] mem) { + if (i == high.length()) + return 1; + if (mem[i][prevDigit][isTight1 ? 1 : 0][isTight2 ? 1 : 0] != null) + return mem[i][prevDigit][isTight1 ? 1 : 0][isTight2 ? 1 : 0]; + + int res = 0; + final int minDigit = isTight1 ? low.charAt(i) - '0' : 0; + final int maxDigit = isTight2 ? high.charAt(i) - '0' : 9; + + for (int d = minDigit; d <= maxDigit; ++d) { + final boolean nextIsTight1 = isTight1 && (d == minDigit); + final boolean nextIsTight2 = isTight2 && (d == maxDigit); + if (isLeadingZero) + // Can place any digit in [minDigit, maxDigit]. + res += count(low, high, i + 1, d, isLeadingZero && d == 0, nextIsTight1, nextIsTight2, mem); + else if (Math.abs(d - prevDigit) == 1) + // Can only place prevDigit - 1 or prevDigit + 1. + res += count(low, high, i + 1, d, false, nextIsTight1, nextIsTight2, mem); + res %= kMod; + } + + return mem[i][prevDigit][isTight1 ? 1 : 0][isTight2 ? 1 : 0] = res; + } +} diff --git a/solutions/2801. Count Stepping Numbers in Range/2801.py b/solutions/2801. Count Stepping Numbers in Range/2801.py new file mode 100644 index 00000000000..f58320b78bd --- /dev/null +++ b/solutions/2801. Count Stepping Numbers in Range/2801.py @@ -0,0 +1,34 @@ +class Solution: + def countSteppingNumbers(self, low: str, high: str) -> int: + kMod = 1_000_000_007 + low = '0' * (len(high) - len(low)) + low + + @functools.lru_cache(None) + def dp(i: int, prevDigit: int, isLeadingZero: bool, isTight1: bool, isTight2: bool) -> int: + """ + Returns the number of valid integers, considering the i-th digit, where + `prevDigit` is the previous digit, `isTight1` indicates if the current + digit is tightly bound for `low`, and `isTight2` indicates if the current + digit is tightly bound for `high`. + """ + if i == len(high): + return 1 + + res = 0 + minDigit = int(low[i]) if isTight1 else 0 + maxDigit = int(high[i]) if isTight2 else 9 + + for d in range(minDigit, maxDigit + 1): + nextIsTight1 = isTight1 and (d == minDigit) + nextIsTight2 = isTight2 and (d == maxDigit) + if isLeadingZero: + # Can place any digit in [minDigit, maxDigit]. + res += dp(i + 1, d, isLeadingZero and d == + 0, nextIsTight1, nextIsTight2) + elif abs(d - prevDigit) == 1: + res += dp(i + 1, d, False, nextIsTight1, nextIsTight2) + res %= kMod + + return res + + return dp(0, -1, True, True, True) diff --git a/solutions/2802. Find The K-th Lucky Number/2802.cpp b/solutions/2802. Find The K-th Lucky Number/2802.cpp new file mode 100644 index 00000000000..a320f74335a --- /dev/null +++ b/solutions/2802. Find The K-th Lucky Number/2802.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + string kthLuckyNumber(int k) { + string ans; + + for (int i = k + 1; i > 0; i /= 2) + ans += i % 2 == 0 ? '4' : '7'; + + reverse(ans.begin(), ans.end()); + return ans.substr(1); + } +}; diff --git a/solutions/2802. Find The K-th Lucky Number/2802.java b/solutions/2802. Find The K-th Lucky Number/2802.java new file mode 100644 index 00000000000..ce95e9757e6 --- /dev/null +++ b/solutions/2802. Find The K-th Lucky Number/2802.java @@ -0,0 +1,10 @@ +class Solution { + public String kthLuckyNumber(int k) { + StringBuilder sb = new StringBuilder(); + + for (int i = k + 1; i > 0; i /= 2) + sb.append(i % 2 == 0 ? '4' : '7'); + + return sb.reverse().substring(1); + } +} diff --git a/solutions/2802. Find The K-th Lucky Number/2802.py b/solutions/2802. Find The K-th Lucky Number/2802.py new file mode 100644 index 00000000000..7162cd3f441 --- /dev/null +++ b/solutions/2802. Find The K-th Lucky Number/2802.py @@ -0,0 +1,3 @@ +class Solution: + def kthLuckyNumber(self, k: int) -> str: + return bin(k + 1)[3:].replace('0', '4').replace('1', '7') diff --git a/solutions/2803. Factorial Generator/2803.ts b/solutions/2803. Factorial Generator/2803.ts new file mode 100644 index 00000000000..01710c163b7 --- /dev/null +++ b/solutions/2803. Factorial Generator/2803.ts @@ -0,0 +1,10 @@ +function* factorial(n: number): Generator { + if (n === 0) { + yield 1; + } + let fact = 1; + for (let i = 1; i <= n; ++i) { + fact *= i; + yield fact; + } +} diff --git a/solutions/2804. Array Prototype ForEach/2804.ts b/solutions/2804. Array Prototype ForEach/2804.ts new file mode 100644 index 00000000000..cd632c0c151 --- /dev/null +++ b/solutions/2804. Array Prototype ForEach/2804.ts @@ -0,0 +1,22 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Callback = ( + currentValue: JSONValue, + index: number, + array: JSONValue[] +) => any; +type Context = Record; + +Array.prototype.forEach = function ( + callback: Callback, + context: Context +): void { + for (let i = 0; i < this.length; ++i) { + callback.call(context, this[i], i, this); + } +}; diff --git a/solutions/2805. Custom Interval/2805.ts b/solutions/2805. Custom Interval/2805.ts new file mode 100644 index 00000000000..e47e04b3917 --- /dev/null +++ b/solutions/2805. Custom Interval/2805.ts @@ -0,0 +1,18 @@ +let id = 0; +const idToTimeout = {}; + +function customInterval(fn: Function, delay: number, period: number): number { + ++id; + (function callFnWithCountPlusOne(count: number): void { + const timeout = setTimeout(() => { + fn(); + callFnWithCountPlusOne(count + 1); + }, delay + period * count); + idToTimeout[id] = timeout; + })(0); + return id; +} + +function customClearInterval(id: number): void { + clearTimeout(idToTimeout[id]); +} diff --git a/solutions/2806. Account Balance After Rounded Purchase/2806.cpp b/solutions/2806. Account Balance After Rounded Purchase/2806.cpp new file mode 100644 index 00000000000..7f9218b8ffa --- /dev/null +++ b/solutions/2806. Account Balance After Rounded Purchase/2806.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int accountBalanceAfterPurchase(int purchaseAmount) { + return 100 - ((purchaseAmount + 5) / 10) * 10; + } +}; diff --git a/solutions/2806. Account Balance After Rounded Purchase/2806.java b/solutions/2806. Account Balance After Rounded Purchase/2806.java new file mode 100644 index 00000000000..d46978faec0 --- /dev/null +++ b/solutions/2806. Account Balance After Rounded Purchase/2806.java @@ -0,0 +1,5 @@ +class Solution { + public int accountBalanceAfterPurchase(int purchaseAmount) { + return 100 - ((purchaseAmount + 5) / 10) * 10; + } +} diff --git a/solutions/2806. Account Balance After Rounded Purchase/2806.py b/solutions/2806. Account Balance After Rounded Purchase/2806.py new file mode 100644 index 00000000000..1501ff04748 --- /dev/null +++ b/solutions/2806. Account Balance After Rounded Purchase/2806.py @@ -0,0 +1,3 @@ +class Solution: + def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int: + return 100 - ((purchaseAmount + 5) // 10) * 10 diff --git a/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.cpp b/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.cpp new file mode 100644 index 00000000000..4be925aafd4 --- /dev/null +++ b/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + ListNode* insertGreatestCommonDivisors(ListNode* head) { + for (ListNode* curr = head; curr->next != nullptr;) { + ListNode* inserted = + new ListNode(__gcd(curr->val, curr->next->val), curr->next); + curr->next = inserted; + curr = inserted->next; + } + return head; + } +}; diff --git a/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.java b/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.java new file mode 100644 index 00000000000..c4c26365c2d --- /dev/null +++ b/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.java @@ -0,0 +1,14 @@ +class Solution { + public ListNode insertGreatestCommonDivisors(ListNode head) { + for (ListNode curr = head; curr.next != null;) { + ListNode inserted = new ListNode(gcd(curr.val, curr.next.val), curr.next); + curr.next = inserted; + curr = inserted.next; + } + return head; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.py b/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.py new file mode 100644 index 00000000000..29f67dd68e7 --- /dev/null +++ b/solutions/2807. Insert Greatest Common Divisors in Linked List/2807.py @@ -0,0 +1,8 @@ +class Solution: + def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]: + curr = head + while curr.next: + inserted = ListNode(math.gcd(curr.val, curr.next.val), curr.next) + curr.next = inserted + curr = inserted.next + return head diff --git a/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.cpp b/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.cpp new file mode 100644 index 00000000000..b3fa605250c --- /dev/null +++ b/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minimumSeconds(vector& nums) { + const int n = nums.size(); + int ans = n; + unordered_map> numToIndices; + + for (int i = 0; i < n; ++i) + numToIndices[nums[i]].push_back(i); + + for (const auto& [_, indices] : numToIndices) { + int seconds = getSeconds(indices.front() + n, indices.back()); + for (int i = 1; i < indices.size(); ++i) + seconds = max(seconds, getSeconds(indices[i], indices[i - 1])); + ans = min(ans, seconds); + } + + return ans; + } + + private: + // Returns the number of seconds required to make nums[i..j] the same. + int getSeconds(int i, int j) { + return (i - j) / 2; + } +}; diff --git a/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.java b/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.java new file mode 100644 index 00000000000..10b60c1bcba --- /dev/null +++ b/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.java @@ -0,0 +1,26 @@ +class Solution { + public int minimumSeconds(List nums) { + int n = nums.size(); + int ans = n; + Map> numToIndices = new HashMap<>(); + + for (int i = 0; i < n; ++i) { + numToIndices.putIfAbsent(nums.get(i), new ArrayList<>()); + numToIndices.get(nums.get(i)).add(i); + } + + for (List indices : numToIndices.values()) { + int seconds = getSeconds(indices.get(0) + n, indices.get(indices.size() - 1)); + for (int i = 1; i < indices.size(); ++i) + seconds = Math.max(seconds, getSeconds(indices.get(i), indices.get(i - 1))); + ans = Math.min(ans, seconds); + } + + return ans; + } + + // Returns the number of seconds required to make nums[i..j] the same. + private int getSeconds(int i, int j) { + return (i - j) / 2; + } +} diff --git a/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.py b/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.py new file mode 100644 index 00000000000..5390dcc5793 --- /dev/null +++ b/solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.py @@ -0,0 +1,20 @@ +class Solution: + def minimumSeconds(self, nums: List[int]) -> int: + n = len(nums) + ans = n + numToIndices = collections.defaultdict(list) + + for i, num in enumerate(nums): + numToIndices[num].append(i) + + def getSeconds(i: int, j: int) -> int: + """Returns the number of seconds required to make nums[i..j] the same.""" + return (i - j) // 2 + + for indices in numToIndices.values(): + seconds = getSeconds(indices[0] + n, indices[-1]) + for i in range(1, len(indices)): + seconds = max(seconds, getSeconds(indices[i], indices[i - 1])) + ans = min(ans, seconds) + + return ans diff --git a/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.cpp b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.cpp new file mode 100644 index 00000000000..f9e9d8374ef --- /dev/null +++ b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int minimumTime(vector& nums1, vector& nums2, int x) { + const int n = nums1.size(); + const int sum1 = accumulate(nums1.begin(), nums1.end(), 0); + const int sum2 = accumulate(nums2.begin(), nums2.end(), 0); + // dp[j] := the maximum reduced value if we do j operations on the numbers + // so far + vector dp(n + 1); + vector> sortedNums; + + for (int i = 0; i < n; ++i) + sortedNums.emplace_back(nums2[i], nums1[i]); + + ranges::sort(sortedNums); + + for (int i = 1; i <= n; ++i) { + const auto [num2, num1] = sortedNums[i - 1]; + for (int j = i; j > 0; --j) + dp[j] = max( + // the maximum reduced value if we do j operations on the first + // i - 1 numbers + dp[j], + // the maximum reduced value if we do j - 1 operations on the first + // i - 1 numbers + making the i-th number of `nums1` to 0 at the + // j-th operation + dp[j - 1] + num2 * j + num1); + } + + for (int op = 0; op <= n; ++op) + if (sum1 + sum2 * op - dp[op] <= x) + return op; + + return -1; + } +}; diff --git a/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.java b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.java new file mode 100644 index 00000000000..2b3febab66b --- /dev/null +++ b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.java @@ -0,0 +1,36 @@ +class Solution { + public int minimumTime(List nums1, List nums2, int x) { + final int n = nums1.size(); + final int sum1 = nums1.stream().mapToInt(Integer::intValue).sum(); + final int sum2 = nums2.stream().mapToInt(Integer::intValue).sum(); + // dp[j] := the maximum reduced value if we do j operations on the numbers + // so far + int[] dp = new int[n + 1]; + List> sortedNums = new ArrayList<>(); + + for (int i = 0; i < n; ++i) + sortedNums.add(new Pair<>(nums2.get(i), nums1.get(i))); + + sortedNums.sort(Comparator.comparingInt(a -> a.getKey())); + + for (int i = 1; i <= n; ++i) { + final int num2 = sortedNums.get(i - 1).getKey(); + final int num1 = sortedNums.get(i - 1).getValue(); + for (int j = i; j > 0; --j) + dp[j] = Math.max( + // the maximum reduced value if we do j operations on the first + // i - 1 numbers + dp[j], + // the maximum reduced value if we do j - 1 operations on the first + // i - 1 numbers + making the i-th number of `nums1` to 0 at the + // j-th operation + dp[j - 1] + num2 * j + num1); + } + + for (int op = 0; op <= n; ++op) + if (sum1 + sum2 * op - dp[op] <= x) + return op; + + return -1; + } +} diff --git a/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.py b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.py new file mode 100644 index 00000000000..466d65d8ee8 --- /dev/null +++ b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809-2.py @@ -0,0 +1,26 @@ +class Solution: + def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: + n = len(nums1) + # dp[j] := the maximum reduced value if we do j operations on the numbers + # so far + dp = [0] * (n + 1) + sum1 = sum(nums1) + sum2 = sum(nums2) + + for i, (num2, num1) in enumerate(sorted(zip(nums2, nums1)), 1): + for j in range(i, 0, -1): + dp[j] = max( + # the maximum reduced value if we do j operations on the first + # i - 1 numbers + dp[j], + # the maximum reduced value if we do j - 1 operations on the first + # i - 1 numbers + making the i-th number of `nums1` to 0 at the + # j-th operation + dp[j - 1] + num2 * j + num1 + ) + + for op in range(n + 1): + if sum1 + sum2 * op - dp[op] <= x: + return op + + return -1 diff --git a/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.cpp b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.cpp new file mode 100644 index 00000000000..5313cad0966 --- /dev/null +++ b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int minimumTime(vector& nums1, vector& nums2, int x) { + const int n = nums1.size(); + const int sum1 = accumulate(nums1.begin(), nums1.end(), 0); + const int sum2 = accumulate(nums2.begin(), nums2.end(), 0); + // dp[i][j] := the maximum reduced value if we do j operations on the first + // i numbers + vector> dp(n + 1, vector(n + 1)); + vector> sortedNums; + + for (int i = 0; i < n; ++i) + sortedNums.emplace_back(nums2[i], nums1[i]); + + ranges::sort(sortedNums); + + for (int i = 1; i <= n; ++i) { + const auto [num2, num1] = sortedNums[i - 1]; + for (int j = 1; j <= i; ++j) + dp[i][j] = max( + // the maximum reduced value if we do j operations on the first + // i - 1 numbers + dp[i - 1][j], + // the maximum reduced value if we do j - 1 operations on the first + // i - 1 numbers + making the i-th number of `nums1` to 0 at the + // j-th operation + dp[i - 1][j - 1] + num2 * j + num1); + } + + for (int op = 0; op <= n; ++op) + if (sum1 + sum2 * op - dp[n][op] <= x) + return op; + + return -1; + } +}; diff --git a/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.java b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.java new file mode 100644 index 00000000000..dd500ee3c06 --- /dev/null +++ b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.java @@ -0,0 +1,34 @@ +class Solution { + public int minimumTime(List nums1, List nums2, int x) { + final int n = nums1.size(); + final int sum1 = nums1.stream().mapToInt(Integer::intValue).sum(); + final int sum2 = nums2.stream().mapToInt(Integer::intValue).sum(); + // dp[i][j] := the maximum reduced value if we do j operations on the first + // i numbers + int[][] dp = new int[n + 1][n + 1]; + List> sortedNums = new ArrayList<>(); + + for (int i = 0; i < n; ++i) + sortedNums.add(new Pair<>(nums2.get(i), nums1.get(i))); + + sortedNums.sort(Comparator.comparingInt(a -> a.getKey())); + + for (int i = 1; i <= n; ++i) { + final int num2 = sortedNums.get(i - 1).getKey(); + final int num1 = sortedNums.get(i - 1).getValue(); + for (int j = 1; j <= i; ++j) + dp[i][j] = Math.max( + // the maximum reduced value if we do j ops on the first i - 1 nums + dp[i - 1][j], + // the maximum reduced value if we do j - 1 ops on the first i - 1 + // nums + making i-th num of nums1 to 0 at j-th operation + dp[i - 1][j - 1] + num2 * j + num1); + } + + for (int op = 0; op <= n; ++op) + if (sum1 + sum2 * op - dp[n][op] <= x) + return op; + + return -1; + } +} diff --git a/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.py b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.py new file mode 100644 index 00000000000..e72f984fcae --- /dev/null +++ b/solutions/2809. Minimum Time to Make Array Sum At Most x/2809.py @@ -0,0 +1,26 @@ +class Solution: + def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: + n = len(nums1) + # dp[i][j] := the maximum reduced value if we do j operations on the first + # i numbers + dp = [[0] * (n + 1) for _ in range(n + 1)] + sum1 = sum(nums1) + sum2 = sum(nums2) + + for i, (num2, num1) in enumerate(sorted(zip(nums2, nums1)), 1): + for j in range(1, i + 1): + dp[i][j] = max( + # the maximum reduced value if we do j operations on the first + # i - 1 numbers + dp[i - 1][j], + # the maximum reduced value if we do j - 1 operations on the first + # i - 1 numbers + making the i-th number of `nums1` to 0 at the + # j-th operation + dp[i - 1][j - 1] + num2 * j + num1 + ) + + for op in range(n + 1): + if sum1 + sum2 * op - dp[n][op] <= x: + return op + + return -1 diff --git a/solutions/281. Zigzag Iterator/281.cpp b/solutions/281. Zigzag Iterator/281.cpp new file mode 100644 index 00000000000..776c6da002d --- /dev/null +++ b/solutions/281. Zigzag Iterator/281.cpp @@ -0,0 +1,25 @@ +class ZigzagIterator { + public: + ZigzagIterator(vector& v1, vector& v2) { + if (!v1.empty()) + q.emplace(v1.begin(), v1.end()); + if (!v2.empty()) + q.emplace(v2.begin(), v2.end()); + } + + int next() { + const auto [it, endIt] = q.front(); + q.pop(); + if (it + 1 != endIt) + q.emplace(it + 1, endIt); + return *it; + } + + bool hasNext() { + return !q.empty(); + } + + private: + // {{ it, endIt }} + queue::iterator, vector::iterator>> q; +}; diff --git a/solutions/281. Zigzag Iterator/281.java b/solutions/281. Zigzag Iterator/281.java new file mode 100644 index 00000000000..3ea6f566bdc --- /dev/null +++ b/solutions/281. Zigzag Iterator/281.java @@ -0,0 +1,22 @@ +public class ZigzagIterator { + public ZigzagIterator(List v1, List v2) { + if (!v1.isEmpty()) + q.offer(v1.iterator()); + if (!v2.isEmpty()) + q.offer(v2.iterator()); + } + + public int next() { + final Iterator it = q.poll(); + final int next = (int) it.next(); + if (it.hasNext()) + q.offer(it); + return next; + } + + public boolean hasNext() { + return !q.isEmpty(); + } + + private Queue q = new ArrayDeque<>(); +} diff --git a/solutions/281. Zigzag Iterator/281.py b/solutions/281. Zigzag Iterator/281.py new file mode 100644 index 00000000000..ca308ea1649 --- /dev/null +++ b/solutions/281. Zigzag Iterator/281.py @@ -0,0 +1,16 @@ +class ZigzagIterator: + def __init__(self, v1: List[int], v2: List[int]): + def vals(): + for i in itertools.count(): + for v in v1, v2: + if i < len(v): + yield v[i] + self.vals = vals() + self.n = len(v1) + len(v2) + + def next(self): + self.n -= 1 + return next(self.vals) + + def hasNext(self): + return self.n > 0 diff --git a/solutions/2810. Faulty Keyboard/2810.cpp b/solutions/2810. Faulty Keyboard/2810.cpp new file mode 100644 index 00000000000..57d88e4ec1d --- /dev/null +++ b/solutions/2810. Faulty Keyboard/2810.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string finalString(string s) { + deque dq; + bool inversed = false; + + for (const char c : s) + if (c == 'i') + inversed = !inversed; + else if (inversed) + dq.push_front(c); + else + dq.push_back(c); + + return inversed ? string{dq.rbegin(), dq.rend()} + : string{dq.begin(), dq.end()}; + } +}; diff --git a/solutions/2810. Faulty Keyboard/2810.java b/solutions/2810. Faulty Keyboard/2810.java new file mode 100644 index 00000000000..dd92407688d --- /dev/null +++ b/solutions/2810. Faulty Keyboard/2810.java @@ -0,0 +1,20 @@ +class Solution { + public String finalString(String s) { + StringBuilder sb = new StringBuilder(); + Deque dq = new ArrayDeque<>(); + boolean inversed = false; + + for (final char c : s.toCharArray()) + if (c == 'i') + inversed = !inversed; + else if (inversed) + dq.addFirst(c); + else + dq.addLast(c); + + while (!dq.isEmpty()) + sb.append(dq.pollFirst()); + + return inversed ? sb.reverse().toString() : sb.toString(); + } +} diff --git a/solutions/2810. Faulty Keyboard/2810.py b/solutions/2810. Faulty Keyboard/2810.py new file mode 100644 index 00000000000..408cf29b02c --- /dev/null +++ b/solutions/2810. Faulty Keyboard/2810.py @@ -0,0 +1,14 @@ +class Solution: + def finalString(self, s: str) -> str: + dq = collections.deque() + inversed = False + + for c in s: + if c == 'i': + inversed = not inversed + elif inversed: + dq.appendleft(c) + else: + dq.append(c) + + return ''.join(reversed(dq)) if inversed else ''.join(dq) diff --git a/solutions/2811. Check if it is Possible to Split Array/2811.cpp b/solutions/2811. Check if it is Possible to Split Array/2811.cpp new file mode 100644 index 00000000000..9d9c005ad9e --- /dev/null +++ b/solutions/2811. Check if it is Possible to Split Array/2811.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool canSplitArray(vector& nums, int m) { + if (nums.size() < 3) + return true; + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] + nums[i - 1] >= m) + return true; + + return false; + } +}; diff --git a/solutions/2811. Check if it is Possible to Split Array/2811.java b/solutions/2811. Check if it is Possible to Split Array/2811.java new file mode 100644 index 00000000000..726e0fc0d14 --- /dev/null +++ b/solutions/2811. Check if it is Possible to Split Array/2811.java @@ -0,0 +1,12 @@ +class Solution { + public boolean canSplitArray(List nums, int m) { + if (nums.size() < 3) + return true; + + for (int i = 1; i < nums.size(); ++i) + if (nums.get(i) + nums.get(i - 1) >= m) + return true; + + return false; + } +} diff --git a/solutions/2811. Check if it is Possible to Split Array/2811.py b/solutions/2811. Check if it is Possible to Split Array/2811.py new file mode 100644 index 00000000000..5cdf48ad6fe --- /dev/null +++ b/solutions/2811. Check if it is Possible to Split Array/2811.py @@ -0,0 +1,3 @@ +class Solution: + def canSplitArray(self, nums: List[int], m: int) -> bool: + return len(nums) < 3 or any(a + b >= m for a, b in itertools.pairwise(nums)) diff --git a/solutions/2812. Find the Safest Path in a Grid/2812.cpp b/solutions/2812. Find the Safest Path in a Grid/2812.cpp new file mode 100644 index 00000000000..b64d8b35f71 --- /dev/null +++ b/solutions/2812. Find the Safest Path in a Grid/2812.cpp @@ -0,0 +1,86 @@ +class Solution { + public: + int maximumSafenessFactor(vector>& grid) { + const vector> distToThief = getDistToThief(grid); + int l = 0; + int r = grid.size() * 2; + + while (l < r) { + const int m = (l + r) / 2; + if (hasValidPath(distToThief, m)) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + bool hasValidPath(const vector>& distToThief, int safeness) { + if (distToThief[0][0] < safeness) + return false; + + const int n = distToThief.size(); + queue> q{{{0, 0}}}; + vector> seen(n, vector(n)); + seen[0][0] = true; + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + if (distToThief[i][j] < safeness) + continue; + if (i == n - 1 && j == n - 1) + return true; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + + return false; + } + + vector> getDistToThief(const vector>& grid) { + const int n = grid.size(); + vector> distToThief(n, vector(n)); + queue> q; + vector> seen(n, vector(n)); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + q.emplace(i, j); + seen[i][j] = true; + } + + for (int dist = 0; !q.empty(); ++dist) { + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + distToThief[i][j] = dist; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + } + + return distToThief; + } +}; diff --git a/solutions/2812. Find the Safest Path in a Grid/2812.java b/solutions/2812. Find the Safest Path in a Grid/2812.java new file mode 100644 index 00000000000..aab689f6977 --- /dev/null +++ b/solutions/2812. Find the Safest Path in a Grid/2812.java @@ -0,0 +1,84 @@ +class Solution { + public int maximumSafenessFactor(List> grid) { + int[][] distToThief = getDistToThief(grid); + int l = 0; + int r = grid.size() * 2; + + while (l < r) { + final int m = (l + r) / 2; + if (hasValidPath(distToThief, m)) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private boolean hasValidPath(int[][] distToThief, int safeness) { + if (distToThief[0][0] < safeness) + return false; + + final int n = distToThief.length; + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(0, 0))); + boolean[][] seen = new boolean[n][n]; + seen[0][0] = true; + + while (!q.isEmpty()) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + if (distToThief[i][j] < safeness) + continue; + if (i == n - 1 && j == n - 1) + return true; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + q.offer(new Pair<>(x, y)); + seen[x][y] = true; + } + } + + return false; + } + + private int[][] getDistToThief(List> grid) { + final int n = grid.size(); + int[][] distToThief = new int[n][n]; + Queue> q = new ArrayDeque<>(); + boolean[][] seen = new boolean[n][n]; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (grid.get(i).get(j) == 1) { + q.offer(new Pair<>(i, j)); + seen[i][j] = true; + } + + for (int dist = 0; !q.isEmpty(); ++dist) { + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + distToThief[i][j] = dist; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + q.offer(new Pair<>(x, y)); + seen[x][y] = true; + } + } + } + + return distToThief; + } +} diff --git a/solutions/2812. Find the Safest Path in a Grid/2812.py b/solutions/2812. Find the Safest Path in a Grid/2812.py new file mode 100644 index 00000000000..aeffa3e5de3 --- /dev/null +++ b/solutions/2812. Find the Safest Path in a Grid/2812.py @@ -0,0 +1,63 @@ +class Solution: + def maximumSafenessFactor(self, grid: List[List[int]]) -> int: + self.dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + n = len(grid) + distToThief = self._getDistToThief(grid) + + def hasValidPath(safeness: int) -> bool: + if distToThief[0][0] < safeness: + return False + + q = collections.deque([(0, 0)]) + seen = {(0, 0)} + + while q: + i, j = q.popleft() + if distToThief[i][j] < safeness: + continue + if i == n - 1 and j == n - 1: + return True + for dx, dy in self.dirs: + x = i + dx + y = j + dy + if x < 0 or x == n or y < 0 or y == n: + continue + if (x, y) in seen: + continue + q.append((x, y)) + seen.add((x, y)) + + return False + + return bisect.bisect_left(range(n * 2), True, + key=lambda m: not hasValidPath(m)) - 1 + + def _getDistToThief(self, grid: List[List[int]]) -> List[List[int]]: + n = len(grid) + distToThief = [[0] * n for _ in range(n)] + q = collections.deque() + seen = set() + + for i in range(n): + for j in range(n): + if grid[i][j] == 1: + q.append((i, j)) + seen.add((i, j)) + + dist = 0 + while q: + for _ in range(len(q)): + i, j = q.popleft() + distToThief[i][j] = dist + for dx, dy in self.dirs: + x = i + dx + y = j + dy + if x < 0 or x == n or y < 0 or y == n: + continue + if (x, y) in seen: + continue + q.append((x, y)) + seen.add((x, y)) + dist += 1 + + return distToThief diff --git a/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.cpp b/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.cpp new file mode 100644 index 00000000000..e30687b117c --- /dev/null +++ b/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + long long findMaximumElegance(vector>& items, int k) { + long ans = 0; + long totalProfit = 0; + unordered_set seenCategories; + stack decreasingDuplicateProfits; + + ranges::sort(items, greater<>()); + + for (int i = 0; i < k; i++) { + const int profit = items[i][0]; + const int category = items[i][1]; + totalProfit += profit; + if (seenCategories.contains(category)) + decreasingDuplicateProfits.push(profit); + else + seenCategories.insert(category); + } + + ans = totalProfit + + static_cast(seenCategories.size()) * seenCategories.size(); + + for (int i = k; i < items.size(); ++i) { + const int profit = items[i][0]; + const int category = items[i][1]; + if (!seenCategories.contains(category) && + !decreasingDuplicateProfits.empty()) { + // If this is a new category we haven't seen before, it's worth + // considering taking it and replacing the one with the least profit + // since it will increase the distinct_categories and potentially result + // in a larger total_profit + distinct_categories^2. + totalProfit -= decreasingDuplicateProfits.top(), + decreasingDuplicateProfits.pop(); + totalProfit += profit; + seenCategories.insert(category); + ans = max(ans, + static_cast(totalProfit + + static_cast(seenCategories.size()) * + seenCategories.size())); + } + } + + return ans; + } +}; diff --git a/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.java b/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.java new file mode 100644 index 00000000000..5af3762786b --- /dev/null +++ b/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.java @@ -0,0 +1,39 @@ +class Solution { + public long findMaximumElegance(int[][] items, int k) { + long ans = 0; + long totalProfit = 0; + Set seenCategories = new HashSet<>(); + Deque decreasingDuplicateProfits = new ArrayDeque<>(); + + Arrays.sort(items, (a, b) -> b[0] - a[0]); + + for (int i = 0; i < k; ++i) { + final int profit = items[i][0]; + final int category = items[i][1]; + totalProfit += profit; + if (seenCategories.contains(category)) + decreasingDuplicateProfits.push(profit); + else + seenCategories.add(category); + } + + ans = totalProfit + 1L * seenCategories.size() * seenCategories.size(); + + for (int i = k; i < items.length; ++i) { + final int profit = items[i][0]; + final int category = items[i][1]; + if (!seenCategories.contains(category) && !decreasingDuplicateProfits.isEmpty()) { + // If this is a new category we haven't seen before, it's worth + // considering taking it and replacing the one with the least profit + // since it will increase the distinct_categories and potentially result + // in a larger total_profit + distinct_categories^2. + totalProfit -= decreasingDuplicateProfits.pop(); + totalProfit += profit; + seenCategories.add(category); + ans = Math.max(ans, totalProfit + 1L * seenCategories.size() * seenCategories.size()); + } + } + + return ans; + } +} diff --git a/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.py b/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.py new file mode 100644 index 00000000000..fba87128680 --- /dev/null +++ b/solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.py @@ -0,0 +1,32 @@ +class Solution: + def findMaximumElegance(self, items: List[List[int]], k: int) -> int: + ans = 0 + totalProfit = 0 + seenCategories = set() + decreasingDuplicateProfits = [] + + items.sort(reverse=True) + + for i in range(k): + profit, category = items[i] + totalProfit += profit + if category in seenCategories: + decreasingDuplicateProfits.append(profit) + else: + seenCategories.add(category) + + ans = totalProfit + len(seenCategories)**2 + + for i in range(k, len(items)): + profit, category = items[i] + if category not in seenCategories and decreasingDuplicateProfits: + # If this is a new category we haven't seen before, it's worth + # considering taking it and replacing the one with the least profit + # since it will increase the distinct_categories and potentially result + # in a larger total_profit + distinct_categories^2. + totalProfit -= decreasingDuplicateProfits.pop() + totalProfit += profit + seenCategories.add(category) + ans = max(ans, totalProfit + len(seenCategories)**2) + + return ans diff --git a/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.cpp b/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.cpp new file mode 100644 index 00000000000..3b2ce9c2788 --- /dev/null +++ b/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.cpp @@ -0,0 +1,74 @@ +class Solution { + public: + int minimumSeconds(vector>& land) { + const int m = land.size(); + const int n = land[0].size(); + const vector> floodDist = getFloodDist(land); + queue> q; + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (land[i][j] == "S") { + q.emplace(i, j); + seen[i][j] = true; + } + + for (int step = 1; !q.empty(); ++step) + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (land[x][y] == "D") + return step; + if (floodDist[x][y] <= step || land[x][y] == "X" || seen[x][y]) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + + return -1; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + vector> getFloodDist(const vector>& land) { + const int m = land.size(); + const int n = land[0].size(); + vector> dist(m, vector(n, INT_MAX)); + queue> q; + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (land[i][j] == "*") { + q.emplace(i, j); + seen[i][j] = true; + } + + for (int d = 0; !q.empty(); ++d) + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + dist[i][j] = d; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (land[x][y] == "X" || land[x][y] == "D" || seen[x][y]) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + + return dist; + } +}; diff --git a/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.java b/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.java new file mode 100644 index 00000000000..a7ee38ea815 --- /dev/null +++ b/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.java @@ -0,0 +1,74 @@ +class Solution { + public int minimumSeconds(List> land) { + final int m = land.size(); + final int n = land.get(0).size(); + final int[][] floodDist = getFloodDist(land); + Queue> q = new LinkedList<>(); + boolean[][] seen = new boolean[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (land.get(i).get(j).equals("S")) { + q.offer(new Pair<>(i, j)); + seen[i][j] = true; + } + + for (int step = 1; !q.isEmpty(); ++step) + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (land.get(x).get(y).equals("D")) + return step; + if (floodDist[x][y] <= step || land.get(x).get(y).equals("X") || seen[x][y]) + continue; + q.offer(new Pair<>(x, y)); + seen[x][y] = true; + } + } + + return -1; + } + + private final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private int[][] getFloodDist(List> land) { + final int m = land.size(); + final int n = land.get(0).size(); + int[][] dist = new int[m][n]; + Queue> q = new LinkedList<>(); + boolean[][] seen = new boolean[m][n]; + + Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (land.get(i).get(j).equals("*")) { + q.offer(new Pair<>(i, j)); + seen[i][j] = true; + } + + for (int d = 0; !q.isEmpty(); ++d) + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().getKey(); + final int j = q.poll().getValue(); + dist[i][j] = d; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (land.get(x).get(y).equals("X") || land.get(x).get(y).equals("D") || seen[x][y]) + continue; + q.offer(new Pair<>(x, y)); + seen[x][y] = true; + } + } + + return dist; + } +} diff --git a/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.py b/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.py new file mode 100644 index 00000000000..ccd91f612b2 --- /dev/null +++ b/solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.py @@ -0,0 +1,66 @@ +class Solution: + def minimumSeconds(self, land: List[List[str]]) -> int: + self.dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(land) + n = len(land[0]) + floodDist = self._getFloodDist(land) + startPos = self._getStartPos(land, 'S') + + q = collections.deque([startPos]) + seen = {startPos} + + step = 1 + while q: + for _ in range(len(q)): + i, j = q.popleft() + for dx, dy in self.dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if land[x][y] == 'D': + return step + if floodDist[x][y] <= step or land[x][y] == 'X' or (x, y) in seen: + continue + q.append((x, y)) + seen.add((x, y)) + step += 1 + + return -1 + + def _getFloodDist(self, land: List[List[str]]) -> List[List[int]]: + m = len(land) + n = len(land[0]) + dist = [[math.inf] * n for _ in range(m)] + q = collections.deque() + seen = set() + + for i, row in enumerate(land): + for j, cell in enumerate(row): + if cell == '*': + q.append((i, j)) + seen.add((i, j)) + + d = 0 + while q: + for _ in range(len(q)): + i, j = q.popleft() + dist[i][j] = d + for dx, dy in self.dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if land[x][y] in 'XD' or (x, y) in seen: + continue + q.append((x, y)) + seen.add((x, y)) + d += 1 + + return dist + + def _getStartPos(self, land: List[List[str]], c: str) -> Tuple[int, int]: + for i, row in enumerate(land): + for j, cell in enumerate(row): + if cell == c: + return i, j diff --git a/solutions/2815. Max Pair Sum in an Array/2815.cpp b/solutions/2815. Max Pair Sum in an Array/2815.cpp new file mode 100644 index 00000000000..8650c33fe2d --- /dev/null +++ b/solutions/2815. Max Pair Sum in an Array/2815.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxSum(vector& nums) { + int ans = 0; + // maxNum[i] := the maximum num we met so far with the maximum digit i + vector maxNum(10); + + for (const int num : nums) { + const int d = getMaxDigit(num); + if (maxNum[d] > 0) + ans = max(ans, num + maxNum[d]); + maxNum[d] = max(maxNum[d], num); + } + + return ans == 0 ? -1 : ans; + } + + private: + int getMaxDigit(int num) { + int maxDigit = 0; + while (num > 0) { + maxDigit = max(maxDigit, num % 10); + num /= 10; + } + return maxDigit; + } +}; diff --git a/solutions/2815. Max Pair Sum in an Array/2815.java b/solutions/2815. Max Pair Sum in an Array/2815.java new file mode 100644 index 00000000000..e3d0c14495b --- /dev/null +++ b/solutions/2815. Max Pair Sum in an Array/2815.java @@ -0,0 +1,25 @@ +class Solution { + public int maxSum(int[] nums) { + int ans = 0; + // maxNum[i] := the maximum num we met so far with the maximum digit i + int[] maxNum = new int[10]; + + for (final int num : nums) { + final int d = getMaxDigit(num); + if (maxNum[d] > 0) + ans = Math.max(ans, num + maxNum[d]); + maxNum[d] = Math.max(maxNum[d], num); + } + + return ans == 0 ? -1 : ans; + } + + private int getMaxDigit(int num) { + int maxDigit = 0; + while (num > 0) { + maxDigit = Math.max(maxDigit, num % 10); + num /= 10; + } + return maxDigit; + } +} diff --git a/solutions/2815. Max Pair Sum in an Array/2815.py b/solutions/2815. Max Pair Sum in an Array/2815.py new file mode 100644 index 00000000000..9a08588886f --- /dev/null +++ b/solutions/2815. Max Pair Sum in an Array/2815.py @@ -0,0 +1,20 @@ +class Solution: + def maxSum(self, nums: List[int]) -> int: + ans = 0 + # maxNum[i] := the maximum num we met so far with the maximum digit i + maxNum = [0] * 10 + + def getMaxDigit(num: int) -> int: + maxDigit = 0 + while num > 0: + maxDigit = max(maxDigit, num % 10) + num //= 10 + return maxDigit + + for num in nums: + d = getMaxDigit(num) + if maxNum[d] > 0: + ans = max(ans, num + maxNum[d]) + maxNum[d] = max(maxNum[d], num) + + return -1 if ans == 0 else ans diff --git a/solutions/2816. Double a Number Represented as a Linked List/2816-2.cpp b/solutions/2816. Double a Number Represented as a Linked List/2816-2.cpp new file mode 100644 index 00000000000..b5f68bf645e --- /dev/null +++ b/solutions/2816. Double a Number Represented as a Linked List/2816-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + ListNode* doubleIt(ListNode* head) { + if (head->val >= 5) + head = new ListNode(0, head); + + for (ListNode* curr = head; curr != nullptr; curr = curr->next) { + curr->val *= 2; + curr->val %= 10; + if (curr->next && curr->next->val >= 5) + ++curr->val; + } + + return head; + } +}; diff --git a/solutions/2816. Double a Number Represented as a Linked List/2816-2.java b/solutions/2816. Double a Number Represented as a Linked List/2816-2.java new file mode 100644 index 00000000000..915550c33cf --- /dev/null +++ b/solutions/2816. Double a Number Represented as a Linked List/2816-2.java @@ -0,0 +1,15 @@ +class Solution { + public ListNode doubleIt(ListNode head) { + if (head.val >= 5) + head = new ListNode(0, head); + + for (ListNode curr = head; curr != null; curr = curr.next) { + curr.val *= 2; + curr.val %= 10; + if (curr.next != null && curr.next.val >= 5) + ++curr.val; + } + + return head; + } +} diff --git a/solutions/2816. Double a Number Represented as a Linked List/2816-2.py b/solutions/2816. Double a Number Represented as a Linked List/2816-2.py new file mode 100644 index 00000000000..a5f0c548224 --- /dev/null +++ b/solutions/2816. Double a Number Represented as a Linked List/2816-2.py @@ -0,0 +1,15 @@ +class Solution: + def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head.val >= 5: + head = ListNode(0, head) + + curr = head + + while curr: + curr.val *= 2 + curr.val %= 10 + if curr.next and curr.next.val >= 5: + curr.val += 1 + curr = curr.next + + return head diff --git a/solutions/2816. Double a Number Represented as a Linked List/2816.cpp b/solutions/2816. Double a Number Represented as a Linked List/2816.cpp new file mode 100644 index 00000000000..e2adc1cf87f --- /dev/null +++ b/solutions/2816. Double a Number Represented as a Linked List/2816.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + ListNode* doubleIt(ListNode* head) { + if (getCarry(head) == 1) + return new ListNode(1, head); + return head; + } + + private: + int getCarry(ListNode* node) { + int val = node->val * 2; + if (node->next != nullptr) + val += getCarry(node->next); + + node->val = val % 10; + return val / 10; + } +}; diff --git a/solutions/2816. Double a Number Represented as a Linked List/2816.java b/solutions/2816. Double a Number Represented as a Linked List/2816.java new file mode 100644 index 00000000000..65c542e3e00 --- /dev/null +++ b/solutions/2816. Double a Number Represented as a Linked List/2816.java @@ -0,0 +1,15 @@ +class Solution { + public ListNode doubleIt(ListNode head) { + if (getCarry(head) == 1) + return new ListNode(1, head); + return head; + } + + private int getCarry(ListNode node) { + int val = node.val * 2; + if (node.next != null) + val += getCarry(node.next); + node.val = val % 10; + return val / 10; + } +} diff --git a/solutions/2816. Double a Number Represented as a Linked List/2816.py b/solutions/2816. Double a Number Represented as a Linked List/2816.py new file mode 100644 index 00000000000..08e97eb9b27 --- /dev/null +++ b/solutions/2816. Double a Number Represented as a Linked List/2816.py @@ -0,0 +1,12 @@ +class Solution: + def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: + def getCarry(node: Optional[ListNode]) -> Optional[ListNode]: + val = node.val * 2 + if node.next: + val += getCarry(node.next) + node.val = val % 10 + return val // 10 + + if getCarry(head) == 1: + return ListNode(1, head) + return head diff --git a/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.cpp b/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.cpp new file mode 100644 index 00000000000..66a2d45a4f2 --- /dev/null +++ b/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minAbsoluteDifference(vector& nums, int x) { + int ans = INT_MAX; + set seen; + + for (int i = x; i < nums.size(); ++i) { + seen.insert(nums[i - x]); + // `upper_bound` works as well. + const auto it = seen.lower_bound(nums[i]); + if (it != seen.cend()) + ans = min(ans, *it - nums[i]); + if (it != seen.cbegin()) + ans = min(ans, nums[i] - *prev(it)); + } + + return ans; + } +}; diff --git a/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.java b/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.java new file mode 100644 index 00000000000..0cab39bc45a --- /dev/null +++ b/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.java @@ -0,0 +1,18 @@ +class Solution { + public int minAbsoluteDifference(List nums, int x) { + int ans = Integer.MAX_VALUE; + TreeSet seen = new TreeSet<>(); + + for (int i = x; i < nums.size(); ++i) { + seen.add(nums.get(i - x)); + Integer hi = seen.ceiling(nums.get(i)); + if (hi != null) + ans = Math.min(ans, hi - nums.get(i)); + Integer lo = seen.floor(nums.get(i)); + if (lo != null) + ans = Math.min(ans, nums.get(i) - lo); + } + + return ans; + } +} diff --git a/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.py b/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.py new file mode 100644 index 00000000000..bcccc761070 --- /dev/null +++ b/solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.py @@ -0,0 +1,17 @@ +from sortedcontainers import SortedSet + + +class Solution: + def minAbsoluteDifference(self, nums: List[int], x: int) -> int: + ans = math.inf + seen = SortedSet() + + for i in range(x, len(nums)): + seen.add(nums[i - x]) + it = seen.bisect_left(nums[i]) + if it != len(seen): + ans = min(ans, seen[it] - nums[i]) + if it != 0: + ans = min(ans, nums[i] - seen[it - 1]) + + return ans diff --git a/solutions/2818. Apply Operations to Maximize Score/2818.cpp b/solutions/2818. Apply Operations to Maximize Score/2818.cpp new file mode 100644 index 00000000000..cb794ebe404 --- /dev/null +++ b/solutions/2818. Apply Operations to Maximize Score/2818.cpp @@ -0,0 +1,97 @@ +class Solution { + public: + int maximumScore(vector& nums, int k) { + const int n = nums.size(); + const int maxNum = ranges::max(nums); + const vector minPrimeFactors = sieveEratosthenes(maxNum + 1); + const vector primeScores = getPrimeScores(nums, minPrimeFactors); + int ans = 1; + // left[i] := the next index on the left (if any) s.t. + // primeScores[left[i]] >= primeScores[i] + vector left(n, -1); + // right[i] := the next index on the right (if any) s.t. + // primeScores[right[i]] > primeScores[i] + vector right(n, n); + stack stack; + + // Find the next indices on the left where `primeScores` are greater or + // equal. + for (int i = n - 1; i >= 0; --i) { + while (!stack.empty() && primeScores[stack.top()] <= primeScores[i]) + left[stack.top()] = i, stack.pop(); + stack.push(i); + } + + stack = std::stack(); + + // Find the next indices on the right where `primeScores` are greater. + for (int i = 0; i < n; ++i) { + while (!stack.empty() && primeScores[stack.top()] < primeScores[i]) + right[stack.top()] = i, stack.pop(); + stack.push(i); + } + + vector> numAndIndexes; + + for (int i = 0; i < n; ++i) + numAndIndexes.emplace_back(nums[i], i); + + ranges::sort(numAndIndexes, + [&](const pair& a, const pair& b) { + return a.first == b.first ? a.second < b.second : a.first > b.first; + }); + + for (const auto& [num, i] : numAndIndexes) { + // nums[i] is the maximum value in the range [left[i] + 1, right[i] - 1] + // So, there are (i - left[i]) * (right[i] - 1) ranges where nums[i] will + // be chosen. + const int rangeCount = (i - left[i]) * (right[i] - i); + const int actualCount = min(rangeCount, k); + k -= actualCount; + ans = (static_cast(ans) * modPow(num, actualCount)) % kMod; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } + + // Gets the minimum prime factor of i, where 1 < i <= n. + vector sieveEratosthenes(int n) { + vector minPrimeFactors(n + 1); + iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + vector getPrimeScores(const vector& nums, + const vector& minPrimeFactors) { + vector primeScores; + for (const int num : nums) + primeScores.push_back(getPrimeScore(num, minPrimeFactors)); + return primeScores; + } + + int getPrimeScore(int num, const vector& minPrimeFactors) { + unordered_set primeFactors; + while (num > 1) { + const int divisor = minPrimeFactors[num]; + primeFactors.insert(divisor); + while (num % divisor == 0) + num /= divisor; + } + return primeFactors.size(); + } +}; diff --git a/solutions/2818. Apply Operations to Maximize Score/2818.java b/solutions/2818. Apply Operations to Maximize Score/2818.java new file mode 100644 index 00000000000..48e25280803 --- /dev/null +++ b/solutions/2818. Apply Operations to Maximize Score/2818.java @@ -0,0 +1,98 @@ +class Solution { + public int maximumScore(List nums, int k) { + final int n = nums.size(); + final int maxNum = Collections.max(nums); + final int[] minPrimeFactors = sieveEratosthenes(maxNum + 1); + final int[] primeScores = getPrimeScores(nums, minPrimeFactors); + int ans = 1; + // left[i] := the next index on the left (if any) + // s.t. primeScores[left[i]] >= primeScores[i] + int[] left = new int[n]; + Arrays.fill(left, -1); + // right[i] := the next index on the right (if any) + // s.t. primeScores[right[i]] > primeScores[i] + int[] right = new int[n]; + Arrays.fill(right, n); + Deque stack = new ArrayDeque<>(); + + // Find the next indices on the left where `primeScores` are greater or equal. + for (int i = n - 1; i >= 0; --i) { + while (!stack.isEmpty() && primeScores[stack.peek()] <= primeScores[i]) + left[stack.pop()] = i; + stack.push(i); + } + + stack.clear(); + + // Find the next indices on the right where `primeScores` are greater. + for (int i = 0; i < n; ++i) { + while (!stack.isEmpty() && primeScores[stack.peek()] < primeScores[i]) + right[stack.pop()] = i; + stack.push(i); + } + + Pair[] numAndIndexes = new Pair[n]; + + for (int i = 0; i < n; ++i) + numAndIndexes[i] = new Pair<>(nums.get(i), i); + + Arrays.sort(numAndIndexes, + (a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue() - b.getValue() + : b.getKey() - a.getKey()); + + for (Pair numAndIndex : numAndIndexes) { + final int num = numAndIndex.getKey(); + final int i = numAndIndex.getValue(); + // nums[i] is the maximum value in the range [left[i] + 1, right[i] - 1] + // So, there are (i - left[i]) * (right[i] - 1) ranges where nums[i] will + // be chosen. + final int rangeCount = (i - left[i]) * (right[i] - i); + final int actualCount = Math.min(rangeCount, k); + k -= actualCount; + ans = (int) ((1L * ans * modPow(num, actualCount)) % kMod); + } + + return ans; + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } + + // Gets the minimum prime factor of i, where 1 < i <= n. + private int[] sieveEratosthenes(int n) { + int[] minPrimeFactors = new int[n + 1]; + for (int i = 2; i <= n; ++i) + minPrimeFactors[i] = i; + for (int i = 2; i * i < n; ++i) + if (minPrimeFactors[i] == i) // `i` is prime. + for (int j = i * i; j < n; j += i) + minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); + return minPrimeFactors; + } + + private int[] getPrimeScores(List nums, int[] minPrimeFactors) { + int[] primeScores = new int[nums.size()]; + for (int i = 0; i < nums.size(); ++i) + primeScores[i] = getPrimeScore(nums.get(i), minPrimeFactors); + return primeScores; + } + + private int getPrimeScore(int num, int[] minPrimeFactors) { + Set primeFactors = new HashSet<>(); + while (num > 1) { + final int divisor = minPrimeFactors[num]; + primeFactors.add(divisor); + while (num % divisor == 0) + num /= divisor; + } + return primeFactors.size(); + } +} diff --git a/solutions/2818. Apply Operations to Maximize Score/2818.py b/solutions/2818. Apply Operations to Maximize Score/2818.py new file mode 100644 index 00000000000..6d2a5dcb425 --- /dev/null +++ b/solutions/2818. Apply Operations to Maximize Score/2818.py @@ -0,0 +1,67 @@ +class Solution: + def maximumScore(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + n = len(nums) + ans = 1 + minPrimeFactors = self._sieveEratosthenes(max(nums) + 1) + primeScores = [self._getPrimeScore(num, minPrimeFactors) for num in nums] + # left[i] := the next index on the left (if any) + # s.t. primeScores[left[i]] >= primeScores[i] + left = [-1] * n + # right[i] := the next index on the right (if any) + # s.t. primeScores[right[i]] > primeScores[i] + right = [n] * n + stack = [] + + # Find the next indices on the left where `primeScores` are greater or equal. + for i in reversed(range(n)): + while stack and primeScores[stack[-1]] <= primeScores[i]: + left[stack.pop()] = i + stack.append(i) + + stack = [] + + # Find the next indices on the right where `primeScores` are greater. + for i in range(n): + while stack and primeScores[stack[-1]] < primeScores[i]: + right[stack.pop()] = i + stack.append(i) + + numAndIndexes = [(num, i) for i, num in enumerate(nums)] + + def modPow(x: int, n: int) -> int: + if n == 0: + return 1 + if n % 2 == 1: + return x * modPow(x, n - 1) % kMod + return modPow(x * x % kMod, n // 2) + + for num, i in sorted(numAndIndexes, key=lambda x: (-x[0], x[1])): + # nums[i] is the maximum value in the range [left[i] + 1, right[i] - 1] + # So, there are (i - left[i]) * (right[i] - 1) ranges where nums[i] will + # be chosen. + rangeCount = (i - left[i]) * (right[i] - i) + actualCount = min(rangeCount, k) + k -= actualCount + ans *= modPow(num, actualCount) + ans %= kMod + + return ans + + def _sieveEratosthenes(self, n: int) -> List[int]: + """Gets the minimum prime factor of i, where 2 <= i <= n.""" + minPrimeFactors = [i for i in range(n + 1)] + for i in range(2, int(n**0.5) + 1): + if minPrimeFactors[i] == i: # `i` is prime. + for j in range(i * i, n, i): + minPrimeFactors[j] = min(minPrimeFactors[j], i) + return minPrimeFactors + + def _getPrimeScore(self, num: int, minPrimeFactors: List[int]) -> int: + primeFactors = set() + while num > 1: + divisor = minPrimeFactors[num] + primeFactors.add(divisor) + while num % divisor == 0: + num //= divisor + return len(primeFactors) diff --git a/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.cpp b/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.cpp new file mode 100644 index 00000000000..ebf0e3b894c --- /dev/null +++ b/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.cpp @@ -0,0 +1,75 @@ +class Solution { + public: + vector minimumRelativeLosses(vector& prices, + vector>& queries) { + const int n = prices.size(); + vector ans; + vector prefix{0}; + + ranges::sort(prices); + + for (const int price : prices) + prefix.push_back(prefix.back() + price); + + for (const vector& query : queries) { + const int k = query[0]; + const int m = query[1]; + const int countFront = getCountFront(k, m, prices, prefix); + const int countBack = m - countFront; + ans.push_back(getRelativeLoss(countFront, countBack, k, prefix)); + } + + return ans; + } + + private: + // Returns `countFront` for query (k, m) s.t. picking the first `countFront` + // and the last `m - countFront` chocolates is optimal. + // + // Define loss[i] := the relative loss of picking `prices[i]`. + // 1. For prices[i] <= k, Bob pays prices[i] while Alice pays 0. + // Thus, loss[i] = prices[i] - 0 = prices[i]. + // 2. For prices[i] > k, Bob pays k while Alice pays prices[i] - k. + // Thus, loss[i] = k - (prices[i] - k) = 2 * k - prices[i]. + // By observation, we deduce that it is always better to pick from the front + // or the back since loss[i] is increasing for 1. and is decreasing for 2. + // + // Assume that picking `left` chocolates from the left and `right = m - left` + // chocolates from the right is optimal. Therefore, we are selecting + // chocolates from `prices[0..left - 1]` and `prices[n - right..n - 1]`. + // + // To determine the optimal `left` in each iteration, we simply compare + // `loss[left]` with `loss[n - right]`; if `loss[left] < loss[n - right]`, + // it's worth increasing `left`. + int getCountFront(int k, int m, const vector& prices, + const vector& prefix) { + const int n = prices.size(); + const int countNoGreaterThanK = + ranges::upper_bound(prices, k) - prices.begin(); + int l = 0; + int r = min(countNoGreaterThanK, m); + + while (l < r) { + const int mid = (l + r) / 2; + const int right = m - mid; + // Picking prices[mid] is better than picking prices[n - right]. + if (prices[mid] < 2L * k - prices[n - right]) + l = mid + 1; + else + r = mid; + } + + return l; + } + + // Returns the relative loss of picking `countFront` and `countBack` + // chocolates. + long getRelativeLoss(int countFront, int countBack, int k, + const vector& prefix) { + const long lossFront = prefix[countFront]; + const long lossBack = + 2L * k * countBack - + (prefix.back() - prefix[prefix.size() - 1 - countBack]); + return lossFront + lossBack; + } +}; diff --git a/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.java b/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.java new file mode 100644 index 00000000000..63475d33d51 --- /dev/null +++ b/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.java @@ -0,0 +1,73 @@ +class Solution { + long[] minimumRelativeLosses(int[] prices, int[][] queries) { + final int n = prices.length; + long[] ans = new long[queries.length]; + long[] prefix = new long[prices.length + 1]; + + Arrays.sort(prices); + + for (int i = 0; i < prices.length; ++i) + prefix[i + 1] = prefix[i] + prices[i]; + + for (int i = 0; i < queries.length; ++i) { + final int k = queries[i][0]; + final int m = queries[i][1]; + final int countFront = getCountFront(k, m, prices, prefix); + final int countBack = m - countFront; + ans[i] = getRelativeLoss(countFront, countBack, k, prefix); + } + + return ans; + } + + // Returns `countFront` for query (k, m) s.t. picking the first `countFront` + // and the last `m - countFront` chocolates is optimal. + // + // Define loss[i] := the relative loss of picking `prices[i]`. + // 1. For prices[i] <= k, Bob pays prices[i] while Alice pays 0. + // Thus, loss[i] = prices[i] - 0 = prices[i]. + // 2. For prices[i] > k, Bob pays k while Alice pays prices[i] - k. + // Thus, loss[i] = k - (prices[i] - k) = 2 * k - prices[i]. + // By observation, we deduce that it is always better to pick from the front + // or the back since loss[i] is increasing for 1. and is decreasing for 2. + // + // Assume that picking `left` chocolates from the left and `right = m - left` + // chocolates from the right is optimal. Therefore, we are selecting + // chocolates from `prices[0..left - 1]` and `prices[n - right..n - 1]`. + // + // To determine the optimal `left` in each iteration, we simply compare + // `loss[left]` with `loss[n - right]`; if `loss[left] < loss[n - right]`, + // it's worth increasing `left`. + private int getCountFront(int k, int m, int[] prices, long[] prefix) { + final int n = prices.length; + final int countNoGreaterThanK = firstGreater(prices, k); + int l = 0; + int r = Math.min(countNoGreaterThanK, m); + + while (l < r) { + final int mid = (l + r) / 2; + final int right = m - mid; + // Picking prices[mid] is better than picking prices[n - right]. + if (prices[mid] < 2L * k - prices[n - right]) + l = mid + 1; + else + r = mid; + } + + return l; + } + + private int firstGreater(int[] A, int target) { + final int i = Arrays.binarySearch(A, target + 1); + return i < 0 ? -i - 1 : i; + } + + // Returns the relative loss of picking `countFront` and `countBack` + // chocolates. + private long getRelativeLoss(int countFront, int countBack, int k, long[] prefix) { + final int n = prefix.length - 1; + final long lossFront = prefix[countFront]; + final long lossBack = 2L * k * countBack - (prefix[n] - prefix[n - countBack]); + return lossFront + lossBack; + } +} diff --git a/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.py b/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.py new file mode 100644 index 00000000000..762fa8b3572 --- /dev/null +++ b/solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.py @@ -0,0 +1,59 @@ +class Solution: + def minimumRelativeLosses(self, prices: List[int], queries: List[List[int]]) -> List[int]: + ans = [] + + prices.sort() + + prefix = [0] + list(itertools.accumulate(prices)) + + for k, m in queries: + countFront = self._getCountFront(k, m, prices, prefix) + countBack = m - countFront + ans.append(self._getRelativeLoss(countFront, countBack, k, prefix)) + + return ans + + def _getCountFront(self, k: int, m: int, prices: List[int], prefix: List[int]) -> int: + """Returns `countFront` for query (k, m). + + + Returns `countFront` for query (k, m) s.t. picking the first `countFront` + and the last `m - countFront` chocolates is optimal. + + Define loss[i] := the relative loss of picking `prices[i]`. + 1. For prices[i] <= k, Bob pays prices[i] while Alice pays 0. + Thus, loss[i] = prices[i] - 0 = prices[i]. + 2. For prices[i] > k, Bob pays k while Alice pays prices[i] - k. + Thus, loss[i] = k - (prices[i] - k) = 2 * k - prices[i]. + By observation, we deduce that it is always better to pick from the front + or the back since loss[i] is increasing for 1. and is decreasing for 2. + + Assume that picking `left` chocolates from the left and `right = m - left` + chocolates from the right is optimal. Therefore, we are selecting + chocolates from `prices[0..left - 1]` and `prices[n - right..n - 1]`. + + To determine the optimal `left` in each iteration, we simply compare + `loss[left]` with `loss[n - right]` if `loss[left] < loss[n - right]`, + it's worth increasing `left`. + """ + n = len(prices) + countNoGreaterThanK = bisect.bisect_right(prices, k) + l = 0 + r = min(countNoGreaterThanK, m) + + while l < r: + mid = (l + r) // 2 + right = m - mid + # Picking prices[mid] is better than picking prices[n - right]. + if prices[mid] < 2 * k - prices[n - right]: + l = mid + 1 + else: + r = mid + + return l + + def _getRelativeLoss(self, countFront: int, countBack: int, k: int, prefix: List[int]) -> int: + """Returns the relative loss of picking `countFront` and `countBack` chocolates.""" + lossFront = prefix[countFront] + lossBack = 2 * k * countBack - (prefix[-1] - prefix[-countBack - 1]) + return lossFront + lossBack diff --git a/solutions/282. Expression Add Operators/282.cpp b/solutions/282. Expression Add Operators/282.cpp new file mode 100644 index 00000000000..c75120025f4 --- /dev/null +++ b/solutions/282. Expression Add Operators/282.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + vector addOperators(string num, int target) { + vector ans; + dfs(num, target, 0, 0, 0, {}, ans); + return ans; + } + + private: + string join(const vector& path) { + string joined; + for (const string& s : path) + joined += s; + return joined; + } + + void dfs(const string& num, int target, int start, long prev, long eval, + vector&& path, vector& ans) { + if (start == num.length()) { + if (eval == target) + ans.push_back(join(path)); + return; + } + + for (int i = start; i < num.length(); ++i) { + if (i > start && num[start] == '0') + return; + const string& s = num.substr(start, i - start + 1); + const long curr = stol(s); + if (start == 0) { + path.push_back(s); + dfs(num, target, i + 1, curr, curr, move(path), ans); + path.pop_back(); + } else { + for (const string& op : {"+", "-", "*"}) { + path.push_back(op + s); + if (op == "+") + dfs(num, target, i + 1, curr, eval + curr, move(path), ans); + else if (op == "-") + dfs(num, target, i + 1, -curr, eval - curr, move(path), ans); + else + dfs(num, target, i + 1, prev * curr, eval - prev + prev * curr, + move(path), ans); + path.pop_back(); + } + } + } + } +}; diff --git a/solutions/282. Expression Add Operators/282.java b/solutions/282. Expression Add Operators/282.java new file mode 100644 index 00000000000..d4902f303dc --- /dev/null +++ b/solutions/282. Expression Add Operators/282.java @@ -0,0 +1,35 @@ +class Solution { + public List addOperators(String num, int target) { + List ans = new ArrayList<>(); + dfs(num, target, 0, 0, 0, new StringBuilder(), ans); + return ans; + } + + private void dfs(String num, int target, int s, long prev, long eval, StringBuilder sb, + List ans) { + if (s == num.length()) { + if (eval == target) + ans.add(sb.toString()); + return; + } + + for (int i = s; i < num.length(); ++i) { + if (i > s && num.charAt(s) == '0') + return; + final long curr = Long.parseLong(num.substring(s, i + 1)); + final int length = sb.length(); + if (s == 0) { // the first number + dfs(num, target, i + 1, curr, curr, sb.append(curr), ans); + sb.setLength(length); + } else { + dfs(num, target, i + 1, curr, eval + curr, sb.append("+").append(curr), ans); + sb.setLength(length); + dfs(num, target, i + 1, -curr, eval - curr, sb.append("-").append(curr), ans); + sb.setLength(length); + dfs(num, target, i + 1, prev * curr, eval - prev + prev * curr, sb.append("*").append(curr), + ans); + sb.setLength(length); + } + } + } +} diff --git a/solutions/282. Expression Add Operators/282.py b/solutions/282. Expression Add Operators/282.py new file mode 100644 index 00000000000..6ba5e1408a4 --- /dev/null +++ b/solutions/282. Expression Add Operators/282.py @@ -0,0 +1,32 @@ +class Solution: + def addOperators(self, num: str, target: int) -> List[str]: + ans = [] + + def dfs(start: int, prev: int, eval: int, path: List[str]) -> None: + if start == len(num): + if eval == target: + ans.append(''.join(path)) + return + + for i in range(start, len(num)): + if i > start and num[start] == '0': + return + s = num[start:i + 1] + curr = int(s) + if start == 0: + path.append(s) + dfs(i + 1, curr, curr, path) + path.pop() + else: + for op in ['+', '-', '*']: + path.append(op + s) + if op == '+': + dfs(i + 1, curr, eval + curr, path) + elif op == '-': + dfs(i + 1, -curr, eval - curr, path) + else: + dfs(i + 1, prev * curr, eval - prev + prev * curr, path) + path.pop() + + dfs(0, 0, 0, []) + return ans diff --git a/solutions/2820. Election Results/2820.sql b/solutions/2820. Election Results/2820.sql new file mode 100644 index 00000000000..34bde00d328 --- /dev/null +++ b/solutions/2820. Election Results/2820.sql @@ -0,0 +1,22 @@ +WITH + VoterToValue AS ( + SELECT + voter, + 1 / COUNT(*) AS value + FROM Votes + GROUP BY voter + ), + RankedCandidates AS ( + SELECT + candidate, + RANK() OVER(ORDER BY SUM(value) DESC) AS `rank` + FROM Votes + INNER JOIN VoterToValue + USING (voter) + WHERE candidate IS NOT NULL + GROUP BY 1 + ) +SELECT candidate +FROM RankedCandidates +WHERE `rank` = 1 +ORDER BY 1; diff --git a/solutions/2821. Delay the Resolution of Each Promise/2821.ts b/solutions/2821. Delay the Resolution of Each Promise/2821.ts new file mode 100644 index 00000000000..53e40eb802c --- /dev/null +++ b/solutions/2821. Delay the Resolution of Each Promise/2821.ts @@ -0,0 +1,15 @@ +type Fn = () => Promise; + +function delayAll(functions: Fn[], ms: number): Fn[] { + return functions.map((fn) => { + return async () => { + await new Promise((resolve) => setTimeout(resolve, ms)); + try { + const result = await fn(); + return Promise.resolve(result); + } catch (error) { + return Promise.reject(error); + } + }; + }); +} diff --git a/solutions/2822. Inversion of Object/2822.ts b/solutions/2822. Inversion of Object/2822.ts new file mode 100644 index 00000000000..a5119d5b58d --- /dev/null +++ b/solutions/2822. Inversion of Object/2822.ts @@ -0,0 +1,27 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Obj = Record | Array; + +function invertObject(obj: Obj): Record { + const ans: Record = {}; + + for (const [key, value] of Object.entries(obj)) { + const valueKey = value as string; + if (ans.hasOwnProperty(valueKey)) { + const curr = ans[valueKey]; + if (!Array.isArray(curr)) { + ans[valueKey] = [curr]; + } + (ans[valueKey] as JSONValue[]).push(key); + } else { + ans[valueKey] = key; + } + } + + return ans; +} diff --git a/solutions/2823. Deep Object Filter/2823.ts b/solutions/2823. Deep Object Filter/2823.ts new file mode 100644 index 00000000000..470c6784a78 --- /dev/null +++ b/solutions/2823. Deep Object Filter/2823.ts @@ -0,0 +1,28 @@ +type JSONValue = + | null + | boolean + | number + | string + | JSONValue[] + | { [key: string]: JSONValue }; +type Obj = Record | Array; + +function deepFilter(obj: Obj, fn: Function): Obj | undefined { + if (obj === null || typeof obj !== 'object') { + return fn(obj) ? obj : undefined; + } + if (Array.isArray(obj)) { + const ans = (obj as Obj[]) + .map((item) => deepFilter(item, fn)) + .filter((item) => item !== undefined); + return ans.length > 0 ? ans : undefined; + } + let ans = {}; + for (const [key, value] of Object.entries(obj)) { + const ans = deepFilter(value as Obj, fn); + if (ans !== undefined) { + ans[key] = ans; + } + } + return Object.keys(ans).length > 0 ? ans : undefined; +} diff --git a/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.cpp b/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.cpp new file mode 100644 index 00000000000..d54fda4b129 --- /dev/null +++ b/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int countPairs(vector& nums, int target) { + int ans = 0; + + for (int i = 0; i < nums.size(); ++i) + for (int j = i + 1; j < nums.size(); ++j) + if (nums[i] + nums[j] < target) + ++ans; + + return ans; + } +}; diff --git a/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.java b/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.java new file mode 100644 index 00000000000..3024ea4013f --- /dev/null +++ b/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.java @@ -0,0 +1,12 @@ +class Solution { + public int countPairs(List nums, int target) { + int ans = 0; + + for (int i = 0; i < nums.size(); ++i) + for (int j = i + 1; j < nums.size(); ++j) + if (nums.get(i) + nums.get(j) < target) + ++ans; + + return ans; + } +} diff --git a/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.py b/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.py new file mode 100644 index 00000000000..acf630b7b24 --- /dev/null +++ b/solutions/2824. Count Pairs Whose Sum is Less than Target/2824.py @@ -0,0 +1,5 @@ +class Solution: + def countPairs(self, nums: List[int], target: int) -> int: + return sum(nums[i] + nums[j] < target + for i in range(len(nums)) + for j in range(i + 1, len(nums))) diff --git a/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.cpp b/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.cpp new file mode 100644 index 00000000000..4321f4817c0 --- /dev/null +++ b/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool canMakeSubsequence(string str1, string str2) { + int i = 0; // str2's index + + for (const char c : str1) + if (c == str2[i] || ('a' + ((c - 'a' + 1) % 26)) == str2[i]) + if (++i == str2.length()) + return true; + + return false; + } +}; diff --git a/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.java b/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.java new file mode 100644 index 00000000000..9c3ef3c88b1 --- /dev/null +++ b/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.java @@ -0,0 +1,12 @@ +class Solution { + public boolean canMakeSubsequence(String str1, String str2) { + int i = 0; // str2's index + + for (final char c : str1.toCharArray()) + if (c == str2.charAt(i) || ('a' + ((c - 'a' + 1) % 26)) == str2.charAt(i)) + if (++i == str2.length()) + return true; + + return false; + } +} diff --git a/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.py b/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.py new file mode 100644 index 00000000000..d702fe94505 --- /dev/null +++ b/solutions/2825. Make String a Subsequence Using Cyclic Increments/2825.py @@ -0,0 +1,11 @@ +class Solution: + def canMakeSubsequence(self, str1: str, str2: str) -> bool: + i = 0 # str2's index + + for c in str1: + if c == str2[i] or chr(ord('a') + ((ord(c) - ord('a') + 1) % 26)) == str2[i]: + i += 1 + if i == len(str2): + return True + + return False diff --git a/solutions/2826. Sorting Three Groups/2826.cpp b/solutions/2826. Sorting Three Groups/2826.cpp new file mode 100644 index 00000000000..47fbd138bd2 --- /dev/null +++ b/solutions/2826. Sorting Three Groups/2826.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minimumOperations(vector& nums) { + // dp[i] := the longest non-decreasing subsequence so far with numbers in + // [1..i] + vector dp(4); + + for (const int num : nums) { + ++dp[num]; + dp[2] = max(dp[2], dp[1]); + dp[3] = max(dp[3], dp[2]); + } + + return nums.size() - dp[3]; + } +}; diff --git a/solutions/2826. Sorting Three Groups/2826.java b/solutions/2826. Sorting Three Groups/2826.java new file mode 100644 index 00000000000..e0b0df57836 --- /dev/null +++ b/solutions/2826. Sorting Three Groups/2826.java @@ -0,0 +1,14 @@ +class Solution { + public int minimumOperations(List nums) { + // dp[i] := the longest non-decreasing subsequence so far with numbers in [1..i] + int[] dp = new int[4]; + + for (final int num : nums) { + ++dp[num]; + dp[2] = Math.max(dp[2], dp[1]); + dp[3] = Math.max(dp[3], dp[2]); + } + + return nums.size() - dp[3]; + } +} diff --git a/solutions/2826. Sorting Three Groups/2826.py b/solutions/2826. Sorting Three Groups/2826.py new file mode 100644 index 00000000000..dc4d2e50086 --- /dev/null +++ b/solutions/2826. Sorting Three Groups/2826.py @@ -0,0 +1,11 @@ +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + # dp[i] := the longest non-decreasing subsequence so far with numbers in [1..i] + dp = [0] * 4 + + for num in nums: + dp[num] += 1 # Append num to the sequence so far. + dp[2] = max(dp[2], dp[1]) + dp[3] = max(dp[3], dp[2]) + + return len(nums) - dp[3] diff --git a/solutions/2827. Number of Beautiful Integers in the Range/2827.cpp b/solutions/2827. Number of Beautiful Integers in the Range/2827.cpp new file mode 100644 index 00000000000..2069e9877c6 --- /dev/null +++ b/solutions/2827. Number of Beautiful Integers in the Range/2827.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + int numberOfBeautifulIntegers(int low, int high, int k) { + const string lowString = to_string(low); + const string highString = to_string(high); + const string lowWithLeadingZeros = + string(highString.length() - lowString.length(), '0') + lowString; + vector>>>>> mem( + highString.length(), + vector>>>>( + 10, vector>>>( + 10, vector>>( + k, vector>(2, vector(2, -1)))))); + return count(lowWithLeadingZeros, highString, k, 0, 0, 0, 0, true, true, + true, mem); + } + + private: + // Returns the number of beautiful integers, considering the i-th digit with + // counts of even `even` digits and odd `odd` digits, where the current number + // modulo k equals remainder, `isTight1` indicates if the current digit is + // tightly bound for `low` and `isTight2` indicates if the current digit is + // tightly bound for `high` + int count(const string& low, const string& high, int k, int i, int even, + int odd, int remainder, bool isLeadingZero, bool isTight1, + bool isTight2, + vector>>>>>& mem) { + if (i == high.length()) + return !isLeadingZero && even == odd && remainder == 0; + if (mem[i][even][odd][remainder][isTight1][isTight2] != -1) + return mem[i][even][odd][remainder][isTight1][isTight2]; + + int res = 0; + const int minDigit = isTight1 ? low[i] - '0' : 0; + const int maxDigit = isTight2 ? high[i] - '0' : 9; + + for (int d = minDigit; d <= maxDigit; ++d) { + const int nextEven = even + ((!isLeadingZero || d > 0) && d % 2 == 0); + const int nextOdd = odd + (d % 2 == 1); + const int nextRemainder = (remainder * 10 + d) % k; + const bool nextIsTight1 = isTight1 && (d == minDigit); + const bool nextIsTight2 = isTight2 && (d == maxDigit); + res += count(low, high, k, i + 1, nextEven, nextOdd, nextRemainder, + isLeadingZero && d == 0, nextIsTight1, nextIsTight2, mem); + } + + return mem[i][even][odd][remainder][isTight1][isTight2] = res; + } +}; diff --git a/solutions/2828. Check if a String Is an Acronym of Words/2828.cpp b/solutions/2828. Check if a String Is an Acronym of Words/2828.cpp new file mode 100644 index 00000000000..7b0e45dcc97 --- /dev/null +++ b/solutions/2828. Check if a String Is an Acronym of Words/2828.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool isAcronym(vector& words, string s) { + if (words.size() != s.length()) + return false; + + for (int i = 0; i < words.size(); ++i) + if (words[i][0] != s[i]) + return false; + + return true; + } +}; diff --git a/solutions/2828. Check if a String Is an Acronym of Words/2828.java b/solutions/2828. Check if a String Is an Acronym of Words/2828.java new file mode 100644 index 00000000000..d60613b4b07 --- /dev/null +++ b/solutions/2828. Check if a String Is an Acronym of Words/2828.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isAcronym(List words, String s) { + if (words.size() != s.length()) + return false; + + for (int i = 0; i < words.size(); ++i) + if (words.get(i).charAt(0) != s.charAt(i)) + return false; + + return true; + } +} diff --git a/solutions/2828. Check if a String Is an Acronym of Words/2828.py b/solutions/2828. Check if a String Is an Acronym of Words/2828.py new file mode 100644 index 00000000000..1c1559732d4 --- /dev/null +++ b/solutions/2828. Check if a String Is an Acronym of Words/2828.py @@ -0,0 +1,4 @@ +class Solution: + def isAcronym(self, words: List[str], s: str) -> bool: + return len(words) == len(s) and \ + all(word[0] == c for word, c in zip(words, s)) diff --git a/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.cpp b/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.cpp new file mode 100644 index 00000000000..5a957fbd2aa --- /dev/null +++ b/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minimumSum(int n, int k) { + // These are the unique pairs that sum up to k: + // (1, k - 1), (2, k - 2), ..., (ceil(k / 2), floor(k / 2)). + // Our optimal strategy is to select 1, 2, ..., floor(k / 2), and then + // choose k, k + 1, ... if necessary, as selecting any number in the range + // [ceil(k / 2), k - 1] will result in a pair summing up to k. + const int mid = k / 2; // floor(k / 2) + if (n <= mid) + return trapezoid(1, n); + return trapezoid(1, mid) + trapezoid(k, k + (n - mid - 1)); + } + + private: + // Returns sum(a..b). + int trapezoid(int a, int b) { + return (a + b) * (b - a + 1) / 2; + } +}; diff --git a/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.java b/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.java new file mode 100644 index 00000000000..1767a221f45 --- /dev/null +++ b/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.java @@ -0,0 +1,18 @@ +class Solution { + public int minimumSum(int n, int k) { + // These are the unique pairs that sum up to k: + // (1, k - 1), (2, k - 2), ..., (ceil(k / 2), floor(k / 2)). + // Our optimal strategy is to select 1, 2, ..., floor(k / 2), and then + // choose k, k + 1, ... if necessary, as selecting any number in the range + // [ceil(k / 2), k - 1] will result in a pair summing up to k. + final int mid = k / 2; // floor(k / 2) + if (n <= mid) + return trapezoid(1, n); + return trapezoid(1, mid) + trapezoid(k, k + (n - mid - 1)); + } + + // Returns sum(a..b). + private int trapezoid(int a, int b) { + return (a + b) * (b - a + 1) / 2; + } +} diff --git a/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.py b/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.py new file mode 100644 index 00000000000..37ae51cdb27 --- /dev/null +++ b/solutions/2829. Determine the Minimum Sum of a k-avoiding Array/2829.py @@ -0,0 +1,16 @@ +class Solution: + def minimumSum(self, n: int, k: int) -> int: + # These are the unique pairs that sum up to k: + # (1, k - 1), (2, k - 2), ..., (ceil(k // 2), floor(k // 2)). + # Our optimal strategy is to select 1, 2, ..., floor(k // 2), and then + # choose k, k + 1, ... if necessary, as selecting any number in the range + # [ceil(k // 2), k - 1] will result in a pair summing up to k. + + def trapezoid(a: int, b: int) -> int: + """Returns sum(a..b).""" + return (a + b) * (b - a + 1) // 2 + + mid = k // 2 # floor(k // 2) + if n <= mid: + return trapezoid(1, n) + return trapezoid(1, mid) + trapezoid(k, k + (n - mid - 1)) diff --git a/solutions/283. Move Zeroes/283.cpp b/solutions/283. Move Zeroes/283.cpp new file mode 100644 index 00000000000..e6e86a42da1 --- /dev/null +++ b/solutions/283. Move Zeroes/283.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + void moveZeroes(vector& nums) { + int i = 0; + for (const int num : nums) + if (num != 0) + nums[i++] = num; + + while (i < nums.size()) + nums[i++] = 0; + } +}; diff --git a/solutions/283. Move Zeroes/283.java b/solutions/283. Move Zeroes/283.java new file mode 100644 index 00000000000..bd96418f507 --- /dev/null +++ b/solutions/283. Move Zeroes/283.java @@ -0,0 +1,11 @@ +class Solution { + public void moveZeroes(int[] nums) { + int i = 0; + for (final int num : nums) + if (num != 0) + nums[i++] = num; + + while (i < nums.length) + nums[i++] = 0; + } +} diff --git a/solutions/283. Move Zeroes/283.py b/solutions/283. Move Zeroes/283.py new file mode 100644 index 00000000000..92e782d20c5 --- /dev/null +++ b/solutions/283. Move Zeroes/283.py @@ -0,0 +1,10 @@ +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + j = 0 + for num in nums: + if num != 0: + nums[j] = num + j += 1 + + for i in range(j, len(nums)): + nums[i] = 0 diff --git a/solutions/2830. Maximize the Profit as the Salesman/2830.cpp b/solutions/2830. Maximize the Profit as the Salesman/2830.cpp new file mode 100644 index 00000000000..31daad7a396 --- /dev/null +++ b/solutions/2830. Maximize the Profit as the Salesman/2830.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int maximizeTheProfit(int n, vector>& offers) { + // dp[i] := the maximum amount of gold of selling the first i houses + vector dp(n + 1); + vector>> endToStartAndGolds(n); + + for (const vector& offer : offers) { + const int start = offer[0]; + const int end = offer[1]; + const int gold = offer[2]; + endToStartAndGolds[end].emplace_back(start, gold); + } + + for (int end = 1; end <= n; ++end) { + // Get at least the same gold as selling the first `end - 1` houses. + dp[end] = dp[end - 1]; + for (const auto& [start, gold] : endToStartAndGolds[end - 1]) + dp[end] = max(dp[end], dp[start] + gold); + } + + return dp[n]; + } +}; diff --git a/solutions/2830. Maximize the Profit as the Salesman/2830.java b/solutions/2830. Maximize the Profit as the Salesman/2830.java new file mode 100644 index 00000000000..d2960c8f8f1 --- /dev/null +++ b/solutions/2830. Maximize the Profit as the Salesman/2830.java @@ -0,0 +1,29 @@ +class Solution { + public int maximizeTheProfit(int n, List> offers) { + // dp[i] := the maximum amount of gold of selling the first i houses + int[] dp = new int[n + 1]; + List>[] endToStartAndGolds = new List[n]; + + for (int i = 0; i < n; ++i) + endToStartAndGolds[i] = new ArrayList<>(); + + for (List offer : offers) { + final int start = offer.get(0); + final int end = offer.get(1); + final int gold = offer.get(2); + endToStartAndGolds[end].add(new Pair<>(start, gold)); + } + + for (int end = 1; end <= n; ++end) { + // Get at least the same gold as selling the first `end - 1` houses. + dp[end] = dp[end - 1]; + for (Pair pair : endToStartAndGolds[end - 1]) { + final Integer start = pair.getKey(); + final Integer gold = pair.getValue(); + dp[end] = Math.max(dp[end], dp[start] + gold); + } + } + + return dp[n]; + } +} diff --git a/solutions/2830. Maximize the Profit as the Salesman/2830.py b/solutions/2830. Maximize the Profit as the Salesman/2830.py new file mode 100644 index 00000000000..74599c9a64b --- /dev/null +++ b/solutions/2830. Maximize the Profit as the Salesman/2830.py @@ -0,0 +1,16 @@ +class Solution: + def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int: + # dp[i] := the maximum amount of gold of selling the first i houses + dp = [0] * (n + 1) + endToStartAndGolds = [[] for _ in range(n)] + + for start, end, gold in offers: + endToStartAndGolds[end].append((start, gold)) + + for end in range(1, n + 1): + # Get at least the same gold as selling the first `end - 1` houses. + dp[end] = dp[end - 1] + for start, gold in endToStartAndGolds[end - 1]: + dp[end] = max(dp[end], dp[start] + gold) + + return dp[n] diff --git a/solutions/2831. Find the Longest Equal Subarray/2831-2.cpp b/solutions/2831. Find the Longest Equal Subarray/2831-2.cpp new file mode 100644 index 00000000000..18767ba8e2a --- /dev/null +++ b/solutions/2831. Find the Longest Equal Subarray/2831-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int longestEqualSubarray(vector& nums, int k) { + int ans = 0; + unordered_map count; + + // l and r track the maximum window instead of the valid window. + for (int l = 0, r = 0; r < nums.size(); ++r) { + ans = max(ans, ++count[nums[r]]); + if (r - l + 1 - k > ans) + --count[nums[l++]]; + } + + return ans; + } +}; diff --git a/solutions/2831. Find the Longest Equal Subarray/2831-2.java b/solutions/2831. Find the Longest Equal Subarray/2831-2.java new file mode 100644 index 00000000000..6f0dad93a42 --- /dev/null +++ b/solutions/2831. Find the Longest Equal Subarray/2831-2.java @@ -0,0 +1,15 @@ +class Solution { + public int longestEqualSubarray(List nums, int k) { + int ans = 0; + Map count = new HashMap<>(); + + // l and r track the maximum window instead of the valid window. + for (int l = 0, r = 0; r < nums.size(); ++r) { + ans = Math.max(ans, count.merge(nums.get(r), 1, Integer::sum)); + if (r - l + 1 - k > ans) + count.merge(nums.get(l++), -1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/2831. Find the Longest Equal Subarray/2831-2.py b/solutions/2831. Find the Longest Equal Subarray/2831-2.py new file mode 100644 index 00000000000..dbbbab06233 --- /dev/null +++ b/solutions/2831. Find the Longest Equal Subarray/2831-2.py @@ -0,0 +1,15 @@ +class Solution: + def longestEqualSubarray(self, nums: List[int], k: int) -> int: + ans = 0 + count = collections.Counter() + + # l and r track the maximum window instead of the valid window. + l = 0 + for r, num in enumerate(nums): + count[num] += 1 + ans = max(ans, count[num]) + if r - l + 1 - k > ans: + count[nums[l]] -= 1 + l += 1 + + return ans diff --git a/solutions/2831. Find the Longest Equal Subarray/2831.cpp b/solutions/2831. Find the Longest Equal Subarray/2831.cpp new file mode 100644 index 00000000000..00e2f36b664 --- /dev/null +++ b/solutions/2831. Find the Longest Equal Subarray/2831.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int longestEqualSubarray(vector& nums, int k) { + int ans = 0; + unordered_map count; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + ans = max(ans, ++count[nums[r]]); + while (r - l + 1 - k > ans) + --count[nums[l++]]; + } + + return ans; + } +}; diff --git a/solutions/2831. Find the Longest Equal Subarray/2831.java b/solutions/2831. Find the Longest Equal Subarray/2831.java new file mode 100644 index 00000000000..9c62217f645 --- /dev/null +++ b/solutions/2831. Find the Longest Equal Subarray/2831.java @@ -0,0 +1,14 @@ +class Solution { + public int longestEqualSubarray(List nums, int k) { + int ans = 0; + Map count = new HashMap<>(); + + for (int l = 0, r = 0; r < nums.size(); ++r) { + ans = Math.max(ans, count.merge(nums.get(r), 1, Integer::sum)); + while (r - l + 1 - k > ans) + count.merge(nums.get(l++), -1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/2831. Find the Longest Equal Subarray/2831.py b/solutions/2831. Find the Longest Equal Subarray/2831.py new file mode 100644 index 00000000000..73a6cf9de81 --- /dev/null +++ b/solutions/2831. Find the Longest Equal Subarray/2831.py @@ -0,0 +1,14 @@ +class Solution: + def longestEqualSubarray(self, nums: List[int], k: int) -> int: + ans = 0 + count = collections.Counter() + + l = 0 + for r, num in enumerate(nums): + count[num] += 1 + ans = max(ans, count[num]) + while r - l + 1 - k > ans: + count[nums[l]] -= 1 + l += 1 + + return ans diff --git a/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.cpp b/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.cpp new file mode 100644 index 00000000000..852dd23742a --- /dev/null +++ b/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector maximumLengthOfRanges(vector& nums) { + vector ans(nums.size()); + stack stack; // a decreasing stack + + for (int i = 0; i <= nums.size(); ++i) { + while (!stack.empty() && + (i == nums.size() || nums[stack.top()] < nums[i])) { + const int index = stack.top(); + stack.pop(); + const int left = stack.empty() ? -1 : stack.top(); + ans[index] = i - left - 1; + } + stack.push(i); + } + + return ans; + } +}; diff --git a/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.java b/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.java new file mode 100644 index 00000000000..ad8e34e8579 --- /dev/null +++ b/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.java @@ -0,0 +1,17 @@ +class Solution { + public int[] maximumLengthOfRanges(int[] nums) { + int[] ans = new int[nums.length]; + Deque stack = new ArrayDeque<>(); // a decreasing stack + + for (int i = 0; i <= nums.length; ++i) { + while (!stack.isEmpty() && (i == nums.length || nums[stack.peek()] < nums[i])) { + final int index = stack.pop(); + final int left = stack.isEmpty() ? -1 : stack.peek(); + ans[index] = i - left - 1; + } + stack.push(i); + } + + return ans; + } +} diff --git a/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.py b/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.py new file mode 100644 index 00000000000..86d16b3cb5e --- /dev/null +++ b/solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.py @@ -0,0 +1,13 @@ +class Solution: + def maximumLengthOfRanges(self, nums: List[int]) -> List[int]: + ans = [0] * len(nums) + stack = [] # a decreasing stack + + for i in range(len(nums) + 1): + while stack and (i == len(nums) or nums[stack[-1]] < nums[i]): + index = stack.pop() + left = stack[-1] if stack else -1 + ans[index] = i - left - 1 + stack.append(i) + + return ans diff --git a/solutions/2833. Furthest Point From Origin/2833.cpp b/solutions/2833. Furthest Point From Origin/2833.cpp new file mode 100644 index 00000000000..34505229d26 --- /dev/null +++ b/solutions/2833. Furthest Point From Origin/2833.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int furthestDistanceFromOrigin(string moves) { + int countL = 0; + int countR = 0; + int countUnderline = 0; + + for (const char c : moves) + if (c == 'L') + ++countL; + else if (c == 'R') + ++countR; + else // c == '_' + ++countUnderline; + + return abs(countL - countR) + countUnderline; + } +}; diff --git a/solutions/2833. Furthest Point From Origin/2833.java b/solutions/2833. Furthest Point From Origin/2833.java new file mode 100644 index 00000000000..cb607280584 --- /dev/null +++ b/solutions/2833. Furthest Point From Origin/2833.java @@ -0,0 +1,17 @@ +class Solution { + public int furthestDistanceFromOrigin(String moves) { + int countL = 0; + int countR = 0; + int countUnderline = 0; + + for (final char c : moves.toCharArray()) + if (c == 'L') + ++countL; + else if (c == 'R') + ++countR; + else // c == '_' + ++countUnderline; + + return Math.abs(countL - countR) + countUnderline; + } +} diff --git a/solutions/2833. Furthest Point From Origin/2833.py b/solutions/2833. Furthest Point From Origin/2833.py new file mode 100644 index 00000000000..d3c21f474d0 --- /dev/null +++ b/solutions/2833. Furthest Point From Origin/2833.py @@ -0,0 +1,3 @@ +class Solution: + def furthestDistanceFromOrigin(self, moves: str) -> int: + return abs(moves.count('L') - moves.count('R')) + moves.count('_') diff --git a/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.cpp b/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.cpp new file mode 100644 index 00000000000..6de51f6be05 --- /dev/null +++ b/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + // Same as 2829. Determine the Minimum Sum of a k-avoiding Array + int minimumPossibleSum(int n, int target) { + // These are the unique pairs that sum up to target (k): + // (1, k - 1), (2, k - 2), ..., (ceil(k / 2), floor(k / 2)). + // Our optimal strategy is to select 1, 2, ..., floor(k / 2), and then + // choose k, k + 1, ... if necessary, as selecting any number in the range + // [ceil(k / 2), k - 1] will result in a pair summing up to k. + const int mid = target / 2; + if (n <= mid) + return trapezoid(1, n); + return (trapezoid(1, mid) + trapezoid(target, target + (n - mid - 1))) % + kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns sum(a..b). + long trapezoid(long a, long b) { + return (a + b) * (b - a + 1) / 2; + } +}; diff --git a/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.java b/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.java new file mode 100644 index 00000000000..b8b98cae9ca --- /dev/null +++ b/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.java @@ -0,0 +1,21 @@ +class Solution { + // Same as 2829. Determine the Minimum Sum of a k-avoiding Array + public int minimumPossibleSum(int n, int target) { + // These are the unique pairs that sum up to target (k): + // (1, k - 1), (2, k - 2), ..., (ceil(k / 2), floor(k / 2)). + // Our optimal strategy is to select 1, 2, ..., floor(k / 2), and then + // choose k, k + 1, ... if necessary, as selecting any number in the range + // [ceil(k / 2), k - 1] will result in a pair summing up to k. + final int mid = target / 2; // floor(k / 2) + if (n <= mid) + return (int) trapezoid(1, n); + return (int) ((trapezoid(1, mid) + trapezoid(target, target + (n - mid - 1))) % kMod); + } + + private static final int kMod = 1_000_000_007; + + // Returns sum(a..b). + private long trapezoid(long a, long b) { + return (a + b) * (b - a + 1) / 2; + } +} diff --git a/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.py b/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.py new file mode 100644 index 00000000000..b51c9a63ea9 --- /dev/null +++ b/solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.py @@ -0,0 +1,18 @@ +class Solution: + # Same as 2829. Determine the Minimum Sum of a k-avoiding Array + def minimumPossibleSum(self, n: int, target: int) -> int: + # These are the unique pairs that sum up to k (target): + # (1, k - 1), (2, k - 2), ..., (ceil(k // 2), floor(k // 2)). + # Our optimal strategy is to select 1, 2, ..., floor(k // 2), and then + # choose k, k + 1, ... if necessary, as selecting any number in the range + # [ceil(k // 2), k - 1] will result in a pair summing up to k. + kMod = 1_000_000_007 + + def trapezoid(a: int, b: int) -> int: + """Returns sum(a..b).""" + return (a + b) * (b - a + 1) // 2 + + mid = target // 2 # floor(k // 2) + if n <= mid: + return trapezoid(1, n) + return (trapezoid(1, mid) + trapezoid(target, target + (n - mid - 1))) % kMod diff --git a/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.cpp b/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.cpp new file mode 100644 index 00000000000..d85a520f103 --- /dev/null +++ b/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int minOperations(vector& nums, int target) { + constexpr int kNoMissingBit = 31; + constexpr int maxBit = 31; + int ans = 0; + int minMissingBit = kNoMissingBit; + // count[i] := the number of occurrences of 2^i + vector count(maxBit + 1); + + for (const int num : nums) + ++count[static_cast(log2(num))]; + + for (int bit = 0; bit < maxBit; ++bit) { + // Check if `bit` is in the target. + if (target >> bit & 1) { + // If there are available bits, use one bit. + if (count[bit] > 0) + --count[bit]; + else + minMissingBit = min(minMissingBit, bit); + } + // If we previously missed a bit and there are available bits. + if (minMissingBit != kNoMissingBit && count[bit] > 0) { + --count[bit]; + // Count the operations to break `bit` into `minMissingBit`. + ans += bit - minMissingBit; + minMissingBit = kNoMissingBit; + } + // Combining smaller numbers costs nothing. + count[bit + 1] += count[bit] / 2; + } + + // Check if all target bits have been covered, otherwise return -1. + return minMissingBit == kNoMissingBit ? ans : -1; + } +}; diff --git a/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.java b/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.java new file mode 100644 index 00000000000..200d4b13745 --- /dev/null +++ b/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.java @@ -0,0 +1,36 @@ +public class Solution { + public int minOperations(List nums, int target) { + final int kNoMissingBit = 31; + final int maxBit = 31; + int ans = 0; + int minMissingBit = kNoMissingBit; + // count[i] := the number of occurrences of 2^i + int[] count = new int[maxBit + 1]; + + for (final int num : nums) + ++count[(int) (Math.log(num) / Math.log(2))]; + + for (int bit = 0; bit < maxBit; ++bit) { + // Check if `bit` is in the target. + if ((target >> bit & 1) == 1) { + // If there are available bits, use one bit. + if (count[bit] > 0) + --count[bit]; + else + minMissingBit = Math.min(minMissingBit, bit); + } + // If we previously missed a bit and there are available bits. + if (minMissingBit != kNoMissingBit && count[bit] > 0) { + --count[bit]; + // Count the operations to break `bit` into `minMissingBit`. + ans += bit - minMissingBit; + minMissingBit = kNoMissingBit; // Set it to an the invalid value. + } + // Combining smaller numbers costs nothing. + count[bit + 1] += count[bit] / 2; + } + + // Check if all target bits have been covered, otherwise return -1. + return minMissingBit == kNoMissingBit ? ans : -1; + } +} diff --git a/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.py b/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.py new file mode 100644 index 00000000000..a13f0a672e3 --- /dev/null +++ b/solutions/2835. Minimum Operations to Form Subsequence With Target Sum/2835.py @@ -0,0 +1,28 @@ +class Solution: + def minOperations(self, nums: List[int], target: int) -> int: + kNoMissingBit = 31 + maxBit = 31 + ans = 0 + minMissingBit = kNoMissingBit + # count[i] := the number of occurrences of 2^i + count = collections.Counter(int(math.log2(num)) for num in nums) + + for bit in range(maxBit): + # Check if `bit` is in the target. + if target >> bit & 1: + # If there are available bits, use one bit. + if count[bit] > 0: + count[bit] -= 1 + else: + minMissingBit = min(minMissingBit, bit) + # If we previously missed a bit and there are available bits. + if minMissingBit != kNoMissingBit and count[bit] > 0: + count[bit] -= 1 + # Count the operations to break `bit` into `minMissingBit`. + ans += bit - minMissingBit + minMissingBit = kNoMissingBit # Set it to an the invalid value. + # Combining smaller numbers costs nothing. + count[bit + 1] += count[bit] // 2 + + # Check if all target bits have been covered, otherwise return -1. + return ans if minMissingBit == maxBit else -1 diff --git a/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.cpp b/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.cpp new file mode 100644 index 00000000000..228101d5f16 --- /dev/null +++ b/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + long long getMaxFunctionValue(vector& receiver, long long k) { + const int n = receiver.size(); + const int m = log2(k) + 1; + long ans = 0; + // jump[i][j] := the the node you reach after jumping 2^j steps from i + vector> jump(n, vector(m)); + // sum[i][j] := the sum of the first 2^j nodes you reach when jumping from i + vector> sum(n, vector(m)); + + for (int i = 0; i < n; ++i) { + jump[i][0] = receiver[i]; + sum[i][0] = receiver[i]; + } + + // Calculate binary lifting. + for (int j = 1; j < m; ++j) + for (int i = 0; i < n; ++i) { + const int midNode = jump[i][j - 1]; + // the the node you reach after jumping 2^j steps from i + // = the node you reach after jumping 2^(j - 1) steps from i + // + the node you reach after jumping another 2^(j - 1) steps + jump[i][j] = jump[midNode][j - 1]; + // the sum of the first 2^j nodes you reach when jumping from i + // = the sum of the first 2^(j - 1) nodes you reach when jumping from i + // + the sum of another 2^(j - 1) nodes you reach + sum[i][j] = sum[i][j - 1] + sum[midNode][j - 1]; + } + + for (int i = 0; i < n; ++i) { + long currSum = i; + int currPos = i; + for (int j = 0; j < m; ++j) + if (k >> j & 1) { + currSum += sum[currPos][j]; + currPos = jump[currPos][j]; + } + ans = max(ans, currSum); + } + + return ans; + } +}; diff --git a/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.java b/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.java new file mode 100644 index 00000000000..2ebf6abf660 --- /dev/null +++ b/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.java @@ -0,0 +1,43 @@ +class Solution { + public long getMaxFunctionValue(List receiver, long k) { + final int n = receiver.size(); + final int m = (int) (Math.log(k) / Math.log(2)) + 1; + long ans = 0; + // jump[i][j] := the the node you reach after jumping 2^j steps from i + int[][] jump = new int[n][m]; + // sum[i][j] := the sum of the first 2^j nodes you reach when jumping from i + long[][] sum = new long[n][m]; + + for (int i = 0; i < n; ++i) { + jump[i][0] = receiver.get(i); + sum[i][0] = receiver.get(i); + } + + // Calculate binary lifting. + for (int j = 1; j < m; ++j) + for (int i = 0; i < n; ++i) { + final int midNode = jump[i][j - 1]; + // the the node you reach after jumping 2^j steps from i + // = the node you reach after jumping 2^(j - 1) steps from i + // + the node you reach after jumping another 2^(j - 1) steps + jump[i][j] = jump[midNode][j - 1]; + // the sum of the first 2^j nodes you reach when jumping from i + // = the sum of the first 2^(j - 1) nodes you reach when jumping from i + // + the sum of another 2^(j - 1) nodes you reach + sum[i][j] = sum[i][j - 1] + sum[midNode][j - 1]; + } + + for (int i = 0; i < n; ++i) { + long currSum = i; + int currPos = i; + for (int j = 0; j < m; ++j) + if ((k >> j & 1) == 1) { + currSum += sum[currPos][j]; + currPos = jump[currPos][j]; + } + ans = Math.max(ans, currSum); + } + + return ans; + } +} diff --git a/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.py b/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.py new file mode 100644 index 00000000000..77cb70722e9 --- /dev/null +++ b/solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.py @@ -0,0 +1,37 @@ +class Solution: + def getMaxFunctionValue(self, receiver: List[int], k: int) -> int: + n = len(receiver) + m = int(math.log2(k)) + 1 + ans = 0 + # jump[i][j] := the the node you reach after jumping 2^j steps from i + jump = [[0] * m for _ in range(n)] + # summ[i][j] := the sum of the first 2^j nodes you reach when jumping from i + summ = [[0] * m for _ in range(n)] + + for i in range(n): + jump[i][0] = receiver[i] + summ[i][0] = receiver[i] + + # Calculate binary lifting. + for j in range(1, m): + for i in range(n): + midNode = jump[i][j - 1] + # the the node you reach after jumping 2^j steps from i + # = the node you reach after jumping 2^(j - 1) steps from i + # + the node you reach after jumping another 2^(j - 1) steps + jump[i][j] = jump[midNode][j - 1] + # the sum of the first 2^j nodes you reach when jumping from i + # = the sum of the first 2^(j - 1) nodes you reach when jumping from i + # + the sum of another 2^(j - 1) nodes you reach + summ[i][j] = summ[i][j - 1] + summ[midNode][j - 1] + + for i in range(n): + currSum = i + currPos = i + for j in range(m): + if (k >> j) & 1 == 1: + currSum += summ[currPos][j] + currPos = jump[currPos][j] + ans = max(ans, currSum) + + return ans diff --git a/solutions/2837. Total Traveled Distance/2837.sql b/solutions/2837. Total Traveled Distance/2837.sql new file mode 100644 index 00000000000..71a678505bb --- /dev/null +++ b/solutions/2837. Total Traveled Distance/2837.sql @@ -0,0 +1,9 @@ +SELECT + Users.user_id, + Users.name, + SUM(IFNULL(Rides.distance, 0)) AS 'traveled distance' +FROM Users +LEFT JOIN Rides + USING (user_id) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2838. Maximum Coins Heroes Can Collect/2838.cpp b/solutions/2838. Maximum Coins Heroes Can Collect/2838.cpp new file mode 100644 index 00000000000..a9b8dc5b2b9 --- /dev/null +++ b/solutions/2838. Maximum Coins Heroes Can Collect/2838.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + vector maximumCoins(vector& heroes, vector& monsters, + vector& coins) { + const vector> monsterAndCoins = + getSortedMonsterAndCoins(monsters, coins); + vector ans; + vector coinsPrefix{0}; + + for (const auto& [_, coin] : monsterAndCoins) + coinsPrefix.push_back(coinsPrefix.back() + coin); + + for (const int hero : heroes) + ans.push_back(coinsPrefix[firstGreaterEqual(monsterAndCoins, hero)]); + + return ans; + } + + private: + vector> getSortedMonsterAndCoins(const vector& monsters, + const vector& coins) { + vector> monsterAndCoins; + for (int i = 0; i < monsters.size(); ++i) + monsterAndCoins.emplace_back(monsters[i], coins[i]); + ranges::sort(monsterAndCoins); + return monsterAndCoins; + } + + int firstGreaterEqual(const vector>& monsterAndCoins, + int hero) { + int l = 0; + int r = monsterAndCoins.size(); + while (l < r) { + const int m = (l + r) / 2; + if (monsterAndCoins[m].first > hero) + r = m; + else + l = m + 1; + } + return l; + } +}; diff --git a/solutions/2838. Maximum Coins Heroes Can Collect/2838.java b/solutions/2838. Maximum Coins Heroes Can Collect/2838.java new file mode 100644 index 00000000000..ffc77a22ec5 --- /dev/null +++ b/solutions/2838. Maximum Coins Heroes Can Collect/2838.java @@ -0,0 +1,36 @@ +class Solution { + public long[] maximumCoins(int[] heroes, int[] monsters, int[] coins) { + Pair[] monsterAndCoins = getSortedMonsterAndCoins(monsters, coins); + long[] ans = new long[heroes.length]; + long[] coinsPrefix = new long[coins.length + 1]; + + for (int i = 0; i < monsterAndCoins.length; ++i) + coinsPrefix[i + 1] = coinsPrefix[i] + monsterAndCoins[i].getValue(); + + for (int i = 0; i < heroes.length; ++i) + ans[i] = coinsPrefix[firstGreaterEqual(monsterAndCoins, heroes[i])]; + + return ans; + } + + private Pair[] getSortedMonsterAndCoins(int[] monsters, int[] coins) { + Pair[] monsterAndCoins = new Pair[monsters.length]; + for (int i = 0; i < monsters.length; ++i) + monsterAndCoins[i] = new Pair<>(monsters[i], coins[i]); + Arrays.sort(monsterAndCoins, (a, b) -> a.getKey() - b.getKey()); + return monsterAndCoins; + } + + private int firstGreaterEqual(Pair[] monsterAndCoins, int hero) { + int l = 0; + int r = monsterAndCoins.length; + while (l < r) { + final int m = (l + r) / 2; + if (monsterAndCoins[m].getKey() > hero) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/2838. Maximum Coins Heroes Can Collect/2838.py b/solutions/2838. Maximum Coins Heroes Can Collect/2838.py new file mode 100644 index 00000000000..620a7ee1ac4 --- /dev/null +++ b/solutions/2838. Maximum Coins Heroes Can Collect/2838.py @@ -0,0 +1,16 @@ +class Solution: + def maximumCoins(self, heroes: List[int], monsters: List[int], coins: List[int]) -> List[int]: + monsterAndCoins = sorted(list(zip(monsters, coins))) + coinsPrefix = [0] + \ + list(itertools.accumulate(coin for _, coin in monsterAndCoins)) + return [coinsPrefix[self._firstGreaterEqual(monsterAndCoins, hero)] for hero in heroes] + + def _firstGreaterEqual(self, monsterAndCoins: List[tuple[int, int]], hero: int) -> int: + l, r = 0, len(monsterAndCoins) + while l < r: + m = (l + r) // 2 + if monsterAndCoins[m][0] > hero: + r = m + else: + l = m + 1 + return l diff --git a/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.cpp b/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.cpp new file mode 100644 index 00000000000..5d0e9453b93 --- /dev/null +++ b/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool canBeEqual(string s1, string s2) { + for (const string& a : swappedStrings(s1)) + for (const string& b : swappedStrings(s2)) + if (a == b) + return true; + return false; + } + + private: + vector swappedStrings(const string& s) { + vector chars(s.begin(), s.end()); + return {s, string({chars[2], chars[1], chars[0], chars[3]}), + string({chars[0], chars[3], chars[2], chars[1]}), + string({chars[2], chars[3], chars[0], chars[1]})}; + } +}; diff --git a/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.java b/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.java new file mode 100644 index 00000000000..496b89a60f9 --- /dev/null +++ b/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.java @@ -0,0 +1,19 @@ +class Solution { + public boolean canBeEqual(String s1, String s2) { + for (final String a : swappedStrings(s1)) + for (final String b : swappedStrings(s2)) + if (a.equals(b)) + return true; + return false; + } + + private List swappedStrings(final String s) { + List res = new ArrayList<>(); + char[] chars = s.toCharArray(); + res.add(s); + res.add(new String(new char[] {chars[2], chars[1], chars[0], chars[3]})); + res.add(new String(new char[] {chars[0], chars[3], chars[2], chars[1]})); + res.add(new String(new char[] {chars[2], chars[3], chars[0], chars[1]})); + return res; + } +} diff --git a/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.py b/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.py new file mode 100644 index 00000000000..571189d86c6 --- /dev/null +++ b/solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.py @@ -0,0 +1,12 @@ +class Solution: + def canBeEqual(self, s1: str, s2: str) -> bool: + def swappedStrings(s: str) -> List[str]: + chars = list(s) + return [chars, + ''.join([chars[2], chars[1], chars[0], chars[3]]), + ''.join([chars[0], chars[3], chars[2], chars[1]]), + ''.join([chars[2], chars[3], chars[0], chars[1]])] + + return any(a == b + for a in swappedStrings(s1) + for b in swappedStrings(s2)) diff --git a/solutions/284. Peeking Iterator/284.cpp b/solutions/284. Peeking Iterator/284.cpp new file mode 100644 index 00000000000..0ca89fd42cd --- /dev/null +++ b/solutions/284. Peeking Iterator/284.cpp @@ -0,0 +1,21 @@ +class PeekingIterator : public Iterator { + public: + PeekingIterator(const vector& nums) : Iterator(nums) {} + + // Returns the next element in the iteration without advancing the iterator. + int peek() { + // Iterator(*this) makes a copy of current iterator, then call next on the + // Copied iterator to get the next value without affecting current iterator + return Iterator(*this).next(); + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + int next() { + return Iterator::next(); + } + + bool hasNext() const { + return Iterator::hasNext(); + } +}; diff --git a/solutions/284. Peeking Iterator/284.java b/solutions/284. Peeking Iterator/284.java new file mode 100644 index 00000000000..fbf2e161921 --- /dev/null +++ b/solutions/284. Peeking Iterator/284.java @@ -0,0 +1,31 @@ +// Java Iterator interface reference: +// Https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html + +class PeekingIterator implements Iterator { + public PeekingIterator(Iterator iterator) { + this.iterator = iterator; + buffer = iterator.hasNext() ? iterator.next() : null; + } + + // Returns the next element in the iteration without advancing the iterator. + public Integer peek() { + return buffer; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + @Override + public Integer next() { + Integer next = buffer; + buffer = iterator.hasNext() ? iterator.next() : null; + return next; + } + + @Override + public boolean hasNext() { + return buffer != null; + } + + private Iterator iterator; + private Integer buffer; +} diff --git a/solutions/284. Peeking Iterator/284.py b/solutions/284. Peeking Iterator/284.py new file mode 100644 index 00000000000..90211b78e57 --- /dev/null +++ b/solutions/284. Peeking Iterator/284.py @@ -0,0 +1,18 @@ +class PeekingIterator: + def __init__(self, iterator: Iterator): + self.iterator = iterator + self.buffer = self.iterator.next() if self.iterator.hasNext() else None + + def peek(self) -> int: + """ + Returns the next element in the iteration without advancing the iterator. + """ + return self.buffer + + def next(self) -> int: + next = self.buffer + self.buffer = self.iterator.next() if self.iterator.hasNext() else None + return next + + def hasNext(self) -> bool: + return self.buffer is not None diff --git a/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.cpp b/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.cpp new file mode 100644 index 00000000000..ef60993afdf --- /dev/null +++ b/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool checkStrings(string s1, string s2) { + vector> count(2, vector(26)); + + for (int i = 0; i < s1.length(); ++i) { + ++count[i % 2][s1[i] - 'a']; + --count[i % 2][s2[i] - 'a']; + } + + for (int i = 0; i < 26; ++i) + if (count[0][i] > 0 || count[1][i] > 0) + return false; + + return true; + } +}; diff --git a/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.java b/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.java new file mode 100644 index 00000000000..8b5b97654d2 --- /dev/null +++ b/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.java @@ -0,0 +1,16 @@ +class Solution { + public boolean checkStrings(String s1, String s2) { + int[][] count = new int[2][26]; + + for (int i = 0; i < s1.length(); ++i) { + ++count[i % 2][s1.charAt(i) - 'a']; + --count[i % 2][s2.charAt(i) - 'a']; + } + + for (int i = 0; i < 26; ++i) + if (count[0][i] > 0 || count[1][i] > 0) + return false; + + return true; + } +} diff --git a/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.py b/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.py new file mode 100644 index 00000000000..811a1cb0877 --- /dev/null +++ b/solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.py @@ -0,0 +1,10 @@ +class Solution: + def checkStrings(self, s1: str, s2: str) -> bool: + count = [collections.Counter() for _ in range(2)] + + for i, (a, b) in enumerate(zip(s1, s2)): + count[i % 2][a] += 1 + count[i % 2][b] -= 1 + + return all(freq == 0 for freq in count[0].values()) \ + and all(freq == 0 for freq in count[1].values()) diff --git a/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.cpp b/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.cpp new file mode 100644 index 00000000000..d7ed5d2fb80 --- /dev/null +++ b/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long maxSum(vector& nums, int m, int k) { + long ans = 0; + long sum = 0; + unordered_map count; + + for (int i = 0; i < nums.size(); ++i) { + sum += nums[i]; + ++count[nums[i]]; + if (i >= k) { + const int numToRemove = nums[i - k]; + sum -= numToRemove; + if (--count[numToRemove] == 0) + count.erase(numToRemove); + } + if (count.size() >= m) + ans = max(ans, sum); + } + + return ans; + } +}; diff --git a/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.java b/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.java new file mode 100644 index 00000000000..71f91ea53bd --- /dev/null +++ b/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.java @@ -0,0 +1,23 @@ +public class Solution { + public long maxSum(List nums, int m, int k) { + long ans = 0; + long sum = 0; + Map count = new HashMap<>(); + + for (int i = 0; i < nums.size(); ++i) { + sum += nums.get(i); + count.merge(nums.get(i), 1, Integer::sum); + if (i >= k) { + final int numToRemove = nums.get(i - k); + sum -= numToRemove; + count.merge(numToRemove, -1, Integer::sum); + if (count.get(numToRemove) == 0) + count.remove(numToRemove); + } + if (count.size() >= m) + ans = Math.max(ans, sum); + } + + return ans; + } +} diff --git a/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.py b/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.py new file mode 100644 index 00000000000..d68e9ca8f8a --- /dev/null +++ b/solutions/2841. Maximum Sum of Almost Unique Subarray/2841.py @@ -0,0 +1,19 @@ +class Solution: + def maxSum(self, nums: List[int], m: int, k: int) -> int: + ans = 0 + summ = 0 + count = collections.Counter() + + for i, num in enumerate(nums): + summ += num + count[num] += 1 + if i >= k: + numToRemove = nums[i - k] + summ -= numToRemove + count[numToRemove] -= 1 + if count[numToRemove] == 0: + del count[numToRemove] + if len(count) >= m: + ans = max(ans, summ) + + return ans diff --git a/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.cpp b/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.cpp new file mode 100644 index 00000000000..05ee03ae3da --- /dev/null +++ b/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.cpp @@ -0,0 +1,58 @@ +class Solution { + public: + int countKSubsequencesWithMaxBeauty(string s, int k) { + unordered_map count; + for (const char c : s) + ++count[c]; + if (count.size() < k) + return 0; + + long ans = 1; + + for (const auto& [fc, numOfChars] : getFreqCountPairs(count)) { + if (numOfChars >= k) { + ans *= nCk(numOfChars, k); + ans %= kMod; + return ans * modPow(fc, k) % kMod; + } + ans *= modPow(fc, numOfChars); + ans %= kMod; + k -= numOfChars; + } + + return ans; + } + + private: + static constexpr int kMod = 1'000'000'007; + + vector> getFreqCountPairs( + const unordered_map& count) { + unordered_map freqCount; + for (const auto& [_, value] : count) + ++freqCount[value]; + vector> freqCountPairs; + for (const auto& [fc, numOfChars] : freqCount) + freqCountPairs.emplace_back(fc, numOfChars); + ranges::sort(freqCountPairs, + [](const pair& a, const pair& b) { + return b.first < a.first; + }); + return freqCountPairs; + } + + long nCk(int n, int k) { + long res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.java b/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.java new file mode 100644 index 00000000000..5136c94d476 --- /dev/null +++ b/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.java @@ -0,0 +1,54 @@ +public class Solution { + public int countKSubsequencesWithMaxBeauty(String s, int k) { + Map count = new HashMap<>(); + for (final char c : s.toCharArray()) + count.merge(c, 1, Integer::sum); + if (count.size() < k) + return 0; + + long ans = 1; + + for (Pair pair : getFreqCountPairs(count)) { + final int fc = pair.getKey(); + final int numOfChars = pair.getValue(); + if (numOfChars >= k) { + ans *= nCk(numOfChars, k) * modPow(fc, k); + return (int) (ans % kMod); + } + ans *= modPow(fc, numOfChars); + ans %= kMod; + k -= numOfChars; + } + + return (int) ans; + } + + private static final int kMod = 1_000_000_007; + + private List> getFreqCountPairs(Map count) { + // freqCount := (f(c), # of chars with f(c)) + Map freqCount = new HashMap<>(); + for (final int value : count.values()) + freqCount.merge(value, 1, Integer::sum); + List> freqCountPairs = new ArrayList<>(); + for (Map.Entry entry : freqCount.entrySet()) + freqCountPairs.add(new Pair<>(entry.getKey(), entry.getValue())); + freqCountPairs.sort((a, b) -> b.getKey() - a.getKey()); + return freqCountPairs; + } + + private long nCk(int n, int k) { + long res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } + + private int modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return (int) (x * modPow(x % kMod, (n - 1)) % kMod); + return modPow(x * x % kMod, (n / 2)) % kMod; + } +} diff --git a/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.py b/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.py new file mode 100644 index 00000000000..d64d741c09e --- /dev/null +++ b/solutions/2842. Count K-Subsequences of a String With Maximum Beauty Solved/2842.py @@ -0,0 +1,18 @@ +class Solution: + def countKSubsequencesWithMaxBeauty(self, s: str, k: int) -> int: + kMod = 1_000_000_007 + count = collections.Counter(s) + if len(count) < k: + return 0 + + ans = 1 + # freqCount := (f(c), # of chars with f(c)) + freqCount = collections.Counter(count.values()) + + for fc, numOfChars in list(sorted(freqCount.items(), reverse=True)): + if numOfChars >= k: + ans *= math.comb(numOfChars, k) * pow(fc, k, kMod) + return ans % kMod + ans *= pow(fc, numOfChars, kMod) + ans %= kMod + k -= numOfChars diff --git a/solutions/2843. Count Symmetric Integers/2843.cpp b/solutions/2843. Count Symmetric Integers/2843.cpp new file mode 100644 index 00000000000..d9e461e7b16 --- /dev/null +++ b/solutions/2843. Count Symmetric Integers/2843.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int countSymmetricIntegers(int low, int high) { + int ans = 0; + + for (int num = low; num <= high; ++num) + if (isSymmetricInteger(num)) + ++ans; + + return ans; + } + + private: + bool isSymmetricInteger(int num) { + if (num >= 10 && num <= 99) + return num / 10 == num % 10; + if (num >= 1000 && num <= 9999) { + const int left = num / 100; + const int right = num % 100; + return left / 10 + left % 10 == right / 10 + right % 10; + } + return false; + } +}; diff --git a/solutions/2843. Count Symmetric Integers/2843.java b/solutions/2843. Count Symmetric Integers/2843.java new file mode 100644 index 00000000000..f0048eee8ee --- /dev/null +++ b/solutions/2843. Count Symmetric Integers/2843.java @@ -0,0 +1,22 @@ +class Solution { + public int countSymmetricIntegers(int low, int high) { + int ans = 0; + + for (int num = low; num <= high; ++num) + if (isSymmetricInteger(num)) + ++ans; + + return ans; + } + + private boolean isSymmetricInteger(int num) { + if (num >= 10 && num <= 99) + return num / 10 == num % 10; + if (num >= 1000 && num <= 9999) { + final int left = num / 100; + final int right = num % 100; + return left / 10 + left % 10 == right / 10 + right % 10; + } + return false; + } +} diff --git a/solutions/2843. Count Symmetric Integers/2843.py b/solutions/2843. Count Symmetric Integers/2843.py new file mode 100644 index 00000000000..e9ff22fd279 --- /dev/null +++ b/solutions/2843. Count Symmetric Integers/2843.py @@ -0,0 +1,12 @@ +class Solution: + def countSymmetricIntegers(self, low: int, high: int) -> int: + def isSymmetricInteger(num: int) -> bool: + if num >= 10 and num <= 99: + return num // 10 == num % 10 + if num >= 1000 and num <= 9999: + left = num // 100 + right = num % 100 + return left // 10 + left % 10 == right // 10 + right % 10 + return False + + return sum(isSymmetricInteger(num) for num in range(low, high + 1)) diff --git a/solutions/2844. Minimum Operations to Make a Special Number/2844.cpp b/solutions/2844. Minimum Operations to Make a Special Number/2844.cpp new file mode 100644 index 00000000000..1c293762693 --- /dev/null +++ b/solutions/2844. Minimum Operations to Make a Special Number/2844.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minimumOperations(string num) { + const int n = num.length(); + bool seenFive = false; + bool seenZero = false; + + for (int i = n - 1; i >= 0; --i) { + if (seenZero && num[i] == '0') // '00' + return n - i - 2; + if (seenZero && num[i] == '5') // '50' + return n - i - 2; + if (seenFive && num[i] == '2') // '25' + return n - i - 2; + if (seenFive && num[i] == '7') // '75' + return n - i - 2; + seenZero = seenZero || num[i] == '0'; + seenFive = seenFive || num[i] == '5'; + } + + return seenZero ? n - 1 : n; + } +}; diff --git a/solutions/2844. Minimum Operations to Make a Special Number/2844.java b/solutions/2844. Minimum Operations to Make a Special Number/2844.java new file mode 100644 index 00000000000..0e30696e278 --- /dev/null +++ b/solutions/2844. Minimum Operations to Make a Special Number/2844.java @@ -0,0 +1,22 @@ +class Solution { + public int minimumOperations(String num) { + final int n = num.length(); + boolean seenFive = false; + boolean seenZero = false; + + for (int i = n - 1; i >= 0; --i) { + if (seenZero && num.charAt(i) == '0') // '00' + return n - i - 2; + if (seenZero && num.charAt(i) == '5') // '50' + return n - i - 2; + if (seenFive && num.charAt(i) == '2') // '25' + return n - i - 2; + if (seenFive && num.charAt(i) == '7') // '75' + return n - i - 2; + seenZero = seenZero || num.charAt(i) == '0'; + seenFive = seenFive || num.charAt(i) == '5'; + } + + return seenZero ? n - 1 : n; + } +} diff --git a/solutions/2844. Minimum Operations to Make a Special Number/2844.py b/solutions/2844. Minimum Operations to Make a Special Number/2844.py new file mode 100644 index 00000000000..8b1f22912c6 --- /dev/null +++ b/solutions/2844. Minimum Operations to Make a Special Number/2844.py @@ -0,0 +1,19 @@ +class Solution: + def minimumOperations(self, num: str) -> int: + n = len(num) + seenFive = False + seenZero = False + + for i in range(n - 1, -1, -1): + if seenZero and num[i] == '0': # '00' + return n - i - 2 + if seenZero and num[i] == '5': # '50' + return n - i - 2 + if seenFive and num[i] == '2': # '25' + return n - i - 2 + if seenFive and num[i] == '7': # '75' + return n - i - 2 + seenZero = seenZero or num[i] == '0' + seenFive = seenFive or num[i] == '5' + + return n - 1 if seenZero else n diff --git a/solutions/2845. Count of Interesting Subarrays/2845.cpp b/solutions/2845. Count of Interesting Subarrays/2845.cpp new file mode 100644 index 00000000000..a4bbf73290d --- /dev/null +++ b/solutions/2845. Count of Interesting Subarrays/2845.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + long countInterestingSubarrays(vector& nums, int modulo, int k) { + long ans = 0; + int prefix = 0; // (number of nums[i] % modulo == k so far) % modulo + unordered_map prefixCount{{0, 1}}; + + for (const int num : nums) { + if (num % modulo == k) + prefix = (prefix + 1) % modulo; + ans += prefixCount[(prefix - k + modulo) % modulo]; + ++prefixCount[prefix]; + } + + return ans; + } +}; diff --git a/solutions/2845. Count of Interesting Subarrays/2845.java b/solutions/2845. Count of Interesting Subarrays/2845.java new file mode 100644 index 00000000000..7fabdc01760 --- /dev/null +++ b/solutions/2845. Count of Interesting Subarrays/2845.java @@ -0,0 +1,17 @@ +class Solution { + public long countInterestingSubarrays(List nums, int modulo, int k) { + long ans = 0; + int prefix = 0; // (number of nums[i] % modulo == k so far) % modulo + Map prefixCount = new HashMap<>(); + prefixCount.put(0, 1); + + for (final int num : nums) { + if (num % modulo == k) + prefix = (prefix + 1) % modulo; + ans += prefixCount.getOrDefault((prefix - k + modulo) % modulo, 0); + prefixCount.merge(prefix, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/2845. Count of Interesting Subarrays/2845.py b/solutions/2845. Count of Interesting Subarrays/2845.py new file mode 100644 index 00000000000..986943367dd --- /dev/null +++ b/solutions/2845. Count of Interesting Subarrays/2845.py @@ -0,0 +1,13 @@ +class Solution: + def countInterestingSubarrays(self, nums: List[int], modulo: int, k: int) -> int: + ans = 0 + prefix = 0 # (number of nums[i] % modulo == k so far) % modulo + prefixCount = collections.Counter({0: 1}) + + for num in nums: + if num % modulo == k: + prefix = (prefix + 1) % modulo + ans += prefixCount[(prefix - k + modulo) % modulo] + prefixCount[prefix] += 1 + + return ans diff --git a/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.cpp b/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.cpp new file mode 100644 index 00000000000..43711aefb42 --- /dev/null +++ b/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.cpp @@ -0,0 +1,86 @@ +class Solution { + public: + vector minOperationsQueries(int n, vector>& edges, + vector>& queries) { + constexpr int kMax = 26; + const int m = log2(n) + 1; + vector ans; + vector>> graph(n); + // jump[i][j] := the node you reach after jumping 2^j from i + vector> jump(n, vector(m)); + // count[i][j] := the count of j from root to i, where 1 <= j <= 26 + vector> count(n); + // depth[i] := the depth of i + vector depth(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + count[0] = vector(kMax + 1); + dfs(graph, 0, /*prev=*/-1, 0, jump, count, depth); + + // Calculate binary lifting. + for (int j = 1; j < m; ++j) + for (int i = 0; i < n; ++i) + jump[i][j] = jump[jump[i][j - 1]][j - 1]; + + for (const vector& query : queries) { + const int u = query[0]; + const int v = query[1]; + const int lca = getLCA(u, v, jump, depth); + // the number of edges between (u, v). + const int numEdges = depth[u] + depth[v] - 2 * depth[lca]; + // the maximum frequency of edges between (u, v) + int maxFreq = 0; + for (int j = 1; j <= kMax; ++j) + maxFreq = max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]); + ans.push_back(numEdges - maxFreq); + } + + return ans; + } + + private: + void dfs(const vector>>& graph, int u, int prev, int d, + vector>& jump, vector>& count, + vector& depth) { + if (prev != -1) + jump[u][0] = prev; + depth[u] = d; + for (const auto& [v, w] : graph[u]) { + if (v == prev) + continue; + // Inherit the count from the parent. + count[v] = count[u]; + // Add one to this edge. + ++count[v][w]; + dfs(graph, v, u, d + 1, jump, count, depth); + } + } + + // Returns the lca(u, v) via Calculate binary lifting. + int getLCA(int u, int v, const vector>& jump, + const vector& depth) { + // v is always deeper than u. + if (depth[u] > depth[v]) + return getLCA(v, u, jump, depth); + // Jump v to the same height of u. + for (int j = 0; j < jump[0].size(); ++j) + if (depth[v] - depth[u] >> j & 1) + v = jump[v][j]; + if (u == v) + return u; + // Jump u and v to the node right below the lca. + for (int j = jump[0].size() - 1; j >= 0; --j) + if (jump[u][j] != jump[v][j]) { + u = jump[u][j]; + v = jump[v][j]; + } + return jump[v][0]; + } +}; diff --git a/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.java b/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.java new file mode 100644 index 00000000000..a86041311bf --- /dev/null +++ b/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.java @@ -0,0 +1,86 @@ +class Solution { + public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) { + final int kMax = 26; + final int m = (int) (Math.log(n) / Math.log(2)) + 1; + int[] ans = new int[queries.length]; + List>[] graph = new List[n]; + // jump[i][j] := the node you reach after jumping 2^j from i + int[][] jump = new int[n][m]; + // count[i][j] := the count of j from root to i, where 1 <= j <= 26 + int[][] count = new int[n][]; + // depth[i] := the depth of i + int[] depth = new int[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + count[0] = new int[kMax + 1]; + dfs(graph, 0, /*prev=*/-1, 0, jump, count, depth); + + // Calculate binary lifting. + for (int j = 1; j < m; ++j) + for (int i = 0; i < n; ++i) + jump[i][j] = jump[jump[i][j - 1]][j - 1]; + + for (int i = 0; i < queries.length; ++i) { + final int u = queries[i][0]; + final int v = queries[i][1]; + final int lca = getLCA(u, v, jump, depth); + // the number of edges between (u, v). + final int numEdges = depth[u] + depth[v] - 2 * depth[lca]; + // the maximum frequency of edges between (u, v) + int maxFreq = 0; + for (int j = 1; j <= kMax; ++j) + maxFreq = Math.max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]); + ans[i] = numEdges - maxFreq; + } + + return ans; + } + + private void dfs(List>[] graph, int u, int prev, int d, int[][] jump, + int[][] count, int[] depth) { + if (prev != -1) + jump[u][0] = prev; + depth[u] = d; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (v == prev) + continue; + // Inherit the count from the parent. + count[v] = count[u].clone(); + // Add one to this edge. + ++count[v][w]; + dfs(graph, v, u, d + 1, jump, count, depth); + } + } + + // Returns the lca(u, v) via Calculate binary lifting. + private int getLCA(int u, int v, int[][] jump, int[] depth) { + // v is always deeper than u. + if (depth[u] > depth[v]) + return getLCA(v, u, jump, depth); + // Jump v to the same height of u. + for (int j = 0; j < jump[0].length; ++j) + if ((depth[v] - depth[u] >> j & 1) == 1) + v = jump[v][j]; + if (u == v) + return u; + // Jump u and v to the node right below the lca. + for (int j = jump[0].length - 1; j >= 0; --j) + if (jump[u][j] != jump[v][j]) { + u = jump[u][j]; + v = jump[v][j]; + } + return jump[v][0]; + } +} diff --git a/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.py b/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.py new file mode 100644 index 00000000000..30ab2bcd51b --- /dev/null +++ b/solutions/2846. Minimum Edge Weight Equilibrium Queries in a Tree/2846.py @@ -0,0 +1,66 @@ +class Solution: + def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]: + kMax = 26 + m = int(math.log2(n)) + 1 + ans = [] + graph = [[] for _ in range(n)] + # jump[i][j] := the node you reach after jumping 2^j from i + jump = [[0] * m for _ in range(n)] + # count[i][j] := the count of j from root to i, where 1 <= j <= 26 + count = [[] for _ in range(n)] + # depth[i] := the depth of i + depth = [0] * n + + for u, v, w in edges: + graph[u].append((v, w)) + graph[v].append((u, w)) + + def dfs(u: int, prev: int, d: int): + if prev != -1: + jump[u][0] = prev + depth[u] = d + for v, w in graph[u]: + if v == prev: + continue + # Inherit the count from the parent. + count[v] = count[u][:] + # Add one to this edge. + count[v][w] += 1 + dfs(v, u, d + 1) + + count[0] = [0] * (kMax + 1) + dfs(0, -1, 0) + + # Calculate binary lifting. + for j in range(1, m): + for i in range(n): + jump[i][j] = jump[jump[i][j - 1]][j - 1] + + def getLCA(u: int, v: int) -> int: + """Returns the lca(u, v) via Calculate binary lifting.""" + # v is always deeper than u. + if depth[u] > depth[v]: + return getLCA(v, u) + # Jump v to the same height of u. + for j in range(m): + if depth[v] - depth[u] >> j & 1: + v = jump[v][j] + if u == v: + return u + # Jump u and v to the node right below the lca. + for j in range(m - 1, -1, -1): + if jump[u][j] != jump[v][j]: + u = jump[u][j] + v = jump[v][j] + return jump[v][0] + + for u, v in queries: + lca = getLCA(u, v) + # the number of edges between (u, v). + numEdges = depth[u] + depth[v] - 2 * depth[lca] + # the maximum frequency of edges between (u, v) + maxFreq = max(count[u][j] + count[v][j] - 2 * count[lca][j] + for j in range(1, kMax + 1)) + ans.append(numEdges - maxFreq) + + return ans diff --git a/solutions/2847. Smallest Number With Given Digit Product/2847.cpp b/solutions/2847. Smallest Number With Given Digit Product/2847.cpp new file mode 100644 index 00000000000..4792a416758 --- /dev/null +++ b/solutions/2847. Smallest Number With Given Digit Product/2847.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string smallestNumber(long long n) { + if (n <= 9) + return to_string(n); + + string ans; + + for (int divisor = 9; divisor > 1; --divisor) + while (n % divisor == 0) { + ans += to_string(divisor); + n /= divisor; + } + + return n > 1 ? "-1" : string{ans.rbegin(), ans.rend()}; + } +}; diff --git a/solutions/2847. Smallest Number With Given Digit Product/2847.java b/solutions/2847. Smallest Number With Given Digit Product/2847.java new file mode 100644 index 00000000000..a191faf4e2b --- /dev/null +++ b/solutions/2847. Smallest Number With Given Digit Product/2847.java @@ -0,0 +1,16 @@ +class Solution { + public String smallestNumber(long n) { + if (n <= 9) + return Long.toString(n); + + StringBuilder ans = new StringBuilder(); + + for (int divisor = 9; divisor > 1; --divisor) + while (n % divisor == 0) { + ans.append(Integer.toString(divisor)); + n /= divisor; + } + + return n > 1 ? "-1" : ans.reverse().toString(); + } +} diff --git a/solutions/2847. Smallest Number With Given Digit Product/2847.py b/solutions/2847. Smallest Number With Given Digit Product/2847.py new file mode 100644 index 00000000000..28f3f496950 --- /dev/null +++ b/solutions/2847. Smallest Number With Given Digit Product/2847.py @@ -0,0 +1,13 @@ +class Solution: + def smallestNumber(self, n: int) -> str: + if n <= 9: + return str(n) + + ans = [] + + for divisor in range(9, 1, -1): + while n % divisor == 0: + ans.append(str(divisor)) + n //= divisor + + return '-1' if n > 1 else ''.join(reversed(ans)) diff --git a/solutions/2848. Points That Intersect With Cars/2848.cpp b/solutions/2848. Points That Intersect With Cars/2848.cpp new file mode 100644 index 00000000000..9b176d2e1b9 --- /dev/null +++ b/solutions/2848. Points That Intersect With Cars/2848.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int numberOfPoints(vector>& nums) { + constexpr int kMax = 100; + int ans = 0; + int runningSum = 0; + vector count(kMax + 2); + + for (const vector& num : nums) { + const int start = num[0]; + const int end = num[1]; + ++count[start]; + --count[end + 1]; + } + + for (int i = 1; i <= kMax; ++i) { + runningSum += count[i]; + if (runningSum > 0) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2848. Points That Intersect With Cars/2848.java b/solutions/2848. Points That Intersect With Cars/2848.java new file mode 100644 index 00000000000..4613c083243 --- /dev/null +++ b/solutions/2848. Points That Intersect With Cars/2848.java @@ -0,0 +1,23 @@ +class Solution { + public int numberOfPoints(List> nums) { + final int kMax = 100; + int ans = 0; + int runningSum = 0; + int[] count = new int[kMax + 2]; + + for (List num : nums) { + final int start = num.get(0); + final int end = num.get(1); + ++count[start]; + --count[end + 1]; + } + + for (int i = 1; i <= kMax; i++) { + runningSum += count[i]; + if (runningSum > 0) + ++ans; + } + + return ans; + } +} diff --git a/solutions/2848. Points That Intersect With Cars/2848.py b/solutions/2848. Points That Intersect With Cars/2848.py new file mode 100644 index 00000000000..6e5fed57ff6 --- /dev/null +++ b/solutions/2848. Points That Intersect With Cars/2848.py @@ -0,0 +1,17 @@ +class Solution: + def numberOfPoints(self, nums: List[List[int]]) -> int: + kMax = 100 + ans = 0 + runningSum = 0 + count = [0] * (kMax + 2) + + for start, end in nums: + count[start] += 1 + count[end + 1] -= 1 + + for i in range(1, kMax + 1): + runningSum += count[i] + if runningSum > 0: + ans += 1 + + return ans diff --git a/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.cpp b/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.cpp new file mode 100644 index 00000000000..8957773f8cd --- /dev/null +++ b/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + bool isReachableAtTime(int sx, int sy, int fx, int fy, int t) { + const int minStep = max(abs(sx - fx), abs(sy - fy)); + return minStep == 0 ? t != 1 : minStep <= t; + } +}; diff --git a/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.java b/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.java new file mode 100644 index 00000000000..1c8347d0f4b --- /dev/null +++ b/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.java @@ -0,0 +1,6 @@ +class Solution { + public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { + final int minStep = Math.max(Math.abs(sx - fx), Math.abs(sy - fy)); + return minStep == 0 ? t != 1 : minStep <= t; + } +} diff --git a/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.py b/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.py new file mode 100644 index 00000000000..c2320879e47 --- /dev/null +++ b/solutions/2849. Determine if a Cell Is Reachable at a Given Time/2849.py @@ -0,0 +1,4 @@ +class Solution: + def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool: + minStep = max(abs(sx - fx), abs(sy - fy)) + return t != 1 if minStep == 0 else minStep <= t diff --git a/solutions/285. Inorder Successor in BST/285.cpp b/solutions/285. Inorder Successor in BST/285.cpp new file mode 100644 index 00000000000..f8cbbb136cb --- /dev/null +++ b/solutions/285. Inorder Successor in BST/285.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { + if (root == nullptr) + return nullptr; + if (root->val <= p->val) + return inorderSuccessor(root->right, p); + + TreeNode* left = inorderSuccessor(root->left, p); + return left ? left : root; + } +}; diff --git a/solutions/285. Inorder Successor in BST/285.java b/solutions/285. Inorder Successor in BST/285.java new file mode 100644 index 00000000000..2efed2094b2 --- /dev/null +++ b/solutions/285. Inorder Successor in BST/285.java @@ -0,0 +1,11 @@ +class Solution { + public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { + if (root == null) + return null; + if (root.val <= p.val) + return inorderSuccessor(root.right, p); + + TreeNode left = inorderSuccessor(root.left, p); + return left == null ? root : left; + } +} diff --git a/solutions/285. Inorder Successor in BST/285.py b/solutions/285. Inorder Successor in BST/285.py new file mode 100644 index 00000000000..2c4325630c3 --- /dev/null +++ b/solutions/285. Inorder Successor in BST/285.py @@ -0,0 +1,7 @@ +class Solution: + def inorderSuccessor(self, root: Optional[TreeNode], p: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: + return None + if root.val <= p.val: + return self.inorderSuccessor(root.right, p) + return self.inorderSuccessor(root.left, p) or root diff --git a/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.cpp b/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.cpp new file mode 100644 index 00000000000..208c05a54e1 --- /dev/null +++ b/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minimumMoves(vector>& grid) { + const int zeroCount = accumulate(grid.begin(), grid.end(), 0, + [](int subtotal, const vector& row) { + return subtotal + ranges::count(row, 0); + }); + if (zeroCount == 0) + return 0; + + int ans = INT_MAX; + + for (int i = 0; i < 3; ++i) + for (int j = 0; j < 3; ++j) + if (grid[i][j] == 0) + for (int x = 0; x < 3; ++x) + for (int y = 0; y < 3; ++y) + // Move a stone at (x, y) to (i, j). + if (grid[x][y] > 1) { + --grid[x][y]; + ++grid[i][j]; + ans = min(ans, abs(x - i) + abs(y - j) + minimumMoves(grid)); + ++grid[x][y]; + --grid[i][j]; + } + + return ans; + } +}; diff --git a/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.java b/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.java new file mode 100644 index 00000000000..48fa81917bc --- /dev/null +++ b/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.java @@ -0,0 +1,28 @@ +class Solution { + public int minimumMoves(int[][] grid) { + int zeroCount = 0; + for (int[] row : grid) + for (int cell : row) + if (cell == 0) + ++zeroCount; + if (zeroCount == 0) + return 0; + + int ans = Integer.MAX_VALUE; + + for (int i = 0; i < 3; ++i) + for (int j = 0; j < 3; ++j) + if (grid[i][j] == 0) + for (int x = 0; x < 3; ++x) + for (int y = 0; y < 3; ++y) + if (grid[x][y] > 1) { + --grid[x][y]; + ++grid[i][j]; + ans = Math.min(ans, Math.abs(x - i) + Math.abs(y - j) + minimumMoves(grid)); + ++grid[x][y]; + --grid[i][j]; + } + + return ans; + } +} diff --git a/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.py b/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.py new file mode 100644 index 00000000000..628ea92d9ff --- /dev/null +++ b/solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.py @@ -0,0 +1,21 @@ +class Solution: + def minimumMoves(self, grid: List[List[int]]) -> int: + if sum(row.count(0) for row in grid) == 0: + return 0 + + ans = math.inf + + for i in range(3): + for j in range(3): + if grid[i][j] == 0: + for x in range(3): + for y in range(3): + if grid[x][y] > 1: + grid[x][y] -= 1 + grid[i][j] += 1 + ans = min(ans, abs(x - i) + abs(y - j) + + self.minimumMoves(grid)) + grid[x][y] += 1 + grid[i][j] -= 1 + + return ans diff --git a/solutions/2851. String Transformation/2851.cpp b/solutions/2851. String Transformation/2851.cpp new file mode 100644 index 00000000000..b81a8036473 --- /dev/null +++ b/solutions/2851. String Transformation/2851.cpp @@ -0,0 +1,78 @@ +class Solution { + public: + // This dynamic programming table dp[k][i] represents the number of ways to + // rearrange the string s after k steps such that it starts with s[i]. + // A string can be rotated from 1 to n - 1 times. The transition rule is + // dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and + // k = 3, the table looks like this: + // + // ----------------------------------------------------------- + // | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k | + // ----------------------------------------------------------- + // | k = 0 | 1 | 0 | 0 | 0 | 1 | + // | k = 1 | 0 | 1 | 1 | 1 | 3 | + // | k = 2 | 3 | 2 | 2 | 2 | 9 | + // | k = 3 | 6 | 7 | 7 | 7 | 27 | + // ----------------------------------------------------------- + // + // By observation, we have + // * dp[k][!0] = ((n - 1)^k - (-1)^k) / n + // * dp[k][0] = dp[k][!0] + (-1)^k + int numberOfWays(string s, string t, long long k) { + const int n = s.length(); + const int negOnePowK = (k % 2 == 0 ? 1 : -1); // (-1)^k + const vector z = zFunction(s + t + t); + const vector indices = getIndices(z, n); + vector dp(2); // dp[0] := dp[k][0]; dp[1] := dp[k][!0] + dp[1] = (modPow(n - 1, k) - negOnePowK + kMod) % kMod * + modPow(n, kMod - 2) % kMod; + dp[0] = (dp[1] + negOnePowK + kMod) % kMod; + return accumulate(indices.begin(), indices.end(), 0L, + [&](long subtotal, int index) { + return (subtotal + dp[index == 0 ? 0 : 1]) % kMod; + }); + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } + + // Returns the z array, where z[i] is the length of the longest prefix of + // s[i..n) which is also a prefix of s. + // + // https://cp-algorithms.com/string/z-function.html#implementation + vector zFunction(const string& s) { + const int n = s.length(); + vector z(n); + int l = 0; + int r = 0; + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = min(r - i, z[i - l]); + while (i + z[i] < n && s[z[i]] == s[i + z[i]]) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + return z; + } + + // Returns the indices in `s` s.t. for each `i` in the returned indices, + // `s[i..n) + s[0..i) = t`. + vector getIndices(const vector& z, int n) { + vector indices; + for (int i = n; i < n + n; ++i) + if (z[i] >= n) + indices.push_back(i - n); + return indices; + } +}; diff --git a/solutions/2851. String Transformation/2851.java b/solutions/2851. String Transformation/2851.java new file mode 100644 index 00000000000..eb06e2984fa --- /dev/null +++ b/solutions/2851. String Transformation/2851.java @@ -0,0 +1,77 @@ +class Solution { + // This dynamic programming table dp[k][i] represents the number of ways to + // rearrange the String s after k steps such that it starts with s[i]. + // A String can be rotated from 1 to n - 1 times. The transition rule is + // dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and + // k = 3, the table looks like this: + // + // ----------------------------------------------------------- + // | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k | + // ----------------------------------------------------------- + // | k = 0 | 1 | 0 | 0 | 0 | 1 | + // | k = 1 | 0 | 1 | 1 | 1 | 3 | + // | k = 2 | 3 | 2 | 2 | 2 | 9 | + // | k = 3 | 6 | 7 | 7 | 7 | 27 | + // ----------------------------------------------------------- + // + // By observation, we have + // * dp[k][!0] = ((n - 1)^k - (-1)^k) / n + // * dp[k][0] = dp[k][!0] + (-1)^k + public int numberOfWays(String s, String t, long k) { + final int n = s.length(); + final int negOnePowK = (k % 2 == 0 ? 1 : -1); // (-1)^k + final int[] z = zFunction(s + t + t); + final List indices = getIndices(z, n); + int[] dp = new int[2]; // dp[0] := dp[k][0]; dp[1] := dp[k][!0] + dp[1] = (int) ((modPow(n - 1, k) - negOnePowK + kMod) % kMod * modPow(n, kMod - 2) % kMod); + dp[0] = (int) ((dp[1] + negOnePowK + kMod) % kMod); + int ans = 0; + for (final int index : getIndices(z, n)) { + ans += dp[index == 0 ? 0 : 1]; + ans %= kMod; + } + return ans; + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } + + // Returns the z array, where z[i] is the length of the longest prefix of + // s[i..n) which is also a prefix of s. + // + // https://cp-algorithms.com/string/z-function.html#implementation + private int[] zFunction(final String s) { + final int n = s.length(); + int[] z = new int[n]; + int l = 0; + int r = 0; + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = Math.min(r - i, z[i - l]); + while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + return z; + } + + // Returns the indices in `s` s.t. for each `i` in the returned indices, + // `s[i..n) + s[0..i) = t`. + private List getIndices(int[] z, int n) { + List indices = new ArrayList<>(); + for (int i = n; i < n + n; ++i) + if (z[i] >= n) + indices.add(i - n); + return indices; + } +} diff --git a/solutions/2851. String Transformation/2851.py b/solutions/2851. String Transformation/2851.py new file mode 100644 index 00000000000..68de62c62b8 --- /dev/null +++ b/solutions/2851. String Transformation/2851.py @@ -0,0 +1,52 @@ +class Solution: + # This dynamic programming table dp[k][i] represents the number of ways to + # rearrange the String s after k steps such that it starts with s[i]. + # A String can be rotated from 1 to n - 1 times. The transition rule is + # dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and + # k = 3, the table looks like this: + # + # ----------------------------------------------------------- + # | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k | + # ----------------------------------------------------------- + # | k = 0 | 1 | 0 | 0 | 0 | 1 | + # | k = 1 | 0 | 1 | 1 | 1 | 3 | + # | k = 2 | 3 | 2 | 2 | 2 | 9 | + # | k = 3 | 6 | 7 | 7 | 7 | 27 | + # ----------------------------------------------------------- + # + # By observation, we have + # * dp[k][!0] = ((n - 1)^k - (-1)^k) / n + # * dp[k][0] = dp[k][!0] + (-1)^k + def numberOfWays(self, s: str, t: str, k: int) -> int: + kMod = 1_000_000_007 + n = len(s) + negOnePowK = 1 if k % 2 == 0 else -1 # (-1)^k + z = self._zFunction(s + t + t) + # indices in `s` s.t. for each `i` in the returned indices, + # `s[i..n) + s[0..i) = t`. + indices = [i - n for i in range(n, n + n) if z[i] >= n] + dp = [0] * 2 # dp[0] := dp[k][0]; dp[1] := dp[k][!0] + dp[1] = (pow(n - 1, k, kMod) - negOnePowK) * pow(n, kMod - 2, kMod) + dp[0] = dp[1] + negOnePowK + return sum(dp[0] if index == 0 else dp[1] for index in indices) % kMod + + def _zFunction(self, s: str) -> List[int]: + """ + Returns the z array, where z[i] is the length of the longest prefix of + s[i..n) which is also a prefix of s. + + https://cp-algorithms.com/string/z-function.html#implementation + """ + n = len(s) + z = [0] * n + l = 0 + r = 0 + for i in range(1, n): + if i < r: + z[i] = min(r - i, z[i - l]) + while i + z[i] < n and s[z[i]] == s[i + z[i]]: + z[i] += 1 + if i + z[i] > r: + l = i + r = i + z[i] + return z diff --git a/solutions/2852. Sum of Remoteness of All Cells/2852.cpp b/solutions/2852. Sum of Remoteness of All Cells/2852.cpp new file mode 100644 index 00000000000..a17f82e505a --- /dev/null +++ b/solutions/2852. Sum of Remoteness of All Cells/2852.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + long long sumRemoteness(vector>& grid) { + const long sum = accumulate(grid.begin(), grid.end(), 0L, + [](long subtotal, const vector& row) { + return subtotal + accumulate(row.begin(), row.end(), 0L, + [](long subtotal, const int cell) { + return subtotal + max(0, cell); + }); + }); + + long ans = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] > 0) { + const auto [count, componentSum] = dfs(grid, i, j); + ans += (sum - componentSum) * count; + } + + return ans; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns the (count, componentSum) of the connected component that contains + // (x, y). + pair dfs(vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return {0, 0}; + if (grid[i][j] == -1) + return {0, 0}; + + int count = 1; + long componentSum = grid[i][j]; + grid[i][j] = -1; // Mark as visited.; + + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + const auto [nextCount, nextComponentSum] = dfs(grid, x, y); + count += nextCount; + componentSum += nextComponentSum; + } + + return {count, componentSum}; + } +}; diff --git a/solutions/2852. Sum of Remoteness of All Cells/2852.java b/solutions/2852. Sum of Remoteness of All Cells/2852.java new file mode 100644 index 00000000000..4bb58d9623e --- /dev/null +++ b/solutions/2852. Sum of Remoteness of All Cells/2852.java @@ -0,0 +1,48 @@ +class Solution { + public long sumRemoteness(int[][] grid) { + long ans = 0; + long sum = 0; + + for (int[] row : grid) + for (int cell : row) + sum += Math.max(0, cell); + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] > 0) { + long[] res = dfs(grid, i, j); + final long count = res[0]; + final long componentSum = res[1]; + ans += (sum - componentSum) * count; + } + + return ans; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + // Returns the (count, componentSum) of the connected component that contains + // (x, y). + private long[] dfs(int[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return new long[] {0, 0}; + if (grid[i][j] == -1) + return new long[] {0, 0}; + + long count = 1; + long componentSum = grid[i][j]; + grid[i][j] = -1; // Mark as visited.; + + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + long[] nextRes = dfs(grid, x, y); + final long nextCount = nextRes[0]; + final long nextComponentSum = nextRes[1]; + count += nextCount; + componentSum += nextComponentSum; + } + + return new long[] {count, componentSum}; + } +} diff --git a/solutions/2852. Sum of Remoteness of All Cells/2852.py b/solutions/2852. Sum of Remoteness of All Cells/2852.py new file mode 100644 index 00000000000..9027a3575da --- /dev/null +++ b/solutions/2852. Sum of Remoteness of All Cells/2852.py @@ -0,0 +1,37 @@ +class Solution: + def sumRemoteness(self, grid: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + n = len(grid) + summ = sum(max(0, cell) for row in grid for cell in row) + ans = 0 + + def dfs(i: int, j: int) -> Tuple[int, int]: + """ + Returns the (count, componentSum) of the connected component that contains + (x, y). + """ + if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]): + return (0, 0) + if grid[i][j] == -1: + return (0, 0) + + count = 1 + componentSum = grid[i][j] + grid[i][j] = -1 # Mark as visited. + + for dx, dy in dirs: + x = i + dx + y = j + dy + nextCount, nextComponentSum = dfs(x, y) + count += nextCount + componentSum += nextComponentSum + + return (count, componentSum) + + for i in range(n): + for j in range(n): + if grid[i][j] > 0: + count, componentSum = dfs(i, j) + ans += (summ - componentSum) * count + + return ans diff --git a/solutions/2853. Highest Salaries Difference/2853.sql b/solutions/2853. Highest Salaries Difference/2853.sql new file mode 100644 index 00000000000..3f3e281d62e --- /dev/null +++ b/solutions/2853. Highest Salaries Difference/2853.sql @@ -0,0 +1,11 @@ +SELECT ABS( + ( + SELECT MAX(salary) AS salary + FROM Salaries + WHERE department = 'Engineering' + ) - ( + SELECT MAX(salary) AS salary + FROM Salaries + WHERE department = 'Marketing' + ) + ) AS salary_difference; diff --git a/solutions/2854. Rolling Average Steps/2854.sql b/solutions/2854. Rolling Average Steps/2854.sql new file mode 100644 index 00000000000..86a16a3d33f --- /dev/null +++ b/solutions/2854. Rolling Average Steps/2854.sql @@ -0,0 +1,25 @@ +WITH + StepsWithRollingAverage AS ( + SELECT + user_id, + steps_date, + ROUND( + AVG(steps_count) OVER( + PARTITION by user_id + ORDER BY steps_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW + ), + 2 + ) AS rolling_average, + LAG(steps_date, 2) OVER( + PARTITION by user_id + ORDER BY steps_date + ) AS two_dates_before + FROM Steps + ) +SELECT + user_id, + steps_date, + rolling_average +FROM StepsWithRollingAverage +WHERE DATEDIFF(steps_date, two_dates_before) = 2 +ORDER BY 1, 2; diff --git a/solutions/2855. Minimum Right Shifts to Sort the Array/2855.cpp b/solutions/2855. Minimum Right Shifts to Sort the Array/2855.cpp new file mode 100644 index 00000000000..5e673fdfbe5 --- /dev/null +++ b/solutions/2855. Minimum Right Shifts to Sort the Array/2855.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minimumRightShifts(vector& nums) { + int count = 0; + int pivot = -1; + + for (int i = 0; i + 1 < nums.size(); i++) + if (nums[i] > nums[i + 1]) { + ++count; + pivot = i; + } + + if (count == 0) + return 0; + if (count > 1 || nums.back() > nums.front()) + return -1; + return nums.size() - 1 - pivot; + } +}; diff --git a/solutions/2855. Minimum Right Shifts to Sort the Array/2855.java b/solutions/2855. Minimum Right Shifts to Sort the Array/2855.java new file mode 100644 index 00000000000..f4b223b47a8 --- /dev/null +++ b/solutions/2855. Minimum Right Shifts to Sort the Array/2855.java @@ -0,0 +1,18 @@ +class Solution { + public int minimumRightShifts(List nums) { + int pivot = -1; + int count = 0; + + for (int i = 0; i + 1 < nums.size(); i++) + if (nums.get(i) > nums.get(i + 1)) { + ++count; + pivot = i; + } + + if (count == 0) + return 0; + if (count > 1 || nums.get(nums.size() - 1) > nums.get(0)) + return -1; + return nums.size() - 1 - pivot; + } +} diff --git a/solutions/2855. Minimum Right Shifts to Sort the Array/2855.py b/solutions/2855. Minimum Right Shifts to Sort the Array/2855.py new file mode 100644 index 00000000000..d01fd7d6d41 --- /dev/null +++ b/solutions/2855. Minimum Right Shifts to Sort the Array/2855.py @@ -0,0 +1,14 @@ +class Solution: + def minimumRightShifts(self, nums: List[int]) -> int: + count = 0 + + for i, (a, b) in enumerate(itertools.pairwise(nums)): + if a > b: + count += 1 + pivot = i + + if count == 0: + return 0 + if count > 1 or nums[-1] > nums[0]: + return -1 + return len(nums) - pivot - 1 diff --git a/solutions/2856. Minimum Array Length After Pair Removals/2856.cpp b/solutions/2856. Minimum Array Length After Pair Removals/2856.cpp new file mode 100644 index 00000000000..7463bba35c6 --- /dev/null +++ b/solutions/2856. Minimum Array Length After Pair Removals/2856.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minLengthAfterRemovals(vector& nums) { + const int n = nums.size(); + unordered_map count; + int maxFreq = 0; + + for (const int num : nums) + ++count[num]; + + for (const auto& [_, freq] : count) + maxFreq = max(maxFreq, freq); + + // The number with the maximum frequency cancel all the other numbers. + if (maxFreq <= n / 2) + return n % 2; + // The number with the maximum frequency cancel all the remaining numbers. + return maxFreq - (n - maxFreq); + } +}; diff --git a/solutions/2856. Minimum Array Length After Pair Removals/2856.java b/solutions/2856. Minimum Array Length After Pair Removals/2856.java new file mode 100644 index 00000000000..25e340cdb14 --- /dev/null +++ b/solutions/2856. Minimum Array Length After Pair Removals/2856.java @@ -0,0 +1,19 @@ +class Solution { + public int minLengthAfterRemovals(List nums) { + final int n = nums.size(); + Map count = new HashMap<>(); + int maxFreq = 0; + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int freq : count.values()) + maxFreq = Math.max(maxFreq, freq); + + // The number with the maximum frequency cancel all the other numbers. + if (maxFreq <= n / 2) + return n % 2; + // The number with the maximum frequency cancel all the remaining numbers. + return maxFreq - (n - maxFreq); + } +} diff --git a/solutions/2856. Minimum Array Length After Pair Removals/2856.py b/solutions/2856. Minimum Array Length After Pair Removals/2856.py new file mode 100644 index 00000000000..ce6e9a7465b --- /dev/null +++ b/solutions/2856. Minimum Array Length After Pair Removals/2856.py @@ -0,0 +1,11 @@ +class Solution: + def minLengthAfterRemovals(self, nums: List[int]) -> int: + n = len(nums) + count = collections.Counter(nums) + maxFreq = max(count.values()) + + # The number with the maximum frequency cancel all the other numbers. + if maxFreq <= n / 2: + return n % 2 + # The number with the maximum frequency cancel all the remaining numbers. + return maxFreq - (n - maxFreq) diff --git a/solutions/2857. Count Pairs of Points With Distance k/2857.cpp b/solutions/2857. Count Pairs of Points With Distance k/2857.cpp new file mode 100644 index 00000000000..fdc0d9ebfb6 --- /dev/null +++ b/solutions/2857. Count Pairs of Points With Distance k/2857.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int countPairs(vector>& coordinates, int k) { + int ans = 0; + + for (int x = 0; x <= k; ++x) { + const int y = k - x; + unordered_map, int, PairHash> count; + for (const vector& point : coordinates) { + const int xi = point[0]; + const int yi = point[1]; + if (const auto it = count.find({xi ^ x, yi ^ y}); it != count.cend()) + ans += it->second; + ++count[{xi, yi}]; + } + } + + return ans; + } + + private: + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/2857. Count Pairs of Points With Distance k/2857.java b/solutions/2857. Count Pairs of Points With Distance k/2857.java new file mode 100644 index 00000000000..19ee9071b8a --- /dev/null +++ b/solutions/2857. Count Pairs of Points With Distance k/2857.java @@ -0,0 +1,18 @@ +class Solution { + public int countPairs(List> coordinates, int k) { + int ans = 0; + + for (int x = 0; x <= k; ++x) { + final int y = k - x; + Map, Integer> count = new HashMap<>(); + for (List point : coordinates) { + final int xi = point.get(0); + final int yi = point.get(1); + ans += count.getOrDefault(new Pair<>(xi ^ x, yi ^ y), 0); + count.merge(new Pair<>(xi, yi), 1, Integer::sum); + } + } + + return ans; + } +} diff --git a/solutions/2857. Count Pairs of Points With Distance k/2857.py b/solutions/2857. Count Pairs of Points With Distance k/2857.py new file mode 100644 index 00000000000..953b903a29e --- /dev/null +++ b/solutions/2857. Count Pairs of Points With Distance k/2857.py @@ -0,0 +1,12 @@ +class Solution: + def countPairs(self, coordinates: List[List[int]], k: int) -> int: + ans = 0 + + for x in range(k + 1): + y = k - x + count = collections.Counter() + for xi, yi in coordinates: + ans += count[(xi ^ x, yi ^ y)] + count[(xi, yi)] += 1 + + return ans diff --git a/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.cpp b/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.cpp new file mode 100644 index 00000000000..f8d65348aea --- /dev/null +++ b/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + vector minEdgeReversals(int n, vector>& edges) { + vector ans(n); + vector>> graph(n); + vector seen(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].emplace_back(v, /*isForward=*/true); + graph[v].emplace_back(u, /*isForward=*/false); + } + + vector mem(n, -1); + ans[0] = minEdgeReversals(graph, 0, seen, mem); + seen = vector(n); + dfs(graph, 0, seen, ans); + return ans; + } + + private: + // Returns the minimum number of edge reversals so node u can reach every + // node in its subtree. + int minEdgeReversals(const vector>>& graph, int u, + vector& seen, vector& mem) { + if (mem[u] != -1) + return mem[u]; + int res = 0; + seen[u] = true; + for (const auto& [v, isForward] : graph[u]) { + if (seen[v]) + continue; + seen[v] = true; + res += minEdgeReversals(graph, v, seen, mem) + (isForward ? 0 : 1); + } + return mem[u] = res; + } + + void dfs(const vector>>& graph, int u, + vector& seen, vector& ans) { + seen[u] = true; + for (const auto& [v, isForward] : graph[u]) { + if (seen[v]) + continue; + seen[v] = true; + ans[v] = ans[u] + (isForward ? 1 : -1); + dfs(graph, v, seen, ans); + } + } +}; diff --git a/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.java b/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.java new file mode 100644 index 00000000000..83fd828e8c3 --- /dev/null +++ b/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.java @@ -0,0 +1,55 @@ +class Solution { + public int[] minEdgeReversals(int n, int[][] edges) { + int[] ans = new int[n]; + List>[] graph = new List[n]; + boolean[] seen = new boolean[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(new Pair<>(v, /*isForward=*/true)); + graph[v].add(new Pair<>(u, /*isForward=*/false)); + } + + Integer[] mem = new Integer[n]; + ans[0] = minEdgeReversals(graph, 0, seen, mem); + seen = new boolean[n]; + dfs(graph, 0, seen, ans); + return ans; + } + + // Returns the minimum number of edge reversals so node u can reach every + // node in its subtree. + private int minEdgeReversals(List>[] graph, int u, boolean[] seen, + Integer[] mem) { + if (mem[u] != null) + return mem[u]; + int res = 0; + seen[u] = true; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final boolean isForward = pair.getValue(); + if (seen[v]) + continue; + seen[v] = true; + res += minEdgeReversals(graph, v, seen, mem) + (isForward ? 0 : 1); + } + return mem[u] = res; + } + + private void dfs(List>[] graph, int u, boolean[] seen, int[] ans) { + seen[u] = true; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final boolean isForward = pair.getValue(); + if (seen[v]) + continue; + seen[v] = true; + ans[v] = ans[u] + (isForward ? 1 : -1); + dfs(graph, v, seen, ans); + } + } +} diff --git a/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.py b/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.py new file mode 100644 index 00000000000..457b05b1219 --- /dev/null +++ b/solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.py @@ -0,0 +1,38 @@ +class Solution: + def minEdgeReversals(self, n: int, edges: List[List[int]]) -> List[int]: + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append((v, True)) # 1 means (u -> v) + graph[v].append((u, False)) # 0 means (v <- u) + + seen = {0} + + @functools.lru_cache(None) + def dp(u: int) -> int: + """ + Returns the minimum number of edge reversals so node u can reach every + node in its subtree. + """ + res = 0 + for v, isForward in graph[u]: + if v in seen: + continue + seen.add(v) + res += dp(v) + (0 if isForward else 1) + return res + + ans = [0] * n + ans[0] = dp(0) + + def dfs(u: int) -> None: + for v, isForward in graph[u]: + if v in seen: + continue + seen.add(v) + ans[v] = ans[u] + (1 if isForward else -1) + dfs(v) + + seen = {0} + dfs(0) + return ans diff --git a/solutions/2859. Sum of Values at Indices With K Set Bits/2859.cpp b/solutions/2859. Sum of Values at Indices With K Set Bits/2859.cpp new file mode 100644 index 00000000000..01aa841298f --- /dev/null +++ b/solutions/2859. Sum of Values at Indices With K Set Bits/2859.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int sumIndicesWithKSetBits(vector& nums, int k) { + int ans = 0; + for (unsigned i = 0; i < nums.size(); ++i) + if (popcount(i) == k) + ans += nums[i]; + return ans; + } +}; diff --git a/solutions/2859. Sum of Values at Indices With K Set Bits/2859.java b/solutions/2859. Sum of Values at Indices With K Set Bits/2859.java new file mode 100644 index 00000000000..843e0941a8f --- /dev/null +++ b/solutions/2859. Sum of Values at Indices With K Set Bits/2859.java @@ -0,0 +1,9 @@ +class Solution { + public int sumIndicesWithKSetBits(List nums, int k) { + int ans = 0; + for (int i = 0; i < nums.size(); ++i) + if (Integer.bitCount(i) == k) + ans += nums.get(i); + return ans; + } +} diff --git a/solutions/2859. Sum of Values at Indices With K Set Bits/2859.py b/solutions/2859. Sum of Values at Indices With K Set Bits/2859.py new file mode 100644 index 00000000000..07efd82ae29 --- /dev/null +++ b/solutions/2859. Sum of Values at Indices With K Set Bits/2859.py @@ -0,0 +1,4 @@ +class Solution: + def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int: + return sum(num for i, num in enumerate(nums) + if i.bit_count() == k) diff --git a/solutions/286. Walls and Gates/286.cpp b/solutions/286. Walls and Gates/286.cpp new file mode 100644 index 00000000000..685e49b089d --- /dev/null +++ b/solutions/286. Walls and Gates/286.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + void wallsAndGates(vector>& rooms) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = rooms.size(); + const int n = rooms[0].size(); + queue> q; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (rooms[i][j] == 0) + q.emplace(i, j); + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (rooms[x][y] != INT_MAX) + continue; + rooms[x][y] = rooms[i][j] + 1; + q.emplace(x, y); + } + } + } +}; diff --git a/solutions/286. Walls and Gates/286.java b/solutions/286. Walls and Gates/286.java new file mode 100644 index 00000000000..caf76246de3 --- /dev/null +++ b/solutions/286. Walls and Gates/286.java @@ -0,0 +1,29 @@ +class Solution { + public void wallsAndGates(int[][] rooms) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = rooms.length; + final int n = rooms[0].length; + Queue q = new ArrayDeque<>(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (rooms[i][j] == 0) + q.offer(new int[] {i, j}); + + while (!q.isEmpty()) { + int[] p = q.poll(); + final int i = p[0]; + final int j = p[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (rooms[x][y] != Integer.MAX_VALUE) + continue; + rooms[x][y] = rooms[i][j] + 1; + q.offer(new int[] {x, y}); + } + } + } +} diff --git a/solutions/286. Walls and Gates/286.py b/solutions/286. Walls and Gates/286.py new file mode 100644 index 00000000000..1a5eadebbf0 --- /dev/null +++ b/solutions/286. Walls and Gates/286.py @@ -0,0 +1,24 @@ +class Solution: + def wallsAndGates(self, rooms: List[List[int]]) -> None: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + kInf = 2**31 - 1 + m = len(rooms) + n = len(rooms[0]) + q = collections.deque() + + for i in range(m): + for j in range(n): + if rooms[i][j] == 0: + q.append((i, j)) + + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if rooms[x][y] != kInf: + continue + rooms[x][y] = rooms[i][j] + 1 + q.append((x, y)) diff --git a/solutions/2860. Happy Students/2860.cpp b/solutions/2860. Happy Students/2860.cpp new file mode 100644 index 00000000000..00b2af4f2bd --- /dev/null +++ b/solutions/2860. Happy Students/2860.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countWays(vector& nums) { + nums.push_back(-1); + nums.push_back(INT_MAX); + ranges::sort(nums); + + int ans = 0; + + // i := the number of the selected numbers + for (int i = 0; i + 1 < nums.size(); ++i) + if (nums[i] < i && i < nums[i + 1]) + ++ans; + + return ans; + } +}; diff --git a/solutions/2860. Happy Students/2860.java b/solutions/2860. Happy Students/2860.java new file mode 100644 index 00000000000..2227ade88be --- /dev/null +++ b/solutions/2860. Happy Students/2860.java @@ -0,0 +1,16 @@ +class Solution { + public int countWays(List nums) { + nums.add(-1); + nums.add(Integer.MAX_VALUE); + Collections.sort(nums); + + int ans = 0; + + // i := the number of the selected numbers + for (int i = 0; i + 1 < nums.size(); ++i) + if (nums.get(i) < i && i < nums.get(i + 1)) + ++ans; + + return ans; + } +} diff --git a/solutions/2860. Happy Students/2860.py b/solutions/2860. Happy Students/2860.py new file mode 100644 index 00000000000..a7645dace6b --- /dev/null +++ b/solutions/2860. Happy Students/2860.py @@ -0,0 +1,5 @@ +class Solution: + def countWays(self, nums: List[int]) -> int: + return sum(a < i < b + for i, (a, b) in # i := the number of the selected numbers + enumerate(itertools.pairwise([-1] + sorted(nums) + [math.inf]))) diff --git a/solutions/2861. Maximum Number of Alloys/2861.cpp b/solutions/2861. Maximum Number of Alloys/2861.cpp new file mode 100644 index 00000000000..587ead7f832 --- /dev/null +++ b/solutions/2861. Maximum Number of Alloys/2861.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int maxNumberOfAlloys(int n, int k, int budget, + vector>& composition, vector& stock, + vector& cost) { + int l = 1; + int r = 1'000'000'000; + + while (l < r) { + const int m = (l + r) / 2; + if (isPossible(n, budget, composition, stock, cost, m)) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + private: + // Returns true if it's possible to create `m` alloys by using any machine. + bool isPossible(int n, int budget, const vector>& composition, + const vector& stock, const vector& costs, int m) { + // Try all the possible machines. + for (const vector& machine : composition) { + long requiredMoney = 0; + for (int j = 0; j < n; ++j) { + const long requiredUnits = + max(0L, static_cast(machine[j]) * m - stock[j]); + requiredMoney += static_cast(requiredUnits) * costs[j]; + } + if (requiredMoney <= budget) + return true; + } + return false; + } +}; diff --git a/solutions/2861. Maximum Number of Alloys/2861.java b/solutions/2861. Maximum Number of Alloys/2861.java new file mode 100644 index 00000000000..86a82da59c8 --- /dev/null +++ b/solutions/2861. Maximum Number of Alloys/2861.java @@ -0,0 +1,33 @@ +class Solution { + public int maxNumberOfAlloys(int n, int k, int budget, List> composition, + List stock, List cost) { + int l = 1; + int r = 1_000_000_000; + + while (l < r) { + final int m = (l + r) / 2; + if (isPossible(n, budget, composition, stock, cost, m)) + l = m + 1; + else + r = m; + } + + return l - 1; + } + + // Returns true if it's possible to create `m` alloys by using any machine. + private boolean isPossible(int n, int budget, List> composition, + List stock, List costs, int m) { + // Try all the possible machines. + for (List machine : composition) { + long requiredMoney = 0; + for (int j = 0; j < n; ++j) { + final long requiredUnits = Math.max(0L, (long) machine.get(j) * m - stock.get(j)); + requiredMoney += requiredUnits * costs.get(j); + } + if (requiredMoney <= budget) + return true; + } + return false; + } +} diff --git a/solutions/2861. Maximum Number of Alloys/2861.py b/solutions/2861. Maximum Number of Alloys/2861.py new file mode 100644 index 00000000000..db57669771c --- /dev/null +++ b/solutions/2861. Maximum Number of Alloys/2861.py @@ -0,0 +1,27 @@ +class Solution: + def maxNumberOfAlloys(self, n: int, k: int, budget: int, + composition: List[List[int]], stock: List[int], + costs: List[int]) -> int: + l = 1 + r = 1_000_000_000 + + def isPossible(m: int) -> bool: + """Returns True if it's possible to create `m` alloys by using any machine.""" + # Try all the possible machines. + for machine in composition: + requiredMoney = 0 + for j in range(n): + requiredUnits = max(0, machine[j] * m - stock[j]) + requiredMoney += requiredUnits * costs[j] + if requiredMoney <= budget: + return True + return False + + while l < r: + m = (l + r) // 2 + if isPossible(m): + l = m + 1 + else: + r = m + + return l - 1 diff --git a/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.cpp b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.cpp new file mode 100644 index 00000000000..1fa8e539925 --- /dev/null +++ b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + long long maximumSum(vector& nums) { + long ans = 0; + + for (int oddPower = 1; oddPower <= nums.size(); ++oddPower) { + long sum = 0; + for (int num = 1; num * num * oddPower <= nums.size(); ++num) + sum += nums[oddPower * num * num - 1]; + ans = max(ans, sum); + } + + return ans; + } +}; diff --git a/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.java b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.java new file mode 100644 index 00000000000..9526097501f --- /dev/null +++ b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.java @@ -0,0 +1,14 @@ +class Solution { + public long maximumSum(List nums) { + long ans = 0; + + for (int oddPower = 1; oddPower <= nums.size(); ++oddPower) { + long sum = 0; + for (int num = 1; num * num * oddPower <= nums.size(); ++num) + sum += nums.get(oddPower * num * num - 1); + ans = Math.max(ans, sum); + } + + return ans; + } +} diff --git a/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.py b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.py new file mode 100644 index 00000000000..97b2a4cdfbc --- /dev/null +++ b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.py @@ -0,0 +1,13 @@ +class Solution: + def maximumSum(self, nums: List[int]) -> int: + ans = 0 + + for oddPower in range(1, len(nums) + 1): + summ = 0 + for num in range(1, len(nums) + 1): + if num * num * oddPower > len(nums): + break + summ += nums[oddPower * num * num - 1] + ans = max(ans, summ) + + return ans diff --git a/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.cpp b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.cpp new file mode 100644 index 00000000000..f4e320f6c60 --- /dev/null +++ b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + long long maximumSum(vector& nums) { + long ans = 0; + unordered_map oddPowerToSum; + + for (int i = 0; i < nums.size(); ++i) { + const int oddPower = divideSquares(i + 1); + ans = max(ans, oddPowerToSum[oddPower] += nums[i]); + } + + return ans; + } + + private: + int divideSquares(int val) { + for (int num = 2; num * num <= val; ++num) + while (val % (num * num) == 0) + val /= num * num; + return val; + } +}; diff --git a/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.java b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.java new file mode 100644 index 00000000000..71fca56239a --- /dev/null +++ b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.java @@ -0,0 +1,20 @@ +class Solution { + public long maximumSum(List nums) { + long ans = 0; + HashMap oddPowerToSum = new HashMap<>(); + + for (int i = 0; i < nums.size(); ++i) { + final int oddPower = divideSquares(i + 1); + ans = Math.max(ans, oddPowerToSum.merge(oddPower, (long) nums.get(i), Long::sum)); + } + + return ans; + } + + private int divideSquares(int val) { + for (int num = 2; num * num <= val; ++num) + while (val % (num * num) == 0) + val /= num * num; + return val; + } +} diff --git a/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.py b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.py new file mode 100644 index 00000000000..3dbc3ef85e0 --- /dev/null +++ b/solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862.py @@ -0,0 +1,17 @@ +class Solution: + def maximumSum(self, nums: List[int]) -> int: + ans = 0 + oddPowerToSum = collections.Counter() + + def divideSquares(val: int) -> int: + for num in range(2, val + 1): + while val % (num * num) == 0: + val //= (num * num) + return val + + for i, num in enumerate(nums): + oddPower = divideSquares(i + 1) + oddPowerToSum[oddPower] += num + ans = max(ans, oddPowerToSum[oddPower]) + + return ans diff --git a/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.cpp b/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.cpp new file mode 100644 index 00000000000..686a31f016f --- /dev/null +++ b/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maxSubarrayLength(vector& nums) { + int ans = 0; + stack stack; + + for (int i = nums.size() - 1; i >= 0; --i) + // If nums[stack.top()] <= nums[i], stack.top() is better than i. + // So, no need to push it. + if (stack.empty() || nums[stack.top()] > nums[i]) + stack.push(i); + + for (int i = 0; i < nums.size(); ++i) + while (!stack.empty() && num > nums[stack.top()]) + ans = max(ans, stack.top() - i + 1), stack.pop(); + + return ans; + } +}; diff --git a/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.java b/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.java new file mode 100644 index 00000000000..e1f40dedabf --- /dev/null +++ b/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.java @@ -0,0 +1,18 @@ +class Solution { + public int maxSubarrayLength(int[] nums) { + int ans = 0; + Deque stack = new ArrayDeque<>(); + + for (int i = nums.length - 1; i >= 0; --i) + // If nums[stack.peek()] <= nums[i], stack.peek() is better than i. + // So, no need to push it. + if (stack.isEmpty() || nums[stack.peek()] > nums[i]) + stack.push(i); + + for (int i = 0; i < nums.length; ++i) + while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) + ans = Math.max(ans, stack.pop() - i + 1); + + return ans; + } +} diff --git a/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.py b/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.py new file mode 100644 index 00000000000..5a16f595ded --- /dev/null +++ b/solutions/2863. Maximum Length of Semi-Decreasing Subarrays/2863.py @@ -0,0 +1,16 @@ +class Solution: + def maxSubarrayLength(self, nums: List[int]) -> int: + ans = 0 + stack = [] + + for i in range(len(nums) - 1, -1, -1): + # If nums[stack[-1]] <= nums[i], stack[-1] is better than i. + # So, no need to append it. + if not stack or nums[stack[-1]] > nums[i]: + stack.append(i) + + for i, num in enumerate(nums): + while stack and num > nums[stack[-1]]: + ans = max(ans, stack.pop() - i + 1) + + return ans diff --git a/solutions/2864. Maximum Odd Binary Number/2864.cpp b/solutions/2864. Maximum Odd Binary Number/2864.cpp new file mode 100644 index 00000000000..b2c63150e14 --- /dev/null +++ b/solutions/2864. Maximum Odd Binary Number/2864.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + string maximumOddBinaryNumber(string s) { + const int zeros = ranges::count(s, '0'); + const int ones = s.length() - zeros; + return string(ones - 1, '1') + string(zeros, '0') + '1'; + } +}; diff --git a/solutions/2864. Maximum Odd Binary Number/2864.java b/solutions/2864. Maximum Odd Binary Number/2864.java new file mode 100644 index 00000000000..5d5ef9da974 --- /dev/null +++ b/solutions/2864. Maximum Odd Binary Number/2864.java @@ -0,0 +1,7 @@ +class Solution { + public String maximumOddBinaryNumber(String s) { + final int zeros = (int) s.chars().filter(c -> c == '0').count(); + final int ones = s.length() - zeros; + return "1".repeat(ones - 1) + "0".repeat(zeros) + "1"; + } +} diff --git a/solutions/2864. Maximum Odd Binary Number/2864.py b/solutions/2864. Maximum Odd Binary Number/2864.py new file mode 100644 index 00000000000..f44cdb5879c --- /dev/null +++ b/solutions/2864. Maximum Odd Binary Number/2864.py @@ -0,0 +1,3 @@ +class Solution: + def maximumOddBinaryNumber(self, s: str) -> str: + return '1' * (s.count('1') - 1) + '0' * s.count('0') + '1' diff --git a/solutions/2865. Beautiful Towers I/2865.cpp b/solutions/2865. Beautiful Towers I/2865.cpp new file mode 100644 index 00000000000..0c7617190a2 --- /dev/null +++ b/solutions/2865. Beautiful Towers I/2865.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + long long maximumSumOfHeights(vector& maxHeights) { + const int n = maxHeights.size(); + vector maxSum(n); // maxSum[i] := the maximum sum with peak i + + stack stack{{-1}}; + long summ = 0; + + for (int i = 0; i < n; ++i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] = summ; + } + + stack = std::stack{{n}}; + summ = 0; + + for (int i = n - 1; i >= 0; --i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] += summ - maxHeights[i]; + } + + return ranges::max(maxSum); + } + + private: + long process(stack& stack, vector& maxHeights, int i, long summ) { + while (stack.size() > 1 && maxHeights[stack.top()] > maxHeights[i]) { + int j = stack.top(); + stack.pop(); + // The last abs(j - stack.top()) heights are maxHeights[j]. + summ -= abs(j - stack.top()) * static_cast(maxHeights[j]); + } + // Put abs(i - stack.top()) * maxHeights[i] in `heights`. + summ += abs(i - stack.top()) * static_cast(maxHeights[i]); + stack.push(i); + return summ; + } +}; diff --git a/solutions/2865. Beautiful Towers I/2865.java b/solutions/2865. Beautiful Towers I/2865.java new file mode 100644 index 00000000000..9e8cf45b065 --- /dev/null +++ b/solutions/2865. Beautiful Towers I/2865.java @@ -0,0 +1,37 @@ +class Solution { + public long maximumSumOfHeights(List maxHeights) { + final int n = maxHeights.size(); + long[] maxSum = new long[n]; // maxSum[i] := the maximum sum with peak i + + Deque stack = new ArrayDeque<>(Arrays.asList(-1)); + stack.push(-1); + long summ = 0; + + for (int i = 0; i < n; ++i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] = summ; + } + + stack = new ArrayDeque<>(Arrays.asList(n)); + summ = 0; + + for (int i = n - 1; i >= 0; --i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] += summ - maxHeights.get(i); + } + + return Arrays.stream(maxSum).max().getAsLong(); + } + + private long process(Deque stack, List maxHeights, int i, long summ) { + while (stack.size() > 1 && maxHeights.get(stack.peek()) > maxHeights.get(i)) { + final int j = stack.pop(); + // The last abs(j - stack.peek()) heights are maxHeights.get(j). + summ -= Math.abs(j - stack.peek()) * (long) maxHeights.get(j); + } + // Put abs(i - stack.peek()) `maxHeights.get(i)` in heights. + summ += Math.abs(i - stack.peek()) * (long) maxHeights.get(i); + stack.push(i); + return summ; + } +} diff --git a/solutions/2865. Beautiful Towers I/2865.py b/solutions/2865. Beautiful Towers I/2865.py new file mode 100644 index 00000000000..10082b55f67 --- /dev/null +++ b/solutions/2865. Beautiful Towers I/2865.py @@ -0,0 +1,28 @@ +class Solution: + def maximumSumOfHeights(self, maxHeights: List[int]) -> int: + n = len(maxHeights) + maxSum = [0] * n # maxSum[i] := the maximum sum with peak i + + def process(stack: List[int], i: int, summ: int) -> int: + while len(stack) > 1 and maxHeights[stack[-1]] > maxHeights[i]: + j = stack.pop() + # The last abs(j - stack[-1]) heights are maxHeights[j]. + summ -= abs(j - stack[-1]) * maxHeights[j] + # Put abs(i - stack[-1]) `maxHeight` in heights. + summ += abs(i - stack[-1]) * maxHeights[i] + stack.append(i) + return summ + + stack = [-1] + summ = 0 + for i in range(len(maxHeights)): + summ = process(stack, i, summ) + maxSum[i] = summ + + stack = [n] + summ = 0 + for i in range(n - 1, -1, -1): + summ = process(stack, i, summ) + maxSum[i] += summ - maxHeights[i] + + return max(maxSum) diff --git a/solutions/2866. Beautiful Towers II/2866.cpp b/solutions/2866. Beautiful Towers II/2866.cpp new file mode 100644 index 00000000000..37fbf047e56 --- /dev/null +++ b/solutions/2866. Beautiful Towers II/2866.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + // Same as 2865. Beautiful Towers I + long long maximumSumOfHeights(vector& maxHeights) { + const int n = maxHeights.size(); + vector maxSum(n); // maxSum[i] := the maximum sum with peak i + + stack stack{{-1}}; + long summ = 0; + + for (int i = 0; i < n; ++i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] = summ; + } + + stack = std::stack{{n}}; + summ = 0; + + for (int i = n - 1; i >= 0; --i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] += summ - maxHeights[i]; + } + + return ranges::max(maxSum); + } + + private: + long process(stack& stack, vector& maxHeights, int i, long summ) { + while (stack.size() > 1 && maxHeights[stack.top()] > maxHeights[i]) { + int j = stack.top(); + stack.pop(); + // The last abs(j - stack.top()) heights are maxHeights[j]. + summ -= abs(j - stack.top()) * static_cast(maxHeights[j]); + } + // Put abs(i - stack.top()) * maxHeights[i] in `heights`. + summ += abs(i - stack.top()) * static_cast(maxHeights[i]); + stack.push(i); + return summ; + } +}; diff --git a/solutions/2866. Beautiful Towers II/2866.java b/solutions/2866. Beautiful Towers II/2866.java new file mode 100644 index 00000000000..9f3b9ce7228 --- /dev/null +++ b/solutions/2866. Beautiful Towers II/2866.java @@ -0,0 +1,38 @@ +class Solution { + // Same as 2865. Beautiful Towers I + public long maximumSumOfHeights(List maxHeights) { + final int n = maxHeights.size(); + long[] maxSum = new long[n]; // maxSum[i] := the maximum sum with peak i + + Deque stack = new ArrayDeque<>(Arrays.asList(-1)); + stack.push(-1); + long summ = 0; + + for (int i = 0; i < n; ++i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] = summ; + } + + stack = new ArrayDeque<>(Arrays.asList(n)); + summ = 0; + + for (int i = n - 1; i >= 0; --i) { + summ = process(stack, maxHeights, i, summ); + maxSum[i] += summ - maxHeights.get(i); + } + + return Arrays.stream(maxSum).max().getAsLong(); + } + + private long process(Deque stack, List maxHeights, int i, long summ) { + while (stack.size() > 1 && maxHeights.get(stack.peek()) > maxHeights.get(i)) { + final int j = stack.pop(); + // The last abs(j - stack.peek()) heights are maxHeights.get(j). + summ -= Math.abs(j - stack.peek()) * (long) maxHeights.get(j); + } + // Put abs(i - stack.peek()) `maxHeights.get(i)` in heights. + summ += Math.abs(i - stack.peek()) * (long) maxHeights.get(i); + stack.push(i); + return summ; + } +} diff --git a/solutions/2866. Beautiful Towers II/2866.py b/solutions/2866. Beautiful Towers II/2866.py new file mode 100644 index 00000000000..52630e8f1f8 --- /dev/null +++ b/solutions/2866. Beautiful Towers II/2866.py @@ -0,0 +1,29 @@ +class Solution: + # Same as 2865. Beautiful Towers I + def maximumSumOfHeights(self, maxHeights: List[int]) -> int: + n = len(maxHeights) + maxSum = [0] * n # maxSum[i] := the maximum sum with peak i + + def process(stack: List[int], i: int, summ: int) -> int: + while len(stack) > 1 and maxHeights[stack[-1]] > maxHeights[i]: + j = stack.pop() + # The last abs(j - stack[-1]) heights are maxHeights[j]. + summ -= abs(j - stack[-1]) * maxHeights[j] + # Put abs(i - stack[-1]) `maxHeight` in heights. + summ += abs(i - stack[-1]) * maxHeights[i] + stack.append(i) + return summ + + stack = [-1] + summ = 0 + for i in range(len(maxHeights)): + summ = process(stack, i, summ) + maxSum[i] = summ + + stack = [n] + summ = 0 + for i in range(n - 1, -1, -1): + summ = process(stack, i, summ) + maxSum[i] += summ - maxHeights[i] + + return max(maxSum) diff --git a/solutions/2867. Count Valid Paths in a Tree/2867.cpp b/solutions/2867. Count Valid Paths in a Tree/2867.cpp new file mode 100644 index 00000000000..cf5c6b207c8 --- /dev/null +++ b/solutions/2867. Count Valid Paths in a Tree/2867.cpp @@ -0,0 +1,53 @@ +class Solution { + public: + long long countPaths(int n, vector>& edges) { + long ans = 0; + const vector isPrime = sieveEratosthenes(n + 1); + vector> graph(n + 1); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + dfs(graph, 1, /*prev=*/-1, isPrime, ans); + return ans; + } + + private: + pair dfs(const vector>& graph, int u, int prev, + const vector& isPrime, long& ans) { + long countZeroPrimePath = !isPrime[u]; + long countOnePrimePath = isPrime[u]; + + for (const int v : graph[u]) { + if (v == prev) + continue; + const auto& [countZeroPrimeChildPath, countOnePrimeChildPath] = + dfs(graph, v, u, isPrime, ans); + ans += countZeroPrimePath * countOnePrimeChildPath + + countOnePrimePath * countZeroPrimeChildPath; + if (isPrime[u]) { + countOnePrimePath += countZeroPrimeChildPath; + } else { + countZeroPrimePath += countZeroPrimeChildPath; + countOnePrimePath += countOnePrimeChildPath; + } + } + + return {countZeroPrimePath, countOnePrimePath}; + } + + vector sieveEratosthenes(int n) { + vector isPrime(n, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +}; diff --git a/solutions/2867. Count Valid Paths in a Tree/2867.java b/solutions/2867. Count Valid Paths in a Tree/2867.java new file mode 100644 index 00000000000..ef8695ee7b8 --- /dev/null +++ b/solutions/2867. Count Valid Paths in a Tree/2867.java @@ -0,0 +1,56 @@ +class Solution { + public long countPaths(int n, int[][] edges) { + final boolean[] isPrime = sieveEratosthenes(n + 1); + List[] graph = new List[n + 1]; + + for (int i = 1; i <= n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + dfs(graph, 1, /*prev=*/-1, isPrime); + return ans; + } + + private long ans = 0; + + private Pair dfs(List[] graph, int u, int prev, boolean[] isPrime) { + long countZeroPrimePath = isPrime[u] ? 0 : 1; + long countOnePrimePath = isPrime[u] ? 1 : 0; + + for (final int v : graph[u]) { + if (v == prev) + continue; + Pair pair = dfs(graph, v, u, isPrime); + final long countZeroPrimeChildPath = pair.getKey(); + final long countOnePrimeChildPath = pair.getValue(); + ans += + countZeroPrimePath * countOnePrimeChildPath + countOnePrimePath * countZeroPrimeChildPath; + if (isPrime[u]) { + countOnePrimePath += countZeroPrimeChildPath; + } else { + countZeroPrimePath += countZeroPrimeChildPath; + countOnePrimePath += countOnePrimeChildPath; + } + } + + return new Pair<>(countZeroPrimePath, countOnePrimePath); + } + + private boolean[] sieveEratosthenes(int n) { + boolean[] isPrime = new boolean[n]; + Arrays.fill(isPrime, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +} diff --git a/solutions/2867. Count Valid Paths in a Tree/2867.py b/solutions/2867. Count Valid Paths in a Tree/2867.py new file mode 100644 index 00000000000..2a498f9bea9 --- /dev/null +++ b/solutions/2867. Count Valid Paths in a Tree/2867.py @@ -0,0 +1,41 @@ +class Solution: + def countPaths(self, n: int, edges: List[List[int]]) -> int: + ans = 0 + isPrime = self._sieveEratosthenes(n + 1) + graph = [[] for _ in range(n + 1)] + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + def dfs(u: int, prev: int) -> Tuple[int, int]: + nonlocal ans + countZeroPrimePath = int(not isPrime[u]) + countOnePrimePath = int(isPrime[u]) + + for v in graph[u]: + if v == prev: + continue + countZeroPrimeChildPath, countOnePrimeChildPath = dfs(v, u) + ans += countZeroPrimePath * countOnePrimeChildPath + \ + countOnePrimePath * countZeroPrimeChildPath + if isPrime[u]: + countOnePrimePath += countZeroPrimeChildPath + else: + countZeroPrimePath += countZeroPrimeChildPath + countOnePrimePath += countOnePrimeChildPath + + return countZeroPrimePath, countOnePrimePath + + dfs(1, -1) + return ans + + def _sieveEratosthenes(self, n: int) -> List[bool]: + isPrime = [True] * n + isPrime[0] = False + isPrime[1] = False + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n, i): + isPrime[j] = False + return isPrime diff --git a/solutions/2868. The Wording Game/2868.cpp b/solutions/2868. The Wording Game/2868.cpp new file mode 100644 index 00000000000..2eba94dd368 --- /dev/null +++ b/solutions/2868. The Wording Game/2868.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + bool canAliceWin(vector& a, vector& b) { + // words[0][i] := the biggest word starting with ('a' + i) for Alice + // words[1][i] := the biggest word starting with ('a' + i) for Bob + vector> words(2, vector(26)); + + // For each letter, only the biggest word is useful. + for (const string& word : a) + words[0][word[0] - 'a'] = word; + + for (const string& word : b) + words[1][word[0] - 'a'] = word; + + // Find Alice's smallest word. + int i = 0; + while (words[0][i].empty()) + ++i; + + // Iterate through each letter until we find a winner. + // Start with Alice's turn (0), so it's Bob's turn (1) now. + for (int turn = 1; true; turn = turn ^ 1) + // If the current player has a word that having the letter that is greater + // than the opponent's word, choose it. + if (!words[turn][i].empty() && words[turn][i] > words[turn ^ 1][i]) { + // Choose the current words[turn][i]. + } else if (!words[turn][i + 1].empty()) { + // Choose the next words[turn][i + 1]. + ++i; + } else { + // Game over. If it's Bob's turn, Alice wins, and vice versa. + return turn == 1; + } + } +}; diff --git a/solutions/2868. The Wording Game/2868.java b/solutions/2868. The Wording Game/2868.java new file mode 100644 index 00000000000..bc5e6590245 --- /dev/null +++ b/solutions/2868. The Wording Game/2868.java @@ -0,0 +1,34 @@ +class Solution { + public boolean canAliceWin(String[] a, String[] b) { + // words[0][i] := the biggest word starting with ('a' + i) for Alice + // words[1][i] := the biggest word starting with ('a' + i) for Bob + String[][] words = new String[2][26]; + + // For each letter, only the biggest word is useful. + for (final String word : a) + words[0][word.charAt(0) - 'a'] = word; + + for (final String word : b) + words[1][word.charAt(0) - 'a'] = word; + + // Find Alice's smallest word. + int i = 0; + while (words[0][i] == null) + ++i; + + // Iterate through each letter until we find a winner. + // Start with Alice's turn (0), so it's Bob's turn (1) now. + for (int turn = 1; true; turn = turn ^ 1) + // If the current player has a word that having the letter that is greater + // than the opponent's word, choose it. + if (words[turn][i] != null && words[turn][i].compareTo(words[1 - turn][i]) > 0) { + // Choose the current words[turn][i]. + } else if (words[turn][i + 1] != null) { + // Choose the next words[turn][i + 1]. + ++i; + } else { + // Game over. If it's Bob's turn, Alice wins, and vice versa. + return turn == 1; + } + } +} diff --git a/solutions/2868. The Wording Game/2868.py b/solutions/2868. The Wording Game/2868.py new file mode 100644 index 00000000000..b327e43d807 --- /dev/null +++ b/solutions/2868. The Wording Game/2868.py @@ -0,0 +1,36 @@ +class Solution: + def canAliceWin(self, a: List[str], b: List[str]) -> bool: + # words[0][i] := the biggest word starting with ('a' + i) for Alice + # words[1][i] := the biggest word starting with ('a' + i) for Bob + words = [[''] * 26 for _ in range(2)] + + # For each letter, only the biggest word is useful. + for word in a: + words[0][ord(word[0]) - ord('a')] = word + + for word in b: + words[1][ord(word[0]) - ord('a')] = word + + # Find Alice's smallest word. + i = 0 + while not words[0][i]: + i += 1 + + # 0 := Alice, 1 := Bob + # Start with Alice, so it's Bob's turn now. + turn = 1 + + # Iterate through each letter until we find a winner. + while True: + # If the current player has a word that having the letter that is greater + # than the opponent's word, choose it. + if words[turn][i] and words[turn][i] > words[1 - turn][i]: + # Choose the current words[turn][i]. + pass + elif words[turn][i + 1]: + # Choose the next words[turn][i + 1]. + i += 1 + else: + # Game over. If it's Bob's turn, Alice wins, and vice versa. + return turn == 1 + turn = 1 - turn diff --git a/solutions/2869. Minimum Operations to Collect Elements/2869.cpp b/solutions/2869. Minimum Operations to Collect Elements/2869.cpp new file mode 100644 index 00000000000..2e1f3fe93a2 --- /dev/null +++ b/solutions/2869. Minimum Operations to Collect Elements/2869.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minOperations(vector& nums, int k) { + unordered_set seen; + + for (int i = nums.size() - 1; i >= 0; --i) { + if (nums[i] > k) + continue; + seen.insert(nums[i]); + if (seen.size() == k) + return nums.size() - i; + } + + throw; + } +}; diff --git a/solutions/2869. Minimum Operations to Collect Elements/2869.java b/solutions/2869. Minimum Operations to Collect Elements/2869.java new file mode 100644 index 00000000000..1c537c1bee0 --- /dev/null +++ b/solutions/2869. Minimum Operations to Collect Elements/2869.java @@ -0,0 +1,15 @@ +class Solution { + public int minOperations(List nums, int k) { + Set seen = new HashSet<>(); + + for (int i = nums.size() - 1; i >= 0; --i) { + if (nums.get(i) > k) + continue; + seen.add(nums.get(i)); + if (seen.size() == k) + return nums.size() - i; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2869. Minimum Operations to Collect Elements/2869.py b/solutions/2869. Minimum Operations to Collect Elements/2869.py new file mode 100644 index 00000000000..8c2e2f1a6a6 --- /dev/null +++ b/solutions/2869. Minimum Operations to Collect Elements/2869.py @@ -0,0 +1,10 @@ +class Solution: + def minOperations(self, nums: List[int], k: int) -> int: + seen = set() + + for i, num in enumerate(reversed(nums)): + if num > k: + continue + seen.add(num) + if len(seen) == k: + return i + 1 diff --git a/solutions/287. Find the Duplicate Number/287.cpp b/solutions/287. Find the Duplicate Number/287.cpp new file mode 100644 index 00000000000..cfbe4670649 --- /dev/null +++ b/solutions/287. Find the Duplicate Number/287.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int findDuplicate(vector& nums) { + int slow = nums[nums[0]]; + int fast = nums[nums[nums[0]]]; + + while (slow != fast) { + slow = nums[slow]; + fast = nums[nums[fast]]; + } + + slow = nums[0]; + + while (slow != fast) { + slow = nums[slow]; + fast = nums[fast]; + } + + return slow; + } +}; diff --git a/solutions/287. Find the Duplicate Number/287.java b/solutions/287. Find the Duplicate Number/287.java new file mode 100644 index 00000000000..42ac2bd138e --- /dev/null +++ b/solutions/287. Find the Duplicate Number/287.java @@ -0,0 +1,20 @@ +class Solution { + public int findDuplicate(int[] nums) { + int slow = nums[nums[0]]; + int fast = nums[nums[nums[0]]]; + + while (slow != fast) { + slow = nums[slow]; + fast = nums[nums[fast]]; + } + + slow = nums[0]; + + while (slow != fast) { + slow = nums[slow]; + fast = nums[fast]; + } + + return slow; + } +} diff --git a/solutions/287. Find the Duplicate Number/287.py b/solutions/287. Find the Duplicate Number/287.py new file mode 100644 index 00000000000..cac285cc91f --- /dev/null +++ b/solutions/287. Find the Duplicate Number/287.py @@ -0,0 +1,16 @@ +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + slow = nums[nums[0]] + fast = nums[nums[nums[0]]] + + while slow != fast: + slow = nums[slow] + fast = nums[nums[fast]] + + slow = nums[0] + + while slow != fast: + slow = nums[slow] + fast = nums[fast] + + return slow diff --git a/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.cpp b/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.cpp new file mode 100644 index 00000000000..fad9292af8c --- /dev/null +++ b/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minOperations(vector& nums) { + int ans = 0; + unordered_map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [_, freq] : count) { + // If freq == 3k, need k operations. + // If freq == 3k + 1 = 3*(k - 1) + 2*2, need k + 1 operations. + // If freq == 3k + 2, need k + 1 operations. + if (freq == 1) + return -1; + ans += (freq + 2) / 3; + } + + return ans; + } +}; diff --git a/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.java b/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.java new file mode 100644 index 00000000000..c3b2a4d94bd --- /dev/null +++ b/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.java @@ -0,0 +1,20 @@ +class Solution { + public int minOperations(int[] nums) { + int ans = 0; + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int freq : count.values()) { + // If freq == 3k, need k operations. + // If freq == 3k + 1 = 3*(k - 1) + 2*2, need k + 1 operations. + // If freq == 3k + 2, need k + 1 operations. + if (freq == 1) + return -1; + ans += (freq + 2) / 3; + } + + return ans; + } +} diff --git a/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.py b/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.py new file mode 100644 index 00000000000..f1189d8b243 --- /dev/null +++ b/solutions/2870. Minimum Number of Operations to Make Array Empty/2870.py @@ -0,0 +1,6 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + count = collections.Counter(nums) + if 1 in count.values(): + return -1 + return sum((freq + 2) // 3 for freq in count.values()) diff --git a/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.cpp b/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.cpp new file mode 100644 index 00000000000..7f7a4061cdc --- /dev/null +++ b/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxSubarrays(vector& nums) { + int ans = 0; + int score = 0; + + for (const int num : nums) { + score = score == 0 ? num : score & num; + if (score == 0) + ++ans; + } + + return max(1, ans); + } +}; diff --git a/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.java b/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.java new file mode 100644 index 00000000000..7afe6c74438 --- /dev/null +++ b/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.java @@ -0,0 +1,14 @@ +class Solution { + public int maxSubarrays(int[] nums) { + int ans = 0; + int score = 0; + + for (final int num : nums) { + score = score == 0 ? num : score & num; + if (score == 0) + ++ans; + } + + return Math.max(1, ans); + } +} diff --git a/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.py b/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.py new file mode 100644 index 00000000000..fff5175bc2a --- /dev/null +++ b/solutions/2871. Split Array Into Maximum Number of Subarrays/2871.py @@ -0,0 +1,11 @@ +class Solution: + def maxSubarrays(self, nums: List[int]) -> int: + ans = 0 + score = 0 + + for num in nums: + score = num if score == 0 else score & num + if score == 0: + ans += 1 + + return max(1, ans) diff --git a/solutions/2872. Maximum Number of K-Divisible Components/2872.cpp b/solutions/2872. Maximum Number of K-Divisible Components/2872.cpp new file mode 100644 index 00000000000..37190bbbd02 --- /dev/null +++ b/solutions/2872. Maximum Number of K-Divisible Components/2872.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int maxKDivisibleComponents(int n, vector>& edges, + vector& values, int k) { + int ans = 0; + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + dfs(graph, 0, /*prev=*/-1, values, k, ans); + return ans; + } + + private: + long dfs(const vector>& graph, int u, int prev, + const vector& values, int k, int& ans) { + long treeSum = values[u]; + + for (const int v : graph[u]) + if (v != prev) + treeSum += dfs(graph, v, u, values, k, ans); + + if (treeSum % k == 0) + ++ans; + return treeSum; + } +}; diff --git a/solutions/2872. Maximum Number of K-Divisible Components/2872.java b/solutions/2872. Maximum Number of K-Divisible Components/2872.java new file mode 100644 index 00000000000..f21cb4c79aa --- /dev/null +++ b/solutions/2872. Maximum Number of K-Divisible Components/2872.java @@ -0,0 +1,32 @@ +class Solution { + public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { + List[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + dfs(graph, 0, /*prev=*/-1, values, k); + return ans; + } + + private int ans = 0; + + private long dfs(List[] graph, int u, int prev, int[] values, int k) { + long treeSum = values[u]; + + for (int v : graph[u]) + if (v != prev) + treeSum += dfs(graph, v, u, values, k); + + if (treeSum % k == 0) + ++ans; + return treeSum; + } +} diff --git a/solutions/2872. Maximum Number of K-Divisible Components/2872.py b/solutions/2872. Maximum Number of K-Divisible Components/2872.py new file mode 100644 index 00000000000..7dc63b06f8a --- /dev/null +++ b/solutions/2872. Maximum Number of K-Divisible Components/2872.py @@ -0,0 +1,23 @@ +class Solution: + def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int: + ans = 0 + graph = [[] for _ in range(n)] + + def dfs(u: int, prev: int) -> int: + nonlocal ans + treeSum = values[u] + + for v in graph[u]: + if v != prev: + treeSum += dfs(v, u) + + if treeSum % k == 0: + ans += 1 + return treeSum + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + dfs(0, -1) + return ans diff --git a/solutions/2873. Maximum Value of an Ordered Triplet I/2873.cpp b/solutions/2873. Maximum Value of an Ordered Triplet I/2873.cpp new file mode 100644 index 00000000000..a0f12c6e350 --- /dev/null +++ b/solutions/2873. Maximum Value of an Ordered Triplet I/2873.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + long long maximumTripletValue(vector& nums) { + long ans = 0; + int maxDiff = 0; // max(nums[i] - nums[j]) + int maxNum = 0; // max(nums[i]) + + for (const int num : nums) { + ans = max(ans, static_cast(maxDiff) * num); // num := nums[k] + maxDiff = max(maxDiff, maxNum - num); // num := nums[j] + maxNum = max(maxNum, num); // num := nums[i] + } + + return ans; + } +}; diff --git a/solutions/2873. Maximum Value of an Ordered Triplet I/2873.java b/solutions/2873. Maximum Value of an Ordered Triplet I/2873.java new file mode 100644 index 00000000000..6c049af5f77 --- /dev/null +++ b/solutions/2873. Maximum Value of an Ordered Triplet I/2873.java @@ -0,0 +1,15 @@ +class Solution { + public long maximumTripletValue(int[] nums) { + long ans = 0; + int maxDiff = 0; // max(nums[i] - nums[j]) + int maxNum = 0; // max(nums[i]) + + for (final int num : nums) { + ans = Math.max(ans, (long) maxDiff * num); // num := nums[k] + maxDiff = Math.max(maxDiff, maxNum - num); // num := nums[j] + maxNum = Math.max(maxNum, num); // num := nums[i] + } + + return ans; + } +} diff --git a/solutions/2873. Maximum Value of an Ordered Triplet I/2873.py b/solutions/2873. Maximum Value of an Ordered Triplet I/2873.py new file mode 100644 index 00000000000..5f5177e7a9a --- /dev/null +++ b/solutions/2873. Maximum Value of an Ordered Triplet I/2873.py @@ -0,0 +1,12 @@ +class Solution: + def maximumTripletValue(self, nums: List[int]) -> int: + ans = 0 + maxDiff = 0 # max(nums[i] - nums[j]) + maxNum = 0 # max(nums[i]) + + for num in nums: + ans = max(ans, maxDiff * num) # num := nums[k] + maxDiff = max(maxDiff, maxNum - num) # num := nums[j] + maxNum = max(maxNum, num) # num := nums[i] + + return ans diff --git a/solutions/2874. Maximum Value of an Ordered Triplet II/2874.cpp b/solutions/2874. Maximum Value of an Ordered Triplet II/2874.cpp new file mode 100644 index 00000000000..9ed092e2b84 --- /dev/null +++ b/solutions/2874. Maximum Value of an Ordered Triplet II/2874.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + // Same as 2873. Maximum Value of an Ordered Triplet I + long long maximumTripletValue(vector& nums) { + long ans = 0; + int maxDiff = 0; // max(nums[i] - nums[j]) + int maxNum = 0; // max(nums[i]) + + for (const int num : nums) { + ans = max(ans, static_cast(maxDiff) * num); // num := nums[k] + maxDiff = max(maxDiff, maxNum - num); // num := nums[j] + maxNum = max(maxNum, num); // num := nums[i] + } + + return ans; + } +}; diff --git a/solutions/2874. Maximum Value of an Ordered Triplet II/2874.java b/solutions/2874. Maximum Value of an Ordered Triplet II/2874.java new file mode 100644 index 00000000000..bc858c67c2e --- /dev/null +++ b/solutions/2874. Maximum Value of an Ordered Triplet II/2874.java @@ -0,0 +1,16 @@ +class Solution { + // Same as 2873. Maximum Value of an Ordered Triplet I + public long maximumTripletValue(int[] nums) { + long ans = 0; + int maxDiff = 0; // max(nums[i] - nums[j]) + int maxNum = 0; // max(nums[i]) + + for (final int num : nums) { + ans = Math.max(ans, (long) maxDiff * num); // num := nums[k] + maxDiff = Math.max(maxDiff, maxNum - num); // num := nums[j] + maxNum = Math.max(maxNum, num); // num := nums[i] + } + + return ans; + } +} diff --git a/solutions/2874. Maximum Value of an Ordered Triplet II/2874.py b/solutions/2874. Maximum Value of an Ordered Triplet II/2874.py new file mode 100644 index 00000000000..b68419ab7a8 --- /dev/null +++ b/solutions/2874. Maximum Value of an Ordered Triplet II/2874.py @@ -0,0 +1,13 @@ +class Solution: + # Same as 2873. Maximum Value of an Ordered Triplet I + def maximumTripletValue(self, nums: List[int]) -> int: + ans = 0 + maxDiff = 0 # max(nums[i] - nums[j]) + maxNum = 0 # max(nums[i]) + + for num in nums: + ans = max(ans, maxDiff * num) # num := nums[k] + maxDiff = max(maxDiff, maxNum - num) # num := nums[j] + maxNum = max(maxNum, num) # num := nums[i] + + return ans diff --git a/solutions/2875. Minimum Size Subarray in Infinite Array/2875.cpp b/solutions/2875. Minimum Size Subarray in Infinite Array/2875.cpp new file mode 100644 index 00000000000..a0091a56502 --- /dev/null +++ b/solutions/2875. Minimum Size Subarray in Infinite Array/2875.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minSizeSubarray(vector& nums, int target) { + const long sum = accumulate(nums.begin(), nums.end(), 0L); + const int n = nums.size(); + const int remainingTarget = target % sum; + const int repeatLength = (target / sum) * n; + if (remainingTarget == 0) + return repeatLength; + + int suffixPlusPrefixLength = n; + long prefix = 0; + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < 2 * n; ++i) { + prefix += nums[i % n]; + if (const auto it = prefixToIndex.find(prefix - remainingTarget); + it != prefixToIndex.cend()) + suffixPlusPrefixLength = min(suffixPlusPrefixLength, i - it->second); + prefixToIndex[prefix] = i; + } + + return suffixPlusPrefixLength == n ? -1 + : suffixPlusPrefixLength + repeatLength; + } +}; diff --git a/solutions/2875. Minimum Size Subarray in Infinite Array/2875.java b/solutions/2875. Minimum Size Subarray in Infinite Array/2875.java new file mode 100644 index 00000000000..4977ff0b180 --- /dev/null +++ b/solutions/2875. Minimum Size Subarray in Infinite Array/2875.java @@ -0,0 +1,25 @@ +class Solution { + public int minSizeSubarray(int[] nums, int target) { + final long sum = Arrays.stream(nums).asLongStream().sum(); + final int n = nums.length; + final int remainingTarget = (int) (target % sum); + final int repeatLength = (int) (target / sum) * n; + if (remainingTarget == 0) + return repeatLength; + + int suffixPlusPrefixLength = n; + long prefix = 0; + HashMap prefixToIndex = new HashMap<>(); + prefixToIndex.put(0L, -1); + + for (int i = 0; i < 2 * n; ++i) { + prefix += nums[i % n]; + if (prefixToIndex.containsKey(prefix - remainingTarget)) + suffixPlusPrefixLength = + Math.min(suffixPlusPrefixLength, i - prefixToIndex.get(prefix - remainingTarget)); + prefixToIndex.put(prefix, i); + } + + return suffixPlusPrefixLength == n ? -1 : repeatLength + suffixPlusPrefixLength; + } +} diff --git a/solutions/2875. Minimum Size Subarray in Infinite Array/2875.py b/solutions/2875. Minimum Size Subarray in Infinite Array/2875.py new file mode 100644 index 00000000000..b8c8e83f9b6 --- /dev/null +++ b/solutions/2875. Minimum Size Subarray in Infinite Array/2875.py @@ -0,0 +1,22 @@ +class Solution: + def minSizeSubarray(self, nums: List[int], target: int) -> int: + summ = sum(nums) + n = len(nums) + remainingTarget = target % summ + repeatLength = (target // summ) * n + if remainingTarget == 0: + return repeatLength + + suffixPlusPrefixLength = n + prefix = 0 + prefixToIndex = {0: -1} + + for i in range(2 * n): + prefix += nums[i % n] + if prefix - remainingTarget in prefixToIndex: + suffixPlusPrefixLength = min( + suffixPlusPrefixLength, + i - prefixToIndex[prefix - remainingTarget]) + prefixToIndex[prefix] = i + + return -1 if suffixPlusPrefixLength == n else suffixPlusPrefixLength + repeatLength diff --git a/solutions/2876. Count Visited Nodes in a Directed Graph/2876.cpp b/solutions/2876. Count Visited Nodes in a Directed Graph/2876.cpp new file mode 100644 index 00000000000..8db79fc1135 --- /dev/null +++ b/solutions/2876. Count Visited Nodes in a Directed Graph/2876.cpp @@ -0,0 +1,56 @@ +class Solution { + public: + vector countVisitedNodes(vector& edges) { + const int n = edges.size(); + vector ans(n); + vector inDegrees(n); + vector seen(n); + queue q; + stack stack; + + for (const int v : edges) + ++inDegrees[v]; + + // Perform topological sorting. + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + // Push non-cyclic nodes to stack. + while (!q.empty()) { + const int u = q.front(); + q.pop(); + if (--inDegrees[edges[u]] == 0) + q.push(edges[u]); + stack.push(u); + seen[u] = true; + } + + // Fill the length of cyclic nodes. + for (int i = 0; i < n; ++i) + if (!seen[i]) + fillCycle(edges, i, seen, ans); + + // Fill the length of non-cyclic nodes. + while (!stack.empty()) { + const int u = stack.top(); + stack.pop(); + ans[u] = ans[edges[u]] + 1; + } + + return ans; + } + + private: + void fillCycle(const vector& edges, int start, vector& seen, + vector& ans) { + int cycleLength = 0; + for (int u = start; !seen[u]; u = edges[u]) { + ++cycleLength; + seen[u] = true; + } + ans[start] = cycleLength; + for (int u = edges[start]; u != start; u = edges[u]) + ans[u] = cycleLength; + } +}; diff --git a/solutions/2876. Count Visited Nodes in a Directed Graph/2876.java b/solutions/2876. Count Visited Nodes in a Directed Graph/2876.java new file mode 100644 index 00000000000..ef7fbe6549d --- /dev/null +++ b/solutions/2876. Count Visited Nodes in a Directed Graph/2876.java @@ -0,0 +1,51 @@ +class Solution { + public int[] countVisitedNodes(List edges) { + final int n = edges.size(); + int[] ans = new int[n]; + int[] inDegrees = new int[n]; + boolean[] seen = new boolean[n]; + Queue q = new ArrayDeque<>(); + Stack stack = new Stack<>(); + + for (int v : edges) + ++inDegrees[v]; + + // Perform topological sorting. + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.add(i); + + // Push non-cyclic nodes to stack. + while (!q.isEmpty()) { + int u = q.poll(); + if (--inDegrees[edges.get(u)] == 0) + q.add(edges.get(u)); + stack.push(u); + seen[u] = true; + } + + // Fill the length of cyclic nodes. + for (int i = 0; i < n; ++i) + if (!seen[i]) + fillCycle(edges, i, seen, ans); + + // Fill the length of non-cyclic nodes. + while (!stack.isEmpty()) { + int u = stack.pop(); + ans[u] = ans[edges.get(u)] + 1; + } + + return ans; + } + + private void fillCycle(List edges, int start, boolean[] seen, int[] ans) { + int cycleLength = 0; + for (int u = start; !seen[u]; u = edges.get(u)) { + ++cycleLength; + seen[u] = true; + } + ans[start] = cycleLength; + for (int u = edges.get(start); u != start; u = edges.get(u)) + ans[u] = cycleLength; + } +} diff --git a/solutions/2876. Count Visited Nodes in a Directed Graph/2876.py b/solutions/2876. Count Visited Nodes in a Directed Graph/2876.py new file mode 100644 index 00000000000..e194f7bc2a7 --- /dev/null +++ b/solutions/2876. Count Visited Nodes in a Directed Graph/2876.py @@ -0,0 +1,47 @@ +class Solution: + def countVisitedNodes(self, edges: List[int]) -> List[int]: + n = len(edges) + ans = [0] * n + inDegrees = [0] * n + seen = [False] * n + stack = [] + + for v in edges: + inDegrees[v] += 1 + + # Perform topological sorting. + q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) + + # Push non-cyclic nodes to stack. + while q: + u = q.popleft() + inDegrees[edges[u]] -= 1 + if inDegrees[edges[u]] == 0: + q.append(edges[u]) + stack.append(u) + seen[u] = True + + # Fill the length of cyclic nodes. + for i in range(n): + if not seen[i]: + self._fillCycle(edges, i, seen, ans) + + # Fill the length of non-cyclic nodes. + while stack: + u = stack.pop() + ans[u] = ans[edges[u]] + 1 + + return ans + + def _fillCycle(self, edges: List[int], start: int, seen: List[bool], ans: List[int]) -> None: + cycleLength = 0 + u = start + while not seen[u]: + cycleLength += 1 + seen[u] = True + u = edges[u] + ans[start] = cycleLength + u = edges[start] + while u != start: + ans[u] = cycleLength + u = edges[u] diff --git a/solutions/2877. Create a DataFrame from List/2877.py b/solutions/2877. Create a DataFrame from List/2877.py new file mode 100644 index 00000000000..ce25d2be239 --- /dev/null +++ b/solutions/2877. Create a DataFrame from List/2877.py @@ -0,0 +1,5 @@ +import pandas as pd + + +def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: + return pd.DataFrame(student_data, columns=['student_id', 'age']) diff --git a/solutions/2878. Get the Size of a DataFrame/2878.py b/solutions/2878. Get the Size of a DataFrame/2878.py new file mode 100644 index 00000000000..be5a18ba55a --- /dev/null +++ b/solutions/2878. Get the Size of a DataFrame/2878.py @@ -0,0 +1,5 @@ +import pandas as pd + + +def getDataframeSize(players: pd.DataFrame) -> List[int]: + return [*players.shape] diff --git a/solutions/2879. Display the First Three Rows/2879.py b/solutions/2879. Display the First Three Rows/2879.py new file mode 100644 index 00000000000..6ccd5cf1e5d --- /dev/null +++ b/solutions/2879. Display the First Three Rows/2879.py @@ -0,0 +1,5 @@ +import pandas as pd + + +def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame: + return employees.head(3) diff --git a/solutions/288. Unique Word Abbreviation/288.cpp b/solutions/288. Unique Word Abbreviation/288.cpp new file mode 100644 index 00000000000..9eba616e69c --- /dev/null +++ b/solutions/288. Unique Word Abbreviation/288.cpp @@ -0,0 +1,28 @@ +class ValidWordAbbr { + public: + ValidWordAbbr(vector& dictionary) { + dict = unordered_set(dictionary.begin(), dictionary.end()); + + for (const string& word : dict) { + const string& abbr = getAbbr(word); + abbrUnique[abbr] = !abbrUnique.contains(abbr); + } + } + + bool isUnique(string word) { + const string& abbr = getAbbr(word); + return !abbrUnique.contains(abbr) || + abbrUnique[abbr] && dict.contains(word); + } + + private: + unordered_set dict; + unordered_map abbrUnique; // T := unique, F := not unique + + string getAbbr(const string& s) { + const int n = s.length(); + if (n <= 2) + return s; + return s[0] + to_string(n - 2) + s.back(); + } +}; diff --git a/solutions/288. Unique Word Abbreviation/288.java b/solutions/288. Unique Word Abbreviation/288.java new file mode 100644 index 00000000000..cc9f6219e4b --- /dev/null +++ b/solutions/288. Unique Word Abbreviation/288.java @@ -0,0 +1,26 @@ +class ValidWordAbbr { + public ValidWordAbbr(String[] dictionary) { + dict = new HashSet<>(Arrays.asList(dictionary)); + + for (final String word : dict) { + final String abbr = getAbbr(word); + abbrUnique.put(abbr, !abbrUnique.containsKey(abbr)); + } + } + + public boolean isUnique(String word) { + final String abbr = getAbbr(word); + final Boolean hasAbbr = abbrUnique.get(abbr); + return hasAbbr == null || hasAbbr && dict.contains(word); + } + + private Set dict; + private Map abbrUnique = new HashMap<>(); // T := unique, F := not unique + + private String getAbbr(final String s) { + final int n = s.length(); + if (n <= 2) + return s; + return s.charAt(0) + Integer.toString(n - 2) + s.charAt(n - 1); + } +} diff --git a/solutions/288. Unique Word Abbreviation/288.py b/solutions/288. Unique Word Abbreviation/288.py new file mode 100644 index 00000000000..1ada8d7f1ff --- /dev/null +++ b/solutions/288. Unique Word Abbreviation/288.py @@ -0,0 +1,19 @@ +class ValidWordAbbr: + def __init__(self, dictionary: List[str]): + self.dict = set(dictionary) + # T := unique, F := not unique + self.abbrUnique = {} + + for word in self.dict: + abbr = self._getAbbr(word) + self.abbrUnique[abbr] = abbr not in self.abbrUnique + + def isUnique(self, word: str) -> bool: + abbr = self._getAbbr(word) + return abbr not in self.abbrUnique or self.abbrUnique[abbr] and word in self.dict + + def _getAbbr(self, s: str) -> str: + n = len(s) + if n <= 2: + return s + return s[0] + str(n - 2) + s[-1] diff --git a/solutions/2880. Select Data/2880.py b/solutions/2880. Select Data/2880.py new file mode 100644 index 00000000000..4242aae2417 --- /dev/null +++ b/solutions/2880. Select Data/2880.py @@ -0,0 +1,5 @@ +import pandas as pd + + +def selectData(students: pd.DataFrame) -> pd.DataFrame: + return students.loc[students['student_id'] == 101, ['name', 'age']] diff --git a/solutions/2881. Create a New Column/2881.py b/solutions/2881. Create a New Column/2881.py new file mode 100644 index 00000000000..a8a465b49f8 --- /dev/null +++ b/solutions/2881. Create a New Column/2881.py @@ -0,0 +1,6 @@ +import pandas as pd + + +def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: + employees['bonus'] = employees['salary'] * 2 + return employees diff --git a/solutions/2882. Drop Duplicate Rows/2882.py b/solutions/2882. Drop Duplicate Rows/2882.py new file mode 100644 index 00000000000..0ce17102aaa --- /dev/null +++ b/solutions/2882. Drop Duplicate Rows/2882.py @@ -0,0 +1,6 @@ +import pandas as pd + + +def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: + customers.drop_duplicates(subset='email', keep='first', inplace=True) + return customers diff --git a/solutions/2883. Drop Missing Data/2883.py b/solutions/2883. Drop Missing Data/2883.py new file mode 100644 index 00000000000..9b42029bef2 --- /dev/null +++ b/solutions/2883. Drop Missing Data/2883.py @@ -0,0 +1,6 @@ +import pandas as pd + + +def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: + students.dropna(subset=['name'], inplace=True) + return students diff --git a/solutions/2884. Modify Columns/2884.py b/solutions/2884. Modify Columns/2884.py new file mode 100644 index 00000000000..282780d5d0b --- /dev/null +++ b/solutions/2884. Modify Columns/2884.py @@ -0,0 +1,6 @@ +import pandas as pd + + +def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame: + employees['salary'] = employees['salary'] * 2 + return employees diff --git a/solutions/2885. Rename Columns/2885.py b/solutions/2885. Rename Columns/2885.py new file mode 100644 index 00000000000..4afd8a68ed5 --- /dev/null +++ b/solutions/2885. Rename Columns/2885.py @@ -0,0 +1,12 @@ +import pandas as pd + + +def renameColumns(students: pd.DataFrame) -> pd.DataFrame: + return students.rename( + columns={ + "id": "student_id", + "first": "first_name", + "last": "last_name", + "age": "age_in_years", + } + ) diff --git a/solutions/2886. Change Data Type/2886.py b/solutions/2886. Change Data Type/2886.py new file mode 100644 index 00000000000..b76553d73e1 --- /dev/null +++ b/solutions/2886. Change Data Type/2886.py @@ -0,0 +1,5 @@ +import pandas as pd + + +def changeDatatype(students: pd.DataFrame) -> pd.DataFrame: + return students.astype({'grade': int}) diff --git a/solutions/2887. Fill Missing Data/2887.py b/solutions/2887. Fill Missing Data/2887.py new file mode 100644 index 00000000000..09bb01e8629 --- /dev/null +++ b/solutions/2887. Fill Missing Data/2887.py @@ -0,0 +1,6 @@ +import pandas as pd + + +def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame: + products['quantity'].fillna(0, inplace=True) + return products diff --git a/solutions/2888. Reshape Data: Concatenate/2888.py b/solutions/2888. Reshape Data: Concatenate/2888.py new file mode 100644 index 00000000000..685204dbf21 --- /dev/null +++ b/solutions/2888. Reshape Data: Concatenate/2888.py @@ -0,0 +1,5 @@ +import pandas as pd + + +def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame: + return pd.concat([df1, df2], axis=0) diff --git a/solutions/2889. Reshape Data: Pivot/2889.py b/solutions/2889. Reshape Data: Pivot/2889.py new file mode 100644 index 00000000000..35fd7809fcd --- /dev/null +++ b/solutions/2889. Reshape Data: Pivot/2889.py @@ -0,0 +1,10 @@ +import pandas as pd + + +def pivotTable(weather: pd.DataFrame) -> pd.DataFrame: + return weather.pivot_table( + index='month', + columns='city', + values='temperature', + aggfunc='max', + ) diff --git a/solutions/289. Game of Life/289.cpp b/solutions/289. Game of Life/289.cpp new file mode 100644 index 00000000000..ff46fe8bee2 --- /dev/null +++ b/solutions/289. Game of Life/289.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + void gameOfLife(vector>& board) { + const int m = board.size(); + const int n = board[0].size(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + int ones = 0; + for (int x = max(0, i - 1); x < min(m, i + 2); ++x) + for (int y = max(0, j - 1); y < min(n, j + 2); ++y) + ones += board[x][y] & 1; + // Any live cell with two or three live neighbors lives on to the next + // generation. + if (board[i][j] == 1 && (ones == 3 || ones == 4)) + board[i][j] |= 0b10; + // Any dead cell with exactly three live neighbors becomes a live cell, + // as if by reproduction. + if (board[i][j] == 0 && ones == 3) + board[i][j] |= 0b10; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + board[i][j] >>= 1; + } +}; diff --git a/solutions/289. Game of Life/289.java b/solutions/289. Game of Life/289.java new file mode 100644 index 00000000000..e7df458aeb0 --- /dev/null +++ b/solutions/289. Game of Life/289.java @@ -0,0 +1,26 @@ +class Solution { + public void gameOfLife(int[][] board) { + final int m = board.length; + final int n = board[0].length; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + int ones = 0; + for (int x = Math.max(0, i - 1); x < Math.min(m, i + 2); ++x) + for (int y = Math.max(0, j - 1); y < Math.min(n, j + 2); ++y) + ones += board[x][y] & 1; + // Any live cell with two or three live neighbors lives on to the next + // generation. + if (board[i][j] == 1 && (ones == 3 || ones == 4)) + board[i][j] |= 0b10; + // Any dead cell with exactly three live neighbors becomes a live cell, + // as if by reproduction. + if (board[i][j] == 0 && ones == 3) + board[i][j] |= 0b10; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + board[i][j] >>= 1; + } +} diff --git a/solutions/289. Game of Life/289.py b/solutions/289. Game of Life/289.py new file mode 100644 index 00000000000..8992eac6b00 --- /dev/null +++ b/solutions/289. Game of Life/289.py @@ -0,0 +1,23 @@ +class Solution: + def gameOfLife(self, board: List[List[int]]) -> None: + m = len(board) + n = len(board[0]) + + for i in range(m): + for j in range(n): + ones = 0 + for x in range(max(0, i - 1), min(m, i + 2)): + for y in range(max(0, j - 1), min(n, j + 2)): + ones += board[x][y] & 1 + # Any live cell with two or three live neighbors lives on to the next + # generation. + if board[i][j] == 1 and (ones == 3 or ones == 4): + board[i][j] |= 0b10 + # Any dead cell with exactly three live neighbors becomes a live cell, + # as if by reproduction. + if board[i][j] == 0 and ones == 3: + board[i][j] |= 0b10 + + for i in range(m): + for j in range(n): + board[i][j] >>= 1 diff --git a/solutions/2890. Reshape Data: Melt/2890.py b/solutions/2890. Reshape Data: Melt/2890.py new file mode 100644 index 00000000000..fc82cddf7e1 --- /dev/null +++ b/solutions/2890. Reshape Data: Melt/2890.py @@ -0,0 +1,10 @@ +import pandas as pd + + +def meltTable(report: pd.DataFrame) -> pd.DataFrame: + return pd.melt( + report, + id_vars=['product'], + var_name='quarter', + value_name='sales', + ) diff --git a/solutions/2891. Method Chaining/2891.py b/solutions/2891. Method Chaining/2891.py new file mode 100644 index 00000000000..c29787f9a99 --- /dev/null +++ b/solutions/2891. Method Chaining/2891.py @@ -0,0 +1,8 @@ +import pandas as pd + + +def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame: + return animals[animals['weight'] > 100].sort_values( + by='weight', + ascending=False + )[['name']] diff --git a/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.cpp b/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.cpp new file mode 100644 index 00000000000..7401e42aaa6 --- /dev/null +++ b/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minArrayLength(vector& nums, int k) { + int count = 0; + long prod = -1; + + for (const int num : nums) { + if (num == 0) + return 1; + if (prod != -1 && prod * num <= k) { + prod *= num; + } else { + prod = num; + ++count; + } + } + + return count; + } +}; diff --git a/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.java b/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.java new file mode 100644 index 00000000000..031e31de98d --- /dev/null +++ b/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.java @@ -0,0 +1,19 @@ +class Solution { + public int minArrayLength(int[] nums, int k) { + int count = 0; + long prod = -1; + + for (final int num : nums) { + if (num == 0) + return 1; + if (prod != -1 && prod * num <= k) { + prod *= num; + } else { + prod = num; + count++; + } + } + + return count; + } +} diff --git a/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.py b/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.py new file mode 100644 index 00000000000..ffcbca07824 --- /dev/null +++ b/solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.py @@ -0,0 +1,15 @@ +class Solution: + def minArrayLength(self, nums: List[int], k: int) -> int: + count = 0 + prod = -1 + + for num in nums: + if num == 0: + return 1 + if prod != -1 and prod * num <= k: + prod *= num + else: + prod = num + count += 1 + + return count diff --git a/solutions/2893. Calculate Orders Within Each Interval/2893.sql b/solutions/2893. Calculate Orders Within Each Interval/2893.sql new file mode 100644 index 00000000000..4a88502d5a0 --- /dev/null +++ b/solutions/2893. Calculate Orders Within Each Interval/2893.sql @@ -0,0 +1,6 @@ +SELECT + CEIL(minute / 6) AS interval_no, + SUM(order_count) AS total_orders +FROM Orders +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2894. Divisible and Non-divisible Sums Difference/2894.cpp b/solutions/2894. Divisible and Non-divisible Sums Difference/2894.cpp new file mode 100644 index 00000000000..db7fc78be83 --- /dev/null +++ b/solutions/2894. Divisible and Non-divisible Sums Difference/2894.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int differenceOfSums(int n, int m) { + const int sum = (1 + n) * n / 2; + const int num2 = getDivisibleSum(n, m); + const int num1 = sum - num2; + return num1 - num2; + } + + private: + // Returns the sum of all the integers in [1, n] that are divisible by m. + int getDivisibleSum(int n, int m) { + const int last = n / m * m; + if (last == 0) + return 0; + const int first = m; + const int count = (last - first) / m + 1; + return (first + last) * count / 2; + } +}; diff --git a/solutions/2894. Divisible and Non-divisible Sums Difference/2894.java b/solutions/2894. Divisible and Non-divisible Sums Difference/2894.java new file mode 100644 index 00000000000..aa42361b139 --- /dev/null +++ b/solutions/2894. Divisible and Non-divisible Sums Difference/2894.java @@ -0,0 +1,18 @@ +class Solution { + public int differenceOfSums(int n, int m) { + final int sum = (1 + n) * n / 2; + final int num2 = getDivisibleSum(n, m); + final int num1 = sum - num2; + return num1 - num2; + } + + // Returns the sum of all the integers in [1, n] that are divisible by m. + private int getDivisibleSum(int n, int m) { + final int last = n / m * m; + if (last == 0) + return 0; + final int first = m; + final int count = (last - first) / m + 1; + return (first + last) * count / 2; + } +} diff --git a/solutions/2894. Divisible and Non-divisible Sums Difference/2894.py b/solutions/2894. Divisible and Non-divisible Sums Difference/2894.py new file mode 100644 index 00000000000..53fff0e7ff5 --- /dev/null +++ b/solutions/2894. Divisible and Non-divisible Sums Difference/2894.py @@ -0,0 +1,15 @@ +class Solution: + def differenceOfSums(self, n: int, m: int) -> int: + summ = (1 + n) * n // 2 + num2 = self._getDivisibleSum(n, m) + num1 = summ - num2 + return num1 - num2 + + def _getDivisibleSum(self, n: int, m: int) -> int: + """Returns the sum of all the integers in [1, n] that are divisible by m.""" + last = n // m * m + if last == 0: + return 0 + first = m + count = (last - first) // m + 1 + return (first + last) * count // 2 diff --git a/solutions/2895. Minimum Processing Time/2895.cpp b/solutions/2895. Minimum Processing Time/2895.cpp new file mode 100644 index 00000000000..dee5cdfb98e --- /dev/null +++ b/solutions/2895. Minimum Processing Time/2895.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minProcessingTime(vector& processorTime, vector& tasks) { + int ans = 0; + ranges::sort(processorTime); + ranges::sort(tasks, greater<>()); + + // It's optimal to run each 4 longer tasks with a smaller processor time. + // Therefore, for each processor, take the maximum of the sum of the + // processor time and the largest assigned tasks[i]. + for (int i = 0; i < processorTime.size(); ++i) + ans = max(ans, processorTime[i] + tasks[i * 4]); + + return ans; + } +}; diff --git a/solutions/2895. Minimum Processing Time/2895.java b/solutions/2895. Minimum Processing Time/2895.java new file mode 100644 index 00000000000..1401e218c8f --- /dev/null +++ b/solutions/2895. Minimum Processing Time/2895.java @@ -0,0 +1,15 @@ +class Solution { + public int minProcessingTime(List processorTime, List tasks) { + int ans = 0; + Collections.sort(processorTime); + Collections.sort(tasks, Collections.reverseOrder()); + + // It's optimal to run each 4 longer tasks with a smaller processor time. + // Therefore, for each processor, take the maximum of the sum of the + // processor time and the largest assigned tasks[i]. + for (int i = 0; i < processorTime.size(); ++i) + ans = Math.max(ans, processorTime.get(i) + tasks.get(i * 4)); + + return ans; + } +} diff --git a/solutions/2895. Minimum Processing Time/2895.py b/solutions/2895. Minimum Processing Time/2895.py new file mode 100644 index 00000000000..137ff9f7e88 --- /dev/null +++ b/solutions/2895. Minimum Processing Time/2895.py @@ -0,0 +1,4 @@ +class Solution: + def minProcessingTime(self, processorTime: List[int], tasks: List[int]) -> int: + return max(time + task + for (time, task) in zip(sorted(processorTime), sorted(tasks)[::-4])) diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.cpp b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.cpp new file mode 100644 index 00000000000..815cdc778c7 --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int minOperations(string s1, string s2, int x) { + const vector diffIndices = getDiffIndices(s1, s2); + if (diffIndices.empty()) + return 0; + // It's impossible to make two strings equal if there are an odd number of + // differences. + if (diffIndices.size() % 2 == 1) + return -1; + + vector dp(diffIndices.size() + 1, DBL_MAX); + dp.back() = 0; + dp[diffIndices.size() - 1] = x / 2.0; + + for (int i = diffIndices.size() - 2; i >= 0; --i) + dp[i] = min(dp[i + 1] + x / 2.0, + dp[i + 2] + diffIndices[i + 1] - diffIndices[i]); + + return dp[0]; + } + + private: + vector getDiffIndices(const string& s1, const string& s2) { + vector diffIndices; + for (int i = 0; i < s1.length(); ++i) + if (s1[i] != s2[i]) + diffIndices.push_back(i); + return diffIndices; + } +}; diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.java b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.java new file mode 100644 index 00000000000..433179c2540 --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.java @@ -0,0 +1,30 @@ +class Solution { + public int minOperations(String s1, String s2, int x) { + List diffIndices = getDiffIndices(s1, s2); + if (diffIndices.isEmpty()) + return 0; + // It's impossible to make two strings equal if there are odd number of + // differences. + if (diffIndices.size() % 2 == 1) + return -1; + + double[] dp = new double[diffIndices.size() + 1]; + Arrays.fill(dp, Double.MAX_VALUE); + dp[diffIndices.size()] = 0; + dp[diffIndices.size() - 1] = x / 2.0; + + for (int i = diffIndices.size() - 2; i >= 0; --i) + dp[i] = Math.min(dp[i + 1] + x / 2.0, // + dp[i + 2] + diffIndices.get(i + 1) - diffIndices.get(i)); + + return (int) dp[0]; + } + + private List getDiffIndices(final String s1, final String s2) { + List diffIndices = new ArrayList<>(); + for (int i = 0; i < s1.length(); ++i) + if (s1.charAt(i) != s2.charAt(i)) + diffIndices.add(i); + return diffIndices; + } +} diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.py b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.py new file mode 100644 index 00000000000..dcb5c332768 --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.py @@ -0,0 +1,20 @@ +class Solution: + def minOperations(self, s1: str, s2: str, x: int) -> int: + diffIndices = [i for i, (a, b) in enumerate(zip(s1, s2)) + if a != b] + if not diffIndices: + return 0 + # It's impossible to make two strings equal if there are odd number of + # differences. + if len(diffIndices) & 1: + return -1 + + # dp[i] := the minimum cost to correct diffIndices[i:] + dp = [math.inf] * len(diffIndices) + [0] + dp[-2] = x / 2 + + for i in reversed(range(len(diffIndices) - 1)): + dp[i] = min(dp[i + 1] + x / 2, + dp[i + 2] + diffIndices[i + 1] - diffIndices[i]) + + return int(dp[0]) diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.cpp b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.cpp new file mode 100644 index 00000000000..716cb5f3c71 --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minOperations(string s1, string s2, int x) { + const vector diffIndices = getDiffIndices(s1, s2); + if (diffIndices.empty()) + return 0; + // It's impossible to make two strings equal if there are an odd number of + // differences. + if (diffIndices.size() % 2 == 1) + return -1; + + double dp = 0; + double dpNext = x / 2.0; + double dpNextNext = 0; + + for (int i = diffIndices.size() - 2; i >= 0; --i) { + dp = min(dpNext + x / 2.0, + dpNextNext + diffIndices[i + 1] - diffIndices[i]); + dpNextNext = dpNext; + dpNext = dp; + } + + return dp; + } + + private: + vector getDiffIndices(const string& s1, const string& s2) { + vector diffIndices; + for (int i = 0; i < s1.length(); ++i) + if (s1[i] != s2[i]) + diffIndices.push_back(i); + return diffIndices; + } +}; diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.java b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.java new file mode 100644 index 00000000000..8506b287d85 --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.java @@ -0,0 +1,32 @@ +class Solution { + public int minOperations(String s1, String s2, int x) { + List diffIndices = getDiffIndices(s1, s2); + if (diffIndices.isEmpty()) + return 0; + // It's impossible to make two strings equal if there are odd number of + // differences. + if (diffIndices.size() % 2 == 1) + return -1; + + double dp = 0; + double dpNext = x / 2.0; + double dpNextNext = 0; + + for (int i = diffIndices.size() - 2; i >= 0; --i) { + dp = Math.min(dpNext + x / 2.0, // + dpNextNext + diffIndices.get(i + 1) - diffIndices.get(i)); + dpNextNext = dpNext; + dpNext = dp; + } + + return (int) dp; + } + + private List getDiffIndices(final String s1, final String s2) { + List diffIndices = new ArrayList<>(); + for (int i = 0; i < s1.length(); ++i) + if (s1.charAt(i) != s2.charAt(i)) + diffIndices.add(i); + return diffIndices; + } +} diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.py b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.py new file mode 100644 index 00000000000..a86e0f27b42 --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896-3.py @@ -0,0 +1,24 @@ +class Solution: + def minOperations(self, s1: str, s2: str, x: int) -> int: + diffIndices = [i for i, (a, b) in enumerate(zip(s1, s2)) + if a != b] + if not diffIndices: + return 0 + # It's impossible to make two strings equal if there are odd number of + # differences. + if len(diffIndices) & 1: + return -1 + + # dp := the minimum cost to correct diffIndices[i:] + # dpNext := the minimum cost to correct diffIndices[i + 1:] + # dpNextNext := the minimum cost to correct diffIndices[i + 2:] + dpNext = x / 2 + dpNextNext = 0 + + for i in reversed(range(len(diffIndices) - 1)): + dp = min(dpNext + x / 2, + dpNextNext + diffIndices[i + 1] - diffIndices[i]) + dpNextNext = dpNext + dpNext = dp + + return int(dp) diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896.cpp b/solutions/2896. Apply Operations to Make Two Strings Equal/2896.cpp new file mode 100644 index 00000000000..f69c8fa7573 --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int minOperations(string s1, string s2, int x) { + const vector diffIndices = getDiffIndices(s1, s2); + if (diffIndices.empty()) + return 0; + // It's impossible to make two strings equal if there are an odd number of + // differences. + if (diffIndices.size() % 2 == 1) + return -1; + vector mem(diffIndices.size(), -1.0); + return minOperations(diffIndices, 0, x, mem); + } + + private: + // Returns the minimum cost to correct diffIndices[i..n). + double minOperations(const vector& diffIndices, int i, double x, + vector& mem) { + if (i == diffIndices.size()) + return 0; + if (i == diffIndices.size() - 1) + return x / 2; + if (mem[i] != -1.0) + return mem[i]; + return mem[i] = min(minOperations(diffIndices, i + 1, x, mem) + x / 2, + minOperations(diffIndices, i + 2, x, mem) + + diffIndices[i + 1] - diffIndices[i]); + } + + vector getDiffIndices(const string& s1, const string& s2) { + vector diffIndices; + for (int i = 0; i < s1.length(); ++i) + if (s1[i] != s2[i]) + diffIndices.push_back(i); + return diffIndices; + } +}; diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896.java b/solutions/2896. Apply Operations to Make Two Strings Equal/2896.java new file mode 100644 index 00000000000..5600dbf3dcb --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896.java @@ -0,0 +1,33 @@ +class Solution { + public int minOperations(String s1, String s2, int x) { + List diffIndices = getDiffIndices(s1, s2); + if (diffIndices.isEmpty()) + return 0; + // It's impossible to make two strings equal if there are odd number of + // differences. + if (diffIndices.size() % 2 == 1) + return -1; + Double[] mem = new Double[diffIndices.size()]; + return (int) minOperations(diffIndices, 0, x, mem); + } + + private double minOperations(List diffIndices, int i, double x, Double[] mem) { + if (i == diffIndices.size()) + return 0; + if (i == diffIndices.size() - 1) + return x / 2; + if (mem[i] != null) + return mem[i]; + return mem[i] = Math.min(minOperations(diffIndices, i + 1, x, mem) + x / 2, + minOperations(diffIndices, i + 2, x, mem) + diffIndices.get(i + 1) - + diffIndices.get(i)); + } + + private List getDiffIndices(final String s1, final String s2) { + List diffIndices = new ArrayList<>(); + for (int i = 0; i < s1.length(); ++i) + if (s1.charAt(i) != s2.charAt(i)) + diffIndices.add(i); + return diffIndices; + } +} diff --git a/solutions/2896. Apply Operations to Make Two Strings Equal/2896.py b/solutions/2896. Apply Operations to Make Two Strings Equal/2896.py new file mode 100644 index 00000000000..84d92a5fa0f --- /dev/null +++ b/solutions/2896. Apply Operations to Make Two Strings Equal/2896.py @@ -0,0 +1,22 @@ +class Solution: + def minOperations(self, s1: str, s2: str, x: int) -> int: + diffIndices = [i for i, (a, b) in enumerate(zip(s1, s2)) + if a != b] + if not diffIndices: + return 0 + # It's impossible to make two strings equal if there are odd number of + # differences. + if len(diffIndices) & 1: + return -1 + + @functools.lru_cache(None) + def dp(i: int) -> int: + """Returns the minimum cost to correct diffIndices[i..n).""" + if i == len(diffIndices): + return 0 + if i == len(diffIndices) - 1: + return x / 2 + return min(dp(i + 1) + x / 2, + dp(i + 2) + diffIndices[i + 1] - diffIndices[i]) + + return int(dp(0)) diff --git a/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.cpp b/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.cpp new file mode 100644 index 00000000000..2a0894f4bb8 --- /dev/null +++ b/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maxSum(vector& nums, int k) { + constexpr int kMod = 1'000'000'007; + constexpr int kMaxBit = 30; + int ans = 0; + // minIndices[i] := the minimum index in `optimalNums` that the i-th bit + // should be moved to + vector minIndices(kMaxBit); + vector optimalNums(nums.size()); + + for (const int num : nums) + for (int i = 0; i < kMaxBit; ++i) + if (num >> i & 1) + optimalNums[minIndices[i]++] |= 1 << i; + + for (int i = 0; i < k; ++i) + ans = (ans + static_cast(optimalNums[i]) * optimalNums[i]) % kMod; + + return ans; + } +}; diff --git a/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.java b/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.java new file mode 100644 index 00000000000..48d5282e5c8 --- /dev/null +++ b/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.java @@ -0,0 +1,21 @@ +class Solution { + public int maxSum(List nums, int k) { + final int kMod = 1_000_000_007; + final int kMaxBit = 30; + int ans = 0; + // minIndices[i] := the minimum index in `optimalNums` that the i-th bit + // should be moved to + int[] minIndices = new int[kMaxBit]; + int[] optimalNums = new int[nums.size()]; + + for (final int num : nums) + for (int i = 0; i < kMaxBit; i++) + if ((num >> i & 1) == 1) + optimalNums[minIndices[i]++] |= 1 << i; + + for (int i = 0; i < k; i++) + ans = (int) (((long) ans + (long) optimalNums[i] * optimalNums[i]) % kMod); + + return ans; + } +} diff --git a/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.py b/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.py new file mode 100644 index 00000000000..1e88d5df858 --- /dev/null +++ b/solutions/2897. Apply Operations on Array to Maximize Sum of Squares/2897.py @@ -0,0 +1,21 @@ +class Solution: + def maxSum(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + kMaxBit = 30 + ans = 0 + # minIndices[i] := the minimum index in `optimalNums` that the i-th bit + # should be moved to + minIndices = [0] * kMaxBit + optimalNums = [0] * len(nums) + + for num in nums: + for i in range(kMaxBit): + if num >> i & 1: + optimalNums[minIndices[i]] |= 1 << i + minIndices[i] += 1 + + for i in range(k): + ans += optimalNums[i]**2 + ans %= kMod + + return ans diff --git a/solutions/2898. Maximum Linear Stock Score/2898.cpp b/solutions/2898. Maximum Linear Stock Score/2898.cpp new file mode 100644 index 00000000000..97ead2d2201 --- /dev/null +++ b/solutions/2898. Maximum Linear Stock Score/2898.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long maxScore(vector& prices) { + // prices[indexes[j]] - prices[indexes[j - 1]] + // == indexes[j] - indexes[j - 1] + // prices[indexes[j]] - indexes[j] + // == prices[indexes[j - 1]] - indexes[j - 1] + // + // So, elements in the same subsequence must have the same prices[i] - i. + unordered_map groupIdToSum; + + for (int i = 0; i < prices.size(); ++i) + groupIdToSum[prices[i] - i] += prices[i]; + + return ranges::max_element(groupIdToSum, + [](const std::pair& p1, + const std::pair& p2) { + return p1.second < p2.second; + })->second; + } +}; diff --git a/solutions/2898. Maximum Linear Stock Score/2898.java b/solutions/2898. Maximum Linear Stock Score/2898.java new file mode 100644 index 00000000000..219470ec47c --- /dev/null +++ b/solutions/2898. Maximum Linear Stock Score/2898.java @@ -0,0 +1,16 @@ +class Solution { + public long maxScore(int[] prices) { + // prices[indexes[j]] - prices[indexes[j - 1]] + // == indexes[j] - indexes[j - 1] + // prices[indexes[j]] - indexes[j] + // == prices[indexes[j - 1]] - indexes[j - 1] + // + // So, elements in the same subsequence must have the same prices[i] - i. + Map groupIdToSum = new HashMap<>(); + + for (int i = 0; i < prices.length; ++i) + groupIdToSum.merge(prices[i] - i, (long) prices[i], Long::sum); + + return groupIdToSum.values().stream().max(Long::compare).orElse(0L); + } +} diff --git a/solutions/2898. Maximum Linear Stock Score/2898.py b/solutions/2898. Maximum Linear Stock Score/2898.py new file mode 100644 index 00000000000..9fa42bbfc88 --- /dev/null +++ b/solutions/2898. Maximum Linear Stock Score/2898.py @@ -0,0 +1,8 @@ +class Solution: + def maxScore(self, prices: List[int]) -> int: + groupIdToSum = collections.defaultdict(int) + + for i, price in enumerate(prices): + groupIdToSum[price - i] += price + + return max(groupIdToSum.values()) diff --git a/solutions/2899. Last Visited Integers/2899.cpp b/solutions/2899. Last Visited Integers/2899.cpp new file mode 100644 index 00000000000..ee34d073218 --- /dev/null +++ b/solutions/2899. Last Visited Integers/2899.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector lastVisitedIntegers(vector& words) { + vector ans; + vector nums; + int k = 0; + + for (const string& word : words) + if (word == "prev") { + ++k; + ans.push_back(k > nums.size() ? -1 : nums[nums.size() - k]); + } else { + k = 0; + nums.push_back(stoi(word)); + } + + return ans; + } +}; diff --git a/solutions/2899. Last Visited Integers/2899.java b/solutions/2899. Last Visited Integers/2899.java new file mode 100644 index 00000000000..1e11a92c8ac --- /dev/null +++ b/solutions/2899. Last Visited Integers/2899.java @@ -0,0 +1,18 @@ +class Solution { + public List lastVisitedIntegers(List words) { + List ans = new ArrayList<>(); + List nums = new ArrayList<>(); + int k = 0; + + for (final String word : words) + if (word.equals("prev")) { + ++k; + ans.add(k > nums.size() ? -1 : nums.get(nums.size() - k)); + } else { + k = 0; + nums.add(Integer.valueOf(word)); + } + + return ans; + } +} diff --git a/solutions/2899. Last Visited Integers/2899.py b/solutions/2899. Last Visited Integers/2899.py new file mode 100644 index 00000000000..2299796cdc5 --- /dev/null +++ b/solutions/2899. Last Visited Integers/2899.py @@ -0,0 +1,15 @@ +class Solution: + def lastVisitedIntegers(self, words: List[str]) -> List[int]: + ans = [] + nums = [] + k = 0 + + for word in words: + if word == 'prev': + k += 1 + ans.append(-1 if k > len(nums) else nums[-k]) + else: + k = 0 + nums.append(int(word)) + + return ans diff --git a/solutions/29. Divide Two Integers/29.cpp b/solutions/29. Divide Two Integers/29.cpp new file mode 100644 index 00000000000..6aea144c838 --- /dev/null +++ b/solutions/29. Divide Two Integers/29.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int divide(int dividend, int divisor) { + // -2^{31} / -1 = 2^31 will overflow, so return 2^31 - 1. + if (dividend == INT_MIN && divisor == -1) + return INT_MAX; + + const int sign = dividend > 0 ^ divisor > 0 ? -1 : 1; + long ans = 0; + long dvd = labs(dividend); + long dvs = labs(divisor); + + while (dvd >= dvs) { + long k = 1; + while (k * 2 * dvs <= dvd) + k *= 2; + dvd -= k * dvs; + ans += k; + } + + return sign * ans; + } +}; diff --git a/solutions/29. Divide Two Integers/29.java b/solutions/29. Divide Two Integers/29.java new file mode 100644 index 00000000000..8af69c97824 --- /dev/null +++ b/solutions/29. Divide Two Integers/29.java @@ -0,0 +1,22 @@ +class Solution { + public int divide(long dividend, long divisor) { + // -2^{31} / -1 = 2^31 will overflow, so return 2^31 - 1. + if (dividend == Integer.MIN_VALUE && divisor == -1) + return Integer.MAX_VALUE; + + final int sign = dividend > 0 ^ divisor > 0 ? -1 : 1; + long ans = 0; + long dvd = Math.abs(dividend); + long dvs = Math.abs(divisor); + + while (dvd >= dvs) { + long k = 1; + while (k * 2 * dvs <= dvd) + k *= 2; + dvd -= k * dvs; + ans += k; + } + + return sign * (int) ans; + } +} diff --git a/solutions/29. Divide Two Integers/29.py b/solutions/29. Divide Two Integers/29.py new file mode 100644 index 00000000000..97b2c98eb4d --- /dev/null +++ b/solutions/29. Divide Two Integers/29.py @@ -0,0 +1,19 @@ +class Solution: + def divide(self, dividend: int, divisor: int) -> int: + # -2^{31} / -1 = 2^31 will overflow, so return 2^31 - 1. + if dividend == -2**31 and divisor == -1: + return 2**31 - 1 + + sign = -1 if (dividend > 0) ^ (divisor > 0) else 1 + ans = 0 + dvd = abs(dividend) + dvs = abs(divisor) + + while dvd >= dvs: + k = 1 + while k * 2 * dvs <= dvd: + k <<= 1 + dvd -= k * dvs + ans += k + + return sign * ans diff --git a/solutions/290. Word Pattern/290.cpp b/solutions/290. Word Pattern/290.cpp new file mode 100644 index 00000000000..ddc55cffce6 --- /dev/null +++ b/solutions/290. Word Pattern/290.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool wordPattern(string pattern, string str) { + const int n = pattern.length(); + istringstream iss(str); + vector charToIndex(128); + unordered_map stringToIndex; + + int i = 0; + for (string word; iss >> word; ++i) { + if (i == n) // out-of-bounds + return false; + if (charToIndex[pattern[i]] != stringToIndex[word]) + return false; + charToIndex[pattern[i]] = i + 1; + stringToIndex[word] = i + 1; + } + + return i == n; + } +}; diff --git a/solutions/290. Word Pattern/290.java b/solutions/290. Word Pattern/290.java new file mode 100644 index 00000000000..eb3a06c5249 --- /dev/null +++ b/solutions/290. Word Pattern/290.java @@ -0,0 +1,16 @@ +class Solution { + public boolean wordPattern(String pattern, String str) { + String[] words = str.split(" "); + if (words.length != pattern.length()) + return false; + + Map charToIndex = new HashMap<>(); + Map stringToIndex = new HashMap<>(); + + for (Integer i = 0; i < pattern.length(); ++i) + if (charToIndex.put(pattern.charAt(i), i) != stringToIndex.put(words[i], i)) + return false; + + return true; + } +} diff --git a/solutions/290. Word Pattern/290.py b/solutions/290. Word Pattern/290.py new file mode 100644 index 00000000000..283c5a7306e --- /dev/null +++ b/solutions/290. Word Pattern/290.py @@ -0,0 +1,4 @@ +class Solution: + def wordPattern(self, pattern: str, str: str) -> bool: + t = str.split() + return [*map(pattern.index, pattern)] == [*map(t.index, t)] diff --git a/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.cpp b/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.cpp new file mode 100644 index 00000000000..08e5d63c5e7 --- /dev/null +++ b/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector getWordsInLongestSubsequence(int n, vector& words, + vector& groups) { + vector ans; + int groupId = -1; + + for (int i = 0; i < n; ++i) + if (groups[i] != groupId) { + groupId = groups[i]; + ans.push_back(words[i]); + } + + return ans; + } +}; diff --git a/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.java b/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.java new file mode 100644 index 00000000000..24a88dccf3f --- /dev/null +++ b/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.java @@ -0,0 +1,14 @@ +class Solution { + public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + List ans = new ArrayList<>(); + int groupId = -1; + + for (int i = 0; i < n; ++i) + if (groups[i] != groupId) { + groupId = groups[i]; + ans.add(words[i]); + } + + return ans; + } +} diff --git a/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.py b/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.py new file mode 100644 index 00000000000..938737ff8d9 --- /dev/null +++ b/solutions/2900. Longest Unequal Adjacent Groups Subsequence I/2900.py @@ -0,0 +1,11 @@ +class Solution: + def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]: + ans = [] + groupId = -1 + + for word, group in zip(words, groups): + if group != groupId: + groupId = group + ans.append(word) + + return ans diff --git a/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.cpp b/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.cpp new file mode 100644 index 00000000000..ca76d7c8550 --- /dev/null +++ b/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + vector getWordsInLongestSubsequence(int n, vector& words, + vector& groups) { + vector ans; + // dp[i] := the length of the longest subsequence ending in `words[i]` + vector dp(n, 1); + // prev[i] := the best index of words[i] + vector prev(n, -1); + + for (int i = 1; i < n; ++i) + for (int j = 0; j < i; ++j) { + if (groups[i] == groups[j]) + continue; + if (words[i].length() != words[j].length()) + continue; + if (hammingDist(words[i], words[j]) != 1) + continue; + if (dp[i] < dp[j] + 1) { + dp[i] = dp[j] + 1; + prev[i] = j; + } + } + + // Find the last index of the subsequence. + int index = ranges::max_element(dp) - dp.begin(); + while (index != -1) { + ans.push_back(words[index]); + index = prev[index]; + } + + return {ans.rbegin(), ans.rend()}; + } + + private: + int hammingDist(const string& s1, const string& s2) { + int dist = 0; + for (int i = 0; i < s1.length(); ++i) + if (s1[i] != s2[i]) + ++dist; + return dist; + } +}; diff --git a/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.java b/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.java new file mode 100644 index 00000000000..252559ba0dd --- /dev/null +++ b/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.java @@ -0,0 +1,51 @@ +class Solution { + public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + List ans = new ArrayList<>(); + // dp[i] := the length of the longest subsequence ending in `words[i]` + int[] dp = new int[n]; + Arrays.fill(dp, 1); + // prev[i] := the best index of words[i] + int[] prev = new int[n]; + Arrays.fill(prev, -1); + + for (int i = 1; i < n; ++i) + for (int j = 0; j < i; ++j) { + if (groups[i] == groups[j]) + continue; + if (words[i].length() != words[j].length()) + continue; + if (hammingDist(words[i], words[j]) != 1) + continue; + if (dp[i] < dp[j] + 1) { + dp[i] = dp[j] + 1; + prev[i] = j; + } + } + + // Find the last index of the subsequence. + int index = getMaxIndex(dp); + while (index != -1) { + ans.add(words[index]); + index = prev[index]; + } + + Collections.reverse(ans); + return ans; + } + + private int hammingDist(final String s1, final String s2) { + int dist = 0; + for (int i = 0; i < s1.length(); ++i) + if (s1.charAt(i) != s2.charAt(i)) + ++dist; + return dist; + } + + private int getMaxIndex(int[] dp) { + int maxIndex = 0; + for (int i = 0; i < dp.length; ++i) + if (dp[i] > dp[maxIndex]) + maxIndex = i; + return maxIndex; + } +} diff --git a/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.py b/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.py new file mode 100644 index 00000000000..522527a1ade --- /dev/null +++ b/solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.py @@ -0,0 +1,27 @@ +class Solution: + def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]: + ans = [] + # dp[i] := the length of the longest subsequence ending in `words[i]` + dp = [1] * n + # prev[i] := the best index of words[i] + prev = [-1] * n + + for i in range(1, n): + for j in range(i): + if groups[i] == groups[j]: + continue + if len(words[i]) != len(words[j]): + continue + if sum(a != b for a, b in zip(words[i], words[j])) != 1: + continue + if dp[i] < dp[j] + 1: + dp[i] = dp[j] + 1 + prev[i] = j + + # Find the last index of the subsequence. + index = dp.index(max(dp)) + while index != -1: + ans.append(words[index]) + index = prev[index] + + return ans[::-1] diff --git a/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.cpp b/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.cpp new file mode 100644 index 00000000000..4b8b284ebc2 --- /dev/null +++ b/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int countSubMultisets(vector& nums, int l, int r) { + constexpr int kMod = 1'000'000'007; + // dp[i] := the number of submultisets of `nums` with sum i + vector dp(r + 1); + dp[0] = 1; + unordered_map count; + + for (const int num : nums) + ++count[num]; + + const int zeros = count[0]; + count.erase(0); + + for (const auto& [num, freq] : count) { + // stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ... + vector stride = dp; + for (int i = num; i <= r; ++i) + stride[i] += stride[i - num]; + for (int i = r; i > 0; --i) + if (i >= num * (freq + 1)) + // dp[i] + dp[i - num] + dp[i - freq * num] + dp[i] = (stride[i] - stride[i - num * (freq + 1)]) % kMod; + else + dp[i] = stride[i] % kMod; + } + + long ans = 0; + for (int i = l; i <= r; ++i) + ans = (ans + dp[i]) % kMod; + return ((zeros + 1) * ans) % kMod; + } +}; diff --git a/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.java b/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.java new file mode 100644 index 00000000000..b220dde3214 --- /dev/null +++ b/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.java @@ -0,0 +1,34 @@ +class Solution { + public int countSubMultisets(List nums, int l, int r) { + final int kMod = 1_000_000_007; + // dp[i] := the number of submultisets of `nums` with sum i + long[] dp = new long[r + 1]; + dp[0] = 1; + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + final int zeros = count.containsKey(0) ? count.remove(0) : 0; + + for (Map.Entry entry : count.entrySet()) { + final int num = entry.getKey(); + final int freq = entry.getValue(); + // stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ... + long[] stride = dp.clone(); + for (int i = num; i <= r; ++i) + stride[i] += stride[i - num]; + for (int i = r; i > 0; --i) + if (i >= num * (freq + 1)) + // dp[i] + dp[i - num] + dp[i - freq * num] + dp[i] = (stride[i] - stride[i - num * (freq + 1)]) % kMod; + else + dp[i] = stride[i] % kMod; + } + + long ans = 0; + for (int i = l; i <= r; ++i) + ans = (ans + dp[i]) % kMod; + return (int) (((zeros + 1) * ans) % kMod); + } +} diff --git a/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.py b/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.py new file mode 100644 index 00000000000..b365d5edeb6 --- /dev/null +++ b/solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.py @@ -0,0 +1,21 @@ +class Solution: + def countSubMultisets(self, nums: List[int], l: int, r: int) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of submultisets of `nums` with sum i + dp = [1] + [0] * r + count = collections.Counter(nums) + zeros = count.pop(0, 0) + + for num, freq in count.items(): + # stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ... + stride = dp.copy() + for i in range(num, r + 1): + stride[i] += stride[i - num] + for i in range(r, 0, -1): + if i >= num * (freq + 1): + # dp[i] + dp[i - num] + dp[i - freq * num] + dp[i] = stride[i] - stride[i - num * (freq + 1)] + else: + dp[i] = stride[i] + + return (zeros + 1) * sum(dp[l:r + 1]) % kMod diff --git a/solutions/2903. Find Indices With Index and Value Difference I/2903.cpp b/solutions/2903. Find Indices With Index and Value Difference I/2903.cpp new file mode 100644 index 00000000000..af429f713e5 --- /dev/null +++ b/solutions/2903. Find Indices With Index and Value Difference I/2903.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector findIndices(vector& nums, int indexDifference, + int valueDifference) { + // nums[minIndex] := the minimum number with enough index different from the + // current number + int minIndex = 0; + // nums[maxIndex] := the maximum number with enough index different from the + // current number + int maxIndex = 0; + + for (int i = indexDifference; i < nums.size(); ++i) { + if (nums[i - indexDifference] < nums[minIndex]) + minIndex = i - indexDifference; + if (nums[i - indexDifference] > nums[maxIndex]) + maxIndex = i - indexDifference; + if (nums[i] - nums[minIndex] >= valueDifference) + return {i, minIndex}; + if (nums[maxIndex] - nums[i] >= valueDifference) + return {i, maxIndex}; + } + + return {-1, -1}; + } +}; diff --git a/solutions/2903. Find Indices With Index and Value Difference I/2903.java b/solutions/2903. Find Indices With Index and Value Difference I/2903.java new file mode 100644 index 00000000000..d1a6d783c66 --- /dev/null +++ b/solutions/2903. Find Indices With Index and Value Difference I/2903.java @@ -0,0 +1,23 @@ +class Solution { + public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { + // nums[minIndex] := the minimum number with enough index different from the + // current number + int minIndex = 0; + // nums[maxIndex] := the maximum number with enough index different from the + // current number + int maxIndex = 0; + + for (int i = indexDifference; i < nums.length; ++i) { + if (nums[i - indexDifference] < nums[minIndex]) + minIndex = i - indexDifference; + if (nums[i - indexDifference] > nums[maxIndex]) + maxIndex = i - indexDifference; + if (nums[i] - nums[minIndex] >= valueDifference) + return new int[] {i, minIndex}; + if (nums[maxIndex] - nums[i] >= valueDifference) + return new int[] {i, maxIndex}; + } + + return new int[] {-1, -1}; + } +} diff --git a/solutions/2903. Find Indices With Index and Value Difference I/2903.py b/solutions/2903. Find Indices With Index and Value Difference I/2903.py new file mode 100644 index 00000000000..fceb0cc0988 --- /dev/null +++ b/solutions/2903. Find Indices With Index and Value Difference I/2903.py @@ -0,0 +1,20 @@ +class Solution: + def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]: + # nums[minIndex] := the minimum number with enough index different from the + # current number + minIndex = 0 + # nums[maxIndex] := the maximum number with enough index different from the + # current number + maxIndex = 0 + + for i in range(indexDifference, len(nums)): + if nums[i - indexDifference] < nums[minIndex]: + minIndex = i - indexDifference + if nums[i - indexDifference] > nums[maxIndex]: + maxIndex = i - indexDifference + if nums[i] - nums[minIndex] >= valueDifference: + return [i, minIndex] + if nums[maxIndex] - nums[i] >= valueDifference: + return [i, maxIndex] + + return [-1, -1] diff --git a/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.cpp b/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.cpp new file mode 100644 index 00000000000..4a23c7aee53 --- /dev/null +++ b/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + // Same as 76. Minimum Window Substring + string shortestBeautifulSubstring(string s, int k) { + int bestLeft = -1; + int minLength = s.length() + 1; + int ones = 0; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (s[r] == '1') + ++ones; + while (ones == k) { + if (r - l + 1 < minLength) { + bestLeft = l; + minLength = r - l + 1; + } else if (r - l + 1 == minLength && + s.compare(l, minLength, s, bestLeft, minLength) < 0) { + bestLeft = l; + } + if (s[l++] == '1') + --ones; + } + } + + return bestLeft == -1 ? "" : s.substr(bestLeft, minLength); + } +}; diff --git a/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.java b/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.java new file mode 100644 index 00000000000..3d78667b1e0 --- /dev/null +++ b/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.java @@ -0,0 +1,27 @@ +class Solution { + // Same as 76. Minimum Window Substring + public String shortestBeautifulSubstring(String s, int k) { + int bestLeft = -1; + int minLength = s.length() + 1; + int ones = 0; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (s.charAt(r) == '1') + ++ones; + while (ones == k) { + if (r - l + 1 < minLength) { + bestLeft = l; + minLength = r - l + 1; + } else if (r - l + 1 == minLength && + s.substring(l, l + minLength) + .compareTo(s.substring(bestLeft, bestLeft + minLength)) < 0) { + bestLeft = l; + } + if (s.charAt(l++) == '1') + --ones; + } + } + + return bestLeft == -1 ? "" : s.substring(bestLeft, bestLeft + minLength); + } +} diff --git a/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.py b/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.py new file mode 100644 index 00000000000..cba4edec8f2 --- /dev/null +++ b/solutions/2904. Shortest and Lexicographically Smallest Beautiful String/2904.py @@ -0,0 +1,22 @@ +class Solution: + # Same as 76. Minimum Window Substring + def shortestBeautifulSubstring(self, s: str, k: int) -> str: + bestLeft = -1 + minLength = len(s) + 1 + ones = 0 + + l = 0 + for r, c in enumerate(s): + if c == '1': + ones += 1 + while ones == k: + if r - l + 1 < minLength: + bestLeft = l + minLength = r - l + 1 + elif r - l + 1 == minLength and s[l:l + minLength] < s[bestLeft:bestLeft + minLength]: + bestLeft = l + if s[l] == '1': + ones -= 1 + l += 1 + + return "" if bestLeft == -1 else s[bestLeft:bestLeft + minLength] diff --git a/solutions/2905. Find Indices With Index and Value Difference II/2905.cpp b/solutions/2905. Find Indices With Index and Value Difference II/2905.cpp new file mode 100644 index 00000000000..af429f713e5 --- /dev/null +++ b/solutions/2905. Find Indices With Index and Value Difference II/2905.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector findIndices(vector& nums, int indexDifference, + int valueDifference) { + // nums[minIndex] := the minimum number with enough index different from the + // current number + int minIndex = 0; + // nums[maxIndex] := the maximum number with enough index different from the + // current number + int maxIndex = 0; + + for (int i = indexDifference; i < nums.size(); ++i) { + if (nums[i - indexDifference] < nums[minIndex]) + minIndex = i - indexDifference; + if (nums[i - indexDifference] > nums[maxIndex]) + maxIndex = i - indexDifference; + if (nums[i] - nums[minIndex] >= valueDifference) + return {i, minIndex}; + if (nums[maxIndex] - nums[i] >= valueDifference) + return {i, maxIndex}; + } + + return {-1, -1}; + } +}; diff --git a/solutions/2905. Find Indices With Index and Value Difference II/2905.java b/solutions/2905. Find Indices With Index and Value Difference II/2905.java new file mode 100644 index 00000000000..dc9bcab85d3 --- /dev/null +++ b/solutions/2905. Find Indices With Index and Value Difference II/2905.java @@ -0,0 +1,21 @@ +class Solution { + public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { + // nums[minIndex] := the minimum number with enough index different from the current number + int minIndex = 0; + // nums[maxIndex] := the maximum number with enough index different from the current number + int maxIndex = 0; + + for (int i = indexDifference; i < nums.length; ++i) { + if (nums[i - indexDifference] < nums[minIndex]) + minIndex = i - indexDifference; + if (nums[i - indexDifference] > nums[maxIndex]) + maxIndex = i - indexDifference; + if (nums[i] - nums[minIndex] >= valueDifference) + return new int[] {i, minIndex}; + if (nums[maxIndex] - nums[i] >= valueDifference) + return new int[] {i, maxIndex}; + } + + return new int[] {-1, -1}; + } +} diff --git a/solutions/2905. Find Indices With Index and Value Difference II/2905.py b/solutions/2905. Find Indices With Index and Value Difference II/2905.py new file mode 100644 index 00000000000..2556a20e12d --- /dev/null +++ b/solutions/2905. Find Indices With Index and Value Difference II/2905.py @@ -0,0 +1,18 @@ +class Solution: + def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]: + # nums[minIndex] := the minimum number with enough index different from the current number + minIndex = 0 + # nums[maxIndex] := the maximum number with enough index different from the current number + maxIndex = 0 + + for i in range(indexDifference, len(nums)): + if nums[i - indexDifference] < nums[minIndex]: + minIndex = i - indexDifference + if nums[i - indexDifference] > nums[maxIndex]: + maxIndex = i - indexDifference + if nums[i] - nums[minIndex] >= valueDifference: + return [i, minIndex] + if nums[maxIndex] - nums[i] >= valueDifference: + return [i, maxIndex] + + return [-1, -1] diff --git a/solutions/2906. Construct Product Matrix/2906.cpp b/solutions/2906. Construct Product Matrix/2906.cpp new file mode 100644 index 00000000000..0704a7f1c61 --- /dev/null +++ b/solutions/2906. Construct Product Matrix/2906.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector> constructProductMatrix(vector>& grid) { + constexpr int kMod = 12345; + const int m = grid.size(); + const int n = grid[0].size(); + vector> ans(m, vector(n)); + vector prefix{1}; + int suffix = 1; + + for (const vector& row : grid) + for (const int cell : row) + prefix.push_back(static_cast(prefix.back()) * cell % kMod); + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) { + ans[i][j] = prefix[i * n + j] * suffix % kMod; + suffix = static_cast(suffix) * grid[i][j] % kMod; + } + + return ans; + } +}; diff --git a/solutions/2906. Construct Product Matrix/2906.java b/solutions/2906. Construct Product Matrix/2906.java new file mode 100644 index 00000000000..0f8fce57ef6 --- /dev/null +++ b/solutions/2906. Construct Product Matrix/2906.java @@ -0,0 +1,22 @@ +class Solution { + public int[][] constructProductMatrix(int[][] grid) { + final int kMod = 12345; + final int m = grid.length; + final int n = grid[0].length; + int[][] ans = new int[m][n]; + List prefix = new ArrayList<>(Arrays.asList(1)); + int suffix = 1; + + for (int[] row : grid) + for (int cell : row) + prefix.add((int) ((long) prefix.get(prefix.size() - 1) * cell % kMod)); + + for (int i = m - 1; i >= 0; i--) + for (int j = n - 1; j >= 0; j--) { + ans[i][j] = (int) ((long) prefix.get(i * n + j) * suffix % kMod); + suffix = (int) ((long) suffix * grid[i][j] % kMod); + } + + return ans; + } +} diff --git a/solutions/2906. Construct Product Matrix/2906.py b/solutions/2906. Construct Product Matrix/2906.py new file mode 100644 index 00000000000..da7d0d4362d --- /dev/null +++ b/solutions/2906. Construct Product Matrix/2906.py @@ -0,0 +1,19 @@ +class Solution: + def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]: + kMod = 12345 + m = len(grid) + n = len(grid[0]) + ans = [[0] * n for _ in range(m)] + prefix = [1] + suffix = 1 + + for row in grid: + for cell in row: + prefix.append(prefix[-1] * cell % kMod) + + for i in reversed(range(m)): + for j in reversed(range(n)): + ans[i][j] = prefix[i * n + j] * suffix % kMod + suffix = suffix * grid[i][j] % kMod + + return ans diff --git a/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.cpp b/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.cpp new file mode 100644 index 00000000000..9d6f18a81f9 --- /dev/null +++ b/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.cpp @@ -0,0 +1,53 @@ +class FenwickTree { + public: + FenwickTree(int n) : vals(n + 1) {} + + void maximize(int i, int val) { + while (i < vals.size()) { + vals[i] = max(vals[i], val); + i += lowbit(i); + } + } + + int get(int i) const { + int res = 0; + while (i > 0) { + res = max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private: + vector vals; + + static int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + int maxProfit(vector& prices, vector& profits) { + const int maxPrice = ranges::max(prices); + int ans = -1; + FenwickTree maxProfitTree1(maxPrice); + FenwickTree maxProfitTree2(maxPrice); + + for (int i = 0; i < prices.size(); ++i) { + const int price = prices[i]; + const int profit = profits[i]; + // max(proftis[i]) + const int maxProfit1 = maxProfitTree1.get(price - 1); + // max(proftis[i]) + max(profits[j]) + const int maxProfit2 = maxProfitTree2.get(price - 1); + maxProfitTree1.maximize(price, profit); + if (maxProfit1 > 0) + maxProfitTree2.maximize(price, profit + maxProfit1); + if (maxProfit2 > 0) + ans = max(ans, profit + maxProfit2); + } + + return ans; + } +}; diff --git a/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.java b/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.java new file mode 100644 index 00000000000..3be2fb0c8e0 --- /dev/null +++ b/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.java @@ -0,0 +1,52 @@ +class FenwickTree { + public FenwickTree(int n) { + vals = new int[n + 1]; + } + + public void maximize(int i, int val) { + while (i < vals.length) { + vals[i] = Math.max(vals[i], val); + i += lowbit(i); + } + } + + public int get(int i) { + int res = 0; + while (i > 0) { + res = Math.max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private int[] vals; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public int maxProfit(int[] prices, int[] profits) { + final int maxPrice = Arrays.stream(prices).max().getAsInt(); + int ans = -1; + FenwickTree maxProfitTree1 = new FenwickTree(maxPrice); + FenwickTree maxProfitTree2 = new FenwickTree(maxPrice); + + for (int i = 0; i < prices.length; ++i) { + final int price = prices[i]; + final int profit = profits[i]; + // max(profits[i]) + final int maxProfit1 = maxProfitTree1.get(price - 1); + // max(proftis[i]) + max(profits[j]) + final int maxProfit2 = maxProfitTree2.get(price - 1); + maxProfitTree1.maximize(price, profit); + if (maxProfit1 > 0) + maxProfitTree2.maximize(price, profit + maxProfit1); + if (maxProfit2 > 0) + ans = Math.max(ans, profit + maxProfit2); + } + + return ans; + } +} diff --git a/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.py b/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.py new file mode 100644 index 00000000000..fc975091ac9 --- /dev/null +++ b/solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.py @@ -0,0 +1,40 @@ +class FenwickTree: + def __init__(self, n: int): + self.vals = [0] * (n + 1) + + def maximize(self, i: int, val: int) -> None: + while i < len(self.vals): + self.vals[i] = max(self.vals[i], val) + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + res = 0 + while i > 0: + res = max(res, self.vals[i]) + i -= FenwickTree.lowbit(i) + return res + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + ans = -1 + maxPrice = max(prices) + maxProfitTree1 = FenwickTree(maxPrice) + maxProfitTree2 = FenwickTree(maxPrice) + + for price, profit in zip(prices, profits): + # max(proftis[i]) + maxProfit1 = maxProfitTree1.get(price - 1) + # max(proftis[i]) + max(profits[j]) + maxProfit2 = maxProfitTree2.get(price - 1) + maxProfitTree1.maximize(price, profit) + if maxProfit1 > 0: + maxProfitTree2.maximize(price, profit + maxProfit1) + if maxProfit2 > 0: + ans = max(ans, profit + maxProfit2) + + return ans diff --git a/solutions/2908. Minimum Sum of Mountain Triplets I/2908.cpp b/solutions/2908. Minimum Sum of Mountain Triplets I/2908.cpp new file mode 100644 index 00000000000..7c3ce106dad --- /dev/null +++ b/solutions/2908. Minimum Sum of Mountain Triplets I/2908.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minimumSum(vector& nums) { + const int n = nums.size(); + int ans = INT_MAX; + vector minPrefix(n); + vector minSuffix(n); + + partial_sum(nums.begin(), nums.end(), minPrefix.begin(), + [](int x, int y) { return min(x, y); }); + partial_sum(nums.rbegin(), nums.rend(), minSuffix.begin(), + [](int x, int y) { return min(x, y); }); + reverse(minSuffix.begin(), minSuffix.end()); + + for (int i = 0; i < n; ++i) + if (nums[i] > minPrefix[i] && nums[i] > minSuffix[i]) + ans = min(ans, nums[i] + minPrefix[i] + minSuffix[i]); + + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/2908. Minimum Sum of Mountain Triplets I/2908.java b/solutions/2908. Minimum Sum of Mountain Triplets I/2908.java new file mode 100644 index 00000000000..33e5bec7fac --- /dev/null +++ b/solutions/2908. Minimum Sum of Mountain Triplets I/2908.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumSum(int[] nums) { + final int n = nums.length; + int ans = Integer.MAX_VALUE; + int[] minPrefix = new int[n]; + int[] minSuffix = new int[n]; + + minPrefix[0] = nums[0]; + minSuffix[n - 1] = nums[n - 1]; + + for (int i = 1; i < n; ++i) + minPrefix[i] = Math.min(minPrefix[i - 1], nums[i]); + + for (int i = n - 2; i >= 0; --i) + minSuffix[i] = Math.min(minSuffix[i + 1], nums[i]); + + for (int i = 0; i < n; ++i) + if (nums[i] > minPrefix[i] && nums[i] > minSuffix[i]) + ans = Math.min(ans, nums[i] + minPrefix[i] + minSuffix[i]); + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/2908. Minimum Sum of Mountain Triplets I/2908.py b/solutions/2908. Minimum Sum of Mountain Triplets I/2908.py new file mode 100644 index 00000000000..56b58bcb112 --- /dev/null +++ b/solutions/2908. Minimum Sum of Mountain Triplets I/2908.py @@ -0,0 +1,12 @@ +class Solution: + # Same as 2908. Minimum Sum of Mountain Triplets I + def minimumSum(self, nums: List[int]) -> int: + ans = math.inf + minPrefix = list(itertools.accumulate(nums, min)) + minSuffix = list(itertools.accumulate(reversed(nums), min))[::-1] + + for i, num in enumerate(nums): + if num > minPrefix[i] and num > minSuffix[i]: + ans = min(ans, num + minPrefix[i] + minSuffix[i]) + + return -1 if ans == math.inf else ans diff --git a/solutions/2909. Minimum Sum of Mountain Triplets II/2909.cpp b/solutions/2909. Minimum Sum of Mountain Triplets II/2909.cpp new file mode 100644 index 00000000000..f36d6d9f8b6 --- /dev/null +++ b/solutions/2909. Minimum Sum of Mountain Triplets II/2909.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + // Same as 2908. Minimum Sum of Mountain Triplets I + int minimumSum(vector& nums) { + const int n = nums.size(); + int ans = INT_MAX; + vector minPrefix(n); + vector minSuffix(n); + + partial_sum(nums.begin(), nums.end(), minPrefix.begin(), + [](int x, int y) { return min(x, y); }); + partial_sum(nums.rbegin(), nums.rend(), minSuffix.begin(), + [](int x, int y) { return min(x, y); }); + reverse(minSuffix.begin(), minSuffix.end()); + + for (int i = 0; i < n; ++i) + if (nums[i] > minPrefix[i] && nums[i] > minSuffix[i]) + ans = min(ans, nums[i] + minPrefix[i] + minSuffix[i]); + + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/2909. Minimum Sum of Mountain Triplets II/2909.java b/solutions/2909. Minimum Sum of Mountain Triplets II/2909.java new file mode 100644 index 00000000000..d0fa3af81cf --- /dev/null +++ b/solutions/2909. Minimum Sum of Mountain Triplets II/2909.java @@ -0,0 +1,24 @@ +class Solution { + // Same as 2908. Minimum Sum of Mountain Triplets I + public int minimumSum(int[] nums) { + final int n = nums.length; + int ans = Integer.MAX_VALUE; + int[] minPrefix = new int[n]; + int[] minSuffix = new int[n]; + + minPrefix[0] = nums[0]; + minSuffix[n - 1] = nums[n - 1]; + + for (int i = 1; i < n; ++i) + minPrefix[i] = Math.min(minPrefix[i - 1], nums[i]); + + for (int i = n - 2; i >= 0; --i) + minSuffix[i] = Math.min(minSuffix[i + 1], nums[i]); + + for (int i = 0; i < n; ++i) + if (nums[i] > minPrefix[i] && nums[i] > minSuffix[i]) + ans = Math.min(ans, nums[i] + minPrefix[i] + minSuffix[i]); + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/2909. Minimum Sum of Mountain Triplets II/2909.py b/solutions/2909. Minimum Sum of Mountain Triplets II/2909.py new file mode 100644 index 00000000000..56b58bcb112 --- /dev/null +++ b/solutions/2909. Minimum Sum of Mountain Triplets II/2909.py @@ -0,0 +1,12 @@ +class Solution: + # Same as 2908. Minimum Sum of Mountain Triplets I + def minimumSum(self, nums: List[int]) -> int: + ans = math.inf + minPrefix = list(itertools.accumulate(nums, min)) + minSuffix = list(itertools.accumulate(reversed(nums), min))[::-1] + + for i, num in enumerate(nums): + if num > minPrefix[i] and num > minSuffix[i]: + ans = min(ans, num + minPrefix[i] + minSuffix[i]) + + return -1 if ans == math.inf else ans diff --git a/solutions/291. Word Pattern II/291.cpp b/solutions/291. Word Pattern II/291.cpp new file mode 100644 index 00000000000..88846ec9d75 --- /dev/null +++ b/solutions/291. Word Pattern II/291.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + bool wordPatternMatch(string pattern, string s) { + return isMatch(pattern, 0, s, 0, unordered_map(), + unordered_set()); + } + + private: + bool isMatch(const string& pattern, int i, const string& s, int j, + unordered_map&& charToString, + unordered_set&& seen) { + if (i == pattern.length() && j == s.length()) + return true; + if (i == pattern.length() || j == s.length()) + return false; + + const char c = pattern[i]; + + if (const auto it = charToString.find(c); it != charToString.cend()) { + const string& t = it->second; + // See if we can match t with s[j..n). + if (s.substr(j).find(t) == string::npos) + return false; + + // If there's a match, continue to match the rest. + return isMatch(pattern, i + 1, s, j + t.length(), move(charToString), + move(seen)); + } + + for (int k = j; k < s.length(); ++k) { + const string& t = s.substr(j, k - j + 1); + + // This string is mapped by another character. + if (seen.contains(t)) + continue; + + charToString[c] = t; + seen.insert(t); + + if (isMatch(pattern, i + 1, s, k + 1, move(charToString), move(seen))) + return true; + + // Backtrack. + charToString.erase(c); + seen.erase(t); + } + + return false; + } +}; diff --git a/solutions/291. Word Pattern II/291.java b/solutions/291. Word Pattern II/291.java new file mode 100644 index 00000000000..3bff5b12a28 --- /dev/null +++ b/solutions/291. Word Pattern II/291.java @@ -0,0 +1,45 @@ +class Solution { + public boolean wordPatternMatch(String pattern, String s) { + return isMatch(pattern, 0, s, 0, new HashMap<>(), new HashSet<>()); + } + + private boolean isMatch(final String pattern, int i, final String s, int j, + Map charToString, Set seen) { + if (i == pattern.length() && j == s.length()) + return true; + if (i == pattern.length() || j == s.length()) + return false; + + final char c = pattern.charAt(i); + + if (charToString.containsKey(c)) { + final String t = charToString.get(c); + // See if we can match t with s[j..n). + if (!s.startsWith(t, j)) + return false; + + // If there's a match, continue to match the rest. + return isMatch(pattern, i + 1, s, j + t.length(), charToString, seen); + } + + for (int k = j; k < s.length(); ++k) { + final String t = s.substring(j, k + 1); + + // This string is mapped by another character. + if (seen.contains(t)) + continue; + + charToString.put(c, t); + seen.add(t); + + if (isMatch(pattern, i + 1, s, k + 1, charToString, seen)) + return true; + + // Backtrack. + charToString.remove(c); + seen.remove(t); + } + + return false; + } +} diff --git a/solutions/291. Word Pattern II/291.py b/solutions/291. Word Pattern II/291.py new file mode 100644 index 00000000000..15b263351e5 --- /dev/null +++ b/solutions/291. Word Pattern II/291.py @@ -0,0 +1,39 @@ +class Solution: + def wordPatternMatch(self, pattern: str, s: str) -> bool: + def isMatch(i: int, j: int, charToString: Dict[chr, str], seen: Set[str]) -> bool: + if i == len(pattern) and j == len(s): + return True + if i == len(pattern) or j == len(s): + return False + + c = pattern[i] + + if c in charToString: + t = charToString[c] + # See if we can match t with s[j..n). + if t not in s[j:]: + return False + + # If there's a match, continue to match the rest. + return isMatch(i + 1, j + len(t), charToString, seen) + + for k in range(j, len(s)): + t = s[j:k + 1] + + # This string is mapped by another character. + if t in seen: + continue + + charToString[c] = t + seen.add(t) + + if isMatch(i + 1, k + 1, charToString, seen): + return True + + # Backtrack. + del charToString[c] + seen.remove(t) + + return False + + return isMatch(0, 0, {}, set()) diff --git a/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.cpp b/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.cpp new file mode 100644 index 00000000000..563da382dd1 --- /dev/null +++ b/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + int minGroupsForValidAssignment(vector& nums) { + unordered_map count; + int minFreq = nums.size(); + + for (const int num : nums) + ++count[num]; + + for (const auto& [_, freq] : count) + minFreq = min(minFreq, freq); + + for (int groupSize = minFreq; groupSize >= 1; --groupSize) { + const int numGroups = getNumGroups(count, groupSize); + if (numGroups > 0) + return numGroups; + } + + throw; + } + + private: + // Returns the number of groups if each group's size is `groupSize` or + // `groupSize + 1`. + int getNumGroups(unordered_map& count, int groupSize) { + int numGroups = 0; + for (const auto& [_, freq] : count) { + const int a = freq / (groupSize + 1); + const int b = freq % (groupSize + 1); + if (b == 0) { + numGroups += a; + } else if (groupSize - b <= a) { + // Assign 1 number from `groupSize - b` out of `a` groups to this group, + // so we'll have `a - (groupSize - b)` groups of size `groupSize + 1` + // and `groupSize - b + 1` groups of size `groupSize`. In total, we have + // `a + 1` groups. + numGroups += a + 1; + } else { + return 0; + } + } + return numGroups; + } +}; diff --git a/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.java b/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.java new file mode 100644 index 00000000000..c7ed485b968 --- /dev/null +++ b/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.java @@ -0,0 +1,42 @@ +class Solution { + public int minGroupsForValidAssignment(int[] nums) { + Map count = new HashMap<>(); + int minFreq = nums.length; + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int freq : count.values()) + minFreq = Math.min(minFreq, freq); + + for (int groupSize = minFreq; groupSize >= 1; --groupSize) { + final int numGroups = getNumGroups(count, groupSize); + if (numGroups > 0) + return numGroups; + } + + throw new IllegalArgumentException(); + } + + // Returns the number of groups if each group's size is `groupSize` or + // `groupSize + 1`. + private int getNumGroups(Map count, int groupSize) { + int numGroups = 0; + for (final int freq : count.values()) { + final int a = freq / (groupSize + 1); + final int b = freq % (groupSize + 1); + if (b == 0) { + numGroups += a; + } else if (groupSize - b <= a) { + // Assign 1 number from `groupSize - b` out of `a` groups to this group, + // so we'll have `a - (groupSize - b)` groups of size `groupSize + 1` + // and `groupSize - b + 1` groups of size `groupSize`. In total, we have + // `a + 1` groups. + numGroups += a + 1; + } else { + return 0; + } + } + return numGroups; + } +} diff --git a/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.py b/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.py new file mode 100644 index 00000000000..bc3f53f5281 --- /dev/null +++ b/solutions/2910. Minimum Number of Groups to Create a Valid Assignment/2910.py @@ -0,0 +1,29 @@ +class Solution: + def minGroupsForValidAssignment(self, nums: List[int]) -> int: + count = collections.Counter(nums) + minFreq = min(count.values()) + + for groupSize in range(minFreq, 0, -1): + numGroups = self.getNumGroups(count, groupSize) + if numGroups > 0: + return numGroups + + raise ValueError("Invalid argument") + + def getNumGroups(self, count: Dict[int, int], groupSize: int) -> int: + """Returns the number of groups if each group's size is `groupSize` or `groupSize + 1`.""" + numGroups = 0 + for freq in count.values(): + a = freq // (groupSize + 1) + b = freq % (groupSize + 1) + if b == 0: + # Assign 1 number from `groupSize - b` out of `a` groups to this group, + # so we'll have `a - (groupSize - b)` groups of size `groupSize + 1` + # and `groupSize - b + 1` groups of size `groupSize`. In total, we have + # `a + 1` groups. + numGroups += a + elif groupSize - b <= a: + numGroups += a + 1 + else: + return 0 + return numGroups diff --git a/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.cpp b/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.cpp new file mode 100644 index 00000000000..a0f2fff4a81 --- /dev/null +++ b/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + int minimumChanges(string s, int k) { + const int n = s.length(); + // factors[i] := factors of i + const vector> factors = getFactors(n); + // cost[i][j] := changes to make s[i..j] a semi-palindrome + const vector> cost = getCost(s, n, factors); + // dp[i][j] := the minimum changes to split s[i:] into j valid parts + vector> dp(n + 1, vector(k + 1, n)); + + dp[n][0] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = 1; j <= k; ++j) + for (int l = i + 1; l < n; ++l) + dp[i][j] = min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]); + + return dp[0][k]; + } + + private: + vector> getFactors(int n) { + vector> factors(n + 1); + for (int i = 1; i <= n; ++i) + factors[i].push_back(1); + for (int d = 2; d < n; ++d) + for (int i = d * 2; i <= n; i += d) + factors[i].push_back(d); + return factors; + } + + vector> getCost(const string& s, int n, + const vector>& factors) { + vector> cost(n, vector(n)); + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + const int length = j - i + 1; + int minCost = length; + for (const int d : factors[length]) + minCost = min(minCost, getCost(s, i, j, d)); + cost[i][j] = minCost; + } + return cost; + } + + // Returns the cost to make s[i..j] a semi-palindrome of `d`. + int getCost(const string& s, int i, int j, int d) { + int cost = 0; + for (int offset = 0; offset < d; ++offset) { + int l = i + offset; + int r = j - d + 1 + offset; + while (l < r) { + if (s[l] != s[r]) + ++cost; + l += d; + r -= d; + } + } + return cost; + } +}; diff --git a/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.java b/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.java new file mode 100644 index 00000000000..c9683dc6f56 --- /dev/null +++ b/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.java @@ -0,0 +1,60 @@ +class Solution { + public int minimumChanges(String s, int k) { + final int n = s.length(); + // factors[i] := factors of i + List[] factors = getFactors(n); + // cost[i][j] := changes to make s[i..j] a semi-palindrome + int[][] cost = getCost(s, n, factors); + // dp[i][j] := the minimum changes to split s[i:] into j valid parts + int[][] dp = new int[n + 1][k + 1]; + + Arrays.stream(dp).forEach(A -> Arrays.fill(A, n)); + dp[n][0] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = 1; j <= k; ++j) + for (int l = i + 1; l < n; ++l) + dp[i][j] = Math.min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]); + + return dp[0][k]; + } + + private List[] getFactors(int n) { + List[] factors = new List[n + 1]; + for (int i = 1; i <= n; ++i) + factors[i] = new ArrayList<>(Arrays.asList(1)); + for (int d = 2; d < n; ++d) + for (int i = d * 2; i <= n; i += d) + factors[i].add(d); + return factors; + } + + private int[][] getCost(final String s, int n, List[] factors) { + int[][] cost = new int[n][n]; + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + final int length = j - i + 1; + int minCost = length; + for (final int d : factors[length]) + minCost = Math.min(minCost, getCost(s, i, j, d)); + cost[i][j] = minCost; + } + return cost; + } + + // Returns the cost to make s[i..j] a semi-palindrome of `d`. + private int getCost(final String s, int i, int j, int d) { + int cost = 0; + for (int offset = 0; offset < d; ++offset) { + int l = i + offset; + int r = j - d + 1 + offset; + while (l < r) { + if (s.charAt(l) != s.charAt(r)) + ++cost; + l += d; + r -= d; + } + } + return cost; + } +} diff --git a/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.py b/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.py new file mode 100644 index 00000000000..8c731fd1680 --- /dev/null +++ b/solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.py @@ -0,0 +1,49 @@ +class Solution: + def minimumChanges(self, s: str, k: int) -> int: + n = len(s) + # factors[i] := factors of i + factors = self._getFactors(n) + # cost[i][j] := changes to make s[i..j] a semi-palindrome + cost = self._getCost(s, n, factors) + # dp[i][j] := the minimum changes to split s[i:] into j valid parts + dp = [[n] * (k + 1) for _ in range(n + 1)] + + dp[n][0] = 0 + + for i in range(n - 1, -1, -1): + for j in range(1, k + 1): + for l in range(i + 1, n): + dp[i][j] = min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]) + + return dp[0][k] + + def _getFactors(self, n: int) -> List[List[int]]: + factors = [[1] for _ in range(n + 1)] + for d in range(2, n): + for i in range(d * 2, n + 1, d): + factors[i].append(d) + return factors + + def _getCost(self, s: str, n: int, factors: List[List[int]]) -> List[List[int]]: + cost = [[0] * n for _ in range(n)] + for i in range(n): + for j in range(i + 1, n): + length = j - i + 1 + minCost = length + for d in factors[length]: + minCost = min(minCost, self._getCostD(s, i, j, d)) + cost[i][j] = minCost + return cost + + def _getCostD(self, s: str, i: int, j: int, d: int) -> int: + """Returns the cost to make s[i..j] a semi-palindrome of `d`.""" + cost = 0 + for offset in range(d): + l = i + offset + r = j - d + 1 + offset + while l < r: + if s[l] != s[r]: + cost += 1 + l += d + r -= d + return cost diff --git a/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.cpp b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.cpp new file mode 100644 index 00000000000..5401949151b --- /dev/null +++ b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int numberOfWays(int n, int m, int k, vector& source, + vector& dest) { + constexpr int kMod = 1'000'000'007; + // the number of ways of `source` to `dest` using steps so far + int ans = source[0] == dest[0] && source[1] == dest[1]; + // the number of ways of `source` to dest's row using steps so far + int row = source[0] == dest[0] && source[1] != dest[1]; + // the number of ways of `source` to dest's col using steps so far + int col = source[0] != dest[0] && source[1] == dest[1]; + // the number of ways of `source` to others using steps so far + int others = source[0] != dest[0] && source[1] != dest[1]; + + for (int i = 0; i < k; ++i) { + const int nextAns = (row + col) % kMod; + const int nextRow = static_cast((ans * (m - 1L) + // -self + row * (m - 2L) + //-self, -center + others) % + kMod); + const int nextCol = static_cast((ans * (n - 1L) + // -self + col * (n - 2L) + // -self, -center + others) % + kMod); + const int nextOthers = + static_cast((row * (n - 1L) + // -self + col * (m - 1L) + // -self + others * (m + n - 1 - 3L)) % // -self, -row, -col + kMod); + ans = nextAns; + row = nextRow; + col = nextCol; + others = nextOthers; + } + + return ans; + } +}; diff --git a/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.java b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.java new file mode 100644 index 00000000000..09a08c8ddc9 --- /dev/null +++ b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.java @@ -0,0 +1,35 @@ +class Solution { + public int numberOfWays(int n, int m, int k, int[] source, int[] dest) { + final int kMod = 1_000_000_007; + // the number of ways of `source` to `dest` using steps so far + int ans = (source[0] == dest[0] && source[1] == dest[1]) ? 1 : 0; + // the number of ways of `source` to dest's row using steps so far + int row = (source[0] == dest[0] && source[1] != dest[1]) ? 1 : 0; + // the number of ways of `source` to dest's col using steps so far + int col = (source[0] != dest[0] && source[1] == dest[1]) ? 1 : 0; + // the number of ways of `source` to others using steps so far + int others = (source[0] != dest[0] && source[1] != dest[1]) ? 1 : 0; + + for (int i = 0; i < k; ++i) { + final int nextAns = (row + col) % kMod; + final int nextRow = (int) ((ans * (m - 1L) + // -self + row * (m - 2L) + //-self, -center + others) % + kMod); + final int nextCol = (int) ((ans * (n - 1L) + // -self + col * (n - 2L) + // -self, -center + others) % + kMod); + final int nextOthers = (int) ((row * (n - 1L) + // -self + col * (m - 1L) + // -self + others * (m + n - 1 - 3L)) % // -self, -row, -col + kMod); + ans = nextAns; + row = nextRow; + col = nextCol; + others = nextOthers; + } + + return ans; + } +} diff --git a/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.py b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.py new file mode 100644 index 00000000000..b247dcd024d --- /dev/null +++ b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.py @@ -0,0 +1,29 @@ +class Solution: + def numberOfWays(self, n: int, m: int, k: int, source: List[int], dest: List[int]) -> int: + kMod = 1_000_000_007 + # the number of ways of `source` to `dest` using steps so far + ans = int(source == dest) + # the number of ways of `source` to dest's row using steps so far + row = int(source[0] == dest[0] and source[1] != dest[1]) + # the number of ways of `source` to dest's col using steps so far + col = int(source[0] != dest[0] and source[1] == dest[1]) + # the number of ways of `source` to others using steps so far + others = int(source[0] != dest[0] and source[1] != dest[1]) + + for _ in range(k): + nextAns = (row + col) % kMod + nextRow = (ans * (m - 1) + # -self + row * (m - 2) + # -self, -center + others) % kMod + nextCol = (ans * (n - 1) + # -self + col * (n - 2) + # -self, -center + others) % kMod + nextOthers = (row * (n - 1) + # -self + col * (m - 1) + # -self + others * (m + n - 1 - 3)) % kMod # -self, -row, -col + ans = nextAns + row = nextRow + col = nextCol + others = nextOthers + + return ans diff --git a/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.cpp b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.cpp new file mode 100644 index 00000000000..c84c13be6eb --- /dev/null +++ b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int numberOfWays(int n, int m, int k, vector& source, + vector& dest) { + constexpr int kMod = 1'000'000'007; + // dp[i][0] := the the number of ways of `source` to `dest` using i + // steps dp[i][1] := the the number of ways of `source` to dest's row + // using i steps dp[i][2] := the the number of ways of `source` to + // dest's col using i steps dp[i][3] := the the number of ways of + // `source` to others using i steps + vector> dp(k + 1, vector(4)); + if (source == dest) + dp[0][0] = 1; + else if (source[0] == dest[0]) + dp[0][1] = 1; + else if (source[1] == dest[1]) + dp[0][2] = 1; + else + dp[0][3] = 1; + + for (int i = 1; i <= k; i++) { + dp[i][0] = (dp[i - 1][1] + dp[i - 1][2]) % kMod; + dp[i][1] = ((dp[i - 1][0] * (m - 1L) + // -self + dp[i - 1][1] * (m - 2L) + // -self, -center + dp[i - 1][3]) % + kMod); + dp[i][2] = ((dp[i - 1][0] * (n - 1L) + // -self + dp[i - 1][2] * (n - 2L) + // -self, -center + dp[i - 1][3]) % + kMod); + dp[i][3] = ((dp[i - 1][1] * (n - 1L) + // -self + dp[i - 1][2] * (m - 1L) + // -self + dp[i - 1][3] * (m + n - 1 - 3L)) // -self, -row, -col + % kMod); + } + + return dp[k][0]; + } +}; diff --git a/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.java b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.java new file mode 100644 index 00000000000..45a1b241cd3 --- /dev/null +++ b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.java @@ -0,0 +1,36 @@ +class Solution { + public int numberOfWays(int n, int m, int k, int[] source, int[] dest) { + final int kMod = 1_000_000_007; + // dp[i][0] := the the number of ways of `source` to `dest` using i steps + // dp[i][1] := the the number of ways of `source` to dest's row using i steps + // dp[i][2] := the the number of ways of `source` to dest's col using i steps + // dp[i][3] := the the number of ways of `source` to others using i steps + int[][] dp = new int[k + 1][4]; + if (Arrays.equals(source, dest)) + dp[0][0] = 1; + else if (source[0] == dest[0]) + dp[0][1] = 1; + else if (source[1] == dest[1]) + dp[0][2] = 1; + else + dp[0][3] = 1; + + for (int i = 1; i <= k; i++) { + dp[i][0] = (dp[i - 1][1] + dp[i - 1][2]) % kMod; + dp[i][1] = (int) ((dp[i - 1][0] * (m - 1L) + // -self + dp[i - 1][1] * (m - 2L) + // -self, -center + dp[i - 1][3]) % + kMod); + dp[i][2] = (int) ((dp[i - 1][0] * (n - 1L) + // -self + dp[i - 1][2] * (n - 2L) + // -self, -center + dp[i - 1][3]) % + kMod); + dp[i][3] = (int) ((dp[i - 1][1] * (n - 1L) + // -self + dp[i - 1][2] * (m - 1L) + // -self + dp[i - 1][3] * (m + n - 1 - 3L)) // -self, -row, -col + % kMod); + } + + return dp[k][0]; + } +} diff --git a/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.py b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.py new file mode 100644 index 00000000000..933bc2e7c16 --- /dev/null +++ b/solutions/2912. Number of Ways to Reach Destination in the Grid/2912.py @@ -0,0 +1,30 @@ +class Solution: + def numberOfWays(self, n: int, m: int, k: int, source: List[int], dest: List[int]) -> int: + kMod = 1_000_000_007 + # dp[i][0] := the the number of ways of `source` to `dest` using i steps + # dp[i][1] := the the number of ways of `source` to dest's row using i steps + # dp[i][2] := the the number of ways of `source` to dest's col using i steps + # dp[i][3] := the the number of ways of `source` to others using i steps + dp = [[0] * 4 for _ in range(k + 1)] + if source == dest: + dp[0][0] = 1 + elif source[0] == dest[0]: + dp[0][1] = 1 + elif source[1] == dest[1]: + dp[0][2] = 1 + else: + dp[0][3] = 1 + + for i in range(1, k + 1): + dp[i][0] = (dp[i - 1][1] + dp[i - 1][2]) % kMod + dp[i][1] = (dp[i - 1][0] * (m - 1) + # -self + dp[i - 1][1] * (m - 2) + # -self, -center + dp[i - 1][3]) % kMod + dp[i][2] = (dp[i - 1][0] * (n - 1) + # -self + dp[i - 1][2] * (n - 2) + # -self, -center + dp[i - 1][3]) % kMod + dp[i][3] = (dp[i - 1][1] * (n - 1) + # -self + dp[i - 1][2] * (m - 1) + # -self + dp[i - 1][3] * (m + n - 1 - 3)) % kMod # -self, -row, -col + + return dp[k][0] diff --git a/solutions/2913. Subarrays Distinct Element Sum of Squares I/2913.cpp b/solutions/2913. Subarrays Distinct Element Sum of Squares I/2913.cpp new file mode 100644 index 00000000000..d18ec48a592 --- /dev/null +++ b/solutions/2913. Subarrays Distinct Element Sum of Squares I/2913.cpp @@ -0,0 +1,72 @@ +class SegmentTree { + public: + SegmentTree(int n, int kMod) + : n(n), kMod(kMod), lazy(4 * n), sums(4 * n), squaredSums(4 * n) {} + + void updateRange(int l, int r) { + return updateRange(/*i=*/0, /*start=*/0, /*end=*/n - 1, l, r); + } + + void propagate(int i, int l, int r) { + const int gap = r - l + 1; + // (a + L)^2 + (b + L)^2 + (c + L)^2, where L = lazy[i] + // a^2 + b^2 + c^2 + 2 * L (a + b + c) + L^2 * gap, where gap = 3 + squaredSums[i] += 2 * lazy[i] * sums[i] + lazy[i] * lazy[i] * gap; + squaredSums[i] %= kMod; + sums[i] += lazy[i] * gap; + sums[i] %= kMod; + if (l < r) { + lazy[i * 2 + 1] += lazy[i]; + lazy[i * 2 + 2] += lazy[i]; + } + lazy[i] = 0; + } + + int getTreeSquaredSums() { + return squaredSums[0]; + } + + private: + const int kMod; + const int n; + vector lazy; + vector sums; + vector squaredSums; + + void updateRange(int i, int start, int end, int l, int r) { + if (lazy[i] > 0) + propagate(i, start, end); + if (end < l || start > r) + return; + if (start >= l && end <= r) { + lazy[i] = 1; + propagate(i, start, end); + return; + } + const int mid = (start + end) / 2; + updateRange(i * 2 + 1, start, mid, l, r); + updateRange(i * 2 + 2, mid + 1, end, l, r); + sums[i] = (sums[i * 2 + 1] + sums[i * 2 + 2]) % kMod; + squaredSums[i] = (squaredSums[i * 2 + 1] + squaredSums[i * 2 + 2]) % kMod; + } +}; + +class Solution { + public: + int sumCounts(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + unordered_map lastSeen; + SegmentTree tree(n, kMod); + + for (int r = 0; r < n; ++r) { + const int l = lastSeen.contains(nums[r]) ? lastSeen[nums[r]] + 1 : 0; + tree.updateRange(l, r); + lastSeen[nums[r]] = r; + ans = (ans + tree.getTreeSquaredSums()) % kMod; + } + + return ans; + } +}; diff --git a/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.cpp b/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.cpp new file mode 100644 index 00000000000..558f70fa842 --- /dev/null +++ b/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int minChanges(string s) { + int ans = 0; + + for (int i = 0; i + 1 < s.length(); i += 2) + if (s[i] != s[i + 1]) + ++ans; + + return ans; + } +}; diff --git a/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.java b/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.java new file mode 100644 index 00000000000..8f3ad328e0b --- /dev/null +++ b/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.java @@ -0,0 +1,11 @@ +class Solution { + public int minChanges(String s) { + int ans = 0; + + for (int i = 0; i + 1 < s.length(); i += 2) + if (s.charAt(i) != s.charAt(i + 1)) + ++ans; + + return ans; + } +} diff --git a/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.py b/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.py new file mode 100644 index 00000000000..4a53a8c13c6 --- /dev/null +++ b/solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.py @@ -0,0 +1,3 @@ +class Solution: + def minChanges(self, s: str) -> int: + return sum(a != b for a, b in zip(s[::2], s[1::2])) diff --git a/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.cpp b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.cpp new file mode 100644 index 00000000000..5b8ac87d9e6 --- /dev/null +++ b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int lengthOfLongestSubsequence(vector& nums, int target) { + // dp[i] := the maximum length of any subsequence of numbers so far that + // sum to j + vector dp(target + 1); + + for (const int num : nums) + for (int i = target; i >= num; --i) + if (i == num || dp[i - num] > 0) + dp[i] = max(dp[i], 1 + dp[i - num]); + + return dp[target] > 0 ? dp[target] : -1; + } +}; diff --git a/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.java b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.java new file mode 100644 index 00000000000..57bdf4cbd8a --- /dev/null +++ b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.java @@ -0,0 +1,14 @@ +class Solution { + public int lengthOfLongestSubsequence(List nums, int target) { + // dp[i] := the maximum length of any subsequence of numbers so far that + // sum to j + int[] dp = new int[target + 1]; + + for (final int num : nums) + for (int i = target; i >= num; --i) + if (i == num || dp[i - num] > 0) + dp[i] = Math.max(dp[i], 1 + dp[i - num]); + + return dp[target] > 0 ? dp[target] : -1; + } +} diff --git a/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.py b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.py new file mode 100644 index 00000000000..d3b43251e2e --- /dev/null +++ b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915-2.py @@ -0,0 +1,12 @@ +class Solution: + def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: + # dp[i] := the maximum length of any subsequence of numbers so far that + # sum to j + dp = [0] * (target + 1) + + for num in nums: + for i in range(target, num - 1, -1): + if i == num or dp[i - num] > 0: + dp[i] = max(dp[i], 1 + dp[i - num]) + + return dp[target] if dp[target] > 0 else -1 diff --git a/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.cpp b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.cpp new file mode 100644 index 00000000000..488a772e9fa --- /dev/null +++ b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int lengthOfLongestSubsequence(vector& nums, int target) { + const int n = nums.size(); + // dp[i][j] := the maximum length of any subsequence of the first i numbers + // that sum to j + vector> dp(n + 1, vector(target + 1, -1)); + + for (int i = 0; i <= n; ++i) + dp[i][0] = 0; + + for (int i = 1; i <= n; ++i) { + const int num = nums[i - 1]; + for (int j = 1; j <= target; ++j) + // 1. Skip `num`. + if (j < num || dp[i - 1][j - num] == -1) + dp[i][j] = dp[i - 1][j]; + // 2. Skip `num` or pick `num`. + else + dp[i][j] = max(dp[i - 1][j], 1 + dp[i - 1][j - num]); + } + + return dp[n][target]; + } +}; diff --git a/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.java b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.java new file mode 100644 index 00000000000..77f2d8fa8e4 --- /dev/null +++ b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.java @@ -0,0 +1,26 @@ +class Solution { + public int lengthOfLongestSubsequence(List nums, int target) { + final int n = nums.size(); + // dp[i][j] := the maximum length of any subsequence of the first i numbers + // that sum to j + int[][] dp = new int[n + 1][target + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, -1)); + + for (int i = 0; i <= n; ++i) + dp[i][0] = 0; + + for (int i = 1; i <= n; ++i) { + final int num = nums.get(i - 1); + for (int j = 1; j <= target; ++j) { + // 1. Skip `num`. + if (j < num || dp[i - 1][j - num] == -1) + dp[i][j] = dp[i - 1][j]; + // 2. Skip `num` or pick `num`. + else + dp[i][j] = Math.max(dp[i - 1][j], 1 + dp[i - 1][j - num]); + } + } + + return dp[n][target]; + } +} diff --git a/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.py b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.py new file mode 100644 index 00000000000..ad565643abe --- /dev/null +++ b/solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.py @@ -0,0 +1,21 @@ +class Solution: + def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: + n = len(nums) + # dp[i][j] := the maximum length of any subsequence of the first i numbers + # that sum to j + dp = [[-1] * (target + 1) for _ in range(n + 1)] + + for i in range(n + 1): + dp[i][0] = 0 + + for i in range(1, n + 1): + num = nums[i - 1] + for j in range(1, target + 1): + # 1. Skip `num`. + if j < num or dp[i - 1][j - num] == -1: + dp[i][j] = dp[i - 1][j] + # 2. Skip `num` or pick `num`. + else: + dp[i][j] = max(dp[i - 1][j], 1 + dp[i - 1][j - num]) + + return dp[n][target] diff --git a/solutions/2916. Subarrays Distinct Element Sum of Squares II/2916.cpp b/solutions/2916. Subarrays Distinct Element Sum of Squares II/2916.cpp new file mode 100644 index 00000000000..d18ec48a592 --- /dev/null +++ b/solutions/2916. Subarrays Distinct Element Sum of Squares II/2916.cpp @@ -0,0 +1,72 @@ +class SegmentTree { + public: + SegmentTree(int n, int kMod) + : n(n), kMod(kMod), lazy(4 * n), sums(4 * n), squaredSums(4 * n) {} + + void updateRange(int l, int r) { + return updateRange(/*i=*/0, /*start=*/0, /*end=*/n - 1, l, r); + } + + void propagate(int i, int l, int r) { + const int gap = r - l + 1; + // (a + L)^2 + (b + L)^2 + (c + L)^2, where L = lazy[i] + // a^2 + b^2 + c^2 + 2 * L (a + b + c) + L^2 * gap, where gap = 3 + squaredSums[i] += 2 * lazy[i] * sums[i] + lazy[i] * lazy[i] * gap; + squaredSums[i] %= kMod; + sums[i] += lazy[i] * gap; + sums[i] %= kMod; + if (l < r) { + lazy[i * 2 + 1] += lazy[i]; + lazy[i * 2 + 2] += lazy[i]; + } + lazy[i] = 0; + } + + int getTreeSquaredSums() { + return squaredSums[0]; + } + + private: + const int kMod; + const int n; + vector lazy; + vector sums; + vector squaredSums; + + void updateRange(int i, int start, int end, int l, int r) { + if (lazy[i] > 0) + propagate(i, start, end); + if (end < l || start > r) + return; + if (start >= l && end <= r) { + lazy[i] = 1; + propagate(i, start, end); + return; + } + const int mid = (start + end) / 2; + updateRange(i * 2 + 1, start, mid, l, r); + updateRange(i * 2 + 2, mid + 1, end, l, r); + sums[i] = (sums[i * 2 + 1] + sums[i * 2 + 2]) % kMod; + squaredSums[i] = (squaredSums[i * 2 + 1] + squaredSums[i * 2 + 2]) % kMod; + } +}; + +class Solution { + public: + int sumCounts(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + unordered_map lastSeen; + SegmentTree tree(n, kMod); + + for (int r = 0; r < n; ++r) { + const int l = lastSeen.contains(nums[r]) ? lastSeen[nums[r]] + 1 : 0; + tree.updateRange(l, r); + lastSeen[nums[r]] = r; + ans = (ans + tree.getTreeSquaredSums()) % kMod; + } + + return ans; + } +}; diff --git a/solutions/2917. Find the K-or of an Array/2917.cpp b/solutions/2917. Find the K-or of an Array/2917.cpp new file mode 100644 index 00000000000..e69de29bb2d diff --git a/solutions/2917. Find the K-or of an Array/2917.java b/solutions/2917. Find the K-or of an Array/2917.java new file mode 100644 index 00000000000..b50954ad388 --- /dev/null +++ b/solutions/2917. Find the K-or of an Array/2917.java @@ -0,0 +1,17 @@ +class Solution { + public int findKOr(int[] nums, int k) { + final int kMaxBit = 30; + int ans = 0; + + for (int i = 0; i <= kMaxBit; ++i) { + final int finalI = i; + final int count = (int) Arrays.stream(nums) + .filter(num -> (num >> finalI & 1) == 1) // + .count(); + if (count >= k) + ans += Math.pow(2, i); + } + + return ans; + } +} diff --git a/solutions/2917. Find the K-or of an Array/2917.py b/solutions/2917. Find the K-or of an Array/2917.py new file mode 100644 index 00000000000..d601923776f --- /dev/null +++ b/solutions/2917. Find the K-or of an Array/2917.py @@ -0,0 +1,6 @@ +class Solution: + def findKOr(self, nums: List[int], k: int) -> int: + kMaxBit = 30 + return sum(2**i + for i in range(kMaxBit + 1) + if sum(num >> i & 1 for num in nums) >= k) diff --git a/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.cpp b/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.cpp new file mode 100644 index 00000000000..9715db9359b --- /dev/null +++ b/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + long long minSum(vector& nums1, vector& nums2) { + const long sum1 = accumulate(nums1.begin(), nums1.end(), 0L); + const long sum2 = accumulate(nums2.begin(), nums2.end(), 0L); + const int zero1 = ranges::count(nums1, 0); + const int zero2 = ranges::count(nums2, 0); + if (zero1 == 0 && sum1 < sum2 + zero2) + return -1; + if (zero2 == 0 && sum2 < sum1 + zero1) + return -1; + return max(sum1 + zero1, sum2 + zero2); + } +}; diff --git a/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.java b/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.java new file mode 100644 index 00000000000..a145de17a9d --- /dev/null +++ b/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.java @@ -0,0 +1,13 @@ +class Solution { + public long minSum(int[] nums1, int[] nums2) { + long sum1 = Arrays.stream(nums1).asLongStream().sum(); + long sum2 = Arrays.stream(nums2).asLongStream().sum(); + long zero1 = Arrays.stream(nums1).filter(num -> num == 0).count(); + long zero2 = Arrays.stream(nums2).filter(num -> num == 0).count(); + if (zero1 == 0 && sum1 < sum2 + zero2) + return -1; + if (zero2 == 0 && sum2 < sum1 + zero1) + return -1; + return Math.max(sum1 + zero1, sum2 + zero2); + } +} diff --git a/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.py b/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.py new file mode 100644 index 00000000000..3101aa5a75c --- /dev/null +++ b/solutions/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros/2918.py @@ -0,0 +1,11 @@ +class Solution: + def minSum(self, nums1: List[int], nums2: List[int]) -> int: + sum1 = sum(nums1) + sum2 = sum(nums2) + zero1 = nums1.count(0) + zero2 = nums2.count(0) + if zero1 == 0 and sum1 < sum2 + zero2: + return -1 + if zero2 == 0 and sum2 < sum1 + zero1: + return -1 + return max(sum1 + zero1, sum2 + zero2) diff --git a/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.cpp b/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.cpp new file mode 100644 index 00000000000..ec642c358aa --- /dev/null +++ b/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + long long minIncrementOperations(std::vector& nums, int k) { + // the minimum operations to increase nums[i - 3] and nums[0..i - 3) + long prev3 = 0; + // the minimum operations to increase nums[i - 2] and nums[0..i - 2) + long prev2 = 0; + // the minimum operations to increase nums[i - 1] and nums[0..i - 1) + long prev1 = 0; + + for (const int& num : nums) { + const long dp = min({prev1, prev2, prev3}) + max(0, k - num); + prev3 = prev2; + prev2 = prev1; + prev1 = dp; + } + + return min({prev1, prev2, prev3}); + } +}; diff --git a/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.java b/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.java new file mode 100644 index 00000000000..1dc71ca1e56 --- /dev/null +++ b/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.java @@ -0,0 +1,19 @@ +class Solution { + public long minIncrementOperations(int[] nums, int k) { + // the minimum operations to increase nums[i - 3] and nums[0..i - 3) + long prev3 = 0; + // the minimum operations to increase nums[i - 2] and nums[0..i - 2) + long prev2 = 0; + // the minimum operations to increase nums[i - 1] and nums[0..i - 1) + long prev1 = 0; + + for (final int num : nums) { + final long dp = Math.min(prev1, Math.min(prev2, prev3)) + Math.max(0, k - num); + prev3 = prev2; + prev2 = prev1; + prev1 = dp; + } + + return Math.min(prev1, Math.min(prev2, prev3)); + } +} diff --git a/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.py b/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.py new file mode 100644 index 00000000000..cbb4350b17d --- /dev/null +++ b/solutions/2919. Minimum Increment Operations to Make Array Beautiful/2919.py @@ -0,0 +1,16 @@ +class Solution: + def minIncrementOperations(self, nums: List[int], k: int) -> int: + # the minimum operations to increase nums[i - 3] and nums[0..i - 3) + prev3 = 0 + # the minimum operations to increase nums[i - 2] and nums[0..i - 2) + prev2 = 0 + # the minimum operations to increase nums[i - 1] and nums[0..i - 1) + prev1 = 0 + + for num in nums: + dp = min(prev1, prev2, prev3) + max(0, k - num) + prev3 = prev2 + prev2 = prev1 + prev1 = dp + + return min(prev1, prev2, prev3) diff --git a/solutions/292. Nim Game/292.cpp b/solutions/292. Nim Game/292.cpp new file mode 100644 index 00000000000..6f19c08885f --- /dev/null +++ b/solutions/292. Nim Game/292.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool canWinNim(int n) { + return n % 4 != 0; + } +}; diff --git a/solutions/292. Nim Game/292.java b/solutions/292. Nim Game/292.java new file mode 100644 index 00000000000..26f746607e2 --- /dev/null +++ b/solutions/292. Nim Game/292.java @@ -0,0 +1,5 @@ +class Solution { + public boolean canWinNim(int n) { + return n % 4 != 0; + } +} diff --git a/solutions/292. Nim Game/292.py b/solutions/292. Nim Game/292.py new file mode 100644 index 00000000000..110a52d2455 --- /dev/null +++ b/solutions/292. Nim Game/292.py @@ -0,0 +1,3 @@ +class Solution: + def canWinNim(self, n: int) -> bool: + return n % 4 != 0 diff --git a/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.cpp b/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.cpp new file mode 100644 index 00000000000..e6590ecc2d0 --- /dev/null +++ b/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + int maximumPoints(vector>& edges, vector& coins, int k) { + const int n = coins.size(); + vector> graph(n); + vector> mem(n, vector(kMaxHalved + 1, -1)); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + return dfs(graph, 0, /*prev=*/-1, coins, k, /*halved=*/0, mem); + } + + private: + static constexpr int kMaxCoin = 10000; + static constexpr int kMaxHalved = 13; // log2(kMaxCoin) = 13 + + int dfs(const vector>& graph, int u, int prev, + const vector& coins, int k, int halved, + vector>& mem) { + // All the children will be 0, so no need to explore. + if (halved > kMaxHalved) + return 0; + if (mem[u][halved] != -1) + return mem[u][halved]; + + const int val = coins[u] / (1 << halved); + int takeAll = val - k; + int takeHalf = floor(val / 2.0); + + for (const int v : graph[u]) { + if (v == prev) + continue; + takeAll += dfs(graph, v, u, coins, k, halved, mem); + takeHalf += dfs(graph, v, u, coins, k, halved + 1, mem); + } + + return mem[u][halved] = max(takeAll, takeHalf); + } +}; diff --git a/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.java b/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.java new file mode 100644 index 00000000000..658486cd2e2 --- /dev/null +++ b/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.java @@ -0,0 +1,45 @@ +class Solution { + public int maximumPoints(int[][] edges, int[] coins, int k) { + final int n = coins.length; + List[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + Integer[][] mem = new Integer[n][kMaxHalved + 1]; + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + return dfs(graph, 0, /*prev=*/-1, coins, k, /*halved=*/0, mem); + } + + private static final int kMaxCoin = 10000; + private static final int kMaxHalved = (int) (Math.log(kMaxCoin) / Math.log(2)) + 1; + + private int dfs(List[] graph, int u, int prev, int[] coins, int k, int halved, + Integer[][] mem) { + // All the children will be 0, so no need to explore. + if (halved > kMaxHalved) + return 0; + if (mem[u][halved] != null) + return mem[u][halved]; + + final int val = coins[u] / (1 << halved); + int takeAll = val - k; + int takeHalf = (int) Math.floor(val / 2.0); + + for (final int v : graph[u]) { + if (v == prev) + continue; + takeAll += dfs(graph, v, u, coins, k, halved, mem); + takeHalf += dfs(graph, v, u, coins, k, halved + 1, mem); + } + + return mem[u][halved] = Math.max(takeAll, takeHalf); + } +} diff --git a/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.py b/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.py new file mode 100644 index 00000000000..8bf45b113a4 --- /dev/null +++ b/solutions/2920. Maximum Points After Collecting Coins From All Nodes/2920.py @@ -0,0 +1,30 @@ +class Solution: + def maximumPoints(self, edges: List[List[int]], coins: List[int], k: int) -> int: + kMaxCoin = 10000 + kMaxHalved = int(kMaxCoin).bit_length() + n = len(coins) + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + @functools.lru_cache(None) + def dfs(u: int, prev: int, halved: int) -> int: + # All the children will be 0, so no need to explore. + if halved > kMaxHalved: + return 0 + + val = coins[u] // (1 << halved) + takeAll = val - k + takeHalf = math.floor(val / 2) + + for v in graph[u]: + if v == prev: + continue + takeAll += dfs(v, u, halved) + takeHalf += dfs(v, u, halved + 1) + + return max(takeAll, takeHalf) + + return dfs(0, -1, 0) diff --git a/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.cpp b/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.cpp new file mode 100644 index 00000000000..c273a9f842a --- /dev/null +++ b/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.cpp @@ -0,0 +1,54 @@ +class FenwickTree { + public: + FenwickTree(int n) : vals(n + 1) {} + + void maximize(int i, int val) { + while (i < vals.size()) { + vals[i] = max(vals[i], val); + i += lowbit(i); + } + } + + int get(int i) const { + int res = 0; + while (i > 0) { + res = max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private: + vector vals; + + static int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + // Same as 2907. Maximum Profitable Triplets With Increasing Prices I + int maxProfit(vector& prices, vector& profits) { + const int maxPrice = ranges::max(prices); + int ans = -1; + FenwickTree maxProfitTree1(maxPrice); + FenwickTree maxProfitTree2(maxPrice); + + for (int i = 0; i < prices.size(); ++i) { + const int price = prices[i]; + const int profit = profits[i]; + // max(proftis[i]) + const int maxProfit1 = maxProfitTree1.get(price - 1); + // max(proftis[i]) + max(profits[j]) + const int maxProfit2 = maxProfitTree2.get(price - 1); + maxProfitTree1.maximize(price, profit); + if (maxProfit1 > 0) + maxProfitTree2.maximize(price, profit + maxProfit1); + if (maxProfit2 > 0) + ans = max(ans, profit + maxProfit2); + } + + return ans; + } +}; diff --git a/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.java b/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.java new file mode 100644 index 00000000000..e05ae7a3be6 --- /dev/null +++ b/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.java @@ -0,0 +1,53 @@ +class FenwickTree { + public FenwickTree(int n) { + vals = new int[n + 1]; + } + + public void maximize(int i, int val) { + while (i < vals.length) { + vals[i] = Math.max(vals[i], val); + i += lowbit(i); + } + } + + public int get(int i) { + int res = 0; + while (i > 0) { + res = Math.max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private int[] vals; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + // Same as 2907. Maximum Profitable Triplets With Increasing Prices I + public int maxProfit(int[] prices, int[] profits) { + final int maxPrice = Arrays.stream(prices).max().getAsInt(); + int ans = -1; + FenwickTree maxProfitTree1 = new FenwickTree(maxPrice); + FenwickTree maxProfitTree2 = new FenwickTree(maxPrice); + + for (int i = 0; i < prices.length; ++i) { + final int price = prices[i]; + final int profit = profits[i]; + // max(profits[i]) + final int maxProfit1 = maxProfitTree1.get(price - 1); + // max(proftis[i]) + max(profits[j]) + final int maxProfit2 = maxProfitTree2.get(price - 1); + maxProfitTree1.maximize(price, profit); + if (maxProfit1 > 0) + maxProfitTree2.maximize(price, profit + maxProfit1); + if (maxProfit2 > 0) + ans = Math.max(ans, profit + maxProfit2); + } + + return ans; + } +} diff --git a/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.py b/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.py new file mode 100644 index 00000000000..779a8389bdd --- /dev/null +++ b/solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.py @@ -0,0 +1,41 @@ +class FenwickTree: + def __init__(self, n: int): + self.vals = [0] * (n + 1) + + def maximize(self, i: int, val: int) -> None: + while i < len(self.vals): + self.vals[i] = max(self.vals[i], val) + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + res = 0 + while i > 0: + res = max(res, self.vals[i]) + i -= FenwickTree.lowbit(i) + return res + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + # Same as 2907. Maximum Profitable Triplets With Increasing Prices I + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + ans = -1 + maxPrice = max(prices) + maxProfitTree1 = FenwickTree(maxPrice) + maxProfitTree2 = FenwickTree(maxPrice) + + for price, profit in zip(prices, profits): + # max(proftis[i]) + maxProfit1 = maxProfitTree1.get(price - 1) + # max(proftis[i]) + max(profits[j]) + maxProfit2 = maxProfitTree2.get(price - 1) + maxProfitTree1.maximize(price, profit) + if maxProfit1 > 0: + maxProfitTree2.maximize(price, profit + maxProfit1) + if maxProfit2 > 0: + ans = max(ans, profit + maxProfit2) + + return ans diff --git a/solutions/2922. Market Analysis III/2922.sql b/solutions/2922. Market Analysis III/2922.sql new file mode 100644 index 00000000000..ed3a0895d10 --- /dev/null +++ b/solutions/2922. Market Analysis III/2922.sql @@ -0,0 +1,23 @@ +WITH + Sellers AS( + SELECT + Users.seller_id, + COUNT(DISTINCT Orders.item_id) AS num_items + FROM Users + INNER JOIN Orders + USING (seller_id) + INNER JOIN Items + USING (item_id) + WHERE Items.item_brand != Users.favorite_brand + GROUP BY 1 + ), + RankedSellers AS ( + SELECT + seller_id, + num_items, + RANK() OVER(ORDER BY num_items DESC) AS `rank` + FROM Sellers + ) +SELECT seller_id, num_items +FROM RankedSellers +WHERE `rank` = 1; diff --git a/solutions/2923. Find Champion I/2923-2.cpp b/solutions/2923. Find Champion I/2923-2.cpp new file mode 100644 index 00000000000..0bdc8313d20 --- /dev/null +++ b/solutions/2923. Find Champion I/2923-2.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int findChampion(vector>& grid) { + for (int i = 0; i < grid.size(); ++i) + if (accumulate(grid[i].begin(), grid[i].end(), 0) == grid.size() - 1) + return i; + return -1; + } +}; diff --git a/solutions/2923. Find Champion I/2923-2.java b/solutions/2923. Find Champion I/2923-2.java new file mode 100644 index 00000000000..331c14506fe --- /dev/null +++ b/solutions/2923. Find Champion I/2923-2.java @@ -0,0 +1,8 @@ +class Solution { + public int findChampion(int[][] grid) { + for (int i = 0; i < grid.length; ++i) + if (Arrays.stream(grid[i]).sum() == grid.length - 1) + return i; + return -1; + } +} diff --git a/solutions/2923. Find Champion I/2923-2.py b/solutions/2923. Find Champion I/2923-2.py new file mode 100644 index 00000000000..20664a23447 --- /dev/null +++ b/solutions/2923. Find Champion I/2923-2.py @@ -0,0 +1,3 @@ +class Solution: + def findChampion(self, grid: List[List[int]]) -> int: + return max(range(len(grid)), key=lambda i: sum(grid[i])) diff --git a/solutions/2923. Find Champion I/2923.cpp b/solutions/2923. Find Champion I/2923.cpp new file mode 100644 index 00000000000..b72c8a16b1f --- /dev/null +++ b/solutions/2923. Find Champion I/2923.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int findChampion(vector>& grid) { + const int n = grid.size(); + int ans = -1; + int count = 0; + vector inDegrees(n); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + grid[i][j] == 1 ? ++inDegrees[j] : ++inDegrees[i]; + } + + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) { + ++count; + ans = i; + } + + return count > 1 ? -1 : ans; + } +}; diff --git a/solutions/2923. Find Champion I/2923.java b/solutions/2923. Find Champion I/2923.java new file mode 100644 index 00000000000..4c365b528cb --- /dev/null +++ b/solutions/2923. Find Champion I/2923.java @@ -0,0 +1,26 @@ +class Solution { + public int findChampion(int[][] grid) { + final int n = grid.length; + int ans = -1; + int count = 0; + int[] inDegrees = new int[n]; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + if (i == j) + continue; + if (grid[i][j] == 1) + ++inDegrees[j]; + else + ++inDegrees[i]; + } + + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) { + ++count; + ans = i; + } + + return count > 1 ? -1 : ans; + } +} diff --git a/solutions/2923. Find Champion I/2923.py b/solutions/2923. Find Champion I/2923.py new file mode 100644 index 00000000000..1ca13e9ee0f --- /dev/null +++ b/solutions/2923. Find Champion I/2923.py @@ -0,0 +1,16 @@ +class Solution: + def findChampion(self, grid: List[List[int]]) -> int: + n = len(grid) + inDegrees = [0] * n + + for i in range(n): + for j in range(n): + if i == j: + continue + if grid[i][j] == 1: + inDegrees[j] += 1 + else: + inDegrees[i] += 1 + + return -1 if inDegrees.count(0) > 1 \ + else inDegrees.index(0) diff --git a/solutions/2924. Find Champion II/2924.cpp b/solutions/2924. Find Champion II/2924.cpp new file mode 100644 index 00000000000..f52f5784cf7 --- /dev/null +++ b/solutions/2924. Find Champion II/2924.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int findChampion(int n, vector>& edges) { + int ans = -1; + int count = 0; + vector inDegrees(n); + + for (const vector& edge : edges) { + const int v = edge[1]; + ++inDegrees[v]; + } + + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) { + ++count; + ans = i; + } + + return count > 1 ? -1 : ans; + } +}; diff --git a/solutions/2924. Find Champion II/2924.java b/solutions/2924. Find Champion II/2924.java new file mode 100644 index 00000000000..f5d28b20eed --- /dev/null +++ b/solutions/2924. Find Champion II/2924.java @@ -0,0 +1,20 @@ +class Solution { + public int findChampion(int n, int[][] edges) { + int ans = -1; + int count = 0; + int[] inDegrees = new int[n]; + + for (int[] edge : edges) { + final int v = edge[1]; + ++inDegrees[v]; + } + + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) { + ++count; + ans = i; + } + + return count > 1 ? -1 : ans; + } +} diff --git a/solutions/2924. Find Champion II/2924.py b/solutions/2924. Find Champion II/2924.py new file mode 100644 index 00000000000..5d2cef17ed9 --- /dev/null +++ b/solutions/2924. Find Champion II/2924.py @@ -0,0 +1,9 @@ +class Solution: + def findChampion(self, n: int, edges: List[List[int]]) -> int: + inDegrees = [0] * n + + for _, v in edges: + inDegrees[v] += 1 + + return -1 if inDegrees.count(0) > 1 \ + else inDegrees.index(0) diff --git a/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.cpp b/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.cpp new file mode 100644 index 00000000000..8860e9bc176 --- /dev/null +++ b/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + long long maximumScoreAfterOperations(vector>& edges, + vector& values) { + vector> tree(values.size()); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + return accumulate(values.begin(), values.end(), 0L) - + dfs(tree, 0, /*prev=*/-1, values); + } + + private: + // Returns the minimum of sum to be reduced. + long dfs(const vector>& tree, int u, int prev, + const vector& values) { + if (u > 0 && tree[u].size() == 1) + return values[u]; + long childrenSum = 0; + for (const int v : tree[u]) + if (v != prev) + childrenSum += dfs(tree, v, u, values); + return min(childrenSum, static_cast(values[u])); + } +}; diff --git a/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.java b/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.java new file mode 100644 index 00000000000..60017629118 --- /dev/null +++ b/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.java @@ -0,0 +1,27 @@ +class Solution { + public long maximumScoreAfterOperations(int[][] edges, int[] values) { + List[] tree = new ArrayList[values.length]; + + for (int i = 0; i < values.length; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + return Arrays.stream(values).sum() - dfs(tree, 0, /*prev=*/-1, values); + } + + private long dfs(List[] tree, int u, int prev, int[] values) { + if (u > 0 && tree[u].size() == 1) + return values[u]; + long childrenSum = 0; + for (final int v : tree[u]) + if (v != prev) + childrenSum += dfs(tree, v, u, values); + return Math.min(childrenSum, 1L * values[u]); + } +} diff --git a/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.py b/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.py new file mode 100644 index 00000000000..321790e00c3 --- /dev/null +++ b/solutions/2925. Maximum Score After Applying Operations on a Tree/2925.py @@ -0,0 +1,17 @@ +class Solution: + def maximumScoreAfterOperations(self, edges: List[List[int]], values: List[int]) -> int: + tree = [[] for _ in values] + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def dfs(u: int, prev: int) -> None: + if u > 0 and len(tree[u]) == 1: + return values[u] + childrenSum = sum(dfs(v, u) + for v in tree[u] + if v != prev) + return min(childrenSum, values[u]) + + return sum(values) - dfs(0, -1) diff --git a/solutions/2926. Maximum Balanced Subsequence Sum/2926.cpp b/solutions/2926. Maximum Balanced Subsequence Sum/2926.cpp new file mode 100644 index 00000000000..e2d3807fae7 --- /dev/null +++ b/solutions/2926. Maximum Balanced Subsequence Sum/2926.cpp @@ -0,0 +1,60 @@ +class FenwickTree { + public: + FenwickTree(int n) : vals(n + 1) {} + + // Updates the maximum sum of subsequence ending in (i - 1) with `val`. + void maximize(int i, long val) { + while (i < vals.size()) { + vals[i] = max(vals[i], val); + i += lowbit(i); + } + } + + // Returns the maximum sum of subsequence ending in (i - 1). + long get(int i) const { + long res = 0; + while (i > 0) { + res = max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private: + vector vals; + + static int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + long long maxBalancedSubsequenceSum(vector& nums) { + // Let's define maxSum[i] := subsequence with the maximum sum ending in i + // By observation: + // nums[i] - nums[j] >= i - j + // => nums[i] - i >= nums[j] - j + // So, if nums[i] - i >= nums[j] - j, where i > j, + // maxSum[i] = max(maxSum[i], maxSum[j] + nums[i]) + long ans = LONG_MIN; + FenwickTree tree(nums.size()); + + for (const auto& [_, i] : getPairs(nums)) { + const long subseqSum = tree.get(i) + nums[i]; + tree.maximize(i + 1, subseqSum); + ans = max(ans, subseqSum); + } + + return ans; + } + + private: + vector> getPairs(const vector& nums) { + vector> pairs; + for (int i = 0; i < nums.size(); ++i) + pairs.emplace_back(nums[i] - i, i); + ranges::sort(pairs); + return pairs; + } +}; diff --git a/solutions/2926. Maximum Balanced Subsequence Sum/2926.java b/solutions/2926. Maximum Balanced Subsequence Sum/2926.java new file mode 100644 index 00000000000..157be529337 --- /dev/null +++ b/solutions/2926. Maximum Balanced Subsequence Sum/2926.java @@ -0,0 +1,59 @@ +class FenwickTree { + public FenwickTree(int n) { + vals = new long[n + 1]; + } + + // Updates the maximum sum of subsequence ending in (i - 1) with `val`. + public void maximize(int i, long val) { + while (i < vals.length) { + vals[i] = Math.max(vals[i], val); + i += lowbit(i); + } + } + + // Returns the maximum sum of subsequence ending in (i - 1). + public long get(int i) { + long res = 0; + while (i > 0) { + res = Math.max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private long[] vals; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public long maxBalancedSubsequenceSum(int[] nums) { + // Let's define maxSum[i] := subsequence with the maximum sum ending in i + // By observation: + // nums[i] - nums[j] >= i - j + // => nums[i] - i >= nums[j] - j + // So, if nums[i] - i >= nums[j] - j, where i > j, + // maxSum[i] = max(maxSum[i], maxSum[j] + nums[i]) + long ans = Long.MIN_VALUE; + FenwickTree tree = new FenwickTree(nums.length); + + for (Pair pair : getPairs(nums)) { + final int i = pair.getValue(); + final long subseqSum = tree.get(i) + nums[i]; + tree.maximize(i + 1, subseqSum); + ans = Math.max(ans, subseqSum); + } + + return ans; + } + + private List> getPairs(int[] nums) { + List> pairs = new ArrayList<>(); + for (int i = 0; i < nums.length; ++i) + pairs.add(new Pair<>(nums[i] - i, i)); + pairs.sort((p1, p2) -> p1.getKey() - p2.getKey()); + return pairs; + } +} diff --git a/solutions/2926. Maximum Balanced Subsequence Sum/2926.py b/solutions/2926. Maximum Balanced Subsequence Sum/2926.py new file mode 100644 index 00000000000..9ff9faf4342 --- /dev/null +++ b/solutions/2926. Maximum Balanced Subsequence Sum/2926.py @@ -0,0 +1,40 @@ +class FenwickTree: + def __init__(self, n: int): + self.vals = [0] * (n + 1) + + def maximize(self, i: int, val: int) -> None: + """Updates the maximum sum of subsequence ending in (i - 1) with `val`.""" + while i < len(self.vals): + self.vals[i] = max(self.vals[i], val) + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + """Returns the maximum sum of subsequence ending in (i - 1).""" + res = 0 + while i > 0: + res = max(res, self.vals[i]) + i -= FenwickTree.lowbit(i) + return res + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def maxBalancedSubsequenceSum(self, nums: List[int]) -> int: + # Let's define maxSum[i] := subsequence with the maximum sum ending in i + # By observation: + # nums[i] - nums[j] >= i - j + # => nums[i] - i >= nums[j] - j + # So, if nums[i] - i >= nums[j] - j, where i > j, + # maxSum[i] = max(maxSum[i], maxSum[j] + nums[i]) + ans = -math.inf + tree = FenwickTree(len(nums)) + + for _, i in sorted([(num - i, i) for i, num in enumerate(nums)]): + subseqSum = tree.get(i) + nums[i] + tree.maximize(i + 1, subseqSum) + ans = max(ans, subseqSum) + + return ans diff --git a/solutions/2927. Distribute Candies Among Children III/2927.cpp b/solutions/2927. Distribute Candies Among Children III/2927.cpp new file mode 100644 index 00000000000..8fa675bf1f3 --- /dev/null +++ b/solutions/2927. Distribute Candies Among Children III/2927.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + long long distributeCandies(int n, int limit) { + const int limitPlusOne = limit + 1; + const long oneChildExceedsLimit = ways(n - limitPlusOne); + const long twoChildrenExceedLimit = ways(n - 2 * limitPlusOne); + const long threeChildrenExceedLimit = ways(n - 3 * limitPlusOne); + // Principle of Inclusion-Exclusion (PIE) + return ways(n) - 3 * oneChildExceedsLimit + 3 * twoChildrenExceedLimit - + threeChildrenExceedLimit; + } + + private: + // Returns the number of ways to distribute n candies to 3 children. + long ways(int n) { + if (n < 0) + return 0; + // Stars and bars method: + // e.g. '**|**|*' means to distribute 5 candies to 3 children, where + // stars (*) := candies and bars (|) := dividers between children. + return nCk(n + 2, 2); + } + + long nCk(int n, int k) { + long res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } +}; diff --git a/solutions/2927. Distribute Candies Among Children III/2927.java b/solutions/2927. Distribute Candies Among Children III/2927.java new file mode 100644 index 00000000000..f52e7da2d86 --- /dev/null +++ b/solutions/2927. Distribute Candies Among Children III/2927.java @@ -0,0 +1,27 @@ +class Solution { + public long distributeCandies(int n, int limit) { + final int limitPlusOne = limit + 1; + final long oneChildExceedsLimit = ways(n - limitPlusOne); + final long twoChildrenExceedLimit = ways(n - 2 * limitPlusOne); + final long threeChildrenExceedLimit = ways(n - 3 * limitPlusOne); + // Principle of Inclusion-Exclusion (PIE) + return ways(n) - 3 * oneChildExceedsLimit + 3 * twoChildrenExceedLimit - + threeChildrenExceedLimit; + } + + private long ways(int n) { + if (n < 0) + return 0; + // Stars and bars method: + // e.g. '**|**|*' means to distribute 5 candies to 3 children, where + // stars (*) := candies and bars (|) := dividers between children. + return nCk(n + 2, 2); + } + + private long nCk(int n, int k) { + long res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } +} diff --git a/solutions/2927. Distribute Candies Among Children III/2927.py b/solutions/2927. Distribute Candies Among Children III/2927.py new file mode 100644 index 00000000000..f0d98aa8670 --- /dev/null +++ b/solutions/2927. Distribute Candies Among Children III/2927.py @@ -0,0 +1,20 @@ +class Solution: + def distributeCandies(self, n: int, limit: int) -> int: + def ways(n: int) -> int: + """Returns the number of ways to distribute n candies to 3 children.""" + if n < 0: + return 0 + # Stars and bars method: + # e.g. '**|**|*' means to distribute 5 candies to 3 children, where + # stars (*) := candies and bars (|) := dividers between children. + return math.comb(n + 2, 2) + + limitPlusOne = limit + 1 + oneChildExceedsLimit = ways(n - limitPlusOne) + twoChildrenExceedLimit = ways(n - 2 * limitPlusOne) + threeChildrenExceedLimit = ways(n - 3 * limitPlusOne) + # Principle of Inclusion-Exclusion (PIE) + return ways(n) \ + - 3 * oneChildExceedsLimit \ + + 3 * twoChildrenExceedLimit \ + - threeChildrenExceedLimit diff --git a/solutions/2928. Distribute Candies Among Children I/2928.cpp b/solutions/2928. Distribute Candies Among Children I/2928.cpp new file mode 100644 index 00000000000..5ea68b679cf --- /dev/null +++ b/solutions/2928. Distribute Candies Among Children I/2928.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + // Same as 2927. Distribute Candies Among Children III + int distributeCandies(int n, int limit) { + const int limitPlusOne = limit + 1; + const int oneChildExceedsLimit = ways(n - limitPlusOne); + const int twoChildrenExceedLimit = ways(n - 2 * limitPlusOne); + const int threeChildrenExceedLimit = ways(n - 3 * limitPlusOne); + // Principle of Inclusion-Exclusion (PIE) + return ways(n) - 3 * oneChildExceedsLimit + 3 * twoChildrenExceedLimit - + threeChildrenExceedLimit; + } + + private: + // Returns the number of ways to distribute n candies to 3 children. + int ways(int n) { + if (n < 0) + return 0; + // Stars and bars method: + // e.g. '**|**|*' means to distribute 5 candies to 3 children, where + // stars (*) := candies and bars (|) := dividers between children. + return nCk(n + 2, 2); + } + + int nCk(int n, int k) { + int res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } +}; diff --git a/solutions/2928. Distribute Candies Among Children I/2928.java b/solutions/2928. Distribute Candies Among Children I/2928.java new file mode 100644 index 00000000000..c5916e88efe --- /dev/null +++ b/solutions/2928. Distribute Candies Among Children I/2928.java @@ -0,0 +1,28 @@ +class Solution { + // Returns the number of ways to distribute n candies to 3 children. + public int distributeCandies(int n, int limit) { + final int limitPlusOne = limit + 1; + final int oneChildExceedsLimit = ways(n - limitPlusOne); + final int twoChildrenExceedLimit = ways(n - 2 * limitPlusOne); + final int threeChildrenExceedLimit = ways(n - 3 * limitPlusOne); + // Principle of Inclusion-Exclusion (PIE) + return ways(n) - 3 * oneChildExceedsLimit + 3 * twoChildrenExceedLimit - + threeChildrenExceedLimit; + } + + private int ways(int n) { + if (n < 0) + return 0; + // Stars and bars method: + // e.g. '**|**|*' means to distribute 5 candies to 3 children, where + // stars (*) := candies and bars (|) := dividers between children. + return nCk(n + 2, 2); + } + + private int nCk(int n, int k) { + int res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } +} diff --git a/solutions/2928. Distribute Candies Among Children I/2928.py b/solutions/2928. Distribute Candies Among Children I/2928.py new file mode 100644 index 00000000000..f0d98aa8670 --- /dev/null +++ b/solutions/2928. Distribute Candies Among Children I/2928.py @@ -0,0 +1,20 @@ +class Solution: + def distributeCandies(self, n: int, limit: int) -> int: + def ways(n: int) -> int: + """Returns the number of ways to distribute n candies to 3 children.""" + if n < 0: + return 0 + # Stars and bars method: + # e.g. '**|**|*' means to distribute 5 candies to 3 children, where + # stars (*) := candies and bars (|) := dividers between children. + return math.comb(n + 2, 2) + + limitPlusOne = limit + 1 + oneChildExceedsLimit = ways(n - limitPlusOne) + twoChildrenExceedLimit = ways(n - 2 * limitPlusOne) + threeChildrenExceedLimit = ways(n - 3 * limitPlusOne) + # Principle of Inclusion-Exclusion (PIE) + return ways(n) \ + - 3 * oneChildExceedsLimit \ + + 3 * twoChildrenExceedLimit \ + - threeChildrenExceedLimit diff --git a/solutions/2929. Distribute Candies Among Children II/2929.cpp b/solutions/2929. Distribute Candies Among Children II/2929.cpp new file mode 100644 index 00000000000..91f14808a1e --- /dev/null +++ b/solutions/2929. Distribute Candies Among Children II/2929.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + // Same as 2927. Distribute Candies Among Children III + long long distributeCandies(int n, int limit) { + const int limitPlusOne = limit + 1; + const long oneChildExceedsLimit = ways(n - limitPlusOne); + const long twoChildrenExceedLimit = ways(n - 2 * limitPlusOne); + const long threeChildrenExceedLimit = ways(n - 3 * limitPlusOne); + // Principle of Inclusion-Exclusion (PIE) + return ways(n) - 3 * oneChildExceedsLimit + 3 * twoChildrenExceedLimit - + threeChildrenExceedLimit; + } + + private: + // Returns the number of ways to distribute n candies to 3 children. + long ways(int n) { + if (n < 0) + return 0; + // Stars and bars method: + // e.g. '**|**|*' means to distribute 5 candies to 3 children, where + // stars (*) := candies and bars (|) := dividers between children. + return nCk(n + 2, 2); + } + + long nCk(int n, int k) { + long res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } +}; diff --git a/solutions/2929. Distribute Candies Among Children II/2929.java b/solutions/2929. Distribute Candies Among Children II/2929.java new file mode 100644 index 00000000000..5ff2a476aff --- /dev/null +++ b/solutions/2929. Distribute Candies Among Children II/2929.java @@ -0,0 +1,28 @@ +class Solution { + // Same as 2927. Distribute Candies Among Children III + public long distributeCandies(int n, int limit) { + final int limitPlusOne = limit + 1; + final long oneChildExceedsLimit = ways(n - limitPlusOne); + final long twoChildrenExceedLimit = ways(n - 2 * limitPlusOne); + final long threeChildrenExceedLimit = ways(n - 3 * limitPlusOne); + // Principle of Inclusion-Exclusion (PIE) + return ways(n) - 3 * oneChildExceedsLimit + 3 * twoChildrenExceedLimit - + threeChildrenExceedLimit; + } + + private long ways(int n) { + if (n < 0) + return 0; + // Stars and bars method: + // e.g. '**|**|*' means to distribute 5 candies to 3 children, where + // stars (*) := candies and bars (|) := dividers between children. + return nCk(n + 2, 2); + } + + private long nCk(int n, int k) { + long res = 1; + for (int i = 1; i <= k; ++i) + res = res * (n - i + 1) / i; + return res; + } +} diff --git a/solutions/2929. Distribute Candies Among Children II/2929.py b/solutions/2929. Distribute Candies Among Children II/2929.py new file mode 100644 index 00000000000..f0d98aa8670 --- /dev/null +++ b/solutions/2929. Distribute Candies Among Children II/2929.py @@ -0,0 +1,20 @@ +class Solution: + def distributeCandies(self, n: int, limit: int) -> int: + def ways(n: int) -> int: + """Returns the number of ways to distribute n candies to 3 children.""" + if n < 0: + return 0 + # Stars and bars method: + # e.g. '**|**|*' means to distribute 5 candies to 3 children, where + # stars (*) := candies and bars (|) := dividers between children. + return math.comb(n + 2, 2) + + limitPlusOne = limit + 1 + oneChildExceedsLimit = ways(n - limitPlusOne) + twoChildrenExceedLimit = ways(n - 2 * limitPlusOne) + threeChildrenExceedLimit = ways(n - 3 * limitPlusOne) + # Principle of Inclusion-Exclusion (PIE) + return ways(n) \ + - 3 * oneChildExceedsLimit \ + + 3 * twoChildrenExceedLimit \ + - threeChildrenExceedLimit diff --git a/solutions/293. Flip Game/293.cpp b/solutions/293. Flip Game/293.cpp new file mode 100644 index 00000000000..53337dc48b2 --- /dev/null +++ b/solutions/293. Flip Game/293.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector generatePossibleNextMoves(string currentState) { + vector ans; + + for (int i = 0; i + 1 < currentState.length(); ++i) + if (currentState[i] == '+' && currentState[i + 1] == '+') + ans.push_back(currentState.substr(0, i) + "--" + + currentState.substr(i + 2)); + + return ans; + } +}; diff --git a/solutions/293. Flip Game/293.java b/solutions/293. Flip Game/293.java new file mode 100644 index 00000000000..e2bce6a4626 --- /dev/null +++ b/solutions/293. Flip Game/293.java @@ -0,0 +1,15 @@ +class Solution { + public List generatePossibleNextMoves(String currentState) { + List ans = new ArrayList<>(); + + for (int i = 0; i + 1 < currentState.length(); ++i) + if (currentState.charAt(i) == '+' && currentState.charAt(i + 1) == '+') { + StringBuilder sb = new StringBuilder(currentState); + sb.setCharAt(i, '-'); + sb.setCharAt(i + 1, '-'); + ans.add(sb.toString()); + } + + return ans; + } +} diff --git a/solutions/293. Flip Game/293.py b/solutions/293. Flip Game/293.py new file mode 100644 index 00000000000..ea71eeb577a --- /dev/null +++ b/solutions/293. Flip Game/293.py @@ -0,0 +1,5 @@ +class Solution: + def generatePossibleNextMoves(self, currentState: str) -> List[str]: + return [currentState[:i] + '--' + currentState[i + 2:] + for i, (a, b) in enumerate(zip(currentState, currentState[1:])) + if a == '+' and b == '+'] diff --git a/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.cpp b/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.cpp new file mode 100644 index 00000000000..ca6222b38d1 --- /dev/null +++ b/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int stringCount(int n) { + // There're three invalid conditions: + // a. count('l') == 0 + // b. count('e') < 2 + // c. count('t') == 0 + // + // By Principle of Inclusion-Exclusion (PIE): + // ans = allCount - a - b - c + ab + ac + bc - abc + const long allCount = modPow(26, n); + const long a = modPow(25, n); + const long b = modPow(25, n); + const long c = modPow(25, n) + n * modPow(25, n - 1); + const long ab = modPow(24, n) + n * modPow(24, n - 1); + const long ac = modPow(24, n); + const long bc = modPow(24, n) + n * modPow(24, n - 1); + const long abc = modPow(23, n) + n * modPow(23, n - 1); + return ((allCount - a - b - c + ab + ac + bc - abc) % kMod + kMod) % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.java b/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.java new file mode 100644 index 00000000000..7f77296033c --- /dev/null +++ b/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.java @@ -0,0 +1,30 @@ +class Solution { + public int stringCount(int n) { + // There're three invalid conditions: + // a. count('l') == 0 + // b. count('e') < 2 + // c. count('t') == 0 + // + // By Principle of Inclusion-Exclusion (PIE): + // ans = allCount - a - b - c + ab + ac + bc - abc + final long allCount = modPow(26, n); + final long a = modPow(25, n); + final long b = modPow(25, n); + final long c = modPow(25, n) + n * modPow(25, n - 1); + final long ab = modPow(24, n) + n * modPow(24, n - 1); + final long ac = modPow(24, n); + final long bc = modPow(24, n) + n * modPow(24, n - 1); + final long abc = modPow(23, n) + n * modPow(23, n - 1); + return (int) (((allCount - a - b - c + ab + ac + bc - abc) % kMod + kMod) % kMod); + } + + private static final int kMod = 1_000_000_007; + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x, n - 1) % kMod; + return modPow(x * x % kMod, n / 2); + } +} diff --git a/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.py b/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.py new file mode 100644 index 00000000000..c976d227ab9 --- /dev/null +++ b/solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.py @@ -0,0 +1,19 @@ +class Solution: + def stringCount(self, n: int) -> int: + # There're three invalid conditions: + # a. count('l') == 0 + # b. count('e') < 2 + # c. count('t') == 0 + # + # By Principle of Inclusion-Exclusion (PIE): + # ans = allCount - a - b - c + ab + ac + bc - abc + kMod = 1_000_000_007 + allCount = pow(26, n, kMod) + a = pow(25, n, kMod) + b = pow(25, n, kMod) + c = pow(25, n, kMod) + n * pow(25, n - 1, kMod) + ab = pow(24, n, kMod) + n * pow(24, n - 1, kMod) + ac = pow(24, n, kMod) + bc = pow(24, n, kMod) + n * pow(24, n - 1, kMod) + abc = pow(23, n, kMod) + n * pow(23, n - 1, kMod) + return (allCount - a - b - c + ab + ac + bc - abc) % kMod diff --git a/solutions/2931. Maximum Spending After Buying Items/2931.cpp b/solutions/2931. Maximum Spending After Buying Items/2931.cpp new file mode 100644 index 00000000000..7a03b6d49d8 --- /dev/null +++ b/solutions/2931. Maximum Spending After Buying Items/2931.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + long long maxSpending(vector>& values) { + const int m = values.size(); + const int n = values[0].size(); + long ans = 0; + long d = 1; + vector items; + + for (const vector& shop : values) + for (const int item : shop) + items.push_back(item); + + ranges::sort(items); + + for (const int item : items) + ans += item * d++; + + return ans; + } +}; diff --git a/solutions/2931. Maximum Spending After Buying Items/2931.java b/solutions/2931. Maximum Spending After Buying Items/2931.java new file mode 100644 index 00000000000..386227e6550 --- /dev/null +++ b/solutions/2931. Maximum Spending After Buying Items/2931.java @@ -0,0 +1,11 @@ +class Solution { + public long maxSpending(int[][] values) { + int[] sorted = Arrays.stream(values) + .flatMapToInt(Arrays::stream) // + .sorted() // + .toArray(); // + return LongStream.range(0, sorted.length) + .map(i -> (i + 1) * sorted[(int) i]) // + .sum(); // + } +} diff --git a/solutions/2931. Maximum Spending After Buying Items/2931.py b/solutions/2931. Maximum Spending After Buying Items/2931.py new file mode 100644 index 00000000000..9781f52a41e --- /dev/null +++ b/solutions/2931. Maximum Spending After Buying Items/2931.py @@ -0,0 +1,4 @@ +class Solution: + def maxSpending(self, values: List[List[int]]) -> int: + items = sorted(item for shop in values for item in shop) + return sum(item * d for d, item in enumerate(items, 1)) diff --git a/solutions/2932. Maximum Strong Pair XOR I/2932.cpp b/solutions/2932. Maximum Strong Pair XOR I/2932.cpp new file mode 100644 index 00000000000..274eade4ab3 --- /dev/null +++ b/solutions/2932. Maximum Strong Pair XOR I/2932.cpp @@ -0,0 +1,74 @@ +struct TrieNode { + vector> children; + TrieNode() : children(2) {} + int mn = INT_MAX; + int mx = INT_MIN; +}; + +class BitTrie { + public: + BitTrie(int maxBit) : maxBit(maxBit) {} + + void insert(int num) { + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + if (node->children[bit] == nullptr) + node->children[bit] = make_shared(); + node = node->children[bit]; + node->mn = min(node->mn, num); + node->mx = max(node->mx, num); + } + } + + // Returns max(x ^ y), where |x - y| <= min(x, y). + // + // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. + // So, y <= 2 * x. + int getMaxXor(int x) { + int maxXor = 0; + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = x >> i & 1; + const int toggleBit = bit ^ 1; + // If `node.children[toggleBit].mx > x`, it means there's a number in the + // node that satisfies the condition to ensure that x <= y among x and y. + // If `node.children[toggleBit].mn <= 2 * x`, it means there's a number + // in the node that satisfies the condition for a valid y. + if (node->children[toggleBit] != nullptr && + node->children[toggleBit]->mx > x && + node->children[toggleBit]->mn <= 2 * x) { + maxXor = maxXor | 1 << i; + node = node->children[toggleBit]; + } else if (node->children[bit] != nullptr) { + node = node->children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private: + const int maxBit; + shared_ptr root = make_shared(); +}; + +class Solution { + public: + // Similar to 421. Maximum XOR of Two Numbers in an Array + int maximumStrongPairXor(vector& nums) { + const int maxNum = ranges::max(nums); + const int maxBit = static_cast(log2(maxNum)); + int ans = 0; + BitTrie bitTrie(maxBit); + + for (const int num : nums) + bitTrie.insert(num); + + for (const int num : nums) + ans = max(ans, bitTrie.getMaxXor(num)); + + return ans; + } +}; diff --git a/solutions/2932. Maximum Strong Pair XOR I/2932.java b/solutions/2932. Maximum Strong Pair XOR I/2932.java new file mode 100644 index 00000000000..c701798bf58 --- /dev/null +++ b/solutions/2932. Maximum Strong Pair XOR I/2932.java @@ -0,0 +1,71 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[2]; + public int mn = Integer.MAX_VALUE; + public int mx = Integer.MIN_VALUE; +} + +class BitTrie { + public BitTrie(int maxBit) { + this.maxBit = maxBit; + } + + public void insert(int num) { + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + if (node.children[bit] == null) + node.children[bit] = new TrieNode(); + node = node.children[bit]; + node.mn = Math.min(node.mn, num); + node.mx = Math.max(node.mx, num); + } + } + + // Returns max(x ^ y), where |x - y| <= min(x, y). + // + // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. + // So, y <= 2 * x. + public int getMaxXor(int x) { + int maxXor = 0; + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (x >> i & 1); + final int toggleBit = bit ^ 1; + // If `node.children[toggleBit].mx > x`, it means there's a number in the + // node that satisfies the condition to ensure that x <= y among x and y. + // If `node.children[toggleBit].mn <= 2 * x`, it means there's a number + // in the node that satisfies the condition for a valid y. + if (node.children[toggleBit] != null && node.children[toggleBit].mx > x && + node.children[toggleBit].mn <= 2 * x) { + maxXor = maxXor | 1 << i; + node = node.children[toggleBit]; + } else if (node.children[bit] != null) { + node = node.children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private int maxBit; + private TrieNode root = new TrieNode(); +} + +class Solution { + // Similar to 421. Maximum XOR of Two Numbers in an Array + public int maximumStrongPairXor(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + final int maxBit = (int) (Math.log(maxNum) / Math.log(2)); + int ans = 0; + BitTrie bitTrie = new BitTrie(maxBit); + + for (final int num : nums) + bitTrie.insert(num); + + for (final int num : nums) + ans = Math.max(ans, bitTrie.getMaxXor(num)); + + return ans; + } +} diff --git a/solutions/2932. Maximum Strong Pair XOR I/2932.py b/solutions/2932. Maximum Strong Pair XOR I/2932.py new file mode 100644 index 00000000000..dbdfce7d697 --- /dev/null +++ b/solutions/2932. Maximum Strong Pair XOR I/2932.py @@ -0,0 +1,60 @@ +class TrieNode: + def __init__(self): + self.children: List[Optional[TrieNode]] = [None] * 2 + self.mn = math.inf + self.mx = -math.inf + + +class BitTrie: + def __init__(self, maxBit: int): + self.maxBit = maxBit + self.root = TrieNode() + + def insert(self, num: int) -> None: + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + if not node.children[bit]: + node.children[bit] = TrieNode() + node = node.children[bit] + node.mn = min(node.mn, num) + node.mx = max(node.mx, num) + + def getMaxXor(self, x: int) -> int: + """Returns max(x ^ y) where |x - y| <= min(x, y). + + If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. + So, y <= 2 * x. + """ + maxXor = 0 + node = self.root + for i in range(self.maxBit, -1, -1): + bit = x >> i & 1 + toggleBit = bit ^ 1 + # If `node.children[toggleBit].mx > x`, it means there's a number in the + # node that satisfies the condition to ensure that x <= y among x and y. + # If `node.children[toggleBit].mn <= 2 * x`, it means there's a number in + # the node that satisfies the condition for a valid y. + if node.children[toggleBit] \ + and node.children[toggleBit].mx > x \ + and node.children[toggleBit].mn <= 2 * x: + maxXor = maxXor | 1 << i + node = node.children[toggleBit] + elif node.children[bit]: + node = node.children[bit] + else: # There's nothing in the Bit Trie. + return 0 + return maxXor + + +class Solution: + # Similar to 421. Maximum XOR of Two Numbers in an Array + def maximumStrongPairXor(self, nums: List[int]) -> int: + maxNum = max(nums) + maxBit = int(math.log2(maxNum)) + bitTrie = BitTrie(maxBit) + + for num in nums: + bitTrie.insert(num) + + return max(bitTrie.getMaxXor(num) for num in nums) diff --git a/solutions/2933. High-Access Employees/2933.cpp b/solutions/2933. High-Access Employees/2933.cpp new file mode 100644 index 00000000000..6b8ba9c78e3 --- /dev/null +++ b/solutions/2933. High-Access Employees/2933.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector findHighAccessEmployees(vector>& access_times) { + unordered_set ans; + + ranges::sort(access_times); + + for (int i = 0; i + 2 < access_times.size(); ++i) { + const string& name = access_times[i][0]; + if (ans.contains(name)) + continue; + if (name != access_times[i + 2][0]) + continue; + if (stoi(access_times[i + 2][1]) - stoi(access_times[i][1]) < 100) + ans.insert(name); + } + + return {ans.begin(), ans.end()}; + } +}; diff --git a/solutions/2933. High-Access Employees/2933.java b/solutions/2933. High-Access Employees/2933.java new file mode 100644 index 00000000000..3971ff6bd6b --- /dev/null +++ b/solutions/2933. High-Access Employees/2933.java @@ -0,0 +1,24 @@ +class Solution { + public List findHighAccessEmployees(List> access_times) { + Set ans = new HashSet<>(); + + Collections.sort(access_times, + (a, b) + -> a.get(0).equals(b.get(0)) ? a.get(1).compareTo(b.get(1)) + : a.get(0).compareTo(b.get(0))); + + for (int i = 0; i + 2 < access_times.size(); ++i) { + String name = access_times.get(i).get(0); + if (ans.contains(name)) + continue; + if (!name.equals(access_times.get(i + 2).get(0))) + continue; + if (Integer.parseInt(access_times.get(i + 2).get(1)) - + Integer.parseInt(access_times.get(i).get(1)) < + 100) + ans.add(name); + } + + return new ArrayList<>(ans); + } +} diff --git a/solutions/2933. High-Access Employees/2933.py b/solutions/2933. High-Access Employees/2933.py new file mode 100644 index 00000000000..dbcd5e62ce4 --- /dev/null +++ b/solutions/2933. High-Access Employees/2933.py @@ -0,0 +1,16 @@ +class Solution: + def findHighAccessEmployees(self, access_times: List[List[str]]) -> List[str]: + ans = set() + + access_times.sort() + + for i in range(len(access_times) - 2): + name = access_times[i][0] + if name in ans: + continue + if name != access_times[i + 2][0]: + continue + if int(access_times[i + 2][1]) - int(access_times[i][1]) < 100: + ans.add(name) + + return list(ans) diff --git a/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.cpp b/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.cpp new file mode 100644 index 00000000000..8927ad6a7db --- /dev/null +++ b/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minOperations(vector& nums1, vector& nums2) { + const int n = nums1.size(); + const int mn = min(nums1.back(), nums2.back()); + const int mx = max(nums1.back(), nums2.back()); + // the number of the minimum operations, where nums1[n - 1] is not swapped + // with nums2[n - 1] + int dp1 = 0; + // the number of the minimum operations, where nums1[n - 1] is swapped with + // nums2[n - 1] + int dp2 = 0; + + for (int i = 0; i < n; ++i) { + const int a = nums1[i]; + const int b = nums2[i]; + if (min(a, b) > mn) + return -1; + if (max(a, b) > mx) + return -1; + if (a > nums1.back() || b > nums2.back()) + ++dp1; + if (a > nums2.back() || b > nums1.back()) + ++dp2; + } + + return min(dp1, dp2); + } +}; diff --git a/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.java b/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.java new file mode 100644 index 00000000000..778f517bbdc --- /dev/null +++ b/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.java @@ -0,0 +1,28 @@ +class Solution { + public int minOperations(int[] nums1, int[] nums2) { + final int n = nums1.length; + final int mn = Math.min(nums1[n - 1], nums2[n - 1]); + final int mx = Math.max(nums1[n - 1], nums2[n - 1]); + // the number of the minimum operations, where nums1[n - 1] is not swapped + // with nums2[n - 1] + int dp1 = 0; + // the number of the minimum operations, where nums1[n - 1] is swapped with + // nums2[n - 1] + int dp2 = 0; + + for (int i = 0; i < n; ++i) { + final int a = nums1[i]; + final int b = nums2[i]; + if (Math.min(a, b) > mn) + return -1; + if (Math.max(a, b) > mx) + return -1; + if (a > nums1[n - 1] || b > nums2[n - 1]) + ++dp1; + if (a > nums2[n - 1] || b > nums1[n - 1]) + ++dp2; + } + + return Math.min(dp1, dp2); + } +} diff --git a/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.py b/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.py new file mode 100644 index 00000000000..df854383989 --- /dev/null +++ b/solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.py @@ -0,0 +1,23 @@ +class Solution: + def minOperations(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums1) + mn = min(nums1[-1], nums2[-1]) + mx = max(nums1[-1], nums2[-1]) + # the number of the minimum operations, where nums1[n - 1] is not swapped + # with nums2[n - 1] + dp1 = 0 + # the number of the minimum operations, where nums1[n - 1] is swapped with + # nums2[n - 1] + dp2 = 0 + + for a, b in zip(nums1, nums2): + if min(a, b) > mn: + return -1 + if max(a, b) > mx: + return -1 + if a > nums1[-1] or b > nums2[-1]: + dp1 += 1 + if a > nums2[-1] or b > nums1[-1]: + dp2 += 1 + + return min(dp1, dp2) diff --git a/solutions/2935. Maximum Strong Pair XOR II/2935.cpp b/solutions/2935. Maximum Strong Pair XOR II/2935.cpp new file mode 100644 index 00000000000..43e23aefd53 --- /dev/null +++ b/solutions/2935. Maximum Strong Pair XOR II/2935.cpp @@ -0,0 +1,74 @@ +struct TrieNode { + vector> children; + TrieNode() : children(2) {} + int mn = INT_MAX; + int mx = INT_MIN; +}; + +class BitTrie { + public: + BitTrie(int maxBit) : maxBit(maxBit) {} + + void insert(int num) { + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + if (node->children[bit] == nullptr) + node->children[bit] = make_shared(); + node = node->children[bit]; + node->mn = min(node->mn, num); + node->mx = max(node->mx, num); + } + } + + // Returns max(x ^ y), where |x - y| <= min(x, y). + // + // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. + // So, y <= 2 * x. + int getMaxXor(int x) { + int maxXor = 0; + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = x >> i & 1; + const int toggleBit = bit ^ 1; + // If `node.children[toggleBit].max > x`, it means there's a number in the + // node that satisfies the condition to ensure that x <= y among x and y. + // If `node.children[toggleBit].min <= 2 * x`, it means there's a number + // in the node that satisfies the condition for a valid y. + if (node->children[toggleBit] != nullptr && + node->children[toggleBit]->mx > x && + node->children[toggleBit]->mn <= 2 * x) { + maxXor = maxXor | 1 << i; + node = node->children[toggleBit]; + } else if (node->children[bit] != nullptr) { + node = node->children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private: + const int maxBit; + shared_ptr root = make_shared(); +}; + +class Solution { + public: + // Same as 2932. Maximum Strong Pair XOR I + int maximumStrongPairXor(vector& nums) { + const int maxNum = ranges::max(nums); + const int maxBit = static_cast(log2(maxNum)); + int ans = 0; + BitTrie bitTrie(maxBit); + + for (const int num : nums) + bitTrie.insert(num); + + for (const int num : nums) + ans = max(ans, bitTrie.getMaxXor(num)); + + return ans; + } +}; diff --git a/solutions/2935. Maximum Strong Pair XOR II/2935.java b/solutions/2935. Maximum Strong Pair XOR II/2935.java new file mode 100644 index 00000000000..337262031ca --- /dev/null +++ b/solutions/2935. Maximum Strong Pair XOR II/2935.java @@ -0,0 +1,71 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[2]; + public int mn = Integer.MAX_VALUE; + public int mx = Integer.MIN_VALUE; +} + +class BitTrie { + public BitTrie(int maxBit) { + this.maxBit = maxBit; + } + + public void insert(int num) { + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + if (node.children[bit] == null) + node.children[bit] = new TrieNode(); + node = node.children[bit]; + node.mn = Math.min(node.mn, num); + node.mx = Math.max(node.mx, num); + } + } + + // Returns max(x ^ y), where |x - y| <= min(x, y). + // + // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. + // So, y <= 2 * x. + public int getMaxXor(int x) { + int maxXor = 0; + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (x >> i & 1); + final int toggleBit = bit ^ 1; + // If `node.children[toggleBit].mx > x`, it means there's a number in the + // node that satisfies the condition to ensure that x <= y among x and y. + // If `node.children[toggleBit].mn <= 2 * x`, it means there's a number + // in the node that satisfies the condition for a valid y. + if (node.children[toggleBit] != null && node.children[toggleBit].mx > x && + node.children[toggleBit].mn <= 2 * x) { + maxXor = maxXor | 1 << i; + node = node.children[toggleBit]; + } else if (node.children[bit] != null) { + node = node.children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private int maxBit; + private TrieNode root = new TrieNode(); +} + +class Solution { + // Same as 2932. Maximum Strong Pair XOR I + public int maximumStrongPairXor(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + final int maxBit = (int) (Math.log(maxNum) / Math.log(2)); + int ans = 0; + BitTrie bitTrie = new BitTrie(maxBit); + + for (final int num : nums) + bitTrie.insert(num); + + for (final int num : nums) + ans = Math.max(ans, bitTrie.getMaxXor(num)); + + return ans; + } +} diff --git a/solutions/2935. Maximum Strong Pair XOR II/2935.py b/solutions/2935. Maximum Strong Pair XOR II/2935.py new file mode 100644 index 00000000000..67c9f0db4c9 --- /dev/null +++ b/solutions/2935. Maximum Strong Pair XOR II/2935.py @@ -0,0 +1,60 @@ +class TrieNode: + def __init__(self): + self.children: List[Optional[TrieNode]] = [None] * 2 + self.mn = math.inf + self.mx = -math.inf + + +class BitTrie: + def __init__(self, maxBit: int): + self.maxBit = maxBit + self.root = TrieNode() + + def insert(self, num: int) -> None: + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + if not node.children[bit]: + node.children[bit] = TrieNode() + node = node.children[bit] + node.mn = min(node.mn, num) + node.mx = max(node.mx, num) + + def getMaxXor(self, x: int) -> int: + """Returns max(x ^ y) where |x - y| <= min(x, y). + + If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. + So, y <= 2 * x. + """ + maxXor = 0 + node = self.root + for i in range(self.maxBit, -1, -1): + bit = x >> i & 1 + toggleBit = bit ^ 1 + # If `node.children[toggleBit].mx > x`, it means there's a number in the + # node that satisfies the condition to ensure that x <= y among x and y. + # If `node.children[toggleBit].mn <= 2 * x`, it means there's a number in + # the node that satisfies the condition for a valid y. + if node.children[toggleBit] \ + and node.children[toggleBit].mx > x \ + and node.children[toggleBit].mn <= 2 * x: + maxXor = maxXor | 1 << i + node = node.children[toggleBit] + elif node.children[bit]: + node = node.children[bit] + else: # There's nothing in the Bit Trie. + return 0 + return maxXor + + +class Solution: + # Same as 2932. Maximum Strong Pair XOR I + def maximumStrongPairXor(self, nums: List[int]) -> int: + maxNum = max(nums) + maxBit = int(math.log2(maxNum)) + bitTrie = BitTrie(maxBit) + + for num in nums: + bitTrie.insert(num) + + return max(bitTrie.getMaxXor(num) for num in nums) diff --git a/solutions/2936. Number of Equal Numbers Blocks/2936.cpp b/solutions/2936. Number of Equal Numbers Blocks/2936.cpp new file mode 100644 index 00000000000..92bd9e820aa --- /dev/null +++ b/solutions/2936. Number of Equal Numbers Blocks/2936.cpp @@ -0,0 +1,32 @@ +/** + * Definition for BigArray. + * class BigArray { + * public: + * BigArray(vector elements); + * int at(long long index); + * long long size(); + * }; + */ + +class Solution { + public: + int countBlocks(BigArray* nums) { + return countBlocks(nums, 0, nums->size() - 1, nums->at(0), + nums->at(nums->size() - 1)); + } + + private: + // Returns the number of maximal blocks in nums[l..r]. + int countBlocks(BigArray* nums, long l, long r, int leftValue, + int rightValue) { + if (leftValue == rightValue) // nums[l..r] are identical. + return 1; + if (l + 1 == r) // nums[l] != nums[r]. + return 2; + const long m = (l + r) / 2; + const int midValue = nums->at(m); + // Substract nums[m], which will be counted twice. + return countBlocks(nums, l, m, leftValue, midValue) + + countBlocks(nums, m, r, midValue, rightValue) - 1; + } +}; diff --git a/solutions/2936. Number of Equal Numbers Blocks/2936.java b/solutions/2936. Number of Equal Numbers Blocks/2936.java new file mode 100644 index 00000000000..6e7ad0676a0 --- /dev/null +++ b/solutions/2936. Number of Equal Numbers Blocks/2936.java @@ -0,0 +1,27 @@ +/** + * Definition for BigArray. + * class BigArray { + * public BigArray(int[] elements); + * public int at(long index); + * public long size(); + * } + */ + +class Solution { + public int countBlocks(BigArray nums) { + return countBlocks(nums, 0, nums.size() - 1, nums.at(0), nums.at(nums.size() - 1)); + } + + // Returns the number of maximal blocks in nums[l..r]. + private int countBlocks(BigArray nums, long l, long r, int leftValue, int rightValue) { + if (leftValue == rightValue) // nums[l..r] are identical. + return 1; + if (l + 1 == r) // nums[l] != nums[r]. + return 2; + final long m = (l + r) / 2; + final int midValue = nums.at(m); + // Substract nums[m], which will be counted twice. + return countBlocks(nums, l, m, leftValue, midValue) + + countBlocks(nums, m, r, midValue, rightValue) - 1; + } +} diff --git a/solutions/2936. Number of Equal Numbers Blocks/2936.py b/solutions/2936. Number of Equal Numbers Blocks/2936.py new file mode 100644 index 00000000000..2d76f16e0ca --- /dev/null +++ b/solutions/2936. Number of Equal Numbers Blocks/2936.py @@ -0,0 +1,22 @@ +# Definition for BigArray. +# class BigArray: +# def at(self, index: long) -> int: +# pass +# def size(self) -> long: +# pass + +class Solution(object): + def countBlocks(self, nums: Optional['BigArray']) -> int: + def countBlocks(l: int, r: int, leftValue: int, rightValue: int) -> int: + """Returns the number of maximal blocks in nums[l..r].""" + if leftValue == rightValue: + return 1 + if l + 1 == r: + return 2 + m = (l + r) // 2 + midValue = nums.at(m) + return countBlocks(l, m, leftValue, midValue) + countBlocks(m, r, midValue, rightValue) - 1 + + # Substract nums[m], which will be counted twice. + return countBlocks(0, nums.size() - 1, + nums.at(0), nums.at(nums.size() - 1)) diff --git a/solutions/2937. Make Three Strings Equal/2937.cpp b/solutions/2937. Make Three Strings Equal/2937.cpp new file mode 100644 index 00000000000..212c05ca7eb --- /dev/null +++ b/solutions/2937. Make Three Strings Equal/2937.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int findMinimumOperations(string s1, string s2, string s3) { + const int minLength = min({s1.length(), s2.length(), s3.length()}); + int i = 0; + while (i < minLength && s1[i] == s2[i] && s2[i] == s3[i]) + ++i; + return i == 0 ? -1 : s1.length() + s2.length() + s3.length() - i * 3; + } +}; diff --git a/solutions/2937. Make Three Strings Equal/2937.java b/solutions/2937. Make Three Strings Equal/2937.java new file mode 100644 index 00000000000..89272c7b2da --- /dev/null +++ b/solutions/2937. Make Three Strings Equal/2937.java @@ -0,0 +1,9 @@ +class Solution { + public int findMinimumOperations(String s1, String s2, String s3) { + final int minLength = Math.min(s1.length(), Math.min(s2.length(), s3.length())); + int i = 0; + while (i < minLength && s1.charAt(i) == s2.charAt(i) && s2.charAt(i) == s3.charAt(i)) + ++i; + return i == 0 ? -1 : s1.length() + s2.length() + s3.length() - i * 3; + } +} diff --git a/solutions/2937. Make Three Strings Equal/2937.py b/solutions/2937. Make Three Strings Equal/2937.py new file mode 100644 index 00000000000..414d82465d4 --- /dev/null +++ b/solutions/2937. Make Three Strings Equal/2937.py @@ -0,0 +1,7 @@ +class Solution: + def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int: + minLength = min(map(len, [s1, s2, s3])) + i = 0 + while i < minLength and s1[i] == s2[i] and s2[i] == s3[i]: + i += 1 + return -1 if i == 0 else len(s1) + len(s2) + len(s3) - i * 3 diff --git a/solutions/2938. Separate Black and White Balls/2938.cpp b/solutions/2938. Separate Black and White Balls/2938.cpp new file mode 100644 index 00000000000..f7e96724358 --- /dev/null +++ b/solutions/2938. Separate Black and White Balls/2938.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + long long minimumSteps(string s) { + long ans = 0; + int ones = 0; + + for (const char c : s) + if (c == '1') + ++ones; + else // Move 1s to the front of the current '0'. + ans += ones; + + return ans; + } +}; diff --git a/solutions/2938. Separate Black and White Balls/2938.java b/solutions/2938. Separate Black and White Balls/2938.java new file mode 100644 index 00000000000..307ba162311 --- /dev/null +++ b/solutions/2938. Separate Black and White Balls/2938.java @@ -0,0 +1,14 @@ +class Solution { + public long minimumSteps(String s) { + long ans = 0; + int ones = 0; + + for (final char c : s.toCharArray()) + if (c == '1') + ++ones; + else // Move 1s to the front of the current '0'. + ans += ones; + + return ans; + } +} diff --git a/solutions/2938. Separate Black and White Balls/2938.py b/solutions/2938. Separate Black and White Balls/2938.py new file mode 100644 index 00000000000..22aa4b263fe --- /dev/null +++ b/solutions/2938. Separate Black and White Balls/2938.py @@ -0,0 +1,12 @@ +class Solution: + def minimumSteps(self, s: str) -> int: + ans = 0 + ones = 0 + + for c in s: + if c == '1': + ones += 1 + else: # Move 1s to the front of the current '0'. + ans += ones + + return ans diff --git a/solutions/2939. Maximum Xor Product/2939.cpp b/solutions/2939. Maximum Xor Product/2939.cpp new file mode 100644 index 00000000000..f8a828d81ae --- /dev/null +++ b/solutions/2939. Maximum Xor Product/2939.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maximumXorProduct(long long a, long long b, int n) { + constexpr int kMod = 1'000'000'007; + if (n > 0) + for (long bit = 1L << (n - 1); bit > 0; bit >>= 1) + // Pick a bit if it makes min(a, b) larger. + if ((min(a, b) & bit) == 0) { + a ^= bit; + b ^= bit; + } + return a % kMod * (b % kMod) % kMod; + } +}; diff --git a/solutions/2939. Maximum Xor Product/2939.java b/solutions/2939. Maximum Xor Product/2939.java new file mode 100644 index 00000000000..7fdcf047ebf --- /dev/null +++ b/solutions/2939. Maximum Xor Product/2939.java @@ -0,0 +1,13 @@ +class Solution { + public int maximumXorProduct(long a, long b, int n) { + final int kMod = 1_000_000_007; + if (n > 0) + for (long bit = 1L << (n - 1); bit > 0; bit >>= 1) + // Pick a bit if it makes Math.min(a, b) larger. + if ((Math.min(a, b) & bit) == 0) { + a ^= bit; + b ^= bit; + } + return (int) (a % kMod * (b % kMod) % kMod); + } +} diff --git a/solutions/2939. Maximum Xor Product/2939.py b/solutions/2939. Maximum Xor Product/2939.py new file mode 100644 index 00000000000..4a02c6d2599 --- /dev/null +++ b/solutions/2939. Maximum Xor Product/2939.py @@ -0,0 +1,9 @@ +class Solution: + def maximumXorProduct(self, a: int, b: int, n: int) -> int: + kMod = 1_000_000_007 + for bit in (2**i for i in range(n)): + # Pick a bit if it makes min(a, b) larger. + if a * b < (a ^ bit) * (b ^ bit): + a ^= bit + b ^= bit + return a * b % kMod diff --git a/solutions/294. Flip Game II/294.cpp b/solutions/294. Flip Game II/294.cpp new file mode 100644 index 00000000000..02afab8b386 --- /dev/null +++ b/solutions/294. Flip Game II/294.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool canWin(string currentState) { + const auto it = mem.find(currentState); + if (it == mem.cend()) + return it->second; + + // If any of currentState[i:i + 2] == "++" and your friend can't win after + // changing currentState[i:i + 2] to "--" (or "-"), then you can win. + for (int i = 0; i + 1 < currentState.length(); ++i) + if (currentState[i] == '+' && currentState[i + 1] == '+' && + !canWin(currentState.substr(0, i) + '-' + currentState.substr(i + 2))) + return mem[currentState] = true; + + return mem[currentState] = false; + } + + private: + unordered_map mem; +}; diff --git a/solutions/294. Flip Game II/294.java b/solutions/294. Flip Game II/294.java new file mode 100644 index 00000000000..1d11200f91a --- /dev/null +++ b/solutions/294. Flip Game II/294.java @@ -0,0 +1,20 @@ +class Solution { + public boolean canWin(String currentState) { + if (mem.containsKey(currentState)) + mem.get(currentState); + + // If any of currentState[i:i + 2] == "++" and your friend can't win after + // changing currentState[i:i + 2] to "--" (or "-"), then you can win. + for (int i = 0; i + 1 < currentState.length(); ++i) + if (currentState.charAt(i) == '+' && currentState.charAt(i + 1) == '+' && + !canWin(currentState.substring(0, i) + "-" + currentState.substring(i + 2))) { + mem.put(currentState, true); + return true; + } + + mem.put(currentState, false); + return false; + } + + private Map mem = new HashMap<>(); +} diff --git a/solutions/294. Flip Game II/294.py b/solutions/294. Flip Game II/294.py new file mode 100644 index 00000000000..fc9ac558faf --- /dev/null +++ b/solutions/294. Flip Game II/294.py @@ -0,0 +1,9 @@ +class Solution: + @functools.lru_cache(None) + def canWin(self, currentState: str) -> bool: + # If any of currentState[i:i + 2] == "++" and your friend can't win after + # changing currentState[i:i + 2] to "--" (or "-"), then you can win. + return any(True + for i, (a, b) in enumerate(zip(currentState, currentState[1:])) + if a == '+' and b == '+' and + not self.canWin(currentState[:i] + '-' + currentState[i + 2:])) diff --git a/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.cpp b/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.cpp new file mode 100644 index 00000000000..26e2ed62026 --- /dev/null +++ b/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.cpp @@ -0,0 +1,64 @@ +struct IndexedQuery { + int queryIndex; + int a; // Alice's index + int b; // Bob's index +}; + +class Solution { + public: + // Similar to 2736. Maximum Sum Queries + vector leftmostBuildingQueries(vector& heights, + vector>& queries) { + vector ans(queries.size(), -1); + // Store indices (heightsIndex) of heights with heights[heightsIndex] in + // descending order. + vector stack; + + // Iterate through queries and heights simultaneously. + int heightsIndex = heights.size() - 1; + for (const auto& [queryIndex, a, b] : getIndexedQueries(queries)) { + if (a == b || heights[a] < heights[b]) { + // 1. Alice and Bob are already in the same index (a == b) or + // 2. Alice can jump from a -> b (heights[a] < heights[b]). + ans[queryIndex] = b; + } else { + // Now, a < b and heights[a] >= heights[b]. + // Gradually add heights with an index > b to the monotonic stack. + while (heightsIndex > b) { + // heights[heightsIndex] is a better candidate, given that + // heightsIndex is smaller than the indices in the stack and + // heights[heightsIndex] is larger or equal to the heights mapped in + // the stack. + while (!stack.empty() && + heights[stack.back()] <= heights[heightsIndex]) + stack.pop_back(); + stack.push_back(heightsIndex--); + } + // Binary search to find the smallest index j such that j > b and + // heights[j] > heights[a], thereby ensuring heights[j] > heights[b]. + if (const auto it = upper_bound( + stack.rbegin(), stack.rend(), a, + [&](int a, int b) { return heights[a] < heights[b]; }); + it != stack.rend()) + ans[queryIndex] = *it; + } + } + + return ans; + } + + private: + vector getIndexedQueries(const vector>& queries) { + vector indexedQueries; + for (int i = 0; i < queries.size(); ++i) { + // Make sure that a <= b. + const int a = min(queries[i][0], queries[i][1]); + const int b = max(queries[i][0], queries[i][1]); + indexedQueries.push_back({i, a, b}); + } + ranges::sort( + indexedQueries, + [](const IndexedQuery& a, const IndexedQuery& b) { return a.b > b.b; }); + return indexedQueries; + } +}; diff --git a/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.java b/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.java new file mode 100644 index 00000000000..2b00b8aa8d9 --- /dev/null +++ b/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.java @@ -0,0 +1,71 @@ +class Solution { + // Similar to 2736. Maximum Sum Queries + public int[] leftmostBuildingQueries(int[] heights, int[][] queries) { + IndexedQuery[] indexedQueries = getIndexedQueries(queries); + int[] ans = new int[queries.length]; + Arrays.fill(ans, -1); + // Store indices (heightsIndex) of heights with heights[heightsIndex] in + // descending order. + List stack = new ArrayList<>(); + + // Iterate through queries and heights simultaneously. + int heightsIndex = heights.length - 1; + for (IndexedQuery indexedQuery : indexedQueries) { + final int queryIndex = indexedQuery.queryIndex; + final int a = indexedQuery.a; + final int b = indexedQuery.b; + if (a == b || heights[a] < heights[b]) { + // 1. Alice and Bob are already in the same index (a == b) or + // 2. Alice can jump from a -> b (heights[a] < heights[b]). + ans[queryIndex] = b; + } else { + // Now, a < b and heights[a] >= heights[b]. + // Gradually add heights with an index > b to the monotonic stack. + while (heightsIndex > b) { + // heights[heightsIndex] is a better candidate, given that + // heightsIndex is smaller than the indices in the stack and + // heights[heightsIndex] is larger or equal to the heights mapped in + // the stack. + while (!stack.isEmpty() && heights[stack.get(stack.size() - 1)] <= heights[heightsIndex]) + stack.remove(stack.size() - 1); + stack.add(heightsIndex--); + } + // Binary search to find the smallest index j such that j > b and + // heights[j] > heights[a], thereby ensuring heights[t] > heights[b]. + final int j = lastGreater(stack, a, heights); + if (j != -1) + ans[queryIndex] = stack.get(j); + } + } + + return ans; + } + + private record IndexedQuery(int queryIndex, int a, int b){}; + + // Returns the last index i in A s.t. heights[A.get(i)] is > heights[target]. + private int lastGreater(List A, int target, int[] heights) { + int l = -1; + int r = A.size() - 1; + while (l < r) { + final int m = (l + r + 1) / 2; + if (heights[A.get(m)] > heights[target]) + l = m; + else + r = m - 1; + } + return l; + } + + private IndexedQuery[] getIndexedQueries(int[][] queries) { + IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; + for (int i = 0; i < queries.length; ++i) { + // Make sure that a <= b. + final int a = Math.min(queries[i][0], queries[i][1]); + final int b = Math.max(queries[i][0], queries[i][1]); + indexedQueries[i] = new IndexedQuery(i, a, b); + } + Arrays.sort(indexedQueries, (a, b) -> b.b - a.b); + return indexedQueries; + } +} diff --git a/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.py b/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.py new file mode 100644 index 00000000000..4acaa372ebb --- /dev/null +++ b/solutions/2940. Find Building Where Alice and Bob Can Meet/2940.py @@ -0,0 +1,62 @@ +class IndexedQuery: + def __init__(self, queryIndex: int, a: int, b: int): + self.queryIndex = queryIndex + self.a = a # Alice's index + self.b = b # Bob's index + + def __iter__(self): + yield self.queryIndex + yield self.a + yield self.b + + +class Solution: + # Similar to 2736. Maximum Sum Queries + def leftmostBuildingQueries(self, heights: List[int], queries: List[List[int]]) -> List[int]: + ans = [-1] * len(queries) + # Store indices (heightsIndex) of heights with heights[heightsIndex] in + # descending order. + stack = [] + + # Iterate through queries and heights simultaneously. + heightsIndex = len(heights) - 1 + for queryIndex, a, b in sorted([IndexedQuery(i, min(a, b), max(a, b)) + for i, (a, b) in enumerate(queries)], + key=lambda iq: -iq.b): + if a == b or heights[a] < heights[b]: + # 1. Alice and Bob are already in the same index (a == b) or + # 2. Alice can jump from a -> b (heights[a] < heights[b]). + ans[queryIndex] = b + else: + # Now, a < b and heights[a] >= heights[b]. + # Gradually add heights with an index > b to the monotonic stack. + while heightsIndex > b: + # heights[heightsIndex] is a better candidate, given that + # heightsIndex is smaller than the indices in the stack and + # heights[heightsIndex] is larger or equal to the heights mapped in + # the stack. + while stack and heights[stack[-1]] <= heights[heightsIndex]: + stack.pop() + stack.append(heightsIndex) + heightsIndex -= 1 + # Binary search to find the smallest index j such that j > b and + # heights[j] > heights[a], thereby ensuring heights[j] > heights[b]. + j = self._lastGreater(stack, a, heights) + if j != -1: + ans[queryIndex] = stack[j] + + return ans + + def _lastGreater(self, A: List[int], target: int, heights: List[int]): + """ + Returns the last index i in A s.t. heights[A.get(i)] is > heights[target]. + """ + l = -1 + r = len(A) - 1 + while l < r: + m = (l + r + 1) // 2 + if heights[A[m]] > heights[target]: + l = m + else: + r = m - 1 + return l diff --git a/solutions/2941. Maximum GCD-Sum of a Subarray/2941.cpp b/solutions/2941. Maximum GCD-Sum of a Subarray/2941.cpp new file mode 100644 index 00000000000..d2e8ead43af --- /dev/null +++ b/solutions/2941. Maximum GCD-Sum of a Subarray/2941.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + long long maxGcdSum(vector& nums, int k) { + long long ans = 0; + // [(startIndex, gcd of subarray starting at startIndex)] + vector> startIndexAndGcds; + vector prefix = {0}; + + for (const int num : nums) + prefix.push_back(prefix.back() + num); + + for (int i = 0; i < nums.size(); ++i) { + vector> nextStartIndexAndGcds; + for (const auto& [startIndex, gcd] : startIndexAndGcds) { + const int nextGcd = __gcd(gcd, nums[i]); + if (nextStartIndexAndGcds.empty() || + nextStartIndexAndGcds.back().second != nextGcd) // Skip duplicates. + nextStartIndexAndGcds.emplace_back(startIndex, nextGcd); + } + startIndexAndGcds = move(nextStartIndexAndGcds); + startIndexAndGcds.emplace_back(i, nums[i]); + for (const auto& [startIndex, gcd] : startIndexAndGcds) + if (i - startIndex + 1 >= k) + ans = max(ans, (prefix[i + 1] - prefix[startIndex]) * gcd); + } + + return ans; + } +}; diff --git a/solutions/2941. Maximum GCD-Sum of a Subarray/2941.java b/solutions/2941. Maximum GCD-Sum of a Subarray/2941.java new file mode 100644 index 00000000000..b1e4c814340 --- /dev/null +++ b/solutions/2941. Maximum GCD-Sum of a Subarray/2941.java @@ -0,0 +1,39 @@ +class Solution { + public long maxGcdSum(int[] nums, int k) { + long ans = 0; + // [(startIndex, gcd of subarray starting at startIndex)] + List> startIndexAndGcds = new ArrayList<>(); + long[] prefix = new long[nums.length + 1]; + + for (int i = 0; i < nums.length; ++i) + prefix[i + 1] = (long) nums[i] + prefix[i]; + + for (int i = 0; i < nums.length; ++i) { + List> nextStartIndexAndGcds = new ArrayList<>(); + for (Pair pair : startIndexAndGcds) { + final int startIndex = pair.getKey(); + final int gcd = pair.getValue(); + final int nextGcd = gcd(gcd, nums[i]); + if (nextStartIndexAndGcds.isEmpty() || + !nextStartIndexAndGcds.get(nextStartIndexAndGcds.size() - 1) + .getValue() + .equals(nextGcd)) // Skip duplicates. + nextStartIndexAndGcds.add(new Pair<>(startIndex, nextGcd)); + } + startIndexAndGcds = new ArrayList<>(nextStartIndexAndGcds); + startIndexAndGcds.add(new Pair<>(i, nums[i])); + for (Pair pair : startIndexAndGcds) { + final int startIndex = pair.getKey(); + final int gcd = pair.getValue(); + if (i - startIndex + 1 >= k) + ans = Math.max(ans, (prefix[i + 1] - prefix[startIndex]) * gcd); + } + } + + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/2941. Maximum GCD-Sum of a Subarray/2941.py b/solutions/2941. Maximum GCD-Sum of a Subarray/2941.py new file mode 100644 index 00000000000..2f34b4785c6 --- /dev/null +++ b/solutions/2941. Maximum GCD-Sum of a Subarray/2941.py @@ -0,0 +1,21 @@ +class Solution: + def maxGcdSum(self, nums: List[int], k: int) -> int: + ans = 0 + # [(startIndex, gcd of subarray starting at startIndex)] + startIndexAndGcds = [] + prefix = [0] + list(itertools.accumulate(nums)) + + for i, num in enumerate(nums): + nextStartIndexAndGcds = [] + for startIndex, gcd in startIndexAndGcds: + nextGcd = math.gcd(gcd, nums[i]) + if not nextStartIndexAndGcds or \ + nextStartIndexAndGcds[-1][1] != nextGcd: # Skip duplicates. + nextStartIndexAndGcds.append((startIndex, nextGcd)) + startIndexAndGcds = nextStartIndexAndGcds + startIndexAndGcds.append((i, nums[i])) + for startIndex, gcd in startIndexAndGcds: + if i - startIndex + 1 >= k: + ans = max(ans, (prefix[i + 1] - prefix[startIndex]) * gcd) + + return ans diff --git a/solutions/2942. Find Words Containing Character/2942.cpp b/solutions/2942. Find Words Containing Character/2942.cpp new file mode 100644 index 00000000000..0af18169521 --- /dev/null +++ b/solutions/2942. Find Words Containing Character/2942.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector findWordsContaining(vector& words, char x) { + vector ans; + + for (int i = 0; i < words.size(); ++i) + if (words[i].find(x) != string::npos) + ans.push_back(i); + + return ans; + } +}; diff --git a/solutions/2943. Maximize Area of Square Hole in Grid Solved Medium/2943.cpp b/solutions/2943. Maximize Area of Square Hole in Grid Solved Medium/2943.cpp new file mode 100644 index 00000000000..8e59944e7ac --- /dev/null +++ b/solutions/2943. Maximize Area of Square Hole in Grid Solved Medium/2943.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maximizeSquareHoleArea(int n, int m, vector& hBars, + vector& vBars) { + const int gap = min(maxContinousGap(hBars), maxContinousGap(vBars)); + return gap * gap; + } + + private: + int maxContinousGap(vector& bars) { + int res = 2; + int runningGap = 2; + ranges::sort(bars); + for (int i = 1; i < bars.size(); ++i) { + runningGap = bars[i] == bars[i - 1] + 1 ? runningGap + 1 : 2; + res = max(res, runningGap); + } + return res; + } +}; diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944-2.cpp b/solutions/2944. Minimum Number of Coins for Fruits/2944-2.cpp new file mode 100644 index 00000000000..8669e13f151 --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minimumCoins(vector& prices) { + const int n = prices.size(); + int ans = 0; + using P = pair; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed). + priority_queue, greater<>> minHeap; + minHeap.emplace(0, n); + + for (int i = n - 1; i >= 0; --i) { + while (!minHeap.empty() && minHeap.top().second > (i + 1) * 2) + minHeap.pop(); + ans = prices[i] + minHeap.top().first; + minHeap.emplace(ans, i); + } + + return ans; + } +}; diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944-2.java b/solutions/2944. Minimum Number of Coins for Fruits/2944-2.java new file mode 100644 index 00000000000..4e8da664b5e --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944-2.java @@ -0,0 +1,19 @@ +class Solution { + public int minimumCoins(int[] prices) { + final int n = prices.length; + int ans = 0; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed). + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + minHeap.offer(new Pair<>(0, n)); + + for (int i = n - 1; i >= 0; --i) { + while (!minHeap.isEmpty() && minHeap.peek().getValue() > (i + 1) * 2) + minHeap.poll(); + ans = prices[i] + minHeap.peek().getKey(); + minHeap.offer(new Pair<>(ans, i)); + } + + return ans; + } +} diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944-2.py b/solutions/2944. Minimum Number of Coins for Fruits/2944-2.py new file mode 100644 index 00000000000..696ecd68d56 --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944-2.py @@ -0,0 +1,15 @@ +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + # Stores (dp[i], i), where dp[i] is the minimum number of coins to acquire + # fruits[i:] (0-indexed). + minHeap = [(0, n)] + ans = 0 + + for i in range(n - 1, -1, -1): + while minHeap and minHeap[0][1] > (i + 1) * 2: + heapq.heappop(minHeap) + ans = prices[i] + minHeap[0][0] + heapq.heappush(minHeap, (ans, i)) + + return ans diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944-3.cpp b/solutions/2944. Minimum Number of Coins for Fruits/2944-3.cpp new file mode 100644 index 00000000000..1828a0bf988 --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944-3.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minimumCoins(vector& prices) { + const int n = prices.size(); + int ans = INT_MAX; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed) in ascending order. + deque> minQ{{0, n}}; + + for (int i = n - 1; i >= 0; --i) { + while (!minQ.empty() && minQ.front().second > (i + 1) * 2) + minQ.pop_front(); + ans = prices[i] + minQ.front().first; + while (!minQ.empty() && minQ.back().first >= ans) + minQ.pop_back(); + minQ.emplace_back(ans, i); + } + + return ans; + } +}; diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944-3.java b/solutions/2944. Minimum Number of Coins for Fruits/2944-3.java new file mode 100644 index 00000000000..1d416989c82 --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944-3.java @@ -0,0 +1,21 @@ +class Solution { + public int minimumCoins(int[] prices) { + final int n = prices.length; + int ans = Integer.MAX_VALUE; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed) in ascending order. + Deque> minQ = new ArrayDeque<>(); + minQ.offerFirst(new Pair<>(0, n)); + + for (int i = n - 1; i >= 0; --i) { + while (!minQ.isEmpty() && minQ.peekFirst().getValue() > (i + 1) * 2) + minQ.pollFirst(); + ans = prices[i] + minQ.peekFirst().getKey(); + while (!minQ.isEmpty() && minQ.peekLast().getKey() >= ans) + minQ.pollLast(); + minQ.offerLast(new Pair<>(ans, i)); + } + + return ans; + } +} diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944-3.py b/solutions/2944. Minimum Number of Coins for Fruits/2944-3.py new file mode 100644 index 00000000000..e120e8e56b6 --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944-3.py @@ -0,0 +1,17 @@ +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + ans = math.inf + # Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + # fruits[i:] (0-indexed) in ascending order. + minQ = collections.deque([(0, n)]) + + for i in range(n - 1, -1, -1): + while minQ and minQ[0][1] > (i + 1) * 2: + minQ.popleft() + ans = prices[i] + minQ[0][0] + while minQ and minQ[-1][0] >= ans: + minQ.pop() + minQ.append((ans, i)) + + return ans diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944.cpp b/solutions/2944. Minimum Number of Coins for Fruits/2944.cpp new file mode 100644 index 00000000000..c203ee01c06 --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minimumCoins(vector& prices) { + const int n = prices.size(); + vector dp(n + 1, INT_MAX); + dp[n] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j <= min((i + 1) * 2, n); ++j) + dp[i] = min(dp[i], prices[i] + dp[j]); + + return dp[0]; + } +}; diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944.java b/solutions/2944. Minimum Number of Coins for Fruits/2944.java new file mode 100644 index 00000000000..d7c71dda34d --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944.java @@ -0,0 +1,14 @@ +class Solution { + public int minimumCoins(int[] prices) { + final int n = prices.length; + int[] dp = new int[n + 1]; + Arrays.fill(dp, Integer.MAX_VALUE); + dp[n] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j <= Math.min((i + 1) * 2, n); ++j) + dp[i] = Math.min(dp[i], prices[i] + dp[j]); + + return dp[0]; + } +} diff --git a/solutions/2944. Minimum Number of Coins for Fruits/2944.py b/solutions/2944. Minimum Number of Coins for Fruits/2944.py new file mode 100644 index 00000000000..430ac15807b --- /dev/null +++ b/solutions/2944. Minimum Number of Coins for Fruits/2944.py @@ -0,0 +1,13 @@ +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + # Convert to 0-indexed for easy computation. + # dp[i] := the minimum number of coins to acquire fruits[i:] + dp = [math.inf] * n + [0] + + for i in range(n - 1, -1, -1): + # Convert back to 1-indexed. + for j in range(i + 1, min((i + 1) * 2 + 1, n + 1)): + dp[i] = min(dp[i], prices[i] + dp[j]) + + return dp[0] diff --git a/solutions/2945. Find Maximum Non-decreasing Array Length/2945-2.py b/solutions/2945. Find Maximum Non-decreasing Array Length/2945-2.py new file mode 100644 index 00000000000..8f5a87d55cc --- /dev/null +++ b/solutions/2945. Find Maximum Non-decreasing Array Length/2945-2.py @@ -0,0 +1,25 @@ +class Solution: + def findMaximumLength(self, nums: List[int]) -> int: + n = len(nums) + # prefix[i] := the sum of the first i nums + prefix = list(itertools.accumulate(nums, initial=0)) + # dp[i] := the maximum number of elements in the increasing + # sequence after processing the first i nums + dp = [0] * (n + 1) + # bestLeft[i] := the index l s.t. merging nums[l..i) is the + # optimal strategy among processing the first i nums + bestLeft = [0] * (n + 2) + + for i in range(1, n + 1): + bestLeft[i] = max(bestLeft[i], bestLeft[i - 1]) + # When merging nums[l, i), consider the next segment as [i, r). + # Find the minimum `r` where sum(nums[l, i)) <= sum(nums[i, r)). + # Equivalently, prefix[i] - prefix[l] <= prefix[r] - prefix[i]. + # => prefix[r] >= prefix[i] * 2 - prefix[l] + # Therefore, we can binary search `prefix` to find the minimum `r`. + l = bestLeft[i] + r = bisect.bisect_left(prefix, 2 * prefix[i] - prefix[l]) + dp[i] = dp[l] + 1 + bestLeft[r] = i + + return dp[n] diff --git a/solutions/2945. Find Maximum Non-decreasing Array Length/2945.py b/solutions/2945. Find Maximum Non-decreasing Array Length/2945.py new file mode 100644 index 00000000000..cf448561a85 --- /dev/null +++ b/solutions/2945. Find Maximum Non-decreasing Array Length/2945.py @@ -0,0 +1,28 @@ +class Solution: + def findMaximumLength(self, nums: List[int]) -> int: + n = len(nums) + kInf = 10_000_000_000 + # prefix[i] := the sum of the first i nums + prefix = list(itertools.accumulate(nums, initial=0)) + # dp[i] := the maximum number of elements in the increasing + # sequence after processing the first i nums + dp = [0] * (n + 1) + # last[i] := the last sum after processing the first i nums + last = [0] + [kInf] * n + + for i in range(n): + j = self._findIndex(i, prefix, last) + dp[i + 1] = max(dp[i], dp[j] + 1) + last[i + 1] = prefix[i + 1] - prefix[j] + + return dp[n] + + def _findIndex(self, i: int, prefix: List[int], last: List[int]) -> int: + """Returns the index in [0..i]. + + Returns the maximum index j in [0..i] s.t. + prefix[i + 1] - prefix[j] >= last[j]. + """ + for j in range(i, -1, -1): + if prefix[i + 1] - prefix[j] >= last[j]: + return j diff --git a/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.cpp b/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.cpp new file mode 100644 index 00000000000..68ec6dcd3bd --- /dev/null +++ b/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool areSimilar(vector>& mat, int k) { + const int n = mat[0].size(); + for (const vector& row : mat) + for (int j = 0; j < n; ++j) + if (row[j] != row[(j + k) % n]) + return false; + return true; + } +}; diff --git a/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.java b/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.java new file mode 100644 index 00000000000..0756fdfc3b4 --- /dev/null +++ b/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.java @@ -0,0 +1,10 @@ +class Solution { + public boolean areSimilar(int[][] mat, int k) { + final int n = mat[0].length; + for (int[] row : mat) + for (int j = 0; j < n; ++j) + if (row[j] != row[(j + k) % n]) + return false; + return true; + } +} diff --git a/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.py b/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.py new file mode 100644 index 00000000000..c12214bca25 --- /dev/null +++ b/solutions/2946. Matrix Similarity After Cyclic Shifts/2946.py @@ -0,0 +1,8 @@ +class Solution: + def areSimilar(self, mat: List[List[int]], k: int) -> bool: + n = len(mat[0]) + for row in mat: + for j in range(n): + if row[j] != row[(j + k) % n]: + return False + return True diff --git a/solutions/2947. Count Beautiful Substrings I/2947.cpp b/solutions/2947. Count Beautiful Substrings I/2947.cpp new file mode 100644 index 00000000000..cc4756855bd --- /dev/null +++ b/solutions/2947. Count Beautiful Substrings I/2947.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int beautifulSubstrings(string s, int k) { + const int root = getRoot(k); + int ans = 0; + int vowels = 0; + int vowelsMinusConsonants = 0; + // {(vowels, vowelsMinusConsonants): count} + unordered_map, int, PairHash> prefixCount{{{0, 0}, 1}}; + + for (const char c : s) { + if (isVowel(c)) { + vowels = (vowels + 1) % root; + ++vowelsMinusConsonants; + } else { + --vowelsMinusConsonants; + } + const pair prefix{vowels, vowelsMinusConsonants}; + ans += prefixCount[prefix]++; + } + + return ans; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } + + int getRoot(int k) { + for (int i = 1; i <= k; ++i) + if (i * i % k == 0) + return i; + throw; + } + + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/2947. Count Beautiful Substrings I/2947.java b/solutions/2947. Count Beautiful Substrings I/2947.java new file mode 100644 index 00000000000..f505344e1a1 --- /dev/null +++ b/solutions/2947. Count Beautiful Substrings I/2947.java @@ -0,0 +1,36 @@ +class Solution { + public int beautifulSubstrings(String s, int k) { + final int root = getRoot(k); + int ans = 0; + int vowels = 0; + int vowelsMinusConsonants = 0; + // {(vowels, vowelsMinusConsonants): count} + Map, Integer> prefixCount = new HashMap<>(); + prefixCount.put(new Pair<>(0, 0), 1); + + for (final char c : s.toCharArray()) { + if (isVowel(c)) { + vowels = (vowels + 1) % root; + ++vowelsMinusConsonants; + } else { + --vowelsMinusConsonants; + } + Pair prefix = new Pair<>(vowels, vowelsMinusConsonants); + ans += prefixCount.getOrDefault(prefix, 0); + prefixCount.merge(prefix, 1, Integer::sum); + } + + return ans; + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(c) != -1; + } + + private int getRoot(int k) { + for (int i = 1; i <= k; ++i) + if (i * i % k == 0) + return i; + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2947. Count Beautiful Substrings I/2947.py b/solutions/2947. Count Beautiful Substrings I/2947.py new file mode 100644 index 00000000000..956837c5136 --- /dev/null +++ b/solutions/2947. Count Beautiful Substrings I/2947.py @@ -0,0 +1,25 @@ +class Solution: + def beautifulSubstrings(self, s: str, k: int) -> int: + kVowels = 'aeiou' + root = self._getRoot(k) + ans = 0 + vowels = 0 + vowelsMinusConsonants = 0 + # {(vowels, vowelsMinusConsonants): count} + prefixCount = collections.Counter({(0, 0): 1}) + + for c in s: + if c in kVowels: + vowelsMinusConsonants += 1 + vowels = (vowels + 1) % root + else: + vowelsMinusConsonants -= 1 + ans += prefixCount[(vowels, vowelsMinusConsonants)] + prefixCount[(vowels, vowelsMinusConsonants)] += 1 + + return ans + + def _getRoot(self, k: int) -> int: + for i in range(1, k + 1): + if i * i % k == 0: + return i diff --git a/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.cpp b/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.cpp new file mode 100644 index 00000000000..e73db4f5e9b --- /dev/null +++ b/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + vector lexicographicallySmallestArray(vector& nums, int limit) { + vector ans(nums.size()); + // [[(num, index)]], where the difference between in each pair in each + // `[(num, index)]` group <= `limit` + vector>> numAndIndexesGroups; + + for (const pair& numAndIndex : getNumAndIndexes(nums)) + if (numAndIndexesGroups.empty() || + numAndIndex.first - numAndIndexesGroups.back().back().first > limit) { + // Start a new group. + numAndIndexesGroups.push_back({numAndIndex}); + } else { + // Append to the existing group. + numAndIndexesGroups.back().push_back(numAndIndex); + } + + for (const vector>& numAndIndexesGroup : + numAndIndexesGroups) { + vector sortedNums; + vector sortedIndices; + for (const auto& [num, index] : numAndIndexesGroup) { + sortedNums.push_back(num); + sortedIndices.push_back(index); + } + ranges::sort(sortedIndices); + for (int i = 0; i < sortedNums.size(); ++i) + ans[sortedIndices[i]] = sortedNums[i]; + } + + return ans; + } + + private: + vector> getNumAndIndexes(const vector& nums) { + vector> numAndIndexes; + for (int i = 0; i < nums.size(); ++i) + numAndIndexes.emplace_back(nums[i], i); + ranges::sort(numAndIndexes); + return numAndIndexes; + } +}; diff --git a/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.java b/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.java new file mode 100644 index 00000000000..e652c85bd58 --- /dev/null +++ b/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.java @@ -0,0 +1,43 @@ +class Solution { + public int[] lexicographicallySmallestArray(int[] nums, int limit) { + int[] ans = new int[nums.length]; + List>> numAndIndexesGroups = new ArrayList<>(); + + for (Pair numAndIndex : getNumAndIndexes(nums)) + if (numAndIndexesGroups.isEmpty() || + numAndIndex.getKey() - + numAndIndexesGroups.get(numAndIndexesGroups.size() - 1) + .get(numAndIndexesGroups.get(numAndIndexesGroups.size() - 1).size() - 1) + .getKey() > + limit) { + // Start a new group. + numAndIndexesGroups.add(new ArrayList<>(List.of(numAndIndex))); + } else { + // Append to the existing group. + numAndIndexesGroups.get(numAndIndexesGroups.size() - 1).add(numAndIndex); + } + + for (List> numAndIndexesGroup : numAndIndexesGroups) { + List sortedNums = new ArrayList<>(); + List sortedIndices = new ArrayList<>(); + for (Pair pair : numAndIndexesGroup) { + sortedNums.add(pair.getKey()); + sortedIndices.add(pair.getValue()); + } + sortedIndices.sort(null); + for (int i = 0; i < sortedNums.size(); ++i) { + ans[sortedIndices.get(i)] = sortedNums.get(i); + } + } + + return ans; + } + + private Pair[] getNumAndIndexes(int[] nums) { + Pair[] numAndIndexes = new Pair[nums.length]; + for (int i = 0; i < nums.length; ++i) + numAndIndexes[i] = new Pair<>(nums[i], i); + Arrays.sort(numAndIndexes, (a, b) -> Integer.compare(a.getKey(), b.getKey())); + return numAndIndexes; + } +} diff --git a/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.py b/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.py new file mode 100644 index 00000000000..5e84927dd88 --- /dev/null +++ b/solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.py @@ -0,0 +1,23 @@ +class Solution: + def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: + ans = [0] * len(nums) + numAndIndexes = sorted([(num, i) for i, num in enumerate(nums)]) + # [[(num, index)]], where the difference between in each pair in each + # `[(num, index)]` group <= `limit` + numAndIndexesGroups: List[List[Tuple[int, int]]] = [] + + for numAndIndex in numAndIndexes: + if not numAndIndexesGroups or numAndIndex[0] - numAndIndexesGroups[-1][-1][0] > limit: + # Start a new group. + numAndIndexesGroups.append([numAndIndex]) + else: + # Append to the existing group. + numAndIndexesGroups[-1].append(numAndIndex) + + for numAndIndexesGroup in numAndIndexesGroups: + sortedNums = [num for num, _ in numAndIndexesGroup] + sortedIndices = sorted([index for _, index in numAndIndexesGroup]) + for num, index in zip(sortedNums, sortedIndices): + ans[index] = num + + return ans diff --git a/solutions/2949. Count Beautiful Substrings II/2949.cpp b/solutions/2949. Count Beautiful Substrings II/2949.cpp new file mode 100644 index 00000000000..6a6a4747100 --- /dev/null +++ b/solutions/2949. Count Beautiful Substrings II/2949.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + // Same as 2947. Count Beautiful Substrings I + int beautifulSubstrings(string s, int k) { + const int root = getRoot(k); + int ans = 0; + int vowels = 0; + int vowelsMinusConsonants = 0; + // {(vowels, vowelsMinusConsonants): count} + unordered_map, int, PairHash> prefixCount{{{0, 0}, 1}}; + + for (const char c : s) { + if (isVowel(c)) { + vowels = (vowels + 1) % root; + ++vowelsMinusConsonants; + } else { + --vowelsMinusConsonants; + } + const pair prefix{vowels, vowelsMinusConsonants}; + ans += prefixCount[prefix]++; + } + + return ans; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } + + int getRoot(int k) { + for (int i = 1; i <= k; ++i) + if (i * i % k == 0) + return i; + throw; + } + + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/2949. Count Beautiful Substrings II/2949.java b/solutions/2949. Count Beautiful Substrings II/2949.java new file mode 100644 index 00000000000..5637482fa79 --- /dev/null +++ b/solutions/2949. Count Beautiful Substrings II/2949.java @@ -0,0 +1,37 @@ +class Solution { + // Same as 2947. Count Beautiful Substrings I + public int beautifulSubstrings(String s, int k) { + final int root = getRoot(k); + int ans = 0; + int vowels = 0; + int vowelsMinusConsonants = 0; + // {(vowels, vowelsMinusConsonants): count} + Map, Integer> prefixCount = new HashMap<>(); + prefixCount.put(new Pair<>(0, 0), 1); + + for (final char c : s.toCharArray()) { + if (isVowel(c)) { + vowels = (vowels + 1) % root; + ++vowelsMinusConsonants; + } else { + --vowelsMinusConsonants; + } + Pair prefix = new Pair<>(vowels, vowelsMinusConsonants); + ans += prefixCount.getOrDefault(prefix, 0); + prefixCount.merge(prefix, 1, Integer::sum); + } + + return ans; + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(c) != -1; + } + + private int getRoot(int k) { + for (int i = 1; i <= k; ++i) + if (i * i % k == 0) + return i; + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2949. Count Beautiful Substrings II/2949.py b/solutions/2949. Count Beautiful Substrings II/2949.py new file mode 100644 index 00000000000..15e2f638f04 --- /dev/null +++ b/solutions/2949. Count Beautiful Substrings II/2949.py @@ -0,0 +1,26 @@ +class Solution: + # Same as 2947. Count Beautiful Substrings I + def beautifulSubstrings(self, s: str, k: int) -> int: + kVowels = 'aeiou' + root = self._getRoot(k) + ans = 0 + vowels = 0 + vowelsMinusConsonants = 0 + # {(vowels, vowelsMinusConsonants): count} + prefixCount = collections.Counter({(0, 0): 1}) + + for c in s: + if c in kVowels: + vowelsMinusConsonants += 1 + vowels = (vowels + 1) % root + else: + vowelsMinusConsonants -= 1 + ans += prefixCount[(vowels, vowelsMinusConsonants)] + prefixCount[(vowels, vowelsMinusConsonants)] += 1 + + return ans + + def _getRoot(self, k: int) -> int: + for i in range(1, k + 1): + if i * i % k == 0: + return i diff --git a/solutions/295. Find Median from Data Stream/295.cpp b/solutions/295. Find Median from Data Stream/295.cpp new file mode 100644 index 00000000000..da7f6adde35 --- /dev/null +++ b/solutions/295. Find Median from Data Stream/295.cpp @@ -0,0 +1,26 @@ +class MedianFinder { + public: + void addNum(int num) { + if (maxHeap.empty() || num <= maxHeap.top()) + maxHeap.push(num); + else + minHeap.push(num); + + // Balance the two heaps s.t. + // |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1. + if (maxHeap.size() < minHeap.size()) + maxHeap.push(minHeap.top()), minHeap.pop(); + else if (maxHeap.size() - minHeap.size() > 1) + minHeap.push(maxHeap.top()), maxHeap.pop(); + } + + double findMedian() { + if (maxHeap.size() == minHeap.size()) + return (maxHeap.top() + minHeap.top()) / 2.0; + return maxHeap.top(); + } + + private: + priority_queue maxHeap; + priority_queue, greater<>> minHeap; +}; diff --git a/solutions/295. Find Median from Data Stream/295.java b/solutions/295. Find Median from Data Stream/295.java new file mode 100644 index 00000000000..846319fad82 --- /dev/null +++ b/solutions/295. Find Median from Data Stream/295.java @@ -0,0 +1,24 @@ +class MedianFinder { + public void addNum(int num) { + if (maxHeap.isEmpty() || num <= maxHeap.peek()) + maxHeap.offer(num); + else + minHeap.offer(num); + + // Balance the two heaps s.t. + // |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1. + if (maxHeap.size() < minHeap.size()) + maxHeap.offer(minHeap.poll()); + else if (maxHeap.size() - minHeap.size() > 1) + minHeap.offer(maxHeap.poll()); + } + + public double findMedian() { + if (maxHeap.size() == minHeap.size()) + return (double) (maxHeap.peek() + minHeap.peek()) / 2.0; + return (double) maxHeap.peek(); + } + + private Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + private Queue minHeap = new PriorityQueue<>(); +} diff --git a/solutions/295. Find Median from Data Stream/295.py b/solutions/295. Find Median from Data Stream/295.py new file mode 100644 index 00000000000..2de96269d27 --- /dev/null +++ b/solutions/295. Find Median from Data Stream/295.py @@ -0,0 +1,22 @@ +class MedianFinder: + def __init__(self): + self.maxHeap = [] + self.minHeap = [] + + def addNum(self, num: int) -> None: + if not self.maxHeap or num <= -self.maxHeap[0]: + heapq.heappush(self.maxHeap, -num) + else: + heapq.heappush(self.minHeap, num) + + # Balance the two heaps s.t. + # |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1. + if len(self.maxHeap) < len(self.minHeap): + heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap)) + elif len(self.maxHeap) - len(self.minHeap) > 1: + heapq.heappush(self.minHeap, -heapq.heappop(self.maxHeap)) + + def findMedian(self) -> float: + if len(self.maxHeap) == len(self.minHeap): + return (-self.maxHeap[0] + self.minHeap[0]) / 2.0 + return -self.maxHeap[0] diff --git a/solutions/2950. Number of Divisible Substrings/2950.cpp b/solutions/2950. Number of Divisible Substrings/2950.cpp new file mode 100644 index 00000000000..323796e6352 --- /dev/null +++ b/solutions/2950. Number of Divisible Substrings/2950.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int countDivisibleSubstrings(string word) { + // Let f(c) = d, where d = 1, 2, ..., 9. + // Rephrase the question to return the number of substrings that satisfy + // f(c1) + f(c2) + ... + f(ck) / k = avg + // => f(c1) + f(c2) + ... + f(ck) - k * avg, where avg in [1, 9]. + int ans = 0; + + for (int avg = 1; avg <= 9; ++avg) { + int prefix = 0; + unordered_map prefixCount{{0, 1}}; + for (const char c : word) { + prefix += f(c) - avg; + ans += prefixCount[prefix]++; + } + } + + return ans; + } + + private: + int f(char c) { + return 9 - ('z' - c) / 3; + } +}; diff --git a/solutions/2950. Number of Divisible Substrings/2950.java b/solutions/2950. Number of Divisible Substrings/2950.java new file mode 100644 index 00000000000..7324487a8d2 --- /dev/null +++ b/solutions/2950. Number of Divisible Substrings/2950.java @@ -0,0 +1,26 @@ +class Solution { + public int countDivisibleSubstrings(String word) { + // Let f(c) = d, where d = 1, 2, ..., 9. + // Rephrase the question to return the number of substrings that satisfy + // f(c1) + f(c2) + ... + f(ck) / k = avg + // => f(c1) + f(c2) + ... + f(ck) - k * avg, where avg in [1, 9]. + int ans = 0; + + for (int avg = 1; avg <= 9; ++avg) { + int prefix = 0; + Map prefixCount = new HashMap<>(); + prefixCount.put(0, 1); + for (final char c : word.toCharArray()) { + prefix += f(c) - avg; + ans += prefixCount.getOrDefault(prefix, 0); + prefixCount.merge(prefix, 1, Integer::sum); + } + } + + return ans; + } + + private int f(char c) { + return 9 - ('z' - c) / 3; + } +} diff --git a/solutions/2950. Number of Divisible Substrings/2950.py b/solutions/2950. Number of Divisible Substrings/2950.py new file mode 100644 index 00000000000..176a886b2fb --- /dev/null +++ b/solutions/2950. Number of Divisible Substrings/2950.py @@ -0,0 +1,20 @@ +class Solution: + def countDivisibleSubstrings(self, word: str) -> int: + # Let f(c) = d, where d = 1, 2, ..., 9. + # Rephrase the question to return the number of substrings that satisfy + # f(c1) + f(c2) + ... + f(ck) // k = avg + # => f(c1) + f(c2) + ... + f(ck) - k * avg, where avg in [1, 9]. + ans = 0 + + def f(c: str) -> int: + return 9 - (ord('z') - ord(c)) // 3 + + for avg in range(1, 10): + prefix = 0 + prefixCount = collections.Counter({0: 1}) + for c in word: + prefix += f(c) - avg + ans += prefixCount[prefix] + prefixCount[prefix] += 1 + + return ans diff --git a/solutions/2951. Find the Peaks/2951.cpp b/solutions/2951. Find the Peaks/2951.cpp new file mode 100644 index 00000000000..0eaafdbe942 --- /dev/null +++ b/solutions/2951. Find the Peaks/2951.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + vector findPeaks(vector& mountain) { + vector ans; + for (int i = 1; i + 1 < mountain.size(); ++i) + if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) + ans.push_back(i); + return ans; + } +}; diff --git a/solutions/2951. Find the Peaks/2951.java b/solutions/2951. Find the Peaks/2951.java new file mode 100644 index 00000000000..1a86f2f574b --- /dev/null +++ b/solutions/2951. Find the Peaks/2951.java @@ -0,0 +1,9 @@ +class Solution { + public List findPeaks(int[] mountain) { + List ans = new ArrayList<>(); + for (int i = 1; i + 1 < mountain.length; ++i) + if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) + ans.add(i); + return ans; + } +} diff --git a/solutions/2951. Find the Peaks/2951.py b/solutions/2951. Find the Peaks/2951.py new file mode 100644 index 00000000000..3738f1d2204 --- /dev/null +++ b/solutions/2951. Find the Peaks/2951.py @@ -0,0 +1,4 @@ +class Solution: + def findPeaks(self, mountain: List[int]) -> List[int]: + return [i for i in range(1, len(mountain) - 1) + if mountain[i - 1] < mountain[i] > mountain[i + 1]] diff --git a/solutions/2952. Minimum Number of Coins to be Added/2952.cpp b/solutions/2952. Minimum Number of Coins to be Added/2952.cpp new file mode 100644 index 00000000000..6f6977558cd --- /dev/null +++ b/solutions/2952. Minimum Number of Coins to be Added/2952.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + // Same as 330. Patching Array + int minimumAddedCoins(vector& coins, int target) { + int ans = 0; + int i = 0; // coins' index + long miss = 1; // the minimum sum in [1, n] we might miss + + ranges::sort(coins); + + while (miss <= target) + if (i < coins.size() && coins[i] <= miss) { + miss += coins[i++]; + } else { + // Greedily add `miss` itself to increase the range from + // [1, miss) to [1, 2 * miss). + miss += miss; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/2952. Minimum Number of Coins to be Added/2952.java b/solutions/2952. Minimum Number of Coins to be Added/2952.java new file mode 100644 index 00000000000..082227985d0 --- /dev/null +++ b/solutions/2952. Minimum Number of Coins to be Added/2952.java @@ -0,0 +1,22 @@ +class Solution { + // Same as 330. Patching Array + public int minimumAddedCoins(int[] coins, int target) { + int ans = 0; + int i = 0; // coins' index + long miss = 1; // the minimum sum in [1, n] we might miss + + Arrays.sort(coins); + + while (miss <= target) + if (i < coins.length && coins[i] <= miss) { + miss += coins[i++]; + } else { + // Greedily add `miss` itself to increase the range from + // [1, miss) to [1, 2 * miss). + miss += miss; + ++ans; + } + + return ans; + } +} diff --git a/solutions/2952. Minimum Number of Coins to be Added/2952.py b/solutions/2952. Minimum Number of Coins to be Added/2952.py new file mode 100644 index 00000000000..4ba88d2a65b --- /dev/null +++ b/solutions/2952. Minimum Number of Coins to be Added/2952.py @@ -0,0 +1,20 @@ +class Solution: + # Same as 330. Patching Array + def minimumAddedCoins(self, coins: List[int], target: int) -> int: + ans = 0 + i = 0 # coins' index + miss = 1 # the minimum sum in [1, n] we might miss + + coins.sort() + + while miss <= target: + if i < len(coins) and coins[i] <= miss: + miss += coins[i] + i += 1 + else: + # Greedily add `miss` itself to increase the range from + # [1, miss) to [1, 2 * miss). + miss += miss + ans += 1 + + return ans diff --git a/solutions/2953. Count Complete Substrings/2953.cpp b/solutions/2953. Count Complete Substrings/2953.cpp new file mode 100644 index 00000000000..fad8f484415 --- /dev/null +++ b/solutions/2953. Count Complete Substrings/2953.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int countCompleteSubstrings(string word, int k) { + const int uniqueLetters = + unordered_set{word.begin(), word.end()}.size(); + int ans = 0; + + for (int windowSize = k; + windowSize <= k * uniqueLetters && windowSize <= word.length(); + windowSize += k) + ans += countCompleteStrings(word, k, windowSize); + + return ans; + } + + private: + // Returns the number of complete substrings of `windowSize` of `word`. + int countCompleteStrings(const string& word, int k, int windowSize) { + int res = 0; + int countLetters = 0; // the number of letters in the running substring + vector count(26); + + for (int i = 0; i < word.length(); ++i) { + ++count[word[i] - 'a']; + ++countLetters; + if (i > 0 && abs(word[i] - word[i - 1]) > 2) { + count = vector(26); + // Start a new substring starting at word[i]. + ++count[word[i] - 'a']; + countLetters = 1; + } + if (countLetters == windowSize + 1) { + --count[word[i - windowSize] - 'a']; + --countLetters; + } + if (countLetters == windowSize) + res += ranges::all_of(count, + [k](int freq) { return freq == 0 || freq == k; }) + ? 1 + : 0; + } + + return res; + } +}; diff --git a/solutions/2953. Count Complete Substrings/2953.java b/solutions/2953. Count Complete Substrings/2953.java new file mode 100644 index 00000000000..ad67331371b --- /dev/null +++ b/solutions/2953. Count Complete Substrings/2953.java @@ -0,0 +1,39 @@ +class Solution { + public int countCompleteSubstrings(String word, int k) { + final int uniqueLetters = word.chars().boxed().collect(Collectors.toSet()).size(); + int ans = 0; + + for (int windowSize = k; windowSize <= k * uniqueLetters && windowSize <= word.length(); + windowSize += k) { + ans += countCompleteStrings(word, k, windowSize); + } + + return ans; + } + + // Returns the number of complete substrings of `windowSize` of `word`. + private int countCompleteStrings(final String word, int k, int windowSize) { + int res = 0; + int countLetters = 0; // the number of letters in the running substring + int[] count = new int[26]; + + for (int i = 0; i < word.length(); ++i) { + ++count[word.charAt(i) - 'a']; + ++countLetters; + if (i > 0 && Math.abs(word.charAt(i) - word.charAt(i - 1)) > 2) { + count = new int[26]; + // Start a new substring starting at word[i]. + ++count[word.charAt(i) - 'a']; + countLetters = 1; + } + if (countLetters == windowSize + 1) { + --count[word.charAt(i - windowSize) - 'a']; + --countLetters; + } + if (countLetters == windowSize) + res += Arrays.stream(count).allMatch(freq -> freq == 0 || freq == k) ? 1 : 0; + } + + return res; + } +} diff --git a/solutions/2953. Count Complete Substrings/2953.py b/solutions/2953. Count Complete Substrings/2953.py new file mode 100644 index 00000000000..1303d9cbe74 --- /dev/null +++ b/solutions/2953. Count Complete Substrings/2953.py @@ -0,0 +1,29 @@ +class Solution: + def countCompleteSubstrings(self, word: str, k: int) -> int: + uniqueLetters = len(set(word)) + return sum(self._countCompleteStrings(word, k, windowSize) + for windowSize in range(k, k * uniqueLetters + 1, k)) + + def _countCompleteStrings(self, word: str, k: int, windowSize: int) -> int: + """ + Returns the number of complete substrings of `windowSize` of `word`. + """ + res = 0 + countLetters = 0 # the number of letters in the running substring + count = collections.Counter() + + for i, c in enumerate(word): + count[c] += 1 + countLetters += 1 + if i > 0 and abs(ord(c) - ord(word[i - 1])) > 2: + count = collections.Counter() + # Start a new substring starting at word[i]. + count[c] += 1 + countLetters = 1 + if countLetters == windowSize + 1: + count[word[i - windowSize]] -= 1 + countLetters -= 1 + if countLetters == windowSize: + res += all(freq == 0 or freq == k for freq in count.values()) + + return res diff --git a/solutions/2954. Count the Number of Infection Sequences/2954.cpp b/solutions/2954. Count the Number of Infection Sequences/2954.cpp new file mode 100644 index 00000000000..521ab4f788f --- /dev/null +++ b/solutions/2954. Count the Number of Infection Sequences/2954.cpp @@ -0,0 +1,57 @@ +class Solution { + public: + int numberOfSequence(int n, vector& sick) { + const auto [fact, invFact] = getFactAndInvFact(n - sick.size()); + long ans = fact[n - sick.size()]; // the number of infected children + int prevSick = -1; + + for (int i = 0; i < sick.size(); ++i) { + // The segment [prevSick + 1, sick - 1] are the current non-infected + // children. + const int nonInfected = sick[i] - prevSick - 1; + prevSick = sick[i]; + if (nonInfected == 0) + continue; + ans *= invFact[nonInfected]; + ans %= kMod; + if (i > 0) { + // There're two choices per second since the children at the two + // endpoints can both be the infect candidates. So, there are + // 2^{nonInfected - 1} ways to infect all children in the current + // segment. + ans *= modPow(2, nonInfected - 1); + ans %= kMod; + } + } + + const int nonInfected = n - sick.back() - 1; + ans *= invFact[nonInfected]; + return ans % kMod; + } + + private: + static constexpr int kMod = 1'000'000'007; + + pair, vector> getFactAndInvFact(int n) { + vector fact(n + 1); + vector invFact(n + 1); + vector inv(n + 1); + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return {fact, invFact}; + } + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/2954. Count the Number of Infection Sequences/2954.java b/solutions/2954. Count the Number of Infection Sequences/2954.java new file mode 100644 index 00000000000..f38ccfbd50d --- /dev/null +++ b/solutions/2954. Count the Number of Infection Sequences/2954.java @@ -0,0 +1,57 @@ +class Solution { + public int numberOfSequence(int n, int[] sick) { + final long[][] factAndInvFact = getFactAndInvFact(n - sick.length); + final long[] fact = factAndInvFact[0]; + final long[] invFact = factAndInvFact[1]; + long ans = fact[n - sick.length]; // the number of infected children + int prevSick = -1; + + for (int i = 0; i < sick.length; ++i) { + // The segment [prevSick + 1, sick - 1] are the current non-infected + // children. + final int nonInfected = sick[i] - prevSick - 1; + prevSick = sick[i]; + if (nonInfected == 0) + continue; + ans *= invFact[nonInfected]; + ans %= kMod; + if (i > 0) { + // There're two choices per second since the children at the two + // endpoints can both be the infect candidates. So, there are + // 2^{nonInfected - 1} ways to infect all children in the current + // segment. + ans *= modPow(2, nonInfected - 1); + ans %= kMod; + } + } + + final int nonInfected = n - sick[sick.length - 1] - 1; + ans *= invFact[nonInfected]; + return (int) (ans % kMod); + } + + private static final int kMod = 1_000_000_007; + + private long[][] getFactAndInvFact(int n) { + long[] fact = new long[n + 1]; + long[] invFact = new long[n + 1]; + long[] inv = new long[n + 1]; + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return new long[][] {fact, invFact}; + } + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +} diff --git a/solutions/2954. Count the Number of Infection Sequences/2954.py b/solutions/2954. Count the Number of Infection Sequences/2954.py new file mode 100644 index 00000000000..307e9632e67 --- /dev/null +++ b/solutions/2954. Count the Number of Infection Sequences/2954.py @@ -0,0 +1,33 @@ +class Solution: + def numberOfSequence(self, n: int, sick: List[int]) -> int: + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def fact(i: int) -> int: + return 1 if i <= 1 else i * fact(i - 1) % kMod + + @functools.lru_cache(None) + def inv(i: int) -> int: + return pow(i, kMod - 2, kMod) + + ans = fact(n - len(sick)) # the number of infected children + prevSick = -1 + + for i, s in enumerate(sick): + # The segment [prevSick + 1, sick - 1] are the current non-infected + # children. + nonInfected = sick[i] - prevSick - 1 + prevSick = sick[i] + if nonInfected == 0: + continue + ans *= inv(fact(nonInfected)) + ans %= kMod + if i > 0: + # There're two choices per second since the children at the two + # endpoints can both be the infect candidates. So, there are + # 2^[nonInfected - 1] ways to infect all children in the current + # segment. + ans *= pow(2, nonInfected - 1, kMod) + + nonInfected = n - sick[-1] - 1 + return ans * inv(fact(nonInfected)) % kMod diff --git a/solutions/2955. Number of Same-End Substrings/2955.cpp b/solutions/2955. Number of Same-End Substrings/2955.cpp new file mode 100644 index 00000000000..77cee982fc0 --- /dev/null +++ b/solutions/2955. Number of Same-End Substrings/2955.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector sameEndSubstringCount(string s, vector>& queries) { + vector ans; + vector count(26); + // counts[i] := the count of s[0..i) + vector> counts = {count}; + + for (const char c : s) { + ++count[c - 'a']; + counts.push_back(count); + } + + for (const vector& query : queries) { + const int l = query[0]; + const int r = query[1]; + int sameEndCount = 0; + for (char c = 'a'; c <= 'z'; ++c) { + // the count of s[0..r + 1) - the count of s[0..l) + // = the count of s[l..r] + const int freq = counts[r + 1][c - 'a'] - counts[l][c - 'a']; + // C(freq, 2) + freq + // = freq * (freq - 1) / 2 + freq + // = freq * (freq + 1) / 2 + sameEndCount += freq * (freq + 1) / 2; + } + ans.push_back(sameEndCount); + } + + return ans; + } +}; diff --git a/solutions/2955. Number of Same-End Substrings/2955.java b/solutions/2955. Number of Same-End Substrings/2955.java new file mode 100644 index 00000000000..de3932bde61 --- /dev/null +++ b/solutions/2955. Number of Same-End Substrings/2955.java @@ -0,0 +1,31 @@ +class Solution { + public int[] sameEndSubstringCount(String s, int[][] queries) { + int[] ans = new int[queries.length]; + int[] count = new int[26]; + // counts[i] := the count of s[0..i) + int[][] counts = new int[s.length() + 1][26]; + + for (int i = 0; i < s.length(); i++) { + ++count[s.charAt(i) - 'a']; + System.arraycopy(count, 0, counts[i + 1], 0, 26); + } + + for (int i = 0; i < queries.length; ++i) { + final int l = queries[i][0]; + final int r = queries[i][1]; + int sameEndCount = 0; + for (char c = 'a'; c <= 'z'; ++c) { + // the count of s[0..r + 1) - the count of s[0..l) + // = the count of s[l..r] + final int freq = counts[r + 1][c - 'a'] - counts[l][c - 'a']; + // C(freq, 2) + freq + // = freq * (freq - 1) / 2 + freq + // = freq * (freq + 1) / 2 + sameEndCount += freq * (freq + 1) / 2; + } + ans[i] = sameEndCount; + } + + return ans; + } +} diff --git a/solutions/2955. Number of Same-End Substrings/2955.py b/solutions/2955. Number of Same-End Substrings/2955.py new file mode 100644 index 00000000000..683c1ce21fd --- /dev/null +++ b/solutions/2955. Number of Same-End Substrings/2955.py @@ -0,0 +1,25 @@ +class Solution: + def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]: + count = collections.Counter() + # counts[i] := the count of s[0..i) + counts = [count.copy()] + + for c in s: + count[c] += 1 + counts.append(count.copy()) + + ans = [] + + for l, r in queries: + sameEndCount = 0 + for c in string.ascii_lowercase: + # the count of s[0..r] - the count of s[0..l - 1] + # = the count of s[l..r] + freq = counts[r + 1][c] - counts[l][c] + # C(freq, 2) + freq + # = freq * (freq - 1) / 2 + freq + # = freq * (freq + 1) / 2 + sameEndCount += freq * (freq + 1) // 2 + ans.append(sameEndCount) + + return ans diff --git a/solutions/2956. Find Common Elements Between Two Arrays/2956.cpp b/solutions/2956. Find Common Elements Between Two Arrays/2956.cpp new file mode 100644 index 00000000000..95c82ec2455 --- /dev/null +++ b/solutions/2956. Find Common Elements Between Two Arrays/2956.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector findIntersectionValues(vector& nums1, vector& nums2) { + const unordered_set set1{nums1.begin(), nums1.end()}; + const unordered_set set2{nums2.begin(), nums2.end()}; + const int ans1 = ranges::count_if( + nums1, [&set2](int num) { return set2.contains(num); }); + const int ans2 = ranges::count_if( + nums2, [&set1](int num) { return set1.contains(num); }); + return {ans1, ans2}; + } +}; diff --git a/solutions/2956. Find Common Elements Between Two Arrays/2956.java b/solutions/2956. Find Common Elements Between Two Arrays/2956.java new file mode 100644 index 00000000000..41a199c77fb --- /dev/null +++ b/solutions/2956. Find Common Elements Between Two Arrays/2956.java @@ -0,0 +1,9 @@ +class Solution { + public int[] findIntersectionValues(int[] nums1, int[] nums2) { + Set nums1Set = Arrays.stream(nums1).boxed().collect(Collectors.toSet()); + Set nums2Set = Arrays.stream(nums2).boxed().collect(Collectors.toSet()); + final int ans1 = (int) Arrays.stream(nums1).filter(nums2Set::contains).count(); + final int ans2 = (int) Arrays.stream(nums2).filter(nums1Set::contains).count(); + return new int[] {ans1, ans2}; + } +} diff --git a/solutions/2956. Find Common Elements Between Two Arrays/2956.py b/solutions/2956. Find Common Elements Between Two Arrays/2956.py new file mode 100644 index 00000000000..6a44990c107 --- /dev/null +++ b/solutions/2956. Find Common Elements Between Two Arrays/2956.py @@ -0,0 +1,6 @@ +class Solution: + def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]: + nums1Set = set(nums1) + nums2Set = set(nums2) + return [sum(num in nums2Set for num in nums1), + sum(num in nums1Set for num in nums2)] diff --git a/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.cpp b/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.cpp new file mode 100644 index 00000000000..021c295904d --- /dev/null +++ b/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int removeAlmostEqualCharacters(string word) { + int ans = 0; + + int i = 1; + while (i < word.length()) + if (abs(word[i] - word[i - 1]) <= 1) { + ++ans; + i += 2; + } else { + i += 1; + } + + return ans; + } +}; diff --git a/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.java b/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.java new file mode 100644 index 00000000000..0844707cf66 --- /dev/null +++ b/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.java @@ -0,0 +1,16 @@ +class Solution { + public int removeAlmostEqualCharacters(String word) { + int ans = 0; + + int i = 1; + while (i < word.length()) + if (Math.abs(word.charAt(i) - word.charAt(i - 1)) <= 1) { + ++ans; + i += 2; + } else { + i += 1; + } + + return ans; + } +} diff --git a/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.py b/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.py new file mode 100644 index 00000000000..26c3e0fd20f --- /dev/null +++ b/solutions/2957. Remove Adjacent Almost-Equal Characters/2957.py @@ -0,0 +1,11 @@ +class Solution: + def removeAlmostEqualCharacters(self, word: str) -> int: + ans = 0 + i = 1 + while i < len(word): + if abs(ord(word[i]) - ord(word[i - 1])) <= 1: + ans += 1 + i += 2 + else: + i += 1 + return ans diff --git a/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.cpp b/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.cpp new file mode 100644 index 00000000000..d2f19949ab4 --- /dev/null +++ b/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxSubarrayLength(vector& nums, int k) { + int ans = 0; + unordered_map count; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + ++count[nums[r]]; + while (count[nums[r]] == k + 1) + --count[nums[l++]]; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.java b/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.java new file mode 100644 index 00000000000..fbf40feb39a --- /dev/null +++ b/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.java @@ -0,0 +1,15 @@ +class Solution { + public int maxSubarrayLength(int[] nums, int k) { + int ans = 0; + Map count = new HashMap<>(); + + for (int l = 0, r = 0; r < nums.length; ++r) { + count.merge(nums[r], 1, Integer::sum); + while (count.get(nums[r]) == k + 1) + count.merge(nums[l++], -1, Integer::sum); + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.py b/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.py new file mode 100644 index 00000000000..65f1060d64b --- /dev/null +++ b/solutions/2958. Length of Longest Subarray With at Most K Frequency/2958.py @@ -0,0 +1,14 @@ +class Solution: + def maxSubarrayLength(self, nums: List[int], k: int) -> int: + ans = 0 + count = collections.Counter() + + l = 0 + for r, num in enumerate(nums): + count[num] += 1 + while count[num] == k + 1: + count[nums[l]] -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/2959. Number of Possible Sets of Closing Branches/2959.cpp b/solutions/2959. Number of Possible Sets of Closing Branches/2959.cpp new file mode 100644 index 00000000000..c2f08313880 --- /dev/null +++ b/solutions/2959. Number of Possible Sets of Closing Branches/2959.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int numberOfSets(int n, int maxDistance, vector>& roads) { + const int maxMask = 1 << n; + int ans = 0; + + for (int mask = 0; mask < maxMask; ++mask) + if (floydWarshall(n, maxDistance, roads, mask) <= maxDistance) + ++ans; + + return ans; + } + + private: + // Returns the maximum distance between any two branches, where the mask + // represents the selected branches. + int floydWarshall(int n, int maxDistanceThreshold, vector>& roads, + int mask) { + int maxDistance = 0; + vector> dist(n, vector(n, maxDistanceThreshold + 1)); + + for (int i = 0; i < n; ++i) + if (mask >> i & 1) + dist[i][i] = 0; + + for (const vector& road : roads) { + const int u = road[0]; + const int v = road[1]; + const int w = road[2]; + if (mask >> u & 1 && mask >> v & 1) { + dist[u][v] = min(dist[u][v], w); + dist[v][u] = min(dist[v][u], w); + } + } + + for (int k = 0; k < n; ++k) + if (mask >> k & 1) + for (int i = 0; i < n; ++i) + if (mask >> i & 1) + for (int j = 0; j < n; ++j) + if (mask >> j & 1) + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); + + for (int i = 0; i < n; ++i) + if (mask >> i & 1) + for (int j = i + 1; j < n; ++j) + if (mask >> j & 1) + maxDistance = max(maxDistance, dist[i][j]); + + return maxDistance; + } +}; diff --git a/solutions/2959. Number of Possible Sets of Closing Branches/2959.java b/solutions/2959. Number of Possible Sets of Closing Branches/2959.java new file mode 100644 index 00000000000..d2864ae33ee --- /dev/null +++ b/solutions/2959. Number of Possible Sets of Closing Branches/2959.java @@ -0,0 +1,48 @@ +class Solution { + public int numberOfSets(int n, int maxDistance, int[][] roads) { + final int maxMask = 1 << n; + int ans = 0; + + for (int mask = 0; mask < maxMask; ++mask) + if (floydWarshall(n, maxDistance, roads, mask) <= maxDistance) + ++ans; + + return ans; + } + + private int floydWarshall(int n, int maxDistanceThreshold, int[][] roads, int mask) { + int maxDistance = 0; + int[][] dist = new int[n][n]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, maxDistanceThreshold + 1)); + + for (int i = 0; i < n; ++i) + if ((mask >> i & 1) == 1) + dist[i][i] = 0; + + for (int[] road : roads) { + final int u = road[0]; + final int v = road[1]; + final int w = road[2]; + if ((mask >> u & 1) == 1 && (mask >> v & 1) == 1) { + dist[u][v] = Math.min(dist[u][v], w); + dist[v][u] = Math.min(dist[v][u], w); + } + } + + for (int k = 0; k < n; ++k) + if ((mask >> k & 1) == 1) + for (int i = 0; i < n; ++i) + if ((mask >> i & 1) == 1) + for (int j = 0; j < n; ++j) + if ((mask >> j & 1) == 1) + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + + for (int i = 0; i < n; ++i) + if ((mask >> i & 1) == 1) + for (int j = i + 1; j < n; ++j) + if ((mask >> j & 1) == 1) + maxDistance = Math.max(maxDistance, dist[i][j]); + + return maxDistance; + } +} diff --git a/solutions/2959. Number of Possible Sets of Closing Branches/2959.py b/solutions/2959. Number of Possible Sets of Closing Branches/2959.py new file mode 100644 index 00000000000..50e00d3b04a --- /dev/null +++ b/solutions/2959. Number of Possible Sets of Closing Branches/2959.py @@ -0,0 +1,38 @@ +class Solution: + def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: + return sum(self._floydWarshall(n, maxDistance, roads, mask) <= maxDistance + for mask in range(1 << n)) + + def _floydWarshall(self, n: int, maxDistanceThreshold: int, + roads: List[List[int]], mask: int) -> List[List[int]]: + """ + Returns the maximum distance between any two branches, where the mask + represents the selected branches. + """ + maxDistance = 0 + dist = [[maxDistanceThreshold + 1] * n for _ in range(n)] + + for i in range(n): + if mask >> i & 1: + dist[i][i] = 0 + + for u, v, w in roads: + if mask >> u & 1 and mask >> v & 1: + dist[u][v] = min(dist[u][v], w) + dist[v][u] = min(dist[v][u], w) + + for k in range(n): + if mask >> k & 1: + for i in range(n): + if mask >> i & 1: + for j in range(n): + if mask >> j & 1: + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + + for i in range(n): + if mask >> i & 1: + for j in range(i + 1, n): + if mask >> j & 1: + maxDistance = max(maxDistance, dist[i][j]) + + return maxDistance diff --git a/solutions/296. Best Meeting Point/296.cpp b/solutions/296. Best Meeting Point/296.cpp new file mode 100644 index 00000000000..919bfeedf93 --- /dev/null +++ b/solutions/296. Best Meeting Point/296.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int minTotalDistance(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector I; // i indices s.t. grid[i][j] == 1 + vector J; // j indices s.t. grid[i][j] == 1 + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j]) + I.push_back(i); + + for (int j = 0; j < n; ++j) + for (int i = 0; i < m; ++i) + if (grid[i][j]) + J.push_back(j); + + // sum(i - median(I)) + sum(j - median(J)) + return minTotalDistance(I) + minTotalDistance(J); + } + + private: + int minTotalDistance(const vector& grid) { + int sum = 0; + int i = 0; + int j = grid.size() - 1; + while (i < j) + sum += grid[j--] - grid[i++]; + return sum; + } +}; diff --git a/solutions/296. Best Meeting Point/296.java b/solutions/296. Best Meeting Point/296.java new file mode 100644 index 00000000000..52c408d60fd --- /dev/null +++ b/solutions/296. Best Meeting Point/296.java @@ -0,0 +1,30 @@ +class Solution { + public int minTotalDistance(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + List I = new ArrayList<>(); // i indices s.t. grid[i][j] == 1 + List J = new ArrayList<>(); // j indices s.t. grid[i][j] == 1 + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + I.add(i); + + for (int j = 0; j < n; ++j) + for (int i = 0; i < m; ++i) + if (grid[i][j] == 1) + J.add(j); + + // sum(i - median(I)) + sum(j - median(J)) + return minTotalDistance(I) + minTotalDistance(J); + } + + private int minTotalDistance(List grid) { + int sum = 0; + int i = 0; + int j = grid.size() - 1; + while (i < j) + sum += grid.get(j--) - grid.get(i++); + return sum; + } +} diff --git a/solutions/296. Best Meeting Point/296.py b/solutions/296. Best Meeting Point/296.py new file mode 100644 index 00000000000..e2fd0525cb8 --- /dev/null +++ b/solutions/296. Best Meeting Point/296.py @@ -0,0 +1,21 @@ +class Solution: + def minTotalDistance(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + # i indices s.t. grid[i][j] == 1 + I = [i for i in range(m) for j in range(n) if grid[i][j]] + # j indices s.t. grid[i][j] == 1 + J = [j for j in range(n) for i in range(m) if grid[i][j]] + + def minTotalDistance(grid: List[int]) -> int: + summ = 0 + i = 0 + j = len(grid) - 1 + while i < j: + summ += grid[j] - grid[i] + i += 1 + j -= 1 + return summ + + # sum(i - median(I)) + sum(j - median(J)) + return minTotalDistance(I) + minTotalDistance(J) diff --git a/solutions/2960. Count Tested Devices After Test Operations/2960.cpp b/solutions/2960. Count Tested Devices After Test Operations/2960.cpp new file mode 100644 index 00000000000..cc7adbf1c61 --- /dev/null +++ b/solutions/2960. Count Tested Devices After Test Operations/2960.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int countTestedDevices(vector& batteryPercentages) { + int ans = 0; + + for (const int batteryPercentage : batteryPercentages) + if (batteryPercentage - ans > 0) + ++ans; + + return ans; + } +}; diff --git a/solutions/2960. Count Tested Devices After Test Operations/2960.java b/solutions/2960. Count Tested Devices After Test Operations/2960.java new file mode 100644 index 00000000000..62eedaa9167 --- /dev/null +++ b/solutions/2960. Count Tested Devices After Test Operations/2960.java @@ -0,0 +1,11 @@ +class Solution { + public int countTestedDevices(int[] batteryPercentages) { + int ans = 0; + + for (final int batteryPercentage : batteryPercentages) + if (batteryPercentage - ans > 0) + ++ans; + + return ans; + } +} diff --git a/solutions/2960. Count Tested Devices After Test Operations/2960.py b/solutions/2960. Count Tested Devices After Test Operations/2960.py new file mode 100644 index 00000000000..4791c670b64 --- /dev/null +++ b/solutions/2960. Count Tested Devices After Test Operations/2960.py @@ -0,0 +1,9 @@ +class Solution: + def countTestedDevices(self, batteryPercentages: List[int]) -> int: + ans = 0 + + for batteryPercentage in batteryPercentages: + if batteryPercentage - ans > 0: + ans += 1 + + return ans diff --git a/solutions/2961. Double Modular Exponentiation/2961.cpp b/solutions/2961. Double Modular Exponentiation/2961.cpp new file mode 100644 index 00000000000..f32b7296c0e --- /dev/null +++ b/solutions/2961. Double Modular Exponentiation/2961.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector getGoodIndices(vector>& variables, int target) { + vector ans; + for (int i = 0; i < variables.size(); ++i) { + const int a = variables[i][0]; + const int b = variables[i][1]; + const int c = variables[i][2]; + const int m = variables[i][3]; + if (modPow(modPow(a, b, 10), c, m) == target) + ans.push_back(i); + } + return ans; + } + + private: + long modPow(long x, long n, int mod) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % mod, (n - 1), mod) % mod; + return modPow(x * x % mod, (n / 2), mod) % mod; + } +}; diff --git a/solutions/2961. Double Modular Exponentiation/2961.java b/solutions/2961. Double Modular Exponentiation/2961.java new file mode 100644 index 00000000000..90fec296430 --- /dev/null +++ b/solutions/2961. Double Modular Exponentiation/2961.java @@ -0,0 +1,22 @@ +class Solution { + public List getGoodIndices(int[][] variables, int target) { + List ans = new ArrayList<>(); + for (int i = 0; i < variables.length; ++i) { + final int a = variables[i][0]; + final int b = variables[i][1]; + final int c = variables[i][2]; + final int m = variables[i][3]; + if (modPow(modPow(a, b, 10), c, m) == target) + ans.add(i); + } + return ans; + } + + private long modPow(long x, long n, int mod) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % mod, (n - 1), mod) % mod; + return modPow(x * x % mod, (n / 2), mod) % mod; + } +} diff --git a/solutions/2961. Double Modular Exponentiation/2961.py b/solutions/2961. Double Modular Exponentiation/2961.py new file mode 100644 index 00000000000..3878962e9a7 --- /dev/null +++ b/solutions/2961. Double Modular Exponentiation/2961.py @@ -0,0 +1,4 @@ +class Solution: + def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]: + return [i for i, (a, b, c, m) in enumerate(variables) + if pow(pow(a, b, 10), c, m) == target] diff --git a/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.cpp b/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.cpp new file mode 100644 index 00000000000..975877e83fb --- /dev/null +++ b/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + long long countSubarrays(vector& nums, int k) { + const int maxNum = ranges::max(nums); + long ans = 0; + int count = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (nums[r] == maxNum) + ++count; + // Keep the window to include k - 1 times of the maximum number. + while (count == k) + if (nums[l++] == maxNum) + --count; + // If l > 0, nums[l..r] has k - 1 times of the maximum number. For any + // subarray nums[i..r], where i < l, it will have at least k times of the + // maximum number, since nums[l - 1] equals the maximum number. + ans += l; + } + + return ans; + } +}; diff --git a/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.java b/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.java new file mode 100644 index 00000000000..90d4490c24b --- /dev/null +++ b/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.java @@ -0,0 +1,22 @@ +class Solution { + public long countSubarrays(int[] nums, int k) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + long ans = 0; + int count = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (nums[r] == maxNum) + ++count; + // Keep the window to include k - 1 times of the maximum number. + while (count == k) + if (nums[l++] == maxNum) + --count; + // If l > 0, nums[l..r] has k - 1 times of the maximum number. For any + // subarray nums[i..r], where i < l, it will have at least k times of the + // maximum number, since nums[l - 1] equals the maximum number. + ans += l; + } + + return ans; + } +} diff --git a/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.py b/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.py new file mode 100644 index 00000000000..04ee1730912 --- /dev/null +++ b/solutions/2962. Count Subarrays Where Max Element Appears at Least K Times/2962.py @@ -0,0 +1,21 @@ +class Solution: + def countSubarrays(self, nums: List[int], k: int) -> int: + maxNum = max(nums) + ans = 0 + count = 0 + + l = 0 + for r, num in enumerate(nums): + if num == maxNum: + count += 1 + # Keep the window to include k - 1 times of the maxNummum number. + while count == k: + if nums[l] == maxNum: + count -= 1 + l += 1 + # If l > 0, nums[l:r+1] has k - 1 times of the maxNummum number. For any + # subarray nums[i:r+1], where i < l, it will have at least k times of the + # maxNummum number, since nums[l - 1] equals the maxNummum number. + ans += l + + return ans diff --git a/solutions/2963. Count the Number of Good Partitions/2963.cpp b/solutions/2963. Count the Number of Good Partitions/2963.cpp new file mode 100644 index 00000000000..fe1ce4c6b0c --- /dev/null +++ b/solutions/2963. Count the Number of Good Partitions/2963.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int numberOfGoodPartitions(vector& nums) { + constexpr int kMod = 1'000'000'007; + int ans = 1; + // lastSeen[num] := the index of the last time `num` appeared + unordered_map lastSeen; + + for (int i = 0; i < nums.size(); ++i) + lastSeen[nums[i]] = i; + + // Track the maximum right index of each running partition by ensuring that + // the first and last occurrences of a number fall within the same + // partition. + int maxRight = 0; + for (int i = 0; i < nums.size(); ++i) { + if (i > maxRight) + // Start a new partition that starts from nums[i]. + // Each partition doubles the total number of good partitions. + ans = (ans * 2L) % kMod; + maxRight = max(maxRight, lastSeen[nums[i]]); + } + + return ans; + } +}; diff --git a/solutions/2963. Count the Number of Good Partitions/2963.java b/solutions/2963. Count the Number of Good Partitions/2963.java new file mode 100644 index 00000000000..557b2552c42 --- /dev/null +++ b/solutions/2963. Count the Number of Good Partitions/2963.java @@ -0,0 +1,26 @@ +class Solution { + public int numberOfGoodPartitions(int[] nums) { + final int kMod = 1_000_000_007; + int ans = 1; + + // lastSeen[num] := the index of the last time `num` appeared + HashMap lastSeen = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) + lastSeen.put(nums[i], i); + + // Track the maximum right index of each running partition by ensuring that + // the first and last occurrences of a number fall within the same + // partition. + int maxRight = 0; + for (int i = 0; i < nums.length; ++i) { + if (i > maxRight) + // Start a new partition that starts from nums[i]. + // Each partition doubles the total number of good partitions. + ans = (int) ((ans * 2L) % kMod); + maxRight = Math.max(maxRight, lastSeen.get(nums[i])); + } + + return ans; + } +} diff --git a/solutions/2963. Count the Number of Good Partitions/2963.py b/solutions/2963. Count the Number of Good Partitions/2963.py new file mode 100644 index 00000000000..ebca68f0104 --- /dev/null +++ b/solutions/2963. Count the Number of Good Partitions/2963.py @@ -0,0 +1,21 @@ +class Solution: + def numberOfGoodPartitions(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + ans = 1 + # lastSeen[num] := the index of the last time `num` appeared + lastSeen = {} + + for i, num in enumerate(nums): + lastSeen[num] = i + + # Track the maximum right index of each running partition by ensuring that + # the first and last occurrences of a number fall within the same partition. + maxRight = 0 + for i, num in enumerate(nums): + if i > maxRight: + # Start a new partition that starts from nums[i]. + # Each partition doubles the total number of good partitions. + ans = ans * 2 % kMod + maxRight = max(maxRight, lastSeen[num]) + + return ans diff --git a/solutions/2964. Number of Divisible Triplet Sums/2964.cpp b/solutions/2964. Number of Divisible Triplet Sums/2964.cpp new file mode 100644 index 00000000000..22a33d79d93 --- /dev/null +++ b/solutions/2964. Number of Divisible Triplet Sums/2964.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + // Similar to 1995. Count Special Quadruplets + int divisibleTripletCount(vector& nums, int d) { + int ans = 0; + unordered_map count; + + for (int j = nums.size() - 1; j > 0; --j) { // 'j' also represents k. + for (int i = j - 1; i >= 0; --i) + ans += count[(-(nums[i] + nums[j]) % d + d) % d]; + ++count[nums[j] % d]; // j := k + } + + return ans; + } +}; diff --git a/solutions/2964. Number of Divisible Triplet Sums/2964.java b/solutions/2964. Number of Divisible Triplet Sums/2964.java new file mode 100644 index 00000000000..3694aaed3a4 --- /dev/null +++ b/solutions/2964. Number of Divisible Triplet Sums/2964.java @@ -0,0 +1,15 @@ +class Solution { + // Similar to 1995. Count Special Quadruplets + public int divisibleTripletCount(int[] nums, int d) { + int ans = 0; + Map count = new HashMap<>(); + + for (int j = nums.length - 1; j > 0; --j) { // 'j' also represents k. + for (int i = j - 1; i >= 0; --i) + ans += count.getOrDefault((-(nums[i] + nums[j]) % d + d) % d, 0); + count.merge(nums[j] % d, 1, Integer::sum); // j := k + } + + return ans; + } +} diff --git a/solutions/2964. Number of Divisible Triplet Sums/2964.py b/solutions/2964. Number of Divisible Triplet Sums/2964.py new file mode 100644 index 00000000000..cb613d23935 --- /dev/null +++ b/solutions/2964. Number of Divisible Triplet Sums/2964.py @@ -0,0 +1,12 @@ +class Solution: + # Similar to 1995. Count Special Quadruplets + def divisibleTripletCount(self, nums: List[int], d: int) -> int: + ans = 0 + count = collections.Counter() + + for j in range(len(nums) - 1, 0, -1): # `j` also represents k. + for i in range(j - 1, -1, -1): + ans += count[-(nums[i] + nums[j]) % d] + count[nums[j] % d] += 1 # j := k + + return ans diff --git a/solutions/2965. Find Missing and Repeated Values/2965.cpp b/solutions/2965. Find Missing and Repeated Values/2965.cpp new file mode 100644 index 00000000000..4a8973a361f --- /dev/null +++ b/solutions/2965. Find Missing and Repeated Values/2965.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector findMissingAndRepeatedValues(vector>& grid) { + const int n = grid.size(); + const int nSquared = n * n; + vector count(nSquared + 1); + + for (const vector& row : grid) + for (const int num : row) + ++count[num]; + + int repeated = -1; + int missing = -1; + + for (int i = 1; i <= nSquared; ++i) { + if (count[i] == 2) + repeated = i; + if (count[i] == 0) + missing = i; + } + + return {repeated, missing}; + } +}; diff --git a/solutions/2965. Find Missing and Repeated Values/2965.java b/solutions/2965. Find Missing and Repeated Values/2965.java new file mode 100644 index 00000000000..e882d9bb636 --- /dev/null +++ b/solutions/2965. Find Missing and Repeated Values/2965.java @@ -0,0 +1,23 @@ +class Solution { + public int[] findMissingAndRepeatedValues(int[][] grid) { + final int n = grid.length; + final int nSquared = n * n; + int[] count = new int[nSquared + 1]; + + for (int[] row : grid) + for (final int num : row) + ++count[num]; + + int repeated = -1; + int missing = -1; + + for (int i = 1; i <= nSquared; ++i) { + if (count[i] == 2) + repeated = i; + if (count[i] == 0) + missing = i; + } + + return new int[] {repeated, missing}; + } +} diff --git a/solutions/2965. Find Missing and Repeated Values/2965.py b/solutions/2965. Find Missing and Repeated Values/2965.py new file mode 100644 index 00000000000..a46daed276a --- /dev/null +++ b/solutions/2965. Find Missing and Repeated Values/2965.py @@ -0,0 +1,9 @@ +class Solution: + def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]: + count = [1] + [0] * len(grid)**2 # padding for 1-indexed + + for row in grid: + for num in row: + count[num] += 1 + + return [count.index(2), count.index(0)] diff --git a/solutions/2966. Divide Array Into Arrays With Max Difference/2966.cpp b/solutions/2966. Divide Array Into Arrays With Max Difference/2966.cpp new file mode 100644 index 00000000000..757e98666b6 --- /dev/null +++ b/solutions/2966. Divide Array Into Arrays With Max Difference/2966.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector> divideArray(vector& nums, int k) { + vector> ans; + + ranges::sort(nums); + + for (int i = 2; i < nums.size(); i += 3) { + if (nums[i] - nums[i - 2] > k) + return {}; + ans.push_back({nums[i - 2], nums[i - 1], nums[i]}); + } + + return ans; + } +}; diff --git a/solutions/2966. Divide Array Into Arrays With Max Difference/2966.java b/solutions/2966. Divide Array Into Arrays With Max Difference/2966.java new file mode 100644 index 00000000000..e7c08dd897b --- /dev/null +++ b/solutions/2966. Divide Array Into Arrays With Max Difference/2966.java @@ -0,0 +1,15 @@ +class Solution { + public int[][] divideArray(int[] nums, int k) { + int[][] ans = new int[nums.length / 3][3]; + + Arrays.sort(nums); + + for (int i = 2; i < nums.length; i += 3) { + if (nums[i] - nums[i - 2] > k) + return new int[0][]; + ans[i / 3] = new int[] {nums[i - 2], nums[i - 1], nums[i]}; + } + + return ans; + } +} diff --git a/solutions/2966. Divide Array Into Arrays With Max Difference/2966.py b/solutions/2966. Divide Array Into Arrays With Max Difference/2966.py new file mode 100644 index 00000000000..23d83872818 --- /dev/null +++ b/solutions/2966. Divide Array Into Arrays With Max Difference/2966.py @@ -0,0 +1,12 @@ +class Solution: + def divideArray(self, nums: List[int], k: int) -> List[List[int]]: + ans = [] + + nums.sort() + + for i in range(2, len(nums), 3): + if nums[i] - nums[i - 2] > k: + return [] + ans.append([nums[i - 2], nums[i - 1], nums[i]]) + + return ans diff --git a/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.cpp b/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.cpp new file mode 100644 index 00000000000..d596dd7438c --- /dev/null +++ b/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + long long minimumCost(vector& nums) { + ranges::sort(nums); + const int median = nums[nums.size() / 2]; + const int nextPalindrome = getPalindrome(median, /*delta=*/1); + const int prevPalindrome = getPalindrome(median, /*delta=*/-1); + return min(cost(nums, nextPalindrome), cost(nums, prevPalindrome)); + } + + private: + // Returns the cost to change all the numbers to `palindrome`. + long cost(const vector& nums, int palindrome) { + return accumulate(nums.begin(), nums.end(), 0L, + [palindrome](long subtotal, int num) { + return subtotal + abs(palindrome - num); + }); + } + + // Returns the palindrome `p`, where p = num + a * delta and a > 0. + int getPalindrome(int num, int delta) { + while (!isPalindrome(num)) + num += delta; + return num; + } + + bool isPalindrome(int num) { + const string original = to_string(num); + const string reversed = {original.rbegin(), original.rend()}; + return original == reversed; + } +}; diff --git a/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.java b/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.java new file mode 100644 index 00000000000..da80e4cd209 --- /dev/null +++ b/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.java @@ -0,0 +1,27 @@ +class Solution { + public long minimumCost(int[] nums) { + Arrays.sort(nums); + final int median = nums[nums.length / 2]; + final int nextPalindrome = getPalindrome(median, 1); + final int prevPalindrome = getPalindrome(median, -1); + return Math.min(cost(nums, nextPalindrome), cost(nums, prevPalindrome)); + } + + // Returns the cost to change all the numbers to `palindrome`. + private long cost(int[] nums, int palindrome) { + return Arrays.stream(nums).mapToLong(num -> Math.abs(palindrome - num)).sum(); + } + + // Returns the palindrome `p`, where p = num + a * delta and a > 0. + private int getPalindrome(int num, int delta) { + while (!isPalindrome(num)) + num += delta; + return num; + } + + private boolean isPalindrome(int num) { + final String original = Integer.toString(num); + final String reversed = new StringBuilder(original).reverse().toString(); + return original.equals(reversed); + } +} diff --git a/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.py b/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.py new file mode 100644 index 00000000000..2c96b466302 --- /dev/null +++ b/solutions/2967. Minimum Cost to Make Array Equalindromic/2967.py @@ -0,0 +1,22 @@ +class Solution: + def minimumCost(self, nums: List[int]) -> int: + nums.sort() + median = nums[len(nums) // 2] + nextPalindrome = self._getPalindrome(median, delta=1) + prevPalindrome = self._getPalindrome(median, delta=-1) + return min(self._cost(nums, nextPalindrome), + self._cost(nums, prevPalindrome)) + + def _cost(self, nums: List[int], palindrome: int) -> int: + """Returns the cost to change all the numbers to `palindrome`.""" + return sum(abs(palindrome - num) for num in nums) + + def _getPalindrome(self, num: int, delta: int) -> int: + """Returns the palindrome `p`, where p = num + a * delta and a > 0.""" + while not self._isPalindrome(num): + num += delta + return num + + def _isPalindrome(self, num: int) -> int: + original = str(num) + return original == original[::-1] diff --git a/solutions/2968. Apply Operations to Maximize Frequency Score/2968.cpp b/solutions/2968. Apply Operations to Maximize Frequency Score/2968.cpp new file mode 100644 index 00000000000..b5634f67a40 --- /dev/null +++ b/solutions/2968. Apply Operations to Maximize Frequency Score/2968.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxFrequencyScore(vector& nums, long long k) { + int ans = 0; + long cost = 0; + + ranges::sort(nums); + + for (int l = 0, r = 0; r < nums.size(); ++r) { + cost += nums[r] - nums[(l + r) / 2]; + while (cost > k) + cost -= nums[(l + r + 1) / 2] - nums[l++]; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/2968. Apply Operations to Maximize Frequency Score/2968.java b/solutions/2968. Apply Operations to Maximize Frequency Score/2968.java new file mode 100644 index 00000000000..471eaa5d214 --- /dev/null +++ b/solutions/2968. Apply Operations to Maximize Frequency Score/2968.java @@ -0,0 +1,19 @@ +class Solution { + public int maxFrequencyScore(int[] nums, long k) { + int ans = 0; + long cost = 0; + + Arrays.sort(nums); + + // For a window [l, r], the best choice to make the numbers in the range + // equal is to make them all equal to the median in this range. + for (int l = 0, r = 0; r < nums.length; ++r) { + cost += nums[r] - nums[(l + r) / 2]; + while (cost > k) + cost -= nums[(l + r + 1) / 2] - nums[l++]; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/2968. Apply Operations to Maximize Frequency Score/2968.py b/solutions/2968. Apply Operations to Maximize Frequency Score/2968.py new file mode 100644 index 00000000000..747000a76a2 --- /dev/null +++ b/solutions/2968. Apply Operations to Maximize Frequency Score/2968.py @@ -0,0 +1,15 @@ +class Solution: + def maxFrequencyScore(self, nums: List[int], k: int) -> int: + nums.sort() + ans = 0 + cost = 0 + + l = 0 + for r, num in enumerate(nums): + cost += num - nums[(l + r) // 2] + while cost > k: + cost -= nums[(l + r + 1) // 2] - nums[l] + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.cpp b/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.cpp new file mode 100644 index 00000000000..75c48acb552 --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + // Same as 2944. Minimum Number of Coins for Fruits + int minimumCoins(vector& prices) { + const int n = prices.size(); + int ans = 0; + using P = pair; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed). + priority_queue, greater<>> minHeap; + minHeap.emplace(0, n); + + for (int i = n - 1; i >= 0; --i) { + while (!minHeap.empty() && minHeap.top().second > (i + 1) * 2) + minHeap.pop(); + ans = prices[i] + minHeap.top().first; + minHeap.emplace(ans, i); + } + + return ans; + } +}; diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.java b/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.java new file mode 100644 index 00000000000..b51ee80c14c --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.java @@ -0,0 +1,20 @@ +class Solution { + // Same as 2944. Minimum Number of Coins for Fruits + public int minimumCoins(int[] prices) { + final int n = prices.length; + int ans = 0; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed). + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + minHeap.offer(new Pair<>(0, n)); + + for (int i = n - 1; i >= 0; --i) { + while (!minHeap.isEmpty() && minHeap.peek().getValue() > (i + 1) * 2) + minHeap.poll(); + ans = prices[i] + minHeap.peek().getKey(); + minHeap.offer(new Pair<>(ans, i)); + } + + return ans; + } +} diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.py b/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.py new file mode 100644 index 00000000000..37ed472e77a --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969-2.py @@ -0,0 +1,16 @@ +class Solution: + # Same as 2944. Minimum Number of Coins for Fruits + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + # Stores (dp[i], i), where dp[i] is the minimum number of coins to acquire + # fruits[i:] (0-indexed). + minHeap = [(0, n)] + ans = 0 + + for i in range(n - 1, -1, -1): + while minHeap and minHeap[0][1] > (i + 1) * 2: + heapq.heappop(minHeap) + ans = prices[i] + minHeap[0][0] + heapq.heappush(minHeap, (ans, i)) + + return ans diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.cpp b/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.cpp new file mode 100644 index 00000000000..534421b27f9 --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + // Same as 2944. Minimum Number of Coins for Fruits + int minimumCoins(vector& prices) { + const int n = prices.size(); + int ans = INT_MAX; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed) in ascending order. + deque> minQ{{0, n}}; + + for (int i = n - 1; i >= 0; --i) { + while (!minQ.empty() && minQ.front().second > (i + 1) * 2) + minQ.pop_front(); + ans = prices[i] + minQ.front().first; + while (!minQ.empty() && minQ.back().first >= ans) + minQ.pop_back(); + minQ.emplace_back(ans, i); + } + + return ans; + } +}; diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.java b/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.java new file mode 100644 index 00000000000..18e3cc55f8c --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.java @@ -0,0 +1,22 @@ +class Solution { + // Same as 2944. Minimum Number of Coins for Fruits + public int minimumCoins(int[] prices) { + final int n = prices.length; + int ans = Integer.MAX_VALUE; + // Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + // fruits[i:] (0-indexed) in ascending order. + Deque> minQ = new ArrayDeque<>(); + minQ.offerFirst(new Pair<>(0, n)); + + for (int i = n - 1; i >= 0; --i) { + while (!minQ.isEmpty() && minQ.peekFirst().getValue() > (i + 1) * 2) + minQ.pollFirst(); + ans = prices[i] + minQ.peekFirst().getKey(); + while (!minQ.isEmpty() && minQ.peekLast().getKey() >= ans) + minQ.pollLast(); + minQ.offerLast(new Pair<>(ans, i)); + } + + return ans; + } +} diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.py b/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.py new file mode 100644 index 00000000000..2b62821d39b --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969-3.py @@ -0,0 +1,18 @@ +class Solution: + # Same as 2944. Minimum Number of Coins for Fruits + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + ans = math.inf + # Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire + # fruits[i:] (0-indexed) in ascending order. + minQ = collections.deque([(0, n)]) + + for i in range(n - 1, -1, -1): + while minQ and minQ[0][1] > (i + 1) * 2: + minQ.popleft() + ans = prices[i] + minQ[0][0] + while minQ and minQ[-1][0] >= ans: + minQ.pop() + minQ.append((ans, i)) + + return ans diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969.cpp b/solutions/2969. Minimum Number of Coins for Fruits II/2969.cpp new file mode 100644 index 00000000000..8aa0be5b738 --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + // Same as 2944. Minimum Number of Coins for Fruits + int minimumCoins(vector& prices) { + const int n = prices.size(); + vector dp(n + 1, INT_MAX); + dp[n] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j <= min((i + 1) * 2, n); ++j) + dp[i] = min(dp[i], prices[i] + dp[j]); + + return dp[0]; + } +}; diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969.java b/solutions/2969. Minimum Number of Coins for Fruits II/2969.java new file mode 100644 index 00000000000..0a49e7c890f --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969.java @@ -0,0 +1,15 @@ +class Solution { + // Same as 2944. Minimum Number of Coins for Fruits + public int minimumCoins(int[] prices) { + final int n = prices.length; + int[] dp = new int[n + 1]; + Arrays.fill(dp, Integer.MAX_VALUE); + dp[n] = 0; + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j <= Math.min((i + 1) * 2, n); ++j) + dp[i] = Math.min(dp[i], prices[i] + dp[j]); + + return dp[0]; + } +} diff --git a/solutions/2969. Minimum Number of Coins for Fruits II/2969.py b/solutions/2969. Minimum Number of Coins for Fruits II/2969.py new file mode 100644 index 00000000000..cc94cc15c7d --- /dev/null +++ b/solutions/2969. Minimum Number of Coins for Fruits II/2969.py @@ -0,0 +1,14 @@ +class Solution: + # Same as 2944. Minimum Number of Coins for Fruits + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + # Convert to 0-indexed for easy computation. + # dp[i] := the minimum number of coins to acquire fruits[i:] + dp = [math.inf] * n + [0] + + for i in range(n - 1, -1, -1): + # Convert back to 1-indexed. + for j in range(i + 1, min((i + 1) * 2 + 1, n + 1)): + dp[i] = min(dp[i], prices[i] + dp[j]) + + return dp[0] diff --git a/solutions/297. Serialize and Deserialize Binary Tree/297-2.cpp b/solutions/297. Serialize and Deserialize Binary Tree/297-2.cpp new file mode 100644 index 00000000000..6c36dff0f01 --- /dev/null +++ b/solutions/297. Serialize and Deserialize Binary Tree/297-2.cpp @@ -0,0 +1,44 @@ +class Codec { + public: + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + string s; + preorder(root, s); + return s; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + istringstream iss(data); + queue q; + + for (string s; iss >> s;) + q.push(s); + + return preorder(q); + } + + private: + void preorder(TreeNode* root, string& s) { + if (root == nullptr) { + s += "n "; + return; + } + + s += to_string(root->val) + " "; + preorder(root->left, s); + preorder(root->right, s); + } + + TreeNode* preorder(queue& q) { + const string s = q.front(); + q.pop(); + if (s == "n") + return nullptr; + + TreeNode* root = new TreeNode(stoi(s)); + root->left = preorder(q); + root->right = preorder(q); + return root; + } +}; diff --git a/solutions/297. Serialize and Deserialize Binary Tree/297-2.java b/solutions/297. Serialize and Deserialize Binary Tree/297-2.java new file mode 100644 index 00000000000..5fbdb49aef7 --- /dev/null +++ b/solutions/297. Serialize and Deserialize Binary Tree/297-2.java @@ -0,0 +1,37 @@ +public class Codec { + // Encodes a tree to a single string. + public String serialize(TreeNode root) { + StringBuilder sb = new StringBuilder(); + preorder(root, sb); + return sb.toString(); + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + final String[] vals = data.split(" "); + Queue q = new ArrayDeque<>(Arrays.asList(vals)); + return preorder(q); + } + + private void preorder(TreeNode root, StringBuilder sb) { + if (root == null) { + sb.append("n "); + return; + } + + sb.append(root.val).append(" "); + preorder(root.left, sb); + preorder(root.right, sb); + } + + private TreeNode preorder(Queue q) { + final String s = q.poll(); + if (s.equals("n")) + return null; + + TreeNode root = new TreeNode(Integer.parseInt(s)); + root.left = preorder(q); + root.right = preorder(q); + return root; + } +} diff --git a/solutions/297. Serialize and Deserialize Binary Tree/297-2.py b/solutions/297. Serialize and Deserialize Binary Tree/297-2.py new file mode 100644 index 00000000000..e92c7764aa1 --- /dev/null +++ b/solutions/297. Serialize and Deserialize Binary Tree/297-2.py @@ -0,0 +1,32 @@ +class Codec: + def serialize(self, root: 'TreeNode') -> str: + """Encodes a tree to a single string.""" + s = [] + + def preorder(root: 'TreeNode') -> None: + if not root: + s.append('n') + return + + s.append(str(root.val)) + preorder(root.left) + preorder(root.right) + + preorder(root) + return ' '.join(s) + + def deserialize(self, data: str) -> 'TreeNode': + """Decodes your encoded data to tree.""" + q = collections.deque(data.split()) + + def preorder() -> 'TreeNode': + s = q.popleft() + if s == 'n': + return None + + root = TreeNode(s) + root.left = preorder() + root.right = preorder() + return root + + return preorder() diff --git a/solutions/297. Serialize and Deserialize Binary Tree/297.cpp b/solutions/297. Serialize and Deserialize Binary Tree/297.cpp new file mode 100644 index 00000000000..3f5c7233597 --- /dev/null +++ b/solutions/297. Serialize and Deserialize Binary Tree/297.cpp @@ -0,0 +1,53 @@ +class Codec { + public: + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (root == nullptr) + return ""; + + string s; + queue q{{root}}; + + while (!q.empty()) { + TreeNode* node = q.front(); + q.pop(); + if (node != nullptr) { + s += to_string(node->val) + " "; + q.push(node->left); + q.push(node->right); + } else { + s += "n "; + } + } + + return s; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + if (data.empty()) + return nullptr; + + istringstream iss(data); + string word; + iss >> word; + TreeNode* root = new TreeNode(stoi(word)); + queue q{{root}}; + + while (iss >> word) { + TreeNode* node = q.front(); + q.pop(); + if (word != "n") { + node->left = new TreeNode(stoi(word)); + q.push(node->left); + } + iss >> word; + if (word != "n") { + node->right = new TreeNode(stoi(word)); + q.push(node->right); + } + } + + return root; + } +}; diff --git a/solutions/297. Serialize and Deserialize Binary Tree/297.java b/solutions/297. Serialize and Deserialize Binary Tree/297.java new file mode 100644 index 00000000000..45093c62fe7 --- /dev/null +++ b/solutions/297. Serialize and Deserialize Binary Tree/297.java @@ -0,0 +1,47 @@ +public class Codec { + // Encodes a tree to a single string. + public String serialize(TreeNode root) { + if (root == null) + return ""; + + StringBuilder sb = new StringBuilder(); + Queue q = new LinkedList<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + TreeNode node = q.poll(); + if (node == null) { + sb.append("n "); + } else { + sb.append(node.val).append(" "); + q.offer(node.left); + q.offer(node.right); + } + } + + return sb.toString(); + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + if (data.equals("")) + return null; + + final String[] vals = data.split(" "); + TreeNode root = new TreeNode(Integer.parseInt(vals[0])); + Queue q = new LinkedList<>(Arrays.asList(root)); + + for (int i = 1; i < vals.length; i += 2) { + TreeNode node = q.poll(); + if (!vals[i].equals("n")) { + node.left = new TreeNode(Integer.parseInt(vals[i])); + q.offer(node.left); + } + if (!vals[i + 1].equals("n")) { + node.right = new TreeNode(Integer.parseInt(vals[i + 1])); + q.offer(node.right); + } + } + + return root; + } +} diff --git a/solutions/297. Serialize and Deserialize Binary Tree/297.py b/solutions/297. Serialize and Deserialize Binary Tree/297.py new file mode 100644 index 00000000000..8e262ac2c3a --- /dev/null +++ b/solutions/297. Serialize and Deserialize Binary Tree/297.py @@ -0,0 +1,39 @@ +class Codec: + def serialize(self, root: 'TreeNode') -> str: + """Encodes a tree to a single string.""" + if not root: + return '' + + s = '' + q = collections.deque([root]) + + while q: + node = q.popleft() + if node: + s += str(node.val) + ' ' + q.append(node.left) + q.append(node.right) + else: + s += 'n ' + + return s + + def deserialize(self, data: str) -> 'TreeNode': + """Decodes your encoded data to tree.""" + if not data: + return None + + vals = data.split() + root = TreeNode(vals[0]) + q = collections.deque([root]) + + for i in range(1, len(vals), 2): + node = q.popleft() + if vals[i] != 'n': + node.left = TreeNode(vals[i]) + q.append(node.left) + if vals[i + 1] != 'n': + node.right = TreeNode(vals[i + 1]) + q.append(node.right) + + return root diff --git a/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.cpp b/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.cpp new file mode 100644 index 00000000000..26197ed0677 --- /dev/null +++ b/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int incremovableSubarrayCount(vector& nums) { + const int n = nums.size(); + const int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return n * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + int ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0, j = startIndex; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, move j to the place such that + // nums[j] > nums[i]. The valid removals will then be nums[i + 1..j - 1], + // nums[i + 1..j], ..., nums[i + 1..n). + while (j < n && nums[i] >= nums[j]) + ++j; + ans += n - j + 1; + } + + return ans; + } + + private: + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + int getStartIndexOfSuffix(const vector& nums) { + for (int i = nums.size() - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } +}; diff --git a/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.java b/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.java new file mode 100644 index 00000000000..2baf0c3254c --- /dev/null +++ b/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.java @@ -0,0 +1,42 @@ +class Solution { + public int incremovableSubarrayCount(int[] nums) { + final int n = nums.length; + final int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return n * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + int ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0, j = startIndex; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, move j to the place such that + // nums[j] > nums[i]. The valid removals will then be nums[i + 1..j - 1], + // nums[i + 1..j], ..., nums[i + 1..n). + while (j < n && nums[i] >= nums[j]) + ++j; + ans += n - j + 1; + } + + return ans; + } + + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + private int getStartIndexOfSuffix(int[] nums) { + for (int i = nums.length - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } + + private int firstGreater(int[] A, int startIndex, int target) { + final int i = Arrays.binarySearch(A, startIndex, A.length, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.py b/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.py new file mode 100644 index 00000000000..f7ed01ae480 --- /dev/null +++ b/solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.py @@ -0,0 +1,32 @@ +class Solution: + def incremovableSubarrayCount(self, nums: List[int]) -> int: + n = len(nums) + startIndex = self._getStartIndexOfSuffix(nums) + # If the complete array is strictly increasing, the total number of ways we + # can remove elements equals the total number of possible subarrays. + if startIndex == 0: + return n * (n + 1) // 2 + + # The valid removals starting from nums[0] include nums[0..startIndex - 1], + # nums[0..startIndex], ..., nums[0..n). + ans = n - startIndex + 1 + + # Enumerate each prefix subarray that is strictly increasing. + j = startIndex + for i in range(startIndex): + if i > 0 and nums[i] <= nums[i - 1]: + break + # Since nums[0..i] is strictly increasing, move j to the place such that + # nums[j] > nums[i]. The valid removals will then be nums[i + 1..j - 1], + # nums[i + 1..j], ..., nums[i + 1..n). + while j < n and nums[i] >= nums[j]: + j += 1 + ans += n - j + 1 + + return ans + + def _getStartIndexOfSuffix(self, nums: List[int]) -> int: + for i in range(len(nums) - 2, -1, -1): + if nums[i] >= nums[i + 1]: + return i + 1 + return 0 diff --git a/solutions/2970. Count the Number of Incremovable Subarrays I/2970.cpp b/solutions/2970. Count the Number of Incremovable Subarrays I/2970.cpp new file mode 100644 index 00000000000..05b463b0189 --- /dev/null +++ b/solutions/2970. Count the Number of Incremovable Subarrays I/2970.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int incremovableSubarrayCount(vector& nums) { + const int n = nums.size(); + const int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return n * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + int ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, find the first index j in + // nums[startIndex..n) such that nums[j] > nums[i]. The valid removals + // will then be nums[i + 1..j - 1], nums[i + 1..j], ..., nums[i + 1..n). + ans += nums.end() - + upper_bound(nums.begin() + startIndex, nums.end(), nums[i]) + 1; + } + + return ans; + } + + private: + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + int getStartIndexOfSuffix(const vector& nums) { + for (int i = nums.size() - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } +}; diff --git a/solutions/2970. Count the Number of Incremovable Subarrays I/2970.java b/solutions/2970. Count the Number of Incremovable Subarrays I/2970.java new file mode 100644 index 00000000000..1998ea82f46 --- /dev/null +++ b/solutions/2970. Count the Number of Incremovable Subarrays I/2970.java @@ -0,0 +1,40 @@ +class Solution { + public int incremovableSubarrayCount(int[] nums) { + final int n = nums.length; + final int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return n * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + int ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, find the first index j in + // nums[startIndex..n) such that nums[j] > nums[i]. The valid removals + // will then be nums[i + 1..j - 1], nums[i + 1..j], ..., nums[i + 1..n). + ans += n - firstGreater(nums, startIndex, nums[i]) + 1; + } + + return ans; + } + + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + private int getStartIndexOfSuffix(int[] nums) { + for (int i = nums.length - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } + + private int firstGreater(int[] A, int startIndex, int target) { + final int i = Arrays.binarySearch(A, startIndex, A.length, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2970. Count the Number of Incremovable Subarrays I/2970.py b/solutions/2970. Count the Number of Incremovable Subarrays I/2970.py new file mode 100644 index 00000000000..7d7bb206de7 --- /dev/null +++ b/solutions/2970. Count the Number of Incremovable Subarrays I/2970.py @@ -0,0 +1,29 @@ +class Solution: + def incremovableSubarrayCount(self, nums: List[int]) -> int: + n = len(nums) + startIndex = self._getStartIndexOfSuffix(nums) + # If the complete array is strictly increasing, the total number of ways we + # can remove elements equals the total number of possible subarrays. + if startIndex == 0: + return n * (n + 1) // 2 + + # The valid removals starting from nums[0] include nums[0..startIndex - 1], + # nums[0..startIndex], ..., nums[0..n). + ans = n - startIndex + 1 + + # Enumerate each prefix subarray that is strictly increasing. + for i in range(startIndex): + if i > 0 and nums[i] <= nums[i - 1]: + break + # Since nums[0..i] is strictly increasing, find the first index j in + # nums[startIndex..n) such that nums[j] > nums[i]. The valid removals + # will then be nums[i + 1..j - 1], nums[i + 1..j], ..., nums[i + 1..n). + ans += n - bisect.bisect_right(nums, nums[i], startIndex) + 1 + + return ans + + def _getStartIndexOfSuffix(self, nums: List[int]) -> int: + for i in range(len(nums) - 2, -1, -1): + if nums[i] >= nums[i + 1]: + return i + 1 + return 0 diff --git a/solutions/2971. Find Polygon With the Largest Perimeter/2971.cpp b/solutions/2971. Find Polygon With the Largest Perimeter/2971.cpp new file mode 100644 index 00000000000..3bd890abda3 --- /dev/null +++ b/solutions/2971. Find Polygon With the Largest Perimeter/2971.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long long largestPerimeter(vector& nums) { + long prefix = accumulate(nums.begin(), nums.end(), 0L); + + ranges::sort(nums); + + for (int i = nums.size() - 1; i >= 2; --i) { + prefix -= nums[i]; + // Let nums[i] be the longest side. Check if the sum of all the edges with + // length no longer than nums[i] > nums[i]. + if (prefix > nums[i]) + return prefix + nums[i]; + } + + return -1; + } +}; diff --git a/solutions/2971. Find Polygon With the Largest Perimeter/2971.java b/solutions/2971. Find Polygon With the Largest Perimeter/2971.java new file mode 100644 index 00000000000..91009cb6c1f --- /dev/null +++ b/solutions/2971. Find Polygon With the Largest Perimeter/2971.java @@ -0,0 +1,17 @@ +class Solution { + public long largestPerimeter(int[] nums) { + long prefix = Arrays.stream(nums).asLongStream().sum(); + + Arrays.sort(nums); + + for (int i = nums.length - 1; i >= 2; --i) { + prefix -= nums[i]; + // Let nums[i] be the longest side. Check if the sum of all the edges with + // length no longer than nums[i] > nums[i]. + if (prefix > nums[i]) + return prefix + nums[i]; + } + + return -1; + } +} diff --git a/solutions/2971. Find Polygon With the Largest Perimeter/2971.py b/solutions/2971. Find Polygon With the Largest Perimeter/2971.py new file mode 100644 index 00000000000..20b261d0f2a --- /dev/null +++ b/solutions/2971. Find Polygon With the Largest Perimeter/2971.py @@ -0,0 +1,12 @@ +class Solution: + def largestPerimeter(self, nums: List[int]) -> int: + prefix = sum(nums) + + for num in sorted(nums, reverse=True): + prefix -= num + # Let `num` be the longest side. Check if the sum of all the edges with + # length no longer than `num` > `num``. + if prefix > num: + return prefix + num + + return -1 diff --git a/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.cpp b/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.cpp new file mode 100644 index 00000000000..052833ef0c4 --- /dev/null +++ b/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + // Same as 2970. Count the Number of Incremovable Subarrays I + long long incremovableSubarrayCount(vector& nums) { + const int n = nums.size(); + const int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return static_cast(n) * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + long ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0, j = startIndex; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, move j to the place such that + // nums[j] > nums[i]. The valid removals will then be nums[i + 1..j - 1], + // nums[i + 1..j], ..., nums[i + 1..n). + while (j < n && nums[i] >= nums[j]) + ++j; + ans += n - j + 1; + } + + return ans; + } + + private: + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + int getStartIndexOfSuffix(const vector& nums) { + for (int i = nums.size() - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } +}; diff --git a/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.java b/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.java new file mode 100644 index 00000000000..5a7342bb89c --- /dev/null +++ b/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.java @@ -0,0 +1,43 @@ +class Solution { + // Same as 2970. Count the Number of Incremovable Subarrays I + public long incremovableSubarrayCount(int[] nums) { + final int n = nums.length; + final int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return (long) n * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + long ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0, j = startIndex; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, move j to the place such that + // nums[j] > nums[i]. The valid removals will then be nums[i + 1..j - 1], + // nums[i + 1..j], ..., nums[i + 1..n). + while (j < n && nums[i] >= nums[j]) + ++j; + ans += n - j + 1; + } + + return ans; + } + + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + private int getStartIndexOfSuffix(int[] nums) { + for (int i = nums.length - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } + + private int firstGreater(int[] A, int startIndex, int target) { + final int i = Arrays.binarySearch(A, startIndex, A.length, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.py b/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.py new file mode 100644 index 00000000000..d9a2d0b0244 --- /dev/null +++ b/solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.py @@ -0,0 +1,33 @@ +class Solution: + # Same as 2970. Count the Number of Incremovable Subarrays I + def incremovableSubarrayCount(self, nums: List[int]) -> int: + n = len(nums) + startIndex = self._getStartIndexOfSuffix(nums) + # If the complete array is strictly increasing, the total number of ways we + # can remove elements equals the total number of possible subarrays. + if startIndex == 0: + return n * (n + 1) // 2 + + # The valid removals starting from nums[0] include nums[0..startIndex - 1], + # nums[0..startIndex], ..., nums[0..n). + ans = n - startIndex + 1 + + # Enumerate each prefix subarray that is strictly increasing. + j = startIndex + for i in range(startIndex): + if i > 0 and nums[i] <= nums[i - 1]: + break + # Since nums[0..i] is strictly increasing, move j to the place such that + # nums[j] > nums[i]. The valid removals will then be nums[i + 1..j - 1], + # nums[i + 1..j], ..., nums[i + 1..n). + while j < n and nums[i] >= nums[j]: + j += 1 + ans += n - j + 1 + + return ans + + def _getStartIndexOfSuffix(self, nums: List[int]) -> int: + for i in range(len(nums) - 2, -1, -1): + if nums[i] >= nums[i + 1]: + return i + 1 + return 0 diff --git a/solutions/2972. Count the Number of Incremovable Subarrays II/2972.cpp b/solutions/2972. Count the Number of Incremovable Subarrays II/2972.cpp new file mode 100644 index 00000000000..2e4698e2dca --- /dev/null +++ b/solutions/2972. Count the Number of Incremovable Subarrays II/2972.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + // Same as 2970. Count the Number of Incremovable Subarrays I + long long incremovableSubarrayCount(vector& nums) { + const int n = nums.size(); + const int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return static_cast(n) * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + long ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, find the first index j in + // nums[startIndex..n) such that nums[j] > nums[i]. The valid removals + // will then be nums[i + 1..j - 1], nums[i + 1..j], ..., nums[i + 1..n). + ans += nums.end() - + upper_bound(nums.begin() + startIndex, nums.end(), nums[i]) + 1; + } + + return ans; + } + + private: + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + int getStartIndexOfSuffix(const vector& nums) { + for (int i = nums.size() - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } +}; diff --git a/solutions/2972. Count the Number of Incremovable Subarrays II/2972.java b/solutions/2972. Count the Number of Incremovable Subarrays II/2972.java new file mode 100644 index 00000000000..61f22b103c0 --- /dev/null +++ b/solutions/2972. Count the Number of Incremovable Subarrays II/2972.java @@ -0,0 +1,41 @@ +class Solution { + // Same as 2970. Count the Number of Incremovable Subarrays I + public long incremovableSubarrayCount(int[] nums) { + final int n = nums.length; + final int startIndex = getStartIndexOfSuffix(nums); + // If the complete array is strictly increasing, the total number of ways we + // can remove elements equals the total number of possible subarrays. + if (startIndex == 0) + return (long) n * (n + 1) / 2; + + // The valid removals starting from nums[0] include nums[0..startIndex - 1], + // nums[0..startIndex], ..., nums[0..n). + long ans = n - startIndex + 1; + + // Enumerate each prefix subarray that is strictly increasing. + for (int i = 0; i < startIndex; ++i) { + if (i > 0 && nums[i] <= nums[i - 1]) + break; + // Since nums[0..i] is strictly increasing, find the first index j in + // nums[startIndex..n) such that nums[j] > nums[i]. The valid removals + // will then be nums[i + 1..j - 1], nums[i + 1..j], ..., nums[i + 1..n). + ans += n - firstGreater(nums, startIndex, nums[i]) + 1; + } + + return ans; + } + + // Returns the start index i of the suffix subarray such that nums[i..n) is + // strictly increasing. + private int getStartIndexOfSuffix(int[] nums) { + for (int i = nums.length - 2; i >= 0; --i) + if (nums[i] >= nums[i + 1]) + return i + 1; + return 0; + } + + private int firstGreater(int[] A, int startIndex, int target) { + final int i = Arrays.binarySearch(A, startIndex, A.length, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/2972. Count the Number of Incremovable Subarrays II/2972.py b/solutions/2972. Count the Number of Incremovable Subarrays II/2972.py new file mode 100644 index 00000000000..7584a7e940f --- /dev/null +++ b/solutions/2972. Count the Number of Incremovable Subarrays II/2972.py @@ -0,0 +1,30 @@ +class Solution: + # Same as 2970. Count the Number of Incremovable Subarrays I + def incremovableSubarrayCount(self, nums: List[int]) -> int: + n = len(nums) + startIndex = self._getStartIndexOfSuffix(nums) + # If the complete array is strictly increasing, the total number of ways we + # can remove elements equals the total number of possible subarrays. + if startIndex == 0: + return n * (n + 1) // 2 + + # The valid removals starting from nums[0] include nums[0..startIndex - 1], + # nums[0..startIndex], ..., nums[0..n). + ans = n - startIndex + 1 + + # Enumerate each prefix subarray that is strictly increasing. + for i in range(startIndex): + if i > 0 and nums[i] <= nums[i - 1]: + break + # Since nums[0..i] is strictly increasing, find the first index j in + # nums[startIndex..n) such that nums[j] > nums[i]. The valid removals + # will then be nums[i + 1..j - 1], nums[i + 1..j], ..., nums[i + 1..n). + ans += n - bisect.bisect_right(nums, nums[i], startIndex) + 1 + + return ans + + def _getStartIndexOfSuffix(self, nums: List[int]) -> int: + for i in range(len(nums) - 2, -1, -1): + if nums[i] >= nums[i + 1]: + return i + 1 + return 0 diff --git a/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.cpp b/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.cpp new file mode 100644 index 00000000000..86f7286eb01 --- /dev/null +++ b/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.cpp @@ -0,0 +1,69 @@ +class ChildCost { + public: + ChildCost(int cost) { + numNodes = 1; + if (cost > 0) + maxPosCosts.push_back(cost); + else + minNegCosts.push_back(cost); + } + + void update(ChildCost childCost) { + numNodes += childCost.numNodes; + ranges::copy(childCost.maxPosCosts, back_inserter(maxPosCosts)); + ranges::copy(childCost.minNegCosts, back_inserter(minNegCosts)); + ranges::sort(maxPosCosts, greater()); + ranges::sort(minNegCosts); + maxPosCosts.resize(min(static_cast(maxPosCosts.size()), 3)); + minNegCosts.resize(min(static_cast(minNegCosts.size()), 2)); + } + + long maxProduct() { + if (numNodes < 3) + return 1; + if (maxPosCosts.empty()) + return 0; + long res = 0; + if (maxPosCosts.size() == 3) + res = static_cast(maxPosCosts[0]) * maxPosCosts[1] * maxPosCosts[2]; + if (minNegCosts.size() == 2) + res = max(res, static_cast(minNegCosts[0]) * minNegCosts[1] * + maxPosCosts[0]); + return res; + } + + private: + int numNodes; + vector maxPosCosts; + vector minNegCosts; +}; + +class Solution { + public: + vector placedCoins(vector>& edges, vector& cost) { + const int n = cost.size(); + vector ans(n); + vector> tree(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + tree[v].push_back(u); + } + + dfs(tree, 0, /*prev=*/-1, cost, ans); + return ans; + } + + private: + ChildCost dfs(const vector>& tree, int u, int prev, + const vector& cost, vector& ans) { + ChildCost res(cost[u]); + for (const int v : tree[u]) + if (v != prev) + res.update(dfs(tree, v, u, cost, ans)); + ans[u] = res.maxProduct(); + return res; + } +}; diff --git a/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.java b/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.java new file mode 100644 index 00000000000..916d925e898 --- /dev/null +++ b/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.java @@ -0,0 +1,67 @@ +class ChildCost { + public ChildCost(int cost) { + if (cost > 0) + maxPosCosts.add(cost); + else + minNegCosts.add(cost); + } + + public void update(ChildCost childCost) { + numNodes += childCost.numNodes; + maxPosCosts.addAll(childCost.maxPosCosts); + minNegCosts.addAll(childCost.minNegCosts); + maxPosCosts.sort(Comparator.reverseOrder()); + minNegCosts.sort(Comparator.naturalOrder()); + if (maxPosCosts.size() > 3) + maxPosCosts = maxPosCosts.subList(0, 3); + if (minNegCosts.size() > 2) + minNegCosts = minNegCosts.subList(0, 2); + } + + public long maxProduct() { + if (numNodes < 3) + return 1; + if (maxPosCosts.isEmpty()) + return 0; + long res = 0; + if (maxPosCosts.size() == 3) + res = (long) maxPosCosts.get(0) * maxPosCosts.get(1) * maxPosCosts.get(2); + if (minNegCosts.size() == 2) + res = Math.max(res, (long) minNegCosts.get(0) * minNegCosts.get(1) * maxPosCosts.get(0)); + return res; + } + + private int numNodes = 1; + private List maxPosCosts = new ArrayList<>(); + private List minNegCosts = new ArrayList<>(); +} + +class Solution { + public long[] placedCoins(int[][] edges, int[] cost) { + final int n = cost.length; + long[] ans = new long[n]; + List[] tree = new List[n]; + + for (int i = 0; i < n; i++) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + dfs(tree, 0, /*prev=*/-1, cost, ans); + return ans; + } + + private ChildCost dfs(List[] tree, int u, int prev, int[] cost, long[] ans) { + ChildCost res = new ChildCost(cost[u]); + for (final int v : tree[u]) + if (v != prev) + res.update(dfs(tree, v, u, cost, ans)); + ans[u] = res.maxProduct(); + return res; + } +} diff --git a/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.py b/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.py new file mode 100644 index 00000000000..e0036cb25ab --- /dev/null +++ b/solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.py @@ -0,0 +1,49 @@ +class ChildCost: + def __init__(self, cost: int): + self.numNodes = 1 + self.maxPosCosts = [cost] if cost > 0 else [] + self.minNegCosts = [cost] if cost < 0 else [] + + def update(self, childCost: 'ChildCost') -> None: + self.numNodes += childCost.numNodes + self.maxPosCosts.extend(childCost.maxPosCosts) + self.minNegCosts.extend(childCost.minNegCosts) + self.maxPosCosts.sort(reverse=True) + self.minNegCosts.sort() + self.maxPosCosts = self.maxPosCosts[:3] + self.minNegCosts = self.minNegCosts[:2] + + def maxProduct(self) -> int: + if self.numNodes < 3: + return 1 + if not self.maxPosCosts: + return 0 + res = 0 + if len(self.maxPosCosts) == 3: + res = self.maxPosCosts[0] * self.maxPosCosts[1] * self.maxPosCosts[2] + if len(self.minNegCosts) == 2: + res = max(res, + self.minNegCosts[0] * self.minNegCosts[1] * self.maxPosCosts[0]) + return res + + +class Solution: + def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]: + n = len(cost) + ans = [0] * n + tree = [[] for _ in range(n)] + + for u, v in edges: + tree[u].append(v) + tree[v].append(u) + + def dfs(u: int, prev: int) -> None: + res = ChildCost(cost[u]) + for v in tree[u]: + if v != prev: + res.update(dfs(v, u)) + ans[u] = res.maxProduct() + return res + + dfs(0, -1) + return ans diff --git a/solutions/2974. Minimum Number Game/2974.cpp b/solutions/2974. Minimum Number Game/2974.cpp new file mode 100644 index 00000000000..87a04825822 --- /dev/null +++ b/solutions/2974. Minimum Number Game/2974.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + vector numberGame(vector& nums) { + ranges::sort(nums); + for (int i = 0; i < nums.size(); i += 2) + swap(nums[i], nums[i + 1]); + return nums; + } +}; diff --git a/solutions/2974. Minimum Number Game/2974.java b/solutions/2974. Minimum Number Game/2974.java new file mode 100644 index 00000000000..9a711096c27 --- /dev/null +++ b/solutions/2974. Minimum Number Game/2974.java @@ -0,0 +1,13 @@ +class Solution { + public int[] numberGame(int[] nums) { + Arrays.sort(nums); + + for (int i = 0; i < nums.length; i += 2) { + final int temp = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = temp; + } + + return nums; + } +} diff --git a/solutions/2974. Minimum Number Game/2974.py b/solutions/2974. Minimum Number Game/2974.py new file mode 100644 index 00000000000..072fc212619 --- /dev/null +++ b/solutions/2974. Minimum Number Game/2974.py @@ -0,0 +1,6 @@ +class Solution: + def numberGame(self, nums: List[int]) -> List[int]: + nums.sort() + return [nums[i + 1] if i % 2 == 0 + else nums[i - 1] + for i in range(len(nums))] diff --git a/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.cpp b/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.cpp new file mode 100644 index 00000000000..9c1116ad7a0 --- /dev/null +++ b/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int maximizeSquareArea(int m, int n, vector& hFences, + vector& vFences) { + constexpr int kMod = 1'000'000'007; + + hFences.push_back(1); + hFences.push_back(m); + vFences.push_back(1); + vFences.push_back(n); + + ranges::sort(hFences); + ranges::sort(vFences); + + const unordered_set hGaps = getGaps(hFences); + const unordered_set vGaps = getGaps(vFences); + int maxGap = -1; + + for (const int hGap : hGaps) + if (vGaps.contains(hGap)) + maxGap = max(maxGap, hGap); + + return maxGap == -1 ? -1 : static_cast(maxGap) * maxGap % kMod; + } + + private: + unordered_set getGaps(const vector& fences) { + unordered_set gaps; + for (int i = 0; i < fences.size(); ++i) + for (int j = 0; j < i; ++j) + gaps.insert(fences[i] - fences[j]); + return gaps; + } +}; diff --git a/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.java b/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.java new file mode 100644 index 00000000000..72a4c26b3cd --- /dev/null +++ b/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.java @@ -0,0 +1,34 @@ +class Solution { + public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) { + final int kMod = 1_000_000_007; + + hFences = Arrays.copyOf(hFences, hFences.length + 2); + vFences = Arrays.copyOf(vFences, vFences.length + 2); + + hFences[hFences.length - 2] = 1; + hFences[hFences.length - 1] = m; + vFences[vFences.length - 2] = 1; + vFences[vFences.length - 1] = n; + + Arrays.sort(hFences); + Arrays.sort(vFences); + + Set hGaps = getGaps(hFences); + Set vGaps = getGaps(vFences); + int maxGap = -1; + + for (final int hGap : hGaps) + if (vGaps.contains(hGap)) + maxGap = Math.max(maxGap, hGap); + + return maxGap == -1 ? -1 : (int) ((long) maxGap * maxGap % kMod); + } + + private Set getGaps(int[] fences) { + Set gaps = new HashSet<>(); + for (int i = 0; i < fences.length; ++i) + for (int j = 0; j < i; ++j) + gaps.add(fences[i] - fences[j]); + return gaps; + } +} diff --git a/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.py b/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.py new file mode 100644 index 00000000000..32fa01ff080 --- /dev/null +++ b/solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.py @@ -0,0 +1,14 @@ +class Solution: + def maximizeSquareArea(self, m: int, n: int, hFences: List[int], vFences: List[int]) -> int: + hFences = sorted(hFences + [1, m]) + vFences = sorted(vFences + [1, n]) + hGaps = {hFences[i] - hFences[j] + for i in range(len(hFences)) + for j in range(i)} + vGaps = {vFences[i] - vFences[j] + for i in range(len(vFences)) + for j in range(i)} + maxGap = next((hGap + for hGap in sorted(hGaps, reverse=True) + if hGap in vGaps), -1) + return -1 if maxGap == -1 else maxGap**2 % (10**9 + 7) diff --git a/solutions/2976. Minimum Cost to Convert String I/2976.cpp b/solutions/2976. Minimum Cost to Convert String I/2976.cpp new file mode 100644 index 00000000000..0d52ee49aeb --- /dev/null +++ b/solutions/2976. Minimum Cost to Convert String I/2976.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + long long minimumCost(string source, string target, vector& original, + vector& changed, vector& cost) { + long ans = 0; + // dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v) + vector> dist(26, vector(26, LONG_MAX)); + + for (int i = 0; i < cost.size(); ++i) { + const int u = original[i] - 'a'; + const int v = changed[i] - 'a'; + dist[u][v] = min(dist[u][v], static_cast(cost[i])); + } + + for (int k = 0; k < 26; ++k) + for (int i = 0; i < 26; ++i) + if (dist[i][k] < LONG_MAX) + for (int j = 0; j < 26; ++j) + if (dist[k][j] < LONG_MAX) + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); + + for (int i = 0; i < source.length(); ++i) { + if (source[i] == target[i]) + continue; + const int u = source[i] - 'a'; + const int v = target[i] - 'a'; + if (dist[u][v] == LONG_MAX) + return -1; + ans += dist[u][v]; + } + + return ans; + } +}; diff --git a/solutions/2976. Minimum Cost to Convert String I/2976.java b/solutions/2976. Minimum Cost to Convert String I/2976.java new file mode 100644 index 00000000000..086af85141b --- /dev/null +++ b/solutions/2976. Minimum Cost to Convert String I/2976.java @@ -0,0 +1,34 @@ +class Solution { + public long minimumCost(String source, String target, char[] original, char[] changed, + int[] cost) { + long ans = 0; + // dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v) + long[][] dist = new long[26][26]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE)); + + for (int i = 0; i < cost.length; ++i) { + final int u = original[i] - 'a'; + final int v = changed[i] - 'a'; + dist[u][v] = Math.min(dist[u][v], cost[i]); + } + + for (int k = 0; k < 26; ++k) + for (int i = 0; i < 26; ++i) + if (dist[i][k] < Long.MAX_VALUE) + for (int j = 0; j < 26; ++j) + if (dist[k][j] < Long.MAX_VALUE) + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + + for (int i = 0; i < source.length(); ++i) { + if (source.charAt(i) == target.charAt(i)) + continue; + final int u = source.charAt(i) - 'a'; + final int v = target.charAt(i) - 'a'; + if (dist[u][v] == Long.MAX_VALUE) + return -1; + ans += dist[u][v]; + } + + return ans; + } +} diff --git a/solutions/2976. Minimum Cost to Convert String I/2976.py b/solutions/2976. Minimum Cost to Convert String I/2976.py new file mode 100644 index 00000000000..13ff0788117 --- /dev/null +++ b/solutions/2976. Minimum Cost to Convert String I/2976.py @@ -0,0 +1,28 @@ +class Solution: + def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int: + ans = 0 + # dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v) + dist = [[math.inf] * 26 for _ in range(26)] + + for a, b, c in zip(original, changed, cost): + u = ord(a) - ord('a') + v = ord(b) - ord('a') + dist[u][v] = min(dist[u][v], c) + + for k in range(26): + for i in range(26): + if dist[i][k] < math.inf: + for j in range(26): + if dist[k][j] < math.inf: + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + + for s, t in zip(source, target): + if s == t: + continue + u = ord(s) - ord('a') + v = ord(t) - ord('a') + if dist[u][v] == math.inf: + return -1 + ans += dist[u][v] + + return ans diff --git a/solutions/2977. Minimum Cost to Convert String II/2977.cpp b/solutions/2977. Minimum Cost to Convert String II/2977.cpp new file mode 100644 index 00000000000..2971250dd45 --- /dev/null +++ b/solutions/2977. Minimum Cost to Convert String II/2977.cpp @@ -0,0 +1,71 @@ +class Solution { + public: + long long minimumCost(string source, string target, vector& original, + vector& changed, vector& cost) { + const unordered_set subLengths = getSubLengths(original); + const unordered_map subToId = getSubToId(original, changed); + const int subCount = subToId.size(); + // dist[u][v] := the minimum distance to change the substring with id u to + // the substring with id v + vector> dist(subCount, vector(subCount, LONG_MAX)); + // dp[i] := the minimum cost to change the first i letters of `source` into + // `target`, leaving the suffix untouched + vector dp(source.length() + 1, LONG_MAX); + + for (int i = 0; i < cost.size(); ++i) { + const int u = subToId.at(original[i]); + const int v = subToId.at(changed[i]); + dist[u][v] = min(dist[u][v], static_cast(cost[i])); + } + + for (int k = 0; k < subCount; ++k) + for (int i = 0; i < subCount; ++i) + if (dist[i][k] < LONG_MAX) + for (int j = 0; j < subCount; ++j) + if (dist[k][j] < LONG_MAX) + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); + + dp[0] = 0; + + for (int i = 0; i < source.length(); ++i) { + if (dp[i] == LONG_MAX) + continue; + if (target[i] == source[i]) + dp[i + 1] = min(dp[i + 1], dp[i]); + for (const int subLength : subLengths) { + if (i + subLength > source.length()) + continue; + const string subSource = source.substr(i, subLength); + const string subTarget = target.substr(i, subLength); + if (!subToId.contains(subSource) || !subToId.contains(subTarget)) + continue; + const int u = subToId.at(subSource); + const int v = subToId.at(subTarget); + if (dist[u][v] < LONG_MAX) + dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v]); + } + } + + return dp[source.length()] == LONG_MAX ? -1 : dp[source.length()]; + } + + private: + unordered_map getSubToId(const vector& original, + const vector& changed) { + unordered_map subToId; + for (const string& s : original) + if (!subToId.contains(s)) + subToId[s] = subToId.size(); + for (const string& s : changed) + if (!subToId.contains(s)) + subToId[s] = subToId.size(); + return subToId; + } + + unordered_set getSubLengths(const vector& original) { + unordered_set subLengths; + for (const string& s : original) + subLengths.insert(s.length()); + return subLengths; + } +}; diff --git a/solutions/2977. Minimum Cost to Convert String II/2977.java b/solutions/2977. Minimum Cost to Convert String II/2977.java new file mode 100644 index 00000000000..455f6360d45 --- /dev/null +++ b/solutions/2977. Minimum Cost to Convert String II/2977.java @@ -0,0 +1,68 @@ +class Solution { + public long minimumCost(String source, String target, String[] original, String[] changed, + int[] cost) { + Set subLengths = getSubLengths(original); + Map subToId = getSubToId(original, changed); + final int subCount = subToId.size(); + // dist[u][v] := the minimum distance to change the substring with id u to + // the substring with id v + long[][] dist = new long[subCount][subCount]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE)); + // dp[i] := the minimum cost to change the first i letters of `source` into + // `target`, leaving the suffix untouched + long[] dp = new long[source.length() + 1]; + Arrays.fill(dp, Long.MAX_VALUE); + + for (int i = 0; i < cost.length; ++i) { + final int u = subToId.get(original[i]); + final int v = subToId.get(changed[i]); + dist[u][v] = Math.min(dist[u][v], (long) cost[i]); + } + + for (int k = 0; k < subCount; ++k) + for (int i = 0; i < subCount; ++i) + if (dist[i][k] < Long.MAX_VALUE) + for (int j = 0; j < subCount; ++j) + if (dist[k][j] < Long.MAX_VALUE) + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + + dp[0] = 0; + + for (int i = 0; i < source.length(); ++i) { + if (dp[i] == Long.MAX_VALUE) + continue; + if (target.charAt(i) == source.charAt(i)) + dp[i + 1] = Math.min(dp[i + 1], dp[i]); + for (int subLength : subLengths) { + if (i + subLength > source.length()) + continue; + String subSource = source.substring(i, i + subLength); + String subTarget = target.substring(i, i + subLength); + if (!subToId.containsKey(subSource) || !subToId.containsKey(subTarget)) + continue; + final int u = subToId.get(subSource); + final int v = subToId.get(subTarget); + if (dist[u][v] < Long.MAX_VALUE) + dp[i + subLength] = Math.min(dp[i + subLength], dp[i] + dist[u][v]); + } + } + + return dp[source.length()] == Long.MAX_VALUE ? -1 : dp[source.length()]; + } + + private Map getSubToId(String[] original, String[] changed) { + Map subToId = new HashMap<>(); + for (final String s : original) + subToId.putIfAbsent(s, subToId.size()); + for (final String s : changed) + subToId.putIfAbsent(s, subToId.size()); + return subToId; + } + + private Set getSubLengths(String[] original) { + Set subLengths = new HashSet<>(); + for (final String s : original) + subLengths.add(s.length()); + return subLengths; + } +} diff --git a/solutions/2977. Minimum Cost to Convert String II/2977.py b/solutions/2977. Minimum Cost to Convert String II/2977.py new file mode 100644 index 00000000000..e561c966ed9 --- /dev/null +++ b/solutions/2977. Minimum Cost to Convert String II/2977.py @@ -0,0 +1,51 @@ +class Solution: + def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int: + subLengths = set(len(s) for s in original) + subToId = self._getSubToId(original, changed) + subCount = len(subToId) + # dist[u][v] := the minimum distance to change the substring with id u to + # the substring with id v + dist = [[math.inf for _ in range(subCount)] for _ in range(subCount)] + # dp[i] := the minimum cost to change the first i letters of `source` into + # `target`, leaving the suffix untouched + dp = [math.inf for _ in range(len(source) + 1)] + + for a, b, c in zip(original, changed, cost): + u = subToId[a] + v = subToId[b] + dist[u][v] = min(dist[u][v], c) + + for k in range(subCount): + for i in range(subCount): + if dist[i][k] < math.inf: + for j in range(subCount): + if dist[k][j] < math.inf: + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + + dp[0] = 0 + + for i, (s, t) in enumerate(zip(source, target)): + if dp[i] == math.inf: + continue + if s == t: + dp[i + 1] = min(dp[i + 1], dp[i]) + for subLength in subLengths: + if i + subLength > len(source): + continue + subSource = source[i:i + subLength] + subTarget = target[i:i + subLength] + if subSource not in subToId or subTarget not in subToId: + continue + u = subToId[subSource] + v = subToId[subTarget] + if dist[u][v] != math.inf: + dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v]) + + return -1 if dp[len(source)] == math.inf else dp[len(source)] + + def _getSubToId(self, original: str, changed: str) -> Dict[str, int]: + subToId = {} + for s in original + changed: + if s not in subToId: + subToId[s] = len(subToId) + return subToId diff --git a/solutions/2978. Symmetric Coordinates/2978.sql b/solutions/2978. Symmetric Coordinates/2978.sql new file mode 100644 index 00000000000..c32cfc36ed4 --- /dev/null +++ b/solutions/2978. Symmetric Coordinates/2978.sql @@ -0,0 +1,17 @@ +WITH + SymmetricCoordinates AS ( + SELECT DISTINCT C1.x, C1.y + FROM Coordinates AS C1 + INNER JOIN Coordinates AS C2 + ON (C1.x, C1.y) = (C2.y, C2.x) + WHERE C1.x < C1.y + UNION ALL + SELECT x, y + FROM Coordinates + WHERE x = y + GROUP BY 1 + HAVING COUNT(*) > 1 + ) +SELECT x, y +FROM SymmetricCoordinates +ORDER BY 1, 2; diff --git a/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.cpp b/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.cpp new file mode 100644 index 00000000000..ffc88df4418 --- /dev/null +++ b/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int mostExpensiveItem(int primeOne, int primeTwo) { + // https://en.wikipedia.org/wiki/Coin_problem + return primeOne * primeTwo - primeOne - primeTwo; + } +}; diff --git a/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.java b/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.java new file mode 100644 index 00000000000..87ec652aee7 --- /dev/null +++ b/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.java @@ -0,0 +1,6 @@ +class Solution { + public int mostExpensiveItem(int primeOne, int primeTwo) { + // https://en.wikipedia.org/wiki/Coin_problem + return primeOne * primeTwo - primeOne - primeTwo; + } +} diff --git a/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.py b/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.py new file mode 100644 index 00000000000..787611c0010 --- /dev/null +++ b/solutions/2979. Most Expensive Item That Can Not Be Bought/2979.py @@ -0,0 +1,4 @@ +class Solution: + def mostExpensiveItem(self, primeOne: int, primeTwo: int) -> int: + # https://en.wikipedia.org/wiki/Coin_problem + return primeOne * primeTwo - primeOne - primeTwo diff --git a/solutions/298. Binary Tree Longest Consecutive Sequence/298.cpp b/solutions/298. Binary Tree Longest Consecutive Sequence/298.cpp new file mode 100644 index 00000000000..c7bee1e9fdf --- /dev/null +++ b/solutions/298. Binary Tree Longest Consecutive Sequence/298.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int longestConsecutive(TreeNode* root) { + if (root == nullptr) + return 0; + return dfs(root, root->val, 0, 0); + } + + private: + int dfs(TreeNode* root, int target, int length, int maxLength) { + if (root == nullptr) + return maxLength; + if (root->val == target) + maxLength = max(maxLength, ++length); + else + length = 1; + return max(dfs(root->left, root->val + 1, length, maxLength), + dfs(root->right, root->val + 1, length, maxLength)); + } +}; diff --git a/solutions/298. Binary Tree Longest Consecutive Sequence/298.java b/solutions/298. Binary Tree Longest Consecutive Sequence/298.java new file mode 100644 index 00000000000..bddb97d4252 --- /dev/null +++ b/solutions/298. Binary Tree Longest Consecutive Sequence/298.java @@ -0,0 +1,18 @@ +class Solution { + public int longestConsecutive(TreeNode root) { + if (root == null) + return 0; + return dfs(root, -1, 0, 1); + } + + private int dfs(TreeNode root, int target, int length, int mx) { + if (root == null) + return mx; + if (root.val == target) + mx = Math.max(mx, ++length); + else + length = 1; + return Math.max(dfs(root.left, root.val + 1, length, mx), + dfs(root.right, root.val + 1, length, mx)); + } +} diff --git a/solutions/298. Binary Tree Longest Consecutive Sequence/298.py b/solutions/298. Binary Tree Longest Consecutive Sequence/298.py new file mode 100644 index 00000000000..72d17655ad3 --- /dev/null +++ b/solutions/298. Binary Tree Longest Consecutive Sequence/298.py @@ -0,0 +1,17 @@ +class Solution: + def longestConsecutive(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + def dfs(root: Optional[TreeNode], target: int, length: int, maxLength: int) -> int: + if not root: + return maxLength + if root.val == target: + length += 1 + maxLength = max(maxLength, length) + else: + length = 1 + return max(dfs(root.left, root.val + 1, length, maxLength), + dfs(root.right, root.val + 1, length, maxLength)) + + return dfs(root, root.val, 0, 0) diff --git a/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.cpp b/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.cpp new file mode 100644 index 00000000000..f4f19ec3677 --- /dev/null +++ b/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool hasTrailingZeros(vector& nums) { + int countEven = 0; + + for (const int num : nums) + if (num % 2 == 0) + ++countEven; + + return countEven >= 2; + } +}; diff --git a/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.java b/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.java new file mode 100644 index 00000000000..256c07bc53c --- /dev/null +++ b/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.java @@ -0,0 +1,11 @@ +class Solution { + public boolean hasTrailingZeros(int[] nums) { + int countEven = 0; + + for (final int num : nums) + if (num % 2 == 0) + ++countEven; + + return countEven >= 2; + } +} diff --git a/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.py b/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.py new file mode 100644 index 00000000000..8263ea835c1 --- /dev/null +++ b/solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.py @@ -0,0 +1,3 @@ +class Solution: + def hasTrailingZeros(self, nums: List[int]) -> bool: + return sum(num % 2 == 0 for num in nums) >= 2 diff --git a/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.cpp b/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.cpp new file mode 100644 index 00000000000..6547d11329f --- /dev/null +++ b/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int maximumLength(string s) { + const int n = s.length(); + int ans = -1; + int runningLen = 0; + char prevLetter = '@'; + // counts[i][j] := the frequency of ('a' + i) repeating j times + vector> counts(26, vector(n + 1)); + + for (const char c : s) + if (c == prevLetter) { + ++counts[c - 'a'][++runningLen]; + } else { + runningLen = 1; + ++counts[c - 'a'][runningLen]; + prevLetter = c; + } + + for (const vector& count : counts) + ans = max(ans, getMaxFreq(count, n)); + + return ans; + } + + private: + // Returns the maximum frequency that occurs more than three times. + int getMaxFreq(const vector& count, int maxFreq) { + int times = 0; + for (int freq = maxFreq; freq >= 1; --freq) { + times += count[freq]; + if (times >= 3) + return freq; + } + return -1; + } +}; diff --git a/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.java b/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.java new file mode 100644 index 00000000000..92ab4f5c75a --- /dev/null +++ b/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.java @@ -0,0 +1,36 @@ +class Solution { + public int maximumLength(String s) { + final int n = s.length(); + int ans = -1; + int runningLen = 0; + char prevLetter = '@'; + // counts[i][j] := the frequency of ('a' + i) repeating j times + int[][] counts = new int[26][n + 1]; + + for (final char c : s.toCharArray()) + if (c == prevLetter) { + ++counts[c - 'a'][++runningLen]; + } else { + runningLen = 1; + ++counts[c - 'a'][runningLen]; + prevLetter = c; + } + + for (int[] count : counts) { + ans = Math.max(ans, getMaxFreq(count, n)); + } + + return ans; + } + + // Returns the maximum frequency that occurs more than three times. + private int getMaxFreq(int[] count, int maxFreq) { + int times = 0; + for (int freq = maxFreq; freq >= 1; --freq) { + times += count[freq]; + if (times >= 3) + return freq; + } + return -1; + } +} diff --git a/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.py b/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.py new file mode 100644 index 00000000000..29e9623ab36 --- /dev/null +++ b/solutions/2981. Find Longest Special Substring That Occurs Thrice I/2981.py @@ -0,0 +1,27 @@ +class Solution: + def maximumLength(self, s: str) -> int: + n = len(s) + runningLen = 0 + prevLetter = '@' + # counts[i][j] := the frequency of ('a' + i) repeating j times + counts = [[0] * (n + 1) for _ in range(26)] + + for c in s: + if c == prevLetter: + runningLen += 1 + counts[ord(c) - ord('a')][runningLen] += 1 + else: + runningLen = 1 + counts[ord(c) - ord('a')][runningLen] += 1 + prevLetter = c + + def getMaxFreq(count: List[int]) -> int: + """Returns the maximum frequency that occurs more than three times.""" + times = 0 + for freq in range(n, 0, -1): + times += count[freq] + if times >= 3: + return freq + return -1 + + return max(getMaxFreq(count) for count in counts) diff --git a/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.cpp b/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.cpp new file mode 100644 index 00000000000..6547d11329f --- /dev/null +++ b/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int maximumLength(string s) { + const int n = s.length(); + int ans = -1; + int runningLen = 0; + char prevLetter = '@'; + // counts[i][j] := the frequency of ('a' + i) repeating j times + vector> counts(26, vector(n + 1)); + + for (const char c : s) + if (c == prevLetter) { + ++counts[c - 'a'][++runningLen]; + } else { + runningLen = 1; + ++counts[c - 'a'][runningLen]; + prevLetter = c; + } + + for (const vector& count : counts) + ans = max(ans, getMaxFreq(count, n)); + + return ans; + } + + private: + // Returns the maximum frequency that occurs more than three times. + int getMaxFreq(const vector& count, int maxFreq) { + int times = 0; + for (int freq = maxFreq; freq >= 1; --freq) { + times += count[freq]; + if (times >= 3) + return freq; + } + return -1; + } +}; diff --git a/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.java b/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.java new file mode 100644 index 00000000000..92ab4f5c75a --- /dev/null +++ b/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.java @@ -0,0 +1,36 @@ +class Solution { + public int maximumLength(String s) { + final int n = s.length(); + int ans = -1; + int runningLen = 0; + char prevLetter = '@'; + // counts[i][j] := the frequency of ('a' + i) repeating j times + int[][] counts = new int[26][n + 1]; + + for (final char c : s.toCharArray()) + if (c == prevLetter) { + ++counts[c - 'a'][++runningLen]; + } else { + runningLen = 1; + ++counts[c - 'a'][runningLen]; + prevLetter = c; + } + + for (int[] count : counts) { + ans = Math.max(ans, getMaxFreq(count, n)); + } + + return ans; + } + + // Returns the maximum frequency that occurs more than three times. + private int getMaxFreq(int[] count, int maxFreq) { + int times = 0; + for (int freq = maxFreq; freq >= 1; --freq) { + times += count[freq]; + if (times >= 3) + return freq; + } + return -1; + } +} diff --git a/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.py b/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.py new file mode 100644 index 00000000000..29e9623ab36 --- /dev/null +++ b/solutions/2982. Find Longest Special Substring That Occurs Thrice II/2982.py @@ -0,0 +1,27 @@ +class Solution: + def maximumLength(self, s: str) -> int: + n = len(s) + runningLen = 0 + prevLetter = '@' + # counts[i][j] := the frequency of ('a' + i) repeating j times + counts = [[0] * (n + 1) for _ in range(26)] + + for c in s: + if c == prevLetter: + runningLen += 1 + counts[ord(c) - ord('a')][runningLen] += 1 + else: + runningLen = 1 + counts[ord(c) - ord('a')][runningLen] += 1 + prevLetter = c + + def getMaxFreq(count: List[int]) -> int: + """Returns the maximum frequency that occurs more than three times.""" + times = 0 + for freq in range(n, 0, -1): + times += count[freq] + if times >= 3: + return freq + return -1 + + return max(getMaxFreq(count) for count in counts) diff --git a/solutions/2983. Palindrome Rearrangement Queries/2983.cpp b/solutions/2983. Palindrome Rearrangement Queries/2983.cpp new file mode 100644 index 00000000000..471abada838 --- /dev/null +++ b/solutions/2983. Palindrome Rearrangement Queries/2983.cpp @@ -0,0 +1,85 @@ +class Solution { + public: + vector canMakePalindromeQueries(string s, + vector>& queries) { + const int n = s.length(); + // mirroredDiffs[i] := the number of different letters between the first i + // letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1] + const vector mirroredDiffs = getMirroredDiffs(s); + // counts[i] := the count of s[0..i) + const vector> counts = getCounts(s); + vector ans; + + for (const vector& query : queries) { + // Use left-closed, right-open intervals to facilitate the calculation. + // ...... [a, b) ...|... [rb, ra) ...... + // .... [rd, rc) .....|..... [c, d) .... + const int a = query[0]; + const int b = query[1] + 1; + const int c = query[2]; + const int d = query[3] + 1; + const int ra = n - a; // the reflected index of a in s[n / 2..n) + const int rb = n - b; // the reflected index of b in s[n / 2..n) + const int rc = n - c; // the reflected index of c in s[n / 2..n) + const int rd = n - d; // the reflected index of d in s[n / 2..n) + // No difference is allowed outside the query ranges. + if (min(a, rd) > 0 && mirroredDiffs[min(a, rd)] > 0 || + n / 2 > max(b, rc) && + mirroredDiffs[n / 2] - mirroredDiffs[max(b, rc)] > 0 || + rd > b && mirroredDiffs[rd] - mirroredDiffs[b] > 0 || + a > rc && mirroredDiffs[a] - mirroredDiffs[rc] > 0) { + ans.push_back(false); + } else { + // The `count` map of the intersection of [a, b) and [rd, rc) in + // s[0..n / 2) must equate to the `count` map of the intersection of + // [c, d) and [rb, ra) in s[n / 2..n). + vector leftRangeCount = subtractArrays(counts[b], counts[a]); + vector rightRangeCount = subtractArrays(counts[d], counts[c]); + if (a > rd) + rightRangeCount = subtractArrays( + rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd])); + if (rc > b) + rightRangeCount = subtractArrays( + rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)])); + if (c > rb) + leftRangeCount = subtractArrays( + leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb])); + if (ra > d) + leftRangeCount = subtractArrays( + leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)])); + ans.push_back(ranges::all_of(leftRangeCount, [](int freq) { + return freq >= 0; + }) && ranges::all_of(rightRangeCount, [](int freq) { + return freq >= 0; + }) && leftRangeCount == rightRangeCount); + } + } + + return ans; + } + + private: + vector getMirroredDiffs(const string& s) { + vector diffs(1); + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) + diffs.push_back(diffs.back() + (s[i] != s[j] ? 1 : 0)); + return diffs; + } + + vector> getCounts(const string& s) { + vector count(26); + vector> counts{count}; + for (const char c : s) { + ++count[c - 'a']; + counts.push_back(count); + } + return counts; + } + + vector subtractArrays(const vector& a, const vector& b) { + vector res; + for (int i = 0; i < a.size(); ++i) + res.push_back(a[i] - b[i]); + return res; + } +}; diff --git a/solutions/2983. Palindrome Rearrangement Queries/2983.java b/solutions/2983. Palindrome Rearrangement Queries/2983.java new file mode 100644 index 00000000000..20f7984682d --- /dev/null +++ b/solutions/2983. Palindrome Rearrangement Queries/2983.java @@ -0,0 +1,81 @@ +class Solution { + public boolean[] canMakePalindromeQueries(String s, int[][] queries) { + final int n = s.length(); + // mirroredDiffs[i] := the number of different letters between the first i + // letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1] + final int[] mirroredDiffs = getMirroredDiffs(s); + // counts[i] := the count of s[0..i) + final int[][] counts = getCounts(s); + boolean[] ans = new boolean[queries.length]; + + for (int i = 0; i < queries.length; i++) { + // Use left-closed, right-open intervals to facilitate the calculation. + // ...... [a, b) ...|... [rb, ra) ...... + // .... [rd, rc) .....|..... [c, d) .... + int[] query = queries[i]; + final int a = query[0]; + final int b = query[1] + 1; + final int c = query[2]; + final int d = query[3] + 1; + final int ra = n - a; // the reflected index of a in s[n / 2..n) + final int rb = n - b; // the reflected index of b in s[n / 2..n) + final int rc = n - c; // the reflected index of c in s[n / 2..n) + final int rd = n - d; // the reflected index of d in s[n / 2..n) + // No difference is allowed outside the query ranges. + if ((Math.min(a, rd) > 0 && mirroredDiffs[Math.min(a, rd)] > 0) || + (n / 2 > Math.max(b, rc) && mirroredDiffs[n / 2] - mirroredDiffs[Math.max(b, rc)] > 0) || + (rd > b && mirroredDiffs[rd] - mirroredDiffs[b] > 0) || + (a > rc && mirroredDiffs[a] - mirroredDiffs[rc] > 0)) { + ans[i] = false; + } else { + // The `count` map of the intersection of [a, b) and [rd, rc) in + // s[0..n / 2) must equate to the `count` map of the intersection of + // [c, d) and [rb, ra) in s[n / 2..n). + int[] leftRangeCount = subtractArrays(counts[b], counts[a]); + int[] rightRangeCount = subtractArrays(counts[d], counts[c]); + if (a > rd) + rightRangeCount = + subtractArrays(rightRangeCount, subtractArrays(counts[Math.min(a, rc)], counts[rd])); + if (rc > b) + rightRangeCount = + subtractArrays(rightRangeCount, subtractArrays(counts[rc], counts[Math.max(b, rd)])); + if (c > rb) + leftRangeCount = + subtractArrays(leftRangeCount, subtractArrays(counts[Math.min(c, ra)], counts[rb])); + if (ra > d) + leftRangeCount = + subtractArrays(leftRangeCount, subtractArrays(counts[ra], counts[Math.max(d, rb)])); + ans[i] = Arrays.stream(leftRangeCount).allMatch(freq -> freq >= 0) && + Arrays.stream(rightRangeCount).allMatch(freq -> freq >= 0) && + Arrays.equals(leftRangeCount, rightRangeCount); + } + } + + return ans; + } + + private int[] getMirroredDiffs(final String s) { + int[] diffs = new int[s.length() / 2 + 1]; + for (int i = 0, j = s.length() - 1; i < j; i++, j--) { + diffs[i + 1] = diffs[i] + (s.charAt(i) != s.charAt(j) ? 1 : 0); + } + return diffs; + } + + private int[][] getCounts(final String s) { + int[][] counts = new int[s.length() + 1][26]; + int[] count = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++count[s.charAt(i) - 'a']; + System.arraycopy(count, 0, counts[i + 1], 0, 26); + } + return counts; + } + + private int[] subtractArrays(int[] a, int[] b) { + int[] res = new int[a.length]; + for (int i = 0; i < a.length; ++i) + res[i] = a[i] - b[i]; + return res; + } +} diff --git a/solutions/2983. Palindrome Rearrangement Queries/2983.py b/solutions/2983. Palindrome Rearrangement Queries/2983.py new file mode 100644 index 00000000000..694d59aa4af --- /dev/null +++ b/solutions/2983. Palindrome Rearrangement Queries/2983.py @@ -0,0 +1,68 @@ +class Solution: + def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]: + n = len(s) + # mirroredDiffs[i] := the number of different letters between the first i + # letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1] + mirroredDiffs = self._getMirroredDiffs(s) + # counts[i] := the count of s[0..i) + counts = self._getCounts(s) + ans = [] + + def subtractArrays(a: List[int], b: List[int]): + return [x - y for x, y in zip(a, b)] + + for a, b, c, d in queries: + # Use left-closed, right-open intervals to facilitate the calculation. + # ...... [a, b) ...|... [rb, ra) ...... + # .... [rd, rc) .....|..... [c, d) .... + b += 1 + d += 1 + ra = n - a # the reflected index of a in s[n / 2..n) + rb = n - b # the reflected index of b in s[n / 2..n) + rc = n - c # the reflected index of c in s[n / 2..n) + rd = n - d # the reflected index of d in s[n / 2..n) + # No difference is allowed outside the query ranges. + if (min(a, rd) > 0 and mirroredDiffs[min(a, rd)] > 0) or \ + (n // 2 > max(b, rc) and mirroredDiffs[n // 2] - mirroredDiffs[max(b, rc)] > 0) or \ + (rd > b and mirroredDiffs[rd] - mirroredDiffs[b] > 0) or \ + (a > rc and mirroredDiffs[a] - mirroredDiffs[rc] > 0): + ans.append(False) + else: + # The `count` map of the intersection of [a, b) and [rd, rc) in + # s[0..n / 2) must equate to the `count` map of the intersection of + # [c, d) and [rb, ra) in s[n / 2..n). + leftRangeCount = subtractArrays(counts[b], counts[a]) + rightRangeCount = subtractArrays(counts[d], counts[c]) + if a > rd: + rightRangeCount = subtractArrays( + rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd])) + if rc > b: + rightRangeCount = subtractArrays( + rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)])) + if c > rb: + leftRangeCount = subtractArrays( + leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb])) + if ra > d: + leftRangeCount = subtractArrays( + leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)])) + ans.append(min(leftRangeCount) >= 0 + and min(rightRangeCount) >= 0 + and leftRangeCount == rightRangeCount) + + return ans + + def _getMirroredDiffs(self, s: str) -> List[int]: + diffs = [0] + for i, j in zip(range(len(s)), reversed(range(len(s)))): + if i >= j: + break + diffs.append(diffs[-1] + (s[i] != s[j])) + return diffs + + def _getCounts(self, s: str) -> List[List[int]]: + count = [0] * 26 + counts = [count.copy()] + for c in s: + count[ord(c) - ord('a')] += 1 + counts.append(count.copy()) + return counts diff --git a/solutions/2984. Find Peak Calling Hours for Each City/2984.sql b/solutions/2984. Find Peak Calling Hours for Each City/2984.sql new file mode 100644 index 00000000000..c2554988591 --- /dev/null +++ b/solutions/2984. Find Peak Calling Hours for Each City/2984.sql @@ -0,0 +1,25 @@ +WITH + CityHourCount AS ( + SELECT + city, + HOUR(call_time) AS call_hour, + COUNT(*) AS number_of_calls + FROM Calls + GROUP BY 1, 2 + ), + RankedCityHourCount AS ( + SELECT + *, + RANK() OVER( + PARTITION BY city + ORDER BY number_of_calls DESC + ) AS `rank` + FROM CityHourCount + ) +SELECT + city, + call_hour AS peak_calling_hour, + number_of_calls +FROM RankedCityHourCount +WHERE `rank` = 1 +ORDER BY 2 DESC, 1 DESC; diff --git a/solutions/2985. Calculate Compressed Mean/2985.sql b/solutions/2985. Calculate Compressed Mean/2985.sql new file mode 100644 index 00000000000..c30d5947a41 --- /dev/null +++ b/solutions/2985. Calculate Compressed Mean/2985.sql @@ -0,0 +1,6 @@ +SELECT + ROUND( + SUM(item_count * order_occurrences) / SUM(order_occurrences), + 2 + ) AS average_items_per_order +FROM Orders; diff --git a/solutions/2986. Find Third Transaction/2986.sql b/solutions/2986. Find Third Transaction/2986.sql new file mode 100644 index 00000000000..9f05b608dc1 --- /dev/null +++ b/solutions/2986. Find Third Transaction/2986.sql @@ -0,0 +1,27 @@ +WITH + TransactionNeighbors AS ( + SELECT + user_id, + spend, + transaction_date, + RANK() OVER(PARTITION BY user_id ORDER BY transaction_date) AS date_rank, + FIRST_VALUE(spend) OVER( + PARTITION BY user_id + ORDER BY transaction_date + ) AS first_spend, + LAG(spend) OVER( + PARTITION BY user_id + ORDER BY transaction_date + ) AS second_spend + FROM Transactions + ) +SELECT + user_id, + spend AS third_transaction_spend, + transaction_date AS third_transaction_date +FROM TransactionNeighbors +WHERE + date_rank = 3 + AND spend > first_spend + AND spend > second_spend +ORDER BY 1; diff --git a/solutions/2987. Find Expensive Cities/2987.sql b/solutions/2987. Find Expensive Cities/2987.sql new file mode 100644 index 00000000000..9da5f031906 --- /dev/null +++ b/solutions/2987. Find Expensive Cities/2987.sql @@ -0,0 +1,5 @@ +SELECT city +FROM Listings +GROUP BY 1 +HAVING AVG(price) > (SELECT AVG(price) FROM Listings) +ORDER BY 1; diff --git a/solutions/2988. Manager of the Largest Department/2988.sql b/solutions/2988. Manager of the Largest Department/2988.sql new file mode 100644 index 00000000000..bb60470bad4 --- /dev/null +++ b/solutions/2988. Manager of the Largest Department/2988.sql @@ -0,0 +1,20 @@ +WITH + RankedDepartments AS ( + SELECT + dep_id, + DENSE_RANK() OVER( + ORDER BY COUNT(*) DESC + ) AS `rank` + FROM Employees + GROUP BY 1 + ) +SELECT + Employees.emp_name AS manager_name, + Employees.dep_id +FROM Employees +INNER JOIN RankedDepartments + USING (dep_id) +WHERE + Employees.position = 'Manager' + AND RankedDepartments.`rank` = 1 +ORDER BY dep_id; diff --git a/solutions/2989. Class Performance/2989.sql b/solutions/2989. Class Performance/2989.sql new file mode 100644 index 00000000000..6e7b637cd59 --- /dev/null +++ b/solutions/2989. Class Performance/2989.sql @@ -0,0 +1,7 @@ +WITH + TotalScores AS ( + SELECT assignment1 + assignment2 + assignment3 AS score + FROM Scores + ) +SELECT MAX(score) - MIN(score) AS difference_in_score +FROM TotalScores; diff --git a/solutions/299. Bulls and Cows/299.cpp b/solutions/299. Bulls and Cows/299.cpp new file mode 100644 index 00000000000..a180039cb0c --- /dev/null +++ b/solutions/299. Bulls and Cows/299.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + string getHint(string secret, string guess) { + int A = 0; + int B = 0; + vector count1(10); + vector count2(10); + + for (int i = 0; i < secret.length(); ++i) + if (secret[i] == guess[i]) + ++A; + else { + ++count1[secret[i] - '0']; + ++count2[guess[i] - '0']; + } + + for (int i = 0; i < 10; ++i) + B += min(count1[i], count2[i]); + + return to_string(A) + "A" + to_string(B) + "B"; + } +}; diff --git a/solutions/299. Bulls and Cows/299.java b/solutions/299. Bulls and Cows/299.java new file mode 100644 index 00000000000..085ba74dfc1 --- /dev/null +++ b/solutions/299. Bulls and Cows/299.java @@ -0,0 +1,21 @@ +class Solution { + public String getHint(String secret, String guess) { + int A = 0; + int B = 0; + int[] count1 = new int[10]; + int[] count2 = new int[10]; + + for (int i = 0; i < secret.length(); ++i) + if (secret.charAt(i) == guess.charAt(i)) + ++A; + else { + ++count1[secret.charAt(i) - '0']; + ++count2[guess.charAt(i) - '0']; + } + + for (int i = 0; i < 10; ++i) + B += Math.min(count1[i], count2[i]); + + return String.valueOf(A) + "A" + String.valueOf(B) + "B"; + } +} diff --git a/solutions/299. Bulls and Cows/299.py b/solutions/299. Bulls and Cows/299.py new file mode 100644 index 00000000000..7b4ffc7eb89 --- /dev/null +++ b/solutions/299. Bulls and Cows/299.py @@ -0,0 +1,5 @@ +class Solution: + def getHint(self, secret: str, guess: str) -> str: + bulls = sum(map(operator.eq, secret, guess)) + bovine = sum(min(secret.count(x), guess.count(x)) for x in set(guess)) + return '%dA%dB' % (bulls, bovine - bulls) diff --git a/solutions/2990. Loan Types/2990.sql b/solutions/2990. Loan Types/2990.sql new file mode 100644 index 00000000000..6828c27c409 --- /dev/null +++ b/solutions/2990. Loan Types/2990.sql @@ -0,0 +1,6 @@ +SELECT user_id +FROM Loans +WHERE loan_type IN ('Refinance', 'Mortgage') +GROUP BY 1 +HAVING COUNT(DISTINCT loan_type) = 2 +ORDER BY 1; diff --git a/solutions/2991. Top Three Wineries/2991.sql b/solutions/2991. Top Three Wineries/2991.sql new file mode 100644 index 00000000000..be676374825 --- /dev/null +++ b/solutions/2991. Top Three Wineries/2991.sql @@ -0,0 +1,35 @@ +WITH + WineryToTotalPoints AS ( + SELECT + country, + winery, + SUM(points) AS total_points + FROM Wineries + GROUP BY 1, 2 + ), + RankedWineries AS ( + SELECT + *, + RANK() OVER( + PARTITION BY country + ORDER BY total_points DESC, winery + ) AS `rank` + FROM WineryToTotalPoints + ) +SELECT + country, + MAX( + CASE WHEN `rank` = 1 THEN CONCAT(winery, ' (', total_points, ')') END + ) AS top_winery, + IFNULL( + MAX(CASE WHEN `rank` = 2 THEN CONCAT(winery, ' (', total_points, ')') END), + 'No second winery' + ) AS second_winery, + IFNULL( + MAX(CASE WHEN `rank` = 3 THEN CONCAT(winery, ' (', total_points, ')') END), + 'No third winery' + ) AS third_winery +FROM RankedWineries +WHERE `rank` <= 3 +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/2992. Number of Self-Divisible Permutations/2992.cpp b/solutions/2992. Number of Self-Divisible Permutations/2992.cpp new file mode 100644 index 00000000000..ac7830c80c8 --- /dev/null +++ b/solutions/2992. Number of Self-Divisible Permutations/2992.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int selfDivisiblePermutationCount(int n) { + return dfs(1, /*used=*/0, n); + } + + private: + int dfs(int num, int used, int n) { + if (num > n) + return 1; + + int count = 0; + for (int i = 1; i <= n; ++i) + if ((used >> i & 1) == 0 && (num % i == 0 || i % num == 0)) + count += dfs(num + 1, used | (1 << i), n); + + return count; + } +}; diff --git a/solutions/2992. Number of Self-Divisible Permutations/2992.java b/solutions/2992. Number of Self-Divisible Permutations/2992.java new file mode 100644 index 00000000000..063a61dc3d9 --- /dev/null +++ b/solutions/2992. Number of Self-Divisible Permutations/2992.java @@ -0,0 +1,17 @@ +class Solution { + public int selfDivisiblePermutationCount(int n) { + return dfs(1, /*used=*/0, n); + } + + private int dfs(int num, int used, int n) { + if (num > n) + return 1; + + int count = 0; + for (int i = 1; i <= n; i++) + if (((used >> i) & 1) == 0 && (num % i == 0 || i % num == 0)) + count += dfs(num + 1, used | (1 << i), n); + + return count; + } +} diff --git a/solutions/2992. Number of Self-Divisible Permutations/2992.py b/solutions/2992. Number of Self-Divisible Permutations/2992.py new file mode 100644 index 00000000000..3a4328d5ca7 --- /dev/null +++ b/solutions/2992. Number of Self-Divisible Permutations/2992.py @@ -0,0 +1,14 @@ +class Solution: + def selfDivisiblePermutationCount(self, n: int) -> int: + def dfs(num: int, used: int) -> int: + if num > n: + return 1 + + count = 0 + for i in range(1, n + 1): + if (used >> i & 1) == 0 and (num % i == 0 or i % num == 0): + count += dfs(num + 1, used | 1 << i) + + return count + + return dfs(1, 0) diff --git a/solutions/2993. Friday Purchases I/2993.sql b/solutions/2993. Friday Purchases I/2993.sql new file mode 100644 index 00000000000..99281e88a90 --- /dev/null +++ b/solutions/2993. Friday Purchases I/2993.sql @@ -0,0 +1,11 @@ +SELECT + WEEK(purchase_date, 1) - WEEK('2023-11-01', 1) + 1 AS week_of_month, + purchase_date, + SUM(amount_spend) AS total_amount +FROM Purchases +WHERE + DAYOFWEEK(purchase_date) = 6 + AND MONTH(purchase_date) = 11 + AND YEAR(purchase_date) = 2023 +GROUP BY purchase_date +ORDER BY week_of_month; diff --git a/solutions/2994. Friday Purchases II/2994.sql b/solutions/2994. Friday Purchases II/2994.sql new file mode 100644 index 00000000000..e1e3f52c3dd --- /dev/null +++ b/solutions/2994. Friday Purchases II/2994.sql @@ -0,0 +1,19 @@ +WITH + Recursive Fridays AS ( + -- the first Friday of November 2023 + SELECT '2023-11-03' AS friday + UNION ALL + SELECT DATE_ADD(friday, INTERVAL 7 DAY) + FROM Fridays + -- the last day of November 2023 - 7 days + WHERE friday < '2023-11-23' + ) +SELECT + WEEK(Fridays.friday, 1) - WEEK('2023-11-01', 1) + 1 AS week_of_month, + Fridays.friday AS purchase_date, + IFNULL(SUM(Purchases.amount_spend), 0) AS total_amount +FROM Fridays +LEFT JOIN Purchases + ON (Fridays.friday = Purchases.purchase_date) +GROUP BY Fridays.friday +ORDER BY week_of_month; diff --git a/solutions/2995. Viewers Turned Streamers/2995.sql b/solutions/2995. Viewers Turned Streamers/2995.sql new file mode 100644 index 00000000000..3c2950f9080 --- /dev/null +++ b/solutions/2995. Viewers Turned Streamers/2995.sql @@ -0,0 +1,22 @@ +WITH + FirstSessions AS ( + SELECT + user_id, + session_type, + RANK() OVER(PARTITION BY user_id ORDER BY session_start) AS session_rank + FROM Sessions + ), + ViewerFirst AS ( + SELECT user_id + FROM FirstSessions + WHERE session_rank = 1 AND session_type = 'Viewer' + ) +SELECT + Sessions.user_id, + COUNT(*) AS sessions_count +FROM Sessions +INNER JOIN ViewerFirst + USING (user_id) +WHERE Sessions.session_type = 'Streamer' +GROUP BY 1 +ORDER BY sessions_count DESC, Sessions.user_id DESC; diff --git a/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.cpp b/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.cpp new file mode 100644 index 00000000000..3a74c00f32f --- /dev/null +++ b/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int missingInteger(vector& nums) { + const unordered_set numsSet{nums.begin(), nums.end()}; + int ans = nums[0]; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] != nums[i - 1] + 1) + break; + ans += nums[i]; + } + + while (numsSet.contains(ans)) + ++ans; + + return ans; + } +}; diff --git a/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.java b/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.java new file mode 100644 index 00000000000..d74d36916c9 --- /dev/null +++ b/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.java @@ -0,0 +1,17 @@ +class Solution { + public int missingInteger(int[] nums) { + Set numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + int ans = nums[0]; + + for (int i = 1; i < nums.length; ++i) { + if (nums[i] != nums[i - 1] + 1) + break; + ans += nums[i]; + } + + while (numsSet.contains(ans)) + ++ans; + + return ans; + } +} diff --git a/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.py b/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.py new file mode 100644 index 00000000000..c1594d5c3f9 --- /dev/null +++ b/solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.py @@ -0,0 +1,14 @@ +class Solution: + def missingInteger(self, nums: List[int]) -> int: + numsSet = set(nums) + ans = nums[0] + + for i in range(1, len(nums)): + if nums[i] != nums[i - 1] + 1: + break + ans += nums[i] + + while ans in numsSet: + ans += 1 + + return ans diff --git a/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.cpp b/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.cpp new file mode 100644 index 00000000000..09e39868d27 --- /dev/null +++ b/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int minOperations(vector& nums, unsigned k) { + const unsigned xors = accumulate(nums.begin(), nums.end(), 0, bit_xor<>()); + return popcount(k ^ xors); + } +}; diff --git a/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.java b/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.java new file mode 100644 index 00000000000..8f3fdd64a74 --- /dev/null +++ b/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.java @@ -0,0 +1,6 @@ +class Solution { + public int minOperations(int[] nums, int k) { + final int xors = Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt(); + return Integer.bitCount(k ^ xors); + } +} diff --git a/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.py b/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.py new file mode 100644 index 00000000000..aabeb5b24d9 --- /dev/null +++ b/solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.py @@ -0,0 +1,3 @@ +class Solution: + def minOperations(self, nums: List[int], k: int) -> int: + return functools.reduce(operator.xor, nums, k).bit_count() diff --git a/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.cpp b/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.cpp new file mode 100644 index 00000000000..169fab04e12 --- /dev/null +++ b/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int minimumOperationsToMakeEqual(int x, int y) { + if (x <= y) + return y - x; + + queue q{{x}}; + unordered_set seen; + + for (int ans = 0; !q.empty(); ++ans) { + for (int sz = q.size(); sz > 0; --sz) { + const int num = q.front(); + q.pop(); + if (num == y) + return ans; + if (seen.find(num) != seen.end()) + continue; + seen.insert(num); + if (num % 11 == 0) + q.push(num / 11); + if (num % 5 == 0) + q.push(num / 5); + q.push(num - 1); + q.push(num + 1); + } + } + + throw; + } +}; diff --git a/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.java b/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.java new file mode 100644 index 00000000000..f254d7a8a19 --- /dev/null +++ b/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.java @@ -0,0 +1,28 @@ +class Solution { + public int minimumOperationsToMakeEqual(int x, int y) { + if (x <= y) + return y - x; + + Queue q = new ArrayDeque<>(Arrays.asList(x)); + Set seen = new HashSet<>(); + + for (int ans = 0; !q.isEmpty(); ++ans) { + for (int sz = q.size(); sz > 0; --sz) { + final int num = q.poll(); + if (num == y) + return ans; + if (seen.contains(num)) + continue; + seen.add(num); + if (num % 11 == 0) + q.offer(num / 11); + if (num % 5 == 0) + q.offer(num / 5); + q.offer(num - 1); + q.offer(num + 1); + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.py b/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.py new file mode 100644 index 00000000000..a709a72b86c --- /dev/null +++ b/solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.py @@ -0,0 +1,24 @@ +class Solution: + def minimumOperationsToMakeEqual(self, x, y): + if x <= y: + return y - x + + queue = collections.deque([x]) + seen = set() + + ans = 0 + while queue: + for _ in range(len(queue)): + num = queue.popleft() + if num == y: + return ans + if num in seen: + continue + seen.add(num) + if num % 11 == 0: + queue.append(num // 11) + if num % 5 == 0: + queue.append(num // 5) + queue.append(num - 1) + queue.append(num + 1) + ans += 1 diff --git a/solutions/2999. Count the Number of Powerful Integers/2999.cpp b/solutions/2999. Count the Number of Powerful Integers/2999.cpp new file mode 100644 index 00000000000..680c5eace7a --- /dev/null +++ b/solutions/2999. Count the Number of Powerful Integers/2999.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + long long numberOfPowerfulInt(long long start, long long finish, int limit, + string s) { + const string a = to_string(start); + const string b = to_string(finish); + const string aWithLeadingZeros = string(b.length() - a.length(), '0') + a; + vector>> mem( + b.length(), vector>(2, vector(2, -1))); + const string sWithLeadingZeros = string(b.length() - s.length(), '0') + s; + return count(aWithLeadingZeros, b, 0, limit, s, true, true, mem); + } + + private: + // Returns the number of powerful integers, considering the i-th digit, where + // `isTight1` indicates if the current digit is tightly bound for `a` and + // `isTight2` indicates if the current digit is tightly bound for `b`. + long count(const string& a, const string& b, int i, int limit, + const string& s, bool isTight1, bool isTight2, + vector>>& mem) { + if (i + s.length() == b.length()) { + const string aMinSuffix = isTight1 + ? std::string(a.end() - s.length(), a.end()) + : string(s.length(), '0'); + const string bMaxSuffix = isTight2 + ? std::string(b.end() - s.length(), b.end()) + : string(s.length(), '9'); + const long suffix = stoll(s); + return stoll(aMinSuffix) <= suffix && suffix <= stoll(bMaxSuffix); + } + + if (mem[i][isTight1][isTight2] != -1) + return mem[i][isTight1][isTight2]; + + long res = 0; + const int minDigit = isTight1 ? a[i] - '0' : 0; + const int maxDigit = isTight2 ? b[i] - '0' : 9; + + for (int d = minDigit; d <= maxDigit; ++d) { + if (d > limit) + continue; + const bool nextIsTight1 = isTight1 && (d == minDigit); + const bool nextIsTight2 = isTight2 && (d == maxDigit); + res += count(a, b, i + 1, limit, s, nextIsTight1, nextIsTight2, mem); + } + + return mem[i][isTight1][isTight2] = res; + } +}; diff --git a/solutions/3. Longest Substring Without Repeating Characters/3-2.cpp b/solutions/3. Longest Substring Without Repeating Characters/3-2.cpp new file mode 100644 index 00000000000..3ade16c9eb0 --- /dev/null +++ b/solutions/3. Longest Substring Without Repeating Characters/3-2.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int lengthOfLongestSubstring(string s) { + int ans = 0; + // The substring s[j + 1..i] has no repeating characters. + int j = -1; + // lastSeen[c] := the index of the last time c appeared + vector lastSeen(128, -1); + + for (int i = 0; i < s.length(); ++i) { + // Update j to lastSeen[s[i]], so the window must start from j + 1. + j = max(j, lastSeen[s[i]]); + ans = max(ans, i - j); + lastSeen[s[i]] = i; + } + + return ans; + } +}; diff --git a/solutions/3. Longest Substring Without Repeating Characters/3-2.java b/solutions/3. Longest Substring Without Repeating Characters/3-2.java new file mode 100644 index 00000000000..7d7963f2b59 --- /dev/null +++ b/solutions/3. Longest Substring Without Repeating Characters/3-2.java @@ -0,0 +1,19 @@ +class Solution { + public int lengthOfLongestSubstring(String s) { + int ans = 0; + // The substring s[j + 1..i] has no repeating characters. + int j = -1; + // lastSeen[c] := the index of the last time c appeared + int[] lastSeen = new int[128]; + Arrays.fill(lastSeen, -1); + + for (int i = 0; i < s.length(); ++i) { + // Update j to lastSeen[s.charAt(i)], so the window must start from j + 1. + j = Math.max(j, lastSeen[s.charAt(i)]); + ans = Math.max(ans, i - j); + lastSeen[s.charAt(i)] = i; + } + + return ans; + } +} diff --git a/solutions/3. Longest Substring Without Repeating Characters/3-2.py b/solutions/3. Longest Substring Without Repeating Characters/3-2.py new file mode 100644 index 00000000000..79276cefe09 --- /dev/null +++ b/solutions/3. Longest Substring Without Repeating Characters/3-2.py @@ -0,0 +1,15 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + ans = 0 + # The substring s[j + 1..i] has no repeating characters. + j = -1 + # lastSeen[c] := the index of the last time c appeared + lastSeen = {} + + for i, c in enumerate(s): + # Update j to lastSeen[c], so the window must start from j + 1. + j = max(j, lastSeen.get(c, -1)) + ans = max(ans, i - j) + lastSeen[c] = i + + return ans diff --git a/solutions/3. Longest Substring Without Repeating Characters/3.cpp b/solutions/3. Longest Substring Without Repeating Characters/3.cpp new file mode 100644 index 00000000000..09a0eb1b272 --- /dev/null +++ b/solutions/3. Longest Substring Without Repeating Characters/3.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int lengthOfLongestSubstring(string s) { + int ans = 0; + vector count(128); + + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s[r]]; + while (count[s[r]] > 1) + --count[s[l++]]; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/3. Longest Substring Without Repeating Characters/3.java b/solutions/3. Longest Substring Without Repeating Characters/3.java new file mode 100644 index 00000000000..99c0f0e9580 --- /dev/null +++ b/solutions/3. Longest Substring Without Repeating Characters/3.java @@ -0,0 +1,15 @@ +class Solution { + public int lengthOfLongestSubstring(String s) { + int ans = 0; + int[] count = new int[128]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s.charAt(r)]; + while (count[s.charAt(r)] > 1) + --count[s.charAt(l++)]; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/3. Longest Substring Without Repeating Characters/3.py b/solutions/3. Longest Substring Without Repeating Characters/3.py new file mode 100644 index 00000000000..32f38dbc4fc --- /dev/null +++ b/solutions/3. Longest Substring Without Repeating Characters/3.py @@ -0,0 +1,14 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + ans = 0 + count = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + while count[c] > 1: + count[s[l]] -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/30. Substring with Concatenation of All Words/30.cpp b/solutions/30. Substring with Concatenation of All Words/30.cpp new file mode 100644 index 00000000000..7fa8e70034a --- /dev/null +++ b/solutions/30. Substring with Concatenation of All Words/30.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector findSubstring(string s, vector& words) { + if (s.empty() || words.empty()) + return {}; + + const int k = words.size(); + const int n = words[0].length(); + vector ans; + unordered_map count; + + for (const string& word : words) + ++count[word]; + + for (int i = 0; i < s.length() - k * n + 1; ++i) { + unordered_map seen; + int j; + for (j = 0; j < k; ++j) { + const string& word = s.substr(i + j * n, n); + if (++seen[word] > count[word]) + break; + } + if (j == k) + ans.push_back(i); + } + + return ans; + } +}; diff --git a/solutions/30. Substring with Concatenation of All Words/30.java b/solutions/30. Substring with Concatenation of All Words/30.java new file mode 100644 index 00000000000..fb45d287d67 --- /dev/null +++ b/solutions/30. Substring with Concatenation of All Words/30.java @@ -0,0 +1,29 @@ +class Solution { + public List findSubstring(String s, String[] words) { + if (s.isEmpty() || words.length == 0) + return new ArrayList<>(); + + final int k = words.length; + final int n = words[0].length(); + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + + for (final String word : words) + count.merge(word, 1, Integer::sum); + + for (int i = 0; i <= s.length() - k * n; ++i) { + Map seen = new HashMap<>(); + int j = 0; + for (; j < k; ++j) { + final String word = s.substring(i + j * n, i + j * n + n); + seen.merge(word, 1, Integer::sum); + if (seen.get(word) > count.getOrDefault(word, 0)) + break; + } + if (j == k) + ans.add(i); + } + + return ans; + } +} diff --git a/solutions/30. Substring with Concatenation of All Words/30.py b/solutions/30. Substring with Concatenation of All Words/30.py new file mode 100644 index 00000000000..b207cea2015 --- /dev/null +++ b/solutions/30. Substring with Concatenation of All Words/30.py @@ -0,0 +1,23 @@ +class Solution: + def findSubstring(self, s: str, words: List[str]) -> List[int]: + if len(s) == 0 or words == []: + return [] + + k = len(words) + n = len(words[0]) + ans = [] + count = collections.Counter(words) + + for i in range(len(s) - k * n + 1): + seen = collections.defaultdict(int) + j = 0 + while j < k: + word = s[i + j * n: i + j * n + n] + seen[word] += 1 + if seen[word] > count[word]: + break + j += 1 + if j == k: + ans.append(i) + + return ans diff --git a/solutions/300. Longest Increasing Subsequence/300-2.cpp b/solutions/300. Longest Increasing Subsequence/300-2.cpp new file mode 100644 index 00000000000..5f130db1e9c --- /dev/null +++ b/solutions/300. Longest Increasing Subsequence/300-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int lengthOfLIS(vector& nums) { + // tails[i] := the minimum tail of all the increasing subsequences having + // length i + 1 + vector tails; + + for (const int num : nums) + if (tails.empty() || num > tails.back()) + tails.push_back(num); + else + tails[firstGreaterEqual(tails, num)] = num; + + return tails.size(); + } + + private: + int firstGreaterEqual(const vector& A, int target) { + return ranges::lower_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/300. Longest Increasing Subsequence/300-2.java b/solutions/300. Longest Increasing Subsequence/300-2.java new file mode 100644 index 00000000000..b8a3306cbdb --- /dev/null +++ b/solutions/300. Longest Increasing Subsequence/300-2.java @@ -0,0 +1,20 @@ +class Solution { + public int lengthOfLIS(int[] nums) { + // tails[i] := the minimum tail of all the increasing subsequences having + // length i + 1 + List tails = new ArrayList<>(); + + for (final int num : nums) + if (tails.isEmpty() || num > tails.get(tails.size() - 1)) + tails.add(num); + else + tails.set(firstGreaterEqual(tails, num), num); + + return tails.size(); + } + + private int firstGreaterEqual(List A, int target) { + final int i = Collections.binarySearch(A, target); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/300. Longest Increasing Subsequence/300-2.py b/solutions/300. Longest Increasing Subsequence/300-2.py new file mode 100644 index 00000000000..de534335d9b --- /dev/null +++ b/solutions/300. Longest Increasing Subsequence/300-2.py @@ -0,0 +1,13 @@ +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + # tails[i] := the minimum tails of all the increasing subsequences having + # length i + 1 + tails = [] + + for num in nums: + if not tails or num > tails[-1]: + tails.append(num) + else: + tails[bisect.bisect_left(tails, num)] = num + + return len(tails) diff --git a/solutions/300. Longest Increasing Subsequence/300.cpp b/solutions/300. Longest Increasing Subsequence/300.cpp new file mode 100644 index 00000000000..219104c6134 --- /dev/null +++ b/solutions/300. Longest Increasing Subsequence/300.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int lengthOfLIS(vector& nums) { + if (nums.empty()) + return 0; + + // dp[i] := the length of LIS ending in nums[i] + vector dp(nums.size(), 1); + + for (int i = 1; i < nums.size(); ++i) + for (int j = 0; j < i; ++j) + if (nums[j] < nums[i]) + dp[i] = max(dp[i], dp[j] + 1); + + return ranges::max(dp); + } +}; diff --git a/solutions/300. Longest Increasing Subsequence/300.java b/solutions/300. Longest Increasing Subsequence/300.java new file mode 100644 index 00000000000..6cfa01341c6 --- /dev/null +++ b/solutions/300. Longest Increasing Subsequence/300.java @@ -0,0 +1,17 @@ +class Solution { + public int lengthOfLIS(int[] nums) { + if (nums.length == 0) + return 0; + + // dp[i] := the length of LIS ending in nums[i] + int[] dp = new int[nums.length]; + Arrays.fill(dp, 1); + + for (int i = 1; i < nums.length; ++i) + for (int j = 0; j < i; ++j) + if (nums[j] < nums[i]) + dp[i] = Math.max(dp[i], dp[j] + 1); + + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/300. Longest Increasing Subsequence/300.py b/solutions/300. Longest Increasing Subsequence/300.py new file mode 100644 index 00000000000..fb0d4b218d1 --- /dev/null +++ b/solutions/300. Longest Increasing Subsequence/300.py @@ -0,0 +1,14 @@ +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + if not nums: + return 0 + + # dp[i] the length of LIS ending in nums[i] + dp = [1] * len(nums) + + for i in range(1, len(nums)): + for j in range(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + + return max(dp) diff --git a/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.cpp b/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.cpp new file mode 100644 index 00000000000..c46806cddbc --- /dev/null +++ b/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int areaOfMaxDiagonal(vector>& dimensions) { + const vector maxDimension = *ranges::max_element( + dimensions, [](const vector& a, const vector& b) { + return (a[0] * a[0] + a[1] * a[1] == b[0] * b[0] + b[1] * b[1]) + ? (a[0] * a[1] < b[0] * b[1]) + : (a[0] * a[0] + a[1] * a[1] < b[0] * b[0] + b[1] * b[1]); + }); + return maxDimension[0] * maxDimension[1]; + } +}; diff --git a/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.java b/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.java new file mode 100644 index 00000000000..3c31207338b --- /dev/null +++ b/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.java @@ -0,0 +1,12 @@ +class Solution { + public int areaOfMaxDiagonal(int[][] dimensions) { + int[] maxDimension = + Arrays.stream(dimensions) + .max((a, b) + -> a[0] * a[0] + a[1] * a[1] == b[0] * b[0] + b[1] * b[1] + ? Integer.compare(a[0] * a[1], b[0] * b[1]) + : Integer.compare(a[0] * a[0] + a[1] * a[1], b[0] * b[0] + b[1] * b[1])) + .orElseThrow(); + return maxDimension[0] * maxDimension[1]; + } +} diff --git a/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.py b/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.py new file mode 100644 index 00000000000..6ae78343eb2 --- /dev/null +++ b/solutions/3000. Maximum Area of Longest Diagonal Rectangle/3000.py @@ -0,0 +1,4 @@ +class Solution: + def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int: + a, b = max(dimensions, key=lambda x: (x[0]**2 + x[1]**2, x[0] * x[1])) + return a * b diff --git a/solutions/3001. Minimum Moves to Capture The Queen/3001.cpp b/solutions/3001. Minimum Moves to Capture The Queen/3001.cpp new file mode 100644 index 00000000000..9de5e81b7d0 --- /dev/null +++ b/solutions/3001. Minimum Moves to Capture The Queen/3001.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { + // The rook is in the same row as the queen. + if (a == e) + // The bishop blocks the rook or not. + return (c == a && (b < d && d < f || b > d && d > f)) ? 2 : 1; + // The rook is in the same column as the queen. + if (b == f) + // The bishop blocks the rook or not. + return (d == f && (a < c && c < e || a > c && c > e)) ? 2 : 1; + // The bishop is in the same up-diagonal as the queen. + if (c + d == e + f) + // The rook blocks the bishop or not. + return (a + b == c + d && (c < a && a < e || c > a && a > e)) ? 2 : 1; + // The bishop is in the same down-diagonal as the queen. + if (c - d == e - f) + // The rook blocks the bishop or not. + return (a - b == c - d && (c < a && a < e || c > a && a > e)) ? 2 : 1; + // The rook can always get the green in two steps. + return 2; + } +}; diff --git a/solutions/3001. Minimum Moves to Capture The Queen/3001.java b/solutions/3001. Minimum Moves to Capture The Queen/3001.java new file mode 100644 index 00000000000..108239aac1e --- /dev/null +++ b/solutions/3001. Minimum Moves to Capture The Queen/3001.java @@ -0,0 +1,22 @@ +class Solution { + public int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { + // The rook is in the same row as the queen. + if (a == e) + // The bishop blocks the rook or not. + return (c == a && (b < d && d < f || b > d && d > f)) ? 2 : 1; + // The rook is in the same column as the queen. + if (b == f) + // The bishop blocks the rook or not. + return (d == f && (a < c && c < e || a > c && c > e)) ? 2 : 1; + // The bishop is in the same up-diagonal as the queen. + if (c + d == e + f) + // The rook blocks the bishop or not. + return (a + b == c + d && (c < a && a < e || c > a && a > e)) ? 2 : 1; + // The bishop is in the same down-diagonal as the queen. + if (c - d == e - f) + // The rook blocks the bishop or not. + return (a - b == c - d && (c < a && a < e || c > a && a > e)) ? 2 : 1; + // The rook can always get the green in two steps. + return 2; + } +} diff --git a/solutions/3001. Minimum Moves to Capture The Queen/3001.py b/solutions/3001. Minimum Moves to Capture The Queen/3001.py new file mode 100644 index 00000000000..6122f8fa30f --- /dev/null +++ b/solutions/3001. Minimum Moves to Capture The Queen/3001.py @@ -0,0 +1,20 @@ +class Solution: + def minMovesToCaptureTheQueen(self, a: int, b: int, c: int, d: int, e: int, f: int) -> int: + # The rook is in the same row as the queen. + if a == e: + # The bishop blocks the rook or not. + return 2 if c == a and (b < d < f or b > d > f) else 1 + # The rook is in the same column as the queen. + if b == f: + # The bishop blocks the rook or not. + return 2 if d == f and (a < c < e or a > c > e) else 1 + # The bishop is in the same up-diagonal as the queen. + if c + d == e + f: + # The rook blocks the bishop or not. + return 2 if a + b == c + d and (c < a < e or c > a > e) else 1 + # The bishop is in the same down-diagonal as the queen. + if c - d == e - f: + # The rook blocks the bishop or not. + return 2 if a - b == c - d and (c < a < e or c > a > e) else 1 + # The rook can always get the green in two steps. + return 2 diff --git a/solutions/3002. Maximum Size of a Set After Removals/3002.cpp b/solutions/3002. Maximum Size of a Set After Removals/3002.cpp new file mode 100644 index 00000000000..9cc3fc24c3e --- /dev/null +++ b/solutions/3002. Maximum Size of a Set After Removals/3002.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maximumSetSize(vector& nums1, vector& nums2) { + const unordered_set set1{nums1.begin(), nums1.end()}; + const unordered_set set2{nums2.begin(), nums2.end()}; + unordered_set common; + + for (const int num1 : set1) + if (set2.contains(num1)) + common.insert(num1); + + const int n = nums1.size(); + const int n1 = set1.size(); + const int n2 = set2.size(); + const int nc = common.size(); + const int maxUniqueNums1 = min(n1 - nc, n / 2); + const int maxUniqueNums2 = min(n2 - nc, n / 2); + return min(n, maxUniqueNums1 + maxUniqueNums2 + nc); + } +}; diff --git a/solutions/3002. Maximum Size of a Set After Removals/3002.java b/solutions/3002. Maximum Size of a Set After Removals/3002.java new file mode 100644 index 00000000000..5ef86d78c99 --- /dev/null +++ b/solutions/3002. Maximum Size of a Set After Removals/3002.java @@ -0,0 +1,19 @@ +class Solution { + public int maximumSetSize(int[] nums1, int[] nums2) { + Set set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet()); + Set set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet()); + Set common = new HashSet<>(); + + for (final int num1 : set1) + if (set2.contains(num1)) + common.add(num1); + + final int n = nums1.length; + final int n1 = set1.size(); + final int n2 = set2.size(); + final int nc = common.size(); + final int maxUniqueNums1 = Math.min(n1 - nc, n / 2); + final int maxUniqueNums2 = Math.min(n2 - nc, n / 2); + return Math.min(n, maxUniqueNums1 + maxUniqueNums2 + nc); + } +} diff --git a/solutions/3002. Maximum Size of a Set After Removals/3002.py b/solutions/3002. Maximum Size of a Set After Removals/3002.py new file mode 100644 index 00000000000..8239168004b --- /dev/null +++ b/solutions/3002. Maximum Size of a Set After Removals/3002.py @@ -0,0 +1,13 @@ +class Solution: + def maximumSetSize(self, nums1: List[int], nums2: List[int]) -> int: + set1 = set(nums1) + set2 = set(nums2) + common = set1.intersection(set2) + + n = len(nums1) + n1 = len(set1) + n2 = len(set2) + nc = len(common) + maxUniqueNums1 = min(n1 - nc, n // 2) + maxUniqueNums2 = min(n2 - nc, n // 2) + return min(n, maxUniqueNums1 + maxUniqueNums2 + nc) diff --git a/solutions/3003. Maximize the Number of Partitions After Operations/3003.cpp b/solutions/3003. Maximize the Number of Partitions After Operations/3003.cpp new file mode 100644 index 00000000000..1f82a9b74d0 --- /dev/null +++ b/solutions/3003. Maximize the Number of Partitions After Operations/3003.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int maxPartitionsAfterOperations(string s, int k) { + unordered_map mem; + return maxPartitionsAfterOperations(s, 0, true, 0, k, mem) + 1; + } + + private: + // Returns the maximum number of partitions of s[i..n), where `canChange` is + // true if we can still change a letter, and `mask` is the bitmask of the + // letters we've seen. + int maxPartitionsAfterOperations(const string& s, int i, bool canChange, + int mask, int k, + unordered_map& mem) { + if (i == s.length()) + return 0; + + long key = static_cast(i) << 27 | (canChange ? 1 : 0) << 26 | mask; + if (const auto it = mem.find(key); it != mem.end()) + return it->second; + + // Initialize the result based on the current letter. + int res = getRes(s, i, canChange, mask, 1 << (s[i] - 'a'), k, mem); + + // If allowed, explore the option to change the current letter. + if (canChange) + for (int j = 0; j < 26; ++j) + res = max(res, getRes(s, i, false, mask, 1 << j, k, mem)); + + return mem[key] = res; + } + + int getRes(const string& s, int i, bool nextCanChange, unsigned mask, + int newBit, int k, unordered_map& mem) { + const unsigned nextMask = mask | newBit; + if (popcount(nextMask) > k) // fresh start + return 1 + maxPartitionsAfterOperations(s, i + 1, nextCanChange, newBit, + k, mem); + return maxPartitionsAfterOperations(s, i + 1, nextCanChange, nextMask, k, + mem); + } +}; diff --git a/solutions/3003. Maximize the Number of Partitions After Operations/3003.java b/solutions/3003. Maximize the Number of Partitions After Operations/3003.java new file mode 100644 index 00000000000..4f87f305847 --- /dev/null +++ b/solutions/3003. Maximize the Number of Partitions After Operations/3003.java @@ -0,0 +1,38 @@ +class Solution { + public int maxPartitionsAfterOperations(String s, int k) { + Map mem = new HashMap<>(); + return maxPartitionsAfterOperations(s, 0, true, 0, k, mem) + 1; + } + + // Returns the maximum number of partitions of s[i..n), where `canChange` is + // true if we can still change a letter, and `mask` is the bitmask of the + // letters we've seen. + private int maxPartitionsAfterOperations(final String s, int i, boolean canChange, int mask, + int k, Map mem) { + if (i == s.length()) + return 0; + + Long key = (long) i << 27 | (canChange ? 1 : 0) << 26 | mask; + if (mem.containsKey(key)) + return mem.get(key); + + // Initialize the result based on the current letter. + int res = getRes(s, i, canChange, mask, 1 << (s.charAt(i) - 'a'), k, mem); + + // If allowed, explore the option to change the current letter. + if (canChange) + for (int j = 0; j < 26; ++j) + res = Math.max(res, getRes(s, i, false, mask, 1 << j, k, mem)); + + mem.put(key, res); + return res; + } + + private int getRes(final String s, int i, boolean nextCanChange, int mask, int newBit, int k, + Map mem) { + final int nextMask = mask | newBit; + if (Integer.bitCount(nextMask) > k) // fresh start + return 1 + maxPartitionsAfterOperations(s, i + 1, nextCanChange, newBit, k, mem); + return maxPartitionsAfterOperations(s, i + 1, nextCanChange, nextMask, k, mem); + } +} diff --git a/solutions/3003. Maximize the Number of Partitions After Operations/3003.py b/solutions/3003. Maximize the Number of Partitions After Operations/3003.py new file mode 100644 index 00000000000..0c8210e653c --- /dev/null +++ b/solutions/3003. Maximize the Number of Partitions After Operations/3003.py @@ -0,0 +1,28 @@ +class Solution: + def maxPartitionsAfterOperations(self, s: str, k: int) -> int: + @functools.lru_cache(None) + def dp(i: int, canChange: bool, mask: int) -> int: + """ + Returns the maximum number of partitions of s[i..n), where `canChange` is + True if we can still change a letter, and `mask` is the bitmask of the + letters we've seen. + """ + if i == len(s): + return 0 + + def getRes(newBit: int, nextCanChange: bool) -> int: + nextMask = mask | newBit + if nextMask.bit_count() > k: + return 1 + dp(i + 1, nextCanChange, newBit) + return dp(i + 1, nextCanChange, nextMask) + + # Initialize the result based on the current letter. + res = getRes(1 << (ord(s[i]) - ord('a')), canChange) + + # If allowed, explore the option to change the current letter. + if canChange: + for j in range(26): + res = max(res, getRes(1 << j, False)) + return res + + return dp(0, True, 0) + 1 diff --git a/solutions/3004. Maximum Subtree of the Same Color/3004.cpp b/solutions/3004. Maximum Subtree of the Same Color/3004.cpp new file mode 100644 index 00000000000..3362d8ab079 --- /dev/null +++ b/solutions/3004. Maximum Subtree of the Same Color/3004.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int maximumSubtreeSize(vector>& edges, vector& colors) { + int ans = 1; + vector> tree(colors.size()); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].push_back(v); + } + + dfs(tree, 0, colors, ans); + return ans; + } + + private: + // Returns the size of subtree of u if every node in the subtree has the same + // color. Otherwise, returns -1. + int dfs(const vector>& tree, int u, const vector& colors, + int& ans) { + int res = 1; + for (const int v : tree[u]) { + if (colors[v] != colors[u]) + res = -1; + // If any node in the subtree of v has a different color, the result of + // the subtree of u will be -1 as well. + const int subtreeSize = dfs(tree, v, colors, ans); + if (subtreeSize == -1) + res = -1; + else if (res != -1) + res += subtreeSize; + } + ans = max(ans, res); + return res; + } +}; diff --git a/solutions/3004. Maximum Subtree of the Same Color/3004.java b/solutions/3004. Maximum Subtree of the Same Color/3004.java new file mode 100644 index 00000000000..d03e60d1e06 --- /dev/null +++ b/solutions/3004. Maximum Subtree of the Same Color/3004.java @@ -0,0 +1,38 @@ +class Solution { + public int maximumSubtreeSize(int[][] edges, int[] colors) { + List[] tree = new ArrayList[colors.length]; + + for (int i = 0; i < colors.length; ++i) + tree[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + } + + dfs(tree, 0, colors); + return ans; + } + + private int ans = 1; + + // Returns the size of subtree of u if every node in the subtree has the same + // color. Otherwise, returns -1. + private int dfs(List[] tree, int u, int[] colors) { + int res = 1; + for (int v : tree[u]) { + if (colors[v] != colors[u]) + res = -1; + // If any node in the subtree of v has a different color, the result of + // the subtree of u will be -1 as well. + int subtreeSize = dfs(tree, v, colors); + if (subtreeSize == -1) + res = -1; + else if (res != -1) + res += subtreeSize; + } + ans = Math.max(ans, res); + return res; + } +} diff --git a/solutions/3004. Maximum Subtree of the Same Color/3004.py b/solutions/3004. Maximum Subtree of the Same Color/3004.py new file mode 100644 index 00000000000..78c852b14c9 --- /dev/null +++ b/solutions/3004. Maximum Subtree of the Same Color/3004.py @@ -0,0 +1,30 @@ +class Solution: + def maximumSubtreeSize(self, edges: List[List[int]], colors: List[int]) -> int: + ans = 1 + tree = [[] for _ in range(len(colors))] + + for u, v in edges: + tree[u].append(v) + + def dfs(u: int) -> int: + """ + Returns the size of subtree of u if every node in the subtree has the same + color. Otherwise, returns -1. + """ + nonlocal ans + res = 1 + for v in tree[u]: + if colors[v] != colors[u]: + res = -1 + # If any node in the subtree of v has a different color, the result of + # the subtree of u will be -1 as well. + subtreeSize = dfs(v) + if subtreeSize == -1: + res = -1 + elif res != -1: + res += subtreeSize + ans = max(ans, res) + return res + + dfs(0) + return ans diff --git a/solutions/3005. Count Elements With Maximum Frequency/3005.cpp b/solutions/3005. Count Elements With Maximum Frequency/3005.cpp new file mode 100644 index 00000000000..611c12f9164 --- /dev/null +++ b/solutions/3005. Count Elements With Maximum Frequency/3005.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int maxFrequencyElements(vector& nums) { + constexpr int kMax = 100; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + const int maxFreq = ranges::max(count); + return ranges::count(count, maxFreq) * maxFreq; + } +}; diff --git a/solutions/3005. Count Elements With Maximum Frequency/3005.java b/solutions/3005. Count Elements With Maximum Frequency/3005.java new file mode 100644 index 00000000000..148e1199ee2 --- /dev/null +++ b/solutions/3005. Count Elements With Maximum Frequency/3005.java @@ -0,0 +1,18 @@ +class Solution { + public int maxFrequencyElements(int[] nums) { + final int kMax = 100; + int ans = 0; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + final int maxFreq = Arrays.stream(count).max().getAsInt(); + + for (final int freq : count) + if (freq == maxFreq) + ans += maxFreq; + + return ans; + } +} diff --git a/solutions/3005. Count Elements With Maximum Frequency/3005.py b/solutions/3005. Count Elements With Maximum Frequency/3005.py new file mode 100644 index 00000000000..875c14f9f5d --- /dev/null +++ b/solutions/3005. Count Elements With Maximum Frequency/3005.py @@ -0,0 +1,5 @@ +class Solution: + def maxFrequencyElements(self, nums: List[int]) -> int: + count = collections.Counter(nums) + maxFreq = max(count.values()) + return sum(freq == maxFreq for freq in count.values()) * maxFreq diff --git a/solutions/3006. Find Beautiful Indices in the Given Array I/3006.cpp b/solutions/3006. Find Beautiful Indices in the Given Array I/3006.cpp new file mode 100644 index 00000000000..bbfaf9e4517 --- /dev/null +++ b/solutions/3006. Find Beautiful Indices in the Given Array I/3006.cpp @@ -0,0 +1,61 @@ +class Solution { + public: + vector beautifulIndices(string s, string a, string b, int k) { + vector ans; + const vector indicesA = kmp(s, a); + const vector indicesB = kmp(s, b); + int indicesBIndex = 0; // indicesB's index + + for (const int i : indicesA) { + // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move + // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. + while (indicesBIndex < indicesB.size() && + indicesB[indicesBIndex] - i < -k) + ++indicesBIndex; + if (indicesBIndex < indicesB.size() && indicesB[indicesBIndex] - i <= k) + ans.push_back(i); + } + + return ans; + } + + private: + // Returns the starting indices of all occurrences of the pattern in `s`. + vector kmp(const string& s, const string& pattern) { + vector res; + const vector lps = getLPS(pattern); + int i = 0; // s' index + int j = 0; // pattern's index + while (i < s.length()) { + if (s[i] == pattern[j]) { + ++i; + ++j; + if (j == pattern.length()) { + res.push_back(i - j); + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + vector getLPS(const string& pattern) { + vector lps(pattern.length()); + for (int i = 1, j = 0; i < pattern.length(); ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +}; diff --git a/solutions/3006. Find Beautiful Indices in the Given Array I/3006.java b/solutions/3006. Find Beautiful Indices in the Given Array I/3006.java new file mode 100644 index 00000000000..2dd3280a72d --- /dev/null +++ b/solutions/3006. Find Beautiful Indices in the Given Array I/3006.java @@ -0,0 +1,58 @@ +class Solution { + public List beautifulIndices(String s, String a, String b, int k) { + List ans = new ArrayList<>(); + List indicesA = kmp(s, a); + List indicesB = kmp(s, b); + int indicesBIndex = 0; // indicesB' index + + for (final int i : indicesA) { + // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move + // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. + while (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i < -k) + ++indicesBIndex; + if (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i <= k) + ans.add(i); + } + + return ans; + } + + // Returns the starting indices of all occurrences of the pattern in `s`. + private List kmp(final String s, final String pattern) { + List res = new ArrayList<>(); + int[] lps = getLPS(pattern); + int i = 0; // s' index + int j = 0; // pattern's index + while (i < s.length()) { + if (s.charAt(i) == pattern.charAt(j)) { + ++i; + ++j; + if (j == pattern.length()) { + res.add(i - j); + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j != 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + private int[] getLPS(final String pattern) { + int[] lps = new int[pattern.length()]; + for (int i = 1, j = 0; i < pattern.length(); ++i) { + while (j > 0 && pattern.charAt(j) != pattern.charAt(i)) + j = lps[j - 1]; + if (pattern.charAt(i) == pattern.charAt(j)) + lps[i] = ++j; + } + return lps; + } +} diff --git a/solutions/3006. Find Beautiful Indices in the Given Array I/3006.py b/solutions/3006. Find Beautiful Indices in the Given Array I/3006.py new file mode 100644 index 00000000000..fbb1e445569 --- /dev/null +++ b/solutions/3006. Find Beautiful Indices in the Given Array I/3006.py @@ -0,0 +1,53 @@ +class Solution: + def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]: + ans = [] + indicesA = self._kmp(s, a) + indicesB = self._kmp(s, b) + indicesBIndex = 0 # indicesB' index + + for i in indicesA: + # The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move + # `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. + while indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i < -k: + indicesBIndex += 1 + if indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i <= k: + ans.append(i) + + return ans + + def _kmp(self, s: str, pattern: str) -> List[int]: + """Returns the starting indices of all occurrences of the pattern in `s`.""" + + def getLPS(pattern: str) -> List[int]: + """ + Returns the lps array, where lps[i] is the length of the longest prefix of + pattern[0..i] which is also a suffix of this substring. + """ + lps = [0] * len(pattern) + j = 0 + for i in range(1, len(pattern)): + while j > 0 and pattern[j] != pattern[i]: + j = lps[j - 1] + if pattern[i] == pattern[j]: + lps[i] = j + 1 + j += 1 + return lps + + res = [] + lps = getLPS(pattern) + i = 0 # s' index + j = 0 # pattern's index + while i < len(s): + if s[i] == pattern[j]: + i += 1 + j += 1 + if j == len(pattern): + res.append(i - j) + j = lps[j - 1] + # Mismatch after j matches. + elif j != 0: + # Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1] + else: + i += 1 + return res diff --git a/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.cpp b/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.cpp new file mode 100644 index 00000000000..158b1433a88 --- /dev/null +++ b/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + long long findMaximumNumber(long long k, int x) { + long l = 1; + long r = 1e15; + + while (l < r) { + const long m = (l + r + 1) / 2; + if (getSumPrices(m, x) > k) + r = m - 1; + else + l = m; + } + + return l; + } + + private: + // Returns the sum of prices of all numbers from 1 to `num`. + long getSumPrices(long num, int x) { + long sumPrices = 0; + // Increment `num` to account the 0-th row in the count of groups. + ++num; + for (int i = leftmostColumnIndex(num); i > 0; --i) + // If the current column is valid, count the number of 1s in this column. + if (i % x == 0) { + const long groupSize = 1L << i; + const long halfGroupSize = 1L << i - 1; + sumPrices += num / groupSize * halfGroupSize; + sumPrices += max(0L, (num % groupSize) - halfGroupSize); + } + return sumPrices; + } + + // Returns the leftmost column index in 1-indexed. + int leftmostColumnIndex(long num) { + return 63 - __builtin_clzl(num) + 1; + } +}; diff --git a/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.java b/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.java new file mode 100644 index 00000000000..ced7a956e3c --- /dev/null +++ b/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.java @@ -0,0 +1,35 @@ +class Solution { + public long findMaximumNumber(long k, int x) { + long l = 1; + long r = 1000000000000000L; + + while (l < r) { + final long m = (l + r + 1) / 2; + if (getSumPrices(m, x) > k) + r = m - 1; + else + l = m; + } + + return l; + } + + // Returns the sum of prices of all numbers from 1 to `num`. + private long getSumPrices(long num, int x) { + long sumPrices = 0; + num++; // Increment `num` to account the 0-th row in the count of groups. + for (int i = leftmostColumnIndex(num); i > 0; --i) + if (i % x == 0) { + final long groupSize = 1L << i; + final long halfGroupSize = 1L << i - 1; + sumPrices += num / groupSize * halfGroupSize; + sumPrices += Math.max(0L, (num % groupSize) - halfGroupSize); + } + return sumPrices; + } + + // Returns the leftmost column index in 1-indexed. + private int leftmostColumnIndex(long num) { + return 63 - Long.numberOfLeadingZeros(num) + 1; + } +} diff --git a/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.py b/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.py new file mode 100644 index 00000000000..8f3257f824b --- /dev/null +++ b/solutions/3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K/3007.py @@ -0,0 +1,17 @@ +class Solution: + def findMaximumNumber(self, k: int, x: int) -> int: + def getSumPrices(num: int) -> int: + """Returns the sum of prices of all numbers from 1 to `num`.""" + sumPrices = 0 + # Increment `num` to account the 0-th row in the count of groups. + num += 1 + for i in range(num.bit_length(), 0, -1): + if i % x == 0: + groupSize = 1 << i + halfGroupSize = 1 << i - 1 + sumPrices += num // groupSize * halfGroupSize + sumPrices += max(0, (num % groupSize) - halfGroupSize) + return sumPrices + + return bisect.bisect_right(range(1, 10**15), k, + key=lambda m: getSumPrices(m)) diff --git a/solutions/3008. Find Beautiful Indices in the Given Array II/3008.cpp b/solutions/3008. Find Beautiful Indices in the Given Array II/3008.cpp new file mode 100644 index 00000000000..0c915b72510 --- /dev/null +++ b/solutions/3008. Find Beautiful Indices in the Given Array II/3008.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + // Same as 3006. Find Beautiful Indices in the Given Array I + vector beautifulIndices(string s, string a, string b, int k) { + vector ans; + const vector indicesA = kmp(s, a); + const vector indicesB = kmp(s, b); + int indicesBIndex = 0; // indicesB's index + + for (const int i : indicesA) { + // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move + // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. + while (indicesBIndex < indicesB.size() && + indicesB[indicesBIndex] - i < -k) + ++indicesBIndex; + if (indicesBIndex < indicesB.size() && indicesB[indicesBIndex] - i <= k) + ans.push_back(i); + } + + return ans; + } + + private: + // Returns the starting indices of all occurrences of the pattern in `s`. + vector kmp(const string& s, const string& pattern) { + vector res; + const vector lps = getLPS(pattern); + int i = 0; // s' index + int j = 0; // pattern's index + while (i < s.length()) { + if (s[i] == pattern[j]) { + ++i; + ++j; + if (j == pattern.length()) { + res.push_back(i - j); + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + vector getLPS(const string& pattern) { + vector lps(pattern.length()); + for (int i = 1, j = 0; i < pattern.length(); ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +}; diff --git a/solutions/3008. Find Beautiful Indices in the Given Array II/3008.java b/solutions/3008. Find Beautiful Indices in the Given Array II/3008.java new file mode 100644 index 00000000000..f1d78a64b93 --- /dev/null +++ b/solutions/3008. Find Beautiful Indices in the Given Array II/3008.java @@ -0,0 +1,59 @@ +class Solution { + // Same as 3006. Find Beautiful Indices in the Given Array I + public List beautifulIndices(String s, String a, String b, int k) { + List ans = new ArrayList<>(); + List indicesA = kmp(s, a); + List indicesB = kmp(s, b); + int indicesBIndex = 0; // indicesB' index + + for (final int i : indicesA) { + // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move + // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. + while (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i < -k) + ++indicesBIndex; + if (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i <= k) + ans.add(i); + } + + return ans; + } + + // Returns the starting indices of all occurrences of the pattern in `s`. + private List kmp(final String s, final String pattern) { + List res = new ArrayList<>(); + int[] lps = getLPS(pattern); + int i = 0; // s' index + int j = 0; // pattern's index + while (i < s.length()) { + if (s.charAt(i) == pattern.charAt(j)) { + ++i; + ++j; + if (j == pattern.length()) { + res.add(i - j); + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j != 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + private int[] getLPS(final String pattern) { + int[] lps = new int[pattern.length()]; + for (int i = 1, j = 0; i < pattern.length(); ++i) { + while (j > 0 && pattern.charAt(j) != pattern.charAt(i)) + j = lps[j - 1]; + if (pattern.charAt(i) == pattern.charAt(j)) + lps[i] = ++j; + } + return lps; + } +} diff --git a/solutions/3008. Find Beautiful Indices in the Given Array II/3008.py b/solutions/3008. Find Beautiful Indices in the Given Array II/3008.py new file mode 100644 index 00000000000..b0b3a233a71 --- /dev/null +++ b/solutions/3008. Find Beautiful Indices in the Given Array II/3008.py @@ -0,0 +1,54 @@ +class Solution: + # Same as 3006. Find Beautiful Indices in the Given Array I + def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]: + ans = [] + indicesA = self._kmp(s, a) + indicesB = self._kmp(s, b) + indicesBIndex = 0 # indicesB' index + + for i in indicesA: + # The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move + # `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. + while indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i < -k: + indicesBIndex += 1 + if indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i <= k: + ans.append(i) + + return ans + + def _kmp(self, s: str, pattern: str) -> List[int]: + """Returns the starting indices of all occurrences of the pattern in `s`.""" + + def getLPS(pattern: str) -> List[int]: + """ + Returns the lps array, where lps[i] is the length of the longest prefix of + pattern[0..i] which is also a suffix of this substring. + """ + lps = [0] * len(pattern) + j = 0 + for i in range(1, len(pattern)): + while j > 0 and pattern[j] != pattern[i]: + j = lps[j - 1] + if pattern[i] == pattern[j]: + lps[i] = j + 1 + j += 1 + return lps + + lps = getLPS(pattern) + res = [] + i = 0 # s' index + j = 0 # pattern's index + while i < len(s): + if s[i] == pattern[j]: + i += 1 + j += 1 + if j == len(pattern): + res.append(i - j) + j = lps[j - 1] + # Mismatch after j matches. + elif j != 0: + # Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1] + else: + i += 1 + return res diff --git a/solutions/3009. Maximum Number of Intersections on the Chart/3009.cpp b/solutions/3009. Maximum Number of Intersections on the Chart/3009.cpp new file mode 100644 index 00000000000..ba5ac51449c --- /dev/null +++ b/solutions/3009. Maximum Number of Intersections on the Chart/3009.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int maxIntersectionCount(vector& y) { + const int n = y.size(); + int ans = 0; + int intersectionCount = 0; + map line; + + for (int i = 1; i < n; ++i) { + const int start = 2 * y[i - 1]; + const int end = 2 * y[i] + (i == n - 1 ? 0 : y[i] > y[i - 1] ? -1 : 1); + ++line[min(start, end)]; + --line[max(start, end) + 1]; + } + + for (const auto& [_, count] : line) { + intersectionCount += count; + ans = max(ans, intersectionCount); + } + + return ans; + } +}; diff --git a/solutions/3009. Maximum Number of Intersections on the Chart/3009.java b/solutions/3009. Maximum Number of Intersections on the Chart/3009.java new file mode 100644 index 00000000000..b12efd081b8 --- /dev/null +++ b/solutions/3009. Maximum Number of Intersections on the Chart/3009.java @@ -0,0 +1,22 @@ +class Solution { + public int maxIntersectionCount(int[] y) { + final int n = y.length; + int ans = 0; + int intersectionCount = 0; + TreeMap line = new TreeMap<>(); + + for (int i = 1; i < n; ++i) { + final int start = 2 * y[i - 1]; + final int end = 2 * y[i] + (i == n - 1 ? 0 : y[i] > y[i - 1] ? -1 : 1); + line.merge(Math.min(start, end), 1, Integer::sum); + line.merge(Math.max(start, end) + 1, -1, Integer::sum); + } + + for (final int count : line.values()) { + intersectionCount += count; + ans = Math.max(ans, intersectionCount); + } + + return ans; + } +} diff --git a/solutions/3009. Maximum Number of Intersections on the Chart/3009.py b/solutions/3009. Maximum Number of Intersections on the Chart/3009.py new file mode 100644 index 00000000000..747a2dc2afa --- /dev/null +++ b/solutions/3009. Maximum Number of Intersections on the Chart/3009.py @@ -0,0 +1,17 @@ +class Solution: + def maxIntersectionCount(self, y: List[int]) -> int: + ans = 0 + intersectionCount = 0 + line = collections.Counter() + + for i, (a, b) in enumerate(itertools.pairwise(y)): + start = 2 * a + end = 2 * b + (0 if i == len(y) - 2 else -1 if b > a else 1) + line[min(start, end)] += 1 + line[max(start, end) + 1] -= 1 + + for count in sorted(line): + intersectionCount += line[count] + ans = max(ans, intersectionCount) + + return ans diff --git a/solutions/301. Remove Invalid Parentheses/301.cpp b/solutions/301. Remove Invalid Parentheses/301.cpp new file mode 100644 index 00000000000..40ced17c8a8 --- /dev/null +++ b/solutions/301. Remove Invalid Parentheses/301.cpp @@ -0,0 +1,58 @@ +class Solution { + public: + vector removeInvalidParentheses(string s) { + vector ans; + const auto [l, r] = getLeftAndRightCounts(s); + dfs(s, 0, l, r, ans); + return ans; + } + + private: + // Similar to 921. Minimum Add to Make Parentheses Valid + // Returns how many '(' and ')' need to be deleted. + pair getLeftAndRightCounts(const string& s) { + int l = 0; + int r = 0; + + for (const char c : s) + if (c == '(') + ++l; + else if (c == ')') { + if (l == 0) + ++r; + else + --l; + } + + return {l, r}; + } + + void dfs(const string& s, int start, int l, int r, vector& ans) { + if (l == 0 && r == 0 && isValid(s)) { + ans.push_back(s); + return; + } + + for (int i = start; i < s.length(); ++i) { + if (i > start && s[i] == s[i - 1]) + continue; + if (l > 0 && s[i] == '(') // Delete s[i]. + dfs(s.substr(0, i) + s.substr(i + 1), i, l - 1, r, ans); + if (r > 0 && s[i] == ')') // Delete s[i]. + dfs(s.substr(0, i) + s.substr(i + 1), i, l, r - 1, ans); + } + } + + bool isValid(const string& s) { + int opened = 0; // the number of '(' - # of ')' + for (const char c : s) { + if (c == '(') + ++opened; + else if (c == ')') + --opened; + if (opened < 0) + return false; + } + return true; // opened == 0 + } +}; diff --git a/solutions/301. Remove Invalid Parentheses/301.java b/solutions/301. Remove Invalid Parentheses/301.java new file mode 100644 index 00000000000..11ea6cea580 --- /dev/null +++ b/solutions/301. Remove Invalid Parentheses/301.java @@ -0,0 +1,56 @@ +class Solution { + public List removeInvalidParentheses(String s) { + List ans = new ArrayList<>(); + final int[] counts = getLeftAndRightCounts(s); + dfs(s, 0, counts[0], counts[1], ans); + return ans; + } + + // Similar to 921. Minimum Add to Make Parentheses Valid + // Returns how many '(' and ')' need to be deleted. + private int[] getLeftAndRightCounts(final String s) { + int l = 0; + int r = 0; + + for (final char c : s.toCharArray()) + if (c == '(') + ++l; + else if (c == ')') { + if (l == 0) + ++r; + else + --l; + } + + return new int[] {l, r}; + } + + private void dfs(final String s, int start, int l, int r, List ans) { + if (l == 0 && r == 0 && isValid(s)) { + ans.add(s); + return; + } + + for (int i = start; i < s.length(); ++i) { + if (i > start && s.charAt(i) == s.charAt(i - 1)) + continue; + if (l > 0 && s.charAt(i) == '(') // Delete s[i]. + dfs(s.substring(0, i) + s.substring(i + 1), i, l - 1, r, ans); + else if (r > 0 && s.charAt(i) == ')') // Delete s[i]. + dfs(s.substring(0, i) + s.substring(i + 1), i, l, r - 1, ans); + } + } + + private boolean isValid(final String s) { + int opened = 0; // the number of '(' - # of ')' + for (final char c : s.toCharArray()) { + if (c == '(') + ++opened; + else if (c == ')') + --opened; + if (opened < 0) + return false; + } + return true; // opened == 0 + } +} diff --git a/solutions/301. Remove Invalid Parentheses/301.py b/solutions/301. Remove Invalid Parentheses/301.py new file mode 100644 index 00000000000..2f3af74e142 --- /dev/null +++ b/solutions/301. Remove Invalid Parentheses/301.py @@ -0,0 +1,48 @@ +class Solution: + def removeInvalidParentheses(self, s: str) -> List[str]: + # Similar to 921. Minimum Add to Make Parentheses Valid + def getLeftAndRightCounts(s: str) -> Tuple[int, int]: + """Returns how many '(' and ')' need to be deleted.""" + l = 0 + r = 0 + + for c in s: + if c == '(': + l += 1 + elif c == ')': + if l == 0: + r += 1 + else: + l -= 1 + + return l, r + + def isValid(s: str): + opened = 0 # the number of '(' - # of ')' + for c in s: + if c == '(': + opened += 1 + elif c == ')': + opened -= 1 + if opened < 0: + return False + return True # opened == 0 + + ans = [] + + def dfs(s: str, start: int, l: int, r: int) -> None: + if l == 0 and r == 0 and isValid(s): + ans.append(s) + return + + for i in range(start, len(s)): + if i > start and s[i] == s[i - 1]: + continue + if r > 0 and s[i] == ')': # Delete s[i] + dfs(s[:i] + s[i + 1:], i, l, r - 1) + elif l > 0 and s[i] == '(': # Delete s[i] + dfs(s[:i] + s[i + 1:], i, l - 1, r) + + l, r = getLeftAndRightCounts(s) + dfs(s, 0, l, r) + return ans diff --git a/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.cpp b/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.cpp new file mode 100644 index 00000000000..bcde3d2668a --- /dev/null +++ b/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minimumCost(vector& nums) { + constexpr int kMax = 50; + int min1 = kMax; + int min2 = kMax; + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] < min1) { + min2 = min1; + min1 = nums[i]; + } else if (nums[i] < min2) { + min2 = nums[i]; + } + + return nums[0] + min1 + min2; + } +}; diff --git a/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.java b/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.java new file mode 100644 index 00000000000..3241101a1c2 --- /dev/null +++ b/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.java @@ -0,0 +1,17 @@ +class Solution { + public int minimumCost(int[] nums) { + final int kMax = 50; + int min1 = kMax; + int min2 = kMax; + + for (int i = 1; i < nums.length; ++i) + if (nums[i] < min1) { + min2 = min1; + min1 = nums[i]; + } else if (nums[i] < min2) { + min2 = nums[i]; + } + + return nums[0] + min1 + min2; + } +} diff --git a/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.py b/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.py new file mode 100644 index 00000000000..db78187ed58 --- /dev/null +++ b/solutions/3010. Divide an Array Into Subarrays With Minimum Cost I/3010.py @@ -0,0 +1,14 @@ +class Solution: + def minimumCost(self, nums: List[int]) -> int: + kMax = 50 + min1 = kMax + min2 = kMax + + for i in range(1, len(nums)): + if nums[i] < min1: + min2 = min1 + min1 = nums[i] + elif nums[i] < min2: + min2 = nums[i] + + return nums[0] + min1 + min2 diff --git a/solutions/3011. Find if Array Can Be Sorted/3011.cpp b/solutions/3011. Find if Array Can Be Sorted/3011.cpp new file mode 100644 index 00000000000..67683afeaaf --- /dev/null +++ b/solutions/3011. Find if Array Can Be Sorted/3011.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool canSortArray(vector& nums) { + // Divide the array into distinct segments where each segment is comprised + // of consecutive elements sharing an equal number of set bits. Ensure that + // for each segment, when moving from left to right, the maximum of a + // preceding segment is less than the minimum of the following segment. + int prevSetBits = 0; + int prevMax = INT_MIN; // the maximum of the previous segment + int currMax = INT_MIN; // the maximum of the current segment + int currMin = INT_MAX; // the minimum of the current segment + + for (const int num : nums) { + const int setBits = __builtin_popcount(num); + if (setBits != prevSetBits) { // Start a new segment. + if (prevMax > currMin) + return false; + prevSetBits = setBits; + prevMax = currMax; + currMax = num; + currMin = num; + } else { // Continue with the current segment. + currMax = max(currMax, num); + currMin = min(currMin, num); + } + } + + return prevMax <= currMin; + } +}; diff --git a/solutions/3011. Find if Array Can Be Sorted/3011.java b/solutions/3011. Find if Array Can Be Sorted/3011.java new file mode 100644 index 00000000000..b95d8af823d --- /dev/null +++ b/solutions/3011. Find if Array Can Be Sorted/3011.java @@ -0,0 +1,29 @@ +class Solution { + public boolean canSortArray(int[] nums) { + // Divide the array into distinct segments where each segment is comprised + // of consecutive elements sharing an equal number of set bits. Ensure that + // for each segment, when moving from left to right, the maximum of a + // preceding segment is less than the minimum of the following segment. + int prevSetBits = 0; + int prevMax = Integer.MIN_VALUE; // the maximum of the previous segment + int currMax = Integer.MIN_VALUE; // the maximum of the current segment + int currMin = Integer.MAX_VALUE; // the minimum of the current segment + + for (final int num : nums) { + final int setBits = Integer.bitCount(num); + if (setBits != prevSetBits) { // Start a new segment. + if (prevMax > currMin) + return false; + prevSetBits = setBits; + prevMax = currMax; + currMax = num; + currMin = num; + } else { // Continue with the current segment. + currMax = Math.max(currMax, num); + currMin = Math.min(currMin, num); + } + } + + return prevMax <= currMin; + } +} diff --git a/solutions/3011. Find if Array Can Be Sorted/3011.py b/solutions/3011. Find if Array Can Be Sorted/3011.py new file mode 100644 index 00000000000..85a8077f6ae --- /dev/null +++ b/solutions/3011. Find if Array Can Be Sorted/3011.py @@ -0,0 +1,25 @@ +class Solution: + def canSortArray(self, nums: List[int]) -> int: + # Divide the array into distinct segments where each segment is comprised + # of consecutive elements sharing an equal number of set bits. Ensure that + # for each segment, when moving from left to right, the maximum of a + # preceding segment is less than the minimum of the following segment. + prevSetBits = 0 + prevMax = -math.inf # the maximum of the previous segment + currMax = -math.inf # the maximum of the current segment + currMin = math.inf # the minimum of the current segment + + for num in nums: + setBits = num.bit_count() + if setBits != prevSetBits: # Start a new segment. + if prevMax > currMin: + return False + prevSetBits = setBits + prevMax = currMax + currMax = num + currMin = num + else: # Continue with the current segment. + currMax = max(currMax, num) + currMin = min(currMin, num) + + return prevMax <= currMin diff --git a/solutions/3012. Minimize Length of Array Using Operations/3012.cpp b/solutions/3012. Minimize Length of Array Using Operations/3012.cpp new file mode 100644 index 00000000000..a84b2d85195 --- /dev/null +++ b/solutions/3012. Minimize Length of Array Using Operations/3012.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minimumArrayLength(vector& nums) { + // Let the minimum number in the array `nums` be x. + // * If there exists any element nums[i] where nums[i] % x > 0, a new + // minimum can be generated and all other numbers can be removed. + // * If not, count the frequency of x in `nums`. For each pair of x, a 0 is + // generated which cannot be removed. Therefore, the result will be + // (frequency of x + 1) / 2. + const int minNum = ranges::min(nums); + if (ranges::any_of(nums, [minNum](int num) { return num % minNum > 0; })) + return 1; + return (ranges::count(nums, minNum) + 1) / 2; + } +}; diff --git a/solutions/3012. Minimize Length of Array Using Operations/3012.java b/solutions/3012. Minimize Length of Array Using Operations/3012.java new file mode 100644 index 00000000000..6f487ae7f77 --- /dev/null +++ b/solutions/3012. Minimize Length of Array Using Operations/3012.java @@ -0,0 +1,15 @@ +class Solution { + public int minimumArrayLength(int[] nums) { + // Let the minimum number in the array `nums` be x. + // * If there exists any element nums[i] where nums[i] % x > 0, a new + // minimum can be generated and all other numbers can be removed. + // * If not, count the frequency of x in `nums`. For each pair of x, a 0 is + // generated which cannot be removed. Therefore, the result will be + // (frequency of x + 1) / 2. + final int minNum = Arrays.stream(nums).min().getAsInt(); + if (Arrays.stream(nums).anyMatch(num -> num % minNum > 0)) + return 1; + final int freq = (int) Arrays.stream(nums).filter(num -> num == minNum).count(); + return (freq + 1) / 2; + } +} diff --git a/solutions/3012. Minimize Length of Array Using Operations/3012.py b/solutions/3012. Minimize Length of Array Using Operations/3012.py new file mode 100644 index 00000000000..006966a05cb --- /dev/null +++ b/solutions/3012. Minimize Length of Array Using Operations/3012.py @@ -0,0 +1,12 @@ +class Solution: + def minimumArrayLength(self, nums: List[int]) -> int: + # Let the minimum number in the array `nums` be x. + # * If there exists any element nums[i] where nums[i] % x > 0, a new + # minimum can be generated and all other numbers can be removed. + # * If not, count the frequency of x in `nums`. For each pair of x, a 0 is + # generated which cannot be removed. Therefore, the result will be + # (frequency of x + 1) / 2. + minNum = min(nums) + if any(num % minNum > 0 for num in nums): + return 1 + return (nums.count(minNum) + 1) // 2 diff --git a/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.cpp b/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.cpp new file mode 100644 index 00000000000..f5deed3c17f --- /dev/null +++ b/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.cpp @@ -0,0 +1,58 @@ +class Solution { + public: + long long minimumCost(vector& nums, int k, int dist) { + // Equivalently, the problem is to find nums[0] + the minimum sum of the top + // k - 1 numbers in nums[i..i + dist], where i > 0 and i + dist < n. + long windowSum = 0; + multiset selected; + multiset candidates; + + for (int i = 1; i <= dist + 1; ++i) { + windowSum += nums[i]; + selected.insert(nums[i]); + } + + windowSum = balance(windowSum, selected, candidates, k); + long minWindowSum = windowSum; + + for (int i = dist + 2; i < nums.size(); ++i) { + const int outOfScope = nums[i - dist - 1]; + if (selected.find(outOfScope) != selected.end()) { + windowSum -= outOfScope; + selected.erase(selected.find(outOfScope)); + } else { + candidates.erase(candidates.find(outOfScope)); + } + if (nums[i] < *selected.rbegin()) { // nums[i] is a better number. + windowSum += nums[i]; + selected.insert(nums[i]); + } else { + candidates.insert(nums[i]); + } + windowSum = balance(windowSum, selected, candidates, k); + minWindowSum = min(minWindowSum, windowSum); + } + + return nums[0] + minWindowSum; + } + + private: + // Returns the updated `windowSum` by balancing the multiset `selected` to + // keep the top k - 1 numbers. + long balance(long windowSum, multiset& selected, + multiset& candidates, int k) { + while (selected.size() < k - 1) { + const int minCandidate = *candidates.begin(); + windowSum += minCandidate; + selected.insert(minCandidate); + candidates.erase(candidates.find(minCandidate)); + } + while (selected.size() > k - 1) { + const int maxSelected = *selected.rbegin(); + windowSum -= maxSelected; + selected.erase(selected.find(maxSelected)); + candidates.insert(maxSelected); + } + return windowSum; + } +}; diff --git a/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.java b/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.java new file mode 100644 index 00000000000..56fd419356d --- /dev/null +++ b/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.java @@ -0,0 +1,88 @@ +class Multiset { + public void add(int num) { + map.merge(num, 1, Integer::sum); + ++sz; + } + + public void remove(int num) { + map.merge(num, -1, Integer::sum); + if (map.get(num) == 0) + map.remove(num); + --sz; + } + + public int min() { + return map.firstEntry().getKey(); + } + + public int max() { + return map.lastEntry().getKey(); + } + + public int size() { + return sz; + } + + public boolean contains(int num) { + return map.containsKey(num); + } + + private TreeMap map = new TreeMap<>(); + private int sz = 0; +} + +class Solution { + public long minimumCost(int[] nums, int k, int dist) { + // Equivalently, the problem is to find nums[0] + the minimum sum of the top + // k - 1 numbers in nums[i..i + dist], where i > 0 and i + dist < n. + long windowSum = 0; + Multiset selected = new Multiset(); + Multiset candidates = new Multiset(); + + for (int i = 1; i <= dist + 1; ++i) { + windowSum += nums[i]; + selected.add(nums[i]); + } + + windowSum = balance(windowSum, selected, candidates, k); + long minWindowSum = windowSum; + + for (int i = dist + 2; i < nums.length; ++i) { + final int outOfScope = nums[i - dist - 1]; + if (selected.contains(outOfScope)) { + windowSum -= outOfScope; + selected.remove(outOfScope); + } else { + candidates.remove(outOfScope); + } + if (nums[i] < selected.max()) { // nums[i] is a better number. + windowSum += nums[i]; + selected.add(nums[i]); + } else { + candidates.add(nums[i]); + } + windowSum = balance(windowSum, selected, candidates, k); + minWindowSum = Math.min(minWindowSum, windowSum); + } + + return nums[0] + minWindowSum; + } + + // Returns the updated `windowSum` by balancing the multiset `selected` to + // keep the top k - 1 numbers. + private long balance(long windowSum, Multiset selected, Multiset candidates, int k) { + while (selected.size() < k - 1) { + final int minCandidate = candidates.min(); + windowSum += minCandidate; + selected.add(minCandidate); + candidates.remove(minCandidate); + } + while (selected.size() > k - 1) { + final int maxSelected = selected.max(); + windowSum -= maxSelected; + selected.remove(maxSelected); + candidates.add(maxSelected); + } + return windowSum; + } +} diff --git a/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.py b/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.py new file mode 100644 index 00000000000..acae3dc4f9a --- /dev/null +++ b/solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.py @@ -0,0 +1,48 @@ +from sortedcontainers import SortedList + + +class Solution: + def minimumCost(self, nums: List[int], k: int, dist: int) -> int: + # Equivalently, the problem is to find nums[0] + the minimum sum of the top + # k - 1 numbers in nums[i..i + dist], where i > 0 and i + dist < n. + windowSum = sum(nums[i] for i in range(1, dist + 2)) + selected = SortedList(nums[i] for i in range(1, dist + 2)) + candidates = SortedList() + + def balance() -> int: + """ + Returns the updated `windowSum` by balancing the multiset `selected` to + keep the top k - 1 numbers. + """ + nonlocal windowSum + while len(selected) < k - 1: + minCandidate = candidates[0] + windowSum += minCandidate + selected.add(minCandidate) + candidates.remove(minCandidate) + while len(selected) > k - 1: + maxSelected = selected[-1] + windowSum -= maxSelected + selected.remove(maxSelected) + candidates.add(maxSelected) + return windowSum + + windowSum = balance() + minWindowSum = windowSum + + for i in range(dist + 2, len(nums)): + outOfScope = nums[i - dist - 1] + if outOfScope in selected: + windowSum -= outOfScope + selected.remove(outOfScope) + else: + candidates.remove(outOfScope) + if nums[i] < selected[-1]: # nums[i] is a better number. + windowSum += nums[i] + selected.add(nums[i]) + else: + candidates.add(nums[i]) + windowSum = balance() + minWindowSum = min(minWindowSum, windowSum) + + return nums[0] + minWindowSum diff --git a/solutions/3014. Minimum Number of Pushes to Type Word I/3014.cpp b/solutions/3014. Minimum Number of Pushes to Type Word I/3014.cpp new file mode 100644 index 00000000000..f5b3d50874b --- /dev/null +++ b/solutions/3014. Minimum Number of Pushes to Type Word I/3014.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minimumPushes(string word) { + int ans = 0; + vector count(26); + + for (const char c : word) + ++count[c - 'a']; + + ranges::sort(count, greater<>()); + + for (int i = 0; i < 26; ++i) + ans += count[i] * (i / 8 + 1); + + return ans; + } +}; diff --git a/solutions/3014. Minimum Number of Pushes to Type Word I/3014.java b/solutions/3014. Minimum Number of Pushes to Type Word I/3014.java new file mode 100644 index 00000000000..01e9f415ff7 --- /dev/null +++ b/solutions/3014. Minimum Number of Pushes to Type Word I/3014.java @@ -0,0 +1,16 @@ +class Solution { + public int minimumPushes(String word) { + int ans = 0; + int[] count = new int[26]; + + for (final char c : word.toCharArray()) + ++count[c - 'a']; + + Arrays.sort(count); + + for (int i = 0; i < 26; ++i) + ans += count[26 - i - 1] * (i / 8 + 1); + + return ans; + } +} diff --git a/solutions/3014. Minimum Number of Pushes to Type Word I/3014.py b/solutions/3014. Minimum Number of Pushes to Type Word I/3014.py new file mode 100644 index 00000000000..db77e0795d6 --- /dev/null +++ b/solutions/3014. Minimum Number of Pushes to Type Word I/3014.py @@ -0,0 +1,4 @@ +class Solution: + def minimumPushes(self, word: str) -> int: + freqs = sorted(collections.Counter(word).values(), reverse=True) + return sum(freq * (i // 8 + 1) for i, freq in enumerate(freqs)) diff --git a/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.cpp b/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.cpp new file mode 100644 index 00000000000..b8b14c126ac --- /dev/null +++ b/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.cpp @@ -0,0 +1,104 @@ +class Solution { + public: + vector countOfPairs(int n, int x, int y) { + if (x > y) + swap(x, y); + + const int ringLen = y - x + 1; + const int leftLineLen = x - 1; + const int rightLineLen = n - y; + + vector ans(n); + ans = addVectors(ans, bothInRing(n, ringLen)); + ans = addVectors(ans, bothInTheSameLine(n, leftLineLen)); + ans = addVectors(ans, bothInTheSameLine(n, rightLineLen)); + ans = addVectors(ans, lineToRing(n, leftLineLen, ringLen)); + ans = addVectors(ans, lineToRing(n, rightLineLen, ringLen)); + ans = addVectors(ans, lineToLine(n, x, y, leftLineLen, rightLineLen)); + for (int& freq : ans) + freq *= 2; + return ans; + } + + private: + // Returns the contribution from the scenario where two houses are located in + // the ring. + vector bothInRing(int n, int ringLen) { + vector res(n); + for (int k = 1; k <= (ringLen - 1) / 2; ++k) + res[k - 1] += ringLen; + if (ringLen % 2 == 0) + res[ringLen / 2 - 1] += ringLen / 2; + return res; + } + + // Returns the contribution from the scenario where two houses are either + // located in the left line [1, x) or the right line (y, n]. + vector bothInTheSameLine(int n, int lineLen) { + vector res(n); + for (int k = 1; k <= lineLen; ++k) + res[k - 1] += lineLen - k; + return res; + } + + // Returns the contribution from the scenario where one house is either + // located in the left line [1, x) or the right line (y, n] and the other + // house is located in the cycle. + vector lineToRing(int n, int lineLen, int ringLen) { + vector res(n); + for (int k = 1; k <= lineLen + ringLen; ++k) { + // min( + // at most k - 1 since we need to give 1 to the line, + // at most ringLen / 2 since for length > ringLen / 2, it can always be + // calculated as ringLen - ringLen / 2 + // ) + const int maxInRingLen = min(k - 1, ringLen / 2); + // max(at least 0, at lest k - lineLen) + const int minInRingLen = max(0, k - lineLen); + if (minInRingLen <= maxInRingLen) { + // Each ring length contributes 2 to the count due to the split of + // paths when entering the ring: One path traverses the upper half of + // the ring, and the other traverses the lower half. + // This is illustrated as follows: + // Path 1: ... -- x -- (upper half of the ring) + // Path 2: ... -- x -- (lower half of the ring) + res[k - 1] += (maxInRingLen - minInRingLen + 1) * 2; + if (minInRingLen == 0) + // Subtract 1 since there's no split. + res[k - 1] -= 1; + if (maxInRingLen * 2 == ringLen) + // Subtract 1 since the following case only contribute one: + // ... -- x -- (upper half of the ring) -- middle point + // ... -- x -- (upper half of the ring) -- middle point + res[k - 1] -= 1; + } + } + return res; + } + + // Returns the contribution from the scenario where one house is in the left + // line [1, x) and the other house is in the right line (y, n]. + vector lineToLine(int n, int x, int y, int leftLineLen, + int rightLineLen) { + vector res(n); + for (int k = 1; k <= leftLineLen + rightLineLen + 2; ++k) { + // min( + // at most leftLineLen, + // at most k - 1 - (x < y) since we need to give 1 to the right line + // and if x < y we need to give another 1 to "x - y". + // ) + const int maxInLeft = min(leftLineLen, k - 1 - (x < y)); + // max(at least 1, at least k - rightLineLen - (x < y)) + const int minInLeft = max(1, k - rightLineLen - (x < y)); + if (minInLeft <= maxInLeft) + res[k - 1] += maxInLeft - minInLeft + 1; + } + return res; + } + + vector addVectors(const vector& a, const vector& b) { + vector res(a.size()); + transform(a.begin(), a.end(), b.begin(), res.begin(), plus()); + return res; + }; +}; diff --git a/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.java b/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.java new file mode 100644 index 00000000000..7720d28d156 --- /dev/null +++ b/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.java @@ -0,0 +1,104 @@ +class Solution { + public int[] countOfPairs(int n, int x, int y) { + if (x > y) { + final int temp = x; + x = y; + y = temp; + } + + final int ringLen = y - x + 1; + final int leftLineLen = x - 1; + final int rightLineLen = n - y; + + int[] ans = new int[n]; + ans = addVectors(ans, bothInRing(n, ringLen)); + ans = addVectors(ans, bothInTheSameLine(n, leftLineLen)); + ans = addVectors(ans, bothInTheSameLine(n, rightLineLen)); + ans = addVectors(ans, lineToRing(n, leftLineLen, ringLen)); + ans = addVectors(ans, lineToRing(n, rightLineLen, ringLen)); + ans = addVectors(ans, lineToLine(n, x, y, leftLineLen, rightLineLen)); + for (int i = 0; i < ans.length; ++i) + ans[i] *= 2; + return ans; + } + + // Returns the contribution from the scenario where two houses are located in + // the ring. + private int[] bothInRing(int n, int ringLen) { + int[] res = new int[n]; + for (int k = 1; k <= (ringLen - 1) / 2; ++k) + res[k - 1] += ringLen; + if (ringLen % 2 == 0) + res[ringLen / 2 - 1] += ringLen / 2; + return res; + } + + // Returns the contribution from the scenario where two houses are either + // located in the left line [1, x) or the right line (y, n]. + private int[] bothInTheSameLine(int n, int lineLen) { + int[] res = new int[n]; + for (int k = 1; k <= lineLen; ++k) + res[k - 1] += lineLen - k; + return res; + } + + // Returns the contribution from the scenario where one house is either + // located in the left line [1, x) or the right line (y, n] and the other + // house is located in the cycle. + private int[] lineToRing(int n, int lineLen, int ringLen) { + int[] res = new int[n]; + for (int k = 1; k <= lineLen + ringLen; ++k) { + // min( + // at most k - 1 since we need to give 1 to the line, + // at most ringLen / 2 since for length > ringLen / 2, it can always be + // calculated as ringLen - ringLen / 2 + // ) + final int maxInRingLen = Math.min(k - 1, ringLen / 2); + // max(at least 0, at lest k - lineLen) + final int minInRingLen = Math.max(0, k - lineLen); + if (minInRingLen <= maxInRingLen) { + // Each ring length contributes 2 to the count due to the split of + // paths when entering the ring: One path traverses the upper half of + // the ring, and the other traverses the lower half. + // This is illustrated as follows: + // Path 1: ... -- x -- (upper half of the ring) + // Path 2: ... -- x -- (lower half of the ring) + res[k - 1] += (maxInRingLen - minInRingLen + 1) * 2; + if (minInRingLen == 0) + // Subtract 1 since there's no split. + res[k - 1] -= 1; + if (maxInRingLen * 2 == ringLen) + // Subtract 1 since the following case only contribute one: + // ... -- x -- (upper half of the ring) -- middle point + // ... -- x -- (upper half of the ring) -- middle point + res[k - 1] -= 1; + } + } + return res; + } + + // Returns the contribution from the scenario where one house is in the left + // line [1, x) and the other house is in the right line (y, n]. + private int[] lineToLine(int n, int x, int y, int leftLineLen, int rightLineLen) { + int[] res = new int[n]; + for (int k = 1; k <= leftLineLen + rightLineLen + 2; ++k) { + // min( + // at most leftLineLen, + // at most k - 1 - (x < y) since we need to give 1 to the right line + // and if x < y we need to give another 1 to "x - y". + // ) + final int maxInLeft = Math.min(leftLineLen, k - 1 - (x < y ? 1 : 0)); + // max(at least 1, at least k - rightLineLen - (x < y)) + final int minInLeft = Math.max(1, k - rightLineLen - (x < y ? 1 : 0)); + if (minInLeft <= maxInLeft) + res[k - 1] += maxInLeft - minInLeft + 1; + } + return res; + } + + private int[] addVectors(int[] a, int[] b) { + for (int i = 0; i < a.length; ++i) + a[i] += b[i]; + return a; + } +} diff --git a/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.py b/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.py new file mode 100644 index 00000000000..ce25d7a24d3 --- /dev/null +++ b/solutions/3015. Count the Number of Houses at a Certain Distance I/3015.py @@ -0,0 +1,92 @@ +class Solution: + def countOfPairs(self, n: int, x: int, y: int) -> List[int]: + if x > y: + x, y = y, x + + def bothInRing(ringLen: int) -> List[int]: + """ + Returns the contribution from the scenario where two houses are located + in the ring. + """ + res = [0] * n + for k in range(1, (ringLen - 1) // 2 + 1): + res[k - 1] += ringLen + if ringLen % 2 == 0: + res[ringLen // 2 - 1] += ringLen // 2 + return res + + def bothInTheSameLine(lineLen: int) -> List[int]: + """ + Returns the contribution from the scenario where two houses are either + located in the left line [1, x) or the right line (y, n]. + """ + res = [0] * n + for k in range(1, lineLen + 1): + res[k - 1] += lineLen - k + return res + + def lineToRing(lineLen: int, ringLen: int) -> List[int]: + """ + Returns the contribution from the scenario where one house is either + located in the left line [1, x) or the right line (y, n] and the + other house is located in the cycle. + """ + res = [0] * n + for k in range(1, lineLen + ringLen): + # min( + # at most k - 1 since we need to give 1 to the line, + # at most ringLen / 2 since for length > ringLen / 2, it can always be + # calculated as ringLen - ringLen / 2 + # ) + maxInRingLen = min(k - 1, ringLen // 2) + # max(at least 0, at lest k - lineLen) + minInRingLen = max(0, k - lineLen) + if minInRingLen <= maxInRingLen: + # Each ring length contributes 2 to the count due to the split of + # paths when entering the ring: One path traverses the upper half of + # the ring, and the other traverses the lower half. + # This is illustrated as follows: + # Path 1: ... -- x -- (upper half of the ring) + # Path 2: ... -- x -- (lower half of the ring) + res[k - 1] += (maxInRingLen - minInRingLen + 1) * 2 + if minInRingLen == 0: + # Subtract 1 since there's no split. + res[k - 1] -= 1 + if maxInRingLen * 2 == ringLen: + # Subtract 1 since the following case only contribute one: + # ... -- x -- (upper half of the ring) -- middle point + # ... -- x -- (upper half of the ring) -- middle point + res[k - 1] -= 1 + return res + + def lineToLine(leftLineLen: int, rightLineLen: int) -> List[int]: + """ + Returns the contribution from the scenario where one house is in the left + line [1, x) and the other house is in the right line (y, n]. + """ + res = [0] * n + for k in range(leftLineLen + rightLineLen + 2): + # min( + # at most leftLineLen, + # at most k - 1 - (x < y) since we need to give 1 to the right line + # and if x < y we need to give another 1 to "x - y". + # ) + maxInLeft = min(leftLineLen, k - 1 - (x < y)) + # max(at least 1, at least k - rightLineLen - (x < y)) + minInLeft = max(1, k - rightLineLen - (x < y)) + if minInLeft <= maxInLeft: + res[k - 1] += maxInLeft - minInLeft + 1 + return res + + ringLen = y - x + 1 + leftLineLen = x - 1 + rightLineLen = (n - y) + + ans = [0] * n + ans = list(map(operator.add, ans, bothInRing(ringLen))) + ans = list(map(operator.add, ans, bothInTheSameLine(leftLineLen))) + ans = list(map(operator.add, ans, bothInTheSameLine(rightLineLen))) + ans = list(map(operator.add, ans, lineToRing(leftLineLen, ringLen))) + ans = list(map(operator.add, ans, lineToRing(rightLineLen, ringLen))) + ans = list(map(operator.add, ans, lineToLine(leftLineLen, rightLineLen))) + return [freq * 2 for freq in ans] diff --git a/solutions/3016. Minimum Number of Pushes to Type Word II/3016.cpp b/solutions/3016. Minimum Number of Pushes to Type Word II/3016.cpp new file mode 100644 index 00000000000..8d832c1de66 --- /dev/null +++ b/solutions/3016. Minimum Number of Pushes to Type Word II/3016.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + // Same as 3014. Minimum Number of Pushes to Type Word I + int minimumPushes(string word) { + int ans = 0; + vector count(26); + + for (const char c : word) + ++count[c - 'a']; + + ranges::sort(count, greater<>()); + + for (int i = 0; i < 26; ++i) + ans += count[i] * (i / 8 + 1); + + return ans; + } +}; diff --git a/solutions/3016. Minimum Number of Pushes to Type Word II/3016.java b/solutions/3016. Minimum Number of Pushes to Type Word II/3016.java new file mode 100644 index 00000000000..7c278fb029f --- /dev/null +++ b/solutions/3016. Minimum Number of Pushes to Type Word II/3016.java @@ -0,0 +1,17 @@ +class Solution { + // Same as 3014. Minimum Number of Pushes to Type Word I + public int minimumPushes(String word) { + int ans = 0; + int[] count = new int[26]; + + for (final char c : word.toCharArray()) + ++count[c - 'a']; + + Arrays.sort(count); + + for (int i = 0; i < 26; ++i) + ans += count[26 - i - 1] * (i / 8 + 1); + + return ans; + } +} diff --git a/solutions/3016. Minimum Number of Pushes to Type Word II/3016.py b/solutions/3016. Minimum Number of Pushes to Type Word II/3016.py new file mode 100644 index 00000000000..77bb85ba5eb --- /dev/null +++ b/solutions/3016. Minimum Number of Pushes to Type Word II/3016.py @@ -0,0 +1,5 @@ +class Solution: + # Same as 3014. Minimum Number of Pushes to Type Word I + def minimumPushes(self, word: str) -> int: + freqs = sorted(collections.Counter(word).values(), reverse=True) + return sum(freq * (i // 8 + 1) for i, freq in enumerate(freqs)) diff --git a/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.cpp b/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.cpp new file mode 100644 index 00000000000..cff6ddd84fb --- /dev/null +++ b/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.cpp @@ -0,0 +1,106 @@ +class Solution { + public: + // Same as 3015. Count the Number of Houses at a Certain Distance I + vector countOfPairs(int n, int x, int y) { + if (x > y) + swap(x, y); + + const int ringLen = y - x + 1; + const int leftLineLen = x - 1; + const int rightLineLen = n - y; + + vector ans(n); + ans = addVectors(ans, bothInRing(n, ringLen)); + ans = addVectors(ans, bothInTheSameLine(n, leftLineLen)); + ans = addVectors(ans, bothInTheSameLine(n, rightLineLen)); + ans = addVectors(ans, lineToRing(n, leftLineLen, ringLen)); + ans = addVectors(ans, lineToRing(n, rightLineLen, ringLen)); + ans = addVectors(ans, lineToLine(n, x, y, leftLineLen, rightLineLen)); + for (long long& freq : ans) + freq *= 2; + return ans; + } + + private: + // Returns the contribution from the scenario where two houses are located in + // the ring. + vector bothInRing(int n, int ringLen) { + vector res(n); + for (int k = 1; k <= (ringLen - 1) / 2; ++k) + res[k - 1] += ringLen; + if (ringLen % 2 == 0) + res[ringLen / 2 - 1] += ringLen / 2; + return res; + } + + // Returns the contribution from the scenario where two houses are either + // located in the left line [1, x) or the right line (y, n]. + vector bothInTheSameLine(int n, int lineLen) { + vector res(n); + for (int k = 1; k <= lineLen; ++k) + res[k - 1] += lineLen - k; + return res; + } + + // Returns the contribution from the scenario where one house is either + // located in the left line [1, x) or the right line (y, n] and the other + // house is located in the cycle. + vector lineToRing(int n, int lineLen, int ringLen) { + vector res(n); + for (int k = 1; k <= lineLen + ringLen; ++k) { + // min( + // at most k - 1 since we need to give 1 to the line, + // at most ringLen / 2 since for length > ringLen / 2, it can always be + // calculated as ringLen - ringLen / 2 + // ) + const int maxInRingLen = min(k - 1, ringLen / 2); + // max(at least 0, at lest k - lineLen) + const int minInRingLen = max(0, k - lineLen); + if (minInRingLen <= maxInRingLen) { + // Each ring length contributes 2 to the count due to the split of + // paths when entering the ring: One path traverses the upper half of + // the ring, and the other traverses the lower half. + // This is illustrated as follows: + // Path 1: ... -- x -- (upper half of the ring) + // Path 2: ... -- x -- (lower half of the ring) + res[k - 1] += (maxInRingLen - minInRingLen + 1) * 2; + if (minInRingLen == 0) + // Subtract 1 since there's no split. + res[k - 1] -= 1; + if (maxInRingLen * 2 == ringLen) + // Subtract 1 since the following case only contribute one: + // ... -- x -- (upper half of the ring) -- middle point + // ... -- x -- (upper half of the ring) -- middle point + res[k - 1] -= 1; + } + } + return res; + } + + // Returns the contribution from the scenario where one house is in the left + // line [1, x) and the other house is in the right line (y, n]. + vector lineToLine(int n, int x, int y, int leftLineLen, + int rightLineLen) { + vector res(n); + for (int k = 1; k <= leftLineLen + rightLineLen + 2; ++k) { + // min( + // at most leftLineLen, + // at most k - 1 - (x < y) since we need to give 1 to the right line + // and if x < y we need to give another 1 to "x - y". + // ) + const int maxInLeft = min(leftLineLen, k - 1 - (x < y)); + // max(at least 1, at least k - rightLineLen - (x < y)) + const int minInLeft = max(1, k - rightLineLen - (x < y)); + if (minInLeft <= maxInLeft) + res[k - 1] += maxInLeft - minInLeft + 1; + } + return res; + } + + vector addVectors(const vector& a, + const vector& b) { + vector res(a.size()); + transform(a.begin(), a.end(), b.begin(), res.begin(), plus()); + return res; + }; +}; diff --git a/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.java b/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.java new file mode 100644 index 00000000000..3d9a9b306e9 --- /dev/null +++ b/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.java @@ -0,0 +1,105 @@ +class Solution { + // Same as 3015. Count the Number of Houses at a Certain Distance I + public long[] countOfPairs(int n, int x, int y) { + if (x > y) { + final int temp = x; + x = y; + y = temp; + } + + final int ringLen = y - x + 1; + final int leftLineLen = x - 1; + final int rightLineLen = n - y; + + long[] ans = new long[n]; + ans = addVectors(ans, bothInRing(n, ringLen)); + ans = addVectors(ans, bothInTheSameLine(n, leftLineLen)); + ans = addVectors(ans, bothInTheSameLine(n, rightLineLen)); + ans = addVectors(ans, lineToRing(n, leftLineLen, ringLen)); + ans = addVectors(ans, lineToRing(n, rightLineLen, ringLen)); + ans = addVectors(ans, lineToLine(n, x, y, leftLineLen, rightLineLen)); + for (int i = 0; i < ans.length; ++i) + ans[i] *= 2; + return ans; + } + + // Returns the contribution from the scenario where two houses are located in + // the ring. + private long[] bothInRing(int n, int ringLen) { + long[] res = new long[n]; + for (int k = 1; k <= (ringLen - 1) / 2; ++k) + res[k - 1] += ringLen; + if (ringLen % 2 == 0) + res[ringLen / 2 - 1] += ringLen / 2; + return res; + } + + // Returns the contribution from the scenario where two houses are either + // located in the left line [1, x) or the right line (y, n]. + private long[] bothInTheSameLine(int n, int lineLen) { + long[] res = new long[n]; + for (int k = 1; k <= lineLen; ++k) + res[k - 1] += lineLen - k; + return res; + } + + // Returns the contribution from the scenario where one house is either + // located in the left line [1, x) or the right line (y, n] and the other + // house is located in the cycle. + private long[] lineToRing(int n, int lineLen, int ringLen) { + long[] res = new long[n]; + for (int k = 1; k <= lineLen + ringLen; ++k) { + // min( + // at most k - 1 since we need to give 1 to the line, + // at most ringLen / 2 since for length > ringLen / 2, it can always be + // calculated as ringLen - ringLen / 2 + // ) + final int maxInRingLen = Math.min(k - 1, ringLen / 2); + // max(at least 0, at lest k - lineLen) + final int minInRingLen = Math.max(0, k - lineLen); + if (minInRingLen <= maxInRingLen) { + // Each ring length contributes 2 to the count due to the split of + // paths when entering the ring: One path traverses the upper half of + // the ring, and the other traverses the lower half. + // This is illustrated as follows: + // Path 1: ... -- x -- (upper half of the ring) + // Path 2: ... -- x -- (lower half of the ring) + res[k - 1] += (maxInRingLen - minInRingLen + 1) * 2; + if (minInRingLen == 0) + // Subtract 1 since there's no split. + res[k - 1] -= 1; + if (maxInRingLen * 2 == ringLen) + // Subtract 1 since the following case only contribute one: + // ... -- x -- (upper half of the ring) -- middle point + // ... -- x -- (upper half of the ring) -- middle point + res[k - 1] -= 1; + } + } + return res; + } + + // Returns the contribution from the scenario where one house is in the left + // line [1, x) and the other house is in the right line (y, n]. + private long[] lineToLine(int n, int x, int y, int leftLineLen, int rightLineLen) { + long[] res = new long[n]; + for (int k = 1; k <= leftLineLen + rightLineLen + 2; ++k) { + // min( + // at most leftLineLen, + // at most k - 1 - (x < y) since we need to give 1 to the right line + // and if x < y we need to give another 1 to "x - y". + // ) + final int maxInLeft = Math.min(leftLineLen, k - 1 - (x < y ? 1 : 0)); + // max(at least 1, at least k - rightLineLen - (x < y)) + final int minInLeft = Math.max(1, k - rightLineLen - (x < y ? 1 : 0)); + if (minInLeft <= maxInLeft) + res[k - 1] += maxInLeft - minInLeft + 1; + } + return res; + } + + private long[] addVectors(long[] a, long[] b) { + for (int i = 0; i < a.length; ++i) + a[i] += b[i]; + return a; + } +} diff --git a/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.py b/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.py new file mode 100644 index 00000000000..d31aeadc9d5 --- /dev/null +++ b/solutions/3017. Count the Number of Houses at a Certain Distance II/3017.py @@ -0,0 +1,93 @@ +class Solution: + # Same as 3015. Count the Number of Houses at a Certain Distance I + def countOfPairs(self, n: int, x: int, y: int) -> List[int]: + if x > y: + x, y = y, x + + def bothInRing(ringLen: int) -> List[int]: + """ + Returns the contribution from the scenario where two houses are located + in the ring. + """ + res = [0] * n + for k in range(1, (ringLen - 1) // 2 + 1): + res[k - 1] += ringLen + if ringLen % 2 == 0: + res[ringLen // 2 - 1] += ringLen // 2 + return res + + def bothInTheSameLine(lineLen: int) -> List[int]: + """ + Returns the contribution from the scenario where two houses are either + located in the left line [1, x) or the right line (y, n]. + """ + res = [0] * n + for k in range(1, lineLen + 1): + res[k - 1] += lineLen - k + return res + + def lineToRing(lineLen: int, ringLen: int) -> List[int]: + """ + Returns the contribution from the scenario where one house is either + located in the left line [1, x) or the right line (y, n] and the + other house is located in the cycle. + """ + res = [0] * n + for k in range(1, lineLen + ringLen): + # min( + # at most k - 1 since we need to give 1 to the line, + # at most ringLen / 2 since for length > ringLen / 2, it can always be + # calculated as ringLen - ringLen / 2 + # ) + maxInRingLen = min(k - 1, ringLen // 2) + # max(at least 0, at lest k - lineLen) + minInRingLen = max(0, k - lineLen) + if minInRingLen <= maxInRingLen: + # Each ring length contributes 2 to the count due to the split of + # paths when entering the ring: One path traverses the upper half of + # the ring, and the other traverses the lower half. + # This is illustrated as follows: + # Path 1: ... -- x -- (upper half of the ring) + # Path 2: ... -- x -- (lower half of the ring) + res[k - 1] += (maxInRingLen - minInRingLen + 1) * 2 + if minInRingLen == 0: + # Subtract 1 since there's no split. + res[k - 1] -= 1 + if maxInRingLen * 2 == ringLen: + # Subtract 1 since the following case only contribute one: + # ... -- x -- (upper half of the ring) -- middle point + # ... -- x -- (upper half of the ring) -- middle point + res[k - 1] -= 1 + return res + + def lineToLine(leftLineLen: int, rightLineLen: int) -> List[int]: + """ + Returns the contribution from the scenario where one house is in the left + line [1, x) and the other house is in the right line (y, n]. + """ + res = [0] * n + for k in range(leftLineLen + rightLineLen + 2): + # min( + # at most leftLineLen, + # at most k - 1 - (x < y) since we need to give 1 to the right line + # and if x < y we need to give another 1 to "x - y". + # ) + maxInLeft = min(leftLineLen, k - 1 - (x < y)) + # max(at least 1, at least k - rightLineLen - (x < y)) + minInLeft = max(1, k - rightLineLen - (x < y)) + if minInLeft <= maxInLeft: + res[k - 1] += maxInLeft - minInLeft + 1 + return res + + ringLen = y - x + 1 + leftLineLen = x - 1 + rightLineLen = (n - y) + + ans = [0] * n + ans = list(map(operator.add, ans, bothInRing(ringLen))) + ans = list(map(operator.add, ans, bothInTheSameLine(leftLineLen))) + ans = list(map(operator.add, ans, bothInTheSameLine(rightLineLen))) + ans = list(map(operator.add, ans, lineToRing(leftLineLen, ringLen))) + ans = list(map(operator.add, ans, lineToRing(rightLineLen, ringLen))) + ans = list(map(operator.add, ans, lineToLine(leftLineLen, rightLineLen))) + return [freq * 2 for freq in ans] diff --git a/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.cpp b/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.cpp new file mode 100644 index 00000000000..0df1bcaa88f --- /dev/null +++ b/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int maximumProcessableQueries(vector& nums, vector& queries) { + const int n = nums.size(); + int ans = 0; + // dp[i][j] := the maximum number of queries processed if nums[i..j] are not + // removed after processing dp[i][j] queries + vector> dp(n, vector(n)); + + for (int d = n - 1; d >= 0; --d) { + for (int i = 0; i < n; ++i) { + const int j = i + d; + if (j >= n) + continue; + if (i > 0) + // Remove nums[i - 1] from nums[i - 1..j] if possible. + dp[i][j] = max(dp[i][j], + dp[i - 1][j] + (nums[i - 1] >= queries[dp[i - 1][j]])); + if (j + 1 < n) + // Remove nums[j + 1] from nums[i..j + 1] if possible. + dp[i][j] = max(dp[i][j], + dp[i][j + 1] + (nums[j + 1] >= queries[dp[i][j + 1]])); + if (dp[i][j] == queries.size()) + return queries.size(); + } + } + + for (int i = 0; i < n; ++i) + ans = max(ans, dp[i][i] + (nums[i] >= queries[dp[i][i]])); + + return ans; + } +}; diff --git a/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.java b/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.java new file mode 100644 index 00000000000..823d66c4d9b --- /dev/null +++ b/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.java @@ -0,0 +1,32 @@ +class Solution { + public int maximumProcessableQueries(int[] nums, int[] queries) { + final int n = nums.length; + int ans = 0; + // dp[i][j] := the maximum number of queries processed if nums[i..j] are not + // removed after processing dp[i][j] queries + int[][] dp = new int[n][n]; + + for (int d = n - 1; d >= 0; --d) { + for (int i = 0; i < n; ++i) { + final int j = i + d; + if (j >= n) + continue; + if (i > 0) + // Remove nums[i - 1] from nums[i - 1..j] if possible. + dp[i][j] = + Math.max(dp[i][j], dp[i - 1][j] + (nums[i - 1] >= queries[dp[i - 1][j]] ? 1 : 0)); + if (j + 1 < n) + // Remove nums[j + 1] from nums[i..j + 1] if possible. + dp[i][j] = + Math.max(dp[i][j], dp[i][j + 1] + (nums[j + 1] >= queries[dp[i][j + 1]] ? 1 : 0)); + if (dp[i][j] == queries.length) + return queries.length; + } + } + + for (int i = 0; i < n; ++i) + ans = Math.max(ans, dp[i][i] + (nums[i] >= queries[dp[i][i]] ? 1 : 0)); + + return ans; + } +} diff --git a/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.py b/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.py new file mode 100644 index 00000000000..8cccf8a19a0 --- /dev/null +++ b/solutions/3018. Maximum Number of Removal Queries That Can Be Processed I/3018.py @@ -0,0 +1,25 @@ +class Solution: + def maximumProcessableQueries(self, nums: List[int], queries: List[int]) -> int: + n = len(nums) + # dp[i][j] := the maximum number of queries processed if nums[i..j] are not + # removed after processing dp[i][j] queries + dp = [[0] * n for _ in range(n)] + + for d in range(n - 1, -1, -1): + for i in range(n): + j = i + d + if j >= n: + continue + if i > 0: + # Remove nums[i - 1] from nums[i - 1..j] if possible. + dp[i][j] = max(dp[i][j], dp[i - 1][j] + + (nums[i - 1] >= queries[dp[i - 1][j]])) + if j + 1 < n: + # Remove nums[j + 1] from nums[i..j + 1] if possible. + dp[i][j] = max(dp[i][j], dp[i][j + 1] + + (nums[j + 1] >= queries[dp[i][j + 1]])) + if dp[i][j] == len(queries): + return len(queries) + + return max(dp[i][i] + (nums[i] >= queries[dp[i][i]]) + for i in range(n)) diff --git a/solutions/3019. Number of Changing Keys/3019.cpp b/solutions/3019. Number of Changing Keys/3019.cpp new file mode 100644 index 00000000000..9011d8134c6 --- /dev/null +++ b/solutions/3019. Number of Changing Keys/3019.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int countKeyChanges(string s) { + int ans = 0; + for (int i = 1; i < s.length(); ++i) + if (tolower(s[i]) != tolower(s[i - 1])) + ++ans; + return ans; + } +}; diff --git a/solutions/3019. Number of Changing Keys/3019.java b/solutions/3019. Number of Changing Keys/3019.java new file mode 100644 index 00000000000..e081023424a --- /dev/null +++ b/solutions/3019. Number of Changing Keys/3019.java @@ -0,0 +1,9 @@ +class Solution { + public int countKeyChanges(String s) { + int ans = 0; + for (int i = 1; i < s.length(); ++i) + if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(i - 1))) + ++ans; + return ans; + } +} diff --git a/solutions/3019. Number of Changing Keys/3019.py b/solutions/3019. Number of Changing Keys/3019.py new file mode 100644 index 00000000000..9afd7e2d5fa --- /dev/null +++ b/solutions/3019. Number of Changing Keys/3019.py @@ -0,0 +1,4 @@ +class Solution: + def countKeyChanges(self, s: str) -> int: + return sum(a.lower() != b.lower() + for a, b in itertools.pairwise(s)) diff --git a/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.cpp b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.cpp new file mode 100644 index 00000000000..5ef548d6aa7 --- /dev/null +++ b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + int minArea(vector>& image, int x, int y) { + const int x1 = firstAnyOne(image, 0, x, &rowAllZeros); + const int x2 = firstAllZeros(image, x + 1, image.size(), &rowAllZeros); + const int y1 = firstAnyOne(image, 0, y, &colAllZeros); + const int y2 = firstAllZeros(image, y + 1, image[0].size(), &colAllZeros); + return (x2 - x1) * (y2 - y1); + } + + private: + int firstAnyOne(const vector>& image, int l, int r, + function>&, int)> allZeros) { + while (l < r) { + const int m = (l + r) / 2; + if (allZeros(image, m)) + l = m + 1; + else + r = m; + } + return l; + } + + int firstAllZeros(const vector>& image, int l, int r, + function>&, int)> allZeros) { + while (l < r) { + const int m = (l + r) / 2; + if (allZeros(image, m)) + r = m; + else + l = m + 1; + } + return l; + } + + static bool rowAllZeros(const vector>& image, int rowIndex) { + return all_of(image[rowIndex].cbegin(), image[rowIndex].cend(), + [](int pixel) { return pixel == '0'; }); + } + + static bool colAllZeros(const vector>& image, int colIndex) { + for (int i = 0; i < image.size(); ++i) + if (image[i][colIndex] == '1') + return false; + return true; + } +}; diff --git a/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.java b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.java new file mode 100644 index 00000000000..b99b5615d68 --- /dev/null +++ b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.java @@ -0,0 +1,49 @@ +class Solution { + public int minArea(char[][] image, int x, int y) { + this.image = image; + final int x1 = firstAnyOne(0, x, rowAllZeros); + final int x2 = firstAllZeros(x + 1, image.length, rowAllZeros); + final int y1 = firstAnyOne(0, y, colAllZeros); + final int y2 = firstAllZeros(y + 1, image[0].length, colAllZeros); + return (x2 - x1) * (y2 - y1); + } + + private char[][] image; + + private int firstAnyOne(int l, int r, Function allZeros) { + while (l < r) { + final int m = (l + r) / 2; + if (allZeros.apply(m)) + l = m + 1; + else + r = m; + } + return l; + } + + private int firstAllZeros(int l, int r, Function allZeros) { + while (l < r) { + final int m = (l + r) / 2; + if (allZeros.apply(m)) + r = m; + else + l = m + 1; + } + return l; + } + + Function rowAllZeros = new Function<>() { + public Boolean apply(Integer rowIndex) { + return new String(image[rowIndex]).chars().allMatch(pixel -> pixel == '0'); + } + }; + + Function colAllZeros = new Function<>() { + public Boolean apply(Integer colIndex) { + for (int i = 0; i < image.length; ++i) + if (image[i][colIndex] == '1') + return false; + return true; + } + }; +} diff --git a/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.py b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.py new file mode 100644 index 00000000000..18b7c288811 --- /dev/null +++ b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302-2.py @@ -0,0 +1,31 @@ +class Solution: + def minArea(self, image: List[List[str]], x: int, y: int) -> int: + def firstAnyOne(l: int, r: int, allZeros: Callable[[int], bool]) -> int: + while l < r: + m = (l + r) // 2 + if allZeros(m): + l = m + 1 + else: + r = m + return l + + def firstAllZeros(l: int, r: int, allZeros: Callable[[int], bool]) -> int: + while l < r: + m = (l + r) // 2 + if allZeros(m): + r = m + else: + l = m + 1 + return l + + def colAllZeros(colIndex: int) -> bool: + return all(pixel == '0' for pixel in list(zip(*image))[colIndex]) + + def rowAllZeros(rowIndex: int) -> bool: + return all(pixel == '0' for pixel in image[rowIndex]) + + x1 = firstAnyOne(0, x, rowAllZeros) + x2 = firstAllZeros(x + 1, len(image), rowAllZeros) + y1 = firstAnyOne(0, y, colAllZeros) + y2 = firstAllZeros(y + 1, len(image[0]), colAllZeros) + return (x2 - x1) * (y2 - y1) diff --git a/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.cpp b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.cpp new file mode 100644 index 00000000000..baf45cdffdf --- /dev/null +++ b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int minArea(vector>& image, int x, int y) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = image.size(); + const int n = image[0].size(); + vector topLeft{x, y}; + vector bottomRight{x, y}; + queue> q{{{x, y}}}; + image[x][y] = '2'; // Mark as visited. + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int r = i + dx; + const int c = j + dy; + if (r < 0 || r == m || c < 0 || c == n) + continue; + if (image[r][c] != '1') + continue; + topLeft[0] = min(topLeft[0], r); + topLeft[1] = min(topLeft[1], c); + bottomRight[0] = max(bottomRight[0], r); + bottomRight[1] = max(bottomRight[1], c); + q.emplace(r, c); + image[r][c] = '2'; + } + } + + const int width = bottomRight[1] - topLeft[1] + 1; + const int height = bottomRight[0] - topLeft[0] + 1; + return width * height; + } +}; diff --git a/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.java b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.java new file mode 100644 index 00000000000..39d03afa96a --- /dev/null +++ b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.java @@ -0,0 +1,34 @@ +class Solution { + public int minArea(char[][] image, int x, int y) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = image.length; + final int n = image[0].length; + int[] topLeft = {x, y}; + int[] bottomRight = {x, y}; + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {x, y})); + image[x][y] = '2'; // Mark as visited. + + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int r = i + dir[0]; + final int c = j + dir[1]; + if (r < 0 || r == m || c < 0 || c == n) + continue; + if (image[r][c] != '1') + continue; + topLeft[0] = Math.min(topLeft[0], r); + topLeft[1] = Math.min(topLeft[1], c); + bottomRight[0] = Math.max(bottomRight[0], r); + bottomRight[1] = Math.max(bottomRight[1], c); + q.offer(new int[] {r, c}); + image[r][c] = '2'; + } + } + + final int width = bottomRight[1] - topLeft[1] + 1; + final int height = bottomRight[0] - topLeft[0] + 1; + return width * height; + } +} diff --git a/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.py b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.py new file mode 100644 index 00000000000..c70689b37e1 --- /dev/null +++ b/solutions/302. Smallest Rectangle Enclosing Black Pixels/302.py @@ -0,0 +1,29 @@ +class Solution: + def minArea(self, image: List[List[str]], x: int, y: int) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(image) + n = len(image[0]) + topLeft = [x, y] + bottomRight = [x, y] + q = collections.deque([(x, y)]) + image[x][y] = '2' # Mark as visited. + + while q: + i, j = q.popleft() + for dx, dy in dirs: + r = i + dx + c = j + dy + if r < 0 or r == m or c < 0 or c == n: + continue + if image[r][c] != '1': + continue + topLeft[0] = min(topLeft[0], r) + topLeft[1] = min(topLeft[1], c) + bottomRight[0] = max(bottomRight[0], r) + bottomRight[1] = max(bottomRight[1], c) + q.append((r, c)) + image[r][c] = '2' + + width = bottomRight[1] - topLeft[1] + 1 + height = bottomRight[0] - topLeft[0] + 1 + return width * height diff --git a/solutions/3020. Find the Maximum Number of Elements in Subset/3020.cpp b/solutions/3020. Find the Maximum Number of Elements in Subset/3020.cpp new file mode 100644 index 00000000000..e4d376b5dd4 --- /dev/null +++ b/solutions/3020. Find the Maximum Number of Elements in Subset/3020.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maximumLength(vector& nums) { + const int maxNum = ranges::max(nums); + unordered_map count; + + for (const int num : nums) + ++count[num]; + + int ans = count.contains(1) ? count[1] - (count[1] % 2 == 0) : 1; + + for (const int num : nums) { + if (num == 1) + continue; + int length = 0; + long x = num; + while (x <= maxNum && count.contains(x) && count[x] >= 2) { + length += 2; + x *= x; + } + // x is now x^k, and the pattern is [x, ..., x^(k/2), x^(k/2), ..., x]. + // The goal is to determine if we can insert x^k in the middle of the + // pattern to increase the length by 1. If not, we make x^(k/2) the middle + // and decrease the length by 1. + ans = max(ans, length + (count.contains(x) ? 1 : -1)); + } + + return ans; + } +}; diff --git a/solutions/3020. Find the Maximum Number of Elements in Subset/3020.java b/solutions/3020. Find the Maximum Number of Elements in Subset/3020.java new file mode 100644 index 00000000000..91c367680c5 --- /dev/null +++ b/solutions/3020. Find the Maximum Number of Elements in Subset/3020.java @@ -0,0 +1,29 @@ +class Solution { + public int maximumLength(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + int ans = count.containsKey(1) ? count.get(1) - (count.get(1) % 2 == 0 ? 1 : 0) : 1; + + for (final int num : nums) { + if (num == 1) + continue; + int length = 0; + long x = num; + while (x <= maxNum && count.containsKey((int) x) && count.get((int) x) >= 2) { + length += 2; + x *= x; + } + // x is now x^k, and the pattern is [x, ..., x^(k/2), x^(k/2), ..., x]. + // The goal is to determine if we can insert x^k in the middle of the + // pattern to increase the length by 1. If not, we make x^(k/2) the middle + // and decrease the length by 1. + ans = Math.max(ans, length + (count.containsKey((int) x) ? 1 : -1)); + } + + return ans; + } +} diff --git a/solutions/3020. Find the Maximum Number of Elements in Subset/3020.py b/solutions/3020. Find the Maximum Number of Elements in Subset/3020.py new file mode 100644 index 00000000000..6d0df4b0fb4 --- /dev/null +++ b/solutions/3020. Find the Maximum Number of Elements in Subset/3020.py @@ -0,0 +1,21 @@ +class Solution: + def maximumLength(self, nums: List[int]) -> int: + maxNum = max(nums) + count = collections.Counter(nums) + ans = count[1] - (count[1] % 2 == 0) if 1 in count else 1 + + for num in nums: + if num == 1: + continue + length = 0 + x = num + while x <= maxNum and x in count and count[x] >= 2: + length += 2 + x *= x + # x is now x^k, and the pattern is [x, ..., x^(k/2), x^(k/2), ..., x]. + # The goal is to determine if we can insert x^k in the middle of the + # pattern to increase the length by 1. If not, we make x^(k/2) the middle + # and decrease the length by 1. + ans = max(ans, length + (1 if x in count else -1)) + + return ans diff --git a/solutions/3021. Alice and Bob Playing Flower Game/3021.cpp b/solutions/3021. Alice and Bob Playing Flower Game/3021.cpp new file mode 100644 index 00000000000..bd5c7a6cc32 --- /dev/null +++ b/solutions/3021. Alice and Bob Playing Flower Game/3021.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + long long flowerGame(int n, int m) { + // Alice wins if x + y is odd, occurring when: + // 1. x is even and y is odd, or + // 2. y is even and x is odd. + const int xEven = n / 2; + const int yEven = m / 2; + const int xOdd = (n + 1) / 2; + const int yOdd = (m + 1) / 2; + return static_cast(xEven) * yOdd + static_cast(yEven) * xOdd; + } +}; diff --git a/solutions/3021. Alice and Bob Playing Flower Game/3021.java b/solutions/3021. Alice and Bob Playing Flower Game/3021.java new file mode 100644 index 00000000000..79468aa5e0c --- /dev/null +++ b/solutions/3021. Alice and Bob Playing Flower Game/3021.java @@ -0,0 +1,12 @@ +class Solution { + public long flowerGame(int n, int m) { + // Alice wins if x + y is odd, occurring when: + // 1. x is even and y is odd, or + // 2. y is even and x is odd. + final int xEven = n / 2; + final int yEven = m / 2; + final int xOdd = (n + 1) / 2; + final int yOdd = (m + 1) / 2; + return (long) xEven * yOdd + (long) yEven * xOdd; + } +} diff --git a/solutions/3021. Alice and Bob Playing Flower Game/3021.py b/solutions/3021. Alice and Bob Playing Flower Game/3021.py new file mode 100644 index 00000000000..422c54a0d79 --- /dev/null +++ b/solutions/3021. Alice and Bob Playing Flower Game/3021.py @@ -0,0 +1,10 @@ +class Solution: + def flowerGame(self, n: int, m: int) -> int: + # Alice wins if x + y is odd, occurring when: + # 1. x is even and y is odd, or + # 2. y is even and x is odd. + xEven = n // 2 + yEven = m // 2 + xOdd = (n + 1) // 2 + yOdd = (m + 1) // 2 + return xEven * yOdd + yEven * xOdd diff --git a/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.cpp b/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.cpp new file mode 100644 index 00000000000..02830ca9fa7 --- /dev/null +++ b/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int minOrAfterOperations(vector& nums, int k) { + constexpr int kMaxBit = 30; + int ans = 0; + int prefixMask = 0; // Grows like: 10000 -> 11000 -> ... -> 11111. + + for (int i = kMaxBit; i >= 0; --i) { + // Add the i-th bit to `prefixMask` and attempt to "turn off" the + // currently added bit within k operations. If it's impossible, then we + // add the i-th bit to the answer. + prefixMask |= 1 << i; + if (getMergeOps(nums, prefixMask, ans) > k) + ans |= 1 << i; + } + + return ans; + } + + private: + // Returns the number of merge operations to turn `prefixMask` to the target + // by ANDing `nums`. + int getMergeOps(const vector& nums, int prefixMask, int target) { + int mergeOps = 0; + int ands = prefixMask; + for (const int num : nums) { + ands &= num; + if ((ands | target) == target) + ands = prefixMask; + else + ++mergeOps; // Keep merging the next num. + } + return mergeOps; + } +}; diff --git a/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.java b/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.java new file mode 100644 index 00000000000..17e88d50cce --- /dev/null +++ b/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.java @@ -0,0 +1,33 @@ +class Solution { + public int minOrAfterOperations(int[] nums, int k) { + final int kMaxBit = 30; + int ans = 0; + int prefixMask = 0; // Grows like: 10000 -> 11000 -> ... -> 11111. + + for (int i = kMaxBit; i >= 0; --i) { + // Add the i-th bit to `prefixMask` and attempt to "turn off" the + // currently added bit within k operations. If it's impossible, then we + // add the i-th bit to the answer. + prefixMask |= 1 << i; + if (getMergeOps(nums, prefixMask, ans) > k) + ans |= 1 << i; + } + + return ans; + } + + // Returns the number of merge operations to turn `prefixMask` to the target + // by ANDing `nums`. + private int getMergeOps(int[] nums, int prefixMask, int target) { + int mergeOps = 0; + int ands = prefixMask; + for (final int num : nums) { + ands &= num; + if ((ands | target) == target) + ands = prefixMask; + else + ++mergeOps; // Keep merging the next num. + } + return mergeOps; + } +} diff --git a/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.py b/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.py new file mode 100644 index 00000000000..5ce51bf6056 --- /dev/null +++ b/solutions/3022. Minimize OR of Remaining Elements Using Operations/3022.py @@ -0,0 +1,30 @@ +class Solution: + def minOrAfterOperations(self, nums: List[int], k: int) -> int: + kMaxBit = 30 + ans = 0 + prefixMask = 0 # Grows like: 10000 -> 11000 -> ... -> 11111 + + for i in range(kMaxBit, -1, -1): + # Add the i-th bit to `prefixMask` and attempt to "turn off" the + # currently added bit within k operations. If it's impossible, then we + # add the i-th bit to the answer. + prefixMask |= 1 << i + if self._getMergeOps(nums, prefixMask, ans) > k: + ans |= 1 << i + + return ans + + def _getMergeOps(self, nums: List[int], prefixMask: int, target: int) -> int: + """ + Returns the number of merge operations to turn `prefixMask` to the target + by ANDing `nums`. + """ + mergeOps = 0 + ands = prefixMask + for num in nums: + ands &= num + if (ands | target) == target: + ands = prefixMask + else: + mergeOps += 1 # Keep merging the next num + return mergeOps diff --git a/solutions/3023. Find Pattern in Infinite Stream I/3023.cpp b/solutions/3023. Find Pattern in Infinite Stream I/3023.cpp new file mode 100644 index 00000000000..6641d22ac57 --- /dev/null +++ b/solutions/3023. Find Pattern in Infinite Stream I/3023.cpp @@ -0,0 +1,53 @@ +/** + * Definition for an infinite stream. + * class InfiniteStream { + * public: + * InfiniteStream(vector bits); + * int next(); + * }; + */ + +class Solution { + public: + int findPattern(InfiniteStream* stream, vector& pattern) { + const vector lps = getLPS(pattern); + int i = 0; // stream's index + int j = 0; // pattern's index + int bit = 0; // the bit in the stream + bool readNext = false; + while (true) { + if (!readNext) { + bit = stream->next(); + readNext = true; + } + if (bit == pattern[j]) { + ++i, readNext = false; + ++j; + if (j == pattern.size()) + return i - j; + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i, readNext = false; + } + } + throw; + } + + private: + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + vector getLPS(const vector& pattern) { + vector lps(pattern.size()); + for (int i = 1, j = 0; i < pattern.size(); ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +}; diff --git a/solutions/3023. Find Pattern in Infinite Stream I/3023.java b/solutions/3023. Find Pattern in Infinite Stream I/3023.java new file mode 100644 index 00000000000..404f38aacaa --- /dev/null +++ b/solutions/3023. Find Pattern in Infinite Stream I/3023.java @@ -0,0 +1,52 @@ +/** + * Definition for an infinite stream. + * class InfiniteStream { + * public InfiniteStream(int[] bits); + * public int next(); + * } + */ + +class Solution { + public int findPattern(InfiniteStream stream, int[] pattern) { + int[] lps = getLPS(pattern); + int i = 0; // stream's index + int j = 0; // pattern's index + int bit = 0; // the bit in the stream + boolean readNext = false; + while (true) { + if (!readNext) { + bit = stream.next(); + readNext = true; + } + if (bit == pattern[j]) { + ++i; + readNext = false; + ++j; + if (j == pattern.length) + return i - j; + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + readNext = false; + } + } + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + private int[] getLPS(int[] pattern) { + int[] lps = new int[pattern.length]; + int j = 0; + for (int i = 1; i < pattern.length; ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +} diff --git a/solutions/3023. Find Pattern in Infinite Stream I/3023.py b/solutions/3023. Find Pattern in Infinite Stream I/3023.py new file mode 100644 index 00000000000..03bb3a71cc5 --- /dev/null +++ b/solutions/3023. Find Pattern in Infinite Stream I/3023.py @@ -0,0 +1,44 @@ +# Definition for an infinite stream. +# class InfiniteStream: +# def next(self) -> int: +# pass + +class Solution: + def findPattern(self, stream: Optional['InfiniteStream'], pattern: List[int]) -> int: + lps = self._getLPS(pattern) + i = 0 # stream's index + j = 0 # pattern's index + bit = 0 # the bit in the stream + readNext = False + while True: + if not readNext: + bit = stream.next() + readNext = True + if bit == pattern[j]: + i += 1 + readNext = False + j += 1 + if j == len(pattern): + return i - j + # Mismatch after j matches. + elif j > 0: + # Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1] + else: + i += 1 + readNext = False + + def _getLPS(self, pattern: List[int]) -> List[int]: + """ + Returns the lps array, where lps[i] is the length of the longest prefix of + pattern[0..i] which is also a suffix of this substring. + """ + lps = [0] * len(pattern) + j = 0 + for i in range(1, len(pattern)): + while j > 0 and pattern[j] != pattern[i]: + j = lps[j - 1] + if pattern[i] == pattern[j]: + j += 1 + lps[i] = j + return lps diff --git a/solutions/3024. Type of Triangle II Easy/3024.cpp b/solutions/3024. Type of Triangle II Easy/3024.cpp new file mode 100644 index 00000000000..a37e965af09 --- /dev/null +++ b/solutions/3024. Type of Triangle II Easy/3024.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + string triangleType(vector& nums) { + ranges::sort(nums); + if (nums[0] + nums[1] <= nums[2]) + return "none"; + if (nums[0] == nums[1] && nums[1] == nums[2]) + return "equilateral"; + if (nums[0] == nums[1] || nums[1] == nums[2]) + return "isosceles"; + return "scalene"; + } +}; diff --git a/solutions/3024. Type of Triangle II Easy/3024.java b/solutions/3024. Type of Triangle II Easy/3024.java new file mode 100644 index 00000000000..93b71449150 --- /dev/null +++ b/solutions/3024. Type of Triangle II Easy/3024.java @@ -0,0 +1,12 @@ +class Solution { + public String triangleType(int[] nums) { + Arrays.sort(nums); + if (nums[0] + nums[1] <= nums[2]) + return "none"; + if (nums[0] == nums[1] && nums[1] == nums[2]) + return "equilateral"; + if (nums[0] == nums[1] || nums[1] == nums[2]) + return "isosceles"; + return "scalene"; + } +} diff --git a/solutions/3024. Type of Triangle II Easy/3024.py b/solutions/3024. Type of Triangle II Easy/3024.py new file mode 100644 index 00000000000..68c19d52cda --- /dev/null +++ b/solutions/3024. Type of Triangle II Easy/3024.py @@ -0,0 +1,10 @@ +class Solution: + def triangleType(self, nums: List[int]) -> str: + nums.sort() + if nums[0] + nums[1] <= nums[2]: + return 'none' + if nums[0] == nums[1] and nums[1] == nums[2]: + return 'equilateral' + if nums[0] == nums[1] or nums[1] == nums[2]: + return 'isosceles' + return 'scalene' diff --git a/solutions/3025. Find the Number of Ways to Place People I/3025.cpp b/solutions/3025. Find the Number of Ways to Place People I/3025.cpp new file mode 100644 index 00000000000..b4284af1e75 --- /dev/null +++ b/solutions/3025. Find the Number of Ways to Place People I/3025.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int numberOfPairs(vector>& points) { + int ans = 0; + + ranges::sort(points, [](const vector& a, const vector& b) { + return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]); + }); + + for (int i = 0; i < points.size(); ++i) { + int maxY = INT_MIN; + for (int j = i + 1; j < points.size(); ++j) + if (points[i][1] >= points[j][1] && points[j][1] > maxY) { + ++ans; + maxY = points[j][1]; + } + } + + return ans; + } +}; diff --git a/solutions/3025. Find the Number of Ways to Place People I/3025.java b/solutions/3025. Find the Number of Ways to Place People I/3025.java new file mode 100644 index 00000000000..ca465d25dbb --- /dev/null +++ b/solutions/3025. Find the Number of Ways to Place People I/3025.java @@ -0,0 +1,18 @@ +class Solution { + public int numberOfPairs(int[][] points) { + int ans = 0; + + Arrays.sort(points, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + + for (int i = 0; i < points.length; ++i) { + int maxY = Integer.MIN_VALUE; + for (int j = i + 1; j < points.length; ++j) + if (points[i][1] >= points[j][1] && points[j][1] > maxY) { + ++ans; + maxY = points[j][1]; + } + } + + return ans; + } +} diff --git a/solutions/3025. Find the Number of Ways to Place People I/3025.py b/solutions/3025. Find the Number of Ways to Place People I/3025.py new file mode 100644 index 00000000000..7412f29fde5 --- /dev/null +++ b/solutions/3025. Find the Number of Ways to Place People I/3025.py @@ -0,0 +1,18 @@ +class Solution: + def numberOfPairs(self, points: List[List[int]]) -> int: + ans = 0 + + points.sort(key=lambda x: (x[0], -x[1])) + + for i, (_, yi) in enumerate(points): + maxY = -math.inf + for j in range(i + 1, len(points)): + _, yj = points[j] + # Chisato is in the upper-left corner at (xi, yi), and Takina is in the + # lower-right corner at (xj, yj). Also, if yj > maxY, it means that + # nobody other than Chisato and Takina is inside or on the fence. + if yi >= yj > maxY: + ans += 1 + maxY = yj + + return ans diff --git a/solutions/3026. Maximum Good Subarray Sum/3026.cpp b/solutions/3026. Maximum Good Subarray Sum/3026.cpp new file mode 100644 index 00000000000..65e5ff5ea48 --- /dev/null +++ b/solutions/3026. Maximum Good Subarray Sum/3026.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + long long maximumSubarraySum(vector& nums, int k) { + long ans = LONG_MIN; + long prefix = 0; + // {num: the minimum prefix sum excluding `num`} + unordered_map numToMinPrefix; + + for (const int num : nums) { + if (const auto it = numToMinPrefix.find(num); + it == numToMinPrefix.cend() || it->second > prefix) { + numToMinPrefix[num] = prefix; + } + prefix += num; + if (const auto it = numToMinPrefix.find(num + k); + it != numToMinPrefix.cend()) + ans = max(ans, prefix - it->second); + if (const auto it = numToMinPrefix.find(num - k); + it != numToMinPrefix.cend()) + ans = max(ans, prefix - it->second); + } + + return ans == LONG_MIN ? 0 : ans; + } +}; diff --git a/solutions/3026. Maximum Good Subarray Sum/3026.java b/solutions/3026. Maximum Good Subarray Sum/3026.java new file mode 100644 index 00000000000..44661b9e624 --- /dev/null +++ b/solutions/3026. Maximum Good Subarray Sum/3026.java @@ -0,0 +1,19 @@ +class Solution { + public long maximumSubarraySum(int[] nums, int k) { + long ans = Long.MIN_VALUE; + long prefix = 0; + Map numToMinPrefix = new HashMap<>(); + + for (final int num : nums) { + if (!numToMinPrefix.containsKey(num) || numToMinPrefix.get(num) > prefix) + numToMinPrefix.put(num, prefix); + prefix += num; + if (numToMinPrefix.containsKey(num + k)) + ans = Math.max(ans, prefix - numToMinPrefix.get(num + k)); + if (numToMinPrefix.containsKey(num - k)) + ans = Math.max(ans, prefix - numToMinPrefix.get(num - k)); + } + + return ans == Long.MIN_VALUE ? 0 : ans; + } +} diff --git a/solutions/3026. Maximum Good Subarray Sum/3026.py b/solutions/3026. Maximum Good Subarray Sum/3026.py new file mode 100644 index 00000000000..2252e9c4807 --- /dev/null +++ b/solutions/3026. Maximum Good Subarray Sum/3026.py @@ -0,0 +1,16 @@ +class Solution: + def maximumSubarraySum(self, nums: List[int], k: int) -> int: + ans = -math.inf + prefix = 0 + numToMinPrefix = {} + + for num in nums: + if num not in numToMinPrefix or numToMinPrefix[num] > prefix: + numToMinPrefix[num] = prefix + prefix += num + if num + k in numToMinPrefix: + ans = max(ans, prefix - numToMinPrefix[num + k]) + if num - k in numToMinPrefix: + ans = max(ans, prefix - numToMinPrefix[num - k]) + + return 0 if ans == -math.inf else ans diff --git a/solutions/3027. Find the Number of Ways to Place People II/3027.cpp b/solutions/3027. Find the Number of Ways to Place People II/3027.cpp new file mode 100644 index 00000000000..16ed4c797d3 --- /dev/null +++ b/solutions/3027. Find the Number of Ways to Place People II/3027.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + // Same as 3025. Find the Number of Ways to Place People I + int numberOfPairs(vector>& points) { + int ans = 0; + + ranges::sort(points, [](const vector& a, const vector& b) { + return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]); + }); + + for (int i = 0; i < points.size(); ++i) { + int maxY = INT_MIN; + for (int j = i + 1; j < points.size(); ++j) + if (points[i][1] >= points[j][1] && points[j][1] > maxY) { + ++ans; + maxY = points[j][1]; + } + } + + return ans; + } +}; diff --git a/solutions/3027. Find the Number of Ways to Place People II/3027.java b/solutions/3027. Find the Number of Ways to Place People II/3027.java new file mode 100644 index 00000000000..dcffe54f736 --- /dev/null +++ b/solutions/3027. Find the Number of Ways to Place People II/3027.java @@ -0,0 +1,19 @@ +class Solution { + // Same as 3025. Find the Number of Ways to Place People I + public int numberOfPairs(int[][] points) { + int ans = 0; + + Arrays.sort(points, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + + for (int i = 0; i < points.length; ++i) { + int maxY = Integer.MIN_VALUE; + for (int j = i + 1; j < points.length; ++j) + if (points[i][1] >= points[j][1] && points[j][1] > maxY) { + ++ans; + maxY = points[j][1]; + } + } + + return ans; + } +} diff --git a/solutions/3027. Find the Number of Ways to Place People II/3027.py b/solutions/3027. Find the Number of Ways to Place People II/3027.py new file mode 100644 index 00000000000..704e6acb8ef --- /dev/null +++ b/solutions/3027. Find the Number of Ways to Place People II/3027.py @@ -0,0 +1,19 @@ +class Solution: + # Same as 3025. Find the Number of Ways to Place People I + def numberOfPairs(self, points: List[List[int]]) -> int: + ans = 0 + + points.sort(key=lambda x: (x[0], -x[1])) + + for i, (_, yi) in enumerate(points): + maxY = -math.inf + for j in range(i + 1, len(points)): + _, yj = points[j] + # Chisato is in the upper-left corner at (xi, yi), and Takina is in the + # lower-right corner at (xj, yj). Also, if yj > maxY, it means that + # nobody other than Chisato and Takina is inside or on the fence. + if yi >= yj > maxY: + ans += 1 + maxY = yj + + return ans diff --git a/solutions/3028. Ant on the Boundary/3028.cpp b/solutions/3028. Ant on the Boundary/3028.cpp new file mode 100644 index 00000000000..2c5bd62a2f9 --- /dev/null +++ b/solutions/3028. Ant on the Boundary/3028.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int returnToBoundaryCount(vector& nums) { + partial_sum(nums.begin(), nums.end(), nums.begin()); + return ranges::count(nums, 0); + } +}; diff --git a/solutions/3028. Ant on the Boundary/3028.java b/solutions/3028. Ant on the Boundary/3028.java new file mode 100644 index 00000000000..367f6b8a72f --- /dev/null +++ b/solutions/3028. Ant on the Boundary/3028.java @@ -0,0 +1,14 @@ +class Solution { + public int returnToBoundaryCount(int[] nums) { + int ans = 0; + int prefix = 0; + + for (final int num : nums) { + prefix += num; + if (prefix == 0) + ++ans; + } + + return ans; + } +} diff --git a/solutions/3028. Ant on the Boundary/3028.py b/solutions/3028. Ant on the Boundary/3028.py new file mode 100644 index 00000000000..6c7ff82dd3f --- /dev/null +++ b/solutions/3028. Ant on the Boundary/3028.py @@ -0,0 +1,3 @@ +class Solution: + def returnToBoundaryCount(self, nums: List[int]) -> int: + return sum(prefix == 0 for prefix in itertools.accumulate(nums)) diff --git a/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.cpp b/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.cpp new file mode 100644 index 00000000000..c078f3a5db6 --- /dev/null +++ b/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + // Same as 3029. Minimum Time to Revert Word to Initial State I + int minimumTimeToInitialState(string word, int k) { + const int n = word.length(); + const int maxOps = (n - 1) / k + 1; + const vector z = zFunction(word); + for (int ans = 1; ans < maxOps; ++ans) + if (z[ans * k] >= n - ans * k) + return ans; + return maxOps; + } + + // Returns the z array, where z[i] is the length of the longest prefix of + // s[i..n) which is also a prefix of s. + // + // https://cp-algorithms.com/string/z-function.html#implementation + vector zFunction(const string& s) { + const int n = s.length(); + vector z(n); + int l = 0; + int r = 0; + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = min(r - i, z[i - l]); + while (i + z[i] < n && s[z[i]] == s[i + z[i]]) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + return z; + } +}; diff --git a/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.java b/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.java new file mode 100644 index 00000000000..fc92dfbecb4 --- /dev/null +++ b/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.java @@ -0,0 +1,34 @@ +class Solution { + // Same as 3029. Minimum Time to Revert Word to Initial State I + public int minimumTimeToInitialState(String word, int k) { + final int n = word.length(); + final int maxOps = (n - 1) / k + 1; + final int[] z = zFunction(word); + for (int ans = 1; ans < maxOps; ++ans) + if (z[ans * k] >= n - ans * k) + return ans; + return maxOps; + } + + // Returns the z array, where z[i] is the length of the longest prefix of + // s[i..n) which is also a prefix of s. + // + // https://cp-algorithms.com/string/z-function.html#implementation + private int[] zFunction(final String s) { + final int n = s.length(); + int[] z = new int[n]; + int l = 0; + int r = 0; + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = Math.min(r - i, z[i - l]); + while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + return z; + } +} diff --git a/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.py b/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.py new file mode 100644 index 00000000000..8d4dd7419d9 --- /dev/null +++ b/solutions/3029. Minimum Time to Revert Word to Initial State I/3029.py @@ -0,0 +1,33 @@ +class Solution: + # Same as 3029. Minimum Time to Revert Word to Initial State I + def minimumTimeToInitialState(self, word: str, k: int) -> int: + n = len(word) + maxOps = (n - 1) // k + 1 + z = self._zFunction(word) + + for ans in range(1, maxOps): + if z[ans * k] >= n - ans * k: + return ans + + return maxOps + + def _zFunction(self, s: str) -> List[int]: + """ + Returns the z array, where z[i] is the length of the longest prefix of + s[i..n) which is also a prefix of s. + + https://cp-algorithms.com/string/z-function.html#implementation + """ + n = len(s) + z = [0] * n + l = 0 + r = 0 + for i in range(1, n): + if i < r: + z[i] = min(r - i, z[i - l]) + while i + z[i] < n and s[z[i]] == s[i + z[i]]: + z[i] += 1 + if i + z[i] > r: + l = i + r = i + z[i] + return z diff --git a/solutions/303. Range Sum Query - Immutable/303.cpp b/solutions/303. Range Sum Query - Immutable/303.cpp new file mode 100644 index 00000000000..911e3590568 --- /dev/null +++ b/solutions/303. Range Sum Query - Immutable/303.cpp @@ -0,0 +1,13 @@ +class NumArray { + public: + NumArray(vector& nums) : prefix(nums.size() + 1) { + partial_sum(nums.begin(), nums.end(), prefix.begin() + 1); + } + + int sumRange(int left, int right) { + return prefix[right + 1] - prefix[left]; + } + + private: + vector prefix; +}; diff --git a/solutions/303. Range Sum Query - Immutable/303.java b/solutions/303. Range Sum Query - Immutable/303.java new file mode 100644 index 00000000000..37d46380fec --- /dev/null +++ b/solutions/303. Range Sum Query - Immutable/303.java @@ -0,0 +1,13 @@ +class NumArray { + public NumArray(int[] nums) { + prefix = new int[nums.length + 1]; + for (int i = 0; i < nums.length; ++i) + prefix[i + 1] = nums[i] + prefix[i]; + } + + public int sumRange(int left, int right) { + return prefix[right + 1] - prefix[left]; + } + + private int[] prefix; +} diff --git a/solutions/303. Range Sum Query - Immutable/303.py b/solutions/303. Range Sum Query - Immutable/303.py new file mode 100644 index 00000000000..430c4af588d --- /dev/null +++ b/solutions/303. Range Sum Query - Immutable/303.py @@ -0,0 +1,6 @@ +class NumArray: + def __init__(self, nums: List[int]): + self.prefix = [0] + list(itertools.accumulate(nums)) + + def sumRange(self, left: int, right: int) -> int: + return self.prefix[right + 1] - self.prefix[left] diff --git a/solutions/3030. Find the Grid of Region Average/3030.cpp b/solutions/3030. Find the Grid of Region Average/3030.cpp new file mode 100644 index 00000000000..4906092c182 --- /dev/null +++ b/solutions/3030. Find the Grid of Region Average/3030.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + vector> resultGrid(vector>& image, int threshold) { + const int m = image.size(); + const int n = image[0].size(); + vector> sums(m, vector(n)); + vector> counts(m, vector(n)); + + for (int i = 0; i < m - 2; ++i) + for (int j = 0; j < n - 2; ++j) + if (isRegion(image, i, j, threshold)) { + const int subgridSum = getSubgridSum(image, i, j); + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) { + sums[x][y] += subgridSum / 9; + counts[x][y] += 1; + } + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (counts[i][j] > 0) + image[i][j] = sums[i][j] / counts[i][j]; + + return image; + } + + private: + // Returns true if image[i..i + 2][j..j + 2] is a region. + bool isRegion(const vector>& image, int i, int j, int threshold) { + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) { + if (x > i && abs(image[x][y] - image[x - 1][y]) > threshold) + return false; + if (y > j && abs(image[x][y] - image[x][y - 1]) > threshold) + return false; + } + return true; + } + + // Returns the sum of image[i..i + 2][j..j + 2]. + int getSubgridSum(const vector>& image, int i, int j) { + int subgridSum = 0; + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) + subgridSum += image[x][y]; + return subgridSum; + } +}; diff --git a/solutions/3030. Find the Grid of Region Average/3030.java b/solutions/3030. Find the Grid of Region Average/3030.java new file mode 100644 index 00000000000..07ea459f9da --- /dev/null +++ b/solutions/3030. Find the Grid of Region Average/3030.java @@ -0,0 +1,47 @@ +class Solution { + public int[][] resultGrid(int[][] image, int threshold) { + final int m = image.length; + final int n = image[0].length; + int[][] sums = new int[m][n]; + int[][] counts = new int[m][n]; + + for (int i = 0; i < m - 2; ++i) + for (int j = 0; j < n - 2; ++j) + if (isRegion(image, i, j, threshold)) { + final int subgridSum = getSubgridSum(image, i, j); + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) { + sums[x][y] += subgridSum / 9; + counts[x][y] += 1; + } + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (counts[i][j] > 0) + image[i][j] = sums[i][j] / counts[i][j]; + + return image; + } + + // Returns true if image[i..i + 2][j..j + 2] is a region. + private boolean isRegion(int[][] image, int i, int j, int threshold) { + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) { + if (x > i && Math.abs(image[x][y] - image[x - 1][y]) > threshold) + return false; + if (y > j && Math.abs(image[x][y] - image[x][y - 1]) > threshold) + return false; + } + return true; + } + + // Returns the sum of image[i..i + 2][j..j + 2]. + private int getSubgridSum(int[][] image, int i, int j) { + int subgridSum = 0; + for (int x = i; x < i + 3; ++x) + for (int y = j; y < j + 3; ++y) + subgridSum += image[x][y]; + return subgridSum; + } +} diff --git a/solutions/3030. Find the Grid of Region Average/3030.py b/solutions/3030. Find the Grid of Region Average/3030.py new file mode 100644 index 00000000000..721cfdfa076 --- /dev/null +++ b/solutions/3030. Find the Grid of Region Average/3030.py @@ -0,0 +1,34 @@ +class Solution: + def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]: + m = len(image) + n = len(image[0]) + sums = [[0] * n for _ in range(m)] + counts = [[0] * n for _ in range(m)] + + for i in range(m - 2): + for j in range(n - 2): + if self._isRegion(image, i, j, threshold): + subgridSum = sum(image[x][y] + for x in range(i, i + 3) + for y in range(j, j + 3)) + for x in range(i, i + 3): + for y in range(j, j + 3): + sums[x][y] += subgridSum // 9 + counts[x][y] += 1 + + for i in range(m): + for j in range(n): + if counts[i][j] > 0: + image[i][j] = sums[i][j] // counts[i][j] + + return image + + def _isRegion(self, image: List[List[int]], i: int, j: int, threshold: int) -> bool: + """Returns True if image[i..i + 2][j..j + 2] is a region.""" + for x in range(i, i + 3): + for y in range(j, j + 3): + if x > i and abs(image[x][y] - image[x - 1][y]) > threshold: + return False + if y > j and abs(image[x][y] - image[x][y - 1]) > threshold: + return False + return True diff --git a/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.cpp b/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.cpp new file mode 100644 index 00000000000..c078f3a5db6 --- /dev/null +++ b/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + // Same as 3029. Minimum Time to Revert Word to Initial State I + int minimumTimeToInitialState(string word, int k) { + const int n = word.length(); + const int maxOps = (n - 1) / k + 1; + const vector z = zFunction(word); + for (int ans = 1; ans < maxOps; ++ans) + if (z[ans * k] >= n - ans * k) + return ans; + return maxOps; + } + + // Returns the z array, where z[i] is the length of the longest prefix of + // s[i..n) which is also a prefix of s. + // + // https://cp-algorithms.com/string/z-function.html#implementation + vector zFunction(const string& s) { + const int n = s.length(); + vector z(n); + int l = 0; + int r = 0; + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = min(r - i, z[i - l]); + while (i + z[i] < n && s[z[i]] == s[i + z[i]]) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + return z; + } +}; diff --git a/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.java b/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.java new file mode 100644 index 00000000000..fc92dfbecb4 --- /dev/null +++ b/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.java @@ -0,0 +1,34 @@ +class Solution { + // Same as 3029. Minimum Time to Revert Word to Initial State I + public int minimumTimeToInitialState(String word, int k) { + final int n = word.length(); + final int maxOps = (n - 1) / k + 1; + final int[] z = zFunction(word); + for (int ans = 1; ans < maxOps; ++ans) + if (z[ans * k] >= n - ans * k) + return ans; + return maxOps; + } + + // Returns the z array, where z[i] is the length of the longest prefix of + // s[i..n) which is also a prefix of s. + // + // https://cp-algorithms.com/string/z-function.html#implementation + private int[] zFunction(final String s) { + final int n = s.length(); + int[] z = new int[n]; + int l = 0; + int r = 0; + for (int i = 1; i < n; ++i) { + if (i < r) + z[i] = Math.min(r - i, z[i - l]); + while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) + ++z[i]; + if (i + z[i] > r) { + l = i; + r = i + z[i]; + } + } + return z; + } +} diff --git a/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.py b/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.py new file mode 100644 index 00000000000..8d4dd7419d9 --- /dev/null +++ b/solutions/3031. Minimum Time to Revert Word to Initial State II/3031.py @@ -0,0 +1,33 @@ +class Solution: + # Same as 3029. Minimum Time to Revert Word to Initial State I + def minimumTimeToInitialState(self, word: str, k: int) -> int: + n = len(word) + maxOps = (n - 1) // k + 1 + z = self._zFunction(word) + + for ans in range(1, maxOps): + if z[ans * k] >= n - ans * k: + return ans + + return maxOps + + def _zFunction(self, s: str) -> List[int]: + """ + Returns the z array, where z[i] is the length of the longest prefix of + s[i..n) which is also a prefix of s. + + https://cp-algorithms.com/string/z-function.html#implementation + """ + n = len(s) + z = [0] * n + l = 0 + r = 0 + for i in range(1, n): + if i < r: + z[i] = min(r - i, z[i - l]) + while i + z[i] < n and s[z[i]] == s[i + z[i]]: + z[i] += 1 + if i + z[i] > r: + l = i + r = i + z[i] + return z diff --git a/solutions/3032. Count Numbers With Unique Digits II/3032.cpp b/solutions/3032. Count Numbers With Unique Digits II/3032.cpp new file mode 100644 index 00000000000..55f7a04d31e --- /dev/null +++ b/solutions/3032. Count Numbers With Unique Digits II/3032.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int numberCount(int a, int b) { + int ans = 0; + for (int num = a; num <= b; ++num) + if (isUniqueDigits(num)) + ++ans; + return ans; + } + + private: + bool isUniqueDigits(int num) { + vector seen(10); + while (num > 0) { + const int digit = num % 10; + if (seen[digit]) + return false; + seen[digit] = true; + num /= 10; + } + return true; + } +}; diff --git a/solutions/3032. Count Numbers With Unique Digits II/3032.java b/solutions/3032. Count Numbers With Unique Digits II/3032.java new file mode 100644 index 00000000000..9578ce06fa0 --- /dev/null +++ b/solutions/3032. Count Numbers With Unique Digits II/3032.java @@ -0,0 +1,21 @@ +class Solution { + public int numberCount(int a, int b) { + int ans = 0; + for (int num = a; num <= b; ++num) + if (isUniqueDigits(num)) + ++ans; + return ans; + } + + private boolean isUniqueDigits(int num) { + boolean[] seen = new boolean[10]; + while (num > 0) { + final int digit = num % 10; + if (seen[digit]) + return false; + seen[digit] = true; + num /= 10; + } + return true; + } +} diff --git a/solutions/3032. Count Numbers With Unique Digits II/3032.py b/solutions/3032. Count Numbers With Unique Digits II/3032.py new file mode 100644 index 00000000000..65b9c69381c --- /dev/null +++ b/solutions/3032. Count Numbers With Unique Digits II/3032.py @@ -0,0 +1,4 @@ +class Solution: + def numberCount(self, a: int, b: int) -> int: + return sum(len(set(str(num))) == len(str(num)) + for num in range(a, b + 1)) diff --git a/solutions/3033. Modify the Matrix/3033.cpp b/solutions/3033. Modify the Matrix/3033.cpp new file mode 100644 index 00000000000..79949a2120a --- /dev/null +++ b/solutions/3033. Modify the Matrix/3033.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector> modifiedMatrix(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + vector> ans = matrix; + + for (int j = 0; j < n; ++j) { + int mx = 0; + for (int i = 0; i < m; ++i) + mx = max(mx, matrix[i][j]); + for (int i = 0; i < m; ++i) + if (matrix[i][j] == -1) + ans[i][j] = mx; + } + + return ans; + } +}; diff --git a/solutions/3033. Modify the Matrix/3033.java b/solutions/3033. Modify the Matrix/3033.java new file mode 100644 index 00000000000..be2539518d6 --- /dev/null +++ b/solutions/3033. Modify the Matrix/3033.java @@ -0,0 +1,18 @@ +class Solution { + public int[][] modifiedMatrix(int[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + int[][] ans = matrix.clone(); + + for (int j = 0; j < n; ++j) { + int mx = 0; + for (int i = 0; i < m; ++i) + mx = Math.max(mx, matrix[i][j]); + for (int i = 0; i < m; ++i) + if (matrix[i][j] == -1) + ans[i][j] = mx; + } + + return ans; + } +} diff --git a/solutions/3033. Modify the Matrix/3033.py b/solutions/3033. Modify the Matrix/3033.py new file mode 100644 index 00000000000..c5b636d5956 --- /dev/null +++ b/solutions/3033. Modify the Matrix/3033.py @@ -0,0 +1,13 @@ +class Solution: + def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]: + m = len(matrix) + n = len(matrix[0]) + ans = matrix.copy() + + for j in range(n): + mx = max(matrix[i][j] for i in range(m)) + for i in range(m): + if matrix[i][j] == -1: + ans[i][j] = mx + + return ans diff --git a/solutions/3034. Number of Subarrays That Match a Pattern I/3034.cpp b/solutions/3034. Number of Subarrays That Match a Pattern I/3034.cpp new file mode 100644 index 00000000000..f537274672c --- /dev/null +++ b/solutions/3034. Number of Subarrays That Match a Pattern I/3034.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + int countMatchingSubarrays(vector& nums, vector& pattern) { + const vector numsPattern = getNumsPattern(nums); + return kmp(numsPattern, pattern); + } + + private: + int getNum(int a, int b) { + if (a < b) + return 1; + if (a > b) + return -1; + return 0; + } + + vector getNumsPattern(const vector& nums) { + vector numsPattern; + for (int i = 1; i < nums.size(); ++i) + numsPattern.push_back(getNum(nums[i - 1], nums[i])); + return numsPattern; + } + + // Returns the number of occurrences of the pattern in `nums`. + int kmp(const vector& nums, const vector& pattern) { + const vector lps = getLPS(pattern); + int res = 0; + int i = 0; // nums' index + int j = 0; // pattern's index + while (i < nums.size()) { + if (nums[i] == pattern[j]) { + ++i; + ++j; + if (j == pattern.size()) { + ++res; + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + vector getLPS(const vector& pattern) { + vector lps(pattern.size()); + for (int i = 1, j = 0; i < pattern.size(); ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +}; diff --git a/solutions/3034. Number of Subarrays That Match a Pattern I/3034.java b/solutions/3034. Number of Subarrays That Match a Pattern I/3034.java new file mode 100644 index 00000000000..37a7b49c5ab --- /dev/null +++ b/solutions/3034. Number of Subarrays That Match a Pattern I/3034.java @@ -0,0 +1,60 @@ +class Solution { + public int countMatchingSubarrays(int[] nums, int[] pattern) { + int[] numsPattern = getNumsPattern(nums); + return kmp(numsPattern, pattern); + } + + private int getNum(int a, int b) { + if (a < b) + return 1; + if (a > b) + return -1; + return 0; + } + + private int[] getNumsPattern(int[] nums) { + int[] numsPattern = new int[nums.length - 1]; + for (int i = 1; i < nums.length; ++i) + numsPattern[i - 1] = getNum(nums[i - 1], nums[i]); + return numsPattern; + } + + // Returns the number of occurrences of the pattern in `nums`. + private int kmp(int[] nums, int[] pattern) { + int[] lps = getLPS(pattern); + int res = 0; + int i = 0; // nums' index + int j = 0; // pattern's index + while (i < nums.length) { + if (nums[i] == pattern[j]) { + ++i; + ++j; + if (j == pattern.length) { + ++res; + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the longest proper prefix of + // pattern[0..i] which is also a suffix of this substring. + private int[] getLPS(int[] pattern) { + int[] lps = new int[pattern.length]; + for (int i = 1, j = 0; i < pattern.length; ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +} diff --git a/solutions/3034. Number of Subarrays That Match a Pattern I/3034.py b/solutions/3034. Number of Subarrays That Match a Pattern I/3034.py new file mode 100644 index 00000000000..5ed7e51c211 --- /dev/null +++ b/solutions/3034. Number of Subarrays That Match a Pattern I/3034.py @@ -0,0 +1,48 @@ +class Solution: + def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: + def getNum(a: int, b: int) -> int: + if a < b: + return 1 + if a > b: + return -1 + return 0 + + numsPattern = [getNum(a, b) for a, b in itertools.pairwise(nums)] + return self._kmp(numsPattern, pattern) + + def _kmp(self, nums: List[int], pattern: List[int]) -> int: + """Returns the number of occurrences of the pattern in `nums`.""" + + def getLPS(nums: List[int]) -> List[int]: + """ + Returns the lps array, where lps[i] is the length of the longest prefix of + nums[0..i] which is also a suffix of this substring. + """ + lps = [0] * len(nums) + j = 0 + for i in range(1, len(nums)): + while j > 0 and nums[j] != nums[i]: + j = lps[j - 1] + if nums[i] == nums[j]: + lps[i] = j + 1 + j += 1 + return lps + + lps = getLPS(pattern) + res = 0 + i = 0 # s' index + j = 0 # pattern's index + while i < len(nums): + if nums[i] == pattern[j]: + i += 1 + j += 1 + if j == len(pattern): + res += 1 + j = lps[j - 1] + # Mismatch after j matches. + elif j != 0: + # Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1] + else: + i += 1 + return res diff --git a/solutions/3035. Maximum Palindromes After Operations/3035.cpp b/solutions/3035. Maximum Palindromes After Operations/3035.cpp new file mode 100644 index 00000000000..cfb49dc40bc --- /dev/null +++ b/solutions/3035. Maximum Palindromes After Operations/3035.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int maxPalindromesAfterOperations(vector& words) { + int ans = 0; + int pairs = getPairs(words); + + for (const int length : getSortedLengths(words)) { + const int needPairs = length / 2; + if (pairs < needPairs) + return ans; + ++ans; + pairs -= needPairs; + } + + return ans; + } + + private: + int getPairs(const vector& words) { + int pairs = 0; + unordered_map count; + + for (const string& word : words) + for (const char c : word) + ++count[c]; + + for (const auto& [_, freq] : count) + pairs += freq / 2; + + return pairs; + } + + vector getSortedLengths(const vector& words) { + vector lengths; + for (const string& word : words) + lengths.push_back(word.length()); + ranges::sort(lengths); + return lengths; + } +}; diff --git a/solutions/3035. Maximum Palindromes After Operations/3035.java b/solutions/3035. Maximum Palindromes After Operations/3035.java new file mode 100644 index 00000000000..7f764856571 --- /dev/null +++ b/solutions/3035. Maximum Palindromes After Operations/3035.java @@ -0,0 +1,38 @@ +class Solution { + public int maxPalindromesAfterOperations(String[] words) { + int ans = 0; + int pairs = getPairs(words); + + for (final int length : getSortedLengths(words)) { + final int neededPairs = length / 2; + if (pairs < neededPairs) + return ans; + ++ans; + pairs -= neededPairs; + } + + return ans; + } + + private int getPairs(String[] words) { + int pairs = 0; + Map count = new HashMap<>(); + + for (final String word : words) + for (final char c : word.toCharArray()) + count.merge(c, 1, Integer::sum); + + for (final int freq : count.values()) + pairs += freq / 2; + + return pairs; + } + + private int[] getSortedLengths(String[] words) { + int[] lengths = new int[words.length]; + for (int i = 0; i < words.length; ++i) + lengths[i] = words[i].length(); + Arrays.sort(lengths); + return lengths; + } +} diff --git a/solutions/3035. Maximum Palindromes After Operations/3035.py b/solutions/3035. Maximum Palindromes After Operations/3035.py new file mode 100644 index 00000000000..f132ada303c --- /dev/null +++ b/solutions/3035. Maximum Palindromes After Operations/3035.py @@ -0,0 +1,14 @@ +class Solution: + def maxPalindromesAfterOperations(self, words: List[str]) -> int: + ans = 0 + count = collections.Counter(''.join(words)) + pairs = sum(value // 2 for value in count.values()) + + for length in sorted(len(word) for word in words): + needPairs = length // 2 + if pairs < needPairs: + return ans + ans += 1 + pairs -= needPairs + + return ans diff --git a/solutions/3036. Number of Subarrays That Match a Pattern II/3036.cpp b/solutions/3036. Number of Subarrays That Match a Pattern II/3036.cpp new file mode 100644 index 00000000000..5daa441bfbe --- /dev/null +++ b/solutions/3036. Number of Subarrays That Match a Pattern II/3036.cpp @@ -0,0 +1,63 @@ +class Solution { + public: + // Same as 3034. Number of Subarrays That Match a Pattern I + int countMatchingSubarrays(vector& nums, vector& pattern) { + const vector numsPattern = getNumsPattern(nums); + return kmp(numsPattern, pattern); + } + + private: + int getNum(int a, int b) { + if (a < b) + return 1; + if (a > b) + return -1; + return 0; + } + + vector getNumsPattern(const vector& nums) { + vector numsPattern; + for (int i = 1; i < nums.size(); ++i) + numsPattern.push_back(getNum(nums[i - 1], nums[i])); + return numsPattern; + } + + // Returns the number of occurrences of the pattern in `nums`. + int kmp(const vector& nums, const vector& pattern) { + const vector lps = getLPS(pattern); + int res = 0; + int i = 0; // nums' index + int j = 0; // pattern's index + while (i < nums.size()) { + if (nums[i] == pattern[j]) { + ++i; + ++j; + if (j == pattern.size()) { + ++res; + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + vector getLPS(const vector& pattern) { + vector lps(pattern.size()); + for (int i = 1, j = 0; i < pattern.size(); ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +}; diff --git a/solutions/3036. Number of Subarrays That Match a Pattern II/3036.java b/solutions/3036. Number of Subarrays That Match a Pattern II/3036.java new file mode 100644 index 00000000000..e03d9cf999b --- /dev/null +++ b/solutions/3036. Number of Subarrays That Match a Pattern II/3036.java @@ -0,0 +1,61 @@ +class Solution { + // Same as 3034. Number of Subarrays That Match a Pattern I + public int countMatchingSubarrays(int[] nums, int[] pattern) { + int[] numsPattern = getNumsPattern(nums); + return kmp(numsPattern, pattern); + } + + private int getNum(int a, int b) { + if (a < b) + return 1; + if (a > b) + return -1; + return 0; + } + + private int[] getNumsPattern(int[] nums) { + int[] numsPattern = new int[nums.length - 1]; + for (int i = 1; i < nums.length; ++i) + numsPattern[i - 1] = getNum(nums[i - 1], nums[i]); + return numsPattern; + } + + // Returns the number of occurrences of the pattern in `nums`. + private int kmp(int[] nums, int[] pattern) { + int[] lps = getLPS(pattern); + int res = 0; + int i = 0; // nums' index + int j = 0; // pattern's index + while (i < nums.length) { + if (nums[i] == pattern[j]) { + ++i; + ++j; + if (j == pattern.length) { + ++res; + j = lps[j - 1]; + } + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + } + } + return res; + } + + // Returns the lps array, where lps[i] is the longest proper prefix of + // pattern[0..i] which is also a suffix of this substring. + private int[] getLPS(int[] pattern) { + int[] lps = new int[pattern.length]; + for (int i = 1, j = 0; i < pattern.length; ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +} diff --git a/solutions/3036. Number of Subarrays That Match a Pattern II/3036.py b/solutions/3036. Number of Subarrays That Match a Pattern II/3036.py new file mode 100644 index 00000000000..589539121ec --- /dev/null +++ b/solutions/3036. Number of Subarrays That Match a Pattern II/3036.py @@ -0,0 +1,49 @@ +class Solution: + # Same as 3034. Number of Subarrays That Match a Pattern I + def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: + def getNum(a: int, b: int) -> int: + if a < b: + return 1 + if a > b: + return -1 + return 0 + + numsPattern = [getNum(a, b) for a, b in itertools.pairwise(nums)] + return self._kmp(numsPattern, pattern) + + def _kmp(self, nums: List[int], pattern: List[int]) -> int: + """Returns the number of occurrences of the pattern in `nums`.""" + + def getLPS(nums: List[int]) -> List[int]: + """ + Returns the lps array, where lps[i] is the length of the longest prefix of + nums[0..i] which is also a suffix of this substring. + """ + lps = [0] * len(nums) + j = 0 + for i in range(1, len(nums)): + while j > 0 and nums[j] != nums[i]: + j = lps[j - 1] + if nums[i] == nums[j]: + lps[i] = j + 1 + j += 1 + return lps + + lps = getLPS(pattern) + res = 0 + i = 0 # s' index + j = 0 # pattern's index + while i < len(nums): + if nums[i] == pattern[j]: + i += 1 + j += 1 + if j == len(pattern): + res += 1 + j = lps[j - 1] + # Mismatch after j matches. + elif j != 0: + # Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1] + else: + i += 1 + return res diff --git a/solutions/3037. Find Pattern in Infinite Stream II/3037.cpp b/solutions/3037. Find Pattern in Infinite Stream II/3037.cpp new file mode 100644 index 00000000000..e882b8a3ff0 --- /dev/null +++ b/solutions/3037. Find Pattern in Infinite Stream II/3037.cpp @@ -0,0 +1,54 @@ +/** + * Definition for an infinite stream. + * class InfiniteStream { + * public: + * InfiniteStream(vector bits); + * int next(); + * }; + */ + +class Solution { + public: + // Same as 3023. Find Pattern in Infinite Stream I + int findPattern(InfiniteStream* stream, vector& pattern) { + const vector lps = getLPS(pattern); + int i = 0; // stream's index + int j = 0; // pattern's index + int bit = 0; // the bit in the stream + bool readNext = false; + while (true) { + if (!readNext) { + bit = stream->next(); + readNext = true; + } + if (bit == pattern[j]) { + ++i, readNext = false; + ++j; + if (j == pattern.size()) + return i - j; + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i, readNext = false; + } + } + throw; + } + + private: + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + vector getLPS(const vector& pattern) { + vector lps(pattern.size()); + for (int i = 1, j = 0; i < pattern.size(); ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +}; diff --git a/solutions/3037. Find Pattern in Infinite Stream II/3037.java b/solutions/3037. Find Pattern in Infinite Stream II/3037.java new file mode 100644 index 00000000000..f0d4dafa8a4 --- /dev/null +++ b/solutions/3037. Find Pattern in Infinite Stream II/3037.java @@ -0,0 +1,53 @@ +/** + * Definition for an infinite stream. + * class InfiniteStream { + * public InfiniteStream(int[] bits); + * public int next(); + * } + */ + +class Solution { + // Same as 3023. Find Pattern in Infinite Stream I + public int findPattern(InfiniteStream stream, int[] pattern) { + int[] lps = getLPS(pattern); + int i = 0; // stream's index + int j = 0; // pattern's index + int bit = 0; // the bit in the stream + boolean readNext = false; + while (true) { + if (!readNext) { + bit = stream.next(); + readNext = true; + } + if (bit == pattern[j]) { + ++i; + readNext = false; + ++j; + if (j == pattern.length) + return i - j; + } + // Mismatch after j matches. + else if (j > 0) { + // Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1]; + } else { + ++i; + readNext = false; + } + } + } + + // Returns the lps array, where lps[i] is the length of the longest prefix of + // pattern[0..i] which is also a suffix of this substring. + private int[] getLPS(int[] pattern) { + int[] lps = new int[pattern.length]; + int j = 0; + for (int i = 1; i < pattern.length; ++i) { + while (j > 0 && pattern[j] != pattern[i]) + j = lps[j - 1]; + if (pattern[i] == pattern[j]) + lps[i] = ++j; + } + return lps; + } +} diff --git a/solutions/3037. Find Pattern in Infinite Stream II/3037.py b/solutions/3037. Find Pattern in Infinite Stream II/3037.py new file mode 100644 index 00000000000..063c33d1299 --- /dev/null +++ b/solutions/3037. Find Pattern in Infinite Stream II/3037.py @@ -0,0 +1,45 @@ +# Definition for an infinite stream. +# class InfiniteStream: +# def next(self) -> int: +# pass + +class Solution: + # Same as 3023. Find Pattern in Infinite Stream I + def findPattern(self, stream: Optional['InfiniteStream'], pattern: List[int]) -> int: + lps = self._getLPS(pattern) + i = 0 # stream's index + j = 0 # pattern's index + bit = 0 # the bit in the stream + readNext = False + while True: + if not readNext: + bit = stream.next() + readNext = True + if bit == pattern[j]: + i += 1 + readNext = False + j += 1 + if j == len(pattern): + return i - j + # Mismatch after j matches. + elif j > 0: + # Don't match lps[0..lps[j - 1]] since they will match anyway. + j = lps[j - 1] + else: + i += 1 + readNext = False + + def _getLPS(self, pattern: List[int]) -> List[int]: + """ + Returns the lps array, where lps[i] is the length of the longest prefix of + pattern[0..i] which is also a suffix of this substring. + """ + lps = [0] * len(pattern) + j = 0 + for i in range(1, len(pattern)): + while j > 0 and pattern[j] != pattern[i]: + j = lps[j - 1] + if pattern[i] == pattern[j]: + j += 1 + lps[i] = j + return lps diff --git a/solutions/3038. Maximum Number of Operations With the Same Score I/3038.cpp b/solutions/3038. Maximum Number of Operations With the Same Score I/3038.cpp new file mode 100644 index 00000000000..29b7e0618a3 --- /dev/null +++ b/solutions/3038. Maximum Number of Operations With the Same Score I/3038.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxOperations(vector& nums) { + int ans = 1; + int sum = nums[0] + nums[1]; + + for (int i = 2; i + 1 < nums.size(); i += 2) { + if (nums[i] + nums[i + 1] == sum) + ++ans; + else + break; + } + + return ans; + } +}; diff --git a/solutions/3038. Maximum Number of Operations With the Same Score I/3038.java b/solutions/3038. Maximum Number of Operations With the Same Score I/3038.java new file mode 100644 index 00000000000..af4f3934151 --- /dev/null +++ b/solutions/3038. Maximum Number of Operations With the Same Score I/3038.java @@ -0,0 +1,15 @@ +class Solution { + public int maxOperations(int[] nums) { + int ans = 1; + int sum = nums[0] + nums[1]; + + for (int i = 2; i + 1 < nums.length; i += 2) { + if (nums[i] + nums[i + 1] == sum) + ++ans; + else + break; + } + + return ans; + } +} diff --git a/solutions/3038. Maximum Number of Operations With the Same Score I/3038.py b/solutions/3038. Maximum Number of Operations With the Same Score I/3038.py new file mode 100644 index 00000000000..cd0c6575e47 --- /dev/null +++ b/solutions/3038. Maximum Number of Operations With the Same Score I/3038.py @@ -0,0 +1,12 @@ +class Solution: + def maxOperations(self, nums: List[int]) -> int: + ans = 1 + summ = nums[0] + nums[1] + + for i in range(2, len(nums) - 1, 2): + if nums[i] + nums[i + 1] == summ: + ans += 1 + else: + break + + return ans diff --git a/solutions/3039. Apply Operations to Make String Empty/3039.cpp b/solutions/3039. Apply Operations to Make String Empty/3039.cpp new file mode 100644 index 00000000000..5e734374242 --- /dev/null +++ b/solutions/3039. Apply Operations to Make String Empty/3039.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string lastNonEmptyString(string s) { + string ans; + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + const int maxFreq = ranges::max(count); + + for (int i = s.length() - 1; i >= 0; --i) + if (count[s[i] - 'a']-- == maxFreq) + ans += s[i]; + + return {ans.rbegin(), ans.rend()}; + } +}; diff --git a/solutions/3039. Apply Operations to Make String Empty/3039.java b/solutions/3039. Apply Operations to Make String Empty/3039.java new file mode 100644 index 00000000000..4c5ad4a97b3 --- /dev/null +++ b/solutions/3039. Apply Operations to Make String Empty/3039.java @@ -0,0 +1,17 @@ +class Solution { + public String lastNonEmptyString(String s) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + final int maxFreq = Arrays.stream(count).max().getAsInt(); + + for (int i = s.length() - 1; i >= 0; --i) + if (count[s.charAt(i) - 'a']-- == maxFreq) + sb.append(s.charAt(i)); + + return sb.reverse().toString(); + } +} diff --git a/solutions/3039. Apply Operations to Make String Empty/3039.py b/solutions/3039. Apply Operations to Make String Empty/3039.py new file mode 100644 index 00000000000..e37d0d5ba1a --- /dev/null +++ b/solutions/3039. Apply Operations to Make String Empty/3039.py @@ -0,0 +1,12 @@ +class Solution: + def lastNonEmptyString(self, s: str) -> str: + ans = [] + count = collections.Counter(s) + maxFreq = max(count.values()) + + for c in reversed(s): + if count[c] == maxFreq: + ans.append(c) + count[c] -= 1 + + return ''.join(reversed(ans)) diff --git a/solutions/304. Range Sum Query 2D - Immutable/304.cpp b/solutions/304. Range Sum Query 2D - Immutable/304.cpp new file mode 100644 index 00000000000..96a4ccb9581 --- /dev/null +++ b/solutions/304. Range Sum Query 2D - Immutable/304.cpp @@ -0,0 +1,25 @@ +class NumMatrix { + public: + NumMatrix(vector>& matrix) { + if (matrix.empty()) + return; + + const int m = matrix.size(); + const int n = matrix[0].size(); + // prefix[i][j] := the sum of matrix[0..i)[0..j) + prefix.resize(m + 1, vector(n + 1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + prefix[i + 1][j + 1] = + matrix[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return prefix[row2 + 1][col2 + 1] - prefix[row1][col2 + 1] - + prefix[row2 + 1][col1] + prefix[row1][col1]; + } + + private: + vector> prefix; +}; diff --git a/solutions/304. Range Sum Query 2D - Immutable/304.java b/solutions/304. Range Sum Query 2D - Immutable/304.java new file mode 100644 index 00000000000..073060ef59c --- /dev/null +++ b/solutions/304. Range Sum Query 2D - Immutable/304.java @@ -0,0 +1,22 @@ +class NumMatrix { + public NumMatrix(int[][] matrix) { + if (matrix.length == 0) + return; + + final int m = matrix.length; + final int n = matrix[0].length; + // prefix[i][j] := the sum of matrix[0..i)[0..j) + prefix = new int[m + 1][n + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + prefix[i + 1][j + 1] = matrix[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + return prefix[row2 + 1][col2 + 1] - prefix[row1][col2 + 1] // + - prefix[row2 + 1][col1] + prefix[row1][col1]; + } + + private int[][] prefix; +} diff --git a/solutions/304. Range Sum Query 2D - Immutable/304.py b/solutions/304. Range Sum Query 2D - Immutable/304.py new file mode 100644 index 00000000000..dfac8bb754e --- /dev/null +++ b/solutions/304. Range Sum Query 2D - Immutable/304.py @@ -0,0 +1,19 @@ +class NumMatrix: + def __init__(self, matrix: List[List[int]]): + if not matrix: + return + + m = len(matrix) + n = len(matrix[0]) + # prefix[i][j] := the sum of matrix[0..i)[0..j) + self.prefix = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(m): + for j in range(n): + self.prefix[i + 1][j + 1] = \ + matrix[i][j] + self.prefix[i][j + 1] + \ + self.prefix[i + 1][j] - self.prefix[i][j] + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return self.prefix[row2 + 1][col2 + 1] - self.prefix[row1][col2 + 1] - \ + self.prefix[row2 + 1][col1] + self.prefix[row1][col1] diff --git a/solutions/3040. Maximum Number of Operations With the Same Score II/3040.cpp b/solutions/3040. Maximum Number of Operations With the Same Score II/3040.cpp new file mode 100644 index 00000000000..4ad54b9ad21 --- /dev/null +++ b/solutions/3040. Maximum Number of Operations With the Same Score II/3040.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int maxOperations(vector& nums) { + const int n = nums.size(); + unordered_map mem; + return max({maxOperations(nums, 0, n - 1, nums[0] + nums[1], mem), + maxOperations(nums, 0, n - 1, nums[n - 1] + nums[n - 2], mem), + maxOperations(nums, 0, n - 1, nums[0] + nums[n - 1], mem)}); + } + + private: + // Returns the maximum number of operations that can be performed for + // nums[i..j], s.t. all operations have the same `score`. + int maxOperations(const vector& nums, int i, int j, int score, + unordered_map& mem) { + if (i >= j) + return 0; + const string key = hash(i, j, score); + if (const auto it = mem.find(key); it != mem.end()) + return it->second; + const int deleteFirstTwo = + nums[i] + nums[i + 1] == score + ? 1 + maxOperations(nums, i + 2, j, score, mem) + : 0; + const int deleteLastTwo = + nums[j] + nums[j - 1] == score + ? 1 + maxOperations(nums, i, j - 2, score, mem) + : 0; + const int deleteFirstAndLast = + nums[i] + nums[j] == score + ? 1 + maxOperations(nums, i + 1, j - 1, score, mem) + : 0; + return mem[key] = max({deleteFirstTwo, deleteLastTwo, deleteFirstAndLast}); + } + + string hash(int i, int j, int score) { + return to_string(i) + "," + to_string(j) + "," + to_string(score); + } +}; diff --git a/solutions/3040. Maximum Number of Operations With the Same Score II/3040.java b/solutions/3040. Maximum Number of Operations With the Same Score II/3040.java new file mode 100644 index 00000000000..a6406672e2f --- /dev/null +++ b/solutions/3040. Maximum Number of Operations With the Same Score II/3040.java @@ -0,0 +1,31 @@ +class Solution { + public int maxOperations(int[] nums) { + final int n = nums.length; + Map mem = new HashMap<>(); + return Math.max(Math.max(maxOperations(nums, 0, n - 1, nums[0] + nums[1], mem), + maxOperations(nums, 0, n - 1, nums[n - 1] + nums[n - 2], mem)), + maxOperations(nums, 0, n - 1, nums[0] + nums[n - 1], mem)); + } + + // Returns the maximum number of operations that can be performed for + // nums[i..j], s.t. all operations have the same `score`. + private int maxOperations(int[] nums, int i, int j, int score, Map mem) { + if (i >= j) + return 0; + final String key = hash(i, j, score); + if (mem.containsKey(key)) + return mem.get(key); + final int deleteFirstTwo = + nums[i] + nums[i + 1] == score ? 1 + maxOperations(nums, i + 2, j, score, mem) : 0; + final int deleteLastTwo = + nums[j] + nums[j - 1] == score ? 1 + maxOperations(nums, i, j - 2, score, mem) : 0; + final int deleteFirstAndLast = + nums[i] + nums[j] == score ? 1 + maxOperations(nums, i + 1, j - 1, score, mem) : 0; + mem.put(key, Math.max(Math.max(deleteFirstTwo, deleteLastTwo), deleteFirstAndLast)); + return mem.get(key); + } + + private String hash(int i, int j, int score) { + return i + "," + j + "," + score; + } +} diff --git a/solutions/3040. Maximum Number of Operations With the Same Score II/3040.py b/solutions/3040. Maximum Number of Operations With the Same Score II/3040.py new file mode 100644 index 00000000000..0e75fe960e2 --- /dev/null +++ b/solutions/3040. Maximum Number of Operations With the Same Score II/3040.py @@ -0,0 +1,22 @@ +class Solution: + def maxOperations(self, nums: List[int]) -> int: + @functools.lru_cache(None) + def dp(i: int, j: int, score: int) -> int: + """ + Returns the maximum number of operations that can be performed for + nums[i..j], s.t. all operations have the same `score`. + """ + if i >= j: + return 0 + deleteFirstTwo = 1 + dp(i + 2, j, score) \ + if nums[i] + nums[i + 1] == score else 0 + deleteLastTwo = 1 + dp(i, j - 2, score) \ + if nums[j] + nums[j - 1] == score else 0 + deleteFirstAndLast = 1 + dp(i + 1, j - 1, score) \ + if nums[i] + nums[j] == score else 0 + return max(deleteFirstTwo, deleteLastTwo, deleteFirstAndLast) + + n = len(nums) + return max(dp(0, n - 1, nums[0] + nums[1]), + dp(0, n - 1, nums[-1] + nums[-2]), + dp(0, n - 1, nums[0] + nums[-1])) diff --git a/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.cpp b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.cpp new file mode 100644 index 00000000000..365a5446a14 --- /dev/null +++ b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int maxSelectedElements(vector& nums) { + int ans = 1; + int prev = INT_MIN; + // the length of the longest consecutive elements (seq0) ending in the + // previous number + int dp0 = 1; + // the length of the longest consecutive elements (seq1) ending in the + // previous number + 1 + int dp1 = 1; + + ranges::sort(nums); + + for (const int num : nums) { + if (num == prev) { + dp1 = dp0 + 1; // Append `num + 1` to seq0. + } else if (num == prev + 1) { + ++dp0; // Append `num` to seq0. + ++dp1; // Add 1 to every number in seq0 and append `num + 1` to seq0. + } else if (num == prev + 2) { + dp0 = dp1 + 1; // Append `num` to seq1. + dp1 = 1; // Start a new sequence [`num + 1`]. + } else { + dp0 = 1; // Start a new sequence [`num`]. + dp1 = 1; // Start a new sequence [`num + 1`]. + } + ans = max({ans, dp0, dp1}); + prev = num; + } + + return ans; + } +}; diff --git a/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.java b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.java new file mode 100644 index 00000000000..3121db9e47f --- /dev/null +++ b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.java @@ -0,0 +1,33 @@ +class Solution { + public int maxSelectedElements(int[] nums) { + int ans = 1; + int prev = Integer.MIN_VALUE; + // the length of the longest consecutive elements (seq0) ending in the + // previous number + int dp0 = 1; + // the length of the longest consecutive elements (seq1) ending in the + // previous number + 1 + int dp1 = 1; + + Arrays.sort(nums); + + for (final int num : nums) { + if (num == prev) { + dp1 = dp0 + 1; // Append `num + 1` to seq0. + } else if (num == prev + 1) { + ++dp0; // Append `num` to seq0. + ++dp1; // Add 1 to every number in seq0 and append `num + 1` to seq0. + } else if (num == prev + 2) { + dp0 = dp1 + 1; // Append `num` to seq1. + dp1 = 1; // Start a new sequence [`num + 1`]. + } else { + dp0 = 1; // Start a new sequence [`num`]. + dp1 = 1; // Start a new sequence [`num + 1`]. + } + ans = Math.max(ans, Math.max(dp0, dp1)); + prev = num; + } + + return ans; + } +} diff --git a/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.py b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.py new file mode 100644 index 00000000000..a5ea6c77382 --- /dev/null +++ b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.py @@ -0,0 +1,27 @@ +class Solution: + def maxSelectedElements(self, nums: List[int]) -> int: + ans = 1 + prev = -math.inf + # the length of the longest consecutive elements (seq0) ending in the + # previous number + dp0 = 1 + # the length of the longest consecutive elements (seq1) ending in the + # previous number + 1 + dp1 = 1 + + for num in sorted(nums): + if num == prev: + dp1 = dp0 + 1 # Append `num + 1` to seq0. + elif num == prev + 1: + dp0 += 1 # Append `num` to seq0. + dp1 += 1 # Add 1 to every number in seq0 and append `num + 1` to seq0. + elif num == prev + 2: + dp0 = dp1 + 1 # Append `num` to seq1. + dp1 = 1 # Start a new sequence [`num + 1`]. + else: + dp0 = 1 # Start a new sequence [`num`]. + dp1 = 1 # Start a new sequence [`num + 1`]. + ans = max(ans, dp0, dp1) + prev = num + + return ans diff --git a/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.cpp b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.cpp new file mode 100644 index 00000000000..f9a839f7034 --- /dev/null +++ b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maxSelectedElements(vector& nums) { + int ans = 0; + // {num: the length of the longest consecutive elements ending in num} + unordered_map dp; + + ranges::sort(nums); + + for (const int num : nums) { + dp[num + 1] = dp[num] + 1; + dp[num] = dp[num - 1] + 1; + ans = max({ans, dp[num], dp[num + 1]}); + } + + return ans; + } +}; diff --git a/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.java b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.java new file mode 100644 index 00000000000..fecfb4a7576 --- /dev/null +++ b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.java @@ -0,0 +1,17 @@ +class Solution { + public int maxSelectedElements(int[] nums) { + int ans = 0; + // {num: the length of the longest consecutive elements ending in num} + HashMap dp = new HashMap<>(); + + Arrays.sort(nums); + + for (final int num : nums) { + dp.put(num + 1, dp.getOrDefault(num, 0) + 1); + dp.put(num, dp.getOrDefault(num - 1, 0) + 1); + ans = Math.max(ans, Math.max(dp.get(num), dp.get(num + 1))); + } + + return ans; + } +} diff --git a/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.py b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.py new file mode 100644 index 00000000000..e99b2e77042 --- /dev/null +++ b/solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.py @@ -0,0 +1,12 @@ +class Solution: + def maxSelectedElements(self, nums: List[int]) -> int: + ans = 0 + # {num: the length of the longest consecutive elements ending in num} + dp = {} + + for num in sorted(nums): + dp[num + 1] = dp.get(num, 0) + 1 + dp[num] = dp.get(num - 1, 0) + 1 + ans = max(ans, dp[num], dp[num + 1]) + + return ans diff --git a/solutions/3042. Count Prefix and Suffix Pairs I/3042.cpp b/solutions/3042. Count Prefix and Suffix Pairs I/3042.cpp new file mode 100644 index 00000000000..1543355322c --- /dev/null +++ b/solutions/3042. Count Prefix and Suffix Pairs I/3042.cpp @@ -0,0 +1,42 @@ +struct TrieNode { + unordered_map> children; + int count = 0; +}; + +class Trie { + public: + int insert(const string& word) { + const int n = word.length(); + int count = 0; + shared_ptr node = root; + for (int i = 0; i < n; ++i) { + const int j = hash(word[i], word[n - 1 - i]); + if (node->children[j] == nullptr) + node->children[j] = make_shared(); + node = node->children[j]; + count += node->count; + } + ++node->count; + return count; + } + + private: + shared_ptr root = make_shared(); + + static int hash(char prefix, char suffix) { + return 26 * (prefix - 'a') + (suffix - 'a'); + } +}; + +class Solution { + public: + long long countPrefixSuffixPairs(vector& words) { + long ans = 0; + Trie trie; + + for (const string& word : words) + ans += trie.insert(word); + + return ans; + } +}; diff --git a/solutions/3042. Count Prefix and Suffix Pairs I/3042.java b/solutions/3042. Count Prefix and Suffix Pairs I/3042.java new file mode 100644 index 00000000000..1881fc7bbee --- /dev/null +++ b/solutions/3042. Count Prefix and Suffix Pairs I/3042.java @@ -0,0 +1,36 @@ +class TrieNode { + Map children = new HashMap<>(); + int count = 0; +} + +class Trie { + public int insert(final String word) { + final int n = word.length(); + int count = 0; + TrieNode node = root; + for (int i = 0; i < n; ++i) { + final char prefix = word.charAt(i); + final char suffix = word.charAt(n - 1 - i); + final int key = (prefix - 'a') * 26 + (suffix - 'a'); + node.children.putIfAbsent(key, new TrieNode()); + node = node.children.get(key); + count += node.count; + } + ++node.count; + return count; + } + + private TrieNode root = new TrieNode(); +} + +class Solution { + public long countPrefixSuffixPairs(String[] words) { + long ans = 0; + Trie trie = new Trie(); + + for (final String word : words) + ans += trie.insert(word); + + return ans; + } +} diff --git a/solutions/3042. Count Prefix and Suffix Pairs I/3042.py b/solutions/3042. Count Prefix and Suffix Pairs I/3042.py new file mode 100644 index 00000000000..9f46b9ff675 --- /dev/null +++ b/solutions/3042. Count Prefix and Suffix Pairs I/3042.py @@ -0,0 +1,25 @@ +class TrieNode: + def __init__(self): + self.children: Dict[Tuple[str, str], TrieNode] = {} + self.count = 0 + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> int: + node = self.root + count = 0 + for i, prefix in enumerate(word): + suffix = word[-i - 1] + node = node.children.setdefault((prefix, suffix), TrieNode()) + count += node.count + node.count += 1 + return count + + +class Solution: + def countPrefixSuffixPairs(self, words: List[str]) -> int: + trie = Trie() + return sum(trie.insert(word) for word in words) diff --git a/solutions/3043. Find the Length of the Longest Common Prefix/3043.cpp b/solutions/3043. Find the Length of the Longest Common Prefix/3043.cpp new file mode 100644 index 00000000000..bb6fc7d7923 --- /dev/null +++ b/solutions/3043. Find the Length of the Longest Common Prefix/3043.cpp @@ -0,0 +1,49 @@ +struct TrieNode { + vector> children; + TrieNode() : children(10) {} +}; + +class Trie { + public: + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - '0'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + } + + int search(const string& word) { + int prefixLength = 0; + shared_ptr node = root; + for (const char c : word) { + const int i = c - '0'; + if (node->children[i] == nullptr) + break; + node = node->children[i]; + ++prefixLength; + } + return prefixLength; + } + + private: + shared_ptr root = make_shared(); +}; + +class Solution { + public: + int longestCommonPrefix(vector& arr1, vector& arr2) { + int ans = 0; + Trie trie; + + for (const int num : arr1) + trie.insert(to_string(num)); + + for (const int num : arr2) + ans = max(ans, trie.search(to_string(num))); + + return ans; + } +}; diff --git a/solutions/3043. Find the Length of the Longest Common Prefix/3043.java b/solutions/3043. Find the Length of the Longest Common Prefix/3043.java new file mode 100644 index 00000000000..97fb1f2be30 --- /dev/null +++ b/solutions/3043. Find the Length of the Longest Common Prefix/3043.java @@ -0,0 +1,45 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[10]; +} + +class Trie { + public void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - '0'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + } + + public int search(final String word) { + int prefixLength = 0; + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - '0'; + if (node.children[i] == null) + break; + node = node.children[i]; + ++prefixLength; + } + return prefixLength; + } + + private TrieNode root = new TrieNode(); +} + +class Solution { + public int longestCommonPrefix(int[] arr1, int[] arr2) { + int ans = 0; + Trie trie = new Trie(); + + for (final int num : arr1) + trie.insert(Integer.toString(num)); + + for (final int num : arr2) + ans = Math.max(ans, trie.search(Integer.toString(num))); + + return ans; + } +} diff --git a/solutions/3043. Find the Length of the Longest Common Prefix/3043.py b/solutions/3043. Find the Length of the Longest Common Prefix/3043.py new file mode 100644 index 00000000000..717b541eddd --- /dev/null +++ b/solutions/3043. Find the Length of the Longest Common Prefix/3043.py @@ -0,0 +1,34 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> None: + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + def search(self, word: str) -> int: + prefixLength = 0 + node = self.root + for c in word: + if c not in node.children: + break + node = node.children[c] + prefixLength += 1 + return prefixLength + + +class Solution: + def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int: + trie = Trie() + + for num in arr1: + trie.insert(str(num)) + + return max(trie.search(str(num)) for num in arr2) diff --git a/solutions/3044. Most Frequent Prime/3044.cpp b/solutions/3044. Most Frequent Prime/3044.cpp new file mode 100644 index 00000000000..cb7320074dd --- /dev/null +++ b/solutions/3044. Most Frequent Prime/3044.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int mostFrequentPrime(vector>& mat) { + constexpr int dirs[8][2] = {{1, 0}, {1, -1}, {0, -1}, {-1, -1}, + {-1, 0}, {-1, 1}, {0, 1}, {1, 1}}; + const int m = mat.size(); + const int n = mat[0].size(); + int ans = -1; + int maxFreq = 0; + unordered_map count; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (const auto& [dx, dy] : dirs) { + int num = 0; + for (int x = i, y = j; 0 <= x && x < m && 0 <= y && y < n; + x += dx, y += dy) { + num = num * 10 + mat[x][y]; + if (num > 10 && isPrime(num)) + ++count[num]; + } + } + + for (const auto& [prime, freq] : count) + if (freq > maxFreq) { + ans = prime; + maxFreq = freq; + } else if (freq == maxFreq) { + ans = max(ans, prime); + } + + return ans; + } + + private: + bool isPrime(int num) { + for (int i = 2; i < sqrt(num) + 1; ++i) + if (num % i == 0) + return false; + return true; + } +}; diff --git a/solutions/3044. Most Frequent Prime/3044.java b/solutions/3044. Most Frequent Prime/3044.java new file mode 100644 index 00000000000..b2b86b703b6 --- /dev/null +++ b/solutions/3044. Most Frequent Prime/3044.java @@ -0,0 +1,45 @@ +class Solution { + public int mostFrequentPrime(int[][] mat) { + final int[][] dirs = {{1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}}; + final int m = mat.length; + final int n = mat[0].length; + int ans = -1; + int maxFreq = 0; + Map count = new HashMap<>(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + for (int[] dir : dirs) { + int num = 0; + int x = i; + int y = j; + while (0 <= x && x < m && 0 <= y && y < n) { + num = num * 10 + mat[x][y]; + if (num > 10 && isPrime(num)) + count.merge(num, 1, Integer::sum); + x += dir[0]; + y += dir[1]; + } + } + + for (Map.Entry entry : count.entrySet()) { + final int prime = entry.getKey(); + final int freq = entry.getValue(); + if (freq > maxFreq) { + ans = prime; + maxFreq = freq; + } else if (freq == maxFreq) { + ans = Math.max(ans, prime); + } + } + + return ans; + } + + private boolean isPrime(int num) { + for (int i = 2; i < (int) Math.sqrt(num) + 1; ++i) + if (num % i == 0) + return false; + return true; + } +} diff --git a/solutions/3044. Most Frequent Prime/3044.py b/solutions/3044. Most Frequent Prime/3044.py new file mode 100644 index 00000000000..8012cf20197 --- /dev/null +++ b/solutions/3044. Most Frequent Prime/3044.py @@ -0,0 +1,27 @@ +class Solution: + def mostFrequentPrime(self, mat: List[List[int]]) -> int: + dirs = ((1, 0), (1, -1), (0, -1), (-1, -1), + (-1, 0), (-1, 1), (0, 1), (1, 1)) + m = len(mat) + n = len(mat[0]) + count = collections.Counter() + + def isPrime(num: int) -> bool: + return not any(num % i == 0 for i in range(2, int(num**0.5 + 1))) + + for i in range(m): + for j in range(n): + for dx, dy in dirs: + num = 0 + x = i + y = j + while 0 <= x < m and 0 <= y < n: + num = num * 10 + mat[x][y] + if num > 10 and isPrime(num): + count[num] += 1 + x += dx + y += dy + + if not count.items(): + return -1 + return max(count.items(), key=lambda x: (x[1], x[0]))[0] diff --git a/solutions/3045. Count Prefix and Suffix Pairs II/3045.cpp b/solutions/3045. Count Prefix and Suffix Pairs II/3045.cpp new file mode 100644 index 00000000000..89dde4b9c63 --- /dev/null +++ b/solutions/3045. Count Prefix and Suffix Pairs II/3045.cpp @@ -0,0 +1,43 @@ +struct TrieNode { + unordered_map> children; + int count = 0; +}; + +class Trie { + public: + int insert(const string& word) { + const int n = word.length(); + int count = 0; + shared_ptr node = root; + for (int i = 0; i < n; ++i) { + const int j = hash(word[i], word[n - 1 - i]); + if (node->children[j] == nullptr) + node->children[j] = make_shared(); + node = node->children[j]; + count += node->count; + } + ++node->count; + return count; + } + + private: + shared_ptr root = make_shared(); + + static int hash(char prefix, char suffix) { + return 26 * (prefix - 'a') + (suffix - 'a'); + } +}; + +class Solution { + public: + // Same as 3042. Count Prefix and Suffix Pairs I + long long countPrefixSuffixPairs(vector& words) { + long ans = 0; + Trie trie; + + for (const string& word : words) + ans += trie.insert(word); + + return ans; + } +}; diff --git a/solutions/3045. Count Prefix and Suffix Pairs II/3045.java b/solutions/3045. Count Prefix and Suffix Pairs II/3045.java new file mode 100644 index 00000000000..6adf60020cb --- /dev/null +++ b/solutions/3045. Count Prefix and Suffix Pairs II/3045.java @@ -0,0 +1,37 @@ +class TrieNode { + Map children = new HashMap<>(); + int count = 0; +} + +class Trie { + public int insert(final String word) { + final int n = word.length(); + int count = 0; + TrieNode node = root; + for (int i = 0; i < n; ++i) { + final char prefix = word.charAt(i); + final char suffix = word.charAt(n - 1 - i); + final int key = (prefix - 'a') * 26 + (suffix - 'a'); + node.children.putIfAbsent(key, new TrieNode()); + node = node.children.get(key); + count += node.count; + } + ++node.count; + return count; + } + + private TrieNode root = new TrieNode(); +} + +class Solution { + // Same as 3045. Count Prefix and Suffix Pairs II + public long countPrefixSuffixPairs(String[] words) { + long ans = 0; + Trie trie = new Trie(); + + for (final String word : words) + ans += trie.insert(word); + + return ans; + } +} diff --git a/solutions/3045. Count Prefix and Suffix Pairs II/3045.py b/solutions/3045. Count Prefix and Suffix Pairs II/3045.py new file mode 100644 index 00000000000..06a49b9170b --- /dev/null +++ b/solutions/3045. Count Prefix and Suffix Pairs II/3045.py @@ -0,0 +1,26 @@ +class TrieNode: + def __init__(self): + self.children: Dict[Tuple[str, str], TrieNode] = {} + self.count = 0 + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> int: + node = self.root + count = 0 + for i, prefix in enumerate(word): + suffix = word[-i - 1] + node = node.children.setdefault((prefix, suffix), TrieNode()) + count += node.count + node.count += 1 + return count + + +class Solution: + # Same as 3045. Count Prefix and Suffix Pairs II + def countPrefixSuffixPairs(self, words: List[str]) -> int: + trie = Trie() + return sum(trie.insert(word) for word in words) diff --git a/solutions/3046. Split the Array/3046.cpp b/solutions/3046. Split the Array/3046.cpp new file mode 100644 index 00000000000..6cabb7c9c95 --- /dev/null +++ b/solutions/3046. Split the Array/3046.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool isPossibleToSplit(vector& nums) { + constexpr int kMax = 100; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + return ranges::all_of(count, [](int freq) { return freq <= 2; }); + } +}; diff --git a/solutions/3046. Split the Array/3046.java b/solutions/3046. Split the Array/3046.java new file mode 100644 index 00000000000..492e2ad76a9 --- /dev/null +++ b/solutions/3046. Split the Array/3046.java @@ -0,0 +1,11 @@ +class Solution { + public boolean isPossibleToSplit(int[] nums) { + final int kMax = 100; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + return Arrays.stream(count).allMatch(freq -> freq <= 2); + } +} diff --git a/solutions/3046. Split the Array/3046.py b/solutions/3046. Split the Array/3046.py new file mode 100644 index 00000000000..6298f4ceb9d --- /dev/null +++ b/solutions/3046. Split the Array/3046.py @@ -0,0 +1,3 @@ +class Solution: + def isPossibleToSplit(self, nums: List[int]) -> bool: + return all(freq <= 2 for freq in collections.Counter(nums).values()) diff --git a/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.cpp b/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.cpp new file mode 100644 index 00000000000..fc97a0876d7 --- /dev/null +++ b/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long largestSquareArea(vector>& bottomLeft, + vector>& topRight) { + int minSide = 0; + + for (int i = 0; i < bottomLeft.size(); ++i) + for (int j = i + 1; j < bottomLeft.size(); ++j) { + const int ax1 = bottomLeft[i][0]; + const int ay1 = bottomLeft[i][1]; + const int ax2 = topRight[i][0]; + const int ay2 = topRight[i][1]; + const int bx1 = bottomLeft[j][0]; + const int by1 = bottomLeft[j][1]; + const int bx2 = topRight[j][0]; + const int by2 = topRight[j][1]; + const int overlapX = min(ax2, bx2) - max(ax1, bx1); + const int overlapY = min(ay2, by2) - max(ay1, by1); + minSide = max(minSide, min(overlapX, overlapY)); + } + + return static_cast(minSide) * minSide; + } +}; diff --git a/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.java b/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.java new file mode 100644 index 00000000000..99ab8232625 --- /dev/null +++ b/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.java @@ -0,0 +1,22 @@ +class Solution { + public long largestSquareArea(int[][] bottomLeft, int[][] topRight) { + int minSide = 0; + + for (int i = 0; i < bottomLeft.length; ++i) + for (int j = i + 1; j < bottomLeft.length; ++j) { + final int ax1 = bottomLeft[i][0]; + final int ay1 = bottomLeft[i][1]; + final int ax2 = topRight[i][0]; + final int ay2 = topRight[i][1]; + final int bx1 = bottomLeft[j][0]; + final int by1 = bottomLeft[j][1]; + final int bx2 = topRight[j][0]; + final int by2 = topRight[j][1]; + final int overlapX = Math.min(ax2, bx2) - Math.max(ax1, bx1); + final int overlapY = Math.min(ay2, by2) - Math.max(ay1, by1); + minSide = Math.max(minSide, Math.min(overlapX, overlapY)); + } + + return (long) minSide * minSide; + } +} diff --git a/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.py b/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.py new file mode 100644 index 00000000000..2006d3aab8f --- /dev/null +++ b/solutions/3047. Find the Largest Area of Square Inside Two Rectangles/3047.py @@ -0,0 +1,10 @@ +class Solution: + def largestSquareArea(self, bottomLeft: List[List[int]], topRight: List[List[int]]) -> int: + minSide = 0 + + for ((ax1, ay1), (ax2, ay2)), ((bx1, by1), (bx2, by2)) in itertools.combinations(zip(bottomLeft, topRight), 2): + overlapX = min(ax2, bx2) - max(ax1, bx1) + overlapY = min(ay2, by2) - max(ay1, by1) + minSide = max(minSide, min(overlapX, overlapY)) + + return minSide**2 diff --git a/solutions/3048. Earliest Second to Mark Indices I/3048.cpp b/solutions/3048. Earliest Second to Mark Indices I/3048.cpp new file mode 100644 index 00000000000..4b060af102e --- /dev/null +++ b/solutions/3048. Earliest Second to Mark Indices I/3048.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int earliestSecondToMarkIndices(vector& nums, + vector& changeIndices) { + int l = 0; + int r = changeIndices.size() + 1; + + while (l < r) { + const int m = (l + r) / 2; + if (canMark(nums, changeIndices, m)) + r = m; + else + l = m + 1; + } + + return l <= changeIndices.size() ? l : -1; + } + + private: + // Returns true if all indices of `nums` can be marked within `second`. + bool canMark(const vector& nums, const vector& changeIndices, + int second) { + int numMarked = 0; + int decrement = 0; + // indexToLastSecond[i] := the last second to mark the index i + vector indexToLastSecond(nums.size(), -1); + + for (int i = 0; i < second; ++i) + indexToLastSecond[changeIndices[i] - 1] = i; + + for (int i = 0; i < second; ++i) { + const int index = changeIndices[i] - 1; // Convert to 0-indexed. + if (i == indexToLastSecond[index]) { + // Reach the last occurrence of the number. + // So, the current second will be used to mark the index. + if (nums[index] > decrement) + // The decrement is less than the number to be marked. + return false; + decrement -= nums[index]; + ++numMarked; + } else { + ++decrement; + } + } + + return numMarked == nums.size(); + } +}; diff --git a/solutions/3048. Earliest Second to Mark Indices I/3048.java b/solutions/3048. Earliest Second to Mark Indices I/3048.java new file mode 100644 index 00000000000..dc5e05e93b1 --- /dev/null +++ b/solutions/3048. Earliest Second to Mark Indices I/3048.java @@ -0,0 +1,45 @@ +class Solution { + public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) { + int l = 0; + int r = changeIndices.length + 1; + + while (l < r) { + final int m = (l + r) / 2; + if (canMark(nums, changeIndices, m)) + r = m; + else + l = m + 1; + } + + return l <= changeIndices.length ? l : -1; + } + + // Returns true if all indices of `nums` can be marked within `second`. + private boolean canMark(int[] nums, int[] changeIndices, int second) { + int numMarked = 0; + int decrement = 0; + // indexToLastSecond[i] := the last second to mark the index i + int[] indexToLastSecond = new int[nums.length]; + Arrays.fill(indexToLastSecond, -1); + + for (int i = 0; i < second; ++i) + indexToLastSecond[changeIndices[i] - 1] = i; + + for (int i = 0; i < second; ++i) { + final int index = changeIndices[i] - 1; // Convert to 0-indexed. + if (i == indexToLastSecond[index]) { + // Reach the last occurrence of the number. + // So, the current second will be used to mark the index. + if (nums[index] > decrement) + // The decrement is less than the number to be marked. + return false; + decrement -= nums[index]; + ++numMarked; + } else { + ++decrement; + } + } + + return numMarked == nums.length; + } +} diff --git a/solutions/3048. Earliest Second to Mark Indices I/3048.py b/solutions/3048. Earliest Second to Mark Indices I/3048.py new file mode 100644 index 00000000000..bf240ee4f78 --- /dev/null +++ b/solutions/3048. Earliest Second to Mark Indices I/3048.py @@ -0,0 +1,31 @@ +class Solution: + def earliestSecondToMarkIndices(self, nums: List[int], changeIndices: List[int]) -> int: + def canMark(second: int) -> bool: + """ + Returns True if all indices of `nums` can be marked within `second`. + """ + numMarked = 0 + decrement = 0 + indexToLastSecond = {} + + for i in range(second): + indexToLastSecond[changeIndices[i] - 1] = i + + for i in range(second): + index = changeIndices[i] - 1 # Convert to 0-indexed + if i == indexToLastSecond[index]: + # Reach the last occurrence of the number. + # So, the current second will be used to mark the index. + if nums[index] > decrement: + # The decrement is less than the number to be marked. + return False + decrement -= nums[index] + numMarked += 1 + else: + decrement += 1 + + return numMarked == len(nums) + + l = bisect.bisect_left(range(1, len(changeIndices) + 1), True, + key=lambda m: canMark(m)) + 1 + return l if l <= len(changeIndices) else -1 diff --git a/solutions/3049. Earliest Second to Mark Indices II/3049.cpp b/solutions/3049. Earliest Second to Mark Indices II/3049.cpp new file mode 100644 index 00000000000..c34e01b8e29 --- /dev/null +++ b/solutions/3049. Earliest Second to Mark Indices II/3049.cpp @@ -0,0 +1,86 @@ +class Solution { + public: + int earliestSecondToMarkIndices(vector& nums, + vector& changeIndices) { + const long numsSum = accumulate(nums.begin(), nums.end(), 0L); + // {the second: the index of nums can be zeroed at the current second} + const unordered_map secondToIndex = + getSecondToIndex(nums, changeIndices); + int l = 0; + int r = changeIndices.size() + 1; + + while (l < r) { + const int m = (l + r) / 2; + if (canMark(nums, secondToIndex, m, numsSum)) + r = m; + else + l = m + 1; + } + + return l <= changeIndices.size() ? l : -1; + } + + private: + // Returns true if all indices of `nums` can be marked within `maxSecond`. + bool canMark(const vector& nums, + const unordered_map& secondToIndex, int maxSecond, + const long numsSum) { + // Use a min-heap to greedily pop out the minimum number, which yields the + // least saving. + priority_queue, greater> minHeap; + int marks = 0; + + for (int second = maxSecond - 1; second >= 0; --second) { + if (const auto it = secondToIndex.find(second); + it != secondToIndex.end()) { + // The number mapped by the index is a candidate to be zeroed out. + const int index = it->second; + minHeap.push(nums[index]); + if (marks == 0) { + // Running out of marks, so need to pop out the minimum number. + // So, the current second will be used to mark an index. + minHeap.pop(); + ++marks; + } else { + // There're enough marks. + // So, the current second will be used to zero out a number. + --marks; + } + } else { + // There's no candidate to be zeroed out. + // So, the current second will be used to mark an index. + ++marks; + } + } + + const int heapSize = minHeap.size(); + const long decrementAndMarkCost = + numsSum - getHeapSum(minHeap) + (nums.size() - heapSize); + const long zeroAndMarkCost = heapSize + heapSize; + return decrementAndMarkCost + zeroAndMarkCost <= maxSecond; + } + + long getHeapSum(priority_queue, greater>& heap) { + long heapSum = 0; + while (!heap.empty()) + heapSum += heap.top(), heap.pop(); + return heapSum; + } + + unordered_map getSecondToIndex(const vector& nums, + const vector& changeIndices) { + // {the `index` of nums: the earliest second to zero out nums[index]} + unordered_map indexToFirstSecond; + unordered_map secondToIndex; + for (int zeroIndexedSecond = 0; zeroIndexedSecond < changeIndices.size(); + ++zeroIndexedSecond) { + // Convert to 0-indexed. + const int index = changeIndices[zeroIndexedSecond] - 1; + if (nums[index] > 0 && !indexToFirstSecond.contains(index)) + indexToFirstSecond[index] = zeroIndexedSecond; + } + for (const auto& [index, second] : indexToFirstSecond) + secondToIndex[second] = index; + return secondToIndex; + } +}; diff --git a/solutions/3049. Earliest Second to Mark Indices II/3049.java b/solutions/3049. Earliest Second to Mark Indices II/3049.java new file mode 100644 index 00000000000..f2d5d75ee65 --- /dev/null +++ b/solutions/3049. Earliest Second to Mark Indices II/3049.java @@ -0,0 +1,80 @@ +class Solution { + public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) { + final long numsSum = Arrays.stream(nums).asLongStream().sum(); + // {the second: the index of nums can be zeroed at the current second} + Map secondToIndex = getSecondToIndex(nums, changeIndices); + int l = 0; + int r = changeIndices.length + 1; + + while (l < r) { + final int m = (l + r) / 2; + if (canMark(nums, secondToIndex, m)) + r = m; + else + l = m + 1; + } + + return l <= changeIndices.length ? l : -1; + } + + // Returns true if all indices of `nums` can be marked within `maxSecond`. + private boolean canMark(int[] nums, Map secondToIndex, int maxSecond, + final long numsSum) { + // Use a min-heap to greedily pop out the minimum number, which yields the + // least saving. + Queue minHeap = new PriorityQueue<>(); + int marks = 0; + + for (int second = maxSecond - 1; second >= 0; --second) { + if (secondToIndex.containsKey(second)) { + // The number mapped by the index is a candidate to be zeroed out. + final int index = secondToIndex.get(second); + minHeap.offer(nums[index]); + if (marks == 0) { + // Running out of marks, so need to pop out the minimum number. + // So, the current second will be used to mark an index. + minHeap.poll(); + ++marks; + } else { + // There're enough marks. + // So, the current second will be used to zero out a number. + --marks; + } + } else { + // There's no candidate to be zeroed out. + // So, the current second will be used to mark an index. + ++marks; + } + } + + final int heapSize = minHeap.size(); + final long decrementAndMarkCost = numsSum - getHeapSum(minHeap) + (nums.length - heapSize); + final long zeroAndMarkCost = heapSize + heapSize; + return decrementAndMarkCost + zeroAndMarkCost <= maxSecond; + } + + private long getHeapSum(Queue minHeap) { + long sum = 0; + while (!minHeap.isEmpty()) + sum += minHeap.poll(); + return sum; + } + + private Map getSecondToIndex(int[] nums, int[] changeIndices) { + // {the `index` of nums: the earliest second to zero out nums[index]} + Map indexToFirstSecond = new HashMap<>(); + Map secondToIndex = new HashMap<>(); + for (int zeroIndexedSecond = 0; zeroIndexedSecond < changeIndices.length; ++zeroIndexedSecond) { + // Convert to 0-indexed. + final int index = changeIndices[zeroIndexedSecond] - 1; + if (nums[index] > 0) + indexToFirstSecond.putIfAbsent(index, zeroIndexedSecond); + } + for (Map.Entry entry : indexToFirstSecond.entrySet()) { + final int index = entry.getKey(); + final int second = entry.getValue(); + secondToIndex.put(second, index); + } + return secondToIndex; + } +} diff --git a/solutions/3049. Earliest Second to Mark Indices II/3049.py b/solutions/3049. Earliest Second to Mark Indices II/3049.py new file mode 100644 index 00000000000..76e80d70238 --- /dev/null +++ b/solutions/3049. Earliest Second to Mark Indices II/3049.py @@ -0,0 +1,51 @@ +class Solution: + def earliestSecondToMarkIndices(self, nums: List[int], changeIndices: List[int]) -> int: + # {the second: the index of nums can be zeroed at the current second} + secondToIndex = self._getSecondToIndex(nums, changeIndices) + numsSum = sum(nums) + + def canMark(maxSecond: int) -> bool: + """ + Returns True if all indices of `nums` can be marked within `maxSecond`. + """ + # Use a min-heap to greedily pop out the minimum number, which yields the + # least saving. + minHeap = [] + marks = 0 + + for second in range(maxSecond - 1, -1, -1): + if second in secondToIndex: + # The number mapped by the index is a candidate to be zeroed out. + index = secondToIndex[second] + heapq.heappush(minHeap, nums[index]) + if marks == 0: + # Running out of marks, so need to pop out the minimum number. + # So, the current second will be used to mark an index. + heapq.heappop(minHeap) + marks += 1 + else: + # There're enough marks. + # So, the current second will be used to zero out a number. + marks -= 1 + else: + # There's no candidate to be zeroed out. + # So, the current second will be used to mark an index. + marks += 1 + + decrementAndMarkCost = (numsSum - sum(minHeap)) + \ + (len(nums) - len(minHeap)) + zeroAndMarkCost = len(minHeap) + len(minHeap) + return decrementAndMarkCost + zeroAndMarkCost <= maxSecond + + l = bisect.bisect_left(range(1, len(changeIndices) + 1), True, + key=lambda m: canMark(m)) + 1 + return l if l <= len(changeIndices) else -1 + + def _getSecondToIndex(self, nums: List[int], changeIndices: List[int]) -> Dict[int, int]: + # {the `index` of nums: the earliest second to zero out nums[index]} + indexToFirstSecond = {} + for zeroIndexedSecond, oneIndexedIndex in enumerate(changeIndices): + index = oneIndexedIndex - 1 # Convert to 0-indexed. + if nums[index] > 0 and index not in indexToFirstSecond: + indexToFirstSecond[index] = zeroIndexedSecond + return {second: index for index, second in indexToFirstSecond.items()} diff --git a/solutions/305. Number of Islands II/305.cpp b/solutions/305. Number of Islands II/305.cpp new file mode 100644 index 00000000000..1acbff2b2ec --- /dev/null +++ b/solutions/305. Number of Islands II/305.cpp @@ -0,0 +1,75 @@ +class UnionFind { + public: + vector id; + + UnionFind(int n) : id(n, -1), rank(n) {} + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector rank; +}; + +class Solution { + public: + vector numIslands2(int m, int n, vector>& positions) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + vector ans; + vector> seen(m, vector(n)); + UnionFind uf(m * n); + int count = 0; + + for (const vector& p : positions) { + const int i = p[0]; + const int j = p[1]; + if (seen[i][j]) { + ans.push_back(count); + continue; + } + seen[i][j] = true; + const int id = getId(i, j, n); + uf.id[id] = id; + ++count; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + const int neighborId = getId(x, y, n); + if (uf.id[neighborId] == -1) // water + continue; + const int currentRoot = uf.find(id); + const int neighborRoot = uf.find(neighborId); + if (currentRoot != neighborRoot) { + uf.unionByRank(currentRoot, neighborRoot); + --count; + } + } + ans.push_back(count); + } + + return ans; + } + + private: + int getId(int i, int j, int n) { + return i * n + j; + } +}; diff --git a/solutions/305. Number of Islands II/305.java b/solutions/305. Number of Islands II/305.java new file mode 100644 index 00000000000..17607703624 --- /dev/null +++ b/solutions/305. Number of Islands II/305.java @@ -0,0 +1,75 @@ +class UnionFind { + public int[] id; + + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + Arrays.fill(id, -1); // water + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] rank; +} + +class Solution { + public List numIslands2(int m, int n, int[][] positions) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + List ans = new ArrayList<>(); + boolean[][] seen = new boolean[m][n]; + UnionFind uf = new UnionFind(m * n); + int count = 0; + + for (int[] p : positions) { + final int i = p[0]; + final int j = p[1]; + if (seen[i][j]) { + ans.add(count); + continue; + } + seen[i][j] = true; + final int id = getId(i, j, n); + uf.id[id] = id; + ++count; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + final int neighborId = getId(x, y, n); + if (uf.id[neighborId] == -1) // Water + continue; + final int currentParent = uf.find(id); + final int neighborParent = uf.find(neighborId); + if (currentParent != neighborParent) { + uf.unionByRank(currentParent, neighborParent); + --count; + } + } + ans.add(count); + } + + return ans; + } + + private int getId(int i, int j, int n) { + return i * n + j; + } +} diff --git a/solutions/305. Number of Islands II/305.py b/solutions/305. Number of Islands II/305.py new file mode 100644 index 00000000000..a7b5e04833e --- /dev/null +++ b/solutions/305. Number of Islands II/305.py @@ -0,0 +1,59 @@ +class UnionFind: + def __init__(self, n: int): + self.id = [-1] * n + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + ans = [] + seen = [[False] * n for _ in range(m)] + uf = UnionFind(m * n) + count = 0 + + def getId(i: int, j: int, n: int) -> int: + return i * n + j + + for i, j in positions: + if seen[i][j]: + ans.append(count) + continue + seen[i][j] = True + id = getId(i, j, n) + uf.id[id] = id + count += 1 + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + neighborId = getId(x, y, n) + if uf.id[neighborId] == -1: # water + continue + currentParent = uf.find(id) + neighborParent = uf.find(neighborId) + if currentParent != neighborParent: + uf.unionByRank(currentParent, neighborParent) + count -= 1 + ans.append(count) + + return ans diff --git a/solutions/3050. Pizza Toppings Cost Analysis/3050.sql b/solutions/3050. Pizza Toppings Cost Analysis/3050.sql new file mode 100644 index 00000000000..e39730dcf48 --- /dev/null +++ b/solutions/3050. Pizza Toppings Cost Analysis/3050.sql @@ -0,0 +1,9 @@ +SELECT + CONCAT(T1.topping_name, ',', T2.topping_name, ',', T3.topping_name) AS pizza, + ROUND(T1.cost + T2.cost + T3.cost, 2) AS total_cost +FROM Toppings AS T1 +INNER JOIN Toppings AS T2 + ON (T1.topping_name < T2.topping_name) +INNER JOIN Toppings AS T3 + ON (T2.topping_name < T3.topping_name) +ORDER BY total_cost DESC, pizza; diff --git a/solutions/3051. Find Candidates for Data Scientist Position/3051.sql b/solutions/3051. Find Candidates for Data Scientist Position/3051.sql new file mode 100644 index 00000000000..3a94f07ea8b --- /dev/null +++ b/solutions/3051. Find Candidates for Data Scientist Position/3051.sql @@ -0,0 +1,6 @@ +SELECT candidate_id +FROM Candidates +WHERE skill IN ('Python', 'Tableau', 'PostgreSQL') +GROUP BY 1 +HAVING COUNT(skill) = 3 +ORDER BY 1; diff --git a/solutions/3052. Maximize Items/3052.sql b/solutions/3052. Maximize Items/3052.sql new file mode 100644 index 00000000000..c177e476f5d --- /dev/null +++ b/solutions/3052. Maximize Items/3052.sql @@ -0,0 +1,17 @@ +WITH + Prime AS ( + SELECT SUM(square_footage) AS sum_square_footage + FROM Inventory + WHERE item_type = 'prime_eligible' + ) +SELECT + 'prime_eligible' AS item_type, + COUNT(*) * FLOOR(500000 / Prime.sum_square_footage) AS item_count +FROM Inventory, Prime +WHERE item_type = 'prime_eligible' +UNION ALL +SELECT + 'not_prime', + COUNT(*) * FLOOR(500000 % Prime.sum_square_footage / SUM(square_footage)) +FROM Inventory, Prime +WHERE item_type = 'not_prime'; diff --git a/solutions/3053. Classifying Triangles by Lengths/3053.sql b/solutions/3053. Classifying Triangles by Lengths/3053.sql new file mode 100644 index 00000000000..8cf86f41929 --- /dev/null +++ b/solutions/3053. Classifying Triangles by Lengths/3053.sql @@ -0,0 +1,13 @@ +SELECT + ( + CASE + WHEN A = B AND B = C THEN 'Equilateral' + WHEN + A = B AND A + B > C OR + A = C AND A + C > B OR + B = C AND B + C > A THEN 'Isosceles' + WHEN A + B > C AND A + C > B AND B + C > A THEN 'Scalene' + ELSE 'Not A Triangle' + END + ) AS triangle_type +FROM Triangles; diff --git a/solutions/3054. Binary Tree Nodes/3054.sql b/solutions/3054. Binary Tree Nodes/3054.sql new file mode 100644 index 00000000000..2e0be211056 --- /dev/null +++ b/solutions/3054. Binary Tree Nodes/3054.sql @@ -0,0 +1,13 @@ +# Similar to 608. Tree Node +SELECT DISTINCT Parent.N, + ( + CASE + WHEN Parent.P IS NULL THEN 'Root' + WHEN Parent.P IS NOT NULL AND Child.P IS NOT NULL THEN 'Inner' + WHEN Parent.P IS NOT NULL AND Child.P IS NULL THEN 'Leaf' + END + ) AS type +FROM Tree AS Parent +LEFT JOIN Tree AS Child + ON (Parent.N = Child.P) +ORDER BY 1; diff --git a/solutions/3055. Top Percentile Fraud/3055.sql b/solutions/3055. Top Percentile Fraud/3055.sql new file mode 100644 index 00000000000..d5ff220a8d2 --- /dev/null +++ b/solutions/3055. Top Percentile Fraud/3055.sql @@ -0,0 +1,16 @@ +WITH + FraudPercentile AS ( + SELECT + policy_id, + state, + fraud_score, + PERCENT_RANK() OVER( + PARTITION BY state + ORDER BY fraud_score DESC + ) AS `percent_rank` + FROM Fraud + ) +SELECT policy_id, state, fraud_score +FROM FraudPercentile +WHERE `percent_rank` < 0.05 +ORDER BY state, fraud_score DESC, policy_id; diff --git a/solutions/3056. Snaps Analysis/3056.sql b/solutions/3056. Snaps Analysis/3056.sql new file mode 100644 index 00000000000..642156b0703 --- /dev/null +++ b/solutions/3056. Snaps Analysis/3056.sql @@ -0,0 +1,16 @@ +SELECT + Age.age_bucket, + ROUND( + SUM(IF(Activities.activity_type = 'send', Activities.time_spent, 0)) / + SUM(Activities.time_spent) * 100, + 2 + ) AS send_perc, + ROUND( + SUM(IF(Activities.activity_type = 'open', Activities.time_spent, 0)) / + SUM(Activities.time_spent) * 100, + 2 + ) AS open_perc +FROM Activities +INNER JOIN Age + USING (user_id) +GROUP BY 1; diff --git a/solutions/3057. Employees Project Allocation/3057.sql b/solutions/3057. Employees Project Allocation/3057.sql new file mode 100644 index 00000000000..31f246427e7 --- /dev/null +++ b/solutions/3057. Employees Project Allocation/3057.sql @@ -0,0 +1,20 @@ +WITH + EmployeesWithAvgWorkload AS ( + SELECT + Employees.employee_id, + Employees.name AS employee_name, + Project.project_id, + Project.workload AS project_workload, + AVG(workload) OVER(PARTITION BY team) AS avg_team_workload + FROM Project + INNER JOIN Employees + USING (employee_id) +) +SELECT + employee_id, + project_id, + employee_name, + project_workload +FROM EmployeesWithAvgWorkload +WHERE project_workload > avg_team_workload +ORDER BY 1, 2; diff --git a/solutions/3058. Friends With No Mutual Friends/3058.sql b/solutions/3058. Friends With No Mutual Friends/3058.sql new file mode 100644 index 00000000000..aec80d6170c --- /dev/null +++ b/solutions/3058. Friends With No Mutual Friends/3058.sql @@ -0,0 +1,22 @@ +WITH + TwoWayFriends AS ( + SELECT user_id1 AS user_id, user_id2 AS friend_id FROM Friends + UNION ALL + SELECT user_id2, user_id1 FROM Friends + ), + UserToMutualFriend AS ( + SELECT + User1.user_id, + User2.user_id AS friend_id + FROM TwoWayFriends AS User1 + INNER JOIN TwoWayFriends AS User2 + USING (friend_id) + WHERE User1.user_id != User2.user_id + ) +SELECT Friends.* FROM Friends +LEFT JOIN UserToMutualFriend + ON ( + Friends.user_id1 = UserToMutualFriend.user_id + AND Friends.user_id2 = UserToMutualFriend.friend_id) +WHERE UserToMutualFriend.friend_id IS NULL +ORDER BY 1, 2; diff --git a/solutions/3059. Find All Unique Email Domains/3059.sql b/solutions/3059. Find All Unique Email Domains/3059.sql new file mode 100644 index 00000000000..3d901b6ba3e --- /dev/null +++ b/solutions/3059. Find All Unique Email Domains/3059.sql @@ -0,0 +1,7 @@ +SELECT + SUBSTRING_INDEX(email, '@', -1) AS email_domain, + COUNT(*) AS count +FROM Emails +WHERE email LIKE '%.com' +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/306. Additive Number/306.cpp b/solutions/306. Additive Number/306.cpp new file mode 100644 index 00000000000..14845d0effa --- /dev/null +++ b/solutions/306. Additive Number/306.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + bool isAdditiveNumber(string num) { + const int n = num.length(); + + // num[0..i] = firstNum + for (int i = 0; i < n / 2; ++i) { + if (i > 0 && num[0] == '0') + return false; + const long firstNum = stol(num.substr(0, i + 1)); + // num[i + 1..j] = secondNum + // |thirdNum| >= max(|firstNum|, |secondNum|) + for (int j = i + 1; max(i, j - i) < n - j; ++j) { + if (j > i + 1 && num[i + 1] == '0') + break; + const long secondNum = stol(num.substr(i + 1, j - i)); + if (dfs(num, firstNum, secondNum, j + 1)) + return true; + } + } + + return false; + } + + private: + bool dfs(const string& num, long firstNum, long secondNum, long s) { + if (s == num.length()) + return true; + + const long thirdNum = firstNum + secondNum; + const string& thirdNumStr = to_string(thirdNum); + return num.find(thirdNumStr, s) == s && + dfs(num, secondNum, thirdNum, s + thirdNumStr.length()); + } +}; diff --git a/solutions/306. Additive Number/306.java b/solutions/306. Additive Number/306.java new file mode 100644 index 00000000000..7222f8b7d7f --- /dev/null +++ b/solutions/306. Additive Number/306.java @@ -0,0 +1,33 @@ +class Solution { + public boolean isAdditiveNumber(String num) { + final int n = num.length(); + + // num[0..i] = firstNum + for (int i = 0; i < n / 2; ++i) { + if (i > 0 && num.charAt(0) == '0') + return false; + final long firstNum = Long.parseLong(num.substring(0, i + 1)); + // num[i + 1..j] = secondNum + // |thirdNum| >= max(|firstNum|, |secondNum|) + for (int j = i + 1; Math.max(i, j - i) < n - j; ++j) { + if (j > i + 1 && num.charAt(i + 1) == '0') + break; + final long secondNum = Long.parseLong(num.substring(i + 1, j + 1)); + if (dfs(num, firstNum, secondNum, j + 1)) + return true; + } + } + + return false; + } + + private boolean dfs(final String num, long firstNum, long secondNum, long s) { + if (s == num.length()) + return true; + + final long thirdNum = firstNum + secondNum; + final String thirdNumStr = String.valueOf(thirdNum); + return num.indexOf(thirdNumStr, (int) s) == s && + dfs(num, secondNum, thirdNum, s + thirdNumStr.length()); + } +} diff --git a/solutions/306. Additive Number/306.py b/solutions/306. Additive Number/306.py new file mode 100644 index 00000000000..1df82a17d37 --- /dev/null +++ b/solutions/306. Additive Number/306.py @@ -0,0 +1,30 @@ +class Solution: + def isAdditiveNumber(self, num: str) -> bool: + n = len(num) + + def dfs(firstNum: int, secondNum: int, s: int) -> bool: + if s == len(num): + return True + + thirdNum = firstNum + secondNum + thirdNumStr = str(thirdNum) + + return num.find(thirdNumStr, s) == s and dfs(secondNum, thirdNum, s + len(thirdNumStr)) + + # num[0..i] = firstNum + for i in range(n // 2): + if i > 0 and num[0] == '0': + return False + firstNum = int(num[:i + 1]) + # num[i + 1..j] = secondNum + # |thirdNum| >= max(|firstNum|, |secondNum|) + j = i + 1 + while max(i, j - i) < n - j: + if j > i + 1 and num[i + 1] == '0': + break + secondNum = int(num[i + 1:j + 1]) + if dfs(firstNum, secondNum, j + 1): + return True + j += 1 + + return False diff --git a/solutions/3060. User Activities within Time Bounds/3060.sql b/solutions/3060. User Activities within Time Bounds/3060.sql new file mode 100644 index 00000000000..8b4c958cc25 --- /dev/null +++ b/solutions/3060. User Activities within Time Bounds/3060.sql @@ -0,0 +1,15 @@ +WITH + SessionDifferences AS ( + SELECT + user_id, + session_start, + LAG(session_end) OVER( + PARTITION BY user_id, session_type + ORDER BY session_end + ) AS prev_session_end + FROM Sessions + ) +SELECT DISTINCT user_id +FROM SessionDifferences +WHERE TIMESTAMPDIFF(HOUR, prev_session_end, session_start) <= 12 +ORDER BY 1; diff --git a/solutions/3061. Calculate Trapping Rain Water/3061.sql b/solutions/3061. Calculate Trapping Rain Water/3061.sql new file mode 100644 index 00000000000..0942c1cb54f --- /dev/null +++ b/solutions/3061. Calculate Trapping Rain Water/3061.sql @@ -0,0 +1,11 @@ +WITH + HeightsWithMinMax AS ( + SELECT + height, + MAX(height) OVER(ORDER BY id ASC) AS prev_max_height, + MAX(height) OVER(ORDER BY id DESC) AS next_max_height + FROM Heights + ) +SELECT + SUM(LEAST(prev_max_height, next_max_height) - height) AS total_trapped_water +FROM HeightsWithMinMax; diff --git a/solutions/3062. Winner of the Linked List Game/3062.cpp b/solutions/3062. Winner of the Linked List Game/3062.cpp new file mode 100644 index 00000000000..f641c467ab2 --- /dev/null +++ b/solutions/3062. Winner of the Linked List Game/3062.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string gameResult(ListNode* head) { + int even = 0; + int odd = 0; + + while (head != nullptr) { + if (head->val > head->next->val) + ++even; + else if (head->val < head->next->val) + ++odd; + head = head->next->next; + } + + if (even > odd) + return "Even"; + if (even < odd) + return "Odd"; + return "Tie"; + } +}; diff --git a/solutions/3062. Winner of the Linked List Game/3062.java b/solutions/3062. Winner of the Linked List Game/3062.java new file mode 100644 index 00000000000..eed5e6406b4 --- /dev/null +++ b/solutions/3062. Winner of the Linked List Game/3062.java @@ -0,0 +1,20 @@ +class Solution { + public String gameResult(ListNode head) { + int even = 0; + int odd = 0; + + while (head != null) { + if (head.val > head.next.val) + ++even; + else if (head.val < head.next.val) + ++odd; + head = head.next.next; + } + + if (even > odd) + return "Even"; + if (even < odd) + return "Odd"; + return "Tie"; + } +} diff --git a/solutions/3062. Winner of the Linked List Game/3062.py b/solutions/3062. Winner of the Linked List Game/3062.py new file mode 100644 index 00000000000..294df3bd6dd --- /dev/null +++ b/solutions/3062. Winner of the Linked List Game/3062.py @@ -0,0 +1,17 @@ +class Solution: + def gameResult(self, head: Optional[ListNode]) -> str: + even = 0 + odd = 0 + + while head: + if head.val > head.next.val: + even += 1 + elif head.val < head.next.val: + odd += 1 + head = head.next.next + + if even > odd: + return 'Even' + if even < odd: + return 'Odd' + return 'Tie' diff --git a/solutions/3063. Linked List Frequency/3063.cpp b/solutions/3063. Linked List Frequency/3063.cpp new file mode 100644 index 00000000000..d6f0791316c --- /dev/null +++ b/solutions/3063. Linked List Frequency/3063.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + ListNode* frequenciesOfElements(ListNode* head) { + unordered_map count; + ListNode* curr = head; + + while (curr != nullptr) { + ++count[curr->val]; + curr = curr->next; + } + + ListNode dummy(0); + ListNode* tail = &dummy; + + for (const auto& [_, freq] : count) { + tail->next = new ListNode(freq); + tail = tail->next; + } + + return dummy.next; + } +}; diff --git a/solutions/3063. Linked List Frequency/3063.java b/solutions/3063. Linked List Frequency/3063.java new file mode 100644 index 00000000000..5c78f3b5768 --- /dev/null +++ b/solutions/3063. Linked List Frequency/3063.java @@ -0,0 +1,21 @@ +class Solution { + public ListNode frequenciesOfElements(ListNode head) { + HashMap count = new HashMap<>(); + ListNode curr = head; + + while (curr != null) { + count.merge(curr.val, 1, Integer::sum); + curr = curr.next; + } + + ListNode dummy = new ListNode(0); + ListNode tail = dummy; + + for (final int freq : count.values()) { + tail.next = new ListNode(freq); + tail = tail.next; + } + + return dummy.next; + } +} diff --git a/solutions/3063. Linked List Frequency/3063.py b/solutions/3063. Linked List Frequency/3063.py new file mode 100644 index 00000000000..91e18ddb9c0 --- /dev/null +++ b/solutions/3063. Linked List Frequency/3063.py @@ -0,0 +1,17 @@ +class Solution: + def frequenciesOfElements(self, head: Optional[ListNode]) -> Optional[ListNode]: + count = collections.Counter() + curr = head + + while curr: + count[curr.val] += 1 + curr = curr.next + + dummy = ListNode(0) + tail = dummy + + for freq in count.values(): + tail.next = ListNode(freq) + tail = tail.next + + return dummy.next diff --git a/solutions/3064. Guess the Number Using Bitwise Questions I/3064.cpp b/solutions/3064. Guess the Number Using Bitwise Questions I/3064.cpp new file mode 100644 index 00000000000..7a7a3ac5581 --- /dev/null +++ b/solutions/3064. Guess the Number Using Bitwise Questions I/3064.cpp @@ -0,0 +1,16 @@ +/** + * Definition of commonSetBits API. + * int commonSetBits(int num); + */ + +class Solution { + public: + int findNumber() { + constexpr int kMaxBit = 30; + int ans = 0; + for (int i = 0; i <= kMaxBit; ++i) + if (commonSetBits(1 << i) == 1) + ans |= 1 << i; + return ans; + } +}; diff --git a/solutions/3064. Guess the Number Using Bitwise Questions I/3064.java b/solutions/3064. Guess the Number Using Bitwise Questions I/3064.java new file mode 100644 index 00000000000..736592dfae7 --- /dev/null +++ b/solutions/3064. Guess the Number Using Bitwise Questions I/3064.java @@ -0,0 +1,15 @@ +/** + * Definition of commonSetBits API (defined in the parent class Problem). + * int commonSetBits(int num); + */ + +public class Solution extends Problem { + public int findNumber() { + final int kMaxBit = 30; + int ans = 0; + for (int i = 0; i <= kMaxBit; ++i) + if (commonSetBits(1 << i) == 1) + ans |= 1 << i; + return ans; + } +} diff --git a/solutions/3064. Guess the Number Using Bitwise Questions I/3064.py b/solutions/3064. Guess the Number Using Bitwise Questions I/3064.py new file mode 100644 index 00000000000..083ba2c1d76 --- /dev/null +++ b/solutions/3064. Guess the Number Using Bitwise Questions I/3064.py @@ -0,0 +1,7 @@ +# Definition of commonSetBits API. +# def commonSetBits(num: int) -> int: + +class Solution: + def findNumber(self) -> int: + return sum(1 << i for i in range(31) + if commonSetBits(1 << i) == 1) diff --git a/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.cpp b/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.cpp new file mode 100644 index 00000000000..c68fb36a485 --- /dev/null +++ b/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int minOperations(vector& nums, int k) { + return ranges::count_if(nums, [k](int num) { return num < k; }); + } +}; diff --git a/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.java b/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.java new file mode 100644 index 00000000000..794188ffd04 --- /dev/null +++ b/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.java @@ -0,0 +1,5 @@ +class Solution { + public int minOperations(int[] nums, int k) { + return (int) Arrays.stream(nums).filter(num -> num < k).count(); + } +} diff --git a/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.py b/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.py new file mode 100644 index 00000000000..4b050c9da61 --- /dev/null +++ b/solutions/3065. Minimum Operations to Exceed Threshold Value I/3065.py @@ -0,0 +1,3 @@ +class Solution: + def minOperations(self, nums: List[int], k: int) -> int: + return sum(num < k for num in nums) diff --git a/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.cpp b/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.cpp new file mode 100644 index 00000000000..d13d3ee5b08 --- /dev/null +++ b/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minOperations(vector& nums, int k) { + int ans = 0; + priority_queue, greater<>> minHeap; + + for (const int num : nums) + minHeap.push(num); + + while (minHeap.size() > 1 && minHeap.top() < k) { + const int x = minHeap.top(); + minHeap.pop(); + const int y = minHeap.top(); + minHeap.pop(); + minHeap.push(min(x, y) * 2L + max(x, y)); + ++ans; + } + + return ans; + } +}; diff --git a/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.java b/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.java new file mode 100644 index 00000000000..7a84a0afb2a --- /dev/null +++ b/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.java @@ -0,0 +1,18 @@ +class Solution { + public int minOperations(int[] nums, int k) { + int ans = 0; + Queue minHeap = new PriorityQueue<>(); + + for (final int num : nums) + minHeap.add((long) num); + + while (minHeap.size() > 1 && minHeap.peek() < k) { + final long x = minHeap.poll(); + final long y = minHeap.poll(); + minHeap.add(Math.min(x, y) * 2 + Math.max(x, y)); + ++ans; + } + + return ans; + } +} diff --git a/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.py b/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.py new file mode 100644 index 00000000000..55866e8ecc8 --- /dev/null +++ b/solutions/3066. Minimum Operations to Exceed Threshold Value II/3066.py @@ -0,0 +1,13 @@ +class Solution: + def minOperations(self, nums: List[int], k: int) -> int: + ans = 0 + minHeap = nums.copy() + heapq.heapify(minHeap) + + while len(minHeap) > 1 and minHeap[0] < k: + x = heapq.heappop(minHeap) + y = heapq.heappop(minHeap) + heapq.heappush(minHeap, min(x, y) * 2 + max(x, y)) + ans += 1 + + return ans diff --git a/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.cpp b/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.cpp new file mode 100644 index 00000000000..ab16631238a --- /dev/null +++ b/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + vector countPairsOfConnectableServers(vector>& edges, + int signalSpeed) { + const int n = edges.size() + 1; + vector ans; + vector>> tree(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + tree[u].emplace_back(v, w); + tree[v].emplace_back(u, w); + } + + for (int i = 0; i < n; ++i) + ans.push_back(connectablePairsRootedAt(tree, i, signalSpeed)); + + return ans; + } + + private: + // Returns the number of server pairs that are connectable through the server + // `u`. + int connectablePairsRootedAt(const vector>>& tree, + int u, int signalSpeed) { + int pairs = 0; + int count = 0; + for (const auto& [v, w] : tree[u]) { + const int childCount = dfs(tree, v, u, w, signalSpeed); + pairs += count * childCount; + count += childCount; + } + return pairs; + } + + // Returns the number of servers that are connectable throught the server `u` + // (dist % signalSpeed == 0). + int dfs(const vector>>& tree, int u, int prev, int dist, + int signalSpeed) { + int count = 0; + for (const auto& [v, w] : tree[u]) { + if (v == prev) + continue; + count += dfs(tree, v, u, dist + w, signalSpeed); + } + return (dist % signalSpeed == 0 ? 1 : 0) + count; + } +}; diff --git a/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.java b/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.java new file mode 100644 index 00000000000..f4b438e2cfa --- /dev/null +++ b/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.java @@ -0,0 +1,54 @@ +class Solution { + public int[] countPairsOfConnectableServers(int[][] edges, int signalSpeed) { + final int n = edges.length + 1; + int[] ans = new int[n]; + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (final int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + for (int i = 0; i < n; ++i) + ans[i] = connectablePairsRootedAt(graph, i, signalSpeed); + + return ans; + } + + // Returns the number of server pairs that are connectable through the server + // `u`. + private int connectablePairsRootedAt(List>[] graph, int u, + int signalSpeed) { + int pairs = 0; + int count = 0; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + final int childCount = dfs(graph, v, u, w, signalSpeed); + pairs += count * childCount; + count += childCount; + } + return pairs; + } + + // Returns the number of servers that are connectable throught the server `u` + // (dist % signalSpeed == 0). + private int dfs(List>[] graph, int u, int prev, int dist, + int signalSpeed) { + int count = 0; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (v == prev) + continue; + count += dfs(graph, v, u, dist + w, signalSpeed); + } + return (dist % signalSpeed == 0 ? 1 : 0) + count; + } +} diff --git a/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.py b/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.py new file mode 100644 index 00000000000..5194bb2743a --- /dev/null +++ b/solutions/3067. Count Pairs of Connectable Servers in a Weighted Tree Network/3067.py @@ -0,0 +1,25 @@ +class Solution: + def countPairsOfConnectableServers(self, edges: List[List[int]], signalSpeed: int) -> List[int]: + n = len(edges) + 1 + tree = [[] for _ in range(n)] + + for u, v, w in edges: + tree[u].append((v, w)) + tree[v].append((u, w)) + + def connectablePairsRootedAt(u: int) -> int: + pairs = 0 + count = 0 + for v, w in tree[u]: + childCount = dfs(v, u, w) + pairs += count * childCount + count += childCount + return pairs + + def dfs(u: int, prev: int, dist: int) -> int: + return int(dist % signalSpeed == 0) + \ + sum(dfs(v, u, dist + w) + for v, w in tree[u] + if v != prev) + + return [connectablePairsRootedAt(i) for i in range(n)] diff --git a/solutions/3068. Find the Maximum Sum of Node Values/3068.cpp b/solutions/3068. Find the Maximum Sum of Node Values/3068.cpp new file mode 100644 index 00000000000..5c3ccf747e5 --- /dev/null +++ b/solutions/3068. Find the Maximum Sum of Node Values/3068.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + long long maximumValueSum(vector& nums, int k, + vector>& edges) { + long maxSum = 0; + int changedCount = 0; + int minChangeDiff = INT_MAX; + + for (const int num : nums) { + maxSum += max(num, num ^ k); + changedCount += ((num ^ k) > num) ? 1 : 0; + minChangeDiff = min(minChangeDiff, abs(num - (num ^ k))); + } + + if (changedCount % 2 == 0) + return maxSum; + return maxSum - minChangeDiff; + } +}; diff --git a/solutions/3068. Find the Maximum Sum of Node Values/3068.java b/solutions/3068. Find the Maximum Sum of Node Values/3068.java new file mode 100644 index 00000000000..62dbb76bc44 --- /dev/null +++ b/solutions/3068. Find the Maximum Sum of Node Values/3068.java @@ -0,0 +1,17 @@ +class Solution { + public long maximumValueSum(int[] nums, int k, int[][] edges) { + long maxSum = 0; + int changedCount = 0; + int minChangeDiff = Integer.MAX_VALUE; + + for (final int num : nums) { + maxSum += Math.max(num, num ^ k); + changedCount += ((num ^ k) > num) ? 1 : 0; + minChangeDiff = Math.min(minChangeDiff, Math.abs(num - (num ^ k))); + } + + if (changedCount % 2 == 0) + return maxSum; + return maxSum - minChangeDiff; + } +} diff --git a/solutions/3068. Find the Maximum Sum of Node Values/3068.py b/solutions/3068. Find the Maximum Sum of Node Values/3068.py new file mode 100644 index 00000000000..b8ae8f4661c --- /dev/null +++ b/solutions/3068. Find the Maximum Sum of Node Values/3068.py @@ -0,0 +1,8 @@ +class Solution: + def maximumValueSum(self, nums: List[int], k: int, edges: List[List[int]]) -> int: + maxSum = sum(max(num, num ^ k) for num in nums) + changedCount = sum((num ^ k) > num for num in nums) + if changedCount % 2 == 0: + return maxSum + minChangeDiff = min(abs(num - (num ^ k)) for num in nums) + return maxSum - minChangeDiff diff --git a/solutions/3069. Distribute Elements Into Two Arrays I/3069.cpp b/solutions/3069. Distribute Elements Into Two Arrays I/3069.cpp new file mode 100644 index 00000000000..ba2f2377f97 --- /dev/null +++ b/solutions/3069. Distribute Elements Into Two Arrays I/3069.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector resultArray(vector& nums) { + vector arr1{nums[0]}; + vector arr2{nums[1]}; + + for (int i = 2; i < nums.size(); i++) + if (arr1.back() > arr2.back()) + arr1.push_back(nums[i]); + else + arr2.push_back(nums[i]); + + arr1.insert(arr1.end(), arr2.begin(), arr2.end()); + return arr1; + } +}; diff --git a/solutions/3069. Distribute Elements Into Two Arrays I/3069.java b/solutions/3069. Distribute Elements Into Two Arrays I/3069.java new file mode 100644 index 00000000000..31bf3ceb819 --- /dev/null +++ b/solutions/3069. Distribute Elements Into Two Arrays I/3069.java @@ -0,0 +1,15 @@ +class Solution { + public int[] resultArray(int[] nums) { + List arr1 = new ArrayList<>(Arrays.asList(nums[0])); + List arr2 = new ArrayList<>(Arrays.asList(nums[1])); + + for (int i = 2; i < nums.length; ++i) + if (arr1.get(arr1.size() - 1) > arr2.get(arr2.size() - 1)) + arr1.add(nums[i]); + else + arr2.add(nums[i]); + + arr1.addAll(arr2); + return arr1.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/3069. Distribute Elements Into Two Arrays I/3069.py b/solutions/3069. Distribute Elements Into Two Arrays I/3069.py new file mode 100644 index 00000000000..aff3d0a6a80 --- /dev/null +++ b/solutions/3069. Distribute Elements Into Two Arrays I/3069.py @@ -0,0 +1,12 @@ +class Solution: + def resultArray(self, nums: List[int]) -> List[int]: + arr1 = [nums[0]] + arr2 = [nums[1]] + + for i in range(2, len(nums)): + if arr1[-1] > arr2[-1]: + arr1.append(nums[i]) + else: + arr2.append(nums[i]) + + return arr1 + arr2 diff --git a/solutions/307. Range Sum Query - Mutable/307-2.cpp b/solutions/307. Range Sum Query - Mutable/307-2.cpp new file mode 100644 index 00000000000..d7648cb3791 --- /dev/null +++ b/solutions/307. Range Sum Query - Mutable/307-2.cpp @@ -0,0 +1,75 @@ +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) : n(nums.size()), tree(n * 4) { + build(nums, 0, 0, n - 1); + } + + // Updates nums[i] to val. + void update(int i, int val) { + update(0, 0, n - 1, i, val); + } + + // Returns sum(nums[i..j]). + int query(int i, int j) { + return query(0, 0, n - 1, i, j); + } + + private: + const int n; // the size of the input array + vector tree; // the segment tree + + void build(const vector& nums, int treeIndex, int lo, int hi) { + if (lo == hi) { + tree[treeIndex] = nums[lo]; + return; + } + const int mid = (lo + hi) / 2; + build(nums, 2 * treeIndex + 1, lo, mid); + build(nums, 2 * treeIndex + 2, mid + 1, hi); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + void update(int treeIndex, int lo, int hi, int i, int val) { + if (lo == hi) { + tree[treeIndex] = val; + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + update(2 * treeIndex + 1, lo, mid, i, val); + else + update(2 * treeIndex + 2, mid + 1, hi, i, val); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + int query(int treeIndex, int lo, int hi, int i, int j) { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return 0; + const int mid = (lo + hi) / 2; + return merge(query(treeIndex * 2 + 1, lo, mid, i, j), + query(treeIndex * 2 + 2, mid + 1, hi, i, j)); + } + + // Merges the result of the left node and the right node. + int merge(int a, int b) const { + return a + b; + } +}; + +class NumArray { + public: + NumArray(vector& nums) : tree(nums) {} + + void update(int index, int val) { + tree.update(index, val); + } + + int sumRange(int left, int right) { + return tree.query(left, right); + } + + private: + SegmentTree tree; +}; diff --git a/solutions/307. Range Sum Query - Mutable/307-3.cpp b/solutions/307. Range Sum Query - Mutable/307-3.cpp new file mode 100644 index 00000000000..33043dd1337 --- /dev/null +++ b/solutions/307. Range Sum Query - Mutable/307-3.cpp @@ -0,0 +1,81 @@ +struct SegmentTreeNode { + int lo; + int hi; + int sum; + SegmentTreeNode* left; + SegmentTreeNode* right; + SegmentTreeNode(int lo, int hi, int sum, SegmentTreeNode* left = nullptr, + SegmentTreeNode* right = nullptr) + : lo(lo), hi(hi), sum(sum), left(left), right(right) {} + ~SegmentTreeNode() { + delete left; + delete right; + left = nullptr; + right = nullptr; + } +}; + +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) + : root(build(nums, 0, nums.size() - 1)) {} + + void update(int i, int val) { + update(root.get(), i, val); + } + + int query(int i, int j) const { + return query(root.get(), i, j); + } + + private: + std::unique_ptr root; + + SegmentTreeNode* build(const vector& nums, int lo, int hi) const { + if (lo == hi) + return new SegmentTreeNode(lo, hi, nums[lo]); + const int mid = (lo + hi) / 2; + SegmentTreeNode* left = build(nums, lo, mid); + SegmentTreeNode* right = build(nums, mid + 1, hi); + return new SegmentTreeNode(lo, hi, left->sum + right->sum, left, right); + } + + void update(SegmentTreeNode* root, int i, int val) { + if (root->lo == i && root->hi == i) { + root->sum = val; + return; + } + const int mid = (root->lo + root->hi) / 2; + if (i <= mid) + update(root->left, i, val); + else + update(root->right, i, val); + root->sum = root->left->sum + root->right->sum; + } + + int query(SegmentTreeNode* root, int i, int j) const { + // [lo, hi] lies completely inside [i, j]. + if (i <= root->lo && root->hi <= j) + return root->sum; + // [lo, hi] lies completely outside [i, j]. + if (j < root->lo || root->hi < i) + return 0; + return query(root->left, i, j) + query(root->right, i, j); + } +}; + +class NumArray { + public: + NumArray(vector& nums) : tree(nums) {} + + void update(int index, int val) { + tree.update(index, val); + } + + int sumRange(int left, int right) { + return tree.query(left, right); + } + + private: + SegmentTree tree; +}; diff --git a/solutions/307. Range Sum Query - Mutable/307.cpp b/solutions/307. Range Sum Query - Mutable/307.cpp new file mode 100644 index 00000000000..547caf1fad1 --- /dev/null +++ b/solutions/307. Range Sum Query - Mutable/307.cpp @@ -0,0 +1,48 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class NumArray { + public: + NumArray(vector& nums) : nums(nums), tree(nums.size()) { + for (int i = 0; i < nums.size(); ++i) + tree.add(i + 1, nums[i]); + } + + void update(int index, int val) { + tree.add(index + 1, val - nums[index]); + nums[index] = val; + } + + int sumRange(int left, int right) { + return tree.get(right + 1) - tree.get(left); + } + + private: + vector nums; + FenwickTree tree; +}; diff --git a/solutions/307. Range Sum Query - Mutable/307.java b/solutions/307. Range Sum Query - Mutable/307.java new file mode 100644 index 00000000000..662d9d628ed --- /dev/null +++ b/solutions/307. Range Sum Query - Mutable/307.java @@ -0,0 +1,48 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class NumArray { + public NumArray(int[] nums) { + this.nums = nums; + tree = new FenwickTree(nums.length); + for (int i = 0; i < nums.length; ++i) + tree.add(i + 1, nums[i]); + } + + public void update(int index, int val) { + tree.add(index + 1, val - nums[index]); + nums[index] = val; + } + + public int sumRange(int left, int right) { + return tree.get(right + 1) - tree.get(left); + } + + private int[] nums; + private FenwickTree tree; +} diff --git a/solutions/307. Range Sum Query - Mutable/307.py b/solutions/307. Range Sum Query - Mutable/307.py new file mode 100644 index 00000000000..c53e3cda74a --- /dev/null +++ b/solutions/307. Range Sum Query - Mutable/307.py @@ -0,0 +1,34 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class NumArray: + def __init__(self, nums: List[int]): + self.nums = nums + self.tree = FenwickTree(len(nums)) + for i, num in enumerate(nums): + self.tree.add(i + 1, num) + + def update(self, index: int, val: int) -> None: + self.tree.add(index + 1, val - self.nums[index]) + self.nums[index] = val + + def sumRange(self, left: int, right: int) -> int: + return self.tree.get(right + 1) - self.tree.get(left) diff --git a/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.cpp b/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.cpp new file mode 100644 index 00000000000..ae63d16fc91 --- /dev/null +++ b/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countSubmatrices(vector>& grid, int k) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + vector> prefix(m + 1, vector(n + 1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + prefix[i + 1][j + 1] = + grid[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + if (prefix[i + 1][j + 1] <= k) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.java b/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.java new file mode 100644 index 00000000000..f9aa86ab180 --- /dev/null +++ b/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.java @@ -0,0 +1,17 @@ +class Solution { + public int countSubmatrices(int[][] grid, int k) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + int[][] prefix = new int[m + 1][n + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + prefix[i + 1][j + 1] = grid[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; + if (prefix[i + 1][j + 1] <= k) + ++ans; + } + + return ans; + } +} diff --git a/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.py b/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.py new file mode 100644 index 00000000000..7eee9f4e040 --- /dev/null +++ b/solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.py @@ -0,0 +1,17 @@ +class Solution: + def countSubmatrices(self, grid: List[List[int]], k: int) -> int: + m = len(grid) + n = len(grid[0]) + ans = 0 + # prefix[i][j] := the sum of matrix[0..i)[0..j) + prefix = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(m): + for j in range(n): + prefix[i + 1][j + 1] = \ + grid[i][j] + prefix[i][j + 1] + \ + prefix[i + 1][j] - prefix[i][j] + if prefix[i + 1][j + 1] <= k: + ans += 1 + + return ans diff --git a/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.cpp b/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.cpp new file mode 100644 index 00000000000..d99540388ff --- /dev/null +++ b/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int minimumOperationsToWriteY(vector>& grid) { + return min({getOperations(grid, 0, 1), getOperations(grid, 0, 2), + getOperations(grid, 1, 0), getOperations(grid, 1, 2), + getOperations(grid, 2, 0), getOperations(grid, 2, 1)}); + } + + private: + // Returns the number of operations to turn Y into a and non-Y into b. + int getOperations(const vector>& grid, int a, int b) { + const int n = grid.size(); + const int mid = n / 2; + int operations = 0; + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + // For the 'Y' pattern, before the midpoint, check the diagonal and + // anti-diagonal. After the midpoint, check the middle column. + if ((i < mid && (i == j || i + j == n - 1)) || (i >= mid && j == mid)) { + if (grid[i][j] != a) + ++operations; + } else if (grid[i][j] != b) { + ++operations; + } + return operations; + }; +}; diff --git a/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.java b/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.java new file mode 100644 index 00000000000..d8bc7bd2009 --- /dev/null +++ b/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.java @@ -0,0 +1,25 @@ +class Solution { + public int minimumOperationsToWriteY(int[][] grid) { + return Math.min(Math.min(Math.min(getOperations(grid, 0, 1), getOperations(grid, 0, 2)), + Math.min(getOperations(grid, 1, 0), getOperations(grid, 1, 2))), + Math.min(getOperations(grid, 2, 0), getOperations(grid, 2, 1))); + } + + // Returns the number of operations to turn Y into a and non-Y into b. + private int getOperations(int[][] grid, int a, int b) { + final int n = grid.length; + final int mid = n / 2; + int operations = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + // For the 'Y' pattern, before the midpoint, check the diagonal and + // anti-diagonal. After the midpoint, check the middle column. + if ((i < mid && (i == j || i + j == n - 1)) || (i >= mid && j == mid)) { + if (grid[i][j] != a) + ++operations; + } else if (grid[i][j] != b) { + ++operations; + } + return operations; + } +} diff --git a/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.py b/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.py new file mode 100644 index 00000000000..c453d5389a0 --- /dev/null +++ b/solutions/3071. Minimum Operations to Write the Letter Y on a Grid/3071.py @@ -0,0 +1,22 @@ +class Solution: + def minimumOperationsToWriteY(self, grid: List[List[int]]) -> int: + n = len(grid) + mid = n // 2 + + def getOperations(a: int, b: int) -> int: + """Returns the number of operations to turn Y into a and non-Y into b.""" + operations = 0 + for i, row in enumerate(grid): + for j, num in enumerate(row): + # For the 'Y' pattern, before the midpoint, check the diagonal and + # anti-diagonal. After the midpoint, check the middle column. + if (i < mid and (i == j or i + j == n - 1)) or i >= mid and j == mid: + if num != a: + operations += 1 + elif num != b: + operations += 1 + return operations + + return min(getOperations(0, 1), getOperations(0, 2), + getOperations(1, 0), getOperations(1, 2), + getOperations(2, 0), getOperations(2, 1)) diff --git a/solutions/3072. Distribute Elements Into Two Arrays II/3072.cpp b/solutions/3072. Distribute Elements Into Two Arrays II/3072.cpp new file mode 100644 index 00000000000..f0ed54db74f --- /dev/null +++ b/solutions/3072. Distribute Elements Into Two Arrays II/3072.cpp @@ -0,0 +1,73 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + vector resultArray(vector& nums) { + vector arr1; + vector arr2; + const unordered_map ranks = getRanks(nums); + FenwickTree tree1(ranks.size()); + FenwickTree tree2(ranks.size()); + + add(nums[0], arr1, tree1, ranks); + add(nums[1], arr2, tree2, ranks); + + for (int i = 2; i < nums.size(); ++i) { + const int greaterCount1 = arr1.size() - tree1.get(ranks.at(nums[i])); + const int greaterCount2 = arr2.size() - tree2.get(ranks.at(nums[i])); + if (greaterCount1 > greaterCount2) + add(nums[i], arr1, tree1, ranks); + else if (greaterCount1 < greaterCount2) + add(nums[i], arr2, tree2, ranks); + else if (arr1.size() > arr2.size()) + add(nums[i], arr2, tree2, ranks); + else + add(nums[i], arr1, tree1, ranks); + } + + arr1.insert(arr1.end(), arr2.begin(), arr2.end()); + return arr1; + } + + private: + unordered_map getRanks(const vector& nums) { + unordered_map ranks; + set sorted(nums.begin(), nums.end()); + int rank = 0; + for (const int num : sorted) + ranks[num] = ++rank; + return ranks; + } + + void add(int num, vector& arr, FenwickTree& tree, + const unordered_map& ranks) { + arr.push_back(num); + tree.add(ranks.at(num), 1); + }; +}; diff --git a/solutions/3072. Distribute Elements Into Two Arrays II/3072.java b/solutions/3072. Distribute Elements Into Two Arrays II/3072.java new file mode 100644 index 00000000000..384abb61dab --- /dev/null +++ b/solutions/3072. Distribute Elements Into Two Arrays II/3072.java @@ -0,0 +1,72 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public int[] resultArray(int[] nums) { + List arr1 = new ArrayList<>(); + List arr2 = new ArrayList<>(); + Map ranks = getRanks(nums); + FenwickTree tree1 = new FenwickTree(ranks.size()); + FenwickTree tree2 = new FenwickTree(ranks.size()); + + add(nums[0], arr1, tree1, ranks); + add(nums[1], arr2, tree2, ranks); + + for (int i = 2; i < nums.length; ++i) { + final int greaterCount1 = arr1.size() - tree1.get(ranks.get(nums[i])); + final int greaterCount2 = arr2.size() - tree2.get(ranks.get(nums[i])); + if (greaterCount1 > greaterCount2) + add(nums[i], arr1, tree1, ranks); + else if (greaterCount1 < greaterCount2) + add(nums[i], arr2, tree2, ranks); + else if (arr1.size() > arr2.size()) + add(nums[i], arr2, tree2, ranks); + else + add(nums[i], arr1, tree1, ranks); + } + + arr1.addAll(arr2); + return arr1.stream().mapToInt(Integer::intValue).toArray(); + } + + private Map getRanks(int[] nums) { + Map ranks = new HashMap<>(); + SortedSet sorted = new TreeSet<>(); + for (final int num : nums) + sorted.add(num); + int rank = 0; + for (Iterator it = sorted.iterator(); it.hasNext();) + ranks.put(it.next(), ++rank); + return ranks; + } + + private void add(int num, List arr, FenwickTree tree, Map ranks) { + arr.add(num); + tree.add(ranks.get(num), 1); + }; +} diff --git a/solutions/3072. Distribute Elements Into Two Arrays II/3072.py b/solutions/3072. Distribute Elements Into Two Arrays II/3072.py new file mode 100644 index 00000000000..8af40ab54dd --- /dev/null +++ b/solutions/3072. Distribute Elements Into Two Arrays II/3072.py @@ -0,0 +1,57 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def resultArray(self, nums: List[int]) -> List[int]: + arr1 = [] + arr2 = [] + ranks = self._getRanks(nums) + tree1 = FenwickTree(len(ranks)) + tree2 = FenwickTree(len(ranks)) + + def add(num: int, arr: List[int], tree: FenwickTree) -> None: + arr.append(num) + tree.add(ranks[num], 1) + + add(nums[0], arr1, tree1) + add(nums[1], arr2, tree2) + + for i in range(2, len(nums)): + greaterCount1 = len(arr1) - tree1.get(ranks[nums[i]]) + greaterCount2 = len(arr2) - tree2.get(ranks[nums[i]]) + if greaterCount1 > greaterCount2: + add(nums[i], arr1, tree1) + elif greaterCount1 < greaterCount2: + add(nums[i], arr2, tree2) + elif len(arr1) > len(arr2): + add(nums[i], arr2, tree2) + else: + add(nums[i], arr1, tree1) + + return arr1 + arr2 + + def _getRanks(self, nums: List[int]) -> Dict[int, int]: + ranks = collections.Counter() + rank = 0 + for num in sorted(set(nums)): + rank += 1 + ranks[num] = rank + return ranks diff --git a/solutions/3073. Maximum Increasing Triplet Value/3073.cpp b/solutions/3073. Maximum Increasing Triplet Value/3073.cpp new file mode 100644 index 00000000000..da6b39da72e --- /dev/null +++ b/solutions/3073. Maximum Increasing Triplet Value/3073.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maximumTripletValue(vector& nums) { + const int n = nums.size(); + int ans = 0; + vector rightMax(n); // rightMax[i] := max(nums[i + 1..n)) + set leftSortedSet{nums[0]}; + + for (int i = n - 2; i >= 0; --i) + rightMax[i] = max(nums[i + 1], rightMax[i + 1]); + + for (int j = 1; j < n - 1; ++j) { + if (const auto it = leftSortedSet.lower_bound(nums[j]); + it != leftSortedSet.begin() && rightMax[j] > nums[j]) + ans = max(ans, *prev(it) - nums[j] + rightMax[j]); + + leftSortedSet.insert(nums[j]); + } + + return ans; + } +}; diff --git a/solutions/3073. Maximum Increasing Triplet Value/3073.java b/solutions/3073. Maximum Increasing Triplet Value/3073.java new file mode 100644 index 00000000000..77274f06183 --- /dev/null +++ b/solutions/3073. Maximum Increasing Triplet Value/3073.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumTripletValue(int[] nums) { + final int n = nums.length; + int ans = 0; + int[] rightMax = new int[n]; // rightMax[i] := max(nums[i + 1..n)) + TreeSet leftSortedSet = new TreeSet<>(Arrays.asList(nums[0])); + + for (int i = n - 2; i >= 0; --i) + rightMax[i] = Math.max(nums[i + 1], rightMax[i + 1]); + + for (int j = 1; j < n - 1; ++j) { + Integer lower = leftSortedSet.lower(nums[j]); + if (lower != null && rightMax[j] > nums[j]) + ans = Math.max(ans, lower - nums[j] + rightMax[j]); + leftSortedSet.add(nums[j]); + } + + return ans; + } +} diff --git a/solutions/3073. Maximum Increasing Triplet Value/3073.py b/solutions/3073. Maximum Increasing Triplet Value/3073.py new file mode 100644 index 00000000000..85bcc346119 --- /dev/null +++ b/solutions/3073. Maximum Increasing Triplet Value/3073.py @@ -0,0 +1,19 @@ +from sortedcontainers import SortedSet + + +class Solution: + def maximumTripletValue(self, nums: List[int]) -> int: + ans = 0 + rightMax = [0] * len(nums) # rightMax[i] := max(nums[i + 1..n)) + leftSortedSet = SortedSet([nums[0]]) + + for i in range(len(nums) - 2, -1, -1): + rightMax[i] = max(nums[i + 1], rightMax[i + 1]) + + for j in range(1, len(nums) - 1): + i = bisect.bisect_left(leftSortedSet, nums[j]) + if i > 0 and rightMax[j] > nums[j]: + ans = max(ans, leftSortedSet[i - 1] - nums[j] + rightMax[j]) + leftSortedSet.add(nums[j]) + + return ans diff --git a/solutions/3074. Apple Redistribution into Boxes/3074.cpp b/solutions/3074. Apple Redistribution into Boxes/3074.cpp new file mode 100644 index 00000000000..39e6cd8aa65 --- /dev/null +++ b/solutions/3074. Apple Redistribution into Boxes/3074.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minimumBoxes(vector& apple, vector& capacity) { + const int appleSum = accumulate(apple.begin(), apple.end(), 0); + int capacitySum = 0; + + ranges::sort(capacity, greater<>()); + + for (int i = 0; i < capacity.size(); ++i) { + capacitySum += capacity[i]; + if (capacitySum >= appleSum) + return i + 1; + } + + return capacity.size(); + } +}; diff --git a/solutions/3074. Apple Redistribution into Boxes/3074.java b/solutions/3074. Apple Redistribution into Boxes/3074.java new file mode 100644 index 00000000000..e5c398b12c7 --- /dev/null +++ b/solutions/3074. Apple Redistribution into Boxes/3074.java @@ -0,0 +1,16 @@ +class Solution { + public int minimumBoxes(int[] apple, int[] capacity) { + final int appleSum = Arrays.stream(apple).sum(); + int capacitySum = 0; + + Arrays.sort(capacity); + + for (int i = 0; i < capacity.length; ++i) { + capacitySum += capacity[capacity.length - 1 - i]; + if (capacitySum >= appleSum) + return i + 1; + } + + return capacity.length; + } +} diff --git a/solutions/3074. Apple Redistribution into Boxes/3074.py b/solutions/3074. Apple Redistribution into Boxes/3074.py new file mode 100644 index 00000000000..f6fede073ef --- /dev/null +++ b/solutions/3074. Apple Redistribution into Boxes/3074.py @@ -0,0 +1,11 @@ +class Solution: + def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int: + appleSum = sum(apple) + capacitySum = 0 + + for i, c in enumerate(sorted(capacity, reverse=True)): + capacitySum += c + if capacitySum >= appleSum: + return i + 1 + + return len(capacity) diff --git a/solutions/3075. Maximize Happiness of Selected Children/3075.cpp b/solutions/3075. Maximize Happiness of Selected Children/3075.cpp new file mode 100644 index 00000000000..fa26e1f6309 --- /dev/null +++ b/solutions/3075. Maximize Happiness of Selected Children/3075.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + long long maximumHappinessSum(vector& happiness, int k) { + long ans = 0; + int decremented = 0; + + ranges::sort(happiness, greater<>()); + + for (int i = 0; i < k; ++i) { + ans += max(0, happiness[i] - decremented); + ++decremented; + } + + return ans; + } +}; diff --git a/solutions/3075. Maximize Happiness of Selected Children/3075.java b/solutions/3075. Maximize Happiness of Selected Children/3075.java new file mode 100644 index 00000000000..6394ad39d02 --- /dev/null +++ b/solutions/3075. Maximize Happiness of Selected Children/3075.java @@ -0,0 +1,16 @@ +class Solution { + public long maximumHappinessSum(int[] happiness, int k) { + final int n = happiness.length; + long ans = 0; + int decremented = 0; + + Arrays.sort(happiness); + + for (int i = n - 1; i >= n - k; --i) { + ans += Math.max(0, happiness[i] - decremented); + ++decremented; + } + + return ans; + } +} diff --git a/solutions/3075. Maximize Happiness of Selected Children/3075.py b/solutions/3075. Maximize Happiness of Selected Children/3075.py new file mode 100644 index 00000000000..0e3c14b0003 --- /dev/null +++ b/solutions/3075. Maximize Happiness of Selected Children/3075.py @@ -0,0 +1,12 @@ +class Solution: + def maximumHappinessSum(self, happiness: List[int], k: int) -> int: + ans = 0 + decremented = 0 + + happiness.sort(reverse=True) + + for i in range(k): + ans += max(0, happiness[i] - decremented) + decremented += 1 + + return ans diff --git a/solutions/3076. Shortest Uncommon Substring in an Array/3076.cpp b/solutions/3076. Shortest Uncommon Substring in an Array/3076.cpp new file mode 100644 index 00000000000..4e952688d1a --- /dev/null +++ b/solutions/3076. Shortest Uncommon Substring in an Array/3076.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + vector shortestSubstrings(vector& arr) { + vector ans; + unordered_map count; + + for (const string& s : arr) { + add(s, count); + } + + for (const string& s : arr) { + remove(s, count); + ans.push_back(getMinSub(s, count)); + add(s, count); + } + + return ans; + } + + private: + vector getSubstrings(const string& s) { + vector substrings; + for (int i = 0; i < s.length(); ++i) + for (int j = i + 1; j <= s.length(); ++j) + substrings.push_back(s.substr(i, j - i)); + return substrings; + } + + void add(const string& s, unordered_map& count) { + for (const string& sub : getSubstrings(s)) + ++count[sub]; + } + + void remove(const string& s, unordered_map& count) { + for (const string& sub : getSubstrings(s)) + --count[sub]; + } + + string getMinSub(const string& s, const unordered_map& count) { + string minSub; + for (const string& sub : getSubstrings(s)) { + if (count.at(sub) > 0) + continue; + if (minSub.empty() || sub.length() < minSub.length() || + sub.length() == minSub.length() && sub < minSub) + minSub = sub; + } + return minSub; + } +}; diff --git a/solutions/3076. Shortest Uncommon Substring in an Array/3076.java b/solutions/3076. Shortest Uncommon Substring in an Array/3076.java new file mode 100644 index 00000000000..71f9a7f50be --- /dev/null +++ b/solutions/3076. Shortest Uncommon Substring in an Array/3076.java @@ -0,0 +1,47 @@ +class Solution { + public String[] shortestSubstrings(String[] arr) { + String[] ans = new String[arr.length]; + Map count = new HashMap<>(); + + for (int i = 0; i < arr.length; ++i) + add(arr[i], count); + + for (int i = 0; i < arr.length; ++i) { + remove(arr[i], count); + ans[i] = getMinSub(arr[i], count); + add(arr[i], count); + } + + return ans; + } + + private List getSubstrings(String s) { + List substrings = new ArrayList<>(); + for (int i = 0; i < s.length(); ++i) + for (int j = i + 1; j <= s.length(); ++j) + substrings.add(s.substring(i, j)); + return substrings; + } + + private void add(final String s, Map count) { + for (final String sub : getSubstrings(s)) + count.merge(sub, 1, Integer::sum); + } + + private void remove(String s, Map count) { + for (final String sub : getSubstrings(s)) + count.merge(sub, -1, Integer::sum); + } + + private String getMinSub(String s, Map count) { + String minSub = ""; + for (final String sub : getSubstrings(s)) { + if (count.get(sub) > 0) + continue; + if (minSub.equals("") || sub.length() < minSub.length() || + sub.length() == minSub.length() && sub.compareTo(minSub) < 0) + minSub = sub; + } + return minSub; + } +} diff --git a/solutions/3076. Shortest Uncommon Substring in an Array/3076.py b/solutions/3076. Shortest Uncommon Substring in an Array/3076.py new file mode 100644 index 00000000000..9f559fa0641 --- /dev/null +++ b/solutions/3076. Shortest Uncommon Substring in an Array/3076.py @@ -0,0 +1,40 @@ +class Solution: + def shortestSubstrings(self, arr: List[str]) -> List[str]: + ans = [] + count = collections.Counter() + + def getSubstrings(s: str) -> Iterator[str]: + for i in range(len(s)): + for j in range(i + 1, len(s) + 1): + yield s[i:j] + + def add(s: str) -> None: + """Adds all substrings of s to `count`.""" + for sub in getSubstrings(s): + count[sub] += 1 + + def remove(s: str) -> None: + """Removes all substrings of s from `count`.""" + for sub in getSubstrings(s): + count[sub] -= 1 + + def getMinSub(s: str) -> str: + minSub = '' + for sub in getSubstrings(s): + if count[sub] > 0: + continue + if minSub == '' or \ + len(sub) < len(minSub) or \ + len(sub) == len(minSub) and sub < minSub: + minSub = sub + return minSub + + for s in arr: + add(s) + + for s in arr: + remove(s) + ans.append(getMinSub(s)) + add(s) + + return ans diff --git a/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.cpp b/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.cpp new file mode 100644 index 00000000000..cfc203b1c69 --- /dev/null +++ b/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + long long maximumStrength(vector& nums, int k) { + vector>> mem( + nums.size(), vector>(k + 1, vector(2, -1))); + return maximumStrength(nums, 0, k, /*fresh=*/true, mem); + } + + private: + static constexpr long kMin = LONG_MIN / 2; + + // Returns the maximum strength of nums[i..n) with k operations left, where + // `fresh` means we're starting a new subarray. + long maximumStrength(const vector& nums, int i, int k, bool fresh, + vector>>& mem) { + if (nums.size() - i < k) + return kMin; + if (k == 0) + return 0; + if (i == nums.size()) + return k == 0 ? 0 : kMin; + if (mem[i][k][fresh] != -1) + return mem[i][k][fresh]; + // If it's not fresh, we can't skip the current number and consider it as a + // fresh start, since the case where it's fresh is already covered by + // `includeAndFreshStart`. + const long skip = fresh ? maximumStrength(nums, i + 1, k, true, mem) : kMin; + const long gain = (k % 2 == 0 ? -1 : 1) * static_cast(nums[i]) * k; + const long includeAndContinue = + maximumStrength(nums, i + 1, k, false, mem) + gain; + const long includeAndFreshStart = + maximumStrength(nums, i + 1, k - 1, true, mem) + gain; + return mem[i][k][fresh] = + max(skip, max(includeAndContinue, includeAndFreshStart)); + } +}; diff --git a/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.java b/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.java new file mode 100644 index 00000000000..f083c1a89d1 --- /dev/null +++ b/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.java @@ -0,0 +1,30 @@ +class Solution { + public long maximumStrength(int[] nums, int k) { + Long[][][] mem = new Long[nums.length][k + 1][2]; + return maximumStrength(nums, 0, k, /*fresh=*/true, mem); + } + + private static final long kMin = Long.MIN_VALUE / 2; + + // Returns the maximum strength of nums[i..n) with k operations left, where + // `fresh` means we're starting a new subarray. + private long maximumStrength(int[] nums, int i, int k, boolean fresh, Long[][][] mem) { + if (nums.length - i < k) + return kMin; + if (k == 0) + return 0; + if (i == nums.length) + return k == 0 ? 0 : kMin; + if (mem[i][k][fresh ? 1 : 0] != null) + return mem[i][k][fresh ? 1 : 0]; + // If it's not fresh, we can't skip the current number and consider it as a + // fresh start, since the case where it's fresh is already covered by + // `includeAndFreshStart`. + final long skip = fresh ? maximumStrength(nums, i + 1, k, true, mem) : kMin; + final long gain = (k % 2 == 0 ? -1 : 1) * 1L * nums[i] * k; + final long includeAndContinue = maximumStrength(nums, i + 1, k, false, mem) + gain; + final long includeAndFreshStart = maximumStrength(nums, i + 1, k - 1, true, mem) + gain; + return mem[i][k][fresh ? 1 : 0] = + Math.max(skip, Math.max(includeAndContinue, includeAndFreshStart)); + } +} diff --git a/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.py b/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.py new file mode 100644 index 00000000000..caf23f366c1 --- /dev/null +++ b/solutions/3077. Maximum Strength of K Disjoint Subarrays/3077.py @@ -0,0 +1,25 @@ +class Solution: + def maximumStrength(self, nums: List[int], k: int) -> int: + + @functools.lru_cache(None) + def dp(i: int, k: int, fresh: bool) -> int: + """ + Returns the maximum strength of nums[i..n) with k operations left, where + `fresh` means we're starting a new subarray. + """ + if len(nums) - i < k: + return -math.inf + if k == 0: + return 0 + if i == len(nums): + return 0 if k == 0 else -math.inf + # If it's not fresh, we can't skip the current number and consider it as a + # fresh start, since the case where it's fresh is already covered by + # `includeAndFreshStart`. + skip = dp(i + 1, k, True) if fresh else -math.inf + gain = (-1 if k % 2 == 0 else 1) * nums[i] * k + includeAndContinue = dp(i + 1, k, False) + gain + includeAndFreshStart = dp(i + 1, k - 1, True) + gain + return max(skip, includeAndContinue, includeAndFreshStart) + + return dp(0, k, True) diff --git a/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.cpp b/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.cpp new file mode 100644 index 00000000000..d057576ff90 --- /dev/null +++ b/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector findPattern(vector>& board, vector& pattern) { + for (int x = 0; x < board.size() - pattern.size() + 1; ++x) + for (int y = 0; y < board[0].size() - pattern[0].size() + 1; ++y) + if (isMatch(board, x, y, pattern)) + return {x, y}; + return {-1, -1}; + } + + private: + bool isMatch(const vector>& board, int x, int y, + const vector& pattern) { + unordered_map digitToLetter; + unordered_map letterToDigit; + for (int i = 0; i < pattern.size(); ++i) + for (int j = 0; j < pattern[i].size(); ++j) { + const int digit = board[i + x][j + y]; + const char c = pattern[i][j]; + if (isdigit(c)) { + if (c - '0' != digit) + return false; + } else { + if (const auto it = digitToLetter.find(digit); + it != digitToLetter.end() && it->second != c) + return false; + if (const auto it = letterToDigit.find(c); + it != letterToDigit.end() && it->second != digit) + return false; + digitToLetter[digit] = c; + letterToDigit[c] = digit; + } + } + return true; + } +}; diff --git a/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.java b/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.java new file mode 100644 index 00000000000..4b7c6223c59 --- /dev/null +++ b/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.java @@ -0,0 +1,31 @@ +class Solution { + public int[] findPattern(int[][] board, String[] pattern) { + for (int x = 0; x < board.length - pattern.length + 1; ++x) + for (int y = 0; y < board[0].length - pattern[0].length() + 1; ++y) + if (isMatch(board, x, y, pattern)) + return new int[] {x, y}; + return new int[] {-1, -1}; + } + + private boolean isMatch(int[][] board, int x, int y, String[] pattern) { + Map digitToLetter = new HashMap<>(); + Map letterToDigit = new HashMap<>(); + for (int i = 0; i < pattern.length; ++i) + for (int j = 0; j < pattern[i].length(); ++j) { + final int digit = board[i + x][j + y]; + final char c = pattern[i].charAt(j); + if (Character.isDigit(c)) { + if (c - '0' != digit) + return false; + } else { + if (digitToLetter.getOrDefault(digit, c) != c) + return false; + if (letterToDigit.getOrDefault(c, digit) != digit) + return false; + digitToLetter.putIfAbsent(digit, c); + letterToDigit.putIfAbsent(c, digit); + } + } + return true; + } +} diff --git a/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.py b/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.py new file mode 100644 index 00000000000..58c6ce698d5 --- /dev/null +++ b/solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.py @@ -0,0 +1,26 @@ +class Solution: + def findPattern(self, board: List[List[int]], pattern: List[str]) -> List[int]: + def isMatch(x: int, y: int) -> bool: + digitToLetter = {} + letterToDigit = {} + for i, row in enumerate(pattern): + for j, c in enumerate(row): + digit = board[i + x][j + y] + if c.isdigit(): + if int(c) != digit: + return False + else: + if digitToLetter.get(digit, c) != c: + return False + if letterToDigit.get(c, digit) != digit: + return False + digitToLetter[digit] = c + letterToDigit[c] = digit + return True + + for x in range(len(board) - len(pattern) + 1): + for y in range(len(board[0]) - len(pattern[0]) + 1): + if isMatch(x, y): + return [x, y] + + return [-1, -1] diff --git a/solutions/3079. Find the Sum of Encrypted Integers/3079.cpp b/solutions/3079. Find the Sum of Encrypted Integers/3079.cpp new file mode 100644 index 00000000000..4d5a6546824 --- /dev/null +++ b/solutions/3079. Find the Sum of Encrypted Integers/3079.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int sumOfEncryptedInt(vector& nums) { + int ans = 0; + + for (const int num : nums) { + int maxDigit = 0; + int base = 0; + for (int x = num; x > 0; x /= 10) { + maxDigit = max(maxDigit, x % 10); + base = base * 10 + 1; + } + ans += base * maxDigit; + } + + return ans; + } +}; diff --git a/solutions/3079. Find the Sum of Encrypted Integers/3079.java b/solutions/3079. Find the Sum of Encrypted Integers/3079.java new file mode 100644 index 00000000000..13361fb2cc3 --- /dev/null +++ b/solutions/3079. Find the Sum of Encrypted Integers/3079.java @@ -0,0 +1,17 @@ +class Solution { + public int sumOfEncryptedInt(int[] nums) { + int ans = 0; + + for (final int num : nums) { + int maxDigit = 0; + int base = 0; + for (int x = num; x > 0; x /= 10) { + maxDigit = Math.max(maxDigit, x % 10); + base = base * 10 + 1; + } + ans += base * maxDigit; + } + + return ans; + } +} diff --git a/solutions/3079. Find the Sum of Encrypted Integers/3079.py b/solutions/3079. Find the Sum of Encrypted Integers/3079.py new file mode 100644 index 00000000000..cf8f4013ead --- /dev/null +++ b/solutions/3079. Find the Sum of Encrypted Integers/3079.py @@ -0,0 +1,12 @@ +class Solution: + def sumOfEncryptedInt(self, nums: List[int]) -> int: + def getEncrypted(num: int) -> int: + maxDigit = 0 + base = 0 + while num > 0: + maxDigit = max(maxDigit, num % 10) + base = base * 10 + 1 + num //= 10 + return base * maxDigit + + return sum(getEncrypted(num) for num in nums) diff --git a/solutions/308. Range Sum Query 2D - Mutable/308.cpp b/solutions/308. Range Sum Query 2D - Mutable/308.cpp new file mode 100644 index 00000000000..95eba14c3d4 --- /dev/null +++ b/solutions/308. Range Sum Query 2D - Mutable/308.cpp @@ -0,0 +1,49 @@ +class FenwickTree { + public: + FenwickTree(int m, int n) : sums(m + 1, vector(n + 1)) {} + + void add(int row, int col, int delta) { + for (int i = row; i < sums.size(); i += lowbit(i)) + for (int j = col; j < sums[0].size(); j += lowbit(j)) + sums[i][j] += delta; + } + + int get(int row, int col) { + int sum = 0; + for (int i = row; i > 0; i -= lowbit(i)) + for (int j = col; j > 0; j -= lowbit(j)) + sum += sums[i][j]; + return sum; + } + + private: + vector> sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class NumMatrix { + public: + NumMatrix(vector>& matrix) + : matrix(matrix), tree(matrix.size(), matrix[0].size()) { + for (int i = 0; i < matrix.size(); ++i) + for (int j = 0; j < matrix[0].size(); ++j) + tree.add(i + 1, j + 1, matrix[i][j]); + } + + void update(int row, int col, int val) { + tree.add(row + 1, col + 1, val - matrix[row][col]); + matrix[row][col] = val; + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return tree.get(row2 + 1, col2 + 1) - tree.get(row1, col2 + 1) - + tree.get(row2 + 1, col1) + tree.get(row1, col1); + } + + private: + vector> matrix; + FenwickTree tree; +}; diff --git a/solutions/308. Range Sum Query 2D - Mutable/308.java b/solutions/308. Range Sum Query 2D - Mutable/308.java new file mode 100644 index 00000000000..a520df5b87e --- /dev/null +++ b/solutions/308. Range Sum Query 2D - Mutable/308.java @@ -0,0 +1,48 @@ +class FenwickTree { + public FenwickTree(int m, int n) { + sums = new int[m + 1][n + 1]; + } + + public void add(int row, int col, int delta) { + for (int i = row; i < sums.length; i += lowbit(i)) + for (int j = col; j < sums[0].length; j += lowbit(j)) + sums[i][j] += delta; + } + + public int get(int row, int col) { + int sum = 0; + for (int i = row; i > 0; i -= lowbit(i)) + for (int j = col; j > 0; j -= lowbit(j)) + sum += sums[i][j]; + return sum; + } + + private int[][] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class NumMatrix { + public NumMatrix(int[][] matrix) { + this.matrix = matrix; + tree = new FenwickTree(matrix.length, matrix[0].length); + for (int i = 0; i < matrix.length; ++i) + for (int j = 0; j < matrix[0].length; ++j) + tree.add(i + 1, j + 1, matrix[i][j]); + } + + public void update(int row, int col, int val) { + tree.add(row + 1, col + 1, val - matrix[row][col]); + matrix[row][col] = val; + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + return tree.get(row2 + 1, col2 + 1) - tree.get(row1, col2 + 1) - tree.get(row2 + 1, col1) + + tree.get(row1, col1); + } + + private int[][] matrix; + private FenwickTree tree; +} diff --git a/solutions/308. Range Sum Query 2D - Mutable/308.py b/solutions/308. Range Sum Query 2D - Mutable/308.py new file mode 100644 index 00000000000..887bee7c227 --- /dev/null +++ b/solutions/308. Range Sum Query 2D - Mutable/308.py @@ -0,0 +1,45 @@ +class FenwickTree: + def __init__(self, m: int, n: int): + self.sums = [[0] * (n + 1) for _ in range(m + 1)] + + def add(self, row: int, col: int, delta: int) -> None: + i = row + while i < len(self.sums): + j = col + while j < len(self.sums[0]): + self.sums[i][j] += delta + j += FenwickTree.lowbit(j) + i += FenwickTree.lowbit(i) + + def get(self, row: int, col: int) -> int: + summ = 0 + i = row + while i > 0: + j = col + while j > 0: + summ += self.sums[i][j] + j -= FenwickTree.lowbit(j) + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class NumMatrix: + def __init__(self, matrix: List[List[int]]): + self.matrix = matrix + self.tree = FenwickTree(len(matrix), len(matrix[0])) + + for i in range(len(matrix)): + for j, val in enumerate(matrix[i]): + self.tree.add(i + 1, j + 1, val) + + def update(self, row: int, col: int, val: int) -> None: + self.tree.add(row + 1, col + 1, val - self.matrix[row][col]) + self.matrix[row][col] = val + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return self.tree.get(row2 + 1, col2 + 1) - self.tree.get(row1, col2 + 1) - \ + self.tree.get(row2 + 1, col1) + self.tree.get(row1, col1) diff --git a/solutions/3080. Mark Elements on Array by Performing Queries/3080.cpp b/solutions/3080. Mark Elements on Array by Performing Queries/3080.cpp new file mode 100644 index 00000000000..614f78e6385 --- /dev/null +++ b/solutions/3080. Mark Elements on Array by Performing Queries/3080.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector unmarkedSumArray(vector& nums, + vector>& queries) { + vector ans; + vector marked(nums.size()); + long sum = accumulate(nums.begin(), nums.end(), 0L); + using P = pair; // (nums[i], i) + priority_queue, greater<>> minHeap; + + for (int i = 0; i < nums.size(); ++i) + minHeap.emplace(nums[i], i); + + for (const vector& query : queries) { + const int index = query[0]; + const int k = query[1]; + if (!marked[index]) { + marked[index] = true; + sum -= nums[index]; + } + for (int popped = 0; popped < k && !minHeap.empty();) { + const auto [num, i] = minHeap.top(); + minHeap.pop(); + if (!marked[i]) { + marked[i] = true; + sum -= num; + ++popped; + } + } + ans.push_back(sum); + } + + return ans; + } +}; diff --git a/solutions/3080. Mark Elements on Array by Performing Queries/3080.java b/solutions/3080. Mark Elements on Array by Performing Queries/3080.java new file mode 100644 index 00000000000..07cac7af2ac --- /dev/null +++ b/solutions/3080. Mark Elements on Array by Performing Queries/3080.java @@ -0,0 +1,36 @@ +class Solution { + public long[] unmarkedSumArray(int[] nums, int[][] queries) { + long[] ans = new long[queries.length]; + boolean[] marked = new boolean[nums.length]; + long sum = Arrays.stream(nums).asLongStream().sum(); + // (nums[i], i) + Queue> minHeap = new PriorityQueue<>( + (a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue().compareTo(b.getValue()) + : a.getKey().compareTo(b.getKey())); + + for (int i = 0; i < nums.length; ++i) + minHeap.offer(new Pair<>(nums[i], i)); + + for (int queryIndex = 0; queryIndex < queries.length; ++queryIndex) { + final int index = queries[queryIndex][0]; + final int k = queries[queryIndex][1]; + if (!marked[index]) { + marked[index] = true; + sum -= nums[index]; + } + for (int popped = 0; popped < k && !minHeap.isEmpty();) { + final int num = minHeap.peek().getKey(); + final int i = minHeap.poll().getValue(); + if (!marked[i]) { + marked[i] = true; + sum -= num; + ++popped; + } + } + ans[queryIndex] = sum; + } + + return ans; + } +} diff --git a/solutions/3080. Mark Elements on Array by Performing Queries/3080.py b/solutions/3080. Mark Elements on Array by Performing Queries/3080.py new file mode 100644 index 00000000000..434ebc2d096 --- /dev/null +++ b/solutions/3080. Mark Elements on Array by Performing Queries/3080.py @@ -0,0 +1,22 @@ +class Solution: + def unmarkedSumArray(self, nums: List[int], queries: List[List[int]]) -> List[int]: + ans = [] + marked = set() + summ = sum(nums) + minHeap = [(num, i) for i, num in enumerate(nums)] + heapq.heapify(minHeap) + + for index, k in queries: + if index not in marked: + marked.add(index) + summ -= nums[index] + popped = 0 + while popped < k and minHeap: + num, i = heapq.heappop(minHeap) + if i not in marked: + marked.add(i) + summ -= num + popped += 1 + ans.append(summ) + + return ans diff --git a/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.cpp b/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.cpp new file mode 100644 index 00000000000..4017b693df7 --- /dev/null +++ b/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + string minimizeStringValue(string s) { + string ans; + vector count(26); + vector letters; + + for (const char c : s) + if (c != '?') + ++count[c - 'a']; + + for (const char c : s) { + if (c != '?') + continue; + const char minFreqLetter = getMinFreqLetter(count); + letters.push_back(minFreqLetter); + ++count[minFreqLetter - 'a']; + } + + ranges::sort(letters); + int i = 0; // letters' index + + for (const char c : s) + ans += c == '?' ? letters[i++] : c; + + return ans; + } + + private: + char getMinFreqLetter(const vector& count) { + char minFreqLetter = 'a'; + for (char c = 'b'; c <= 'z'; ++c) + if (count[c - 'a'] < count[minFreqLetter - 'a']) + minFreqLetter = c; + return minFreqLetter; + } +}; diff --git a/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.java b/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.java new file mode 100644 index 00000000000..059e84748ef --- /dev/null +++ b/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.java @@ -0,0 +1,35 @@ +class Solution { + public String minimizeStringValue(String s) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[26]; + List letters = new ArrayList<>(); + + for (final char c : s.toCharArray()) + if (c != '?') + ++count[c - 'a']; + + for (final char c : s.toCharArray()) { + if (c != '?') + continue; + final char minFreqLetter = getMinFreqLetter(count); + letters.add(minFreqLetter); + ++count[minFreqLetter - 'a']; + } + + Collections.sort(letters); + int i = 0; // letters' index + + for (final char c : s.toCharArray()) + sb.append(c == '?' ? letters.get(i++) : c); + + return sb.toString(); + } + + private char getMinFreqLetter(int[] count) { + char minFreqLetter = 'a'; + for (char c = 'b'; c <= 'z'; ++c) + if (count[c - 'a'] < count[minFreqLetter - 'a']) + minFreqLetter = c; + return minFreqLetter; + } +} diff --git a/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.py b/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.py new file mode 100644 index 00000000000..97b2e0bd07b --- /dev/null +++ b/solutions/3081. Replace Question Marks in String to Minimize Its Value/3081.py @@ -0,0 +1,32 @@ +class Solution: + def minimizeStringValue(self, s: str) -> str: + ans = [] + count = collections.Counter(s) + letters = [] + + del count['?'] + + def getMinFreqLetter(count: Dict[str, int]) -> str: + minFreqLetter = 'a' + for c in string.ascii_lowercase: + if count[c] < count[minFreqLetter]: + minFreqLetter = c + return minFreqLetter + + for c in s: + if c == '?': + minFreqLetter = getMinFreqLetter(count) + letters.append(minFreqLetter) + count[minFreqLetter] += 1 + + letters.sort() + i = 0 # letters' index + + for c in s: + if c == '?': + ans.append(letters[i]) + i += 1 + else: + ans.append(c) + + return ''.join(ans) diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.cpp b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.cpp new file mode 100644 index 00000000000..c424370d299 --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int sumOfPower(vector& nums, int k) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + // dp[i][j] := the number of subsequences in nums[0..i) that sums to k + vector> dp(n + 1, vector(k + 1)); + dp[0][0] = 1; + + for (int i = 1; i <= n; ++i) { + const int num = nums[i - 1]; + for (int j = 0; j <= k; ++j) + if (j < num) + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + dp[i][j] = (dp[i - 1][j] * 2L) % kMod; + else + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + // 3. Include nums[i] in the subsequence and pick it. + dp[i][j] = (dp[i - 1][j] * 2L + dp[i - 1][j - num]) % kMod; + } + + return dp[n][k]; + } +}; diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.java b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.java new file mode 100644 index 00000000000..9e6e3b36117 --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.java @@ -0,0 +1,25 @@ +class Solution { + public int sumOfPower(int[] nums, int k) { + final int kMod = 1_000_000_007; + final int n = nums.length; + // dp[i][j] := the number of subsequences in nums[0..i) that sums to k + int[][] dp = new int[n + 1][k + 1]; + dp[0][0] = 1; + + for (int i = 1; i <= n; ++i) { + final int num = nums[i - 1]; + for (int j = 0; j <= k; ++j) + if (j < num) + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + dp[i][j] = (int) ((dp[i - 1][j] * 2L) % kMod); + else + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + // 3. Include nums[i] in the subsequence and pick it. + dp[i][j] = (int) ((dp[i - 1][j] * 2L + dp[i - 1][j - num]) % kMod); + } + + return dp[n][k]; + } +} diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.py b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.py new file mode 100644 index 00000000000..bb5591b690d --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.py @@ -0,0 +1,22 @@ +class Solution: + def sumOfPower(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + n = len(nums) + # dp[i][j] := the number of subsequences in nums[0..i) that sums to k + dp = [[0] * (k + 1) for _ in range(n + 1)] + dp[0][0] = 1 + + for i in range(1, n + 1): + num = nums[i - 1] + for j in range(k + 1): + if j < num: + # 1. Exclude nums[i] in the subsequence. + # 2. Include nums[i] in the subsequence and skip it. + dp[i][j] = (dp[i - 1][j] * 2) % kMod + else: + # 1. Exclude nums[i] in the subsequence. + # 2. Include nums[i] in the subsequence and skip it. + # 3. Include nums[i] in the subsequence and pick it. + dp[i][j] = (dp[i - 1][j] * 2 + dp[i - 1][j - num]) % kMod + + return dp[n][k] diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.cpp b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.cpp new file mode 100644 index 00000000000..ac86972572f --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int sumOfPower(vector& nums, int k) { + constexpr int kMod = 1'000'000'007; + // dp[i] := the number of subsequences in nums so far that sums to k + vector dp(k + 1); + dp[0] = 1; + + for (const int num : nums) + for (int i = k; i >= 0; --i) + if (i < num) + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + dp[i] = (dp[i] * 2L) % kMod; + else + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + // 3. Include nums[i] in the subsequence and pick it. + dp[i] = (dp[i] * 2L + dp[i - num]) % kMod; + + return dp[k]; + } +}; diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.java b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.java new file mode 100644 index 00000000000..9f7daefd772 --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.java @@ -0,0 +1,22 @@ +class Solution { + public int sumOfPower(int[] nums, int k) { + final int kMod = 1_000_000_007; + // dp[i] := the number of subsequences in nums so far that sums to k + int[] dp = new int[k + 1]; + dp[0] = 1; + + for (final int num : nums) + for (int i = k; i >= 0; --i) + if (i < num) + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + dp[i] = (int) ((dp[i] * 2L) % kMod); + else + // 1. Exclude nums[i] in the subsequence. + // 2. Include nums[i] in the subsequence and skip it. + // 3. Include nums[i] in the subsequence and pick it. + dp[i] = (int) ((dp[i] * 2L + dp[i - num]) % kMod); + + return dp[k]; + } +} diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.py b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.py new file mode 100644 index 00000000000..d35e92214f4 --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.py @@ -0,0 +1,14 @@ +class Solution: + def sumOfPower(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of subsequences in nums so far that sums to k + dp = [1] + [0] * k + + for num in nums: + for i in range(k, -1, -1): + if i < num: + dp[i] = (dp[i] * 2) % kMod + else: + dp[i] = (dp[i] * 2 + dp[i - num]) % kMod + + return dp[k] diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082.cpp b/solutions/3082. Find the Sum of the Power of All Subsequences/3082.cpp new file mode 100644 index 00000000000..7061e461405 --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int sumOfPower(vector& nums, int k) { + vector> mem(nums.size(), vector(k + 1, -1)); + return sumOfPower(nums, 0, k, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of subsequences in nums[i..n) that sums to j. + int sumOfPower(const vector& nums, int i, int j, + vector>& mem) { + if (j == 0) + // For each of the remaining number, we can either pick it or skip it. + return modPow(2, nums.size() - i); + if (i == nums.size() || j < 0) + return 0; + if (mem[i][j] != -1) + return mem[i][j]; + // 1. Include nums[i] in the subsequence and pick it. + // 2. Include nums[i] in the subsequence and skip it. + // 3. Exclude nums[i] in the subsequence. + return mem[i][j] = (sumOfPower(nums, i + 1, j - nums[i], mem) + + 2L * sumOfPower(nums, i + 1, j, mem)) % + kMod; + } + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082.java b/solutions/3082. Find the Sum of the Power of All Subsequences/3082.java new file mode 100644 index 00000000000..405af3c8044 --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082.java @@ -0,0 +1,33 @@ +class Solution { + public int sumOfPower(int[] nums, int k) { + Integer[][] mem = new Integer[nums.length][k + 1]; + return sumOfPower(nums, 0, k, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of subsequences in nums[i..n) that sums to j. + private int sumOfPower(int[] nums, int i, int j, Integer[][] mem) { + if (j == 0) + // For each of the remaining number, we can either pick it or skip it. + return (int) modPow(2, nums.length - i); + if (i == nums.length || j < 0) + return 0; + if (mem[i][j] != null) + return mem[i][j]; + // 1. Include nums[i] in the subsequence and pick it. + // 2. Include nums[i] in the subsequence and skip it. + // 3. Exclude nums[i] in the subsequence. + return mem[i][j] = (int) ((sumOfPower(nums, i + 1, j - nums[i], mem) + // + 2L * sumOfPower(nums, i + 1, j, mem)) % + kMod); + } + + private long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +} diff --git a/solutions/3082. Find the Sum of the Power of All Subsequences/3082.py b/solutions/3082. Find the Sum of the Power of All Subsequences/3082.py new file mode 100644 index 00000000000..d88582b4fc8 --- /dev/null +++ b/solutions/3082. Find the Sum of the Power of All Subsequences/3082.py @@ -0,0 +1,18 @@ +class Solution: + def sumOfPower(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def dp(i: int, j: int) -> int: + """Returns the number of subsequences in nums[i..n) that sums to j.""" + if j == 0: + # For each of the remaining number, we can either pick it or skip it. + return pow(2, len(nums) - i, kMod) + if i == len(nums) or j < 0: + return 0 + # 1. Include nums[i] in the subsequence and pick it. + # 2. Include nums[i] in the subsequence and skip it. + # 3. Exclude nums[i] in the subsequence. + return (dp(i + 1, j - nums[i]) + 2 * dp(i + 1, j)) % kMod + + return dp(0, k) diff --git a/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.cpp b/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.cpp new file mode 100644 index 00000000000..35072ed0af1 --- /dev/null +++ b/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + bool isSubstringPresent(string s) { + const string reversed = {s.rbegin(), s.rend()}; + for (int i = 0; i + 2 <= s.length(); ++i) + if (reversed.find(s.substr(i, 2)) != string::npos) + return true; + return false; + } +}; diff --git a/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.java b/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.java new file mode 100644 index 00000000000..6bcd8917b13 --- /dev/null +++ b/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.java @@ -0,0 +1,9 @@ +class Solution { + public boolean isSubstringPresent(String s) { + String reversed = new StringBuilder(s).reverse().toString(); + for (int i = 0; i + 2 <= s.length(); ++i) + if (reversed.contains(s.substring(i, i + 2))) + return true; + return false; + } +} diff --git a/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.py b/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.py new file mode 100644 index 00000000000..263701f9b3f --- /dev/null +++ b/solutions/3083. Existence of a Substring in a String and Its Reverse/3083.py @@ -0,0 +1,3 @@ +class Solution: + def isSubstringPresent(self, s: str) -> bool: + return any(s[i:i + 2] in s[::-1] for i in range(len(s) - 1)) diff --git a/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.cpp b/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.cpp new file mode 100644 index 00000000000..b6fdc32bcb9 --- /dev/null +++ b/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + long long countSubstrings(string s, char c) { + const int freq = ranges::count(s, c); + return static_cast(freq) * (freq + 1) / 2; + } +}; diff --git a/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.java b/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.java new file mode 100644 index 00000000000..835138cab94 --- /dev/null +++ b/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.java @@ -0,0 +1,6 @@ +class Solution { + public long countSubstrings(String s, char c) { + final long freq = s.chars().filter(ch -> ch == c).count(); + return freq * (freq + 1) / 2; + } +} diff --git a/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.py b/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.py new file mode 100644 index 00000000000..2c92a3b7e16 --- /dev/null +++ b/solutions/3084. Count Substrings Starting and Ending with Given Character/3084.py @@ -0,0 +1,4 @@ +class Solution: + def countSubstrings(self, s: str, c: str) -> int: + freq = s.count(c) + return freq * (freq + 1) // 2 diff --git a/solutions/3085. Minimum Deletions to Make String K-Special/3085.cpp b/solutions/3085. Minimum Deletions to Make String K-Special/3085.cpp new file mode 100644 index 00000000000..721a37b0775 --- /dev/null +++ b/solutions/3085. Minimum Deletions to Make String K-Special/3085.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minimumDeletions(string word, int k) { + int ans = INT_MAX; + vector count(26); + + for (const char c : word) + ++count[c - 'a']; + + for (const int minFreq : count) { + int deletions = 0; + for (const int freq : count) + if (freq < minFreq) // Delete all the letters with smaller frequency. + deletions += freq; + else // Delete letters with exceeding frequency. + deletions += max(0, freq - (minFreq + k)); + ans = min(ans, deletions); + } + + return ans; + } +}; diff --git a/solutions/3085. Minimum Deletions to Make String K-Special/3085.java b/solutions/3085. Minimum Deletions to Make String K-Special/3085.java new file mode 100644 index 00000000000..8d1858735a2 --- /dev/null +++ b/solutions/3085. Minimum Deletions to Make String K-Special/3085.java @@ -0,0 +1,21 @@ +class Solution { + public int minimumDeletions(String word, int k) { + int ans = Integer.MAX_VALUE; + int count[] = new int[26]; + + for (final char c : word.toCharArray()) + ++count[c - 'a']; + + for (final int minFreq : count) { + int deletions = 0; + for (final int freq : count) + if (freq < minFreq) // Delete all the letters with smaller frequency. + deletions += freq; + else // Delete letters with exceeding frequency. + deletions += Math.max(0, freq - (minFreq + k)); + ans = Math.min(ans, deletions); + } + + return ans; + } +} diff --git a/solutions/3085. Minimum Deletions to Make String K-Special/3085.py b/solutions/3085. Minimum Deletions to Make String K-Special/3085.py new file mode 100644 index 00000000000..c06e79b88ab --- /dev/null +++ b/solutions/3085. Minimum Deletions to Make String K-Special/3085.py @@ -0,0 +1,15 @@ +class Solution: + def minimumDeletions(self, word: str, k: int) -> int: + ans = math.inf + count = collections.Counter(word) + + for minFreq in count.values(): + deletions = 0 + for freq in count.values(): + if freq < minFreq: + deletions += freq + else: + deletions += max(0, freq - (minFreq + k)) + ans = min(ans, deletions) + + return ans diff --git a/solutions/3086. Minimum Moves to Pick K Ones/3086.cpp b/solutions/3086. Minimum Moves to Pick K Ones/3086.cpp new file mode 100644 index 00000000000..ae465ba3cdc --- /dev/null +++ b/solutions/3086. Minimum Moves to Pick K Ones/3086.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + long long minimumMoves(vector& nums, int k, int maxChanges) { + // Dylan has two actions for collecting '1's in a sequence: + // Action 1: Put a '1' next to him and pick it up. + // The cost is 2. + // Action 2: Swap a '1' towards him and collect it. + // The cost equals the distance to the '1'. + // + // To minimize the swapping cost, Dylan can use a sliding window strategy, + // selecting the optimal position (middle '1' in the window) for efficient + // collection. The window's size is crucial: + + // The minimum window size: min(0, k - maxChanges), ensuring the window + // isn't too small. + // The maximum window size: min(k, minOnesByTwo + 3, the number of ones), + // preventing overly ambitious swaps. + // + // Note that if needing to move a '1' beyond `minOnesByTwo + 3`, it's + // cheaper to use Action 1. + + // At most three indices, (dylanIndex - 1, dylanIndex, dylanIndex + 1), have + // a distance <= 1 from dylanIndex, implying that we'll be taking at most + // `maxOnesByTwo + 3` using Action 2. Any more Action 2 is not optimal and + // should be replaced with Action 1. + constexpr int kNumOfIndicesWithinOneDistance = 3; + long ans = LONG_MAX; + vector oneIndices; // the indices of 1s + vector prefix{0}; // the accumulated indices of 1s + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == 1) + oneIndices.push_back(i); + + for (const int oneIndex : oneIndices) + prefix.push_back(prefix.back() + oneIndex); + + const int minOnesByTwo = max(0, k - maxChanges); + const int maxOnesByTwo = + min({k, minOnesByTwo + kNumOfIndicesWithinOneDistance, + static_cast(oneIndices.size())}); + + for (int onesByTwo = minOnesByTwo; onesByTwo <= maxOnesByTwo; ++onesByTwo) + for (int l = 0; l + onesByTwo < prefix.size(); ++l) { + const int r = l + onesByTwo; // Collect 1s in oneIndices[l - 1..r - 1]. + const long cost1 = (k - onesByTwo) * 2; + const long cost2 = (prefix[r] - prefix[(l + r) / 2]) - + (prefix[(l + r + 1) / 2] - prefix[l]); + ans = min(ans, cost1 + cost2); + } + + return ans; + } +}; diff --git a/solutions/3086. Minimum Moves to Pick K Ones/3086.java b/solutions/3086. Minimum Moves to Pick K Ones/3086.java new file mode 100644 index 00000000000..26bfec67a3c --- /dev/null +++ b/solutions/3086. Minimum Moves to Pick K Ones/3086.java @@ -0,0 +1,53 @@ +class Solution { + public long minimumMoves(int[] nums, int k, int maxChanges) { + // Dylan has two actions for collecting '1's in a sequence: + // Action 1: Put a '1' next to him and pick it up. + // The cost is 2. + // Action 2: Swap a '1' towards him and collect it. + // The cost equals the distance to the '1'. + // + // To minimize the swapping cost, Dylan can use a sliding window strategy, + // selecting the optimal position (middle '1' in the window) for efficient + // collection. The window's size is crucial: + + // The minimum window size: min(0, k - maxChanges), ensuring the window + // isn't too small. + // The maximum window size: min(k, minOnesByTwo + 3, the number of ones), + // preventing overly ambitious swaps. + // + // Note that if needing to move a '1' beyond `minOnesByTwo + 3`, it's + // cheaper to use Action 1. + + // At most three indices, (dylanIndex - 1, dylanIndex, dylanIndex + 1), have + // a distance <= 1 from dylanIndex, implying that we'll be taking at most + // `maxOnesByTwo + 3` using Action 2. Any more Action 2 is not optimal and + // should be replaced with Action 1. + final int kNumOfIndicesWithinOneDistance = 3; + long ans = Long.MAX_VALUE; + List oneIndices = new ArrayList<>(); // the indices of 1s + List prefix = new ArrayList<>(); // the accumulated indices of 1s + prefix.add(0L); + + for (int i = 0; i < nums.length; ++i) + if (nums[i] == 1) + oneIndices.add(i); + + for (final int oneIndex : oneIndices) + prefix.add(prefix.get(prefix.size() - 1) + oneIndex); + + final int minOnesByTwo = Math.max(0, k - maxChanges); + final int maxOnesByTwo = + Math.min(k, Math.min(minOnesByTwo + kNumOfIndicesWithinOneDistance, oneIndices.size())); + + for (int onesByTwo = minOnesByTwo; onesByTwo <= maxOnesByTwo; ++onesByTwo) + for (int l = 0; l + onesByTwo < prefix.size(); ++l) { + final int r = l + onesByTwo; // Collect 1s in oneIndices[l - 1..r - 1]. + final long cost1 = (k - onesByTwo) * 2; + final long cost2 = (prefix.get(r) - prefix.get((l + r) / 2)) - + (prefix.get((l + r + 1) / 2) - prefix.get(l)); + ans = Math.min(ans, cost1 + cost2); + } + + return ans; + } +} diff --git a/solutions/3086. Minimum Moves to Pick K Ones/3086.py b/solutions/3086. Minimum Moves to Pick K Ones/3086.py new file mode 100644 index 00000000000..00da63d2a96 --- /dev/null +++ b/solutions/3086. Minimum Moves to Pick K Ones/3086.py @@ -0,0 +1,42 @@ +class Solution: + def minimumMoves(self, nums: List[int], k: int, maxChanges: int) -> int: + # Dylan has two actions for collecting '1's in a sequence: + # Action 1: Put a '1' next to him and pick it up. + # The cost is 2. + # Action 2: Swap a '1' towards him and collect it. + # The cost equals the distance to the '1'. + # + # To minimize the swapping cost, Dylan can use a sliding window strategy, + # selecting the optimal position (middle '1' in the window) for efficient + # collection. The window's size is crucial: + + # The minimum window size: min(0, k - maxChanges), ensuring the window + # isn't too small. + # The maximum window size: min(k, minOnesByTwo + 3, the number of ones), + # preventing overly ambitious swaps. + # + # Note that if needing to move a '1' beyond `minOnesByTwo + 3`, it's + # cheaper to use Action 1. + + # At most three indices, (dylanIndex - 1, dylanIndex, dylanIndex + 1), have + # a distance <= 1 from dylanIndex, implying that we'll be taking at most + # `maxOnesByTwo + 3` using Action 2. Any more Action 2 is not optimal and + # should be replaced with Action 1. + kNumOfIndicesWithinOneDistance = 3 + ans = math.inf + oneIndices = [i for i, num in enumerate(nums) if num == 1] + prefix = list(itertools.accumulate(oneIndices, initial=0)) + + minOnesByTwo = max(0, k - maxChanges) + maxOnesByTwo = min( + k, minOnesByTwo + kNumOfIndicesWithinOneDistance, len(oneIndices)) + + for onesByTwo in range(minOnesByTwo, maxOnesByTwo + 1): + for l in range(len(prefix) - onesByTwo): + r = l + onesByTwo # Collect 1s in oneIndices[l - 1..r - 1]. + cost1 = (k - onesByTwo) * 2 + cost2 = (prefix[r] - prefix[(l + r) // 2]) - \ + (prefix[(l + r + 1) // 2] - prefix[l]) + ans = min(ans, cost1 + cost2) + + return ans diff --git a/solutions/3087. Find Trending Hashtags/3087.sql b/solutions/3087. Find Trending Hashtags/3087.sql new file mode 100644 index 00000000000..d15c9edc225 --- /dev/null +++ b/solutions/3087. Find Trending Hashtags/3087.sql @@ -0,0 +1,11 @@ +SELECT + CONCAT( + '#', + SUBSTRING_INDEX(SUBSTRING_INDEX(tweet, '#', -1), ' ', 1) + ) AS hashtag, + COUNT(*) AS hashtag_count +FROM Tweets +WHERE MONTH(tweet_date) = 2 +GROUP BY hashtag +ORDER BY hashtag_count DESC, hashtag DESC +LIMIT 3; diff --git a/solutions/3088. Make String Anti-palindrome/3088.cpp b/solutions/3088. Make String Anti-palindrome/3088.cpp new file mode 100644 index 00000000000..edde7782295 --- /dev/null +++ b/solutions/3088. Make String Anti-palindrome/3088.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + string makeAntiPalindrome(string s) { + const int n = s.length(); + int i = n / 2; + ranges::sort(s); + if (s[i] != s[n - i - 1]) + return s; + + int j = getFirstDiffIndexInSecondHalf(s); + while (s[i] == s[n - i - 1]) { + if (j == n) + return "-1"; + swap(s[i++], s[j++]); + } + + return s; + } + + private: + // Returns the first index in s[n / 2..n) that is different from the first + // letter of the second half, s[n / 2]. + int getFirstDiffIndexInSecondHalf(const string& s) { + const int n = s.size(); + const char firstLetter = s[n / 2]; + int firstDiffIndex = n / 2; + while (firstDiffIndex < n && s[firstDiffIndex] == firstLetter) + ++firstDiffIndex; + return firstDiffIndex; + } +}; diff --git a/solutions/3088. Make String Anti-palindrome/3088.java b/solutions/3088. Make String Anti-palindrome/3088.java new file mode 100644 index 00000000000..9257348e94b --- /dev/null +++ b/solutions/3088. Make String Anti-palindrome/3088.java @@ -0,0 +1,34 @@ +class Solution { + public String makeAntiPalindrome(String s) { + final int n = s.length(); + int i = n / 2; + char[] chars = s.toCharArray(); + Arrays.sort(chars); + if (chars[i] != chars[n - i - 1]) + return new String(chars); + + int j = getFirstDiffIndexInSecondHalf(chars); + while (chars[i] == chars[n - i - 1]) { + if (j == n) + return "-1"; + final char temp = chars[i]; + chars[i] = chars[j]; + chars[j] = temp; + ++i; + ++j; + } + + return new String(chars); + } + + // Returns the first index in chars[n / 2..n) that is different from the first + // letter of the second half, chars[n / 2]. + private int getFirstDiffIndexInSecondHalf(char[] chars) { + final int n = chars.length; + final char firstLetter = chars[n / 2]; + int firstDiffIndex = n / 2; + while (firstDiffIndex < n && chars[firstDiffIndex] == firstLetter) + ++firstDiffIndex; + return firstDiffIndex; + } +} diff --git a/solutions/3088. Make String Anti-palindrome/3088.py b/solutions/3088. Make String Anti-palindrome/3088.py new file mode 100644 index 00000000000..3ae049c0dc4 --- /dev/null +++ b/solutions/3088. Make String Anti-palindrome/3088.py @@ -0,0 +1,29 @@ +class Solution: + def makeAntiPalindrome(self, s: str) -> str: + n = len(s) + i = n // 2 + chars = sorted(list(s)) + if chars[i] != chars[n - i - 1]: + return ''.join(chars) + + j = self._getFirstDiffIndexInSecondHalf(chars) + while chars[i] == chars[n - i - 1]: + if j == n: + return '-1' + chars[i], chars[j] = chars[j], chars[i] + i += 1 + j += 1 + + return ''.join(chars) + + def _getFirstDiffIndexInSecondHalf(self, chars: List[str]) -> int: + """ + Returns the first index in chars[n / 2..n) that is different from the first + letter of the second half, chars[n / 2]. + """ + n = len(chars) + firstLetter = chars[n // 2] + firstDiffIndex = n // 2 + while firstDiffIndex < n and chars[firstDiffIndex] == firstLetter: + firstDiffIndex += 1 + return firstDiffIndex diff --git a/solutions/3089. Find Bursty Behavior/3089.sql b/solutions/3089. Find Bursty Behavior/3089.sql new file mode 100644 index 00000000000..969dad67cda --- /dev/null +++ b/solutions/3089. Find Bursty Behavior/3089.sql @@ -0,0 +1,34 @@ +WITH + FilteredPosts AS ( + SELECT * + FROM Posts + WHERE post_date BETWEEN '2024-02-01' AND '2024-02-28' + ), + AvgWeeklyPosts AS ( + SELECT user_id, COUNT(*) / 4.0 AS avg_weekly_posts + FROM FilteredPosts + GROUP BY 1 + ), + UserTo7dayPosts AS ( + SELECT + FirstPost.user_id, + COUNT(*) AS sevenday_posts + FROM Posts AS FirstPost + INNER JOIN Posts AS FollowingPost + ON ( + FirstPost.user_id = FollowingPost.user_id + AND FollowingPost.post_date BETWEEN FirstPost.post_date + AND DATE_ADD(FirstPost.post_date, INTERVAL 6 DAY)) + GROUP BY FirstPost.user_id, FirstPost.post_date + ), + UserToMax7dayPosts AS ( + SELECT user_id, MAX(sevenday_posts) AS max_7day_posts + FROM UserTo7dayPosts + GROUP BY 1 + ) +SELECT * +FROM UserToMax7dayPosts +INNER JOIN AvgWeeklyPosts + USING (user_id) +WHERE UserToMax7dayPosts.max_7day_posts >= 2 * AvgWeeklyPosts.avg_weekly_posts +ORDER BY user_id; diff --git a/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.cpp b/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.cpp new file mode 100644 index 00000000000..415f8028244 --- /dev/null +++ b/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxProfit(vector& prices) { + int sell = 0; + int hold = INT_MIN; + int prev = 0; + + for (const int price : prices) { + const int cache = sell; + sell = max(sell, hold + price); + hold = max(hold, prev - price); + prev = cache; + } + + return sell; + } +}; diff --git a/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.java b/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.java new file mode 100644 index 00000000000..dae81608d72 --- /dev/null +++ b/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.java @@ -0,0 +1,16 @@ +class Solution { + public int maxProfit(int[] prices) { + int sell = 0; + int hold = Integer.MIN_VALUE; + int prev = 0; + + for (final int price : prices) { + final int cache = sell; + sell = Math.max(sell, hold + price); + hold = Math.max(hold, prev - price); + prev = cache; + } + + return sell; + } +} diff --git a/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.py b/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.py new file mode 100644 index 00000000000..3a6a4c7d076 --- /dev/null +++ b/solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.py @@ -0,0 +1,13 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + sell = 0 + hold = -math.inf + prev = 0 + + for price in prices: + cache = sell + sell = max(sell, hold + price) + hold = max(hold, prev - price) + prev = cache + + return sell diff --git a/solutions/3090. Maximum Length Substring With Two Occurrences/3090.cpp b/solutions/3090. Maximum Length Substring With Two Occurrences/3090.cpp new file mode 100644 index 00000000000..0aafa74135e --- /dev/null +++ b/solutions/3090. Maximum Length Substring With Two Occurrences/3090.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maximumLengthSubstring(string s) { + int ans = 0; + vector count(26); + + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s[r] - 'a']; + while (count[s[r] - 'a'] > 2) + --count[s[l++] - 'a']; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/3090. Maximum Length Substring With Two Occurrences/3090.java b/solutions/3090. Maximum Length Substring With Two Occurrences/3090.java new file mode 100644 index 00000000000..7d2c4611a3d --- /dev/null +++ b/solutions/3090. Maximum Length Substring With Two Occurrences/3090.java @@ -0,0 +1,15 @@ +class Solution { + public int maximumLengthSubstring(String s) { + int ans = 0; + int[] count = new int[26]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s.charAt(r) - 'a']; + while (count[s.charAt(r) - 'a'] > 2) + --count[s.charAt(l++) - 'a']; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/3090. Maximum Length Substring With Two Occurrences/3090.py b/solutions/3090. Maximum Length Substring With Two Occurrences/3090.py new file mode 100644 index 00000000000..158da686ec0 --- /dev/null +++ b/solutions/3090. Maximum Length Substring With Two Occurrences/3090.py @@ -0,0 +1,14 @@ +class Solution: + def maximumLengthSubstring(self, s: str) -> int: + ans = 0 + count = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + while count[c] > 2: + count[s[l]] -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.cpp b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.cpp new file mode 100644 index 00000000000..73bc6be409b --- /dev/null +++ b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minOperations(int k) { + // The required operations are + // 1. Increase `1` to `x` + // 2. Duplicate `x`, `y` times, to `sum` s.t. x * (1 + y) >= k. + // The number of operations used would be (x - 1) + y. Equivalently, the + // problem can be rephrased as finding min(x - 1 + y) s.t. x * (1 + y) >= k. + // Optimally, `x` should equal to `1 + y`, implying that x^2 >= k, and + // hence, x >= sqrt(k) and y = ceil(k / x) - 1. + const int x = sqrt(k); + const int y = (k - 1) / x + 1 - 1; // ceil(k / x) - 1 + return x - 1 + y; + } +}; diff --git a/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.java b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.java new file mode 100644 index 00000000000..da20ca3e069 --- /dev/null +++ b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.java @@ -0,0 +1,14 @@ +class Solution { + public int minOperations(int k) { + // The required operations are + // 1. Increase `1` to `x` + // 2. Duplicate `x`, `y` times, to `sum` s.t. x * (1 + y) >= k. + // The number of operations used would be (x - 1) + y. Equivalently, the + // problem can be rephrased as finding min(x - 1 + y) s.t. x * (1 + y) >= k. + // Optimally, `x` should equal to `1 + y`, implying that x^2 >= k, and + // hence, x >= sqrt(k) and y = ceil(k / x) - 1. + final int x = (int) Math.sqrt(k); + final int y = (k - 1) / x + 1 - 1; // ceil(k / x) - 1 + return x - 1 + y; + } +} diff --git a/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.py b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.py new file mode 100644 index 00000000000..00406fbe7fb --- /dev/null +++ b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091-2.py @@ -0,0 +1,12 @@ +class Solution: + def minOperations(self, k: int) -> int: + # The required operations are + # 1. Increase `1` to `x` + # 2. Duplicate `x`, `y` times, to `sum` s.t. x * (1 + y) >= k. + # The number of operations used would be (x - 1) + y. Equivalently, the + # problem can be rephrased as finding min(x - 1 + y) s.t. x * (1 + y) >= k. + # Optimally, `x` should equal to `1 + y`, implying that x^2 >= k, and + # hence, x >= sqrt(k) and y = ceil(k / x) - 1. + x = math.isqrt(k) + y = (k - 1) // x + 1 - 1 # ceil(k / x) - 1 + return x - 1 + y diff --git a/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.cpp b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.cpp new file mode 100644 index 00000000000..3edaa083af9 --- /dev/null +++ b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minOperations(int k) { + // The required operations are + // 1. Increase `1` to `x` + // 2. Duplicate `x`, `y` times, to `sum` s.t. x * (1 + y) >= k. + // The number of operations used would be (x - 1) + y. Equivalently, the + // problem can be rephrased as finding min(x - 1 + y) s.t. x * (1 + y) >= k. + // Optimally, `x` should equal to `1 + y`, implying that x^2 >= k, and + // hence, x >= sqrt(k) and y = ceil(k / x) - 1. + const int x = ceil(sqrt(k)); + const int y = (k - 1) / x + 1 - 1; // ceil(k / x) - 1 + return x - 1 + y; + } +}; diff --git a/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.java b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.java new file mode 100644 index 00000000000..d0df8ce6402 --- /dev/null +++ b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.java @@ -0,0 +1,14 @@ +class Solution { + public int minOperations(int k) { + // The required operations are + // 1. Increase `1` to `x` + // 2. Duplicate `x`, `y` times, to `sum` s.t. x * (1 + y) >= k. + // The number of operations used would be (x - 1) + y. Equivalently, the + // problem can be rephrased as finding min(x - 1 + y) s.t. x * (1 + y) >= k. + // Optimally, `x` should equal to `1 + y`, implying that x^2 >= k, and + // hence, x >= sqrt(k) and y = ceil(k / x) - 1. + final int x = (int) Math.ceil(Math.sqrt(k)); + final int y = (k - 1) / x + 1 - 1; // ceil(k / x) - 1 + return x - 1 + y; + } +} diff --git a/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.py b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.py new file mode 100644 index 00000000000..44c8f0d3d89 --- /dev/null +++ b/solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.py @@ -0,0 +1,12 @@ +class Solution: + def minOperations(self, k: int) -> int: + # The required operations are + # 1. Increase `1` to `x` + # 2. Duplicate `x`, `y` times, to `sum` s.t. x * (1 + y) >= k. + # The number of operations used would be (x - 1) + y. Equivalently, the + # problem can be rephrased as finding min(x - 1 + y) s.t. x * (1 + y) >= k. + # Optimally, `x` should equal to `1 + y`, implying that x^2 >= k, and + # hence, x >= sqrt(k) and y = ceil(k / x) - 1. + x = math.ceil(math.sqrt(k)) + y = (k - 1) // x + 1 - 1 # ceil(k / x) - 1 + return x - 1 + y diff --git a/solutions/3092. Most Frequent IDs/3092.cpp b/solutions/3092. Most Frequent IDs/3092.cpp new file mode 100644 index 00000000000..bac0de0732b --- /dev/null +++ b/solutions/3092. Most Frequent IDs/3092.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector mostFrequentIDs(vector& nums, vector& freq) { + vector ans; + unordered_map numCount; // {num: freq} + map freqCount; // {num's freq: freq} + + for (int i = 0; i < nums.size(); ++i) { + const int num = nums[i]; + const int f = freq[i]; + if (const auto it = numCount.find(num); it != numCount.cend()) { + const int numFreq = it->second; + if (--freqCount[numFreq] == 0) + freqCount.erase(numFreq); + } + const long newFreq = numCount[num] + f; + if (newFreq == 0) { + numCount.erase(num); + } else { + numCount[num] = newFreq; + ++freqCount[newFreq]; + } + ans.push_back(freqCount.empty() ? 0 : freqCount.rbegin()->first); + } + + return ans; + } +}; diff --git a/solutions/3092. Most Frequent IDs/3092.java b/solutions/3092. Most Frequent IDs/3092.java new file mode 100644 index 00000000000..b32e99489b6 --- /dev/null +++ b/solutions/3092. Most Frequent IDs/3092.java @@ -0,0 +1,27 @@ +class Solution { + public long[] mostFrequentIDs(int[] nums, int[] freq) { + long[] ans = new long[nums.length]; + Map numCount = new HashMap<>(); // {num: freq} + TreeMap freqCount = new TreeMap<>(); // {num's freq: freq} + + for (int i = 0; i < nums.length; ++i) { + final int num = nums[i]; + final int f = freq[i]; + if (numCount.containsKey(num)) { + final long numFreq = numCount.get(num); + if (freqCount.merge(numFreq, -1, Integer::sum) == 0) + freqCount.remove(numFreq); + } + final long newFreq = numCount.getOrDefault(num, 0L) + f; + if (newFreq == 0) { + numCount.remove(num); + } else { + numCount.put(num, newFreq); + freqCount.merge(newFreq, 1, Integer::sum); + } + ans[i] = freqCount.isEmpty() ? 0 : freqCount.lastKey(); + } + + return ans; + } +} diff --git a/solutions/3092. Most Frequent IDs/3092.py b/solutions/3092. Most Frequent IDs/3092.py new file mode 100644 index 00000000000..220e6c4b396 --- /dev/null +++ b/solutions/3092. Most Frequent IDs/3092.py @@ -0,0 +1,24 @@ +from sortedcontainers import SortedDict + + +class Solution: + def mostFrequentIDs(self, nums: List[int], freq: List[int]) -> List[int]: + ans = [] + numCount = collections.Counter() # {num: freq} + freqCount = SortedDict() # {num's freq: freq} + + for num, f in zip(nums, freq): + if numCount[num] > 0: + numFreq = numCount[num] + freqCount[numFreq] -= 1 + if freqCount[numFreq] == 0: + del freqCount[numFreq] + newFreq = numCount[num] + f + if newFreq == 0: + del numCount[num] + else: + numCount[num] = newFreq + freqCount[newFreq] = freqCount.get(newFreq, 0) + 1 + ans.append(freqCount.peekitem(-1)[0] if freqCount else 0) + + return ans diff --git a/solutions/3093. Longest Common Suffix Queries/3093.cpp b/solutions/3093. Longest Common Suffix Queries/3093.cpp new file mode 100644 index 00000000000..9002df81f27 --- /dev/null +++ b/solutions/3093. Longest Common Suffix Queries/3093.cpp @@ -0,0 +1,56 @@ +struct TrieNode { + vector> children; + TrieNode() : children(26) {} + int length = INT_MAX; + int index = -1; +}; + +class Solution { + public: + vector stringIndices(vector& wordsContainer, + vector& wordsQuery) { + vector ans; + int minIndex = 0; + + for (int i = 0; i < wordsContainer.size(); ++i) { + insert(wordsContainer[i], i); + if (wordsContainer[i].length() < wordsContainer[minIndex].length()) + minIndex = i; + } + + for (const string& query : wordsQuery) { + const int index = search(query); + ans.push_back(index == -1 ? minIndex : index); + } + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word, int index) { + shared_ptr node = root; + for (int i = word.length() - 1; i >= 0; --i) { + const int j = word[i] - 'a'; + if (node->children[j] == nullptr) + node->children[j] = make_shared(); + node = node->children[j]; + if (node->length > word.length()) { + node->length = word.length(); + node->index = index; + } + } + } + + int search(const string& word) { + shared_ptr node = root; + for (int i = word.length() - 1; i >= 0; --i) { + const int j = word[i] - 'a'; + if (node->children[j] == nullptr) + return node->index; + node = node->children[j]; + } + return node->index; + } +}; diff --git a/solutions/3093. Longest Common Suffix Queries/3093.java b/solutions/3093. Longest Common Suffix Queries/3093.java new file mode 100644 index 00000000000..e2998eb8051 --- /dev/null +++ b/solutions/3093. Longest Common Suffix Queries/3093.java @@ -0,0 +1,53 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; + public int length = Integer.MAX_VALUE; + public int index = -1; +} + +class Solution { + public int[] stringIndices(String[] wordsContainer, String[] wordsQuery) { + int[] ans = new int[wordsQuery.length]; + int minIndex = 0; + + for (int i = 0; i < wordsContainer.length; ++i) { + insert(wordsContainer[i], i); + if (wordsContainer[i].length() < wordsContainer[minIndex].length()) + minIndex = i; + } + + for (int i = 0; i < wordsQuery.length; ++i) { + final int index = search(wordsQuery[i]); + ans[i] = index == -1 ? minIndex : index; + } + + return ans; + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word, int index) { + TrieNode node = root; + for (int i = word.length() - 1; i >= 0; --i) { + final int j = word.charAt(i) - 'a'; + if (node.children[j] == null) + node.children[j] = new TrieNode(); + node = node.children[j]; + if (node.length > word.length()) { + node.length = word.length(); + node.index = index; + } + } + } + + private int search(final String word) { + TrieNode node = root; + for (int i = word.length() - 1; i >= 0; --i) { + final int j = word.charAt(i) - 'a'; + if (node.children[j] == null) + return node.index; + node = node.children[j]; + } + return node.index; + } +} diff --git a/solutions/3093. Longest Common Suffix Queries/3093.py b/solutions/3093. Longest Common Suffix Queries/3093.py new file mode 100644 index 00000000000..e42d980093d --- /dev/null +++ b/solutions/3093. Longest Common Suffix Queries/3093.py @@ -0,0 +1,38 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.isWord = False + self.length = math.inf + self.index = -1 + + +class Solution: + def stringIndices(self, wordsContainer: List[str], wordsQuery: List[str]) -> List[int]: + ans = [] + root = TrieNode() + minIndex = min(enumerate(wordsContainer), key=lambda x: len(x[1]))[0] + + def insert(word: str, index: int) -> None: + node = root + for c in reversed(word): + node = node.children.setdefault(c, TrieNode()) + if node.length > len(word): + node.length = len(word) + node.index = index + + def search(word: str) -> int: + node = root + for c in reversed(word): + if c not in node.children: + return node.index + node = node.children[c] + return node.index + + for i, word in enumerate(wordsContainer): + insert(word, i) + + for query in wordsQuery: + index = search(query) + ans.append(minIndex if index == -1 else index) + + return ans diff --git a/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.cpp b/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.cpp new file mode 100644 index 00000000000..04d65317601 --- /dev/null +++ b/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.cpp @@ -0,0 +1,18 @@ +/** + * Definition of commonBits API. + * int commonBits(int num); + */ + +class Solution { + public: + int findNumber() { + constexpr int kMaxBit = 30; + int ans = 0; + + for (int i = 0; i <= kMaxBit; ++i) + if (commonBits(1 << i) > commonBits(1 << i)) + ans |= 1 << i; + + return ans; + } +}; diff --git a/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.java b/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.java new file mode 100644 index 00000000000..3cc0b9ee6f8 --- /dev/null +++ b/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.java @@ -0,0 +1,17 @@ +/** + * Definition of commonBits API (defined in the parent class Problem). + * int commonBits(int num); + */ + +public class Solution extends Problem { + public int findNumber() { + final int kMaxBit = 30; + int ans = 0; + + for (int i = 0; i <= kMaxBit; ++i) + if (commonBits(1 << i) > commonBits(1 << i)) + ans |= 1 << i; + + return ans; + } +} diff --git a/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.py b/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.py new file mode 100644 index 00000000000..de22daceb82 --- /dev/null +++ b/solutions/3094. Guess the Number Using Bitwise Questions II/3094-2.py @@ -0,0 +1,8 @@ +# Definition of commonBits API. +# def commonBits(num: int) -> int: + +class Solution: + def findNumber(self) -> int: + return functools.reduce(lambda x, i: x | (1 << i) + if commonBits(1 << i) > commonBits(1 << i) + else x, range(31), 0) diff --git a/solutions/3094. Guess the Number Using Bitwise Questions II/3094.cpp b/solutions/3094. Guess the Number Using Bitwise Questions II/3094.cpp new file mode 100644 index 00000000000..1d348bad0c2 --- /dev/null +++ b/solutions/3094. Guess the Number Using Bitwise Questions II/3094.cpp @@ -0,0 +1,21 @@ +/** + * Definition of commonBits API. + * int commonBits(int num); + */ + +class Solution { + public: + int findNumber() { + constexpr int kMaxBit = 30; + const int sameCount = commonBits(0); + int ans = 0; + + for (int i = 0; i <= kMaxBit; ++i) { + if (commonBits(1 << i) > sameCount) + ans |= 1 << i; + commonBits(1 << i); // Revert the XOR. + } + + return ans; + } +}; diff --git a/solutions/3094. Guess the Number Using Bitwise Questions II/3094.java b/solutions/3094. Guess the Number Using Bitwise Questions II/3094.java new file mode 100644 index 00000000000..65c48c6a6c2 --- /dev/null +++ b/solutions/3094. Guess the Number Using Bitwise Questions II/3094.java @@ -0,0 +1,20 @@ +/** + * Definition of commonBits API (defined in the parent class Problem). + * int commonBits(int num); + */ + +public class Solution extends Problem { + public int findNumber() { + final int kMaxBit = 30; + final int sameCount = commonBits(0); + int ans = 0; + + for (int i = 0; i <= kMaxBit; ++i) { + if (commonBits(1 << i) > sameCount) + ans |= 1 << i; + commonBits(1 << i); // Revert the XOR. + } + + return ans; + } +} diff --git a/solutions/3094. Guess the Number Using Bitwise Questions II/3094.py b/solutions/3094. Guess the Number Using Bitwise Questions II/3094.py new file mode 100644 index 00000000000..d54d7c5fc22 --- /dev/null +++ b/solutions/3094. Guess the Number Using Bitwise Questions II/3094.py @@ -0,0 +1,14 @@ +# Definition of commonBits API. +# def commonBits(num: int) -> int: + +class Solution: + def findNumber(self) -> int: + ans = 0 + sameCount = commonBits(0) + + for i in range(31): + if commonBits(1 << i) > sameCount: + ans |= 1 << i + commonBits(1 << i) # Revert the XOR. + + return ans diff --git a/solutions/3095. Shortest Subarray With OR at Least K I/3095.cpp b/solutions/3095. Shortest Subarray With OR at Least K I/3095.cpp new file mode 100644 index 00000000000..b6054701e08 --- /dev/null +++ b/solutions/3095. Shortest Subarray With OR at Least K I/3095.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int minimumSubarrayLength(vector& nums, int k) { + constexpr int kMax = 50; + const int n = nums.size(); + int ans = n + 1; + int ors = 0; + vector count(kMax + 1); + + for (int l = 0, r = 0; r < n; r++) { + ors = orNum(ors, nums[r], count); + while (ors >= k && l <= r) { + ans = min(ans, r - l + 1); + ors = undoOrNum(ors, nums[l], count); + ++l; + } + } + + return (ans == n + 1) ? -1 : ans; + } + + private: + static constexpr int kMaxBit = 30; + + int orNum(int ors, int num, vector& count) { + for (int i = 0; i < kMaxBit; ++i) + if (num >> i & 1 && ++count[i] == 1) + ors += 1 << i; + return ors; + } + + int undoOrNum(int ors, int num, vector& count) { + for (int i = 0; i < kMaxBit; ++i) + if (num >> i & 1 && --count[i] == 0) + ors -= 1 << i; + return ors; + } +}; diff --git a/solutions/3095. Shortest Subarray With OR at Least K I/3095.java b/solutions/3095. Shortest Subarray With OR at Least K I/3095.java new file mode 100644 index 00000000000..660fd8afe69 --- /dev/null +++ b/solutions/3095. Shortest Subarray With OR at Least K I/3095.java @@ -0,0 +1,36 @@ +class Solution { + public int minimumSubarrayLength(int[] nums, int k) { + final int kMax = 50; + final int n = nums.length; + int ans = n + 1; + int ors = 0; + int[] count = new int[kMax + 1]; + + for (int l = 0, r = 0; r < n; ++r) { + ors = orNum(ors, nums[r], count); + while (ors >= k && l <= r) { + ans = Math.min(ans, r - l + 1); + ors = undoOrNum(ors, nums[l], count); + ++l; + } + } + + return (ans == n + 1) ? -1 : ans; + } + + private static final int kMaxBit = 30; + + private int orNum(int ors, int num, int[] count) { + for (int i = 0; i < kMaxBit; ++i) + if ((num >> i & 1) == 1 && ++count[i] == 1) + ors += 1 << i; + return ors; + } + + private int undoOrNum(int ors, int num, int[] count) { + for (int i = 0; i < kMaxBit; ++i) + if ((num >> i & 1) == 1 && --count[i] == 0) + ors -= 1 << i; + return ors; + } +} diff --git a/solutions/3095. Shortest Subarray With OR at Least K I/3095.py b/solutions/3095. Shortest Subarray With OR at Least K I/3095.py new file mode 100644 index 00000000000..96a740f1a5d --- /dev/null +++ b/solutions/3095. Shortest Subarray With OR at Least K I/3095.py @@ -0,0 +1,31 @@ +class Solution: + def minimumSubarrayLength(self, nums: List[int], k: int) -> int: + ans = len(nums) + 1 + ors = 0 + count = collections.Counter() + + l = 0 + for r, num in enumerate(nums): + ors = self._orNum(ors, num, count) + while ors >= k and l <= r: + ans = min(ans, r - l + 1) + ors = self._undoOrNum(ors, nums[l], count) + l += 1 + + return -1 if ans == len(nums) + 1 else ans + + def _orNum(self, ors: int, num: int, count: Dict[int, int]) -> int: + for i in range(30): + if num >> i & 1: + count[i] += 1 + if count[i] == 1: + ors += 1 << i + return ors + + def _undoOrNum(self, ors: int, num: int, count: Dict[int, int]) -> int: + for i in range(30): + if num >> i & 1: + count[i] -= 1 + if count[i] == 0: + ors -= 1 << i + return ors diff --git a/solutions/3096. Minimum Levels to Gain More Points/3096.cpp b/solutions/3096. Minimum Levels to Gain More Points/3096.cpp new file mode 100644 index 00000000000..231f548aa7c --- /dev/null +++ b/solutions/3096. Minimum Levels to Gain More Points/3096.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minimumLevels(vector& possible) { + const int n = possible.size(); + const vector nums = getNums(possible); + vector prefix(n + 1); + + partial_sum(nums.begin(), nums.end(), prefix.begin() + 1); + + for (int i = 1; i < n; ++i) + if (prefix[i] > prefix[n] - prefix[i]) + return i; + + return -1; + } + + private: + vector getNums(const vector& possible) { + vector nums; + for (const int num : possible) + nums.push_back(num == 1 ? 1 : -1); + return nums; + } +}; diff --git a/solutions/3096. Minimum Levels to Gain More Points/3096.java b/solutions/3096. Minimum Levels to Gain More Points/3096.java new file mode 100644 index 00000000000..5b991c515a0 --- /dev/null +++ b/solutions/3096. Minimum Levels to Gain More Points/3096.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumLevels(int[] possible) { + final int n = possible.length; + final int[] nums = getNums(possible); + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; ++i) + prefix[i + 1] = prefix[i] + nums[i]; + + for (int i = 1; i < n; ++i) + if (prefix[i] > prefix[n] - prefix[i]) + return i; + + return -1; + } + + private int[] getNums(int[] possible) { + int[] nums = new int[possible.length]; + for (int i = 0; i < possible.length; ++i) + nums[i] = possible[i] == 0 ? -1 : 1; + return nums; + } +} diff --git a/solutions/3096. Minimum Levels to Gain More Points/3096.py b/solutions/3096. Minimum Levels to Gain More Points/3096.py new file mode 100644 index 00000000000..3fd9e98fcda --- /dev/null +++ b/solutions/3096. Minimum Levels to Gain More Points/3096.py @@ -0,0 +1,11 @@ +class Solution: + def minimumLevels(self, possible: List[int]) -> int: + n = len(possible) + nums = [num if num == 1 else -1 for num in possible] + prefix = list(itertools.accumulate(nums, initial=0)) + + for i in range(1, n): + if prefix[i] > prefix[n] - prefix[i]: + return i + + return -1 diff --git a/solutions/3097. Shortest Subarray With OR at Least K II/3097.cpp b/solutions/3097. Shortest Subarray With OR at Least K II/3097.cpp new file mode 100644 index 00000000000..48cc6485f94 --- /dev/null +++ b/solutions/3097. Shortest Subarray With OR at Least K II/3097.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + // Same as 3095. Shortest Subarray With OR at Least K I + int minimumSubarrayLength(vector& nums, int k) { + constexpr int kMax = 50; + const int n = nums.size(); + int ans = n + 1; + int ors = 0; + vector count(kMax + 1); + + for (int l = 0, r = 0; r < n; r++) { + ors = orNum(ors, nums[r], count); + while (ors >= k && l <= r) { + ans = min(ans, r - l + 1); + ors = undoOrNum(ors, nums[l], count); + ++l; + } + } + + return (ans == n + 1) ? -1 : ans; + } + + private: + static constexpr int kMaxBit = 30; + + int orNum(int ors, int num, vector& count) { + for (int i = 0; i < kMaxBit; ++i) + if (num >> i & 1 && ++count[i] == 1) + ors += 1 << i; + return ors; + } + + int undoOrNum(int ors, int num, vector& count) { + for (int i = 0; i < kMaxBit; ++i) + if (num >> i & 1 && --count[i] == 0) + ors -= 1 << i; + return ors; + } +}; diff --git a/solutions/3097. Shortest Subarray With OR at Least K II/3097.java b/solutions/3097. Shortest Subarray With OR at Least K II/3097.java new file mode 100644 index 00000000000..6f79b999a29 --- /dev/null +++ b/solutions/3097. Shortest Subarray With OR at Least K II/3097.java @@ -0,0 +1,37 @@ +class Solution { + // Same as 3095. Shortest Subarray With OR at Least K I + public int minimumSubarrayLength(int[] nums, int k) { + final int kMax = 50; + final int n = nums.length; + int ans = n + 1; + int ors = 0; + int[] count = new int[kMax + 1]; + + for (int l = 0, r = 0; r < n; ++r) { + ors = orNum(ors, nums[r], count); + while (ors >= k && l <= r) { + ans = Math.min(ans, r - l + 1); + ors = undoOrNum(ors, nums[l], count); + ++l; + } + } + + return (ans == n + 1) ? -1 : ans; + } + + private static final int kMaxBit = 30; + + private int orNum(int ors, int num, int[] count) { + for (int i = 0; i < kMaxBit; ++i) + if ((num >> i & 1) == 1 && ++count[i] == 1) + ors += 1 << i; + return ors; + } + + private int undoOrNum(int ors, int num, int[] count) { + for (int i = 0; i < kMaxBit; ++i) + if ((num >> i & 1) == 1 && --count[i] == 0) + ors -= 1 << i; + return ors; + } +} diff --git a/solutions/3097. Shortest Subarray With OR at Least K II/3097.py b/solutions/3097. Shortest Subarray With OR at Least K II/3097.py new file mode 100644 index 00000000000..b73376cca3f --- /dev/null +++ b/solutions/3097. Shortest Subarray With OR at Least K II/3097.py @@ -0,0 +1,32 @@ +class Solution: + # Same as 3095. Shortest Subarray With OR at Least K I + def minimumSubarrayLength(self, nums: List[int], k: int) -> int: + ans = len(nums) + 1 + ors = 0 + count = collections.Counter() + + l = 0 + for r, num in enumerate(nums): + ors = self._orNum(ors, num, count) + while ors >= k and l <= r: + ans = min(ans, r - l + 1) + ors = self._undoOrNum(ors, nums[l], count) + l += 1 + + return -1 if ans == len(nums) + 1 else ans + + def _orNum(self, ors: int, num: int, count: Dict[int, int]) -> int: + for i in range(30): + if num >> i & 1: + count[i] += 1 + if count[i] == 1: + ors += 1 << i + return ors + + def _undoOrNum(self, ors: int, num: int, count: Dict[int, int]) -> int: + for i in range(30): + if num >> i & 1: + count[i] -= 1 + if count[i] == 0: + ors -= 1 << i + return ors diff --git a/solutions/3098. Find the Sum of Subsequence Powers/3098-2.py b/solutions/3098. Find the Sum of Subsequence Powers/3098-2.py new file mode 100644 index 00000000000..cf547a69409 --- /dev/null +++ b/solutions/3098. Find the Sum of Subsequence Powers/3098-2.py @@ -0,0 +1,20 @@ +class Solution: + def sumOfPowers(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + n = len(nums) + + nums.sort() + + @functools.lru_cache(None) + def dp(i: int, k: int, lastPickIndex: int, minDiff: int) -> int: + if k == 0: + return minDiff + if i == n: + return 0 + newMinDiff = minDiff if lastPickIndex == - 1 \ + else min(minDiff, nums[i] - nums[lastPickIndex]) + pick = dp(i + 1, k - 1, i, newMinDiff) + skip = dp(i + 1, k, lastPickIndex, minDiff) + return (pick + skip) % kMod + + return dp(0, k, -1, math.inf) diff --git a/solutions/3098. Find the Sum of Subsequence Powers/3098.cpp b/solutions/3098. Find the Sum of Subsequence Powers/3098.cpp new file mode 100644 index 00000000000..ca59b16bddf --- /dev/null +++ b/solutions/3098. Find the Sum of Subsequence Powers/3098.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int sumOfPowers(vector& nums, int k) { + const int n = nums.size(); + ranges::sort(nums); + vector>>> mem( + n + 1, vector>>( + n + 1, vector>(n + 1, vector(k + 1, -1)))); + return sumOfPowers(nums, 0, k, -1, -1, -1, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the sum of powers of all subsequences of nums[i..n) which + // have length equal to k, where `lastPickedIndex` is the index of the last + // picked number and nums[secondIndex] - nums[firstIndex] is the minimum power + // so far. + int sumOfPowers(const vector& nums, int i, int k, int lastPickedIndex, + int firstIndex, int secondIndex, + vector>>>& mem) { + if (k == 0) + return nums[secondIndex] - nums[firstIndex]; + if (i == nums.size()) + return 0; + const int a = hash(lastPickedIndex); + const int b = hash(firstIndex); + const int c = hash(secondIndex); + if (mem[a][b][c][k] != -1) + return mem[a][b][c][k]; + int newFirstIndex = firstIndex; + int newSecondIndex = secondIndex; + if (firstIndex == -1) { + newFirstIndex = i; + } else if (secondIndex == -1) { + newSecondIndex = i; + } else if (nums[i] - nums[lastPickedIndex] < + nums[secondIndex] - nums[firstIndex]) { + newFirstIndex = lastPickedIndex; + newSecondIndex = i; + } + const int pick = + sumOfPowers(nums, i + 1, k - 1, i, newFirstIndex, newSecondIndex, mem); + const int skip = sumOfPowers(nums, i + 1, k, lastPickedIndex, firstIndex, + secondIndex, mem); + return mem[a][b][c][k] = (pick + skip) % kMod; + } + + constexpr int hash(int x) { + return x + 1; + } +}; diff --git a/solutions/3098. Find the Sum of Subsequence Powers/3098.java b/solutions/3098. Find the Sum of Subsequence Powers/3098.java new file mode 100644 index 00000000000..5857bc56d9d --- /dev/null +++ b/solutions/3098. Find the Sum of Subsequence Powers/3098.java @@ -0,0 +1,44 @@ +class Solution { + public int sumOfPowers(int[] nums, int k) { + final int n = nums.length; + Arrays.sort(nums); + Integer[][][][] mem = new Integer[n + 1][n + 1][n + 1][k + 1]; + return sumOfPowers(nums, 0, k, -1, -1, -1, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the sum of powers of all subsequences of nums[i..n) which + // have length equal to k, where `lastPickedIndex` is the index of the last + // picked number and nums[secondIndex] - nums[firstIndex] is the minimum power + // so far. + private int sumOfPowers(int[] nums, int i, int k, int lastPickedIndex, int firstIndex, + int secondIndex, Integer[][][][] mem) { + if (k == 0) + return nums[secondIndex] - nums[firstIndex]; + if (i == nums.length) + return 0; + final int a = hash(lastPickedIndex); + final int b = hash(firstIndex); + final int c = hash(secondIndex); + if (mem[a][b][c][k] != null) + return mem[a][b][c][k]; + int newFirstIndex = firstIndex; + int newSecondIndex = secondIndex; + if (firstIndex == -1) { + newFirstIndex = i; + } else if (secondIndex == -1) { + newSecondIndex = i; + } else if (nums[i] - nums[lastPickedIndex] < nums[secondIndex] - nums[firstIndex]) { + newFirstIndex = lastPickedIndex; + newSecondIndex = i; + } + final int pick = sumOfPowers(nums, i + 1, k - 1, i, newFirstIndex, newSecondIndex, mem); + final int skip = sumOfPowers(nums, i + 1, k, lastPickedIndex, firstIndex, secondIndex, mem); + return mem[a][b][c][k] = (pick + skip) % kMod; + } + + private int hash(int x) { + return x + 1; + } +} diff --git a/solutions/3098. Find the Sum of Subsequence Powers/3098.py b/solutions/3098. Find the Sum of Subsequence Powers/3098.py new file mode 100644 index 00000000000..20d60216cf4 --- /dev/null +++ b/solutions/3098. Find the Sum of Subsequence Powers/3098.py @@ -0,0 +1,25 @@ +class Solution: + def sumOfPowers(self, nums: List[int], k: int) -> int: + kMod = 1_000_000_007 + nums.sort() + + @functools.lru_cache(None) + def dp(i: int, k: int, lastPickedIndex: int, firstIndex: int, secondIndex: int) -> int: + if k == 0: + return nums[secondIndex] - nums[firstIndex] + if i == len(nums): + return 0 + newFirstIndex = firstIndex + newSecondIndex = secondIndex + if firstIndex == -1: + newFirstIndex = i + elif secondIndex == -1: + newSecondIndex = i + elif nums[i] - nums[lastPickedIndex] < nums[secondIndex] - nums[firstIndex]: + newFirstIndex = lastPickedIndex + newSecondIndex = i + pick = dp(i + 1, k - 1, i, newFirstIndex, newSecondIndex) + skip = dp(i + 1, k, lastPickedIndex, firstIndex, secondIndex) + return (pick + skip) % kMod + + return dp(0, k, -1, -1, -1) diff --git a/solutions/3099. Harshad Number/3099.cpp b/solutions/3099. Harshad Number/3099.cpp new file mode 100644 index 00000000000..bec2fd54052 --- /dev/null +++ b/solutions/3099. Harshad Number/3099.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int sumOfTheDigitsOfHarshadNumber(int x) { + const int digitSum = getDigitSum(x); + return x % digitSum == 0 ? digitSum : -1; + } + + private: + int getDigitSum(int x) { + int digitSum = 0; + while (x > 0) { + digitSum += x % 10; + x /= 10; + } + return digitSum; + } +}; diff --git a/solutions/3099. Harshad Number/3099.java b/solutions/3099. Harshad Number/3099.java new file mode 100644 index 00000000000..aefd0c2cd01 --- /dev/null +++ b/solutions/3099. Harshad Number/3099.java @@ -0,0 +1,15 @@ +class Solution { + public int sumOfTheDigitsOfHarshadNumber(int x) { + final int digitSum = getDigitSum(x); + return x % digitSum == 0 ? digitSum : -1; + } + + private int getDigitSum(int x) { + int digitSum = 0; + while (x > 0) { + digitSum += x % 10; + x /= 10; + } + return digitSum; + } +} diff --git a/solutions/3099. Harshad Number/3099.py b/solutions/3099. Harshad Number/3099.py new file mode 100644 index 00000000000..bdfbf45f02f --- /dev/null +++ b/solutions/3099. Harshad Number/3099.py @@ -0,0 +1,7 @@ +class Solution: + def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int: + digitSum = self._getDigitSum(x) + return digitSum if x % digitSum == 0 else -1 + + def _getDigitSum(self, num: int) -> int: + return sum(int(digit) for digit in str(num)) diff --git a/solutions/31. Next Permutation/31.cpp b/solutions/31. Next Permutation/31.cpp new file mode 100644 index 00000000000..130cd49437a --- /dev/null +++ b/solutions/31. Next Permutation/31.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + void nextPermutation(vector& nums) { + const int n = nums.size(); + + // From back to front, find the first number < nums[i + 1]. + int i; + for (i = n - 2; i >= 0; --i) + if (nums[i] < nums[i + 1]) + break; + + // From back to front, find the first number > nums[i], swap it with + // nums[i]. + if (i >= 0) + for (int j = n - 1; j > i; --j) + if (nums[j] > nums[i]) { + swap(nums[i], nums[j]); + break; + } + + // Reverse nums[i + 1..n - 1]. + reverse(nums, i + 1, n - 1); + } + + private: + void reverse(vector& nums, int l, int r) { + while (l < r) + swap(nums[l++], nums[r--]); + } +}; diff --git a/solutions/31. Next Permutation/31.java b/solutions/31. Next Permutation/31.java new file mode 100644 index 00000000000..ed2b366ce6e --- /dev/null +++ b/solutions/31. Next Permutation/31.java @@ -0,0 +1,34 @@ +class Solution { + public void nextPermutation(int[] nums) { + final int n = nums.length; + + // From back to front, find the first number < nums[i + 1]. + int i; + for (i = n - 2; i >= 0; --i) + if (nums[i] < nums[i + 1]) + break; + + // From back to front, find the first number > nums[i], swap it with + // nums[i]. + if (i >= 0) + for (int j = n - 1; j > i; --j) + if (nums[j] > nums[i]) { + swap(nums, i, j); + break; + } + + // Reverse nums[i + 1..n - 1]. + reverse(nums, i + 1, n - 1); + } + + private void reverse(int[] nums, int l, int r) { + while (l < r) + swap(nums, l++, r--); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/31. Next Permutation/31.py b/solutions/31. Next Permutation/31.py new file mode 100644 index 00000000000..b372fd25b82 --- /dev/null +++ b/solutions/31. Next Permutation/31.py @@ -0,0 +1,26 @@ +class Solution: + def nextPermutation(self, nums: List[int]) -> None: + n = len(nums) + + # From back to front, find the first number < nums[i + 1]. + i = n - 2 + while i >= 0: + if nums[i] < nums[i + 1]: + break + i -= 1 + + # From back to front, find the first number > nums[i], swap it with nums[i]. + if i >= 0: + for j in range(n - 1, i, -1): + if nums[j] > nums[i]: + nums[i], nums[j] = nums[j], nums[i] + break + + def reverse(nums: List[int], l: int, r: int) -> None: + while l < r: + nums[l], nums[r] = nums[r], nums[l] + l += 1 + r -= 1 + + # Reverse nums[i + 1..n - 1]. + reverse(nums, i + 1, len(nums) - 1) diff --git a/solutions/310. Minimum Height Trees/310.cpp b/solutions/310. Minimum Height Trees/310.cpp new file mode 100644 index 00000000000..3ef6c121bdb --- /dev/null +++ b/solutions/310. Minimum Height Trees/310.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector findMinHeightTrees(int n, vector>& edges) { + if (n == 1 || edges.empty()) + return {0}; + + vector ans; + unordered_map> graph; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].insert(v); + graph[v].insert(u); + } + + for (const auto& [label, children] : graph) + if (children.size() == 1) + ans.push_back(label); + + while (n > 2) { + n -= ans.size(); + vector nextLeaves; + for (const int leaf : ans) { + const int u = *graph[leaf].begin(); + graph[u].erase(leaf); + if (graph[u].size() == 1) + nextLeaves.push_back(u); + } + ans = nextLeaves; + } + + return ans; + } +}; diff --git a/solutions/310. Minimum Height Trees/310.java b/solutions/310. Minimum Height Trees/310.java new file mode 100644 index 00000000000..f5dde02d4ad --- /dev/null +++ b/solutions/310. Minimum Height Trees/310.java @@ -0,0 +1,40 @@ +class Solution { + public List findMinHeightTrees(int n, int[][] edges) { + if (n == 0 || edges.length == 0) + return new ArrayList<>(Arrays.asList(0)); + + List ans = new ArrayList<>(); + Map> graph = new HashMap<>(); + + for (int i = 0; i < n; ++i) + graph.put(i, new HashSet<>()); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph.get(u).add(v); + graph.get(v).add(u); + } + + for (Map.Entry> entry : graph.entrySet()) { + final int label = entry.getKey(); + Set children = entry.getValue(); + if (children.size() == 1) + ans.add(label); + } + + while (n > 2) { + n -= ans.size(); + List nextLeaves = new ArrayList<>(); + for (final int leaf : ans) { + final int u = (int) graph.get(leaf).iterator().next(); + graph.get(u).remove(leaf); + if (graph.get(u).size() == 1) + nextLeaves.add(u); + } + ans = nextLeaves; + } + + return ans; + } +} diff --git a/solutions/310. Minimum Height Trees/310.py b/solutions/310. Minimum Height Trees/310.py new file mode 100644 index 00000000000..c21f85c4b4e --- /dev/null +++ b/solutions/310. Minimum Height Trees/310.py @@ -0,0 +1,27 @@ +class Solution: + def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: + if n == 1 or not edges: + return [0] + + ans = [] + graph = collections.defaultdict(set) + + for u, v in edges: + graph[u].add(v) + graph[v].add(u) + + for label, children in graph.items(): + if len(children) == 1: + ans.append(label) + + while n > 2: + n -= len(ans) + nextLeaves = [] + for leaf in ans: + u = next(iter(graph[leaf])) + graph[u].remove(leaf) + if len(graph[u]) == 1: + nextLeaves.append(u) + ans = nextLeaves + + return ans diff --git a/solutions/3100. Water Bottles II/3100.cpp b/solutions/3100. Water Bottles II/3100.cpp new file mode 100644 index 00000000000..63cb6c28efc --- /dev/null +++ b/solutions/3100. Water Bottles II/3100.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxBottlesDrunk(int numBottles, int numExchange) { + int ans = numBottles; + + while (numBottles >= numExchange) { + numBottles = (numBottles - numExchange + 1); + ++numExchange; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/3100. Water Bottles II/3100.java b/solutions/3100. Water Bottles II/3100.java new file mode 100644 index 00000000000..f829010db49 --- /dev/null +++ b/solutions/3100. Water Bottles II/3100.java @@ -0,0 +1,13 @@ +class Solution { + public int maxBottlesDrunk(int numBottles, int numExchange) { + int ans = numBottles; + + while (numBottles >= numExchange) { + numBottles = (numBottles - numExchange + 1); + ++numExchange; + ++ans; + } + + return ans; + } +} diff --git a/solutions/3100. Water Bottles II/3100.py b/solutions/3100. Water Bottles II/3100.py new file mode 100644 index 00000000000..baec0ee07f2 --- /dev/null +++ b/solutions/3100. Water Bottles II/3100.py @@ -0,0 +1,10 @@ +class Solution: + def maxBottlesDrunk(self, numBottles: int, numExchange: int) -> int: + ans = numBottles + + while numBottles >= numExchange: + numBottles = numBottles - numExchange + 1 + numExchange += 1 + ans += 1 + + return ans diff --git a/solutions/3101. Count Alternating Subarrays/3101.cpp b/solutions/3101. Count Alternating Subarrays/3101.cpp new file mode 100644 index 00000000000..283e7f89b55 --- /dev/null +++ b/solutions/3101. Count Alternating Subarrays/3101.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + long long countAlternatingSubarrays(vector& nums) { + // dp[i] := the number of alternating subarrays ending in index i + vector dp(nums.size(), 1); + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] != nums[i - 1]) + dp[i] += dp[i - 1]; + + return accumulate(dp.begin(), dp.end(), 0L); + } +}; diff --git a/solutions/3101. Count Alternating Subarrays/3101.java b/solutions/3101. Count Alternating Subarrays/3101.java new file mode 100644 index 00000000000..cde24c2f8be --- /dev/null +++ b/solutions/3101. Count Alternating Subarrays/3101.java @@ -0,0 +1,13 @@ +class Solution { + public long countAlternatingSubarrays(int[] nums) { + // dp[i] := the number of alternating subarrays ending in index i + long[] dp = new long[nums.length]; + Arrays.fill(dp, 1); + + for (int i = 1; i < nums.length; ++i) + if (nums[i] != nums[i - 1]) + dp[i] += dp[i - 1]; + + return Arrays.stream(dp).sum(); + } +} diff --git a/solutions/3101. Count Alternating Subarrays/3101.py b/solutions/3101. Count Alternating Subarrays/3101.py new file mode 100644 index 00000000000..df33b4f961d --- /dev/null +++ b/solutions/3101. Count Alternating Subarrays/3101.py @@ -0,0 +1,10 @@ +class Solution: + def countAlternatingSubarrays(self, nums: List[int]) -> int: + # dp[i] := the number of alternating subarrays ending in index i + dp = [1] * len(nums) + + for i in range(1, len(nums)): + if nums[i] != nums[i - 1]: + dp[i] += dp[i - 1] + + return sum(dp) diff --git a/solutions/3102. Minimize Manhattan Distances/3102.cpp b/solutions/3102. Minimize Manhattan Distances/3102.cpp new file mode 100644 index 00000000000..b51493a1031 --- /dev/null +++ b/solutions/3102. Minimize Manhattan Distances/3102.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + int minimumDistance(vector>& points) { + const auto [i, j] = maxManhattanDistance(points, -1); + const auto [xi, yi] = maxManhattanDistance(points, i); + const auto [xj, yj] = maxManhattanDistance(points, j); + return min(manhattan(points, xi, yi), manhattan(points, xj, yj)); + } + + private: + // Returns the pair of indices a and b where points[a] and points[b] have the + // maximum Manhattan distance and a != excludedIndex and b != excludedIndex. + pair maxManhattanDistance(const vector>& points, + int excludedIndex) { + int minSum = INT_MAX; + int maxSum = INT_MIN; + int minDiff = INT_MAX; + int maxDiff = INT_MIN; + int minSumIndex = -1; + int maxSumIndex = -1; + int minDiffIndex = -1; + int maxDiffIndex = -1; + + for (int i = 0; i < points.size(); ++i) { + if (i == excludedIndex) + continue; + const int x = points[i][0]; + const int y = points[i][1]; + const int sum = x + y; + const int diff = x - y; + if (sum < minSum) + minSum = sum, minSumIndex = i; + if (sum > maxSum) + maxSum = sum, maxSumIndex = i; + if (diff < minDiff) + minDiff = diff, minDiffIndex = i; + if (diff > maxDiff) + maxDiff = diff, maxDiffIndex = i; + } + + return maxSum - minSum >= maxDiff - minDiff + ? pair(minSumIndex, maxSumIndex) + : pair(minDiffIndex, maxDiffIndex); + } + + int manhattan(const vector>& points, int i, int j) { + return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]); + } +}; diff --git a/solutions/3102. Minimize Manhattan Distances/3102.java b/solutions/3102. Minimize Manhattan Distances/3102.java new file mode 100644 index 00000000000..841b23b6830 --- /dev/null +++ b/solutions/3102. Minimize Manhattan Distances/3102.java @@ -0,0 +1,54 @@ +class Solution { + public int minimumDistance(int[][] points) { + final int[] maxIndices = maxManhattanDistance(points, -1); + final int[] xiyi = maxManhattanDistance(points, maxIndices[0]); + final int[] xjyj = maxManhattanDistance(points, maxIndices[1]); + return Math.min(manhattan(points, xiyi[0], xiyi[1]), // + manhattan(points, xjyj[0], xjyj[1])); + } + + // Returns the pair of indices a and b where points[a] and points[b] have the + // maximum Manhattan distance and a != excludedIndex and b != excludedIndex. + private int[] maxManhattanDistance(int[][] points, int excludedIndex) { + int minSum = Integer.MAX_VALUE; + int maxSum = Integer.MIN_VALUE; + int minDiff = Integer.MAX_VALUE; + int maxDiff = Integer.MIN_VALUE; + int minSumIndex = -1; + int maxSumIndex = -1; + int minDiffIndex = -1; + int maxDiffIndex = -1; + + for (int i = 0; i < points.length; ++i) { + if (i == excludedIndex) + continue; + final int x = points[i][0]; + final int y = points[i][1]; + final int sum = x + y; + final int diff = x - y; + if (sum < minSum) { + minSum = sum; + minSumIndex = i; + } + if (sum > maxSum) { + maxSum = sum; + maxSumIndex = i; + } + if (diff < minDiff) { + minDiff = diff; + minDiffIndex = i; + } + if (diff > maxDiff) { + maxDiff = diff; + maxDiffIndex = i; + } + } + + return maxSum - minSum >= maxDiff - minDiff ? new int[] {minSumIndex, maxSumIndex} + : new int[] {minDiffIndex, maxDiffIndex}; + } + + private int manhattan(int[][] points, int i, int j) { + return Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]); + } +} diff --git a/solutions/3102. Minimize Manhattan Distances/3102.py b/solutions/3102. Minimize Manhattan Distances/3102.py new file mode 100644 index 00000000000..d96c8f61cdb --- /dev/null +++ b/solutions/3102. Minimize Manhattan Distances/3102.py @@ -0,0 +1,41 @@ +class Solution: + def minimumDistance(self, points: List[List[int]]) -> int: + i, j = self._maxManhattanDistance(points, -1) + xi, yi = self._maxManhattanDistance(points, i) + xj, yj = self._maxManhattanDistance(points, j) + return min(self._manhattan(points, xi, yi), + self._manhattan(points, xj, yj)) + + def _maxManhattanDistance(self, points: List[List[int]], excludedIndex: int) -> int: + minSum = math.inf + maxSum = -math.inf + minDiff = math.inf + maxDiff = -math.inf + minSumIndex = -1 + maxSumIndex = -1 + minDiffIndex = -1 + maxDiffIndex = -1 + + for i, (x, y) in enumerate(points): + if i == excludedIndex: + continue + summ = x + y + diff = x - y + if summ < minSum: + minSum = summ + minSumIndex = i + if summ > maxSum: + maxSum = summ + maxSumIndex = i + if diff < minDiff: + minDiff = diff + minDiffIndex = i + if diff > maxDiff: + maxDiff = diff + maxDiffIndex = i + + return [minSumIndex, maxSumIndex] if maxSum - minSum >= maxDiff - minDiff \ + else [minDiffIndex, maxDiffIndex] + + def _manhattan(self, points: List[List[int]], i: int, j: int) -> int: + return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) diff --git a/solutions/3103. Find Trending Hashtags II/3103.sql b/solutions/3103. Find Trending Hashtags II/3103.sql new file mode 100644 index 00000000000..88961da9304 --- /dev/null +++ b/solutions/3103. Find Trending Hashtags II/3103.sql @@ -0,0 +1,24 @@ +WITH + RECURSIVE FebruaryTweets AS ( + SELECT * FROM Tweets + WHERE YEAR(tweet_date) = 2024 AND MONTH(tweet_date) = 2 + ), + HashtagToTweet AS ( + SELECT + REGEXP_SUBSTR(tweet, '#[^\\s]+') AS hashtag, + REGEXP_REPLACE(tweet, '#[^\\s]+', '', 1, 1) AS tweet + FROM FebruaryTweets + UNION ALL + SELECT + REGEXP_SUBSTR(tweet, '#[^\\s]+') AS hashtag, + REGEXP_REPLACE(tweet, '#[^\\s]+', '', 1, 1) AS tweet + FROM HashtagToTweet + WHERE POSITION('#' IN tweet) > 0 + ) +SELECT + hashtag, + COUNT(*) AS count +FROM HashtagToTweet +GROUP BY hashtag +ORDER BY count DESC, hashtag DESC +LIMIT 3; diff --git a/solutions/3104. Find Longest Self-Contained Substring/3104.cpp b/solutions/3104. Find Longest Self-Contained Substring/3104.cpp new file mode 100644 index 00000000000..8a7779665b6 --- /dev/null +++ b/solutions/3104. Find Longest Self-Contained Substring/3104.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int maxSubstringLength(string s) { + int ans = -1; + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + for (int n = 1; n <= 26; ++n) + ans = max(ans, maxSubstringLengthWithNUniqueLetters(s, n, count)); + + return ans; + } + + private: + // Similar to 395. Longest Substring with At Least K Repeating Characters + int maxSubstringLengthWithNUniqueLetters(const string& s, int n, + const vector& allCount) { + int res = -1; + // the number of unique letters + int uniqueLetters = 0; + // the number of letters that have all their frequency in the substring + int lettersHavingAllFreq = 0; + vector count(26); + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s[r] - 'a'] == 1) + ++uniqueLetters; + if (count[s[r] - 'a'] == allCount[s[r] - 'a']) + ++lettersHavingAllFreq; + while (uniqueLetters > n) { + if (count[s[l] - 'a'] == allCount[s[l] - 'a']) + --lettersHavingAllFreq; + if (--count[s[l] - 'a'] == 0) + --uniqueLetters; + ++l; + } + // Since both the number of unique letters and the number of letters + // having all their frequency are equal to n, this is a valid window. + // Implcit: uniqueLetters == n + if (lettersHavingAllFreq == n && r - l + 1 < s.length()) + res = max(res, r - l + 1); + } + + return res; + } +}; diff --git a/solutions/3104. Find Longest Self-Contained Substring/3104.java b/solutions/3104. Find Longest Self-Contained Substring/3104.java new file mode 100644 index 00000000000..48714aff2e8 --- /dev/null +++ b/solutions/3104. Find Longest Self-Contained Substring/3104.java @@ -0,0 +1,45 @@ +class Solution { + public int maxSubstringLength(String s) { + int ans = -1; + int count[] = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (int n = 1; n <= 26; ++n) + ans = Math.max(ans, maxSubstringLengthWithNUniqueLetters(s, n, count)); + + return ans; + } + + // Similar to 395. Longest Substring with At Least K Repeating Characters + private int maxSubstringLengthWithNUniqueLetters(final String s, int n, int[] allCount) { + int res = -1; + // the number of unique letters + int uniqueLetters = 0; + // the number of letters that have all their frequency in the substring + int lettersHavingAllFreq = 0; + int[] count = new int[26]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s.charAt(r) - 'a'] == 1) + ++uniqueLetters; + if (count[s.charAt(r) - 'a'] == allCount[s.charAt(r) - 'a']) + ++lettersHavingAllFreq; + while (uniqueLetters > n) { + if (count[s.charAt(l) - 'a'] == allCount[s.charAt(l) - 'a']) + --lettersHavingAllFreq; + if (--count[s.charAt(l) - 'a'] == 0) + --uniqueLetters; + ++l; + } + // Since both the number of unique letters and the number of letters + // having all their frequency are equal to n, this is a valid window. + // Implcit: uniqueLetters == n + if (lettersHavingAllFreq == n && r - l + 1 < s.length()) + res = Math.max(res, r - l + 1); + } + + return res; + } +} diff --git a/solutions/3104. Find Longest Self-Contained Substring/3104.py b/solutions/3104. Find Longest Self-Contained Substring/3104.py new file mode 100644 index 00000000000..79bd3e36268 --- /dev/null +++ b/solutions/3104. Find Longest Self-Contained Substring/3104.py @@ -0,0 +1,37 @@ +class Solution: + def maxSubstringLength(self, s: str) -> int: + allCount = collections.Counter(s) + + # Similar to 395. Longest Substring with At Least K Repeating Characters + def maxSubstringLengthWithNUniqueLetters(n: int) -> int: + res = -1 + # the number of unique letters + uniqueLetters = 0 + # the number of letters that have all their frequency in the substring + lettersHavingAllFreq = 0 + count = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + if count[c] == 1: + uniqueLetters += 1 + if count[c] == allCount[c]: + lettersHavingAllFreq += 1 + while uniqueLetters > n: + if count[s[l]] == allCount[s[l]]: + lettersHavingAllFreq -= 1 + count[s[l]] -= 1 + if count[s[l]] == 0: + uniqueLetters -= 1 + l += 1 + # Since both the number of unique letters and the number of letters + # having all their frequency are equal to n, this is a valid window. + # Implcit: uniqueLetters == n + if lettersHavingAllFreq == n and r - l + 1 < len(s): + res = max(res, r - l + 1) + + return res + + return max(maxSubstringLengthWithNUniqueLetters(n) + for n in range(1, 27)) diff --git a/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.cpp b/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.cpp new file mode 100644 index 00000000000..2f2d01de4f2 --- /dev/null +++ b/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + // Similar to 978. Longest Turbulent Subarray + int longestMonotonicSubarray(vector& nums) { + int ans = 1; + int increasing = 1; + int decreasing = 1; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > nums[i - 1]) { + increasing += 1; + decreasing = 1; + } else if (nums[i] < nums[i - 1]) { + decreasing += 1; + increasing = 1; + } else { + increasing = 1; + decreasing = 1; + } + ans = max({ans, increasing, decreasing}); + } + + return ans; + } +}; diff --git a/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.java b/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.java new file mode 100644 index 00000000000..047d1265067 --- /dev/null +++ b/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.java @@ -0,0 +1,24 @@ +class Solution { + // Similar to 978. Longest Turbulent Subarray + public int longestMonotonicSubarray(int[] nums) { + int ans = 1; + int increasing = 1; + int decreasing = 1; + + for (int i = 1; i < nums.length; ++i) { + if (nums[i] > nums[i - 1]) { + increasing += 1; + decreasing = 1; + } else if (nums[i] < nums[i - 1]) { + decreasing += 1; + increasing = 1; + } else { + increasing = 1; + decreasing = 1; + } + ans = Math.max(ans, Math.max(increasing, decreasing)); + } + + return ans; + } +} diff --git a/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.py b/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.py new file mode 100644 index 00000000000..15b8d16a6fd --- /dev/null +++ b/solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.py @@ -0,0 +1,20 @@ +class Solution: + # Similar to 978. Longest Turbulent Subarray + def longestMonotonicSubarray(self, nums: List[int]) -> int: + ans = 1 + increasing = 1 + decreasing = 1 + + for i in range(1, len(nums)): + if nums[i] > nums[i - 1]: + increasing += 1 + decreasing = 1 + elif nums[i] < nums[i - 1]: + decreasing += 1 + increasing = 1 + else: + increasing = 1 + decreasing = 1 + ans = max(ans, increasing, decreasing) + + return ans diff --git a/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.cpp b/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.cpp new file mode 100644 index 00000000000..244669570ad --- /dev/null +++ b/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + string getSmallestString(string s, int k) { + string ans = s; + + for (char& c : ans) { + if (k == 0) + break; + const int distToA = min(c - 'a', 'z' - c + 1); + if (k >= distToA) { + k -= distToA; + c = 'a'; + } else { + // k is not enough to change the current letter to 'a', so move as + // closer to 'a' as possible. + c -= k; + k = 0; + } + } + + return ans; + } +}; diff --git a/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.java b/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.java new file mode 100644 index 00000000000..b088e0e87ea --- /dev/null +++ b/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.java @@ -0,0 +1,22 @@ +class Solution { + public String getSmallestString(String s, int k) { + StringBuilder sb = new StringBuilder(s); + + for (int i = 0; i < sb.length(); ++i) { + if (k == 0) + break; + final int distToA = Math.min(sb.charAt(i) - 'a', 'z' - sb.charAt(i) + 1); + if (k >= distToA) { + k -= distToA; + sb.setCharAt(i, 'a'); + } else { + // k is not enough to change the current letter to 'a', so move as + // closer to 'a' as possible. + sb.setCharAt(i, (char) (sb.charAt(i) - k)); + k = 0; + } + } + + return sb.toString(); + } +} diff --git a/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.py b/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.py new file mode 100644 index 00000000000..6bef0947f78 --- /dev/null +++ b/solutions/3106. Lexicographically Smallest String After Operations With Constraint/3106.py @@ -0,0 +1,18 @@ +class Solution: + def getSmallestString(self, s: str, k: int) -> str: + ans = list(s) + + for i, c in enumerate(s): + if k == 0: + break + distToA = min(ord(c) - ord('a'), ord('z') - ord(c) + 1) + if k >= distToA: + k -= distToA + ans[i] = 'a' + else: + # k is not enough to change the current letter to 'a', so move as closer + # to 'a' as possible. + ans[i] = chr(ord(c) - k) + k = 0 + + return ''.join(ans) diff --git a/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.cpp b/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.cpp new file mode 100644 index 00000000000..7fc0cbc9e29 --- /dev/null +++ b/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + long long minOperationsToMakeMedianK(vector& nums, int k) { + const int n = nums.size(); + long ans = 0; + + ranges::sort(nums); + + for (int i = 0; i <= n / 2; ++i) + ans += max(0, nums[i] - k); + + for (int i = n / 2; i < n; ++i) + ans += max(0, k - nums[i]); + + return ans; + } +}; diff --git a/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.java b/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.java new file mode 100644 index 00000000000..47a856ced39 --- /dev/null +++ b/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.java @@ -0,0 +1,16 @@ +class Solution { + public long minOperationsToMakeMedianK(int[] nums, int k) { + final int n = nums.length; + long ans = 0; + + Arrays.sort(nums); + + for (int i = 0; i <= n / 2; ++i) + ans += Math.max(0, nums[i] - k); + + for (int i = n / 2; i < n; ++i) + ans += Math.max(0, k - nums[i]); + + return ans; + } +} diff --git a/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.py b/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.py new file mode 100644 index 00000000000..6c9cb7c3eca --- /dev/null +++ b/solutions/3107. Minimum Operations to Make Median of Array Equal to K/3107.py @@ -0,0 +1,14 @@ +class Solution: + def minOperationsToMakeMedianK(self, nums: List[int], k: int) -> int: + n = len(nums) + ans = 0 + + nums.sort() + + for i in range(n // 2 + 1): + ans += max(0, nums[i] - k) + + for i in range(n // 2, n): + ans += max(0, k - nums[i]) + + return ans diff --git a/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.cpp b/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.cpp new file mode 100644 index 00000000000..31fa4f73a2d --- /dev/null +++ b/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.cpp @@ -0,0 +1,66 @@ +class UnionFind { + public: + // 2^17 - 1 is the minimum number in the form 2^x - 1 > 10^5. + UnionFind(int n) : id(n), rank(n), weight(n, (1 << 17) - 1) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v, int w) { + const int i = find(u); + const int j = find(v); + const int newWeight = weight[i] & weight[j] & w; + weight[i] = newWeight; + weight[j] = newWeight; + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int getMinCost(int u, int v) { + if (u == v) + return 0; + const int i = find(u); + const int j = find(v); + return i == j ? weight[i] : -1; + } + + private: + vector id; + vector rank; + vector weight; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + vector minimumCost(int n, vector>& edges, + vector>& query) { + vector ans; + UnionFind uf(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + uf.unionByRank(u, v, w); + } + + for (const vector& q : query) { + const int u = q[0]; + const int v = q[1]; + ans.push_back(uf.getMinCost(u, v)); + } + + return ans; + } +}; diff --git a/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.java b/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.java new file mode 100644 index 00000000000..bfe29e44219 --- /dev/null +++ b/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.java @@ -0,0 +1,67 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + weight = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + // 2^17 - 1 is the minimum number in the form 2^x - 1 > 10^5. + Arrays.fill(weight, (1 << 17) - 1); + } + + public void unionByRank(int u, int v, int w) { + final int i = find(u); + final int j = find(v); + final int newWeight = weight[i] & weight[j] & w; + weight[i] = newWeight; + weight[j] = newWeight; + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int getMinCost(int u, int v) { + if (u == v) + return 0; + final int i = find(u); + final int j = find(v); + return i == j ? weight[i] : -1; + } + + private int[] id; + private int[] rank; + private int[] weight; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int[] minimumCost(int n, int[][] edges, int[][] query) { + int[] ans = new int[query.length]; + UnionFind uf = new UnionFind(n); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + uf.unionByRank(u, v, w); + } + + for (int i = 0; i < query.length; ++i) { + final int u = query[i][0]; + final int v = query[i][1]; + ans[i] = uf.getMinCost(u, v); + } + + return ans; + } +} diff --git a/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.py b/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.py new file mode 100644 index 00000000000..11f454e0c82 --- /dev/null +++ b/solutions/3108. Minimum Cost Walk in Weighted Graph/3108.py @@ -0,0 +1,44 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + # 2^17 - 1 is the minimum number in the form 2^x - 1 > 10^5. + self.weight = [(1 << 17) - 1] * n + + def unionByRank(self, u: int, v: int, w: int) -> None: + i = self._find(u) + j = self._find(v) + newWeight = self.weight[i] & self.weight[j] & w + self.weight[i] = newWeight + self.weight[j] = newWeight + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def getMinCost(self, u: int, v: int) -> int: + if u == v: + return 0 + i = self._find(u) + j = self._find(v) + return self.weight[i] if i == j else -1 + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def minimumCost(self, n: int, edges: List[List[int]], query: List[List[int]]) -> List[int]: + uf = UnionFind(n) + + for u, v, w in edges: + uf.unionByRank(u, v, w) + + return [uf.getMinCost(u, v) for u, v in query] diff --git a/solutions/3109. Find the Index of Permutation/3109.cpp b/solutions/3109. Find the Index of Permutation/3109.cpp new file mode 100644 index 00000000000..a0c78e31d91 --- /dev/null +++ b/solutions/3109. Find the Index of Permutation/3109.cpp @@ -0,0 +1,52 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + int getPermutationIndex(vector& perm) { + constexpr int kMod = 1'000'000'007; + const int n = perm.size(); + int ans = 0; + FenwickTree tree(n); + vector fact(n + 1, 1); // fact[i] := i! + + for (int i = 2; i <= n; ++i) + fact[i] = (fact[i - 1] * static_cast(i)) % kMod; + + for (int i = 0; i < n; ++i) { + const int num = perm[i]; + // the number of unused numbers less than `num` + const int unusedNums = num - 1 - tree.get(num - 1); + const int suffixLength = fact[n - 1 - i]; + ans = (ans + unusedNums * static_cast(suffixLength)) % kMod; + tree.add(num, 1); + } + + return ans; + } +}; diff --git a/solutions/3109. Find the Index of Permutation/3109.java b/solutions/3109. Find the Index of Permutation/3109.java new file mode 100644 index 00000000000..6b848ef5795 --- /dev/null +++ b/solutions/3109. Find the Index of Permutation/3109.java @@ -0,0 +1,52 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public int getPermutationIndex(int[] perm) { + final int kMod = 1_000_000_007; + final int n = perm.length; + int ans = 0; + FenwickTree tree = new FenwickTree(n); + int[] fact = new int[n + 1]; // fact[i] := i! + Arrays.fill(fact, 1); + + for (int i = 2; i <= n; ++i) + fact[i] = (int) ((fact[i - 1] * (long) i) % kMod); + + for (int i = 0; i < n; ++i) { + final int num = perm[i]; + // the number of unused numbers less than `num` + final int unusedNums = num - 1 - tree.get(num - 1); + final int suffixLength = fact[n - 1 - i]; + ans = (int) ((ans + unusedNums * (long) suffixLength) % kMod); + tree.add(num, 1); + } + + return ans; + } +} diff --git a/solutions/3109. Find the Index of Permutation/3109.py b/solutions/3109. Find the Index of Permutation/3109.py new file mode 100644 index 00000000000..489db276007 --- /dev/null +++ b/solutions/3109. Find the Index of Permutation/3109.py @@ -0,0 +1,41 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def getPermutationIndex(self, perm: List[int]) -> int: + kMod = 1_000_000_007 + n = len(perm) + ans = 0 + tree = FenwickTree(n) + fact = [1] * (n + 1) # fact[i] := i! + + for i in range(2, n + 1): + fact[i] = (fact[i - 1] * i) % kMod + + for i, num in enumerate(perm): + # the number of unused numbers less than `num` + unusedNums = num - 1 - tree.get(num - 1) + suffixLength = fact[n - 1 - i] + ans += unusedNums * suffixLength + ans %= kMod + tree.add(num, 1) + + return ans diff --git a/solutions/311. Sparse Matrix Multiplication/311-2.cpp b/solutions/311. Sparse Matrix Multiplication/311-2.cpp new file mode 100644 index 00000000000..b3e23e0b826 --- /dev/null +++ b/solutions/311. Sparse Matrix Multiplication/311-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector> multiply(vector>& mat1, + vector>& mat2) { + const int m = mat1.size(); + const int n = mat2.size(); + const int l = mat2[0].size(); + vector> ans(m, vector(l)); + vector> nonZeroColIndicesInMat2; + + for (int i = 0; i < n; ++i) { + vector colIndices; + for (int j = 0; j < l; ++j) + if (mat2[i][j] != 0) + colIndices.push_back(j); + nonZeroColIndicesInMat2.push_back(colIndices); + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (mat1[i][j] == 0) + continue; + // mat1's j-th column matches mat2's j-th row + for (const int colIndex : nonZeroColIndicesInMat2[j]) + ans[i][colIndex] += mat1[i][j] * mat2[j][colIndex]; + } + + return ans; + } +}; diff --git a/solutions/311. Sparse Matrix Multiplication/311-2.java b/solutions/311. Sparse Matrix Multiplication/311-2.java new file mode 100644 index 00000000000..0a2d2093da3 --- /dev/null +++ b/solutions/311. Sparse Matrix Multiplication/311-2.java @@ -0,0 +1,28 @@ +class Solution { + public int[][] multiply(int[][] mat1, int[][] mat2) { + final int m = mat1.length; + final int n = mat2.length; + final int l = mat2[0].length; + int[][] ans = new int[m][l]; + List[] nonZeroColIndicesInMat2 = new List[n]; + + for (int i = 0; i < n; ++i) { + List colIndices = new ArrayList<>(); + for (int j = 0; j < l; ++j) + if (mat2[i][j] != 0) + colIndices.add(j); + nonZeroColIndicesInMat2[i] = colIndices; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + if (mat1[i][j] == 0) + continue; + // mat1s j-th column matches mat2's j-th row + for (final int colIndex : nonZeroColIndicesInMat2[j]) + ans[i][colIndex] += mat1[i][j] * mat2[j][colIndex]; + } + + return ans; + } +} diff --git a/solutions/311. Sparse Matrix Multiplication/311-2.py b/solutions/311. Sparse Matrix Multiplication/311-2.py new file mode 100644 index 00000000000..3932108ffda --- /dev/null +++ b/solutions/311. Sparse Matrix Multiplication/311-2.py @@ -0,0 +1,20 @@ +class Solution: + def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: + m = len(mat1) + n = len(mat2) + l = len(mat2[0]) + ans = [[0] * l for _ in range(m)] + nonZeroColIndicesInMat2 = [ + [j for j, a in enumerate(row) if a] + for row in mat2 + ] + + for i in range(m): + for j, a in enumerate(mat1[i]): + if a == 0: + continue + # mat1s j-th column matches mat2's j-th row + for colIndex in nonZeroColIndicesInMat2[j]: + ans[i][colIndex] += a * mat2[j][colIndex] + + return ans diff --git a/solutions/311. Sparse Matrix Multiplication/311.cpp b/solutions/311. Sparse Matrix Multiplication/311.cpp new file mode 100644 index 00000000000..18e6a6c7ff5 --- /dev/null +++ b/solutions/311. Sparse Matrix Multiplication/311.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector> multiply(vector>& mat1, + vector>& mat2) { + const int m = mat1.size(); + const int n = mat2.size(); + const int l = mat2[0].size(); + vector> ans(m, vector(l)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < l; ++j) + for (int k = 0; k < n; ++k) + ans[i][j] += mat1[i][k] * mat2[k][j]; + + return ans; + } +}; diff --git a/solutions/311. Sparse Matrix Multiplication/311.java b/solutions/311. Sparse Matrix Multiplication/311.java new file mode 100644 index 00000000000..da555318f74 --- /dev/null +++ b/solutions/311. Sparse Matrix Multiplication/311.java @@ -0,0 +1,15 @@ +class Solution { + public int[][] multiply(int[][] mat1, int[][] mat2) { + final int m = mat1.length; + final int n = mat2.length; + final int l = mat2[0].length; + int[][] ans = new int[m][l]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < l; ++j) + for (int k = 0; k < n; ++k) + ans[i][j] += mat1[i][k] * mat2[k][j]; + + return ans; + } +} diff --git a/solutions/311. Sparse Matrix Multiplication/311.py b/solutions/311. Sparse Matrix Multiplication/311.py new file mode 100644 index 00000000000..efccc3c658d --- /dev/null +++ b/solutions/311. Sparse Matrix Multiplication/311.py @@ -0,0 +1,13 @@ +class Solution: + def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: + m = len(mat1) + n = len(mat2) + l = len(mat2[0]) + ans = [[0] * l for _ in range(m)] + + for i in range(m): + for j in range(l): + for k in range(n): + ans[i][j] += mat1[i][k] * mat2[k][j] + + return ans diff --git a/solutions/3110. Score of a String/3110.cpp b/solutions/3110. Score of a String/3110.cpp new file mode 100644 index 00000000000..cef4cbbaa8a --- /dev/null +++ b/solutions/3110. Score of a String/3110.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int scoreOfString(string s) { + int ans = 0; + + for (int i = 1; i < s.length(); ++i) + ans += abs(s[i] - s[i - 1]); + + return ans; + } +}; diff --git a/solutions/3110. Score of a String/3110.java b/solutions/3110. Score of a String/3110.java new file mode 100644 index 00000000000..5140f9de96d --- /dev/null +++ b/solutions/3110. Score of a String/3110.java @@ -0,0 +1,10 @@ +class Solution { + public int scoreOfString(String s) { + int ans = 0; + + for (int i = 1; i < s.length(); ++i) + ans += Math.abs(s.charAt(i) - s.charAt(i - 1)); + + return ans; + } +} diff --git a/solutions/3110. Score of a String/3110.py b/solutions/3110. Score of a String/3110.py new file mode 100644 index 00000000000..9fa2d31a352 --- /dev/null +++ b/solutions/3110. Score of a String/3110.py @@ -0,0 +1,4 @@ +class Solution: + def scoreOfString(self, s: str) -> int: + return sum(abs(ord(a) - ord(b)) + for a, b in itertools.pairwise(s)) diff --git a/solutions/3111. Minimum Rectangles to Cover Points/3111.cpp b/solutions/3111. Minimum Rectangles to Cover Points/3111.cpp new file mode 100644 index 00000000000..0e838ab4486 --- /dev/null +++ b/solutions/3111. Minimum Rectangles to Cover Points/3111.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minRectanglesToCoverPoints(vector>& points, int w) { + int ans = 0; + int prevX = -w - 1; + vector xs; + + for (const vector& point : points) { + const int x = point[0]; + xs.push_back(x); + } + + ranges::sort(xs); + + for (const int x : xs) + if (x > prevX + w) { + ++ans; + prevX = x; + } + + return ans; + } +}; diff --git a/solutions/3111. Minimum Rectangles to Cover Points/3111.java b/solutions/3111. Minimum Rectangles to Cover Points/3111.java new file mode 100644 index 00000000000..55f095893f9 --- /dev/null +++ b/solutions/3111. Minimum Rectangles to Cover Points/3111.java @@ -0,0 +1,20 @@ +class Solution { + public int minRectanglesToCoverPoints(int[][] points, int w) { + int ans = 0; + int prevX = -w - 1; + int[] xs = new int[points.length]; + + for (int i = 0; i < points.length; ++i) + xs[i] = points[i][0]; + + Arrays.sort(xs); + + for (final int x : xs) + if (x > prevX + w) { + ++ans; + prevX = x; + } + + return ans; + } +} diff --git a/solutions/3111. Minimum Rectangles to Cover Points/3111.py b/solutions/3111. Minimum Rectangles to Cover Points/3111.py new file mode 100644 index 00000000000..19b4c06955c --- /dev/null +++ b/solutions/3111. Minimum Rectangles to Cover Points/3111.py @@ -0,0 +1,12 @@ +class Solution: + def minRectanglesToCoverPoints(self, points: List[List[int]], w: int) -> int: + ans = 0 + prevX = -w - 1 + xs = sorted([x for x, _ in points]) + + for x in xs: + if x > prevX + w: + ans += 1 + prevX = x + + return ans diff --git a/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.cpp b/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.cpp new file mode 100644 index 00000000000..c28a1a1eeb4 --- /dev/null +++ b/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + vector minimumTime(int n, vector>& edges, + vector& disappear) { + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + return dijkstra(graph, 0, disappear); + } + + private: + vector dijkstra(const vector>>& graph, int src, + const vector& disappear) { + vector dist(graph.size(), INT_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < disappear[v] && d + w < dist[v]) { + dist[v] = d + w; + minHeap.push({dist[v], v}); + } + } + + for (int& d : dist) + if (d == INT_MAX) + d = -1; + + return dist; + } +}; diff --git a/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.java b/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.java new file mode 100644 index 00000000000..27a98641e9d --- /dev/null +++ b/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.java @@ -0,0 +1,49 @@ +class Solution { + public int[] minimumTime(int n, int[][] edges, int[] disappear) { + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + return dijkstra(graph, 0, disappear); + } + + private int[] dijkstra(List>[] graph, int src, int[] disappear) { + int[] dist = new int[graph.length]; + Arrays.fill(dist, Integer.MAX_VALUE); + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < disappear[v] && d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + for (int i = 0; i < dist.length; ++i) + if (dist[i] == Integer.MAX_VALUE) + dist[i] = -1; + + return dist; + } +} diff --git a/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.py b/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.py new file mode 100644 index 00000000000..3f2c2924178 --- /dev/null +++ b/solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.py @@ -0,0 +1,27 @@ +class Solution: + def minimumTime(self, n: int, edges: List[List[int]], disappear: List[int]) -> List[int]: + graph = [[] for _ in range(n)] + + for u, v, w in edges: + graph[u].append((v, w)) + graph[v].append((u, w)) + + return self._dijkstra(graph, 0, disappear) + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, disappear: List[int]) -> List[int]: + dist = [math.inf] * len(graph) + + dist[src] = 0 + minHeap = [(dist[src], src)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < disappear[v] and d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + + return [d if d != math.inf else -1 + for d in dist] diff --git a/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.cpp b/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.cpp new file mode 100644 index 00000000000..92b5ea1e24d --- /dev/null +++ b/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + long long numberOfSubarrays(vector& nums) { + long ans = 0; + vector> stack; + + for (const int num : nums) { + while (!stack.empty() && stack.back().first < num) + stack.pop_back(); + if (stack.empty() || stack.back().first != num) + stack.emplace_back(num, 0); + ans += ++stack.back().second; + } + + return ans; + } +}; diff --git a/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.java b/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.java new file mode 100644 index 00000000000..0828e0fe650 --- /dev/null +++ b/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.java @@ -0,0 +1,17 @@ +class Solution { + public long numberOfSubarrays(int[] nums) { + Deque stack = new ArrayDeque<>(); + long ans = 0; + int top = -1; + + for (final int num : nums) { + while (!stack.isEmpty() && stack.peek()[0] < num) + stack.pop(); + if (stack.isEmpty() || stack.peek()[0] != num) + stack.push(new int[] {num, 0}); + ans += ++stack.peek()[1]; + } + + return ans; + } +} diff --git a/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.py b/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.py new file mode 100644 index 00000000000..5d62c9e7c10 --- /dev/null +++ b/solutions/3113. Find the Number of Subarrays Where Boundary Elements Are Maximum/3113.py @@ -0,0 +1,14 @@ +class Solution: + def numberOfSubarrays(self, nums: List[int]) -> int: + ans = 0 + stack = [] + + for num in nums: + while stack and stack[-1][0] < num: + stack.pop() + if not stack or stack[-1][0] != num: + stack.append([num, 0]) + stack[-1][1] += 1 + ans += stack[-1][1] + + return ans diff --git a/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.cpp b/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.cpp new file mode 100644 index 00000000000..c200be9edaa --- /dev/null +++ b/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + // Similar to 1736. Latest Time by Replacing Hidden Digits + string findLatestTime(string s) { + string ans = s; + if (s[0] == '?') + ans[0] = s[1] == '?' || s[1] < '2' ? '1' : '0'; + if (s[1] == '?') + ans[1] = ans[0] == '1' ? '1' : '9'; + if (s[3] == '?') + ans[3] = '5'; + if (s[4] == '?') + ans[4] = '9'; + return ans; + } +}; diff --git a/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.java b/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.java new file mode 100644 index 00000000000..67ed57a5551 --- /dev/null +++ b/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.java @@ -0,0 +1,15 @@ +class Solution { + // Similar to 1736. Latest Time by Replacing Hidden Digits + public String findLatestTime(String s) { + char[] ans = s.toCharArray(); + if (s.charAt(0) == '?') + ans[0] = s.charAt(1) == '?' || s.charAt(1) < '2' ? '1' : '0'; + if (s.charAt(1) == '?') + ans[1] = ans[0] == '1' ? '1' : '9'; + if (s.charAt(3) == '?') + ans[3] = '5'; + if (s.charAt(4) == '?') + ans[4] = '9'; + return new String(ans); + } +} diff --git a/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.py b/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.py new file mode 100644 index 00000000000..70650f12031 --- /dev/null +++ b/solutions/3114. Latest Time You Can Obtain After Replacing Characters/3114.py @@ -0,0 +1,13 @@ +class Solution: + # Similar to 1736. Latest Time by Replacing Hidden Digits + def findLatestTime(self, s: str) -> str: + ans = list(s) + if s[0] == '?': + ans[0] = '1' if s[1] == '?' or s[1] < '2' else '0' + if s[1] == '?': + ans[1] = '1' if ans[0] == '1' else '9' + if s[3] == '?': + ans[3] = '5' + if s[4] == '?': + ans[4] = '9' + return ''.join(ans) diff --git a/solutions/3115. Maximum Prime Difference/3115.cpp b/solutions/3115. Maximum Prime Difference/3115.cpp new file mode 100644 index 00000000000..1ee359e9960 --- /dev/null +++ b/solutions/3115. Maximum Prime Difference/3115.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int maximumPrimeDifference(vector& nums) { + constexpr int kMax = 100; + const vector isPrime = sieveEratosthenes(kMax + 1); + int minPrimeIndex = -1; + int maxPrimeIndex = -1; + + for (int i = 0; i < nums.size(); ++i) + if (isPrime[nums[i]]) { + if (minPrimeIndex == -1) + minPrimeIndex = i; + maxPrimeIndex = i; + } + + return maxPrimeIndex - minPrimeIndex; + } + + private: + vector sieveEratosthenes(int n) { + vector isPrime(n, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +}; diff --git a/solutions/3115. Maximum Prime Difference/3115.java b/solutions/3115. Maximum Prime Difference/3115.java new file mode 100644 index 00000000000..b39cc5a5624 --- /dev/null +++ b/solutions/3115. Maximum Prime Difference/3115.java @@ -0,0 +1,29 @@ +class Solution { + public int maximumPrimeDifference(int[] nums) { + final int kMax = 100; + boolean[] isPrime = sieveEratosthenes(kMax + 1); + int minPrimeIndex = -1; + int maxPrimeIndex = -1; + + for (int i = 0; i < nums.length; ++i) + if (isPrime[nums[i]]) { + if (minPrimeIndex == -1) + minPrimeIndex = i; + maxPrimeIndex = i; + } + + return maxPrimeIndex - minPrimeIndex; + } + + private boolean[] sieveEratosthenes(int n) { + boolean[] isPrime = new boolean[n]; + Arrays.fill(isPrime, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +}; diff --git a/solutions/3115. Maximum Prime Difference/3115.py b/solutions/3115. Maximum Prime Difference/3115.py new file mode 100644 index 00000000000..fc9dfe62e41 --- /dev/null +++ b/solutions/3115. Maximum Prime Difference/3115.py @@ -0,0 +1,24 @@ +class Solution: + def maximumPrimeDifference(self, nums: List[int]) -> int: + kMax = 100 + isPrime = self._sieveEratosthenes(kMax + 1) + minPrimeIndex = -1 + maxPrimeIndex = -1 + + for i, num in enumerate(nums): + if isPrime[num]: + if minPrimeIndex == -1: + minPrimeIndex = i + maxPrimeIndex = i + + return maxPrimeIndex - minPrimeIndex + + def _sieveEratosthenes(self, n: int) -> List[bool]: + isPrime = [True] * n + isPrime[0] = False + isPrime[1] = False + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n, i): + isPrime[j] = False + return isPrime diff --git a/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.cpp b/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.cpp new file mode 100644 index 00000000000..dd6aa4de34e --- /dev/null +++ b/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + long long findKthSmallest(vector& coins, int k) { + const vector> sizeToLcms = getSizeToLcms(coins); + long l = 0; + long r = static_cast(k) * ranges::min(coins); + + while (l < r) { + const long m = (l + r) / 2; + if (numDenominationsNoGreaterThan(sizeToLcms, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Returns the number of denominations <= m. + long numDenominationsNoGreaterThan(const vector>& sizeToLcms, + long m) { + long res = 0; + for (int sz = 1; sz < sizeToLcms.size(); ++sz) + for (const long lcm : sizeToLcms[sz]) + // Principle of Inclusion-Exclusion (PIE) + res += m / lcm * pow(-1, sz + 1); + return res; + }; + + // Returns the LCMs for each number of combination of coins. + vector> getSizeToLcms(const vector& coins) { + const int n = coins.size(); + const int maxMask = 1 << n; + vector> sizeToLcms(n + 1); + + for (unsigned mask = 1; mask < maxMask; ++mask) { + long lcmOfSelectedCoins = 1; + for (int i = 0; i < n; ++i) + if (mask >> i & 1) + lcmOfSelectedCoins = lcm(lcmOfSelectedCoins, coins[i]); + sizeToLcms[popcount(mask)].push_back(lcmOfSelectedCoins); + } + + return sizeToLcms; + } +}; diff --git a/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.java b/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.java new file mode 100644 index 00000000000..eb812855f6a --- /dev/null +++ b/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.java @@ -0,0 +1,54 @@ +class Solution { + public long findKthSmallest(int[] coins, int k) { + List[] sizeToLcms = getSizeToLcms(coins); + long l = 0; + long r = (long) k * Arrays.stream(coins).min().getAsInt(); + + while (l < r) { + final long m = (l + r) / 2; + if (numDenominationsNoGreaterThan(sizeToLcms, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + // Returns the number of denominations <= m. + private long numDenominationsNoGreaterThan(List[] sizeToLcms, long m) { + long res = 0; + for (int sz = 1; sz < sizeToLcms.length; ++sz) + for (long lcm : sizeToLcms[sz]) + res += m / lcm * Math.pow(-1, sz + 1); + return res; + } + + // Returns the LCMs for each number of combination of coins. + private List[] getSizeToLcms(int[] coins) { + final int n = coins.length; + final int maxMask = 1 << n; + List[] sizeToLcms = new List[n + 1]; + + for (int i = 1; i <= n; ++i) + sizeToLcms[i] = new ArrayList<>(); + + for (int mask = 1; mask < maxMask; ++mask) { + long lcmOfSelectedCoins = 1; + for (int i = 0; i < n; ++i) + if ((mask >> i & 1) == 1) + lcmOfSelectedCoins = lcm(lcmOfSelectedCoins, coins[i]); + sizeToLcms[Integer.bitCount(mask)].add(lcmOfSelectedCoins); + } + + return sizeToLcms; + } + + private long lcm(long a, long b) { + return a * b / gcd(a, b); + } + + private long gcd(long a, long b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.py b/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.py new file mode 100644 index 00000000000..50cfa6bde4c --- /dev/null +++ b/solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.py @@ -0,0 +1,23 @@ +class Solution: + def findKthSmallest(self, coins: List[int], k: int) -> int: + sizeToLcms = self._getSizeToLcms(coins) + + def count(m: int) -> int: + """Returns the number of denominations <= m.""" + res = 0 + for sz, lcms in enumerate(sizeToLcms): + for lcm in lcms: + # Principle of Inclusion-Exclusion (PIE) + res += m // lcm * pow(-1, sz + 1) + return res + + return bisect.bisect_left(range(0, k * min(coins)), k, + key=lambda m: count(m)) + + def _getSizeToLcms(self, coins: List[int]) -> List[List[int]]: + # Returns the LCMs for each number of combination of coins. + sizeToLcms = [[] for _ in range(len(coins) + 1)] + for sz in range(1, len(coins) + 1): + for combination in itertools.combinations(coins, sz): + sizeToLcms[sz].append(math.lcm(*combination)) + return sizeToLcms diff --git a/solutions/3117. Minimum Sum of Values by Dividing Array/3117.cpp b/solutions/3117. Minimum Sum of Values by Dividing Array/3117.cpp new file mode 100644 index 00000000000..b485df55524 --- /dev/null +++ b/solutions/3117. Minimum Sum of Values by Dividing Array/3117.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int minimumValueSum(vector& nums, vector& andValues) { + vector>> mem( + nums.size(), vector>(andValues.size())); + const int ans = minimumValueSum(nums, andValues, 0, 0, kAllMask, mem); + return ans == kInf ? -1 : ans; + } + + private: + static constexpr int kInf = 1'000'000'000; + static constexpr int kAllMask = (1 << 17) - 1; + + // Returns the minimum value sum of nums[i..n) and andValues[j..m), where + // `mask` is the running value of the current subarray. + int minimumValueSum(const vector& nums, const vector& andValues, + int i, int j, int mask, + vector>>& mem) { + if (i == nums.size() && j == andValues.size()) + return 0; + if (i == nums.size() || j == andValues.size()) + return kInf; + if (const auto it = mem[i][j].find(mask); it != mem[i][j].cend()) + return it->second; + mask &= nums[i]; + if (mask < andValues[j]) + return mem[i][j][mask] = kInf; + if (mask == andValues[j]) + // 1. Keep going. + // 2. End the subarray here and pick nums[i], then fresh start. + return mem[i][j][mask] = + min(minimumValueSum(nums, andValues, i + 1, j, mask, mem), + nums[i] + minimumValueSum(nums, andValues, i + 1, j + 1, + kAllMask, mem)); + // Keep going. + return mem[i][j][mask] = + minimumValueSum(nums, andValues, i + 1, j, mask, mem); + }; +}; diff --git a/solutions/3117. Minimum Sum of Values by Dividing Array/3117.java b/solutions/3117. Minimum Sum of Values by Dividing Array/3117.java new file mode 100644 index 00000000000..03e4fce3b1f --- /dev/null +++ b/solutions/3117. Minimum Sum of Values by Dividing Array/3117.java @@ -0,0 +1,41 @@ +class Solution { + public int minimumValueSum(int[] nums, int[] andValues) { + Map[][] mem = new Map[nums.length][andValues.length]; + Arrays.stream(mem).forEach(row -> Arrays.setAll(row, j -> new HashMap<>())); + final int ans = minimumValueSum(nums, andValues, 0, 0, kAllMask, mem); + return ans == kInf ? -1 : ans; + } + + private static final int kInf = 1_000_000_000; + private static final int kAllMask = (1 << 17) - 1; + + // Returns the minimum value sum of nums[i..n) and andValues[j..m), where + // `mask` is the running value of the current subarray. + private int minimumValueSum(int[] nums, int[] andValues, int i, int j, int mask, + Map[][] mem) { + if (i == nums.length && j == andValues.length) + return 0; + if (i == nums.length || j == andValues.length) + return kInf; + if (mem[i][j].containsKey(mask)) + return mem[i][j].get(mask); + mask &= nums[i]; + if (mask < andValues[j]) { + mem[i][j].put(mask, kInf); + return kInf; + } + if (mask == andValues[j]) { + // 1. Keep going. + // 2. End the subarray here and pick nums[i], then fresh start. + final int res = + Math.min(minimumValueSum(nums, andValues, i + 1, j, mask, mem), + nums[i] + minimumValueSum(nums, andValues, i + 1, j + 1, kAllMask, mem)); + mem[i][j].put(mask, res); + return res; + } + // Keep going. + final int res = minimumValueSum(nums, andValues, i + 1, j, mask, mem); + mem[i][j].put(mask, res); + return res; + } +} diff --git a/solutions/3117. Minimum Sum of Values by Dividing Array/3117.py b/solutions/3117. Minimum Sum of Values by Dividing Array/3117.py new file mode 100644 index 00000000000..6ae1528627b --- /dev/null +++ b/solutions/3117. Minimum Sum of Values by Dividing Array/3117.py @@ -0,0 +1,27 @@ +class Solution: + def minimumValueSum(self, nums: List[int], andValues: List[int]) -> int: + n = len(nums) + m = len(andValues) + + @functools.lru_cache(None) + def dp(i: int, j: int, mask: int) -> int: + """ + Returns the minimum value sum of nums[i..n) and andValues[j..m), where + `mask` is the running value of the current subarray. + """ + if i == n and j == m: + return 0 + if i == n or j == m: + return math.inf + mask &= nums[i] + if mask < andValues[j]: + return math.inf + if mask == andValues[j]: + # 1. Keep going. + # 2. End the subarray here and pick nums[i], then fresh start. + return min(dp(i + 1, j, mask), + nums[i] + dp(i + 1, j + 1, -1)) + return dp(i + 1, j, mask) # Keep going. + + ans = dp(0, 0, -1) + return ans if ans < math.inf else -1 diff --git a/solutions/3118. Friday Purchase III/3118.sql b/solutions/3118. Friday Purchase III/3118.sql new file mode 100644 index 00000000000..45f1ea0b4fe --- /dev/null +++ b/solutions/3118. Friday Purchase III/3118.sql @@ -0,0 +1,27 @@ +WITH + RECURSIVE Fridays AS ( + SELECT 1 AS week_of_month, '2023-11-03' AS purchase_date + UNION ALL + SELECT week_of_month + 1, DATE_ADD(purchase_date, INTERVAL 7 DAY) + FROM Fridays + WHERE week_of_month < 4 + ), + Memberships AS ( + SELECT 'Premium' AS membership + UNION ALL + SELECT 'VIP' + ) +SELECT + Fridays.week_of_month, + Memberships.membership, + IFNULL(SUM(Purchases.amount_spend), 0) AS total_amount +FROM Fridays +CROSS JOIN Memberships +LEFT JOIN Users + ON (Memberships.membership = Users.membership) +LEFT JOIN Purchases + ON ( + Fridays.purchase_date = Purchases.purchase_date + AND Users.user_id = Purchases.user_id) +GROUP BY 1, 2 +ORDER BY 1, 2; diff --git a/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.cpp b/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.cpp new file mode 100644 index 00000000000..6c9b423eb5e --- /dev/null +++ b/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maxPotholes(string road, int budget) { + int ans = 0; + + for (const int length : getSortedPotholeLengths(road)) { + const int canRepair = max(0, budget - 1); + if (length > canRepair) + return ans + canRepair; + ans += length; + budget -= length + 1; + } + + return ans; + } + + private: + vector getSortedPotholeLengths(const string& road) { + vector potholeLengths; + istringstream iss(road); + string pothole; + + while (getline(iss, pothole, '.')) + potholeLengths.push_back(pothole.length()); + + ranges::sort(potholeLengths, greater<>()); + return potholeLengths; + } +}; diff --git a/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.java b/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.java new file mode 100644 index 00000000000..dc5fb46a4eb --- /dev/null +++ b/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.java @@ -0,0 +1,23 @@ +class Solution { + public int maxPotholes(String road, int budget) { + int ans = 0; + + for (final int length : getSortedPotholeLengths(road)) { + final int canRepair = Math.max(0, budget - 1); + if (length > canRepair) + return ans + canRepair; + ans += length; + budget -= length + 1; + } + + return ans; + } + + private List getSortedPotholeLengths(final String road) { + List potholeLengths = new ArrayList<>(); + for (String pothole : road.split("\\.")) + potholeLengths.add(pothole.length()); + Collections.sort(potholeLengths, Collections.reverseOrder()); + return potholeLengths; + } +} diff --git a/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.py b/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.py new file mode 100644 index 00000000000..466ad3c62ed --- /dev/null +++ b/solutions/3119. Maximum Number of Potholes That Can Be Fixed/3119.py @@ -0,0 +1,12 @@ +class Solution: + def maxPotholes(self, road: str, budget: int) -> int: + ans = 0 + + for length in sorted(map(len, road.split('.')), reverse=True): + canRepair = max(0, budget - 1) + if length > canRepair: + return ans + canRepair + ans += length + budget -= length + 1 + + return ans diff --git a/solutions/312. Burst Balloons/312-2.cpp b/solutions/312. Burst Balloons/312-2.cpp new file mode 100644 index 00000000000..5f763ced0c1 --- /dev/null +++ b/solutions/312. Burst Balloons/312-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maxCoins(vector& nums) { + const int n = nums.size(); + // dp[i][j] := maxCoins(nums[i..j]) + vector> dp(n + 2, vector(n + 2)); + + nums.insert(nums.begin(), 1); + nums.insert(nums.end(), 1); + + for (int d = 0; d < n; ++d) + for (int i = 1; i + d <= n; ++i) { + const int j = i + d; + for (int k = i; k <= j; ++k) + dp[i][j] = max(dp[i][j], // + dp[i][k - 1] + dp[k + 1][j] + // + nums[i - 1] * nums[k] * nums[j + 1]); + } + + return dp[1][n]; + } +}; diff --git a/solutions/312. Burst Balloons/312-2.java b/solutions/312. Burst Balloons/312-2.java new file mode 100644 index 00000000000..f813569a33e --- /dev/null +++ b/solutions/312. Burst Balloons/312-2.java @@ -0,0 +1,23 @@ +class Solution { + public int maxCoins(int[] nums) { + final int n = nums.length; + // dp[i][j] := maxCoins(A[i..j]) + int[][] dp = new int[n + 2][n + 2]; + int[] A = new int[n + 2]; + + System.arraycopy(nums, 0, A, 1, n); + A[0] = 1; + A[n + 1] = 1; + + for (int d = 0; d < n; ++d) + for (int i = 1; i + d <= n; ++i) { + final int j = i + d; + for (int k = i; k <= j; ++k) + dp[i][j] = Math.max(dp[i][j], // + dp[i][k - 1] + dp[k + 1][j] + // + A[i - 1] * A[k] * A[j + 1]); + } + + return dp[1][n]; + } +} diff --git a/solutions/312. Burst Balloons/312-2.py b/solutions/312. Burst Balloons/312-2.py new file mode 100644 index 00000000000..811328472d0 --- /dev/null +++ b/solutions/312. Burst Balloons/312-2.py @@ -0,0 +1,19 @@ +class Solution: + def maxCoins(self, nums: List[int]) -> int: + n = len(nums) + # dp[i][j] := maxCoins(nums[i..j]) + dp = [[0] * (n + 2) for _ in range(n + 2)] + + nums = [1] + nums + [1] + + for d in range(n): + for i in range(1, n - d + 1): + j = i + d + for k in range(i, j + 1): + dp[i][j] = max( + dp[i][j], + dp[i][k - 1] + + dp[k + 1][j] + + nums[i - 1] * nums[k] * nums[j + 1]) + + return dp[1][n] diff --git a/solutions/312. Burst Balloons/312.cpp b/solutions/312. Burst Balloons/312.cpp new file mode 100644 index 00000000000..5fb62ff42dc --- /dev/null +++ b/solutions/312. Burst Balloons/312.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxCoins(vector& nums) { + const int n = nums.size(); + vector> mem(n + 2, vector(n + 2)); + nums.insert(nums.begin(), 1); + nums.insert(nums.end(), 1); + return maxCoins(nums, 1, n, mem); + } + + private: + // Returns maxCoins(nums[i..j]). + int maxCoins(const vector& nums, int i, int j, + vector>& mem) { + if (i > j) + return 0; + if (mem[i][j] > 0) + return mem[i][j]; + + for (int k = i; k <= j; ++k) + mem[i][j] = max(mem[i][j], maxCoins(nums, i, k - 1, mem) + + maxCoins(nums, k + 1, j, mem) + + nums[i - 1] * nums[k] * nums[j + 1]); + + return mem[i][j]; + } +}; diff --git a/solutions/312. Burst Balloons/312.java b/solutions/312. Burst Balloons/312.java new file mode 100644 index 00000000000..eb6e095319d --- /dev/null +++ b/solutions/312. Burst Balloons/312.java @@ -0,0 +1,27 @@ +class Solution { + public int maxCoins(int[] nums) { + final int n = nums.length; + int[][] mem = new int[n + 2][n + 2]; + int[] extendedNums = new int[n + 2]; + System.arraycopy(nums, 0, extendedNums, 1, n); + extendedNums[0] = 1; + extendedNums[n + 1] = 1; + return maxCoins(extendedNums, 1, n, mem); + } + + // Returns maxCoins(nums[i..j]). + private int maxCoins(int[] nums, int i, int j, int[][] mem) { + if (i > j) + return 0; + if (mem[i][j] > 0) + return mem[i][j]; + + for (int k = i; k <= j; ++k) + mem[i][j] = Math.max(mem[i][j], // + maxCoins(nums, i, k - 1, mem) + // + maxCoins(nums, k + 1, j, mem) + // + nums[i - 1] * nums[k] * nums[j + 1]); + + return mem[i][j]; + } +} diff --git a/solutions/312. Burst Balloons/312.py b/solutions/312. Burst Balloons/312.py new file mode 100644 index 00000000000..57db7a9cf8c --- /dev/null +++ b/solutions/312. Burst Balloons/312.py @@ -0,0 +1,16 @@ +class Solution: + def maxCoins(self, nums: List[int]) -> int: + n = len(nums) + nums = [1] + nums + [1] + + @functools.lru_cache(None) + def dp(i: int, j: int) -> int: + """Returns maxCoins(nums[i..j]).""" + if i > j: + return 0 + return max(dp(i, k - 1) + + dp(k + 1, j) + + nums[i - 1] * nums[k] * nums[j + 1] + for k in range(i, j + 1)) + + return dp(1, n) diff --git a/solutions/3120. Count the Number of Special Characters I/3120.cpp b/solutions/3120. Count the Number of Special Characters I/3120.cpp new file mode 100644 index 00000000000..ea88886d414 --- /dev/null +++ b/solutions/3120. Count the Number of Special Characters I/3120.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int numberOfSpecialChars(string word) { + int ans = 0; + vector lower(26); + vector upper(26); + + for (const char c : word) + if (islower(c)) + lower[c - 'a'] = true; + else + upper[c - 'A'] = true; + + for (int i = 0; i < 26; ++i) + if (lower[i] && upper[i]) + ++ans; + + return ans; + } +}; diff --git a/solutions/3120. Count the Number of Special Characters I/3120.java b/solutions/3120. Count the Number of Special Characters I/3120.java new file mode 100644 index 00000000000..b2ce8127113 --- /dev/null +++ b/solutions/3120. Count the Number of Special Characters I/3120.java @@ -0,0 +1,19 @@ +class Solution { + public int numberOfSpecialChars(String word) { + int ans = 0; + boolean[] lower = new boolean[26]; + boolean[] upper = new boolean[26]; + + for (final char c : word.toCharArray()) + if (Character.isLowerCase(c)) + lower[c - 'a'] = true; + else + upper[c - 'A'] = true; + + for (int i = 0; i < 26; ++i) + if (lower[i] && upper[i]) + ++ans; + + return ans; + } +} diff --git a/solutions/3120. Count the Number of Special Characters I/3120.py b/solutions/3120. Count the Number of Special Characters I/3120.py new file mode 100644 index 00000000000..5dc2e43482c --- /dev/null +++ b/solutions/3120. Count the Number of Special Characters I/3120.py @@ -0,0 +1,14 @@ +class Solution: + def numberOfSpecialChars(self, word: str) -> int: + lower = collections.defaultdict(bool) + upper = collections.defaultdict(bool) + + for c in word: + if c.islower(): + lower[c] = True + else: + upper[c] = True + + return sum(lower[a] and upper[b] + for a, b in zip(string.ascii_lowercase, + string.ascii_uppercase)) diff --git a/solutions/3121. Count the Number of Special Characters II/3121.cpp b/solutions/3121. Count the Number of Special Characters II/3121.cpp new file mode 100644 index 00000000000..534bd2a5f9b --- /dev/null +++ b/solutions/3121. Count the Number of Special Characters II/3121.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int numberOfSpecialChars(string word) { + int ans = 0; + vector lower(26); + vector upper(26); + + for (const char c : word) + if (islower(c)) + lower[c - 'a'] = !upper[c - 'a']; + else + upper[c - 'A'] = true; + + for (int i = 0; i < 26; ++i) + if (lower[i] && upper[i]) + ++ans; + + return ans; + } +}; diff --git a/solutions/3121. Count the Number of Special Characters II/3121.java b/solutions/3121. Count the Number of Special Characters II/3121.java new file mode 100644 index 00000000000..04a85fc6d6b --- /dev/null +++ b/solutions/3121. Count the Number of Special Characters II/3121.java @@ -0,0 +1,19 @@ +class Solution { + public int numberOfSpecialChars(String word) { + int ans = 0; + boolean[] lower = new boolean[26]; + boolean[] upper = new boolean[26]; + + for (final char c : word.toCharArray()) + if (Character.isLowerCase(c)) + lower[c - 'a'] = !upper[c - 'a']; + else + upper[c - 'A'] = true; + + for (int i = 0; i < 26; ++i) + if (lower[i] && upper[i]) + ++ans; + + return ans; + } +} diff --git a/solutions/3121. Count the Number of Special Characters II/3121.py b/solutions/3121. Count the Number of Special Characters II/3121.py new file mode 100644 index 00000000000..546c3efeab7 --- /dev/null +++ b/solutions/3121. Count the Number of Special Characters II/3121.py @@ -0,0 +1,14 @@ +class Solution: + def numberOfSpecialChars(self, word: str) -> int: + lower = collections.defaultdict(bool) + upper = collections.defaultdict(bool) + + for c in word: + if c.islower(): + lower[c] = not upper[c.upper()] + else: + upper[c] = True + + return sum(lower[a] and upper[b] + for a, b in zip(string.ascii_lowercase, + string.ascii_uppercase)) diff --git a/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.cpp b/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.cpp new file mode 100644 index 00000000000..9ce2133f32e --- /dev/null +++ b/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int minimumOperations(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + vector> count(n, vector(10)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + ++count[j][grid[i][j]]; + + vector> mem(n, vector(10, -1)); + return minimumOperations(count, 0, 0, m, mem); + } + + private: + // Returns the number of minimum operations needed to make grid[:][j..n) + // satisfy the conditions, where the (j - 1)-th column is filled with `prev`. + int minimumOperations(const vector>& count, int j, int prev, + int m, vector>& mem) { + if (j == count.size()) + return 0; + if (mem[j][prev] != -1) + return mem[j][prev]; + + int res = INT_MAX; + + for (int num = 0; num < 10; ++num) + if (j == 0 || num != prev) + res = min(res, m - count[j][num] + + minimumOperations(count, j + 1, num, m, mem)); + + return mem[j][prev] = res; + } +}; diff --git a/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.java b/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.java new file mode 100644 index 00000000000..1c2de0ced7b --- /dev/null +++ b/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.java @@ -0,0 +1,31 @@ +class Solution { + public int minimumOperations(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int[][] count = new int[n][10]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + ++count[j][grid[i][j]]; + + Integer[][] mem = new Integer[n][10]; + return minimumOperations(count, 0, 0, m, mem); + } + + // Returns the number of minimum operations needed to make grid[:][j..n) + // satisfy the conditions, where the (j - 1)-th column is filled with `prev`. + private int minimumOperations(int[][] count, int j, int prev, int m, Integer[][] mem) { + if (j == count.length) + return 0; + if (mem[j][prev] != null) + return mem[j][prev]; + + int res = Integer.MAX_VALUE; + + for (int num = 0; num < 10; ++num) + if (j == 0 || num != prev) + res = Math.min(res, m - count[j][num] + minimumOperations(count, j + 1, num, m, mem)); + + return mem[j][prev] = res; + } +} diff --git a/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.py b/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.py new file mode 100644 index 00000000000..3be44ba02ed --- /dev/null +++ b/solutions/3122. Minimum Number of Operations to Satisfy Conditions/3122.py @@ -0,0 +1,28 @@ +class Solution: + def minimumOperations(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + count = [[0] * 10 for _ in range(n)] + + for row in grid: + for j, num in enumerate(row): + count[j][num] += 1 + + @functools.lru_cache(None) + def dp(i: int, prev: int) -> int: + """ + Returns the number of minimum operations needed to make grid[:][j..n) + satisfy the conditions, where the (j - 1)-th column is filled with `prev`. + """ + if i == n: + return 0 + + res = math.inf + + for num in range(10): + if i == 0 or num != prev: + res = min(res, m - count[i][num] + dp(i + 1, num)) + + return res + + return dp(0, 0) diff --git a/solutions/3123. Find Edges in Shortest Paths/3123.cpp b/solutions/3123. Find Edges in Shortest Paths/3123.cpp new file mode 100644 index 00000000000..c592d91cab2 --- /dev/null +++ b/solutions/3123. Find Edges in Shortest Paths/3123.cpp @@ -0,0 +1,55 @@ +class Solution { + public: + // Similar to 2203. Minimum Weighted Subgraph With the Required Paths + vector findAnswer(int n, vector>& edges) { + vector ans; + vector>> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + graph[u].emplace_back(v, w); + graph[v].emplace_back(u, w); + } + + const vector from0 = dijkstra(graph, 0); + const vector from1 = dijkstra(graph, n - 1); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int w = edge[2]; + ans.push_back(from0[u] + w + from1[v] == from0[n - 1] || + from0[v] + w + from1[u] == from0[n - 1]); + } + + return ans; + } + + private: + static constexpr int kMax = 1'000'000'000; + + vector dijkstra(const vector>>& graph, int src) { + vector dist(graph.size(), kMax); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + } + + return dist; + } +}; diff --git a/solutions/3123. Find Edges in Shortest Paths/3123.java b/solutions/3123. Find Edges in Shortest Paths/3123.java new file mode 100644 index 00000000000..d67d8c2d737 --- /dev/null +++ b/solutions/3123. Find Edges in Shortest Paths/3123.java @@ -0,0 +1,60 @@ +class Solution { + // Similar to 2203. Minimum Weighted Subgraph With the Required Paths + public boolean[] findAnswer(int n, int[][] edges) { + boolean[] ans = new boolean[edges.length]; + List>[] graph = new List[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int w = edge[2]; + graph[u].add(new Pair<>(v, w)); + graph[v].add(new Pair<>(u, w)); + } + + int[] from0 = dijkstra(graph, 0); + int[] from1 = dijkstra(graph, n - 1); + + for (int i = 0; i < edges.length; ++i) { + final int u = edges[i][0]; + final int v = edges[i][1]; + final int w = edges[i][2]; + ans[i] = from0[u] + w + from1[v] == from0[n - 1] || // + from0[v] + w + from1[u] == from0[n - 1]; + } + + return ans; + } + + private static int kMax = 1_000_000_000; + + private int[] dijkstra(List>[] graph, int src) { + int[] dist = new int[graph.length]; + Arrays.fill(dist, kMax); + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + return dist; + } +}; diff --git a/solutions/3123. Find Edges in Shortest Paths/3123.py b/solutions/3123. Find Edges in Shortest Paths/3123.py new file mode 100644 index 00000000000..961c82b6986 --- /dev/null +++ b/solutions/3123. Find Edges in Shortest Paths/3123.py @@ -0,0 +1,31 @@ +class Solution: + # Similar to 2203. Minimum Weighted Subgraph With the Required Paths + def findAnswer(self, n: int, edges: List[List[int]]) -> List[bool]: + graph = [[] for _ in range(n)] + + for u, v, w in edges: + graph[u].append((v, w)) + graph[v].append((u, w)) + + from0 = self._dijkstra(graph, 0) + from1 = self._dijkstra(graph, n - 1) + return [from0[u] + w + from1[v] == from0[-1] or + from0[v] + w + from1[u] == from0[-1] + for u, v, w in edges] + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> List[int]: + dist = [10**9] * len(graph) + + dist[src] = 0 + minHeap = [(dist[src], src)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + + return dist diff --git a/solutions/3124. Find Longest Calls/3124.sql b/solutions/3124. Find Longest Calls/3124.sql new file mode 100644 index 00000000000..abe1318510a --- /dev/null +++ b/solutions/3124. Find Longest Calls/3124.sql @@ -0,0 +1,25 @@ +WITH + RankedCalls AS ( + SELECT + Contacts.first_name, + Calls.type, + Calls.duration, + RANK() OVER( + PARTITION BY type + ORDER BY duration DESC + ) AS `rank` + FROM Calls + INNER JOIN Contacts + ON (Calls.contact_id = Contacts.id) + ) +SELECT + first_name, + type, + CONCAT( + LPAD(FLOOR(duration / 3600), 2, '0'), ':', + LPAD(FLOOR((duration % 3600) / 60), 2, '0'), ':', + LPAD(FLOOR(duration % 60), 2, '0') + ) AS duration_formatted +FROM RankedCalls +WHERE `rank` <= 3 +ORDER BY type, duration DESC, first_name DESC; diff --git a/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.cpp b/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.cpp new file mode 100644 index 00000000000..72dff87b827 --- /dev/null +++ b/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + long long maxNumber(long long n) { + // assume n = 0b00...11??? + // x = 0b00...01111 + // since y = 0b00...10000 is in [x, n] + // and x & y = 0 + const int i = 63 - __builtin_clzll(n); + return (1L << i) - 1; + } +}; diff --git a/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.java b/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.java new file mode 100644 index 00000000000..f5a0da64ff0 --- /dev/null +++ b/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.java @@ -0,0 +1,10 @@ +class Solution { + public long maxNumber(long n) { + // assume n = 0b00...11??? + // x = 0b00...01111 + // since y = 0b00...10000 is in [x, n] + // and x & y = 0 + final int i = 63 - Long.numberOfLeadingZeros(n); + return (1L << i) - 1; + } +} diff --git a/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.py b/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.py new file mode 100644 index 00000000000..612113d91c8 --- /dev/null +++ b/solutions/3125. Maximum Number That Makes Result of Bitwise AND Zero/3125.py @@ -0,0 +1,7 @@ +class Solution: + def maxNumber(self, n: int) -> int: + # assume n = 0b00...11??? + # x = 0b00...01111 + # since y = 0b00...10000 is in [x, n] + # and x & y = 0 + return (1 << n.bit_length() - 1) - 1 diff --git a/solutions/3126. Server Utilization Time/3126.sql b/solutions/3126. Server Utilization Time/3126.sql new file mode 100644 index 00000000000..3d23a60a835 --- /dev/null +++ b/solutions/3126. Server Utilization Time/3126.sql @@ -0,0 +1,19 @@ +WITH + ServerNeighbors AS ( + SELECT + status_time, + session_status, + LEAD(status_time) OVER( + PARTITION BY server_id + ORDER BY status_time + ) AS next_status_time + FROM Servers + ) +SELECT + FLOOR( + SUM( + TIMESTAMPDIFF(SECOND, status_time, next_status_time) + ) / 86400 + ) AS total_uptime_days +FROM ServerNeighbors +WHERE ServerNeighbors.session_status = 'start'; diff --git a/solutions/3127. Make a Square with the Same Color/3127.cpp b/solutions/3127. Make a Square with the Same Color/3127.cpp new file mode 100644 index 00000000000..adc5f590a3b --- /dev/null +++ b/solutions/3127. Make a Square with the Same Color/3127.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool canMakeSquare(vector>& grid) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 2; ++j) { + int black = 0; + int white = 0; + for (int x = 0; x < 2; ++x) + for (int y = 0; y < 2; ++y) + if (grid[i + x][j + y] == 'B') + ++black; + else + ++white; + if (black >= 3 || white >= 3) + return true; + } + return false; + } +}; diff --git a/solutions/3127. Make a Square with the Same Color/3127.java b/solutions/3127. Make a Square with the Same Color/3127.java new file mode 100644 index 00000000000..3fa73446d7b --- /dev/null +++ b/solutions/3127. Make a Square with the Same Color/3127.java @@ -0,0 +1,18 @@ +class Solution { + public boolean canMakeSquare(char[][] grid) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 2; ++j) { + int black = 0; + int white = 0; + for (int x = 0; x < 2; ++x) + for (int y = 0; y < 2; ++y) + if (grid[i + x][j + y] == 'B') + ++black; + else + ++white; + if (black >= 3 || white >= 3) + return true; + } + return false; + } +} diff --git a/solutions/3127. Make a Square with the Same Color/3127.py b/solutions/3127. Make a Square with the Same Color/3127.py new file mode 100644 index 00000000000..7f8a643683d --- /dev/null +++ b/solutions/3127. Make a Square with the Same Color/3127.py @@ -0,0 +1,15 @@ +class Solution: + def canMakeSquare(self, grid: List[List[str]]) -> bool: + for i in range(2): + for j in range(2): + black = 0 + white = 0 + for x in range(2): + for y in range(2): + if grid[i + x][j + y] == 'B': + black += 1 + else: + white += 1 + if black >= 3 or white >= 3: + return True + return False diff --git a/solutions/3128. Right Triangles/3128.cpp b/solutions/3128. Right Triangles/3128.cpp new file mode 100644 index 00000000000..c2da2e6d843 --- /dev/null +++ b/solutions/3128. Right Triangles/3128.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + long long numberOfRightTriangles(vector>& grid) { + long count = 0; + const int m = grid.size(); + const int n = grid[0].size(); + vector rows(m); + vector cols(n); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + ++rows[i]; + ++cols[j]; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + count += (rows[i] - 1) * (cols[j] - 1); + + return count; + } +}; diff --git a/solutions/3128. Right Triangles/3128.java b/solutions/3128. Right Triangles/3128.java new file mode 100644 index 00000000000..a0c388aa8dc --- /dev/null +++ b/solutions/3128. Right Triangles/3128.java @@ -0,0 +1,23 @@ +class Solution { + public long numberOfRightTriangles(int[][] grid) { + long count = 0; + final int m = grid.length; + final int n = grid[0].length; + int[] rows = new int[m]; + int[] cols = new int[n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + ++rows[i]; + ++cols[j]; + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + count += (rows[i] - 1) * (cols[j] - 1); + + return count; + } +} diff --git a/solutions/3128. Right Triangles/3128.py b/solutions/3128. Right Triangles/3128.py new file mode 100644 index 00000000000..e283ef747e9 --- /dev/null +++ b/solutions/3128. Right Triangles/3128.py @@ -0,0 +1,15 @@ +class Solution: + def numberOfRightTriangles(self, grid: List[List[int]]) -> int: + rows = [0] * len(grid) + cols = [0] * len(grid[0]) + + for i, row in enumerate(grid): + for j, num in enumerate(row): + if num == 1: + rows[i] += 1 + cols[j] += 1 + + return sum((rows[i] - 1) * (cols[j] - 1) + for i, row in enumerate(grid) + for j, num in enumerate(row) + if num == 1) diff --git a/solutions/3129. Find All Possible Stable Binary Arrays I/3129.cpp b/solutions/3129. Find All Possible Stable Binary Arrays I/3129.cpp new file mode 100644 index 00000000000..fc95f431c8c --- /dev/null +++ b/solutions/3129. Find All Possible Stable Binary Arrays I/3129.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + // Same as 3129. Find All Possible Stable Binary Arrays I + int numberOfStableArrays(int zero, int one, int limit) { + constexpr int kMod = 1'000'000'007; + // dp[i][j][k] := the number of stable arrays, where the number of + // ocurrences of 0 is i and the number of ocurrences of 1 is j and the last + // number is k (0/1) + vector>> dp( + zero + 1, vector>(one + 1, vector(2))); + + for (int i = 0; i <= min(zero, limit); ++i) + dp[i][0][0] = 1; + + for (int j = 0; j <= min(one, limit); ++j) + dp[0][j][1] = 1; + + for (int i = 1; i <= zero; ++i) + for (int j = 1; j <= one; ++j) { + dp[i][j][0] = (dp[i - 1][j][0] + dp[i - 1][j][1] - + (i - limit < 1 ? 0 : dp[i - limit - 1][j][1]) + kMod) % + kMod; + dp[i][j][1] = (dp[i][j - 1][0] + dp[i][j - 1][1] - + (j - limit < 1 ? 0 : dp[i][j - limit - 1][0]) + kMod) % + kMod; + } + + return (dp[zero][one][0] + dp[zero][one][1]) % kMod; + } +}; diff --git a/solutions/3129. Find All Possible Stable Binary Arrays I/3129.java b/solutions/3129. Find All Possible Stable Binary Arrays I/3129.java new file mode 100644 index 00000000000..b66101757d8 --- /dev/null +++ b/solutions/3129. Find All Possible Stable Binary Arrays I/3129.java @@ -0,0 +1,28 @@ +class Solution { + // Same as 3129. Find All Possible Stable Binary Arrays I + public int numberOfStableArrays(int zero, int one, int limit) { + final int kMod = 1_000_000_007; + // dp[i][j][k] := the number of stable arrays, where the number of + // occurrences of 0 is i and the number of occurrences of 1 is j and the last + // number is k (0/1) + long[][][] dp = new long[zero + 1][one + 1][2]; + + for (int i = 0; i <= Math.min(zero, limit); ++i) + dp[i][0][0] = 1; + + for (int j = 0; j <= Math.min(one, limit); ++j) + dp[0][j][1] = 1; + + for (int i = 1; i <= zero; ++i) + for (int j = 1; j <= one; ++j) { + dp[i][j][0] = (dp[i - 1][j][0] + dp[i - 1][j][1] - + (i - limit < 1 ? 0 : dp[i - limit - 1][j][1]) + kMod) % + kMod; + dp[i][j][1] = (dp[i][j - 1][0] + dp[i][j - 1][1] - + (j - limit < 1 ? 0 : dp[i][j - limit - 1][0]) + kMod) % + kMod; + } + + return (int) ((dp[zero][one][0] + dp[zero][one][1]) % kMod); + } +} diff --git a/solutions/3129. Find All Possible Stable Binary Arrays I/3129.py b/solutions/3129. Find All Possible Stable Binary Arrays I/3129.py new file mode 100644 index 00000000000..79f4e4120e3 --- /dev/null +++ b/solutions/3129. Find All Possible Stable Binary Arrays I/3129.py @@ -0,0 +1,25 @@ +class Solution: + # Same as 3129. Find All Possible Stable Binary Arrays I + def numberOfStableArrays(self, zero: int, one: int, limit: int) -> int: + kMod = 1_000_000_007 + # dp[i][j][k] := the number of stable arrays, where the number of + # occurrences of 0 is i and the number of occurrences of 1 is j and the last + # number is k (0/1) + dp = [[[0] * 2 + for _ in range(one + 1)] + for _ in range(zero + 1)] + + for i in range(min(zero, limit) + 1): + dp[i][0][0] = 1 + + for j in range(min(one, limit) + 1): + dp[0][j][1] = 1 + + for i in range(1, zero + 1): + for j in range(1, one + 1): + dp[i][j][0] = (dp[i - 1][j][0] + dp[i - 1][j][1] - + (dp[i - limit - 1][j][1] if i - limit >= 1 else 0) + kMod) % kMod + dp[i][j][1] = (dp[i][j - 1][0] + dp[i][j - 1][1] - + (dp[i][j - limit - 1][0] if j - limit >= 1 else 0) + kMod) % kMod + + return (dp[zero][one][0] + dp[zero][one][1]) % kMod diff --git a/solutions/313. Super Ugly Number/313-2.cpp b/solutions/313. Super Ugly Number/313-2.cpp new file mode 100644 index 00000000000..1f038d6c298 --- /dev/null +++ b/solutions/313. Super Ugly Number/313-2.cpp @@ -0,0 +1,34 @@ +struct UglyNum { + int prime; + int index; // the next index in `uglyNums` + long value; // prime * uglyNums[index] + UglyNum(int prime, int index, long value) + : prime(prime), index(index), value(value) {} +}; + +class Solution { + public: + int nthSuperUglyNumber(int n, vector& primes) { + auto compare = [&](const UglyNum& a, const UglyNum& b) { + return a.value > b.value; + }; + priority_queue, decltype(compare)> minHeap( + compare); + vector uglyNums{1}; + + for (const int prime : primes) + minHeap.emplace(prime, 1, prime * uglyNums[0]); + + while (uglyNums.size() < n) { + uglyNums.push_back(minHeap.top().value); + while (minHeap.top().value == uglyNums.back()) { + const auto [prime, index, _] = minHeap.top(); + minHeap.pop(); + minHeap.emplace(prime, index + 1, + prime * static_cast(uglyNums[index])); + } + } + + return uglyNums.back(); + } +}; diff --git a/solutions/313. Super Ugly Number/313-2.java b/solutions/313. Super Ugly Number/313-2.java new file mode 100644 index 00000000000..25a766859af --- /dev/null +++ b/solutions/313. Super Ugly Number/313-2.java @@ -0,0 +1,31 @@ +class UglyNum { + public int prime; + public int index; // the next index in `uglyNums` + public int value; // prime * uglyNums[index] + public UglyNum(int prime, int index, int value) { + this.prime = prime; + this.index = index; + this.value = value; + } +} + +class Solution { + public int nthSuperUglyNumber(int n, int[] primes) { + Queue minHeap = new PriorityQueue<>((a, b) -> a.value - b.value); + int[] uglyNums = new int[n]; + uglyNums[0] = 1; + + for (final int prime : primes) + minHeap.offer(new UglyNum(prime, 1, prime * uglyNums[0])); + + for (int i = 1; i < n; ++i) { + uglyNums[i] = minHeap.peek().value; + while (minHeap.peek().value == uglyNums[i]) { + final UglyNum u = minHeap.poll(); + minHeap.offer(new UglyNum(u.prime, u.index + 1, u.prime * uglyNums[u.index])); + } + } + + return uglyNums[n - 1]; + } +} diff --git a/solutions/313. Super Ugly Number/313-2.py b/solutions/313. Super Ugly Number/313-2.py new file mode 100644 index 00000000000..cdfabac31ae --- /dev/null +++ b/solutions/313. Super Ugly Number/313-2.py @@ -0,0 +1,22 @@ +class UglyNum: + def __init__(self, prime: int, index: int, value: int): + self.prime = prime + self.index = index # Point the next index of uglyNums. + self.value = value # prime * uglyNums[index] + + +class Solution: + def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: + minHeap = [] # (value, prime, index) + uglyNums = [1] + + for prime in primes: + heapq.heappush(minHeap, (prime * uglyNums[0], prime, 1)) + + while len(uglyNums) < n: + uglyNums.append(minHeap[0][0]) + while minHeap[0][0] == uglyNums[-1]: + _, prime, index = heapq.heappop(minHeap) + heapq.heappush(minHeap, (prime * uglyNums[index], prime, index + 1)) + + return uglyNums[-1] diff --git a/solutions/313. Super Ugly Number/313.cpp b/solutions/313. Super Ugly Number/313.cpp new file mode 100644 index 00000000000..dc71e58281f --- /dev/null +++ b/solutions/313. Super Ugly Number/313.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int nthSuperUglyNumber(int n, vector& primes) { + const int k = primes.size(); + vector indices(k); + vector uglyNums{1}; + + while (uglyNums.size() < n) { + vector nexts(k); + for (int i = 0; i < k; ++i) + nexts[i] = uglyNums[indices[i]] * primes[i]; + const int next = ranges::min(nexts); + for (int i = 0; i < k; ++i) + if (next == nexts[i]) + ++indices[i]; + uglyNums.push_back(next); + } + + return uglyNums.back(); + } +}; diff --git a/solutions/313. Super Ugly Number/313.java b/solutions/313. Super Ugly Number/313.java new file mode 100644 index 00000000000..f8b0c857303 --- /dev/null +++ b/solutions/313. Super Ugly Number/313.java @@ -0,0 +1,21 @@ +class Solution { + public int nthSuperUglyNumber(int n, int[] primes) { + final int k = primes.length; + int[] indices = new int[k]; + int[] uglyNums = new int[n]; + uglyNums[0] = 1; + + for (int i = 1; i < n; ++i) { + int[] nexts = new int[k]; + for (int j = 0; j < k; ++j) + nexts[j] = uglyNums[indices[j]] * primes[j]; + final int next = Arrays.stream(nexts).min().getAsInt(); + for (int j = 0; j < k; ++j) + if (next == nexts[j]) + ++indices[j]; + uglyNums[i] = next; + } + + return uglyNums[n - 1]; + } +} diff --git a/solutions/313. Super Ugly Number/313.py b/solutions/313. Super Ugly Number/313.py new file mode 100644 index 00000000000..a9befe86af4 --- /dev/null +++ b/solutions/313. Super Ugly Number/313.py @@ -0,0 +1,17 @@ +class Solution: + def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: + k = len(primes) + nums = [1] + indices = [0] * k + + while len(nums) < n: + nexts = [0] * k + for i in range(k): + nexts[i] = nums[indices[i]] * primes[i] + next = min(nexts) + for i in range(k): + if next == nexts[i]: + indices[i] += 1 + nums.append(next) + + return nums[-1] diff --git a/solutions/3130. Find All Possible Stable Binary Arrays II/3130.cpp b/solutions/3130. Find All Possible Stable Binary Arrays II/3130.cpp new file mode 100644 index 00000000000..fc95f431c8c --- /dev/null +++ b/solutions/3130. Find All Possible Stable Binary Arrays II/3130.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + // Same as 3129. Find All Possible Stable Binary Arrays I + int numberOfStableArrays(int zero, int one, int limit) { + constexpr int kMod = 1'000'000'007; + // dp[i][j][k] := the number of stable arrays, where the number of + // ocurrences of 0 is i and the number of ocurrences of 1 is j and the last + // number is k (0/1) + vector>> dp( + zero + 1, vector>(one + 1, vector(2))); + + for (int i = 0; i <= min(zero, limit); ++i) + dp[i][0][0] = 1; + + for (int j = 0; j <= min(one, limit); ++j) + dp[0][j][1] = 1; + + for (int i = 1; i <= zero; ++i) + for (int j = 1; j <= one; ++j) { + dp[i][j][0] = (dp[i - 1][j][0] + dp[i - 1][j][1] - + (i - limit < 1 ? 0 : dp[i - limit - 1][j][1]) + kMod) % + kMod; + dp[i][j][1] = (dp[i][j - 1][0] + dp[i][j - 1][1] - + (j - limit < 1 ? 0 : dp[i][j - limit - 1][0]) + kMod) % + kMod; + } + + return (dp[zero][one][0] + dp[zero][one][1]) % kMod; + } +}; diff --git a/solutions/3130. Find All Possible Stable Binary Arrays II/3130.java b/solutions/3130. Find All Possible Stable Binary Arrays II/3130.java new file mode 100644 index 00000000000..b66101757d8 --- /dev/null +++ b/solutions/3130. Find All Possible Stable Binary Arrays II/3130.java @@ -0,0 +1,28 @@ +class Solution { + // Same as 3129. Find All Possible Stable Binary Arrays I + public int numberOfStableArrays(int zero, int one, int limit) { + final int kMod = 1_000_000_007; + // dp[i][j][k] := the number of stable arrays, where the number of + // occurrences of 0 is i and the number of occurrences of 1 is j and the last + // number is k (0/1) + long[][][] dp = new long[zero + 1][one + 1][2]; + + for (int i = 0; i <= Math.min(zero, limit); ++i) + dp[i][0][0] = 1; + + for (int j = 0; j <= Math.min(one, limit); ++j) + dp[0][j][1] = 1; + + for (int i = 1; i <= zero; ++i) + for (int j = 1; j <= one; ++j) { + dp[i][j][0] = (dp[i - 1][j][0] + dp[i - 1][j][1] - + (i - limit < 1 ? 0 : dp[i - limit - 1][j][1]) + kMod) % + kMod; + dp[i][j][1] = (dp[i][j - 1][0] + dp[i][j - 1][1] - + (j - limit < 1 ? 0 : dp[i][j - limit - 1][0]) + kMod) % + kMod; + } + + return (int) ((dp[zero][one][0] + dp[zero][one][1]) % kMod); + } +} diff --git a/solutions/3130. Find All Possible Stable Binary Arrays II/3130.py b/solutions/3130. Find All Possible Stable Binary Arrays II/3130.py new file mode 100644 index 00000000000..79f4e4120e3 --- /dev/null +++ b/solutions/3130. Find All Possible Stable Binary Arrays II/3130.py @@ -0,0 +1,25 @@ +class Solution: + # Same as 3129. Find All Possible Stable Binary Arrays I + def numberOfStableArrays(self, zero: int, one: int, limit: int) -> int: + kMod = 1_000_000_007 + # dp[i][j][k] := the number of stable arrays, where the number of + # occurrences of 0 is i and the number of occurrences of 1 is j and the last + # number is k (0/1) + dp = [[[0] * 2 + for _ in range(one + 1)] + for _ in range(zero + 1)] + + for i in range(min(zero, limit) + 1): + dp[i][0][0] = 1 + + for j in range(min(one, limit) + 1): + dp[0][j][1] = 1 + + for i in range(1, zero + 1): + for j in range(1, one + 1): + dp[i][j][0] = (dp[i - 1][j][0] + dp[i - 1][j][1] - + (dp[i - limit - 1][j][1] if i - limit >= 1 else 0) + kMod) % kMod + dp[i][j][1] = (dp[i][j - 1][0] + dp[i][j - 1][1] - + (dp[i][j - limit - 1][0] if j - limit >= 1 else 0) + kMod) % kMod + + return (dp[zero][one][0] + dp[zero][one][1]) % kMod diff --git a/solutions/3131. Find the Integer Added to Array I/3131.cpp b/solutions/3131. Find the Integer Added to Array I/3131.cpp new file mode 100644 index 00000000000..3a7a0bbfef7 --- /dev/null +++ b/solutions/3131. Find the Integer Added to Array I/3131.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int addedInteger(vector& nums1, vector& nums2) { + return ranges::min(nums2) - ranges::min(nums1); + } +}; diff --git a/solutions/3131. Find the Integer Added to Array I/3131.java b/solutions/3131. Find the Integer Added to Array I/3131.java new file mode 100644 index 00000000000..c905482bf0a --- /dev/null +++ b/solutions/3131. Find the Integer Added to Array I/3131.java @@ -0,0 +1,5 @@ +class Solution { + public int addedInteger(int[] nums1, int[] nums2) { + return Arrays.stream(nums2).min().getAsInt() - Arrays.stream(nums1).min().getAsInt(); + } +} diff --git a/solutions/3131. Find the Integer Added to Array I/3131.py b/solutions/3131. Find the Integer Added to Array I/3131.py new file mode 100644 index 00000000000..fda4f9fb8f5 --- /dev/null +++ b/solutions/3131. Find the Integer Added to Array I/3131.py @@ -0,0 +1,3 @@ +class Solution: + def addedInteger(self, nums1: List[int], nums2: List[int]) -> int: + return min(nums2) - min(nums1) diff --git a/solutions/3132. Find the Integer Added to Array II/3132.cpp b/solutions/3132. Find the Integer Added to Array II/3132.cpp new file mode 100644 index 00000000000..fa741382bb3 --- /dev/null +++ b/solutions/3132. Find the Integer Added to Array II/3132.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int minimumAddedInteger(vector& nums1, vector& nums2) { + // After removing two elements from nums1, either nums1[0], nums1[1], or + // nums1[2] will persist. Therefore, the difference between nums1 (with two + // elements removed) and nums2 is represented by nums2[0] - nums1[i], where + // 0 <= i <= 2. + int ans = INT_MAX; + + ranges::sort(nums1); + ranges::sort(nums2); + + for (int i = 0; i < 3; ++i) { + const int inc = nums2[0] - nums1[i]; + if (isValidDiff(nums1, nums2, inc)) + ans = min(ans, inc); + } + + return ans; + } + + private: + // Returns true if it's possible to increase nums1 (with two elements removed) + // by `inc` to nums2. + bool isValidDiff(const vector& nums1, const vector& nums2, + int inc) { + int removed = 0; + int i = 0; // nums2's index + + for (const int num : nums1) + if (num + inc == nums2[i]) { + if (++i == nums2.size()) + break; + } else { + ++removed; + } + + return removed <= 2; + } +}; diff --git a/solutions/3132. Find the Integer Added to Array II/3132.java b/solutions/3132. Find the Integer Added to Array II/3132.java new file mode 100644 index 00000000000..a7bd5b23a1c --- /dev/null +++ b/solutions/3132. Find the Integer Added to Array II/3132.java @@ -0,0 +1,37 @@ +class Solution { + public int minimumAddedInteger(int[] nums1, int[] nums2) { + // After removing two elements from nums1, either nums1[0], nums1[1], or + // nums1[2] will persist. Therefore, the difference between nums1 (with two + // elements removed) and nums2 is represented by nums2[0] - nums1[i], where + // 0 <= i <= 2. + int ans = Integer.MAX_VALUE; + + Arrays.sort(nums1); + Arrays.sort(nums2); + + for (int i = 0; i < 3; ++i) { + final int inc = nums2[0] - nums1[i]; + if (isValidDiff(nums1, nums2, inc)) + ans = Math.min(ans, inc); + } + + return ans; + } + + // Returns true if it's possible to increase nums1 (with two elements removed) + // by `inc` to nums2. + private boolean isValidDiff(int[] nums1, int[] nums2, int inc) { + int removed = 0; + int i = 0; // nums2's index + + for (final int num : nums1) + if (num + inc == nums2[i]) { + if (++i == nums2.length) + break; + } else { + ++removed; + } + + return removed <= 2; + } +} diff --git a/solutions/3132. Find the Integer Added to Array II/3132.py b/solutions/3132. Find the Integer Added to Array II/3132.py new file mode 100644 index 00000000000..a0d25199233 --- /dev/null +++ b/solutions/3132. Find the Integer Added to Array II/3132.py @@ -0,0 +1,35 @@ +class Solution: + def minimumAddedInteger(self, nums1: List[int], nums2: List[int]) -> int: + # After removing two elements from nums1, either nums1[0], nums1[1], or + # nums1[2] will persist. Therefore, the difference between nums1 (with two + # elements removed) and nums2 is represented by nums2[0] - nums1[i], where + # 0 <= i <= 2. + ans = math.inf + + nums1.sort() + nums2.sort() + + for i in range(3): + inc = nums2[0] - nums1[i] + if self._isValidDiff(nums1, nums2, inc): + ans = min(ans, inc) + + return ans + + def _isValidDiff(self, nums1: List[int], nums2: List[int], inc: int) -> bool: + """ + Returns True if it's possible to increase nums1 (with two elements removed) + by `inc` to nums2. + """ + removed = 0 + i = 0 # nums2's index + + for num in nums1: + if num + inc == nums2[i]: + i += 1 + if i == len(nums2): + break + else: + removed += 1 + + return removed <= 2 diff --git a/solutions/3133. Minimum Array End/3133.cpp b/solutions/3133. Minimum Array End/3133.cpp new file mode 100644 index 00000000000..e4a10121c09 --- /dev/null +++ b/solutions/3133. Minimum Array End/3133.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + long long minEnd(int n, int x) { + // Set x's 0s with (n - 1)'s LSb-to-MSb bits, preserving x's 1s. This + // operation increase x for (n - 1) iterations while preserving x's 1s. + const int kMaxBit = log2(n) + log2(x) + 2; + const long k = n - 1; + long ans = x; + int kBinaryIndex = 0; + + for (int i = 0; i < kMaxBit; ++i) { + if ((ans >> i & 1) == 0) { + // Set x's 0 with k's bit if the running bit of k is 1. + if (k >> kBinaryIndex & 1) + ans |= 1L << i; + ++kBinaryIndex; + } + } + + return ans; + } +}; diff --git a/solutions/3133. Minimum Array End/3133.java b/solutions/3133. Minimum Array End/3133.java new file mode 100644 index 00000000000..d94ab8e8554 --- /dev/null +++ b/solutions/3133. Minimum Array End/3133.java @@ -0,0 +1,25 @@ +class Solution { + public long minEnd(int n, int x) { + // Set x's 0s with (n - 1)'s LSb-to-MSb bits, preserving x's 1s. This + // operation increase x for (n - 1) iterations while preserving x's 1s. + final int kMaxBit = bitLength(n) + bitLength(x); + final long k = n - 1; + long ans = x; + int kBinaryIndex = 0; + + for (int i = 0; i < kMaxBit; ++i) { + if ((ans >> i & 1) == 0) { + // Set x's 0 with k's bit if the running bit of k is 1. + if ((k >> kBinaryIndex & 1) == 1) + ans |= 1L << i; + ++kBinaryIndex; + } + } + + return ans; + } + + private int bitLength(int n) { + return 32 - Integer.numberOfLeadingZeros(n); + } +} diff --git a/solutions/3133. Minimum Array End/3133.py b/solutions/3133. Minimum Array End/3133.py new file mode 100644 index 00000000000..9ac90fe7be8 --- /dev/null +++ b/solutions/3133. Minimum Array End/3133.py @@ -0,0 +1,16 @@ +class Solution: + def minEnd(self, n: int, x: int) -> int: + # Set x's 0s with (n - 1)'s LSb-to-MSb bits, preserving x's 1s. This + # operation increase x for (n - 1) iterations while preserving x's 1s. + kMaxBit = n.bit_length() + x.bit_length() + k = n - 1 + kBinaryIndex = 0 + + for i in range(kMaxBit): + if x >> i & 1 == 0: + # Set x's 0 with k's bit if the running bit of k is 1. + if k >> kBinaryIndex & 1: + x |= 1 << i + kBinaryIndex += 1 + + return x diff --git a/solutions/3134. Find the Median of the Uniqueness Array/3134.cpp b/solutions/3134. Find the Median of the Uniqueness Array/3134.cpp new file mode 100644 index 00000000000..b7b3738a5e5 --- /dev/null +++ b/solutions/3134. Find the Median of the Uniqueness Array/3134.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int medianOfUniquenessArray(vector& nums) { + const int n = nums.size(); + const long subarryCount = n * (n + 1L) / 2; + const long medianCount = (subarryCount + 1) / 2; + int l = 1; + int r = n; + + while (l < r) { + const int m = (l + r) / 2; + if (subarrayWithAtMostKDistinct(nums, m) >= medianCount) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Similar to 992. Subarrays with K Different Integers + long subarrayWithAtMostKDistinct(const vector& nums, int k) { + long res = 0; + unordered_map count; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (++count[nums[r]] == 1) + --k; + while (k == -1) + if (--count[nums[l++]] == 0) + ++k; + res += r - l + 1; // nums[l..r], nums[l + 1..r], ..., nums[r] + } + + return res; + } +}; diff --git a/solutions/3134. Find the Median of the Uniqueness Array/3134.java b/solutions/3134. Find the Median of the Uniqueness Array/3134.java new file mode 100644 index 00000000000..8e85c9b3473 --- /dev/null +++ b/solutions/3134. Find the Median of the Uniqueness Array/3134.java @@ -0,0 +1,36 @@ +class Solution { + public int medianOfUniquenessArray(int[] nums) { + final int n = nums.length; + final long subarrayCount = n * (n + 1L) / 2; + final long medianCount = (subarrayCount + 1) / 2; + int l = 1; + int r = n; + + while (l < r) { + final int m = (l + r) / 2; + if (subarrayWithAtMostKDistinct(nums, m) >= medianCount) + r = m; + else + l = m + 1; + } + + return l; + } + + // Similar to 992. Subarrays with K Different Integers + private long subarrayWithAtMostKDistinct(int[] nums, int k) { + long res = 0; + HashMap count = new HashMap<>(); + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (count.merge(nums[r], 1, Integer::sum) == 1) + --k; + while (k == -1) + if (count.merge(nums[l++], -1, Integer::sum) == 0) + ++k; + res += r - l + 1; // nums[l..r], nums[l + 1..r], ..., nums[r] + } + + return res; + } +} diff --git a/solutions/3134. Find the Median of the Uniqueness Array/3134.py b/solutions/3134. Find the Median of the Uniqueness Array/3134.py new file mode 100644 index 00000000000..4fdd2756b80 --- /dev/null +++ b/solutions/3134. Find the Median of the Uniqueness Array/3134.py @@ -0,0 +1,28 @@ +class Solution: + def medianOfUniquenessArray(self, nums: List[int]): + n = len(nums) + subarrayCount = n * (n + 1) // 2 + medianCount = (subarrayCount + 1) // 2 + + # Similar to 992. Subarrays with K Different Integers + def subarraysWithAtMostKDistinct(k: int) -> int: + res = 0 + count = collections.Counter() + + l = 0 + for r, num in enumerate(nums): + count[num] += 1 + if count[num] == 1: + k -= 1 + while k < 0: + count[nums[l]] -= 1 + if count[nums[l]] == 0: + k += 1 + l += 1 + res += r - l + 1 # nums[l..r], nums[l + 1..r], ..., nums[r] + + return res + + return bisect.bisect_left( + range(1, n), medianCount, + key=lambda m: subarraysWithAtMostKDistinct(m)) + 1 diff --git a/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.cpp b/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.cpp new file mode 100644 index 00000000000..18de095c34f --- /dev/null +++ b/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minOperations(string initial, string target) { + const int m = initial.length(); + const int n = target.length(); + // dp[i][j] := the length of LCS(initial[0..i), target[0..j)) + vector> dp(m + 1, vector(n + 1)); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (initial[i - 1] == target[j - 1]) + dp[i][j] = 1 + dp[i - 1][j - 1]; + + const int maxCommonLength = accumulate( + dp.begin(), dp.end(), 0, [](int subtotal, const vector& row) { + return max(subtotal, ranges::max(row)); + }); + return m + n - 2 * maxCommonLength; + } +}; diff --git a/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.java b/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.java new file mode 100644 index 00000000000..f0e23b4717f --- /dev/null +++ b/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.java @@ -0,0 +1,16 @@ +class Solution { + public int minOperations(String initial, String target) { + final int m = initial.length(); + final int n = target.length(); + // dp[i][j] := the length of LCS(initial[0..i), target[0..j)) + int[][] dp = new int[m + 1][n + 1]; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (initial.charAt(i - 1) == target.charAt(j - 1)) + dp[i][j] = 1 + dp[i - 1][j - 1]; + + final int maxCommonLength = Arrays.stream(dp).flatMapToInt(Arrays::stream).max().getAsInt(); + return m + n - 2 * maxCommonLength; + } +} diff --git a/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.py b/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.py new file mode 100644 index 00000000000..522f35e9a93 --- /dev/null +++ b/solutions/3135. Equalize Strings by Adding or Removing Characters at Ends/3135.py @@ -0,0 +1,13 @@ +class Solution: + def minOperations(self, initial: str, target: str) -> int: + m = len(initial) + n = len(target) + # dp[i][j] := the length of LCS(initial[0..i), target[0..j)) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(1, m + 1): + for j in range(1, n + 1): + if initial[i - 1] == target[j - 1]: + dp[i][j] = 1 + dp[i - 1][j - 1] + + return m + n - 2 * max(map(max, dp)) diff --git a/solutions/3136. Valid Word/3136.cpp b/solutions/3136. Valid Word/3136.cpp new file mode 100644 index 00000000000..f131768d9b5 --- /dev/null +++ b/solutions/3136. Valid Word/3136.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool isValid(string word) { + return word.length() >= 3 && + ranges::all_of(word, [](char c) { return isalnum(c); }) && + ranges::any_of(word, isVowel) && ranges::any_of(word, isConsonant); + } + + private: + static bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } + + static bool isConsonant(char c) { + return isalpha(c) && !isVowel(c); + } +}; diff --git a/solutions/3136. Valid Word/3136.java b/solutions/3136. Valid Word/3136.java new file mode 100644 index 00000000000..1443765b4b2 --- /dev/null +++ b/solutions/3136. Valid Word/3136.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isValid(String word) { + return word.length() >= 3 && word.chars().allMatch(Character::isLetterOrDigit) && + word.chars().anyMatch(c -> isVowel((char) c)) && + word.chars().anyMatch(c -> isConsonant((char) c)); + } + + private boolean isVowel(char c) { + return "aeiouAEIOU".indexOf(c) != -1; + } + + private boolean isConsonant(char c) { + return Character.isLetter(c) && !isVowel(c); + } +} diff --git a/solutions/3136. Valid Word/3136.py b/solutions/3136. Valid Word/3136.py new file mode 100644 index 00000000000..54a4546f83c --- /dev/null +++ b/solutions/3136. Valid Word/3136.py @@ -0,0 +1,11 @@ +class Solution: + def isValid(self, word: str) -> bool: + kVowels = 'aeiouAEIOU' + + def isConsonant(c: str) -> bool: + return c.isalpha() and c not in kVowels + + return len(word) >= 3 and \ + all(c.isalnum() for c in word) and \ + any(c in kVowels for c in word) and \ + any(isConsonant(c) for c in word) diff --git a/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.cpp b/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.cpp new file mode 100644 index 00000000000..6ab0c37a9f6 --- /dev/null +++ b/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minimumOperationsToMakeKPeriodic(string word, int k) { + unordered_map count; + int maxFreq = 0; + + for (int i = 0; i < word.length(); i += k) + ++count[word.substr(i, k)]; + + for (const auto& [_, freq] : count) + maxFreq = max(maxFreq, freq); + + return word.length() / k - maxFreq; + } +}; diff --git a/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.java b/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.java new file mode 100644 index 00000000000..96ec5c8ae98 --- /dev/null +++ b/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.java @@ -0,0 +1,11 @@ +class Solution { + public int minimumOperationsToMakeKPeriodic(String word, int k) { + Map count = new HashMap<>(); + + for (int i = 0; i < word.length(); i += k) + count.merge(word.substring(i, i + k), 1, Integer::sum); + + final int maxFreq = count.values().stream().max(Integer::compare).orElse(0); + return word.length() / k - maxFreq; + } +} diff --git a/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.py b/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.py new file mode 100644 index 00000000000..1e656bc69fb --- /dev/null +++ b/solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.py @@ -0,0 +1,4 @@ +class Solution: + def minimumOperationsToMakeKPeriodic(self, word: str, k: int) -> int: + count = collections.Counter(word[i:i + k] for i in range(0, len(word), k)) + return len(word) // k - max(count.values()) diff --git a/solutions/3138. Minimum Length of Anagram Concatenation/3138.cpp b/solutions/3138. Minimum Length of Anagram Concatenation/3138.cpp new file mode 100644 index 00000000000..3f3408d41a0 --- /dev/null +++ b/solutions/3138. Minimum Length of Anagram Concatenation/3138.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int minAnagramLength(string s) { + const int n = s.length(); + for (int k = 1; k <= n; ++k) + if (n % k == 0 && canFormAnagram(s, k)) + return k; + return n; + } + + private: + // Returns true if we can concatenate an anagram of length k to s. + bool canFormAnagram(const string& s, int k) { + const int n = s.length(); + vector anagramCount(26); + vector runningCount(26); + for (int i = 0; i < k; ++i) + ++anagramCount[s[i] - 'a']; + for (int i = k; i < n; ++i) { + ++runningCount[s[i] - 'a']; + if (i % k == k - 1) { + if (runningCount != anagramCount) + return false; + fill(runningCount.begin(), runningCount.end(), 0); + } + } + return true; + } +}; diff --git a/solutions/3138. Minimum Length of Anagram Concatenation/3138.java b/solutions/3138. Minimum Length of Anagram Concatenation/3138.java new file mode 100644 index 00000000000..0bc13f3f7ba --- /dev/null +++ b/solutions/3138. Minimum Length of Anagram Concatenation/3138.java @@ -0,0 +1,27 @@ +class Solution { + public int minAnagramLength(String s) { + final int n = s.length(); + for (int k = 1; k <= n; ++k) + if (n % k == 0 && canFormAnagram(s, k)) + return k; + return n; + } + + // Returns true if we can concatenate an anagram of length k to s. + private boolean canFormAnagram(String s, int k) { + final int n = s.length(); + int[] anagramCount = new int[26]; + int[] runningCount = new int[26]; + for (int i = 0; i < k; ++i) + ++anagramCount[s.charAt(i) - 'a']; + for (int i = k; i < n; ++i) { + ++runningCount[s.charAt(i) - 'a']; + if (i % k == k - 1) { + if (!Arrays.equals(runningCount, anagramCount)) + return false; + Arrays.fill(runningCount, 0); + } + } + return true; + } +} diff --git a/solutions/3138. Minimum Length of Anagram Concatenation/3138.py b/solutions/3138. Minimum Length of Anagram Concatenation/3138.py new file mode 100644 index 00000000000..e2dae0dddf9 --- /dev/null +++ b/solutions/3138. Minimum Length of Anagram Concatenation/3138.py @@ -0,0 +1,13 @@ +class Solution: + def minAnagramLength(self, s: str) -> int: + n = len(s) + for k in range(1, n + 1): + if n % k == 0 and self._canFormAnagram(s, k): + return k + return n + + def _canFormAnagram(self, s: str, k: int) -> bool: + """Returns True if we can concatenate an anagram of length k to s.""" + anagramCount = collections.Counter(s[:k]) + return all(collections.Counter(s[i:i + k]) == anagramCount + for i in range(k, len(s), k)) diff --git a/solutions/3139. Minimum Cost to Equalize Array/3139.cpp b/solutions/3139. Minimum Cost to Equalize Array/3139.cpp new file mode 100644 index 00000000000..4865e951edc --- /dev/null +++ b/solutions/3139. Minimum Cost to Equalize Array/3139.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minCostToEqualizeArray(vector& nums, int cost1, int cost2) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + const int minNum = ranges::min(nums); + const int maxNum = ranges::max(nums); + const long sum = accumulate(nums.begin(), nums.end(), 0L); + long ans = LONG_MAX; + + if (cost1 * 2 <= cost2 || n < 3) { + const long totalGap = static_cast(maxNum) * n - sum; + return (cost1 * totalGap) % kMod; + } + + for (int target = maxNum; target < 2 * maxNum; ++target) { + const int maxGap = target - minNum; + const long totalGap = static_cast(target) * n - sum; + const long pairs = min(totalGap / 2, totalGap - maxGap); + ans = min(ans, cost1 * (totalGap - 2 * pairs) + cost2 * pairs); + } + + return ans % kMod; + } +}; diff --git a/solutions/3139. Minimum Cost to Equalize Array/3139.java b/solutions/3139. Minimum Cost to Equalize Array/3139.java new file mode 100644 index 00000000000..6a44893c784 --- /dev/null +++ b/solutions/3139. Minimum Cost to Equalize Array/3139.java @@ -0,0 +1,24 @@ +class Solution { + public int minCostToEqualizeArray(int[] nums, int cost1, int cost2) { + final int kMod = 1_000_000_007; + final int n = nums.length; + final int minNum = Arrays.stream(nums).min().getAsInt(); + final int maxNum = Arrays.stream(nums).max().getAsInt(); + final long sum = Arrays.stream(nums).asLongStream().sum(); + long ans = Long.MAX_VALUE; + + if (cost1 * 2 <= cost2 || n < 3) { + final long totalGap = 1L * maxNum * n - sum; + return (int) ((cost1 * totalGap) % kMod); + } + + for (int target = maxNum; target < 2 * maxNum; ++target) { + final int maxGap = target - minNum; + final long totalGap = 1L * target * n - sum; + final long pairs = Math.min(totalGap / 2, totalGap - maxGap); + ans = Math.min(ans, cost1 * (totalGap - 2 * pairs) + cost2 * pairs); + } + + return (int) (ans % kMod); + } +} diff --git a/solutions/3139. Minimum Cost to Equalize Array/3139.py b/solutions/3139. Minimum Cost to Equalize Array/3139.py new file mode 100644 index 00000000000..f82b9477e3d --- /dev/null +++ b/solutions/3139. Minimum Cost to Equalize Array/3139.py @@ -0,0 +1,23 @@ +class Solution: + def minCostToEqualizeArray(self, nums: List[int], cost1: int, cost2: int) -> int: + kMod = 1_000_000_007 + n = len(nums) + minNum = min(nums) + maxNum = max(nums) + summ = sum(nums) + + if cost1 * 2 <= cost2 or n < 3: + totalGap = maxNum * n - summ + return (cost1 * totalGap) % kMod + + def getMinCost(target: int) -> int: + """Returns the minimum cost to make all numbers equal to `target`.""" + maxGap = target - minNum + totalGap = target * n - summ + # Pair one shallowest number with one non-shallowest number, so the worst + # case is that we have `totalGap - maxGap` non-shallowest numbers to pair. + pairs = min(totalGap // 2, totalGap - maxGap) + return cost1 * (totalGap - 2 * pairs) + cost2 * pairs + + return min(getMinCost(target) + for target in range(maxNum, 2 * maxNum)) % kMod diff --git a/solutions/314. Binary Tree Vertical Order Traversal/314.cpp b/solutions/314. Binary Tree Vertical Order Traversal/314.cpp new file mode 100644 index 00000000000..466ab6582ef --- /dev/null +++ b/solutions/314. Binary Tree Vertical Order Traversal/314.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + vector> verticalOrder(TreeNode* root) { + if (root == nullptr) + return {}; + + vector range(2); + getRange(root, range, 0); // Get the leftmost and the rightmost x index. + + vector> ans(range[1] - range[0] + 1); + queue> q{{{root, -range[0]}}}; // (TreeNode, x) + + while (!q.empty()) { + const auto [node, x] = q.front(); + q.pop(); + ans[x].push_back(node->val); + if (node->left) + q.emplace(node->left, x - 1); + if (node->right) + q.emplace(node->right, x + 1); + } + + return ans; + } + + private: + void getRange(TreeNode* root, vector& range, int x) { + if (root == nullptr) + return; + + range[0] = min(range[0], x); + range[1] = max(range[1], x); + + getRange(root->left, range, x - 1); + getRange(root->right, range, x + 1); + } +}; diff --git a/solutions/314. Binary Tree Vertical Order Traversal/314.java b/solutions/314. Binary Tree Vertical Order Traversal/314.java new file mode 100644 index 00000000000..c78431d563d --- /dev/null +++ b/solutions/314. Binary Tree Vertical Order Traversal/314.java @@ -0,0 +1,39 @@ +class Solution { + public List> verticalOrder(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + Queue> q = new ArrayDeque<>(); // (TreeNode, x) + int[] range = new int[2]; + getRange(root, range, 0); // Get the leftmost and the rightmost x index. + + for (int i = range[0]; i <= range[1]; ++i) + ans.add(new ArrayList<>()); + + q.offer(new Pair<>(root, -range[0])); + + while (!q.isEmpty()) { + final TreeNode node = q.peek().getKey(); + final int x = q.poll().getValue(); + ans.get(x).add(node.val); + if (node.left != null) + q.offer(new Pair<>(node.left, x - 1)); + if (node.right != null) + q.offer(new Pair<>(node.right, x + 1)); + } + + return ans; + } + + private void getRange(TreeNode root, int[] range, int x) { + if (root == null) + return; + + range[0] = Math.min(range[0], x); + range[1] = Math.max(range[1], x); + + getRange(root.left, range, x - 1); + getRange(root.right, range, x + 1); + } +} diff --git a/solutions/314. Binary Tree Vertical Order Traversal/314.py b/solutions/314. Binary Tree Vertical Order Traversal/314.py new file mode 100644 index 00000000000..d21a919018a --- /dev/null +++ b/solutions/314. Binary Tree Vertical Order Traversal/314.py @@ -0,0 +1,31 @@ +class Solution: + def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: + return [] + + range_ = [0] * 2 + + def getRange(root: Optional[TreeNode], x: int) -> None: + if not root: + return + + range_[0] = min(range_[0], x) + range_[1] = max(range_[1], x) + + getRange(root.left, x - 1) + getRange(root.right, x + 1) + + getRange(root, 0) # Get the leftmost and the rightmost x index. + + ans = [[] for _ in range(range_[1] - range_[0] + 1)] + q = collections.deque([(root, -range_[0])]) # (TreeNode, x) + + while q: + node, x = q.popleft() + ans[x].append(node.val) + if node.left: + q.append((node.left, x - 1)) + if node.right: + q.append((node.right, x + 1)) + + return ans diff --git a/solutions/3140. Consecutive Available Seats II/3140.sql b/solutions/3140. Consecutive Available Seats II/3140.sql new file mode 100644 index 00000000000..a2407e31901 --- /dev/null +++ b/solutions/3140. Consecutive Available Seats II/3140.sql @@ -0,0 +1,21 @@ +WITH + FreeSeats AS ( + SELECT + *, + seat_id - ROW_NUMBER() OVER(ORDER BY seat_id) AS group_id + FROM Cinema + WHERE free = 1 + ), + RankedFreeSeats AS ( + SELECT + MIN(seat_id) AS first_seat_id, + MAX(seat_id) AS last_seat_id, + COUNT(*) AS consecutive_seats_len, + RANK() OVER(ORDER BY COUNT(*) DESC) AS `rank` + FROM FreeSeats + GROUP BY group_id + ) +SELECT first_seat_id, last_seat_id, consecutive_seats_len +FROM RankedFreeSeats +WHERE `rank` = 1 +ORDER BY 1; diff --git a/solutions/3141. Maximum Hamming Distances/3141.cpp b/solutions/3141. Maximum Hamming Distances/3141.cpp new file mode 100644 index 00000000000..2cf4fe92d4d --- /dev/null +++ b/solutions/3141. Maximum Hamming Distances/3141.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector maxHammingDistances(vector& nums, int m) { + const int kMaxMask = 1 << m; + vector ans; + // dp[i] := the maximum hamming distance from i to any number in `nums` + vector dp(kMaxMask, INT_MIN); + + for (const int num : nums) + dp[num] = 0; + + for (int bit = 0; bit < m; ++bit) { + vector newDp(kMaxMask); + for (int mask = 0; mask < kMaxMask; ++mask) + newDp[mask] = max(dp[mask], dp[mask ^ (1 << bit)] + 1); + dp = move(newDp); + } + + for (const int num : nums) + ans.push_back(dp[num]); + + return ans; + } +}; diff --git a/solutions/3141. Maximum Hamming Distances/3141.java b/solutions/3141. Maximum Hamming Distances/3141.java new file mode 100644 index 00000000000..9c393a9180e --- /dev/null +++ b/solutions/3141. Maximum Hamming Distances/3141.java @@ -0,0 +1,24 @@ +class Solution { + public int[] maxHammingDistances(int[] nums, int m) { + final int kMaxMask = 1 << m; + int[] ans = new int[nums.length]; + // dp[i] := the maximum hamming distance from i to any number in `nums` + int[] dp = new int[kMaxMask]; + Arrays.fill(dp, Integer.MIN_VALUE); + + for (final int num : nums) + dp[num] = 0; + + for (int bit = 0; bit < m; ++bit) { + int[] newDp = new int[kMaxMask]; + for (int mask = 0; mask < kMaxMask; ++mask) + newDp[mask] = Math.max(dp[mask], dp[mask ^ (1 << bit)] + 1); + dp = newDp; + } + + for (int i = 0; i < nums.length; ++i) + ans[i] = dp[nums[i]]; + + return ans; + } +} diff --git a/solutions/3141. Maximum Hamming Distances/3141.py b/solutions/3141. Maximum Hamming Distances/3141.py new file mode 100644 index 00000000000..6ef4590bdbc --- /dev/null +++ b/solutions/3141. Maximum Hamming Distances/3141.py @@ -0,0 +1,16 @@ +class Solution: + def maxHammingDistances(self, nums: List[int], m: int) -> List[int]: + kMaxMask = 1 << m + # dp[i] := the maximum hamming distance from i to any number in `nums` + dp = [-math.inf] * kMaxMask + + for num in nums: + dp[num] = 0 + + for bit in range(m): + newDp = [0] * kMaxMask + for mask in range(kMaxMask): + newDp[mask] = max(dp[mask], dp[mask ^ (1 << bit)] + 1) + dp = newDp + + return [dp[num] for num in nums] diff --git a/solutions/3142. Check if Grid Satisfies Conditions/3142.cpp b/solutions/3142. Check if Grid Satisfies Conditions/3142.cpp new file mode 100644 index 00000000000..a9c9571ec9b --- /dev/null +++ b/solutions/3142. Check if Grid Satisfies Conditions/3142.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool satisfiesConditions(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + + for (int i = 0; i + 1 < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] != grid[i + 1][j]) + return false; + + for (int i = 0; i < m; ++i) + for (int j = 0; j + 1 < n; ++j) + if (grid[i][j] == grid[i][j + 1]) + return false; + + return true; + } +}; diff --git a/solutions/3142. Check if Grid Satisfies Conditions/3142.java b/solutions/3142. Check if Grid Satisfies Conditions/3142.java new file mode 100644 index 00000000000..a742f65d845 --- /dev/null +++ b/solutions/3142. Check if Grid Satisfies Conditions/3142.java @@ -0,0 +1,18 @@ +class Solution { + public boolean satisfiesConditions(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + + for (int i = 0; i + 1 < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] != grid[i + 1][j]) + return false; + + for (int i = 0; i < m; ++i) + for (int j = 0; j + 1 < n; ++j) + if (grid[i][j] == grid[i][j + 1]) + return false; + + return true; + } +}; diff --git a/solutions/3142. Check if Grid Satisfies Conditions/3142.py b/solutions/3142. Check if Grid Satisfies Conditions/3142.py new file mode 100644 index 00000000000..b3ff7c219a9 --- /dev/null +++ b/solutions/3142. Check if Grid Satisfies Conditions/3142.py @@ -0,0 +1,10 @@ +class Solution: + def satisfiesConditions(self, grid: List[List[int]]) -> bool: + m = len(grid) + n = len(grid[0]) + return all(grid[i][j] == grid[i + 1][j] + for i in range(m - 1) + for j in range(n)) and \ + all(grid[i][j] != grid[i][j + 1] + for i in range(m) + for j in range(n - 1)) diff --git a/solutions/3143. Maximum Points Inside the Square/3143.cpp b/solutions/3143. Maximum Points Inside the Square/3143.cpp new file mode 100644 index 00000000000..bf7619e10d5 --- /dev/null +++ b/solutions/3143. Maximum Points Inside the Square/3143.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maxPointsInsideSquare(vector>& points, string s) { + int secondMinSize = INT_MAX; + vector minSizes(26, INT_MAX); + + for (int i = 0; i < points.size(); ++i) { + const int x = points[i][0]; + const int y = points[i][1]; + const int sz = max(abs(x), abs(y)); + const int j = s[i] - 'a'; + if (minSizes[j] == INT_MAX) { + minSizes[j] = sz; + } else if (sz < minSizes[j]) { + // This is because minSizes[j] is about to be replaced by a smaller + // value, so it becomes a candidate for the second minimum size. + secondMinSize = min(secondMinSize, minSizes[j]); + minSizes[j] = sz; + } else { + // `sz` is not smaller than the current minimum size, but it could be + // smaller than the current second minimum size. + secondMinSize = min(secondMinSize, sz); + } + } + + return ranges::count_if(minSizes, + [&](int sz) { return sz < secondMinSize; }); + } +}; diff --git a/solutions/3143. Maximum Points Inside the Square/3143.java b/solutions/3143. Maximum Points Inside the Square/3143.java new file mode 100644 index 00000000000..43a1f0d7385 --- /dev/null +++ b/solutions/3143. Maximum Points Inside the Square/3143.java @@ -0,0 +1,29 @@ +class Solution { + public int maxPointsInsideSquare(int[][] points, String s) { + int secondMinSize = Integer.MAX_VALUE; + int[] minSizes = new int[26]; + Arrays.fill(minSizes, Integer.MAX_VALUE); + + for (int i = 0; i < points.length; ++i) { + final int x = points[i][0]; + final int y = points[i][1]; + final int sz = Math.max(Math.abs(x), Math.abs(y)); + final int j = s.charAt(i) - 'a'; + if (minSizes[j] == Integer.MAX_VALUE) { + minSizes[j] = sz; + } else if (sz < minSizes[j]) { + // This is because minSizes[j] is about to be replaced by a smaller + // value, so it becomes a candidate for the second minimum size. + secondMinSize = Math.min(secondMinSize, minSizes[j]); + minSizes[j] = sz; + } else { + // `sz` is not smaller than the current minimum size, but it could be + // smaller than the current second minimum size. + secondMinSize = Math.min(secondMinSize, sz); + } + } + + final int finalSecondMinSize = secondMinSize; + return (int) Arrays.stream(minSizes).filter(sz -> sz < finalSecondMinSize).count(); + } +} diff --git a/solutions/3143. Maximum Points Inside the Square/3143.py b/solutions/3143. Maximum Points Inside the Square/3143.py new file mode 100644 index 00000000000..4f164874ab1 --- /dev/null +++ b/solutions/3143. Maximum Points Inside the Square/3143.py @@ -0,0 +1,20 @@ +class Solution: + def maxPointsInsideSquare(self, points: List[List[int]], s: str) -> int: + secondMinSize = math.inf + minSizes = {} + + for (x, y), c in zip(points, s): + sz = max(abs(x), abs(y)) + if c not in minSizes: + minSizes[c] = sz + elif sz < minSizes[c]: + # This is because minSizes[j] is about to be replaced by a smaller + # value, so it becomes a candidate for the second minimum size. + secondMinSize = min(secondMinSize, minSizes[c]) + minSizes[c] = sz + else: + # `sz` is not smaller than the current minimum size, but it could be + # smaller than the current second minimum size. + secondMinSize = min(secondMinSize, sz) + + return sum(sz < secondMinSize for sz in minSizes.values()) diff --git a/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.cpp b/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.cpp new file mode 100644 index 00000000000..c0765102517 --- /dev/null +++ b/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minimumSubstringsInPartition(string s) { + const int n = s.length(); + // dp[i] := the minimum number of substrings in s[0..i] + vector dp(n, n); + + for (int i = 0; i < n; ++i) { + vector count(26); + for (int j = i; j >= 0; --j) { + ++count[s[j] - 'a']; + if (isBalanced(count)) // word[j..i] is balanced. + dp[i] = j > 0 ? min(dp[i], 1 + dp[j - 1]) : 1; + } + } + + return dp.back(); + } + + private: + static constexpr int kMax = 1001; + + // Returns true if all non-zero frequencies are the same. + bool isBalanced(const vector& count) { + int minfreq = kMax; + int maxfreq = 0; + for (const int freq : count) + if (freq > 0) { + minfreq = min(minfreq, freq); + maxfreq = max(maxfreq, freq); + } + return minfreq == maxfreq; + } +}; diff --git a/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.java b/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.java new file mode 100644 index 00000000000..dc0cfed40c2 --- /dev/null +++ b/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.java @@ -0,0 +1,33 @@ +class Solution { + public int minimumSubstringsInPartition(String s) { + final int n = s.length(); + // dp[i] := the minimum number of substrings in s[0..i] + int[] dp = new int[n]; + Arrays.fill(dp, n); + + for (int i = 0; i < n; ++i) { + int[] count = new int[26]; + for (int j = i; j >= 0; --j) { + ++count[s.charAt(j) - 'a']; + if (isBalanced(count)) // word[j..i] is balanced. + dp[i] = j > 0 ? Math.min(dp[i], 1 + dp[j - 1]) : 1; + } + } + + return dp[n - 1]; + } + + private static final int kMax = 1001; + + // Returns true if all non-zero frequencies are the same. + private boolean isBalanced(int[] count) { + int minfreq = kMax; + int maxfreq = 0; + for (final int freq : count) + if (freq > 0) { + minfreq = Math.min(minfreq, freq); + maxfreq = Math.max(maxfreq, freq); + } + return minfreq == maxfreq; + } +} diff --git a/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.py b/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.py new file mode 100644 index 00000000000..1b306535e2e --- /dev/null +++ b/solutions/3144. Minimum Substring Partition of Equal Character Frequency/3144.py @@ -0,0 +1,15 @@ +class Solution: + def minimumSubstringsInPartition(self, s: str) -> int: + n = len(s) + # dp[i] := the minimum number of substrings in s[0..i] + dp = [n] * n + + for i in range(n): + count = collections.Counter() + for j in range(i, -1, -1): + count[s[j]] += 1 + # word[j..i] is balanced. + if min(count.values()) == max(count.values()): + dp[i] = min(dp[i], 1 + dp[j - 1] if j > 0 else 1) + + return dp[-1] diff --git a/solutions/3145. Find Products of Elements of Big Array/3145.cpp b/solutions/3145. Find Products of Elements of Big Array/3145.cpp new file mode 100644 index 00000000000..b32d46b2e37 --- /dev/null +++ b/solutions/3145. Find Products of Elements of Big Array/3145.cpp @@ -0,0 +1,84 @@ +class Solution { + public: + vector findProductsOfElements(vector>& queries) { + vector ans; + + for (const vector& query : queries) { + const long a = query[0]; + const long b = query[1]; + const int mod = query[2]; + const int product = modPow(2, + sumPowersFirstKBigNums(b + 1) - // + sumPowersFirstKBigNums(a), + mod); + ans.push_back(product); + } + + return ans; + } + + private: + // Returns the sum of powers of the first k numbers in `big_nums`. + long sumPowersFirstKBigNums(long k) { + const long num = firstNumberHavingSumBitsTillGreaterThan(k); + long sumPowers = sumPowersTill(num - 1); + long remainingCount = k - sumBitsTill(num - 1); + for (int power = 0; power < bitLength(num); ++power) { + if (num >> power & 1) { + sumPowers += power; + --remainingCount; + if (remainingCount == 0) + break; + } + } + return sumPowers; + } + + // Returns the first number in [1, k] that has sumBitsTill(num) >= k. + long firstNumberHavingSumBitsTillGreaterThan(long k) { + long l = 1; + long r = k; + while (l < r) { + const long m = (l + r) / 2; + if (sumBitsTill(m) < k) + l = m + 1; + else + r = m; + } + return l; + } + + // Returns sum(i.bit_count()), where 1 <= i <= x. + long sumBitsTill(long x) { + long sumBits = 0; + for (long powerOfTwo = 1; powerOfTwo <= x; powerOfTwo *= 2) { + sumBits += (x / (2L * powerOfTwo)) * powerOfTwo; + sumBits += max(0L, x % (2L * powerOfTwo) + 1 - powerOfTwo); + } + return sumBits; + } + + // Returns sum(all powers of i), where 1 <= i <= x. + long sumPowersTill(long x) { + long sumPowers = 0; + long powerOfTwo = 1; + for (int power = 0; power < bitLength(x); ++power) { + sumPowers += (x / (2L * powerOfTwo)) * powerOfTwo * power; + sumPowers += max(0L, x % (2L * powerOfTwo) + 1 - powerOfTwo) * power; + powerOfTwo *= 2; + } + return sumPowers; + } + + int modPow(long x, long n, int mod) { + if (n == 0) + return 1 % mod; + if (n % 2 == 1) + return x * modPow(x % mod, (n - 1), mod) % mod; + return modPow(x * x % mod, (n / 2), mod) % mod; + } + + int bitLength(long x) { + return x == 0 ? 0 : 64 - __builtin_clzl(x); + } +}; diff --git a/solutions/3145. Find Products of Elements of Big Array/3145.java b/solutions/3145. Find Products of Elements of Big Array/3145.java new file mode 100644 index 00000000000..2a6af4bb8ff --- /dev/null +++ b/solutions/3145. Find Products of Elements of Big Array/3145.java @@ -0,0 +1,81 @@ +class Solution { + public int[] findProductsOfElements(long[][] queries) { + int[] ans = new int[queries.length]; + + for (int i = 0; i < queries.length; ++i) { + final long a = queries[i][0]; + final long b = queries[i][1]; + final int mod = (int) queries[i][2]; + ans[i] = (int) modPow(2, + sumPowersFirstKBigNums(b + 1) - // + sumPowersFirstKBigNums(a), + mod); + } + + return ans; + } + + // Returns the sum of powers of the first k numbers in `big_nums`. + private long sumPowersFirstKBigNums(long k) { + final long num = firstNumberHavingSumBitsTillGreaterThan(k); + long sumPowers = sumPowersTill(num - 1); + long remainingCount = k - sumBitsTill(num - 1); + for (int power = 0; power < bitLength(num); ++power) { + if ((num >> power & 1) == 1) { + sumPowers += power; + --remainingCount; + if (remainingCount == 0) + break; + } + } + return sumPowers; + } + + // Returns the first number in [1, k] that has sumBitsTill(num) >= k. + private long firstNumberHavingSumBitsTillGreaterThan(long k) { + long l = 1; + long r = k; + while (l < r) { + final long m = (l + r) / 2; + if (sumBitsTill(m) < k) + l = m + 1; + else + r = m; + } + return l; + } + + // Returns sum(i.bit_count()), where 1 <= i <= x. + private long sumBitsTill(long x) { + long sumBits = 0; + for (long powerOfTwo = 1; powerOfTwo <= x; powerOfTwo *= 2) { + sumBits += (x / (2 * powerOfTwo)) * powerOfTwo; + sumBits += Math.max(0, x % (2 * powerOfTwo) + 1 - powerOfTwo); + } + return sumBits; + } + + // Returns sum(all powers of i), where 1 <= i <= x. + private long sumPowersTill(long x) { + long sumPowers = 0; + long powerOfTwo = 1; + for (int power = 0; power < bitLength(x); ++power) { + sumPowers += (x / (2 * powerOfTwo)) * powerOfTwo * power; + sumPowers += Math.max(0, x % (2 * powerOfTwo) + 1 - powerOfTwo) * power; + powerOfTwo *= 2; + } + return sumPowers; + } + + private long modPow(long x, long n, int mod) { + if (n == 0) + return 1 % mod; + if (n % 2 == 1) + return x * modPow(x % mod, (n - 1), mod) % mod; + return modPow(x * x % mod, (n / 2), mod) % mod; + } + + private int bitLength(long x) { + return x == 0 ? 0 : 64 - Long.numberOfLeadingZeros(x); + } +} diff --git a/solutions/3145. Find Products of Elements of Big Array/3145.py b/solutions/3145. Find Products of Elements of Big Array/3145.py new file mode 100644 index 00000000000..f6b53f7f6bb --- /dev/null +++ b/solutions/3145. Find Products of Elements of Big Array/3145.py @@ -0,0 +1,40 @@ +class Solution: + def findProductsOfElements(self, queries: List[List[int]]) -> List[int]: + def sumBitsTill(x: int) -> int: + """Returns sum(i.bit_count()), where 1 <= i <= x.""" + sumBits = 0 + powerOfTwo = 1 + while powerOfTwo <= x: + sumBits += (x // (2 * powerOfTwo)) * powerOfTwo + sumBits += max(0, x % (2 * powerOfTwo) + 1 - powerOfTwo) + powerOfTwo *= 2 + return sumBits + + def sumPowersTill(x: int) -> int: + """Returns sum(all powers of i), where 1 <= i <= x.""" + sumPowers = 0 + powerOfTwo = 1 + for power in range(x.bit_length()): + sumPowers += (x // (2 * powerOfTwo)) * powerOfTwo * power + sumPowers += max(0, x % (2 * powerOfTwo) + 1 - powerOfTwo) * power + powerOfTwo *= 2 + return sumPowers + + def sumPowersFirstKBigNums(k: int) -> int: + """Returns the sum of powers of the first k numbers in `big_nums`.""" + # Find the first number in [1, k] that has sumBitsTill(num) >= k. + num = bisect.bisect_left(range(k), k, key=sumBitsTill) + sumPowers = sumPowersTill(num - 1) + remainingCount = k - sumBitsTill(num - 1) + for power in range(num.bit_length()): + if num >> power & 1: + sumPowers += power + remainingCount -= 1 + if remainingCount == 0: + break + return sumPowers + + return [pow(2, + sumPowersFirstKBigNums(b + 1) - + sumPowersFirstKBigNums(a), mod) + for a, b, mod in queries] diff --git a/solutions/3146. Permutation Difference between Two Strings/3146.cpp b/solutions/3146. Permutation Difference between Two Strings/3146.cpp new file mode 100644 index 00000000000..f178bd23170 --- /dev/null +++ b/solutions/3146. Permutation Difference between Two Strings/3146.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int findPermutationDifference(string s, string t) { + int ans = 0; + vector indices(26); + + for (int i = 0; i < s.length(); ++i) + indices[s[i] - 'a'] = i; + + for (int i = 0; i < t.length(); ++i) + ans += abs(indices[t[i] - 'a'] - i); + + return ans; + } +}; diff --git a/solutions/3146. Permutation Difference between Two Strings/3146.java b/solutions/3146. Permutation Difference between Two Strings/3146.java new file mode 100644 index 00000000000..a243e4b4f1e --- /dev/null +++ b/solutions/3146. Permutation Difference between Two Strings/3146.java @@ -0,0 +1,14 @@ +class Solution { + public int findPermutationDifference(String s, String t) { + int ans = 0; + int[] indices = new int[26]; + + for (int i = 0; i < s.length(); ++i) + indices[s.charAt(i) - 'a'] = i; + + for (int i = 0; i < t.length(); ++i) + ans += Math.abs(indices[t.charAt(i) - 'a'] - i); + + return ans; + } +} diff --git a/solutions/3146. Permutation Difference between Two Strings/3146.py b/solutions/3146. Permutation Difference between Two Strings/3146.py new file mode 100644 index 00000000000..30542b46172 --- /dev/null +++ b/solutions/3146. Permutation Difference between Two Strings/3146.py @@ -0,0 +1,4 @@ +class Solution: + def findPermutationDifference(self, s: str, t: str) -> int: + indices = {c: i for i, c in enumerate(s)} + return sum([abs(indices[c] - i) for i, c in enumerate(t)]) diff --git a/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.cpp b/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.cpp new file mode 100644 index 00000000000..511a9368340 --- /dev/null +++ b/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int maximumEnergy(vector& energy, int k) { + vector dp(energy); + for (int i = energy.size() - 1 - k; i >= 0; --i) + dp[i] += dp[i + k]; + return ranges::max(dp); + } +}; diff --git a/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.java b/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.java new file mode 100644 index 00000000000..d7308aeecbd --- /dev/null +++ b/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.java @@ -0,0 +1,8 @@ +class Solution { + public int maximumEnergy(int[] energy, int k) { + int[] dp = energy.clone(); + for (int i = energy.length - 1 - k; i >= 0; --i) + dp[i] += dp[i + k]; + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.py b/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.py new file mode 100644 index 00000000000..cbd2ff928ca --- /dev/null +++ b/solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.py @@ -0,0 +1,7 @@ +class Solution: + def maximumEnergy(self, energy: List[int], k: int) -> int: + # dp[i] := the sum of energy starting at i + dp = energy.copy() + for i in range(len(energy) - 1 - k, -1, -1): + dp[i] += dp[i + k] + return max(dp) diff --git a/solutions/3148. Maximum Difference Score in a Grid/3148.cpp b/solutions/3148. Maximum Difference Score in a Grid/3148.cpp new file mode 100644 index 00000000000..bb6719b9491 --- /dev/null +++ b/solutions/3148. Maximum Difference Score in a Grid/3148.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxScore(vector>& grid) { + constexpr int kMax = 200'000; + int ans = -kMax; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) { + const int prevMin = min(i > 0 ? grid[i - 1][j] : kMax, // + j > 0 ? grid[i][j - 1] : kMax); + ans = max(ans, grid[i][j] - prevMin); + grid[i][j] = min(grid[i][j], prevMin); + } + + return ans; + } +}; diff --git a/solutions/3148. Maximum Difference Score in a Grid/3148.java b/solutions/3148. Maximum Difference Score in a Grid/3148.java new file mode 100644 index 00000000000..4f26b87af63 --- /dev/null +++ b/solutions/3148. Maximum Difference Score in a Grid/3148.java @@ -0,0 +1,17 @@ +class Solution { + public int maxScore(List> grid) { + final int kMax = 200_000; + int ans = -kMax; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid.get(0).size(); ++j) { + final int prevMin = Math.min(i > 0 ? grid.get(i - 1).get(j) : kMax, // + j > 0 ? grid.get(i).get(j - 1) : kMax); + ans = Math.max(ans, grid.get(i).get(j) - prevMin); + if (prevMin < grid.get(i).get(j)) + grid.get(i).set(j, prevMin); + } + + return ans; + } +} diff --git a/solutions/3148. Maximum Difference Score in a Grid/3148.py b/solutions/3148. Maximum Difference Score in a Grid/3148.py new file mode 100644 index 00000000000..021c325e74b --- /dev/null +++ b/solutions/3148. Maximum Difference Score in a Grid/3148.py @@ -0,0 +1,13 @@ +class Solution: + def maxScore(self, grid: List[List[int]]) -> int: + kMax = 200000 + ans = -kMax + + for i, row in enumerate(grid): + for j, num in enumerate(row): + prevMin = min(grid[i - 1][j] if i > 0 else kMax, + grid[i][j - 1] if j > 0 else kMax) + ans = max(ans, num - prevMin) + grid[i][j] = min(num, prevMin) + + return ans diff --git a/solutions/3149. Find the Minimum Cost Array Permutation/3149.cpp b/solutions/3149. Find the Minimum Cost Array Permutation/3149.cpp new file mode 100644 index 00000000000..32c68020b8c --- /dev/null +++ b/solutions/3149. Find the Minimum Cost Array Permutation/3149.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + vector findPermutation(vector& nums) { + const int n = nums.size(); + vector> mem(n, vector(1 << n)); + // bestPick[last][mask] := the best pick, where `last` is the last chosen + // number and `mask` is the bitmask of the chosen numbers + vector> bestPick(n, vector(1 << n)); + + // Choose 0 as perm[0] since the score function is cyclic. + getScore(nums, /*last=*/0, /*mask=*/1, bestPick, mem); + return construct(bestPick); + } + + private: + // Returns the minimum score, where `last` is the last chosen number and + // `mask` is the bitmask of the chosen numbers. + int getScore(const vector& nums, int last, unsigned mask, + vector>& bestPick, vector>& mem) { + if (popcount(mask) == nums.size()) + return abs(last - nums[0]); // |perm[n - 1] - nums[perm[0]]| + if (mem[last][mask] > 0) + return mem[last][mask]; + + int minScore = INT_MAX; + for (int i = 1; i < nums.size(); ++i) { + if (mask >> i & 1) + continue; + const int nextMinScore = + abs(last - nums[i]) + getScore(nums, i, mask | 1 << i, bestPick, mem); + if (nextMinScore < minScore) { + minScore = nextMinScore; + bestPick[last][mask] = i; + } + } + + return mem[last][mask] = minScore; + } + + vector construct(const vector>& bestPick) { + vector ans; + int last = 0; + int mask = 1; + for (int i = 0; i < bestPick.size(); ++i) { + ans.push_back(last); + last = bestPick[last][mask]; + mask |= 1 << last; + } + return ans; + } +}; diff --git a/solutions/3149. Find the Minimum Cost Array Permutation/3149.java b/solutions/3149. Find the Minimum Cost Array Permutation/3149.java new file mode 100644 index 00000000000..cd84be6778d --- /dev/null +++ b/solutions/3149. Find the Minimum Cost Array Permutation/3149.java @@ -0,0 +1,47 @@ +class Solution { + public int[] findPermutation(int[] nums) { + final int n = nums.length; + int[][] mem = new int[n][1 << n]; + // bestPick[last][mask] := the best pick, where `last` is the last chosen + // number and `mask` is the bitmask of the chosen numbers + int[][] bestPick = new int[n][1 << n]; + + // Choose 0 as perm[0] since the score function is cyclic. + getScore(nums, /*last=*/0, /*mask=*/1, bestPick, mem); + return construct(bestPick); + } + + // Returns the minimum score, where `last` is the last chosen number and + // `mask` is the bitmask of the chosen numbers. + private int getScore(int[] nums, int last, int mask, int[][] bestPick, int[][] mem) { + if (Integer.bitCount(mask) == nums.length) + return Math.abs(last - nums[0]); // |perm[n - 1] - nums[perm[0]]| + if (mem[last][mask] > 0) + return mem[last][mask]; + + int minScore = Integer.MAX_VALUE; + for (int i = 1; i < nums.length; ++i) { + if ((mask >> i & 1) == 1) + continue; + int nextMinScore = Math.abs(last - nums[i]) + getScore(nums, i, mask | 1 << i, bestPick, mem); + if (nextMinScore < minScore) { + minScore = nextMinScore; + bestPick[last][mask] = i; + } + } + + return mem[last][mask] = minScore; + } + + private int[] construct(int[][] bestPick) { + int[] ans = new int[bestPick.length]; + int last = 0; + int mask = 1; + for (int i = 0; i < bestPick.length; ++i) { + ans[i] = last; + last = bestPick[last][mask]; + mask |= 1 << last; + } + return ans; + } +} diff --git a/solutions/3149. Find the Minimum Cost Array Permutation/3149.py b/solutions/3149. Find the Minimum Cost Array Permutation/3149.py new file mode 100644 index 00000000000..82cae395f4c --- /dev/null +++ b/solutions/3149. Find the Minimum Cost Array Permutation/3149.py @@ -0,0 +1,33 @@ +class Solution: + def findPermutation(self, nums: List[int]) -> List[int]: + n = len(nums) + bestPick = [[0] * (1 << n) for _ in range(n)] + + @functools.lru_cache(None) + def getScore(last: int, mask: int) -> int: + if mask.bit_count() == len(nums): + return abs(last - nums[0]) + + minScore = math.inf + for i in range(1, len(nums)): + if mask >> i & 1: + continue + nextMinScore = abs(last - nums[i]) + getScore(i, mask | (1 << i)) + if nextMinScore < minScore: + minScore = nextMinScore + bestPick[last][mask] = i + + return minScore + + getScore(0, 1) + return self._construct(bestPick) + + def _construct(self, bestPick: List[List[int]]) -> List[int]: + ans = [] + last = 0 + mask = 1 + for _ in range(len(bestPick)): + ans.append(last) + last = bestPick[last][mask] + mask |= 1 << last + return ans diff --git a/solutions/315. Count of Smaller Numbers After Self/315-2.cpp b/solutions/315. Count of Smaller Numbers After Self/315-2.cpp new file mode 100644 index 00000000000..373bed805a0 --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315-2.cpp @@ -0,0 +1,85 @@ +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) : n(nums.size()), tree(n * 4) { + build(nums, 0, 0, n - 1); + } + + // Adds val to nums[i]. + void add(int i, int val) { + add(0, 0, n - 1, i, val); + } + + // Returns sum(nums[i..j]). + int query(int i, int j) { + return query(0, 0, n - 1, i, j); + } + + private: + const int n; // the size of the input array + vector tree; // the segment tree + + void build(const vector& nums, int treeIndex, int lo, int hi) { + if (lo == hi) { + tree[treeIndex] = nums[lo]; + return; + } + const int mid = (lo + hi) / 2; + build(nums, 2 * treeIndex + 1, lo, mid); + build(nums, 2 * treeIndex + 2, mid + 1, hi); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + void add(int treeIndex, int lo, int hi, int i, int val) { + if (lo == hi) { + tree[treeIndex] += val; + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + add(2 * treeIndex + 1, lo, mid, i, val); + else + add(2 * treeIndex + 2, mid + 1, hi, i, val); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + int query(int treeIndex, int lo, int hi, int i, int j) { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return 0; + const int mid = (lo + hi) / 2; + return merge(query(treeIndex * 2 + 1, lo, mid, i, j), + query(treeIndex * 2 + 2, mid + 1, hi, i, j)); + } + + // Merges the result of the left node and the right node. + int merge(int a, int b) const { + return a + b; + } +}; + +class Solution { + public: + vector countSmaller(vector& nums) { + vector ans(nums.size()); + unordered_map ranks; + getRanks(nums, ranks); + SegmentTree tree(vector(ranks.size() + 1)); + + for (int i = nums.size() - 1; i >= 0; --i) { + const int num = nums[i]; + ans[i] = tree.query(0, ranks[num] - 1); + tree.add(ranks[num], 1); + } + + return ans; + } + + private: + void getRanks(const vector& nums, unordered_map& ranks) { + set sorted(nums.begin(), nums.end()); + int rank = 0; + for (const int num : sorted) + ranks[num] = ++rank; + } +}; diff --git a/solutions/315. Count of Smaller Numbers After Self/315-3.cpp b/solutions/315. Count of Smaller Numbers After Self/315-3.cpp new file mode 100644 index 00000000000..a02a659cd03 --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315-3.cpp @@ -0,0 +1,91 @@ +struct SegmentTreeNode { + int lo; + int hi; + int sum; + SegmentTreeNode* left; + SegmentTreeNode* right; + SegmentTreeNode(int lo, int hi, int sum, SegmentTreeNode* left = nullptr, + SegmentTreeNode* right = nullptr) + : lo(lo), hi(hi), sum(sum), left(left), right(right) {} + ~SegmentTreeNode() { + delete left; + delete right; + left = nullptr; + right = nullptr; + } +}; + +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) + : root(build(nums, 0, nums.size() - 1)) {} + + void update(int i, int val) { + update(root.get(), i, val); + } + + int query(int i, int j) const { + return query(root.get(), i, j); + } + + private: + std::unique_ptr root; + + SegmentTreeNode* build(const vector& nums, int lo, int hi) const { + if (lo == hi) + return new SegmentTreeNode(lo, hi, nums[lo]); + const int mid = (lo + hi) / 2; + SegmentTreeNode* left = build(nums, lo, mid); + SegmentTreeNode* right = build(nums, mid + 1, hi); + return new SegmentTreeNode(lo, hi, left->sum + right->sum, left, right); + } + + void update(SegmentTreeNode* root, int i, int val) { + if (root->lo == i && root->hi == i) { + root->sum += val; + return; + } + const int mid = (root->lo + root->hi) / 2; + if (i <= mid) + update(root->left, i, val); + else + update(root->right, i, val); + root->sum = root->left->sum + root->right->sum; + } + + int query(SegmentTreeNode* root, int i, int j) const { + // [lo, hi] lies completely inside [i, j]. + if (i <= root->lo && root->hi <= j) + return root->sum; + // [lo, hi] lies completely outside [i, j]. + if (j < root->lo || root->hi < i) + return 0; + return query(root->left, i, j) + query(root->right, i, j); + } +}; + +class Solution { + public: + vector countSmaller(vector& nums) { + vector ans(nums.size()); + unordered_map ranks; + getRanks(nums, ranks); + SegmentTree tree(vector(ranks.size() + 1)); + + for (int i = nums.size() - 1; i >= 0; --i) { + const int num = nums[i]; + ans[i] = tree.query(0, ranks[num] - 1); + tree.update(ranks[num], 1); + } + + return ans; + } + + private: + void getRanks(const vector& nums, unordered_map& ranks) { + set sorted(nums.begin(), nums.end()); + int rank = 0; + for (const int num : sorted) + ranks[num] = ++rank; + } +}; diff --git a/solutions/315. Count of Smaller Numbers After Self/315-4.cpp b/solutions/315. Count of Smaller Numbers After Self/315-4.cpp new file mode 100644 index 00000000000..7b08bf91238 --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315-4.cpp @@ -0,0 +1,60 @@ +struct Item { + int num; + int index; + Item(int num = 0, int index = 0) : num(num), index(index) {} +}; + +class Solution { + public: + vector countSmaller(vector& nums) { + const int n = nums.size(); + vector ans(n); + vector items(n); + + for (int i = 0; i < n; ++i) + items[i] = Item(nums[i], i); + + mergeSort(items, 0, n - 1, ans); + return ans; + } + + private: + void mergeSort(vector& items, int l, int r, vector& ans) { + if (l >= r) + return; + + const int m = (l + r) / 2; + mergeSort(items, l, m, ans); + mergeSort(items, m + 1, r, ans); + merge(items, l, m, r, ans); + } + + void merge(vector& items, int l, int m, int r, vector& ans) { + vector sorted(r - l + 1); + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + int rightCount = 0; // the number of numbers < items[i].num + + while (i <= m && j <= r) + if (items[i].num > items[j].num) { + ++rightCount; + sorted[k++] = items[j++]; + } else { + ans[items[i].index] += rightCount; + sorted[k++] = items[i++]; + } + + // Put the possible remaining left part into the sorted array. + while (i <= m) { + ans[items[i].index] += rightCount; + sorted[k++] = items[i++]; + } + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = items[j++]; + + copy(sorted.begin(), sorted.end(), items.begin() + l); + } +}; diff --git a/solutions/315. Count of Smaller Numbers After Self/315-4.java b/solutions/315. Count of Smaller Numbers After Self/315-4.java new file mode 100644 index 00000000000..7ede66a25d6 --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315-4.java @@ -0,0 +1,61 @@ +class Item { + public int num; + public int index; + public Item(int num, int index) { + this.num = num; + this.index = index; + } +} + +class Solution { + public List countSmaller(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + Item[] items = new Item[n]; + + for (int i = 0; i < n; ++i) + items[i] = new Item(nums[i], i); + + mergeSort(items, 0, n - 1, ans); + return Arrays.stream(ans).boxed().collect(Collectors.toList()); + } + + private void mergeSort(Item[] items, int l, int r, int[] ans) { + if (l >= r) + return; + + final int m = (l + r) / 2; + mergeSort(items, l, m, ans); + mergeSort(items, m + 1, r, ans); + merge(items, l, m, r, ans); + } + + private void merge(Item[] items, int l, int m, int r, int[] ans) { + Item[] sorted = new Item[r - l + 1]; + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + int rightCount = 0; // the number of `nums` < items[i].num + + while (i <= m && j <= r) + if (items[i].num > items[j].num) { + ++rightCount; + sorted[k++] = items[j++]; + } else { + ans[items[i].index] += rightCount; + sorted[k++] = items[i++]; + } + + // Put the possible remaining left part into the sorted array. + while (i <= m) { + ans[items[i].index] += rightCount; + sorted[k++] = items[i++]; + } + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = items[j++]; + + System.arraycopy(sorted, 0, items, l, sorted.length); + } +} diff --git a/solutions/315. Count of Smaller Numbers After Self/315-4.py b/solutions/315. Count of Smaller Numbers After Self/315-4.py new file mode 100644 index 00000000000..0e2a26d3825 --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315-4.py @@ -0,0 +1,57 @@ +class Item: + def __init__(self, num: int = 0, index: int = 0): + self.num = num + self.index = index + + +class Solution: + def countSmaller(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [0] * n + items = [Item(num, i) for i, num in enumerate(nums)] + + self._mergeSort(items, 0, n - 1, ans) + return ans + + def _mergeSort(self, items: List[Item], l: int, r: int, ans: List[int]) -> None: + if l >= r: + return + + m = (l + r) // 2 + self._mergeSort(items, l, m, ans) + self._mergeSort(items, m + 1, r, ans) + self._merge(items, l, m, r, ans) + + def _merge(self, items: List[Item], l: int, m: int, r: int, ans: List[int]) -> None: + sorted = [Item()] * (r - l + 1) + k = 0 # sorted's index + i = l # left's index + j = m + 1 # right's index + rightCount = 0 # the number of numbers < items[i].num + + while i <= m and j <= r: + if items[i].num > items[j].num: + rightCount += 1 + sorted[k] = items[j] + k += 1 + j += 1 + else: + ans[items[i].index] += rightCount + sorted[k] = items[i] + k += 1 + i += 1 + + # Put the possible remaining left part into the sorted array. + while i <= m: + ans[items[i].index] += rightCount + sorted[k] = items[i] + k += 1 + i += 1 + + # Put the possible remaining right part into the sorted array. + while j <= r: + sorted[k] = items[j] + k += 1 + j += 1 + + items[l:l + len(sorted)] = sorted diff --git a/solutions/315. Count of Smaller Numbers After Self/315.cpp b/solutions/315. Count of Smaller Numbers After Self/315.cpp new file mode 100644 index 00000000000..88eeca80311 --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315.cpp @@ -0,0 +1,54 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + vector countSmaller(vector& nums) { + vector ans(nums.size()); + const unordered_map ranks = getRanks(nums); + FenwickTree tree(ranks.size()); + + for (int i = nums.size() - 1; i >= 0; --i) { + const int num = nums[i]; + ans[i] = tree.get(ranks.at(num) - 1); + tree.add(ranks.at(num), 1); + } + + return ans; + } + + private: + unordered_map getRanks(const vector& nums) { + unordered_map ranks; + set sorted(nums.begin(), nums.end()); + int rank = 0; + for (const int num : sorted) + ranks[num] = ++rank; + return ranks; + } +}; diff --git a/solutions/315. Count of Smaller Numbers After Self/315.java b/solutions/315. Count of Smaller Numbers After Self/315.java new file mode 100644 index 00000000000..0fffeda545d --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315.java @@ -0,0 +1,55 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public List countSmaller(int[] nums) { + List ans = new ArrayList<>(); + Map ranks = getRanks(nums); + FenwickTree tree = new FenwickTree(ranks.size()); + + for (int i = nums.length - 1; i >= 0; --i) { + final int num = nums[i]; + ans.add(tree.get(ranks.get(num) - 1)); + tree.add(ranks.get(num), 1); + } + + Collections.reverse(ans); + return ans; + } + + private Map getRanks(int[] nums) { + Map ranks = new HashMap<>(); + SortedSet sorted = new TreeSet<>(); + for (final int num : nums) + sorted.add(num); + int rank = 0; + for (Iterator it = sorted.iterator(); it.hasNext();) + ranks.put(it.next(), ++rank); + return ranks; + } +} diff --git a/solutions/315. Count of Smaller Numbers After Self/315.py b/solutions/315. Count of Smaller Numbers After Self/315.py new file mode 100644 index 00000000000..ef19fc1f409 --- /dev/null +++ b/solutions/315. Count of Smaller Numbers After Self/315.py @@ -0,0 +1,40 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def countSmaller(self, nums: List[int]) -> List[int]: + ans = [] + ranks = self._getRanks(nums) + tree = FenwickTree(len(ranks)) + + for num in reversed(nums): + ans.append(tree.get(ranks[num] - 1)) + tree.add(ranks[num], 1) + + return ans[::-1] + + def _getRanks(self, nums: List[int]) -> Dict[int, int]: + ranks = collections.Counter() + rank = 0 + for num in sorted(set(nums)): + rank += 1 + ranks[num] = rank + return ranks diff --git a/solutions/3150. Invalid Tweets II/3150.sql b/solutions/3150. Invalid Tweets II/3150.sql new file mode 100644 index 00000000000..a57ee0bafd5 --- /dev/null +++ b/solutions/3150. Invalid Tweets II/3150.sql @@ -0,0 +1,7 @@ +SELECT tweet_id +FROM Tweets +WHERE + LENGTH(content) > 140 + OR LENGTH(content) - LENGTH(REPLACE(content, '@', '')) > 3 + OR LENGTH(content) - LENGTH(REPLACE(content, '#', '')) > 3 +ORDER BY 1; diff --git a/solutions/3151. Special Array I/3151.cpp b/solutions/3151. Special Array I/3151.cpp new file mode 100644 index 00000000000..1fd6ad9e031 --- /dev/null +++ b/solutions/3151. Special Array I/3151.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + bool isArraySpecial(vector& nums) { + for (int i = 1; i < nums.size(); ++i) + if (nums[i] % 2 == nums[i - 1] % 2) + return false; + return true; + } +}; diff --git a/solutions/3151. Special Array I/3151.java b/solutions/3151. Special Array I/3151.java new file mode 100644 index 00000000000..fbf1069a566 --- /dev/null +++ b/solutions/3151. Special Array I/3151.java @@ -0,0 +1,8 @@ +class Solution { + public boolean isArraySpecial(int[] nums) { + for (int i = 1; i < nums.length; ++i) + if (nums[i] % 2 == nums[i - 1] % 2) + return false; + return true; + } +} diff --git a/solutions/3151. Special Array I/3151.py b/solutions/3151. Special Array I/3151.py new file mode 100644 index 00000000000..618f1438e32 --- /dev/null +++ b/solutions/3151. Special Array I/3151.py @@ -0,0 +1,3 @@ +class Solution: + def isArraySpecial(self, nums: List[int]) -> bool: + return all(a % 2 != b % 2 for a, b in itertools.pairwise(nums)) diff --git a/solutions/3152. Special Array II/3152.cpp b/solutions/3152. Special Array II/3152.cpp new file mode 100644 index 00000000000..48382c6bc37 --- /dev/null +++ b/solutions/3152. Special Array II/3152.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector isArraySpecial(vector& nums, vector>& queries) { + vector ans; + int id = 0; + // parityIds[i] := the id of the parity group that nums[i] belongs to + vector parityIds = {id}; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] % 2 == nums[i - 1] % 2) + ++id; + parityIds.push_back(id); + } + + for (const vector query : queries) { + const int from = query[0]; + const int to = query[1]; + ans.push_back(parityIds[from] == parityIds[to]); + } + + return ans; + } +}; diff --git a/solutions/3152. Special Array II/3152.java b/solutions/3152. Special Array II/3152.java new file mode 100644 index 00000000000..d4e5e62108d --- /dev/null +++ b/solutions/3152. Special Array II/3152.java @@ -0,0 +1,23 @@ +class Solution { + public boolean[] isArraySpecial(int[] nums, int[][] queries) { + boolean[] ans = new boolean[queries.length]; + // parityIds[i] := the id of the parity group that nums[i] belongs to + int[] parityIds = new int[nums.length]; + int id = 0; + parityIds[0] = id; + + for (int i = 1; i < nums.length; ++i) { + if (nums[i] % 2 == nums[i - 1] % 2) + ++id; + parityIds[i] = id; + } + + for (int i = 0; i < queries.length; ++i) { + final int from = queries[i][0]; + final int to = queries[i][1]; + ans[i] = parityIds[from] == parityIds[to]; + } + + return ans; + } +} diff --git a/solutions/3152. Special Array II/3152.py b/solutions/3152. Special Array II/3152.py new file mode 100644 index 00000000000..4fea2a2a3e1 --- /dev/null +++ b/solutions/3152. Special Array II/3152.py @@ -0,0 +1,16 @@ +class Solution: + def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]: + ans = [] + id = 0 + # parityIds[i] := the id of the parity group that nums[i] belongs to + parityIds = [id] + + for a, b in itertools.pairwise(nums): + if a % 2 == b % 2: + id += 1 + parityIds.append(id) + + for _from, to in queries: + ans.append(parityIds[_from] == parityIds[to]) + + return ans diff --git a/solutions/3153. Sum of Digit Differences of All Pairs/3153.cpp b/solutions/3153. Sum of Digit Differences of All Pairs/3153.cpp new file mode 100644 index 00000000000..a2290f77f9a --- /dev/null +++ b/solutions/3153. Sum of Digit Differences of All Pairs/3153.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long long sumDigitDifferences(vector& nums) { + const int n = nums.size(); + const int digitSize = std::to_string(nums[0]).size(); + long ans = 0; + + for (int i = 0, denominator = 1; i < digitSize; ++i, denominator *= 10) { + vector count(10); + for (const int num : nums) + ++count[num / denominator % 10]; + for (const int freq : count) + ans += freq * (n - freq); + } + + return ans / 2; + } +}; diff --git a/solutions/3153. Sum of Digit Differences of All Pairs/3153.java b/solutions/3153. Sum of Digit Differences of All Pairs/3153.java new file mode 100644 index 00000000000..94233a24a62 --- /dev/null +++ b/solutions/3153. Sum of Digit Differences of All Pairs/3153.java @@ -0,0 +1,17 @@ +class Solution { + public long sumDigitDifferences(int[] nums) { + final int n = nums.length; + final int digitSize = String.valueOf(nums[0]).length(); + long ans = 0; + + for (int i = 0, denominator = 1; i < digitSize; ++i, denominator *= 10) { + int[] count = new int[10]; + for (final int num : nums) + ++count[num / denominator % 10]; + for (final int freq : count) + ans += freq * (n - freq); + } + + return ans / 2; + } +} diff --git a/solutions/3153. Sum of Digit Differences of All Pairs/3153.py b/solutions/3153. Sum of Digit Differences of All Pairs/3153.py new file mode 100644 index 00000000000..e5e0690220e --- /dev/null +++ b/solutions/3153. Sum of Digit Differences of All Pairs/3153.py @@ -0,0 +1,15 @@ +class Solution: + def sumDigitDifferences(self, nums: List[int]) -> int: + n = len(nums) + digitSize = len(str(nums[0])) + ans = 0 + + denominator = 1 + for _ in range(digitSize): + count = [0] * 10 + for num in nums: + count[num // denominator % 10] += 1 + ans += sum(freq * (n - freq) for freq in count) + denominator *= 10 + + return ans // 2 diff --git a/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.cpp b/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.cpp new file mode 100644 index 00000000000..fd3efa4eb19 --- /dev/null +++ b/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int waysToReachStair(int k) { + // Let's say we have `down` operation 1 and `jump` operation 2. + // The final stair is 1 + (2^0 + 2^1 + ... + 2^(jump - 1)) - down = k. + // => 1 + (2^jump - 1) - down = k. + // => down = 2^jump - k. + // Since `down` operations cannot be used consecutively, there're jump + 1 + // positions (before and after each `jump`) for `down`. The maximum jump is + // 29, as it satisfies the condition down = 2^jump - k <= jump + 1, with k + // being the maximum value of 10^9. + constexpr int kMaxJump = 29; + const vector> comb = getComb(kMaxJump + 1, kMaxJump + 1); + int ans = 0; + + for (int jump = 0; jump <= kMaxJump; ++jump) { + const int down = (1 << jump) - k; + if (down < 0 || down > jump + 1) + continue; + ans += comb[jump + 1][down]; + } + + return ans; + } + + private: + // C(n, k) = C(n - 1, k) + C(n - 1, k - 1) + vector> getComb(int n, int k) { + vector> comb(n + 1, vector(k + 1)); + for (int i = 0; i <= n; ++i) + comb[i][0] = 1; + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) + comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1]; + return comb; + } +}; diff --git a/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.java b/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.java new file mode 100644 index 00000000000..1ef79c364e2 --- /dev/null +++ b/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.java @@ -0,0 +1,36 @@ +class Solution { + public int waysToReachStair(int k) { + // Let's say we have `down` operation 1 and `jump` operation 2. + // The final stair is 1 + (2^0 + 2^1 + ... + 2^(jump - 1)) - down = k. + // => 1 + (2^jump - 1) - down = k. + // => down = 2^jump - k. + // Since `down` operations cannot be used consecutively, there're jump + 1 + // positions (before and after each `jump`) for `down`. The maximum jump is + // 29, as it satisfies the condition down = 2^jump - k <= jump + 1, with k + // being the maximum value of 10^9. + final int kMaxJump = 29; + final int[][] comb = getComb(kMaxJump + 1, kMaxJump + 1); + int ans = 0; + + for (int jump = 0; jump <= kMaxJump; ++jump) { + final int down = (1 << jump) - k; + if (down < 0 || down > jump + 1) + continue; + ans += comb[jump + 1][down]; + } + + return ans; + } + + // C(n, k) = C(n - 1, k) + C(n - 1, k - 1) + private int[][] getComb(int n, int k) { + int[][] comb = new int[n + 1][k + 1]; + + for (int i = 0; i <= n; ++i) + comb[i][0] = 1; + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) + comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1]; + return comb; + } +} diff --git a/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.py b/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.py new file mode 100644 index 00000000000..88b748e8210 --- /dev/null +++ b/solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.py @@ -0,0 +1,20 @@ +class Solution: + def waysToReachStair(self, k: int) -> int: + # Let's say we have `down` operation 1 and `jump` operation 2. + # The final stair is 1 + (2^0 + 2^1 + ... + 2^(jump - 1)) - down = k. + # => 1 + (2^jump - 1) - down = k. + # => down = 2^jump - k. + # Since `down` operations cannot be used consecutively, there're jump + 1 + # positions (before and after each `jump`) for `down`. The maximum jump is + # 29, as it satisfies the condition down = 2^jump - k <= jump + 1, with k + # being the maximum value of 10^9. + kMaxJump = 29 + ans = 0 + + for jump in range(kMaxJump + 1): + down = (1 << jump) - k + if down < 0 or down > jump + 1: + continue + ans += math.comb(jump + 1, down) + + return ans diff --git a/solutions/3155. Maximum Number of Upgradable Servers/3155.cpp b/solutions/3155. Maximum Number of Upgradable Servers/3155.cpp new file mode 100644 index 00000000000..0bd987de1ab --- /dev/null +++ b/solutions/3155. Maximum Number of Upgradable Servers/3155.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector maxUpgrades(vector& count, vector& upgrade, + vector& sell, vector& money) { + // If there's enough money, upgrade all servers; otherwise, optimize by + // upgrading x servers. We have x * upgrade <= money + (count - x) * sell. + // Therefore, x = (money + count * sell) / (sell + upgrade). + vector ans; + for (int i = 0; i < count.size(); ++i) + ans.push_back(min( + count[i], + static_cast((money[i] + static_cast(count[i]) * sell[i]) / + (sell[i] + upgrade[i])))); + return ans; + } +}; diff --git a/solutions/3155. Maximum Number of Upgradable Servers/3155.java b/solutions/3155. Maximum Number of Upgradable Servers/3155.java new file mode 100644 index 00000000000..13fd94fb23e --- /dev/null +++ b/solutions/3155. Maximum Number of Upgradable Servers/3155.java @@ -0,0 +1,12 @@ +class Solution { + public int[] maxUpgrades(int[] count, int[] upgrade, int[] sell, int[] money) { + // If there's enough money, upgrade all servers; otherwise, optimize by + // upgrading x servers. We have x * upgrade <= money + (count - x) * sell. + // Therefore, x = (money + count * sell) / (sell + upgrade). + int[] ans = new int[count.length]; + for (int i = 0; i < count.length; ++i) + ans[i] = Math.min(count[i], // + (int) ((money[i] + 1L * count[i] * sell[i]) / (sell[i] + upgrade[i]))); + return ans; + } +} diff --git a/solutions/3155. Maximum Number of Upgradable Servers/3155.py b/solutions/3155. Maximum Number of Upgradable Servers/3155.py new file mode 100644 index 00000000000..072589eef81 --- /dev/null +++ b/solutions/3155. Maximum Number of Upgradable Servers/3155.py @@ -0,0 +1,6 @@ +class Solution: + def maxUpgrades(self, count: List[int], upgrade: List[int], sell: List[int], money: List[int]) -> List[int]: + # If there's enough money, upgrade all servers; otherwise, optimize by + # upgrading x servers. We have x * upgrade <= money + (count - x) * sell. + # Therefore, x = (money + count * sell) / (sell + upgrade). + return [min(c, (m + c * s) // (s + u)) for c, u, s, m in zip(count, upgrade, sell, money)] diff --git a/solutions/3156. Employee Task Duration and Concurrent Tasks/3156.sql b/solutions/3156. Employee Task Duration and Concurrent Tasks/3156.sql new file mode 100644 index 00000000000..878b445bd06 --- /dev/null +++ b/solutions/3156. Employee Task Duration and Concurrent Tasks/3156.sql @@ -0,0 +1,47 @@ +WITH + EmployeeTimes AS ( + SELECT DISTINCT employee_id, start_time AS `time` + FROM Tasks + UNION DISTINCT + SELECT DISTINCT employee_id, end_time AS `time` + FROM Tasks + ), + RankedEmployeeTimes AS ( + SELECT + *, + ROW_NUMBER() OVER( + PARTITION BY employee_id + ORDER BY `time` + ) AS `row_number` + FROM EmployeeTimes + ), + Segments AS ( + SELECT + employee_id, + `time` AS start_time, + LEAD(`time`) OVER(PARTITION BY employee_id ORDER BY `time`) AS end_time + FROM RankedEmployeeTimes + ), + WorkingSegments AS ( + SELECT + Segments.*, + COUNT(*) AS concurrent_count + FROM Segments + INNER JOIN Tasks + USING (employee_id) + WHERE + Segments.start_time >= Tasks.start_time + AND Segments.end_time <= Tasks.end_time + GROUP BY 1, 2, 3 + ) +SELECT + employee_id, + FLOOR( + SUM( + TIME_TO_SEC(TIMEDIFF(end_time, start_time)) / 3600 + ) + ) AS total_task_hours, + MAX(concurrent_count) AS max_concurrent_tasks +FROM WorkingSegments +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.cpp b/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.cpp new file mode 100644 index 00000000000..8369c82be71 --- /dev/null +++ b/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + // Similar to 1161. Maximum Level Sum of a Binary Tree + int minimumLevel(TreeNode* root) { + // levelSums[i] := the sum of level (i + 1) (1-indexed) + vector levelSums; + dfs(root, 0, levelSums); + return 1 + ranges::min_element(levelSums) - levelSums.begin(); + } + + private: + void dfs(TreeNode* root, int level, vector& levelSums) { + if (root == nullptr) + return; + if (levelSums.size() == level) + levelSums.push_back(0); + levelSums[level] += root->val; + dfs(root->left, level + 1, levelSums); + dfs(root->right, level + 1, levelSums); + } +}; diff --git a/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.java b/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.java new file mode 100644 index 00000000000..8cf9ade55df --- /dev/null +++ b/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.java @@ -0,0 +1,20 @@ +class Solution { + // Similar to 1161. Maximum Level Sum of a Binary Tree + public int minimumLevel(TreeNode root) { + // levelSums[i] := the sum of level (i + 1) (1-indexed) + List levelSums = new ArrayList<>(); + dfs(root, 0, levelSums); + return 1 + IntStream.range(0, levelSums.size()) + .reduce(0, (a, b) -> levelSums.get(a) > levelSums.get(b) ? b : a); + } + + private void dfs(TreeNode root, int level, List levelSums) { + if (root == null) + return; + if (levelSums.size() == level) + levelSums.add(0L); + levelSums.set(level, levelSums.get(level) + root.val); + dfs(root.left, level + 1, levelSums); + dfs(root.right, level + 1, levelSums); + } +} diff --git a/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.py b/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.py new file mode 100644 index 00000000000..c056b0a761b --- /dev/null +++ b/solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.py @@ -0,0 +1,17 @@ +class Solution: + # Similar to 1161. Maximum Level Sum of a Binary Tree + def minimumLevel(self, root: Optional[TreeNode]) -> int: + # levelSums[i] := the sum of level (i + 1) (1-indexed) + levelSums = [] + + def dfs(root: Optional[TreeNode], level: int) -> None: + if not root: + return + if len(levelSums) == level: + levelSums.append(0) + levelSums[level] += root.val + dfs(root.left, level + 1) + dfs(root.right, level + 1) + + dfs(root, 0) + return 1 + levelSums.index(min(levelSums)) diff --git a/solutions/3157. Find the Level of Tree with Minimum Sum/3157.cpp b/solutions/3157. Find the Level of Tree with Minimum Sum/3157.cpp new file mode 100644 index 00000000000..3230dc3e1cc --- /dev/null +++ b/solutions/3157. Find the Level of Tree with Minimum Sum/3157.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + // Similar to 1161. Maximum Level Sum of a Binary Tree + int minimumLevel(TreeNode* root) { + int ans = 0; + long minLevelSum = LONG_MAX; + queue q{{root}}; + + for (int level = 1; !q.empty(); ++level) { + long levelSum = 0; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + levelSum += node->val; + if (node->left != nullptr) + q.push(node->left); + if (node->right != nullptr) + q.push(node->right); + } + if (levelSum < minLevelSum) { + minLevelSum = levelSum; + ans = level; + } + } + + return ans; + } +}; diff --git a/solutions/3157. Find the Level of Tree with Minimum Sum/3157.java b/solutions/3157. Find the Level of Tree with Minimum Sum/3157.java new file mode 100644 index 00000000000..0396ad64ba0 --- /dev/null +++ b/solutions/3157. Find the Level of Tree with Minimum Sum/3157.java @@ -0,0 +1,26 @@ +class Solution { + // Similar to 1161. Maximum Level Sum of a Binary Tree + public int minimumLevel(TreeNode root) { + int ans = 0; + long minLevelSum = Long.MAX_VALUE; + Queue q = new LinkedList<>(Arrays.asList(root)); + + for (int level = 1; !q.isEmpty(); ++level) { + long levelSum = 0; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + levelSum += node.val; + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + if (levelSum < minLevelSum) { + minLevelSum = levelSum; + ans = level; + } + } + + return ans; + } +} diff --git a/solutions/3157. Find the Level of Tree with Minimum Sum/3157.py b/solutions/3157. Find the Level of Tree with Minimum Sum/3157.py new file mode 100644 index 00000000000..257bba20163 --- /dev/null +++ b/solutions/3157. Find the Level of Tree with Minimum Sum/3157.py @@ -0,0 +1,23 @@ +class Solution: + # Similar to 1161. Maximum Level Sum of a Binary Tree + def minimumLevel(self, root: Optional[TreeNode]) -> int: + ans = 0 + minLevelSum = math.inf + q = collections.deque([root]) + + level = 1 + while q: + levelSum = 0 + for _ in range(len(q)): + node = q.popleft() + levelSum += node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if levelSum < minLevelSum: + minLevelSum = levelSum + ans = level + level += 1 + + return ans diff --git a/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.cpp b/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.cpp new file mode 100644 index 00000000000..52071c8ff2e --- /dev/null +++ b/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int duplicateNumbersXOR(vector& nums) { + constexpr int kMax = 50; + int ans = 0; + vector count(kMax + 1); + + for (const int num : nums) + ++count[num]; + + for (int num = 1; num <= kMax; ++num) + if (count[num] == 2) + ans ^= num; + + return ans; + } +}; diff --git a/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.java b/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.java new file mode 100644 index 00000000000..9b73c33378b --- /dev/null +++ b/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.java @@ -0,0 +1,16 @@ +class Solution { + public int duplicateNumbersXOR(int[] nums) { + final int kMax = 50; + int ans = 0; + int[] count = new int[kMax + 1]; + + for (final int num : nums) + ++count[num]; + + for (int num = 1; num <= kMax; ++num) + if (count[num] == 2) + ans ^= num; + + return ans; + } +} diff --git a/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.py b/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.py new file mode 100644 index 00000000000..7ce28f5facb --- /dev/null +++ b/solutions/3158. Find the XOR of Numbers Which Appear Twice/3158.py @@ -0,0 +1,5 @@ +class Solution: + def duplicateNumbersXOR(self, nums): + count = collections.Counter(nums) + return functools.reduce(operator.xor, + [num for num, freq in count.items() if freq == 2], 0) diff --git a/solutions/3159. Find Occurrences of an Element in an Array/3159.cpp b/solutions/3159. Find Occurrences of an Element in an Array/3159.cpp new file mode 100644 index 00000000000..00740d6b66b --- /dev/null +++ b/solutions/3159. Find Occurrences of an Element in an Array/3159.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector occurrencesOfElement(vector& nums, vector& queries, + int x) { + const vector indices = getIndices(nums, x); + vector ans; + + for (const int query : queries) + ans.push_back(query <= indices.size() ? indices[query - 1] : -1); + + return ans; + } + + private: + vector getIndices(const vector& nums, int x) { + vector indices; + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == x) + indices.push_back(i); + return indices; + } +}; diff --git a/solutions/3159. Find Occurrences of an Element in an Array/3159.java b/solutions/3159. Find Occurrences of an Element in an Array/3159.java new file mode 100644 index 00000000000..1199c85f07c --- /dev/null +++ b/solutions/3159. Find Occurrences of an Element in an Array/3159.java @@ -0,0 +1,19 @@ +class Solution { + public int[] occurrencesOfElement(int[] nums, int[] queries, int x) { + List indices = getIndices(nums, x); + int[] ans = new int[queries.length]; + + for (int i = 0; i < queries.length; i++) + ans[i] = queries[i] <= indices.size() ? indices.get(queries[i] - 1) : -1; + + return ans; + } + + private List getIndices(int[] nums, int x) { + List indices = new ArrayList<>(); + for (int i = 0; i < nums.length; ++i) + if (nums[i] == x) + indices.add(i); + return indices; + } +} diff --git a/solutions/3159. Find Occurrences of an Element in an Array/3159.py b/solutions/3159. Find Occurrences of an Element in an Array/3159.py new file mode 100644 index 00000000000..7f31820af69 --- /dev/null +++ b/solutions/3159. Find Occurrences of an Element in an Array/3159.py @@ -0,0 +1,5 @@ +class Solution: + def occurrencesOfElement(self, nums: List[int], queries: List[int], x: int) -> List[int]: + indices = [i for i, num in enumerate(nums) if num == x] + return [indices[query - 1] if query <= len(indices) else -1 + for query in queries] diff --git a/solutions/316. Remove Duplicate Letters/316.cpp b/solutions/316. Remove Duplicate Letters/316.cpp new file mode 100644 index 00000000000..c3be197b50b --- /dev/null +++ b/solutions/316. Remove Duplicate Letters/316.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string removeDuplicateLetters(string s) { + string ans; + vector count(128); + vector used(128); + + for (const char c : s) + ++count[c]; + + for (const char c : s) { + --count[c]; + if (used[c]) + continue; + while (!ans.empty() && ans.back() > c && count[ans.back()] > 0) { + used[ans.back()] = false; + ans.pop_back(); + } + used[c] = true; + ans.push_back(c); + } + + return ans; + } +}; diff --git a/solutions/316. Remove Duplicate Letters/316.java b/solutions/316. Remove Duplicate Letters/316.java new file mode 100644 index 00000000000..3e45eed342b --- /dev/null +++ b/solutions/316. Remove Duplicate Letters/316.java @@ -0,0 +1,28 @@ +class Solution { + public String removeDuplicateLetters(String s) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[128]; + boolean[] used = new boolean[128]; + + for (final char c : s.toCharArray()) + ++count[c]; + + for (final char c : s.toCharArray()) { + --count[c]; + if (used[c]) + continue; + while (sb.length() > 0 && last(sb) > c && count[last(sb)] > 0) { + used[last(sb)] = false; + sb.setLength(sb.length() - 1); + } + used[c] = true; + sb.append(c); + } + + return sb.toString(); + } + + private char last(StringBuilder sb) { + return sb.charAt(sb.length() - 1); + } +} diff --git a/solutions/316. Remove Duplicate Letters/316.py b/solutions/316. Remove Duplicate Letters/316.py new file mode 100644 index 00000000000..09b45009cd0 --- /dev/null +++ b/solutions/316. Remove Duplicate Letters/316.py @@ -0,0 +1,17 @@ +class Solution: + def removeDuplicateLetters(self, s: str) -> str: + ans = [] + count = collections.Counter(s) + used = [False] * 26 + + for c in s: + count[c] -= 1 + if used[ord(c) - ord('a')]: + continue + while ans and ans[-1] > c and count[ans[-1]] > 0: + used[ord(ans[-1]) - ord('a')] = False + ans.pop() + ans.append(c) + used[ord(ans[-1]) - ord('a')] = True + + return ''.join(ans) diff --git a/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.cpp b/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.cpp new file mode 100644 index 00000000000..bfb15d059ec --- /dev/null +++ b/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector queryResults(int limit, vector>& queries) { + vector ans; + unordered_map ballToColor; + unordered_map colorCount; + + for (const vector& query : queries) { + const int ball = query[0]; + const int color = query[1]; + if (const auto it = ballToColor.find(ball); it != ballToColor.cend()) { + const int prevColor = it->second; + if (--colorCount[prevColor] == 0) + colorCount.erase(prevColor); + } + ballToColor[ball] = color; + ++colorCount[color]; + ans.push_back(colorCount.size()); + } + + return ans; + } +}; diff --git a/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.java b/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.java new file mode 100644 index 00000000000..a2dcd8868bd --- /dev/null +++ b/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.java @@ -0,0 +1,22 @@ +class Solution { + public int[] queryResults(int limit, int[][] queries) { + int[] ans = new int[queries.length]; + Map ballToColor = new HashMap<>(); + Map colorCount = new HashMap<>(); + + for (int i = 0; i < queries.length; ++i) { + final int ball = queries[i][0]; + final int color = queries[i][1]; + if (ballToColor.containsKey(ball)) { + final int prevColor = ballToColor.get(ball); + if (colorCount.merge(prevColor, -1, Integer::sum) == 0) + colorCount.remove(prevColor); + } + ballToColor.put(ball, color); + colorCount.merge(color, 1, Integer::sum); + ans[i] = colorCount.size(); + } + + return ans; + } +} diff --git a/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.py b/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.py new file mode 100644 index 00000000000..41ede3caeee --- /dev/null +++ b/solutions/3160. Find the Number of Distinct Colors Among the Balls/3160.py @@ -0,0 +1,17 @@ +class Solution: + def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]: + ans = [] + ballToColor = {} + colorCount = collections.Counter() + + for ball, color in queries: + if ball in ballToColor: + prevColor = ballToColor[ball] + colorCount[prevColor] -= 1 + if colorCount[prevColor] == 0: + del colorCount[prevColor] + ballToColor[ball] = color + colorCount[color] += 1 + ans.append(len(colorCount)) + + return ans diff --git a/solutions/3161. Block Placement Queries/3161.cpp b/solutions/3161. Block Placement Queries/3161.cpp new file mode 100644 index 00000000000..255f943f8b9 --- /dev/null +++ b/solutions/3161. Block Placement Queries/3161.cpp @@ -0,0 +1,69 @@ +class FenwickTree { + public: + FenwickTree(int n) : vals(n + 1) {} + + void maximize(int i, int val) { + while (i < vals.size()) { + vals[i] = max(vals[i], val); + i += lowbit(i); + } + } + + int get(int i) const { + int res = 0; + while (i > 0) { + res = max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private: + vector vals; + + static int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + vector getResults(vector>& queries) { + const int n = min(50000, static_cast(queries.size()) * 3); + vector ans; + FenwickTree tree(n + 1); + set obstacles{0, n}; // sentinel values + + for (const vector& query : queries) { + const int type = query[0]; + if (type == 1) { + const int x = query[1]; + obstacles.insert(x); + } + } + + for (auto it = obstacles.begin(); std::next(it) != obstacles.end(); ++it) { + const int x1 = *it; + const int x2 = *std::next(it); + tree.maximize(x2, x2 - x1); + } + + for (int i = queries.size() - 1; i >= 0; --i) { + const int type = queries[i][0]; + const int x = queries[i][1]; + if (type == 1) { + const auto it = obstacles.find(x); + if (next(it) != obstacles.end()) // x is not the last element. + tree.maximize(*next(it), *next(it) - *prev(it)); + obstacles.erase(it); + } else { + const int sz = queries[i][2]; + const auto it = obstacles.upper_bound(x); + const int prev = *std::prev(it); + ans.push_back(tree.get(prev) >= sz || x - prev >= sz); + } + } + + return {ans.rbegin(), ans.rend()}; + } +}; diff --git a/solutions/3161. Block Placement Queries/3161.java b/solutions/3161. Block Placement Queries/3161.java new file mode 100644 index 00000000000..d44c75f8bf3 --- /dev/null +++ b/solutions/3161. Block Placement Queries/3161.java @@ -0,0 +1,71 @@ +class FenwickTree { + public FenwickTree(int n) { + vals = new int[n + 1]; + } + + public void add(int i, int val) { + while (i < vals.length) { + vals[i] = Math.max(vals[i], val); + i += lowbit(i); + } + } + + public int get(int i) { + int res = 0; + while (i > 0) { + res = Math.max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private int[] vals; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public List getResults(int[][] queries) { + final int n = Math.min(50000, queries.length * 3); + List ans = new ArrayList<>(); + FenwickTree tree = new FenwickTree(n + 1); + TreeSet obstacles = new TreeSet<>(Arrays.asList(0, n)); // sentinel values + + for (int[] query : queries) { + final int type = query[0]; + if (type == 1) { + final int x = query[1]; + obstacles.add(x); + } + } + + Iterator it = obstacles.iterator(); + int x1 = it.next(); + while (it.hasNext()) { + final int x2 = it.next(); + tree.add(x2, x2 - x1); + x1 = x2; + } + + for (int i = queries.length - 1; i >= 0; --i) { + final int type = queries[i][0]; + final int x = queries[i][1]; + if (type == 1) { + final Integer next = obstacles.higher(x); + final Integer prev = obstacles.lower(x); + if (next != null) + tree.add(next, next - prev); + obstacles.remove(x); + } else { + final int sz = queries[i][2]; + final int prev = obstacles.floor(x); + ans.add(tree.get(prev) >= sz || x - prev >= sz); + } + } + + Collections.reverse(ans); + return ans; + } +} diff --git a/solutions/3161. Block Placement Queries/3161.py b/solutions/3161. Block Placement Queries/3161.py new file mode 100644 index 00000000000..b31fac6b418 --- /dev/null +++ b/solutions/3161. Block Placement Queries/3161.py @@ -0,0 +1,56 @@ +from sortedcontainers import SortedList + + +class FenwickTree: + def __init__(self, n: int): + self.vals = [0] * (n + 1) + + def maximize(self, i: int, val: int) -> None: + while i < len(self.vals): + self.vals[i] = max(self.vals[i], val) + i += FenwickTree.lowtree(i) + + def get(self, i: int) -> int: + res = 0 + while i > 0: + res = max(res, self.vals[i]) + i -= FenwickTree.lowtree(i) + return res + + @staticmethod + def lowtree(i: int) -> int: + return i & -i + + +class Solution: + def getResults(self, queries: List[List[int]]) -> List[bool]: + n = min(50000, len(queries) * 3) + ans = [] + tree = FenwickTree(n + 1) + obstacles = SortedList([0, n]) # sentinel values + + for query in queries: + type = query[0] + if type == 1: + x = query[1] + obstacles.add(x) + + for x1, x2 in itertools.pairwise(obstacles): + tree.maximize(x2, x2 - x1) + + for query in reversed(queries): + type = query[0] + x = query[1] + if type == 1: + i = obstacles.index(x) + next = obstacles[i + 1] + prev = obstacles[i - 1] + obstacles.remove(x) + tree.maximize(next, next - prev) + else: + sz = query[2] + i = obstacles.bisect_right(x) + prev = obstacles[i - 1] + ans.append(tree.get(prev) >= sz or x - prev >= sz) + + return ans[::-1] diff --git a/solutions/3162. Find the Number of Good Pairs I/3162.cpp b/solutions/3162. Find the Number of Good Pairs I/3162.cpp new file mode 100644 index 00000000000..0359442f746 --- /dev/null +++ b/solutions/3162. Find the Number of Good Pairs I/3162.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int numberOfPairs(vector& nums1, vector& nums2, int k) { + int ans = 0; + for (const int num1 : nums1) + for (const int num2 : nums2) + if (num1 % (num2 * k) == 0) + ++ans; + return ans; + } +}; diff --git a/solutions/3162. Find the Number of Good Pairs I/3162.java b/solutions/3162. Find the Number of Good Pairs I/3162.java new file mode 100644 index 00000000000..40a99523253 --- /dev/null +++ b/solutions/3162. Find the Number of Good Pairs I/3162.java @@ -0,0 +1,10 @@ +class Solution { + public int numberOfPairs(int[] nums1, int[] nums2, int k) { + int ans = 0; + for (final int num1 : nums1) + for (final int num2 : nums2) + if (num1 % (num2 * k) == 0) + ++ans; + return ans; + } +} diff --git a/solutions/3162. Find the Number of Good Pairs I/3162.py b/solutions/3162. Find the Number of Good Pairs I/3162.py new file mode 100644 index 00000000000..b5d53f50c70 --- /dev/null +++ b/solutions/3162. Find the Number of Good Pairs I/3162.py @@ -0,0 +1,5 @@ +class Solution: + def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int: + return sum(num1 % (num2 * k) == 0 + for num1 in nums1 + for num2 in nums2) diff --git a/solutions/3163. String Compression III/3163.cpp b/solutions/3163. String Compression III/3163.cpp new file mode 100644 index 00000000000..85d26a064a7 --- /dev/null +++ b/solutions/3163. String Compression III/3163.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string compressedString(string word) { + const int n = word.length(); + string ans; + + for (int i = 0, j = 0; i < n; i = j) { + int count = 0; + while (j < n && word[j] == word[i] && count < 9) { + ++j; + ++count; + } + ans += to_string(count) + word[i]; + } + + return ans; + } +}; diff --git a/solutions/3163. String Compression III/3163.java b/solutions/3163. String Compression III/3163.java new file mode 100644 index 00000000000..0ce252e4875 --- /dev/null +++ b/solutions/3163. String Compression III/3163.java @@ -0,0 +1,17 @@ +class Solution { + public String compressedString(String word) { + final int n = word.length(); + StringBuilder sb = new StringBuilder(); + + for (int i = 0, j = 0; i < n; i = j) { + int count = 0; + while (j < n && word.charAt(j) == word.charAt(i) && count < 9) { + ++j; + ++count; + } + sb.append(String.valueOf(count)).append(word.charAt(i)); + } + + return sb.toString(); + } +} diff --git a/solutions/3163. String Compression III/3163.py b/solutions/3163. String Compression III/3163.py new file mode 100644 index 00000000000..2e7c72cdba2 --- /dev/null +++ b/solutions/3163. String Compression III/3163.py @@ -0,0 +1,16 @@ +class Solution: + def compressedString(self, word: str) -> str: + n = len(word) + ans = [] + i = 0 + j = 0 + + while i < n: + count = 0 + while j < n and word[j] == word[i] and count < 9: + j += 1 + count += 1 + ans.append(str(count) + word[i]) + i = j + + return ''.join(ans) diff --git a/solutions/3164. Find the Number of Good Pairs II/3164.cpp b/solutions/3164. Find the Number of Good Pairs II/3164.cpp new file mode 100644 index 00000000000..5eb753ec68e --- /dev/null +++ b/solutions/3164. Find the Number of Good Pairs II/3164.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + long long numberOfPairs(vector& nums1, vector& nums2, int k) { + unordered_map count; + long ans = 0; + + for (const int num : nums2) + ++count[num * k]; + + for (const int num : nums1) + for (int divisor = 1; divisor <= sqrt(num); ++divisor) + if (num % divisor == 0) { + ans += count.contains(divisor) ? count[divisor] : 0; + if (num / divisor != divisor) + ans += count.contains(num / divisor) ? count[num / divisor] : 0; + } + + return ans; + } +}; diff --git a/solutions/3164. Find the Number of Good Pairs II/3164.java b/solutions/3164. Find the Number of Good Pairs II/3164.java new file mode 100644 index 00000000000..3407725857f --- /dev/null +++ b/solutions/3164. Find the Number of Good Pairs II/3164.java @@ -0,0 +1,19 @@ +class Solution { + public long numberOfPairs(int[] nums1, int[] nums2, int k) { + HashMap count = new HashMap<>(); + long ans = 0; + + for (final int num : nums2) + count.merge(num * k, 1, Integer::sum); + + for (final int num : nums1) + for (int divisor = 1; divisor <= (int) Math.sqrt(num); ++divisor) + if (num % divisor == 0) { + ans += count.getOrDefault(divisor, 0); + if (num / divisor != divisor) + ans += count.getOrDefault(num / divisor, 0); + } + + return ans; + } +} diff --git a/solutions/3164. Find the Number of Good Pairs II/3164.py b/solutions/3164. Find the Number of Good Pairs II/3164.py new file mode 100644 index 00000000000..8db6cbd6633 --- /dev/null +++ b/solutions/3164. Find the Number of Good Pairs II/3164.py @@ -0,0 +1,13 @@ +class Solution: + def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int: + count = collections.Counter(num * k for num in nums2) + ans = 0 + + for num in nums1: + for divisor in range(1, int(num ** 0.5) + 1): + if num % divisor == 0: + ans += count[divisor] + if num // divisor != divisor: + ans += count[num // divisor] + + return ans diff --git a/solutions/3165. Maximum Sum of Subsequence With Non-adjacent Elements/3165.cpp b/solutions/3165. Maximum Sum of Subsequence With Non-adjacent Elements/3165.cpp new file mode 100644 index 00000000000..301b71f51f2 --- /dev/null +++ b/solutions/3165. Maximum Sum of Subsequence With Non-adjacent Elements/3165.cpp @@ -0,0 +1,98 @@ +using NodeType = array, 2>; + +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) : n(nums.size()), tree(4 * n) { + build(nums, 0, 0, n - 1); + } + + // Updates nums[i] to val. + void update(int i, int val) { + update(0, 0, n - 1, i, val); + } + + // Returns the four values of the range query from nums[i..j]. + // + // The four values are: + // 1. nums[i] is not selected, nums[j] is not selected + // 2. nums[i] is not selected, nums[j] is selected + // 3. nums[i] is selected, nums[j] is not selected + // 4. nums[i] is selected, nums[j] is selected + NodeType query(int i, int j) const { + return query(0, 0, n - 1, i, j); + } + + private: + static constexpr int kInf = 1'000'000'000; + static constexpr NodeType kDefaultNode = {{{-kInf, -kInf}, {-kInf, -kInf}}}; + const int n; // the size of the input array + // tree[i][l][r] := the value of the i-th node, where `l` and `r` represent if + // the leftmost or rightmost element is selected, respectively + vector tree; + + void build(const vector& nums, int treeIndex, int lo, int hi) { + if (lo == hi) { + tree[treeIndex] = {{{0, -kInf}, {-kInf, nums[lo]}}}; + return; + } + const int mid = (lo + hi) / 2; + build(nums, 2 * treeIndex + 1, lo, mid); + build(nums, 2 * treeIndex + 2, mid + 1, hi); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + void update(int treeIndex, int lo, int hi, int i, int val) { + if (lo == hi) { + tree[treeIndex] = {{{0, -kInf}, {-kInf, val}}}; + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + update(2 * treeIndex + 1, lo, mid, i, val); + else + update(2 * treeIndex + 2, mid + 1, hi, i, val); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + NodeType query(int treeIndex, int lo, int hi, int i, int j) const { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return kDefaultNode; + const int mid = (lo + hi) / 2; + return merge(query(2 * treeIndex + 1, lo, mid, i, j), + query(2 * treeIndex + 2, mid + 1, hi, i, j)); + } + + // Merges the result of the left node and the right node. + NodeType merge(const NodeType& a, const NodeType& b) const { + NodeType node = {{{0, 0}, {0, 0}}}; + for (int l = 0; l < 2; ++l) + for (int r = 0; r < 2; ++r) + node[l][r] = + max({a[l][0] + b[0][r], a[l][0] + b[1][r], a[l][1] + b[0][r]}); + return node; + } +}; + +class Solution { + public: + int maximumSumSubsequence(vector& nums, vector>& queries) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + int ans = 0; + SegmentTree tree(nums); + + for (const vector& query : queries) { + const int pos = query[0]; + const int x = query[1]; + tree.update(pos, x); + NodeType res = tree.query(0, n - 1); + ans = (ans + static_cast( + max({res[0][0], res[0][1], res[1][0], res[1][1]}))) % + kMod; + } + + return ans; + } +}; diff --git a/solutions/3166. Calculate Parking Fees and Duration/3166.sql b/solutions/3166. Calculate Parking Fees and Duration/3166.sql new file mode 100644 index 00000000000..eef50503f53 --- /dev/null +++ b/solutions/3166. Calculate Parking Fees and Duration/3166.sql @@ -0,0 +1,37 @@ +WITH + Cars AS ( + SELECT + car_id, + SUM(fee_paid) AS total_fee_paid, + SUM(TIMESTAMPDIFF(MINUTE, entry_time, exit_time)) AS total_duration + FROM ParkingTransactions + GROUP BY 1 + ), + CarToDurationPerLot AS ( + SELECT + car_id, + lot_id, + SUM(TIMESTAMPDIFF(MINUTE, entry_time, exit_time)) AS duration_per_lot + FROM ParkingTransactions + GROUP BY 1, 2 + ), + CarToMaxDurationPerLot AS ( + SELECT + car_id, + MAX(duration_per_lot) AS max_duration_per_lot + FROM CarToDurationPerLot + GROUP BY 1 + ) +SELECT + Cars.car_id, + Cars.total_fee_paid, + ROUND(Cars.total_fee_paid * 60 / Cars.total_duration, 2) AS avg_hourly_fee, + CarToDurationPerLot.lot_id AS most_time_lot +FROM Cars +INNER JOIN CarToDurationPerLot + USING (car_id) +INNER JOIN CarToMaxDurationPerLot + USING (car_id) +WHERE + CarToDurationPerLot.duration_per_lot = CarToMaxDurationPerLot.max_duration_per_lot +ORDER BY 1; diff --git a/solutions/3167. Better Compression of String/3167.cpp b/solutions/3167. Better Compression of String/3167.cpp new file mode 100644 index 00000000000..657c8a99c2d --- /dev/null +++ b/solutions/3167. Better Compression of String/3167.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string betterCompression(string compressed) { + string ans; + vector count(26); + + for (int i = 0; i < compressed.length();) { + const char c = compressed[i++]; + int freq = 0; + while (i < compressed.length() && isdigit(compressed[i])) + freq = freq * 10 + (compressed[i++] - '0'); + count[c - 'a'] += freq; + } + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c - 'a'] > 0) + ans += c + to_string(count[c - 'a']); + + return ans; + } +}; diff --git a/solutions/3167. Better Compression of String/3167.java b/solutions/3167. Better Compression of String/3167.java new file mode 100644 index 00000000000..da226a6c334 --- /dev/null +++ b/solutions/3167. Better Compression of String/3167.java @@ -0,0 +1,20 @@ +class Solution { + public String betterCompression(String compressed) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[26]; + + for (int i = 0; i < compressed.length();) { + final char c = compressed.charAt(i++); + int freq = 0; + while (i < compressed.length() && Character.isDigit(compressed.charAt(i))) + freq = freq * 10 + (compressed.charAt(i++) - '0'); + count[c - 'a'] += freq; + } + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c - 'a'] > 0) + sb.append(c).append(count[c - 'a']); + + return sb.toString(); + } +} diff --git a/solutions/3167. Better Compression of String/3167.py b/solutions/3167. Better Compression of String/3167.py new file mode 100644 index 00000000000..525c73d2619 --- /dev/null +++ b/solutions/3167. Better Compression of String/3167.py @@ -0,0 +1,16 @@ +class Solution: + def betterCompression(self, compressed: str) -> str: + count = collections.Counter() + i = 0 + + while i < len(compressed): + c = compressed[i] + i += 1 + freq = 0 + while i < len(compressed) and compressed[i].isdigit(): + freq = freq * 10 + int(compressed[i]) + i += 1 + count[c] += freq + + return ''.join([c + str(count[c]) + for c in sorted(count.keys())]) diff --git a/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.cpp b/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.cpp new file mode 100644 index 00000000000..111fdd5bff4 --- /dev/null +++ b/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int minimumChairs(string s) { + int ans = 0; + int chairs = 0; + + for (const char c : s) { + chairs += c == 'E' ? 1 : -1; + ans = max(ans, chairs); + } + + return ans; + } +}; diff --git a/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.java b/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.java new file mode 100644 index 00000000000..69040afd8d9 --- /dev/null +++ b/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.java @@ -0,0 +1,13 @@ +class Solution { + public int minimumChairs(String s) { + int ans = 0; + int chairs = 0; + + for (final char c : s.toCharArray()) { + chairs += c == 'E' ? 1 : -1; + ans = Math.max(ans, chairs); + } + + return ans; + } +} diff --git a/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.py b/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.py new file mode 100644 index 00000000000..67dc9ab0f95 --- /dev/null +++ b/solutions/3168. Minimum Number of Chairs in a Waiting Room/3168.py @@ -0,0 +1,10 @@ +class Solution: + def minimumChairs(self, s: str) -> int: + ans = 0 + chairs = 0 + + for c in s: + chairs += 1 if c == 'E' else -1 + ans = max(ans, chairs) + + return ans diff --git a/solutions/3169. Count Days Without Meetings/3169.cpp b/solutions/3169. Count Days Without Meetings/3169.cpp new file mode 100644 index 00000000000..c1ac1da800d --- /dev/null +++ b/solutions/3169. Count Days Without Meetings/3169.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countDays(int days, vector>& meetings) { + int freeDays = 0; + int prevEnd = 0; + + ranges::sort(meetings); + + for (const vector& meeting : meetings) { + const int start = meeting[0]; + const int end = meeting[1]; + if (start > prevEnd) + freeDays += start - prevEnd - 1; + prevEnd = max(prevEnd, end); + } + + return freeDays + max(0, days - prevEnd); + } +}; diff --git a/solutions/3169. Count Days Without Meetings/3169.java b/solutions/3169. Count Days Without Meetings/3169.java new file mode 100644 index 00000000000..86b760c4802 --- /dev/null +++ b/solutions/3169. Count Days Without Meetings/3169.java @@ -0,0 +1,18 @@ +class Solution { + public int countDays(int days, int[][] meetings) { + int freeDays = 0; + int prevEnd = 0; + + Arrays.sort(meetings, (a, b) -> a[0] - b[0]); + + for (int[] meeting : meetings) { + final int start = meeting[0]; + final int end = meeting[1]; + if (start > prevEnd) + freeDays += start - prevEnd - 1; + prevEnd = Math.max(prevEnd, end); + } + + return freeDays + Math.max(0, days - prevEnd); + } +} diff --git a/solutions/3169. Count Days Without Meetings/3169.py b/solutions/3169. Count Days Without Meetings/3169.py new file mode 100644 index 00000000000..78114e02d06 --- /dev/null +++ b/solutions/3169. Count Days Without Meetings/3169.py @@ -0,0 +1,11 @@ +class Solution: + def countDays(self, days: int, meetings: List[List[int]]) -> int: + freeDays = 0 + prevEnd = 0 + + for start, end in sorted(meetings): + if start > prevEnd: + freeDays += start - prevEnd - 1 + prevEnd = max(prevEnd, end) + + return freeDays + max(0, days - prevEnd) diff --git a/solutions/317. Shortest Distance from All Buildings/317.cpp b/solutions/317. Shortest Distance from All Buildings/317.cpp new file mode 100644 index 00000000000..66a78dd6f2f --- /dev/null +++ b/solutions/317. Shortest Distance from All Buildings/317.cpp @@ -0,0 +1,70 @@ +class Solution { + public: + int shortestDistance(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + const int nBuildings = getBuildingsCount(grid); + int ans = INT_MAX; + // dist[i][j] := the total distance of grid[i][j] (0) to reach all the + // buildings (1) + vector> dist(m, vector(n)); + // reachCount[i][j] := the number of buildings (1) grid[i][j] (0) can reach + vector> reachCount(m, vector(n)); + + auto bfs = [&](int row, int col) -> bool { + queue> q{{{row, col}}}; + vector> seen(m, vector(n)); + seen[row][col] = true; + int depth = 0; + int seenBuildings = 1; + + while (!q.empty()) { + ++depth; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + seen[x][y] = true; + if (!grid[x][y]) { + dist[x][y] += depth; + ++reachCount[x][y]; + q.emplace(x, y); + } else if (grid[x][y] == 1) { + ++seenBuildings; + } + } + } + } + + return seenBuildings == nBuildings; + }; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) // BFS from this building. + if (!bfs(i, j)) + return -1; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (reachCount[i][j] == nBuildings) + ans = min(ans, dist[i][j]); + + return ans == INT_MAX ? -1 : ans; + } + + private: + int getBuildingsCount(vector>& grid) { + return accumulate(grid.begin(), grid.end(), 0, + [](int subtotal, vector& row) { + return subtotal + ranges::count(row, 1); + }); + } +}; diff --git a/solutions/317. Shortest Distance from All Buildings/317.java b/solutions/317. Shortest Distance from All Buildings/317.java new file mode 100644 index 00000000000..2579e3ed868 --- /dev/null +++ b/solutions/317. Shortest Distance from All Buildings/317.java @@ -0,0 +1,76 @@ +class Solution { + public int shortestDistance(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + final int nBuildings = getBuildingsCount(grid); + int ans = Integer.MAX_VALUE; + // dist[i][j] := the total distance of grid[i][j] (0) to reach all the + // buildings (1) + int[][] dist = new int[m][n]; + // reachCount[i][j] := the number of buildings (1) grid[i][j] (0) can reach + int[][] reachCount = new int[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) // BFS from this building. + if (!bfs(grid, i, j, dist, reachCount, nBuildings)) + return -1; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (reachCount[i][j] == nBuildings) + ans = Math.min(ans, dist[i][j]); + + return ans == Integer.MAX_VALUE ? -1 : ans; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private boolean bfs(int[][] grid, int row, int col, int[][] dist, int[][] reachCount, + int nBuildings) { + final int m = grid.length; + final int n = grid[0].length; + + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {row, col})); + boolean[][] seen = new boolean[m][n]; + seen[row][col] = true; + int depth = 0; + int seenBuildings = 1; + + while (!q.isEmpty()) { + ++depth; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + seen[x][y] = true; + if (grid[x][y] == 0) { + + dist[x][y] += depth; + ++reachCount[x][y]; + q.offer(new int[] {x, y}); + } else if (grid[x][y] == 1) { + ++seenBuildings; + } + } + } + } + + return seenBuildings == nBuildings; + } + + private int getBuildingsCount(int[][] grid) { + int buildingCount = 0; + for (int[] row : grid) + for (final int cell : row) + if (cell == 1) + ++buildingCount; + return buildingCount; + } +} diff --git a/solutions/317. Shortest Distance from All Buildings/317.py b/solutions/317. Shortest Distance from All Buildings/317.py new file mode 100644 index 00000000000..2b1c3d48214 --- /dev/null +++ b/solutions/317. Shortest Distance from All Buildings/317.py @@ -0,0 +1,53 @@ +class Solution: + def shortestDistance(self, grid: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(grid) + n = len(grid[0]) + nBuildings = sum(a == 1 for row in grid for a in row) + ans = math.inf + # dist[i][j] := the total distance of grid[i][j] (0) to reach all the + # buildings (1) + dist = [[0] * n for _ in range(m)] + # reachCount[i][j] := the number of buildings (1) grid[i][j] (0) can reach + reachCount = [[0] * n for _ in range(m)] + + def bfs(row: int, col: int) -> bool: + q = collections.deque([(row, col)]) + seen = {(row, col)} + depth = 0 + seenBuildings = 1 + + while q: + depth += 1 + for _ in range(len(q)): + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if (x, y) in seen: + continue + seen.add((x, y)) + if not grid[x][y]: + dist[x][y] += depth + reachCount[x][y] += 1 + q.append((x, y)) + elif grid[x][y] == 1: + seenBuildings += 1 + + # True if all the buildings (1) are connected + return seenBuildings == nBuildings + + for i in range(m): + for j in range(n): + if grid[i][j] == 1: # BFS from this building. + if not bfs(i, j): + return -1 + + for i in range(m): + for j in range(n): + if reachCount[i][j] == nBuildings: + ans = min(ans, dist[i][j]) + + return -1 if ans == math.inf else ans diff --git a/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.cpp b/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.cpp new file mode 100644 index 00000000000..760f9bb0c7a --- /dev/null +++ b/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string clearStars(string s) { + string ans = s; + vector> buckets(26); + + for (int i = 0; i < s.length(); ++i) + if (s[i] == '*') { + ans[i] = ' '; + int j = 0; + while (buckets[j].empty()) + ++j; + ans[buckets[j].back()] = ' ', buckets[j].pop_back(); + } else { + buckets[s[i] - 'a'].push_back(i); + } + + std::erase(ans, ' '); + return ans; + } +}; diff --git a/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.java b/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.java new file mode 100644 index 00000000000..674534fdd0e --- /dev/null +++ b/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.java @@ -0,0 +1,22 @@ +class Solution { + public String clearStars(String s) { + StringBuilder sb = new StringBuilder(s); + List[] buckets = new List[26]; + + for (int i = 0; i < 26; ++i) + buckets[i] = new ArrayList<>(); + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) == '*') { + sb.setCharAt(i, ' '); + int j = 0; + while (buckets[j].isEmpty()) + ++j; + sb.setCharAt(buckets[j].remove(buckets[j].size() - 1), ' '); + } else { + buckets[s.charAt(i) - 'a'].add(i); + } + + return sb.toString().replaceAll(" ", ""); + } +} diff --git a/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.py b/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.py new file mode 100644 index 00000000000..05ca9cf9548 --- /dev/null +++ b/solutions/3170. Lexicographically Minimum String After Removing Stars/3170.py @@ -0,0 +1,14 @@ +class Solution: + def clearStars(self, s: str) -> str: + ans = list(s) + buckets = [[] for _ in range(26)] + + for i, c in enumerate(s): + if c == '*': + ans[i] = '' + j = next(j for j, bucket in enumerate(buckets) if bucket) + ans[buckets[j].pop()] = '' + else: + buckets[ord(c) - ord('a')].append(i) + + return ''.join(ans) diff --git a/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.cpp b/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.cpp new file mode 100644 index 00000000000..d441869159d --- /dev/null +++ b/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + // Same as 1521. Find a Value of a Mysterious Function Closest to Target + int minimumDifference(vector& nums, int k) { + int ans = INT_MAX; + // all the values of subarrays that end in the previous number + unordered_set prev; + + for (const int num : nums) { + unordered_set next{num}; + // Extend each subarray that ends in the previous number. Due to + // monotonicity of the AND operation, the size of `next` will be at most + // num.bit_count() + 1. + for (const int val : prev) + next.insert(val & num); + for (const int val : next) + ans = min(ans, abs(k - val)); + prev = move(next); + } + + return ans; + } +}; diff --git a/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.java b/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.java new file mode 100644 index 00000000000..8bbfa5ab292 --- /dev/null +++ b/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.java @@ -0,0 +1,22 @@ +class Solution { + // Same as 1521. Find a Value of a Mysterious Function Closest to Target + public int minimumDifference(int[] nums, int k) { + int ans = Integer.MAX_VALUE; + // all the values of subarrays that end in the previous number + Set prev = new HashSet<>(); + + for (final int num : nums) { + HashSet next = new HashSet<>(Arrays.asList(num)); + // Extend each subarray that ends in the previous number. Due to + // monotonicity of the AND operation, the size of `next` will be at most + // Integer.bitCount(num) + 1. + for (final int val : prev) + next.add(val & num); + for (final int val : next) + ans = Math.min(ans, Math.abs(k - val)); + prev = next; + } + + return ans; + } +} diff --git a/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.py b/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.py new file mode 100644 index 00000000000..35fb2c01390 --- /dev/null +++ b/solutions/3171. Find Subarray With Bitwise AND Closest to K/3171.py @@ -0,0 +1,14 @@ +class Solution: + # Same as 1521. Find a Value of a Mysterious Function Closest to Target + def minimumDifference(self, nums: List[int], k: int) -> int: + ans = math.inf + dp = set() # all the values of subarrays that end in the current number + + for num in nums: + # Extend each subarray that ends in the dpious number. Due to + # monotonicity of the AND operation, the size of `next_set` will be at most + # bin(num).count('1') + 1. + dp = {num} | {val & num for val in dp} + ans = min(ans, min(abs(k - val) for val in dp)) + + return ans diff --git a/solutions/3172. Second Day Verification/3172.sql b/solutions/3172. Second Day Verification/3172.sql new file mode 100644 index 00000000000..eb8d4267314 --- /dev/null +++ b/solutions/3172. Second Day Verification/3172.sql @@ -0,0 +1,8 @@ +SELECT Emails.user_id +FROM Emails +INNER JOIN Texts + USING (email_id) +WHERE + Texts.signup_action = 'Verified' + AND DATEDIFF(Texts.action_date, Emails.signup_date) = 1 +ORDER BY 1; diff --git a/solutions/3173. Bitwise OR of Adjacent Elements/3173.cpp b/solutions/3173. Bitwise OR of Adjacent Elements/3173.cpp new file mode 100644 index 00000000000..4685d97b5d6 --- /dev/null +++ b/solutions/3173. Bitwise OR of Adjacent Elements/3173.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + vector orArray(vector& nums) { + vector ans; + for (int i = 1; i < nums.size(); ++i) + ans.push_back(nums[i - 1] | nums[i]); + return ans; + } +}; diff --git a/solutions/3173. Bitwise OR of Adjacent Elements/3173.java b/solutions/3173. Bitwise OR of Adjacent Elements/3173.java new file mode 100644 index 00000000000..9d630de8d0b --- /dev/null +++ b/solutions/3173. Bitwise OR of Adjacent Elements/3173.java @@ -0,0 +1,8 @@ +class Solution { + public int[] orArray(int[] nums) { + int[] ans = new int[nums.length - 1]; + for (int i = 0; i < nums.length - 1; ++i) + ans[i] = nums[i] | nums[i + 1]; + return ans; + } +} diff --git a/solutions/3173. Bitwise OR of Adjacent Elements/3173.py b/solutions/3173. Bitwise OR of Adjacent Elements/3173.py new file mode 100644 index 00000000000..eadbb576103 --- /dev/null +++ b/solutions/3173. Bitwise OR of Adjacent Elements/3173.py @@ -0,0 +1,3 @@ +class Solution: + def orArray(self, nums: List[int]) -> List[int]: + return [a | b for a, b in itertools.pairwise(nums)] diff --git a/solutions/3174. Clear Digits/3174.cpp b/solutions/3174. Clear Digits/3174.cpp new file mode 100644 index 00000000000..a609d8a7bac --- /dev/null +++ b/solutions/3174. Clear Digits/3174.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + string clearDigits(string s) { + string ans; + + for (const char c : s) + if (isdigit(c)) + // Since `ans` only contains non-digit characters, popping the last + // character is equivalent to deleting the closest non-digit character. + ans.pop_back(); + else + ans += c; + + return ans; + } +}; diff --git a/solutions/3174. Clear Digits/3174.java b/solutions/3174. Clear Digits/3174.java new file mode 100644 index 00000000000..3400a5a99c0 --- /dev/null +++ b/solutions/3174. Clear Digits/3174.java @@ -0,0 +1,15 @@ +class Solution { + public String clearDigits(String s) { + StringBuilder sb = new StringBuilder(); + + for (final char c : s.toCharArray()) + if (Character.isDigit(c)) + // Since `sb` only contains non-digit characters, popping the last + // character is equivalent to deleting the closest non-digit character. + sb.setLength(sb.length() - 1); + else + sb.append(c); + + return sb.toString(); + } +} diff --git a/solutions/3174. Clear Digits/3174.py b/solutions/3174. Clear Digits/3174.py new file mode 100644 index 00000000000..cf9f7ee0eb4 --- /dev/null +++ b/solutions/3174. Clear Digits/3174.py @@ -0,0 +1,13 @@ +class Solution: + def clearDigits(self, s: str) -> str: + ans = [] + + for c in s: + if c.isdigit(): + # Since `ans` only contains non-digit characters, removing the last + # character is equivalent to deleting the closest non-digit character. + ans.pop() + else: + ans.append(c) + + return ''.join(ans) diff --git a/solutions/3175. Find The First Player to win K Games in a Row/3175.cpp b/solutions/3175. Find The First Player to win K Games in a Row/3175.cpp new file mode 100644 index 00000000000..b2df72b2b51 --- /dev/null +++ b/solutions/3175. Find The First Player to win K Games in a Row/3175.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + // Similar to 1535. Find the Winner of an Array Game + int findWinningPlayer(vector& skills, int k) { + int ans = 0; + int wins = 0; + + for (int i = 1; i < skills.size() && wins < k; ++i) + if (skills[i] > skills[ans]) { + ans = i; + wins = 1; + } else { + ++wins; + } + + return ans; + } +}; diff --git a/solutions/3175. Find The First Player to win K Games in a Row/3175.java b/solutions/3175. Find The First Player to win K Games in a Row/3175.java new file mode 100644 index 00000000000..4bbba3a98ab --- /dev/null +++ b/solutions/3175. Find The First Player to win K Games in a Row/3175.java @@ -0,0 +1,17 @@ +class Solution { + // Similar to 1535. Find the Winner of an Array Game + public int findWinningPlayer(int[] skills, int k) { + int ans = 0; + int wins = 0; + + for (int i = 1; i < skills.length && wins < k; ++i) + if (skills[i] > skills[ans]) { + ans = i; + wins = 1; + } else { + ++wins; + } + + return ans; + } +} diff --git a/solutions/3175. Find The First Player to win K Games in a Row/3175.py b/solutions/3175. Find The First Player to win K Games in a Row/3175.py new file mode 100644 index 00000000000..d8f70060337 --- /dev/null +++ b/solutions/3175. Find The First Player to win K Games in a Row/3175.py @@ -0,0 +1,16 @@ +class Solution: + # Similar to 1535. Find the Winner of an Array Game + def findWinningPlayer(self, skills: List[int], k: int) -> int: + ans = 0 + wins = 0 + + i = 1 + while i < len(skills) and wins < k: + if skills[i] > skills[ans]: + ans = i + wins = 1 + else: + wins += 1 + i += 1 + + return ans diff --git a/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.cpp b/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.cpp new file mode 100644 index 00000000000..514d161a7c9 --- /dev/null +++ b/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maximumLength(vector& nums, int k) { + // dp[count][num] := the maximum length of a good subsequence with at most + // `count` indices where seq[i] != seq[i + 1] and it ends in `num`. + vector> dp(k + 1); + // maxLen[count] := the maximum length of a good subsequence with `count` + // indices where seq[i] != seq[i + 1] + vector maxLen(k + 1); + + for (const int num : nums) + for (int count = k; count >= 0; --count) { + // Append `num` to the subsequence. + ++dp[count][num]; + if (count > 0) + dp[count][num] = max(dp[count][num], maxLen[count - 1] + 1); + maxLen[count] = max(maxLen[count], dp[count][num]); + } + + return maxLen[k]; + } +}; diff --git a/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.java b/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.java new file mode 100644 index 00000000000..690232cabd7 --- /dev/null +++ b/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.java @@ -0,0 +1,24 @@ +class Solution { + public int maximumLength(int[] nums, int k) { + // dp[count][num] := the maximum length of a good subsequence with at most + // `count` indices where seq[i] != seq[i + 1] and it ends in `num`. + Map[] dp = new HashMap[k + 1]; + // maxLen[count] := the maximum length of a good subsequence with `count` + // indices where seq[i] != seq[i + 1] + int[] maxLen = new int[k + 1]; + + for (int i = 0; i <= k; ++i) + dp[i] = new HashMap<>(); + + for (final int num : nums) + for (int count = k; count >= 0; --count) { + // Append `num` to the subsequence. + dp[count].merge(num, 1, Integer::sum); + if (count > 0) + dp[count].merge(num, maxLen[count - 1] + 1, Math::max); + maxLen[count] = Math.max(maxLen[count], dp[count].get(num)); + } + + return maxLen[k]; + } +} diff --git a/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.py b/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.py new file mode 100644 index 00000000000..d357753f479 --- /dev/null +++ b/solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.py @@ -0,0 +1,18 @@ +class Solution: + def maximumLength(self, nums: List[int], k: int) -> int: + # dp[count][num] := the maximum length of a good subsequence with at most + # `count` indices where seq[i] != seq[i + 1] and it ends in `num`. + dp = [collections.Counter() for _ in range(k + 1)] + # maxLen[count] := the maximum length of a good subsequence with `count` + # indices where seq[i] != seq[i + 1] + maxLen = [0] * (k + 1) + + for num in nums: + for count in range(k, -1, -1): + # Append `num` to the subsequence. + dp[count][num] += 1 + if count > 0: + dp[count][num] = max(dp[count][num], maxLen[count - 1] + 1) + maxLen[count] = max(maxLen[count], dp[count][num]) + + return maxLen[k] diff --git a/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.cpp b/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.cpp new file mode 100644 index 00000000000..deed31a0b92 --- /dev/null +++ b/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + // Same as 3176. Find the Maximum Length of a Good Subsequence I + int maximumLength(vector& nums, int k) { + // dp[count][num] := the maximum length of a good subsequence with at most + // `count` indices where seq[i] != seq[i + 1] and it ends in `num`. + vector> dp(k + 1); + // maxLen[count] := the maximum length of a good subsequence with `count` + // indices where seq[i] != seq[i + 1] + vector maxLen(k + 1); + + for (const int num : nums) + for (int count = k; count >= 0; --count) { + // Append `num` to the subsequence. + ++dp[count][num]; + if (count > 0) + dp[count][num] = max(dp[count][num], maxLen[count - 1] + 1); + maxLen[count] = max(maxLen[count], dp[count][num]); + } + + return maxLen[k]; + } +}; diff --git a/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.java b/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.java new file mode 100644 index 00000000000..5cee47f7aaa --- /dev/null +++ b/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.java @@ -0,0 +1,25 @@ +class Solution { + // Same as 3176. Find the Maximum Length of a Good Subsequence I + public int maximumLength(int[] nums, int k) { + // dp[count][num] := the maximum length of a good subsequence with at most + // `count` indices where seq[i] != seq[i + 1] and it ends in `num`. + Map[] dp = new HashMap[k + 1]; + // maxLen[count] := the maximum length of a good subsequence with `count` + // indices where seq[i] != seq[i + 1] + int[] maxLen = new int[k + 1]; + + for (int i = 0; i <= k; ++i) + dp[i] = new HashMap<>(); + + for (final int num : nums) + for (int count = k; count >= 0; --count) { + // Append `num` to the subsequence. + dp[count].merge(num, 1, Integer::sum); + if (count > 0) + dp[count].merge(num, maxLen[count - 1] + 1, Math::max); + maxLen[count] = Math.max(maxLen[count], dp[count].get(num)); + } + + return maxLen[k]; + } +} diff --git a/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.py b/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.py new file mode 100644 index 00000000000..bd71fdf442a --- /dev/null +++ b/solutions/3177. Find the Maximum Length of a Good Subsequence II/3177.py @@ -0,0 +1,19 @@ +class Solution: + # Same as 3176. Find the Maximum Length of a Good Subsequence I + def maximumLength(self, nums: List[int], k: int) -> int: + # dp[count][num] := the maximum length of a good subsequence with at most + # `count` indices where seq[i] != seq[i + 1] and it ends in `num`. + dp = [collections.Counter() for _ in range(k + 1)] + # maxLen[count] := the maximum length of a good subsequence with `count` + # indices where seq[i] != seq[i + 1] + maxLen = [0] * (k + 1) + + for num in nums: + for count in range(k, -1, -1): + # Append `num` to the subsequence. + dp[count][num] += 1 + if count > 0: + dp[count][num] = max(dp[count][num], maxLen[count - 1] + 1) + maxLen[count] = max(maxLen[count], dp[count][num]) + + return maxLen[k] diff --git a/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.cpp b/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.cpp new file mode 100644 index 00000000000..9a9927768fc --- /dev/null +++ b/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int numberOfChild(int n, int k) { + // the time for the ball to return to 0 + const int roundTime = 2 * (n - 1); + const int pos = k % roundTime; + return pos < n ? pos : roundTime - pos; + } +}; diff --git a/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.java b/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.java new file mode 100644 index 00000000000..036d8c50856 --- /dev/null +++ b/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.java @@ -0,0 +1,8 @@ +class Solution { + public int numberOfChild(int n, int k) { + // the time for the ball to return to 0 + final int roundTime = 2 * (n - 1); + final int pos = k % roundTime; + return pos < n ? pos : roundTime - pos; + } +} diff --git a/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.py b/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.py new file mode 100644 index 00000000000..b94420cdaa5 --- /dev/null +++ b/solutions/3178. Find the Child Who Has the Ball After K Seconds/3178.py @@ -0,0 +1,6 @@ +class Solution: + def numberOfChild(self, n: int, k: int) -> int: + # the time for the ball to return to 0 + roundTime = 2 * (n - 1) + pos = k % roundTime + return pos if pos < n else roundTime - pos diff --git a/solutions/3179. Find the N-th Value After K Seconds/3179.cpp b/solutions/3179. Find the N-th Value After K Seconds/3179.cpp new file mode 100644 index 00000000000..5d09982247d --- /dev/null +++ b/solutions/3179. Find the N-th Value After K Seconds/3179.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int valueAfterKSeconds(int n, int k) { + const auto [fact, invFact] = getFactAndInvFact(n + k - 1); + return nCk(n + k - 1, n - 1, fact, invFact); + } + + private: + static constexpr int kMod = 1'000'000'007; + + pair, vector> getFactAndInvFact(int n) { + vector fact(n + 1); + vector invFact(n + 1); + vector inv(n + 1); + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return {fact, invFact}; + } + + int nCk(int n, int k, const vector& fact, const vector& invFact) { + return fact[n] * invFact[k] % kMod * invFact[n - k] % kMod; + } +}; diff --git a/solutions/3179. Find the N-th Value After K Seconds/3179.java b/solutions/3179. Find the N-th Value After K Seconds/3179.java new file mode 100644 index 00000000000..c4e2daa6583 --- /dev/null +++ b/solutions/3179. Find the N-th Value After K Seconds/3179.java @@ -0,0 +1,29 @@ +class Solution { + public int valueAfterKSeconds(int n, int k) { + final long[][] factAndInvFact = getFactAndInvFact(n + k - 1); + final long[] fact = factAndInvFact[0]; + final long[] invFact = factAndInvFact[1]; + return nCk(n + k - 1, n - 1, fact, invFact); + } + + private static final int kMod = 1_000_000_007; + + private long[][] getFactAndInvFact(int n) { + long[] fact = new long[n + 1]; + long[] invFact = new long[n + 1]; + long[] inv = new long[n + 1]; + fact[0] = invFact[0] = 1; + inv[0] = inv[1] = 1; + for (int i = 1; i <= n; ++i) { + if (i >= 2) + inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; + fact[i] = fact[i - 1] * i % kMod; + invFact[i] = invFact[i - 1] * inv[i] % kMod; + } + return new long[][] {fact, invFact}; + } + + private int nCk(int n, int k, long[] fact, long[] invFact) { + return (int) (fact[n] * invFact[k] % kMod * invFact[n - k] % kMod); + } +} diff --git a/solutions/3179. Find the N-th Value After K Seconds/3179.py b/solutions/3179. Find the N-th Value After K Seconds/3179.py new file mode 100644 index 00000000000..f7ed7237353 --- /dev/null +++ b/solutions/3179. Find the N-th Value After K Seconds/3179.py @@ -0,0 +1,3 @@ +class Solution: + def valueAfterKSeconds(self, n: int, k: int) -> int: + return math.comb(n + k - 1, n - 1) % 1_000_000_007 diff --git a/solutions/318. Maximum Product of Word Lengths/318.cpp b/solutions/318. Maximum Product of Word Lengths/318.cpp new file mode 100644 index 00000000000..21efed1ceb6 --- /dev/null +++ b/solutions/318. Maximum Product of Word Lengths/318.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int maxProduct(vector& words) { + size_t ans = 0; + vector masks; + + for (const string& word : words) + masks.push_back(getMask(word)); + + for (int i = 0; i < words.size(); ++i) + for (int j = 0; j < i; ++j) + if ((masks[i] & masks[j]) == 0) + ans = max(ans, words[i].length() * words[j].length()); + + return ans; + } + + private: + int getMask(const string& word) { + int mask = 0; + for (const char c : word) + mask |= 1 << c - 'a'; + return mask; + } +}; diff --git a/solutions/318. Maximum Product of Word Lengths/318.java b/solutions/318. Maximum Product of Word Lengths/318.java new file mode 100644 index 00000000000..80c349822df --- /dev/null +++ b/solutions/318. Maximum Product of Word Lengths/318.java @@ -0,0 +1,23 @@ +class Solution { + public int maxProduct(String[] words) { + int ans = 0; + int[] masks = new int[words.length]; // "abd" -> 0b1011 + + for (int i = 0; i < words.length; ++i) + masks[i] = getMask(words[i]); + + for (int i = 0; i < masks.length; ++i) + for (int j = 0; j < i; ++j) + if ((masks[i] & masks[j]) == 0) + ans = Math.max(ans, words[i].length() * words[j].length()); + + return ans; + } + + private int getMask(final String word) { + int mask = 0; + for (final char c : word.toCharArray()) + mask |= 1 << c - 'a'; + return mask; + } +} diff --git a/solutions/318. Maximum Product of Word Lengths/318.py b/solutions/318. Maximum Product of Word Lengths/318.py new file mode 100644 index 00000000000..ac5a08edb62 --- /dev/null +++ b/solutions/318. Maximum Product of Word Lengths/318.py @@ -0,0 +1,18 @@ +class Solution: + def maxProduct(self, words: List[str]) -> int: + ans = 0 + + def getMask(word: str) -> int: + mask = 0 + for c in word: + mask |= 1 << ord(c) - ord('a') + return mask + + masks = [getMask(word) for word in words] + + for i in range(len(words)): + for j in range(i): + if not (masks[i] & masks[j]): + ans = max(ans, len(words[i]) * len(words[j])) + + return ans diff --git a/solutions/3180. Maximum Total Reward Using Operations I/3180.cpp b/solutions/3180. Maximum Total Reward Using Operations I/3180.cpp new file mode 100644 index 00000000000..3f8ef7ae629 --- /dev/null +++ b/solutions/3180. Maximum Total Reward Using Operations I/3180.cpp @@ -0,0 +1,51 @@ +// According to the constraint rewardValues[i] <= 5 * 10^4, the maximum total +// reward < 2 * (5 * 10^4) = 10^5. We can use bitset to record whether each +// `rewardValue` is achievable in O(1). +// +// Let's use `rewardValues = [1, 3, 4]` as an example. +// +// The maximum reward is 4, so the maximum possible total < 2 * 4 = 8. +// Therefore, we can set the size of the bitset to 8 to represent possible +// total rewards from 0 to 7. +// +// Let's define a bitset `dp` to record whether each total reward is +// achievable. dp[num] = true if reward `num` is achievable. +// +// Initially, dp = 0b00000001 := reward 0 is achievable. +// +// * rewardValues[0] = 1, for each dp[i] = 1, where i + 1 < 10, dp[i + 1] = 1. +// => dp = 0b00000011 := rewards 0 and 1 are achievable. +// +// * rewardValues[1] = 3, for each dp[i] = 1, where i + 3 < 10, dp[i + 3] = 1. +// => dp = 0b00011011 := rewards 0, 1, 3, and 4 are achievable. +// +// * rewardValues[2] = 4, for each dp[i] = 1, where i + 4 < 10, dp[i + 4] = 1. +// => dp = 0b10011011 := rewards 0, 1, 3, 4, 5, and 7 are achievable. +// +// Therefore, the maximum total reward is 7. + +class Solution { + public: + int maxTotalReward(vector& rewardValues) { + constexpr int kPossibleRewards = 100'000; + // dp[num] := true if reward `num` is achievable + bitset dp; + dp[0] = true; + + ranges::sort(rewardValues); + + for (const int num : rewardValues) { + bitset newBits = dp; + // Remove the numbers >= the current number. + newBits <<= kPossibleRewards - num; + newBits >>= kPossibleRewards - num; + dp |= newBits << num; + } + + for (int ans = kPossibleRewards - 1; ans >= 0; --ans) + if (dp[ans]) + return ans; + + throw; + } +}; diff --git a/solutions/3180. Maximum Total Reward Using Operations I/3180.java b/solutions/3180. Maximum Total Reward Using Operations I/3180.java new file mode 100644 index 00000000000..a89f6878cc4 --- /dev/null +++ b/solutions/3180. Maximum Total Reward Using Operations I/3180.java @@ -0,0 +1,45 @@ +// According to the constraint rewardValues[i] <= 5 * 10^4, the maximum total +// reward < 2 * (5 * 10^4) = 10^5. We can use bitset to record whether each +// `rewardValue` is achievable in O(1). +// +// Let's use `rewardValues = [1, 3, 4]` as an example. +// +// The maximum reward is 4, so the maximum possible total < 2 * 4 = 8. +// Therefore, we can set the size of the bitset to 8 to represent possible +// total rewards from 0 to 7. +// +// Let's define a bitset `dp` to record whether each total reward is +// achievable. dp[num] = true if reward `num` is achievable. +// +// Initially, dp = 0b00000001 := reward 0 is achievable. +// +// * rewardValues[0] = 1, for each dp[i] = 1, where i + 1 < 10, dp[i + 1] = 1. +// => dp = 0b00000011 := rewards 0 and 1 are achievable. +// +// * rewardValues[1] = 3, for each dp[i] = 1, where i + 3 < 10, dp[i + 3] = 1. +// => dp = 0b00011011 := rewards 0, 1, 3, and 4 are achievable. +// +// * rewardValues[2] = 4, for each dp[i] = 1, where i + 4 < 10, dp[i + 4] = 1. +// => dp = 0b10011011 := rewards 0, 1, 3, 4, 5, and 7 are achievable. +// +// Therefore, the maximum total reward is 7. + +import java.math.BigInteger; + +class Solution { + public int maxTotalReward(int[] rewardValues) { + BigInteger one = BigInteger.ONE; + BigInteger dp = one; // the possible rewards (initially, 0 is achievable) + + Arrays.sort(rewardValues); + + for (final int num : rewardValues) { + // Remove the numbers >= the current number. + BigInteger maskBitsLessThanNum = one.shiftLeft(num).subtract(one); + BigInteger bitsLessThanNum = dp.and(maskBitsLessThanNum); + dp = dp.or(bitsLessThanNum.shiftLeft(num)); + } + + return dp.bitLength() - 1; + } +} diff --git a/solutions/3180. Maximum Total Reward Using Operations I/3180.py b/solutions/3180. Maximum Total Reward Using Operations I/3180.py new file mode 100644 index 00000000000..5a3112662bc --- /dev/null +++ b/solutions/3180. Maximum Total Reward Using Operations I/3180.py @@ -0,0 +1,36 @@ +# According to the constraint rewardValues[i] <= 5 * 10^4, the maximum total +# reward < 2 * (5 * 10^4) = 10^5. We can use bitset to record whether each +# `rewardValue` is achievable in O(1). +# +# Let's use `rewardValues = [1, 3, 4]` as an example. +# +# The maximum reward is 4, so the maximum possible total < 2 * 4 = 8. +# Therefore, we can set the size of the bitset to 8 to represent possible +# total rewards from 0 to 7. +# +# Let's define a bitset `dp` to record whether each total reward is +# achievable. dp[num] = true if reward `num` is achievable. +# +# Initially, dp = 0b00000001 := reward 0 is achievable. +# +# * rewardValues[0] = 1, for each dp[i] = 1, where i + 1 < 10, dp[i + 1] = 1. +# => dp = 0b00000011 := rewards 0 and 1 are achievable. +# +# * rewardValues[1] = 3, for each dp[i] = 1, where i + 3 < 10, dp[i + 3] = 1. +# => dp = 0b00011011 := rewards 0, 1, 3, and 4 are achievable. +# +# * rewardValues[2] = 4, for each dp[i] = 1, where i + 4 < 10, dp[i + 4] = 1. +# => dp = 0b10011011 := rewards 0, 1, 3, 4, 5, and 7 are achievable. +# +# Therefore, the maximum total reward is 7. + +class Solution: + def maxTotalReward(self, rewardValues: List[int]) -> int: + dp = 1 # the possible rewards (initially, 0 is achievable) + + for num in sorted(rewardValues): + # Remove the numbers >= the current number. + smallerNums = dp & ((1 << num) - 1) + dp |= smallerNums << num + + return dp.bit_length() - 1 diff --git a/solutions/3181. Maximum Total Reward Using Operations II/3181.cpp b/solutions/3181. Maximum Total Reward Using Operations II/3181.cpp new file mode 100644 index 00000000000..287fc92225a --- /dev/null +++ b/solutions/3181. Maximum Total Reward Using Operations II/3181.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + // Same as 3180. Maximum Total Reward Using Operations I + int maxTotalReward(vector& rewardValues) { + constexpr int kPossibleRewards = 100'000; + // dp[num] := true if reward `num` is achievable + bitset dp; + dp[0] = true; + + ranges::sort(rewardValues); + + for (const int num : rewardValues) { + bitset newBits = dp; + // Remove the numbers >= the current number. + newBits <<= kPossibleRewards - num; + newBits >>= kPossibleRewards - num; + dp |= newBits << num; + } + + for (int ans = kPossibleRewards - 1; ans >= 0; --ans) + if (dp[ans]) + return ans; + + throw; + } +}; diff --git a/solutions/3181. Maximum Total Reward Using Operations II/3181.java b/solutions/3181. Maximum Total Reward Using Operations II/3181.java new file mode 100644 index 00000000000..a0454fcb614 --- /dev/null +++ b/solutions/3181. Maximum Total Reward Using Operations II/3181.java @@ -0,0 +1,20 @@ +import java.math.BigInteger; + +class Solution { + // Same as 3180. Maximum Total Reward Using Operations I + public int maxTotalReward(int[] rewardValues) { + BigInteger one = BigInteger.ONE; + BigInteger dp = one; // the possible rewards (initially, 0 is achievable) + + Arrays.sort(rewardValues); + + for (final int num : rewardValues) { + // Remove the numbers >= the current number. + BigInteger maskBitsLessThanNum = one.shiftLeft(num).subtract(one); + BigInteger bitsLessThanNum = dp.and(maskBitsLessThanNum); + dp = dp.or(bitsLessThanNum.shiftLeft(num)); + } + + return dp.bitLength() - 1; + } +} diff --git a/solutions/3181. Maximum Total Reward Using Operations II/3181.py b/solutions/3181. Maximum Total Reward Using Operations II/3181.py new file mode 100644 index 00000000000..12df724a959 --- /dev/null +++ b/solutions/3181. Maximum Total Reward Using Operations II/3181.py @@ -0,0 +1,11 @@ +class Solution: + # Same as 3180. Maximum Total Reward Using Operations I + def maxTotalReward(self, rewardValues: List[int]) -> int: + dp = 1 # the possible rewards (initially, 0 is achievable) + + for num in sorted(rewardValues): + # Remove the numbers >= the current number. + smallerNums = dp & ((1 << num) - 1) + dp |= smallerNums << num + + return dp.bit_length() - 1 diff --git a/solutions/3182. Find Top Scoring Students/3182.sql b/solutions/3182. Find Top Scoring Students/3182.sql new file mode 100644 index 00000000000..f319be7bb74 --- /dev/null +++ b/solutions/3182. Find Top Scoring Students/3182.sql @@ -0,0 +1,28 @@ +WITH + Majors AS ( + SELECT major, COUNT(course_id) AS course_count + FROM Courses + GROUP BY 1 + ), + StudentMetadata AS ( + SELECT + Students.student_id, + Students.major, + SUM( + Students.major = Courses.major + AND Enrollments.grade = 'A' + ) AS major_grade_a_count + FROM Students + INNER JOIN Courses + USING (major) + INNER JOIN Enrollments + USING (student_id, course_id) + GROUP BY 1 + ) +SELECT StudentMetadata.student_id +FROM StudentMetadata +INNER JOIN Majors + ON ( + StudentMetadata.major = Majors.major + AND StudentMetadata.major_grade_a_count = Majors.course_count) +ORDER BY 1; diff --git a/solutions/3183. The Number of Ways to Make the Sum/3183.cpp b/solutions/3183. The Number of Ways to Make the Sum/3183.cpp new file mode 100644 index 00000000000..ff60735b010 --- /dev/null +++ b/solutions/3183. The Number of Ways to Make the Sum/3183.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int numberOfWays(int n) { + constexpr int kMod = 1'000'000'007; + // dp[i] := the number of ways to make the sum of i using coins 1, 2, and 6 + vector dp(n + 1); + dp[0] = 1; + + for (const int coin : {1, 2, 6}) + for (int i = coin; i <= n; ++i) + dp[i] = (dp[i] + dp[i - coin]) % kMod; + + int ans = dp[n]; + if (n - 4 >= 0) + ans = (ans + dp[n - 4]) % kMod; + if (n - 8 >= 0) + ans = (ans + dp[n - 8]) % kMod; + return ans; + } +}; diff --git a/solutions/3183. The Number of Ways to Make the Sum/3183.java b/solutions/3183. The Number of Ways to Make the Sum/3183.java new file mode 100644 index 00000000000..96deea6a8c8 --- /dev/null +++ b/solutions/3183. The Number of Ways to Make the Sum/3183.java @@ -0,0 +1,19 @@ +class Solution { + public int numberOfWays(int n) { + final int kMod = 1_000_000_007; + // dp[i] := the number of ways to make the sum of i using coins 1, 2, and 6 + int[] dp = new int[n + 1]; + dp[0] = 1; + + for (final int coin : new int[] {1, 2, 6}) + for (int i = coin; i <= n; ++i) + dp[i] = (dp[i] + dp[i - coin]) % kMod; + + int ans = dp[n]; + if (n - 4 >= 0) + ans = (ans + dp[n - 4]) % kMod; + if (n - 8 >= 0) + ans = (ans + dp[n - 8]) % kMod; + return ans; + } +} diff --git a/solutions/3183. The Number of Ways to Make the Sum/3183.py b/solutions/3183. The Number of Ways to Make the Sum/3183.py new file mode 100644 index 00000000000..5cdd9477441 --- /dev/null +++ b/solutions/3183. The Number of Ways to Make the Sum/3183.py @@ -0,0 +1,16 @@ +class Solution: + def numberOfWays(self, n: int) -> int: + kMod = 1_000_000_007 + # dp[i] := the number of ways to make the sum of i using coins 1, 2, and 6 + dp = [1] + [0] * n + + for coin in (1, 2, 6): + for i in range(coin, n + 1): + dp[i] = (dp[i] + dp[i - coin]) % kMod + + ans = dp[n] + if n - 4 >= 0: + ans = (ans + dp[n - 4]) % kMod + if n - 8 >= 0: + ans = (ans + dp[n - 8]) % kMod + return ans diff --git a/solutions/3184. Count Pairs That Form a Complete Day I/3184.cpp b/solutions/3184. Count Pairs That Form a Complete Day I/3184.cpp new file mode 100644 index 00000000000..c04023d9e2e --- /dev/null +++ b/solutions/3184. Count Pairs That Form a Complete Day I/3184.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int countCompleteDayPairs(vector& hours) { + int ans = 0; + vector count(24); + + for (const int hour : hours) { + ans += count[(24 - hour % 24) % 24]; + ++count[hour % 24]; + } + + return ans; + } +}; diff --git a/solutions/3184. Count Pairs That Form a Complete Day I/3184.java b/solutions/3184. Count Pairs That Form a Complete Day I/3184.java new file mode 100644 index 00000000000..3b7c9501a2d --- /dev/null +++ b/solutions/3184. Count Pairs That Form a Complete Day I/3184.java @@ -0,0 +1,13 @@ +class Solution { + public int countCompleteDayPairs(int[] hours) { + int ans = 0; + int[] count = new int[24]; + + for (final int hour : hours) { + ans += count[(24 - hour % 24) % 24]; + ++count[hour % 24]; + } + + return ans; + } +} diff --git a/solutions/3184. Count Pairs That Form a Complete Day I/3184.py b/solutions/3184. Count Pairs That Form a Complete Day I/3184.py new file mode 100644 index 00000000000..a8e565943e4 --- /dev/null +++ b/solutions/3184. Count Pairs That Form a Complete Day I/3184.py @@ -0,0 +1,10 @@ +class Solution: + def countCompleteDayPairs(self, hours: List[int]) -> int: + ans = 0 + count = [0] * 24 + + for hour in hours: + ans += count[(24 - hour % 24) % 24] + count[hour % 24] += 1 + + return ans diff --git a/solutions/3185. Count Pairs That Form a Complete Day II/3185.cpp b/solutions/3185. Count Pairs That Form a Complete Day II/3185.cpp new file mode 100644 index 00000000000..3a00d29e5a4 --- /dev/null +++ b/solutions/3185. Count Pairs That Form a Complete Day II/3185.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + // Same as 3184. Count Pairs That Form a Complete Day I + long long countCompleteDayPairs(vector& hours) { + long ans = 0; + vector count(24); + + for (const int hour : hours) { + ans += count[(24 - hour % 24) % 24]; + ++count[hour % 24]; + } + + return ans; + } +}; diff --git a/solutions/3185. Count Pairs That Form a Complete Day II/3185.java b/solutions/3185. Count Pairs That Form a Complete Day II/3185.java new file mode 100644 index 00000000000..fbce6820bc1 --- /dev/null +++ b/solutions/3185. Count Pairs That Form a Complete Day II/3185.java @@ -0,0 +1,14 @@ +class Solution { + // Same as 3184. Count Pairs That Form a Complete Day I + public long countCompleteDayPairs(int[] hours) { + long ans = 0; + int[] count = new int[24]; + + for (final int hour : hours) { + ans += count[(24 - hour % 24) % 24]; + ++count[hour % 24]; + } + + return ans; + } +} diff --git a/solutions/3185. Count Pairs That Form a Complete Day II/3185.py b/solutions/3185. Count Pairs That Form a Complete Day II/3185.py new file mode 100644 index 00000000000..28e4c438977 --- /dev/null +++ b/solutions/3185. Count Pairs That Form a Complete Day II/3185.py @@ -0,0 +1,11 @@ +class Solution: + # Same as 3184. Count Pairs That Form a Complete Day I + def countCompleteDayPairs(self, hours: List[int]) -> int: + ans = 0 + count = [0] * 24 + + for hour in hours: + ans += count[(24 - hour % 24) % 24] + count[hour % 24] += 1 + + return ans diff --git a/solutions/3186. Maximum Total Damage With Spell Casting/3186.cpp b/solutions/3186. Maximum Total Damage With Spell Casting/3186.cpp new file mode 100644 index 00000000000..d833ed91b1a --- /dev/null +++ b/solutions/3186. Maximum Total Damage With Spell Casting/3186.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + long long maximumTotalDamage(vector& power) { + unordered_map count; + + for (const int damage : power) + ++count[damage]; + + const vector uniqueDamages = getSortedUniqueDamages(count); + const int n = uniqueDamages.size(); + // dp[i][k] := the maximum damage using uniqueDamages[0..i], where k + // indicates if the i-th damage is used + vector> dp(n, vector(2)); + + for (int i = 0; i < n; ++i) { + const long damage = uniqueDamages[i]; + if (i == 0) { + dp[0][0] = 0; + dp[0][1] = damage * count[damage]; + continue; + } + dp[i][0] = ranges::max(dp[i - 1]); + dp[i][1] = damage * count[damage]; + if (i >= 1 && uniqueDamages[i - 1] != damage - 1 && + uniqueDamages[i - 1] != damage - 2) { + dp[i][1] += max(dp[i - 1][0], dp[i - 1][1]); + } else if (i >= 2 && uniqueDamages[i - 2] != damage - 2) { + dp[i][1] += max(dp[i - 2][0], dp[i - 2][1]); + } else if (i >= 3) { + dp[i][1] += max(dp[i - 3][0], dp[i - 3][1]); + } + } + + return ranges::max(dp.back()); + } + + private: + vector getSortedUniqueDamages(const unordered_map& count) { + vector uniqueDamages; + for (const auto& [damage, _] : count) + uniqueDamages.push_back(damage); + ranges::sort(uniqueDamages); + return uniqueDamages; + } +}; diff --git a/solutions/3186. Maximum Total Damage With Spell Casting/3186.java b/solutions/3186. Maximum Total Damage With Spell Casting/3186.java new file mode 100644 index 00000000000..cba29ef74a0 --- /dev/null +++ b/solutions/3186. Maximum Total Damage With Spell Casting/3186.java @@ -0,0 +1,41 @@ +class Solution { + public long maximumTotalDamage(int[] power) { + Map count = new HashMap<>(); + + for (final int damage : power) + count.merge(damage, 1, Integer::sum); + + List uniqueDamages = getSortedUniqueDamages(count); + final int n = uniqueDamages.size(); + // dp[i][k] := the maximum damage using uniqueDamages[0..i], where k + // indicates if the i-th damage is used + long[][] dp = new long[n][2]; + + for (int i = 0; i < n; ++i) { + final int damage = uniqueDamages.get(i); + if (i == 0) { + dp[0][0] = 0; + dp[0][1] = (long) damage * count.get(damage); + continue; + } + dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); + dp[i][1] = (long) damage * count.get(damage); + if (i >= 1 && uniqueDamages.get(i - 1) != damage - 1 && + uniqueDamages.get(i - 1) != damage - 2) { + dp[i][1] += Math.max(dp[i - 1][0], dp[i - 1][1]); + } else if (i >= 2 && uniqueDamages.get(i - 2) != damage - 2) { + dp[i][1] += Math.max(dp[i - 2][0], dp[i - 2][1]); + } else if (i >= 3) { + dp[i][1] += Math.max(dp[i - 3][0], dp[i - 3][1]); + } + } + + return Math.max(dp[n - 1][0], dp[n - 1][1]); + } + + private List getSortedUniqueDamages(Map count) { + List uniqueDamages = new ArrayList<>(count.keySet()); + Collections.sort(uniqueDamages); + return uniqueDamages; + } +} diff --git a/solutions/3186. Maximum Total Damage With Spell Casting/3186.py b/solutions/3186. Maximum Total Damage With Spell Casting/3186.py new file mode 100644 index 00000000000..08b0acbe3a3 --- /dev/null +++ b/solutions/3186. Maximum Total Damage With Spell Casting/3186.py @@ -0,0 +1,22 @@ +class Solution: + def maximumTotalDamage(self, power: List[int]) -> int: + count = collections.Counter(power) + uniqueDamages = sorted(count.keys()) + # dp[i][k] := the maximum damage using uniqueDamages[0..i], where k + # indicates if the i-th damage is used + dp = [[0] * 2 for _ in range(len(uniqueDamages))] + + for i, damage in enumerate(uniqueDamages): + if i == 0: + dp[0] = [0, damage * count[damage]] + continue + dp[i][0] = max(dp[i - 1]) + dp[i][1] = damage * count[damage] + if i >= 1 and uniqueDamages[i - 1] not in (damage - 1, damage - 2): + dp[i][1] += max(dp[i - 1]) + elif i >= 2 and uniqueDamages[i - 2] != damage - 2: + dp[i][1] += max(dp[i - 2]) + elif i >= 3: + dp[i][1] += max(dp[i - 3]) + + return max(dp[-1]) diff --git a/solutions/3187. Peaks in Array/3187-2.cpp b/solutions/3187. Peaks in Array/3187-2.cpp new file mode 100644 index 00000000000..b90ce295873 --- /dev/null +++ b/solutions/3187. Peaks in Array/3187-2.cpp @@ -0,0 +1,99 @@ +class SegmentTree { + public: + explicit SegmentTree(const vector& peak) : n(peak.size()), tree(n * 4) { + build(peak, 0, 0, n - 1); + } + + // Updates peak[i] to val. + void update(int i, int val) { + update(0, 0, n - 1, i, val); + } + + // Returns sum(peak[i..j]). + int query(int i, int j) { + return query(0, 0, n - 1, i, j); + } + + private: + const int n; // the size of the input array + vector tree; // the segment tree + + void build(const vector& peak, int treeIndex, int lo, int hi) { + if (lo == hi) { + tree[treeIndex] = peak[lo]; + return; + } + const int mid = (lo + hi) / 2; + build(peak, 2 * treeIndex + 1, lo, mid); + build(peak, 2 * treeIndex + 2, mid + 1, hi); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + void update(int treeIndex, int lo, int hi, int i, int val) { + if (lo == hi) { + tree[treeIndex] = val; + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + update(2 * treeIndex + 1, lo, mid, i, val); + else + update(2 * treeIndex + 2, mid + 1, hi, i, val); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + int query(int treeIndex, int lo, int hi, int i, int j) { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return 0; + const int mid = (lo + hi) / 2; + return merge(query(treeIndex * 2 + 1, lo, mid, i, j), + query(treeIndex * 2 + 2, mid + 1, hi, i, j)); + } + + // Merges the result of the left node and the right node. + int merge(int a, int b) const { + return a + b; + } +}; + +class Solution { + public: + vector countOfPeaks(vector& nums, vector>& queries) { + const vector peak = getPeak(nums); + vector ans; + SegmentTree tree(peak); + + for (const vector& query : queries) + if (query[0] == 1) { + const int l = query[1]; + const int r = query[2]; + ans.push_back(tree.query(l + 1, r - 1)); + } else if (query[0] == 2) { + const int index = query[1]; + const int val = query[2]; + nums[index] = val; + tree.update(index, isPeak(nums, index)); + if (index > 0) + tree.update(index - 1, isPeak(nums, index - 1)); + if (index + 1 < nums.size()) + tree.update(index + 1, isPeak(nums, index + 1)); + } + + return ans; + } + + private: + vector getPeak(const vector& nums) { + vector peak(nums.size()); + for (int i = 1; i + 1 < nums.size(); ++i) + peak[i] = nums[i] > nums[i - 1] && nums[i] > nums[i + 1]; + return peak; + } + + bool isPeak(const vector& nums, int i) { + return i > 0 && i + 1 < nums.size() && nums[i] > nums[i - 1] && + nums[i] > nums[i + 1]; + } +}; diff --git a/solutions/3187. Peaks in Array/3187.cpp b/solutions/3187. Peaks in Array/3187.cpp new file mode 100644 index 00000000000..f0574733674 --- /dev/null +++ b/solutions/3187. Peaks in Array/3187.cpp @@ -0,0 +1,80 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + vector countOfPeaks(vector& nums, vector>& queries) { + vector ans; + vector peak = getPeak(nums); + FenwickTree tree(peak.size()); + + for (int i = 0; i < peak.size(); ++i) + tree.add(i + 1, peak[i]); + + // Update the peak array and Fenwick tree if the peak status of nums[i] + // changes. + auto update = [&](int i) { + const int newPeak = isPeak(nums, i); + if (newPeak != peak[i]) { + tree.add(i + 1, newPeak - peak[i]); + peak[i] = newPeak; + } + }; + + for (const vector& query : queries) + if (query[0] == 1) { + const int l = query[1]; + const int r = query[2]; + ans.push_back(r - l < 2 ? 0 : tree.get(r) - tree.get(l + 1)); + } else if (query[0] == 2) { + const int index = query[1]; + const int val = query[2]; + nums[index] = val; + update(index); + if (index > 0) + update(index - 1); + if (index + 1 < nums.size()) + update(index + 1); + } + + return ans; + } + + private: + vector getPeak(const vector& nums) { + vector peak(nums.size()); + for (int i = 1; i + 1 < nums.size(); ++i) + peak[i] = nums[i] > nums[i - 1] && nums[i] > nums[i + 1]; + return peak; + } + + bool isPeak(const vector& nums, int i) { + return i > 0 && i + 1 < nums.size() && nums[i] > nums[i - 1] && + nums[i] > nums[i + 1]; + } +}; diff --git a/solutions/3187. Peaks in Array/3187.java b/solutions/3187. Peaks in Array/3187.java new file mode 100644 index 00000000000..0dc9011512b --- /dev/null +++ b/solutions/3187. Peaks in Array/3187.java @@ -0,0 +1,78 @@ +class FenwickTree { + public FenwickTree(int n) { + sums = new int[n + 1]; + } + + public void add(int i, int delta) { + while (i < sums.length) { + sums[i] += delta; + i += lowbit(i); + } + } + + public int get(int i) { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private int[] sums; + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public List countOfPeaks(int[] nums, int[][] queries) { + List ans = new ArrayList<>(); + int[] peak = getPeak(nums); + FenwickTree tree = new FenwickTree(peak.length); + + for (int i = 0; i < peak.length; ++i) + tree.add(i + 1, peak[i]); + + // Update the peak array and Fenwick tree if the peak status of nums[i] + // changes. + for (int[] query : queries) { + if (query[0] == 1) { + final int l = query[1]; + final int r = query[2]; + ans.add(r - l < 2 ? 0 : tree.get(r) - tree.get(l + 1)); + } else if (query[0] == 2) { + final int index = query[1]; + final int val = query[2]; + nums[index] = val; + update(nums, peak, tree, index); + if (index > 0) + update(nums, peak, tree, index - 1); + if (index + 1 < nums.length) + update(nums, peak, tree, index + 1); + } + } + + return ans; + } + + private void update(int[] nums, int[] peak, FenwickTree tree, int i) { + final int newPeak = isPeak(nums, i) ? 1 : 0; + if (newPeak != peak[i]) { + tree.add(i + 1, newPeak - peak[i]); + peak[i] = newPeak; + } + } + + private int[] getPeak(int[] nums) { + int[] peak = new int[nums.length]; + for (int i = 1; i + 1 < nums.length; i++) + peak[i] = nums[i] > nums[i - 1] && nums[i] > nums[i + 1] ? 1 : 0; + return peak; + } + + private boolean isPeak(int[] nums, int i) { + return i > 0 && i + 1 < nums.length && nums[i] > nums[i - 1] && nums[i] > nums[i + 1]; + } +} diff --git a/solutions/3187. Peaks in Array/3187.py b/solutions/3187. Peaks in Array/3187.py new file mode 100644 index 00000000000..1c76521eea4 --- /dev/null +++ b/solutions/3187. Peaks in Array/3187.py @@ -0,0 +1,60 @@ +class FenwickTree: + def __init__(self, n: int): + self.sums = [0] * (n + 1) + + def add(self, i: int, delta: int) -> None: + while i < len(self.sums): + self.sums[i] += delta + i += FenwickTree.lowbit(i) + + def get(self, i: int) -> int: + summ = 0 + while i > 0: + summ += self.sums[i] + i -= FenwickTree.lowbit(i) + return summ + + @staticmethod + def lowbit(i: int) -> int: + return i & -i + + +class Solution: + def countOfPeaks(self, nums: List[int], queries: List[List[int]]) -> List[int]: + ans = [] + peak = [0] + [int(a < b > c) + for a, b, c in zip(nums[:-2], nums[1:-1], nums[2:])] + [0] + tree = FenwickTree(len(peak)) + + for i, p in enumerate(peak): + tree.add(i + 1, p) + + def update(i: int) -> None: + """ + Update the peak array and Fenwick tree if the peak status of nums[i] + changes. + """ + newPeak = self._isPeak(nums, i) + if newPeak != peak[i]: + tree.add(i + 1, newPeak - peak[i]) + peak[i] = newPeak + + for query in queries: + if query[0] == 1: + l = query[1] + r = query[2] + ans.append(0 if r - l < 2 else tree.get(r) - tree.get(l + 1)) + elif query[0] == 2: + index = query[1] + val = query[2] + nums[index] = val + update(index) + if index > 0: + update(index - 1) + if index + 1 < len(nums): + update(index + 1) + + return ans + + def _isPeak(self, nums: List[int], i: int) -> bool: + return i > 0 and i + 1 < len(nums) and nums[i - 1] < nums[i] > nums[i + 1] diff --git a/solutions/3188. Find Top Scoring Students II/3188.sql b/solutions/3188. Find Top Scoring Students II/3188.sql new file mode 100644 index 00000000000..b6d888435ae --- /dev/null +++ b/solutions/3188. Find Top Scoring Students II/3188.sql @@ -0,0 +1,39 @@ +WITH + MandatoryMajors AS ( + SELECT major, COUNT(course_id) AS course_count + FROM Courses + WHERE mandatory = 'Yes' + GROUP BY 1 + ), + StudentsMetadata AS ( + SELECT + Students.student_id, + Students.major, + SUM( + Students.major = Courses.major + AND Courses.mandatory = 'YES' + AND Enrollments.grade = 'A' + ) AS mandatory_grade_a_count, + SUM( + Students.major = Courses.major + AND Courses.mandatory = 'No' + ) AS elective_count, + ROUND( + SUM(Enrollments.GPA * Courses.credits) / SUM(Courses.credits), + 1 + ) AS avg_gpa + FROM Students + INNER JOIN Enrollments + USING (student_id) + INNER JOIN Courses + USING (course_id) + GROUP BY 1 + ) +SELECT StudentsMetadata.student_id +FROM StudentsMetadata +INNER JOIN MandatoryMajors + ON ( + StudentsMetadata.major = MandatoryMajors.major + AND StudentsMetadata.mandatory_grade_a_count = MandatoryMajors.course_count) +WHERE StudentsMetadata.avg_gpa >= 2.5 AND StudentsMetadata.elective_count >= 2 +ORDER BY 1; diff --git a/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.cpp b/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.cpp new file mode 100644 index 00000000000..560da7ba8ba --- /dev/null +++ b/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minMoves(vector>& rooks) { + const int n = rooks.size(); + int ans = 0; + vector> sortedByRow(rooks); + vector> sortedByCol(rooks); + + ranges::sort(sortedByRow, [](const vector& a, const vector& b) { + return a[0] < b[0]; + }); + + ranges::sort(sortedByCol, [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + + for (int i = 0; i < n; ++i) { + ans += abs(sortedByRow[i][0] - /*targetRow=*/i); + ans += abs(sortedByCol[i][1] - /*targetCol=*/i); + } + + return ans; + } +}; diff --git a/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.java b/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.java new file mode 100644 index 00000000000..43691b86b7b --- /dev/null +++ b/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.java @@ -0,0 +1,18 @@ +class Solution { + public int minMoves(int[][] rooks) { + final int n = rooks.length; + int ans = 0; + int[][] sortedByRow = rooks.clone(); + int[][] sortedByCol = rooks.clone(); + + Arrays.sort(sortedByRow, (a, b) -> Integer.compare(a[0], b[0])); + Arrays.sort(sortedByCol, (a, b) -> Integer.compare(a[1], b[1])); + + for (int i = 0; i < n; ++i) { + ans += Math.abs(sortedByRow[i][0] - /*targetRow=*/i); + ans += Math.abs(sortedByCol[i][1] - /*targetCol=*/i); + } + + return ans; + } +} diff --git a/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.py b/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.py new file mode 100644 index 00000000000..67cb76f91fb --- /dev/null +++ b/solutions/3189. Minimum Moves to Get a Peaceful Board/3189.py @@ -0,0 +1,7 @@ +class Solution: + def minMoves(self, rooks: List[List[int]]) -> int: + n = len(rooks) + sortedByRow = sorted(rooks, key=lambda x: x[0]) + sortedByCol = sorted(rooks, key=lambda x: x[1]) + return sum(abs(i - row) for (i, _), row in zip(sortedByRow, range(n))) \ + + sum(abs(j - col) for (_, j), col in zip(sortedByCol, range(n))) diff --git a/solutions/319. Bulb Switcher/319.cpp b/solutions/319. Bulb Switcher/319.cpp new file mode 100644 index 00000000000..b90162dee8d --- /dev/null +++ b/solutions/319. Bulb Switcher/319.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int bulbSwitch(int n) { + // The k-th bulb can only be switched when k % i == 0. + // So, we can rephrase the problem: + // To find number of numbers <= n that have odd factors. + // Obviously, only square numbers have odd factor(s). + // e.g. n = 10, only 1, 4, and 9 are square numbers that <= 10 + return sqrt(n); + } +}; diff --git a/solutions/319. Bulb Switcher/319.java b/solutions/319. Bulb Switcher/319.java new file mode 100644 index 00000000000..169b7cd9e6a --- /dev/null +++ b/solutions/319. Bulb Switcher/319.java @@ -0,0 +1,10 @@ +class Solution { + public int bulbSwitch(int n) { + // The k-th bulb can only be switched when k % i == 0. + // So, we can rephrase the problem: + // To find number of numbers <= n that have odd factors. + // Obviously, only square numbers have odd factor(s). + // e.g. n = 10, only 1, 4, and 9 are square numbers that <= 10 + return (int) Math.sqrt(n); + } +} diff --git a/solutions/319. Bulb Switcher/319.py b/solutions/319. Bulb Switcher/319.py new file mode 100644 index 00000000000..f2585b8f3b5 --- /dev/null +++ b/solutions/319. Bulb Switcher/319.py @@ -0,0 +1,8 @@ +class Solution: + def bulbSwitch(self, n: int) -> int: + # The k-th bulb can only be switched when k % i == 0. + # So, we can rephrase the problem: + # To find number of numbers <= n that have odd factors. + # Obviously, only square numbers have odd factor(s). + # e.g. n = 10, only 1, 4, and 9 are square numbers that <= 10 + return math.isqrt(n) diff --git a/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.cpp b/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.cpp new file mode 100644 index 00000000000..2cd78a7ed9b --- /dev/null +++ b/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int minimumOperations(vector& nums) { + return ranges::count_if(nums, [](int num) { return num % 3 != 0; }); + } +}; diff --git a/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.java b/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.java new file mode 100644 index 00000000000..5dada7d4aa9 --- /dev/null +++ b/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.java @@ -0,0 +1,5 @@ +class Solution { + public int minimumOperations(int[] nums) { + return (int) Arrays.stream(nums).filter(num -> num % 3 != 0).count(); + } +} diff --git a/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.py b/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.py new file mode 100644 index 00000000000..93eae542551 --- /dev/null +++ b/solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.py @@ -0,0 +1,3 @@ +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + return sum(num % 3 != 0 for num in nums) diff --git a/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.cpp b/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.cpp new file mode 100644 index 00000000000..8c372765fe6 --- /dev/null +++ b/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minOperations(vector& nums) { + const int n = nums.size(); + int ans = 0; + + for (int i = 0; i + 2 < n; ++i) + if (nums[i] == 0) { + nums[i + 1] ^= 1; + nums[i + 2] ^= 1; + ++ans; + } + + return nums[n - 1] == 0 || nums[n - 2] == 0 ? -1 : ans; + } +}; diff --git a/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.java b/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.java new file mode 100644 index 00000000000..2237f212dfc --- /dev/null +++ b/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.java @@ -0,0 +1,15 @@ +class Solution { + public int minOperations(int[] nums) { + final int n = nums.length; + int ans = 0; + + for (int i = 0; i + 2 < n; ++i) + if (nums[i] == 0) { + nums[i + 1] ^= 1; + nums[i + 2] ^= 1; + ++ans; + } + + return nums[n - 1] == 0 || nums[n - 2] == 0 ? -1 : ans; + } +} diff --git a/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.py b/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.py new file mode 100644 index 00000000000..fb70c3740a8 --- /dev/null +++ b/solutions/3191. Minimum Operations to Make Binary Array Elements Equal to One I/3191.py @@ -0,0 +1,11 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + ans = 0 + + for i in range(len(nums) - 2): + if nums[i] == 0: + nums[i + 1] ^= 1 + nums[i + 2] ^= 1 + ans += 1 + + return -1 if nums[-1] == 0 or nums[-2] == 0 else ans diff --git a/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.cpp b/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.cpp new file mode 100644 index 00000000000..a023bdf0676 --- /dev/null +++ b/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minOperations(vector& nums) { + int ans = 0; + int target = 1; + + for (const int num : nums) + if (num != target) { + target ^= 1; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.java b/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.java new file mode 100644 index 00000000000..b8d21e2eb02 --- /dev/null +++ b/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.java @@ -0,0 +1,14 @@ +class Solution { + public int minOperations(int[] nums) { + int ans = 0; + int target = 1; + + for (final int num : nums) + if (num != target) { + target ^= 1; + ++ans; + } + + return ans; + } +} diff --git a/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.py b/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.py new file mode 100644 index 00000000000..38c647afedd --- /dev/null +++ b/solutions/3192. Minimum Operations to Make Binary Array Elements Equal to One II/3192.py @@ -0,0 +1,11 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + ans = 0 + target = 1 + + for num in nums: + if num != target: + ans += 1 + target ^= 1 + + return ans diff --git a/solutions/3193. Count the Number of Inversions/3193.cpp b/solutions/3193. Count the Number of Inversions/3193.cpp new file mode 100644 index 00000000000..4268a1e5386 --- /dev/null +++ b/solutions/3193. Count the Number of Inversions/3193.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int numberOfPermutations(int n, vector>& requirements) { + constexpr int kMod = 1'000'000'007; + constexpr int kMaxInversions = 400; + // dp[i][j] := the number of ways to arrange the first i numbers of the + // permutation s.t. there are j inversions + vector> dp(n + 1, vector(kMaxInversions + 1)); + vector endToCnt(n + 1, -1); + + for (const vector& requirement : requirements) { + const int end = requirement[0]; + const int cnt = requirement[1]; + endToCnt[end + 1] = cnt; + } + + // There's only one way to arrange a single number with zero inversions. + dp[1][0] = 1; + + for (int i = 2; i <= n; ++i) + for (int newInversions = 0; newInversions < i; ++newInversions) + for (int j = 0; j + newInversions <= kMaxInversions; ++j) { + const int inversionsAfterInsertion = j + newInversions; + if (endToCnt[i] != -1 && inversionsAfterInsertion != endToCnt[i]) + continue; + dp[i][inversionsAfterInsertion] += dp[i - 1][j]; + dp[i][inversionsAfterInsertion] %= kMod; + } + + return dp[n][endToCnt[n]]; + } +}; diff --git a/solutions/3193. Count the Number of Inversions/3193.java b/solutions/3193. Count the Number of Inversions/3193.java new file mode 100644 index 00000000000..d4728a3d049 --- /dev/null +++ b/solutions/3193. Count the Number of Inversions/3193.java @@ -0,0 +1,32 @@ +class Solution { + public int numberOfPermutations(int n, int[][] requirements) { + final int kMod = 1_000_000_007; + final int kMaxInversions = 400; + // dp[i][j] := the number of ways to arrange the first i numbers of the + // permutation such that there are j inversions + int[][] dp = new int[n + 1][kMaxInversions + 1]; + int[] endToCnt = new int[n + 1]; + Arrays.fill(endToCnt, -1); + + for (int[] requirement : requirements) { + final int end = requirement[0]; + final int cnt = requirement[1]; + endToCnt[end + 1] = cnt; + } + + // There's only one way to arrange a single number with zero inversions. + dp[1][0] = 1; + + for (int i = 2; i <= n; ++i) + for (int newInversions = 0; newInversions < i; ++newInversions) + for (int j = 0; j + newInversions <= kMaxInversions; ++j) { + final int inversionsAfterInsertion = j + newInversions; + if (endToCnt[i] != -1 && inversionsAfterInsertion != endToCnt[i]) + continue; + dp[i][inversionsAfterInsertion] += dp[i - 1][j]; + dp[i][inversionsAfterInsertion] %= kMod; + } + + return dp[n][endToCnt[n]]; + } +} diff --git a/solutions/3193. Count the Number of Inversions/3193.py b/solutions/3193. Count the Number of Inversions/3193.py new file mode 100644 index 00000000000..516dc9ceecf --- /dev/null +++ b/solutions/3193. Count the Number of Inversions/3193.py @@ -0,0 +1,22 @@ +class Solution: + def numberOfPermutations(self, n: int, requirements: List[List[int]]) -> int: + kMod = 1_000_000_007 + kMaxInversions = 400 + # dp[i][j] := the number of ways to arrange the first i numbers of the + # permutation s.t. there are j inversions + dp = [[0] * (kMaxInversions + 1) for _ in range(n + 1)] + endToCnt = {end + 1: cnt for end, cnt in requirements} + + # There's only one way to arrange a single number with zero inversions. + dp[1][0] = 1 + + for i in range(2, n + 1): + for newInversions in range(i): + for j in range(kMaxInversions - newInversions + 1): + inversionsAfterInsertion = j + newInversions + if i in endToCnt and inversionsAfterInsertion != endToCnt[i]: + continue + dp[i][inversionsAfterInsertion] += dp[i - 1][j] + dp[i][inversionsAfterInsertion] %= kMod + + return dp[n][endToCnt[n]] diff --git a/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.cpp b/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.cpp new file mode 100644 index 00000000000..0e41bdff319 --- /dev/null +++ b/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + double minimumAverage(vector& nums) { + constexpr int kMax = 50; + double ans = kMax; + int i = 0; + int j = nums.size() - 1; + + ranges::sort(nums); + + while (i < j) + ans = min(ans, (nums[i++] + nums[j--]) / 2.0); + + return ans; + } +}; diff --git a/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.java b/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.java new file mode 100644 index 00000000000..95aaf064f87 --- /dev/null +++ b/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.java @@ -0,0 +1,15 @@ +class Solution { + public double minimumAverage(int[] nums) { + final int kMax = 50; + double ans = kMax; + int i = 0; + int j = nums.length - 1; + + Arrays.sort(nums); + + while (i < j) + ans = Math.min(ans, (nums[i++] + nums[j--]) / 2.0); + + return ans; + } +} diff --git a/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.py b/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.py new file mode 100644 index 00000000000..f0b16f4ca92 --- /dev/null +++ b/solutions/3194. Minimum Average of Smallest and Largest Elements/3194.py @@ -0,0 +1,5 @@ +class Solution: + def minimumAverage(self, nums: List[int]) -> float: + nums.sort() + return min((nums[i] + nums[~i]) / 2 + for i in range(len(nums) // 2 + 1)) diff --git a/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.cpp b/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.cpp new file mode 100644 index 00000000000..935bbcbdf8e --- /dev/null +++ b/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minimumArea(vector>& grid) { + int x1 = INT_MAX; + int y1 = INT_MAX; + int x2 = 0; + int y2 = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == 1) { + x1 = min(x1, i); + y1 = min(y1, j); + x2 = max(x2, i); + y2 = max(y2, j); + } + + return (x2 - x1 + 1) * (y2 - y1 + 1); + } +}; diff --git a/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.java b/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.java new file mode 100644 index 00000000000..f2c33558cb6 --- /dev/null +++ b/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.java @@ -0,0 +1,19 @@ +class Solution { + public int minimumArea(int[][] grid) { + int x1 = Integer.MAX_VALUE; + int y1 = Integer.MAX_VALUE; + int x2 = 0; + int y2 = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 1) { + x1 = Math.min(x1, i); + y1 = Math.min(y1, j); + x2 = Math.max(x2, i); + y2 = Math.max(y2, j); + } + + return (x2 - x1 + 1) * (y2 - y1 + 1); + } +} diff --git a/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.py b/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.py new file mode 100644 index 00000000000..ced1f814842 --- /dev/null +++ b/solutions/3195. Find the Minimum Area to Cover All Ones I/3195.py @@ -0,0 +1,16 @@ +class Solution: + def minimumArea(self, grid: List[List[int]]) -> int: + x1 = math.inf + y1 = math.inf + x2 = 0 + y2 = 0 + + for i, row in enumerate(grid): + for j, num in enumerate(row): + if num == 1: + x1 = min(x1, i) + y1 = min(y1, j) + x2 = max(x2, i) + y2 = max(y2, j) + + return (x2 - x1 + 1) * (y2 - y1 + 1) diff --git a/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.cpp b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.cpp new file mode 100644 index 00000000000..3fee279d0a8 --- /dev/null +++ b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + long long maximumTotalCost(vector& nums) { + // A small trick so that we don't need to handle the edge case and can use + // ranged-based for loop. + long keep = LONG_MIN / 2; // the maximum cost if the last number is kept + long flip = 0; // the maximum cost if the last number is flipped + + for (const int num : nums) { + const long keepCurr = max(keep, flip) + num; + const long flipCurr = keep - num; + keep = keepCurr; + flip = flipCurr; + } + + return max(keep, flip); + } +}; diff --git a/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.java b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.java new file mode 100644 index 00000000000..55def085c31 --- /dev/null +++ b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.java @@ -0,0 +1,17 @@ +class Solution { + public long maximumTotalCost(int[] nums) { + // A small trick so that we don't need to handle the edge case and can use + // ranged-based for loop. + long keep = Long.MIN_VALUE / 2; // the maximum cost if the last number is kept + long flip = 0; // the maximum cost if the last number is flipped + + for (final int num : nums) { + final long keepCurr = Math.max(keep, flip) + num; + final long flipCurr = keep - num; + keep = keepCurr; + flip = flipCurr; + } + + return Math.max(keep, flip); + } +} diff --git a/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.py b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.py new file mode 100644 index 00000000000..ee16f98dd4d --- /dev/null +++ b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.py @@ -0,0 +1,11 @@ +class Solution: + def maximumTotalCost(self, nums: List[int]) -> int: + # A small trick so that we don't need to handle the edge case and can use + # ranged-based for loop. + keep = -math.inf # the maximum cost if the last number is kept + flip = 0 # the maximum cost if the last number is flipped + + for num in nums: + keep, flip = max(keep, flip) + num, keep - num + + return max(keep, flip) diff --git a/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.cpp b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.cpp new file mode 100644 index 00000000000..66e56302abc --- /dev/null +++ b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + long long maximumTotalCost(vector& nums) { + long keep = nums[0]; // the maximum cost if the last number is kept + long flip = nums[0]; // the maximum cost if the last number is flipped + + for (int i = 1; i < nums.size(); ++i) { + const long keepCurr = max(keep, flip) + nums[i]; + const long flipCurr = keep - nums[i]; + keep = keepCurr; + flip = flipCurr; + } + + return max(keep, flip); + } +}; diff --git a/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.java b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.java new file mode 100644 index 00000000000..1df0bb22378 --- /dev/null +++ b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.java @@ -0,0 +1,15 @@ +class Solution { + public long maximumTotalCost(int[] nums) { + long keep = nums[0]; // the maximum cost if the last number is kept + long flip = nums[0]; // the maximum cost if the last number is flipped + + for (int i = 1; i < nums.length; ++i) { + final long keepCurr = Math.max(keep, flip) + nums[i]; + final long flipCurr = keep - nums[i]; + keep = keepCurr; + flip = flipCurr; + } + + return Math.max(keep, flip); + } +} diff --git a/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.py b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.py new file mode 100644 index 00000000000..84e3fbe91b9 --- /dev/null +++ b/solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.py @@ -0,0 +1,12 @@ +class Solution: + def maximumTotalCost(self, nums: List[int]) -> int: + keep = nums[0] # the maximum cost if the last number is kept + flip = nums[0] # the maximum cost if the last number is flipped + + for i in range(1, len(nums)): + keepCurr = max(keep, flip) + nums[i] + flipCurr = keep - nums[i] + keep = keepCurr + flip = flipCurr + + return max(keep, flip) diff --git a/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.cpp b/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.cpp new file mode 100644 index 00000000000..b73847c0baa --- /dev/null +++ b/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.cpp @@ -0,0 +1,72 @@ +class Solution { + public: + int minimumSum(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = m * n; + + for (int i = 0; i < m; ++i) { + const int top = minimumArea(grid, 0, i, 0, n - 1); + for (int j = 0; j < n; ++j) + ans = min(ans, + top + /*left*/ minimumArea(grid, i + 1, m - 1, 0, j) + + /*right*/ minimumArea(grid, i + 1, m - 1, j + 1, n - 1)); + } + + for (int i = 0; i < m; ++i) { + const int bottom = minimumArea(grid, i, m - 1, 0, n - 1); + for (int j = 0; j < n; ++j) + ans = min(ans, bottom + /*left*/ minimumArea(grid, 0, i - 1, 0, j) + + /*right*/ minimumArea(grid, 0, i - 1, j + 1, n - 1)); + } + + for (int j = 0; j < n; ++j) { + const int left = minimumArea(grid, 0, m - 1, 0, j); + for (int i = 0; i < m; ++i) + ans = min(ans, + left + /*top*/ minimumArea(grid, 0, i, j + 1, n - 1) + + /*bottom*/ minimumArea(grid, i + 1, m - 1, j + 1, n - 1)); + } + + for (int j = 0; j < n; ++j) { + const int right = minimumArea(grid, 0, m - 1, j, n - 1); + for (int i = 0; i < m; ++i) + ans = + min(ans, right + /*top*/ minimumArea(grid, 0, i, 0, j - 1) + + /*bottom*/ minimumArea(grid, i + 1, m - 1, 0, j - 1)); + } + + for (int i1 = 0; i1 < m; ++i1) + for (int i2 = i1 + 1; i2 < m; ++i2) + ans = + min(ans, /*top*/ minimumArea(grid, 0, i1, 0, n - 1) + + /*middle*/ minimumArea(grid, i1 + 1, i2, 0, n - 1) + + /*bottom*/ minimumArea(grid, i2 + 1, m - 1, 0, n - 1)); + + for (int j1 = 0; j1 < n; ++j1) + for (int j2 = j1 + 1; j2 < n; ++j2) + ans = + min(ans, /*left*/ minimumArea(grid, 0, m - 1, 0, j1) + + /*middle*/ minimumArea(grid, 0, m - 1, j1 + 1, j2) + + /*right*/ minimumArea(grid, 0, m - 1, j2 + 1, n - 1)); + + return ans; + } + + private: + int minimumArea(vector>& grid, int si, int ei, int sj, int ej) { + int x1 = INT_MAX; + int y1 = INT_MAX; + int x2 = 0; + int y2 = 0; + for (int i = si; i <= ei; ++i) + for (int j = sj; j <= ej; ++j) + if (grid[i][j] == 1) { + x1 = min(x1, i); + y1 = min(y1, j); + x2 = max(x2, i); + y2 = max(y2, j); + } + return x1 == INT_MAX ? 0 : (x2 - x1 + 1) * (y2 - y1 + 1); + } +}; diff --git a/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.java b/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.java new file mode 100644 index 00000000000..3e7c2e3e4af --- /dev/null +++ b/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.java @@ -0,0 +1,65 @@ +class Solution { + public int minimumSum(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = m * n; + + for (int i = 0; i < m; ++i) { + final int top = minimumArea(grid, 0, i, 0, n - 1); + for (int j = 0; j < n; ++j) + ans = Math.min(ans, top + /*left*/ minimumArea(grid, i + 1, m - 1, 0, j) + + /*right*/ minimumArea(grid, i + 1, m - 1, j + 1, n - 1)); + } + + for (int i = 0; i < m; ++i) { + final int bottom = minimumArea(grid, i, m - 1, 0, n - 1); + for (int j = 0; j < n; ++j) + ans = Math.min(ans, bottom + /*left*/ minimumArea(grid, 0, i - 1, 0, j) + + /*right*/ minimumArea(grid, 0, i - 1, j + 1, n - 1)); + } + + for (int j = 0; j < n; ++j) { + final int left = minimumArea(grid, 0, m - 1, 0, j); + for (int i = 0; i < m; ++i) + ans = Math.min(ans, left + /*top*/ minimumArea(grid, 0, i, j + 1, n - 1) + + /*bottom*/ minimumArea(grid, i + 1, m - 1, j + 1, n - 1)); + } + + for (int j = 0; j < n; ++j) { + final int right = minimumArea(grid, 0, m - 1, j, n - 1); + for (int i = 0; i < m; ++i) + ans = Math.min(ans, right + /*top*/ minimumArea(grid, 0, i, 0, j - 1) + + /*bottom*/ minimumArea(grid, i + 1, m - 1, 0, j - 1)); + } + + for (int i1 = 0; i1 < m; ++i1) + for (int i2 = i1 + 1; i2 < m; ++i2) + ans = Math.min(ans, /*top*/ minimumArea(grid, 0, i1, 0, n - 1) + + /*middle*/ minimumArea(grid, i1 + 1, i2, 0, n - 1) + + /*bottom*/ minimumArea(grid, i2 + 1, m - 1, 0, n - 1)); + + for (int j1 = 0; j1 < n; ++j1) + for (int j2 = j1 + 1; j2 < n; ++j2) + ans = Math.min(ans, /*left*/ minimumArea(grid, 0, m - 1, 0, j1) + + /*middle*/ minimumArea(grid, 0, m - 1, j1 + 1, j2) + + /*right*/ minimumArea(grid, 0, m - 1, j2 + 1, n - 1)); + + return ans; + } + + private int minimumArea(int[][] grid, int si, int ei, int sj, int ej) { + int x1 = Integer.MAX_VALUE; + int y1 = Integer.MAX_VALUE; + int x2 = 0; + int y2 = 0; + for (int i = si; i <= ei; ++i) + for (int j = sj; j <= ej; ++j) + if (grid[i][j] == 1) { + x1 = Math.min(x1, i); + y1 = Math.min(y1, j); + x2 = Math.max(x2, i); + y2 = Math.max(y2, j); + } + return x1 == Integer.MAX_VALUE ? 0 : (x2 - x1 + 1) * (y2 - y1 + 1); + } +} diff --git a/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.py b/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.py new file mode 100644 index 00000000000..834a4ad6219 --- /dev/null +++ b/solutions/3197. Find the Minimum Area to Cover All Ones II/3197.py @@ -0,0 +1,62 @@ + +class Solution: + def minimumSum(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + ans = m * n + + for i in range(m): + top = self._minimumArea(grid, 0, i, 0, n - 1) + for j in range(n): + ans = min(ans, top + + self._minimumArea(grid, i + 1, m - 1, 0, j) + + self._minimumArea(grid, i + 1, m - 1, j + 1, n - 1)) + + for i in range(m): + bottom = self._minimumArea(grid, i, m - 1, 0, n - 1) + for j in range(n): + ans = min(ans, bottom + + self._minimumArea(grid, 0, i - 1, 0, j) + + self._minimumArea(grid, 0, i - 1, j + 1, n - 1)) + + for j in range(n): + left = self._minimumArea(grid, 0, m - 1, 0, j) + for i in range(m): + ans = min(ans, left + + self._minimumArea(grid, 0, i, j + 1, n - 1) + + self._minimumArea(grid, i + 1, m - 1, j + 1, n - 1)) + + for j in range(n): + right = self._minimumArea(grid, 0, m - 1, j, n - 1) + for i in range(m): + ans = min(ans, right + + self._minimumArea(grid, 0, i, 0, j - 1) + + self._minimumArea(grid, i + 1, m - 1, 0, j - 1)) + + for i1 in range(m): + for i2 in range(i1 + 1, m): + ans = min(ans, self._minimumArea(grid, 0, i1, 0, n - 1) + + self._minimumArea(grid, i1 + 1, i2, 0, n - 1) + + self._minimumArea(grid, i2 + 1, m - 1, 0, n - 1)) + + for j1 in range(n): + for j2 in range(j1 + 1, n): + ans = min(ans, self._minimumArea(grid, 0, m - 1, 0, j1) + + self._minimumArea(grid, 0, m - 1, j1 + 1, j2) + + self._minimumArea(grid, 0, m - 1, j2 + 1, n - 1)) + + return ans + + def _minimumArea(self, grid: List[List[int]], si: int, ei: int, sj: int, ej: int) -> int: + x1 = math.inf + y1 = math.inf + x2 = 0 + y2 = 0 + for i in range(si, ei + 1): + for j in range(sj, ej + 1): + if grid[i][j] == 1: + x1 = min(x1, i) + y1 = min(y1, j) + x2 = max(x2, i) + y2 = max(y2, j) + return 0 if x1 == math.inf else (x2 - x1 + 1) * (y2 - y1 + 1) diff --git a/solutions/3198. Find Cities in Each State/3198.sql b/solutions/3198. Find Cities in Each State/3198.sql new file mode 100644 index 00000000000..d232757f759 --- /dev/null +++ b/solutions/3198. Find Cities in Each State/3198.sql @@ -0,0 +1,6 @@ +SELECT + state, + GROUP_CONCAT(city ORDER BY city SEPARATOR ', ') AS cities +FROM Cities +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.cpp b/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.cpp new file mode 100644 index 00000000000..30e53202ab3 --- /dev/null +++ b/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int tripletCount(vector& a, vector& b, vector& c) { + const auto [evenA, oddA] = getEvenOddBitCount(a); + const auto [evenB, oddB] = getEvenOddBitCount(b); + const auto [evenC, oddC] = getEvenOddBitCount(c); + return evenA * oddB * oddC + oddA * evenB * oddC + oddA * oddB * evenC + + evenA * evenB * evenC; + } + + private: + // Returns the count of numbers in the `nums` arrays that have even number of + // ones and odd number of ones in their binary representation. + pair getEvenOddBitCount(const vector& nums) { + int even = 0; + int odd = 0; + for (const unsigned num : nums) + if (popcount(num) % 2 == 0) + ++even; + else + ++odd; + return {even, odd}; + } +}; diff --git a/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.java b/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.java new file mode 100644 index 00000000000..cf2c4ad2c25 --- /dev/null +++ b/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.java @@ -0,0 +1,27 @@ +class Solution { + public int tripletCount(int[] a, int[] b, int[] c) { + final int[] evenOddA = getEvenOddBitCount(a); + final int[] evenOddB = getEvenOddBitCount(b); + final int[] evenOddC = getEvenOddBitCount(c); + final int evenA = evenOddA[0]; + final int evenB = evenOddB[0]; + final int evenC = evenOddC[0]; + final int oddA = evenOddA[1]; + final int oddB = evenOddB[1]; + final int oddC = evenOddC[1]; + return evenA * oddB * oddC + oddA * evenB * oddC + oddA * oddB * evenC + evenA * evenB * evenC; + } + + // Returns the count of numbers in the `nums` arrays that have even number of + // ones and odd number of ones in their binary representation. + private int[] getEvenOddBitCount(int[] nums) { + int even = 0; + int odd = 0; + for (final int num : nums) + if (Integer.bitCount(num) % 2 == 0) + ++even; + else + ++odd; + return new int[] {even, odd}; + } +} diff --git a/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.py b/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.py new file mode 100644 index 00000000000..84caf2d1991 --- /dev/null +++ b/solutions/3199. Count Triplets with Even XOR Set Bits I/3199.py @@ -0,0 +1,14 @@ +class Solution: + def tripletCount(self, a: List[int], b: List[int], c: List[int]) -> int: + evenA, oddA = self._getEvenOddBitCount(a) + evenB, oddB = self._getEvenOddBitCount(b) + evenC, oddC = self._getEvenOddBitCount(c) + return evenA * oddB * oddC + oddA * evenB * oddC + oddA * oddB * evenC + evenA * evenB * evenC + + def _getEvenOddBitCount(self, nums: List[int]) -> Tuple[int, int]: + """ + Returns the count of numbers in the `nums` arrays that have even number of + ones and odd number of ones in their binary representation. + """ + even = sum(num.bit_count() % 2 == 0 for num in nums) + return (even, len(nums) - even) diff --git a/solutions/32. Longest Valid Parentheses/32.cpp b/solutions/32. Longest Valid Parentheses/32.cpp new file mode 100644 index 00000000000..78856a2e89f --- /dev/null +++ b/solutions/32. Longest Valid Parentheses/32.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int longestValidParentheses(string s) { + const string s2 = ")" + s; + // dp[i] := the length of the longest valid parentheses in the substring + // s2[1..i] + vector dp(s2.length()); + + for (int i = 1; i < s2.length(); ++i) + if (s2[i] == ')' && s2[i - dp[i - 1] - 1] == '(') + dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2; + + return ranges::max(dp); + } +}; diff --git a/solutions/32. Longest Valid Parentheses/32.java b/solutions/32. Longest Valid Parentheses/32.java new file mode 100644 index 00000000000..c9d6544f9ca --- /dev/null +++ b/solutions/32. Longest Valid Parentheses/32.java @@ -0,0 +1,14 @@ +class Solution { + public int longestValidParentheses(String s) { + final String s2 = ")" + s; + // dp[i] := the length of the longest valid parentheses in the substring + // s2[1..i] + int dp[] = new int[s2.length()]; + + for (int i = 1; i < s2.length(); ++i) + if (s2.charAt(i) == ')' && s2.charAt(i - dp[i - 1] - 1) == '(') + dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2; + + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/32. Longest Valid Parentheses/32.py b/solutions/32. Longest Valid Parentheses/32.py new file mode 100644 index 00000000000..39e25495dd5 --- /dev/null +++ b/solutions/32. Longest Valid Parentheses/32.py @@ -0,0 +1,12 @@ +class Solution: + def longestValidParentheses(self, s: str) -> int: + s2 = ')' + s + # dp[i] := the length of the longest valid parentheses in the substring + # s2[1..i] + dp = [0] * len(s2) + + for i in range(1, len(s2)): + if s2[i] == ')' and s2[i - dp[i - 1] - 1] == '(': + dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2 + + return max(dp) diff --git a/solutions/320. Generalized Abbreviation/320.cpp b/solutions/320. Generalized Abbreviation/320.cpp new file mode 100644 index 00000000000..93d436e0750 --- /dev/null +++ b/solutions/320. Generalized Abbreviation/320.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector generateAbbreviations(string word) { + vector ans; + dfs(word, 0, 0, {}, ans); + return ans; + } + + private: + void dfs(const string& word, int i, int count, vector&& path, + vector& ans) { + if (i == word.length()) { + ans.push_back(join(path) + getCountString(count)); + return; + } + + // Abbreviate the word[i]. + dfs(word, i + 1, count + 1, move(path), ans); + // Keep the word[i], so consume the count as a string + path.push_back(getCountString(count) + word[i]); + // Reset the count to 0. + dfs(word, i + 1, 0, move(path), ans); + path.pop_back(); + } + + string getCountString(int count) { + return count > 0 ? to_string(count) : ""; + } + + string join(const vector& path) { + string joined; + for (const string& s : path) + joined += s; + return joined; + }; +}; diff --git a/solutions/320. Generalized Abbreviation/320.java b/solutions/320. Generalized Abbreviation/320.java new file mode 100644 index 00000000000..6cacb8f9168 --- /dev/null +++ b/solutions/320. Generalized Abbreviation/320.java @@ -0,0 +1,28 @@ +class Solution { + public List generateAbbreviations(String word) { + List ans = new ArrayList<>(); + dfs(word, 0, 0, new StringBuilder(), ans); + return ans; + } + + private void dfs(final String word, int i, int count, StringBuilder sb, List ans) { + if (i == word.length()) { + final int length = sb.length(); + ans.add(sb.append(getCountString(count)).toString()); + sb.setLength(length); + return; + } + + // Abbreviate the word[i]. + dfs(word, i + 1, count + 1, sb, ans); + // Keep the word[i], so consume the count as a string. + final int length = sb.length(); + // Reset the count to 0. + dfs(word, i + 1, 0, sb.append(getCountString(count)).append(word.charAt(i)), ans); + sb.setLength(length); + } + + private String getCountString(int count) { + return count > 0 ? String.valueOf(count) : ""; + } +} diff --git a/solutions/320. Generalized Abbreviation/320.py b/solutions/320. Generalized Abbreviation/320.py new file mode 100644 index 00000000000..3a1483960a6 --- /dev/null +++ b/solutions/320. Generalized Abbreviation/320.py @@ -0,0 +1,22 @@ +class Solution: + def generateAbbreviations(self, word: str) -> List[str]: + ans = [] + + def getCountString(count: int) -> str: + return str(count) if count > 0 else '' + + def dfs(i: int, count: int, path: List[str]) -> None: + if i == len(word): + ans.append(''.join(path) + getCountString(count)) + return + + # Abbreviate the word[i]. + dfs(i + 1, count + 1, path) + # Keep the word[i], so consume the count as a string. + path.append(getCountString(count) + word[i]) + # Reset the count to 0. + dfs(i + 1, 0, path) + path.pop() + + dfs(0, 0, []) + return ans diff --git a/solutions/3200. Maximum Height of a Triangle/3200.cpp b/solutions/3200. Maximum Height of a Triangle/3200.cpp new file mode 100644 index 00000000000..90ab797787a --- /dev/null +++ b/solutions/3200. Maximum Height of a Triangle/3200.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int maxHeightOfTriangle(int red, int blue) { + return max(maxHeight(red, blue), maxHeight(blue, red)); + } + + private: + // Returns the maximum height of a triangle with the odd levels having `n1` + // balls and the even levels having `n2` balls. + int maxHeight(int n1, int n2) { + // 1 + 3 + ... + h <= n1 + // ((1 + h) * (n + 1) / 2) / 2 <= n1 + // h <= sqrt(4 * n1) - 1 + const int oddHeight = sqrt(4 * n1) - 1; + // 2 + 4 + ... + h <= n2 + // ((2 + h) * h / 2) / 2 <= n2 + // h <= sqrt(4 * n2 + 1) - 1 + const int evenHeight = sqrt(4 * n2 + 1) - 1; + // If the difference between the odd and even heights is >= 1, we can add an + // extra level to the minimum height. + return min(oddHeight, evenHeight) + + (abs(oddHeight - evenHeight) >= 1 ? 1 : 0); + } +}; diff --git a/solutions/3200. Maximum Height of a Triangle/3200.java b/solutions/3200. Maximum Height of a Triangle/3200.java new file mode 100644 index 00000000000..5d628c34ca2 --- /dev/null +++ b/solutions/3200. Maximum Height of a Triangle/3200.java @@ -0,0 +1,21 @@ +class Solution { + public int maxHeightOfTriangle(int red, int blue) { + return Math.max(maxHeight(red, blue), maxHeight(blue, red)); + } + + // Returns the maximum height of a triangle with the odd levels having `n1` + // balls and the even levels having `n2` balls. + private int maxHeight(int n1, int n2) { + // 1 + 3 + ... + h <= n1 + // ((1 + h) * (n + 1) / 2) / 2 <= n1 + // h <= sqrt(4 * n1) - 1 + final int oddHeight = (int) Math.sqrt(4 * n1) - 1; + // 2 + 4 + ... + h <= n2 + // ((2 + h) * h / 2) / 2 <= n2 + // h <= sqrt(4 * n2 + 1) - 1 + final int evenHeight = (int) Math.sqrt(4 * n2 + 1) - 1; + // If the difference between the odd and even heights is >= 1, we can add an + // extra level to the minimum height. + return Math.min(oddHeight, evenHeight) + (Math.abs(oddHeight - evenHeight) >= 1 ? 1 : 0); + } +} diff --git a/solutions/3200. Maximum Height of a Triangle/3200.py b/solutions/3200. Maximum Height of a Triangle/3200.py new file mode 100644 index 00000000000..cf05d0ecc0b --- /dev/null +++ b/solutions/3200. Maximum Height of a Triangle/3200.py @@ -0,0 +1,21 @@ +class Solution: + def maxHeightOfTriangle(self, red: int, blue: int) -> int: + return max(self._maxHeight(red, blue), + self._maxHeight(blue, red)) + + def _maxHeight(self, n1: int, n2: int) -> int: + """ + Returns the maximum height of a triangle with the odd levels having `n1` + balls and the even levels having `n2` balls. + """ + # 1 + 3 + ... + h <= n1 + # ((1 + h) * (n + 1) / 2) / 2 <= n1 + # h <= sqrt(4 * n1) - 1 + oddHeight = math.isqrt(4 * n1) - 1 + # 2 + 4 + ... + h <= n2 + # ((2 + h) * h / 2) / 2 <= n2 + # h <= sqrt(4 * n2 + 1) - 1 + evenHeight = math.isqrt(4 * n2 + 1) - 1 + # If the difference between the odd and even heights is >= 1, we can add an + # extra level to the minimum height. + return min(oddHeight, evenHeight) + (1 if abs(oddHeight - evenHeight) >= 1 else 0) diff --git a/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.cpp b/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.cpp new file mode 100644 index 00000000000..8dc19422ded --- /dev/null +++ b/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int maximumLength(vector& nums) { + // dp[i][j] := the maximum length of a valid subsequence, where the last + // number mod 2 equal to i and the next desired number mod 2 equal to j + vector> dp(2, vector(2)); + + // Extend the pattern xyxyxy...xy. + for (const int x : nums) + for (int y = 0; y < 2; ++y) + dp[x % 2][y] = dp[y][x % 2] + 1; + + return accumulate(dp.begin(), dp.end(), 0, + [](int acc, const vector& row) { + return max(acc, ranges::max(row)); + }); + } +}; diff --git a/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.java b/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.java new file mode 100644 index 00000000000..c4a2e78ac5e --- /dev/null +++ b/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.java @@ -0,0 +1,14 @@ +class Solution { + public int maximumLength(int[] nums) { + // dp[i][j] := the maximum length of a valid subsequence, where the last + // number mod 2 equal to i and the next desired number mod 2 equal to j + int[][] dp = new int[k][k]; + + // Extend the pattern xyxyxy...xy. + for (final int x : nums) + for (int y = 0; y < 2; ++y) + dp[x % 2][y] = dp[y][x % 2] + 1; + + return Arrays.stream(dp).flatMapToInt(Arrays::stream).max().getAsInt(); + } +} diff --git a/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.py b/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.py new file mode 100644 index 00000000000..3322533f5d9 --- /dev/null +++ b/solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.py @@ -0,0 +1,12 @@ +class Solution: + def maximumLength(self, nums: List[int]) -> int: + # dp[i][j] := the maximum length of a valid subsequence, where the last + # number mod k equal to i and the next desired number mod k equal to j + dp = [[0] * 2 for _ in range(2)] + + # Extend the pattern xyxyxy...xy. + for x in nums: + for y in range(2): + dp[x % 2][y] = dp[y][x % 2] + 1 + + return max(map(max, dp)) diff --git a/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.cpp b/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.cpp new file mode 100644 index 00000000000..1ba68acaccd --- /dev/null +++ b/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + // Similar to 3201. Find the Maximum Length of Valid Subsequence I + int maximumLength(vector& nums, int k) { + // dp[i][j] := the maximum length of a valid subsequence, where the last + // number mod k equal to i and the next desired number mod k equal to j + vector> dp(k, vector(k)); + + // Extend the pattern xyxyxy...xy. + for (const int x : nums) + for (int y = 0; y < k; ++y) + dp[x % k][y] = dp[y][x % k] + 1; + + return accumulate(dp.begin(), dp.end(), 0, + [](int acc, const vector& row) { + return max(acc, ranges::max(row)); + }); + } +}; diff --git a/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.java b/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.java new file mode 100644 index 00000000000..5b57af2ff83 --- /dev/null +++ b/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.java @@ -0,0 +1,15 @@ +class Solution { + // Similar to 3201. Find the Maximum Length of Valid Subsequence I + public int maximumLength(int[] nums, int k) { + // dp[i][j] := the maximum length of a valid subsequence, where the last + // number mod k equal to i and the next desired number mod k equal to j + int[][] dp = new int[k][k]; + + // Extend the pattern xyxyxy...xy. + for (final int x : nums) + for (int y = 0; y < k; ++y) + dp[x % k][y] = dp[y][x % k] + 1; + + return Arrays.stream(dp).flatMapToInt(Arrays::stream).max().getAsInt(); + } +} diff --git a/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.py b/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.py new file mode 100644 index 00000000000..971d982c017 --- /dev/null +++ b/solutions/3202. Find the Maximum Length of Valid Subsequence II/3202.py @@ -0,0 +1,13 @@ +class Solution: + # Similar to 3201. Find the Maximum Length of Valid Subsequence I + def maximumLength(self, nums: List[int], k: int) -> int: + # dp[i][j] := the maximum length of a valid subsequence, where the last + # number mod k equal to i and the next desired number mod k equal to j + dp = [[0] * k for _ in range(k)] + + # Extend the pattern xyxyxy...xy. + for x in nums: + for y in range(k): + dp[x % k][y] = dp[y][x % k] + 1 + + return max(map(max, dp)) diff --git a/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.cpp b/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.cpp new file mode 100644 index 00000000000..7b33d627021 --- /dev/null +++ b/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int minimumDiameterAfterMerge(vector>& edges1, + vector>& edges2) { + const int diameter1 = getDiameter(edges1); + const int diameter2 = getDiameter(edges2); + const int combinedDiameter = (diameter1 + 1) / 2 + (diameter2 + 1) / 2 + 1; + return max({diameter1, diameter2, combinedDiameter}); + } + + private: + int getDiameter(const vector>& edges) { + const int n = edges.size() + 1; + vector> graph(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + int maxDiameter = 0; + maxDepth(graph, 0, /*prev=*/-1, maxDiameter); + return maxDiameter; + } + + // Similar to 1522. Diameter of N-Ary Tree + // Returns the maximum depth of the subtree rooted at u. + int maxDepth(const vector>& graph, int u, int prev, + int& maxDiameter) { + int maxSubDepth1 = 0; + int maxSubDepth2 = 0; + for (const int v : graph[u]) { + if (v == prev) + continue; + const int maxSubDepth = maxDepth(graph, v, u, maxDiameter); + if (maxSubDepth > maxSubDepth1) { + maxSubDepth2 = maxSubDepth1; + maxSubDepth1 = maxSubDepth; + } else if (maxSubDepth > maxSubDepth2) { + maxSubDepth2 = maxSubDepth; + } + } + maxDiameter = max(maxDiameter, maxSubDepth1 + maxSubDepth2); + return 1 + maxSubDepth1; + } +}; diff --git a/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.java b/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.java new file mode 100644 index 00000000000..85ed6c9c01b --- /dev/null +++ b/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.java @@ -0,0 +1,47 @@ +class Solution { + public int minimumDiameterAfterMerge(int[][] edges1, int[][] edges2) { + final int diameter1 = getDiameter(edges1); + final int diameter2 = getDiameter(edges2); + final int combinedDiameter = (diameter1 + 1) / 2 + (diameter2 + 1) / 2 + 1; + return Math.max(Math.max(diameter1, diameter2), combinedDiameter); + } + + private int getDiameter(int[][] edges) { + final int n = edges.length + 1; + List[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + int[] maxDiameter = new int[1]; + maxDepth(graph, 0, -1, maxDiameter); + return maxDiameter[0]; + } + + // Similar to 1522. Diameter of N-Ary Tree + // Returns the maximum depth of the subtree rooted at u. + private int maxDepth(List[] graph, int u, int prev, int[] maxDiameter) { + int maxSubDepth1 = 0; + int maxSubDepth2 = 0; + for (final int v : graph[u]) { + if (v == prev) + continue; + final int maxSubDepth = maxDepth(graph, v, u, maxDiameter); + if (maxSubDepth > maxSubDepth1) { + maxSubDepth2 = maxSubDepth1; + maxSubDepth1 = maxSubDepth; + } else if (maxSubDepth > maxSubDepth2) { + maxSubDepth2 = maxSubDepth; + } + } + maxDiameter[0] = Math.max(maxDiameter[0], maxSubDepth1 + maxSubDepth2); + return 1 + maxSubDepth1; + } +} diff --git a/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.py b/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.py new file mode 100644 index 00000000000..5c7c1c0cefd --- /dev/null +++ b/solutions/3203. Find Minimum Diameter After Merging Two Trees/3203.py @@ -0,0 +1,35 @@ +class Solution: + def minimumDiameterAfterMerge(self, edges1: List[List[int]], edges2: List[List[int]]) -> int: + diameter1 = self._getDiameter(edges1) + diameter2 = self._getDiameter(edges2) + combinedDiameter = (diameter1 + 1) // 2 + (diameter2 + 1) // 2 + 1 + return max(diameter1, diameter2, combinedDiameter) + + def _getDiameter(self, edges: List[List[int]]) -> int: + n = len(edges) + 1 + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + maxDiameter = [0] + self._maxDepth(graph, 0, -1, maxDiameter) + return maxDiameter[0] + + # Similar to 1522. Diameter of N-Ary Tree + def _maxDepth(self, graph: List[List[int]], u: int, prev: int, maxDiameter: List[int]) -> int: + """Returns the maximum depth of the subtree rooted at u.""" + maxSubDepth1 = 0 + maxSubDepth2 = 0 + for v in graph[u]: + if v == prev: + continue + maxSubDepth = self._maxDepth(graph, v, u, maxDiameter) + if maxSubDepth > maxSubDepth1: + maxSubDepth2 = maxSubDepth1 + maxSubDepth1 = maxSubDepth + elif maxSubDepth > maxSubDepth2: + maxSubDepth2 = maxSubDepth + maxDiameter[0] = max(maxDiameter[0], maxSubDepth1 + maxSubDepth2) + return 1 + maxSubDepth1 diff --git a/solutions/3204. Bitwise User Permissions Analysis/3204.sql b/solutions/3204. Bitwise User Permissions Analysis/3204.sql new file mode 100644 index 00000000000..d4fddfed90c --- /dev/null +++ b/solutions/3204. Bitwise User Permissions Analysis/3204.sql @@ -0,0 +1,4 @@ +SELECT + BIT_AND(permissions) AS common_perms, + BIT_OR(permissions) AS any_perms +FROM user_permissions; diff --git a/solutions/3205. Maximum Array Hopping Score I/3205-2.cpp b/solutions/3205. Maximum Array Hopping Score I/3205-2.cpp new file mode 100644 index 00000000000..f8b651ecfab --- /dev/null +++ b/solutions/3205. Maximum Array Hopping Score I/3205-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxScore(vector& nums) { + // The optimal next step is the highest number in the remaining suffix. + int ans = 0; + int suffixMax = 0; + + for (int i = nums.size() - 1; i > 0; --i) { + suffixMax = max(suffixMax, nums[i]); + ans += suffixMax; + } + + return ans; + } +}; diff --git a/solutions/3205. Maximum Array Hopping Score I/3205-2.java b/solutions/3205. Maximum Array Hopping Score I/3205-2.java new file mode 100644 index 00000000000..6da2a56e24d --- /dev/null +++ b/solutions/3205. Maximum Array Hopping Score I/3205-2.java @@ -0,0 +1,14 @@ +class Solution { + public int maxScore(int[] nums) { + // The optimal next step is the highest number in the remaining suffix. + int ans = 0; + int suffixMax = 0; + + for (int i = nums.length - 1; i > 0; --i) { + suffixMax = Math.max(suffixMax, nums[i]); + ans += suffixMax; + } + + return ans; + } +} diff --git a/solutions/3205. Maximum Array Hopping Score I/3205-2.py b/solutions/3205. Maximum Array Hopping Score I/3205-2.py new file mode 100644 index 00000000000..50823ac884d --- /dev/null +++ b/solutions/3205. Maximum Array Hopping Score I/3205-2.py @@ -0,0 +1,4 @@ +class Solution: + def maxScore(self, nums: List[int]) -> int: + # The optimal next step is the highest number in the remaining suffix. + return sum(itertools.accumulate(nums[:0:-1], max)) diff --git a/solutions/3205. Maximum Array Hopping Score I/3205.cpp b/solutions/3205. Maximum Array Hopping Score I/3205.cpp new file mode 100644 index 00000000000..55687290514 --- /dev/null +++ b/solutions/3205. Maximum Array Hopping Score I/3205.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxScore(vector& nums) { + const int n = nums.size(); + // dp[i] := the maximum score to jump from index i to n - 1 + vector dp(n); + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j < n; ++j) + // Jump from i to j, and then jump from j to n - 1. + dp[i] = max(dp[i], (j - i) * nums[j] + dp[j]); + + return dp[0]; + } +}; diff --git a/solutions/3205. Maximum Array Hopping Score I/3205.java b/solutions/3205. Maximum Array Hopping Score I/3205.java new file mode 100644 index 00000000000..665baf13a1c --- /dev/null +++ b/solutions/3205. Maximum Array Hopping Score I/3205.java @@ -0,0 +1,14 @@ +class Solution { + public int maxScore(int[] nums) { + final int n = nums.length; + // dp[i] := the maximum score to jump from index i to n - 1 + int[] dp = new int[n]; + + for (int i = n - 1; i >= 0; --i) + for (int j = i + 1; j < n; ++j) + // Jump from i to j, and then jump from j to n - 1. + dp[i] = Math.max(dp[i], (j - i) * nums[j] + dp[j]); + + return dp[0]; + } +} diff --git a/solutions/3205. Maximum Array Hopping Score I/3205.py b/solutions/3205. Maximum Array Hopping Score I/3205.py new file mode 100644 index 00000000000..04508dedb37 --- /dev/null +++ b/solutions/3205. Maximum Array Hopping Score I/3205.py @@ -0,0 +1,12 @@ +class Solution: + def maxScore(self, nums: List[int]) -> int: + n = len(nums) + # dp[i] := the maximum score to jump from index i to n - 1 + dp = [0] * n + + for i in reversed(range(n)): + for j in range(i + 1, n): + # Jump from i to j, and then jump from j to n - 1. + dp[i] = max(dp[i], (j - i) * nums[j] + dp[j]) + + return dp[0] diff --git a/solutions/3206. Alternating Groups I/3206.cpp b/solutions/3206. Alternating Groups I/3206.cpp new file mode 100644 index 00000000000..ee23bec8bd9 --- /dev/null +++ b/solutions/3206. Alternating Groups I/3206.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int numberOfAlternatingGroups(vector& colors) { + const int n = colors.size(); + int ans = 0; + + for (int i = 0; i < n; ++i) + if (colors[i] != colors[(i - 1 + n) % n] && + colors[i] != colors[(i + 1) % n]) + ++ans; + + return ans; + } +}; diff --git a/solutions/3206. Alternating Groups I/3206.java b/solutions/3206. Alternating Groups I/3206.java new file mode 100644 index 00000000000..0361a1e4746 --- /dev/null +++ b/solutions/3206. Alternating Groups I/3206.java @@ -0,0 +1,12 @@ +class Solution { + public int numberOfAlternatingGroups(int[] colors) { + final int n = colors.length; + int ans = 0; + + for (int i = 0; i < n; ++i) + if (colors[i] != colors[(i - 1 + n) % n] && colors[i] != colors[(i + 1) % n]) + ++ans; + + return ans; + } +} diff --git a/solutions/3206. Alternating Groups I/3206.py b/solutions/3206. Alternating Groups I/3206.py new file mode 100644 index 00000000000..6f5542fa29a --- /dev/null +++ b/solutions/3206. Alternating Groups I/3206.py @@ -0,0 +1,6 @@ +class Solution: + def numberOfAlternatingGroups(self, colors: List[int]) -> int: + n = len(colors) + return sum(colors[i] != colors[i - 1] and + colors[i] != colors[(i + 1) % n] + for i in range(n)) diff --git a/solutions/3207. Maximum Points After Enemy Battles/3207.cpp b/solutions/3207. Maximum Points After Enemy Battles/3207.cpp new file mode 100644 index 00000000000..7a59d7ea399 --- /dev/null +++ b/solutions/3207. Maximum Points After Enemy Battles/3207.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + long long maximumPoints(vector& enemyEnergies, int currentEnergy) { + const int minEnergy = ranges::min(enemyEnergies); + return currentEnergy < minEnergy + ? 0 + : (currentEnergy + + accumulate(enemyEnergies.begin(), enemyEnergies.end(), 0LL) - + minEnergy) / + minEnergy; + } +}; diff --git a/solutions/3207. Maximum Points After Enemy Battles/3207.java b/solutions/3207. Maximum Points After Enemy Battles/3207.java new file mode 100644 index 00000000000..9acc480fd6d --- /dev/null +++ b/solutions/3207. Maximum Points After Enemy Battles/3207.java @@ -0,0 +1,9 @@ +class Solution { + public long maximumPoints(int[] enemyEnergies, int currentEnergy) { + final int minEnergy = Arrays.stream(enemyEnergies).min().orElse(0); + return currentEnergy < minEnergy + ? 0 + : (currentEnergy + Arrays.stream(enemyEnergies).asLongStream().sum() - minEnergy) / + minEnergy; + } +} diff --git a/solutions/3207. Maximum Points After Enemy Battles/3207.py b/solutions/3207. Maximum Points After Enemy Battles/3207.py new file mode 100644 index 00000000000..d8b65f6ae67 --- /dev/null +++ b/solutions/3207. Maximum Points After Enemy Battles/3207.py @@ -0,0 +1,5 @@ +class Solution: + def maximumPoints(self, enemyEnergies: List[int], currentEnergy: int) -> int: + minEnergy = min(enemyEnergies) + return 0 if currentEnergy < minEnergy \ + else (currentEnergy + sum(enemyEnergies) - minEnergy) // minEnergy diff --git a/solutions/3208. Alternating Groups II/3208.cpp b/solutions/3208. Alternating Groups II/3208.cpp new file mode 100644 index 00000000000..3a191471711 --- /dev/null +++ b/solutions/3208. Alternating Groups II/3208.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int numberOfAlternatingGroups(vector& colors, int k) { + const int n = colors.size(); + int ans = 0; + int alternating = 1; + + for (int i = 0; i < n + k - 2; ++i) { + alternating = + colors[i % n] == colors[(i - 1 + n) % n] ? 1 : alternating + 1; + if (alternating >= k) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/3208. Alternating Groups II/3208.java b/solutions/3208. Alternating Groups II/3208.java new file mode 100644 index 00000000000..fb14c7ba83e --- /dev/null +++ b/solutions/3208. Alternating Groups II/3208.java @@ -0,0 +1,15 @@ +class Solution { + public int numberOfAlternatingGroups(int[] colors, int k) { + final int n = colors.length; + int ans = 0; + int alternating = 1; + + for (int i = 0; i < n + k - 2; ++i) { + alternating = colors[i % n] == colors[(i - 1 + n) % n] ? 1 : alternating + 1; + if (alternating >= k) + ++ans; + } + + return ans; + } +} diff --git a/solutions/3208. Alternating Groups II/3208.py b/solutions/3208. Alternating Groups II/3208.py new file mode 100644 index 00000000000..dedb3313f97 --- /dev/null +++ b/solutions/3208. Alternating Groups II/3208.py @@ -0,0 +1,13 @@ +class Solution: + def numberOfAlternatingGroups(self, colors: List[int], k: int) -> int: + n = len(colors) + ans = 0 + alternating = 1 + + for i in range(n + k - 2): + alternating = 1 if colors[i % n] == colors[(i - 1) % n] \ + else alternating + 1 + if alternating >= k: + ans += 1 + + return ans diff --git a/solutions/3209. Number of Subarrays With AND Value of K/3209.cpp b/solutions/3209. Number of Subarrays With AND Value of K/3209.cpp new file mode 100644 index 00000000000..0abdfae4e9a --- /dev/null +++ b/solutions/3209. Number of Subarrays With AND Value of K/3209.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + // Similar to 1521. Find a Value of a Mysterious Function Closest to Target + long long countSubarrays(vector& nums, int k) { + long long ans = 0; + // the counter of all the values of subarrays that end in the previous + // number + unordered_map prev; + + for (const int num : nums) { + unordered_map curr{{num, 1}}; + // Extend each subarray that ends in the previous number. Due to + // monotonicity of the AND operation, the size of `curr` will be at most + // num.bit_count() + 1. + for (const auto& [val, freq] : prev) + curr[val & num] += freq; + ans += curr.contains(k) ? curr[k] : 0; + prev = move(curr); + } + + return ans; + } +}; diff --git a/solutions/3209. Number of Subarrays With AND Value of K/3209.java b/solutions/3209. Number of Subarrays With AND Value of K/3209.java new file mode 100644 index 00000000000..3020c6cb141 --- /dev/null +++ b/solutions/3209. Number of Subarrays With AND Value of K/3209.java @@ -0,0 +1,27 @@ +class Solution { + // Similar to 1521. Find a Value of a Mysterious Function Closest to Target + public long countSubarrays(int[] nums, int k) { + long ans = 0; + // the counter of all the values of subarrays that end in the previous + // number + Map prev = new HashMap<>(); + + for (final int num : nums) { + Map curr = new HashMap<>() { + { put(num, 1); } + }; + // Extend each subarray that ends in the previous number. Due to + // monotonicity of the AND operation, the size of `curr` will be at most + // Integer.bitCount(num) + 1. + for (Map.Entry entry : prev.entrySet()) { + final int val = entry.getKey(); + final int freq = entry.getValue(); + curr.merge(val & num, freq, Integer::sum); + } + ans += curr.getOrDefault(k, 0); + prev = curr; + } + + return ans; + } +} diff --git a/solutions/3209. Number of Subarrays With AND Value of K/3209.py b/solutions/3209. Number of Subarrays With AND Value of K/3209.py new file mode 100644 index 00000000000..448c4aedc52 --- /dev/null +++ b/solutions/3209. Number of Subarrays With AND Value of K/3209.py @@ -0,0 +1,19 @@ +class Solution: + # Similar to 1521. Find a Value of a Mysterious Function Closest to Target + def countSubarrays(self, nums: List[int], k: int) -> int: + ans = 0 + # the counter of all the values of subarrays that end in the previous + # number + prev = collections.Counter() + + for num in nums: + # Extend each subarray that ends in the previous number. Due to + # monotonicity of the AND operation, the size of `curr` will be at most + # num.bit_count() + 1. + curr = collections.Counter({num: 1}) + for val, freq in prev.items(): + curr[val & num] += freq + ans += curr[k] + prev = curr + + return ans diff --git a/solutions/321. Create Maximum Number/321.cpp b/solutions/321. Create Maximum Number/321.cpp new file mode 100644 index 00000000000..44fb92b0fcc --- /dev/null +++ b/solutions/321. Create Maximum Number/321.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + vector maxNumber(vector& nums1, vector& nums2, int k) { + vector ans; + + for (int k1 = 0; k1 <= k; ++k1) { + const int k2 = k - k1; + if (k1 > nums1.size() || k2 > nums2.size()) + continue; + ans = max(ans, merge(maxArray(nums1, k1), maxArray(nums2, k2))); + } + + return ans; + } + + private: + vector maxArray(const vector& nums, int k) { + vector res; + int toPop = nums.size() - k; + for (const int num : nums) { + while (!res.empty() && res.back() < num && toPop-- > 0) + res.pop_back(); + res.push_back(num); + } + return {res.begin(), res.begin() + k}; + } + + // Merges nums1 and nums2. + vector merge(const vector& nums1, const vector& nums2) { + vector res; + auto s1 = nums1.cbegin(); + auto s2 = nums2.cbegin(); + while (s1 != nums1.cend() || s2 != nums2.cend()) + if (lexicographical_compare(s1, nums1.cend(), s2, nums2.cend())) + res.push_back(*s2++); + else + res.push_back(*s1++); + return res; + } +}; diff --git a/solutions/321. Create Maximum Number/321.java b/solutions/321. Create Maximum Number/321.java new file mode 100644 index 00000000000..6db5542aed6 --- /dev/null +++ b/solutions/321. Create Maximum Number/321.java @@ -0,0 +1,45 @@ +class Solution { + public int[] maxNumber(int[] nums1, int[] nums2, int k) { + int[] ans = new int[k]; + + for (int k1 = 0; k1 <= k; ++k1) { + final int k2 = k - k1; + if (k1 > nums1.length || k2 > nums2.length) + continue; + int[] candidate = merge(maxArray(nums1, k1), maxArray(nums2, k2)); + if (greater(candidate, 0, ans, 0)) + ans = candidate; + } + return ans; + } + + private int[] maxArray(int[] nums, int k) { + List res = new ArrayList<>(); + int toPop = nums.length - k; + for (final int num : nums) { + while (!res.isEmpty() && res.get(res.size() - 1) < num && toPop > 0) { + res.remove(res.size() - 1); + --toPop; + } + res.add(num); + } + return res.subList(0, k).stream().mapToInt(i -> i).toArray(); + } + + // Merges nums1 and nums2. + private int[] merge(int[] nums1, int[] nums2) { + int[] res = new int[nums1.length + nums2.length]; + for (int i = 0, j = 0, k = 0; k < res.length; ++k) + res[k] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++]; + return res; + } + + // Returns true if nums1[i..n) > nums2[j..n). + private boolean greater(int[] nums1, int i, int[] nums2, int j) { + while (i < nums1.length && j < nums2.length && nums1[i] == nums2[j]) { + ++i; + ++j; + } + return j == nums2.length || (i < nums1.length && nums1[i] > nums2[j]); + } +} diff --git a/solutions/321. Create Maximum Number/321.py b/solutions/321. Create Maximum Number/321.py new file mode 100644 index 00000000000..64ef2e74775 --- /dev/null +++ b/solutions/321. Create Maximum Number/321.py @@ -0,0 +1,18 @@ +class Solution: + def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: + def maxArray(nums: List[int], k: int) -> List[int]: + res = [] + toTop = len(nums) - k + for num in nums: + while res and res[-1] < num and toTop > 0: + res.pop() + toTop -= 1 + res.append(num) + return res[:k] + + def merge(nums1: List[int], nums2: List[int]) -> List[int]: + return [max(nums1, nums2).pop(0) for _ in nums1 + nums2] + + return max(merge(maxArray(nums1, i), maxArray(nums2, k - i)) + for i in range(k + 1) + if i <= len(nums1) and k - i <= len(nums2)) diff --git a/solutions/3210. Find the Encrypted String/3210.cpp b/solutions/3210. Find the Encrypted String/3210.cpp new file mode 100644 index 00000000000..2e4e98ef1c0 --- /dev/null +++ b/solutions/3210. Find the Encrypted String/3210.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + string getEncryptedString(string s, int k) { + k %= s.length(); + return s.substr(k) + s.substr(0, k); + } +}; diff --git a/solutions/3210. Find the Encrypted String/3210.java b/solutions/3210. Find the Encrypted String/3210.java new file mode 100644 index 00000000000..3a57914ae73 --- /dev/null +++ b/solutions/3210. Find the Encrypted String/3210.java @@ -0,0 +1,6 @@ +class Solution { + public String getEncryptedString(String s, int k) { + k %= s.length(); + return s.substring(k) + s.substring(0, k); + } +} diff --git a/solutions/3210. Find the Encrypted String/3210.py b/solutions/3210. Find the Encrypted String/3210.py new file mode 100644 index 00000000000..9e3ad38328e --- /dev/null +++ b/solutions/3210. Find the Encrypted String/3210.py @@ -0,0 +1,4 @@ +class Solution: + def getEncryptedString(self, s: str, k: int) -> str: + k %= len(s) + return s[k:] + s[0:k] diff --git a/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.cpp b/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.cpp new file mode 100644 index 00000000000..97dd6de47f3 --- /dev/null +++ b/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector validStrings(int n) { + vector ans; + dfs(n, "", ans); + return ans; + } + + private: + void dfs(int n, string&& s, vector& ans) { + if (n == 0) { + ans.push_back(s); + return; + } + if (s.empty() || s.back() == '1') { + s.push_back('0'); + dfs(n - 1, move(s), ans); + s.pop_back(); + } + s.push_back('1'); + dfs(n - 1, move(s), ans); + s.pop_back(); + } +}; diff --git a/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.java b/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.java new file mode 100644 index 00000000000..6aa716efcaf --- /dev/null +++ b/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.java @@ -0,0 +1,22 @@ +class Solution { + public List validStrings(int n) { + List ans = new ArrayList<>(); + dfs(n, new StringBuilder(), ans); + return ans; + } + + private void dfs(int n, StringBuilder s, List ans) { + if (n == 0) { + ans.add(s.toString()); + return; + } + if (s.isEmpty() || s.charAt(s.length() - 1) == '1') { + s.append('0'); + dfs(n - 1, s, ans); + s.deleteCharAt(s.length() - 1); + } + s.append('1'); + dfs(n - 1, s, ans); + s.deleteCharAt(s.length() - 1); + } +} diff --git a/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.py b/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.py new file mode 100644 index 00000000000..d8ba1fee46a --- /dev/null +++ b/solutions/3211. Generate Binary Strings Without Adjacent Zeros/3211.py @@ -0,0 +1,18 @@ +class Solution: + def validStrings(self, n: int) -> List[str]: + ans = [] + + def dfs(n: int, s: List[str]) -> None: + if n == 0: + ans.append(''.join(s)) + return + if not s or s[-1] == '1': + s.append('0') + dfs(n - 1, s) + s.pop() + s.append('1') + dfs(n - 1, s) + s.pop() + + dfs(n, []) + return ans diff --git a/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.cpp b/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.cpp new file mode 100644 index 00000000000..1a2739c9cec --- /dev/null +++ b/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int numberOfSubmatrices(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + // x[i][j] := the number of 'X' in grid[0..i)[0..j) + vector> x(m + 1, vector(n + 1)); + // y[i][j] := the number of 'Y' in grid[0..i)[0..j) + vector> y(m + 1, vector(n + 1)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + x[i + 1][j + 1] = + (grid[i][j] == 'X' ? 1 : 0) + x[i][j + 1] + x[i + 1][j] - x[i][j]; + y[i + 1][j + 1] = + (grid[i][j] == 'Y' ? 1 : 0) + y[i][j + 1] + y[i + 1][j] - y[i][j]; + if (x[i + 1][j + 1] > 0 && x[i + 1][j + 1] == y[i + 1][j + 1]) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.java b/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.java new file mode 100644 index 00000000000..55efa40e4ce --- /dev/null +++ b/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.java @@ -0,0 +1,21 @@ +class Solution { + public int numberOfSubmatrices(char[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + // x[i][j] := the number of 'X' in grid[0..i)[0..j) + int[][] x = new int[m + 1][n + 1]; + // y[i][j] := the number of 'Y' in grid[0..i)[0..j) + int[][] y = new int[m + 1][n + 1]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + x[i + 1][j + 1] = (grid[i][j] == 'X' ? 1 : 0) + x[i][j + 1] + x[i + 1][j] - x[i][j]; + y[i + 1][j + 1] = (grid[i][j] == 'Y' ? 1 : 0) + y[i][j + 1] + y[i + 1][j] - y[i][j]; + if (x[i + 1][j + 1] > 0 && x[i + 1][j + 1] == y[i + 1][j + 1]) + ++ans; + } + + return ans; + } +} diff --git a/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.py b/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.py new file mode 100644 index 00000000000..41c9203187e --- /dev/null +++ b/solutions/3212. Count Submatrices With Equal Frequency of X and Y/3212.py @@ -0,0 +1,18 @@ +class Solution: + def numberOfSubmatrices(self, grid: List[List[str]]) -> int: + m = len(grid) + n = len(grid[0]) + ans = 0 + # x[i][j] := the number of 'X' in grid[0..i)[0..j) + x = [[0] * (n + 1) for _ in range(m + 1)] + # y[i][j] := the number of 'Y' in grid[0..i)[0..j) + y = [[0] * (n + 1) for _ in range(m + 1)] + + for i, row in enumerate(grid): + for j, cell in enumerate(row): + x[i + 1][j + 1] = (cell == 'X') + x[i][j + 1] + x[i + 1][j] - x[i][j] + y[i + 1][j + 1] = (cell == 'Y') + y[i][j + 1] + y[i + 1][j] - y[i][j] + if x[i + 1][j + 1] > 0 and x[i + 1][j + 1] == y[i + 1][j + 1]: + ans += 1 + + return ans diff --git a/solutions/3213. Construct String with Minimum Cost/3213.cpp b/solutions/3213. Construct String with Minimum Cost/3213.cpp new file mode 100644 index 00000000000..34082448f63 --- /dev/null +++ b/solutions/3213. Construct String with Minimum Cost/3213.cpp @@ -0,0 +1,60 @@ +class TrieNode { + public: + vector> children; + int cost = INT_MAX; + TrieNode() : children(26) {} +}; + +class Trie { + public: + // Inserts a word with a cost. + void insert(const string& word, int cost) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->cost = min(node->cost, cost); + } + + // Returns the minimum cost to construct s[i:]. + int search(const string& word, int i, vector& mem) { + if (i == word.size()) + return 0; + if (mem[i] != INT_MAX) + return mem[i]; + int cost = INT_MAX; + shared_ptr node = root; + for (int j = i; j < word.length(); ++j) { + const int index = word[j] - 'a'; + if (node->children[index] == nullptr) + break; + node = node->children[index]; + if (node->cost != INT_MAX) { + const int childCost = search(word, j + 1, mem); + if (childCost != INT_MAX) + cost = min(cost, node->cost + childCost); + } + } + return mem[i] = cost; + } + + private: + shared_ptr root = make_shared(); +}; + +class Solution { + public: + int minimumCost(string target, vector& words, vector& costs) { + Trie trie; + + for (int i = 0; i < words.size(); ++i) + trie.insert(words[i], costs[i]); + + vector mem(target.size(), INT_MAX); + const int ans = trie.search(target, 0, mem); + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/3213. Construct String with Minimum Cost/3213.java b/solutions/3213. Construct String with Minimum Cost/3213.java new file mode 100644 index 00000000000..f7fe9e69293 --- /dev/null +++ b/solutions/3213. Construct String with Minimum Cost/3213.java @@ -0,0 +1,54 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int cost = Integer.MAX_VALUE; +} + +class Trie { + // Inserts a word with a cost. + public void insert(String word, int cost) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.cost = Math.min(node.cost, cost); + } + + // Returns the minimum cost to construct s[i:]. + public int search(final String word, int i, Integer[] mem) { + if (i == word.length()) + return 0; + if (mem[i] != null) + return mem[i]; + int cost = Integer.MAX_VALUE; + TrieNode node = root; + for (int j = i; j < word.length(); ++j) { + final int index = word.charAt(j) - 'a'; + if (node.children[index] == null) + break; + node = node.children[index]; + if (node.cost != Integer.MAX_VALUE) { + final int childCost = search(word, j + 1, mem); + if (childCost != Integer.MAX_VALUE) + cost = Math.min(cost, node.cost + childCost); + } + } + return mem[i] = cost; + } + + private TrieNode root = new TrieNode(); +} + +class Solution { + public int minimumCost(String target, String[] words, int[] costs) { + Trie trie = new Trie(); + + for (int i = 0; i < words.length; ++i) + trie.insert(words[i], costs[i]); + + final int ans = trie.search(target, 0, new Integer[target.length()]); + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/3213. Construct String with Minimum Cost/3213.py b/solutions/3213. Construct String with Minimum Cost/3213.py new file mode 100644 index 00000000000..2f43325a17e --- /dev/null +++ b/solutions/3213. Construct String with Minimum Cost/3213.py @@ -0,0 +1,44 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.cost = math.inf + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str, cost: int) -> None: + """Inserts a word with a cost.""" + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.cost = min(node.cost, cost) + + @functools.lru_cache(None) + def search(self, word: str, i: int) -> int: + """Returns the minimum cost to construct s[i:].""" + if i == len(word): + return 0 + cost = math.inf + node = self.root + for i in range(i, len(word)): + if word[i] not in node.children: + break + node = node.children[word[i]] + if node.cost != math.inf: + childCost = self.search(word, i + 1) + if childCost != math.inf: + cost = min(cost, node.cost + childCost) + return cost + + +class Solution: + def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int: + trie = Trie() + + for word, cost in zip(words, costs): + trie.insert(word, cost) + + ans = trie.search(target, 0) + return -1 if ans == math.inf else ans diff --git a/solutions/3214. Year on Year Growth Rate/3214.sql b/solutions/3214. Year on Year Growth Rate/3214.sql new file mode 100644 index 00000000000..5e51e4e75ab --- /dev/null +++ b/solutions/3214. Year on Year Growth Rate/3214.sql @@ -0,0 +1,21 @@ +WITH + YearlySpends AS ( + SELECT + product_id, + YEAR(transaction_date) AS year, + SUM(spend) AS spend + FROM user_transactions + GROUP BY 1, 2 + ) +SELECT + CurrYear.year, + CurrYear.product_id, + CurrYear.spend AS curr_year_spend, + PrevYear.spend AS prev_year_spend, + ROUND(100 * (CurrYear.spend - PrevYear.spend) / PrevYear.spend, 2) AS yoy_rate +FROM YearlySpends AS CurrYear +LEFT JOIN YearlySpends AS PrevYear + ON ( + CurrYear.product_id = PrevYear.product_id + AND CurrYear.year - 1 = PrevYear.year) +ORDER BY product_id, year; diff --git a/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.cpp b/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.cpp new file mode 100644 index 00000000000..74b6ba7e9cf --- /dev/null +++ b/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + // Same as 3199. Count Triplets with Even XOR Set Bits I + long long tripletCount(vector& a, vector& b, vector& c) { + const auto [evenA, oddA] = getEvenOddBitCount(a); + const auto [evenB, oddB] = getEvenOddBitCount(b); + const auto [evenC, oddC] = getEvenOddBitCount(c); + return static_cast(evenA) * oddB * oddC + + static_cast(oddA) * evenB * oddC + + static_cast(oddA) * oddB * evenC + + static_cast(evenA) * evenB * evenC; + } + + private: + // Returns the count of numbers in the `nums` arrays that have even number of + // ones and odd number of ones in their binary representation. + pair getEvenOddBitCount(const vector& nums) { + int even = 0; + int odd = 0; + for (const unsigned num : nums) + if (popcount(num) % 2 == 0) + ++even; + else + ++odd; + return {even, odd}; + } +}; diff --git a/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.java b/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.java new file mode 100644 index 00000000000..c6bfbc7c5a4 --- /dev/null +++ b/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.java @@ -0,0 +1,29 @@ +class Solution { + // Same as 3199. Count Triplets with Even XOR Set Bits I + public long tripletCount(int[] a, int[] b, int[] c) { + final int[] evenOddA = getEvenOddBitCount(a); + final int[] evenOddB = getEvenOddBitCount(b); + final int[] evenOddC = getEvenOddBitCount(c); + final int evenA = evenOddA[0]; + final int evenB = evenOddB[0]; + final int evenC = evenOddC[0]; + final int oddA = evenOddA[1]; + final int oddB = evenOddB[1]; + final int oddC = evenOddC[1]; + return (long) evenA * oddB * oddC + (long) oddA * evenB * oddC + (long) oddA * oddB * evenC + + (long) evenA * evenB * evenC; + } + + // Returns the count of numbers in the `nums` arrays that have even number of + // ones and odd number of ones in their binary representation. + private int[] getEvenOddBitCount(int[] nums) { + int even = 0; + int odd = 0; + for (final int num : nums) + if (Integer.bitCount(num) % 2 == 0) + ++even; + else + ++odd; + return new int[] {even, odd}; + } +} diff --git a/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.py b/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.py new file mode 100644 index 00000000000..235ecc9724c --- /dev/null +++ b/solutions/3215. Count Triplets with Even XOR Set Bits II/3215.py @@ -0,0 +1,15 @@ +class Solution: + # Same as 3199. Count Triplets with Even XOR Set Bits I + def tripletCount(self, a: List[int], b: List[int], c: List[int]) -> int: + evenA, oddA = self._getEvenOddBitCount(a) + evenB, oddB = self._getEvenOddBitCount(b) + evenC, oddC = self._getEvenOddBitCount(c) + return evenA * oddB * oddC + oddA * evenB * oddC + oddA * oddB * evenC + evenA * evenB * evenC + + def _getEvenOddBitCount(self, nums: List[int]) -> Tuple[int, int]: + """ + Returns the count of numbers in the `nums` arrays that have even number of + ones and odd number of ones in their binary representation. + """ + even = sum(num.bit_count() % 2 == 0 for num in nums) + return (even, len(nums) - even) diff --git a/solutions/3216. Lexicographically Smallest String After a Swap/3216.cpp b/solutions/3216. Lexicographically Smallest String After a Swap/3216.cpp new file mode 100644 index 00000000000..0967d1ad96c --- /dev/null +++ b/solutions/3216. Lexicographically Smallest String After a Swap/3216.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + string getSmallestString(string s) { + for (int i = 1; i < s.length(); ++i) + if (s[i - 1] % 2 == s[i] % 2 && s[i - 1] > s[i]) { + swap(s[i - 1], s[i]); + break; + } + return s; + } +}; diff --git a/solutions/3216. Lexicographically Smallest String After a Swap/3216.java b/solutions/3216. Lexicographically Smallest String After a Swap/3216.java new file mode 100644 index 00000000000..8ba98ea42bc --- /dev/null +++ b/solutions/3216. Lexicographically Smallest String After a Swap/3216.java @@ -0,0 +1,14 @@ +class Solution { + public String getSmallestString(String s) { + char[] chars = s.toCharArray(); + for (int i = 1; i < chars.length; ++i) { + if (chars[i - 1] % 2 == chars[i] % 2 && chars[i - 1] > chars[i]) { + final char temp = chars[i - 1]; + chars[i - 1] = chars[i]; + chars[i] = temp; + return new String(chars); + } + } + return s; + } +} diff --git a/solutions/3216. Lexicographically Smallest String After a Swap/3216.py b/solutions/3216. Lexicographically Smallest String After a Swap/3216.py new file mode 100644 index 00000000000..efd4f3351a6 --- /dev/null +++ b/solutions/3216. Lexicographically Smallest String After a Swap/3216.py @@ -0,0 +1,8 @@ +class Solution: + def getSmallestString(self, s: str) -> str: + chars = list(s) + for i, (a, b) in enumerate(itertools.pairwise(chars)): + if ord(a) % 2 == ord(b) % 2 and a > b: + chars[i], chars[i + 1] = chars[i + 1], chars[i] + return ''.join(chars) + return s diff --git a/solutions/3217. Delete Nodes From Linked List Present in Array/3217.cpp b/solutions/3217. Delete Nodes From Linked List Present in Array/3217.cpp new file mode 100644 index 00000000000..241c26dd7a7 --- /dev/null +++ b/solutions/3217. Delete Nodes From Linked List Present in Array/3217.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + ListNode* modifiedList(vector& nums, ListNode* head) { + ListNode dummy(0, head); + unordered_set numsSet{nums.begin(), nums.end()}; + + for (ListNode* curr = &dummy; curr->next != nullptr;) + if (numsSet.contains(curr->next->val)) + curr->next = curr->next->next; + else + curr = curr->next; + + return dummy.next; + } +}; diff --git a/solutions/3217. Delete Nodes From Linked List Present in Array/3217.java b/solutions/3217. Delete Nodes From Linked List Present in Array/3217.java new file mode 100644 index 00000000000..34529729e40 --- /dev/null +++ b/solutions/3217. Delete Nodes From Linked List Present in Array/3217.java @@ -0,0 +1,14 @@ +class Solution { + public ListNode modifiedList(int[] nums, ListNode head) { + ListNode dummy = new ListNode(0, head); + Set numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + + for (ListNode curr = dummy; curr.next != null;) + if (numsSet.contains(curr.next.val)) + curr.next = curr.next.next; + else + curr = curr.next; + + return dummy.next; + } +} diff --git a/solutions/3217. Delete Nodes From Linked List Present in Array/3217.py b/solutions/3217. Delete Nodes From Linked List Present in Array/3217.py new file mode 100644 index 00000000000..70ebc930034 --- /dev/null +++ b/solutions/3217. Delete Nodes From Linked List Present in Array/3217.py @@ -0,0 +1,13 @@ +class Solution: + def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(0, head) + numsSet = set(nums) + + curr = dummy + while curr.next: + if curr.next.val in numsSet: + curr.next = curr.next.next + else: + curr = curr.next + + return dummy.next diff --git a/solutions/3218. Minimum Cost for Cutting Cake I/3218.cpp b/solutions/3218. Minimum Cost for Cutting Cake I/3218.cpp new file mode 100644 index 00000000000..157f696dab0 --- /dev/null +++ b/solutions/3218. Minimum Cost for Cutting Cake I/3218.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int minimumCost(int m, int n, vector& horizontalCut, + vector& verticalCut) { + int cost = 0; + int sumH = accumulate(horizontalCut.begin(), horizontalCut.end(), 0); + int sumV = accumulate(verticalCut.begin(), verticalCut.end(), 0); + + ranges::sort(horizontalCut, greater<>()); + ranges::sort(verticalCut, greater<>()); + + for (int i = 0, j = 0; i < m - 1 && j < n - 1;) + if (horizontalCut[i] > verticalCut[j]) { + cost += horizontalCut[i] + sumV; + sumH -= horizontalCut[i++]; + } else { + cost += verticalCut[j] + sumH; + sumV -= verticalCut[j++]; + } + + return cost + sumH + sumV; + } +}; diff --git a/solutions/3218. Minimum Cost for Cutting Cake I/3218.java b/solutions/3218. Minimum Cost for Cutting Cake I/3218.java new file mode 100644 index 00000000000..d9a144304d5 --- /dev/null +++ b/solutions/3218. Minimum Cost for Cutting Cake I/3218.java @@ -0,0 +1,21 @@ +class Solution { + public int minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) { + int cost = 0; + int sumH = Arrays.stream(horizontalCut).sum(); + int sumV = Arrays.stream(verticalCut).sum(); + + Arrays.sort(horizontalCut); + Arrays.sort(verticalCut); + + for (int i = m - 2, j = n - 2; i >= 0 && j >= 0;) + if (horizontalCut[i] > verticalCut[j]) { + cost += horizontalCut[i] + sumV; + sumH -= horizontalCut[i--]; + } else { + cost += verticalCut[j] + sumH; + sumV -= verticalCut[j--]; + } + + return cost + sumH + sumV; + } +} diff --git a/solutions/3218. Minimum Cost for Cutting Cake I/3218.py b/solutions/3218. Minimum Cost for Cutting Cake I/3218.py new file mode 100644 index 00000000000..437452cc169 --- /dev/null +++ b/solutions/3218. Minimum Cost for Cutting Cake I/3218.py @@ -0,0 +1,18 @@ +class Solution: + def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int: + ans = 0 + sumH = sum(horizontalCut) + sumV = sum(verticalCut) + + horizontalCut.sort() + verticalCut.sort() + + while horizontalCut and verticalCut: + if horizontalCut[-1] > verticalCut[-1]: + ans += horizontalCut[-1] + sumV + sumH -= horizontalCut.pop() + else: + ans += verticalCut[-1] + sumH + sumV -= verticalCut.pop() + + return ans + sumH + sumV diff --git a/solutions/3219. Minimum Cost for Cutting Cake II/3219.cpp b/solutions/3219. Minimum Cost for Cutting Cake II/3219.cpp new file mode 100644 index 00000000000..6290d709e26 --- /dev/null +++ b/solutions/3219. Minimum Cost for Cutting Cake II/3219.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + // Same as 3218. Minimum Cost for Cutting Cake I + long long minimumCost(int m, int n, vector& horizontalCut, + vector& verticalCut) { + long cost = 0; + long sumH = accumulate(horizontalCut.begin(), horizontalCut.end(), 0L); + long sumV = accumulate(verticalCut.begin(), verticalCut.end(), 0L); + + ranges::sort(horizontalCut, greater<>()); + ranges::sort(verticalCut, greater<>()); + + for (int i = 0, j = 0; i < m - 1 && j < n - 1;) + if (horizontalCut[i] > verticalCut[j]) { + cost += horizontalCut[i] + sumV; + sumH -= horizontalCut[i++]; + } else { + cost += verticalCut[j] + sumH; + sumV -= verticalCut[j++]; + } + + return cost + sumH + sumV; + } +}; diff --git a/solutions/3219. Minimum Cost for Cutting Cake II/3219.java b/solutions/3219. Minimum Cost for Cutting Cake II/3219.java new file mode 100644 index 00000000000..c8c1b016195 --- /dev/null +++ b/solutions/3219. Minimum Cost for Cutting Cake II/3219.java @@ -0,0 +1,22 @@ +class Solution { + // Same as 3218. Minimum Cost for Cutting Cake I + public long minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) { + long cost = 0; + long sumH = Arrays.stream(horizontalCut).asLongStream().sum(); + long sumV = Arrays.stream(verticalCut).asLongStream().sum(); + + Arrays.sort(horizontalCut); + Arrays.sort(verticalCut); + + for (int i = m - 2, j = n - 2; i >= 0 && j >= 0;) + if (horizontalCut[i] > verticalCut[j]) { + cost += horizontalCut[i] + sumV; + sumH -= horizontalCut[i--]; + } else { + cost += verticalCut[j] + sumH; + sumV -= verticalCut[j--]; + } + + return cost + sumH + sumV; + } +} diff --git a/solutions/3219. Minimum Cost for Cutting Cake II/3219.py b/solutions/3219. Minimum Cost for Cutting Cake II/3219.py new file mode 100644 index 00000000000..43389d74d7b --- /dev/null +++ b/solutions/3219. Minimum Cost for Cutting Cake II/3219.py @@ -0,0 +1,19 @@ +class Solution: + # Same as 3218. Minimum Cost for Cutting Cake I + def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int: + ans = 0 + sumH = sum(horizontalCut) + sumV = sum(verticalCut) + + horizontalCut.sort() + verticalCut.sort() + + while horizontalCut and verticalCut: + if horizontalCut[-1] > verticalCut[-1]: + ans += horizontalCut[-1] + sumV + sumH -= horizontalCut.pop() + else: + ans += verticalCut[-1] + sumH + sumV -= verticalCut.pop() + + return ans + sumH + sumV diff --git a/solutions/322. Coin Change/322-2.cpp b/solutions/322. Coin Change/322-2.cpp new file mode 100644 index 00000000000..61e1010ca38 --- /dev/null +++ b/solutions/322. Coin Change/322-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int coinChange(vector& coins, int amount) { + // dp[i] := the minimum number of coins to make up i + vector dp(amount + 1, amount + 1); + dp[0] = 0; + + for (int i = 1; i <= amount; ++i) + for (const int coin : coins) + if (coin <= i) + dp[i] = min(dp[i], dp[i - coin] + 1); + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } +}; diff --git a/solutions/322. Coin Change/322-2.java b/solutions/322. Coin Change/322-2.java new file mode 100644 index 00000000000..b3c1620f701 --- /dev/null +++ b/solutions/322. Coin Change/322-2.java @@ -0,0 +1,14 @@ +class Solution { + public int coinChange(int[] coins, int amount) { + // dp[i] := the minimum number of coins to make up i + int[] dp = new int[amount + 1]; + Arrays.fill(dp, 1, dp.length, amount + 1); + + for (int i = 1; i <= amount; ++i) + for (final int coin : coins) + if (coin <= i) + dp[i] = Math.min(dp[i], dp[i - coin] + 1); + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } +} diff --git a/solutions/322. Coin Change/322.cpp b/solutions/322. Coin Change/322.cpp new file mode 100644 index 00000000000..130d1cfdf0f --- /dev/null +++ b/solutions/322. Coin Change/322.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int coinChange(vector& coins, int amount) { + // dp[i] := the minimum number of coins to make up i + vector dp(amount + 1, amount + 1); + dp[0] = 0; + + for (const int coin : coins) + for (int i = coin; i <= amount; ++i) + dp[i] = min(dp[i], dp[i - coin] + 1); + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } +}; diff --git a/solutions/322. Coin Change/322.java b/solutions/322. Coin Change/322.java new file mode 100644 index 00000000000..ee636116848 --- /dev/null +++ b/solutions/322. Coin Change/322.java @@ -0,0 +1,13 @@ +class Solution { + public int coinChange(int[] coins, int amount) { + // dp[i] := the minimum number of coins to make up i + int[] dp = new int[amount + 1]; + Arrays.fill(dp, 1, dp.length, amount + 1); + + for (final int coin : coins) + for (int i = coin; i <= amount; ++i) + dp[i] = Math.min(dp[i], dp[i - coin] + 1); + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } +} diff --git a/solutions/322. Coin Change/322.py b/solutions/322. Coin Change/322.py new file mode 100644 index 00000000000..3589e5af15b --- /dev/null +++ b/solutions/322. Coin Change/322.py @@ -0,0 +1,10 @@ +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + # dp[i] := the minimum number Of coins to make up i + dp = [0] + [amount + 1] * amount + + for coin in coins: + for i in range(coin, amount + 1): + dp[i] = min(dp[i], dp[i - coin] + 1) + + return -1 if dp[amount] == amount + 1 else dp[amount] diff --git a/solutions/3220. Odd and Even Transactions/3220.sql b/solutions/3220. Odd and Even Transactions/3220.sql new file mode 100644 index 00000000000..b6c369ea89a --- /dev/null +++ b/solutions/3220. Odd and Even Transactions/3220.sql @@ -0,0 +1,7 @@ +SELECT + transaction_date, + SUM(IF(amount % 2 = 1, amount, 0)) AS odd_sum, + SUM(IF(amount % 2 = 0, amount, 0)) AS even_sum +FROM Transactions +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/3221. Maximum Array Hopping Score II/3221.cpp b/solutions/3221. Maximum Array Hopping Score II/3221.cpp new file mode 100644 index 00000000000..ae19b7854a9 --- /dev/null +++ b/solutions/3221. Maximum Array Hopping Score II/3221.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + // Same as 3205. Maximum Array Hopping Score I + long long maxScore(vector& nums) { + // The optimal next step is the highest number in the remaining suffix. + long ans = 0; + int suffixMax = 0; + + for (int i = nums.size() - 1; i > 0; --i) { + suffixMax = max(suffixMax, nums[i]); + ans += suffixMax; + } + + return ans; + } +}; diff --git a/solutions/3221. Maximum Array Hopping Score II/3221.java b/solutions/3221. Maximum Array Hopping Score II/3221.java new file mode 100644 index 00000000000..33b101cdf1b --- /dev/null +++ b/solutions/3221. Maximum Array Hopping Score II/3221.java @@ -0,0 +1,15 @@ +class Solution { + // Same as 3205. Maximum Array Hopping Score I + public long maxScore(int[] nums) { + // The optimal next step is the highest number in the remaining suffix. + long ans = 0; + int suffixMax = 0; + + for (int i = nums.length - 1; i > 0; --i) { + suffixMax = Math.max(suffixMax, nums[i]); + ans += suffixMax; + } + + return ans; + } +} diff --git a/solutions/3221. Maximum Array Hopping Score II/3221.py b/solutions/3221. Maximum Array Hopping Score II/3221.py new file mode 100644 index 00000000000..7fb5fb61914 --- /dev/null +++ b/solutions/3221. Maximum Array Hopping Score II/3221.py @@ -0,0 +1,5 @@ +class Solution: + # Same as 3205. Maximum Array Hopping Score I + def maxScore(self, nums: List[int]) -> int: + # The optimal next step is the highest number in the remaining suffix. + return sum(itertools.accumulate(nums[:0:-1], max)) diff --git a/solutions/3222. Find the Winning Player in Coin Game/3222.cpp b/solutions/3222. Find the Winning Player in Coin Game/3222.cpp new file mode 100644 index 00000000000..d8a8e4c18e3 --- /dev/null +++ b/solutions/3222. Find the Winning Player in Coin Game/3222.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + string losingPlayer(int x, int y) { + return min(x, y / 4) % 2 == 0 ? "Bob" : "Alice"; + } +}; diff --git a/solutions/3222. Find the Winning Player in Coin Game/3222.java b/solutions/3222. Find the Winning Player in Coin Game/3222.java new file mode 100644 index 00000000000..1c1f3de42d1 --- /dev/null +++ b/solutions/3222. Find the Winning Player in Coin Game/3222.java @@ -0,0 +1,5 @@ +class Solution { + public String losingPlayer(int x, int y) { + return Math.min(x, y / 4) % 2 == 0 ? "Bob" : "Alice"; + } +} diff --git a/solutions/3222. Find the Winning Player in Coin Game/3222.py b/solutions/3222. Find the Winning Player in Coin Game/3222.py new file mode 100644 index 00000000000..69549ae8298 --- /dev/null +++ b/solutions/3222. Find the Winning Player in Coin Game/3222.py @@ -0,0 +1,3 @@ +class Solution: + def losingPlayer(self, x: int, y: int) -> str: + return 'Bob' if min(x, y // 4) % 2 == 0 else 'Alice' diff --git a/solutions/3223. Minimum Length of String After Operations/3223.cpp b/solutions/3223. Minimum Length of String After Operations/3223.cpp new file mode 100644 index 00000000000..22ed8b69443 --- /dev/null +++ b/solutions/3223. Minimum Length of String After Operations/3223.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minimumLength(string s) { + int ans = 0; + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + for (int i = 0; i < 26; ++i) + if (count[i] > 0) + ans += count[i] % 2 == 0 ? 2 : 1; + + return ans; + } +}; diff --git a/solutions/3223. Minimum Length of String After Operations/3223.java b/solutions/3223. Minimum Length of String After Operations/3223.java new file mode 100644 index 00000000000..8a40f6e6565 --- /dev/null +++ b/solutions/3223. Minimum Length of String After Operations/3223.java @@ -0,0 +1,15 @@ +class Solution { + public int minimumLength(String s) { + int ans = 0; + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (int i = 0; i < 26; ++i) + if (count[i] > 0) + ans += count[i] % 2 == 0 ? 2 : 1; + + return ans; + } +} diff --git a/solutions/3223. Minimum Length of String After Operations/3223.py b/solutions/3223. Minimum Length of String After Operations/3223.py new file mode 100644 index 00000000000..d5d564cc309 --- /dev/null +++ b/solutions/3223. Minimum Length of String After Operations/3223.py @@ -0,0 +1,4 @@ +class Solution: + def minimumLength(self, s: str) -> int: + count = collections.Counter(s) + return sum(2 if freq % 2 == 0 else 1 for freq in count.values()) diff --git a/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.cpp b/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.cpp new file mode 100644 index 00000000000..7c39de4e5f8 --- /dev/null +++ b/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int minChanges(vector& nums, int k) { + const int n = nums.size(); + const int pairSize = n / 2; + int ans = n; + unordered_map diffCount; // {abs(nums[-i - 1] - nums[i]): freq} + // oneChangeCount[i] := the number of pairs that need only one change to to + // achieve a difference of `i` + vector oneChangeCount(k + 1); + + for (int i = 0; i < pairSize; ++i) { + const int a = nums[i]; + const int b = nums[n - i - 1]; + ++diffCount[abs(a - b)]; + ++oneChangeCount[max({a, b, k - a, k - b})]; + } + + // prefixOneChangeCount[i] := the number of pairs that need only one change + // to achieve a difference >= `i` + // prefixOneChangeCount[i] = sum(oneChangeCount[i..k]) + vector prefixOneChangeCount{oneChangeCount}; + + for (int i = k - 1; i >= 0; --i) + prefixOneChangeCount[i] += prefixOneChangeCount[i + 1]; + + for (const auto& [diff, freq] : diffCount) { + const int oneChange = prefixOneChangeCount[diff] - freq; + const int twoChanges = (pairSize - prefixOneChangeCount[diff]) * 2; + ans = min(ans, oneChange + twoChanges); + } + + return ans; + } +}; diff --git a/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.java b/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.java new file mode 100644 index 00000000000..8332b61e706 --- /dev/null +++ b/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.java @@ -0,0 +1,36 @@ +class Solution { + public int minChanges(int[] nums, int k) { + final int n = nums.length; + final int pairSize = n / 2; + int ans = n; + Map diffCount = new HashMap<>(); // {abs(nums[-i - 1] - nums[i]): freq} + // oneChangeCount[i] := the number of pairs that need only one change to + // achieve a difference of `i` + int[] oneChangeCount = new int[k + 1]; + + for (int i = 0; i < pairSize; ++i) { + final int a = nums[i]; + final int b = nums[n - i - 1]; + diffCount.merge(Math.abs(a - b), 1, Integer::sum); + ++oneChangeCount[Math.max(Math.max(a, b), Math.max(k - a, k - b))]; + } + + // prefixOneChangeCount[i] := the number of pairs that need only one change + // to achieve a difference >= `i` + // prefixOneChangeCount[i] = sum(oneChangeCount[i..k]) + int[] prefixOneChangeCount = oneChangeCount.clone(); + + for (int i = k - 1; i >= 0; --i) + prefixOneChangeCount[i] += prefixOneChangeCount[i + 1]; + + for (Map.Entry entry : diffCount.entrySet()) { + final int diff = entry.getKey(); + final int freq = entry.getValue(); + final int oneChange = prefixOneChangeCount[diff] - freq; + final int twoChanges = (pairSize - prefixOneChangeCount[diff]) * 2; + ans = Math.min(ans, oneChange + twoChanges); + } + + return ans; + } +} diff --git a/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.py b/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.py new file mode 100644 index 00000000000..71c437466e1 --- /dev/null +++ b/solutions/3224. Minimum Array Changes to Make Differences Equal/3224.py @@ -0,0 +1,23 @@ +class Solution: + def minChanges(self, nums: List[int], k: int) -> int: + pairSize = len(nums) // 2 + diffCount = collections.Counter() # {nums[-i - 1] - nums[i]: freq} + # oneChangeCount[i] := the number of pairs that need only one change to + # to achieve a difference of `i` + oneChangeCount = [0] * (k + 1) + + for i in range(pairSize): + a = nums[i] + b = nums[-i - 1] + diffCount[abs(a - b)] += 1 + oneChangeCount[max(a, b, k - a, k - b)] += 1 + + # prefixOneChangeCount[i] := the number of pairs that need only one change + # to achieve a difference >= `i` + # prefixOneChangeCount[i] = sum(oneChangeCount[i..k]) + prefixOneChangeCount = list( + itertools.accumulate(reversed(oneChangeCount)))[::-1] + + return min(prefixOneChangeCount[diff] - freq + # one change + (pairSize - prefixOneChangeCount[diff]) * 2 # two changes + for diff, freq in diffCount.items()) diff --git a/solutions/3225. Maximum Score From Grid Operations/3225.cpp b/solutions/3225. Maximum Score From Grid Operations/3225.cpp new file mode 100644 index 00000000000..b797f6270bc --- /dev/null +++ b/solutions/3225. Maximum Score From Grid Operations/3225.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + long long maximumScore(vector>& grid) { + const int n = grid.size(); + // prefix[j][i] := the sum of the first i elements in the j-th column + vector> prefix(n, vector(n + 1)); + // prevPick[i] := the maximum achievable score up to the previous column, + // where the bottommost selected element in that column is in row (i - 1) + vector prevPick(n + 1); + // prevSkip[i] := the maximum achievable score up to the previous column, + // where the bottommost selected element in the column before the previous + // one is in row (i - 1) + vector prevSkip(n + 1); + + for (int j = 0; j < n; ++j) + for (int i = 0; i < n; ++i) + prefix[j][i + 1] = prefix[j][i] + grid[i][j]; + + for (int j = 1; j < n; ++j) { + vector currPick(n + 1); + vector currSkip(n + 1); + // Consider all possible combinations of the number of current and + // previous selected elements. + for (int curr = 0; curr <= n; ++curr) + for (int prev = 0; prev <= n; ++prev) + if (curr > prev) { + // 1. The current bottom is deeper than the previous bottom. + // Get the score of grid[prev..curr)[j - 1] for pick and skip. + const long score = prefix[j - 1][curr] - prefix[j - 1][prev]; + currPick[curr] = max(currPick[curr], prevSkip[prev] + score); + currSkip[curr] = max(currSkip[curr], prevSkip[prev] + score); + } else { + // 2. The previous bottom is deeper than the current bottom. + // Get the score of grid[curr..prev)[j] for pick only. + const long score = prefix[j][prev] - prefix[j][curr]; + currPick[curr] = max(currPick[curr], prevPick[prev] + score); + currSkip[curr] = max(currSkip[curr], prevPick[prev]); + } + prevPick = move(currPick); + prevSkip = move(currSkip); + } + + return ranges::max(prevPick); + } +}; diff --git a/solutions/3225. Maximum Score From Grid Operations/3225.java b/solutions/3225. Maximum Score From Grid Operations/3225.java new file mode 100644 index 00000000000..697552ab2b3 --- /dev/null +++ b/solutions/3225. Maximum Score From Grid Operations/3225.java @@ -0,0 +1,44 @@ +class Solution { + public long maximumScore(int[][] grid) { + final int n = grid.length; + // prefix[j][i] := the sum of the first i elements in the j-th column + long[][] prefix = new long[n][n + 1]; + // prevPick[i] := the maximum achievable score up to the previous column, + // where the bottommost selected element in that column is in row (i - 1) + long[] prevPick = new long[n + 1]; + // prevSkip[i] := the maximum achievable score up to the previous column, + // where the bottommost selected element in the column before the previous + // one is in row (i - 1) + long[] prevSkip = new long[n + 1]; + + for (int j = 0; j < n; ++j) + for (int i = 0; i < n; ++i) + prefix[j][i + 1] = prefix[j][i] + grid[i][j]; + + for (int j = 1; j < n; ++j) { + long[] currPick = new long[n + 1]; + long[] currSkip = new long[n + 1]; + // Consider all possible combinations of the number of current and + // previous selected elements. + for (int curr = 0; curr <= n; ++curr) + for (int prev = 0; prev <= n; ++prev) + if (curr > prev) { + // 1. The current bottom is deeper than the previous bottom. + // Get the score of grid[prev..curr)[j - 1] for pick and skip. + final long score = prefix[j - 1][curr] - prefix[j - 1][prev]; + currPick[curr] = Math.max(currPick[curr], prevSkip[prev] + score); + currSkip[curr] = Math.max(currSkip[curr], prevSkip[prev] + score); + } else { + // 2. The previous bottom is deeper than the current bottom. + // Get the score of grid[curr..prev)[j] for pick only. + final long score = prefix[j][prev] - prefix[j][curr]; + currPick[curr] = Math.max(currPick[curr], prevPick[prev] + score); + currSkip[curr] = Math.max(currSkip[curr], prevPick[prev]); + } + prevPick = currPick; + prevSkip = currSkip; + } + + return Arrays.stream(prevPick).max().getAsLong(); + } +} diff --git a/solutions/3225. Maximum Score From Grid Operations/3225.py b/solutions/3225. Maximum Score From Grid Operations/3225.py new file mode 100644 index 00000000000..2fe2e98d77b --- /dev/null +++ b/solutions/3225. Maximum Score From Grid Operations/3225.py @@ -0,0 +1,40 @@ +class Solution: + def maximumScore(self, grid: List[List[int]]) -> int: + n = len(grid) + # prefix[j][i] := the sum of the first i elements in the j-th column + prefix = [[0] * (n + 1) for _ in range(n)] + # prevPick[i] := the maximum score up to the previous column, where the + # bottommost selected element in the previous column is in row (i - 1) + prevPick = [0] * (n + 1) + # prevSkip[i] := the maximum score up to the previous column, where the + # bottommost selected element in the column before the previous one is in + # row (i - 1) + prevSkip = [0] * (n + 1) + + for j in range(n): + for i in range(n): + prefix[j][i + 1] = prefix[j][i] + grid[i][j] + + for j in range(1, n): + currPick = [0] * (n + 1) + currSkip = [0] * (n + 1) + # Consider all possible combinations of the number of current and + # previous selected elements. + for curr in range(n + 1): # the number of current selected elements + for prev in range(n + 1): # the number of previous selected elements + if curr > prev: + # 1. The current bottom is deeper than the previous bottom. + # Get the score of grid[prev..curr)[j - 1] for both pick and skip. + score = prefix[j - 1][curr] - prefix[j - 1][prev] + currPick[curr] = max(currPick[curr], prevSkip[prev] + score) + currSkip[curr] = max(currSkip[curr], prevSkip[prev] + score) + else: + # 2. The previous bottom is deeper than the current bottom. + # Get the score of grid[curr..prev)[j] for pick only. + score = prefix[j][prev] - prefix[j][curr] + currPick[curr] = max(currPick[curr], prevPick[prev] + score) + currSkip[curr] = max(currSkip[curr], prevPick[prev]) + prevPick = currPick + prevSkip = currSkip + + return max(prevPick) diff --git a/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.cpp b/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.cpp new file mode 100644 index 00000000000..16105946cd4 --- /dev/null +++ b/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int minChanges(unsigned n, unsigned k) { + // n needs to be a superset of k. + return (n & k) == k ? popcount(n ^ k) : -1; + } +}; diff --git a/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.java b/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.java new file mode 100644 index 00000000000..d9355997600 --- /dev/null +++ b/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.java @@ -0,0 +1,6 @@ +class Solution { + public int minChanges(int n, int k) { + // n needs to be a superset of k. + return (n & k) == k ? Integer.bitCount(n ^ k) : -1; + } +} diff --git a/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.py b/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.py new file mode 100644 index 00000000000..070825a0c81 --- /dev/null +++ b/solutions/3226. Number of Bit Changes to Make Two Integers Equal/3226.py @@ -0,0 +1,4 @@ +class Solution: + def minChanges(self, n: int, k: int) -> int: + # n needs to be a superset of k. + return (n ^ k).bit_count() if (n & k) == k else -1 diff --git a/solutions/3227. Vowels Game in a String/3227.cpp b/solutions/3227. Vowels Game in a String/3227.cpp new file mode 100644 index 00000000000..f6d00f019c8 --- /dev/null +++ b/solutions/3227. Vowels Game in a String/3227.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool doesAliceWin(string s) { + // Let k be the number of vowels in s. + // 1. If k == 0, Bob wins since Alice has no vowels to pick. + // 2. If k % 2 == 1, Alice wins since Alice can pick the entire string. + // 3. If k % 2 == 0, Alice wins since Alice can pick (k - 1) vowels, + // then Bob will either pick a substring containing 0 vowels, resulting in + // Alice picking the remaining entire string, or Bob couldn't pick at all + // (the last vowel). + return ranges::any_of(s, [=](char c) { return isVowel(c); }); + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiou"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/3227. Vowels Game in a String/3227.java b/solutions/3227. Vowels Game in a String/3227.java new file mode 100644 index 00000000000..2b45c69c4a9 --- /dev/null +++ b/solutions/3227. Vowels Game in a String/3227.java @@ -0,0 +1,16 @@ +class Solution { + public boolean doesAliceWin(String s) { + // Let k be the number of vowels in s. + // 1. If k == 0, Bob wins since Alice has no vowels to pick. + // 2. If k % 2 == 1, Alice wins since Alice can pick the entire string. + // 3. If k % 2 == 0, Alice wins since Alice can pick (k - 1) vowels, + // then Bob will either pick a substring containing 0 vowels, resulting in + // Alice picking the remaining entire string, or Bob couldn't pick at all + // (the last vowel). + return s.chars().anyMatch(c -> isVowel((char) c)); + } + + private boolean isVowel(char c) { + return "aeiou".indexOf(Character.toLowerCase(c)) != -1; + } +} diff --git a/solutions/3227. Vowels Game in a String/3227.py b/solutions/3227. Vowels Game in a String/3227.py new file mode 100644 index 00000000000..76916be4eb7 --- /dev/null +++ b/solutions/3227. Vowels Game in a String/3227.py @@ -0,0 +1,11 @@ +class Solution: + def doesAliceWin(self, s: str) -> bool: + # Let k be the number of vowels in s. + # 1. If k == 0, Bob wins since Alice has no vowels to pick. + # 2. If k % 2 == 1, Alice wins since Alice can pick the entire string. + # 3. If k % 2 == 0, Alice wins since Alice can pick (k - 1) vowels, + # then Bob will either pick a substring containing 0 vowels, resulting in + # Alice picking the remaining entire string, or Bob couldn't pick at all + # (the last vowel). + kVowels = 'aeiou' + return any(c in kVowels for c in s) diff --git a/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.cpp b/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.cpp new file mode 100644 index 00000000000..ca4d71e7aa8 --- /dev/null +++ b/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxOperations(string s) { + int ans = 0; + int ones = 0; + + for (int i = 0; i < s.length(); ++i) + if (s[i] == '1') + ++ones; + else if (i + 1 == s.length() || s[i + 1] == '1') + ans += ones; + + return ans; + } +}; diff --git a/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.java b/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.java new file mode 100644 index 00000000000..6374bf543c1 --- /dev/null +++ b/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.java @@ -0,0 +1,14 @@ +class Solution { + public int maxOperations(String s) { + int ans = 0; + int ones = 0; + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) == '1') + ++ones; + else if (i == s.length() - 1 || s.charAt(i + 1) == '1') + ans += ones; + + return ans; + } +} diff --git a/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.py b/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.py new file mode 100644 index 00000000000..546db11a8cf --- /dev/null +++ b/solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.py @@ -0,0 +1,12 @@ +class Solution: + def maxOperations(self, s: str) -> int: + ans = 0 + ones = 0 + + for i, c in enumerate(s): + if c == '1': + ones += 1 + elif i + 1 == len(s) or s[i + 1] == '1': + ans += ones + + return ans diff --git a/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.cpp b/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.cpp new file mode 100644 index 00000000000..dc6da022b79 --- /dev/null +++ b/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + // Similar to 1526. Minimum Number of Increments on Subarrays to Form a Target + // Array + long long minimumOperations(vector& nums, vector& target) { + long ans = abs(nums[0] - target[0]); + + for (int i = 1; i < nums.size(); ++i) { + const int currDiff = target[i] - nums[i]; + const int prevDiff = target[i - 1] - nums[i - 1]; + if (currDiff >= 0 && prevDiff >= 0) + ans += max(0, currDiff - prevDiff); + else if (currDiff <= 0 && prevDiff <= 0) + ans += max(0, abs(currDiff) - abs(prevDiff)); + else + ans += abs(currDiff); + } + + return ans; + } +}; diff --git a/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.java b/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.java new file mode 100644 index 00000000000..7b79ebc5621 --- /dev/null +++ b/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.java @@ -0,0 +1,19 @@ +class Solution { + // Similar to 1526. Minimum Number of Increments on Subarrays to Form a Target Array + public long minimumOperations(int[] nums, int[] target) { + long ans = Math.abs((long) nums[0] - target[0]); + + for (int i = 1; i < nums.length; ++i) { + final int currDiff = target[i] - nums[i]; + final int prevDiff = target[i - 1] - nums[i - 1]; + if (currDiff >= 0 && prevDiff >= 0) + ans += Math.max(0, currDiff - prevDiff); + else if (currDiff <= 0 && prevDiff <= 0) + ans += Math.max(0, Math.abs((long) currDiff) - Math.abs((long) prevDiff)); + else + ans += Math.abs((long) currDiff); + } + + return ans; + } +} diff --git a/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.py b/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.py new file mode 100644 index 00000000000..42624a2c638 --- /dev/null +++ b/solutions/3229. Minimum Operations to Make Array Equal to Target/3229.py @@ -0,0 +1,17 @@ +class Solution: + # Similar to 1526. Minimum Number of Increments on Subarrays to Form a Target Array + def minimumOperations(self, nums: List[int], target: List[int]) -> int: + ans = abs(nums[0] - target[0]) + + for (prevNum, prevTarget), (currNum, currTarget) in \ + itertools.pairwise(zip(nums, target)): + currDiff = currTarget - currNum + prevDiff = prevTarget - prevNum + if currDiff >= 0 and prevDiff >= 0: + ans += max(0, currDiff - prevDiff) + elif currDiff <= 0 and prevDiff <= 0: + ans += max(0, abs(currDiff) - abs(prevDiff)) + else: + ans += abs(currDiff) + + return ans diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323-2.cpp b/solutions/323. Number of Connected Components in an Undirected Graph/323-2.cpp new file mode 100644 index 00000000000..b0ed4dcb62b --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int countComponents(int n, vector>& edges) { + int ans = 0; + vector> graph(n); + unordered_set seen; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + for (int i = 0; i < n; ++i) + if (seen.insert(i).second) { + dfs(graph, i, seen); + ++ans; + } + + return ans; + } + + private: + void dfs(const vector>& graph, int u, unordered_set& seen) { + for (const int v : graph[u]) + if (seen.insert(v).second) + dfs(graph, v, seen); + } +}; diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323-2.java b/solutions/323. Number of Connected Components in an Undirected Graph/323-2.java new file mode 100644 index 00000000000..8f512afaac3 --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323-2.java @@ -0,0 +1,31 @@ +class Solution { + public int countComponents(int n, int[][] edges) { + int ans = 0; + List[] graph = new List[n]; + Set seen = new HashSet<>(); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + for (int i = 0; i < n; ++i) + if (seen.add(i)) { + dfs(graph, i, seen); + ++ans; + } + + return ans; + } + + private void dfs(List[] graph, int u, Set seen) { + for (final int v : graph[u]) + if (seen.add(v)) + dfs(graph, v, seen); + } +} diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323-2.py b/solutions/323. Number of Connected Components in an Undirected Graph/323-2.py new file mode 100644 index 00000000000..7b19ca479f3 --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323-2.py @@ -0,0 +1,23 @@ +class Solution: + def countComponents(self, n: int, edges: List[List[int]]) -> int: + ans = 0 + graph = [[] for _ in range(n)] + seen = set() + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + def dfs(u: int, seen: Set[int]) -> None: + for v in graph[u]: + if v not in seen: + seen.add(v) + dfs(v, seen) + + for i in range(n): + if i not in seen: + seen.add(i) + dfs(graph, i, seen) + ans += 1 + + return ans diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323-3.cpp b/solutions/323. Number of Connected Components in an Undirected Graph/323-3.cpp new file mode 100644 index 00000000000..12cd1065dbf --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323-3.cpp @@ -0,0 +1,50 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + int countComponents(int n, vector>& edges) { + UnionFind uf(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + uf.unionByRank(u, v); + } + + return uf.getCount(); + } +}; diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323-3.java b/solutions/323. Number of Connected Components in an Undirected Graph/323-3.java new file mode 100644 index 00000000000..904f9eabd90 --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323-3.java @@ -0,0 +1,51 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + public int getCount() { + return count; + } + + private int count; + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int countComponents(int n, int[][] edges) { + UnionFind uf = new UnionFind(n); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + uf.unionByRank(u, v); + } + + return uf.getCount(); + } +} diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323-3.py b/solutions/323. Number of Connected Components in an Undirected Graph/323-3.py new file mode 100644 index 00000000000..a62fcd370ca --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323-3.py @@ -0,0 +1,34 @@ +class UnionFind: + def __init__(self, n: int): + self.count = n + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self._find(u) + j = self._find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + self.count -= 1 + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def countComponents(self, n: int, edges: List[List[int]]) -> int: + uf = UnionFind(n) + + for u, v in edges: + uf.unionByRank(u, v) + + return uf.count diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323.cpp b/solutions/323. Number of Connected Components in an Undirected Graph/323.cpp new file mode 100644 index 00000000000..b2d59578bb7 --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int countComponents(int n, vector>& edges) { + int ans = 0; + vector> graph(n); + unordered_set seen; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + for (int i = 0; i < n; ++i) + if (!seen.contains(i)) { + bfs(graph, i, seen); + ++ans; + } + + return ans; + } + + private: + void bfs(const vector>& graph, int node, + unordered_set& seen) { + queue q{{node}}; + seen.insert(node); + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) + if (!seen.contains(v)) { + q.push(v); + seen.insert(v); + } + } + } +}; diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323.java b/solutions/323. Number of Connected Components in an Undirected Graph/323.java new file mode 100644 index 00000000000..4d1928c44b1 --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323.java @@ -0,0 +1,39 @@ +class Solution { + public int countComponents(int n, int[][] edges) { + int ans = 0; + List[] graph = new List[n]; + Set seen = new HashSet<>(); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + for (int i = 0; i < n; ++i) + if (!seen.contains(i)) { + bfs(graph, i, seen); + ++ans; + } + + return ans; + } + + private void bfs(List[] graph, int node, Set seen) { + Queue q = new ArrayDeque<>(Arrays.asList(node)); + seen.add(node); + + while (!q.isEmpty()) { + final int u = q.poll(); + for (final int v : graph[u]) + if (!seen.contains(v)) { + q.offer(v); + seen.add(v); + } + } + } +} diff --git a/solutions/323. Number of Connected Components in an Undirected Graph/323.py b/solutions/323. Number of Connected Components in an Undirected Graph/323.py new file mode 100644 index 00000000000..34bd6895bca --- /dev/null +++ b/solutions/323. Number of Connected Components in an Undirected Graph/323.py @@ -0,0 +1,27 @@ +class Solution: + def countComponents(self, n: int, edges: List[List[int]]) -> int: + ans = 0 + graph = [[] for _ in range(n)] + seen = set() + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + def bfs(node: int, seen: Set[int]) -> None: + q = collections.deque([node]) + seen.add(node) + + while q: + u = q.pop() + for v in graph[u]: + if v not in seen: + q.append(v) + seen.add(v) + + for i in range(n): + if i not in seen: + bfs(i, seen) + ans += 1 + + return ans diff --git a/solutions/3230. Customer Purchasing Behavior Analysis/3230.sql b/solutions/3230. Customer Purchasing Behavior Analysis/3230.sql new file mode 100644 index 00000000000..6c2a3eb18bf --- /dev/null +++ b/solutions/3230. Customer Purchasing Behavior Analysis/3230.sql @@ -0,0 +1,36 @@ +WITH + RankedCategoriesPerCustomer AS ( + SELECT + Transactions.customer_id, + Products.category, + RANK() OVER( + PARTITION BY Transactions.customer_id + ORDER BY COUNT(Products.category) DESC, + MAX(Transactions.transaction_date) DESC + ) AS `rank` + FROM Transactions + INNER JOIN Products + USING (product_id) + GROUP BY 1, 2 + ), + TransactionsMetadata AS ( + SELECT + Transactions.customer_id, + ROUND(SUM(Transactions.amount), 2) AS total_amount, + COUNT(Transactions.transaction_id) AS transaction_count, + COUNT(DISTINCT Products.category) AS unique_categories, + ROUND(AVG(Transactions.amount), 2) AS avg_transaction_amount, + RankedCategoriesPerCustomer.category AS top_category + FROM Transactions + INNER JOIN Products + USING (product_id) + INNER JOIN RankedCategoriesPerCustomer + USING (customer_id) + WHERE RankedCategoriesPerCustomer.`rank` = 1 + GROUP BY 1 + ) +SELECT + *, + ROUND(transaction_count * 10 + total_amount / 100, 2) AS loyalty_score +FROM TransactionsMetadata +ORDER BY loyalty_score DESC, customer_id; diff --git a/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.cpp b/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.cpp new file mode 100644 index 00000000000..06bc63f92f4 --- /dev/null +++ b/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int minOperations(vector& nums) { + // The length of the longest non-increasing subsequence is equal to the + // number of strictly increasing subsequences needed to cover the entire + // array. This is because any number in the non-increasing subsequence must + // use one number from each of the strictly increasing subsequences. e.g., + // [4, 3, 1, 2] has 3 strictly increasing subsequences: [4], [3], and [1, + // 2]. The longest non-increasing subsequences are [4, 3, 1] or [4, 3, 2]. + return lengthOfLIS({nums.rbegin(), nums.rend()}); + } + + private: + // Similar to 300. Longest Increasing Subsequence + int lengthOfLIS(const vector& nums) { + // tails[i] := the minimum tail of all the non-decreasing subsequences + // having length i + 1 + vector tails; + + for (const int num : nums) + if (tails.empty() || num >= tails.back()) + tails.push_back(num); + else + tails[firstGreater(tails, num)] = num; + + return tails.size(); + } + + private: + int firstGreater(const vector& A, int target) { + return ranges::upper_bound(A, target) - A.begin(); + } +}; diff --git a/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.java b/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.java new file mode 100644 index 00000000000..6d90860cf95 --- /dev/null +++ b/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.java @@ -0,0 +1,42 @@ +class Solution { + public int minOperations(int[] nums) { + // The length of the longest non-increasing subsequence is equal to the + // number of strictly increasing subsequences needed to cover the entire + // array. This is because any number in the non-increasing subsequence must + // use one number from each of the strictly increasing subsequences. e.g., + // [4, 3, 1, 2] has 3 strictly increasing subsequences: [4], [3], and [1, + // 2]. The longest non-increasing subsequences are [4, 3, 1] or [4, 3, 2]. + int[] reversedNums = new int[nums.length]; + for (int i = 0; i < nums.length; ++i) + reversedNums[i] = nums[nums.length - 1 - i]; + return lengthOfLIS(reversedNums); + } + + // Similar to 300. Longest Increasing Subsequence + private int lengthOfLIS(int[] nums) { + // tails[i] := the minimum tail of all the increasing subsequences having + // length i + 1 + List tails = new ArrayList<>(); + + for (final int num : nums) + if (tails.isEmpty() || num >= tails.get(tails.size() - 1)) + tails.add(num); + else + tails.set(firstGreater(tails, num), num); + + return tails.size(); + } + + private int firstGreater(List A, int target) { + int l = 0; + int r = A.size(); + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m) > target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.py b/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.py new file mode 100644 index 00000000000..c1f4981e1ac --- /dev/null +++ b/solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.py @@ -0,0 +1,14 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + return self._lengthOfLIS(nums[::-1]) + + def _lengthOfLIS(self, nums: List[int]) -> int: + # tails[i] := the minimum tail of all the increasing subsequences having + # length i + 1 + tails = [] + for num in nums: + if not tails or num >= tails[-1]: + tails.append(num) + else: + tails[bisect.bisect_right(tails, num)] = num + return len(tails) diff --git a/solutions/3232. Find if Digit Game Can Be Won/3232.cpp b/solutions/3232. Find if Digit Game Can Be Won/3232.cpp new file mode 100644 index 00000000000..2fa071a8a45 --- /dev/null +++ b/solutions/3232. Find if Digit Game Can Be Won/3232.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + bool canAliceWin(vector& nums) { + return accumulate(nums.begin(), nums.end(), 0, [](int subtotal, int num) { + return subtotal + (num < 10 ? num : -num); + }) != 0; + } +}; diff --git a/solutions/3232. Find if Digit Game Can Be Won/3232.java b/solutions/3232. Find if Digit Game Can Be Won/3232.java new file mode 100644 index 00000000000..057f2c267b2 --- /dev/null +++ b/solutions/3232. Find if Digit Game Can Be Won/3232.java @@ -0,0 +1,5 @@ +class Solution { + public boolean canAliceWin(int[] nums) { + return Arrays.stream(nums).map(num -> num < 10 ? num : -num).sum() != 0; + } +} diff --git a/solutions/3232. Find if Digit Game Can Be Won/3232.py b/solutions/3232. Find if Digit Game Can Be Won/3232.py new file mode 100644 index 00000000000..64fabd6c465 --- /dev/null +++ b/solutions/3232. Find if Digit Game Can Be Won/3232.py @@ -0,0 +1,3 @@ +class Solution: + def canAliceWin(self, nums: List[int]) -> bool: + return sum(num if num < 10 else -num for num in nums) != 0 diff --git a/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.cpp b/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.cpp new file mode 100644 index 00000000000..36eff98b613 --- /dev/null +++ b/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int nonSpecialCount(int l, int r) { + const int maxRoot = sqrt(r); + const vector isPrime = sieveEratosthenes(maxRoot + 1); + int specialCount = 0; + + for (int num = 2; num <= sqrt(r); ++num) + if (isPrime[num] && l <= num * num && num * num <= r) + ++specialCount; + + return r - l + 1 - specialCount; + } + + private: + vector sieveEratosthenes(int n) { + vector isPrime(n, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +}; diff --git a/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.java b/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.java new file mode 100644 index 00000000000..1a3c9ada65c --- /dev/null +++ b/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.java @@ -0,0 +1,25 @@ +class Solution { + public int nonSpecialCount(int l, int r) { + final int maxRoot = (int) Math.sqrt(r); + final boolean[] isPrime = sieveEratosthenes(maxRoot + 1); + int specialCount = 0; + + for (int num = 2; num <= Math.sqrt(r); ++num) + if (isPrime[num] && l <= num * num && num * num <= r) + ++specialCount; + + return r - l + 1 - specialCount; + } + + private boolean[] sieveEratosthenes(int n) { + boolean[] isPrime = new boolean[n]; + Arrays.fill(isPrime, true); + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i < n; ++i) + if (isPrime[i]) + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + return isPrime; + } +} diff --git a/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.py b/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.py new file mode 100644 index 00000000000..8ec4189da69 --- /dev/null +++ b/solutions/3233. Find the Count of Numbers Which Are Not Special/3233.py @@ -0,0 +1,21 @@ +class Solution: + def nonSpecialCount(self, l: int, r: int) -> int: + maxRoot = math.isqrt(r) + isPrime = self._sieveEratosthenes(maxRoot + 1) + specialCount = 0 + + for num in range(2, math.isqrt(r) + 1): + if isPrime[num] and l <= num**2 <= r: + specialCount += 1 + + return r - l + 1 - specialCount + + def _sieveEratosthenes(self, n: int) -> List[bool]: + isPrime = [True] * n + isPrime[0] = False + isPrime[1] = False + for i in range(2, int(n**0.5) + 1): + if isPrime[i]: + for j in range(i * i, n, i): + isPrime[j] = False + return isPrime diff --git a/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.cpp b/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.cpp new file mode 100644 index 00000000000..11c2b017219 --- /dev/null +++ b/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int numberOfSubstrings(string s) { + int ans = 0; + + // Iterate through all possible number of 0s. + for (int zero = 0; zero + zero * zero <= s.length(); ++zero) { + int lastInvalidPos = -1; + vector count(2); + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s[r] - '0']; + // Try to shrink the window to maintain the "minimum" length of the + // valid substring. + for (; l < r; ++l) + if (s[l] == '0' && count[0] > zero) { + --count[0]; // Remove an extra '0'. + lastInvalidPos = l; + } else if (s[l] == '1' && count[1] - 1 >= zero * zero) { + --count[1]; // Remove an extra '1'. + } else { + break; // Cannot remove more characters. + } + if (count[0] == zero && count[1] >= zero * zero) + // Add the valid substrings ending in s[r] to the answer. They are + // s[lastInvalidPos + 1..r], s[lastInvalidPos + 2..r], ..., s[l..r]. + ans += l - lastInvalidPos; + } + } + + return ans; + } +}; diff --git a/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.java b/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.java new file mode 100644 index 00000000000..693f75da1a5 --- /dev/null +++ b/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.java @@ -0,0 +1,31 @@ +class Solution { + public int numberOfSubstrings(String s) { + int ans = 0; + + // Iterate through all possible number of 0s. + for (int zero = 0; zero + zero * zero <= s.length(); ++zero) { + int lastInvalidPos = -1; + int[] count = new int[2]; + for (int l = 0, r = 0; r < s.length(); ++r) { + ++count[s.charAt(r) - '0']; + // Try to shrink the window to maintain the "minimum" length of the + // valid substring. + for (; l < r; ++l) + if (s.charAt(l) == '0' && count[0] > zero) { + --count[0]; // Remove an extra '0'. + lastInvalidPos = l; + } else if (s.charAt(l) == '1' && count[1] - 1 >= zero * zero) { + --count[1]; // Remove an extra '1'. + } else { + break; // Cannot remove more characters. + } + if (count[0] == zero && count[1] >= zero * zero) + // Add the valid substrings ending in s[r] to the answer. They are + // s[lastInvalidPos + 1..r], s[lastInvalidPos + 2..r], ..., s[l..r]. + ans += l - lastInvalidPos; + } + } + + return ans; + } +} diff --git a/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.py b/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.py new file mode 100644 index 00000000000..60f4452be6a --- /dev/null +++ b/solutions/3234. Count the Number of Substrings With Dominant Ones/3234.py @@ -0,0 +1,33 @@ +class Solution: + def numberOfSubstrings(self, s: str) -> int: + ans = 0 + # z^2 + z = n. + # => z^2 + z - n = 0. + # => z = (-1 + sqrt(1 + 4n)) / 2. + maxZero = (-1 + math.sqrt(1 + 4 * len(s))) // 2 + + # Iterate through all possible number of 0s. + for zero in range(int(maxZero) + 1): + lastInvalidPos = -1 + count = [0, 0] + l = 0 + for r, c in enumerate(s): + count[ord(c) - ord('0')] += 1 + # Try to shrink the window to maintain the "minimum" length of the + # valid substring. + while l < r: + if s[l] == '0' and count[0] > zero: + count[0] -= 1 # Remove an extra '0'. + lastInvalidPos = l + l += 1 + elif s[l] == '1' and count[1] - 1 >= zero * zero: + count[1] -= 1 # Remove an extra '1'. + l += 1 + else: + break # Cannot remove more characters. + if count[0] == zero and count[1] >= zero * zero: + # Add the valid substrings ending in s[r] to the answer. They are + # s[lastInvalidPos + 1..r], s[lastInvalidPos + 2..r], ..., s[l..r]. + ans += l - lastInvalidPos + + return ans diff --git a/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.cpp b/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.cpp new file mode 100644 index 00000000000..ab13e245809 --- /dev/null +++ b/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.cpp @@ -0,0 +1,69 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + bool canReachCorner(int X, int Y, vector>& circles) { + const int n = circles.size(); + // Add two virtual nodes, where node n represents (0, 0) and node n + 1 + // represents (X, Y). + UnionFind uf(n + 2); + + // Iterate through each circle. + for (int i = 0; i < n; ++i) { + const int x = circles[i][0]; + const int y = circles[i][1]; + const int r = circles[i][2]; + // Union the current circle with the node (0, 0) if the circle overlaps + // with the left or top edges. + if (x - r <= 0 || y + r >= Y) + uf.unionByRank(i, n); + // Union the current circle with the node (X, Y) if the circle overlaps + // with the right or bottom edges. + if (x + r >= X || y - r <= 0) + uf.unionByRank(i, n + 1); + // Union the current circle with previous circles if they overlap. + for (int j = 0; j < i; ++j) { + const int x2 = circles[j][0]; + const int y2 = circles[j][1]; + const int r2 = circles[j][2]; + if (static_cast(x - x2) * (x - x2) + + static_cast(y - y2) * (y - y2) <= + static_cast(r + r2) * (r + r2)) + uf.unionByRank(i, j); + } + } + + // If nodes (0, 0) and (X, Y) are in the same union set, that means there's + // a path of overlapping circles that connects the left or top edges to the + // right or bottom edges, implying that (0, 0) cannot reach (X, Y). + return uf.find(n) != uf.find(n + 1); + } +}; diff --git a/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.java b/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.java new file mode 100644 index 00000000000..1010641667d --- /dev/null +++ b/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.java @@ -0,0 +1,67 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public boolean canReachCorner(int X, int Y, int[][] circles) { + final int n = circles.length; + // Add two virtual nodes, where node n represents (0, 0) and node n + 1 + // represents (X, Y). + UnionFind uf = new UnionFind(n + 2); + + // Iterate through each circle. + for (int i = 0; i < n; ++i) { + final int x = circles[i][0]; + final int y = circles[i][1]; + final int r = circles[i][2]; + // Union the current circle with the node (0, 0) if the circle overlaps + // with the left or top edges. + if (x - r <= 0 || y + r >= Y) + uf.unionByRank(i, n); + // Union the current circle with the node (X, Y) if the circle overlaps + // with the right or bottom edges. + if (x + r >= X || y - r <= 0) + uf.unionByRank(i, n + 1); + // Union the current circle with previous circles if they overlap. + for (int j = 0; j < i; j++) { + final int x2 = circles[j][0]; + final int y2 = circles[j][1]; + final int r2 = circles[j][2]; + if ((long) (x - x2) * (x - x2) + (long) (y - y2) * (y - y2) <= (long) (r + r2) * (r + r2)) + uf.unionByRank(i, j); + } + } + + // If nodes (0, 0) and (X, Y) are in the same union set, that means there's + // a path of overlapping circles that connects the left or top edges to the + // right or bottom edges, implying that (0, 0) cannot reach (X, Y). + return uf.find(n) != uf.find(n + 1); + } +} diff --git a/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.py b/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.py new file mode 100644 index 00000000000..5748845bcb7 --- /dev/null +++ b/solutions/3235. Check if the Rectangle Corner Is Reachable/3235.py @@ -0,0 +1,51 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def canReachCorner(self, X: int, Y: int, circles: List[List[int]]) -> bool: + n = len(circles) + # Add two virtual nodes, where node n represents (0, 0) and node n + 1 + # represents (X, Y). + uf = UnionFind(n + 2) + + # Iterate through each circle. + for i, (x, y, r) in enumerate(circles): + # Union the current circle with the node (0, 0) if the circle overlaps + # with the left or top edges. + if x - r <= 0 or y + r >= Y: + uf.unionByRank(i, n) + # Union the current circle with the node (X, Y) if the circle overlaps + # with the right or bottom edges. + if x + r >= X or y - r <= 0: + uf.unionByRank(i, n + 1) + # Union the current circle with previous circles if they overlap. + for j in range(i): + x2, y2, r2 = circles[j] + if (x - x2)**2 + (y - y2)**2 <= (r + r2)**2: + uf.unionByRank(i, j) + + # If nodes (0, 0) and (X, Y) are in the same union set, that means there's + # a path of overlapping circles that connects the left or top edges to the + # right or bottom edges, implying that (0, 0) cannot reach (X, Y). + return uf.find(n) != uf.find(n + 1) diff --git a/solutions/3236. CEO Subordinate Hierarchy/3236.sql b/solutions/3236. CEO Subordinate Hierarchy/3236.sql new file mode 100644 index 00000000000..ade7b4e8e99 --- /dev/null +++ b/solutions/3236. CEO Subordinate Hierarchy/3236.sql @@ -0,0 +1,38 @@ +WITH + RECURSIVE EmployeeHierarchy AS ( + -- Base case: direct reports to CEO + SELECT + employee_id, + employee_name, + salary, + 1 AS hierarchy_level + FROM Employees + WHERE manager_id = ( + SELECT employee_id + FROM Employees + WHERE manager_id IS NULL + ) + UNION ALL + -- Recursive case: reports of reports + SELECT + Employees.employee_id, + Employees.employee_name, + Employees.salary, + EmployeeHierarchy.hierarchy_level + 1 + FROM Employees + INNER JOIN EmployeeHierarchy + ON (Employees.manager_id = EmployeeHierarchy.employee_id) + ), + Ceo AS ( + SELECT salary + FROM Employees + WHERE manager_id IS NULL + ) +SELECT + EmployeeHierarchy.employee_id AS subordinate_id, + EmployeeHierarchy.employee_name AS subordinate_name, + EmployeeHierarchy.hierarchy_level, + EmployeeHierarchy.salary - Ceo.salary AS salary_difference +FROM EmployeeHierarchy +CROSS JOIN Ceo +ORDER BY hierarchy_level, employee_id; diff --git a/solutions/3237. Alt and Tab Simulation/3237.cpp b/solutions/3237. Alt and Tab Simulation/3237.cpp new file mode 100644 index 00000000000..eeed1f16acf --- /dev/null +++ b/solutions/3237. Alt and Tab Simulation/3237.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector simulationResult(vector& windows, vector& queries) { + vector ans; + unordered_set seen; + + for (int i = queries.size() - 1; i >= 0; --i) + if (!seen.contains(queries[i])) { + ans.push_back(queries[i]); + seen.insert(queries[i]); + } + + for (const int window : windows) + if (!seen.contains(window)) { + ans.push_back(window); + seen.insert(window); + } + + return ans; + } +}; diff --git a/solutions/3237. Alt and Tab Simulation/3237.java b/solutions/3237. Alt and Tab Simulation/3237.java new file mode 100644 index 00000000000..f6734242ed3 --- /dev/null +++ b/solutions/3237. Alt and Tab Simulation/3237.java @@ -0,0 +1,21 @@ +class Solution { + public int[] simulationResult(int[] windows, int[] queries) { + int[] ans = new int[windows.length]; + int ansIndex = 0; + Set seen = new HashSet<>(); + + for (int i = queries.length - 1; i >= 0; --i) + if (!seen.contains(queries[i])) { + ans[ansIndex++] = queries[i]; + seen.add(queries[i]); + } + + for (final int window : windows) + if (!seen.contains(window)) { + ans[ansIndex++] = window; + seen.add(window); + } + + return ans; + } +} diff --git a/solutions/3237. Alt and Tab Simulation/3237.py b/solutions/3237. Alt and Tab Simulation/3237.py new file mode 100644 index 00000000000..5bd0d16a11e --- /dev/null +++ b/solutions/3237. Alt and Tab Simulation/3237.py @@ -0,0 +1,16 @@ +class Solution: + def simulationResult(self, windows: List[int], queries: List[int]) -> List[int]: + ans = [] + seen = set() + + for query in reversed(queries): + if query not in seen: + ans.append(query) + seen.add(query) + + for window in windows: + if window not in seen: + ans.append(window) + seen.add(window) + + return ans diff --git a/solutions/324. Wiggle Sort II/324.cpp b/solutions/324. Wiggle Sort II/324.cpp new file mode 100644 index 00000000000..8d26333a907 --- /dev/null +++ b/solutions/324. Wiggle Sort II/324.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + void wiggleSort(vector& nums) { + const int n = nums.size(); + const auto it = nums.begin() + n / 2; + nth_element(nums.begin(), it, nums.end()); + const int median = *it; + +// index-rewiring +#define A(i) nums[(1 + 2 * i) % (n | 1)] + + for (int i = 0, j = 0, k = n - 1; i <= k;) + if (A(i) > median) + swap(A(i++), A(j++)); + else if (A(i) < median) + swap(A(i), A(k--)); + else + ++i; + } +}; diff --git a/solutions/324. Wiggle Sort II/324.java b/solutions/324. Wiggle Sort II/324.java new file mode 100644 index 00000000000..16940518021 --- /dev/null +++ b/solutions/324. Wiggle Sort II/324.java @@ -0,0 +1,45 @@ +class Solution { + public void wiggleSort(int[] nums) { + final int n = nums.length; + final int median = findKthLargest(nums, (n + 1) / 2); + for (int i = 0, j = 0, k = n - 1; i <= k;) + if (nums[A(i, n)] > median) + swap(nums, A(i++, n), A(j++, n)); + else if (nums[A(i, n)] < median) + swap(nums, A(i, n), A(k--, n)); + else + ++i; + } + + private int A(int i, int n) { + return (1 + 2 * i) % (n | 1); + } + + // Same as 215. Kth Largest Element in an Array + private int findKthLargest(int[] nums, int k) { + return quickSelect(nums, 0, nums.length - 1, k); + } + + private int quickSelect(int[] nums, int l, int r, int k) { + final int pivot = nums[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (nums[i] >= pivot) + swap(nums, nextSwapped++, i); + swap(nums, nextSwapped, r); + + final int count = nextSwapped - l + 1; // the number of `nums` >= pivot + if (count == k) + return nums[nextSwapped]; + if (count > k) + return quickSelect(nums, l, nextSwapped - 1, k); + return quickSelect(nums, nextSwapped + 1, r, k - count); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/324. Wiggle Sort II/324.py b/solutions/324. Wiggle Sort II/324.py new file mode 100644 index 00000000000..b39588340aa --- /dev/null +++ b/solutions/324. Wiggle Sort II/324.py @@ -0,0 +1,44 @@ +class Solution: + def wiggleSort(self, nums: List[int]) -> None: + n = len(nums) + median = self._findKthLargest(nums, (n + 1) // 2) + + def A(i: int): + return (1 + 2 * i) % (n | 1) + + i = 0 + j = 0 + k = n - 1 + + while i <= k: + if nums[A(i)] > median: + nums[A(i)], nums[A(j)] = nums[A(j)], nums[A(i)] + i, j = i + 1, j + 1 + elif nums[A(i)] < median: + nums[A(i)], nums[A(k)] = nums[A(k)], nums[A(i)] + k -= 1 + else: + i += 1 + + # Same as 215. Kth Largest Element in an Array + def _findKthLargest(self, nums: List[int], k: int) -> int: + def quickSelect(l: int, r: int, k: int) -> int: + randIndex = random.randint(0, r - l) + l + nums[randIndex], nums[r] = nums[r], nums[randIndex] + pivot = nums[r] + + nextSwapped = l + for i in range(l, r): + if nums[i] >= pivot: + nums[nextSwapped], nums[i] = nums[i], nums[nextSwapped] + nextSwapped += 1 + nums[nextSwapped], nums[r] = nums[r], nums[nextSwapped] + + count = nextSwapped - l + 1 # Number of nums >= pivot + if count == k: + return nums[nextSwapped] + if count > k: + return quickSelect(l, nextSwapped - 1, k) + return quickSelect(nextSwapped + 1, r, k - count) + + return quickSelect(0, len(nums) - 1, k) diff --git a/solutions/3241. Time Taken to Mark All Nodes/3241.py b/solutions/3241. Time Taken to Mark All Nodes/3241.py new file mode 100644 index 00000000000..b77da68475f --- /dev/null +++ b/solutions/3241. Time Taken to Mark All Nodes/3241.py @@ -0,0 +1,72 @@ +class T: + def __init__(self, node: int = -1, time: int = 0): + self.node = node # the node number + self.time = time # the time taken to reach this node + + +class Top2: + def __init__(self, max1: T = T(-1, 0), max2: T = T(-1, 0)): + self.max1 = max1 # the node with the maximum time + self.max2 = max2 # the node with the second maximum time + + +class Solution: + def timeTaken(self, edges: List[List[int]]) -> List[int]: + n = len(edges) + 1 + ans = [0] * n + graph = [[] for _ in range(n)] + + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + # dp[i] := the top two nodes with maximum times to mark all nodes in the + # subtree rooted at node i + dp = [Top2()] * n + + def getTime(u: int) -> int: + """Returns the time taken to mark node u.""" + return 2 if u % 2 == 0 else 1 + + def dfs(u: int, prev: int) -> int: + """ + Performs a DFS traversal of the tree, computing the maximum time to mark + all nodes in the subtree rooted at node u. + + This function calculates and stores the top two maximum times for each + node's subtree. These values are used later in the rerooting process. + """ + max1 = T() + max2 = T() + for v in graph[u]: + if v == prev: + continue + time = dfs(v, u) + getTime(v) + if time >= max1.time: + max2 = max1 + max1 = T(v, time) + elif time > max2.time: + max2 = T(v, time) + dp[u] = Top2(max1, max2) + return max1.time + + dfs(0, -1) + + def reroot(u: int, prev: int, maxTime) -> None: + """ + Reroots the tree at node `u` and updates the answer array, where `maxTime` + is the longest path that doesn't go through `u`'s subtree. + """ + ans[u] = max(maxTime, dp[u].max1.time) + + for v in graph[u]: + if v == prev: + continue + newMaxTime = getTime(u) + max( + maxTime, + dp[u].max2.time if dp[u].max1.node == v else dp[u].max1.time + ) + reroot(v, u, newMaxTime) + + reroot(0, -1, 0) + return ans diff --git a/solutions/325. Maximum Size Subarray Sum Equals k/325.cpp b/solutions/325. Maximum Size Subarray Sum Equals k/325.cpp new file mode 100644 index 00000000000..78f46d5a8d8 --- /dev/null +++ b/solutions/325. Maximum Size Subarray Sum Equals k/325.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxSubArrayLen(vector& nums, int k) { + int ans = 0; + int prefix = 0; + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i]; + const int target = prefix - k; + if (const auto it = prefixToIndex.find(target); + it != prefixToIndex.cend()) + ans = max(ans, i - it->second); + if (!prefixToIndex.contains(prefix)) + prefixToIndex[prefix] = i; + } + + return ans; + } +}; diff --git a/solutions/325. Maximum Size Subarray Sum Equals k/325.java b/solutions/325. Maximum Size Subarray Sum Equals k/325.java new file mode 100644 index 00000000000..52dd4df1696 --- /dev/null +++ b/solutions/325. Maximum Size Subarray Sum Equals k/325.java @@ -0,0 +1,18 @@ +class Solution { + public int maxSubArrayLen(int[] nums, int k) { + int ans = 0; + int prefix = 0; + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i]; + final int target = prefix - k; + if (prefixToIndex.containsKey(target)) + ans = Math.max(ans, i - prefixToIndex.get(target)); + prefixToIndex.putIfAbsent(prefix, i); + } + + return ans; + } +} diff --git a/solutions/325. Maximum Size Subarray Sum Equals k/325.py b/solutions/325. Maximum Size Subarray Sum Equals k/325.py new file mode 100644 index 00000000000..5d46b6db47e --- /dev/null +++ b/solutions/325. Maximum Size Subarray Sum Equals k/325.py @@ -0,0 +1,15 @@ +class Solution: + def maxSubArrayLen(self, nums: List[int], k: int) -> int: + ans = 0 + prefix = 0 + prefixToIndex = {0: -1} + + for i, num in enumerate(nums): + prefix += num + target = prefix - k + if target in prefixToIndex: + ans = max(ans, i - prefixToIndex[target]) + if prefix not in prefixToIndex: + prefixToIndex[prefix] = i + + return ans diff --git a/solutions/326. Power of Three/326.cpp b/solutions/326. Power of Three/326.cpp new file mode 100644 index 00000000000..c3407d851c5 --- /dev/null +++ b/solutions/326. Power of Three/326.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool isPowerOfThree(int n) { + return n > 0 && static_cast(pow(3, 19)) % n == 0; + } +}; diff --git a/solutions/326. Power of Three/326.java b/solutions/326. Power of Three/326.java new file mode 100644 index 00000000000..16bf92b7b5c --- /dev/null +++ b/solutions/326. Power of Three/326.java @@ -0,0 +1,5 @@ +class Solution { + public boolean isPowerOfThree(int n) { + return n > 0 && Math.pow(3, 19) % n == 0; + } +} diff --git a/solutions/326. Power of Three/326.py b/solutions/326. Power of Three/326.py new file mode 100644 index 00000000000..cc93a03d47c --- /dev/null +++ b/solutions/326. Power of Three/326.py @@ -0,0 +1,3 @@ +class Solution: + def isPowerOfThree(self, n: int) -> bool: + return n > 0 and 3**19 % n == 0 diff --git a/solutions/327. Count of Range Sum/327.cpp b/solutions/327. Count of Range Sum/327.cpp new file mode 100644 index 00000000000..57895a96ac2 --- /dev/null +++ b/solutions/327. Count of Range Sum/327.cpp @@ -0,0 +1,62 @@ +class Solution { + public: + int countRangeSum(vector& nums, int lower, int upper) { + const int n = nums.size(); + int ans = 0; + vector prefix{0}; + + for (int i = 0; i < n; ++i) + prefix.push_back(prefix.back() + nums[i]); + + mergeSort(prefix, 0, n, lower, upper, ans); + return ans; + } + + private: + void mergeSort(vector& prefix, int l, int r, int lower, int upper, + int& ans) { + if (l >= r) + return; + + const int m = (l + r) / 2; + mergeSort(prefix, l, m, lower, upper, ans); + mergeSort(prefix, m + 1, r, lower, upper, ans); + merge(prefix, l, m, r, lower, upper, ans); + } + + void merge(vector& prefix, int l, int m, int r, int lower, int upper, + int& ans) { + int lo = m + 1; // the first index s.t. prefix[lo] - prefix[i] >= lower + int hi = m + 1; // the first index s.t. prefix[hi] - prefix[i] > upper + + // For each index i in range [l, m], add hi - lo to `ans`. + for (int i = l; i <= m; ++i) { + while (lo <= r && prefix[lo] - prefix[i] < lower) + ++lo; + while (hi <= r && prefix[hi] - prefix[i] <= upper) + ++hi; + ans += hi - lo; + } + + vector sorted(r - l + 1); + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + + while (i <= m && j <= r) + if (prefix[i] < prefix[j]) + sorted[k++] = prefix[i++]; + else + sorted[k++] = prefix[j++]; + + // Put the possible remaining left part into the sorted array. + while (i <= m) + sorted[k++] = prefix[i++]; + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = prefix[j++]; + + copy(sorted.begin(), sorted.end(), prefix.begin() + l); + } +}; diff --git a/solutions/327. Count of Range Sum/327.java b/solutions/327. Count of Range Sum/327.java new file mode 100644 index 00000000000..8b5ecc928c1 --- /dev/null +++ b/solutions/327. Count of Range Sum/327.java @@ -0,0 +1,59 @@ +class Solution { + public int countRangeSum(int[] nums, int lower, int upper) { + final int n = nums.length; + long[] prefix = new long[n + 1]; + + for (int i = 0; i < n; ++i) + prefix[i + 1] = (long) nums[i] + prefix[i]; + + mergeSort(prefix, 0, n, lower, upper); + return ans; + } + + private int ans = 0; + + private void mergeSort(long[] prefix, int l, int r, int lower, int upper) { + if (l >= r) + return; + + final int m = (l + r) / 2; + mergeSort(prefix, l, m, lower, upper); + mergeSort(prefix, m + 1, r, lower, upper); + merge(prefix, l, m, r, lower, upper); + } + + private void merge(long[] prefix, int l, int m, int r, int lower, int upper) { + int lo = m + 1; // the first index s.t. prefix[lo] - prefix[i] >= lower + int hi = m + 1; // the first index s.t. prefix[hi] - prefix[i] > upper + + // For each index i in range [l, m], add hi - lo to `ans`. + for (int i = l; i <= m; ++i) { + while (lo <= r && prefix[lo] - prefix[i] < lower) + ++lo; + while (hi <= r && prefix[hi] - prefix[i] <= upper) + ++hi; + ans += hi - lo; + } + + long[] sorted = new long[r - l + 1]; + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + + while (i <= m && j <= r) + if (prefix[i] < prefix[j]) + sorted[k++] = prefix[i++]; + else + sorted[k++] = prefix[j++]; + + // Put the possible remaining left part into the sorted array. + while (i <= m) + sorted[k++] = prefix[i++]; + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = prefix[j++]; + + System.arraycopy(sorted, 0, prefix, l, sorted.length); + } +} diff --git a/solutions/327. Count of Range Sum/327.py b/solutions/327. Count of Range Sum/327.py new file mode 100644 index 00000000000..af73a0e3d16 --- /dev/null +++ b/solutions/327. Count of Range Sum/327.py @@ -0,0 +1,58 @@ +class Solution: + def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: + n = len(nums) + self.ans = 0 + prefix = [0] + list(itertools.accumulate(nums)) + + self._mergeSort(prefix, 0, n, lower, upper) + return self.ans + + def _mergeSort(self, prefix: List[int], l: int, r: int, lower: int, upper: int) -> None: + if l >= r: + return + + m = (l + r) // 2 + self._mergeSort(prefix, l, m, lower, upper) + self._mergeSort(prefix, m + 1, r, lower, upper) + self._merge(prefix, l, m, r, lower, upper) + + def _merge(self, prefix: List[int], l: int, m: int, r: int, lower: int, upper: int) -> None: + lo = m + 1 # the first index s.t. prefix[lo] - prefix[i] >= lower + hi = m + 1 # the first index s.t. prefix[hi] - prefix[i] > upper + + # For each index i in range [l, m], add hi - lo to `ans`. + for i in range(l, m + 1): + while lo <= r and prefix[lo] - prefix[i] < lower: + lo += 1 + while hi <= r and prefix[hi] - prefix[i] <= upper: + hi += 1 + self.ans += hi - lo + + sorted = [0] * (r - l + 1) + k = 0 # sorted's index + i = l # left's index + j = m + 1 # right's index + + while i <= m and j <= r: + if prefix[i] < prefix[j]: + sorted[k] = prefix[i] + k += 1 + i += 1 + else: + sorted[k] = prefix[j] + k += 1 + j += 1 + + # Put the possible remaining left part into the sorted array. + while i <= m: + sorted[k] = prefix[i] + k += 1 + i += 1 + + # Put the possible remaining right part into the sorted array. + while j <= r: + sorted[k] = prefix[j] + k += 1 + j += 1 + + prefix[l:l + len(sorted)] = sorted diff --git a/solutions/328. Odd Even Linked List/328.cpp b/solutions/328. Odd Even Linked List/328.cpp new file mode 100644 index 00000000000..183cbe031cf --- /dev/null +++ b/solutions/328. Odd Even Linked List/328.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + ListNode* oddEvenList(ListNode* head) { + ListNode oddHead(0); + ListNode evenHead(0); + ListNode* odd = &oddHead; + ListNode* even = &evenHead; + + for (int isOdd = 0; head; head = head->next) + if (isOdd ^= 1) { + odd->next = head; + odd = odd->next; + } else { + even->next = head; + even = even->next; + } + + odd->next = evenHead.next; + even->next = nullptr; + return oddHead.next; + } +}; diff --git a/solutions/328. Odd Even Linked List/328.java b/solutions/328. Odd Even Linked List/328.java new file mode 100644 index 00000000000..6dc532d00d9 --- /dev/null +++ b/solutions/328. Odd Even Linked List/328.java @@ -0,0 +1,21 @@ +class Solution { + public ListNode oddEvenList(ListNode head) { + ListNode oddHead = new ListNode(0); + ListNode evenHead = new ListNode(0); + ListNode odd = oddHead; + ListNode even = evenHead; + + for (boolean isOdd = true; head != null; head = head.next, isOdd = !isOdd) + if (isOdd) { + odd.next = head; + odd = odd.next; + } else { + even.next = head; + even = even.next; + } + + odd.next = evenHead.next; + even.next = null; + return oddHead.next; + } +} diff --git a/solutions/328. Odd Even Linked List/328.py b/solutions/328. Odd Even Linked List/328.py new file mode 100644 index 00000000000..26438290757 --- /dev/null +++ b/solutions/328. Odd Even Linked List/328.py @@ -0,0 +1,21 @@ +class Solution: + def oddEvenList(self, head: ListNode) -> ListNode: + oddHead = ListNode(0) + evenHead = ListNode(0) + odd = oddHead + even = evenHead + isOdd = True + + while head: + if isOdd: + odd.next = head + odd = head + else: + even.next = head + even = head + head = head.next + isOdd = not isOdd + + even.next = None + odd.next = evenHead.next + return oddHead.next diff --git a/solutions/329. Longest Increasing Path in a Matrix/329.cpp b/solutions/329. Longest Increasing Path in a Matrix/329.cpp new file mode 100644 index 00000000000..1624643609a --- /dev/null +++ b/solutions/329. Longest Increasing Path in a Matrix/329.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int longestIncreasingPath(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + int ans = 0; + vector> mem(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + ans = max(ans, dfs(matrix, i, j, INT_MIN, mem)); + + return ans; + } + + private: + // mem[i][j] := the LIP starting from matrix[i][j] + int dfs(const vector>& matrix, int i, int j, int prev, + vector>& mem) { + if (i < 0 || i == matrix.size() || j < 0 || j == matrix[0].size()) + return 0; + if (matrix[i][j] <= prev) + return 0; + int& ans = mem[i][j]; + if (ans > 0) + return ans; + + const int curr = matrix[i][j]; + return ans = 1 + max({dfs(matrix, i + 1, j, curr, mem), + dfs(matrix, i - 1, j, curr, mem), + dfs(matrix, i, j + 1, curr, mem), + dfs(matrix, i, j - 1, curr, mem)}); + } +}; diff --git a/solutions/329. Longest Increasing Path in a Matrix/329.java b/solutions/329. Longest Increasing Path in a Matrix/329.java new file mode 100644 index 00000000000..ece88629341 --- /dev/null +++ b/solutions/329. Longest Increasing Path in a Matrix/329.java @@ -0,0 +1,31 @@ +class Solution { + public int longestIncreasingPath(int[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + int ans = 0; + // mem[i][j] := the LIP starting from matrix[i][j] + int[][] mem = new int[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + ans = Math.max(ans, dfs(matrix, i, j, Integer.MIN_VALUE, mem)); + + return ans; + } + + private int dfs(int[][] matrix, int i, int j, int prev, int[][] mem) { + if (i < 0 || i == matrix.length || j < 0 || j == matrix[0].length) + return 0; + if (matrix[i][j] <= prev) + return 0; + if (mem[i][j] > 0) + return mem[i][j]; + + final int curr = matrix[i][j]; + final int a = dfs(matrix, i + 1, j, curr, mem); + final int b = dfs(matrix, i - 1, j, curr, mem); + final int c = dfs(matrix, i, j + 1, curr, mem); + final int d = dfs(matrix, i, j - 1, curr, mem); + return mem[i][j] = 1 + Math.max(Math.max(a, b), Math.max(c, d)); + } +} diff --git a/solutions/329. Longest Increasing Path in a Matrix/329.py b/solutions/329. Longest Increasing Path in a Matrix/329.py new file mode 100644 index 00000000000..e0223d5f191 --- /dev/null +++ b/solutions/329. Longest Increasing Path in a Matrix/329.py @@ -0,0 +1,19 @@ +class Solution: + def longestIncreasingPath(self, matrix: List[List[int]]) -> int: + m = len(matrix) + n = len(matrix[0]) + + @functools.lru_cache(None) + def dfs(i: int, j: int, prev: int) -> int: + if i < 0 or i == m or j < 0 or j == n: + return 0 + if matrix[i][j] <= prev: + return 0 + + curr = matrix[i][j] + return 1 + max(dfs(i + 1, j, curr), + dfs(i - 1, j, curr), + dfs(i, j + 1, curr), + dfs(i, j - 1, curr)) + + return max(dfs(i, j, -math.inf) for i in range(m) for j in range(n)) diff --git a/solutions/33. Search in Rotated Sorted Array/33.cpp b/solutions/33. Search in Rotated Sorted Array/33.cpp new file mode 100644 index 00000000000..aa5cfc90f9e --- /dev/null +++ b/solutions/33. Search in Rotated Sorted Array/33.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int search(vector& nums, int target) { + int l = 0; + int r = nums.size() - 1; + + while (l <= r) { + const int m = (l + r) / 2; + if (nums[m] == target) + return m; + if (nums[l] <= nums[m]) { // nums[l..m] are sorted. + if (nums[l] <= target && target < nums[m]) + r = m - 1; + else + l = m + 1; + } else { // nums[m..n - 1] are sorted. + if (nums[m] < target && target <= nums[r]) + l = m + 1; + else + r = m - 1; + } + } + + return -1; + } +}; diff --git a/solutions/33. Search in Rotated Sorted Array/33.java b/solutions/33. Search in Rotated Sorted Array/33.java new file mode 100644 index 00000000000..0f683b5d404 --- /dev/null +++ b/solutions/33. Search in Rotated Sorted Array/33.java @@ -0,0 +1,25 @@ +class Solution { + public int search(int[] nums, int target) { + int l = 0; + int r = nums.length - 1; + + while (l <= r) { + final int m = (l + r) / 2; + if (nums[m] == target) + return m; + if (nums[l] <= nums[m]) { // nums[l..m] are sorted. + if (nums[l] <= target && target < nums[m]) + r = m - 1; + else + l = m + 1; + } else { // nums[m..n - 1] are sorted. + if (nums[m] < target && target <= nums[r]) + l = m + 1; + else + r = m - 1; + } + } + + return -1; + } +} diff --git a/solutions/33. Search in Rotated Sorted Array/33.py b/solutions/33. Search in Rotated Sorted Array/33.py new file mode 100644 index 00000000000..5e3a82b4e31 --- /dev/null +++ b/solutions/33. Search in Rotated Sorted Array/33.py @@ -0,0 +1,21 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + l = 0 + r = len(nums) - 1 + + while l <= r: + m = (l + r) // 2 + if nums[m] == target: + return m + if nums[l] <= nums[m]: # nums[l..m] are sorted. + if nums[l] <= target < nums[m]: + r = m - 1 + else: + l = m + 1 + else: # nums[m..n - 1] are sorted. + if nums[m] < target <= nums[r]: + l = m + 1 + else: + r = m - 1 + + return -1 diff --git a/solutions/330. Patching Array/330.cpp b/solutions/330. Patching Array/330.cpp new file mode 100644 index 00000000000..d8c70aef13d --- /dev/null +++ b/solutions/330. Patching Array/330.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minPatches(vector& nums, int n) { + int ans = 0; + int i = 0; // nums' index + long miss = 1; // the minimum sum in [1, n] we might miss + + while (miss <= n) + if (i < nums.size() && nums[i] <= miss) { + miss += nums[i++]; + } else { + // Greedily add `miss` itself to increase the range from + // [1, miss) to [1, 2 * miss). + miss += miss; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/330. Patching Array/330.java b/solutions/330. Patching Array/330.java new file mode 100644 index 00000000000..bd333773e55 --- /dev/null +++ b/solutions/330. Patching Array/330.java @@ -0,0 +1,19 @@ +class Solution { + public int minPatches(int[] nums, int n) { + int ans = 0; + int i = 0; // nums' index + long miss = 1; // the minimum sum in [1, n] we might miss + + while (miss <= n) + if (i < nums.length && nums[i] <= miss) { + miss += nums[i++]; + } else { + // Greedily add `miss` itself to increase the range from + // [1, miss) to [1, 2 * miss). + miss += miss; + ++ans; + } + + return ans; + } +} diff --git a/solutions/330. Patching Array/330.py b/solutions/330. Patching Array/330.py new file mode 100644 index 00000000000..701dc115878 --- /dev/null +++ b/solutions/330. Patching Array/330.py @@ -0,0 +1,17 @@ +class Solution: + def minPatches(self, nums: List[int], n: int) -> int: + ans = 0 + i = 0 # nums' index + miss = 1 # the minimum sum in [1, n] we might miss + + while miss <= n: + if i < len(nums) and nums[i] <= miss: + miss += nums[i] + i += 1 + else: + # Greedily add `miss` itself to increase the range from + # [1, miss) to [1, 2 * miss). + miss += miss + ans += 1 + + return ans diff --git a/solutions/331. Verify Preorder Serialization of a Binary Tree/331.cpp b/solutions/331. Verify Preorder Serialization of a Binary Tree/331.cpp new file mode 100644 index 00000000000..81c585a4c11 --- /dev/null +++ b/solutions/331. Verify Preorder Serialization of a Binary Tree/331.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool isValidSerialization(string preorder) { + int degree = 1; // out-degree (children) - in-degree (parent) + istringstream iss(preorder); + + for (string node; getline(iss, node, ',');) { + if (--degree < 0) + return false; + if (node != "#") + degree += 2; + } + + return degree == 0; + } +}; diff --git a/solutions/331. Verify Preorder Serialization of a Binary Tree/331.java b/solutions/331. Verify Preorder Serialization of a Binary Tree/331.java new file mode 100644 index 00000000000..f1f7b45aba5 --- /dev/null +++ b/solutions/331. Verify Preorder Serialization of a Binary Tree/331.java @@ -0,0 +1,14 @@ +class Solution { + public boolean isValidSerialization(String preorder) { + int degree = 1; // out-degree (children) - in-degree (parent) + + for (final String node : preorder.split(",")) { + if (--degree < 0) // One parent + return false; + if (!node.equals("#")) + degree += 2; // Two children + } + + return degree == 0; + } +} diff --git a/solutions/331. Verify Preorder Serialization of a Binary Tree/331.py b/solutions/331. Verify Preorder Serialization of a Binary Tree/331.py new file mode 100644 index 00000000000..86747beaa0f --- /dev/null +++ b/solutions/331. Verify Preorder Serialization of a Binary Tree/331.py @@ -0,0 +1,12 @@ +class Solution: + def isValidSerialization(self, preorder: str) -> bool: + degree = 1 # out-degree (children) - in-degree (parent) + + for node in preorder.split(','): + degree -= 1 + if degree < 0: + return False + if node != '#': + degree += 2 + + return degree == 0 diff --git a/solutions/332. Reconstruct Itinerary/332.cpp b/solutions/332. Reconstruct Itinerary/332.cpp new file mode 100644 index 00000000000..6731b099726 --- /dev/null +++ b/solutions/332. Reconstruct Itinerary/332.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector findItinerary(vector>& tickets) { + vector ans; + unordered_map> graph; + + for (const vector& ticket : tickets) + graph[ticket[0]].insert(ticket[1]); + + dfs(graph, "JFK", ans); + reverse(ans.begin(), ans.end()); + return ans; + } + + private: + void dfs(unordered_map>& graph, const string& u, + vector& ans) { + while (graph.contains(u) && !graph[u].empty()) { + const string v = *graph[u].begin(); + graph[u].erase(graph[u].begin()); + dfs(graph, v, ans); + } + ans.push_back(u); + } +}; diff --git a/solutions/332. Reconstruct Itinerary/332.java b/solutions/332. Reconstruct Itinerary/332.java new file mode 100644 index 00000000000..611d503e368 --- /dev/null +++ b/solutions/332. Reconstruct Itinerary/332.java @@ -0,0 +1,21 @@ +class Solution { + public List findItinerary(List> tickets) { + LinkedList ans = new LinkedList<>(); + Map> graph = new HashMap<>(); + + for (final List ticket : tickets) { + graph.putIfAbsent(ticket.get(0), new PriorityQueue<>()); + graph.get(ticket.get(0)).offer(ticket.get(1)); + } + + dfs(graph, "JFK", ans); + return ans; + } + + private void dfs(Map> graph, final String u, LinkedList ans) { + final Queue arrivals = graph.get(u); + while (arrivals != null && !arrivals.isEmpty()) + dfs(graph, arrivals.poll(), ans); + ans.addFirst(u); + } +} diff --git a/solutions/332. Reconstruct Itinerary/332.py b/solutions/332. Reconstruct Itinerary/332.py new file mode 100644 index 00000000000..df0a55f7d33 --- /dev/null +++ b/solutions/332. Reconstruct Itinerary/332.py @@ -0,0 +1,15 @@ +class Solution: + def findItinerary(self, tickets: List[List[str]]) -> List[str]: + ans = [] + graph = collections.defaultdict(list) + + for a, b in reversed(sorted(tickets)): + graph[a].append(b) + + def dfs(u: str) -> None: + while u in graph and graph[u]: + dfs(graph[u].pop()) + ans.append(u) + + dfs('JFK') + return ans[::-1] diff --git a/solutions/333. Largest BST Subtree/333.cpp b/solutions/333. Largest BST Subtree/333.cpp new file mode 100644 index 00000000000..04665123dc6 --- /dev/null +++ b/solutions/333. Largest BST Subtree/333.cpp @@ -0,0 +1,28 @@ +struct T { + int mn; // the minimum value in the subtree + int mx; // the maximum value in the subtree + int size; // the size of the subtree +}; + +class Solution { + public: + int largestBSTSubtree(TreeNode* root) { + return dfs(root).size; + } + + private: + T dfs(TreeNode* root) { + if (root == nullptr) + return {INT_MAX, INT_MIN, 0}; + + T l = dfs(root->left); + T r = dfs(root->right); + + if (l.mx < root->val && root->val < r.mn) + return {min(l.mn, root->val), max(r.mx, root->val), 1 + l.size + r.size}; + + // Mark one as invalid, but still record the size of children. + // Return (-INF, INF) because no node will be > INT or < -INF. + return {INT_MIN, INT_MAX, max(l.size, r.size)}; + } +}; diff --git a/solutions/333. Largest BST Subtree/333.java b/solutions/333. Largest BST Subtree/333.java new file mode 100644 index 00000000000..99860d02bb3 --- /dev/null +++ b/solutions/333. Largest BST Subtree/333.java @@ -0,0 +1,25 @@ +class Solution { + public int largestBSTSubtree(TreeNode root) { + return dfs(root).size; + } + + private T dfs(TreeNode root) { + if (root == null) + return new T(Integer.MAX_VALUE, Integer.MIN_VALUE, 0); + + T l = dfs(root.left); + T r = dfs(root.right); + + if (l.mx < root.val && root.val < r.mn) + return new T(Math.min(l.mn, root.val), Math.max(r.mx, root.val), 1 + l.size + r.size); + + // Mark one as invalid, but still record the size of children. + // Return (-INF, INF) because no node will be > INT or < -INF. + return new T(Integer.MIN_VALUE, Integer.MAX_VALUE, Math.max(l.size, r.size)); + } + + private record T(int mn, // the minimum value in the subtree + int mx, // the maximum value in the subtree + int size // the size of the subtree + ) {} +} diff --git a/solutions/333. Largest BST Subtree/333.py b/solutions/333. Largest BST Subtree/333.py new file mode 100644 index 00000000000..083ad8c0eed --- /dev/null +++ b/solutions/333. Largest BST Subtree/333.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True) +class T: + mn: int # the minimum value in the subtree + mx: int # the maximum value in the subtree + size: int # the size of the subtree + + +class Solution: + def largestBSTSubtree(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]) -> T: + if not root: + return T(math.inf, -math.inf, 0) + + l = dfs(root.left) + r = dfs(root.right) + + if l.mx < root.val < r.mn: + return T(min(l.mn, root.val), max(r.mx, root.val), 1 + l.size + r.size) + + # Mark one as invalid, but still record the size of children. + # Return (-inf, inf) because no node will be > inf or < -inf. + return T(-math.inf, math.inf, max(l.size, r.size)) + + return dfs(root).size diff --git a/solutions/334. Increasing Triplet Subsequence/334.cpp b/solutions/334. Increasing Triplet Subsequence/334.cpp new file mode 100644 index 00000000000..0bb865d8258 --- /dev/null +++ b/solutions/334. Increasing Triplet Subsequence/334.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool increasingTriplet(vector& nums) { + int first = INT_MAX; + int second = INT_MAX; + + for (const int num : nums) + if (num <= first) + first = num; + else if (num <= second) // first < num <= second + second = num; + else + return true; // first < second < num (third) + + return false; + } +}; diff --git a/solutions/334. Increasing Triplet Subsequence/334.java b/solutions/334. Increasing Triplet Subsequence/334.java new file mode 100644 index 00000000000..01f131da019 --- /dev/null +++ b/solutions/334. Increasing Triplet Subsequence/334.java @@ -0,0 +1,16 @@ +class Solution { + public boolean increasingTriplet(int[] nums) { + int first = Integer.MAX_VALUE; + int second = Integer.MAX_VALUE; + + for (final int num : nums) + if (num <= first) + first = num; + else if (num <= second) // first < num <= second + second = num; + else // first < second < num (third) + return true; + + return false; + } +} diff --git a/solutions/334. Increasing Triplet Subsequence/334.py b/solutions/334. Increasing Triplet Subsequence/334.py new file mode 100644 index 00000000000..adbc8e80bfe --- /dev/null +++ b/solutions/334. Increasing Triplet Subsequence/334.py @@ -0,0 +1,14 @@ +class Solution: + def increasingTriplet(self, nums: List[int]) -> bool: + first = math.inf + second = math.inf + + for num in nums: + if num <= first: + first = num + elif num <= second: # first < num <= second + second = num + else: + return True # first < second < num (third) + + return False diff --git a/solutions/335. Self Crossing/335.cpp b/solutions/335. Self Crossing/335.cpp new file mode 100644 index 00000000000..6fec0a1cfca --- /dev/null +++ b/solutions/335. Self Crossing/335.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool isSelfCrossing(vector& x) { + if (x.size() <= 3) + return false; + + for (int i = 3; i < x.size(); ++i) { + if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3]) + return true; + if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4]) + return true; + if (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] && + x[i - 1] <= x[i - 3] && x[i - 3] <= x[i - 1] + x[i - 5]) + return true; + } + + return false; + } +}; diff --git a/solutions/335. Self Crossing/335.java b/solutions/335. Self Crossing/335.java new file mode 100644 index 00000000000..0991e7a6ec9 --- /dev/null +++ b/solutions/335. Self Crossing/335.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isSelfCrossing(int[] x) { + if (x.length <= 3) + return false; + + for (int i = 3; i < x.length; ++i) { + if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3]) + return true; + if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4]) + return true; + if (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] && x[i - 1] <= x[i - 3] && + x[i - 3] <= x[i - 1] + x[i - 5]) + return true; + } + + return false; + } +} diff --git a/solutions/335. Self Crossing/335.py b/solutions/335. Self Crossing/335.py new file mode 100644 index 00000000000..9a441a8c9ca --- /dev/null +++ b/solutions/335. Self Crossing/335.py @@ -0,0 +1,14 @@ +class Solution: + def isSelfCrossing(self, x: List[int]) -> bool: + if len(x) <= 3: + return False + + for i in range(3, len(x)): + if x[i - 2] <= x[i] and x[i - 1] <= x[i - 3]: + return True + if i >= 4 and x[i - 1] == x[i - 3] and x[i - 2] <= x[i] + x[i - 4]: + return True + if i >= 5 and x[i - 4] <= x[i - 2] and x[i - 2] <= x[i] + x[i - 4] and x[i - 1] <= x[i - 3] and x[i - 3] <= x[i - 1] + x[i - 5]: + return True + + return False diff --git a/solutions/336. Palindrome Pairs/336.cpp b/solutions/336. Palindrome Pairs/336.cpp new file mode 100644 index 00000000000..32e7589c0fa --- /dev/null +++ b/solutions/336. Palindrome Pairs/336.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + vector> palindromePairs(vector& words) { + vector> ans; + unordered_map map; // {reversed word: its index} + + for (int i = 0; i < words.size(); ++i) { + string word = words[i]; + reverse(word.begin(), word.end()); + map[word] = i; + } + + for (int i = 0; i < words.size(); ++i) { + const string& word = words[i]; + // a special case to prevent duplicate calculation + if (const auto it = map.find(""); + it != map.cend() && it->second != i && isPalindrome(word)) + ans.push_back({i, it->second}); + for (int j = 1; j <= word.length(); ++j) { + const string& l = word.substr(0, j); + const string& r = word.substr(j); + if (const auto it = map.find(l); + it != map.cend() && it->second != i && isPalindrome(r)) + ans.push_back({i, it->second}); + if (const auto it = map.find(r); + it != map.cend() && it->second != i && isPalindrome(l)) + ans.push_back({it->second, i}); + } + } + + return ans; + } + + private: + bool isPalindrome(const string& word) { + int l = 0; + int r = word.length() - 1; + while (l < r) + if (word[l++] != word[r--]) + return false; + return true; + } +}; diff --git a/solutions/336. Palindrome Pairs/336.java b/solutions/336. Palindrome Pairs/336.java new file mode 100644 index 00000000000..fe99f7b61e5 --- /dev/null +++ b/solutions/336. Palindrome Pairs/336.java @@ -0,0 +1,35 @@ +class Solution { + public List> palindromePairs(String[] words) { + List> ans = new ArrayList<>(); + Map map = new HashMap<>(); // {reversed word: its index} + + for (int i = 0; i < words.length; ++i) + map.put(new StringBuilder(words[i]).reverse().toString(), i); + + for (int i = 0; i < words.length; ++i) { + final String word = words[i]; + // a special case to prevent duplicate calculation + if (map.containsKey("") && map.get("") != i && isPalindrome(word)) + ans.add(Arrays.asList(i, map.get(""))); + for (int j = 1; j <= word.length(); ++j) { + final String l = word.substring(0, j); + final String r = word.substring(j); + if (map.containsKey(l) && map.get(l) != i && isPalindrome(r)) + ans.add(Arrays.asList(i, map.get(l))); + if (map.containsKey(r) && map.get(r) != i && isPalindrome(l)) + ans.add(Arrays.asList(map.get(r), i)); + } + } + + return ans; + } + + private boolean isPalindrome(final String word) { + int l = 0; + int r = word.length() - 1; + while (l < r) + if (word.charAt(l++) != word.charAt(r--)) + return false; + return true; + } +} diff --git a/solutions/336. Palindrome Pairs/336.py b/solutions/336. Palindrome Pairs/336.py new file mode 100644 index 00000000000..1423983e79d --- /dev/null +++ b/solutions/336. Palindrome Pairs/336.py @@ -0,0 +1,18 @@ +class Solution: + def palindromePairs(self, words: List[str]) -> List[List[int]]: + ans = [] + dict = {word[::-1]: i for i, word in enumerate(words)} + + for i, word in enumerate(words): + if "" in dict and dict[""] != i and word == word[::-1]: + ans.append([i, dict[""]]) + + for j in range(1, len(word) + 1): + l = word[:j] + r = word[j:] + if l in dict and dict[l] != i and r == r[::-1]: + ans.append([i, dict[l]]) + if r in dict and dict[r] != i and l == l[::-1]: + ans.append([dict[r], i]) + + return ans diff --git a/solutions/337. House Robber III/337.cpp b/solutions/337. House Robber III/337.cpp new file mode 100644 index 00000000000..c7a930ac7da --- /dev/null +++ b/solutions/337. House Robber III/337.cpp @@ -0,0 +1,22 @@ +struct T { + int robRoot; + int notRobRoot; +}; + +class Solution { + public: + int rob(TreeNode* root) { + const auto& [robRoot, notRobRoot] = robOrNotRob(root); + return max(robRoot, notRobRoot); + } + + private: + T robOrNotRob(TreeNode* root) { + if (root == nullptr) + return {0, 0}; + const T l = robOrNotRob(root->left); + const T r = robOrNotRob(root->right); + return {root->val + l.notRobRoot + r.notRobRoot, + max(l.robRoot, l.notRobRoot) + max(r.robRoot, r.notRobRoot)}; + } +}; diff --git a/solutions/337. House Robber III/337.java b/solutions/337. House Robber III/337.java new file mode 100644 index 00000000000..4602ffc1f84 --- /dev/null +++ b/solutions/337. House Robber III/337.java @@ -0,0 +1,24 @@ +class T { + public int robRoot; + public int notRobRoot; + public T(int robRoot, int notRobRoot) { + this.robRoot = robRoot; + this.notRobRoot = notRobRoot; + } +} + +class Solution { + public int rob(TreeNode root) { + T t = robOrNotRob(root); + return Math.max(t.robRoot, t.notRobRoot); + } + + private T robOrNotRob(TreeNode root) { + if (root == null) + return new T(0, 0); + T l = robOrNotRob(root.left); + T r = robOrNotRob(root.right); + return new T(root.val + l.notRobRoot + r.notRobRoot, + Math.max(l.robRoot, l.notRobRoot) + Math.max(r.robRoot, r.notRobRoot)); + } +} diff --git a/solutions/337. House Robber III/337.py b/solutions/337. House Robber III/337.py new file mode 100644 index 00000000000..d0e30a19edf --- /dev/null +++ b/solutions/337. House Robber III/337.py @@ -0,0 +1,13 @@ +class Solution: + def rob(self, root: Optional[TreeNode]) -> int: + def robOrNot(root: Optional[TreeNode]) -> tuple: + if not root: + return (0, 0) + + robLeft, notRobLeft = robOrNot(root.left) + robRight, notRobRight = robOrNot(root.right) + + return (root.val + notRobLeft + notRobRight, + max(robLeft, notRobLeft) + max(robRight, notRobRight)) + + return max(robOrNot(root)) diff --git a/solutions/338. Counting Bits/338.cpp b/solutions/338. Counting Bits/338.cpp new file mode 100644 index 00000000000..cb7746314ce --- /dev/null +++ b/solutions/338. Counting Bits/338.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector countBits(int n) { + // f(i) := i's number of 1s in bitmask + // f(i) = f(i / 2) + i % 2 + vector ans(n + 1); + + for (int i = 1; i <= n; ++i) + ans[i] = ans[i / 2] + (i & 1); + + return ans; + } +}; diff --git a/solutions/338. Counting Bits/338.java b/solutions/338. Counting Bits/338.java new file mode 100644 index 00000000000..3772ea0bb84 --- /dev/null +++ b/solutions/338. Counting Bits/338.java @@ -0,0 +1,12 @@ +class Solution { + public int[] countBits(int n) { + // f(i) := i's number of 1s in bitmask + // f(i) = f(i / 2) + i % 2 + int[] ans = new int[n + 1]; + + for (int i = 1; i <= n; ++i) + ans[i] = ans[i / 2] + (i % 2); + + return ans; + } +} diff --git a/solutions/338. Counting Bits/338.py b/solutions/338. Counting Bits/338.py new file mode 100644 index 00000000000..41124ef24f6 --- /dev/null +++ b/solutions/338. Counting Bits/338.py @@ -0,0 +1,10 @@ +class Solution: + def countBits(self, n: int) -> List[int]: + # f(i) := i's number of 1s in bitmask + # f(i) = f(i / 2) + i % 2 + ans = [0] * (n + 1) + + for i in range(1, n + 1): + ans[i] = ans[i // 2] + (i & 1) + + return ans diff --git a/solutions/339. Nested List Weight Sum/339-2.cpp b/solutions/339. Nested List Weight Sum/339-2.cpp new file mode 100644 index 00000000000..011a430530e --- /dev/null +++ b/solutions/339. Nested List Weight Sum/339-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int depthSum(vector& nestedList) { + int ans = 0; + dfs(nestedList, 1, ans); + return ans; + } + + private: + void dfs(const vector& nestedList, int depth, int& ans) { + for (const NestedInteger& ni : nestedList) + if (ni.isInteger()) + ans += ni.getInteger() * depth; + else + dfs(ni.getList(), depth + 1, ans); + } +}; diff --git a/solutions/339. Nested List Weight Sum/339-2.java b/solutions/339. Nested List Weight Sum/339-2.java new file mode 100644 index 00000000000..1be1e7346c4 --- /dev/null +++ b/solutions/339. Nested List Weight Sum/339-2.java @@ -0,0 +1,16 @@ +class Solution { + public int depthSum(List nestedList) { + dfs(nestedList, 1); + return ans; + } + + private int ans = 0; + + private void dfs(final List nestedList, int depth) { + for (final NestedInteger ni : nestedList) + if (ni.isInteger()) + ans += ni.getInteger() * depth; + else + dfs(ni.getList(), depth + 1); + } +} diff --git a/solutions/339. Nested List Weight Sum/339-2.py b/solutions/339. Nested List Weight Sum/339-2.py new file mode 100644 index 00000000000..c486f8c106e --- /dev/null +++ b/solutions/339. Nested List Weight Sum/339-2.py @@ -0,0 +1,14 @@ +class Solution: + def depthSum(self, nestedList: List[NestedInteger]) -> int: + ans = 0 + + def dfs(nestedList: List[NestedInteger], depth: int) -> None: + nonlocal ans + for ni in nestedList: + if ni.isInteger(): + ans += ni.getInteger() * depth + else: + dfs(ni.getList(), depth + 1) + + dfs(nestedList, 1) + return ans diff --git a/solutions/339. Nested List Weight Sum/339.cpp b/solutions/339. Nested List Weight Sum/339.cpp new file mode 100644 index 00000000000..9839a980efa --- /dev/null +++ b/solutions/339. Nested List Weight Sum/339.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int depthSum(vector& nestedList) { + int ans = 0; + int depth = 0; + queue q; + + addIntegers(q, nestedList); + + while (!q.empty()) { + ++depth; + for (int sz = q.size(); sz > 0; --sz) { + const NestedInteger ni = q.front(); + q.pop(); + if (ni.isInteger()) + ans += ni.getInteger() * depth; + else + addIntegers(q, ni.getList()); + } + } + + return ans; + } + + private: + void addIntegers(queue& q, + const vector& nestedList) { + for (const NestedInteger& ni : nestedList) + q.push(ni); + } +}; diff --git a/solutions/339. Nested List Weight Sum/339.java b/solutions/339. Nested List Weight Sum/339.java new file mode 100644 index 00000000000..77beea15653 --- /dev/null +++ b/solutions/339. Nested List Weight Sum/339.java @@ -0,0 +1,27 @@ +class Solution { + public int depthSum(List nestedList) { + int ans = 0; + int depth = 0; + Queue q = new ArrayDeque<>(); + + addIntegers(q, nestedList); + + while (!q.isEmpty()) { + ++depth; + for (int sz = q.size(); sz > 0; --sz) { + final NestedInteger ni = q.poll(); + if (ni.isInteger()) + ans += ni.getInteger() * depth; + else + addIntegers(q, ni.getList()); + } + } + + return ans; + } + + private void addIntegers(Queue q, List nestedList) { + for (final NestedInteger ni : nestedList) + q.offer(ni); + } +} diff --git a/solutions/339. Nested List Weight Sum/339.py b/solutions/339. Nested List Weight Sum/339.py new file mode 100644 index 00000000000..4a598d6654b --- /dev/null +++ b/solutions/339. Nested List Weight Sum/339.py @@ -0,0 +1,22 @@ +class Solution: + def depthSum(self, nestedList: List[NestedInteger]) -> int: + ans = 0 + depth = 0 + q = collections.deque() + + def addIntegers(nestedList: List[NestedInteger]) -> None: + for ni in nestedList: + q.append(ni) + + addIntegers(nestedList) + + while q: + depth += 1 + for _ in range(len(q)): + ni = q.popleft() + if ni.isInteger(): + ans += ni.getInteger() * depth + else: + addIntegers(ni.getList()) + + return ans diff --git a/solutions/34. Find First and Last Position of Element in Sorted Array/34.cpp b/solutions/34. Find First and Last Position of Element in Sorted Array/34.cpp new file mode 100644 index 00000000000..6be4878e9df --- /dev/null +++ b/solutions/34. Find First and Last Position of Element in Sorted Array/34.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + vector searchRange(vector& nums, int target) { + const int l = ranges::lower_bound(nums, target) - nums.begin(); + if (l == nums.size() || nums[l] != target) + return {-1, -1}; + const int r = ranges::upper_bound(nums, target) - nums.begin() - 1; + return {l, r}; + } +}; diff --git a/solutions/34. Find First and Last Position of Element in Sorted Array/34.java b/solutions/34. Find First and Last Position of Element in Sorted Array/34.java new file mode 100644 index 00000000000..af811191f70 --- /dev/null +++ b/solutions/34. Find First and Last Position of Element in Sorted Array/34.java @@ -0,0 +1,22 @@ +class Solution { + public int[] searchRange(int[] nums, int target) { + final int l = firstGreaterEqual(nums, target); + if (l == nums.length || nums[l] != target) + return new int[] {-1, -1}; + final int r = firstGreaterEqual(nums, target + 1) - 1; + return new int[] {l, r}; + } + + private int firstGreaterEqual(int[] A, int target) { + int l = 0; + int r = A.length; + while (l < r) { + final int m = (l + r) / 2; + if (A[m] >= target) + r = m; + else + l = m + 1; + } + return l; + } +} diff --git a/solutions/34. Find First and Last Position of Element in Sorted Array/34.py b/solutions/34. Find First and Last Position of Element in Sorted Array/34.py new file mode 100644 index 00000000000..6a9fbcde754 --- /dev/null +++ b/solutions/34. Find First and Last Position of Element in Sorted Array/34.py @@ -0,0 +1,7 @@ +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + l = bisect_left(nums, target) + if l == len(nums) or nums[l] != target: + return -1, -1 + r = bisect_right(nums, target) - 1 + return l, r diff --git a/solutions/340. Longest Substring with At Most K Distinct Characters/340-2.cpp b/solutions/340. Longest Substring with At Most K Distinct Characters/340-2.cpp new file mode 100644 index 00000000000..95de29f184f --- /dev/null +++ b/solutions/340. Longest Substring with At Most K Distinct Characters/340-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int lengthOfLongestSubstringKDistinct(string s, int k) { + int ans = 0; + map lastSeen; // {last index: letter} + unordered_map window; // {letter: index} + + for (int l = 0, r = 0; r < s.length(); ++r) { + const int inChar = s[r]; + if (const auto it = window.find(inChar); it != window.cend()) + lastSeen.erase(it->second); + lastSeen[r] = inChar; + window[inChar] = r; + if (window.size() > k) { + const auto [lastIndex, outChar] = *lastSeen.begin(); + lastSeen.erase(lastSeen.begin()); + window.erase(outChar); + l = lastIndex + 1; + } + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/340. Longest Substring with At Most K Distinct Characters/340.cpp b/solutions/340. Longest Substring with At Most K Distinct Characters/340.cpp new file mode 100644 index 00000000000..0bdb319e527 --- /dev/null +++ b/solutions/340. Longest Substring with At Most K Distinct Characters/340.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int lengthOfLongestSubstringKDistinct(string s, int k) { + int ans = 0; + int distinct = 0; + vector count(128); + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s[r]] == 1) + ++distinct; + while (distinct == k + 1) + if (--count[s[l++]] == 0) + --distinct; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/340. Longest Substring with At Most K Distinct Characters/340.java b/solutions/340. Longest Substring with At Most K Distinct Characters/340.java new file mode 100644 index 00000000000..3d5df583c92 --- /dev/null +++ b/solutions/340. Longest Substring with At Most K Distinct Characters/340.java @@ -0,0 +1,18 @@ +class Solution { + public int lengthOfLongestSubstringKDistinct(String s, int k) { + int ans = 0; + int distinct = 0; + int[] count = new int[128]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s.charAt(r)] == 1) + ++distinct; + while (distinct == k + 1) + if (--count[s.charAt(l++)] == 0) + --distinct; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/340. Longest Substring with At Most K Distinct Characters/340.py b/solutions/340. Longest Substring with At Most K Distinct Characters/340.py new file mode 100644 index 00000000000..71de7a5e27b --- /dev/null +++ b/solutions/340. Longest Substring with At Most K Distinct Characters/340.py @@ -0,0 +1,19 @@ +class Solution: + def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: + ans = 0 + distinct = 0 + count = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + if count[c] == 1: + distinct += 1 + while distinct == k + 1: + count[s[l]] -= 1 + if count[s[l]] == 0: + distinct -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/341. Flatten Nested List Iterator/341-2.cpp b/solutions/341. Flatten Nested List Iterator/341-2.cpp new file mode 100644 index 00000000000..33adfb1c78d --- /dev/null +++ b/solutions/341. Flatten Nested List Iterator/341-2.cpp @@ -0,0 +1,32 @@ +class NestedIterator { + public: + NestedIterator(vector& nestedList) { + addInteger(nestedList); + } + + int next() { + const int num = stack.top().getInteger(); + stack.pop(); + return num; + } + + bool hasNext() { + while (!stack.empty() && !stack.top().isInteger()) { + vector nestedList = stack.top().getList(); + stack.pop(); + addInteger(nestedList); + } + return !stack.empty(); + } + + private: + stack stack; + + // addInteger([1, [4, [6]]]) -> stack = [[4, [6]], 1] + // addInteger([4, [6]]) -> stack = [[6], 4] + // addInteger([6]) -> stack = [6] + void addInteger(const vector& nestedList) { + for (int i = nestedList.size() - 1; i >= 0; --i) + stack.push(nestedList[i]); + } +}; diff --git a/solutions/341. Flatten Nested List Iterator/341-2.java b/solutions/341. Flatten Nested List Iterator/341-2.java new file mode 100644 index 00000000000..9738deb1b6f --- /dev/null +++ b/solutions/341. Flatten Nested List Iterator/341-2.java @@ -0,0 +1,29 @@ +public class NestedIterator implements Iterator { + public NestedIterator(List nestedList) { + addInteger(nestedList); + } + + @Override + public Integer next() { + return stack.pop().getInteger(); + } + + @Override + public boolean hasNext() { + while (!stack.isEmpty() && !stack.peek().isInteger()) { + final NestedInteger ni = stack.pop(); + addInteger(ni.getList()); + } + return !stack.isEmpty(); + } + + private Deque stack = new ArrayDeque<>(); + + // addInteger([1, [4, [6]]]) -> stack = [[4, [6]], 1] + // addInteger([4, [6]]) -> stack = [[6], 4] + // addInteger([6]) -> stack = [6] + private void addInteger(final List nestedList) { + for (int i = nestedList.size() - 1; i >= 0; --i) + stack.push(nestedList.get(i)); + } +} diff --git a/solutions/341. Flatten Nested List Iterator/341-2.py b/solutions/341. Flatten Nested List Iterator/341-2.py new file mode 100644 index 00000000000..27be91d25f4 --- /dev/null +++ b/solutions/341. Flatten Nested List Iterator/341-2.py @@ -0,0 +1,19 @@ +class NestedIterator: + def __init__(self, nestedList: List[NestedInteger]): + self.stack: List[NestedInteger] = [] + self.addInteger(nestedList) + + def next(self) -> int: + return self.stack.pop().getInteger() + + def hasNext(self) -> bool: + while self.stack and not self.stack[-1].isInteger(): + self.addInteger(self.stack.pop().getList()) + return self.stack + + # addInteger([1, [4, [6]]]) . stack = [[4, [6]], 1] + # addInteger([4, [6]]) . stack = [[6], 4] + # addInteger([6]) . stack = [6] + def addInteger(self, nestedList: List[NestedInteger]) -> None: + for n in reversed(nestedList): + self.stack.append(n) diff --git a/solutions/341. Flatten Nested List Iterator/341.cpp b/solutions/341. Flatten Nested List Iterator/341.cpp new file mode 100644 index 00000000000..67279a19fb5 --- /dev/null +++ b/solutions/341. Flatten Nested List Iterator/341.cpp @@ -0,0 +1,27 @@ +class NestedIterator { + public: + NestedIterator(vector& nestedList) { + addInteger(nestedList); + } + + int next() { + const int num = q.front(); + q.pop(); + return num; + } + + bool hasNext() { + return !q.empty(); + } + + private: + queue q; + + void addInteger(const vector& nestedList) { + for (const NestedInteger& ni : nestedList) + if (ni.isInteger()) + q.push(ni.getInteger()); + else + addInteger(ni.getList()); + } +}; diff --git a/solutions/341. Flatten Nested List Iterator/341.java b/solutions/341. Flatten Nested List Iterator/341.java new file mode 100644 index 00000000000..210408420e6 --- /dev/null +++ b/solutions/341. Flatten Nested List Iterator/341.java @@ -0,0 +1,25 @@ +public class NestedIterator implements Iterator { + public NestedIterator(List nestedList) { + addInteger(nestedList); + } + + @Override + public Integer next() { + return q.poll(); + } + + @Override + public boolean hasNext() { + return !q.isEmpty(); + } + + private Queue q = new ArrayDeque<>(); + + private void addInteger(final List nestedList) { + for (final NestedInteger ni : nestedList) + if (ni.isInteger()) + q.offer(ni.getInteger()); + else + addInteger(ni.getList()); + } +} diff --git a/solutions/341. Flatten Nested List Iterator/341.py b/solutions/341. Flatten Nested List Iterator/341.py new file mode 100644 index 00000000000..34070b2204c --- /dev/null +++ b/solutions/341. Flatten Nested List Iterator/341.py @@ -0,0 +1,17 @@ +class NestedIterator: + def __init__(self, nestedList: List[NestedInteger]): + self.q = collections.deque() + self.addInteger(nestedList) + + def next(self) -> int: + return self.q.popleft() + + def hasNext(self) -> bool: + return self.q + + def addInteger(self, nestedList: List[NestedInteger]) -> None: + for ni in nestedList: + if ni.isInteger(): + self.q.append(ni.getInteger()) + else: + self.addInteger(ni.getList()) diff --git a/solutions/342. Power of Four/342.cpp b/solutions/342. Power of Four/342.cpp new file mode 100644 index 00000000000..aeeb549c3e7 --- /dev/null +++ b/solutions/342. Power of Four/342.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool isPowerOfFour(unsigned n) { + // Why (4^n - 1) % 3 == 0? + // (4^n - 1) = (2^n - 1)(2^n + 1) and 2^n - 1, 2^n, 2^n + 1 are + // three consecutive numbers; among one of them, there must be a multiple + // of 3, and that can't be 2^n, so it must be either 2^n - 1 or 2^n + 1. + // Therefore, 4^n - 1 is a multiple of 3. + return n > 0 && popcount(n) == 1 && (n - 1) % 3 == 0; + } +}; diff --git a/solutions/342. Power of Four/342.java b/solutions/342. Power of Four/342.java new file mode 100644 index 00000000000..3eca65cbc54 --- /dev/null +++ b/solutions/342. Power of Four/342.java @@ -0,0 +1,10 @@ +class Solution { + public boolean isPowerOfFour(int n) { + // Why (4^n - 1) % 3 == 0? + // (4^n - 1) = (2^n - 1)(2^n + 1) and 2^n - 1, 2^n, 2^n + 1 are + // three consecutive numbers; among one of them, there must be a multiple + // of 3, and that can't be 2^n, so it must be either 2^n - 1 or 2^n + 1. + // Therefore, 4^n - 1 is a multiple of 3 + return n > 0 && Integer.bitCount(n) == 1 && (n - 1) % 3 == 0; + } +} diff --git a/solutions/342. Power of Four/342.py b/solutions/342. Power of Four/342.py new file mode 100644 index 00000000000..865c146dd21 --- /dev/null +++ b/solutions/342. Power of Four/342.py @@ -0,0 +1,8 @@ +class Solution: + def isPowerOfFour(self, n: int) -> bool: + # Why (4^n - 1) % 3 == 0? + # (4^n - 1) = (2^n - 1)(2^n + 1) and 2^n - 1, 2^n, 2^n + 1 are + # three consecutive numbers; among one of them, there must be a multiple + # of 3, and that can't be 2^n, so it must be either 2^n - 1 or 2^n + 1. + # Therefore, 4^n - 1 is a multiple of 3. + return n > 0 and n.bit_count() == 1 and (n - 1) % 3 == 0 diff --git a/solutions/343. Integer Break/343.cpp b/solutions/343. Integer Break/343.cpp new file mode 100644 index 00000000000..a4f454f0196 --- /dev/null +++ b/solutions/343. Integer Break/343.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int integerBreak(int n) { + // If an optimal product contains a factor f >= 4, then we can replace it + // with 2 and f - 2 without losing optimality. As 2(f - 2) = 2f - 4 >= f, + // we never need a factor >= 4, meaning we only need factors 1, 2, and 3 + // (and 1 is wasteful). + // Also, 3 * 3 is better than 2 * 2 * 2, so we never use 2 more than twice. + if (n == 2) // 1 * 1 + return 1; + if (n == 3) // 1 * 2 + return 2; + + int ans = 1; + + while (n > 4) { + n -= 3; + ans *= 3; + } + ans *= n; + + return ans; + } +}; diff --git a/solutions/343. Integer Break/343.java b/solutions/343. Integer Break/343.java new file mode 100644 index 00000000000..13feb8bf18a --- /dev/null +++ b/solutions/343. Integer Break/343.java @@ -0,0 +1,23 @@ +class Solution { + public int integerBreak(int n) { + // If an optimal product contains a factor f >= 4, then we can replace it + // with 2 and f - 2 without losing optimality. As 2(f - 2) = 2f - 4 >= f, + // we never need a factor >= 4, meaning we only need factors 1, 2, and 3 + // (and 1 is wasteful). + // Also, 3 * 3 is better than 2 * 2 * 2, so we never use 2 more than twice. + if (n == 2) + return 1; // 1 * 1 + if (n == 3) + return 2; // 1 * 2 + + int ans = 1; + + while (n > 4) { + n -= 3; + ans *= 3; + } + ans *= n; + + return ans; + } +} diff --git a/solutions/343. Integer Break/343.py b/solutions/343. Integer Break/343.py new file mode 100644 index 00000000000..ded940c1c16 --- /dev/null +++ b/solutions/343. Integer Break/343.py @@ -0,0 +1,20 @@ +class Solution: + def integerBreak(self, n: int) -> int: + # If an optimal product contains a factor f >= 4, then we can replace it + # with 2 and f - 2 without losing optimality. As 2(f - 2) = 2f - 4 >= f, + # we never need a factor >= 4, meaning we only need factors 1, 2, and 3 + # (and 1 is wasteful). + # Also, 3 * 3 is better than 2 * 2 * 2, so we never use 2 more than twice. + if n == 2: # 1 * 1 + return 1 + if n == 3: # 1 * 2 + return 2 + + ans = 1 + + while n > 4: + n -= 3 + ans *= 3 + ans *= n + + return ans diff --git a/solutions/344. Reverse String/344.cpp b/solutions/344. Reverse String/344.cpp new file mode 100644 index 00000000000..57b291bfd31 --- /dev/null +++ b/solutions/344. Reverse String/344.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + void reverseString(vector& s) { + int l = 0; + int r = s.size() - 1; + + while (l < r) + swap(s[l++], s[r--]); + } +}; diff --git a/solutions/344. Reverse String/344.java b/solutions/344. Reverse String/344.java new file mode 100644 index 00000000000..1fd19a9adc0 --- /dev/null +++ b/solutions/344. Reverse String/344.java @@ -0,0 +1,12 @@ +class Solution { + public void reverseString(char[] s) { + int l = 0; + int r = s.length - 1; + + while (l < r) { + char temp = s[l]; + s[l++] = s[r]; + s[r--] = temp; + } + } +} diff --git a/solutions/344. Reverse String/344.py b/solutions/344. Reverse String/344.py new file mode 100644 index 00000000000..11591ed589b --- /dev/null +++ b/solutions/344. Reverse String/344.py @@ -0,0 +1,9 @@ +class Solution: + def reverseString(self, s: List[str]) -> None: + l = 0 + r = len(s) - 1 + + while l < r: + s[l], s[r] = s[r], s[l] + l += 1 + r -= 1 diff --git a/solutions/345. Reverse Vowels of a String/345.cpp b/solutions/345. Reverse Vowels of a String/345.cpp new file mode 100644 index 00000000000..51f8d148012 --- /dev/null +++ b/solutions/345. Reverse Vowels of a String/345.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + string reverseVowels(string s) { + int l = 0; + int r = s.length() - 1; + + while (l < r) { + while (l < r && !isVowel(s[l])) + ++l; + while (l < r && !isVowel(s[r])) + --r; + swap(s[l++], s[r--]); + } + + return s; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/345. Reverse Vowels of a String/345.java b/solutions/345. Reverse Vowels of a String/345.java new file mode 100644 index 00000000000..5418dd96dd4 --- /dev/null +++ b/solutions/345. Reverse Vowels of a String/345.java @@ -0,0 +1,24 @@ +class Solution { + public String reverseVowels(String s) { + StringBuilder sb = new StringBuilder(s); + int l = 0; + int r = s.length() - 1; + + while (l < r) { + while (l < r && !isVowel(sb.charAt(l))) + ++l; + while (l < r && !isVowel(sb.charAt(r))) + --r; + sb.setCharAt(l, s.charAt(r)); + sb.setCharAt(r, s.charAt(l)); + ++l; + --r; + } + + return sb.toString(); + } + + private boolean isVowel(char c) { + return "aeiouAEIOU".indexOf(c) != -1; + } +} diff --git a/solutions/345. Reverse Vowels of a String/345.py b/solutions/345. Reverse Vowels of a String/345.py new file mode 100644 index 00000000000..026e2532442 --- /dev/null +++ b/solutions/345. Reverse Vowels of a String/345.py @@ -0,0 +1,17 @@ +class Solution: + def reverseVowels(self, s: str) -> str: + chars = list(s) + kVowels = 'aeiouAEIOU' + l = 0 + r = len(s) - 1 + + while l < r: + while l < r and chars[l] not in kVowels: + l += 1 + while l < r and chars[r] not in kVowels: + r -= 1 + chars[l], chars[r] = chars[r], chars[l] + l += 1 + r -= 1 + + return ''.join(chars) diff --git a/solutions/346. Moving Average from Data Stream/346.cpp b/solutions/346. Moving Average from Data Stream/346.cpp new file mode 100644 index 00000000000..042dc4270cc --- /dev/null +++ b/solutions/346. Moving Average from Data Stream/346.cpp @@ -0,0 +1,17 @@ +class MovingAverage { + public: + MovingAverage(int size) : size(size) {} + + double next(int val) { + if (q.size() == size) + sum -= q.front(), q.pop(); + sum += val; + q.push(val); + return sum / q.size(); + } + + private: + int size; + double sum = 0; + queue q; +}; diff --git a/solutions/346. Moving Average from Data Stream/346.java b/solutions/346. Moving Average from Data Stream/346.java new file mode 100644 index 00000000000..c7cf6887f04 --- /dev/null +++ b/solutions/346. Moving Average from Data Stream/346.java @@ -0,0 +1,17 @@ +class MovingAverage { + public MovingAverage(int size) { + this.size = size; + } + + public double next(int val) { + if (q.size() == size) + sum -= q.poll(); + sum += val; + q.offer(val); + return sum / q.size(); + } + + private int size = 0; + private double sum = 0; + private Queue q = new ArrayDeque<>(); +} diff --git a/solutions/346. Moving Average from Data Stream/346.py b/solutions/346. Moving Average from Data Stream/346.py new file mode 100644 index 00000000000..a4fb3159095 --- /dev/null +++ b/solutions/346. Moving Average from Data Stream/346.py @@ -0,0 +1,12 @@ +class MovingAverage: + def __init__(self, size: int): + self.size = size + self.sum = 0 + self.q = collections.deque() + + def next(self, val: int) -> float: + if len(self.q) == self.size: + self.sum -= self.q.popleft() + self.sum += val + self.q.append(val) + return self.sum / len(self.q) diff --git a/solutions/347. Top K Frequent Elements/347-2.cpp b/solutions/347. Top K Frequent Elements/347-2.cpp new file mode 100644 index 00000000000..11473d6e0a0 --- /dev/null +++ b/solutions/347. Top K Frequent Elements/347-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector topKFrequent(vector& nums, int k) { + const int n = nums.size(); + vector ans; + vector> bucket(n + 1); + unordered_map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [num, freq] : count) + bucket[freq].push_back(num); + + for (int freq = n; freq > 0; --freq) { + for (const int num : bucket[freq]) + ans.push_back(num); + if (ans.size() == k) + return ans; + } + + throw; + } +}; diff --git a/solutions/347. Top K Frequent Elements/347-2.java b/solutions/347. Top K Frequent Elements/347-2.java new file mode 100644 index 00000000000..99c52a0a5de --- /dev/null +++ b/solutions/347. Top K Frequent Elements/347-2.java @@ -0,0 +1,27 @@ +class Solution { + public int[] topKFrequent(int[] nums, int k) { + final int n = nums.length; + List ans = new ArrayList<>(); + List[] bucket = new List[n + 1]; + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int num : count.keySet()) { + final int freq = count.get(num); + if (bucket[freq] == null) + bucket[freq] = new ArrayList<>(); + bucket[freq].add(num); + } + + for (int freq = n; freq > 0; --freq) { + if (bucket[freq] != null) + ans.addAll(bucket[freq]); + if (ans.size() == k) + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/347. Top K Frequent Elements/347-2.py b/solutions/347. Top K Frequent Elements/347-2.py new file mode 100644 index 00000000000..8f7d86c4ec8 --- /dev/null +++ b/solutions/347. Top K Frequent Elements/347-2.py @@ -0,0 +1,12 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + ans = [] + bucket = [[] for _ in range(len(nums) + 1)] + + for num, freq in collections.Counter(nums).items(): + bucket[freq].append(num) + + for b in reversed(bucket): + ans += b + if len(ans) == k: + return ans diff --git a/solutions/347. Top K Frequent Elements/347.cpp b/solutions/347. Top K Frequent Elements/347.cpp new file mode 100644 index 00000000000..8e1200b4a38 --- /dev/null +++ b/solutions/347. Top K Frequent Elements/347.cpp @@ -0,0 +1,30 @@ +struct T { + int num; + int freq; + T(int num, int freq) : num(num), freq(freq) {} +}; + +class Solution { + public: + vector topKFrequent(vector& nums, int k) { + const int n = nums.size(); + vector ans; + unordered_map count; + auto compare = [](const T& a, const T& b) { return a.freq > b.freq; }; + priority_queue, decltype(compare)> minHeap(compare); + + for (const int num : nums) + ++count[num]; + + for (const auto& [num, freq] : count) { + minHeap.emplace(num, freq); + if (minHeap.size() > k) + minHeap.pop(); + } + + while (!minHeap.empty()) + ans.push_back(minHeap.top().num), minHeap.pop(); + + return ans; + } +}; diff --git a/solutions/347. Top K Frequent Elements/347.java b/solutions/347. Top K Frequent Elements/347.java new file mode 100644 index 00000000000..0c21c9832c2 --- /dev/null +++ b/solutions/347. Top K Frequent Elements/347.java @@ -0,0 +1,33 @@ +class T { + public int num; + public int freq; + public T(int num, int freq) { + this.num = num; + this.freq = freq; + } +} + +class Solution { + public int[] topKFrequent(int[] nums, int k) { + final int n = nums.length; + int[] ans = new int[k]; + Map count = new HashMap<>(); + Queue minHeap = new PriorityQueue<>((a, b) -> a.freq - b.freq); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (Map.Entry entry : count.entrySet()) { + final int num = entry.getKey(); + final int freq = entry.getValue(); + minHeap.offer(new T(num, freq)); + if (minHeap.size() > k) + minHeap.poll(); + } + + for (int i = 0; i < k; ++i) + ans[i] = minHeap.poll().num; + + return ans; + } +} diff --git a/solutions/348. Design Tic-Tac-Toe/348.cpp b/solutions/348. Design Tic-Tac-Toe/348.cpp new file mode 100644 index 00000000000..b6b7d546cd8 --- /dev/null +++ b/solutions/348. Design Tic-Tac-Toe/348.cpp @@ -0,0 +1,50 @@ +class TicTacToe { + public: + TicTacToe(int n) : n(n), rows(n), cols(n) {} + + /** + * Player {player} makes a move at ({row}, {col}). + * + * @param row The row of the board. + * @param col The column of the board. + * @param player The player, can be either 1 or 2. + * @return The current winning condition, can be either: + * 0: No one wins. + * 1: Player 1 wins. + * 2: Player 2 wins. + */ + int move(int row, int col, int player) { + const int toAdd = player == 1 ? 1 : -1; + const int target = player == 1 ? n : -n; + + if (row == col) { + diag += toAdd; + if (diag == target) + return player; + } + + if (row + col == n - 1) { + antiDiag += toAdd; + if (antiDiag == target) + return player; + } + + rows[row] += toAdd; + if (rows[row] == target) + return player; + + cols[col] += toAdd; + if (cols[col] == target) + return player; + + return 0; + } + + private: + const int n; + // Record count('X') - count('O'). + vector rows; + vector cols; + int diag = 0; + int antiDiag = 0; +}; diff --git a/solutions/348. Design Tic-Tac-Toe/348.java b/solutions/348. Design Tic-Tac-Toe/348.java new file mode 100644 index 00000000000..d12ebbd29dd --- /dev/null +++ b/solutions/348. Design Tic-Tac-Toe/348.java @@ -0,0 +1,52 @@ +class TicTacToe { + public TicTacToe(int n) { + this.n = n; + rows = new int[n]; + cols = new int[n]; + } + + /** + * Player {player} makes a move at ({row}, {col}). + * + * @param row The row of the board. + * @param col The column of the board. + * @param player The player, can be either 1 or 2. + * @return The current winning condition, can be either: + * 0: No one wins. + * 1: Player 1 wins. + * 2: Player 2 wins. + */ + public int move(int row, int col, int player) { + final int toAdd = player == 1 ? 1 : -1; + final int target = player == 1 ? n : -n; + + if (row == col) { + diag += toAdd; + if (diag == target) + return player; + } + + if (row + col == n - 1) { + antiDiag += toAdd; + if (antiDiag == target) + return player; + } + + rows[row] += toAdd; + if (rows[row] == target) + return player; + + cols[col] += toAdd; + if (cols[col] == target) + return player; + + return 0; + } + + private final int n; + // Record count('X') - count('O'). + private int[] rows; + private int[] cols; + private int diag = 0; + private int antiDiag = 0; +} diff --git a/solutions/348. Design Tic-Tac-Toe/348.py b/solutions/348. Design Tic-Tac-Toe/348.py new file mode 100644 index 00000000000..df1e5d624ad --- /dev/null +++ b/solutions/348. Design Tic-Tac-Toe/348.py @@ -0,0 +1,43 @@ +class TicTacToe: + def __init__(self, n: int): + self.n = n + # Record count('X') - count('O'). + self.rows = [0] * n + self.cols = [0] * n + self.diag = 0 + self.antiDiag = 0 + + """ Player {player} makes a move at ({row}, {col}). + + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. + """ + + def move(self, row: int, col: int, player: int) -> int: + toAdd = 1 if player == 1 else -1 + target = self.n if player == 1 else -self.n + + if row == col: + self.diag += toAdd + if self.diag == target: + return player + + if row + col == self.n - 1: + self.antiDiag += toAdd + if self.antiDiag == target: + return player + + self.rows[row] += toAdd + if self.rows[row] == target: + return player + + self.cols[col] += toAdd + if self.cols[col] == target: + return player + + return 0 diff --git a/solutions/349. Intersection of Two Arrays/349.cpp b/solutions/349. Intersection of Two Arrays/349.cpp new file mode 100644 index 00000000000..3376f926c4c --- /dev/null +++ b/solutions/349. Intersection of Two Arrays/349.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector intersection(vector& nums1, vector& nums2) { + vector ans; + unordered_set set{nums1.begin(), nums1.end()}; + + for (const int num : nums2) + if (set.erase(num)) + ans.push_back(num); + + return ans; + } +}; diff --git a/solutions/349. Intersection of Two Arrays/349.java b/solutions/349. Intersection of Two Arrays/349.java new file mode 100644 index 00000000000..e5edfb3fcfa --- /dev/null +++ b/solutions/349. Intersection of Two Arrays/349.java @@ -0,0 +1,12 @@ +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + List ans = new ArrayList<>(); + Set set = Arrays.stream(nums1).boxed().collect(Collectors.toSet()); + + for (final int num : nums2) + if (set.remove(num)) + ans.add(num); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/349. Intersection of Two Arrays/349.py b/solutions/349. Intersection of Two Arrays/349.py new file mode 100644 index 00000000000..7d8be9920ec --- /dev/null +++ b/solutions/349. Intersection of Two Arrays/349.py @@ -0,0 +1,11 @@ +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + ans = [] + nums1 = set(nums1) + + for num in nums2: + if num in nums1: + ans.append(num) + nums1.remove(num) + + return ans diff --git a/solutions/35. Search Insert Position/35.cpp b/solutions/35. Search Insert Position/35.cpp new file mode 100644 index 00000000000..9c4e1b9399e --- /dev/null +++ b/solutions/35. Search Insert Position/35.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int searchInsert(vector& nums, int target) { + int l = 0; + int r = nums.size(); + + while (l < r) { + const int m = (l + r) / 2; + if (nums[m] == target) + return m; + if (nums[m] < target) + l = m + 1; + else + r = m; + } + + return l; + } +}; diff --git a/solutions/35. Search Insert Position/35.java b/solutions/35. Search Insert Position/35.java new file mode 100644 index 00000000000..9e8f5404ab8 --- /dev/null +++ b/solutions/35. Search Insert Position/35.java @@ -0,0 +1,18 @@ +class Solution { + public int searchInsert(int[] nums, int target) { + int l = 0; + int r = nums.length; + + while (l < r) { + final int m = (l + r) / 2; + if (nums[m] == target) + return m; + if (nums[m] < target) + l = m + 1; + else + r = m; + } + + return l; + } +} diff --git a/solutions/35. Search Insert Position/35.py b/solutions/35. Search Insert Position/35.py new file mode 100644 index 00000000000..0eb427aabf8 --- /dev/null +++ b/solutions/35. Search Insert Position/35.py @@ -0,0 +1,15 @@ +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + l = 0 + r = len(nums) + + while l < r: + m = (l + r) // 2 + if nums[m] == target: + return m + if nums[m] < target: + l = m + 1 + else: + r = m + + return l diff --git a/solutions/350. Intersection of Two Arrays II/350-2.cpp b/solutions/350. Intersection of Two Arrays II/350-2.cpp new file mode 100644 index 00000000000..4f0426275b6 --- /dev/null +++ b/solutions/350. Intersection of Two Arrays II/350-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector intersect(vector& nums1, vector& nums2) { + ranges::sort(nums1); + ranges::sort(nums2); + + vector ans; + int i = 0; // nums1's index + int j = 0; // nums2's index + + while (i < nums1.size() && j < nums2.size()) + if (nums1[i] < nums2[j]) { + ++i; + } else if (nums1[i] > nums2[j]) { + ++j; + } else { + ans.push_back(nums1[i]); + ++i; + ++j; + } + + return ans; + } +}; diff --git a/solutions/350. Intersection of Two Arrays II/350-3.cpp b/solutions/350. Intersection of Two Arrays II/350-3.cpp new file mode 100644 index 00000000000..d4c76e49fa6 --- /dev/null +++ b/solutions/350. Intersection of Two Arrays II/350-3.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + vector intersect(vector& nums1, vector& nums2) { + if (nums1.size() > nums2.size()) + return intersect(nums2, nums1); + + vector ans; + int lowerBound = 0; // the lower bound for the binary search + + ranges::sort(nums1); + ranges::sort(nums2); + + for (const int num : nums1) { + const int i = binarySearch(nums2, lowerBound, num); + if (i < nums2.size() && nums2[i] == num) { + ans.push_back(num); + lowerBound = i + 1; + } + } + + return ans; + } + + private: + int binarySearch(vector& nums2, int lo, int target) { + int l = lo; + int r = nums2.size(); + while (l < r) { + const int m = (l + r) / 2; + if (nums2[m] >= target) + r = m; + else + l = m + 1; + } + return l; + } +}; diff --git a/solutions/350. Intersection of Two Arrays II/350.cpp b/solutions/350. Intersection of Two Arrays II/350.cpp new file mode 100644 index 00000000000..f3782ede14b --- /dev/null +++ b/solutions/350. Intersection of Two Arrays II/350.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector intersect(vector& nums1, vector& nums2) { + if (nums1.size() > nums2.size()) + return intersect(nums2, nums1); + + vector ans; + unordered_map count; + + for (const int num : nums1) + ++count[num]; + + for (const int num : nums2) + if (const auto it = count.find(num); + it != count.cend() && it->second-- > 0) + ans.push_back(num); + + return ans; + } +}; diff --git a/solutions/350. Intersection of Two Arrays II/350.java b/solutions/350. Intersection of Two Arrays II/350.java new file mode 100644 index 00000000000..7956071326c --- /dev/null +++ b/solutions/350. Intersection of Two Arrays II/350.java @@ -0,0 +1,20 @@ +class Solution { + public int[] intersect(int[] nums1, int[] nums2) { + if (nums1.length > nums2.length) + return intersect(nums2, nums1); + + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + + for (final int num : nums1) + count.put(num, count.getOrDefault(num, 0) + 1); + + for (final int num : nums2) + if (count.containsKey(num) && count.get(num) > 0) { + ans.add(num); + count.put(num, count.get(num) - 1); + } + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/350. Intersection of Two Arrays II/350.py b/solutions/350. Intersection of Two Arrays II/350.py new file mode 100644 index 00000000000..389a18c03ed --- /dev/null +++ b/solutions/350. Intersection of Two Arrays II/350.py @@ -0,0 +1,14 @@ +class Solution: + def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: + if len(nums1) > len(nums2): + return self.intersect(nums2, nums1) + + ans = [] + count = collections.Counter(nums1) + + for num in nums2: + if count[num] > 0: + ans.append(num) + count[num] -= 1 + + return ans diff --git a/solutions/351. Android Unlock Patterns/351.cpp b/solutions/351. Android Unlock Patterns/351.cpp new file mode 100644 index 00000000000..e3c0e0fe4f8 --- /dev/null +++ b/solutions/351. Android Unlock Patterns/351.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + int numberOfPatterns(int m, int n) { + int ans = 0; + vector> across(10, vector(10)); + vector seen(10); + + across[1][3] = across[3][1] = 2; + across[1][7] = across[7][1] = 4; + across[3][9] = across[9][3] = 6; + across[7][9] = across[9][7] = 8; + across[1][9] = across[9][1] = across[2][8] = across[8][2] = across[3][7] = + across[7][3] = across[4][6] = across[6][4] = 5; + + ans += dfs(m, n, 1, 1, seen, across) * 4; // 1, 3, 7, 9 are symmetric + ans += dfs(m, n, 2, 1, seen, across) * 4; // 2, 4, 6, 8 are symmetric + ans += dfs(m, n, 5, 1, seen, across); // 5 + return ans; + } + + private: + int dfs(int m, int n, int u, int depth, vector& seen, + const vector>& across) { + if (depth > n) + return 0; + + seen[u] = true; + int ans = depth >= m ? 1 : 0; + + for (int v = 1; v <= 9; ++v) { + if (v == u || seen[v]) + continue; + const int acrossed = across[u][v]; + if (acrossed == 0 || seen[acrossed]) + ans += dfs(m, n, v, depth + 1, seen, across); + } + + seen[u] = false; + return ans; + } +}; diff --git a/solutions/351. Android Unlock Patterns/351.java b/solutions/351. Android Unlock Patterns/351.java new file mode 100644 index 00000000000..459501925f2 --- /dev/null +++ b/solutions/351. Android Unlock Patterns/351.java @@ -0,0 +1,38 @@ +class Solution { + public int numberOfPatterns(int m, int n) { + int ans = 0; + int[][] across = new int[10][10]; + boolean[] seen = new boolean[10]; + + across[1][3] = across[3][1] = 2; + across[1][7] = across[7][1] = 4; + across[3][9] = across[9][3] = 6; + across[7][9] = across[9][7] = 8; + across[1][9] = across[9][1] = across[2][8] = across[8][2] = across[3][7] = across[7][3] = + across[4][6] = across[6][4] = 5; + + ans += dfs(m, n, 1, 1, seen, across) * 4; // 1, 3, 7, 9 are symmetric + ans += dfs(m, n, 2, 1, seen, across) * 4; // 2, 4, 6, 8 are symmetric + ans += dfs(m, n, 5, 1, seen, across); // 5 + return ans; + } + + private int dfs(int m, int n, int u, int level, boolean[] seen, int[][] across) { + if (level > n) + return 0; + + seen[u] = true; + int ans = level >= m; + + for (int v = 1; v <= 9; ++v) { + if (v == u || seen[v]) + continue; + final int acrossed = across[u][v]; + if (acrossed == 0 || seen[acrossed]) + ans += dfs(m, n, v, level + 1, seen, across); + } + + seen[u] = false; + return ans; + } +} diff --git a/solutions/351. Android Unlock Patterns/351.py b/solutions/351. Android Unlock Patterns/351.py new file mode 100644 index 00000000000..47c625f8ee3 --- /dev/null +++ b/solutions/351. Android Unlock Patterns/351.py @@ -0,0 +1,32 @@ +class Solution: + def numberOfPatterns(self, m: int, n: int) -> int: + seen = set() + accross = [[0] * 10 for _ in range(10)] + + accross[1][3] = accross[3][1] = 2 + accross[1][7] = accross[7][1] = 4 + accross[3][9] = accross[9][3] = 6 + accross[7][9] = accross[9][7] = 8 + accross[1][9] = accross[9][1] = accross[2][8] = accross[8][2] = \ + accross[3][7] = accross[7][3] = accross[4][6] = accross[6][4] = 5 + + def dfs(u: int, depth: int) -> int: + if depth > n: + return 0 + + seen.add(u) + ans = 1 if depth >= m else 0 + + for v in range(1, 10): + if v == u or v in seen: + continue + accrossed = accross[u][v] + if not accrossed or accrossed in seen: + ans += dfs(v, depth + 1) + + seen.remove(u) + return ans + + # 1, 3, 7, 9 are symmetric + # 2, 4, 6, 8 are symmetric + return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1) diff --git a/solutions/352. Data Stream as Disjoint Intervals/352.cpp b/solutions/352. Data Stream as Disjoint Intervals/352.cpp new file mode 100644 index 00000000000..4d13ee0ab1c --- /dev/null +++ b/solutions/352. Data Stream as Disjoint Intervals/352.cpp @@ -0,0 +1,53 @@ +class SummaryRanges { + public: + void addNum(int val) { + if (intervals.contains(val)) + return; + + const int lo = lowerKey(val); + const int hi = higherKey(val); + + // {lo, intervals[lo][1]} + val + {hi, intervals[hi][1]} = {lo, + // intervals[hi][1]} + if (lo >= 0 && hi >= 0 && intervals[lo][1] + 1 == val && val + 1 == hi) { + intervals[lo][1] = intervals[hi][1]; + intervals.erase(hi); + // {lo, intervals[lo][1]} + val = {lo, val} + // Prevent adding duplicate entry by using '>=' instead of '=='. + } else if (lo >= 0 && intervals[lo][1] + 1 >= val) { + intervals[lo][1] = max(intervals[lo][1], val); + } else if (hi >= 0 && val + 1 == hi) { + // val + {hi, intervals[hi][1]} = {val, intervals[hi][1]} + intervals[val] = {val, intervals[hi][1]}; + intervals.erase(hi); + } else { + intervals[val] = {val, val}; + } + } + + vector> getIntervals() { + vector> res; + for (const auto& [_, interval] : intervals) + res.push_back(interval); + return res; + } + + private: + map> intervals; // {start: (start, end)} + + // Returns the maximum key in `intervals` < `key`. + int lowerKey(int key) { + auto it = intervals.lower_bound(key); + if (it == intervals.begin()) + return -1; + return (--it)->first; + } + + // Returns the minimum key in `intervals` > `key`. + int higherKey(int key) { + const auto it = intervals.upper_bound(key); + if (it == intervals.cend()) + return -1; + return it->first; + } +}; diff --git a/solutions/352. Data Stream as Disjoint Intervals/352.java b/solutions/352. Data Stream as Disjoint Intervals/352.java new file mode 100644 index 00000000000..bdde7183baf --- /dev/null +++ b/solutions/352. Data Stream as Disjoint Intervals/352.java @@ -0,0 +1,34 @@ +class SummaryRanges { + public void addNum(int val) { + if (intervals.containsKey(val)) + return; + + // the maximum key in `intervals` < `key` + final Integer lo = intervals.lowerKey(val); + // the minimum key in `intervals` > `key` + final Integer hi = intervals.higherKey(val); + + // {lo, intervals.get(lo)[1]} + val + {hi, intervals.get(hi)[1]} = {lo, intervals.get(hi)[1]} + if (lo != null && hi != null && intervals.get(lo)[1] + 1 == val && val + 1 == hi) { + intervals.get(lo)[1] = intervals.get(hi)[1]; + intervals.remove(hi); + // {lo, intervals.get(lo)[1]} + val = {lo, val} + // Prevent adding duplicate entry by using '>=' instead of '=='. + } else if (lo != null && intervals.get(lo)[1] + 1 >= val) { + intervals.get(lo)[1] = Math.max(intervals.get(lo)[1], val); + // val + {hi, intervals.get(hi)[1]} = {val, intervals.get(hi)[1]} + } else if (hi != null && val + 1 == hi) { + intervals.put(val, new int[] {val, intervals.get(hi)[1]}); + intervals.remove(hi); + } else { + intervals.put(val, new int[] {val, val}); + } + } + + public int[][] getIntervals() { + return intervals.values().stream().toArray(int[][] ::new); + } + + // {start: (start, end)} + private TreeMap intervals = new TreeMap<>(); +} diff --git a/solutions/352. Data Stream as Disjoint Intervals/352.py b/solutions/352. Data Stream as Disjoint Intervals/352.py new file mode 100644 index 00000000000..3b93ee63478 --- /dev/null +++ b/solutions/352. Data Stream as Disjoint Intervals/352.py @@ -0,0 +1,45 @@ +from sortedcontainers import SortedDict + + +class SummaryRanges: + def __init__(self): + self.intervals = SortedDict() # {start: (start, end)} + + def addNum(self, val: int) -> None: + if val in self.intervals: + return + + lo = self._lowerKey(val) + hi = self._higherKey(val) + + # {lo, map[lo][1]} + val + {hi, map[hi][1]} = {lo, map[hi][1]} + if lo >= 0 and hi >= 0 and self.intervals[lo][1] + 1 == val and val + 1 == hi: + self.intervals[lo][1] = self.intervals[hi][1] + del self.intervals[hi] + # {lo, map[lo][1]} + val = {lo, val} + # Prevent adding duplicate entry by using '>=' instead of '=='. + elif lo >= 0 and self.intervals[lo][1] + 1 >= val: + self.intervals[lo][1] = max(self.intervals[lo][1], val) + elif hi >= 0 and val + 1 == hi: + # val + {hi, map[hi][1]} = {val, map[hi][1]} + self.intervals[val] = [val, self.intervals[hi][1]] + del self.intervals[hi] + else: + self.intervals[val] = [val, val] + + def getIntervals(self) -> List[List[int]]: + return list(self.intervals.values()) + + def _lowerKey(self, key: int): + """Returns the maximum key in `self.intervals` < `key`.""" + i = self.intervals.bisect_left(key) + if i == 0: + return -1 + return self.intervals.peekitem(i - 1)[0] + + def _higherKey(self, key: int): + """Returns the minimum key in `self.intervals` < `key`.""" + i = self.intervals.bisect_right(key) + if i == len(self.intervals): + return -1 + return self.intervals.peekitem(i)[0] diff --git a/solutions/353. Design Snake Game/353.cpp b/solutions/353. Design Snake Game/353.cpp new file mode 100644 index 00000000000..bad1dc356fd --- /dev/null +++ b/solutions/353. Design Snake Game/353.cpp @@ -0,0 +1,70 @@ +class SnakeGame { + public: + /** Initialize your data structure here. + @param width - screen width + @param height - screen height + @param food - A list of food positions + E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the + second is at [1,0]. */ + SnakeGame(int width, int height, vector>& food) + : width(width), height(height), food(food) { + lookup.insert(getId(0, 0)); + body.push_back(getId(0, 0)); + } + + /** Moves the snake. + @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down + @return The game's score after the move. Return -1 if game over. + Game over when snake crosses the screen boundary or bites its body. */ + int move(string direction) { + // the old head's position + int i = body.front() / width; + int j = body.front() % width; + + // Update the head's position and check if it's out-of-bounds. + if (direction == "U" && --i < 0) + return -1; + if (direction == "L" && --j < 0) + return -1; + if (direction == "R" && ++j == width) + return -1; + if (direction == "D" && ++i == height) + return -1; + + const int newHead = getId(i, j); + + // 1. Eat food and increase the size by 1. + if (k < food.size() && i == food[k][0] && j == food[k][1]) { + lookup.insert(newHead); + body.push_front(newHead); + ++k; + return ++score; + } + + // 2. new head != old tail and eat body! + if (newHead != body.back() && lookup.contains(newHead)) + return -1; + + // 3. normal case + // Remove the old tail first, then add new head because new head may be in + // old tail's position. + lookup.erase(body.back()); + lookup.insert(newHead); + body.pop_back(); + body.push_front(newHead); + return score; + } + + private: + int width; + int height; + int score = 0; + int k = 0; // food's index + vector> food; + unordered_set lookup; + deque body; // snake's body + + int getId(int i, int j) { + return i * width + j; + } +}; diff --git a/solutions/353. Design Snake Game/353.java b/solutions/353. Design Snake Game/353.java new file mode 100644 index 00000000000..b3a9364ca9b --- /dev/null +++ b/solutions/353. Design Snake Game/353.java @@ -0,0 +1,75 @@ +class SnakeGame { + /** + * Initialize your data structure here. + * + * @param width - screen width + * @param height - screen height + * @param food - A list of food positions E.g food = [[1,1], [1,0]] means the + * first food is positioned at [1,1], the second is at [1,0]. + */ + public SnakeGame(int width, int height, int[][] food) { + this.width = width; + this.height = height; + this.food = food; + lookup.add(getId(0, 0)); + body.offerLast(getId(0, 0)); + } + + /** + * Moves the snake. + * + * @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down + * @return The game's score after the move. Return -1 if game over. Game over + * when snake crosses the screen boundary or bites its body. + */ + public int move(String direction) { + // the old head's position + int i = body.peekFirst() / width; + int j = body.peekFirst() % width; + + // Update the head's position and check if it's out-of-bounds. + if (direction.equals("U") && --i < 0) + return -1; + if (direction.equals("L") && --j < 0) + return -1; + if (direction.equals("R") && ++j == width) + return -1; + if (direction.equals("D") && ++i == height) + return -1; + + final int newHead = getId(i, j); + + // 1. Eat food and increase the size by 1. + if (k < food.length && i == food[k][0] && j == food[k][1]) { + lookup.add(newHead); + body.offerFirst(newHead); + ++k; + return ++score; + } + + // 2. new head != old tail and eat body! + if (newHead != body.peekLast() && lookup.contains(newHead)) + return -1; + + // 3. normal case + // Remove the old tail first, then add new head because new head may be in + // old tail's position. + lookup.remove(body.peekLast()); + lookup.add(newHead); + body.pollLast(); + body.offerFirst(newHead); + return score; + } + + private int width; + private int height; + private int score = 0; + private int k = 0; // food's index + private int[][] food; + private Set lookup = new HashSet<>(); + private Deque body = new ArrayDeque<>(); // snake's body + + private int getId(int i, int j) { + return i * width + j; + } +} diff --git a/solutions/353. Design Snake Game/353.py b/solutions/353. Design Snake Game/353.py new file mode 100644 index 00000000000..a8c448e5f9d --- /dev/null +++ b/solutions/353. Design Snake Game/353.py @@ -0,0 +1,72 @@ +class SnakeGame: + def __init__(self, width: int, height: int, food: List[List[int]]): + """ + Initialize your data structure here. + @param width - screen width + @param height - screen height + @param food - A list of food positions + E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. + """ + self.width = width + self.height = height + self.food = food + self.score = 0 + self.k = 0 # food's index + self.lookup = set([self.getId(0, 0)]) + self.body = collections.deque([self.getId(0, 0)]) # snake's body + + def move(self, direction: str) -> int: + """ + Moves the snake. + @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down + @return The game's score after the move. Return -1 if game over. + Game over when snake crosses the screen boundary or bites its body. + """ + # the old head's position + i = self.body[0] // self.width + j = self.body[0] % self.width + + # Update the head's position and check if it's out-of-bounds. + if direction == "U": + i -= 1 + if i < 0: + return -1 + if direction == "L": + j -= 1 + if j < 0: + return -1 + if direction == "R": + j += 1 + if j == self.width: + return -1 + if direction == "D": + i += 1 + if i == self.height: + return -1 + + newHead = self.getId(i, j) + + # 1. Eat food and increase the size by 1. + if self.k < len(self.food) and i == self.food[self.k][0] and j == self.food[self.k][1]: + self.lookup.add(newHead) + self.body.appendleft(newHead) + self.k += 1 + self.score += 1 + return self.score + + # 2. new head != old tail and eat body! + if newHead != self.body[-1] and newHead in self.lookup: + return -1 + + # 3. normal case + # Remove the old tail first, then add new head because new head may be in + # old tail's position. + self.lookup.remove(self.body[-1]) + self.lookup.add(newHead) + self.body.pop() + self.body.appendleft(newHead) + + return self.score + + def getId(self, i: int, j: int) -> int: + return i * self.width + j diff --git a/solutions/354. Russian Doll Envelopes/354.cpp b/solutions/354. Russian Doll Envelopes/354.cpp new file mode 100644 index 00000000000..21755faddbc --- /dev/null +++ b/solutions/354. Russian Doll Envelopes/354.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maxEnvelopes(vector>& envelopes) { + ranges::sort(envelopes, [](const auto& a, const auto& b) { + return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; + }); + + // Same as 300. Longest Increasing Subsequence + int ans = 0; + vector dp(envelopes.size()); + + for (const vector& e : envelopes) { + int l = 0; + int r = ans; + while (l < r) { + const int m = (l + r) / 2; + if (dp[m] >= e[1]) + r = m; + else + l = m + 1; + } + dp[l] = e[1]; + if (l == ans) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/354. Russian Doll Envelopes/354.java b/solutions/354. Russian Doll Envelopes/354.java new file mode 100644 index 00000000000..614afea0e6d --- /dev/null +++ b/solutions/354. Russian Doll Envelopes/354.java @@ -0,0 +1,20 @@ +class Solution { + public int maxEnvelopes(int[][] envelopes) { + Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + + // Same as 300. Longest Increasing Subsequence + int ans = 0; + int[] dp = new int[envelopes.length]; + + for (int[] e : envelopes) { + int i = Arrays.binarySearch(dp, 0, ans, e[1]); + if (i < 0) + i = -(i + 1); + dp[i] = e[1]; + if (i == ans) + ++ans; + } + + return ans; + } +} diff --git a/solutions/354. Russian Doll Envelopes/354.py b/solutions/354. Russian Doll Envelopes/354.py new file mode 100644 index 00000000000..878f69338a7 --- /dev/null +++ b/solutions/354. Russian Doll Envelopes/354.py @@ -0,0 +1,21 @@ +class Solution: + def maxEnvelopes(self, envelopes: List[List[int]]) -> int: + envelopes.sort(key=lambda x: (x[0], -x[1])) + # Same as 300. Longest Increasing Subsequence + ans = 0 + dp = [0] * len(envelopes) + + for _, h in envelopes: + l = 0 + r = ans + while l < r: + m = (l + r) // 2 + if dp[m] >= h: + r = m + else: + l = m + 1 + dp[l] = h + if l == ans: + ans += 1 + + return ans diff --git a/solutions/355. Design Twitter/355.cpp b/solutions/355. Design Twitter/355.cpp new file mode 100644 index 00000000000..af25f48fd82 --- /dev/null +++ b/solutions/355. Design Twitter/355.cpp @@ -0,0 +1,106 @@ +struct Tweet { + int id; + int time; + Tweet* next = nullptr; + Tweet(int id, int time) : id(id), time(time) {} +}; + +struct User { + int id; + unordered_set followeeIds; + Tweet* tweetHead = nullptr; + + User() {} + + User(int id) : id(id) { + follow(id); + } + + void follow(int followeeId) { + followeeIds.insert(followeeId); + } + + void unfollow(int followeeId) { + followeeIds.erase(followeeId); + } + + void post(int tweetId, int time) { + Tweet* oldTweetHead = tweetHead; + tweetHead = new Tweet(tweetId, time); + tweetHead->next = oldTweetHead; + } +}; + +class Twitter { + public: + /** Compose a new tweet. */ + void postTweet(int userId, int tweetId) { + if (!users.contains(userId)) + users[userId] = User(userId); + users[userId].post(tweetId, time++); + } + + /** + * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in + * the news feed must be posted by users who the user followed or by the user + * herself. Tweets must be ordered from most recent to least recent. + */ + vector getNewsFeed(int userId) { + if (!users.contains(userId)) + return {}; + + vector newsFeed; + + auto compare = [](const Tweet* a, const Tweet* b) { + return a->time < b->time; + }; + priority_queue, decltype(compare)> maxHeap(compare); + + for (const int followeeId : users[userId].followeeIds) { + Tweet* tweetHead = users[followeeId].tweetHead; + if (tweetHead != nullptr) + maxHeap.push(tweetHead); + } + + int count = 0; + while (!maxHeap.empty() && count++ < 10) { + Tweet* tweet = maxHeap.top(); + maxHeap.pop(); + newsFeed.push_back(tweet->id); + if (tweet->next) + maxHeap.push(tweet->next); + } + + return newsFeed; + } + + /** + * Follower follows a followee. + * If the operation is invalid, it should be a no-op. + */ + void follow(int followerId, int followeeId) { + if (followerId == followeeId) + return; + if (!users.contains(followerId)) + users[followerId] = User(followerId); + if (!users.contains(followeeId)) + users[followeeId] = User(followeeId); + users[followerId].follow(followeeId); + } + + /** + * Follower unfollows a followee. + * If the operation is invalid, it should be a no-op. + */ + void unfollow(int followerId, int followeeId) { + if (followerId == followeeId) + return; + if (const auto it = users.find(followerId); + it != users.cend() && users.contains(followeeId)) + it->second.unfollow(followeeId); + } + + private: + int time = 0; + unordered_map users; // {userId: User} +}; diff --git a/solutions/355. Design Twitter/355.java b/solutions/355. Design Twitter/355.java new file mode 100644 index 00000000000..a377ae822a8 --- /dev/null +++ b/solutions/355. Design Twitter/355.java @@ -0,0 +1,97 @@ +class Tweet { + public int id; + public int time; + public Tweet next = null; + public Tweet(int id, int time) { + this.id = id; + this.time = time; + } +} + +class User { + private int id; + public Set followeeIds = new HashSet<>(); + public Tweet tweetHead = null; + + public User(int id) { + this.id = id; + follow(id); + } + + public void follow(int followeeId) { + followeeIds.add(followeeId); + } + + public void unfollow(int followeeId) { + followeeIds.remove(followeeId); + } + + public void post(int tweetId, int time) { + final Tweet oldTweetHead = tweetHead; + tweetHead = new Tweet(tweetId, time); + tweetHead.next = oldTweetHead; + } +} + +class Twitter { + /** Compose a new tweet. */ + public void postTweet(int userId, int tweetId) { + users.putIfAbsent(userId, new User(userId)); + users.get(userId).post(tweetId, time++); + } + + /** + * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in + * the news feed must be posted by users who the user followed or by the user + * herself. Tweets must be ordered from most recent to least recent. + */ + public List getNewsFeed(int userId) { + if (!users.containsKey(userId)) + return new ArrayList<>(); + + List newsFeed = new ArrayList<>(); + Queue maxHeap = new PriorityQueue<>((a, b) -> b.time - a.time); + + for (final int followeeId : users.get(userId).followeeIds) { + Tweet tweetHead = users.get(followeeId).tweetHead; + if (tweetHead != null) + maxHeap.offer(tweetHead); + } + + int count = 0; + while (!maxHeap.isEmpty() && count++ < 10) { + Tweet tweet = maxHeap.poll(); + newsFeed.add(tweet.id); + if (tweet.next != null) + maxHeap.offer(tweet.next); + } + + return newsFeed; + } + + /** + * Follower follows a followee. + * If the operation is invalid, it should be a no-op. + */ + public void follow(int followerId, int followeeId) { + if (followerId == followeeId) + return; + users.putIfAbsent(followerId, new User(followerId)); + users.putIfAbsent(followeeId, new User(followeeId)); + users.get(followerId).follow(followeeId); + } + + /** + * Follower unfollows a followee. + * If the operation is invalid, it should be a no-op. + */ + public void unfollow(int followerId, int followeeId) { + if (followerId == followeeId) + return; + if (users.containsKey(followerId) && users.containsKey(followeeId)) + users.get(followerId).unfollow(followeeId); + } + + private int time = 0; + private Map users = new HashMap<>(); // {userId: User} +} diff --git a/solutions/355. Design Twitter/355.py b/solutions/355. Design Twitter/355.py new file mode 100644 index 00000000000..f16bd08e529 --- /dev/null +++ b/solutions/355. Design Twitter/355.py @@ -0,0 +1,21 @@ +class Twitter: + def __init__(self): + self.timer = itertools.count(step=-1) + self.tweets = collections.defaultdict(deque) + self.followees = collections.defaultdict(set) + + def postTweet(self, userId: int, tweetId: int) -> None: + self.tweets[userId].appendleft((next(self.timer), tweetId)) + if len(self.tweets[userId]) > 10: + self.tweets[userId].pop() + + def getNewsFeed(self, userId: int) -> List[int]: + tweets = list(heapq.merge( + *(self.tweets[followee] for followee in self.followees[userId] | {userId}))) + return [tweetId for _, tweetId in tweets[:10]] + + def follow(self, followerId: int, followeeId: int) -> None: + self.followees[followerId].add(followeeId) + + def unfollow(self, followerId: int, followeeId: int) -> None: + self.followees[followerId].discard(followeeId) diff --git a/solutions/356. Line Reflection/356.cpp b/solutions/356. Line Reflection/356.cpp new file mode 100644 index 00000000000..0d28608cb19 --- /dev/null +++ b/solutions/356. Line Reflection/356.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + bool isReflected(vector>& points) { + int minX = INT_MAX; + int maxX = INT_MIN; + unordered_set, PairHash> seen; + + for (const vector& p : points) { + const int x = p[0]; + const int y = p[1]; + minX = min(minX, x); + maxX = max(maxX, x); + seen.insert({x, y}); + } + + const int sum = minX + maxX; + // (leftX + rightX) / 2 = (minX + maxX) / 2 + // leftX = minX + maxX - rightX + // rightX = minX + maxX - leftX + + for (const vector& p : points) + if (!seen.contains({sum - p[0], p[1]})) + return false; + + return true; + } + + private: + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/356. Line Reflection/356.java b/solutions/356. Line Reflection/356.java new file mode 100644 index 00000000000..3a908dd3e5d --- /dev/null +++ b/solutions/356. Line Reflection/356.java @@ -0,0 +1,26 @@ +class Solution { + public boolean isReflected(int[][] points) { + int minX = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + Set seen = new HashSet<>(); + + for (int[] p : points) { + final int x = p[0]; + final int y = p[1]; + minX = Math.min(minX, x); + maxX = Math.max(maxX, x); + seen.add(x + "," + y); + } + + final int sum = minX + maxX; + // (leftX + rightX) / 2 = (minX + maxX) / 2 + // leftX = minX + maxX - rightX + // rightX = minX + maxX - leftX + + for (int[] p : points) + if (!seen.contains(sum - p[0] + "," + p[1])) + return false; + + return true; + } +} diff --git a/solutions/356. Line Reflection/356.py b/solutions/356. Line Reflection/356.py new file mode 100644 index 00000000000..f09a767d544 --- /dev/null +++ b/solutions/356. Line Reflection/356.py @@ -0,0 +1,17 @@ +class Solution: + def isReflected(self, points: List[List[int]]) -> bool: + minX = math.inf + maxX = -math.inf + seen = set() + + for x, y in points: + minX = min(minX, x) + maxX = max(maxX, x) + seen.add((x, y)) + + summ = minX + maxX + # (leftX + rightX) / 2 = (minX + maxX) / 2 + # leftX = minX + maxX - rightX + # rightX = minX + maxX - leftX + + return all((summ - x, y) in seen for x, y in points) diff --git a/solutions/357. Count Numbers with Unique Digits/357.cpp b/solutions/357. Count Numbers with Unique Digits/357.cpp new file mode 100644 index 00000000000..e244ce9693e --- /dev/null +++ b/solutions/357. Count Numbers with Unique Digits/357.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countNumbersWithUniqueDigits(int n) { + if (n == 0) + return 1; + + int ans = 10; + int uniqueDigits = 9; + + for (int availableNum = 9; n > 1 && availableNum > 0; --n, --availableNum) { + uniqueDigits *= availableNum; + ans += uniqueDigits; + } + + return ans; + } +}; diff --git a/solutions/357. Count Numbers with Unique Digits/357.java b/solutions/357. Count Numbers with Unique Digits/357.java new file mode 100644 index 00000000000..e0a8b101233 --- /dev/null +++ b/solutions/357. Count Numbers with Unique Digits/357.java @@ -0,0 +1,16 @@ +class Solution { + public int countNumbersWithUniqueDigits(int n) { + if (n == 0) + return 1; + + int ans = 10; + int uniqueDigits = 9; + + for (int availableNum = 9; n > 1 && availableNum > 0; --n, --availableNum) { + uniqueDigits *= availableNum; + ans += uniqueDigits; + } + + return ans; + } +} diff --git a/solutions/357. Count Numbers with Unique Digits/357.py b/solutions/357. Count Numbers with Unique Digits/357.py new file mode 100644 index 00000000000..c6e1df2d31d --- /dev/null +++ b/solutions/357. Count Numbers with Unique Digits/357.py @@ -0,0 +1,16 @@ +class Solution: + def countNumbersWithUniqueDigits(self, n: int) -> int: + if n == 0: + return 1 + + ans = 10 + uniqueDigits = 9 + availableNum = 9 + + while n > 1 and availableNum > 0: + uniqueDigits *= availableNum + ans += uniqueDigits + n -= 1 + availableNum -= 1 + + return ans diff --git a/solutions/358. Rearrange String k Distance Apart/358.cpp b/solutions/358. Rearrange String k Distance Apart/358.cpp new file mode 100644 index 00000000000..2311b4cde52 --- /dev/null +++ b/solutions/358. Rearrange String k Distance Apart/358.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + string rearrangeString(string s, int k) { + const int n = s.length(); + string ans; + vector count(26); + // valid[i] := the leftmost index ('a' + i) can appear + vector valid(26); + + for (const char c : s) + ++count[c - 'a']; + + for (int i = 0; i < n; ++i) { + const char c = getBestLetter(count, valid, i); + if (c == '*') + return ""; + ans += c; + --count[c - 'a']; + valid[c - 'a'] = i + k; + } + + return ans; + } + + private: + // Returns the valid letter that has the most count. + char getBestLetter(const vector& count, const vector& valid, + int index) { + int maxCount = -1; + char bestLetter = '*'; + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c - 'a'] > 0 && count[c - 'a'] > maxCount && + index >= valid[c - 'a']) { + bestLetter = c; + maxCount = count[c - 'a']; + } + + return bestLetter; + } +}; diff --git a/solutions/358. Rearrange String k Distance Apart/358.java b/solutions/358. Rearrange String k Distance Apart/358.java new file mode 100644 index 00000000000..383af0f03f9 --- /dev/null +++ b/solutions/358. Rearrange String k Distance Apart/358.java @@ -0,0 +1,37 @@ +class Solution { + public String rearrangeString(String s, int k) { + final int n = s.length(); + StringBuilder sb = new StringBuilder(); + int[] count = new int[26]; + // valid[i] := the leftmost index character i can appear + int[] valid = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (int i = 0; i < n; ++i) { + final char c = getBestLetter(count, valid, i); + if (c == '*') + return ""; + sb.append(c); + --count[c - 'a']; + valid[c - 'a'] = i + k; + } + + return sb.toString(); + } + + // Returns the valid letter that has the most count. + private char getBestLetter(int[] count, int[] valid, int index) { + int maxCount = -1; + char bestLetter = '*'; + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c - 'a'] > 0 && count[c - 'a'] > maxCount && index >= valid[c - 'a']) { + bestLetter = c; + maxCount = count[c - 'a']; + } + + return bestLetter; + } +} diff --git a/solutions/358. Rearrange String k Distance Apart/358.py b/solutions/358. Rearrange String k Distance Apart/358.py new file mode 100644 index 00000000000..4034a1e1477 --- /dev/null +++ b/solutions/358. Rearrange String k Distance Apart/358.py @@ -0,0 +1,29 @@ +class Solution: + def rearrangeString(self, s: str, k: int) -> str: + n = len(s) + ans = [] + count = collections.Counter(s) + # valid[i] := the leftmost index i can appear + valid = collections.Counter() + + def getBestLetter(index: int) -> chr: + """Returns the valid letter that has the most count.""" + maxCount = -1 + bestLetter = '*' + + for c in string.ascii_lowercase: + if count[c] > 0 and count[c] > maxCount and index >= valid[c]: + bestLetter = c + maxCount = count[c] + + return bestLetter + + for i in range(n): + c = getBestLetter(i) + if c == '*': + return '' + ans.append(c) + count[c] -= 1 + valid[c] = i + k + + return ''.join(ans) diff --git a/solutions/359. Logger Rate Limiter/359-2.cpp b/solutions/359. Logger Rate Limiter/359-2.cpp new file mode 100644 index 00000000000..40f11b3fee0 --- /dev/null +++ b/solutions/359. Logger Rate Limiter/359-2.cpp @@ -0,0 +1,13 @@ +class Logger { + public: + bool shouldPrintMessage(int timestamp, string message) { + if (timestamp < okTime[message]) + return false; + + okTime[message] = timestamp + 10; + return true; + } + + private: + unordered_map okTime; // {message: ok time} +}; diff --git a/solutions/359. Logger Rate Limiter/359-2.java b/solutions/359. Logger Rate Limiter/359-2.java new file mode 100644 index 00000000000..de3610412a5 --- /dev/null +++ b/solutions/359. Logger Rate Limiter/359-2.java @@ -0,0 +1,11 @@ +class Logger { + public boolean shouldPrintMessage(int timestamp, String message) { + if (timestamp < okTime.getOrDefault(message, 0)) + return false; + + okTime.put(message, timestamp + 10); + return true; + } + + private Map okTime = new HashMap<>(); // {message: ok time} +} diff --git a/solutions/359. Logger Rate Limiter/359-2.py b/solutions/359. Logger Rate Limiter/359-2.py new file mode 100644 index 00000000000..e70f9bc8bcd --- /dev/null +++ b/solutions/359. Logger Rate Limiter/359-2.py @@ -0,0 +1,10 @@ +class Logger: + def __init__(self): + self.okTime = {} # {message: ok time} + + def shouldPrintMessage(self, timestamp: int, message: str) -> bool: + if timestamp < self.okTime.get(message, 0): + return False + + self.okTime[message] = timestamp + 10 + return True diff --git a/solutions/359. Logger Rate Limiter/359.cpp b/solutions/359. Logger Rate Limiter/359.cpp new file mode 100644 index 00000000000..fef01f7b903 --- /dev/null +++ b/solutions/359. Logger Rate Limiter/359.cpp @@ -0,0 +1,25 @@ +class Logger { + public: + bool shouldPrintMessage(int timestamp, string message) { + // Remove the messages that are 10 seconds from the current timestamp. + while (!messageQueue.empty()) { + const auto [headTimestamp, headMessage] = messageQueue.front(); + if (timestamp < headTimestamp + 10) + break; + messageQueue.pop_front(); + messageSet.erase(headMessage); + } + + if (messageSet.contains(message)) + return false; + + messageQueue.emplace_back(timestamp, message); + messageSet.insert(message); + return true; + } + + private: + // [(timestamp, message)] + deque> messageQueue; + unordered_set messageSet; +}; diff --git a/solutions/359. Logger Rate Limiter/359.java b/solutions/359. Logger Rate Limiter/359.java new file mode 100644 index 00000000000..d3abf817671 --- /dev/null +++ b/solutions/359. Logger Rate Limiter/359.java @@ -0,0 +1,23 @@ +class Logger { + public boolean shouldPrintMessage(int timestamp, String message) { + // Remove the messages that are 10 seconds from the current timestamp. + while (!messageQueue.isEmpty()) { + Pair head = messageQueue.peekFirst(); + if (timestamp - head.getKey() < 10) + break; + messageQueue.pollFirst(); + messageSet.remove(head.getValue()); + } + + if (messageSet.contains(message)) + return false; + + messageQueue.offerLast(new Pair<>(timestamp, message)); + messageSet.add(message); + return true; + } + + // [(timestamp, message)] + private Deque> messageQueue = new ArrayDeque<>(); + private Set messageSet = new HashSet<>(); +} diff --git a/solutions/359. Logger Rate Limiter/359.py b/solutions/359. Logger Rate Limiter/359.py new file mode 100644 index 00000000000..38924ace42f --- /dev/null +++ b/solutions/359. Logger Rate Limiter/359.py @@ -0,0 +1,21 @@ +class Logger: + def __init__(self): + # [(timestamp, message)] + self.messageQueue = collections.deque() + self.messageSet = set() + + def shouldPrintMessage(self, timestamp: int, message: str) -> bool: + # Remove the messages that are 10 seconds from the current timestamp. + while self.messageQueue: + headTimestamp, headMessage = self.messageQueue[0] + if timestamp < headTimestamp + 10: + break + self.messageQueue.popleft() + self.messageSet.remove(headMessage) + + if message in self.messageSet: + return False + + self.messageQueue.append((timestamp, message)) + self.messageSet.add(message) + return True diff --git a/solutions/36. Valid Sudoku/36.cpp b/solutions/36. Valid Sudoku/36.cpp new file mode 100644 index 00000000000..36506b8694d --- /dev/null +++ b/solutions/36. Valid Sudoku/36.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool isValidSudoku(vector>& board) { + unordered_set seen; + + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 9; ++j) { + if (board[i][j] == '.') + continue; + const string c(1, board[i][j]); + if (!seen.insert(c + "@row" + to_string(i)).second || + !seen.insert(c + "@col" + to_string(j)).second || + !seen.insert(c + "@box" + to_string(i / 3) + to_string(j / 3)) + .second) + return false; + } + + return true; + } +}; diff --git a/solutions/36. Valid Sudoku/36.java b/solutions/36. Valid Sudoku/36.java new file mode 100644 index 00000000000..5a09ba09c07 --- /dev/null +++ b/solutions/36. Valid Sudoku/36.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isValidSudoku(char[][] board) { + Set seen = new HashSet<>(); + + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 9; ++j) { + if (board[i][j] == '.') + continue; + final char c = board[i][j]; + if (!seen.add(c + "@row" + i) || // + !seen.add(c + "@col" + j) || // + !seen.add(c + "@box" + i / 3 + j / 3)) + return false; + } + + return true; + } +} diff --git a/solutions/36. Valid Sudoku/36.py b/solutions/36. Valid Sudoku/36.py new file mode 100644 index 00000000000..e97de64622f --- /dev/null +++ b/solutions/36. Valid Sudoku/36.py @@ -0,0 +1,18 @@ +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + seen = set() + + for i in range(9): + for j in range(9): + c = board[i][j] + if c == '.': + continue + if c + '@row ' + str(i) in seen or \ + c + '@col ' + str(j) in seen or \ + c + '@box ' + str(i // 3) + str(j // 3) in seen: + return False + seen.add(c + '@row ' + str(i)) + seen.add(c + '@col ' + str(j)) + seen.add(c + '@box ' + str(i // 3) + str(j // 3)) + + return True diff --git a/solutions/360. Sort Transformed Array/360.cpp b/solutions/360. Sort Transformed Array/360.cpp new file mode 100644 index 00000000000..92a8fa62688 --- /dev/null +++ b/solutions/360. Sort Transformed Array/360.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector sortTransformedArray(vector& nums, int a, int b, int c) { + const int n = nums.size(); + const bool upward = a > 0; + vector ans(n); + vector quad; + + for (const int num : nums) + quad.push_back(f(num, a, b, c)); + + int i = upward ? n - 1 : 0; + for (int l = 0, r = n - 1; l <= r;) + if (upward) // is the maximum in the both ends + ans[i--] = quad[l] > quad[r] ? quad[l++] : quad[r--]; + else // is the minimum in the both ends + ans[i++] = quad[l] < quad[r] ? quad[l++] : quad[r--]; + + return ans; + } + + private: + // The concavity of f only depends on a's sign. + int f(int x, int a, int b, int c) { + return (a * x + b) * x + c; + } +}; diff --git a/solutions/360. Sort Transformed Array/360.java b/solutions/360. Sort Transformed Array/360.java new file mode 100644 index 00000000000..044b590ec36 --- /dev/null +++ b/solutions/360. Sort Transformed Array/360.java @@ -0,0 +1,25 @@ +class Solution { + public int[] sortTransformedArray(int[] nums, int a, int b, int c) { + final int n = nums.length; + final boolean upward = a > 0; + int[] ans = new int[n]; + int[] quad = new int[n]; + + for (int i = 0; i < nums.length; ++i) + quad[i] = f(nums[i], a, b, c); + + int i = upward ? n - 1 : 0; + for (int l = 0, r = n - 1; l <= r;) + if (upward) // is the maximum in the both ends + ans[i--] = quad[l] > quad[r] ? quad[l++] : quad[r--]; + else // is the minimum in the both ends + ans[i++] = quad[l] < quad[r] ? quad[l++] : quad[r--]; + + return ans; + } + + // The concavity of f only depends on a's sign. + private int f(int x, int a, int b, int c) { + return (a * x + b) * x + c; + } +} diff --git a/solutions/360. Sort Transformed Array/360.py b/solutions/360. Sort Transformed Array/360.py new file mode 100644 index 00000000000..ff060246438 --- /dev/null +++ b/solutions/360. Sort Transformed Array/360.py @@ -0,0 +1,34 @@ +class Solution: + def sortTransformedArray(self, nums: List[int], a: int, b: int, c: int) -> List[int]: + n = len(nums) + upward = a > 0 + ans = [0] * n + + # The concavity of f only depends on a's sign. + def f(x: int, a: int, b: int, c: int) -> int: + return (a * x + b) * x + c + + quad = [f(num, a, b, c) for num in nums] + + i = n - 1 if upward else 0 + l = 0 + r = n - 1 + while l <= r: + if upward: # is the maximum in the both ends + if quad[l] > quad[r]: + ans[i] = quad[l] + l += 1 + else: + ans[i] = quad[r] + r -= 1 + i -= 1 + else: # is the minimum in the both ends + if quad[l] < quad[r]: + ans[i] = quad[l] + l += 1 + else: + ans[i] = quad[r] + r -= 1 + i += 1 + + return ans diff --git a/solutions/361. Bomb Enemy/361.cpp b/solutions/361. Bomb Enemy/361.cpp new file mode 100644 index 00000000000..5f974971c51 --- /dev/null +++ b/solutions/361. Bomb Enemy/361.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int maxKilledEnemies(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int enemyCount = 0; + // dp[i][j] := the maximum enemies grid[i][j] can kill + vector> dp(m, vector(n)); + + auto update = [&](int i, int j) { + if (grid[i][j] == '0') + dp[i][j] += enemyCount; + else if (grid[i][j] == 'E') + ++enemyCount; + else // grid[i][j] == 'W' + enemyCount = 0; + }; + + // Extend the four directions, if meet 'W', need to start over from 0. + for (int i = 0; i < m; ++i) { + enemyCount = 0; + for (int j = 0; j < n; ++j) + update(i, j); + enemyCount = 0; + for (int j = n - 1; j >= 0; --j) + update(i, j); + } + + for (int j = 0; j < n; ++j) { + enemyCount = 0; + for (int i = 0; i < m; ++i) + update(i, j); + enemyCount = 0; + for (int i = m - 1; i >= 0; --i) + update(i, j); + } + + return accumulate(dp.begin(), dp.end(), 0, + [](int subtotal, const vector& row) { + return max(subtotal, ranges::max(row)); + }); + } +}; diff --git a/solutions/361. Bomb Enemy/361.java b/solutions/361. Bomb Enemy/361.java new file mode 100644 index 00000000000..9bfa4fc8c3d --- /dev/null +++ b/solutions/361. Bomb Enemy/361.java @@ -0,0 +1,43 @@ +class Solution { + public int maxKilledEnemies(char[][] grid) { + if (grid.length == 0 || grid[0].length == 0) + return 0; + + final int m = grid.length; + final int n = grid[0].length; + // dp[i][j] := the maximum enemies grid[i][j] can kill + int[][] dp = new int[m][n]; + + // Extend the four directions, if meet 'W', need to start over from 0. + for (int i = 0; i < m; ++i) { + enemyCount = 0; + for (int j = 0; j < n; ++j) + update(grid, i, j, dp); + enemyCount = 0; + for (int j = n - 1; j >= 0; --j) + update(grid, i, j, dp); + } + + for (int j = 0; j < n; ++j) { + enemyCount = 0; + for (int i = 0; i < m; ++i) + update(grid, i, j, dp); + enemyCount = 0; + for (int i = m - 1; i >= 0; --i) + update(grid, i, j, dp); + } + + return Arrays.stream(dp).flatMapToInt(Arrays::stream).max().getAsInt(); + } + + private int enemyCount = 0; + + private void update(char[][] grid, int i, int j, int[][] dp) { + if (grid[i][j] == '0') + dp[i][j] += enemyCount; + else if (grid[i][j] == 'E') + ++enemyCount; + else // grid[i][j] == 'W' + enemyCount = 0; + } +} diff --git a/solutions/361. Bomb Enemy/361.py b/solutions/361. Bomb Enemy/361.py new file mode 100644 index 00000000000..2447e45493e --- /dev/null +++ b/solutions/361. Bomb Enemy/361.py @@ -0,0 +1,36 @@ +class Solution: + def maxKilledEnemies(self, grid: List[List[chr]]) -> int: + m = len(grid) + n = len(grid[0]) + enemyCount = 0 + # dp[i][j] := the maximum enemies grid[i][j] can kill + dp = [[0] * n for _ in range(m)] + + def update(i: int, j: int) -> None: + nonlocal enemyCount + if grid[i][j] == '0': + dp[i][j] += enemyCount + elif grid[i][j] == 'E': + enemyCount += 1 + else: # grid[i][j] == 'W' + enemyCount = 0 + + # Extend the four directions, if meet 'W', need to start over from 0. + for i in range(m): + enemyCount = 0 + for j in range(n): + update(i, j) + enemyCount = 0 + for j in reversed(range(n)): + update(i, j) + + for j in range(n): + enemyCount = 0 + for i in range(m): + update(i, j) + enemyCount = 0 + for i in reversed(range(m)): + update(i, j) + + # Returns sum(map(sum, dp)) + return max(map(max, dp)) diff --git a/solutions/362. Design Hit Counter/362.cpp b/solutions/362. Design Hit Counter/362.cpp new file mode 100644 index 00000000000..d6f9c0b5744 --- /dev/null +++ b/solutions/362. Design Hit Counter/362.cpp @@ -0,0 +1,24 @@ +class HitCounter { + public: + void hit(int timestamp) { + const int i = timestamp % 300; + if (timestamps[i] == timestamp) { + ++hits[i]; + } else { + timestamps[i] = timestamp; + hits[i] = 1; // Reset the hit count to 1. + } + } + + int getHits(int timestamp) { + int countHits = 0; + for (int i = 0; i < 300; ++i) + if (timestamp - timestamps[i] < 300) + countHits += hits[i]; + return countHits; + } + + private: + vector timestamps = vector(300); + vector hits = vector(300); +}; diff --git a/solutions/362. Design Hit Counter/362.java b/solutions/362. Design Hit Counter/362.java new file mode 100644 index 00000000000..da01c79a5b4 --- /dev/null +++ b/solutions/362. Design Hit Counter/362.java @@ -0,0 +1,22 @@ +class HitCounter { + public void hit(int timestamp) { + final int i = timestamp % 300; + if (timestamps[i] == timestamp) { + ++hits[i]; + } else { + timestamps[i] = timestamp; + hits[i] = 1; // Reset the hit count to 1. + } + } + + public int getHits(int timestamp) { + int countHits = 0; + for (int i = 0; i < 300; ++i) + if (timestamp - timestamps[i] < 300) + countHits += hits[i]; + return countHits; + } + + private int[] timestamps = new int[300]; + private int[] hits = new int[300]; +} diff --git a/solutions/362. Design Hit Counter/362.py b/solutions/362. Design Hit Counter/362.py new file mode 100644 index 00000000000..8c9e5ec371c --- /dev/null +++ b/solutions/362. Design Hit Counter/362.py @@ -0,0 +1,15 @@ +class HitCounter: + def __init__(self): + self.timestamps = [0] * 300 + self.hits = [0] * 300 + + def hit(self, timestamp: int) -> None: + i = timestamp % 300 + if self.timestamps[i] == timestamp: + self.hits[i] += 1 + else: + self.timestamps[i] = timestamp + self.hits[i] = 1 # Reset the hit count to 1. + + def getHits(self, timestamp: int) -> int: + return sum(h for t, h in zip(self.timestamps, self.hits) if timestamp - t < 300) diff --git a/solutions/363. Max Sum of Rectangle No Larger Than K/363.cpp b/solutions/363. Max Sum of Rectangle No Larger Than K/363.cpp new file mode 100644 index 00000000000..23220a2e6f1 --- /dev/null +++ b/solutions/363. Max Sum of Rectangle No Larger Than K/363.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int maxSumSubmatrix(vector>& matrix, int k) { + const int m = matrix.size(); + const int n = matrix[0].size(); + int ans = INT_MIN; + + for (int baseCol = 0; baseCol < n; ++baseCol) { + // sums[i] := sum(matrix[i][baseCol..j]) + vector sums(m, 0); + for (int j = baseCol; j < n; ++j) { + for (int i = 0; i < m; ++i) + sums[i] += matrix[i][j]; + // Find the maximum sum <= k of all the subarrays. + set accumulate{0}; + int prefix = 0; + for (const int sum : sums) { + prefix += sum; + if (const auto it = accumulate.lower_bound(prefix - k); + it != accumulate.cend()) + ans = max(ans, prefix - *it); + accumulate.insert(prefix); + } + } + } + + return ans; + } +}; diff --git a/solutions/363. Max Sum of Rectangle No Larger Than K/363.java b/solutions/363. Max Sum of Rectangle No Larger Than K/363.java new file mode 100644 index 00000000000..af6bfce1d0a --- /dev/null +++ b/solutions/363. Max Sum of Rectangle No Larger Than K/363.java @@ -0,0 +1,28 @@ +class Solution { + public int maxSumSubmatrix(int[][] matrix, int k) { + final int m = matrix.length; + final int n = matrix[0].length; + int ans = Integer.MIN_VALUE; + + for (int baseCol = 0; baseCol < n; ++baseCol) { + // sums[i] := sum(matrix[i][baseCol..j]) + int[] sums = new int[m]; + for (int j = baseCol; j < n; ++j) { + for (int i = 0; i < m; ++i) + sums[i] += matrix[i][j]; + // Find the maximum sum <= k of all the subarrays. + TreeSet accumulate = new TreeSet<>(Arrays.asList(0)); + int prefix = 0; + for (final int sum : sums) { + prefix += sum; + final Integer lo = accumulate.ceiling(prefix - k); + if (lo != null) + ans = Math.max(ans, prefix - lo); + accumulate.add(prefix); + } + } + } + + return ans; + } +} diff --git a/solutions/363. Max Sum of Rectangle No Larger Than K/363.py b/solutions/363. Max Sum of Rectangle No Larger Than K/363.py new file mode 100644 index 00000000000..60b4c8a1cd8 --- /dev/null +++ b/solutions/363. Max Sum of Rectangle No Larger Than K/363.py @@ -0,0 +1,26 @@ +from sortedcontainers import SortedList + + +class Solution: + def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: + m = len(matrix) + n = len(matrix[0]) + ans = -math.inf + + for baseCol in range(n): + # sums[i] := sum(matrix[i][baseCol..j]) + sums = [0] * m + for j in range(baseCol, n): + for i in range(m): + sums[i] += matrix[i][j] + # Find the maximum sum <= k of all the subarrays. + accumulate = SortedList([0]) + prefix = 0 + for summ in sums: + prefix += summ + it = accumulate.bisect_left(prefix - k) + if it != len(accumulate): + ans = max(ans, prefix - accumulate[it]) + accumulate.add(prefix) + + return ans diff --git a/solutions/364. Nested List Weight Sum II/364.cpp b/solutions/364. Nested List Weight Sum II/364.cpp new file mode 100644 index 00000000000..4ae23c7a08e --- /dev/null +++ b/solutions/364. Nested List Weight Sum II/364.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int depthSumInverse(vector& nestedList) { + int ans = 0; + int prevSum = 0; + queue q{{nestedList.begin(), nestedList.end()}}; + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const NestedInteger ni = q.front(); + q.pop(); + if (ni.isInteger()) + prevSum += ni.getInteger(); + else { + for (const NestedInteger nextNi : ni.getList()) + q.push(nextNi); + } + } + ans += prevSum; + } + + return ans; + } +}; diff --git a/solutions/364. Nested List Weight Sum II/364.java b/solutions/364. Nested List Weight Sum II/364.java new file mode 100644 index 00000000000..af02b788d16 --- /dev/null +++ b/solutions/364. Nested List Weight Sum II/364.java @@ -0,0 +1,20 @@ +class Solution { + public int depthSumInverse(List nestedList) { + int ans = 0; + int prevSum = 0; + Queue q = new ArrayDeque<>(nestedList); + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final NestedInteger ni = q.poll(); + if (ni.isInteger()) + prevSum += ni.getInteger(); + else + q.addAll(ni.getList()); + } + ans += prevSum; + } + + return ans; + } +} diff --git a/solutions/364. Nested List Weight Sum II/364.py b/solutions/364. Nested List Weight Sum II/364.py new file mode 100644 index 00000000000..40420bc503d --- /dev/null +++ b/solutions/364. Nested List Weight Sum II/364.py @@ -0,0 +1,17 @@ +class Solution: + def depthSumInverse(self, nestedList: List[NestedInteger]) -> int: + ans = 0 + prevSum = 0 + q = collections.deque(nestedList) + + while q: + for _ in range(len(q)): + ni = q.popleft() + if ni.isInteger(): + prevSum += ni.getInteger() + else: + for nextNi in ni.getList(): + q.append(nextNi) + ans += prevSum + + return ans diff --git a/solutions/365. Water and Jug Problem/365.cpp b/solutions/365. Water and Jug Problem/365.cpp new file mode 100644 index 00000000000..32f3aa19af0 --- /dev/null +++ b/solutions/365. Water and Jug Problem/365.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { + return targetCapacity == 0 || + jug1Capacity + jug2Capacity >= targetCapacity && + targetCapacity % __gcd(jug1Capacity, jug2Capacity) == 0; + } +}; diff --git a/solutions/365. Water and Jug Problem/365.java b/solutions/365. Water and Jug Problem/365.java new file mode 100644 index 00000000000..e814d606a86 --- /dev/null +++ b/solutions/365. Water and Jug Problem/365.java @@ -0,0 +1,10 @@ +class Solution { + public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { + return targetCapacity == 0 || jug1Capacity + jug2Capacity >= targetCapacity && + targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/365. Water and Jug Problem/365.py b/solutions/365. Water and Jug Problem/365.py new file mode 100644 index 00000000000..def40137cbb --- /dev/null +++ b/solutions/365. Water and Jug Problem/365.py @@ -0,0 +1,5 @@ +class Solution: + def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool: + return targetCapacity == 0 or \ + jug1Capacity + jug2Capacity >= targetCapacity and \ + targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 diff --git a/solutions/366. Find Leaves of Binary Tree/366.cpp b/solutions/366. Find Leaves of Binary Tree/366.cpp new file mode 100644 index 00000000000..7a98d770463 --- /dev/null +++ b/solutions/366. Find Leaves of Binary Tree/366.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector> findLeaves(TreeNode* root) { + vector> ans; + depth(root, ans); + return ans; + } + + private: + // Returns the depth of the root (0-indexed). + int depth(TreeNode* root, vector>& ans) { + if (root == nullptr) + return -1; + + const int l = depth(root->left, ans); + const int r = depth(root->right, ans); + const int h = 1 + max(l, r); + if (ans.size() == h) // Meet a leaf. + ans.push_back({}); + + ans[h].push_back(root->val); + return h; + } +}; diff --git a/solutions/366. Find Leaves of Binary Tree/366.java b/solutions/366. Find Leaves of Binary Tree/366.java new file mode 100644 index 00000000000..86e53801f0f --- /dev/null +++ b/solutions/366. Find Leaves of Binary Tree/366.java @@ -0,0 +1,22 @@ +class Solution { + public List> findLeaves(TreeNode root) { + List> ans = new ArrayList<>(); + depth(root, ans); + return ans; + } + + // Returns the depth of the root (0-indexed). + private int depth(TreeNode root, List> ans) { + if (root == null) + return -1; + + final int l = depth(root.left, ans); + final int r = depth(root.right, ans); + final int h = 1 + Math.max(l, r); + if (ans.size() == h) // Meet a leaf. + ans.add(new ArrayList<>()); + + ans.get(h).add(root.val); + return h; + } +} diff --git a/solutions/366. Find Leaves of Binary Tree/366.py b/solutions/366. Find Leaves of Binary Tree/366.py new file mode 100644 index 00000000000..c43b9abb33c --- /dev/null +++ b/solutions/366. Find Leaves of Binary Tree/366.py @@ -0,0 +1,21 @@ +class Solution: + def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]: + ans = [] + + def depth(root: Optional[TreeNode]) -> int: + """Returns the depth of the root (0-indexed).""" + if not root: + return -1 + + l = depth(root.left) + r = depth(root.right) + h = 1 + max(l, r) + + if len(ans) == h: # Meet a leaf + ans.append([]) + + ans[h].append(root.val) + return h + + depth(root) + return ans diff --git a/solutions/367. Valid Perfect Square/367.cpp b/solutions/367. Valid Perfect Square/367.cpp new file mode 100644 index 00000000000..d6546beb3eb --- /dev/null +++ b/solutions/367. Valid Perfect Square/367.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool isPerfectSquare(int num) { + long l = 1; + long r = num; + + while (l < r) { + const long m = (l + r) / 2; + if (m >= num / m) + r = m; + else + l = m + 1; + } + + return l * l == num; + } +}; diff --git a/solutions/367. Valid Perfect Square/367.java b/solutions/367. Valid Perfect Square/367.java new file mode 100644 index 00000000000..76c6c516e6f --- /dev/null +++ b/solutions/367. Valid Perfect Square/367.java @@ -0,0 +1,16 @@ +class Solution { + public boolean isPerfectSquare(int num) { + long l = 1; + long r = num; + + while (l < r) { + final long m = (l + r) / 2; + if (m >= num / m) + r = m; + else + l = m + 1; + } + + return l * l == num; + } +} diff --git a/solutions/367. Valid Perfect Square/367.py b/solutions/367. Valid Perfect Square/367.py new file mode 100644 index 00000000000..05ebdf8e9a1 --- /dev/null +++ b/solutions/367. Valid Perfect Square/367.py @@ -0,0 +1,5 @@ +class Solution: + def isPerfectSquare(self, num: int) -> bool: + l = bisect.bisect_left(range(num), num, + key=lambda m: m * m) + return l**2 == num diff --git a/solutions/368. Largest Divisible Subset/368.cpp b/solutions/368. Largest Divisible Subset/368.cpp new file mode 100644 index 00000000000..d53858109cb --- /dev/null +++ b/solutions/368. Largest Divisible Subset/368.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + vector largestDivisibleSubset(vector& nums) { + const int n = nums.size(); + vector ans; + // sizeEndsAt[i] := the maximum size ends in nums[i] + vector sizeEndsAt(n, 1); + // prevIndex[i] := the best index s.t. + // 1. nums[i] % nums[prevIndex[i]] == 0 and + // 2. can increase the size of the subset + vector prevIndex(n, -1); + int maxSize = 0; // Max size of the subset + int index = -1; // Track the best ending index + + ranges::sort(nums); + + // Fix the maximum ending number in the subset. + for (int i = 0; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) + if (nums[i] % nums[j] == 0 && sizeEndsAt[i] < sizeEndsAt[j] + 1) { + sizeEndsAt[i] = sizeEndsAt[j] + 1; + prevIndex[i] = j; + } + // Find a new subset that has a bigger size. + if (maxSize < sizeEndsAt[i]) { + maxSize = sizeEndsAt[i]; + index = i; // Update the best ending index. + } + } + + // Loop from the back to the front. + while (index != -1) { + ans.push_back(nums[index]); + index = prevIndex[index]; + } + + return ans; + } +}; diff --git a/solutions/368. Largest Divisible Subset/368.java b/solutions/368. Largest Divisible Subset/368.java new file mode 100644 index 00000000000..50a38c33c91 --- /dev/null +++ b/solutions/368. Largest Divisible Subset/368.java @@ -0,0 +1,40 @@ +class Solution { + public List largestDivisibleSubset(int[] nums) { + final int n = nums.length; + List ans = new ArrayList<>(); + // sizeEndsAt[i] := the maximum size ends in nums[i] + int[] sizeEndsAt = new int[n]; + // prevIndex[i] := the best index s.t. + // 1. nums[i] % nums[prevIndex[i]] == 0 and + // 2. can increase the size of the subset + int[] prevIndex = new int[n]; + int maxSize = 0; // Max size of the subset + int index = -1; // Track the best ending index + + Arrays.fill(sizeEndsAt, 1); + Arrays.fill(prevIndex, -1); + Arrays.sort(nums); + + // Fix the maximum ending number in the subset. + for (int i = 0; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) + if (nums[i] % nums[j] == 0 && sizeEndsAt[i] < sizeEndsAt[j] + 1) { + sizeEndsAt[i] = sizeEndsAt[j] + 1; + prevIndex[i] = j; + } + // Find a new subset that has a bigger size. + if (maxSize < sizeEndsAt[i]) { + maxSize = sizeEndsAt[i]; + index = i; // Update the best ending index. + } + } + + // Loop from the back to the front. + while (index != -1) { + ans.add(nums[index]); + index = prevIndex[index]; + } + + return ans; + } +} diff --git a/solutions/368. Largest Divisible Subset/368.py b/solutions/368. Largest Divisible Subset/368.py new file mode 100644 index 00000000000..a2b2fa00d7d --- /dev/null +++ b/solutions/368. Largest Divisible Subset/368.py @@ -0,0 +1,25 @@ +class Solution: + def largestDivisibleSubset(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [] + count = [1] * n + prevIndex = [-1] * n + maxCount = 0 + index = -1 + + nums.sort() + + for i, num in enumerate(nums): + for j in reversed(range(i)): + if num % nums[j] == 0 and count[i] < count[j] + 1: + count[i] = count[j] + 1 + prevIndex[i] = j + if count[i] > maxCount: + maxCount = count[i] + index = i + + while index != -1: + ans.append(nums[index]) + index = prevIndex[index] + + return ans diff --git a/solutions/369. Plus One Linked List/369-2.cpp b/solutions/369. Plus One Linked List/369-2.cpp new file mode 100644 index 00000000000..ba1c7ab2026 --- /dev/null +++ b/solutions/369. Plus One Linked List/369-2.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + ListNode* plusOne(ListNode* head) { + ListNode* dummy = new ListNode(0); + ListNode* curr = dummy; + dummy->next = head; + + while (head != nullptr) { + if (head->val != 9) + curr = head; + head = head->next; + } + // `curr` now points to the rightmost non-9 node. + + ++curr->val; + while (curr->next) { + curr->next->val = 0; + curr = curr->next; + } + + return dummy->val == 0 ? dummy->next : dummy; + } +}; diff --git a/solutions/369. Plus One Linked List/369-2.java b/solutions/369. Plus One Linked List/369-2.java new file mode 100644 index 00000000000..30ec13e4e47 --- /dev/null +++ b/solutions/369. Plus One Linked List/369-2.java @@ -0,0 +1,22 @@ +class Solution { + public ListNode plusOne(ListNode head) { + ListNode dummy = new ListNode(0); + ListNode curr = dummy; + dummy.next = head; + + while (head != null) { + if (head.val != 9) + curr = head; + head = head.next; + } + // `curr` now points to the rightmost non-9 node. + + ++curr.val; + while (curr.next != null) { + curr.next.val = 0; + curr = curr.next; + } + + return dummy.val == 0 ? dummy.next : dummy; + } +} diff --git a/solutions/369. Plus One Linked List/369-2.py b/solutions/369. Plus One Linked List/369-2.py new file mode 100644 index 00000000000..45c327281d9 --- /dev/null +++ b/solutions/369. Plus One Linked List/369-2.py @@ -0,0 +1,18 @@ +class Solution: + def plusOne(self, head: ListNode) -> ListNode: + dummy = ListNode(0) + curr = dummy + dummy.next = head + + while head: + if head.val != 9: + curr = head + head = head.next + # `curr` now points to the rightmost non-9 node. + + curr.val += 1 + while curr.next: + curr.next.val = 0 + curr = curr.next + + return dummy.next if dummy.val == 0 else dummy diff --git a/solutions/369. Plus One Linked List/369.cpp b/solutions/369. Plus One Linked List/369.cpp new file mode 100644 index 00000000000..a5f600a987a --- /dev/null +++ b/solutions/369. Plus One Linked List/369.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + ListNode* plusOne(ListNode* head) { + if (head == nullptr) + return new ListNode(1); + if (addOne(head) == 1) + return new ListNode(1, head); + return head; + } + + private: + int addOne(ListNode* node) { + const int carry = node->next ? addOne(node->next) : 1; + const int sum = node->val + carry; + node->val = sum % 10; + return sum / 10; + } +}; diff --git a/solutions/369. Plus One Linked List/369.java b/solutions/369. Plus One Linked List/369.java new file mode 100644 index 00000000000..f96940ccfe7 --- /dev/null +++ b/solutions/369. Plus One Linked List/369.java @@ -0,0 +1,16 @@ +class Solution { + public ListNode plusOne(ListNode head) { + if (head == null) + return new ListNode(1); + if (addOne(head) == 1) + return new ListNode(1, head); + return head; + } + + private int addOne(ListNode node) { + final int carry = node.next == null ? 1 : addOne(node.next); + final int sum = node.val + carry; + node.val = sum % 10; + return sum / 10; + } +} diff --git a/solutions/369. Plus One Linked List/369.py b/solutions/369. Plus One Linked List/369.py new file mode 100644 index 00000000000..dfcf8e1ced4 --- /dev/null +++ b/solutions/369. Plus One Linked List/369.py @@ -0,0 +1,13 @@ +class Solution: + def plusOne(self, head: ListNode) -> ListNode: + if not head: + return ListNode(1) + if self._addOne(head) == 1: + return ListNode(1, head) + return head + + def _addOne(self, node: ListNode) -> int: + carry = self._addOne(node.next) if node.next else 1 + summ = node.val + carry + node.val = summ % 10 + return summ // 10 diff --git a/solutions/37. Sudoku Solver/37.cpp b/solutions/37. Sudoku Solver/37.cpp new file mode 100644 index 00000000000..e177fd918fd --- /dev/null +++ b/solutions/37. Sudoku Solver/37.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + void solveSudoku(vector>& board) { + solve(board, 0); + } + + private: + bool solve(vector>& board, int s) { + if (s == 81) + return true; + + const int i = s / 9; + const int j = s % 9; + + if (board[i][j] != '.') + return solve(board, s + 1); + + for (char c = '1'; c <= '9'; ++c) + if (isValid(board, i, j, c)) { + board[i][j] = c; + if (solve(board, s + 1)) + return true; + board[i][j] = '.'; + } + + return false; + } + + bool isValid(vector>& board, int row, int col, char c) { + for (int i = 0; i < 9; ++i) + if (board[i][col] == c || board[row][i] == c || + board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) + return false; + return true; + } +}; diff --git a/solutions/37. Sudoku Solver/37.java b/solutions/37. Sudoku Solver/37.java new file mode 100644 index 00000000000..8380a4571b6 --- /dev/null +++ b/solutions/37. Sudoku Solver/37.java @@ -0,0 +1,34 @@ +class Solution { + public void solveSudoku(char[][] board) { + dfs(board, 0); + } + + private boolean dfs(char[][] board, int s) { + if (s == 81) + return true; + + final int i = s / 9; + final int j = s % 9; + + if (board[i][j] != '.') + return dfs(board, s + 1); + + for (char c = '1'; c <= '9'; ++c) + if (isValid(board, i, j, c)) { + board[i][j] = c; + if (dfs(board, s + 1)) + return true; + board[i][j] = '.'; + } + + return false; + } + + private boolean isValid(char[][] board, int row, int col, char c) { + for (int i = 0; i < 9; ++i) + if (board[i][col] == c || board[row][i] == c || + board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) + return false; + return true; + } +} diff --git a/solutions/37. Sudoku Solver/37.py b/solutions/37. Sudoku Solver/37.py new file mode 100644 index 00000000000..2e0cbab1755 --- /dev/null +++ b/solutions/37. Sudoku Solver/37.py @@ -0,0 +1,30 @@ +class Solution: + def solveSudoku(self, board: List[List[str]]) -> None: + def isValid(row: int, col: int, c: str) -> bool: + for i in range(9): + if board[i][col] == c or \ + board[row][i] == c or \ + board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == c: + return False + return True + + def solve(s: int) -> bool: + if s == 81: + return True + + i = s // 9 + j = s % 9 + + if board[i][j] != '.': + return solve(s + 1) + + for c in string.digits[1:]: + if isValid(i, j, c): + board[i][j] = c + if solve(s + 1): + return True + board[i][j] = '.' + + return False + + solve(0) diff --git a/solutions/370. Range Addition/370.cpp b/solutions/370. Range Addition/370.cpp new file mode 100644 index 00000000000..3909ab5433c --- /dev/null +++ b/solutions/370. Range Addition/370.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector getModifiedArray(int length, vector>& updates) { + vector ans; + vector line(length); + int prefix = 0; + + for (const vector& update : updates) { + const int start = update[0]; + const int end = update[1]; + const int inc = update[2]; + line[start] += inc; + if (end + 1 < length) + line[end + 1] -= inc; + } + + for (const int diff : line) { + prefix += diff; + ans.push_back(prefix); + } + + return ans; + } +}; diff --git a/solutions/370. Range Addition/370.java b/solutions/370. Range Addition/370.java new file mode 100644 index 00000000000..45fb61d7762 --- /dev/null +++ b/solutions/370. Range Addition/370.java @@ -0,0 +1,23 @@ +class Solution { + public int[] getModifiedArray(int length, int[][] updates) { + int[] ans = new int[length]; + int[] line = new int[length]; + int prefix = 0; + + for (int[] update : updates) { + final int startIndex = update[0]; + final int endIndex = update[1]; + final int inc = update[2]; + line[startIndex] += inc; + if (endIndex + 1 < length) + line[endIndex + 1] -= inc; + } + + for (int i = 0; i < length; ++i) { + prefix += line[i]; + ans[i] = prefix; + } + + return ans; + } +} diff --git a/solutions/370. Range Addition/370.py b/solutions/370. Range Addition/370.py new file mode 100644 index 00000000000..aa2a9899e22 --- /dev/null +++ b/solutions/370. Range Addition/370.py @@ -0,0 +1,10 @@ +class Solution: + def getModifiedArray(self, length: int, updates: list[list[int]]) -> list[int]: + line = [0] * length + + for start, end, inc in updates: + line[start] += inc + if end + 1 < length: + line[end + 1] -= inc + + return itertools.accumulate(line) diff --git a/solutions/371. Sum of Two Integers/371.cpp b/solutions/371. Sum of Two Integers/371.cpp new file mode 100644 index 00000000000..8123eb33fa3 --- /dev/null +++ b/solutions/371. Sum of Two Integers/371.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int getSum(unsigned a, unsigned b) { + while (b > 0) { // Still have carry bits. + const unsigned carry = a & b; // Record the carry bits. + a ^= b; // ^ works like + without handling carry bits. + b = carry << 1; + } + return a; + } +}; diff --git a/solutions/371. Sum of Two Integers/371.java b/solutions/371. Sum of Two Integers/371.java new file mode 100644 index 00000000000..a9dde9ea702 --- /dev/null +++ b/solutions/371. Sum of Two Integers/371.java @@ -0,0 +1,10 @@ +class Solution { + public int getSum(int a, int b) { + while (b != 0) { // Still have carry bits. + final int carry = a & b; // Record the carry bits. + a ^= b; // ^ works like + without handling carry bits. + b = carry << 1; + } + return a; + } +} diff --git a/solutions/371. Sum of Two Integers/371.py b/solutions/371. Sum of Two Integers/371.py new file mode 100644 index 00000000000..3e562154dcc --- /dev/null +++ b/solutions/371. Sum of Two Integers/371.py @@ -0,0 +1,9 @@ +class Solution: + def getSum(self, a: int, b: int) -> int: + mask = 0xFFFFFFFF + kMax = 2000 + + while b != 0: + a, b = (a ^ b) & mask, ((a & b) << 1) & mask + + return a if a < kMax else ~(a ^ mask) diff --git a/solutions/372. Super Pow/372.cpp b/solutions/372. Super Pow/372.cpp new file mode 100644 index 00000000000..09f02bf24f7 --- /dev/null +++ b/solutions/372. Super Pow/372.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int superPow(int a, vector& b) { + int ans = 1; + + a %= kMod; + for (const int i : b) + ans = modPow(ans, 10) * modPow(a, i) % kMod; + + return ans; + } + + private: + static constexpr int kMod = 1337; + + long modPow(long x, long n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +}; diff --git a/solutions/372. Super Pow/372.java b/solutions/372. Super Pow/372.java new file mode 100644 index 00000000000..37cce72c62f --- /dev/null +++ b/solutions/372. Super Pow/372.java @@ -0,0 +1,21 @@ +class Solution { + public int superPow(int a, int[] b) { + int ans = 1; + + a %= kMod; + for (final int i : b) + ans = modPow(ans, 10) * modPow(a, i) % kMod; + + return ans; + } + + private static final int kMod = 1337; + + private int modPow(int x, int n) { + if (n == 0) + return 1; + if (n % 2 == 1) + return x * modPow(x % kMod, (n - 1)) % kMod; + return modPow(x * x % kMod, (n / 2)) % kMod; + } +} diff --git a/solutions/372. Super Pow/372.py b/solutions/372. Super Pow/372.py new file mode 100644 index 00000000000..b9827e66763 --- /dev/null +++ b/solutions/372. Super Pow/372.py @@ -0,0 +1,9 @@ +class Solution: + def superPow(self, a: int, b: List[int]) -> int: + kMod = 1337 + ans = 1 + + for i in b: + ans = pow(ans, 10, kMod) * pow(a, i, kMod) + + return ans % kMod diff --git a/solutions/373. Find K Pairs with Smallest Sums/373.cpp b/solutions/373. Find K Pairs with Smallest Sums/373.cpp new file mode 100644 index 00000000000..0ab38d6e83b --- /dev/null +++ b/solutions/373. Find K Pairs with Smallest Sums/373.cpp @@ -0,0 +1,29 @@ +struct T { + int i; + int j; + int sum; // nums1[i] + nums2[j] + T(int i, int j, int sum) : i(i), j(j), sum(sum) {} +}; + +class Solution { + public: + vector> kSmallestPairs(vector& nums1, vector& nums2, + int k) { + vector> ans; + auto compare = [&](const T& a, const T& b) { return a.sum > b.sum; }; + priority_queue, decltype(compare)> minHeap(compare); + + for (int i = 0; i < k && i < nums1.size(); ++i) + minHeap.emplace(i, 0, nums1[i] + nums2[0]); + + while (!minHeap.empty() && ans.size() < k) { + const auto [i, j, _] = minHeap.top(); + minHeap.pop(); + ans.push_back({nums1[i], nums2[j]}); + if (j + 1 < nums2.size()) + minHeap.emplace(i, j + 1, nums1[i] + nums2[j + 1]); + } + + return ans; + } +}; diff --git a/solutions/373. Find K Pairs with Smallest Sums/373.java b/solutions/373. Find K Pairs with Smallest Sums/373.java new file mode 100644 index 00000000000..82921979ed6 --- /dev/null +++ b/solutions/373. Find K Pairs with Smallest Sums/373.java @@ -0,0 +1,30 @@ +class T { + public int i; + public int j; + public int sum; // nums1[i] + nums2[j] + public T(int i, int j, int sum) { + this.i = i; + this.j = j; + this.sum = sum; + } +} + +class Solution { + public List> kSmallestPairs(int[] nums1, int[] nums2, int k) { + List> ans = new ArrayList<>(); + Queue minHeap = new PriorityQueue<>((a, b) -> a.sum - b.sum); + + for (int i = 0; i < Math.min(k, nums1.length); ++i) + minHeap.offer(new T(i, 0, nums1[i] + nums2[0])); + + while (!minHeap.isEmpty() && ans.size() < k) { + final int i = minHeap.peek().i; + final int j = minHeap.poll().j; + ans.add(Arrays.asList(nums1[i], nums2[j])); + if (j + 1 < nums2.length) + minHeap.offer(new T(i, j + 1, nums1[i] + nums2[j + 1])); + } + + return ans; + } +} diff --git a/solutions/373. Find K Pairs with Smallest Sums/373.py b/solutions/373. Find K Pairs with Smallest Sums/373.py new file mode 100644 index 00000000000..9a28487b6d3 --- /dev/null +++ b/solutions/373. Find K Pairs with Smallest Sums/373.py @@ -0,0 +1,15 @@ +class Solution: + def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: + minHeap = [] + + for i in range(min(k, len(nums1))): + heapq.heappush(minHeap, (nums1[i] + nums2[0], i, 0)) + + ans = [] + while minHeap and len(ans) < k: + _, i, j = heapq.heappop(minHeap) + ans.append([nums1[i], nums2[j]]) + if j + 1 < len(nums2): + heapq.heappush(minHeap, (nums1[i] + nums2[j + 1], i, j + 1)) + + return ans diff --git a/solutions/374. Guess Number Higher or Lower/374.cpp b/solutions/374. Guess Number Higher or Lower/374.cpp new file mode 100644 index 00000000000..addd79a179f --- /dev/null +++ b/solutions/374. Guess Number Higher or Lower/374.cpp @@ -0,0 +1,30 @@ +/** + * Forward declaration of guess API. + * (The problem description is not clear, so I translate it into follows.) + * + * @param traget num + * guess num + * + * @return -1 if guess num > target num + * 0 if guess num == target num + * 1 if guess num < target num + */ + +class Solution { + public: + int guessNumber(int n) { + int l = 1; + int r = n; + + // Find the first guess number that >= the target number + while (l < r) { + const int m = l + (r - l) / 2; + if (guess(m) <= 0) // -1, 0 + r = m; + else + l = m + 1; + } + + return l; + } +}; diff --git a/solutions/374. Guess Number Higher or Lower/374.java b/solutions/374. Guess Number Higher or Lower/374.java new file mode 100644 index 00000000000..c404ede246a --- /dev/null +++ b/solutions/374. Guess Number Higher or Lower/374.java @@ -0,0 +1,29 @@ +/** + * Forward declaration of guess API. + * (The problem description is not clear, so I translate it into follows.) + * + * @param traget num + * guess num + * + * @return -1 if guess num > target num + * 0 if guess num == target num + * 1 if guess num < target num + */ + +public class Solution extends GuessGame { + public int guessNumber(int n) { + int l = 1; + int r = n; + + // Find the first guess number that >= the target number + while (l < r) { + final int m = l + (r - l) / 2; + if (guess(m) <= 0) // -1, 0 + r = m; + else + l = m + 1; + } + + return l; + } +} diff --git a/solutions/374. Guess Number Higher or Lower/374.py b/solutions/374. Guess Number Higher or Lower/374.py new file mode 100644 index 00000000000..a405eb39cbe --- /dev/null +++ b/solutions/374. Guess Number Higher or Lower/374.py @@ -0,0 +1,21 @@ +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if num is higher than the picked number +# 1 if num is lower than the picked number +# otherwise return 0 +# def guess(num: int) -> int: + +class Solution: + def guessNumber(self, n: int) -> int: + l = 1 + r = n + + # Find the first guess number that >= the target number + while l < r: + m = (l + r) // 2 + if guess(m) <= 0: # -1, 0 + r = m + else: + l = m + 1 + + return l diff --git a/solutions/375. Guess Number Higher or Lower II/375-2.cpp b/solutions/375. Guess Number Higher or Lower II/375-2.cpp new file mode 100644 index 00000000000..10b57aa4e74 --- /dev/null +++ b/solutions/375. Guess Number Higher or Lower II/375-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int getMoneyAmount(int n) { + // dp[i][j] := the minimum money you need to guarantee a win of picking i..j + vector> dp(n + 2, vector(n + 2)); + + for (int d = 1; d < n; ++d) + for (int i = 1; i + d <= n; ++i) { + const int j = i + d; + dp[i][j] = INT_MAX; + for (int k = i; k <= j; ++k) + dp[i][j] = min(dp[i][j], max(dp[i][k - 1], dp[k + 1][j]) + k); + } + + return dp[1][n]; + } +}; diff --git a/solutions/375. Guess Number Higher or Lower II/375-2.java b/solutions/375. Guess Number Higher or Lower II/375-2.java new file mode 100644 index 00000000000..d04bff3bae0 --- /dev/null +++ b/solutions/375. Guess Number Higher or Lower II/375-2.java @@ -0,0 +1,16 @@ +class Solution { + public int getMoneyAmount(int n) { + // dp[i][j] := the minimum money you need to guarantee a win of picking i..j + int[][] dp = new int[n + 2][n + 2]; + + for (int d = 1; d < n; ++d) + for (int i = 1; i + d <= n; ++i) { + final int j = i + d; + dp[i][j] = Integer.MAX_VALUE; + for (int k = i; k <= j; ++k) + dp[i][j] = Math.min(dp[i][j], Math.max(dp[i][k - 1], dp[k + 1][j]) + k); + } + + return dp[1][n]; + } +} diff --git a/solutions/375. Guess Number Higher or Lower II/375-2.py b/solutions/375. Guess Number Higher or Lower II/375-2.py new file mode 100644 index 00000000000..8fc5e5b07ac --- /dev/null +++ b/solutions/375. Guess Number Higher or Lower II/375-2.py @@ -0,0 +1,13 @@ +class Solution: + def getMoneyAmount(self, n: int) -> int: + # dp[i][j] := the minimum money you need to guarantee a win of picking i..j + dp = [[0] * (n + 2) for _ in range(n + 2)] + + for d in range(1, n + 1): + for i in range(1, n - d + 1): + j = i + d + dp[i][j] = math.inf + for k in range(i, j + 1): + dp[i][j] = min(dp[i][j], max(dp[i][k - 1], dp[k + 1][j]) + k) + + return dp[1][n] diff --git a/solutions/375. Guess Number Higher or Lower II/375.cpp b/solutions/375. Guess Number Higher or Lower II/375.cpp new file mode 100644 index 00000000000..f516d957b6e --- /dev/null +++ b/solutions/375. Guess Number Higher or Lower II/375.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int getMoneyAmount(int n) { + vector> mem(n + 1, vector(n + 1, INT_MAX)); + return getMoneyAmount(1, n, mem); + } + + private: + // Returns the minimum money you need to guarantee a win of picking i..j. + int getMoneyAmount(int i, int j, vector>& mem) { + if (i >= j) + return 0; + if (mem[i][j] != INT_MAX) + return mem[i][j]; + + for (int k = i; k <= j; ++k) + mem[i][j] = min(mem[i][j], max(getMoneyAmount(i, k - 1, mem), + getMoneyAmount(k + 1, j, mem)) + + k); + + return mem[i][j]; + } +}; diff --git a/solutions/375. Guess Number Higher or Lower II/375.java b/solutions/375. Guess Number Higher or Lower II/375.java new file mode 100644 index 00000000000..5a11e6b95f2 --- /dev/null +++ b/solutions/375. Guess Number Higher or Lower II/375.java @@ -0,0 +1,22 @@ +class Solution { + public int getMoneyAmount(int n) { + int[][] mem = new int[n + 1][n + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + return getMoneyAmount(1, n, mem); + } + + // Returns the minimum money you need to guarantee a win of picking i..j. + private int getMoneyAmount(int i, int j, int[][] mem) { + if (i >= j) + return 0; + if (mem[i][j] != Integer.MAX_VALUE) + return mem[i][j]; + + for (int k = i; k <= j; ++k) + mem[i][j] = Math.min(mem[i][j], Math.max(getMoneyAmount(i, k - 1, mem), // + getMoneyAmount(k + 1, j, mem)) + + k); + + return mem[i][j]; + } +} diff --git a/solutions/375. Guess Number Higher or Lower II/375.py b/solutions/375. Guess Number Higher or Lower II/375.py new file mode 100644 index 00000000000..64966260174 --- /dev/null +++ b/solutions/375. Guess Number Higher or Lower II/375.py @@ -0,0 +1,12 @@ +class Solution: + def getMoneyAmount(self, n: int) -> int: + @functools.lru_cache(None) + def dp(i: int, j: int) -> int: + """Returns the minimum money you need to guarantee a win of picking i..j. + """ + if i >= j: + return 0 + return min(max(dp(i, k - 1), dp(k + 1, j)) + k + for k in range(i, j + 1)) + + return dp(1, n) diff --git a/solutions/376. Wiggle Subsequence/376.cpp b/solutions/376. Wiggle Subsequence/376.cpp new file mode 100644 index 00000000000..a7441e64ecc --- /dev/null +++ b/solutions/376. Wiggle Subsequence/376.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int wiggleMaxLength(vector& nums) { + int increasing = 1; + int decreasing = 1; + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] > nums[i - 1]) + increasing = decreasing + 1; + else if (nums[i] < nums[i - 1]) + decreasing = increasing + 1; + + return max(increasing, decreasing); + } +}; diff --git a/solutions/376. Wiggle Subsequence/376.java b/solutions/376. Wiggle Subsequence/376.java new file mode 100644 index 00000000000..6b933fb79f7 --- /dev/null +++ b/solutions/376. Wiggle Subsequence/376.java @@ -0,0 +1,14 @@ +class Solution { + public int wiggleMaxLength(int[] nums) { + int increasing = 1; + int decreasing = 1; + + for (int i = 1; i < nums.length; ++i) + if (nums[i] > nums[i - 1]) + increasing = decreasing + 1; + else if (nums[i] < nums[i - 1]) + decreasing = increasing + 1; + + return Math.max(increasing, decreasing); + } +} diff --git a/solutions/376. Wiggle Subsequence/376.py b/solutions/376. Wiggle Subsequence/376.py new file mode 100644 index 00000000000..2e6a489f8cb --- /dev/null +++ b/solutions/376. Wiggle Subsequence/376.py @@ -0,0 +1,12 @@ +class Solution: + def wiggleMaxLength(self, nums: List[int]) -> int: + increasing = 1 + decreasing = 1 + + for a, b in itertools.pairwise(nums): + if b > a: + increasing = decreasing + 1 + elif b < a: + decreasing = increasing + 1 + + return max(increasing, decreasing) diff --git a/solutions/377. Combination Sum IV/377.cpp b/solutions/377. Combination Sum IV/377.cpp new file mode 100644 index 00000000000..abd178caaf3 --- /dev/null +++ b/solutions/377. Combination Sum IV/377.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int combinationSum4(vector& nums, int target) { + vector dp(target + 1); + dp[0] = 1; + + for (int i = 1; i <= target; ++i) + for (const int num : nums) + if (i >= num) + dp[i] += dp[i - num]; + + return dp[target]; + } +}; diff --git a/solutions/377. Combination Sum IV/377.java b/solutions/377. Combination Sum IV/377.java new file mode 100644 index 00000000000..4f5eae5eaa6 --- /dev/null +++ b/solutions/377. Combination Sum IV/377.java @@ -0,0 +1,14 @@ +class Solution { + public int combinationSum4(int[] nums, int target) { + // dp[i] := the number of combinations that add up to i + int[] dp = new int[target + 1]; + dp[0] = 1; + + for (int i = 0; i <= target; ++i) + for (final int num : nums) + if (i >= num) + dp[i] += dp[i - num]; + + return dp[target]; + } +} diff --git a/solutions/377. Combination Sum IV/377.py b/solutions/377. Combination Sum IV/377.py new file mode 100644 index 00000000000..b7e9b2790a3 --- /dev/null +++ b/solutions/377. Combination Sum IV/377.py @@ -0,0 +1,14 @@ +class Solution: + def combinationSum4(self, nums: List[int], target: int) -> int: + dp = [1] + [-1] * target + + def dfs(target: int) -> int: + if target < 0: + return 0 + if dp[target] != -1: + return dp[target] + + dp[target] = sum(dfs(target - num) for num in nums) + return dp[target] + + return dfs(target) diff --git a/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.cpp b/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.cpp new file mode 100644 index 00000000000..1b8aa028bc0 --- /dev/null +++ b/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int kthSmallest(vector>& matrix, int k) { + int l = matrix[0][0]; + int r = matrix.back().back(); + + while (l < r) { + const int m = l + (r - l) / 2; + if (numsNoGreaterThan(matrix, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int numsNoGreaterThan(const vector>& matrix, int m) { + int count = 0; + int j = matrix[0].size() - 1; + // For each row, find the first index j s.t. row[j] <= m s.t. the number of + // numbers <= m for this row will be j + 1. + for (const vector& row : matrix) { + while (j >= 0 && row[j] > m) + --j; + count += j + 1; + } + return count; + } +}; diff --git a/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.java b/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.java new file mode 100644 index 00000000000..5c915b1d1c1 --- /dev/null +++ b/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.java @@ -0,0 +1,29 @@ +class Solution { + public int kthSmallest(int[][] matrix, int k) { + int l = matrix[0][0]; + int r = matrix[matrix.length - 1][matrix.length - 1]; + + while (l < r) { + final int m = l + (r - l) / 2; + if (numsNoGreaterThan(matrix, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private int numsNoGreaterThan(int[][] matrix, int m) { + int count = 0; + int j = matrix[0].length - 1; + // For each row, find the first index j s.t. row[j] <= m s.t. the number of + // numbers <= m for this row will be j + 1. + for (int[] row : matrix) { + while (j >= 0 && row[j] > m) + --j; + count += j + 1; + } + return count; + } +} diff --git a/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.py b/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.py new file mode 100644 index 00000000000..72ca426443f --- /dev/null +++ b/solutions/378. Kth Smallest Element in a Sorted Matrix/378-2.py @@ -0,0 +1,15 @@ +class Solution: + def kthSmallest(self, matrix: List[List[int]], k: int) -> int: + def numsNoGreaterThan(m: int) -> int: + count = 0 + j = len(matrix[0]) - 1 + # For each row, find the first index j s.t. row[j] <= m s.t. the number of + # numbers <= m for this row will be j + 1. + for row in matrix: + while j >= 0 and row[j] > m: + j -= 1 + count += j + 1 + return count + + return bisect.bisect_left(range(matrix[0][0], matrix[-1][-1]), k, + key=lambda m: numsNoGreaterThan(m)) + matrix[0][0] diff --git a/solutions/378. Kth Smallest Element in a Sorted Matrix/378.cpp b/solutions/378. Kth Smallest Element in a Sorted Matrix/378.cpp new file mode 100644 index 00000000000..2b7d88a89ad --- /dev/null +++ b/solutions/378. Kth Smallest Element in a Sorted Matrix/378.cpp @@ -0,0 +1,26 @@ +struct T { + int i; + int j; + int num; // matrix[i][j] + T(int i, int j, int num) : i(i), j(j), num(num) {} +}; + +class Solution { + public: + int kthSmallest(vector>& matrix, int k) { + auto compare = [&](const T& a, const T& b) { return a.num > b.num; }; + priority_queue, decltype(compare)> minHeap(compare); + + for (int i = 0; i < k && i < matrix.size(); ++i) + minHeap.emplace(i, 0, matrix[i][0]); + + while (k-- > 1) { + const auto [i, j, _] = minHeap.top(); + minHeap.pop(); + if (j + 1 < matrix[0].size()) + minHeap.emplace(i, j + 1, matrix[i][j + 1]); + } + + return minHeap.top().num; + } +}; diff --git a/solutions/378. Kth Smallest Element in a Sorted Matrix/378.java b/solutions/378. Kth Smallest Element in a Sorted Matrix/378.java new file mode 100644 index 00000000000..5ebd6e7208d --- /dev/null +++ b/solutions/378. Kth Smallest Element in a Sorted Matrix/378.java @@ -0,0 +1,28 @@ +class T { + public int i; + public int j; + public int num; // matrix[i][j] + public T(int i, int j, int num) { + this.i = i; + this.j = j; + this.num = num; + } +} + +class Solution { + public int kthSmallest(int[][] matrix, int k) { + Queue minHeap = new PriorityQueue<>((a, b) -> a.num - b.num); + + for (int i = 0; i < k && i < matrix.length; ++i) + minHeap.offer(new T(i, 0, matrix[i][0])); + + while (k-- > 1) { + final int i = minHeap.peek().i; + final int j = minHeap.poll().j; + if (j + 1 < matrix[0].length) + minHeap.offer(new T(i, j + 1, matrix[i][j + 1])); + } + + return minHeap.peek().num; + } +} diff --git a/solutions/378. Kth Smallest Element in a Sorted Matrix/378.py b/solutions/378. Kth Smallest Element in a Sorted Matrix/378.py new file mode 100644 index 00000000000..32c53835a25 --- /dev/null +++ b/solutions/378. Kth Smallest Element in a Sorted Matrix/378.py @@ -0,0 +1,16 @@ +class Solution: + def kthSmallest(self, matrix: List[List[int]], k: int) -> int: + minHeap = [] # (matrix[i][j], i, j) + + i = 0 + while i < k and i < len(matrix): + heapq.heappush(minHeap, (matrix[i][0], i, 0)) + i += 1 + + while k > 1: + k -= 1 + _, i, j = heapq.heappop(minHeap) + if j + 1 < len(matrix[0]): + heapq.heappush(minHeap, (matrix[i][j + 1], i, j + 1)) + + return minHeap[0][0] diff --git a/solutions/379. Design Phone Directory/379.cpp b/solutions/379. Design Phone Directory/379.cpp new file mode 100644 index 00000000000..d7856867b88 --- /dev/null +++ b/solutions/379. Design Phone Directory/379.cpp @@ -0,0 +1,32 @@ +class PhoneDirectory { + public: + PhoneDirectory(int maxNumbers) : next(maxNumbers) { + for (int i = 0; i < maxNumbers - 1; ++i) + next[i] = i + 1; + next.back() = 0; + } + + int get() { + if (next[number] == -1) + return -1; + const int ans = number; + number = next[number]; + next[ans] = -1; // Mark as used. + return ans; + } + + bool check(int number) { + return next[number] != -1; + } + + void release(int number) { + if (next[number] != -1) + return; + next[number] = this->number; + this->number = number; + } + + private: + int number = 0; // the current possible available number + vector next; // the next available numbers +}; diff --git a/solutions/379. Design Phone Directory/379.java b/solutions/379. Design Phone Directory/379.java new file mode 100644 index 00000000000..a60957cb743 --- /dev/null +++ b/solutions/379. Design Phone Directory/379.java @@ -0,0 +1,32 @@ +class PhoneDirectory { + public PhoneDirectory(int maxNumbers) { + next = new int[maxNumbers]; + for (int i = 0; i < maxNumbers - 1; ++i) + next[i] = i + 1; + next[maxNumbers - 1] = 0; + } + + public int get() { + if (next[number] == -1) + return -1; + final int availableNum = number; + number = next[number]; + next[availableNum] = -1; // Mark as used. + return ans; + } + + public boolean check(int number) { + return next[number] != -1; + } + + public void release(int number) { + if (next[number] != -1) + return; + + next[number] = this.number; + this.number = number; + } + + private int number; // the current possible available number + private int[] next; // the next available numbers +} diff --git a/solutions/379. Design Phone Directory/379.py b/solutions/379. Design Phone Directory/379.py new file mode 100644 index 00000000000..62079302833 --- /dev/null +++ b/solutions/379. Design Phone Directory/379.py @@ -0,0 +1,23 @@ +class PhoneDirectory: + def __init__(self, maxNumbers: int): + # the next available numbers + self.next = [i + 1 for i in range(maxNumbers - 1)] + [0] + # the current possible available number + self.number = 0 + + def get(self) -> int: + if self.next[self.number] == -1: + return -1 + ans = self.number + self.number = self.next[self.number] + self.next[ans] = -1 # Mark as used. + return ans + + def check(self, number: int) -> bool: + return self.next[number] != -1 + + def release(self, number: int) -> None: + if self.next[number] != -1: + return + self.next[number] = self.number + self.number = number diff --git a/solutions/38. Count and Say/38.cpp b/solutions/38. Count and Say/38.cpp new file mode 100644 index 00000000000..69e158e7bc1 --- /dev/null +++ b/solutions/38. Count and Say/38.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string countAndSay(int n) { + string ans = "1"; + + while (--n) { + string next; + for (int i = 0; i < ans.length(); ++i) { + int count = 1; + while (i + 1 < ans.length() && ans[i] == ans[i + 1]) { + ++count; + ++i; + } + next += to_string(count) + ans[i]; + } + ans = move(next); + } + + return ans; + } +}; diff --git a/solutions/38. Count and Say/38.java b/solutions/38. Count and Say/38.java new file mode 100644 index 00000000000..8cfeaa29cd5 --- /dev/null +++ b/solutions/38. Count and Say/38.java @@ -0,0 +1,20 @@ +class Solution { + public String countAndSay(int n) { + StringBuilder sb = new StringBuilder("1"); + + while (--n > 0) { + StringBuilder next = new StringBuilder(); + for (int i = 0; i < sb.length(); ++i) { + int count = 1; + while (i + 1 < sb.length() && sb.charAt(i) == sb.charAt(i + 1)) { + ++count; + ++i; + } + next.append(count).append(sb.charAt(i)); + } + sb = next; + } + + return sb.toString(); + } +} diff --git a/solutions/38. Count and Say/38.py b/solutions/38. Count and Say/38.py new file mode 100644 index 00000000000..6b0be156415 --- /dev/null +++ b/solutions/38. Count and Say/38.py @@ -0,0 +1,17 @@ +class Solution: + def countAndSay(self, n: int) -> str: + ans = '1' + + for _ in range(n - 1): + nxt = '' + i = 0 + while i < len(ans): + count = 1 + while i + 1 < len(ans) and ans[i] == ans[i + 1]: + count += 1 + i += 1 + nxt += str(count) + ans[i] + i += 1 + ans = nxt + + return ans diff --git a/solutions/380. Insert Delete GetRandom O(1)/380.cpp b/solutions/380. Insert Delete GetRandom O(1)/380.cpp new file mode 100644 index 00000000000..575fd09a550 --- /dev/null +++ b/solutions/380. Insert Delete GetRandom O(1)/380.cpp @@ -0,0 +1,31 @@ +class RandomizedSet { + public: + bool insert(int val) { + if (valToIndex.contains(val)) + return false; + valToIndex[val] = vals.size(); + vals.push_back(val); + return true; + } + + bool remove(int val) { + if (!valToIndex.contains(val)) + return false; + const int index = valToIndex[val]; + // The order of the following two lines is important when vals.size() == 1. + valToIndex[vals.back()] = index; + valToIndex.erase(val); + vals[index] = vals.back(); + vals.pop_back(); + return true; + } + + int getRandom() { + const int index = rand() % vals.size(); + return vals[index]; + } + + private: + unordered_map valToIndex; // {val: index in vals} + vector vals; +}; diff --git a/solutions/380. Insert Delete GetRandom O(1)/380.java b/solutions/380. Insert Delete GetRandom O(1)/380.java new file mode 100644 index 00000000000..b741521f4db --- /dev/null +++ b/solutions/380. Insert Delete GetRandom O(1)/380.java @@ -0,0 +1,35 @@ +class RandomizedSet { + public boolean insert(int val) { + if (valToIndex.containsKey(val)) + return false; + valToIndex.put(val, vals.size()); + vals.add(val); + return true; + } + + public boolean remove(int val) { + if (!valToIndex.containsKey(val)) + return false; + final int index = valToIndex.get(val); + // The order of the following two lines is important when vals.size() == 1. + valToIndex.put(last(vals), index); + valToIndex.remove(val); + vals.set(index, last(vals)); + vals.remove(vals.size() - 1); + return true; + } + + public int getRandom() { + final int index = rand.nextInt(vals.size()); + return vals.get(index); + } + + // {val: index in vals} + private Map valToIndex = new HashMap<>(); + private List vals = new ArrayList<>(); + private Random rand = new Random(); + + private int last(List vals) { + return vals.get(vals.size() - 1); + } +} diff --git a/solutions/380. Insert Delete GetRandom O(1)/380.py b/solutions/380. Insert Delete GetRandom O(1)/380.py new file mode 100644 index 00000000000..92f45ed25b1 --- /dev/null +++ b/solutions/380. Insert Delete GetRandom O(1)/380.py @@ -0,0 +1,26 @@ +class RandomizedSet: + def __init__(self): + self.vals = [] + self.valToIndex = collections.defaultdict(int) # {val: index in vals} + + def insert(self, val: int) -> bool: + if val in self.valToIndex: + return False + self.valToIndex[val] = len(self.vals) + self.vals.append(val) + return True + + def remove(self, val: int) -> bool: + if val not in self.valToIndex: + return False + index = self.valToIndex[val] + # The order of the following two lines is important when vals.size() == 1. + self.valToIndex[self.vals[-1]] = index + del self.valToIndex[val] + self.vals[index] = self.vals[-1] + self.vals.pop() + return True + + def getRandom(self) -> int: + index = random.randint(0, len(self.vals) - 1) + return self.vals[index] diff --git a/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.cpp b/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.cpp new file mode 100644 index 00000000000..d224145f7a5 --- /dev/null +++ b/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.cpp @@ -0,0 +1,37 @@ +struct Item { + int val; + int indexInMap; + Item(int val, int indexInMap) : val(val), indexInMap(indexInMap) {} +}; + +class RandomizedCollection { + public: + bool insert(int val) { + valToIndices[val].push_back(items.size()); + items.emplace_back(val, valToIndices[val].size() - 1); + return valToIndices[val].size() == 1; + } + + bool remove(int val) { + if (!valToIndices.contains(val)) + return false; + + const int index = valToIndices[val].back(); + valToIndices[items.back().val][items.back().indexInMap] = index; + valToIndices[val].pop_back(); + if (valToIndices[val].empty()) + valToIndices.erase(val); + items[index] = items.back(); + items.pop_back(); + return true; + } + + int getRandom() { + const int index = rand() % items.size(); + return items[index].val; + } + + private: + unordered_map> valToIndices; + vector items; +}; diff --git a/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.java b/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.java new file mode 100644 index 00000000000..6239e5cfbab --- /dev/null +++ b/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.java @@ -0,0 +1,49 @@ +class Item { + public int val; + public int indexInMap; + public Item(int val, int indexInMap) { + this.val = val; + this.indexInMap = indexInMap; + } +} + +class RandomizedCollection { + public boolean insert(int val) { + valToIndices.putIfAbsent(val, new ArrayList<>()); + valToIndices.get(val).add(items.size()); + items.add(new Item(val, valToIndices.get(val).size() - 1)); + return valToIndices.get(val).size() == 1; + } + + public boolean remove(int val) { + if (!valToIndices.containsKey(val)) + return false; + + final int index = lastIndex(valToIndices.get(val)); + valToIndices.get(last(items).val).set(last(items).indexInMap, index); + final int indicesSize = valToIndices.get(val).size(); + valToIndices.get(val).remove(indicesSize - 1); + if (valToIndices.get(val).isEmpty()) + valToIndices.remove(val); + items.set(index, last(items)); + items.remove(items.size() - 1); + return true; + } + + public int getRandom() { + final int index = rand.nextInt(items.size()); + return items.get(index).val; + } + + private Map> valToIndices = new HashMap<>(); + private List items = new ArrayList<>(); + private Random rand = new Random(); + + private int lastIndex(List indices) { + return indices.get(indices.size() - 1); + } + + private Item last(List items) { + return items.get(items.size() - 1); + } +} diff --git a/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.py b/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.py new file mode 100644 index 00000000000..62ecd3d1a53 --- /dev/null +++ b/solutions/381. Insert Delete GetRandom O(1) - Duplicates allowed/381.py @@ -0,0 +1,24 @@ +class RandomizedCollection: + def __init__(self): + self.vals = [] + self.valToIndices = collections.defaultdict(list) + + def insert(self, val: int) -> bool: + self.valToIndices[val].append(len(self.vals)) + self.vals.append([val, len(self.valToIndices[val]) - 1]) + return len(self.valToIndices[val]) == 1 + + def remove(self, val: int) -> bool: + if val not in self.valToIndices or self.valToIndices[val] == []: + return False + + index = self.valToIndices[val][-1] + self.valToIndices[self.vals[-1][0]][self.vals[-1][1]] = index + self.valToIndices[val].pop() + self.vals[index] = self.vals[-1] + self.vals.pop() + return True + + def getRandom(self) -> int: + index = random.randint(0, len(self.vals) - 1) + return self.vals[index][0] diff --git a/solutions/382. Linked List Random Node/382.cpp b/solutions/382. Linked List Random Node/382.cpp new file mode 100644 index 00000000000..fd5e10a40c6 --- /dev/null +++ b/solutions/382. Linked List Random Node/382.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + /** @param head The linked list's head. + Note that the head is guaranteed to be not null, so it contains at least + one node. */ + Solution(ListNode* head) : head(head) {} + + /** Returns a random node's value. */ + int getRandom() { + int res = -1; + int i = 1; + + for (ListNode* curr = head; curr; curr = curr->next, ++i) + if (rand() % i == 0) + res = curr->val; + + return res; + } + + private: + ListNode* head; +}; diff --git a/solutions/382. Linked List Random Node/382.java b/solutions/382. Linked List Random Node/382.java new file mode 100644 index 00000000000..ce0ce73213f --- /dev/null +++ b/solutions/382. Linked List Random Node/382.java @@ -0,0 +1,24 @@ +class Solution { + /** + * @param head The linked list's head. Note that the head is guaranteed to be + * not null, so it contains at least one node. + */ + public Solution(ListNode head) { + this.head = head; + } + + /** Returns a random node's value. */ + public int getRandom() { + int res = -1; + int i = 1; + + for (ListNode curr = head; curr != null; curr = curr.next, ++i) + if (rand.nextInt(i) == i - 1) + res = curr.val; + + return res; + } + + private ListNode head; + private Random rand = new Random(); +} diff --git a/solutions/382. Linked List Random Node/382.py b/solutions/382. Linked List Random Node/382.py new file mode 100644 index 00000000000..d842109efe6 --- /dev/null +++ b/solutions/382. Linked List Random Node/382.py @@ -0,0 +1,22 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def __init__(self, head: Optional[ListNode]): + self.head = head + + def getRandom(self) -> int: + res = -1 + i = 1 + curr = self.head + + while curr: + if random.randint(0, i - 1) == 0: + res = curr.val + curr = curr.next + i += 1 + + return res diff --git a/solutions/383. Ransom Note/383.cpp b/solutions/383. Ransom Note/383.cpp new file mode 100644 index 00000000000..e4c5042e63a --- /dev/null +++ b/solutions/383. Ransom Note/383.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + // Similar to 0242. Valid Anagram + bool canConstruct(string ransomNote, string magazine) { + vector count(26); + + for (const char c : magazine) + ++count[c - 'a']; + + for (const char c : ransomNote) { + if (count[c - 'a'] == 0) + return false; + --count[c - 'a']; + } + + return true; + } +}; diff --git a/solutions/383. Ransom Note/383.java b/solutions/383. Ransom Note/383.java new file mode 100644 index 00000000000..34229a8d322 --- /dev/null +++ b/solutions/383. Ransom Note/383.java @@ -0,0 +1,16 @@ +class Solution { + public boolean canConstruct(String ransomNote, String magazine) { + int[] count = new int[26]; + + for (final char c : magazine.toCharArray()) + ++count[c - 'a']; + + for (final char c : ransomNote.toCharArray()) { + if (count[c - 'a'] == 0) + return false; + --count[c - 'a']; + } + + return true; + } +} diff --git a/solutions/383. Ransom Note/383.py b/solutions/383. Ransom Note/383.py new file mode 100644 index 00000000000..597d75acaba --- /dev/null +++ b/solutions/383. Ransom Note/383.py @@ -0,0 +1,5 @@ +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + count1 = collections.Counter(ransomNote) + count2 = collections.Counter(magazine) + return all(count1[c] <= count2[c] for c in string.ascii_lowercase) diff --git a/solutions/384. Shuffle an Array/384.cpp b/solutions/384. Shuffle an Array/384.cpp new file mode 100644 index 00000000000..c172d86452f --- /dev/null +++ b/solutions/384. Shuffle an Array/384.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + Solution(vector& nums) : nums(move(nums)) {} + + /** Resets the array to its original configuration and return it. */ + vector reset() { + return nums; + } + + /** Returns a random shuffling of the array. */ + vector shuffle() { + vector A(nums); + for (int i = A.size() - 1; i > 0; --i) { + const int j = rand() % (i + 1); + swap(A[i], A[j]); + } + return A; + } + + private: + vector nums; +}; diff --git a/solutions/384. Shuffle an Array/384.java b/solutions/384. Shuffle an Array/384.java new file mode 100644 index 00000000000..7c3f7fd7a62 --- /dev/null +++ b/solutions/384. Shuffle an Array/384.java @@ -0,0 +1,29 @@ +class Solution { + public Solution(int[] nums) { + this.nums = nums; + } + + /** Resets the array to its original configuration and return it. */ + public int[] reset() { + return nums; + } + + /** Returns a random shuffling of the array. */ + public int[] shuffle() { + int[] A = nums.clone(); + for (int i = A.length - 1; i > 0; --i) { + final int j = rand.nextInt(i + 1); + swap(A, i, j); + } + return A; + } + + private int[] nums; + private Random rand = new Random(); + + private void swap(int[] A, int i, int j) { + final int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} diff --git a/solutions/384. Shuffle an Array/384.py b/solutions/384. Shuffle an Array/384.py new file mode 100644 index 00000000000..2f49b304dab --- /dev/null +++ b/solutions/384. Shuffle an Array/384.py @@ -0,0 +1,19 @@ +class Solution: + def __init__(self, nums: List[int]): + self.nums = nums + + def reset(self) -> List[int]: + """ + Resets the array to its original configuration and return it. + """ + return self.nums + + def shuffle(self) -> List[int]: + """ + Returns a random shuffling of the array. + """ + A = self.nums.copy() + for i in range(len(A) - 1, 0, -1): + j = random.randint(0, i) + A[i], A[j] = A[j], A[i] + return A diff --git a/solutions/385. Mini Parser/385.cpp b/solutions/385. Mini Parser/385.cpp new file mode 100644 index 00000000000..60fc9bb76a3 --- /dev/null +++ b/solutions/385. Mini Parser/385.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + NestedInteger deserialize(string s) { + if (s[0] != '[') + return NestedInteger(stoi(s)); + + stack stack; + int start; // the start index of a number + + for (int i = 0; i < s.length(); ++i) { + switch (s[i]) { + case '[': + stack.push(NestedInteger()); + start = i + 1; + break; + case ',': + if (i > start) { + const int num = stoi(s.substr(start, i)); + stack.top().add(NestedInteger(num)); + } + start = i + 1; + break; + case ']': + NestedInteger popped = stack.top(); + stack.pop(); + if (i > start) { + const int num = stoi(s.substr(start, i)); + popped.add(NestedInteger(num)); + } + if (stack.empty()) + return popped; + else + stack.top().add(popped); + start = i + 1; + break; + } + } + + throw; + } +}; diff --git a/solutions/385. Mini Parser/385.java b/solutions/385. Mini Parser/385.java new file mode 100644 index 00000000000..951243860d7 --- /dev/null +++ b/solutions/385. Mini Parser/385.java @@ -0,0 +1,38 @@ +class Solution { + public NestedInteger deserialize(String s) { + if (s.charAt(0) != '[') + return new NestedInteger(Integer.parseInt(s)); + + Deque stack = new ArrayDeque<>(); + int start; // the start index of a number + + for (int i = 0; i < s.length(); ++i) + switch (s.charAt(i)) { + case '[': + stack.push(new NestedInteger()); + start = i + 1; + break; + case ',': + if (i > start) { + final int num = Integer.parseInt(s.substring(start, i)); + stack.peek().add(new NestedInteger(num)); + } + start = i + 1; + break; + case ']': + NestedInteger popped = stack.pop(); + if (i > start) { + final int num = Integer.parseInt(s.substring(start, i)); + popped.add(new NestedInteger(num)); + } + if (!stack.isEmpty()) + stack.peek().add(popped); + else + return popped; + start = i + 1; + break; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/385. Mini Parser/385.py b/solutions/385. Mini Parser/385.py new file mode 100644 index 00000000000..7745a6bfbdd --- /dev/null +++ b/solutions/385. Mini Parser/385.py @@ -0,0 +1,26 @@ +class Solution: + def deserialize(self, s: str) -> NestedInteger: + if s[0] != '[': + return NestedInteger(int(s)) + + stack = [] + + for i, c in enumerate(s): + if c == '[': + stack.append(NestedInteger()) + start = i + 1 + elif c == ',': + if i > start: + num = int(s[start:i]) + stack[-1].add(NestedInteger(num)) + start = i + 1 + elif c == ']': + popped = stack.pop() + if i > start: + num = int(s[start:i]) + popped.add(NestedInteger(num)) + if stack: + stack[-1].add(popped) + else: + return popped + start = i + 1 diff --git a/solutions/386. Lexicographical Numbers/386.cpp b/solutions/386. Lexicographical Numbers/386.cpp new file mode 100644 index 00000000000..7a1e341007f --- /dev/null +++ b/solutions/386. Lexicographical Numbers/386.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector lexicalOrder(int n) { + vector ans; + int curr = 1; + + while (ans.size() < n) { + ans.push_back(curr); + if (curr * 10 <= n) { + curr *= 10; + } else { + while (curr % 10 == 9 || curr == n) + curr /= 10; + ++curr; + } + } + + return ans; + } +}; diff --git a/solutions/386. Lexicographical Numbers/386.java b/solutions/386. Lexicographical Numbers/386.java new file mode 100644 index 00000000000..7fda60a12a8 --- /dev/null +++ b/solutions/386. Lexicographical Numbers/386.java @@ -0,0 +1,19 @@ +class Solution { + public List lexicalOrder(int n) { + List ans = new ArrayList<>(); + int curr = 1; + + while (ans.size() < n) { + ans.add(curr); + if (curr * 10 <= n) { + curr *= 10; + } else { + while (curr % 10 == 9 || curr == n) + curr /= 10; + ++curr; + } + } + + return ans; + } +} diff --git a/solutions/386. Lexicographical Numbers/386.py b/solutions/386. Lexicographical Numbers/386.py new file mode 100644 index 00000000000..27b631556cf --- /dev/null +++ b/solutions/386. Lexicographical Numbers/386.py @@ -0,0 +1,15 @@ +class Solution: + def lexicalOrder(self, n: int) -> List[int]: + ans = [] + curr = 1 + + while len(ans) < n: + ans.append(curr) + if curr * 10 <= n: + curr *= 10 + else: + while curr % 10 == 9 or curr == n: + curr //= 10 + curr += 1 + + return ans diff --git a/solutions/387. First Unique Character in a String/387.cpp b/solutions/387. First Unique Character in a String/387.cpp new file mode 100644 index 00000000000..7f5c9e8bab2 --- /dev/null +++ b/solutions/387. First Unique Character in a String/387.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int firstUniqChar(string s) { + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + for (int i = 0; i < s.length(); ++i) + if (count[s[i] - 'a'] == 1) + return i; + + return -1; + } +}; diff --git a/solutions/387. First Unique Character in a String/387.java b/solutions/387. First Unique Character in a String/387.java new file mode 100644 index 00000000000..ebe79c190c9 --- /dev/null +++ b/solutions/387. First Unique Character in a String/387.java @@ -0,0 +1,14 @@ +class Solution { + public int firstUniqChar(String s) { + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (int i = 0; i < s.length(); ++i) + if (count[s.charAt(i) - 'a'] == 1) + return i; + + return -1; + } +} diff --git a/solutions/387. First Unique Character in a String/387.py b/solutions/387. First Unique Character in a String/387.py new file mode 100644 index 00000000000..aadc7893351 --- /dev/null +++ b/solutions/387. First Unique Character in a String/387.py @@ -0,0 +1,9 @@ +class Solution: + def firstUniqChar(self, s: str) -> int: + count = collections.Counter(s) + + for i, c in enumerate(s): + if count[c] == 1: + return i + + return -1 diff --git a/solutions/388. Longest Absolute File Path/388.cpp b/solutions/388. Longest Absolute File Path/388.cpp new file mode 100644 index 00000000000..c8cc9e5d054 --- /dev/null +++ b/solutions/388. Longest Absolute File Path/388.cpp @@ -0,0 +1,32 @@ +struct T { + int depth; + size_t length; + T(int depth, size_t length) : depth(depth), length(length) {} +}; + +class Solution { + public: + int lengthLongestPath(string input) { + size_t ans = 0; + stack stack{{{-1, 0}}}; // placeholder + istringstream iss(input); + + for (string token; getline(iss, token, '\n');) { + const int depth = ranges::count(token, '\t'); + std::erase(token, '\t'); + while (depth <= stack.top().depth) + stack.pop(); + if (isFile(token)) + ans = max(ans, stack.top().length + token.length()); + else // directory + '/' + stack.emplace(depth, stack.top().length + token.length() + 1); + } + + return ans; + } + + private: + bool isFile(const string& token) { + return token.find('.') != string::npos; + } +}; diff --git a/solutions/388. Longest Absolute File Path/388.java b/solutions/388. Longest Absolute File Path/388.java new file mode 100644 index 00000000000..92cde658448 --- /dev/null +++ b/solutions/388. Longest Absolute File Path/388.java @@ -0,0 +1,33 @@ +class T { + public int depth; + public int length; + public T(int depth, int length) { + this.depth = depth; + this.length = length; + } +} + +class Solution { + public int lengthLongestPath(String input) { + int ans = 0; + Deque stack = new ArrayDeque<>(); + stack.push(new T(-1, 0)); + + for (String token : input.split("\n")) { + final int depth = getDepth(token); + token = token.replace("\t", ""); + while (depth <= stack.peek().depth) + stack.pop(); + if (token.contains(".")) // `token` is file. + ans = Math.max(ans, stack.peek().length + token.length()); + else // directory + '/' + stack.push(new T(depth, stack.peek().length + token.length() + 1)); + } + + return ans; + } + + private int getDepth(final String token) { + return (int) token.chars().filter(c -> c == '\t').count(); + } +} diff --git a/solutions/388. Longest Absolute File Path/388.py b/solutions/388. Longest Absolute File Path/388.py new file mode 100644 index 00000000000..d27d430a6a5 --- /dev/null +++ b/solutions/388. Longest Absolute File Path/388.py @@ -0,0 +1,16 @@ +class Solution: + def lengthLongestPath(self, input: str) -> int: + ans = 0 + stack = [(-1, 0)] # placeholder + + for token in input.split('\n'): + depth = token.count('\t') + token = token.replace('\t', '') + while depth <= stack[-1][0]: + stack.pop() + if '.' in token: # `token` is file. + ans = max(ans, stack[-1][1] + len(token)) + else: # directory + '/' + stack.append((depth, stack[-1][1] + len(token) + 1)) + + return ans diff --git a/solutions/389. Find the Difference/389-2.cpp b/solutions/389. Find the Difference/389-2.cpp new file mode 100644 index 00000000000..ceb1ac82ae1 --- /dev/null +++ b/solutions/389. Find the Difference/389-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + char findTheDifference(string s, string t) { + vector count(26); + + for (const char c : s) + ++count[c - 'a']; + + for (const char c : t) { + if (count[c - 'a'] == 0) + return c; + --count[c - 'a']; + } + + throw; + } +}; diff --git a/solutions/389. Find the Difference/389-2.java b/solutions/389. Find the Difference/389-2.java new file mode 100644 index 00000000000..fc1ffd77d7e --- /dev/null +++ b/solutions/389. Find the Difference/389-2.java @@ -0,0 +1,16 @@ +class Solution { + public char findTheDifference(String s, String t) { + int[] count = new int[26]; + + for (final char c : s.toCharArray()) + ++count[c - 'a']; + + for (final char c : t.toCharArray()) { + if (count[c - 'a'] == 0) + return c; + --count[c - 'a']; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/389. Find the Difference/389-2.py b/solutions/389. Find the Difference/389-2.py new file mode 100644 index 00000000000..79ad8eb0cd0 --- /dev/null +++ b/solutions/389. Find the Difference/389-2.py @@ -0,0 +1,8 @@ +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + count = collections.Counter(s) + + for c in t: + if count[c] == 0: + return c + count[c] -= 1 diff --git a/solutions/389. Find the Difference/389.cpp b/solutions/389. Find the Difference/389.cpp new file mode 100644 index 00000000000..6ab04acf185 --- /dev/null +++ b/solutions/389. Find the Difference/389.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + char findTheDifference(string s, string t) { + const char sXors = accumulate(s.begin(), s.end(), 0, bit_xor<>()); + const char tXors = accumulate(t.begin(), t.end(), 0, bit_xor<>()); + return sXors ^ tXors; + } +}; diff --git a/solutions/389. Find the Difference/389.java b/solutions/389. Find the Difference/389.java new file mode 100644 index 00000000000..4acfe795112 --- /dev/null +++ b/solutions/389. Find the Difference/389.java @@ -0,0 +1,7 @@ +class Solution { + public char findTheDifference(String s, String t) { + final char sXors = (char) s.chars().reduce(0, (a, b) -> a ^ b); + final char tXors = (char) t.chars().reduce(0, (a, b) -> a ^ b); + return (char) (sXors ^ tXors); + } +} diff --git a/solutions/389. Find the Difference/389.py b/solutions/389. Find the Difference/389.py new file mode 100644 index 00000000000..25ca12f4aa0 --- /dev/null +++ b/solutions/389. Find the Difference/389.py @@ -0,0 +1,5 @@ +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + sXors = chr(functools.reduce(operator.xor, map(ord, s), 0)) + tXors = chr(functools.reduce(operator.xor, map(ord, t), 0)) + return chr(ord(sXors) ^ ord(tXors)) diff --git a/solutions/39. Combination Sum/39.cpp b/solutions/39. Combination Sum/39.cpp new file mode 100644 index 00000000000..00322f6a9a3 --- /dev/null +++ b/solutions/39. Combination Sum/39.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> combinationSum(vector& candidates, int target) { + vector> ans; + ranges::sort(candidates); + dfs(candidates, 0, target, {}, ans); + return ans; + } + + private: + void dfs(const vector& A, int s, int target, vector&& path, + vector>& ans) { + if (target < 0) + return; + if (target == 0) { + ans.push_back(path); + return; + } + + for (int i = s; i < A.size(); ++i) { + path.push_back(A[i]); + dfs(A, i, target - A[i], move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/39. Combination Sum/39.java b/solutions/39. Combination Sum/39.java new file mode 100644 index 00000000000..19cd81d5f98 --- /dev/null +++ b/solutions/39. Combination Sum/39.java @@ -0,0 +1,24 @@ +class Solution { + public List> combinationSum(int[] candidates, int target) { + List> ans = new ArrayList<>(); + Arrays.sort(candidates); + dfs(0, candidates, target, new ArrayList<>(), ans); + return ans; + } + + private void dfs(int s, int[] candidates, int target, List path, + List> ans) { + if (target < 0) + return; + if (target == 0) { + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = s; i < candidates.length; ++i) { + path.add(candidates[i]); + dfs(i, candidates, target - candidates[i], path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/39. Combination Sum/39.py b/solutions/39. Combination Sum/39.py new file mode 100644 index 00000000000..87c2f50810a --- /dev/null +++ b/solutions/39. Combination Sum/39.py @@ -0,0 +1,19 @@ +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + ans = [] + + def dfs(s: int, target: int, path: List[int]) -> None: + if target < 0: + return + if target == 0: + ans.append(path.clone()) + return + + for i in range(s, len(candidates)): + path.append(candidates[i]) + dfs(i, target - candidates[i], path) + path.pop() + + candidates.sort() + dfs(0, target, []) + return ans diff --git a/solutions/390. Elimination Game/390.cpp b/solutions/390. Elimination Game/390.cpp new file mode 100644 index 00000000000..31bbba78db9 --- /dev/null +++ b/solutions/390. Elimination Game/390.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int lastRemaining(int n) { + return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2)); + } +}; diff --git a/solutions/390. Elimination Game/390.java b/solutions/390. Elimination Game/390.java new file mode 100644 index 00000000000..84f6f8ab3e4 --- /dev/null +++ b/solutions/390. Elimination Game/390.java @@ -0,0 +1,5 @@ +class Solution { + public int lastRemaining(int n) { + return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2)); + } +} diff --git a/solutions/390. Elimination Game/390.py b/solutions/390. Elimination Game/390.py new file mode 100644 index 00000000000..a2957ff200d --- /dev/null +++ b/solutions/390. Elimination Game/390.py @@ -0,0 +1,3 @@ +class Solution: + def lastRemaining(self, n: int) -> int: + return 1 if n == 1 else 2 * (1 + n // 2 - self.lastRemaining(n // 2)) diff --git a/solutions/391. Perfect Rectangle/391.cpp b/solutions/391. Perfect Rectangle/391.cpp new file mode 100644 index 00000000000..5d8a45b07f5 --- /dev/null +++ b/solutions/391. Perfect Rectangle/391.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + bool isRectangleCover(vector>& rectangles) { + int area = 0; + int x1 = INT_MAX; + int y1 = INT_MAX; + int x2 = INT_MIN; + int y2 = INT_MIN; + unordered_set corners; + + for (const vector& r : rectangles) { + area += (r[2] - r[0]) * (r[3] - r[1]); + x1 = min(x1, r[0]); + y1 = min(y1, r[1]); + x2 = max(x2, r[2]); + y2 = max(y2, r[3]); + + // the four points of the current rectangle + const vector points{to_string(r[0]) + " " + to_string(r[1]), + to_string(r[0]) + " " + to_string(r[3]), + to_string(r[2]) + " " + to_string(r[1]), + to_string(r[2]) + " " + to_string(r[3])}; + for (const string& point : points) + if (!corners.insert(point).second) + corners.erase(point); + } + + if (corners.size() != 4) + return false; + if (!corners.contains(to_string(x1) + " " + to_string(y1)) || + !corners.contains(to_string(x1) + " " + to_string(y2)) || + !corners.contains(to_string(x2) + " " + to_string(y1)) || + !corners.contains(to_string(x2) + " " + to_string(y2))) + return false; + return area == (x2 - x1) * (y2 - y1); + } +}; diff --git a/solutions/391. Perfect Rectangle/391.java b/solutions/391. Perfect Rectangle/391.java new file mode 100644 index 00000000000..ff926738075 --- /dev/null +++ b/solutions/391. Perfect Rectangle/391.java @@ -0,0 +1,36 @@ +class Solution { + public boolean isRectangleCover(int[][] rectangles) { + int area = 0; + int x1 = Integer.MAX_VALUE; + int y1 = Integer.MAX_VALUE; + int x2 = Integer.MIN_VALUE; + int y2 = Integer.MIN_VALUE; + Set corners = new HashSet<>(); + + for (int[] r : rectangles) { + area += (r[2] - r[0]) * (r[3] - r[1]); + x1 = Math.min(x1, r[0]); + y1 = Math.min(y1, r[1]); + x2 = Math.max(x2, r[2]); + y2 = Math.max(y2, r[3]); + + // the four points of the current rectangle + String[] points = new String[] {r[0] + " " + r[1], // + r[0] + " " + r[3], // + r[2] + " " + r[1], // + r[2] + " " + r[3]}; + for (final String point : points) + if (!corners.add(point)) + corners.remove(point); + } + + if (corners.size() != 4) + return false; + if (!corners.contains(x1 + " " + y1) || // + !corners.contains(x1 + " " + y2) || // + !corners.contains(x2 + " " + y1) || // + !corners.contains(x2 + " " + y2)) + return false; + return area == (x2 - x1) * (y2 - y1); + } +} diff --git a/solutions/391. Perfect Rectangle/391.py b/solutions/391. Perfect Rectangle/391.py new file mode 100644 index 00000000000..42f9304229f --- /dev/null +++ b/solutions/391. Perfect Rectangle/391.py @@ -0,0 +1,31 @@ +class Solution: + def isRectangleCover(self, rectangles: List[List[int]]) -> bool: + area = 0 + x1 = math.inf + y1 = math.inf + x2 = -math.inf + y2 = -math.inf + corners: Set[Tuple[int, int]] = set() + + for x, y, a, b in rectangles: + area += (a - x) * (b - y) + x1 = min(x1, x) + y1 = min(y1, y) + x2 = max(x2, a) + y2 = max(y2, b) + + # the four points of the current rectangle + for point in [(x, y), (x, b), (a, y), (a, b)]: + if point in corners: + corners.remove(point) + else: + corners.add(point) + + if len(corners) != 4: + return False + if (x1, y1) not in corners or \ + (x1, y2) not in corners or \ + (x2, y1) not in corners or \ + (x2, y2) not in corners: + return False + return area == (x2 - x1) * (y2 - y1) diff --git a/solutions/392. Is Subsequence/392.cpp b/solutions/392. Is Subsequence/392.cpp new file mode 100644 index 00000000000..8ab421b312a --- /dev/null +++ b/solutions/392. Is Subsequence/392.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + bool isSubsequence(string s, string t) { + if (s.empty()) + return true; + + int i = 0; + for (const char c : t) + if (s[i] == c && ++i == s.length()) + return true; + + return false; + } +}; diff --git a/solutions/392. Is Subsequence/392.java b/solutions/392. Is Subsequence/392.java new file mode 100644 index 00000000000..617a27ad9d4 --- /dev/null +++ b/solutions/392. Is Subsequence/392.java @@ -0,0 +1,13 @@ +class Solution { + public boolean isSubsequence(String s, String t) { + if (s.isEmpty()) + return true; + + int i = 0; + for (final char c : t.toCharArray()) + if (s.charAt(i) == c && ++i == s.length()) + return true; + + return false; + } +} diff --git a/solutions/392. Is Subsequence/392.py b/solutions/392. Is Subsequence/392.py new file mode 100644 index 00000000000..5561aac7517 --- /dev/null +++ b/solutions/392. Is Subsequence/392.py @@ -0,0 +1,13 @@ +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + if not s: + return True + + i = 0 + for c in t: + if s[i] == c: + i += 1 + if i == len(s): + return True + + return False diff --git a/solutions/393. UTF-8 Validation/393.cpp b/solutions/393. UTF-8 Validation/393.cpp new file mode 100644 index 00000000000..de439143190 --- /dev/null +++ b/solutions/393. UTF-8 Validation/393.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + bool validUtf8(vector& data) { + int followedBytes = 0; + + for (const int d : data) + if (followedBytes == 0) { + if ((d >> 3) == 0b11110) + followedBytes = 3; + else if ((d >> 4) == 0b1110) + followedBytes = 2; + else if ((d >> 5) == 0b110) + followedBytes = 1; + else if ((d >> 7) == 0b0) + followedBytes = 0; + else + return false; + } else { + if ((d >> 6) != 0b10) + return false; + --followedBytes; + } + + return followedBytes == 0; + } +}; diff --git a/solutions/393. UTF-8 Validation/393.java b/solutions/393. UTF-8 Validation/393.java new file mode 100644 index 00000000000..c172a852af4 --- /dev/null +++ b/solutions/393. UTF-8 Validation/393.java @@ -0,0 +1,25 @@ +class Solution { + public boolean validUtf8(int[] data) { + int followedBytes = 0; + + for (final int d : data) + if (followedBytes == 0) { + if ((d >> 3) == 0b11110) + followedBytes = 3; + else if ((d >> 4) == 0b1110) + followedBytes = 2; + else if ((d >> 5) == 0b110) + followedBytes = 1; + else if ((d >> 7) == 0b0) + followedBytes = 0; + else + return false; + } else { + if ((d >> 6) != 0b10) + return false; + --followedBytes; + } + + return followedBytes == 0; + } +} diff --git a/solutions/393. UTF-8 Validation/393.py b/solutions/393. UTF-8 Validation/393.py new file mode 100644 index 00000000000..0794cb70f9c --- /dev/null +++ b/solutions/393. UTF-8 Validation/393.py @@ -0,0 +1,22 @@ +class Solution: + def validUtf8(self, data: List[int]) -> bool: + followedBytes = 0 + + for d in data: + if followedBytes == 0: + if (d >> 3) == 0b11110: + followedBytes = 3 + elif (d >> 4) == 0b1110: + followedBytes = 2 + elif (d >> 5) == 0b110: + followedBytes = 1 + elif (d >> 7) == 0b0: + followedBytes = 0 + else: + return False + else: + if (d >> 6) != 0b10: + return False + followedBytes -= 1 + + return followedBytes == 0 diff --git a/solutions/394. Decode String/394-2.cpp b/solutions/394. Decode String/394-2.cpp new file mode 100644 index 00000000000..86814b3de59 --- /dev/null +++ b/solutions/394. Decode String/394-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string decodeString(string s) { + string ans; + + while (i < s.length() && s[i] != ']') + if (isdigit(s[i])) { + int k = 0; + while (i < s.length() && isdigit(s[i])) + k = k * 10 + (s[i++] - '0'); + ++i; // '[' + const string& decodedString = decodeString(s); + ++i; // ']' + while (k-- > 0) + ans += decodedString; + } else { + ans += s[i++]; + } + + return ans; + } + + private: + int i = 0; +}; diff --git a/solutions/394. Decode String/394-2.java b/solutions/394. Decode String/394-2.java new file mode 100644 index 00000000000..829a6143783 --- /dev/null +++ b/solutions/394. Decode String/394-2.java @@ -0,0 +1,23 @@ +class Solution { + public String decodeString(String s) { + StringBuilder sb = new StringBuilder(); + + while (i < s.length() && s.charAt(i) != ']') + if (Character.isDigit(s.charAt(i))) { + int k = 0; + while (i < s.length() && Character.isDigit(s.charAt(i))) + k = k * 10 + (s.charAt(i++) - '0'); + ++i; // '[' + final String decodedString = decodeString(s); + ++i; // ']' + while (k-- > 0) + sb.append(decodedString); + } else { + sb.append(s.charAt(i++)); + } + + return sb.toString(); + } + + private int i = 0; +} diff --git a/solutions/394. Decode String/394-2.py b/solutions/394. Decode String/394-2.py new file mode 100644 index 00000000000..e648122e60d --- /dev/null +++ b/solutions/394. Decode String/394-2.py @@ -0,0 +1,21 @@ +class Solution: + def decodeString(self, s: str) -> str: + ans = '' + + while self.i < len(s) and s[self.i] != ']': + if s[self.i].isdigit(): + k = 0 + while self.i < len(s) and s[self.i].isdigit(): + k = k * 10 + int(s[self.i]) + self.i += 1 + self.i += 1 # '[' + decodedString = self.decodeString(s) + self.i += 1 # ']' + ans += k * decodedString + else: + ans += s[self.i] + self.i += 1 + + return ans + + i = 0 diff --git a/solutions/394. Decode String/394.cpp b/solutions/394. Decode String/394.cpp new file mode 100644 index 00000000000..5a6948392ca --- /dev/null +++ b/solutions/394. Decode String/394.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + string decodeString(string s) { + stack> stack; // (prevStr, repeatCount) + string currStr; + int currNum = 0; + + for (const char c : s) + if (isdigit(c)) { + currNum = currNum * 10 + (c - '0'); + } else { + if (c == '[') { + stack.emplace(currStr, currNum); + currStr = ""; + currNum = 0; + } else if (c == ']') { + const auto [prevStr, n] = stack.top(); + stack.pop(); + currStr = prevStr + getRepeatedStr(currStr, n); + } else { + currStr += c; + } + } + + return currStr; + } + + private: + // Returns s * n. + string getRepeatedStr(const string& s, int n) { + string repeat; + while (n--) + repeat += s; + return repeat; + } +}; diff --git a/solutions/394. Decode String/394.java b/solutions/394. Decode String/394.java new file mode 100644 index 00000000000..2d7aeef937f --- /dev/null +++ b/solutions/394. Decode String/394.java @@ -0,0 +1,35 @@ +class Solution { + public String decodeString(String s) { + Stack> stack = new Stack<>(); // (prevStr, repeatCount) + StringBuilder currStr = new StringBuilder(); + int currNum = 0; + + for (final char c : s.toCharArray()) + if (Character.isDigit(c)) { + currNum = currNum * 10 + (c - '0'); + } else { + if (c == '[') { + stack.push(new Pair<>(currStr, currNum)); + currStr = new StringBuilder(); + currNum = 0; + } else if (c == ']') { + final Pair pair = stack.pop(); + final StringBuilder prevStr = pair.getKey(); + final int n = pair.getValue(); + currStr = prevStr.append(getRepeatedStr(currStr, n)); + } else { + currStr.append(c); + } + } + + return currStr.toString(); + } + + // Returns s * n. + private StringBuilder getRepeatedStr(StringBuilder s, int n) { + StringBuilder sb = new StringBuilder(); + while (n-- > 0) + sb.append(s); + return sb; + } +} diff --git a/solutions/394. Decode String/394.py b/solutions/394. Decode String/394.py new file mode 100644 index 00000000000..fbcbed83e3f --- /dev/null +++ b/solutions/394. Decode String/394.py @@ -0,0 +1,21 @@ +class Solution: + def decodeString(self, s: str) -> str: + stack = [] # (prevStr, repeatCount) + currStr = '' + currNum = 0 + + for c in s: + if c.isdigit(): + currNum = currNum * 10 + int(c) + else: + if c == '[': + stack.append((currStr, currNum)) + currStr = '' + currNum = 0 + elif c == ']': + prevStr, num = stack.pop() + currStr = prevStr + num * currStr + else: + currStr += c + + return currStr diff --git a/solutions/395. Longest Substring with At Least K Repeating Characters/395.cpp b/solutions/395. Longest Substring with At Least K Repeating Characters/395.cpp new file mode 100644 index 00000000000..5d5b5d1712d --- /dev/null +++ b/solutions/395. Longest Substring with At Least K Repeating Characters/395.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int longestSubstring(string s, int k) { + int ans = 0; + for (int n = 1; n <= 26; ++n) + ans = max(ans, longestSubstringWithNUniqueLetters(s, k, n)); + return ans; + } + + private: + int longestSubstringWithNUniqueLetters(const string& s, int k, int n) { + int res = 0; + int uniqueLetters = 0; // the number of unique letters + int lettersHavingKFreq = 0; // the number of letters having frequency >= k + vector count(26); + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s[r] - 'a'] == 1) + ++uniqueLetters; + if (count[s[r] - 'a'] == k) + ++lettersHavingKFreq; + while (uniqueLetters > n) { + if (count[s[l] - 'a'] == k) + --lettersHavingKFreq; + if (--count[s[l] - 'a'] == 0) + --uniqueLetters; + ++l; + } + // Since both the number of unique letters and the number of letters + // having frequency >= k are equal to n, this is a valid window. + if (lettersHavingKFreq == n) // Implicit: uniqueLetters == n + res = max(res, r - l + 1); + } + + return res; + } +}; diff --git a/solutions/395. Longest Substring with At Least K Repeating Characters/395.java b/solutions/395. Longest Substring with At Least K Repeating Characters/395.java new file mode 100644 index 00000000000..3e96556e4c9 --- /dev/null +++ b/solutions/395. Longest Substring with At Least K Repeating Characters/395.java @@ -0,0 +1,35 @@ +class Solution { + public int longestSubstring(String s, int k) { + int ans = 0; + for (int n = 1; n <= 26; ++n) + ans = Math.max(ans, longestSubstringWithNUniqueLetters(s, k, n)); + return ans; + } + + private int longestSubstringWithNUniqueLetters(final String s, int k, int n) { + int res = 0; + int uniqueLetters = 0; // the number of unique letters + int lettersHavingKFreq = 0; // the number of letters having frequency >= k + int[] count = new int[26]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (++count[s.charAt(r) - 'a'] == 1) + ++uniqueLetters; + if (count[s.charAt(r) - 'a'] == k) + ++lettersHavingKFreq; + while (uniqueLetters > n) { + if (count[s.charAt(l) - 'a'] == k) + --lettersHavingKFreq; + if (--count[s.charAt(l) - 'a'] == 0) + --uniqueLetters; + ++l; + } + // Since both the number of unique letters and the number of letters + // having frequency >= k are equal to n, this is a valid window. + if (lettersHavingKFreq == n) // Implicit: uniqueLetters == n + res = Math.max(res, r - l + 1); + } + + return res; + } +} diff --git a/solutions/395. Longest Substring with At Least K Repeating Characters/395.py b/solutions/395. Longest Substring with At Least K Repeating Characters/395.py new file mode 100644 index 00000000000..eb5750c2c23 --- /dev/null +++ b/solutions/395. Longest Substring with At Least K Repeating Characters/395.py @@ -0,0 +1,31 @@ +class Solution: + def longestSubstring(self, s: str, k: int) -> int: + def longestSubstringWithNUniqueLetters(n: int) -> int: + res = 0 + uniqueLetters = 0 # the number of unique letters + lettersHavingKFreq = 0 # the number of letters having frequency >= k + count = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + if count[c] == 1: + uniqueLetters += 1 + if count[c] == k: + lettersHavingKFreq += 1 + while uniqueLetters > n: + if count[s[l]] == k: + lettersHavingKFreq -= 1 + count[s[l]] -= 1 + if count[s[l]] == 0: + uniqueLetters -= 1 + l += 1 + # Since both the number of unique letters and the number of letters + # having frequency >= k are equal to n, this is a valid window. + if lettersHavingKFreq == n: # Implicit: uniqueLetters == n + res = max(res, r - l + 1) + + return res + + return max(longestSubstringWithNUniqueLetters(n) + for n in range(1, 27)) diff --git a/solutions/396. Rotate Function/396.cpp b/solutions/396. Rotate Function/396.cpp new file mode 100644 index 00000000000..3da76dab80b --- /dev/null +++ b/solutions/396. Rotate Function/396.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxRotateFunction(vector& nums) { + const int sum = accumulate(nums.begin(), nums.end(), 0); + int f = 0; + + // Calculate F(0) first. + for (int i = 0; i < nums.size(); ++i) + f += i * nums[i]; + + int ans = f; + + for (int i = nums.size() - 1; i > 0; --i) { + f += sum - nums.size() * nums[i]; + ans = max(ans, f); + } + + return ans; + } +}; diff --git a/solutions/396. Rotate Function/396.java b/solutions/396. Rotate Function/396.java new file mode 100644 index 00000000000..fe83c251c70 --- /dev/null +++ b/solutions/396. Rotate Function/396.java @@ -0,0 +1,19 @@ +class Solution { + public int maxRotateFunction(int[] nums) { + final int sum = Arrays.stream(nums).sum(); + int f = 0; + + // Calculate F(0) first. + for (int i = 0; i < nums.length; ++i) + f += i * nums[i]; + + int ans = f; + + for (int i = nums.length - 1; i >= 0; --i) { + f += sum - nums.length * nums[i]; + ans = Math.max(ans, f); + } + + return ans; + } +} diff --git a/solutions/396. Rotate Function/396.py b/solutions/396. Rotate Function/396.py new file mode 100644 index 00000000000..a9d1fc92161 --- /dev/null +++ b/solutions/396. Rotate Function/396.py @@ -0,0 +1,11 @@ +class Solution: + def maxRotateFunction(self, nums: List[int]) -> int: + f = sum(i * num for i, num in enumerate(nums)) + ans = f + summ = sum(nums) + + for a in reversed(nums): + f += summ - len(nums) * a + ans = max(ans, f) + + return ans diff --git a/solutions/397. Integer Replacement/397.cpp b/solutions/397. Integer Replacement/397.cpp new file mode 100644 index 00000000000..24512582953 --- /dev/null +++ b/solutions/397. Integer Replacement/397.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int integerReplacement(long n) { + int ans = 0; + + for (; n > 1; ++ans) + if (n % 2 == 0) // `n` ends in 0. + n >>= 1; + else if (n == 3 || (n >> 1 & 1) == 0) // `n` = 3 or ends in 0b01. + --n; + else // `n` ends in 0b11. + ++n; + + return ans; + } +}; diff --git a/solutions/397. Integer Replacement/397.java b/solutions/397. Integer Replacement/397.java new file mode 100644 index 00000000000..e018cdcefad --- /dev/null +++ b/solutions/397. Integer Replacement/397.java @@ -0,0 +1,15 @@ +class Solution { + public int integerReplacement(long n) { + int ans = 0; + + for (; n > 1; ++ans) + if (n % 2 == 0) // `n` ends in 0. + n >>= 1; + else if (n == 3 || (n >> 1 & 1) == 0) // `n` = 3 or ends in 0b01. + --n; + else // `n` ends in 0b11. + ++n; + + return ans; + } +} diff --git a/solutions/397. Integer Replacement/397.py b/solutions/397. Integer Replacement/397.py new file mode 100644 index 00000000000..ef32fc99387 --- /dev/null +++ b/solutions/397. Integer Replacement/397.py @@ -0,0 +1,14 @@ +class Solution: + def integerReplacement(self, n: int) -> int: + ans = 0 + + while n > 1: + if n % 2 == 0: # `n` ends in 0. + n >>= 1 + elif n == 3 or (n >> 1 & 1) == 0: # `n` = 3 or ends in 0b01. + n -= 1 + else: # `n` ends in 0b11. + n += 1 + ans += 1 + + return ans diff --git a/solutions/398. Random Pick Index/398.cpp b/solutions/398. Random Pick Index/398.cpp new file mode 100644 index 00000000000..88b473d8a64 --- /dev/null +++ b/solutions/398. Random Pick Index/398.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + Solution(vector& nums) : nums(move(nums)) {} + + int pick(int target) { + int ans = -1; + int range = 0; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == target && rand() % ++range == 0) + ans = i; + + return ans; + } + + private: + vector nums; +}; diff --git a/solutions/398. Random Pick Index/398.java b/solutions/398. Random Pick Index/398.java new file mode 100644 index 00000000000..b4908ac99a4 --- /dev/null +++ b/solutions/398. Random Pick Index/398.java @@ -0,0 +1,19 @@ +class Solution { + public Solution(int[] nums) { + this.nums = nums; + } + + public int pick(int target) { + int ans = -1; + int range = 0; + + for (int i = 0; i < nums.length; ++i) + if (nums[i] == target && rand.nextInt(++range) == 0) + ans = i; + + return ans; + } + + private int[] nums; + private Random rand = new Random(); +} diff --git a/solutions/398. Random Pick Index/398.py b/solutions/398. Random Pick Index/398.py new file mode 100644 index 00000000000..62a7ec38118 --- /dev/null +++ b/solutions/398. Random Pick Index/398.py @@ -0,0 +1,13 @@ +class Solution: + def __init__(self, nums: List[int]): + self.nums = nums + + def pick(self, target: int) -> int: + ans = -1 + rng = 0 + for i, num in enumerate(self.nums): + if num == target: + rng += 1 + if random.randint(0, rng - 1) == 0: + ans = i + return ans diff --git a/solutions/399. Evaluate Division/399.cpp b/solutions/399. Evaluate Division/399.cpp new file mode 100644 index 00000000000..53d76c8cdb5 --- /dev/null +++ b/solutions/399. Evaluate Division/399.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + vector calcEquation(vector>& equations, + vector& values, + vector>& queries) { + vector ans; + // graph[A][B] := A / B + unordered_map> graph; + + for (int i = 0; i < equations.size(); ++i) { + const string& A = equations[i][0]; + const string& B = equations[i][1]; + graph[A][B] = values[i]; + graph[B][A] = 1 / values[i]; + } + + for (const vector& query : queries) { + const string& A = query[0]; + const string& C = query[1]; + if (!graph.contains(A) || !graph.contains(C)) + ans.push_back(-1); + else + ans.push_back(divide(graph, A, C, unordered_set())); + } + + return ans; + } + + private: + // Returns A / C. + double divide( + const unordered_map>& graph, + const string& A, const string& C, unordered_set&& seen) { + if (A == C) + return 1.0; + + seen.insert(A); + + // value := A / B + for (const auto& [B, value] : graph.at(A)) { + if (seen.contains(B)) + continue; + const double res = divide(graph, B, C, move(seen)); // B / C + if (res > 0) // valid result + return value * res; // A / C = (A / B) * (B / C) + } + + return -1; // invalid result + } +}; diff --git a/solutions/399. Evaluate Division/399.java b/solutions/399. Evaluate Division/399.java new file mode 100644 index 00000000000..54d352e952c --- /dev/null +++ b/solutions/399. Evaluate Division/399.java @@ -0,0 +1,48 @@ +class Solution { + public double[] calcEquation(List> equations, double[] values, + List> queries) { + double[] ans = new double[queries.size()]; + // graph.get(A).get(B) := A / B + Map> graph = new HashMap<>(); + + // Construct the graph. + for (int i = 0; i < equations.size(); ++i) { + final String A = equations.get(i).get(0); + final String B = equations.get(i).get(1); + graph.putIfAbsent(A, new HashMap<>()); + graph.putIfAbsent(B, new HashMap<>()); + graph.get(A).put(B, values[i]); + graph.get(B).put(A, 1.0 / values[i]); + } + + for (int i = 0; i < queries.size(); ++i) { + final String A = queries.get(i).get(0); + final String C = queries.get(i).get(1); + if (!graph.containsKey(A) || !graph.containsKey(C)) + ans[i] = -1.0; + else + ans[i] = divide(graph, A, C, new HashSet<>()); + } + + return ans; + } + + // Returns A / C. + private double divide(Map> graph, final String A, final String C, + Set seen) { + if (A.equals(C)) + return 1.0; + + seen.add(A); + + for (final String B : graph.get(A).keySet()) { + if (seen.contains(B)) + continue; + final double res = divide(graph, B, C, seen); // B / C + if (res > 0) // valid result + return graph.get(A).get(B) * res; // A / C = (A / B) * (B / C) + } + + return -1.0; // invalid result + } +} diff --git a/solutions/399. Evaluate Division/399.py b/solutions/399. Evaluate Division/399.py new file mode 100644 index 00000000000..c1d2440cdc8 --- /dev/null +++ b/solutions/399. Evaluate Division/399.py @@ -0,0 +1,34 @@ +class Solution: + def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: + ans = [] + # graph[A][B] := A / B + graph = collections.defaultdict(dict) + + for (A, B), value in zip(equations, values): + graph[A][B] = value + graph[B][A] = 1 / value + + def devide(A: str, C: str, seen: Set[str]) -> float: + """Returns A / C.""" + if A == C: + return 1.0 + + seen.add(A) + + # value := A / B + for B, value in graph[A].items(): + if B in seen: + continue + res = devide(B, C, seen) # B / C + if res > 0: # valid result + return value * res # (A / B) * (B / C) = A / C + + return -1.0 # invalid result + + for A, C in queries: + if A not in graph or C not in graph: + ans.append(-1.0) + else: + ans.append(devide(A, C, set())) + + return ans diff --git a/solutions/4. Median of Two Sorted Arrays/4.cpp b/solutions/4. Median of Two Sorted Arrays/4.cpp new file mode 100644 index 00000000000..40cf03eabe9 --- /dev/null +++ b/solutions/4. Median of Two Sorted Arrays/4.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + const int n1 = nums1.size(); + const int n2 = nums2.size(); + if (n1 > n2) + return findMedianSortedArrays(nums2, nums1); + + int l = 0; + int r = n1; + + while (l <= r) { + const int partition1 = (l + r) / 2; + const int partition2 = (n1 + n2 + 1) / 2 - partition1; + const int maxLeft1 = partition1 == 0 ? INT_MIN : nums1[partition1 - 1]; + const int maxLeft2 = partition2 == 0 ? INT_MIN : nums2[partition2 - 1]; + const int minRight1 = partition1 == n1 ? INT_MAX : nums1[partition1]; + const int minRight2 = partition2 == n2 ? INT_MAX : nums2[partition2]; + if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) + return (n1 + n2) % 2 == 0 + ? (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5 + : max(maxLeft1, maxLeft2); + else if (maxLeft1 > minRight2) + r = partition1 - 1; + else + l = partition1 + 1; + } + + throw; + } +}; diff --git a/solutions/4. Median of Two Sorted Arrays/4.java b/solutions/4. Median of Two Sorted Arrays/4.java new file mode 100644 index 00000000000..5c84b85ad9f --- /dev/null +++ b/solutions/4. Median of Two Sorted Arrays/4.java @@ -0,0 +1,30 @@ +class Solution { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + final int n1 = nums1.length; + final int n2 = nums2.length; + if (n1 > n2) + return findMedianSortedArrays(nums2, nums1); + + int l = 0; + int r = n1; + + while (l <= r) { + final int partition1 = (l + r) / 2; + final int partition2 = (n1 + n2 + 1) / 2 - partition1; + final int maxLeft1 = partition1 == 0 ? Integer.MIN_VALUE : nums1[partition1 - 1]; + final int maxLeft2 = partition2 == 0 ? Integer.MIN_VALUE : nums2[partition2 - 1]; + final int minRight1 = partition1 == n1 ? Integer.MAX_VALUE : nums1[partition1]; + final int minRight2 = partition2 == n2 ? Integer.MAX_VALUE : nums2[partition2]; + if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) + return (n1 + n2) % 2 == 0 + ? (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) * 0.5 + : Math.max(maxLeft1, maxLeft2); + else if (maxLeft1 > minRight2) + r = partition1 - 1; + else + l = partition1 + 1; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/4. Median of Two Sorted Arrays/4.py b/solutions/4. Median of Two Sorted Arrays/4.py new file mode 100644 index 00000000000..9a98833dc74 --- /dev/null +++ b/solutions/4. Median of Two Sorted Arrays/4.py @@ -0,0 +1,23 @@ +class Solution: + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: + n1 = len(nums1) + n2 = len(nums2) + if n1 > n2: + return self.findMedianSortedArrays(nums2, nums1) + + l = 0 + r = n1 + + while l <= r: + partition1 = (l + r) // 2 + partition2 = (n1 + n2 + 1) // 2 - partition1 + maxLeft1 = -2**31 if partition1 == 0 else nums1[partition1 - 1] + maxLeft2 = -2**31 if partition2 == 0 else nums2[partition2 - 1] + minRight1 = 2**31 - 1 if partition1 == n1 else nums1[partition1] + minRight2 = 2**31 - 1 if partition2 == n2 else nums2[partition2] + if maxLeft1 <= minRight2 and maxLeft2 <= minRight1: + return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5 if (n1 + n2) % 2 == 0 else max(maxLeft1, maxLeft2) + elif maxLeft1 > minRight2: + r = partition1 - 1 + else: + l = partition1 + 1 diff --git a/solutions/40. Combination Sum II/40.cpp b/solutions/40. Combination Sum II/40.cpp new file mode 100644 index 00000000000..def2a0d8f6b --- /dev/null +++ b/solutions/40. Combination Sum II/40.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector> combinationSum2(vector& candidates, int target) { + vector> ans; + ranges::sort(candidates); + dfs(candidates, 0, target, {}, ans); + return ans; + } + + private: + void dfs(const vector& A, int s, int target, vector&& path, + vector>& ans) { + if (target < 0) + return; + if (target == 0) { + ans.push_back(path); + return; + } + + for (int i = s; i < A.size(); ++i) { + if (i > s && A[i] == A[i - 1]) + continue; + path.push_back(A[i]); + dfs(A, i + 1, target - A[i], move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/40. Combination Sum II/40.java b/solutions/40. Combination Sum II/40.java new file mode 100644 index 00000000000..ab5f11ec786 --- /dev/null +++ b/solutions/40. Combination Sum II/40.java @@ -0,0 +1,26 @@ +class Solution { + public List> combinationSum2(int[] candidates, int target) { + List> ans = new ArrayList<>(); + Arrays.sort(candidates); + dfs(0, candidates, target, new ArrayList<>(), ans); + return ans; + } + + private void dfs(int s, int[] candidates, int target, List path, + List> ans) { + if (target < 0) + return; + if (target == 0) { + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = s; i < candidates.length; ++i) { + if (i > s && candidates[i] == candidates[i - 1]) + continue; + path.add(candidates[i]); + dfs(i + 1, candidates, target - candidates[i], path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/40. Combination Sum II/40.py b/solutions/40. Combination Sum II/40.py new file mode 100644 index 00000000000..0f1cc70a780 --- /dev/null +++ b/solutions/40. Combination Sum II/40.py @@ -0,0 +1,21 @@ +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + ans = [] + + def dfs(s: int, target: int, path: List[int]) -> None: + if target < 0: + return + if target == 0: + ans.append(path.copy()) + return + + for i in range(s, len(candidates)): + if i > s and candidates[i] == candidates[i - 1]: + continue + path.append(candidates[i]) + dfs(i + 1, target - candidates[i], path) + path.pop() + + candidates.sort() + dfs(0, target, []) + return ans diff --git a/solutions/400. Nth Digit/400.cpp b/solutions/400. Nth Digit/400.cpp new file mode 100644 index 00000000000..6cf1e27eb5d --- /dev/null +++ b/solutions/400. Nth Digit/400.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findNthDigit(int n) { + int digitSize = 1; + int startNum = 1; + long count = 9; + + while (digitSize * count < n) { + n -= digitSize * count; + ++digitSize; + startNum *= 10; + count *= 10; + } + + const int targetNum = startNum + (n - 1) / digitSize; + const int index = (n - 1) % digitSize; + return to_string(targetNum)[index] - '0'; + } +}; diff --git a/solutions/400. Nth Digit/400.java b/solutions/400. Nth Digit/400.java new file mode 100644 index 00000000000..3df78b11161 --- /dev/null +++ b/solutions/400. Nth Digit/400.java @@ -0,0 +1,18 @@ +class Solution { + public int findNthDigit(int n) { + int digitSize = 1; + int startNum = 1; + long count = 9; + + while (digitSize * count < n) { + n -= digitSize * count; + ++digitSize; + startNum *= 10; + count *= 10; + } + + final int targetNum = startNum + (n - 1) / digitSize; + final int index = (n - 1) % digitSize; + return String.valueOf(targetNum).charAt(index) - '0'; + } +} diff --git a/solutions/400. Nth Digit/400.py b/solutions/400. Nth Digit/400.py new file mode 100644 index 00000000000..6a22fc709b1 --- /dev/null +++ b/solutions/400. Nth Digit/400.py @@ -0,0 +1,23 @@ +class Solution: + def findNthDigit(self, n: int) -> int: + def getDigit(num: int, pos: int, digitSize: int): + if pos == 0: + return num % 10 + for _ in range(digitSize - pos): + num //= 10 + return num % 10 + + digitSize = 1 + startNum = 1 + count = 9 + + while digitSize * count < n: + n -= digitSize * count + digitSize += 1 + startNum *= 10 + count *= 10 + + targetNum = startNum + (n - 1) // digitSize + pos = n % digitSize + + return getDigit(targetNum, pos, digitSize) diff --git a/solutions/401. Binary Watch/401-2.cpp b/solutions/401. Binary Watch/401-2.cpp new file mode 100644 index 00000000000..9275ef15d1f --- /dev/null +++ b/solutions/401. Binary Watch/401-2.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + vector readBinaryWatch(int turnedOn) { + vector ans; + + for (unsigned h = 0; h < 12; ++h) + for (unsigned m = 0; m < 60; ++m) + if (popcount(h << 6 | m) == turnedOn) + ans.push_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m)); + + return ans; + } +}; diff --git a/solutions/401. Binary Watch/401-2.java b/solutions/401. Binary Watch/401-2.java new file mode 100644 index 00000000000..54d5fcbfbb2 --- /dev/null +++ b/solutions/401. Binary Watch/401-2.java @@ -0,0 +1,12 @@ +class Solution { + public List readBinaryWatch(int turnedOn) { + List ans = new LinkedList<>(); + + for (int h = 0; h < 12; ++h) + for (int m = 0; m < 60; ++m) + if (Integer.bitCount(h) + Integer.bitCount(m) == turnedOn) + ans.add(h + (m < 10 ? ":0" : ":") + m); + + return ans; + } +} diff --git a/solutions/401. Binary Watch/401-2.py b/solutions/401. Binary Watch/401-2.py new file mode 100644 index 00000000000..4098384ec3d --- /dev/null +++ b/solutions/401. Binary Watch/401-2.py @@ -0,0 +1,10 @@ +class Solution: + def readBinaryWatch(self, turnedOn: int) -> List[str]: + ans = [] + + for h in range(12): + for m in range(60): + if h.bit_count() + m.bit_count() == turnedOn: + ans.append(f'{h}:{m:02d}') + + return ans diff --git a/solutions/401. Binary Watch/401.cpp b/solutions/401. Binary Watch/401.cpp new file mode 100644 index 00000000000..8b45834e4d1 --- /dev/null +++ b/solutions/401. Binary Watch/401.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector readBinaryWatch(int turnedOn) { + vector ans; + dfs(turnedOn, 0, 0, 0, ans); + return ans; + } + + private: + static constexpr int hours[4] = {1, 2, 4, 8}; + static constexpr int minutes[6] = {1, 2, 4, 8, 16, 32}; + + void dfs(int turnedOn, int s, int h, int m, vector& ans) { + if (turnedOn == 0) { + string time = to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m); + ans.push_back(time); + return; + } + + for (int i = s; i < 4 + 6; ++i) + if (i < 4 && h + hours[i] < 12) + dfs(turnedOn - 1, i + 1, h + hours[i], m, ans); + else if (i >= 4 && m + minutes[i - 4] < 60) + dfs(turnedOn - 1, i + 1, h, m + minutes[i - 4], ans); + } +}; diff --git a/solutions/401. Binary Watch/401.java b/solutions/401. Binary Watch/401.java new file mode 100644 index 00000000000..42b0f34ae0c --- /dev/null +++ b/solutions/401. Binary Watch/401.java @@ -0,0 +1,24 @@ +class Solution { + public List readBinaryWatch(int turnedOn) { + List ans = new ArrayList<>(); + dfs(turnedOn, 0, 0, 0, ans); + return ans; + } + + private int[] hours = new int[] {1, 2, 4, 8}; + private int[] minutes = new int[] {1, 2, 4, 8, 16, 32}; + + private void dfs(int turnedOn, int s, int h, int m, List ans) { + if (turnedOn == 0) { + final String time = String.valueOf(h) + ":" + (m < 10 ? "0" : "") + String.valueOf(m); + ans.add(time); + return; + } + + for (int i = s; i < hours.length + minutes.length; ++i) + if (i < 4 && h + hours[i] < 12) + dfs(turnedOn - 1, i + 1, h + hours[i], m, ans); + else if (i >= 4 && m + minutes[i - 4] < 60) + dfs(turnedOn - 1, i + 1, h, m + minutes[i - 4], ans); + } +} diff --git a/solutions/401. Binary Watch/401.py b/solutions/401. Binary Watch/401.py new file mode 100644 index 00000000000..d0d5c4735b0 --- /dev/null +++ b/solutions/401. Binary Watch/401.py @@ -0,0 +1,20 @@ +class Solution: + def readBinaryWatch(self, turnedOn: int) -> List[str]: + ans = [] + hours = [1, 2, 4, 8] + minutes = [1, 2, 4, 8, 16, 32] + + def dfs(turnedOn: int, s: int, h: int, m: int) -> None: + if turnedOn == 0: + time = str(h) + ":" + (str(m).zfill(2)) + ans.append(time) + return + + for i in range(s, len(hours) + len(minutes)): + if i < 4 and h + hours[i] < 12: + dfs(turnedOn - 1, i + 1, h + hours[i], m) + elif i >= 4 and m + minutes[i - 4] < 60: + dfs(turnedOn - 1, i + 1, h, m + minutes[i - 4]) + + dfs(turnedOn, 0, 0, 0) + return ans diff --git a/solutions/402. Remove K Digits/402.cpp b/solutions/402. Remove K Digits/402.cpp new file mode 100644 index 00000000000..276dc6d33a5 --- /dev/null +++ b/solutions/402. Remove K Digits/402.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + string removeKdigits(string num, int k) { + if (num.length() == k) + return "0"; + + string ans; + vector stack; + + for (int i = 0; i < num.length(); ++i) { + while (k > 0 && !stack.empty() && stack.back() > num[i]) { + stack.pop_back(); + --k; + } + stack.push_back(num[i]); + } + + while (k-- > 0) + stack.pop_back(); + + for (const char c : stack) { + if (c == '0' && ans.empty()) + continue; + ans += c; + } + + return ans.empty() ? "0" : ans; + } +}; diff --git a/solutions/402. Remove K Digits/402.java b/solutions/402. Remove K Digits/402.java new file mode 100644 index 00000000000..7216569b626 --- /dev/null +++ b/solutions/402. Remove K Digits/402.java @@ -0,0 +1,28 @@ +class Solution { + public String removeKdigits(String num, int k) { + if (num.length() == k) + return "0"; + + StringBuilder sb = new StringBuilder(); + LinkedList stack = new LinkedList<>(); + + for (int i = 0; i < num.length(); ++i) { + while (k > 0 && !stack.isEmpty() && stack.getLast() > num.charAt(i)) { + stack.pollLast(); + --k; + } + stack.addLast(num.charAt(i)); + } + + while (k-- > 0) + stack.pollLast(); + + for (final char c : stack) { + if (c == '0' && sb.length() == 0) + continue; + sb.append(c); + } + + return sb.length() == 0 ? "0" : sb.toString(); + } +} diff --git a/solutions/402. Remove K Digits/402.py b/solutions/402. Remove K Digits/402.py new file mode 100644 index 00000000000..3e11f4439ba --- /dev/null +++ b/solutions/402. Remove K Digits/402.py @@ -0,0 +1,23 @@ +class Solution: + def removeKdigits(self, num: str, k: int) -> str: + if len(num) == k: + return '0' + + ans = [] + stack = [] + + for i, digit in enumerate(num): + while k > 0 and stack and stack[-1] > digit: + stack.pop() + k -= 1 + stack.append(digit) + + for _ in range(k): + stack.pop() + + for c in stack: + if c == '0' and not ans: + continue + ans.append(c) + + return ''.join(ans) if ans else '0' diff --git a/solutions/403. Frog Jump/403-2.cpp b/solutions/403. Frog Jump/403-2.cpp new file mode 100644 index 00000000000..74a8ddf9838 --- /dev/null +++ b/solutions/403. Frog Jump/403-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool canCross(vector& stones) { + const int n = stones.size(); + // dp[i][j] := true if a frog can make a size j jump from stones[i] + vector> dp(n, vector(n + 1)); + dp[0][1] = true; + + for (int i = 1; i < n; ++i) + for (int j = 0; j < i; ++j) { + const int k = stones[i] - stones[j]; + if (k <= n && dp[j][k]) { + dp[i][k - 1] = true; + dp[i][k] = true; + dp[i][k + 1] = true; + } + } + + return ranges::any_of(dp.back(), [](bool val) { return val; }); + } +}; diff --git a/solutions/403. Frog Jump/403-2.java b/solutions/403. Frog Jump/403-2.java new file mode 100644 index 00000000000..a22c1fc1f55 --- /dev/null +++ b/solutions/403. Frog Jump/403-2.java @@ -0,0 +1,20 @@ +class Solution { + public boolean canCross(int[] stones) { + final int n = stones.length; + // dp[i][j] := 1 if a frog can make a size j jump from stones[i] + int[][] dp = new int[n][n + 1]; + dp[0][1] = 1; + + for (int i = 1; i < n; ++i) + for (int j = 0; j < i; ++j) { + final int k = stones[i] - stones[j]; + if (k <= n && dp[j][k] == 1) { + dp[i][k - 1] = 1; + dp[i][k] = 1; + dp[i][k + 1] = 1; + } + } + + return Arrays.stream(dp[n - 1]).anyMatch(a -> a == 1); + } +} diff --git a/solutions/403. Frog Jump/403-2.py b/solutions/403. Frog Jump/403-2.py new file mode 100644 index 00000000000..d20b1df0e0c --- /dev/null +++ b/solutions/403. Frog Jump/403-2.py @@ -0,0 +1,16 @@ +class Solution: + def canCross(self, stones: List[int]) -> bool: + n = len(stones) + # dp[i][j] := True if a frog can make a size j jump from stones[i] + dp = [[False] * (n + 1) for _ in range(n)] + dp[0][1] = True + + for i in range(1, n): + for j in range(i): + k = stones[i] - stones[j] + if k <= n and dp[j][k]: + dp[i][k - 1] = True + dp[i][k] = True + dp[i][k + 1] = True + + return any(dp[-1]) diff --git a/solutions/403. Frog Jump/403.cpp b/solutions/403. Frog Jump/403.cpp new file mode 100644 index 00000000000..d19ee8e6549 --- /dev/null +++ b/solutions/403. Frog Jump/403.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool canCross(vector& stones) { + const int n = stones.size(); + // dp[i][j] := true if a frog can make a size j jump to stones[i] + vector> dp(n, vector(n + 1)); + dp[0][0] = true; + + for (int i = 1; i < n; ++i) + for (int j = 0; j < i; ++j) { + const int k = stones[i] - stones[j]; + if (k > n) + continue; + for (const int x : {k - 1, k, k + 1}) + if (0 <= x && x <= n) + dp[i][k] = dp[i][k] || dp[j][x]; + } + + return ranges::any_of(dp.back(), [](bool val) { return val; }); + } +}; diff --git a/solutions/403. Frog Jump/403.java b/solutions/403. Frog Jump/403.java new file mode 100644 index 00000000000..bcdc0cdb362 --- /dev/null +++ b/solutions/403. Frog Jump/403.java @@ -0,0 +1,20 @@ +class Solution { + public boolean canCross(int[] stones) { + final int n = stones.length; + // dp[i][j] := 1 if a frog can make a size j jump to stones[i] + int[][] dp = new int[n][n + 1]; + dp[0][0] = 1; + + for (int i = 1; i < n; ++i) + for (int j = 0; j < i; ++j) { + final int k = stones[i] - stones[j]; + if (k > n) + continue; + for (final int x : new int[] {k - 1, k, k + 1}) + if (0 <= x && x <= n) + dp[i][k] |= dp[j][x]; + } + + return Arrays.stream(dp[n - 1]).anyMatch(a -> a == 1); + } +} diff --git a/solutions/403. Frog Jump/403.py b/solutions/403. Frog Jump/403.py new file mode 100644 index 00000000000..53a488dbe0f --- /dev/null +++ b/solutions/403. Frog Jump/403.py @@ -0,0 +1,17 @@ +class Solution: + def canCross(self, stones: List[int]) -> bool: + n = len(stones) + # dp[i][j] := True if a frog can make a size j jump to stones[i] + dp = [[False] * (n + 1) for _ in range(n)] + dp[0][0] = True + + for i in range(1, n): + for j in range(i): + k = stones[i] - stones[j] + if k > n: + continue + for x in (k - 1, k, k + 1): + if 0 <= x <= n: + dp[i][k] |= dp[j][x] + + return any(dp[-1]) diff --git a/solutions/404. Sum of Left Leaves/404-2.cpp b/solutions/404. Sum of Left Leaves/404-2.cpp new file mode 100644 index 00000000000..1885ca648d9 --- /dev/null +++ b/solutions/404. Sum of Left Leaves/404-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int sumOfLeftLeaves(TreeNode* root) { + if (root == nullptr) + return 0; + + int ans = 0; + stack stack{{root}}; + + while (!stack.empty()) { + root = stack.top(), stack.pop(); + if (root->left) { + if (root->left->left == nullptr && root->left->right == nullptr) + ans += root->left->val; + else + stack.push(root->left); + } + if (root->right) + stack.push(root->right); + } + + return ans; + } +}; diff --git a/solutions/404. Sum of Left Leaves/404-2.java b/solutions/404. Sum of Left Leaves/404-2.java new file mode 100644 index 00000000000..e4c0ed46cf7 --- /dev/null +++ b/solutions/404. Sum of Left Leaves/404-2.java @@ -0,0 +1,24 @@ +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) + return 0; + + int ans = 0; + Deque stack = new ArrayDeque<>(); + stack.push(root); + + while (!stack.isEmpty()) { + root = stack.pop(); + if (root.left != null) { + if (root.left.left == null && root.left.right == null) + ans += root.left.val; + else + stack.push(root.left); + } + if (root.right != null) + stack.push(root.right); + } + + return ans; + } +} diff --git a/solutions/404. Sum of Left Leaves/404-2.py b/solutions/404. Sum of Left Leaves/404-2.py new file mode 100644 index 00000000000..0160600808e --- /dev/null +++ b/solutions/404. Sum of Left Leaves/404-2.py @@ -0,0 +1,19 @@ +class Solution: + def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + ans = 0 + stack = [root] + + while stack: + root = stack.pop() + if root.left: + if not root.left.left and not root.left.right: + ans += root.left.val + else: + stack.append(root.left) + if root.right: + stack.append(root.right) + + return ans diff --git a/solutions/404. Sum of Left Leaves/404.cpp b/solutions/404. Sum of Left Leaves/404.cpp new file mode 100644 index 00000000000..fa6e468b26d --- /dev/null +++ b/solutions/404. Sum of Left Leaves/404.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int sumOfLeftLeaves(TreeNode* root) { + if (root == nullptr) + return 0; + + int ans = 0; + + if (root->left) { + if (root->left->left == nullptr && root->left->right == nullptr) + ans += root->left->val; + else + ans += sumOfLeftLeaves(root->left); + } + ans += sumOfLeftLeaves(root->right); + + return ans; + } +}; diff --git a/solutions/404. Sum of Left Leaves/404.java b/solutions/404. Sum of Left Leaves/404.java new file mode 100644 index 00000000000..bd5a3fb55de --- /dev/null +++ b/solutions/404. Sum of Left Leaves/404.java @@ -0,0 +1,18 @@ +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) + return 0; + + int ans = 0; + + if (root.left != null) { + if (root.left.left == null && root.left.right == null) + ans += root.left.val; + else + ans += sumOfLeftLeaves(root.left); + } + ans += sumOfLeftLeaves(root.right); + + return ans; + } +} diff --git a/solutions/404. Sum of Left Leaves/404.py b/solutions/404. Sum of Left Leaves/404.py new file mode 100644 index 00000000000..160390ed393 --- /dev/null +++ b/solutions/404. Sum of Left Leaves/404.py @@ -0,0 +1,15 @@ +class Solution: + def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + ans = 0 + + if root.left: + if not root.left.left and not root.left.right: + ans += root.left.val + else: + ans += self.sumOfLeftLeaves(root.left) + ans += self.sumOfLeftLeaves(root.right) + + return ans diff --git a/solutions/405. Convert a Number to Hexadecimal/405.cpp b/solutions/405. Convert a Number to Hexadecimal/405.cpp new file mode 100644 index 00000000000..a382f4e3545 --- /dev/null +++ b/solutions/405. Convert a Number to Hexadecimal/405.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string toHex(unsigned num) { + if (num == 0) + return "0"; + + constexpr char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + string ans; + + while (num != 0) { + ans += hex[num & 0xf]; + num >>= 4; + } + + return {ans.rbegin(), ans.rend()}; + } +}; diff --git a/solutions/405. Convert a Number to Hexadecimal/405.java b/solutions/405. Convert a Number to Hexadecimal/405.java new file mode 100644 index 00000000000..3639ab6a216 --- /dev/null +++ b/solutions/405. Convert a Number to Hexadecimal/405.java @@ -0,0 +1,17 @@ +class Solution { + public String toHex(int num) { + if (num == 0) + return "0"; + + final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + StringBuilder sb = new StringBuilder(); + + while (num != 0) { + sb.append(hex[num & 0xf]); + num >>>= 4; + } + + return sb.reverse().toString(); + } +} diff --git a/solutions/405. Convert a Number to Hexadecimal/405.py b/solutions/405. Convert a Number to Hexadecimal/405.py new file mode 100644 index 00000000000..f97b35d7288 --- /dev/null +++ b/solutions/405. Convert a Number to Hexadecimal/405.py @@ -0,0 +1,19 @@ +class Solution: + def toHex(self, num: int) -> str: + if num == 0: + return '0' + + hex = '0123456789abcdef' + ans = [] + + # Handling negative numbers by using 32-bit unsigned representation Python's + # bitwise operation works on signed numbers, so we convert to 32-bit + # unsigned for negative numbers. + if num < 0: + num += 2**32 + + while num > 0: + ans.append(hex[num & 0xF]) + num >>= 4 + + return ''.join(reversed(ans)) diff --git a/solutions/406. Queue Reconstruction by Height/406.cpp b/solutions/406. Queue Reconstruction by Height/406.cpp new file mode 100644 index 00000000000..5bdccff9efd --- /dev/null +++ b/solutions/406. Queue Reconstruction by Height/406.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector> reconstructQueue(vector>& people) { + vector> ans; + + ranges::sort(people, [](const vector& a, const vector& b) { + return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0]; + }); + + for (const vector& p : people) + ans.insert(ans.begin() + p[1], p); + + return ans; + } +}; diff --git a/solutions/406. Queue Reconstruction by Height/406.java b/solutions/406. Queue Reconstruction by Height/406.java new file mode 100644 index 00000000000..1ec397c3935 --- /dev/null +++ b/solutions/406. Queue Reconstruction by Height/406.java @@ -0,0 +1,12 @@ +class Solution { + public int[][] reconstructQueue(int[][] people) { + List ans = new ArrayList<>(); + + Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); + + for (final int[] p : people) + ans.add(p[1], p); + + return ans.stream().toArray(int[][] ::new); + } +} diff --git a/solutions/406. Queue Reconstruction by Height/406.py b/solutions/406. Queue Reconstruction by Height/406.py new file mode 100644 index 00000000000..b50cb6ff4ed --- /dev/null +++ b/solutions/406. Queue Reconstruction by Height/406.py @@ -0,0 +1,10 @@ +class Solution: + def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: + ans = [] + + people.sort(key=lambda x: (-x[0], x[1])) + + for p in people: + ans.insert(p[1], p) + + return ans diff --git a/solutions/407. Trapping Rain Water II/407.cpp b/solutions/407. Trapping Rain Water II/407.cpp new file mode 100644 index 00000000000..02a17df2e8f --- /dev/null +++ b/solutions/407. Trapping Rain Water II/407.cpp @@ -0,0 +1,55 @@ +struct T { + int i; + int j; + int h; // heightMap[i][j] or the height after filling water + T(int i, int j, int h) : i(i), j(j), h(h) {} +}; + +class Solution { + public: + int trapRainWater(vector>& heightMap) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = heightMap.size(); + const int n = heightMap[0].size(); + int ans = 0; + auto compare = [](const T& a, const T& b) { return a.h > b.h; }; + priority_queue, decltype(compare)> minHeap(compare); + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) { + minHeap.emplace(i, 0, heightMap[i][0]); + minHeap.emplace(i, n - 1, heightMap[i][n - 1]); + seen[i][0] = true; + seen[i][n - 1] = true; + } + + for (int j = 1; j < n - 1; ++j) { + minHeap.emplace(0, j, heightMap[0][j]); + minHeap.emplace(m - 1, j, heightMap[m - 1][j]); + seen[0][j] = true; + seen[m - 1][j] = true; + } + + while (!minHeap.empty()) { + const auto [i, j, h] = minHeap.top(); + minHeap.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + if (heightMap[x][y] < h) { + ans += h - heightMap[x][y]; + minHeap.emplace(x, y, h); // Fill water in grid[x][y]. + } else { + minHeap.emplace(x, y, heightMap[x][y]); + } + seen[x][y] = true; + } + } + + return ans; + } +}; diff --git a/solutions/407. Trapping Rain Water II/407.java b/solutions/407. Trapping Rain Water II/407.java new file mode 100644 index 00000000000..505cae4f6f2 --- /dev/null +++ b/solutions/407. Trapping Rain Water II/407.java @@ -0,0 +1,58 @@ +class T { + public int i; + public int j; + public int h; // heightMap[i][j] or the height after filling water + public T(int i, int j, int h) { + this.i = i; + this.j = j; + this.h = h; + } +} + +class Solution { + public int trapRainWater(int[][] heightMap) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = heightMap.length; + final int n = heightMap[0].length; + int ans = 0; + Queue minHeap = new PriorityQueue<>((a, b) -> a.h - b.h); + boolean[][] seen = new boolean[m][n]; + + for (int i = 0; i < m; ++i) { + minHeap.offer(new T(i, 0, heightMap[i][0])); + minHeap.offer(new T(i, n - 1, heightMap[i][n - 1])); + seen[i][0] = true; + seen[i][n - 1] = true; + } + + for (int j = 1; j < n - 1; ++j) { + minHeap.offer(new T(0, j, heightMap[0][j])); + minHeap.offer(new T(m - 1, j, heightMap[m - 1][j])); + seen[0][j] = true; + seen[m - 1][j] = true; + } + + while (!minHeap.isEmpty()) { + final int i = minHeap.peek().i; + final int j = minHeap.peek().j; + final int h = minHeap.poll().h; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + if (heightMap[x][y] < h) { + ans += h - heightMap[x][y]; + minHeap.offer(new T(x, y, h)); // Fill water in grid[x][y]. + } else { + minHeap.offer(new T(x, y, heightMap[x][y])); + } + seen[x][y] = true; + } + } + + return ans; + } +} diff --git a/solutions/407. Trapping Rain Water II/407.py b/solutions/407. Trapping Rain Water II/407.py new file mode 100644 index 00000000000..f3afa5c3f70 --- /dev/null +++ b/solutions/407. Trapping Rain Water II/407.py @@ -0,0 +1,39 @@ +class Solution: + def trapRainWater(self, heightMap: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(heightMap) + n = len(heightMap[0]) + ans = 0 + minHeap = [] + seen = set() + + for i in range(m): + heapq.heappush(minHeap, (heightMap[i][0], i, 0)) + heapq.heappush(minHeap, (heightMap[i][n - 1], i, n - 1)) + seen.add((i, 0)) + seen.add((i, n - 1)) + + for j in range(1, n - 1): + heapq.heappush(minHeap, (heightMap[0][j], 0, j)) + heapq.heappush(minHeap, (heightMap[m - 1][j], m - 1, j)) + seen.add((0, j)) + seen.add((m - 1, j)) + + while minHeap: + h, i, j = heapq.heappop(minHeap) + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if (x, y) in seen: + continue + if heightMap[x][y] < h: + ans += h - heightMap[x][y] + # Fill water in grid[x][y]. + heapq.heappush(minHeap, (h, x, y)) + else: + heapq.heappush(minHeap, (heightMap[x][y], x, y)) + seen.add((x, y)) + + return ans diff --git a/solutions/408. Valid Word Abbreviation/408.cpp b/solutions/408. Valid Word Abbreviation/408.cpp new file mode 100644 index 00000000000..a4c392a07af --- /dev/null +++ b/solutions/408. Valid Word Abbreviation/408.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool validWordAbbreviation(const string& word, const string& abbr) { + int i = 0; // word's index + int j = 0; // abbr's index + + while (i < word.length() && j < abbr.length()) { + if (word[i] == abbr[j]) { + ++i; + ++j; + continue; + } + if (abbr[j] <= '0' || abbr[j] > '9') + return false; + int num = 0; + while (j < abbr.length() && isdigit(abbr[j])) { + num = num * 10 + abbr[j] - '0'; + ++j; + } + i += num; + } + + return i == word.length() && j == abbr.length(); + } +}; diff --git a/solutions/408. Valid Word Abbreviation/408.java b/solutions/408. Valid Word Abbreviation/408.java new file mode 100644 index 00000000000..adb19d622d7 --- /dev/null +++ b/solutions/408. Valid Word Abbreviation/408.java @@ -0,0 +1,24 @@ +class Solution { + public boolean validWordAbbreviation(String word, String abbr) { + int i = 0; // word's index + int j = 0; // abbr's index + + while (i < word.length() && j < abbr.length()) { + if (word.charAt(i) == abbr.charAt(j)) { + ++i; + ++j; + continue; + } + if (abbr.charAt(j) <= '0' || abbr.charAt(j) > '9') + return false; + int num = 0; + while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) { + num = num * 10 + abbr.charAt(j) - '0'; + ++j; + } + i += num; + } + + return i == word.length() && j == abbr.length(); + } +} diff --git a/solutions/408. Valid Word Abbreviation/408.py b/solutions/408. Valid Word Abbreviation/408.py new file mode 100644 index 00000000000..2bb87bded39 --- /dev/null +++ b/solutions/408. Valid Word Abbreviation/408.py @@ -0,0 +1,19 @@ +class Solution: + def validWordAbbreviation(self, word: str, abbr: str) -> bool: + i = 0 # word's index + j = 0 # abbr's index + + while i < len(word) and j < len(abbr): + if word[i] == abbr[j]: + i += 1 + j += 1 + continue + if not abbr[j].isdigit() or abbr[j] == '0': + return False + num = 0 + while j < len(abbr) and abbr[j].isdigit(): + num = num * 10 + int(abbr[j]) + j += 1 + i += num + + return i == len(word) and j == len(abbr) diff --git a/solutions/409. Longest Palindrome/409.cpp b/solutions/409. Longest Palindrome/409.cpp new file mode 100644 index 00000000000..4bb80e87008 --- /dev/null +++ b/solutions/409. Longest Palindrome/409.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int longestPalindrome(string s) { + int ans = 0; + vector count(128); + + for (const char c : s) + ++count[c]; + + for (const int freq : count) + ans += freq % 2 == 0 ? freq : freq - 1; + + const bool hasOddCount = + ranges::any_of(count, [](int c) { return c % 2 == 1; }); + return ans + hasOddCount; + } +}; diff --git a/solutions/409. Longest Palindrome/409.java b/solutions/409. Longest Palindrome/409.java new file mode 100644 index 00000000000..ce83b5293fb --- /dev/null +++ b/solutions/409. Longest Palindrome/409.java @@ -0,0 +1,15 @@ +class Solution { + public int longestPalindrome(String s) { + int ans = 0; + int[] count = new int[128]; + + for (final char c : s.toCharArray()) + ++count[c]; + + for (final int freq : count) + ans += freq % 2 == 0 ? freq : freq - 1; + + final boolean hasOddCount = Arrays.stream(count).anyMatch(freq -> freq % 2 == 1); + return ans + (hasOddCount ? 1 : 0); + } +} diff --git a/solutions/409. Longest Palindrome/409.py b/solutions/409. Longest Palindrome/409.py new file mode 100644 index 00000000000..c91602f388c --- /dev/null +++ b/solutions/409. Longest Palindrome/409.py @@ -0,0 +1,10 @@ +class Solution: + def longestPalindrome(self, s: str) -> int: + ans = 0 + count = collections.Counter(s) + + for c in count.values(): + ans += c if c % 2 == 0 else c - 1 + + hasOddCount = any(c % 2 == 1 for c in count.values()) + return ans + hasOddCount diff --git a/solutions/41. First Missing Positive/41.cpp b/solutions/41. First Missing Positive/41.cpp new file mode 100644 index 00000000000..748544aaa7f --- /dev/null +++ b/solutions/41. First Missing Positive/41.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int firstMissingPositive(vector& nums) { + const int n = nums.size(); + + // Correct slot: + // nums[i] = i + 1 + // nums[i] - 1 = i + // nums[nums[i] - 1] = nums[i] + for (int i = 0; i < n; ++i) + while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) + swap(nums[i], nums[nums[i] - 1]); + + for (int i = 0; i < n; ++i) + if (nums[i] != i + 1) + return i + 1; + + return n + 1; + } +}; diff --git a/solutions/41. First Missing Positive/41.java b/solutions/41. First Missing Positive/41.java new file mode 100644 index 00000000000..ae4ee8432dc --- /dev/null +++ b/solutions/41. First Missing Positive/41.java @@ -0,0 +1,25 @@ +class Solution { + public int firstMissingPositive(int[] nums) { + final int n = nums.length; + + // Correct slot: + // nums[i] = i + 1 + // nums[i] - 1 = i + // nums[nums[i] - 1] = nums[i] + for (int i = 0; i < n; ++i) + while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) + swap(nums, i, nums[i] - 1); + + for (int i = 0; i < n; ++i) + if (nums[i] != i + 1) + return i + 1; + + return n + 1; + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/41. First Missing Positive/41.py b/solutions/41. First Missing Positive/41.py new file mode 100644 index 00000000000..595f6d19a21 --- /dev/null +++ b/solutions/41. First Missing Positive/41.py @@ -0,0 +1,17 @@ +class Solution: + def firstMissingPositive(self, nums: List[int]) -> int: + n = len(nums) + + # Correct slot: + # nums[i] = i + 1 + # nums[i] - 1 = i + # nums[nums[i] - 1] = nums[i] + for i in range(n): + while nums[i] > 0 and nums[i] <= n and nums[nums[i] - 1] != nums[i]: + nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] + + for i, num in enumerate(nums): + if num != i + 1: + return i + 1 + + return n + 1 diff --git a/solutions/410. Split Array Largest Sum/410-2.cpp b/solutions/410. Split Array Largest Sum/410-2.cpp new file mode 100644 index 00000000000..ad214da5c6a --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int splitArray(vector& nums, int k) { + const int n = nums.size(); + // dp[i][k] := the minimum of the maximum sum to split the first i numbers + // into k groups + vector> dp(n + 1, vector(k + 1, INT_MAX)); + vector prefix(n + 1); + + partial_sum(nums.begin(), nums.end(), prefix.begin() + 1); + + for (int i = 1; i <= n; ++i) + dp[i][1] = prefix[i]; + + for (int l = 2; l <= k; ++l) + for (int i = l; i <= n; ++i) + for (int j = l - 1; j < i; ++j) + dp[i][l] = min(dp[i][l], max(dp[j][l - 1], prefix[i] - prefix[j])); + + return dp[n][k]; + } +}; diff --git a/solutions/410. Split Array Largest Sum/410-2.java b/solutions/410. Split Array Largest Sum/410-2.java new file mode 100644 index 00000000000..2d33bd9100e --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410-2.java @@ -0,0 +1,22 @@ +class Solution { + public int splitArray(int[] nums, int k) { + final int n = nums.length; + // dp[i][k] := the minimum of the maximum sum to split the first i numbers + // into k groups + int[][] dp = new int[n + 1][k + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + int[] prefix = new int[n + 1]; + + for (int i = 1; i <= n; ++i) { + prefix[i] = prefix[i - 1] + nums[i - 1]; + dp[i][1] = prefix[i]; + } + + for (int l = 2; l <= k; ++l) + for (int i = l; i <= n; ++i) + for (int j = l - 1; j < i; ++j) + dp[i][l] = Math.min(dp[i][l], Math.max(dp[j][l - 1], prefix[i] - prefix[j])); + + return dp[n][k]; + } +} diff --git a/solutions/410. Split Array Largest Sum/410-2.py b/solutions/410. Split Array Largest Sum/410-2.py new file mode 100644 index 00000000000..f8fe43896ac --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410-2.py @@ -0,0 +1,17 @@ +class Solution: + def splitArray(self, nums: List[int], k: int) -> int: + n = len(nums) + # dp[i][k] := the minimum of the maximum sum to split the first i numbers + # into k groups + dp = [[math.inf] * (k + 1) for _ in range(n + 1)] + prefix = [0] + list(itertools.accumulate(nums)) + + for i in range(1, n + 1): + dp[i][1] = prefix[i] + + for l in range(2, k + 1): + for i in range(l, n + 1): + for j in range(l - 1, i): + dp[i][l] = min(dp[i][l], max(dp[j][l - 1], prefix[i] - prefix[j])) + + return dp[n][k] diff --git a/solutions/410. Split Array Largest Sum/410-3.cpp b/solutions/410. Split Array Largest Sum/410-3.cpp new file mode 100644 index 00000000000..d80e7372d13 --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410-3.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int splitArray(vector& nums, int k) { + int l = ranges::max(nums); + int r = accumulate(nums.begin(), nums.end(), 0) + 1; + + while (l < r) { + const int m = (l + r) / 2; + if (numGroups(nums, m) > k) + l = m + 1; + else + r = m; + } + + return l; + } + + private: + int numGroups(const vector& nums, int maxSumInGroup) { + int groupCount = 1; + int sumInGroup = 0; + + for (const int num : nums) + if (sumInGroup + num <= maxSumInGroup) { + sumInGroup += num; + } else { + ++groupCount; + sumInGroup = num; + } + + return groupCount; + } +}; diff --git a/solutions/410. Split Array Largest Sum/410-3.java b/solutions/410. Split Array Largest Sum/410-3.java new file mode 100644 index 00000000000..c1f4fd7d130 --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410-3.java @@ -0,0 +1,31 @@ +class Solution { + public int splitArray(int[] nums, int k) { + int l = Arrays.stream(nums).max().getAsInt(); + int r = Arrays.stream(nums).sum() + 1; + + while (l < r) { + final int m = (l + r) / 2; + if (numGroups(nums, m) > k) + l = m + 1; + else + r = m; + } + + return l; + } + + private int numGroups(int[] nums, int maxSumInGroup) { + int groupCount = 1; + int sumInGroup = 0; + + for (final int num : nums) + if (sumInGroup + num <= maxSumInGroup) { + sumInGroup += num; + } else { + ++groupCount; + sumInGroup = num; + } + + return groupCount; + } +} diff --git a/solutions/410. Split Array Largest Sum/410-3.py b/solutions/410. Split Array Largest Sum/410-3.py new file mode 100644 index 00000000000..c9afccbb1ce --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410-3.py @@ -0,0 +1,26 @@ +class Solution: + def splitArray(self, nums: List[int], k: int) -> int: + l = max(nums) + r = sum(nums) + 1 + + def numGroups(maxSumInGroup: int) -> int: + groupCount = 1 + sumInGroup = 0 + + for num in nums: + if sumInGroup + num <= maxSumInGroup: + sumInGroup += num + else: + groupCount += 1 + sumInGroup = num + + return groupCount + + while l < r: + m = (l + r) // 2 + if numGroups(m) > k: + l = m + 1 + else: + r = m + + return l diff --git a/solutions/410. Split Array Largest Sum/410.cpp b/solutions/410. Split Array Largest Sum/410.cpp new file mode 100644 index 00000000000..846c3a7103f --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int splitArray(vector& nums, int k) { + const int n = nums.size(); + vector> mem(n + 1, vector(k + 1, INT_MAX)); + vector prefix(n + 1); + partial_sum(nums.begin(), nums.end(), prefix.begin() + 1); + return splitArray(nums, n, k, prefix, mem); + } + + private: + // Returns the minimum of the maximum sum to split the first i numbers into k + // groups. + int splitArray(const vector& nums, int i, int k, + const vector& prefix, vector>& mem) { + if (k == 1) + return prefix[i]; + if (mem[i][k] < INT_MAX) + return mem[i][k]; + + // Try all the possible partitions. + for (int j = k - 1; j < i; ++j) + mem[i][k] = min(mem[i][k], max(splitArray(nums, j, k - 1, prefix, mem), + prefix[i] - prefix[j])); + + return mem[i][k]; + } +}; diff --git a/solutions/410. Split Array Largest Sum/410.java b/solutions/410. Split Array Largest Sum/410.java new file mode 100644 index 00000000000..49d8235e0d7 --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410.java @@ -0,0 +1,30 @@ +class Solution { + public int splitArray(int[] nums, int k) { + final int n = nums.length; + int[][] mem = new int[n + 1][k + 1]; + int[] prefix = new int[n + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + + for (int i = 0; i < n; ++i) + prefix[i + 1] = nums[i] + prefix[i]; + + return splitArray(nums, n, k, prefix, mem); + } + + // Returns the minimum of the maximum sum to split the first i numbers into k + // groups. + private int splitArray(int[] nums, int i, int k, int[] prefix, int[][] mem) { + if (k == 1) + return prefix[i]; + if (mem[i][k] < Integer.MAX_VALUE) + return mem[i][k]; + + // Try all the possible partitions. + for (int j = k - 1; j < i; ++j) + mem[i][k] = Math.min(mem[i][k], // + Math.max(splitArray(nums, j, k - 1, prefix, mem), // + prefix[i] - prefix[j])); + + return mem[i][k]; + } +} diff --git a/solutions/410. Split Array Largest Sum/410.py b/solutions/410. Split Array Largest Sum/410.py new file mode 100644 index 00000000000..26eb818f466 --- /dev/null +++ b/solutions/410. Split Array Largest Sum/410.py @@ -0,0 +1,16 @@ +class Solution: + def splitArray(self, nums: List[int], k: int) -> int: + prefix = list(itertools.accumulate(nums, initial=0)) + + @functools.lru_cache(None) + def dp(i: int, k: int) -> int: + """ + Returns the minimum of the maximum sum to split the first i numbers into + k groups. + """ + if k == 1: + return prefix[i] + return min(max(dp(j, k - 1), prefix[i] - prefix[j]) + for j in range(k - 1, i)) + + return dp(len(nums), k) diff --git a/solutions/411. Minimum Unique Word Abbreviation/411.cpp b/solutions/411. Minimum Unique Word Abbreviation/411.cpp new file mode 100644 index 00000000000..65b805f9e23 --- /dev/null +++ b/solutions/411. Minimum Unique Word Abbreviation/411.cpp @@ -0,0 +1,84 @@ +class Solution { + public: + string minAbbreviation(string target, vector& dictionary) { + const int m = target.length(); + vector masks; + + for (const string& word : dictionary) { + if (word.length() != m) + continue; + masks.push_back(getMask(target, word)); + } + + if (masks.empty()) + return to_string(m); + + vector abbrs; + + const int maxCand = pow(2, m); + // all the candidate representation of the target + for (int cand = 0; cand < maxCand; ++cand) + // All the masks have at lease one bit different from the candidate. + if (ranges::all_of(masks, [cand](int mask) { return cand & mask; })) + abbrs.push_back(getAbbr(target, cand)); + + string ans = target; + + for (const string& abbr : abbrs) + if (getAbbrLen(abbr) < getAbbrLen(ans)) + ans = abbr; + + return ans; + } + + private: + int getMask(const string& target, const string& word) { + const int m = target.length(); + // mask[i] = 0 := target[i] == word[i] + // mask[i] = 1 := target[i] != word[i] + // e.g. target = "apple" + // word = "blade" + // mask = 11110 + int mask = 0; + for (int i = 0; i < m; ++i) + if (word[i] != target[i]) + mask |= 1 << m - 1 - i; + return mask; + } + + string getAbbr(const string& target, int cand) { + const int m = target.length(); + string abbr; + int replacedCount = 0; + for (int i = 0; i < m; ++i) + if (cand >> m - 1 - i & 1) { + // If cand[i] = 1, `abbr` should show the original character. + if (replacedCount > 0) + abbr += to_string(replacedCount); + abbr += target[i]; + replacedCount = 0; + } else { + // If cand[i] = 0, `abbr` can be replaced. + ++replacedCount; + } + if (replacedCount > 0) + abbr += to_string(replacedCount); + return abbr; + } + + int getAbbrLen(const string& abbr) { + int abbrLen = 0; + int i = 0; + int j = 0; + while (i < abbr.length()) { + if (isalpha(abbr[j])) + ++j; + else + while (j < abbr.length() && isdigit(abbr[j])) + ++j; + ++abbrLen; + i = j; + } + return abbrLen; + } +}; diff --git a/solutions/411. Minimum Unique Word Abbreviation/411.java b/solutions/411. Minimum Unique Word Abbreviation/411.java new file mode 100644 index 00000000000..84249dbf765 --- /dev/null +++ b/solutions/411. Minimum Unique Word Abbreviation/411.java @@ -0,0 +1,84 @@ +class Solution { + public String minAbbreviation(String target, String[] dictionary) { + final int m = target.length(); + List masks = new ArrayList<>(); + + for (final String word : dictionary) { + if (word.length() != m) + continue; + masks.add(getMask(target, word)); + } + + if (masks.isEmpty()) + return String.valueOf(m); + + List abbrs = new ArrayList<>(); + + final int maxCand = (int) Math.pow(2, m); + // all the candidate representation of the target + for (int i = 0; i < maxCand; ++i) { + final int cand = i; + // All the masks have at lease one bit different from the candidate. + if (masks.stream().allMatch(mask -> (cand & mask) > 0)) + abbrs.add(getAbbr(target, cand)); + } + + String ans = target; + + for (final String abbr : abbrs) + if (getAbbrLen(abbr) < getAbbrLen(ans)) + ans = abbr; + + return ans; + } + + private int getMask(final String target, final String word) { + final int m = target.length(); + // mask[i] = 0 := target[i] == word[i] + // mask[i] = 1 := target[i] != word[i] + // e.g. target = "apple" + // word = "blade" + // mask = 11110 + int mask = 0; + for (int i = 0; i < m; ++i) + if (word.charAt(i) != target.charAt(i)) + mask |= 1 << m - 1 - i; + return mask; + } + + String getAbbr(final String target, int cand) { + final int m = target.length(); + StringBuilder sb = new StringBuilder(); + int replacedCount = 0; + for (int i = 0; i < m; ++i) + if ((cand >> m - 1 - i & 1) == 1) { + // If cand[i] = 1, `abbr` should show the original character. + if (replacedCount > 0) + sb.append(replacedCount); + sb.append(target.charAt(i)); + replacedCount = 0; + } else { + // If cand[i] = 0, `abbr` can be replaced. + ++replacedCount; + } + if (replacedCount > 0) + sb.append(replacedCount); + return sb.toString(); + } + + int getAbbrLen(final String abbr) { + int abbrLen = 0; + int i = 0; + int j = 0; + while (i < abbr.length()) { + if (Character.isAlphabetic(abbr.charAt(j))) + ++j; + else + while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) + ++j; + ++abbrLen; + i = j; + } + return abbrLen; + } +} diff --git a/solutions/411. Minimum Unique Word Abbreviation/411.py b/solutions/411. Minimum Unique Word Abbreviation/411.py new file mode 100644 index 00000000000..9807ca9b11d --- /dev/null +++ b/solutions/411. Minimum Unique Word Abbreviation/411.py @@ -0,0 +1,61 @@ +class Solution: + def minAbbreviation(self, target: str, dictionary: List[str]) -> str: + m = len(target) + + def getMask(word: str) -> int: + # mask[i] = 0 := target[i] == word[i] + # mask[i] = 1 := target[i] != word[i] + # e.g. target = "apple" + # word = "blade" + # mask = 11110 + mask = 0 + for i, c in enumerate(word): + if c != target[i]: + mask |= 1 << m - 1 - i + return mask + + masks = [getMask(word) for word in dictionary if len(word) == m] + if not masks: + return str(m) + + abbrs = [] + + def getAbbr(cand: int) -> str: + abbr = [] + replacedCount = 0 + for i, c in enumerate(target): + if cand >> m - 1 - i & 1: + # If cand[i] = 1, `abbr` should show the original character. + if replacedCount: + abbr += str(replacedCount) + abbr.append(c) + replacedCount = 0 + else: + # If cand[i] = 0, `abbr` can be replaced. + replacedCount += 1 + if replacedCount: + abbr.append(str(replacedCount)) + return ''.join(abbr) + + # all the candidate representation of the target + for cand in range(2**m): + # All the masks have at lease one bit different from the candidate. + if all(cand & mask for mask in masks): + abbr = getAbbr(cand) + abbrs.append(abbr) + + def getAbbrLen(abbr: str) -> int: + abbrLen = 0 + i = 0 + j = 0 + while i < len(abbr): + if abbr[j].isalpha(): + j += 1 + else: + while j < len(abbr) and abbr[j].isdigit(): + j += 1 + abbrLen += 1 + i = j + return abbrLen + + return min(abbrs, key=lambda x: getAbbrLen(x)) diff --git a/solutions/412. Fizz Buzz/412.cpp b/solutions/412. Fizz Buzz/412.cpp new file mode 100644 index 00000000000..663bd3d85a1 --- /dev/null +++ b/solutions/412. Fizz Buzz/412.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector fizzBuzz(int n) { + vector ans; + + for (int i = 1; i <= n; ++i) { + string s; + if (i % 3 == 0) + s += "Fizz"; + if (i % 5 == 0) + s += "Buzz"; + ans.push_back(s.empty() ? to_string(i) : s); + } + + return ans; + } +}; diff --git a/solutions/412. Fizz Buzz/412.java b/solutions/412. Fizz Buzz/412.java new file mode 100644 index 00000000000..35c9581c077 --- /dev/null +++ b/solutions/412. Fizz Buzz/412.java @@ -0,0 +1,16 @@ +class Solution { + public List fizzBuzz(int n) { + List ans = new ArrayList<>(); + + for (int i = 1; i <= n; ++i) { + StringBuilder sb = new StringBuilder(); + if (i % 3 == 0) + sb.append("Fizz"); + if (i % 5 == 0) + sb.append("Buzz"); + ans.add(sb.length() == 0 ? String.valueOf(i) : sb.toString()); + } + + return ans; + } +} diff --git a/solutions/412. Fizz Buzz/412.py b/solutions/412. Fizz Buzz/412.py new file mode 100644 index 00000000000..e8d51d0b54b --- /dev/null +++ b/solutions/412. Fizz Buzz/412.py @@ -0,0 +1,4 @@ +class Solution: + def fizzBuzz(self, n: int) -> List[str]: + d = {3: 'Fizz', 5: 'Buzz'} + return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)] diff --git a/solutions/413. Arithmetic Slices/413-2.cpp b/solutions/413. Arithmetic Slices/413-2.cpp new file mode 100644 index 00000000000..fefb76c807e --- /dev/null +++ b/solutions/413. Arithmetic Slices/413-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int numberOfArithmeticSlices(vector& nums) { + int ans = 0; + int dp = 0; // the number of arithmetic slices ending in index i + + for (int i = 2; i < nums.size(); ++i) + if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) + ans += ++dp; + else + dp = 0; + + return ans; + } +}; diff --git a/solutions/413. Arithmetic Slices/413-2.java b/solutions/413. Arithmetic Slices/413-2.java new file mode 100644 index 00000000000..89c90ec557a --- /dev/null +++ b/solutions/413. Arithmetic Slices/413-2.java @@ -0,0 +1,15 @@ +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + int ans = 0; + int dp = 0; // the number of arithmetic slices ending in index i + + for (int i = 2; i < nums.length; ++i) { + if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) + ans += ++dp; + else + dp = 0; + } + + return ans; + } +} diff --git a/solutions/413. Arithmetic Slices/413-2.py b/solutions/413. Arithmetic Slices/413-2.py new file mode 100644 index 00000000000..1cd6f95f59e --- /dev/null +++ b/solutions/413. Arithmetic Slices/413-2.py @@ -0,0 +1,13 @@ +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + ans = 0 + dp = 0 + + for i in range(2, len(nums)): + if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]: + dp += 1 + ans += dp + else: + dp = 0 + + return ans diff --git a/solutions/413. Arithmetic Slices/413.cpp b/solutions/413. Arithmetic Slices/413.cpp new file mode 100644 index 00000000000..41cf45e6982 --- /dev/null +++ b/solutions/413. Arithmetic Slices/413.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int numberOfArithmeticSlices(vector& nums) { + const int n = nums.size(); + if (n < 3) + return 0; + + vector dp( + n); // dp[i] := the number of arithmetic slices ending in index i + + for (int i = 2; i < nums.size(); ++i) + if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) + dp[i] = dp[i - 1] + 1; + + return accumulate(dp.begin(), dp.end(), 0); + } +}; diff --git a/solutions/413. Arithmetic Slices/413.java b/solutions/413. Arithmetic Slices/413.java new file mode 100644 index 00000000000..f100fc6d169 --- /dev/null +++ b/solutions/413. Arithmetic Slices/413.java @@ -0,0 +1,15 @@ +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + final int n = nums.length; + if (n < 3) + return 0; + + int[] dp = new int[n]; // dp[i] := the number of arithmetic slices ends in nums[i] + + for (int i = 2; i < n; ++i) + if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) + dp[i] += dp[i - 1] + 1; + + return Arrays.stream(dp).sum(); + } +} diff --git a/solutions/413. Arithmetic Slices/413.py b/solutions/413. Arithmetic Slices/413.py new file mode 100644 index 00000000000..6888c7476b6 --- /dev/null +++ b/solutions/413. Arithmetic Slices/413.py @@ -0,0 +1,13 @@ +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + n = len(nums) + if n < 3: + return 0 + + dp = [0] * n # dp[i] := the number of arithmetic slices ending in index i + + for i in range(2, len(nums)): + if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]: + dp[i] = dp[i - 1] + 1 + + return sum(dp) diff --git a/solutions/414. Third Maximum Number/414-2.cpp b/solutions/414. Third Maximum Number/414-2.cpp new file mode 100644 index 00000000000..7662d9eefa2 --- /dev/null +++ b/solutions/414. Third Maximum Number/414-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int thirdMax(vector& nums) { + priority_queue, greater<>> minHeap; + unordered_set seen; + + for (const int num : nums) + if (!seen.contains(num)) { + seen.insert(num); + minHeap.push(num); + if (minHeap.size() > 3) + minHeap.pop(); + } + + if (minHeap.size() == 2) + minHeap.pop(); + + return minHeap.top(); + } +}; diff --git a/solutions/414. Third Maximum Number/414-2.java b/solutions/414. Third Maximum Number/414-2.java new file mode 100644 index 00000000000..8fc68ce3774 --- /dev/null +++ b/solutions/414. Third Maximum Number/414-2.java @@ -0,0 +1,18 @@ +public class Solution { + public int thirdMax(int[] nums) { + Queue minHeap = new PriorityQueue<>(); + Set seen = new HashSet<>(); + + for (final int num : nums) + if (seen.add(num)) { + minHeap.offer(num); + if (minHeap.size() > 3) + minHeap.poll(); + } + + if (minHeap.size() == 2) + minHeap.poll(); + + return minHeap.peek(); + } +} diff --git a/solutions/414. Third Maximum Number/414-2.py b/solutions/414. Third Maximum Number/414-2.py new file mode 100644 index 00000000000..45786367bac --- /dev/null +++ b/solutions/414. Third Maximum Number/414-2.py @@ -0,0 +1,16 @@ +class Solution: + def thirdMax(self, nums: List[int]) -> int: + minHeap = [] + seen = set() + + for num in nums: + if num not in seen: + seen.add(num) + heapq.heappush(minHeap, num) + if len(minHeap) > 3: + heapq.heappop(minHeap) + + if len(minHeap) == 2: + heapq.heappop(minHeap) + + return minHeap[0] diff --git a/solutions/414. Third Maximum Number/414.cpp b/solutions/414. Third Maximum Number/414.cpp new file mode 100644 index 00000000000..0e997e5bcbf --- /dev/null +++ b/solutions/414. Third Maximum Number/414.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int thirdMax(vector& nums) { + long max1 = LONG_MIN; // the maximum + long max2 = LONG_MIN; // the second maximum + long max3 = LONG_MIN; // the third maximum + + for (const int num : nums) + if (num > max1) { + max3 = max2; + max2 = max1; + max1 = num; + } else if (max1 > num && num > max2) { + max3 = max2; + max2 = num; + } else if (max2 > num && num > max3) { + max3 = num; + } + + return max3 == LONG_MIN ? max1 : max3; + } +}; diff --git a/solutions/414. Third Maximum Number/414.java b/solutions/414. Third Maximum Number/414.java new file mode 100644 index 00000000000..4ecb1c31246 --- /dev/null +++ b/solutions/414. Third Maximum Number/414.java @@ -0,0 +1,21 @@ +public class Solution { + public int thirdMax(int[] nums) { + long max1 = Long.MIN_VALUE; // the maximum + long max2 = Long.MIN_VALUE; // the second maximum + long max3 = Long.MIN_VALUE; // the third maximum + + for (final int num : nums) + if (num > max1) { + max3 = max2; + max2 = max1; + max1 = num; + } else if (max1 > num && num > max2) { + max3 = max2; + max2 = num; + } else if (max2 > num && num > max3) { + max3 = num; + } + + return max3 == Long.MIN_VALUE ? (int) max1 : (int) max3; + } +} diff --git a/solutions/414. Third Maximum Number/414.py b/solutions/414. Third Maximum Number/414.py new file mode 100644 index 00000000000..29b0b49be1e --- /dev/null +++ b/solutions/414. Third Maximum Number/414.py @@ -0,0 +1,18 @@ +class Solution: + def thirdMax(self, nums: List[int]) -> int: + max1 = -math.inf # the maximum + max2 = -math.inf # the second maximum + max3 = -math.inf # the third maximum + + for num in nums: + if num > max1: + max3 = max2 + max2 = max1 + max1 = num + elif max1 > num and num > max2: + max3 = max2 + max2 = num + elif max2 > num and num > max3: + max3 = num + + return max1 if max3 == -math.inf else max3 diff --git a/solutions/415. Add Strings/415.cpp b/solutions/415. Add Strings/415.cpp new file mode 100644 index 00000000000..fb3f779d8e6 --- /dev/null +++ b/solutions/415. Add Strings/415.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string addStrings(string num1, string num2) { + string ans; + int carry = 0; + int i = num1.length() - 1; + int j = num2.length() - 1; + + while (i >= 0 || j >= 0 || carry) { + if (i >= 0) + carry += num1[i--] - '0'; + if (j >= 0) + carry += num2[j--] - '0'; + ans += carry % 10 + '0'; + carry /= 10; + } + + reverse(ans.begin(), ans.end()); + return ans; + } +}; diff --git a/solutions/415. Add Strings/415.java b/solutions/415. Add Strings/415.java new file mode 100644 index 00000000000..105e424a1e6 --- /dev/null +++ b/solutions/415. Add Strings/415.java @@ -0,0 +1,19 @@ +class Solution { + public String addStrings(String num1, String num2) { + StringBuilder sb = new StringBuilder(); + int carry = 0; + int i = num1.length() - 1; + int j = num2.length() - 1; + + while (i >= 0 || j >= 0 || carry > 0) { + if (i >= 0) + carry += num1.charAt(i--) - '0'; + if (j >= 0) + carry += num2.charAt(j--) - '0'; + sb.append(carry % 10); + carry /= 10; + } + + return sb.reverse().toString(); + } +} diff --git a/solutions/415. Add Strings/415.py b/solutions/415. Add Strings/415.py new file mode 100644 index 00000000000..534d3563400 --- /dev/null +++ b/solutions/415. Add Strings/415.py @@ -0,0 +1,18 @@ +class Solution: + def addStrings(self, num1: str, num2: str) -> str: + ans = [] + carry = 0 + i = len(num1) - 1 + j = len(num2) - 1 + + while i >= 0 or j >= 0 or carry: + if i >= 0: + carry += int(num1[i]) + if j >= 0: + carry += int(num2[j]) + ans.append(str(carry % 10)) + carry //= 10 + i -= 1 + j -= 1 + + return ''.join(reversed(ans)) diff --git a/solutions/416. Partition Equal Subset Sum/416-2.cpp b/solutions/416. Partition Equal Subset Sum/416-2.cpp new file mode 100644 index 00000000000..2c47d67c987 --- /dev/null +++ b/solutions/416. Partition Equal Subset Sum/416-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool canPartition(vector& nums) { + const int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % 2 == 1) + return false; + return knapsack(nums, sum / 2); + } + + private: + bool knapsack(const vector& nums, int subsetSum) { + // dp[i] := true if i can be formed by nums so far + vector dp(subsetSum + 1); + dp[0] = true; + + for (const int num : nums) + for (int i = subsetSum; i >= num; --i) + dp[i] = dp[i] || dp[i - num]; + + return dp[subsetSum]; + } +}; diff --git a/solutions/416. Partition Equal Subset Sum/416-2.java b/solutions/416. Partition Equal Subset Sum/416-2.java new file mode 100644 index 00000000000..c468347bf4e --- /dev/null +++ b/solutions/416. Partition Equal Subset Sum/416-2.java @@ -0,0 +1,21 @@ +class Solution { + public boolean canPartition(int[] nums) { + final int sum = Arrays.stream(nums).sum(); + if (sum % 2 == 1) + return false; + + return knapsack(nums, sum / 2); + } + + private boolean knapsack(int[] nums, int subsetSum) { + // dp[i] := true if i can be formed by nums so far + boolean[] dp = new boolean[subsetSum + 1]; + dp[0] = true; + + for (final int num : nums) + for (int i = subsetSum; i >= num; --i) + dp[i] = dp[i] || dp[i - num]; + + return dp[subsetSum]; + } +} diff --git a/solutions/416. Partition Equal Subset Sum/416-2.py b/solutions/416. Partition Equal Subset Sum/416-2.py new file mode 100644 index 00000000000..6a6a7a1abe0 --- /dev/null +++ b/solutions/416. Partition Equal Subset Sum/416-2.py @@ -0,0 +1,17 @@ +class Solution: + def canPartition(self, nums: List[int]) -> bool: + summ = sum(nums) + if summ % 2 == 1: + return False + return self.knapsack_(nums, summ // 2) + + def knapsack_(self, nums: List[int], subsetSum: int) -> bool: + # dp[i] := True if i can be formed by nums so far + dp = [False] * (subsetSum + 1) + dp[0] = True + + for num in nums: + for i in range(subsetSum, num - 1, -1): + dp[i] = dp[i] or dp[i - num] + + return dp[subsetSum] diff --git a/solutions/416. Partition Equal Subset Sum/416.cpp b/solutions/416. Partition Equal Subset Sum/416.cpp new file mode 100644 index 00000000000..4bf386e15cd --- /dev/null +++ b/solutions/416. Partition Equal Subset Sum/416.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool canPartition(vector& nums) { + const int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % 2 == 1) + return false; + return knapsack(nums, sum / 2); + } + + private: + bool knapsack(const vector& nums, int subsetSum) { + const int n = nums.size(); + // dp[i][j] := true if j can be formed by nums[0..i) + vector> dp(n + 1, vector(subsetSum + 1)); + dp[0][0] = true; + + for (int i = 1; i <= n; ++i) { + const int num = nums[i - 1]; + for (int j = 0; j <= subsetSum; ++j) + if (j < num) + dp[i][j] = dp[i - 1][j]; + else + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - num]; + } + + return dp[n][subsetSum]; + } +}; diff --git a/solutions/416. Partition Equal Subset Sum/416.java b/solutions/416. Partition Equal Subset Sum/416.java new file mode 100644 index 00000000000..156aa91b838 --- /dev/null +++ b/solutions/416. Partition Equal Subset Sum/416.java @@ -0,0 +1,26 @@ +class Solution { + public boolean canPartition(int[] nums) { + final int sum = Arrays.stream(nums).sum(); + if (sum % 2 == 1) + return false; + return knapsack(nums, sum / 2); + } + + private boolean knapsack(int[] nums, int subsetSum) { + final int n = nums.length; + // dp[i][j] := true if j can be formed by nums[0..i) + boolean[][] dp = new boolean[n + 1][subsetSum + 1]; + dp[0][0] = true; + + for (int i = 1; i <= n; ++i) { + final int num = nums[i - 1]; + for (int j = 0; j <= subsetSum; ++j) + if (j < num) + dp[i][j] = dp[i - 1][j]; + else + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - num]; + } + + return dp[n][subsetSum]; + } +} diff --git a/solutions/416. Partition Equal Subset Sum/416.py b/solutions/416. Partition Equal Subset Sum/416.py new file mode 100644 index 00000000000..d82df332996 --- /dev/null +++ b/solutions/416. Partition Equal Subset Sum/416.py @@ -0,0 +1,22 @@ +class Solution: + def canPartition(self, nums: List[int]) -> bool: + summ = sum(nums) + if summ % 2 == 1: + return False + return self.knapsack_(nums, summ // 2) + + def knapsack_(self, nums: List[int], subsetSum: int) -> bool: + n = len(nums) + # dp[i][j] := True if j can be formed by nums[0..i) + dp = [[False] * (subsetSum + 1) for _ in range(n + 1)] + dp[0][0] = True + + for i in range(1, n + 1): + num = nums[i - 1] + for j in range(subsetSum + 1): + if j < num: + dp[i][j] = dp[i - 1][j] + else: + dp[i][j] = dp[i - 1][j] or dp[i - 1][j - num] + + return dp[n][subsetSum] diff --git a/solutions/417. Pacific Atlantic Water Flow/417-2.cpp b/solutions/417. Pacific Atlantic Water Flow/417-2.cpp new file mode 100644 index 00000000000..63127f4ae11 --- /dev/null +++ b/solutions/417. Pacific Atlantic Water Flow/417-2.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + vector> pacificAtlantic(vector>& heights) { + const int m = heights.size(); + const int n = heights[0].size(); + vector> ans; + vector> seenP(m, vector(n)); + vector> seenA(m, vector(n)); + + for (int i = 0; i < m; ++i) { + dfs(heights, i, 0, seenP); + dfs(heights, i, n - 1, seenA); + } + + for (int j = 0; j < n; ++j) { + dfs(heights, 0, j, seenP); + dfs(heights, m - 1, j, seenA); + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (seenP[i][j] && seenA[i][j]) + ans.push_back({i, j}); + + return ans; + } + + private: + void dfs(const vector>& heights, int i, int j, + vector>& seen, int h = 0) { + if (i < 0 || i == heights.size() || j < 0 || j == heights[0].size()) + return; + if (seen[i][j] || heights[i][j] < h) + return; + + seen[i][j] = true; + dfs(heights, i + 1, j, seen, heights[i][j]); + dfs(heights, i - 1, j, seen, heights[i][j]); + dfs(heights, i, j + 1, seen, heights[i][j]); + dfs(heights, i, j - 1, seen, heights[i][j]); + } +}; diff --git a/solutions/417. Pacific Atlantic Water Flow/417-2.java b/solutions/417. Pacific Atlantic Water Flow/417-2.java new file mode 100644 index 00000000000..fb1b044b43f --- /dev/null +++ b/solutions/417. Pacific Atlantic Water Flow/417-2.java @@ -0,0 +1,39 @@ +class Solution { + public List> pacificAtlantic(int[][] heights) { + final int m = heights.length; + final int n = heights[0].length; + List> ans = new ArrayList<>(); + boolean[][] seenP = new boolean[m][n]; + boolean[][] seenA = new boolean[m][n]; + + for (int i = 0; i < m; ++i) { + dfs(heights, i, 0, 0, seenP); + dfs(heights, i, n - 1, 0, seenA); + } + + for (int j = 0; j < n; ++j) { + dfs(heights, 0, j, 0, seenP); + dfs(heights, m - 1, j, 0, seenA); + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (seenP[i][j] && seenA[i][j]) + ans.add(new ArrayList<>(Arrays.asList(i, j))); + + return ans; + } + + private void dfs(final int[][] heights, int i, int j, int h, boolean[][] seen) { + if (i < 0 || i == heights.length || j < 0 || j == heights[0].length) + return; + if (seen[i][j] || heights[i][j] < h) + return; + + seen[i][j] = true; + dfs(heights, i + 1, j, heights[i][j], seen); + dfs(heights, i - 1, j, heights[i][j], seen); + dfs(heights, i, j + 1, heights[i][j], seen); + dfs(heights, i, j - 1, heights[i][j], seen); + } +} diff --git a/solutions/417. Pacific Atlantic Water Flow/417-2.py b/solutions/417. Pacific Atlantic Water Flow/417-2.py new file mode 100644 index 00000000000..07d75b876ac --- /dev/null +++ b/solutions/417. Pacific Atlantic Water Flow/417-2.py @@ -0,0 +1,31 @@ +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: + m = len(heights) + n = len(heights[0]) + seenP = [[False] * n for _ in range(m)] + seenA = [[False] * n for _ in range(m)] + + def dfs(i: int, j: int, h: int, seen: List[List[bool]]) -> None: + if i < 0 or i == m or j < 0 or j == n: + return + if seen[i][j] or heights[i][j] < h: + return + + seen[i][j] = True + dfs(i + 1, j, heights[i][j], seen) + dfs(i - 1, j, heights[i][j], seen) + dfs(i, j + 1, heights[i][j], seen) + dfs(i, j - 1, heights[i][j], seen) + + for i in range(m): + dfs(i, 0, 0, seenP) + dfs(i, n - 1, 0, seenA) + + for j in range(n): + dfs(0, j, 0, seenP) + dfs(m - 1, j, 0, seenA) + + return [[i, j] + for i in range(m) + for j in range(n) + if seenP[i][j] and seenA[i][j]] diff --git a/solutions/417. Pacific Atlantic Water Flow/417.cpp b/solutions/417. Pacific Atlantic Water Flow/417.cpp new file mode 100644 index 00000000000..8cc23229b16 --- /dev/null +++ b/solutions/417. Pacific Atlantic Water Flow/417.cpp @@ -0,0 +1,55 @@ +class Solution { + public: + vector> pacificAtlantic(vector>& heights) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = heights.size(); + const int n = heights[0].size(); + vector> ans; + queue> qP; + queue> qA; + vector> seenP(m, vector(n)); + vector> seenA(m, vector(n)); + + auto bfs = [&](queue>& q, vector>& seen) { + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + const int h = heights[i][j]; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y] || heights[x][y] < h) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + }; + + for (int i = 0; i < m; ++i) { + qP.emplace(i, 0); + qA.emplace(i, n - 1); + seenP[i][0] = true; + seenA[i][n - 1] = true; + } + + for (int j = 0; j < n; ++j) { + qP.emplace(0, j); + qA.emplace(m - 1, j); + seenP[0][j] = true; + seenA[m - 1][j] = true; + } + + bfs(qP, seenP); + bfs(qA, seenA); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (seenP[i][j] && seenA[i][j]) + ans.push_back({i, j}); + + return ans; + } +}; diff --git a/solutions/417. Pacific Atlantic Water Flow/417.java b/solutions/417. Pacific Atlantic Water Flow/417.java new file mode 100644 index 00000000000..03a1dfe2f29 --- /dev/null +++ b/solutions/417. Pacific Atlantic Water Flow/417.java @@ -0,0 +1,55 @@ +class Solution { + public List> pacificAtlantic(int[][] heights) { + final int m = heights.length; + final int n = heights[0].length; + List> ans = new ArrayList<>(); + Queue qP = new ArrayDeque<>(); + Queue qA = new ArrayDeque<>(); + boolean[][] seenP = new boolean[m][n]; + boolean[][] seenA = new boolean[m][n]; + + for (int i = 0; i < m; ++i) { + qP.offer(new int[] {i, 0}); + qA.offer(new int[] {i, n - 1}); + seenP[i][0] = true; + seenA[i][n - 1] = true; + } + + for (int j = 0; j < n; ++j) { + qP.offer(new int[] {0, j}); + qA.offer(new int[] {m - 1, j}); + seenP[0][j] = true; + seenA[m - 1][j] = true; + } + + bfs(heights, qP, seenP); + bfs(heights, qA, seenA); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (seenP[i][j] && seenA[i][j]) + ans.add(new ArrayList<>(Arrays.asList(i, j))); + + return ans; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private void bfs(int[][] heights, Queue q, boolean[][] seen) { + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + final int h = heights[i][j]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == heights.length || y < 0 || y == heights[0].length) + continue; + if (seen[x][y] || heights[x][y] < h) + continue; + q.offer(new int[] {x, y}); + seen[x][y] = true; + } + } + } +} diff --git a/solutions/417. Pacific Atlantic Water Flow/417.py b/solutions/417. Pacific Atlantic Water Flow/417.py new file mode 100644 index 00000000000..29f2802d1ba --- /dev/null +++ b/solutions/417. Pacific Atlantic Water Flow/417.py @@ -0,0 +1,40 @@ +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(heights) + n = len(heights[0]) + qP = collections.deque() + qA = collections.deque() + seenP = [[False] * n for _ in range(m)] + seenA = [[False] * n for _ in range(m)] + + for i in range(m): + qP.append((i, 0)) + qA.append((i, n - 1)) + seenP[i][0] = True + seenA[i][n - 1] = True + + for j in range(n): + qP.append((0, j)) + qA.append((m - 1, j)) + seenP[0][j] = True + seenA[m - 1][j] = True + + def bfs(q: deque, seen: List[List[bool]]): + while q: + i, j = q.popleft() + h = heights[i][j] + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if seen[x][y] or heights[x][y] < h: + continue + q.append((x, y)) + seen[x][y] = True + + bfs(qP, seenP) + bfs(qA, seenA) + + return [[i, j] for i in range(m) for j in range(n) if seenP[i][j] and seenA[i][j]] diff --git a/solutions/418. Sentence Screen Fitting/418.cpp b/solutions/418. Sentence Screen Fitting/418.cpp new file mode 100644 index 00000000000..acff99c7c4c --- /dev/null +++ b/solutions/418. Sentence Screen Fitting/418.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int wordsTyping(vector& sentence, int rows, int cols) { + const string& combined = getCombined(sentence); + const int n = combined.length(); + int i = 0; // (i % n) points to the index of combined in each row + + while (rows--) { + i += cols; + if (combined[i % n] == ' ') { + ++i; + } else { + while (i > 0 && combined[(i - 1) % n] != ' ') + --i; + } + } + + return i / n; + } + + private: + string getCombined(const vector& sentence) { + string combined; + for (const string& word : sentence) + combined += (word + ' '); + return combined; + } +}; diff --git a/solutions/418. Sentence Screen Fitting/418.java b/solutions/418. Sentence Screen Fitting/418.java new file mode 100644 index 00000000000..ca7c69f488f --- /dev/null +++ b/solutions/418. Sentence Screen Fitting/418.java @@ -0,0 +1,19 @@ +class Solution { + public int wordsTyping(String[] sentence, int rows, int cols) { + final String combined = String.join(" ", sentence) + " "; + final int n = combined.length(); + int i = 0; // (i % n) points to the index of combined in each row + + while (rows-- > 0) { + i += cols; + if (combined.charAt(i % n) == ' ') { + ++i; + } else { + while (i > 0 && combined.charAt((i - 1) % n) != ' ') + --i; + } + } + + return i / n; + } +} diff --git a/solutions/418. Sentence Screen Fitting/418.py b/solutions/418. Sentence Screen Fitting/418.py new file mode 100644 index 00000000000..b3dfa3db646 --- /dev/null +++ b/solutions/418. Sentence Screen Fitting/418.py @@ -0,0 +1,15 @@ +class Solution: + def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int: + combined = ' '.join(sentence) + ' ' + n = len(combined) + i = 0 + + for _ in range(rows): + i += cols + if combined[i % n] == ' ': + i += 1 + else: + while i > 0 and combined[(i - 1) % n] != ' ': + i -= 1 + + return i // n diff --git a/solutions/419. Battleships in a Board/419.cpp b/solutions/419. Battleships in a Board/419.cpp new file mode 100644 index 00000000000..e3b071dc48a --- /dev/null +++ b/solutions/419. Battleships in a Board/419.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countBattleships(vector>& board) { + int ans = 0; + + for (int i = 0; i < board.size(); ++i) + for (int j = 0; j < board[0].size(); ++j) { + if (board[i][j] == '.') + continue; + if (i > 0 && board[i - 1][j] == 'X') + continue; + if (j > 0 && board[i][j - 1] == 'X') + continue; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/419. Battleships in a Board/419.java b/solutions/419. Battleships in a Board/419.java new file mode 100644 index 00000000000..0bdf269d3f4 --- /dev/null +++ b/solutions/419. Battleships in a Board/419.java @@ -0,0 +1,18 @@ +class Solution { + public int countBattleships(char[][] board) { + int ans = 0; + + for (int i = 0; i < board.length; ++i) + for (int j = 0; j < board[0].length; ++j) { + if (board[i][j] == '.') + continue; + if (i > 0 && board[i - 1][j] == 'X') + continue; + if (j > 0 && board[i][j - 1] == 'X') + continue; + ++ans; + } + + return ans; + } +} diff --git a/solutions/419. Battleships in a Board/419.py b/solutions/419. Battleships in a Board/419.py new file mode 100644 index 00000000000..0b102cb4647 --- /dev/null +++ b/solutions/419. Battleships in a Board/419.py @@ -0,0 +1,15 @@ +class Solution: + def countBattleships(self, board: List[List[str]]) -> int: + ans = 0 + + for i, row in enumerate(board): + for j, cell in enumerate(row): + if cell == '.': + continue + if i > 0 and board[i - 1][j] == 'X': + continue + if j > 0 and board[i][j - 1] == 'X': + continue + ans += 1 + + return ans diff --git a/solutions/42. Trapping Rain Water/42-2.cpp b/solutions/42. Trapping Rain Water/42-2.cpp new file mode 100644 index 00000000000..1a777ce7045 --- /dev/null +++ b/solutions/42. Trapping Rain Water/42-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int trap(vector& height) { + if (height.empty()) + return 0; + + int ans = 0; + int l = 0; + int r = height.size() - 1; + int maxL = height[l]; + int maxR = height[r]; + + while (l < r) + if (maxL < maxR) { + ans += maxL - height[l]; + maxL = max(maxL, height[++l]); + } else { + ans += maxR - height[r]; + maxR = max(maxR, height[--r]); + } + + return ans; + } +}; diff --git a/solutions/42. Trapping Rain Water/42-2.java b/solutions/42. Trapping Rain Water/42-2.java new file mode 100644 index 00000000000..017849dc1da --- /dev/null +++ b/solutions/42. Trapping Rain Water/42-2.java @@ -0,0 +1,23 @@ +class Solution { + public int trap(int[] height) { + if (height.length == 0) + return 0; + + int ans = 0; + int l = 0; + int r = height.length - 1; + int maxL = height[l]; + int maxR = height[r]; + + while (l < r) + if (maxL < maxR) { + ans += maxL - height[l]; + maxL = Math.max(maxL, height[++l]); + } else { + ans += maxR - height[r]; + maxR = Math.max(maxR, height[--r]); + } + + return ans; + } +} diff --git a/solutions/42. Trapping Rain Water/42-2.py b/solutions/42. Trapping Rain Water/42-2.py new file mode 100644 index 00000000000..0124a4991a6 --- /dev/null +++ b/solutions/42. Trapping Rain Water/42-2.py @@ -0,0 +1,22 @@ +class Solution: + def trap(self, height: List[int]) -> int: + if not height: + return 0 + + ans = 0 + l = 0 + r = len(height) - 1 + maxL = height[l] + maxR = height[r] + + while l < r: + if maxL < maxR: + ans += maxL - height[l] + l += 1 + maxL = max(maxL, height[l]) + else: + ans += maxR - height[r] + r -= 1 + maxR = max(maxR, height[r]) + + return ans diff --git a/solutions/42. Trapping Rain Water/42.cpp b/solutions/42. Trapping Rain Water/42.cpp new file mode 100644 index 00000000000..e1108e98058 --- /dev/null +++ b/solutions/42. Trapping Rain Water/42.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int trap(vector& height) { + const int n = height.size(); + int ans = 0; + vector l(n); // l[i] := max(height[0..i]) + vector r(n); // r[i] := max(height[i..n)) + + for (int i = 0; i < n; ++i) + l[i] = i == 0 ? height[i] : max(height[i], l[i - 1]); + + for (int i = n - 1; i >= 0; --i) + r[i] = i == n - 1 ? height[i] : max(height[i], r[i + 1]); + + for (int i = 0; i < n; ++i) + ans += min(l[i], r[i]) - height[i]; + + return ans; + } +}; diff --git a/solutions/42. Trapping Rain Water/42.java b/solutions/42. Trapping Rain Water/42.java new file mode 100644 index 00000000000..f5d4576f98c --- /dev/null +++ b/solutions/42. Trapping Rain Water/42.java @@ -0,0 +1,19 @@ +class Solution { + public int trap(int[] height) { + final int n = height.length; + int ans = 0; + int[] l = new int[n]; // l[i] := max(height[0..i]) + int[] r = new int[n]; // r[i] := max(height[i..n)) + + for (int i = 0; i < n; ++i) + l[i] = i == 0 ? height[i] : Math.max(height[i], l[i - 1]); + + for (int i = n - 1; i >= 0; --i) + r[i] = i == n - 1 ? height[i] : Math.max(height[i], r[i + 1]); + + for (int i = 0; i < n; ++i) + ans += Math.min(l[i], r[i]) - height[i]; + + return ans; + } +} diff --git a/solutions/42. Trapping Rain Water/42.py b/solutions/42. Trapping Rain Water/42.py new file mode 100644 index 00000000000..1a4cd931f33 --- /dev/null +++ b/solutions/42. Trapping Rain Water/42.py @@ -0,0 +1,14 @@ +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + l = [0] * n # l[i] := max(height[0..i]) + r = [0] * n # r[i] := max(height[i..n)) + + for i, h in enumerate(height): + l[i] = h if i == 0 else max(h, l[i - 1]) + + for i, h in reversed(list(enumerate(height))): + r[i] = h if i == n - 1 else max(h, r[i + 1]) + + return sum(min(l[i], r[i]) - h + for i, h in enumerate(height)) diff --git a/solutions/420. Strong Password Checker/420.cpp b/solutions/420. Strong Password Checker/420.cpp new file mode 100644 index 00000000000..1ced495aa9a --- /dev/null +++ b/solutions/420. Strong Password Checker/420.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + int strongPasswordChecker(string password) { + const int n = password.length(); + const int missing = getMissing(password); + // the number of replacements to deal with 3 repeating characters + int replaces = 0; + // the number of sequences that can be substituted with 1 deletions, + // (3k)-seqs + int oneSeq = 0; + // the number of sequences that can be substituted with 2 deletions, + // (3k + 1)-seqs + int twoSeq = 0; + + for (int i = 2; i < n;) + if (password[i] == password[i - 1] && + password[i - 1] == password[i - 2]) { + int length = 2; // the length of the repeating password + while (i < n && password[i] == password[i - 1]) { + ++length; + ++i; + } + replaces += length / 3; // 'aaaaaaa' -> 'aaxaaxa' + if (length % 3 == 0) + ++oneSeq; + if (length % 3 == 1) + ++twoSeq; + } else { + ++i; + } + + if (n < 6) + return max(6 - n, missing); + if (n <= 20) + return max(replaces, missing); + + const int deletes = n - 20; + // Each replacement in (3k)-seqs can be substituted with 1 deletions. + replaces -= min(oneSeq, deletes); + // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions. + replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) / 2; + // Each replacement in other seqs can be substituted with 3 deletions. + replaces -= max(deletes - oneSeq - twoSeq * 2, 0) / 3; + return deletes + max(replaces, missing); + } + + private: + int getMissing(const string& password) { + return 3 - // + ranges::any_of(password, [](char c) { return isupper(c); }) - + ranges::any_of(password, [](char c) { return islower(c); }) - + ranges::any_of(password, [](char c) { return isdigit(c); }); + } +}; diff --git a/solutions/420. Strong Password Checker/420.java b/solutions/420. Strong Password Checker/420.java new file mode 100644 index 00000000000..b471c11a725 --- /dev/null +++ b/solutions/420. Strong Password Checker/420.java @@ -0,0 +1,50 @@ +class Solution { + public int strongPasswordChecker(String password) { + final int n = password.length(); + final int missing = getMissing(password); + // the number of replacements to deal with 3 repeating characters + int replaces = 0; + // the number of sequences that can be substituted with 1 deletions, (3k)-seqs + int oneSeq = 0; + // the number of sequences that can be substituted with 2 deletions, (3k + 1)-seqs + int twoSeq = 0; + + for (int i = 2; i < n;) + if (password.charAt(i) == password.charAt(i - 1) && + password.charAt(i - 1) == password.charAt(i - 2)) { + int length = 2; // the length of the repeating password + while (i < n && password.charAt(i) == password.charAt(i - 1)) { + ++length; + ++i; + } + replaces += length / 3; // 'aaaaaaa' -> 'aaxaaxa' + if (length % 3 == 0) + ++oneSeq; + if (length % 3 == 1) + ++twoSeq; + } else { + ++i; + } + + if (n < 6) + return Math.max(6 - n, missing); + if (n <= 20) + return Math.max(replaces, missing); + + final int deletes = n - 20; + // Each replacement in (3k)-seqs can be substituted with 1 deletions. + replaces -= Math.min(oneSeq, deletes); + // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions. + replaces -= Math.min(Math.max(deletes - oneSeq, 0), twoSeq * 2) / 2; + // Each replacement in other seqs can be substituted with 3 deletions. + replaces -= Math.max(deletes - oneSeq - twoSeq * 2, 0) / 3; + return deletes + Math.max(replaces, missing); + } + + private int getMissing(final String password) { + return 3 - // + (password.chars().anyMatch(Character::isUpperCase) ? 1 : 0) - + (password.chars().anyMatch(Character::isLowerCase) ? 1 : 0) - + (password.chars().anyMatch(Character::isDigit) ? 1 : 0); + } +} diff --git a/solutions/420. Strong Password Checker/420.py b/solutions/420. Strong Password Checker/420.py new file mode 100644 index 00000000000..51955a5b646 --- /dev/null +++ b/solutions/420. Strong Password Checker/420.py @@ -0,0 +1,47 @@ +class Solution: + def strongPasswordChecker(self, password: str) -> int: + n = len(password) + missing = self._getMissing(password) + # the number of replacements to deal with 3 repeating characters + replaces = 0 + # the number of sequences that can be substituted with 1 deletions, + # (3k)-seqs + oneSeq = 0 + # the number of sequences that can be substituted with 2 deletions, + # (3k + 1)-seqs + twoSeq = 0 + + i = 2 + while i < n: + if password[i] == password[i - 1] and password[i - 1] == password[i - 2]: + length = 2 # the length of the repeating password + while i < n and password[i] == password[i - 1]: + length += 1 + i += 1 + replaces += length // 3 # 'aaaaaaa' -> 'aaxaaxa' + if length % 3 == 0: + oneSeq += 1 + if length % 3 == 1: + twoSeq += 1 + else: + i += 1 + + if n < 6: + return max(6 - n, missing) + if n <= 20: + return max(replaces, missing) + + deletes = n - 20 + # Each replacement in (3k)-seqs can be substituted with 1 deletions. + replaces -= min(oneSeq, deletes) + # Each replacement in (3k + 1)-seqs can be substituted with 2 deletions. + replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) // 2 + # Each replacement in other seqs can be substituted with 3 deletions. + replaces -= max(deletes - oneSeq - twoSeq * 2, 0) // 3 + return deletes + max(replaces, missing) + + def _getMissing(self, password: str) -> int: + return 3 - \ + any(c.isupper() for c in password) - \ + any(c.islower() for c in password) - \ + any(c.isdigit() for c in password) diff --git a/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.cpp b/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.cpp new file mode 100644 index 00000000000..52dbada7835 --- /dev/null +++ b/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.cpp @@ -0,0 +1,60 @@ +struct TrieNode { + vector> children; + TrieNode() : children(2) {} +}; + +class BitTrie { + public: + BitTrie(int maxBit) : maxBit(maxBit) {} + + void insert(int num) { + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + if (node->children[bit] == nullptr) + node->children[bit] = make_shared(); + node = node->children[bit]; + } + } + + int getMaxXor(int num) { + int maxXor = 0; + shared_ptr node = root; + for (int i = maxBit; i >= 0; --i) { + const int bit = num >> i & 1; + const int toggleBit = bit ^ 1; + if (node->children[toggleBit] != nullptr) { + maxXor = maxXor | 1 << i; + node = node->children[toggleBit]; + } else if (node->children[bit] != nullptr) { + node = node->children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private: + const int maxBit; + shared_ptr root = make_shared(); +}; + +class Solution { + public: + int findMaximumXOR(vector& nums) { + const int maxNum = ranges::max(nums); + if (maxNum == 0) + return 0; + const int maxBit = static_cast(log2(maxNum)); + int ans = 0; + BitTrie bitTrie(maxBit); + + for (const int num : nums) { + ans = max(ans, bitTrie.getMaxXor(num)); + bitTrie.insert(num); + } + + return ans; + } +}; diff --git a/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.java b/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.java new file mode 100644 index 00000000000..352e6c59242 --- /dev/null +++ b/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.java @@ -0,0 +1,58 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[2]; +} + +class BitTrie { + public BitTrie(int maxBit) { + this.maxBit = maxBit; + } + + public void insert(int num) { + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + if (node.children[bit] == null) + node.children[bit] = new TrieNode(); + node = node.children[bit]; + } + } + + public int getMaxXor(int num) { + int maxXor = 0; + TrieNode node = root; + for (int i = maxBit; i >= 0; --i) { + final int bit = (int) (num >> i & 1); + final int toggleBit = bit ^ 1; + if (node.children[toggleBit] != null) { + maxXor = maxXor | 1 << i; + node = node.children[toggleBit]; + } else if (node.children[bit] != null) { + node = node.children[bit]; + } else { // There's nothing in the Bit Trie. + return 0; + } + } + return maxXor; + } + + private int maxBit; + private TrieNode root = new TrieNode(); +} + +class Solution { + public int findMaximumXOR(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + if (maxNum == 0) + return 0; + final int maxBit = (int) (Math.log(maxNum) / Math.log(2)); + int ans = 0; + BitTrie bitTrie = new BitTrie(maxBit); + + for (final int num : nums) { + ans = Math.max(ans, bitTrie.getMaxXor(num)); + bitTrie.insert(num); + } + + return ans; + } +} diff --git a/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.py b/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.py new file mode 100644 index 00000000000..8b098d5dc64 --- /dev/null +++ b/solutions/421. Maximum XOR of Two Numbers in an Array/421-2.py @@ -0,0 +1,48 @@ +class TrieNode: + def __init__(self): + self.children: List[Optional[TrieNode]] = [None] * 2 + + +class BitTrie: + def __init__(self, maxBit: int): + self.maxBit = maxBit + self.root = TrieNode() + + def insert(self, num: int) -> None: + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + if not node.children[bit]: + node.children[bit] = TrieNode() + node = node.children[bit] + + def getMaxXor(self, num: int) -> int: + maxXor = 0 + node = self.root + for i in range(self.maxBit, -1, -1): + bit = num >> i & 1 + toggleBit = bit ^ 1 + if node.children[toggleBit]: + maxXor = maxXor | 1 << i + node = node.children[toggleBit] + elif node.children[bit]: + node = node.children[bit] + else: # There's nothing in the Bit Trie. + return 0 + return maxXor + + +class Solution: + def findMaximumXOR(self, nums: List[int]) -> int: + maxNum = max(nums) + if maxNum == 0: + return 0 + maxBit = int(math.log2(maxNum)) + ans = 0 + bitTrie = BitTrie(maxBit) + + for num in nums: + ans = max(ans, bitTrie.getMaxXor(num)) + bitTrie.insert(num) + + return ans diff --git a/solutions/421. Maximum XOR of Two Numbers in an Array/421.cpp b/solutions/421. Maximum XOR of Two Numbers in an Array/421.cpp new file mode 100644 index 00000000000..7637ff8674b --- /dev/null +++ b/solutions/421. Maximum XOR of Two Numbers in an Array/421.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int findMaximumXOR(vector& nums) { + const int maxNum = ranges::max(nums); + if (maxNum == 0) + return 0; + const int maxBit = static_cast(log2(maxNum)); + int ans = 0; + int prefixMask = 0; // Grows like: 10000 -> 11000 -> ... -> 11111. + + // If ans is 11100 when i = 2, it means that before we reach the last two + // bits, 11100 is the maximum XOR we have, and we're going to explore if we + // can get another two 1s and put them into `ans`. + for (int i = maxBit; i >= 0; --i) { + prefixMask |= 1 << i; + unordered_set prefixes; + // We only care about the left parts, + // If i = 2, nums = {1110, 1011, 0111} + // -> prefixes = {1100, 1000, 0100} + for (const int num : nums) + prefixes.insert(num & prefixMask); + // If i = 1 and before this iteration, the ans is 10100, it means that we + // want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for + // XOR of two prefixes = candidate. + const int candidate = ans | 1 << i; + for (const int prefix : prefixes) + if (prefixes.contains(prefix ^ candidate)) { + ans = candidate; + break; + } + } + + return ans; + } +}; diff --git a/solutions/421. Maximum XOR of Two Numbers in an Array/421.java b/solutions/421. Maximum XOR of Two Numbers in an Array/421.java new file mode 100644 index 00000000000..97fa772feb5 --- /dev/null +++ b/solutions/421. Maximum XOR of Two Numbers in an Array/421.java @@ -0,0 +1,34 @@ +class Solution { + public int findMaximumXOR(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + if (maxNum == 0) + return 0; + final int maxBit = (int) (Math.log(maxNum) / Math.log(2)); + int ans = 0; + int prefixMask = 0; // Grows like: 10000 -> 11000 -> ... -> 11111. + + // If ans is 11100 when i = 2, it means that before we reach the last two + // bits, 11100 is the maximum XOR we have, and we're going to explore if we + // can get another two 1s and put them into `ans`. + for (int i = maxBit; i >= 0; --i) { + prefixMask |= 1 << i; + Set prefixes = new HashSet<>(); + // We only care about the left parts, + // If i = 2, nums = {1110, 1011, 0111} + // . prefixes = {1100, 1000, 0100} + for (final int num : nums) + prefixes.add(num & prefixMask); + // If i = 1 and before this iteration, the ans is 10100, it means that we + // want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for + // XOR of two prefixes = candidate. + final int candidate = ans | 1 << i; + for (final int prefix : prefixes) + if (prefixes.contains(prefix ^ candidate)) { + ans = candidate; + break; + } + } + + return ans; + } +} diff --git a/solutions/421. Maximum XOR of Two Numbers in an Array/421.py b/solutions/421. Maximum XOR of Two Numbers in an Array/421.py new file mode 100644 index 00000000000..3621c87b760 --- /dev/null +++ b/solutions/421. Maximum XOR of Two Numbers in an Array/421.py @@ -0,0 +1,28 @@ +class Solution: + def findMaximumXOR(self, nums: List[int]) -> int: + maxNum = max(nums) + if maxNum == 0: + return 0 + maxBit = int(math.log2(maxNum)) + ans = 0 + prefixMask = 0 # `prefixMask` grows like: 10000 -> 11000 -> ... -> 11111. + + # If ans is 11100 when i = 2, it means that before we reach the last two + # bits, 11100 is the maximum XOR we have, and we're going to explore if we + # can get another two 1s and put them into `ans`. + for i in range(maxBit, -1, -1): + prefixMask |= 1 << i + # We only care about the left parts, + # If i = 2, nums = [1110, 1011, 0111] + # -> prefixes = [1100, 1000, 0100] + prefixes = set([num & prefixMask for num in nums]) + # If i = 1 and before this iteration, the ans is 10100, it means that we + # want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for + # XOR of two prefixes = candidate. + candidate = ans | 1 << i + for prefix in prefixes: + if prefix ^ candidate in prefixes: + ans = candidate + break + + return ans diff --git a/solutions/422. Valid Word Square/422.cpp b/solutions/422. Valid Word Square/422.cpp new file mode 100644 index 00000000000..6ffa57983b3 --- /dev/null +++ b/solutions/422. Valid Word Square/422.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool validWordSquare(vector& words) { + for (int i = 0; i < words.size(); ++i) + for (int j = 0; j < words[i].size(); ++j) { + if (words.size() <= j || words[j].size() <= i) // out-of-bounds + return false; + if (words[i][j] != words[j][i]) + return false; + } + return true; + } +}; diff --git a/solutions/422. Valid Word Square/422.java b/solutions/422. Valid Word Square/422.java new file mode 100644 index 00000000000..870d359b272 --- /dev/null +++ b/solutions/422. Valid Word Square/422.java @@ -0,0 +1,12 @@ +class Solution { + public boolean validWordSquare(List words) { + for (int i = 0; i < words.size(); ++i) + for (int j = 0; j < words.get(i).length(); ++j) { + if (words.size() <= j || words.get(j).length() <= i) // out-of-bounds + return false; + if (words.get(i).charAt(j) != words.get(j).charAt(i)) + return false; + } + return true; + } +} diff --git a/solutions/422. Valid Word Square/422.py b/solutions/422. Valid Word Square/422.py new file mode 100644 index 00000000000..6074c4231dc --- /dev/null +++ b/solutions/422. Valid Word Square/422.py @@ -0,0 +1,9 @@ +class Solution: + def validWordSquare(self, words: List[str]) -> bool: + for i, word in enumerate(words): + for j, c in enumerate(word): + if len(words) <= j or len(words[j]) <= i: # out-of-bounds + return False + if c != words[j][i]: + return False + return True diff --git a/solutions/423. Reconstruct Original Digits from English/423.cpp b/solutions/423. Reconstruct Original Digits from English/423.cpp new file mode 100644 index 00000000000..564eff17ae5 --- /dev/null +++ b/solutions/423. Reconstruct Original Digits from English/423.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + string originalDigits(string s) { + string ans; + vector count(10); + + for (const char c : s) { + if (c == 'z') + ++count[0]; + if (c == 'o') + ++count[1]; + if (c == 'w') + ++count[2]; + if (c == 'h') + ++count[3]; + if (c == 'u') + ++count[4]; + if (c == 'f') + ++count[5]; + if (c == 'x') + ++count[6]; + if (c == 's') + ++count[7]; + if (c == 'g') + ++count[8]; + if (c == 'i') + ++count[9]; + } + + count[1] -= count[0] + count[2] + count[4]; + count[3] -= count[8]; + count[5] -= count[4]; + count[7] -= count[6]; + count[9] -= count[5] + count[6] + count[8]; + + for (int i = 0; i < 10; ++i) + for (int j = 0; j < count[i]; ++j) + ans += i + '0'; + + return ans; + } +}; diff --git a/solutions/423. Reconstruct Original Digits from English/423.java b/solutions/423. Reconstruct Original Digits from English/423.java new file mode 100644 index 00000000000..3688f7bfdc6 --- /dev/null +++ b/solutions/423. Reconstruct Original Digits from English/423.java @@ -0,0 +1,41 @@ +class Solution { + public String originalDigits(String s) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[10]; + + for (final char c : s.toCharArray()) { + if (c == 'z') + ++count[0]; + if (c == 'o') + ++count[1]; + if (c == 'w') + ++count[2]; + if (c == 'h') + ++count[3]; + if (c == 'u') + ++count[4]; + if (c == 'f') + ++count[5]; + if (c == 'x') + ++count[6]; + if (c == 's') + ++count[7]; + if (c == 'g') + ++count[8]; + if (c == 'i') + ++count[9]; + } + + count[1] -= count[0] + count[2] + count[4]; + count[3] -= count[8]; + count[5] -= count[4]; + count[7] -= count[6]; + count[9] -= count[5] + count[6] + count[8]; + + for (int i = 0; i < 10; ++i) + for (int j = 0; j < count[i]; ++j) + sb.append(i); + + return sb.toString(); + } +} diff --git a/solutions/423. Reconstruct Original Digits from English/423.py b/solutions/423. Reconstruct Original Digits from English/423.py new file mode 100644 index 00000000000..0b48c4fa785 --- /dev/null +++ b/solutions/423. Reconstruct Original Digits from English/423.py @@ -0,0 +1,33 @@ +class Solution: + def originalDigits(self, s: str) -> str: + count = [0] * 10 + + for c in s: + if c == 'z': + count[0] += 1 + if c == 'o': + count[1] += 1 + if c == 'w': + count[2] += 1 + if c == 'h': + count[3] += 1 + if c == 'u': + count[4] += 1 + if c == 'f': + count[5] += 1 + if c == 'x': + count[6] += 1 + if c == 's': + count[7] += 1 + if c == 'g': + count[8] += 1 + if c == 'i': + count[9] += 1 + + count[1] -= count[0] + count[2] + count[4] + count[3] -= count[8] + count[5] -= count[4] + count[7] -= count[6] + count[9] -= count[5] + count[6] + count[8] + + return ''.join(chr(i + ord('0')) for i, c in enumerate(count) for j in range(c)) diff --git a/solutions/424. Longest Repeating Character Replacement/424-2.cpp b/solutions/424. Longest Repeating Character Replacement/424-2.cpp new file mode 100644 index 00000000000..8d6f8b1a789 --- /dev/null +++ b/solutions/424. Longest Repeating Character Replacement/424-2.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int characterReplacement(string s, int k) { + int maxCount = 0; + vector count(26); + + // l and r track the maximum window instead of the valid window. + int l = 0; + int r = 0; + + for (r = 0; r < s.length(); ++r) { + maxCount = max(maxCount, ++count[s[r] - 'A']); + if (maxCount + k < r - l + 1) + --count[s[l++] - 'A']; + } + + return r - l; + } +}; diff --git a/solutions/424. Longest Repeating Character Replacement/424-2.java b/solutions/424. Longest Repeating Character Replacement/424-2.java new file mode 100644 index 00000000000..27cb1765dd0 --- /dev/null +++ b/solutions/424. Longest Repeating Character Replacement/424-2.java @@ -0,0 +1,18 @@ +class Solution { + public int characterReplacement(String s, int k) { + int maxCount = 0; + int[] count = new int[26]; + + // l and r track the maximum window instead of the valid window. + int l = 0; + int r = 0; + + for (r = 0; r < s.length(); ++r) { + maxCount = Math.max(maxCount, ++count[s.charAt(r) - 'A']); + if (maxCount + k < r - l + 1) + --count[s.charAt(l++) - 'A']; + } + + return r - l; + } +} diff --git a/solutions/424. Longest Repeating Character Replacement/424-2.py b/solutions/424. Longest Repeating Character Replacement/424-2.py new file mode 100644 index 00000000000..fb14a1432e7 --- /dev/null +++ b/solutions/424. Longest Repeating Character Replacement/424-2.py @@ -0,0 +1,15 @@ +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + maxCount = 0 + count = collections.Counter() + + # l and r track the maximum window instead of the valid window. + l = 0 + for r, c in enumerate(s): + count[c] += 1 + maxCount = max(maxCount, count[c]) + while maxCount + k < r - l + 1: + count[s[l]] -= 1 + l += 1 + + return r - l + 1 diff --git a/solutions/424. Longest Repeating Character Replacement/424.cpp b/solutions/424. Longest Repeating Character Replacement/424.cpp new file mode 100644 index 00000000000..8ac609aedb3 --- /dev/null +++ b/solutions/424. Longest Repeating Character Replacement/424.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int characterReplacement(string s, int k) { + int ans = 0; + int maxCount = 0; + vector count(26); + + for (int l = 0, r = 0; r < s.length(); ++r) { + maxCount = max(maxCount, ++count[s[r] - 'A']); + while (maxCount + k < r - l + 1) + --count[s[l++] - 'A']; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/424. Longest Repeating Character Replacement/424.java b/solutions/424. Longest Repeating Character Replacement/424.java new file mode 100644 index 00000000000..d05d4ec3e54 --- /dev/null +++ b/solutions/424. Longest Repeating Character Replacement/424.java @@ -0,0 +1,16 @@ +class Solution { + public int characterReplacement(String s, int k) { + int ans = 0; + int maxCount = 0; + int[] count = new int[26]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + maxCount = Math.max(maxCount, ++count[s.charAt(r) - 'A']); + while (maxCount + k < r - l + 1) + --count[s.charAt(l++) - 'A']; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/424. Longest Repeating Character Replacement/424.py b/solutions/424. Longest Repeating Character Replacement/424.py new file mode 100644 index 00000000000..736a11e0830 --- /dev/null +++ b/solutions/424. Longest Repeating Character Replacement/424.py @@ -0,0 +1,16 @@ +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + ans = 0 + maxCount = 0 + count = collections.Counter() + + l = 0 + for r, c in enumerate(s): + count[c] += 1 + maxCount = max(maxCount, count[c]) + while maxCount + k < r - l + 1: + count[s[l]] -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/425. Word Squares/425.cpp b/solutions/425. Word Squares/425.cpp new file mode 100644 index 00000000000..f3691d7da61 --- /dev/null +++ b/solutions/425. Word Squares/425.cpp @@ -0,0 +1,87 @@ +struct TrieNode { + vector> children; + vector startsWith; + TrieNode() : children(26) {} +}; + +class Trie { + public: + Trie(const vector& words) { + for (const string& word : words) + insert(word); + } + + vector findBy(const string& prefix) { + shared_ptr node = root; + for (const char c : prefix) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + return {}; + node = node->children[i]; + } + return node->startsWith; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + node->startsWith.push_back(&word); + } + } +}; + +class Solution { + public: + vector> wordSquares(vector& words) { + if (words.empty()) + return {}; + + const int n = words[0].length(); + vector> ans; + vector path; + Trie trie(words); + + for (const string& word : words) { + path.push_back(word); + dfs(trie, n, path, ans); + path.pop_back(); + } + + return ans; + } + + private: + void dfs(Trie& trie, const int n, vector& path, + vector>& ans) { + if (path.size() == n) { + ans.push_back(path); + return; + } + + const string prefix = getPrefix(path); + + for (const string* s : trie.findBy(prefix)) { + path.push_back(*s); + dfs(trie, n, path, ans); + path.pop_back(); + } + } + + // e.g. path = ["wall", + // "area"] + // prefix = "le.." + string getPrefix(const vector& path) { + string prefix; + const int index = path.size(); + for (const string& s : path) + prefix += s[index]; + return prefix; + } +}; diff --git a/solutions/425. Word Squares/425.java b/solutions/425. Word Squares/425.java new file mode 100644 index 00000000000..288b12b8de4 --- /dev/null +++ b/solutions/425. Word Squares/425.java @@ -0,0 +1,81 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public List startsWith = new ArrayList<>(); +} + +class Trie { + public Trie(final String[] words) { + for (final String word : words) + insert(word); + } + + public List findBy(final String prefix) { + TrieNode node = root; + for (final char c : prefix.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + return new ArrayList<>(); + node = node.children[i]; + } + return node.startsWith; + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + node.startsWith.add(word); + } + } +} + +class Solution { + public List> wordSquares(String[] words) { + if (words.length == 0) + return new ArrayList<>(); + + final int n = words[0].length(); + List> ans = new ArrayList<>(); + List path = new ArrayList<>(); + Trie trie = new Trie(words); + + for (final String word : words) { + path.add(word); + dfs(trie, n, path, ans); + path.remove(path.size() - 1); + } + + return ans; + } + + private void dfs(Trie trie, final int n, List path, List> ans) { + if (path.size() == n) { + ans.add(new ArrayList<>(path)); + return; + } + + final String prefix = getPrefix(path); + + for (final String s : trie.findBy(prefix)) { + path.add(s); + dfs(trie, n, path, ans); + path.remove(path.size() - 1); + } + } + + // e.g. path = ["wall", + // "area"] + // prefix = "le.." + private String getPrefix(List path) { + StringBuilder sb = new StringBuilder(); + final int index = path.size(); + for (final String s : path) + sb.append(s.charAt(index)); + return sb.toString(); + } +} diff --git a/solutions/425. Word Squares/425.py b/solutions/425. Word Squares/425.py new file mode 100644 index 00000000000..2f7a03573c4 --- /dev/null +++ b/solutions/425. Word Squares/425.py @@ -0,0 +1,67 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode) + self.startsWith: List[str] = [] + + +class Trie: + def __init__(self, words: List[str]): + self.root = TrieNode() + for word in words: + self._insert(word) + + def findBy(self, prefix: str) -> List[str]: + node = self.root + for c in prefix: + if c not in node.children: + return [] + node = node.children[c] + return node.startsWith + + def _insert(self, word: str) -> None: + node = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.startsWith.append(word) + + +class Solution: + def wordSquares(self, words: List[str]) -> List[List[str]]: + if not words: + return [] + + n = len(words[0]) + ans = [] + path = [] + trie = Trie(words) + + for word in words: + path.append(word) + self._dfs(trie, n, path, ans) + path.pop() + + return ans + + def _dfs(self, trie: Trie, n: int, path: List[str], ans: List[List[str]]): + if len(path) == n: + ans.append(path.copy()) + return + + prefix = self._getPrefix(path) + + for s in trie.findBy(prefix): + path.append(s) + self.dfs(trie, n, path, ans) + path.pop() + + def _getPrefix(self, path: List[str]) -> str: + """ + e.g. path = ["wall", + "area"] + prefix = "le.." + """ + prefix = [] + index = len(path) + for s in path: + prefix.append(s[index]) + return ''.join(prefix) diff --git a/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.cpp b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.cpp new file mode 100644 index 00000000000..5c8814facb2 --- /dev/null +++ b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + // Similar to 94. Binary Tree Inorder Traversal + Node* treeToDoublyList(Node* root) { + if (root == nullptr) + return nullptr; + + stack stack; + Node* first = nullptr; + Node* pred = nullptr; + + while (root != nullptr || !stack.empty()) { + while (root != nullptr) { + stack.push(root); + root = root->left; + } + root = stack.top(), stack.pop(); + if (first == nullptr) + first = root; + if (pred != nullptr) { + pred->right = root; + root->left = pred; + } + pred = root; + root = root->right; + } + + pred->right = first; + first->left = pred; + return first; + } +}; diff --git a/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.java b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.java new file mode 100644 index 00000000000..da0be8fb273 --- /dev/null +++ b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.java @@ -0,0 +1,31 @@ +class Solution { + // Similar to 94. Binary Tree Inorder Traversal + public Node treeToDoublyList(Node root) { + if (root == null) + return null; + + Deque stack = new ArrayDeque<>(); + Node first = null; + Node pred = null; + + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + root = stack.pop(); + if (first == null) + first = root; + if (pred != null) { + pred.right = root; + root.left = pred; + } + pred = root; + root = root.right; + } + + pred.right = first; + first.left = pred; + return first; + } +} diff --git a/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.py b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.py new file mode 100644 index 00000000000..c7671af8319 --- /dev/null +++ b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426-2.py @@ -0,0 +1,25 @@ +class Solution: + def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]': + if not root: + return None + + stack = [] + first = None + pred = None + + while root or stack: + while root: + stack.append(root) + root = root.left + root = stack.pop() + if not first: + first = root + if pred: + pred.right = root + root.left = pred + pred = root + root = root.right + + pred.right = first + first.left = pred + return first diff --git a/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.cpp b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.cpp new file mode 100644 index 00000000000..a4f535a2a53 --- /dev/null +++ b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + Node* treeToDoublyList(Node* root) { + if (root == nullptr) + return nullptr; + Node* leftHead = treeToDoublyList(root->left); + Node* rightHead = treeToDoublyList(root->right); + root->left = root; + root->right = root; + return connect(connect(leftHead, root), rightHead); + } + + private: + Node* connect(Node* node1, Node* node2) { + if (node1 == nullptr) + return node2; + if (node2 == nullptr) + return node1; + + Node* tail1 = node1->left; + Node* tail2 = node2->left; + + // Connect node1's tail with node2. + tail1->right = node2; + node2->left = tail1; + + // Connect node2's tail with node1. + tail2->right = node1; + node1->left = tail2; + return node1; + } +}; diff --git a/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.java b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.java new file mode 100644 index 00000000000..667d3ea58ce --- /dev/null +++ b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.java @@ -0,0 +1,30 @@ +class Solution { + public Node treeToDoublyList(Node root) { + if (root == null) + return null; + Node leftHead = treeToDoublyList(root.left); + Node rightHead = treeToDoublyList(root.right); + root.left = root; + root.right = root; + return connect(connect(leftHead, root), rightHead); + } + + private Node connect(Node node1, Node node2) { + if (node1 == null) + return node2; + if (node2 == null) + return node1; + + Node tail1 = node1.left; + Node tail2 = node2.left; + + // Connect node1's tail with node2. + tail1.right = node2; + node2.left = tail1; + + // Connect node2's tail with node1. + tail2.right = node1; + node1.left = tail2; + return node1; + } +} diff --git a/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.py b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.py new file mode 100644 index 00000000000..9d72d428b8b --- /dev/null +++ b/solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.py @@ -0,0 +1,27 @@ +class Solution: + def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]': + if not root: + return None + leftHead = self.treeToDoublyList(root.left) + rightHead = self.treeToDoublyList(root.right) + root.left = root + root.right = root + return self._connect(self._connect(leftHead, root), rightHead) + + def _connect(self, node1: 'Optional[Node]', node2: 'Optional[Node]') -> 'Optional[Node]': + if not node1: + return node2 + if not node2: + return node1 + + tail1 = node1.left + tail2 = node2.left + + # Connect node1's tail with node2. + tail1.right = node2 + node2.left = tail1 + + # Connect node2's tail with node1. + tail2.right = node1 + node1.left = tail2 + return node1 diff --git a/solutions/427. Construct Quad Tree/427.cpp b/solutions/427. Construct Quad Tree/427.cpp new file mode 100644 index 00000000000..6652baaefe5 --- /dev/null +++ b/solutions/427. Construct Quad Tree/427.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + Node* construct(vector>& grid) { + return helper(grid, 0, 0, grid.size()); + } + + private: + Node* helper(const vector>& grid, int i, int j, int w) { + if (allSame(grid, i, j, w)) + return new Node(grid[i][j], true); + + Node* node = new Node(true, false); + node->topLeft = helper(grid, i, j, w / 2); + node->topRight = helper(grid, i, j + w / 2, w / 2); + node->bottomLeft = helper(grid, i + w / 2, j, w / 2); + node->bottomRight = helper(grid, i + w / 2, j + w / 2, w / 2); + return node; + } + + bool allSame(const vector>& grid, int i, int j, int w) { + return all_of(grid.begin() + i, grid.begin() + i + w, + [&](const vector& row) { + return all_of(row.begin() + j, row.begin() + j + w, + [&](int num) { return num == grid[i][j]; }); + }); + } +}; diff --git a/solutions/427. Construct Quad Tree/427.java b/solutions/427. Construct Quad Tree/427.java new file mode 100644 index 00000000000..c7f4717611a --- /dev/null +++ b/solutions/427. Construct Quad Tree/427.java @@ -0,0 +1,25 @@ +class Solution { + public Node construct(int[][] grid) { + return helper(grid, 0, 0, grid.length); + } + + private Node helper(int[][] grid, int i, int j, int w) { + if (allSame(grid, i, j, w)) + return new Node(grid[i][j] == 1 ? true : false, true); + + Node node = new Node(true, false); + node.topLeft = helper(grid, i, j, w / 2); + node.topRight = helper(grid, i, j + w / 2, w / 2); + node.bottomLeft = helper(grid, i + w / 2, j, w / 2); + node.bottomRight = helper(grid, i + w / 2, j + w / 2, w / 2); + return node; + } + + private boolean allSame(int[][] grid, int i, int j, int w) { + for (int x = i; x < i + w; ++x) + for (int y = j; y < j + w; ++y) + if (grid[x][y] != grid[i][j]) + return false; + return true; + } +} diff --git a/solutions/428. Serialize and Deserialize N-ary Tree/428.cpp b/solutions/428. Serialize and Deserialize N-ary Tree/428.cpp new file mode 100644 index 00000000000..e75545e95fe --- /dev/null +++ b/solutions/428. Serialize and Deserialize N-ary Tree/428.cpp @@ -0,0 +1,69 @@ +class Codec { + public: + // Encodes a tree to a single string. + string serialize(Node* root) { + if (root == nullptr) + return ""; + + string s; + queue q{{root}}; + s += to_string(root->val) + " "; + + while (!q.empty()) + for (int sz = q.size(); sz > 0; --sz) { + Node* node = q.front(); + q.pop(); + if (node->children.empty()) { + s += "n"; + } else { + for (Node* child : node->children) { + q.push(child); + s += to_string(child->val) + "#"; + } + } + s += " "; + } + + return s; + } + + // Decodes your encoded data to tree. + Node* deserialize(string data) { + if (data.empty()) + return nullptr; + + istringstream iss(data); + string word; + iss >> word; + Node* root = new Node(stoi(word)); + queue q{{root}}; + + while (iss >> word) { + Node* parent = q.front(); + q.pop(); + vector kids = getKids(word); + vector children; + for (const string& kid : kids) { + if (kid == "n") + continue; + Node* child = new Node(stoi(kid)); + children.push_back(child); + q.push(child); + } + parent->children = children; + } + + return root; + } + + private: + vector getKids(const string& word) { + vector kids; + for (int i = 0, j = 0; j < word.length(); ++j) + if (word[j] == '#') { + kids.push_back(word.substr(i, j - i)); + i = j + 1; + } + return kids; + } +}; diff --git a/solutions/428. Serialize and Deserialize N-ary Tree/428.java b/solutions/428. Serialize and Deserialize N-ary Tree/428.java new file mode 100644 index 00000000000..13c141e6023 --- /dev/null +++ b/solutions/428. Serialize and Deserialize N-ary Tree/428.java @@ -0,0 +1,52 @@ +class Codec { + // Encodes a tree to a single string. + public String serialize(Node root) { + if (root == null) + return ""; + + StringBuilder sb = new StringBuilder().append(root.val).append(","); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) + for (int sz = q.size(); sz > 0; --sz) { + Node node = q.poll(); + if (node.children.isEmpty()) { + sb.append("n"); + } else { + for (Node child : node.children) { + q.offer(child); + sb.append(child.val).append("#"); + } + } + sb.append(","); + } + + return sb.toString(); + } + + // Decodes your encoded data to tree. + public Node deserialize(String data) { + if (data.equals("")) + return null; + + final String[] vals = data.split(","); + Node root = new Node(Integer.parseInt(vals[0])); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + for (int i = 1; i < vals.length; ++i) { + Node parent = q.poll(); + final String[] kids = vals[i].split("#"); + List children = new ArrayList<>(); + for (final String kid : kids) { + if (kid.equals("n")) + continue; + Node child = new Node(Integer.parseInt(kid)); + children.add(child); + q.offer(child); + } + parent.children = children; + } + + return root; + } +} diff --git a/solutions/429. N-ary Tree Level Order Traversal/429.cpp b/solutions/429. N-ary Tree Level Order Traversal/429.cpp new file mode 100644 index 00000000000..81205dc3070 --- /dev/null +++ b/solutions/429. N-ary Tree Level Order Traversal/429.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector> levelOrder(Node* root) { + if (root == nullptr) + return {}; + + vector> ans; + queue q{{root}}; + + while (!q.empty()) { + vector currLevel; + for (int sz = q.size(); sz > 0; --sz) { + Node* node = q.front(); + q.pop(); + currLevel.push_back(node->val); + for (Node* child : node->children) + q.push(child); + } + ans.push_back(currLevel); + } + + return ans; + } +}; diff --git a/solutions/429. N-ary Tree Level Order Traversal/429.java b/solutions/429. N-ary Tree Level Order Traversal/429.java new file mode 100644 index 00000000000..a9e58bed478 --- /dev/null +++ b/solutions/429. N-ary Tree Level Order Traversal/429.java @@ -0,0 +1,22 @@ +class Solution { + public List> levelOrder(Node root) { + if (root == null) + return new ArrayList<>(); + + List> ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + List currLevel = new ArrayList<>(); + for (int sz = q.size(); sz > 0; --sz) { + Node node = q.poll(); + currLevel.add(node.val); + for (Node child : node.children) + q.offer(child); + } + ans.add(currLevel); + } + + return ans; + } +} diff --git a/solutions/43. Multiply Strings/43.cpp b/solutions/43. Multiply Strings/43.cpp new file mode 100644 index 00000000000..49cabfa0d93 --- /dev/null +++ b/solutions/43. Multiply Strings/43.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string multiply(string num1, string num2) { + string s(num1.length() + num2.length(), '0'); + + for (int i = num1.length() - 1; i >= 0; --i) + for (int j = num2.length() - 1; j >= 0; --j) { + const int mult = (num1[i] - '0') * (num2[j] - '0'); + const int sum = mult + (s[i + j + 1] - '0'); + s[i + j] += sum / 10; + s[i + j + 1] = '0' + sum % 10; + } + + const int i = s.find_first_not_of('0'); + return i == string::npos ? "0" : s.substr(i); + } +}; diff --git a/solutions/43. Multiply Strings/43.java b/solutions/43. Multiply Strings/43.java new file mode 100644 index 00000000000..7503f845963 --- /dev/null +++ b/solutions/43. Multiply Strings/43.java @@ -0,0 +1,23 @@ +class Solution { + public String multiply(String num1, String num2) { + final int m = num1.length(); + final int n = num2.length(); + + StringBuilder sb = new StringBuilder(); + int[] pos = new int[m + n]; + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) { + final int multiply = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); + final int sum = multiply + pos[i + j + 1]; + pos[i + j] += sum / 10; + pos[i + j + 1] = sum % 10; + } + + for (final int p : pos) + if (p > 0 || sb.length() > 0) + sb.append(p); + + return sb.length() == 0 ? "0" : sb.toString(); + } +} diff --git a/solutions/43. Multiply Strings/43.py b/solutions/43. Multiply Strings/43.py new file mode 100644 index 00000000000..ec71b0d231f --- /dev/null +++ b/solutions/43. Multiply Strings/43.py @@ -0,0 +1,16 @@ +class Solution: + def multiply(self, num1: str, num2: str) -> str: + s = [0] * (len(num1) + len(num2)) + + for i in reversed(range(len(num1))): + for j in reversed(range(len(num2))): + mult = int(num1[i]) * int(num2[j]) + summ = mult + s[i + j + 1] + s[i + j] += summ // 10 + s[i + j + 1] = summ % 10 + + for i, c in enumerate(s): + if c != 0: + break + + return ''.join(map(str, s[i:])) diff --git a/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.cpp b/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.cpp new file mode 100644 index 00000000000..e270c23aa09 --- /dev/null +++ b/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + Node* flatten(Node* head) { + for (Node* curr = head; curr; curr = curr->next) + if (curr->child) { + Node* cachedNext = curr->next; + curr->next = curr->child; + curr->child->prev = curr; + curr->child = nullptr; + Node* tail = curr->next; + while (tail->next) + tail = tail->next; + tail->next = cachedNext; + if (cachedNext != nullptr) + cachedNext->prev = tail; + } + + return head; + } +}; diff --git a/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.java b/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.java new file mode 100644 index 00000000000..d79a569a215 --- /dev/null +++ b/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.java @@ -0,0 +1,19 @@ +class Solution { + public Node flatten(Node head) { + for (Node curr = head; curr != null; curr = curr.next) + if (curr.child != null) { + Node cachedNext = curr.next; + curr.next = curr.child; + curr.child.prev = curr; + curr.child = null; + Node tail = curr.next; + while (tail.next != null) + tail = tail.next; + tail.next = cachedNext; + if (cachedNext != null) + cachedNext.prev = tail; + } + + return head; + } +} diff --git a/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.py b/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.py new file mode 100644 index 00000000000..2ac7a65fcf3 --- /dev/null +++ b/solutions/430. Flatten a Multilevel Doubly Linked List/430-2.py @@ -0,0 +1,19 @@ +class Solution: + def flatten(self, head: 'Node') -> 'Node': + curr = head + + while curr: + if curr.child: + cachedNext = curr.next + curr.next = curr.child + curr.child.prev = curr + curr.child = None + tail = curr.next + while tail.next: + tail = tail.next + tail.next = cachedNext + if cachedNext: + cachedNext.prev = tail + curr = curr.next + + return head diff --git a/solutions/430. Flatten a Multilevel Doubly Linked List/430.cpp b/solutions/430. Flatten a Multilevel Doubly Linked List/430.cpp new file mode 100644 index 00000000000..10ea3f94957 --- /dev/null +++ b/solutions/430. Flatten a Multilevel Doubly Linked List/430.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + Node* flatten(Node* head, Node* rest = nullptr) { + if (head == nullptr) + return rest; + + head->next = flatten(head->child, flatten(head->next, rest)); + if (head->next) + head->next->prev = head; + head->child = nullptr; + return head; + } +}; diff --git a/solutions/430. Flatten a Multilevel Doubly Linked List/430.java b/solutions/430. Flatten a Multilevel Doubly Linked List/430.java new file mode 100644 index 00000000000..063a782c529 --- /dev/null +++ b/solutions/430. Flatten a Multilevel Doubly Linked List/430.java @@ -0,0 +1,16 @@ +class Solution { + public Node flatten(Node head) { + return flatten(head, null); + } + + private Node flatten(Node head, Node rest) { + if (head == null) + return rest; + + head.next = flatten(head.child, flatten(head.next, rest)); + if (head.next != null) + head.next.prev = head; + head.child = null; + return head; + } +} diff --git a/solutions/430. Flatten a Multilevel Doubly Linked List/430.py b/solutions/430. Flatten a Multilevel Doubly Linked List/430.py new file mode 100644 index 00000000000..e03eab4596a --- /dev/null +++ b/solutions/430. Flatten a Multilevel Doubly Linked List/430.py @@ -0,0 +1,13 @@ +class Solution: + def flatten(self, head: 'Node') -> 'Node': + def flatten(head: 'Node', rest: 'Node') -> 'Node': + if not head: + return rest + + head.next = flatten(head.child, flatten(head.next, rest)) + if head.next: + head.next.prev = head + head.child = None + return head + + return flatten(head, None) diff --git a/solutions/431. Encode N-ary Tree to Binary Tree/431-2.cpp b/solutions/431. Encode N-ary Tree to Binary Tree/431-2.cpp new file mode 100644 index 00000000000..97aed73e20e --- /dev/null +++ b/solutions/431. Encode N-ary Tree to Binary Tree/431-2.cpp @@ -0,0 +1,39 @@ +class Codec { + public: + // Encodes an n-ary tree to a binary tree. + TreeNode* encode(Node* root) { + if (root == nullptr) + return nullptr; + + TreeNode* rootTreeNode = new TreeNode(root->val); + if (!root->children.empty()) + rootTreeNode->left = encode(root->children[0]); + + // The parent for the rest of the children + TreeNode* currTreeNode = rootTreeNode->left; + + // Encode the rest of the children + for (int i = 1; i < root->children.size(); ++i) { + currTreeNode->right = encode(root->children[i]); + currTreeNode = currTreeNode->right; + } + + return rootTreeNode; + } + + // Decodes your binary tree to an n-ary tree. + Node* decode(TreeNode* root) { + if (root == nullptr) + return nullptr; + + Node* rootNode = new Node(root->val); + TreeNode* currTreeNode = root->left; + + while (currTreeNode != nullptr) { + rootNode->children.push_back(decode(currTreeNode)); + currTreeNode = currTreeNode->right; + } + + return rootNode; + } +}; diff --git a/solutions/431. Encode N-ary Tree to Binary Tree/431-2.java b/solutions/431. Encode N-ary Tree to Binary Tree/431-2.java new file mode 100644 index 00000000000..97e32be74a7 --- /dev/null +++ b/solutions/431. Encode N-ary Tree to Binary Tree/431-2.java @@ -0,0 +1,38 @@ +class Codec { + // Encodes an n-ary tree to a binary tree. + public TreeNode encode(Node root) { + if (root == null) + return null; + + TreeNode rootTreeNode = new TreeNode(root.val); + if (!root.children.isEmpty()) + rootTreeNode.left = encode(root.children.get(0)); + + // The parent for the rest of the children + TreeNode currTreeNode = rootTreeNode.left; + + // Encode the rest of the children + for (int i = 1; i < root.children.size(); ++i) { + currTreeNode.right = encode(root.children.get(i)); + currTreeNode = currTreeNode.right; + } + + return rootTreeNode; + } + + // Decodes your binary tree to an n-ary tree. + public Node decode(TreeNode root) { + if (root == null) + return null; + + Node rootNode = new Node(root.val, new ArrayList<>()); + TreeNode currTreeNode = root.left; + + while (currTreeNode != null) { + rootNode.children.add(decode(currTreeNode)); + currTreeNode = currTreeNode.right; + } + + return rootNode; + } +} diff --git a/solutions/431. Encode N-ary Tree to Binary Tree/431-2.py b/solutions/431. Encode N-ary Tree to Binary Tree/431-2.py new file mode 100644 index 00000000000..3365a8da743 --- /dev/null +++ b/solutions/431. Encode N-ary Tree to Binary Tree/431-2.py @@ -0,0 +1,33 @@ +class Codec: + # Encodes an n-ary tree to a binary tree. + def encode(self, root: 'Node') -> Optional[TreeNode]: + if not root: + return None + + rootTreeNode = TreeNode(root.val) + if root.children: + rootTreeNode.left = self.encode(root.children[0]) + + # The parent for the rest of the children + currTreeNode = rootTreeNode.left + + # Encode the rest of the children + for i in range(1, len(root.children)): + currTreeNode.right = self.encode(root.children[i]) + currTreeNode = currTreeNode.right + + return rootTreeNode + + # Decodes your binary tree to an n-ary tree. + def decode(self, root: Optional[TreeNode]) -> 'Node': + if not root: + return None + + rootNode = Node(root.val, []) + currTreeNode = root.left + + while currTreeNode: + rootNode.children.append(self.decode(currTreeNode)) + currTreeNode = currTreeNode.right + + return rootNode diff --git a/solutions/431. Encode N-ary Tree to Binary Tree/431.cpp b/solutions/431. Encode N-ary Tree to Binary Tree/431.cpp new file mode 100644 index 00000000000..de91a898553 --- /dev/null +++ b/solutions/431. Encode N-ary Tree to Binary Tree/431.cpp @@ -0,0 +1,53 @@ +class Codec { + public: + // Encodes an n-ary tree to a binary tree. + TreeNode* encode(Node* root) { + if (root == nullptr) + return nullptr; + + TreeNode* rootTreeNode = new TreeNode(root->val); + queue> q{{{root, rootTreeNode}}}; + + while (!q.empty()) { + const auto [parentNode, parentTreeNode] = q.front(); + q.pop(); + TreeNode* prevTreeNode = nullptr; + TreeNode* headTreeNode = nullptr; + for (Node* child : parentNode->children) { + TreeNode* currTreeNode = new TreeNode(child->val); + if (prevTreeNode != nullptr) + prevTreeNode->right = currTreeNode; + else + headTreeNode = currTreeNode; + prevTreeNode = currTreeNode; + q.emplace(child, currTreeNode); + } + parentTreeNode->left = headTreeNode; + } + + return rootTreeNode; + } + + // Decodes your binary tree to an n-ary tree. + Node* decode(TreeNode* root) { + if (root == nullptr) + return nullptr; + + Node* rootNode = new Node(root->val); + queue> q{{{rootNode, root}}}; + + while (!q.empty()) { + const auto [parentNode, parentTreeNode] = q.front(); + q.pop(); + TreeNode* sibling = parentTreeNode->left; + while (sibling) { + Node* currNode = new Node(sibling->val); + parentNode->children.push_back(currNode); + q.emplace(currNode, sibling); + sibling = sibling->right; + } + } + + return rootNode; + } +}; diff --git a/solutions/431. Encode N-ary Tree to Binary Tree/431.java b/solutions/431. Encode N-ary Tree to Binary Tree/431.java new file mode 100644 index 00000000000..ee9dd4e5f71 --- /dev/null +++ b/solutions/431. Encode N-ary Tree to Binary Tree/431.java @@ -0,0 +1,52 @@ +class Codec { + // Encodes an n-ary tree to a binary tree. + public TreeNode encode(Node root) { + if (root == null) + return null; + + TreeNode rootTreeNode = new TreeNode(root.val); + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(root, rootTreeNode))); + + while (!q.isEmpty()) { + Node parentNode = q.peek().getKey(); + TreeNode parentTreeNode = q.poll().getValue(); + TreeNode prevTreeNode = null; + TreeNode headTreeNode = null; + for (Node child : parentNode.children) { + TreeNode currTreeNode = new TreeNode(child.val); + if (prevTreeNode == null) + headTreeNode = currTreeNode; + else + prevTreeNode.right = currTreeNode; + prevTreeNode = currTreeNode; + q.offer(new Pair<>(child, currTreeNode)); + } + parentTreeNode.left = headTreeNode; + } + + return rootTreeNode; + } + + // Decodes your binary tree to an n-ary tree. + public Node decode(TreeNode root) { + if (root == null) + return null; + + Node rootNode = new Node(root.val, new ArrayList<>()); + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(rootNode, root))); + + while (!q.isEmpty()) { + Node parentNode = q.peek().getKey(); + TreeNode parentTreeNode = q.poll().getValue(); + TreeNode sibling = parentTreeNode.left; + while (sibling != null) { + Node currNode = new Node(sibling.val, new ArrayList<>()); + parentNode.children.add(currNode); + q.offer(new Pair<>(currNode, sibling)); + sibling = sibling.right; + } + } + + return rootNode; + } +} diff --git a/solutions/431. Encode N-ary Tree to Binary Tree/431.py b/solutions/431. Encode N-ary Tree to Binary Tree/431.py new file mode 100644 index 00000000000..38f71eea705 --- /dev/null +++ b/solutions/431. Encode N-ary Tree to Binary Tree/431.py @@ -0,0 +1,43 @@ +class Codec: + # Encodes an n-ary tree to a binary tree. + def encode(self, root: 'Node') -> Optional[TreeNode]: + if not root: + return None + + rootTreeNode = TreeNode(root.val) + q = collections.deque([(root, rootTreeNode)]) + + while q: + parentNode, parentTreeNode = q.popleft() + prevTreeNode = None + headTreeNode = None + for child in parentNode.children: + currTreeNode = TreeNode(child.val) + if prevTreeNode: + prevTreeNode.right = currTreeNode + else: + headTreeNode = currTreeNode + prevTreeNode = currTreeNode + q.append((child, currTreeNode)) + parentTreeNode.left = headTreeNode + + return rootTreeNode + + # Decodes your binary tree to an n-ary tree. + def decode(self, root: Optional[TreeNode]) -> 'Node': + if not root: + return None + + rootNode = Node(root.val, []) + q = collections.deque([(rootNode, root)]) + + while q: + parentNode, parentTreeNode = q.popleft() + sibling = parentTreeNode.left + while sibling: + currNode = Node(sibling.val, []) + parentNode.children.append(currNode) + q.append((currNode, sibling)) + sibling = sibling.right + + return rootNode diff --git a/solutions/432. All O`one Data Structure/432.cpp b/solutions/432. All O`one Data Structure/432.cpp new file mode 100644 index 00000000000..0fb2dfd3303 --- /dev/null +++ b/solutions/432. All O`one Data Structure/432.cpp @@ -0,0 +1,75 @@ +class AllOne { + public: + void inc(string key) { + const auto it = keyToIterator.find(key); + + // Doesn't find the key. + if (it == keyToIterator.cend()) { + if (l.empty() || l.front().value > 1) + l.push_front({1, {key}}); + else + l.front().keys.insert(key); + keyToIterator[key] = l.begin(); + return; + } + + const auto lit = it->second; // list iterator + auto nit = next(lit); // next iterator + + if (nit == l.end() || nit->value > lit->value + 1) + nit = l.insert(nit, {lit->value + 1, {key}}); + else // nit->value == lit->value + 1 + nit->keys.insert(key); + keyToIterator[key] = nit; // Reset the mapping. + + // Remove the key in the keys set. + lit->keys.erase(key); + if (lit->keys.empty()) + l.erase(lit); + } + + void dec(string key) { + const auto it = keyToIterator.find(key); + + // Doens't find the key. + if (it == keyToIterator.cend()) + return; + + const auto lit = it->second; // list iterator + + if (lit->value == 1) { + // no need to find the previous iterator in this case. + keyToIterator.erase(key); + } else { + auto pit = prev(lit); // the previous iterator + + if (lit == l.begin() || pit->value < lit->value - 1) + pit = l.insert(lit, {lit->value - 1, {key}}); + else // pit->value == lit-value - 1 + pit->keys.insert(key); + keyToIterator[key] = pit; // Reset the mapping. + } + + // Remove the key in the keys set. + lit->keys.erase(key); + if (lit->keys.empty()) + l.erase(lit); + } + + string getMaxKey() { + return l.empty() ? "" : *l.back().keys.cbegin(); + } + + string getMinKey() { + return l.empty() ? "" : *l.front().keys.cbegin(); + } + + private: + struct Node { + int value; + unordered_set keys; + }; + + list l; + unordered_map::iterator> keyToIterator; +}; diff --git a/solutions/433. Minimum Genetic Mutation/433.cpp b/solutions/433. Minimum Genetic Mutation/433.cpp new file mode 100644 index 00000000000..077812bcebb --- /dev/null +++ b/solutions/433. Minimum Genetic Mutation/433.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int minMutation(string start, string end, vector& bank) { + unordered_set bankSet{bank.begin(), bank.end()}; + if (!bankSet.contains(end)) + return -1; + + int ans = 0; + queue q{{start}}; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + string word = q.front(); + q.pop(); + for (int j = 0; j < word.length(); ++j) { + const char cache = word[j]; + for (const char c : {'A', 'C', 'G', 'T'}) { + word[j] = c; + if (word == end) + return ans; + if (bankSet.contains(word)) { + bankSet.erase(word); + q.push(word); + } + } + word[j] = cache; + } + } + } + + return -1; + } +}; diff --git a/solutions/433. Minimum Genetic Mutation/433.java b/solutions/433. Minimum Genetic Mutation/433.java new file mode 100644 index 00000000000..0ff2ff7e624 --- /dev/null +++ b/solutions/433. Minimum Genetic Mutation/433.java @@ -0,0 +1,33 @@ +class Solution { + public int minMutation(String start, String end, String[] bank) { + Set bankSet = new HashSet<>(Arrays.asList(bank)); + if (!bankSet.contains(end)) + return -1; + + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(start)); + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + StringBuilder sb = new StringBuilder(q.poll()); + for (int j = 0; j < sb.length(); ++j) { + final char cache = sb.charAt(j); + for (final char c : new char[] {'A', 'C', 'G', 'T'}) { + sb.setCharAt(j, c); + final String word = sb.toString(); + if (word.equals(end)) + return ans; + if (bankSet.contains(word)) { + bankSet.remove(word); + q.offer(word); + } + } + sb.setCharAt(j, cache); + } + } + } + + return -1; + } +} diff --git a/solutions/434. Number of Segments in a String/434.cpp b/solutions/434. Number of Segments in a String/434.cpp new file mode 100644 index 00000000000..4407d26f190 --- /dev/null +++ b/solutions/434. Number of Segments in a String/434.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int countSegments(string s) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) + if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) + ++ans; + + return ans; + } +}; diff --git a/solutions/434. Number of Segments in a String/434.java b/solutions/434. Number of Segments in a String/434.java new file mode 100644 index 00000000000..9610cec733b --- /dev/null +++ b/solutions/434. Number of Segments in a String/434.java @@ -0,0 +1,11 @@ +class Solution { + public int countSegments(String s) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) + ++ans; + + return ans; + } +} diff --git a/solutions/434. Number of Segments in a String/434.py b/solutions/434. Number of Segments in a String/434.py new file mode 100644 index 00000000000..d05d24b4906 --- /dev/null +++ b/solutions/434. Number of Segments in a String/434.py @@ -0,0 +1,3 @@ +class Solution: + def countSegments(self, s: str) -> int: + return len(s.split()) diff --git a/solutions/435. Non-overlapping Intervals/435.cpp b/solutions/435. Non-overlapping Intervals/435.cpp new file mode 100644 index 00000000000..5cd54639efd --- /dev/null +++ b/solutions/435. Non-overlapping Intervals/435.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int eraseOverlapIntervals(vector>& intervals) { + if (intervals.empty()) + return 0; + + ranges::sort(intervals, + [](const auto& a, const auto& b) { return a[1] < b[1]; }); + + int ans = 0; + int currentEnd = intervals[0][1]; + + for (int i = 1; i < intervals.size(); ++i) + if (intervals[i][0] >= currentEnd) + currentEnd = intervals[i][1]; + else + ++ans; + + return ans; + } +}; diff --git a/solutions/435. Non-overlapping Intervals/435.java b/solutions/435. Non-overlapping Intervals/435.java new file mode 100644 index 00000000000..c6e617ed05b --- /dev/null +++ b/solutions/435. Non-overlapping Intervals/435.java @@ -0,0 +1,19 @@ +class Solution { + public int eraseOverlapIntervals(int[][] intervals) { + if (intervals.length == 0) + return 0; + + Arrays.sort(intervals, (a, b) -> a[1] - b[1]); + + int ans = 0; + int currentEnd = intervals[0][1]; + + for (int i = 1; i < intervals.length; ++i) + if (intervals[i][0] >= currentEnd) + currentEnd = intervals[i][1]; + else + ++ans; + + return ans; + } +} diff --git a/solutions/435. Non-overlapping Intervals/435.py b/solutions/435. Non-overlapping Intervals/435.py new file mode 100644 index 00000000000..23cac116f74 --- /dev/null +++ b/solutions/435. Non-overlapping Intervals/435.py @@ -0,0 +1,12 @@ +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + ans = 0 + currentEnd = -math.inf + + for interval in sorted(intervals, key=lambda x: x[1]): + if interval[0] >= currentEnd: + currentEnd = interval[1] + else: + ans += 1 + + return ans diff --git a/solutions/436. Find Right Interval/436.cpp b/solutions/436. Find Right Interval/436.cpp new file mode 100644 index 00000000000..31dd3e7fbee --- /dev/null +++ b/solutions/436. Find Right Interval/436.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector findRightInterval(vector>& intervals) { + vector ans; + map startToIndex; + + for (int i = 0; i < intervals.size(); ++i) + startToIndex[intervals[i][0]] = i; + + for (const vector& interval : intervals) { + const auto it = startToIndex.lower_bound(interval[1]); + if (it == startToIndex.cend()) + ans.push_back(-1); + else + ans.push_back(it->second); + } + + return ans; + } +}; diff --git a/solutions/436. Find Right Interval/436.java b/solutions/436. Find Right Interval/436.java new file mode 100644 index 00000000000..e8d1ddcf77c --- /dev/null +++ b/solutions/436. Find Right Interval/436.java @@ -0,0 +1,21 @@ +class Solution { + public int[] findRightInterval(int[][] intervals) { + final int n = intervals.length; + + int[] ans = new int[n]; + java.util.NavigableMap startToIndex = new TreeMap<>(); + + for (int i = 0; i < n; ++i) + startToIndex.put(intervals[i][0], i); + + for (int i = 0; i < n; ++i) { + Map.Entry entry = startToIndex.ceilingEntry(intervals[i][1]); + if (entry == null) + ans[i] = -1; + else + ans[i] = entry.getValue(); + } + + return ans; + } +} diff --git a/solutions/437. Path Sum III/437.cpp b/solutions/437. Path Sum III/437.cpp new file mode 100644 index 00000000000..375c3e784f9 --- /dev/null +++ b/solutions/437. Path Sum III/437.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int pathSum(TreeNode* root, int sum) { + if (root == nullptr) + return 0; + return dfs(root, sum) + // + pathSum(root->left, sum) + // + pathSum(root->right, sum); + } + + private: + int dfs(TreeNode* root, int sum) { + if (root == nullptr) + return 0; + return (sum == root->val) + // + dfs(root->left, sum - root->val) + // + dfs(root->right, sum - root->val); + } +}; diff --git a/solutions/437. Path Sum III/437.java b/solutions/437. Path Sum III/437.java new file mode 100644 index 00000000000..251f59d9c30 --- /dev/null +++ b/solutions/437. Path Sum III/437.java @@ -0,0 +1,15 @@ +class Solution { + public int pathSum(TreeNode root, int sum) { + if (root == null) + return 0; + return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); + } + + private int dfs(TreeNode root, int sum) { + if (root == null) + return 0; + return (sum == root.val ? 1 : 0) + // + dfs(root.left, sum - root.val) + // + dfs(root.right, sum - root.val); + } +} diff --git a/solutions/437. Path Sum III/437.py b/solutions/437. Path Sum III/437.py new file mode 100644 index 00000000000..d1af508da55 --- /dev/null +++ b/solutions/437. Path Sum III/437.py @@ -0,0 +1,15 @@ +class Solution: + def pathSum(self, root: TreeNode, summ: int) -> int: + if not root: + return 0 + + def dfs(root: TreeNode, summ: int) -> int: + if not root: + return 0 + return (summ == root.val) + \ + dfs(root.left, summ - root.val) + \ + dfs(root.right, summ - root.val) + + return dfs(root, summ) + \ + self.pathSum(root.left, summ) + \ + self.pathSum(root.right, summ) diff --git a/solutions/438. Find All Anagrams in a String/438.cpp b/solutions/438. Find All Anagrams in a String/438.cpp new file mode 100644 index 00000000000..2bfd18b5fa0 --- /dev/null +++ b/solutions/438. Find All Anagrams in a String/438.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector findAnagrams(string s, string p) { + vector ans; + vector count(128); + int required = p.length(); + + for (const char c : p) + ++count[c]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (--count[s[r]] >= 0) + --required; + while (required == 0) { + if (r - l + 1 == p.length()) + ans.push_back(l); + if (++count[s[l++]] > 0) + ++required; + } + } + + return ans; + } +}; diff --git a/solutions/438. Find All Anagrams in a String/438.java b/solutions/438. Find All Anagrams in a String/438.java new file mode 100644 index 00000000000..973ab80b054 --- /dev/null +++ b/solutions/438. Find All Anagrams in a String/438.java @@ -0,0 +1,23 @@ +class Solution { + public List findAnagrams(String s, String p) { + List ans = new ArrayList<>(); + int[] count = new int[128]; + int required = p.length(); + + for (final char c : p.toCharArray()) + ++count[c]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (--count[s.charAt(r)] >= 0) + --required; + while (required == 0) { + if (r - l + 1 == p.length()) + ans.add(l); + if (++count[s.charAt(l++)] > 0) + ++required; + } + } + + return ans; + } +} diff --git a/solutions/438. Find All Anagrams in a String/438.py b/solutions/438. Find All Anagrams in a String/438.py new file mode 100644 index 00000000000..d95d3f72235 --- /dev/null +++ b/solutions/438. Find All Anagrams in a String/438.py @@ -0,0 +1,18 @@ +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + ans = [] + count = collections.Counter(p) + required = len(p) + + for r, c in enumerate(s): + count[c] -= 1 + if count[c] >= 0: + required -= 1 + if r >= len(p): + count[s[r - len(p)]] += 1 + if count[s[r - len(p)]] > 0: + required += 1 + if required == 0: + ans.append(r - len(p) + 1) + + return ans diff --git a/solutions/439. Ternary Expression Parser/439.cpp b/solutions/439. Ternary Expression Parser/439.cpp new file mode 100644 index 00000000000..29edbb5450b --- /dev/null +++ b/solutions/439. Ternary Expression Parser/439.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + string parseTernary(string expression) { + const char c = expression[i]; + + if (i + 1 == expression.length() || expression[i + 1] == ':') { + i += 2; // Skip ':'s. + return string(1, c); + } + + i += 2; // Skip '?'s. + const string& first = parseTernary(expression); + const string& second = parseTernary(expression); + return c == 'T' ? first : second; + } + + private: + int i = 0; +}; diff --git a/solutions/439. Ternary Expression Parser/439.java b/solutions/439. Ternary Expression Parser/439.java new file mode 100644 index 00000000000..a8a637333ac --- /dev/null +++ b/solutions/439. Ternary Expression Parser/439.java @@ -0,0 +1,17 @@ +class Solution { + public String parseTernary(String expression) { + final char c = expression.charAt(i); + + if (i + 1 == expression.length() || expression.charAt(i + 1) == ':') { + i += 2; // Skip ':'s. + return String.valueOf(c); + } + + i += 2; // Skip '?'s. + final String first = parseTernary(expression); + final String second = parseTernary(expression); + return c == 'T' ? first : second; + } + + private int i = 0; +} diff --git a/solutions/439. Ternary Expression Parser/439.py b/solutions/439. Ternary Expression Parser/439.py new file mode 100644 index 00000000000..8bcd6a602ce --- /dev/null +++ b/solutions/439. Ternary Expression Parser/439.py @@ -0,0 +1,15 @@ +class Solution: + def parseTernary(self, expression: str) -> str: + c = expression[self.i] + + if self.i + 1 == len(expression) or expression[self.i + 1] == ':': + self.i += 2 + return str(c) + + self.i += 2 + first = self.parseTernary(expression) + second = self.parseTernary(expression) + + return first if c == 'T' else second + + i = 0 diff --git a/solutions/44. Wildcard Matching/44.cpp b/solutions/44. Wildcard Matching/44.cpp new file mode 100644 index 00000000000..ec53ac8f0a3 --- /dev/null +++ b/solutions/44. Wildcard Matching/44.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool isMatch(string s, string p) { + const int m = s.length(); + const int n = p.length(); + // dp[i][j] := true if s[0..i) matches p[0..j) + vector> dp(m + 1, vector(n + 1)); + dp[0][0] = true; + + auto isMatch = [&](int i, int j) -> bool { + return j >= 0 && p[j] == '?' || s[i] == p[j]; + }; + + for (int j = 0; j < p.length(); ++j) + if (p[j] == '*') + dp[0][j + 1] = dp[0][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (p[j] == '*') { + const bool matchEmpty = dp[i + 1][j]; + const bool matchSome = dp[i][j + 1]; + dp[i + 1][j + 1] = matchEmpty || matchSome; + } else if (isMatch(i, j)) { + dp[i + 1][j + 1] = dp[i][j]; + } + + return dp[m][n]; + } +}; diff --git a/solutions/44. Wildcard Matching/44.java b/solutions/44. Wildcard Matching/44.java new file mode 100644 index 00000000000..2df850a339b --- /dev/null +++ b/solutions/44. Wildcard Matching/44.java @@ -0,0 +1,29 @@ +class Solution { + public boolean isMatch(String s, String p) { + final int m = s.length(); + final int n = p.length(); + // dp[i][j] := true if s[0..i) matches p[0..j) + boolean[][] dp = new boolean[m + 1][n + 1]; + dp[0][0] = true; + + for (int j = 0; j < p.length(); ++j) + if (p.charAt(j) == '*') + dp[0][j + 1] = dp[0][j]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (p.charAt(j) == '*') { + final boolean matchEmpty = dp[i + 1][j]; + final boolean matchSome = dp[i][j + 1]; + dp[i + 1][j + 1] = matchEmpty || matchSome; + } else if (isMatch(s, i, p, j)) { + dp[i + 1][j + 1] = dp[i][j]; + } + + return dp[m][n]; + } + + private boolean isMatch(final String s, int i, final String p, int j) { + return j >= 0 && p.charAt(j) == '?' || s.charAt(i) == p.charAt(j); + } +} diff --git a/solutions/44. Wildcard Matching/44.py b/solutions/44. Wildcard Matching/44.py new file mode 100644 index 00000000000..bc772646033 --- /dev/null +++ b/solutions/44. Wildcard Matching/44.py @@ -0,0 +1,25 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + m = len(s) + n = len(p) + # dp[i][j] := True if s[0..i) matches p[0..j) + dp = [[False] * (n + 1) for _ in range(m + 1)] + dp[0][0] = True + + def isMatch(i: int, j: int) -> bool: + return i >= 0 and p[j] == '?' or s[i] == p[j] + + for j, c in enumerate(p): + if c == '*': + dp[0][j + 1] = dp[0][j] + + for i in range(m): + for j in range(n): + if p[j] == '*': + matchEmpty = dp[i + 1][j] + matchSome = dp[i][j + 1] + dp[i + 1][j + 1] = matchEmpty or matchSome + elif isMatch(i, j): + dp[i + 1][j + 1] = dp[i][j] + + return dp[m][n] diff --git a/solutions/440. K-th Smallest in Lexicographical Order/440.cpp b/solutions/440. K-th Smallest in Lexicographical Order/440.cpp new file mode 100644 index 00000000000..f5fb229a19c --- /dev/null +++ b/solutions/440. K-th Smallest in Lexicographical Order/440.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int findKthNumber(long n, int k) { + auto getGap = [&n](long a, long b) { + long gap = 0; + while (a <= n) { + gap += min(n + 1, b) - a; + a *= 10; + b *= 10; + } + return gap; + }; + + long currNum = 1; + + for (int i = 1; i < k;) { + long gap = getGap(currNum, currNum + 1); + if (i + gap <= k) { + i += gap; + ++currNum; + } else { + ++i; + currNum *= 10; + } + } + + return currNum; + } +}; diff --git a/solutions/440. K-th Smallest in Lexicographical Order/440.java b/solutions/440. K-th Smallest in Lexicographical Order/440.java new file mode 100644 index 00000000000..fc07aacec64 --- /dev/null +++ b/solutions/440. K-th Smallest in Lexicographical Order/440.java @@ -0,0 +1,28 @@ +class Solution { + public int findKthNumber(int n, int k) { + long currNum = 1; + + for (int i = 1; i < k;) { + long gap = getGap(currNum, currNum + 1, n); + if (i + gap <= k) { + i += gap; + ++currNum; + } else { + ++i; + currNum *= 10; + } + } + + return (int) currNum; + } + + private long getGap(long a, long b, long n) { + long gap = 0; + while (a <= n) { + gap += Math.min(n + 1, b) - a; + a *= 10; + b *= 10; + } + return gap; + } +} diff --git a/solutions/441. Arranging Coins/441.cpp b/solutions/441. Arranging Coins/441.cpp new file mode 100644 index 00000000000..6ce73eeb8b0 --- /dev/null +++ b/solutions/441. Arranging Coins/441.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int arrangeCoins(long n) { + return (-1 + sqrt(8 * n + 1)) / 2; + } +}; diff --git a/solutions/441. Arranging Coins/441.java b/solutions/441. Arranging Coins/441.java new file mode 100644 index 00000000000..370a48a5f1d --- /dev/null +++ b/solutions/441. Arranging Coins/441.java @@ -0,0 +1,5 @@ +class Solution { + public int arrangeCoins(long n) { + return (int) (-1 + Math.sqrt(8 * n + 1)) / 2; + } +} diff --git a/solutions/441. Arranging Coins/441.py b/solutions/441. Arranging Coins/441.py new file mode 100644 index 00000000000..f29b6dd1868 --- /dev/null +++ b/solutions/441. Arranging Coins/441.py @@ -0,0 +1,3 @@ +class Solution: + def arrangeCoins(self, n: int) -> int: + return int((-1 + math.sqrt(8 * n + 1)) // 2) diff --git a/solutions/442. Find All Duplicates in an Array/442.cpp b/solutions/442. Find All Duplicates in an Array/442.cpp new file mode 100644 index 00000000000..87319f46b8b --- /dev/null +++ b/solutions/442. Find All Duplicates in an Array/442.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector findDuplicates(vector& nums) { + vector ans; + + for (const int num : nums) { + nums[abs(num) - 1] *= -1; + if (nums[abs(num) - 1] > 0) + ans.push_back(abs(num)); + } + + return ans; + } +}; diff --git a/solutions/442. Find All Duplicates in an Array/442.java b/solutions/442. Find All Duplicates in an Array/442.java new file mode 100644 index 00000000000..076152d9aec --- /dev/null +++ b/solutions/442. Find All Duplicates in an Array/442.java @@ -0,0 +1,13 @@ +class Solution { + public List findDuplicates(int[] nums) { + List ans = new ArrayList<>(); + + for (final int num : nums) { + nums[Math.abs(num) - 1] *= -1; + if (nums[Math.abs(num) - 1] > 0) + ans.add(Math.abs(num)); + } + + return ans; + } +} diff --git a/solutions/442. Find All Duplicates in an Array/442.py b/solutions/442. Find All Duplicates in an Array/442.py new file mode 100644 index 00000000000..e182a82b309 --- /dev/null +++ b/solutions/442. Find All Duplicates in an Array/442.py @@ -0,0 +1,10 @@ +class Solution: + def findDuplicates(self, nums: List[int]) -> List[int]: + ans = [] + + for num in nums: + nums[abs(num) - 1] *= -1 + if nums[abs(num) - 1] > 0: + ans.append(abs(num)) + + return ans diff --git a/solutions/443. String Compression/443.cpp b/solutions/443. String Compression/443.cpp new file mode 100644 index 00000000000..e3a17344ffc --- /dev/null +++ b/solutions/443. String Compression/443.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int compress(vector& chars) { + int ans = 0; + + for (int i = 0; i < chars.size();) { + const char letter = chars[i]; + int count = 0; + while (i < chars.size() && chars[i] == letter) { + ++count; + ++i; + } + chars[ans++] = letter; + if (count > 1) + for (const char c : to_string(count)) + chars[ans++] = c; + } + + return ans; + } +}; diff --git a/solutions/443. String Compression/443.java b/solutions/443. String Compression/443.java new file mode 100644 index 00000000000..1581dbd5afa --- /dev/null +++ b/solutions/443. String Compression/443.java @@ -0,0 +1,20 @@ +class Solution { + public int compress(char[] chars) { + int ans = 0; + + for (int i = 0; i < chars.length;) { + final char letter = chars[i]; + int count = 0; + while (i < chars.length && chars[i] == letter) { + ++count; + ++i; + } + chars[ans++] = letter; + if (count > 1) + for (final char c : String.valueOf(count).toCharArray()) + chars[ans++] = c; + } + + return ans; + } +} diff --git a/solutions/443. String Compression/443.py b/solutions/443. String Compression/443.py new file mode 100644 index 00000000000..4b3b8261bc9 --- /dev/null +++ b/solutions/443. String Compression/443.py @@ -0,0 +1,19 @@ +class Solution: + def compress(self, chars: List[str]) -> int: + ans = 0 + i = 0 + + while i < len(chars): + letter = chars[i] + count = 0 + while i < len(chars) and chars[i] == letter: + count += 1 + i += 1 + chars[ans] = letter + ans += 1 + if count > 1: + for c in str(count): + chars[ans] = c + ans += 1 + + return ans diff --git a/solutions/444. Sequence Reconstruction/444.cpp b/solutions/444. Sequence Reconstruction/444.cpp new file mode 100644 index 00000000000..e2f11ad1662 --- /dev/null +++ b/solutions/444. Sequence Reconstruction/444.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + bool sequenceReconstruction(vector& org, vector>& seqs) { + if (seqs.empty()) + return false; + + const int n = org.size(); + vector> graph(n); + vector inDegrees(n); + + // Build the graph. + for (const vector& seq : seqs) { + if (seq.size() == 1 && seq[0] < 1 || seq[0] > n) + return false; + for (int i = 0; i + 1 < seq.size(); ++i) { + const int u = seq[i]; + const int v = seq[i + 1]; + if (u < 1 || u > n || v < 1 || v > n) + return false; + graph[u - 1].push_back(v - 1); + ++inDegrees[v - 1]; + } + } + + // Perform topological sorting. + queue q; + + for (int i = 0; i < n; ++i) + if (inDegrees[i] == 0) + q.push(i); + + int i = 0; // org's index + + while (!q.empty()) { + if (q.size() > 1) + return false; + const int u = q.front(); + q.pop(); + if (u != org[i] - 1) + return false; + ++i; + for (const int v : graph[u]) + if (--inDegrees[v] == 0) + q.push(v); + } + + return i == n; + } +}; diff --git a/solutions/444. Sequence Reconstruction/444.java b/solutions/444. Sequence Reconstruction/444.java new file mode 100644 index 00000000000..5886cca8e15 --- /dev/null +++ b/solutions/444. Sequence Reconstruction/444.java @@ -0,0 +1,49 @@ +class Solution { + public boolean sequenceReconstruction(int[] org, List> seqs) { + if (seqs.isEmpty()) + return false; + + final int n = org.length; + List[] graph = new List[n]; + int[] inDegrees = new int[n]; + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + // Build the graph. + for (List seq : seqs) { + if (seq.size() == 1 && seq.get(0) < 1 || seq.get(0) > n) + return false; + for (int i = 0; i + 1 < seq.size(); ++i) { + final int u = seq.get(i); + final int v = seq.get(i + 1); + if (u < 1 || u > n || v < 1 || v > n) + return false; + graph[u - 1].add(v - 1); + ++inDegrees[v - 1]; + } + } + + // Perform topological sorting. + Queue q = IntStream.range(0, n) + .filter(i -> inDegrees[i] == 0) + .boxed() + .collect(Collectors.toCollection(ArrayDeque::new)); + + int i = 0; // org's index + + while (!q.isEmpty()) { + if (q.size() > 1) + return false; + final int u = q.poll(); + if (u != org[i] - 1) + return false; + ++i; + for (final int v : graph[u]) + if (--inDegrees[v] == 0) + q.offer(v); + } + + return i == n; + } +} diff --git a/solutions/444. Sequence Reconstruction/444.py b/solutions/444. Sequence Reconstruction/444.py new file mode 100644 index 00000000000..6e8659617af --- /dev/null +++ b/solutions/444. Sequence Reconstruction/444.py @@ -0,0 +1,36 @@ +class Solution: + def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool: + if not seqs: + return False + + n = len(org) + graph = [[] for _ in range(n)] + inDegrees = [0] * n + + # Build the graph. + for seq in seqs: + if len(seq) == 1 and seq[0] < 1 or seq[0] > n: + return False + for u, v in zip(seq, seq[1:]): + if u < 1 or u > n or v < 1 or v > n: + return False + graph[u - 1].append(v - 1) + inDegrees[v - 1] += 1 + + # Perform topological sorting. + q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) + i = 0 # org's index + + while q: + if len(q) > 1: + return False + u = q.popleft() + if u != org[i] - 1: + return False + i += 1 + for v in graph[u]: + inDegrees[v] -= 1 + if inDegrees[v] == 0: + q.append(v) + + return i == n diff --git a/solutions/445. Add Two Numbers II/445.cpp b/solutions/445. Add Two Numbers II/445.cpp new file mode 100644 index 00000000000..9fa0d5cbe77 --- /dev/null +++ b/solutions/445. Add Two Numbers II/445.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + stack stack1; + stack stack2; + + while (l1) { + stack1.push(l1); + l1 = l1->next; + } + + while (l2) { + stack2.push(l2); + l2 = l2->next; + } + + ListNode* head = nullptr; + int carry = 0; + + while (carry || !stack1.empty() || !stack2.empty()) { + if (!stack1.empty()) + carry += stack1.top()->val, stack1.pop(); + if (!stack2.empty()) + carry += stack2.top()->val, stack2.pop(); + ListNode* node = new ListNode(carry % 10); + node->next = head; + head = node; + carry /= 10; + } + + return head; + } +}; diff --git a/solutions/445. Add Two Numbers II/445.java b/solutions/445. Add Two Numbers II/445.java new file mode 100644 index 00000000000..5578819019f --- /dev/null +++ b/solutions/445. Add Two Numbers II/445.java @@ -0,0 +1,32 @@ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + Deque stack1 = new ArrayDeque<>(); + Deque stack2 = new ArrayDeque<>(); + + while (l1 != null) { + stack1.push(l1); + l1 = l1.next; + } + + while (l2 != null) { + stack2.push(l2); + l2 = l2.next; + } + + ListNode head = null; + int carry = 0; + + while (carry > 0 || !stack1.isEmpty() || !stack2.isEmpty()) { + if (!stack1.isEmpty()) + carry += stack1.pop().val; + if (!stack2.isEmpty()) + carry += stack2.pop().val; + ListNode node = new ListNode(carry % 10); + node.next = head; + head = node; + carry /= 10; + } + + return head; + } +} diff --git a/solutions/445. Add Two Numbers II/445.py b/solutions/445. Add Two Numbers II/445.py new file mode 100644 index 00000000000..d8b714d4c09 --- /dev/null +++ b/solutions/445. Add Two Numbers II/445.py @@ -0,0 +1,27 @@ +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + stack1 = [] + stack2 = [] + + while l1: + stack1.append(l1) + l1 = l1.next + + while l2: + stack2.append(l2) + l2 = l2.next + + head = None + carry = 0 + + while carry or stack1 or stack2: + if stack1: + carry += stack1.pop().val + if stack2: + carry += stack2.pop().val + node = ListNode(carry % 10) + node.next = head + head = node + carry //= 10 + + return head diff --git a/solutions/446. Arithmetic Slices II - Subsequence/446.cpp b/solutions/446. Arithmetic Slices II - Subsequence/446.cpp new file mode 100644 index 00000000000..41059b13734 --- /dev/null +++ b/solutions/446. Arithmetic Slices II - Subsequence/446.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int numberOfArithmeticSlices(vector& nums) { + const int n = nums.size(); + int ans = 0; + // dp[i][j] := the number of subsequences end in nums[j] nums[i] + vector> dp(n, vector(n)); + unordered_map> numToIndices; + + for (int i = 0; i < n; ++i) + numToIndices[nums[i]].push_back(i); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < i; ++j) { + const long target = nums[j] * 2L - nums[i]; + if (const auto it = numToIndices.find(target); + it != numToIndices.cend()) + for (const int k : it->second) + if (k < j) + dp[i][j] += (dp[j][k] + 1); + ans += dp[i][j]; + } + + return ans; + } +}; diff --git a/solutions/446. Arithmetic Slices II - Subsequence/446.java b/solutions/446. Arithmetic Slices II - Subsequence/446.java new file mode 100644 index 00000000000..919a5ef9a97 --- /dev/null +++ b/solutions/446. Arithmetic Slices II - Subsequence/446.java @@ -0,0 +1,26 @@ +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + final int n = nums.length; + int ans = 0; + // dp[i][j] := the number of subsequences end in nums[j] nums[i] + int[][] dp = new int[n][n]; + Map> numToIndices = new HashMap<>(); + + for (int i = 0; i < n; ++i) { + numToIndices.putIfAbsent((long) nums[i], new ArrayList<>()); + numToIndices.get((long) nums[i]).add(i); + } + + for (int i = 0; i < n; ++i) + for (int j = 0; j < i; ++j) { + final long target = nums[j] * 2L - nums[i]; + if (numToIndices.containsKey(target)) + for (final int k : numToIndices.get(target)) + if (k < j) + dp[i][j] += (dp[j][k] + 1); + ans += dp[i][j]; + } + + return ans; + } +} diff --git a/solutions/447. Number of Boomerangs/447.cpp b/solutions/447. Number of Boomerangs/447.cpp new file mode 100644 index 00000000000..4c1fb119a37 --- /dev/null +++ b/solutions/447. Number of Boomerangs/447.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int numberOfBoomerangs(vector>& points) { + int ans = 0; + + for (const vector& p : points) { + unordered_map distCount; + for (const vector& q : points) { + const int dist = getDist(p, q); + ++distCount[dist]; + } + for (const auto& [_, freq] : distCount) + ans += freq * (freq - 1); // C(freq, 2) + } + + return ans; + } + + private: + int getDist(const vector& p, const vector& q) { + return pow(p[0] - q[0], 2) + pow(p[1] - q[1], 2); + } +}; diff --git a/solutions/447. Number of Boomerangs/447.java b/solutions/447. Number of Boomerangs/447.java new file mode 100644 index 00000000000..0dc52309c2e --- /dev/null +++ b/solutions/447. Number of Boomerangs/447.java @@ -0,0 +1,21 @@ +class Solution { + public int numberOfBoomerangs(int[][] points) { + int ans = 0; + + for (int[] p : points) { + Map distCount = new HashMap<>(); + for (int[] q : points) { + final int dist = (int) getDist(p, q); + distCount.merge(dist, 1, Integer::sum); + } + for (final int freq : distCount.values()) + ans += freq * (freq - 1); // C(freq, 2) + } + + return ans; + } + + private double getDist(int[] p, int[] q) { + return Math.pow(p[0] - q[0], 2) + Math.pow(p[1] - q[1], 2); + } +} diff --git a/solutions/447. Number of Boomerangs/447.py b/solutions/447. Number of Boomerangs/447.py new file mode 100644 index 00000000000..1173478aa84 --- /dev/null +++ b/solutions/447. Number of Boomerangs/447.py @@ -0,0 +1,11 @@ +class Solution: + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + ans = 0 + + for x1, y1 in points: + count = collections.Counter() + for x2, y2 in points: + ans += 2 * count[(x1 - x2)**2 + (y1 - y2)**2] + count[(x1 - x2)**2 + (y1 - y2)**2] += 1 + + return ans diff --git a/solutions/448. Find All Numbers Disappeared in an Array/448.cpp b/solutions/448. Find All Numbers Disappeared in an Array/448.cpp new file mode 100644 index 00000000000..1153b168f3e --- /dev/null +++ b/solutions/448. Find All Numbers Disappeared in an Array/448.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector findDisappearedNumbers(vector& nums) { + vector ans; + + for (const int num : nums) { + const int index = abs(num) - 1; + nums[index] = -abs(nums[index]); + } + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] > 0) + ans.push_back(i + 1); + + return ans; + } +}; diff --git a/solutions/448. Find All Numbers Disappeared in an Array/448.java b/solutions/448. Find All Numbers Disappeared in an Array/448.java new file mode 100644 index 00000000000..2d4b2630018 --- /dev/null +++ b/solutions/448. Find All Numbers Disappeared in an Array/448.java @@ -0,0 +1,16 @@ +class Solution { + public List findDisappearedNumbers(int[] nums) { + List ans = new ArrayList<>(); + + for (final int num : nums) { + final int index = Math.abs(num) - 1; + nums[index] = -Math.abs(nums[index]); + } + + for (int i = 0; i < nums.length; ++i) + if (nums[i] > 0) + ans.add(i + 1); + + return ans; + } +} diff --git a/solutions/448. Find All Numbers Disappeared in an Array/448.py b/solutions/448. Find All Numbers Disappeared in an Array/448.py new file mode 100644 index 00000000000..355905aa44f --- /dev/null +++ b/solutions/448. Find All Numbers Disappeared in an Array/448.py @@ -0,0 +1,7 @@ +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + for num in nums: + index = abs(num) - 1 + nums[index] = -abs(nums[index]) + + return [i + 1 for i, num in enumerate(nums) if num > 0] diff --git a/solutions/449. Serialize and Deserialize BST/449.cpp b/solutions/449. Serialize and Deserialize BST/449.cpp new file mode 100644 index 00000000000..ed7bcc6499d --- /dev/null +++ b/solutions/449. Serialize and Deserialize BST/449.cpp @@ -0,0 +1,50 @@ +class Codec { + public: + string serialize(TreeNode* root) { + if (root == nullptr) + return ""; + + string s; + + serialize(root, s); + return s; + } + + TreeNode* deserialize(string data) { + if (data.empty()) + return nullptr; + + istringstream iss(data); + queue q; + + for (string s; iss >> s;) + q.push(stoi(s)); + + return deserialize(INT_MIN, INT_MAX, q); + } + + private: + void serialize(TreeNode* root, string& s) { + if (root == nullptr) + return; + + s += to_string(root->val) + " "; + serialize(root->left, s); + serialize(root->right, s); + } + + TreeNode* deserialize(int min, int max, queue& q) { + if (q.empty()) + return nullptr; + + const int val = q.front(); + if (val < min || val > max) + return nullptr; + + q.pop(); + TreeNode* root = new TreeNode(val); + root->left = deserialize(min, val, q); + root->right = deserialize(val, max, q); + return root; + } +}; diff --git a/solutions/449. Serialize and Deserialize BST/449.java b/solutions/449. Serialize and Deserialize BST/449.java new file mode 100644 index 00000000000..b6c50b580ed --- /dev/null +++ b/solutions/449. Serialize and Deserialize BST/449.java @@ -0,0 +1,50 @@ +public class Codec { + // Encodes a tree to a single string. + public String serialize(TreeNode root) { + if (root == null) + return ""; + + StringBuilder sb = new StringBuilder(); + + serialize(root, sb); + return sb.toString(); + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + if (data.isEmpty()) + return null; + + final String[] vals = data.split(" "); + Queue q = new ArrayDeque<>(); + + for (final String val : vals) + q.offer(Integer.parseInt(val)); + + return deserialize(Integer.MIN_VALUE, Integer.MAX_VALUE, q); + } + + private void serialize(TreeNode root, StringBuilder sb) { + if (root == null) + return; + + sb.append(root.val).append(" "); + serialize(root.left, sb); + serialize(root.right, sb); + } + + private TreeNode deserialize(int mn, int mx, Queue q) { + if (q.isEmpty()) + return null; + + final int val = q.peek(); + if (val < mn || val > mx) + return null; + + q.poll(); + TreeNode root = new TreeNode(val); + root.left = deserialize(mn, val, q); + root.right = deserialize(val, mx, q); + return root; + } +} diff --git a/solutions/45. Jump Game II/45.cpp b/solutions/45. Jump Game II/45.cpp new file mode 100644 index 00000000000..4d6d7a5cf37 --- /dev/null +++ b/solutions/45. Jump Game II/45.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int jump(vector& nums) { + int ans = 0; + int end = 0; + int farthest = 0; + + // Start an implicit BFS. + for (int i = 0; i < nums.size() - 1; ++i) { + farthest = max(farthest, i + nums[i]); + if (farthest >= nums.size() - 1) { + ++ans; + break; + } + if (i == end) { // Visited all the items on the current level. + ++ans; // Increment the level. + end = farthest; // Make the queue size for the next level. + } + } + + return ans; + } +}; diff --git a/solutions/45. Jump Game II/45.java b/solutions/45. Jump Game II/45.java new file mode 100644 index 00000000000..aa97cb2656b --- /dev/null +++ b/solutions/45. Jump Game II/45.java @@ -0,0 +1,22 @@ +class Solution { + public int jump(int[] nums) { + int ans = 0; + int end = 0; + int farthest = 0; + + // Start an implicit BFS. + for (int i = 0; i < nums.length - 1; ++i) { + farthest = Math.max(farthest, i + nums[i]); + if (farthest >= nums.length - 1) { + ++ans; + break; + } + if (i == end) { // Visited all the items on the current level. + ++ans; // Increment the level. + end = farthest; // Make the queue size for the next level. + } + } + + return ans; + } +} diff --git a/solutions/45. Jump Game II/45.py b/solutions/45. Jump Game II/45.py new file mode 100644 index 00000000000..7f6f68158d6 --- /dev/null +++ b/solutions/45. Jump Game II/45.py @@ -0,0 +1,17 @@ +class Solution: + def jump(self, nums: List[int]) -> int: + ans = 0 + end = 0 + farthest = 0 + + # Start an implicit BFS. + for i in range(len(nums) - 1): + farthest = max(farthest, i + nums[i]) + if farthest >= len(nums) - 1: + ans += 1 + break + if i == end: # Visited all the items on the current level. + ans += 1 # Increment the level. + end = farthest # Make the queue size for the next level. + + return ans diff --git a/solutions/450. Delete Node in a BST/450.cpp b/solutions/450. Delete Node in a BST/450.cpp new file mode 100644 index 00000000000..9c7454767c8 --- /dev/null +++ b/solutions/450. Delete Node in a BST/450.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + TreeNode* deleteNode(TreeNode* root, int key) { + if (root == nullptr) + return nullptr; + if (root->val == key) { + if (root->left == nullptr) + return root->right; + if (root->right == nullptr) + return root->left; + TreeNode* minNode = getMin(root->right); + root->right = deleteNode(root->right, minNode->val); + minNode->left = root->left; + minNode->right = root->right; + root = minNode; + } else if (root->val < key) { + root->right = deleteNode(root->right, key); + } else { // root->val > key + root->left = deleteNode(root->left, key); + } + return root; + } + + private: + TreeNode* getMin(TreeNode* node) { + while (node->left) + node = node->left; + return node; + } +}; diff --git a/solutions/450. Delete Node in a BST/450.java b/solutions/450. Delete Node in a BST/450.java new file mode 100644 index 00000000000..8e94ac48954 --- /dev/null +++ b/solutions/450. Delete Node in a BST/450.java @@ -0,0 +1,28 @@ +class Solution { + public TreeNode deleteNode(TreeNode root, int key) { + if (root == null) + return null; + if (root.val == key) { + if (root.left == null) + return root.right; + if (root.right == null) + return root.left; + TreeNode minNode = getMin(root.right); + root.right = deleteNode(root.right, minNode.val); + minNode.left = root.left; + minNode.right = root.right; + root = minNode; + } else if (root.val < key) { + root.right = deleteNode(root.right, key); + } else { // root.val > key + root.left = deleteNode(root.left, key); + } + return root; + } + + private TreeNode getMin(TreeNode node) { + while (node.left != null) + node = node.left; + return node; + } +} diff --git a/solutions/450. Delete Node in a BST/450.py b/solutions/450. Delete Node in a BST/450.py new file mode 100644 index 00000000000..6b5101110a6 --- /dev/null +++ b/solutions/450. Delete Node in a BST/450.py @@ -0,0 +1,24 @@ +class Solution: + def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: + if not root: + return None + if root.val == key: + if not root.left: + return root.right + if not root.right: + return root.left + minNode = self._getMin(root.right) + root.right = self.deleteNode(root.right, minNode.val) + minNode.left = root.left + minNode.right = root.right + root = minNode + elif root.val < key: + root.right = self.deleteNode(root.right, key) + else: # root.val > key + root.left = self.deleteNode(root.left, key) + return root + + def _getMin(self, node: Optional[TreeNode]) -> Optional[TreeNode]: + while node.left: + node = node.left + return node diff --git a/solutions/451. Sort Characters By Frequency/451.cpp b/solutions/451. Sort Characters By Frequency/451.cpp new file mode 100644 index 00000000000..16454dd4275 --- /dev/null +++ b/solutions/451. Sort Characters By Frequency/451.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string frequencySort(string s) { + const int n = s.length(); + string ans; + vector count(128); + // buckets[i] := characters that appear i times in s + vector> buckets(n + 1); + + for (const char c : s) + ++count[c]; + + for (int i = 0; i < 128; ++i) { + const int freq = count[i]; + if (freq > 0) + buckets[freq].push_back((char)i); + } + + for (int freq = n; freq > 0; --freq) + for (const char c : buckets[freq]) + ans += string(freq, c); + + return ans; + } +}; diff --git a/solutions/451. Sort Characters By Frequency/451.java b/solutions/451. Sort Characters By Frequency/451.java new file mode 100644 index 00000000000..1e487c4089c --- /dev/null +++ b/solutions/451. Sort Characters By Frequency/451.java @@ -0,0 +1,29 @@ +class Solution { + public String frequencySort(String s) { + final int n = s.length(); + StringBuilder sb = new StringBuilder(); + int[] count = new int[128]; + // buckets[i] := characters that appear i times in s + List[] buckets = new List[n + 1]; + + for (final char c : s.toCharArray()) + ++count[c]; + + for (int i = 0; i < 128; ++i) { + final int freq = count[i]; + if (freq > 0) { + if (buckets[freq] == null) + buckets[freq] = new ArrayList<>(); + buckets[freq].add((char) i); + } + } + + for (int freq = n; freq > 0; --freq) + if (buckets[freq] != null) + for (final char c : buckets[freq]) + for (int i = 0; i < freq; ++i) + sb.append(c); + + return sb.toString(); + } +} diff --git a/solutions/451. Sort Characters By Frequency/451.py b/solutions/451. Sort Characters By Frequency/451.py new file mode 100644 index 00000000000..5c67c54156c --- /dev/null +++ b/solutions/451. Sort Characters By Frequency/451.py @@ -0,0 +1,13 @@ +class Solution: + def frequencySort(self, s: str) -> str: + ans = [] + buckets = [[] for _ in range(len(s) + 1)] + + for c, freq in collections.Counter(s).items(): + buckets[freq].append(c) + + for freq in reversed(range(len(buckets))): + for c in buckets[freq]: + ans.append(c * freq) + + return ''.join(ans) diff --git a/solutions/452. Minimum Number of Arrows to Burst Balloons/452.cpp b/solutions/452. Minimum Number of Arrows to Burst Balloons/452.cpp new file mode 100644 index 00000000000..7ad5153a0f4 --- /dev/null +++ b/solutions/452. Minimum Number of Arrows to Burst Balloons/452.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int findMinArrowShots(vector>& points) { + ranges::sort(points, + [](const auto& a, const auto& b) { return a[1] < b[1]; }); + + int ans = 1; + int arrowX = points[0][1]; + + for (int i = 1; i < points.size(); ++i) + if (points[i][0] > arrowX) { + arrowX = points[i][1]; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/452. Minimum Number of Arrows to Burst Balloons/452.java b/solutions/452. Minimum Number of Arrows to Burst Balloons/452.java new file mode 100644 index 00000000000..c99fb7a1d6a --- /dev/null +++ b/solutions/452. Minimum Number of Arrows to Burst Balloons/452.java @@ -0,0 +1,16 @@ +class Solution { + public int findMinArrowShots(int[][] points) { + Arrays.sort(points, (a, b) -> a[1] - b[1]); + + int ans = 1; + int arrowX = points[0][1]; + + for (int i = 1; i < points.length; ++i) + if (points[i][0] > arrowX) { + arrowX = points[i][1]; + ++ans; + } + + return ans; + } +} diff --git a/solutions/452. Minimum Number of Arrows to Burst Balloons/452.py b/solutions/452. Minimum Number of Arrows to Burst Balloons/452.py new file mode 100644 index 00000000000..fc9986c8e18 --- /dev/null +++ b/solutions/452. Minimum Number of Arrows to Burst Balloons/452.py @@ -0,0 +1,11 @@ +class Solution: + def findMinArrowShots(self, points: List[List[int]]) -> int: + ans = 0 + arrowX = -math.inf + + for point in sorted(points, key=lambda x: x[1]): + if point[0] > arrowX: + ans += 1 + arrowX = point[1] + + return ans diff --git a/solutions/453. Minimum Moves to Equal Array Elements/453.cpp b/solutions/453. Minimum Moves to Equal Array Elements/453.cpp new file mode 100644 index 00000000000..b6e29546404 --- /dev/null +++ b/solutions/453. Minimum Moves to Equal Array Elements/453.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int minMoves(vector& nums) { + const int mn = ranges::min(nums); + return accumulate(nums.begin(), nums.end(), 0, [&](int subtotal, int num) { + return subtotal + (num - mn); + }); + } +}; diff --git a/solutions/453. Minimum Moves to Equal Array Elements/453.java b/solutions/453. Minimum Moves to Equal Array Elements/453.java new file mode 100644 index 00000000000..8c2ad3f531a --- /dev/null +++ b/solutions/453. Minimum Moves to Equal Array Elements/453.java @@ -0,0 +1,7 @@ +class Solution { + public int minMoves(int[] nums) { + final int sum = Arrays.stream(nums).sum(); + final int mn = Arrays.stream(nums).min().getAsInt(); + return sum - mn * nums.length; + } +} diff --git a/solutions/453. Minimum Moves to Equal Array Elements/453.py b/solutions/453. Minimum Moves to Equal Array Elements/453.py new file mode 100644 index 00000000000..5e0fae69dc7 --- /dev/null +++ b/solutions/453. Minimum Moves to Equal Array Elements/453.py @@ -0,0 +1,4 @@ +class Solution: + def minMoves(self, nums: List[int]) -> int: + mn = min(nums) + return sum(num - mn for num in nums) diff --git a/solutions/454. 4Sum II/454.cpp b/solutions/454. 4Sum II/454.cpp new file mode 100644 index 00000000000..d5fa30e2e78 --- /dev/null +++ b/solutions/454. 4Sum II/454.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int fourSumCount(vector& nums1, vector& nums2, vector& nums3, + vector& nums4) { + int ans = 0; + unordered_map count; + + for (const int a : nums1) + for (const int b : nums2) + ++count[a + b]; + + for (const int c : nums3) + for (const int d : nums4) + if (const auto it = count.find(-c - d); it != count.cend()) + ans += it->second; + + return ans; + } +}; diff --git a/solutions/454. 4Sum II/454.java b/solutions/454. 4Sum II/454.java new file mode 100644 index 00000000000..d677a4efb53 --- /dev/null +++ b/solutions/454. 4Sum II/454.java @@ -0,0 +1,17 @@ +class Solution { + public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { + int ans = 0; + Map count = new HashMap<>(); + + for (final int a : nums1) + for (final int b : nums2) + count.merge(a + b, 1, Integer::sum); + + for (final int c : nums3) + for (final int d : nums4) + if (count.containsKey(-c - d)) + ans += count.get(-c - d); + + return ans; + } +} diff --git a/solutions/454. 4Sum II/454.py b/solutions/454. 4Sum II/454.py new file mode 100644 index 00000000000..63e6c9e2612 --- /dev/null +++ b/solutions/454. 4Sum II/454.py @@ -0,0 +1,5 @@ +class Solution: + def fourSumCount(self, nums1: List[int], nums2: List[int], + nums3: List[int], nums4: List[int]) -> int: + count = collections.Counter(a + b for a in nums1 for b in nums2) + return sum(count[-c - d] for c in nums3 for d in nums4) diff --git a/solutions/455. Assign Cookies/455.cpp b/solutions/455. Assign Cookies/455.cpp new file mode 100644 index 00000000000..0931001edf7 --- /dev/null +++ b/solutions/455. Assign Cookies/455.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int findContentChildren(vector& g, vector& s) { + ranges::sort(g); + ranges::sort(s); + + int i = 0; + for (int j = 0; j < s.size() && i < g.size(); ++j) + if (g[i] <= s[j]) + ++i; + + return i; + } +}; diff --git a/solutions/455. Assign Cookies/455.java b/solutions/455. Assign Cookies/455.java new file mode 100644 index 00000000000..935d520e1f8 --- /dev/null +++ b/solutions/455. Assign Cookies/455.java @@ -0,0 +1,13 @@ +class Solution { + public int findContentChildren(int[] g, int[] s) { + Arrays.sort(g); + Arrays.sort(s); + + int i = 0; + for (int j = 0; i < g.length && j < s.length; ++j) + if (g[i] <= s[j]) + ++i; + + return i; + } +} diff --git a/solutions/456. 132 Pattern/456.cpp b/solutions/456. 132 Pattern/456.cpp new file mode 100644 index 00000000000..d4b62d84123 --- /dev/null +++ b/solutions/456. 132 Pattern/456.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool find132pattern(vector& nums) { + stack stack; // a decreasing stack + int ak = INT_MIN; // We want to find a seq ai < ak < aj. + + for (int i = nums.size() - 1; i >= 0; --i) { + // If ai < ak, we're done because ai must < aj. + if (nums[i] < ak) + return true; + while (!stack.empty() && stack.top() < nums[i]) + ak = stack.top(), stack.pop(); + stack.push(nums[i]); // `nums[i]` is a candidate of aj. + } + + return false; + } +}; diff --git a/solutions/456. 132 Pattern/456.java b/solutions/456. 132 Pattern/456.java new file mode 100644 index 00000000000..d2963924b8e --- /dev/null +++ b/solutions/456. 132 Pattern/456.java @@ -0,0 +1,17 @@ +class Solution { + public boolean find132pattern(int[] nums) { + Deque stack = new ArrayDeque<>(); // a decreasing stack + int ak = Integer.MIN_VALUE; // We want to find a seq ai < ak < aj. + + for (int i = nums.length - 1; i >= 0; --i) { + // ai < ak, we're done because ai must also smaller than aj + if (nums[i] < ak) + return true; + while (!stack.isEmpty() && stack.peek() < nums[i]) + ak = stack.pop(); + stack.push(nums[i]); // `nums[i]` is a candidate of aj. + } + + return false; + } +} diff --git a/solutions/457. Circular Array Loop/457.cpp b/solutions/457. Circular Array Loop/457.cpp new file mode 100644 index 00000000000..72699f247f8 --- /dev/null +++ b/solutions/457. Circular Array Loop/457.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + bool circularArrayLoop(vector& nums) { + const int n = nums.size(); + if (n < 2) + return false; + + auto advance = [&](int i) { + const int val = (i + nums[i]) % n; + return i + nums[i] >= 0 ? val : n + val; + }; + + for (int i = 0; i < n; ++i) { + if (nums[i] == 0) + continue; + int slow = i; + int fast = advance(slow); + while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(fast)] > 0) { + if (slow == fast) { + if (slow == advance(slow)) + break; + return true; + } + slow = advance(slow); + fast = advance(advance(fast)); + } + + slow = i; + const int sign = nums[i]; + while (sign * nums[slow] > 0) { + const int next = advance(slow); + nums[slow] = 0; + slow = next; + } + } + + return false; + } +}; diff --git a/solutions/457. Circular Array Loop/457.java b/solutions/457. Circular Array Loop/457.java new file mode 100644 index 00000000000..10eb3a6a9ab --- /dev/null +++ b/solutions/457. Circular Array Loop/457.java @@ -0,0 +1,38 @@ +class Solution { + public boolean circularArrayLoop(int[] nums) { + if (nums.length < 2) + return false; + + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == 0) + continue; + int slow = i; + int fast = advance(nums, slow); + while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(nums, fast)] > 0) { + if (slow == fast) { + if (slow == advance(nums, slow)) + break; + return true; + } + slow = advance(nums, slow); + fast = advance(nums, advance(nums, fast)); + } + + slow = i; + final int sign = nums[i]; + while (sign * nums[slow] > 0) { + final int next = advance(nums, slow); + nums[slow] = 0; + slow = next; + } + } + + return false; + } + + private int advance(int[] nums, int i) { + final int n = nums.length; + final int val = (i + nums[i]) % n; + return i + nums[i] >= 0 ? val : n + val; + } +} diff --git a/solutions/457. Circular Array Loop/457.py b/solutions/457. Circular Array Loop/457.py new file mode 100644 index 00000000000..7804046d1c2 --- /dev/null +++ b/solutions/457. Circular Array Loop/457.py @@ -0,0 +1,30 @@ +class Solution: + def circularArrayLoop(self, nums: List[int]) -> bool: + def advance(i: int) -> int: + return (i + nums[i]) % len(nums) + + if len(nums) < 2: + return False + + for i, num in enumerate(nums): + if num == 0: + continue + + slow = i + fast = advance(slow) + while num * nums[fast] > 0 and num * nums[advance(fast)] > 0: + if slow == fast: + if slow == advance(slow): + break + return True + slow = advance(slow) + fast = advance(advance(fast)) + + slow = i + sign = num + while sign * nums[slow] > 0: + next = advance(slow) + nums[slow] = 0 + slow = next + + return False diff --git a/solutions/458. Poor Pigs/458.cpp b/solutions/458. Poor Pigs/458.cpp new file mode 100644 index 00000000000..95c4eedae5a --- /dev/null +++ b/solutions/458. Poor Pigs/458.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int poorPigs(int buckets, int minutesToDie, int minutesToTest) { + const int base = minutesToTest / minutesToDie + 1; + int ans = 0; + for (int x = 1; x < buckets; x *= base) + ++ans; + return ans; + } +}; diff --git a/solutions/458. Poor Pigs/458.java b/solutions/458. Poor Pigs/458.java new file mode 100644 index 00000000000..84c07929068 --- /dev/null +++ b/solutions/458. Poor Pigs/458.java @@ -0,0 +1,9 @@ +class Solution { + public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { + final int base = minutesToTest / minutesToDie + 1; + int ans = 0; + for (int x = 1; x < buckets; x *= base) + ++ans; + return ans; + } +} diff --git a/solutions/458. Poor Pigs/458.py b/solutions/458. Poor Pigs/458.py new file mode 100644 index 00000000000..7b6b374affa --- /dev/null +++ b/solutions/458. Poor Pigs/458.py @@ -0,0 +1,9 @@ +class Solution: + def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int: + base = minutesToTest // minutesToDie + 1 + ans = 0 + x = 1 + while x < buckets: + ans += 1 + x *= base + return ans diff --git a/solutions/459. Repeated Substring Pattern/459.cpp b/solutions/459. Repeated Substring Pattern/459.cpp new file mode 100644 index 00000000000..f377cbeea2c --- /dev/null +++ b/solutions/459. Repeated Substring Pattern/459.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + bool repeatedSubstringPattern(string s) { + const string ss = s + s; + return ss.substr(1, ss.length() - 2).find(s) != string::npos; + } +}; diff --git a/solutions/459. Repeated Substring Pattern/459.java b/solutions/459. Repeated Substring Pattern/459.java new file mode 100644 index 00000000000..e4da62c3b63 --- /dev/null +++ b/solutions/459. Repeated Substring Pattern/459.java @@ -0,0 +1,6 @@ +class Solution { + public boolean repeatedSubstringPattern(String s) { + final String ss = s + s; + return ss.substring(1, ss.length() - 1).contains(s); + } +} diff --git a/solutions/459. Repeated Substring Pattern/459.py b/solutions/459. Repeated Substring Pattern/459.py new file mode 100644 index 00000000000..6557f128392 --- /dev/null +++ b/solutions/459. Repeated Substring Pattern/459.py @@ -0,0 +1,3 @@ +class Solution: + def repeatedSubstringPattern(self, s: str) -> bool: + return s in (s + s)[1:-1] diff --git a/solutions/46. Permutations/46.cpp b/solutions/46. Permutations/46.cpp new file mode 100644 index 00000000000..2abd2c2db24 --- /dev/null +++ b/solutions/46. Permutations/46.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector> permute(vector& nums) { + vector> ans; + + dfs(nums, vector(nums.size()), {}, ans); + return ans; + } + + private: + void dfs(const vector& nums, vector&& used, vector&& path, + vector>& ans) { + if (path.size() == nums.size()) { + ans.push_back(path); + return; + } + + for (int i = 0; i < nums.size(); ++i) { + if (used[i]) + continue; + used[i] = true; + path.push_back(nums[i]); + dfs(nums, move(used), move(path), ans); + path.pop_back(); + used[i] = false; + } + } +}; diff --git a/solutions/46. Permutations/46.java b/solutions/46. Permutations/46.java new file mode 100644 index 00000000000..bb0995818fc --- /dev/null +++ b/solutions/46. Permutations/46.java @@ -0,0 +1,25 @@ +class Solution { + public List> permute(int[] nums) { + List> ans = new ArrayList<>(); + + dfs(nums, new boolean[nums.length], new ArrayList<>(), ans); + return ans; + } + + private void dfs(int[] nums, boolean[] used, List path, List> ans) { + if (path.size() == nums.length) { + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = 0; i < nums.length; ++i) { + if (used[i]) + continue; + used[i] = true; + path.add(nums[i]); + dfs(nums, used, path, ans); + path.remove(path.size() - 1); + used[i] = false; + } + } +} diff --git a/solutions/46. Permutations/46.py b/solutions/46. Permutations/46.py new file mode 100644 index 00000000000..cd20ef25347 --- /dev/null +++ b/solutions/46. Permutations/46.py @@ -0,0 +1,21 @@ +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + ans = [] + used = [False] * len(nums) + + def dfs(path: List[int]) -> None: + if len(path) == len(nums): + ans.append(path.copy()) + return + + for i, num in enumerate(nums): + if used[i]: + continue + used[i] = True + path.append(num) + dfs(path) + path.pop() + used[i] = False + + dfs([]) + return ans diff --git a/solutions/460. LFU Cache/460.cpp b/solutions/460. LFU Cache/460.cpp new file mode 100644 index 00000000000..27a486e6e79 --- /dev/null +++ b/solutions/460. LFU Cache/460.cpp @@ -0,0 +1,68 @@ +struct Node { + int key; + int value; + int freq; + list::const_iterator it; +}; + +class LFUCache { + public: + LFUCache(int capacity) : capacity(capacity), minFreq(0) {} + + int get(int key) { + const auto it = keyToNode.find(key); + if (it == keyToNode.cend()) + return -1; + + Node& node = it->second; + touch(node); + return node.value; + } + + void put(int key, int value) { + if (capacity == 0) + return; + if (const auto it = keyToNode.find(key); it != keyToNode.cend()) { + Node& node = it->second; + node.value = value; + touch(node); + return; + } + + if (keyToNode.size() == capacity) { + // Evict an LRU key from `minFreq` list. + const int keyToEvict = freqToList[minFreq].back(); + freqToList[minFreq].pop_back(); + keyToNode.erase(keyToEvict); + } + + minFreq = 1; + freqToList[1].push_front(key); + keyToNode[key] = {key, value, 1, freqToList[1].cbegin()}; + } + + private: + int capacity; + int minFreq; + unordered_map keyToNode; + unordered_map> freqToList; + + void touch(Node& node) { + // Update the node's frequency. + const int prevFreq = node.freq; + const int newFreq = ++node.freq; + + // Remove the iterator from `prevFreq`'s list + freqToList[prevFreq].erase(node.it); + if (freqToList[prevFreq].empty()) { + freqToList.erase(prevFreq); + // Update `minFreq` if needed. + if (prevFreq == minFreq) + ++minFreq; + } + + // Insert the key to the front of `newFreq`'s list. + freqToList[newFreq].push_front(node.key); + node.it = freqToList[newFreq].cbegin(); + } +}; diff --git a/solutions/460. LFU Cache/460.java b/solutions/460. LFU Cache/460.java new file mode 100644 index 00000000000..8ecaf120a0c --- /dev/null +++ b/solutions/460. LFU Cache/460.java @@ -0,0 +1,55 @@ +class LFUCache { + public LFUCache(int capacity) { + this.capacity = capacity; + } + + public int get(int key) { + if (!keyToVal.containsKey(key)) + return -1; + + final int freq = keyToFreq.get(key); + freqToLRUKeys.get(freq).remove(key); + if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) { + freqToLRUKeys.remove(freq); + ++minFreq; + } + + // Increase key's freq by 1 + // Add this key to next freq's list + putFreq(key, freq + 1); + return keyToVal.get(key); + } + + public void put(int key, int value) { + if (capacity == 0) + return; + if (keyToVal.containsKey(key)) { + keyToVal.put(key, value); + get(key); // Update key's count + return; + } + + if (keyToVal.size() == capacity) { + // Evict an LRU key from `minFreq` list. + final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next(); + freqToLRUKeys.get(minFreq).remove(keyToEvict); + keyToVal.remove(keyToEvict); + } + + minFreq = 1; + putFreq(key, minFreq); // Add new key and freq + keyToVal.put(key, value); // Add new key and value + } + + private int capacity; + private int minFreq = 0; + private Map keyToVal = new HashMap<>(); + private Map keyToFreq = new HashMap<>(); + private Map> freqToLRUKeys = new HashMap<>(); + + private void putFreq(int key, int freq) { + keyToFreq.put(key, freq); + freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>()); + freqToLRUKeys.get(freq).add(key); + } +} diff --git a/solutions/461. Hamming Distance/461.cpp b/solutions/461. Hamming Distance/461.cpp new file mode 100644 index 00000000000..d1e8e495594 --- /dev/null +++ b/solutions/461. Hamming Distance/461.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int hammingDistance(int x, int y) { + int ans = 0; + + while (x || y) { + ans += (x & 1) ^ (y & 1); + x >>= 1; + y >>= 1; + } + + return ans; + } +}; diff --git a/solutions/461. Hamming Distance/461.java b/solutions/461. Hamming Distance/461.java new file mode 100644 index 00000000000..b03d3a0ad34 --- /dev/null +++ b/solutions/461. Hamming Distance/461.java @@ -0,0 +1,13 @@ +class Solution { + public int hammingDistance(int x, int y) { + int ans = 0; + + while (x > 0 || y > 0) { + ans += (x & 1) ^ (y & 1); + x >>= 1; + y >>= 1; + } + + return ans; + } +} diff --git a/solutions/462. Minimum Moves to Equal Array Elements II/462.cpp b/solutions/462. Minimum Moves to Equal Array Elements II/462.cpp new file mode 100644 index 00000000000..53127eed91e --- /dev/null +++ b/solutions/462. Minimum Moves to Equal Array Elements II/462.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int minMoves2(vector& nums) { + const int n = nums.size(); + nth_element(nums.begin(), nums.begin() + n / 2, nums.end()); + const int median = nums[n / 2]; + return accumulate(nums.begin(), nums.end(), 0, [&](int subtotal, int num) { + return subtotal + abs(num - median); + }); + } +}; diff --git a/solutions/462. Minimum Moves to Equal Array Elements II/462.java b/solutions/462. Minimum Moves to Equal Array Elements II/462.java new file mode 100644 index 00000000000..466c70c0ec2 --- /dev/null +++ b/solutions/462. Minimum Moves to Equal Array Elements II/462.java @@ -0,0 +1,37 @@ +class Solution { + public int minMoves2(int[] nums) { + final int n = nums.length; + final int median = quickSelect(nums, 0, n - 1, (n + 1) / 2); + int ans = 0; + + for (final int num : nums) + ans += Math.abs(num - median); + + return ans; + } + + private int quickSelect(int[] nums, int l, int r, int k) { + final int randIndex = new Random().nextInt(r - l + 1) + l; + swap(nums, randIndex, r); + final int pivot = nums[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (nums[i] <= pivot) + swap(nums, nextSwapped++, i); + swap(nums, nextSwapped, r); + + final int count = nextSwapped - l + 1; + if (count == k) + return nums[nextSwapped]; + if (count > k) + return quickSelect(nums, l, nextSwapped - 1, k); + return quickSelect(nums, nextSwapped + 1, r, k - count); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/462. Minimum Moves to Equal Array Elements II/462.py b/solutions/462. Minimum Moves to Equal Array Elements II/462.py new file mode 100644 index 00000000000..1dbff543cfd --- /dev/null +++ b/solutions/462. Minimum Moves to Equal Array Elements II/462.py @@ -0,0 +1,7 @@ +import statistics + + +class Solution: + def minMoves2(self, nums: List[int]) -> int: + median = int(statistics.median(nums)) + return sum(abs(num - median) for num in nums) diff --git a/solutions/463. Island Perimeter/463.cpp b/solutions/463. Island Perimeter/463.cpp new file mode 100644 index 00000000000..ab20ca0db86 --- /dev/null +++ b/solutions/463. Island Perimeter/463.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int islandPerimeter(vector>& grid) { + int islands = 0; + int neighbors = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j]) { + ++islands; + if (i - 1 >= 0 && grid[i - 1][j]) + ++neighbors; + if (j - 1 >= 0 && grid[i][j - 1]) + ++neighbors; + } + + return islands * 4 - neighbors * 2; + } +}; diff --git a/solutions/463. Island Perimeter/463.java b/solutions/463. Island Perimeter/463.java new file mode 100644 index 00000000000..d6247fbd61a --- /dev/null +++ b/solutions/463. Island Perimeter/463.java @@ -0,0 +1,18 @@ +class Solution { + public int islandPerimeter(int[][] grid) { + int islands = 0; + int neighbors = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 1) { + ++islands; + if (i - 1 >= 0 && grid[i - 1][j] == 1) + ++neighbors; + if (j - 1 >= 0 && grid[i][j - 1] == 1) + ++neighbors; + } + + return islands * 4 - neighbors * 2; + } +} diff --git a/solutions/463. Island Perimeter/463.py b/solutions/463. Island Perimeter/463.py new file mode 100644 index 00000000000..69b2887e664 --- /dev/null +++ b/solutions/463. Island Perimeter/463.py @@ -0,0 +1,18 @@ +class Solution: + def islandPerimeter(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + + islands = 0 + neighbors = 0 + + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + islands += 1 + if i + 1 < m and grid[i + 1][j] == 1: + neighbors += 1 + if j + 1 < n and grid[i][j + 1] == 1: + neighbors += 1 + + return islands * 4 - neighbors * 2 diff --git a/solutions/464. Can I Win/464.cpp b/solutions/464. Can I Win/464.cpp new file mode 100644 index 00000000000..d6d337c7535 --- /dev/null +++ b/solutions/464. Can I Win/464.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + bool canIWin(int maxChoosableInteger, int desiredTotal) { + if (desiredTotal <= 0) + return true; + + const int sum = maxChoosableInteger * (maxChoosableInteger + 1) / 2; + if (sum < desiredTotal) + return false; + + unordered_map mem; + return canIWin(desiredTotal, 0, maxChoosableInteger, mem); + } + + private: + // Returns true if the first player can we, where `used` represents the used + // numbers. + bool canIWin(int total, int used, const int& maxChoosableInteger, + unordered_map& mem) { + if (total <= 0) + return false; + if (const auto it = mem.find(used); it != mem.cend()) + return it->second; + + for (int i = 1; i <= maxChoosableInteger; ++i) { + if (used >> i & 1) // Integer i is used. + continue; + if (!canIWin(total - i, used | 1 << i, maxChoosableInteger, mem)) + return true; + } + + return mem[used] = false; + } +}; diff --git a/solutions/464. Can I Win/464.java b/solutions/464. Can I Win/464.java new file mode 100644 index 00000000000..129d7801a1f --- /dev/null +++ b/solutions/464. Can I Win/464.java @@ -0,0 +1,32 @@ +class Solution { + public boolean canIWin(int maxChoosableInteger, int desiredTotal) { + if (desiredTotal <= 0) + return true; + + final int sum = maxChoosableInteger * (maxChoosableInteger + 1) / 2; + if (sum < desiredTotal) + return false; + + Map mem = new HashMap<>(); + return canIWin(desiredTotal, 0, maxChoosableInteger, mem); + } + + // Returns true if the first player can we, where `used` represents the used + // numbers. + private boolean canIWin(int total, int used, int maxChoosableInteger, Map mem) { + if (total <= 0) + return false; + if (mem.containsKey(used)) + return mem.get(used); + + for (int i = 1; i <= maxChoosableInteger; ++i) { + if ((used >> i & 1) == 1) // Integer i is used. + continue; + if (!canIWin(total - i, used | 1 << i, maxChoosableInteger, mem)) + return true; + } + + mem.put(used, false); + return false; + } +} diff --git a/solutions/465. Optimal Account Balancing/465.cpp b/solutions/465. Optimal Account Balancing/465.cpp new file mode 100644 index 00000000000..a55f8844b97 --- /dev/null +++ b/solutions/465. Optimal Account Balancing/465.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int minTransfers(vector>& transactions) { + vector balance(21); + vector debts; + + for (const vector& t : transactions) { + const int from = t[0]; + const int to = t[1]; + const int amount = t[2]; + balance[from] -= amount; + balance[to] += amount; + } + + for (const int b : balance) + if (b > 0) + debts.push_back(b); + + return dfs(debts, 0); + } + + private: + int dfs(vector& debts, int s) { + while (s < debts.size() && !debts[s]) + ++s; + if (s == debts.size()) + return 0; + + int ans = INT_MAX; + + for (int i = s + 1; i < debts.size(); ++i) + if (debts[i] * debts[s] < 0) { + debts[i] += debts[s]; // `debts[s]` is settled. + ans = min(ans, 1 + dfs(debts, s + 1)); + debts[i] -= debts[s]; // Backtrack. + } + + return ans; + } +}; diff --git a/solutions/465. Optimal Account Balancing/465.java b/solutions/465. Optimal Account Balancing/465.java new file mode 100644 index 00000000000..742d41e147e --- /dev/null +++ b/solutions/465. Optimal Account Balancing/465.java @@ -0,0 +1,38 @@ +class Solution { + public int minTransfers(int[][] transactions) { + int[] balance = new int[21]; + List debts = new ArrayList<>(); + + for (int[] t : transactions) { + final int from = t[0]; + final int to = t[1]; + final int amount = t[2]; + balance[from] -= amount; + balance[to] += amount; + } + + for (final int b : balance) + if (b != 0) + debts.add(b); + + return dfs(debts, 0); + } + + private int dfs(List debts, int s) { + while (s < debts.size() && debts.get(s) == 0) + ++s; + if (s == debts.size()) + return 0; + + int ans = Integer.MAX_VALUE; + + for (int i = s + 1; i < debts.size(); ++i) + if (debts.get(i) * debts.get(s) < 0) { + debts.set(i, debts.get(i) + debts.get(s)); // `debts.get(s)` is settled. + ans = Math.min(ans, 1 + dfs(debts, s + 1)); + debts.set(i, debts.get(i) - debts.get(s)); // Backtrack. + } + + return ans; + } +} diff --git a/solutions/465. Optimal Account Balancing/465.py b/solutions/465. Optimal Account Balancing/465.py new file mode 100644 index 00000000000..ceab5f723fe --- /dev/null +++ b/solutions/465. Optimal Account Balancing/465.py @@ -0,0 +1,27 @@ +class Solution: + def minTransfers(self, transactions: List[List[int]]) -> int: + balance = [0] * 21 + + for u, v, amount in transactions: + balance[u] -= amount + balance[v] += amount + + debts = [b for b in balance if b] + + def dfs(s: int) -> int: + while s < len(debts) and not debts[s]: + s += 1 + if s == len(debts): + return 0 + + ans = math.inf + + for i in range(s + 1, len(debts)): + if debts[i] * debts[s] < 0: + debts[i] += debts[s] # `debts[s]` is settled. + ans = min(ans, 1 + dfs(s + 1)) + debts[i] -= debts[s] # Backtrack. + + return ans + + return dfs(0) diff --git a/solutions/466. Count The Repetitions/466.cpp b/solutions/466. Count The Repetitions/466.cpp new file mode 100644 index 00000000000..3c738cbf496 --- /dev/null +++ b/solutions/466. Count The Repetitions/466.cpp @@ -0,0 +1,35 @@ +struct Record { + int count; + int nextIndex; + Record(int count, int nextIndex) : count(count), nextIndex(nextIndex) {} +}; + +class Solution { + public: + int getMaxRepetitions(string s1, int n1, string s2, int n2) { + // [count(s1 matches s2[i..n)), next index of s2[i..n)] + vector records; + + for (int i = 0; i < s2.length(); ++i) { + int count = 0; + int nextIndex = i; + for (int j = 0; j < s1.length(); ++j) + if (s2[nextIndex] == s1[j]) + if (++nextIndex == s2.length()) { // There's a match. + ++count; + nextIndex = 0; + } + records.emplace_back(count, nextIndex); + } + + int matches = 0; // `s1` matches `s2`. + int index = 0; + + while (n1--) { + matches += records[index].count; + index = records[index].nextIndex; + } + + return matches / n2; // `s1` matches `s2`. + } +}; diff --git a/solutions/466. Count The Repetitions/466.java b/solutions/466. Count The Repetitions/466.java new file mode 100644 index 00000000000..06d3b08f347 --- /dev/null +++ b/solutions/466. Count The Repetitions/466.java @@ -0,0 +1,37 @@ +class Record { + public int count; + public int nextIndex; + public Record(int count, int nextIndex) { + this.count = count; + this.nextIndex = nextIndex; + } +}; + +class Solution { + public int getMaxRepetitions(String s1, int n1, String s2, int n2) { + // [count(s1 matches s2[i..n)), next index of s2[i..n)] + List records = new ArrayList<>(); + + for (int i = 0; i < s2.length(); ++i) { + int count = 0; + int nextIndex = i; + for (int j = 0; j < s1.length(); ++j) + if (s2.charAt(nextIndex) == s1.charAt(j)) + if (++nextIndex == s2.length()) { // There's a match. + ++count; + nextIndex = 0; + } + records.add(new Record(count, nextIndex)); + } + + int matches = 0; // `s1` matches `s2`. + int index = 0; + + while (n1-- > 0) { + matches += records.get(index).count; + index = records.get(index).nextIndex; + } + + return matches / n2; // `s1` matches `s2`. + } +} diff --git a/solutions/467. Unique Substrings in Wraparound String/467.cpp b/solutions/467. Unique Substrings in Wraparound String/467.cpp new file mode 100644 index 00000000000..a065c6ba75d --- /dev/null +++ b/solutions/467. Unique Substrings in Wraparound String/467.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findSubstringInWraproundString(string p) { + int maxLength = 1; + // count[i] := the number of substrings ending in ('a' + i) + vector count(26); + + for (int i = 0; i < p.length(); ++i) { + if (i > 0 && (p[i] - p[i - 1] == 1 || p[i - 1] - p[i] == 25)) + ++maxLength; + else + maxLength = 1; + const int index = p[i] - 'a'; + count[index] = max(count[index], maxLength); + } + + return accumulate(count.begin(), count.end(), 0); + } +}; diff --git a/solutions/467. Unique Substrings in Wraparound String/467.java b/solutions/467. Unique Substrings in Wraparound String/467.java new file mode 100644 index 00000000000..563e075f3c7 --- /dev/null +++ b/solutions/467. Unique Substrings in Wraparound String/467.java @@ -0,0 +1,18 @@ +class Solution { + public int findSubstringInWraproundString(String p) { + int maxLength = 1; + // count[i] := the number of substrings ending in ('a' + i) + int[] count = new int[26]; + + for (int i = 0; i < p.length(); ++i) { + if (i > 0 && (p.charAt(i) - p.charAt(i - 1) == 1 || p.charAt(i - 1) - p.charAt(i) == 25)) + ++maxLength; + else + maxLength = 1; + final int index = p.charAt(i) - 'a'; + count[index] = Math.max(count[index], maxLength); + } + + return Arrays.stream(count).sum(); + } +} diff --git a/solutions/468. Validate IP Address/468.cpp b/solutions/468. Validate IP Address/468.cpp new file mode 100644 index 00000000000..79184872041 --- /dev/null +++ b/solutions/468. Validate IP Address/468.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + string validIPAddress(string IP) { + string digit; + istringstream iss(IP); + + if (ranges::count(IP, '.') == 3) { + for (int i = 0; i < 4; ++i) // Make sure that we have four parts. + if (!getline(iss, digit, '.') || !isIPv4(digit)) + return "Neither"; + return "IPv4"; + } + + if (ranges::count(IP, ':') == 7) { + for (int i = 0; i < 8; ++i) // Make sure that we have eight parts. + if (!getline(iss, digit, ':') || !isIPv6(digit)) + return "Neither"; + return "IPv6"; + } + + return "Neither"; + } + + private: + static inline string validIPv6Chars = "0123456789abcdefABCDEF"; + + bool isIPv4(const string& digit) { + if (digit.empty() || digit.length() > 3) + return false; + if (digit.length() > 1 && digit[0] == '0') + return false; + + for (const char c : digit) + if (c < '0' || c > '9') + return false; + + const int num = stoi(digit); + return 0 <= num && num <= 255; + } + + bool isIPv6(const string& digit) { + if (digit.empty() || digit.length() > 4) + return false; + + for (const char c : digit) + if (validIPv6Chars.find(c) == string::npos) + return false; + + return true; + } +}; diff --git a/solutions/468. Validate IP Address/468.java b/solutions/468. Validate IP Address/468.java new file mode 100644 index 00000000000..e5063a1132a --- /dev/null +++ b/solutions/468. Validate IP Address/468.java @@ -0,0 +1,46 @@ +class Solution { + public String validIPAddress(String IP) { + if (IP.chars().filter(c -> c == '.').count() == 3) { + for (final String digit : IP.split("\\.", -1)) + if (!isIPv4(digit)) + return "Neither"; + return "IPv4"; + } + + if (IP.chars().filter(c -> c == ':').count() == 7) { + for (final String digit : IP.split("\\:", -1)) + if (!isIPv6(digit)) + return "Neither"; + return "IPv6"; + } + + return "Neither"; + } + + private static final String validIPv6Chars = "0123456789abcdefABCDEF"; + + private boolean isIPv4(final String digit) { + if (digit.isEmpty() || digit.length() > 3) + return false; + if (digit.length() > 1 && digit.charAt(0) == '0') + return false; + + for (final char c : digit.toCharArray()) + if (c < '0' || c > '9') + return false; + + final int num = Integer.parseInt(digit); + return 0 <= num && num <= 255; + } + + private boolean isIPv6(final String digit) { + if (digit.isEmpty() || digit.length() > 4) + return false; + + for (final char c : digit.toCharArray()) + if (!validIPv6Chars.contains("" + c)) + return false; + + return true; + } +} diff --git a/solutions/469. Convex Polygon/469.cpp b/solutions/469. Convex Polygon/469.cpp new file mode 100644 index 00000000000..b6e474239c6 --- /dev/null +++ b/solutions/469. Convex Polygon/469.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool isConvex(vector>& points) { + auto getCross = [](const vector& p, const vector& q, + const vector& r) -> int { + return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + }; + + const int n = points.size(); + long sign = 0; + + for (int i = 0; i < points.size(); ++i) { + const int cross = + getCross(points[i], points[(i + 1) % n], points[(i + 2) % n]); + if (cross == 0) // p, q, r are collinear. + continue; + if (sign == 0) // Find the first cross that's not 0. + sign = cross; + else if (cross * sign < 0) + return false; + } + + return true; + } +}; diff --git a/solutions/469. Convex Polygon/469.java b/solutions/469. Convex Polygon/469.java new file mode 100644 index 00000000000..a7daf283137 --- /dev/null +++ b/solutions/469. Convex Polygon/469.java @@ -0,0 +1,23 @@ +class Solution { + public boolean isConvex(List> points) { + final int n = points.size(); + long sign = 0; + + for (int i = 0; i < n; ++i) { + final int cross = getCross(points.get(i), points.get((i + 1) % n), points.get((i + 2) % n)); + if (cross == 0) // p, q, r are collinear. + continue; + if (sign == 0) // Find the first cross that's not 0. + sign = cross; + else if (cross * sign < 0) + return false; + } + + return true; + } + + private int getCross(List p, List q, List r) { + return (q.get(0) - p.get(0)) * (r.get(1) - p.get(1)) - + (q.get(1) - p.get(1)) * (r.get(0) - p.get(0)); + } +} diff --git a/solutions/469. Convex Polygon/469.py b/solutions/469. Convex Polygon/469.py new file mode 100644 index 00000000000..39e75502564 --- /dev/null +++ b/solutions/469. Convex Polygon/469.py @@ -0,0 +1,17 @@ +class Solution: + def isConvex(self, points: List[List[int]]) -> bool: + # Pq x qr + def getCross(p: List[int], q: List[int], r: List[int]): + return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) + + sign = 0 + for i in range(len(points)): + cross = getCross(points[i - 2], points[i - 1], points[i]) + if cross == 0: # p, q, r are collinear. + continue + if sign == 0: # Find the first cross that's not 0. + sign = cross + elif cross * sign < 0: + return False + + return True diff --git a/solutions/47. Permutations II/47.cpp b/solutions/47. Permutations II/47.cpp new file mode 100644 index 00000000000..ac2cc3c4088 --- /dev/null +++ b/solutions/47. Permutations II/47.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector> permuteUnique(vector& nums) { + vector> ans; + ranges::sort(nums); + dfs(nums, vector(nums.size()), {}, ans); + return ans; + } + + private: + void dfs(const vector& nums, vector&& used, vector&& path, + vector>& ans) { + if (path.size() == nums.size()) { + ans.push_back(path); + return; + } + + for (int i = 0; i < nums.size(); ++i) { + if (used[i]) + continue; + if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) + continue; + used[i] = true; + path.push_back(nums[i]); + dfs(nums, move(used), move(path), ans); + path.pop_back(); + used[i] = false; + } + } +}; diff --git a/solutions/47. Permutations II/47.java b/solutions/47. Permutations II/47.java new file mode 100644 index 00000000000..4a412b5fcb4 --- /dev/null +++ b/solutions/47. Permutations II/47.java @@ -0,0 +1,27 @@ +class Solution { + public List> permuteUnique(int[] nums) { + List> ans = new ArrayList<>(); + Arrays.sort(nums); + dfs(nums, new boolean[nums.length], new ArrayList<>(), ans); + return ans; + } + + private void dfs(int[] nums, boolean[] used, List path, List> ans) { + if (path.size() == nums.length) { + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = 0; i < nums.length; ++i) { + if (used[i]) + continue; + if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) + continue; + used[i] = true; + path.add(nums[i]); + dfs(nums, used, path, ans); + path.remove(path.size() - 1); + used[i] = false; + } + } +} diff --git a/solutions/47. Permutations II/47.py b/solutions/47. Permutations II/47.py new file mode 100644 index 00000000000..7c7691da4b6 --- /dev/null +++ b/solutions/47. Permutations II/47.py @@ -0,0 +1,24 @@ +class Solution: + def permuteUnique(self, nums: List[int]) -> List[List[int]]: + ans = [] + used = [False] * len(nums) + + def dfs(path: List[int]) -> None: + if len(path) == len(nums): + ans.append(path.copy()) + return + + for i, num in enumerate(nums): + if used[i]: + continue + if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: + continue + used[i] = True + path.append(num) + dfs(path) + path.pop() + used[i] = False + + nums.sort() + dfs([]) + return ans diff --git a/solutions/470. Implement Rand10() Using Rand7()/470.cpp b/solutions/470. Implement Rand10() Using Rand7()/470.cpp new file mode 100644 index 00000000000..c0979468c30 --- /dev/null +++ b/solutions/470. Implement Rand10() Using Rand7()/470.cpp @@ -0,0 +1,15 @@ +// The rand7() API is already defined for you. +// int rand7(); +// @return a random integer in the range 1 to 7 + +class Solution { + public: + int rand10() { + int num = 40; + + while (num >= 40) + num = (rand7() - 1) * 7 + rand7() - 1; + + return num % 10 + 1; + } +}; diff --git a/solutions/470. Implement Rand10() Using Rand7()/470.java b/solutions/470. Implement Rand10() Using Rand7()/470.java new file mode 100644 index 00000000000..80a2fcba83d --- /dev/null +++ b/solutions/470. Implement Rand10() Using Rand7()/470.java @@ -0,0 +1,16 @@ +/** + * The rand7() API is already defined in the parent class SolBase. + * public int rand7(); + * @return a random integer in the range 1 to 7 + */ + +class Solution extends SolBase { + public int rand10() { + int num = 40; + + while (num >= 40) + num = (rand7() - 1) * 7 + rand7() - 1; + + return num % 10 + 1; + } +} diff --git a/solutions/471. Encode String with Shortest Length/471-2.cpp b/solutions/471. Encode String with Shortest Length/471-2.cpp new file mode 100644 index 00000000000..1c4c8ec82dd --- /dev/null +++ b/solutions/471. Encode String with Shortest Length/471-2.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + string encode(string s) { + const int n = s.length(); + // dp[i][j] := the shortest encoded string of s[i..j] + vector> dp(n, vector(n)); + + for (int d = 0; d < n; ++d) { + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + const string& curr = s.substr(i, j - i + 1); + dp[i][j] = curr; + + if (dp[i][j].length() < 5) + continue; + + // Try all the possible partitions. + for (int k = i; k < j; ++k) + if (dp[i][k].length() + dp[k + 1][j].length() < dp[i][j].length()) + dp[i][j] = dp[i][k] + dp[k + 1][j]; + + // Try to compress the string. + // e.g. s = aabaabaab -> 3[aab] + for (int k = i; k <= j; ++k) { + const string& pattern = s.substr(i, k - i + 1); + if (curr.length() % pattern.length() == 0 && + regex_replace(curr, regex(pattern), "").empty()) { + const string& candidate = + to_string(curr.length() / pattern.length()) + '[' + dp[i][k] + + ']'; + if (candidate.length() < dp[i][j].length()) + dp[i][j] = candidate; + } + } + } + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/471. Encode String with Shortest Length/471-2.java b/solutions/471. Encode String with Shortest Length/471-2.java new file mode 100644 index 00000000000..a15449906b6 --- /dev/null +++ b/solutions/471. Encode String with Shortest Length/471-2.java @@ -0,0 +1,37 @@ +class Solution { + public String encode(String s) { + final int n = s.length(); + // dp[i][j] := shortest encoded String of s[i..j] + String[][] dp = new String[n][n]; + + for (int d = 0; d < n; ++d) { + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + final String curr = s.substring(i, j + 1); + dp[i][j] = curr; + + if (dp[i][j].length() < 5) + continue; + + // Try all the possible partitions. + for (int k = i; k < j; ++k) + if (dp[i][k].length() + dp[k + 1][j].length() < dp[i][j].length()) + dp[i][j] = dp[i][k] + dp[k + 1][j]; + + // Try to compress the string. + // e.g. s = aabaabaab -> 3[aab] + for (int k = i; k <= j; ++k) { + final String pattern = s.substring(i, k + 1); + if (curr.length() % pattern.length() == 0 && curr.replaceAll(pattern, "").isEmpty()) { + final String candidate = + String.valueOf(curr.length() / pattern.length()) + "[" + dp[i][k] + "]"; + if (candidate.length() < dp[i][j].length()) + dp[i][j] = candidate; + } + } + } + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/471. Encode String with Shortest Length/471.cpp b/solutions/471. Encode String with Shortest Length/471.cpp new file mode 100644 index 00000000000..45997dff592 --- /dev/null +++ b/solutions/471. Encode String with Shortest Length/471.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + string encode(string s) { + const int n = s.length(); + vector> mem(n, vector(n)); + return encode(s, 0, n - 1); + } + + private: + // Returns the shortest encoded string of s[i..j]. + string encode(const string& s, int i, int j, vector>& mem) { + if (!mem[i][j].empty()) + return mem[i][j]; + + const string& curr = s.substr(i, j - i + 1); + mem[i][j] = curr; + + if (mem[i][j].length() < 5) + return mem[i][j]; + + // Try all the possible partitions. + for (int k = i; k < j; ++k) { + const string& l = encode(s, i, k, mem); + const string& r = encode(s, k + 1, j, mem); + if (l.length() + r.length() < mem[i][j].length()) + mem[i][j] = l + r; + } + + // Try to compress the string. + // e.g. s = aabaabaab -> 3[aab] + for (int k = i; k <= j; ++k) { + const string& pattern = s.substr(i, k - i + 1); + if (curr.length() % pattern.length() == 0 && + regex_replace(curr, regex(pattern), "").empty()) { + const string& candidate = to_string(curr.length() / pattern.length()) + + '[' + encode(s, i, k, mem) + ']'; + if (candidate.length() < mem[i][j].length()) + mem[i][j] = candidate; + } + } + + return mem[i][j]; + } +}; diff --git a/solutions/471. Encode String with Shortest Length/471.java b/solutions/471. Encode String with Shortest Length/471.java new file mode 100644 index 00000000000..1ad0bbc7a06 --- /dev/null +++ b/solutions/471. Encode String with Shortest Length/471.java @@ -0,0 +1,41 @@ +class Solution { + public String encode(String s) { + final int n = s.length(); + String[][] mem = new String[n][n]; + return encode(s, 0, n - 1, mem); + } + + // Returns the shortest encoded string of s[i..j]. + private String encode(final String s, int i, int j, String[][] mem) { + if (mem[i][j] != null) + return mem[i][j]; + + final String curr = s.substring(i, j + 1); + mem[i][j] = curr; + + if (mem[i][j].length() < 5) + return mem[i][j]; + + // Try all the possible partitions. + for (int k = i; k < j; ++k) { + final String l = encode(s, i, k, mem); + final String r = encode(s, k + 1, j, mem); + if (l.length() + r.length() < mem[i][j].length()) + mem[i][j] = l + r; + } + + // Try to compress the string. + // e.g. s = aabaabaab -> 3[aab] + for (int k = i; k <= j; ++k) { + final String pattern = s.substring(i, k + 1); + if (curr.length() % pattern.length() == 0 && curr.replaceAll(pattern, "").isEmpty()) { + final String candidate = + String.valueOf(curr.length() / pattern.length()) + "[" + encode(s, i, k, mem) + "]"; + if (candidate.length() < mem[i][j].length()) + mem[i][j] = candidate; + } + } + + return mem[i][j]; + } +} diff --git a/solutions/472. Concatenated Words/472.cpp b/solutions/472. Concatenated Words/472.cpp new file mode 100644 index 00000000000..09ddacdf5ec --- /dev/null +++ b/solutions/472. Concatenated Words/472.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + vector findAllConcatenatedWordsInADict(vector& words) { + vector ans; + unordered_set wordSet{words.begin(), words.end()}; + unordered_map mem; + + for (const string& word : words) + if (isConcat(word, wordSet, mem)) + ans.push_back(word); + + return ans; + } + + private: + bool isConcat(const string& s, const unordered_set& wordSet, + unordered_map& mem) { + if (const auto it = mem.find(s); it != mem.cend()) + return it->second; + + for (int i = 1; i < s.length(); ++i) { + const string prefix = s.substr(0, i); + const string suffix = s.substr(i); + if (wordSet.contains(prefix) && + (wordSet.contains(suffix) || isConcat(suffix, wordSet, mem))) + return mem[s] = true; + } + + return mem[s] = false; + } +}; diff --git a/solutions/472. Concatenated Words/472.java b/solutions/472. Concatenated Words/472.java new file mode 100644 index 00000000000..5165aa9bdc3 --- /dev/null +++ b/solutions/472. Concatenated Words/472.java @@ -0,0 +1,31 @@ +class Solution { + public List findAllConcatenatedWordsInADict(String[] words) { + List ans = new ArrayList<>(); + Set wordSet = new HashSet<>(Arrays.asList(words)); + Map mem = new HashMap<>(); + + for (final String word : words) + if (wordBreak(word, wordSet, mem)) + ans.add(word); + + return ans; + } + + private boolean wordBreak(final String word, Set wordSet, Map mem) { + if (mem.containsKey(word)) + return mem.get(word); + + for (int i = 1; i < word.length(); ++i) { + final String prefix = word.substring(0, i); + final String suffix = word.substring(i); + if (wordSet.contains(prefix) && + (wordSet.contains(suffix) || wordBreak(suffix, wordSet, mem))) { + mem.put(word, true); + return true; + } + } + + mem.put(word, false); + return false; + } +} diff --git a/solutions/472. Concatenated Words/472.py b/solutions/472. Concatenated Words/472.py new file mode 100644 index 00000000000..53b1e5de278 --- /dev/null +++ b/solutions/472. Concatenated Words/472.py @@ -0,0 +1,15 @@ +class Solution: + def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: + wordSet = set(words) + + @functools.lru_cache(None) + def isConcat(word: str) -> bool: + for i in range(1, len(word)): + prefix = word[:i] + suffix = word[i:] + if prefix in wordSet and (suffix in wordSet or isConcat(suffix)): + return True + + return False + + return [word for word in words if isConcat(word)] diff --git a/solutions/473. Matchsticks to Square/473.cpp b/solutions/473. Matchsticks to Square/473.cpp new file mode 100644 index 00000000000..497e173fb11 --- /dev/null +++ b/solutions/473. Matchsticks to Square/473.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + bool makesquare(vector& matchsticks) { + if (matchsticks.size() < 4) + return false; + + const int perimeter = accumulate(matchsticks.begin(), matchsticks.end(), 0); + if (perimeter % 4 != 0) + return false; + + ranges::sort(matchsticks, greater()); + return dfs(matchsticks, 0, vector(4, perimeter / 4)); + } + + private: + bool dfs(const vector& matchsticks, int selected, vector&& edges) { + if (selected == matchsticks.size()) + return ranges::all_of(edges, [](int edge) { return edge == 0; }); + + for (int i = 0; i < 4; ++i) { + if (matchsticks[selected] > edges[i]) + continue; + edges[i] -= matchsticks[selected]; + if (dfs(matchsticks, selected + 1, move(edges))) + return true; + edges[i] += matchsticks[selected]; + } + + return false; + } +}; diff --git a/solutions/473. Matchsticks to Square/473.java b/solutions/473. Matchsticks to Square/473.java new file mode 100644 index 00000000000..dfe23d71438 --- /dev/null +++ b/solutions/473. Matchsticks to Square/473.java @@ -0,0 +1,31 @@ +class Solution { + public boolean makesquare(int[] matchsticks) { + if (matchsticks.length < 4) + return false; + + final int perimeter = Arrays.stream(matchsticks).sum(); + if (perimeter % 4 != 0) + return false; + + int[] edges = new int[4]; + Arrays.fill(edges, perimeter / 4); + Arrays.sort(edges); // can't do "Arrays.sort(edges, (a, b) -> b - a);" in Java + return dfs(matchsticks, matchsticks.length - 1, edges); + } + + private boolean dfs(int[] matchsticks, int selected, int[] edges) { + if (selected == -1) + return Arrays.stream(edges).allMatch(edge -> edge == 0); + + for (int i = 0; i < 4; ++i) { + if (matchsticks[selected] > edges[i]) + continue; + edges[i] -= matchsticks[selected]; + if (dfs(matchsticks, selected - 1, edges)) + return true; + edges[i] += matchsticks[selected]; + } + + return false; + } +} diff --git a/solutions/473. Matchsticks to Square/473.py b/solutions/473. Matchsticks to Square/473.py new file mode 100644 index 00000000000..e6fe3b2b608 --- /dev/null +++ b/solutions/473. Matchsticks to Square/473.py @@ -0,0 +1,26 @@ +class Solution: + def makesquare(self, matchsticks: List[int]) -> bool: + if len(matchsticks) < 4: + return False + + perimeter = sum(matchsticks) + if perimeter % 4 != 0: + return False + + A = sorted(matchsticks)[::-1] + + def dfs(selected: int, edges: List[int]) -> bool: + if selected == len(A): + return all(edge == edges[0] for edge in edges) + + for i, edge in enumerate(edges): + if A[selected] > edge: + continue + edges[i] -= A[selected] + if dfs(selected + 1, edges): + return True + edges[i] += A[selected] + + return False + + return dfs(0, [perimeter // 4] * 4) diff --git a/solutions/474. Ones and Zeroes/474.cpp b/solutions/474. Ones and Zeroes/474.cpp new file mode 100644 index 00000000000..b9e599c2727 --- /dev/null +++ b/solutions/474. Ones and Zeroes/474.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int findMaxForm(vector& strs, int m, int n) { + // dp[i][j] := the maximum size of the subset given i 0s and j 1s are + // available + vector> dp(m + 1, vector(n + 1)); + + for (const string& s : strs) { + const int count0 = ranges::count(s, '0'); + const int count1 = s.length() - count0; + for (int i = m; i >= count0; --i) + for (int j = n; j >= count1; --j) + dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1); + } + + return dp[m][n]; + } +}; diff --git a/solutions/474. Ones and Zeroes/474.java b/solutions/474. Ones and Zeroes/474.java new file mode 100644 index 00000000000..c539eee0104 --- /dev/null +++ b/solutions/474. Ones and Zeroes/474.java @@ -0,0 +1,17 @@ +class Solution { + public int findMaxForm(String[] strs, int m, int n) { + // dp[i][j] := the maximum size of the subset given i 0s and j 1s are + // available + int[][] dp = new int[m + 1][n + 1]; + + for (final String s : strs) { + final int count0 = (int) s.chars().filter(c -> c == '0').count(); + final int count1 = (int) s.length() - count0; + for (int i = m; i >= count0; --i) + for (int j = n; j >= count1; --j) + dp[i][j] = Math.max(dp[i][j], dp[i - count0][j - count1] + 1); + } + + return dp[m][n]; + } +} diff --git a/solutions/474. Ones and Zeroes/474.py b/solutions/474. Ones and Zeroes/474.py new file mode 100644 index 00000000000..6fd0cfaf14c --- /dev/null +++ b/solutions/474. Ones and Zeroes/474.py @@ -0,0 +1,14 @@ +class Solution: + def findMaxForm(self, strs: List[str], m: int, n: int) -> int: + # dp[i][j] := the maximum size of the subset given i 0s and j 1s are + # available + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for s in strs: + count0 = s.count('0') + count1 = len(s) - count0 + for i in range(m, count0 - 1, -1): + for j in range(n, count1 - 1, -1): + dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1) + + return dp[m][n] diff --git a/solutions/475. Heaters/475.cpp b/solutions/475. Heaters/475.cpp new file mode 100644 index 00000000000..9ca041ee8b8 --- /dev/null +++ b/solutions/475. Heaters/475.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findRadius(vector& houses, vector& heaters) { + ranges::sort(houses); + ranges::sort(heaters); + + int ans = 0; + int i = 0; // heaters' index (currently used) + + for (const int house : houses) { + while (i + 1 < heaters.size() && + house - heaters[i] > heaters[i + 1] - house) + ++i; // The next heater is better. + ans = max(ans, abs(heaters[i] - house)); + } + + return ans; + } +}; diff --git a/solutions/475. Heaters/475.java b/solutions/475. Heaters/475.java new file mode 100644 index 00000000000..5f314337750 --- /dev/null +++ b/solutions/475. Heaters/475.java @@ -0,0 +1,17 @@ +class Solution { + public int findRadius(int[] houses, int[] heaters) { + Arrays.sort(houses); + Arrays.sort(heaters); + + int ans = 0; + int i = 0; // heaters' index (currently used) + + for (final int house : houses) { + while (i + 1 < heaters.length && house - heaters[i] > heaters[i + 1] - house) + ++i; // The next heater is better. + ans = Math.max(ans, Math.abs(heaters[i] - house)); + } + + return ans; + } +} diff --git a/solutions/476. Number Complement/476.cpp b/solutions/476. Number Complement/476.cpp new file mode 100644 index 00000000000..ab3babcf2d9 --- /dev/null +++ b/solutions/476. Number Complement/476.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int findComplement(long num) { + for (long i = 1; i <= num; i <<= 1) + num ^= i; + return num; + } +}; diff --git a/solutions/476. Number Complement/476.java b/solutions/476. Number Complement/476.java new file mode 100644 index 00000000000..9438f38ba02 --- /dev/null +++ b/solutions/476. Number Complement/476.java @@ -0,0 +1,7 @@ +class Solution { + public int findComplement(int num) { + for (long i = 1; i <= num; i <<= 1) + num ^= i; + return num; + } +} diff --git a/solutions/477. Total Hamming Distance/477.cpp b/solutions/477. Total Hamming Distance/477.cpp new file mode 100644 index 00000000000..df5674f202d --- /dev/null +++ b/solutions/477. Total Hamming Distance/477.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int totalHammingDistance(vector& nums) { + constexpr int kMaxMask = 1 << 30; + int ans = 0; + + for (int mask = 1; mask < kMaxMask; mask <<= 1) { + const int ones = + ranges::count_if(nums, [mask](int num) { return num & mask; }); + const int zeros = nums.size() - ones; + ans += ones * zeros; + } + + return ans; + } +}; diff --git a/solutions/477. Total Hamming Distance/477.java b/solutions/477. Total Hamming Distance/477.java new file mode 100644 index 00000000000..7f695823bdf --- /dev/null +++ b/solutions/477. Total Hamming Distance/477.java @@ -0,0 +1,15 @@ +class Solution { + public int totalHammingDistance(int[] nums) { + final int kMaxBit = 30; + int ans = 0; + + for (int i = 0; i < kMaxBit; ++i) { + final int mask = 1 << i; + final int ones = (int) Arrays.stream(nums).filter(num -> (num & mask) > 0).count(); + final int zeros = nums.length - ones; + ans += ones * zeros; + } + + return ans; + } +} diff --git a/solutions/477. Total Hamming Distance/477.py b/solutions/477. Total Hamming Distance/477.py new file mode 100644 index 00000000000..c259d09f03e --- /dev/null +++ b/solutions/477. Total Hamming Distance/477.py @@ -0,0 +1,11 @@ +class Solution: + def totalHammingDistance(self, nums: List[int]) -> int: + kMaxBit = 30 + ans = 0 + + for i in range(kMaxBit): + ones = sum(num & (1 << i) > 0 for num in nums) + zeros = len(nums) - ones + ans += ones * zeros + + return ans diff --git a/solutions/478. Generate Random Point in a Circle/478.cpp b/solutions/478. Generate Random Point in a Circle/478.cpp new file mode 100644 index 00000000000..7a47ce02c71 --- /dev/null +++ b/solutions/478. Generate Random Point in a Circle/478.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + Solution(double radius, double x_center, double y_center) + : radius(radius), x_center(x_center), y_center(y_center) {} + + vector randPoint() { + const double length = sqrt(distribution(generator)) * radius; + const double degree = distribution(generator) * 2 * M_PI; + const double x = x_center + length * cos(degree); + const double y = y_center + length * sin(degree); + return {x, y}; + } + + private: + const double radius; + const double x_center; + const double y_center; + default_random_engine generator; + uniform_real_distribution distribution = + uniform_real_distribution(0.0, 1.0); +}; diff --git a/solutions/478. Generate Random Point in a Circle/478.java b/solutions/478. Generate Random Point in a Circle/478.java new file mode 100644 index 00000000000..d569edaf5f9 --- /dev/null +++ b/solutions/478. Generate Random Point in a Circle/478.java @@ -0,0 +1,19 @@ +class Solution { + public Solution(double radius, double x_center, double y_center) { + this.radius = radius; + this.x_center = x_center; + this.y_center = y_center; + } + + public double[] randPoint() { + final double length = Math.sqrt(Math.random()) * radius; + final double degree = Math.random() * 2 * Math.PI; + final double x = x_center + length * Math.cos(degree); + final double y = y_center + length * Math.sin(degree); + return new double[] {x, y}; + } + + private double radius; + private double x_center; + private double y_center; +} diff --git a/solutions/478. Generate Random Point in a Circle/478.py b/solutions/478. Generate Random Point in a Circle/478.py new file mode 100644 index 00000000000..a439a9e21f0 --- /dev/null +++ b/solutions/478. Generate Random Point in a Circle/478.py @@ -0,0 +1,12 @@ +class Solution: + def __init__(self, radius: float, x_center: float, y_center: float): + self.radius = radius + self.x_center = x_center + self.y_center = y_center + + def randPoint(self) -> List[float]: + length = math.sqrt(random.uniform(0, 1)) * self.radius + degree = random.uniform(0, 1) * 2 * math.pi + x = self.x_center + length * math.cos(degree) + y = self.y_center + length * math.sin(degree) + return [x, y] diff --git a/solutions/479. Largest Palindrome Product/479.cpp b/solutions/479. Largest Palindrome Product/479.cpp new file mode 100644 index 00000000000..ebed9e2749c --- /dev/null +++ b/solutions/479. Largest Palindrome Product/479.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int largestPalindrome(int n) { + if (n == 1) + return 9; + + constexpr int kMod = 1337; + const int upper = pow(10, n) - 1; + const int lower = pow(10, n - 1) - 1; + + for (int i = upper; i > lower; --i) { + const long cand = getPalindromeCandidate(i); + for (long j = upper; j * j >= cand; --j) + if (cand % j == 0) + return cand % kMod; + } + + throw; + } + + private: + long getPalindromeCandidate(int i) { + string reversed = to_string(i); + reverse(reversed.begin(), reversed.end()); + return stol(to_string(i) + reversed); + } +}; diff --git a/solutions/479. Largest Palindrome Product/479.java b/solutions/479. Largest Palindrome Product/479.java new file mode 100644 index 00000000000..c9992264a4e --- /dev/null +++ b/solutions/479. Largest Palindrome Product/479.java @@ -0,0 +1,24 @@ +class Solution { + public int largestPalindrome(int n) { + if (n == 1) + return 9; + + final int kMod = 1337; + final int upper = (int) Math.pow(10, n) - 1; + final int lower = (int) Math.pow(10, n - 1) - 1; + + for (int i = upper; i > lower; --i) { + final long cand = getPalindromeCandidate(i); + for (long j = upper; j * j >= cand; --j) + if (cand % j == 0) + return (int) (cand % kMod); + } + + throw new IllegalArgumentException(); + } + + private long getPalindromeCandidate(int i) { + final String reversed = new StringBuilder().append(i).reverse().toString(); + return Long.valueOf(i + reversed); + } +} diff --git a/solutions/479. Largest Palindrome Product/479.py b/solutions/479. Largest Palindrome Product/479.py new file mode 100644 index 00000000000..03b439a4015 --- /dev/null +++ b/solutions/479. Largest Palindrome Product/479.py @@ -0,0 +1,16 @@ +class Solution: + def largestPalindrome(self, n: int) -> int: + if n == 1: + return 9 + + kMod = 1337 + upper = pow(10, n) - 1 + lower = pow(10, n - 1) - 1 + + for i in range(upper, lower, -1): + cand = int(str(i) + str(i)[::-1]) + j = upper + while j * j >= cand: + if cand % j == 0: + return cand % kMod + j -= 1 diff --git a/solutions/48. Rotate Image/48-2.cpp b/solutions/48. Rotate Image/48-2.cpp new file mode 100644 index 00000000000..5f490d1560b --- /dev/null +++ b/solutions/48. Rotate Image/48-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + void rotate(vector>& matrix) { + for (int mn = 0; mn < matrix.size() / 2; ++mn) { + const int mx = matrix.size() - mn - 1; + for (int i = mn; i < mx; ++i) { + const int offset = i - mn; + const int top = matrix[mn][i]; + matrix[mn][i] = matrix[mx - offset][mn]; + matrix[mx - offset][mn] = matrix[mx][mx - offset]; + matrix[mx][mx - offset] = matrix[i][mx]; + matrix[i][mx] = top; + } + } + } +}; diff --git a/solutions/48. Rotate Image/48-2.java b/solutions/48. Rotate Image/48-2.java new file mode 100644 index 00000000000..2ac7460e3aa --- /dev/null +++ b/solutions/48. Rotate Image/48-2.java @@ -0,0 +1,15 @@ +class Solution { + public void rotate(int[][] matrix) { + for (int mn = 0; mn < matrix.length / 2; ++mn) { + final int mx = matrix.length - mn - 1; + for (int i = mn; i < mx; ++i) { + final int offset = i - mn; + final int top = matrix[mn][i]; + matrix[mn][i] = matrix[mx - offset][mn]; + matrix[mx - offset][mn] = matrix[mx][mx - offset]; + matrix[mx][mx - offset] = matrix[i][mx]; + matrix[i][mx] = top; + } + } + } +} diff --git a/solutions/48. Rotate Image/48-2.py b/solutions/48. Rotate Image/48-2.py new file mode 100644 index 00000000000..60b309d2f81 --- /dev/null +++ b/solutions/48. Rotate Image/48-2.py @@ -0,0 +1,11 @@ +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + for mn in range(len(matrix) // 2): + mx = len(matrix) - mn - 1 + for i in range(mn, mx): + offset = i - mn + top = matrix[mn][i] + matrix[mn][i] = matrix[mx - offset][mn] + matrix[mx - offset][mn] = matrix[mx][mx - offset] + matrix[mx][mx - offset] = matrix[i][mx] + matrix[i][mx] = top diff --git a/solutions/48. Rotate Image/48.cpp b/solutions/48. Rotate Image/48.cpp new file mode 100644 index 00000000000..e6a9f63395b --- /dev/null +++ b/solutions/48. Rotate Image/48.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + void rotate(vector>& matrix) { + reverse(matrix.begin(), matrix.end()); + for (int i = 0; i < matrix.size(); ++i) + for (int j = i + 1; j < matrix.size(); ++j) + swap(matrix[i][j], matrix[j][i]); + } +}; diff --git a/solutions/48. Rotate Image/48.java b/solutions/48. Rotate Image/48.java new file mode 100644 index 00000000000..6eca709a01f --- /dev/null +++ b/solutions/48. Rotate Image/48.java @@ -0,0 +1,16 @@ +class Solution { + public void rotate(int[][] matrix) { + for (int i = 0, j = matrix.length - 1; i < j; ++i, --j) { + int[] temp = matrix[i]; + matrix[i] = matrix[j]; + matrix[j] = temp; + } + + for (int i = 0; i < matrix.length; ++i) + for (int j = i + 1; j < matrix.length; ++j) { + final int temp = matrix[i][j]; + matrix[i][j] = matrix[j][i]; + matrix[j][i] = temp; + } + } +} diff --git a/solutions/48. Rotate Image/48.py b/solutions/48. Rotate Image/48.py new file mode 100644 index 00000000000..74ecc343305 --- /dev/null +++ b/solutions/48. Rotate Image/48.py @@ -0,0 +1,7 @@ +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + matrix.reverse() + + for i in range(len(matrix)): + for j in range(i + 1, len(matrix)): + matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] diff --git a/solutions/480. Sliding Window Median/480.cpp b/solutions/480. Sliding Window Median/480.cpp new file mode 100644 index 00000000000..fb19a892a47 --- /dev/null +++ b/solutions/480. Sliding Window Median/480.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector medianSlidingWindow(vector& nums, int k) { + vector ans; + multiset window(nums.begin(), nums.begin() + k); + auto it = next(window.begin(), (k - 1) / 2); + + for (int i = k;; ++i) { + const double median = k % 2 == 0 ? (*it + *next(it)) / 2.0 : *it; + ans.push_back(median); + if (i == nums.size()) + break; + window.insert(nums[i]); + if (nums[i] < *it) + --it; + if (nums[i - k] <= *it) + ++it; + window.erase(window.lower_bound(nums[i - k])); + } + + return ans; + } +}; diff --git a/solutions/481. Magical String/481.cpp b/solutions/481. Magical String/481.cpp new file mode 100644 index 00000000000..7f96846f3ec --- /dev/null +++ b/solutions/481. Magical String/481.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int magicalString(int n) { + string s = " 122"; + + for (int i = 3; i <= n; ++i) + if (i % 2 == 1) + s.append(s[i] - '0', '1'); + else + s.append(s[i] - '0', '2'); + + return count(s.begin(), s.begin() + n + 1, '1'); + } +}; diff --git a/solutions/482. License Key Formatting/482.cpp b/solutions/482. License Key Formatting/482.cpp new file mode 100644 index 00000000000..3303097b1c8 --- /dev/null +++ b/solutions/482. License Key Formatting/482.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + string licenseKeyFormatting(string s, int k) { + string ans; + int length = 0; + + for (int i = s.length() - 1; i >= 0; --i) { + if (s[i] == '-') + continue; + if (length > 0 && length % k == 0) + ans += "-"; + ans += toupper(s[i]); + ++length; + } + + return {ans.rbegin(), ans.rend()}; + } +}; diff --git a/solutions/482. License Key Formatting/482.java b/solutions/482. License Key Formatting/482.java new file mode 100644 index 00000000000..137f5864231 --- /dev/null +++ b/solutions/482. License Key Formatting/482.java @@ -0,0 +1,17 @@ +class Solution { + public String licenseKeyFormatting(String s, int k) { + StringBuilder sb = new StringBuilder(); + int length = 0; + + for (int i = s.length() - 1; i >= 0; --i) { + if (s.charAt(i) == '-') + continue; + if (length > 0 && length % k == 0) + sb.append('-'); + sb.append(Character.toUpperCase(s.charAt(i))); + ++length; + } + + return sb.reverse().toString(); + } +} diff --git a/solutions/482. License Key Formatting/482.py b/solutions/482. License Key Formatting/482.py new file mode 100644 index 00000000000..48c40c5c7cc --- /dev/null +++ b/solutions/482. License Key Formatting/482.py @@ -0,0 +1,14 @@ +class Solution: + def licenseKeyFormatting(self, s: str, k: int) -> str: + ans = [] + length = 0 + + for i in reversed(range(len(s))): + if s[i] == '-': + continue + if length > 0 and length % k == 0: + ans += '-' + ans += s[i].upper() + length += 1 + + return ''.join(reversed(ans)) diff --git a/solutions/483. Smallest Good Base/483.cpp b/solutions/483. Smallest Good Base/483.cpp new file mode 100644 index 00000000000..d45e1d16915 --- /dev/null +++ b/solutions/483. Smallest Good Base/483.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string smallestGoodBase(string n) { + const long num = stol(n); + + for (int m = log2(num); m >= 2; --m) { + const int k = pow(num, 1.0 / m); + long sum = 1; + long prod = 1; + for (int i = 0; i < m; ++i) { + prod *= k; + sum += prod; + } + if (sum == num) + return to_string(k); + } + + return to_string(num - 1); + } +}; diff --git a/solutions/483. Smallest Good Base/483.java b/solutions/483. Smallest Good Base/483.java new file mode 100644 index 00000000000..ffae9bf747f --- /dev/null +++ b/solutions/483. Smallest Good Base/483.java @@ -0,0 +1,20 @@ +class Solution { + public String smallestGoodBase(String n) { + final long num = Long.parseLong(n); + final int log2 = (int) (Math.log(num) / Math.log(2)); + + for (int m = log2; m >= 2; --m) { + int k = (int) Math.floor(Math.pow(num, 1.0 / m)); + long sum = 1; + long prod = 1; + for (int i = 0; i < m; ++i) { + prod *= k; + sum += prod; + } + if (sum == num) + return String.valueOf(k); + } + + return String.valueOf(num - 1); + } +} diff --git a/solutions/483. Smallest Good Base/483.py b/solutions/483. Smallest Good Base/483.py new file mode 100644 index 00000000000..bca512749a0 --- /dev/null +++ b/solutions/483. Smallest Good Base/483.py @@ -0,0 +1,10 @@ +class Solution: + def smallestGoodBase(self, n: str) -> str: + n = int(n) + + for m in range(int(math.log(n, 2)), 1, -1): + k = int(n**m**-1) + if (k**(m + 1) - 1) // (k - 1) == n: + return str(k) + + return str(n - 1) diff --git a/solutions/484. Find Permutation/484-2.cpp b/solutions/484. Find Permutation/484-2.cpp new file mode 100644 index 00000000000..66e5f5bf8d3 --- /dev/null +++ b/solutions/484. Find Permutation/484-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector findPermutation(string s) { + vector ans(s.length() + 1); + + iota(ans.begin(), ans.end(), 1); + + // For each D* group (s[i..j]), reverse ans[i..j + 1]. + int i = -1; + int j = -1; + + while (true) { + i = getNextIndex(s, 'D', j + 1); + if (i == s.length()) + break; + j = getNextIndex(s, 'I', i + 1); + reverse(ans.begin() + i, ans.begin() + j + 1); + } + + return ans; + } + + private: + int getNextIndex(const string& s, char c, int start) { + for (int i = start; i < s.length(); ++i) + if (s[i] == c) + return i; + return s.length(); + } +}; diff --git a/solutions/484. Find Permutation/484-2.java b/solutions/484. Find Permutation/484-2.java new file mode 100644 index 00000000000..e818db22d7f --- /dev/null +++ b/solutions/484. Find Permutation/484-2.java @@ -0,0 +1,40 @@ +class Solution { + public int[] findPermutation(String s) { + int[] ans = new int[s.length() + 1]; + + for (int i = 0; i < ans.length; ++i) + ans[i] = i + 1; + + // For each D* group (s[i..j]), reverse ans[i..j + 1]. + int i = -1; + int j = -1; + + while (true) { + i = getNextIndex(s, 'D', j + 1); + if (i == s.length()) + break; + j = getNextIndex(s, 'I', i + 1); + reverse(ans, i, j); + } + + return ans; + } + + private int getNextIndex(final String s, char c, int start) { + for (int i = start; i < s.length(); ++i) + if (s.charAt(i) == c) + return i; + return s.length(); + } + + private void reverse(int[] A, int l, int r) { + while (l < r) + swap(A, l++, r--); + } + + private void swap(int[] A, int i, int j) { + final int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} diff --git a/solutions/484. Find Permutation/484-2.py b/solutions/484. Find Permutation/484-2.py new file mode 100644 index 00000000000..2a29a7023a3 --- /dev/null +++ b/solutions/484. Find Permutation/484-2.py @@ -0,0 +1,22 @@ +class Solution: + def findPermutation(self, s: str) -> List[int]: + ans = [i for i in range(1, len(s) + 2)] + + # For each D* group (s[i..j]), reverse ans[i..j + 1]. + i = -1 + j = -1 + + def getNextIndex(c: str, start: int) -> int: + for i in range(start, len(s)): + if s[i] == c: + return i + return len(s) + + while True: + i = getNextIndex('D', j + 1) + if i == len(s): + break + j = getNextIndex('I', i + 1) + ans[i:j + 1] = ans[i:j + 1][::-1] + + return ans diff --git a/solutions/484. Find Permutation/484.cpp b/solutions/484. Find Permutation/484.cpp new file mode 100644 index 00000000000..182271c4b1c --- /dev/null +++ b/solutions/484. Find Permutation/484.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector findPermutation(string s) { + vector ans; + stack stack; + + for (int i = 0; i < s.length(); ++i) { + stack.push(i + 1); + if (s[i] == 'I') + while (!stack.empty()) + ans.push_back(stack.top()), stack.pop(); + } + stack.push(s.length() + 1); + + while (!stack.empty()) + ans.push_back(stack.top()), stack.pop(); + + return ans; + } +}; diff --git a/solutions/484. Find Permutation/484.java b/solutions/484. Find Permutation/484.java new file mode 100644 index 00000000000..ddb13e4ee6f --- /dev/null +++ b/solutions/484. Find Permutation/484.java @@ -0,0 +1,20 @@ +class Solution { + public int[] findPermutation(String s) { + int[] ans = new int[s.length() + 1]; + int ansIndex = 0; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < s.length(); ++i) { + stack.push(i + 1); + if (s.charAt(i) == 'I') + while (!stack.isEmpty()) + ans[ansIndex++] = stack.pop(); + } + stack.push(s.length() + 1); + + while (!stack.isEmpty()) + ans[ansIndex++] = stack.pop(); + + return ans; + } +} diff --git a/solutions/484. Find Permutation/484.py b/solutions/484. Find Permutation/484.py new file mode 100644 index 00000000000..acbbe6a7cb5 --- /dev/null +++ b/solutions/484. Find Permutation/484.py @@ -0,0 +1,16 @@ +class Solution: + def findPermutation(self, s: str) -> List[int]: + ans = [] + stack = [] + + for i, c in enumerate(s): + stack.append(i + 1) + if c == 'I': + while stack: # Consume all decreasings + ans.append(stack.pop()) + stack.append(len(s) + 1) + + while stack: + ans.append(stack.pop()) + + return ans diff --git a/solutions/485. Max Consecutive Ones/485.cpp b/solutions/485. Max Consecutive Ones/485.cpp new file mode 100644 index 00000000000..1a8d8b010b5 --- /dev/null +++ b/solutions/485. Max Consecutive Ones/485.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int findMaxConsecutiveOnes(vector& nums) { + int ans = 0; + int sum = 0; + + for (const int num : nums) + if (num == 1) + ans = max(ans, ++sum); + else + sum = 0; + + return ans; + } +}; diff --git a/solutions/485. Max Consecutive Ones/485.java b/solutions/485. Max Consecutive Ones/485.java new file mode 100644 index 00000000000..3b7b7748211 --- /dev/null +++ b/solutions/485. Max Consecutive Ones/485.java @@ -0,0 +1,14 @@ +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int ans = 0; + int sum = 0; + + for (final int num : nums) + if (num == 1) + ans = Math.max(ans, ++sum); + else + sum = 0; + + return ans; + } +} diff --git a/solutions/485. Max Consecutive Ones/485.py b/solutions/485. Max Consecutive Ones/485.py new file mode 100644 index 00000000000..f9b4afde744 --- /dev/null +++ b/solutions/485. Max Consecutive Ones/485.py @@ -0,0 +1,13 @@ +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + ans = 0 + summ = 0 + + for num in nums: + if num == 0: + summ = 0 + else: + summ += num + ans = max(ans, summ) + + return ans diff --git a/solutions/486. Predict the Winner/486-2.cpp b/solutions/486. Predict the Winner/486-2.cpp new file mode 100644 index 00000000000..0efae059a97 --- /dev/null +++ b/solutions/486. Predict the Winner/486-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool PredictTheWinner(vector& nums) { + const int n = nums.size(); + vector dp = nums; + + for (int d = 1; d < n; ++d) + for (int j = n - 1; j - d >= 0; --j) { + const int i = j - d; + dp[j] = max(nums[i] - dp[j], // Pick the leftmost number. + nums[j] - dp[j - 1]); // Pick the rightmost number. + } + + return dp[n - 1] >= 0; + } +}; diff --git a/solutions/486. Predict the Winner/486-2.java b/solutions/486. Predict the Winner/486-2.java new file mode 100644 index 00000000000..b2060266cb1 --- /dev/null +++ b/solutions/486. Predict the Winner/486-2.java @@ -0,0 +1,15 @@ +class Solution { + public boolean PredictTheWinner(int[] nums) { + final int n = nums.length; + int[] dp = nums.clone(); + + for (int d = 1; d < n; ++d) + for (int j = n - 1; j - d >= 0; --j) { + final int i = j - d; + dp[j] = Math.max(nums[i] - dp[j], // Pick the leftmost number. + nums[j] - dp[j - 1]); // Pick the rightmost number. + } + + return dp[n - 1] >= 0; + } +} diff --git a/solutions/486. Predict the Winner/486.cpp b/solutions/486. Predict the Winner/486.cpp new file mode 100644 index 00000000000..69f55bc9dab --- /dev/null +++ b/solutions/486. Predict the Winner/486.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool PredictTheWinner(vector& nums) { + const int n = nums.size(); + // dp[i][j] := the maximum number you can get more than your opponent in + // nums[i..j] + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = nums[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]); + } + + return dp[0][n - 1] >= 0; + } +}; diff --git a/solutions/486. Predict the Winner/486.java b/solutions/486. Predict the Winner/486.java new file mode 100644 index 00000000000..993d7bd72ce --- /dev/null +++ b/solutions/486. Predict the Winner/486.java @@ -0,0 +1,18 @@ +class Solution { + public boolean PredictTheWinner(int[] nums) { + final int n = nums.length; + // dp[i][j] := the maximum number you can get more than your opponent in nums[i..j] + int[][] dp = new int[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = nums[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]); + } + + return dp[0][n - 1] >= 0; + } +} diff --git a/solutions/487. Max Consecutive Ones II/487-2.cpp b/solutions/487. Max Consecutive Ones II/487-2.cpp new file mode 100644 index 00000000000..da9627aaf98 --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int findMaxConsecutiveOnes(vector& nums) { + constexpr int maxZeros = 1; + int ans = 0; + queue q; // Store indices of zero. + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (nums[r] == 0) + q.push(r); + if (q.size() > maxZeros) + l = q.front() + 1, q.pop(); + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/487. Max Consecutive Ones II/487-2.java b/solutions/487. Max Consecutive Ones II/487-2.java new file mode 100644 index 00000000000..a13f022f0d3 --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487-2.java @@ -0,0 +1,18 @@ +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + final int maxZeros = 1; + int ans = 0; + // Store indices of zero. + Queue q = new ArrayDeque<>(); + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (nums[r] == 0) + q.offer(r); + if (q.size() > maxZeros) + l = q.poll() + 1; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/487. Max Consecutive Ones II/487-2.py b/solutions/487. Max Consecutive Ones II/487-2.py new file mode 100644 index 00000000000..451b7d18b4f --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487-2.py @@ -0,0 +1,15 @@ +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + maxZeros = 1 + ans = 0 + q = collections.deque() # Store indices of zero. + + l = 0 + for r, num in enumerate(nums): + if num == 0: + q.append(r) + if len(q) > maxZeros: + l = q.popleft() + 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/487. Max Consecutive Ones II/487-3.cpp b/solutions/487. Max Consecutive Ones II/487-3.cpp new file mode 100644 index 00000000000..189bc59a5fc --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487-3.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int findMaxConsecutiveOnes(vector& nums) { + int ans = 0; + int lastZeroIndex = -1; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (nums[r] == 0) { + l = lastZeroIndex + 1; + lastZeroIndex = r; + } + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/487. Max Consecutive Ones II/487-3.java b/solutions/487. Max Consecutive Ones II/487-3.java new file mode 100644 index 00000000000..e3b2ff8bd04 --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487-3.java @@ -0,0 +1,16 @@ +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int ans = 0; + int lastZeroIndex = -1; + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (nums[r] == 0) { + l = lastZeroIndex + 1; + lastZeroIndex = r; + } + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/487. Max Consecutive Ones II/487-3.py b/solutions/487. Max Consecutive Ones II/487-3.py new file mode 100644 index 00000000000..d6601ba405e --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487-3.py @@ -0,0 +1,13 @@ +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + ans = 0 + lastZeroIndex = -1 + + l = 0 + for r, num in enumerate(nums): + if num == 0: + l = lastZeroIndex + 1 + lastZeroIndex = r + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/487. Max Consecutive Ones II/487.cpp b/solutions/487. Max Consecutive Ones II/487.cpp new file mode 100644 index 00000000000..51b3d400dc4 --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int findMaxConsecutiveOnes(vector& nums) { + int ans = 0; + int zeros = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (nums[r] == 0) + ++zeros; + while (zeros == 2) + if (nums[l++] == 0) + --zeros; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/487. Max Consecutive Ones II/487.java b/solutions/487. Max Consecutive Ones II/487.java new file mode 100644 index 00000000000..8f7fd4cbd8e --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487.java @@ -0,0 +1,17 @@ +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int ans = 0; + int zeros = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (nums[r] == 0) + ++zeros; + while (zeros == 2) + if (nums[l++] == 0) + --zeros; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/487. Max Consecutive Ones II/487.py b/solutions/487. Max Consecutive Ones II/487.py new file mode 100644 index 00000000000..2f259374e31 --- /dev/null +++ b/solutions/487. Max Consecutive Ones II/487.py @@ -0,0 +1,16 @@ +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + ans = 0 + zeros = 0 + + l = 0 + for r, num in enumerate(nums): + if num == 0: + zeros += 1 + while zeros == 2: + if nums[l] == 0: + zeros -= 1 + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/488. Zuma Game/488.cpp b/solutions/488. Zuma Game/488.cpp new file mode 100644 index 00000000000..6f16bc59a5a --- /dev/null +++ b/solutions/488. Zuma Game/488.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int findMinStep(string board, string hand) { + const int ans = dfs(board + "#", hand, {}); + return ans == INT_MAX ? -1 : ans; + } + + private: + int dfs(string&& board, const string& hand, + unordered_map&& mem) { + const string hashKey = board + '#' + hand; + if (const auto it = mem.find(hashKey); it != mem.cend()) + return it->second; + board = deDup(board); + if (board == "#") + return 0; + + unordered_set boardSet = unordered_set(board.begin(), board.end()); + + string hs; // hand that is in board + for (const char h : hand) + if (boardSet.contains(h)) + hs += h; + if (hs.empty()) // infeasible + return INT_MAX; + + int ans = INT_MAX; + + for (int i = 0; i < board.size(); ++i) + for (int j = 0; j < hs.size(); ++j) { + // Place hs[j] in board[i]. + const string& newHand = hs.substr(0, j) + hs.substr(j + 1); + string newBoard = board.substr(0, i) + hs[j] + board.substr(i); + const int res = dfs(move(newBoard), newHand, move(mem)); + if (res < INT_MAX) + ans = min(ans, 1 + res); + } + + return mem[hashKey] = ans; + } + + string deDup(string board) { + int start = 0; // the start index of a color sequenece + for (int i = 0; i < board.size(); ++i) + if (board[i] != board[start]) { + if (i - start >= 3) + return deDup(board.substr(0, start) + board.substr(i)); + start = i; // Meet a new sequence. + } + return board; + } +}; diff --git a/solutions/488. Zuma Game/488.java b/solutions/488. Zuma Game/488.java new file mode 100644 index 00000000000..c20d321f6a6 --- /dev/null +++ b/solutions/488. Zuma Game/488.java @@ -0,0 +1,54 @@ +class Solution { + public int findMinStep(String board, String hand) { + Map mem = new HashMap<>(); + final int ans = dfs(board + '#', hand, mem); + return ans == Integer.MAX_VALUE ? -1 : ans; + } + + private int dfs(String board, final String hand, Map mem) { + final String hashKey = board + '#' + hand; + if (mem.containsKey(hashKey)) + return mem.get(hashKey); + board = deDup(board); + if (board.equals("#")) + return 0; + + Set boardSet = new HashSet<>(); + for (final char c : board.toCharArray()) + boardSet.add(c); + + StringBuilder sb = new StringBuilder(); + for (final char h : hand.toCharArray()) + if (boardSet.contains(h)) + sb.append(h); + final String hs = sb.toString(); + if (sb.length() == 0) // infeasible + return Integer.MAX_VALUE; + + int ans = Integer.MAX_VALUE; + + for (int i = 0; i < board.length(); ++i) + for (int j = 0; j < hs.length(); ++j) { + // Place hs[j] in board[i]. + final String newHand = hs.substring(0, j) + hs.substring(j + 1); + String newBoard = board.substring(0, i) + hs.charAt(j) + board.substring(i); + final int res = dfs(newBoard, newHand, mem); + if (res < Integer.MAX_VALUE) + ans = Math.min(ans, 1 + res); + } + + mem.put(hashKey, ans); + return ans; + } + + private String deDup(String board) { + int start = 0; // the start index of a color sequenece + for (int i = 0; i < board.length(); ++i) + if (board.charAt(i) != board.charAt(start)) { + if (i - start >= 3) + return deDup(board.substring(0, start) + board.substring(i)); + start = i; // Meet a new sequence. + } + return board; + } +} diff --git a/solutions/488. Zuma Game/488.py b/solutions/488. Zuma Game/488.py new file mode 100644 index 00000000000..8c9170d8183 --- /dev/null +++ b/solutions/488. Zuma Game/488.py @@ -0,0 +1,36 @@ +class Solution: + def findMinStep(self, board: str, hand: str) -> int: + def deDup(board): + start = 0 # the start index of a color sequenece + for i, c in enumerate(board): + if c != board[start]: + if i - start >= 3: + return deDup(board[:start] + board[i:]) + start = i # Meet a new sequence. + return board + + @functools.lru_cache(None) + def dfs(board: str, hand: str): + board = deDup(board) + if board == '#': + return 0 + + boardSet = set(board) + # hand that is in board + hand = ''.join(h for h in hand if h in boardSet) + if not hand: # infeasible + return math.inf + + ans = math.inf + + for i in range(len(board)): + for j, h in enumerate(hand): + # Place hs[j] in board[i]. + newHand = hand[:j] + hand[j + 1:] + newBoard = board[:i] + h + board[i:] + ans = min(ans, 1 + dfs(newBoard, newHand)) + + return ans + + ans = dfs(board + '#', hand) + return -1 if ans == math.inf else ans diff --git a/solutions/489. Robot Room Cleaner/489.cpp b/solutions/489. Robot Room Cleaner/489.cpp new file mode 100644 index 00000000000..7588ebc3254 --- /dev/null +++ b/solutions/489. Robot Room Cleaner/489.cpp @@ -0,0 +1,59 @@ +/** + * // This is the robot's control interface. + * // You should not implement it, or speculate about its implementation + * class Robot { + * public: + * // Returns true if the cell in front is open and robot moves into the cell. + * // Returns false if the cell in front is blocked and robot stays in the + * // Current cell. bool move(); + * + * // Robot will stay in the same cell after calling turnLeft/turnRight. + * // Each turn will be 90 degrees. + * void turnLeft(); + * void turnRight(); + * + * // Clean the current cell. + * void clean(); + * }; + */ + +class Solution { + public: + void cleanRoom(Robot& robot) { + dfs(robot, 0, 0, 0, unordered_set, PairHash>()); + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; + + void dfs(Robot& robot, int i, int j, int d, + unordered_set, PairHash>&& seen) { + seen.insert({i, j}); + robot.clean(); + + // Explore clockwise: 0: ^, 1: >, 2: v, 3: < + // The order is important since the idea is always turning right. + for (int k = 0; k < 4; ++k) { + const int newD = (d + k) % 4; + const int x = i + dirs[newD][0]; + const int y = j + dirs[newD][1]; + if (!seen.contains({x, y}) && robot.move()) { + dfs(robot, x, y, newD, move(seen)); + // Go back to the previous cell. + robot.turnRight(); + robot.turnRight(); + robot.move(); + // Go back to the original direction. + robot.turnRight(); + robot.turnRight(); + } + robot.turnRight(); // Always turn the robot clockwise. + } + } +}; diff --git a/solutions/489. Robot Room Cleaner/489.java b/solutions/489. Robot Room Cleaner/489.java new file mode 100644 index 00000000000..0037fe01347 --- /dev/null +++ b/solutions/489. Robot Room Cleaner/489.java @@ -0,0 +1,49 @@ +/** + * // This is the robot's control interface. + * // You should not implement it, or speculate about its implementation + * interface Robot { + * // Returns true if the cell in front is open and robot moves into the cell. + * // Returns false if the cell in front is blocked and robot stays in the current cell. + * public boolean move(); + * + * // Robot will stay in the same cell after calling turnLeft/turnRight. + * // Each turn will be 90 degrees. + * public void turnLeft(); + * public void turnRight(); + * + * // Clean the current cell. + * public void clean(); + * } + */ + +class Solution { + public void cleanRoom(Robot robot) { + dfs(robot, 0, 0, 0, new HashSet<>()); + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private void dfs(Robot robot, int d, int i, int j, Set> seen) { + seen.add(new Pair<>(i, j)); + robot.clean(); + + // Explore clockwise: 0: ^, 1: >, 2: v, 3: < + // The order is important since the idea is always turning right. + for (int k = 0; k < 4; ++k) { + final int newD = (d + k) % 4; + final int x = i + dirs[newD][0]; + final int y = j + dirs[newD][1]; + if (!seen.contains(new Pair<>(x, y)) && robot.move()) { + dfs(robot, newD, x, y, seen); + // Go back to the previous cell. + robot.turnRight(); + robot.turnRight(); + robot.move(); + // Go back to the original direction. + robot.turnRight(); + robot.turnRight(); + } + robot.turnRight(); // Always turn the robot clockwise. + } + } +} diff --git a/solutions/49. Group Anagrams/49.cpp b/solutions/49. Group Anagrams/49.cpp new file mode 100644 index 00000000000..6de75b8548d --- /dev/null +++ b/solutions/49. Group Anagrams/49.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector> groupAnagrams(vector& strs) { + vector> ans; + unordered_map> keyToAnagrams; + + for (const string& str : strs) { + string key = str; + ranges::sort(key); + keyToAnagrams[key].push_back(str); + } + + for (const auto& [_, anagrams] : keyToAnagrams) + ans.push_back(anagrams); + + return ans; + } +}; diff --git a/solutions/49. Group Anagrams/49.java b/solutions/49. Group Anagrams/49.java new file mode 100644 index 00000000000..495252395dc --- /dev/null +++ b/solutions/49. Group Anagrams/49.java @@ -0,0 +1,14 @@ +class Solution { + public List> groupAnagrams(String[] strs) { + Map> keyToAnagrams = new HashMap<>(); + + for (final String str : strs) { + char[] chars = str.toCharArray(); + Arrays.sort(chars); + String key = String.valueOf(chars); + keyToAnagrams.computeIfAbsent(key, k -> new ArrayList<>()).add(str); + } + + return new ArrayList<>(keyToAnagrams.values()); + } +} diff --git a/solutions/49. Group Anagrams/49.py b/solutions/49. Group Anagrams/49.py new file mode 100644 index 00000000000..731f367da9b --- /dev/null +++ b/solutions/49. Group Anagrams/49.py @@ -0,0 +1,9 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + dict = collections.defaultdict(list) + + for str in strs: + key = ''.join(sorted(str)) + dict[key].append(str) + + return dict.values() diff --git a/solutions/490. The Maze/490-2.cpp b/solutions/490. The Maze/490-2.cpp new file mode 100644 index 00000000000..38b4f788efc --- /dev/null +++ b/solutions/490. The Maze/490-2.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + bool hasPath(vector>& maze, vector& start, + vector& destination) { + return dfs(maze, + vector>(maze.size(), vector(maze[0].size())), + start[0], start[1], destination); + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + bool dfs(vector>& maze, vector>&& seen, int i, int j, + const vector& destination) { + if (i == destination[0] && j == destination[1]) + return true; + if (seen[i][j]) + return false; + + seen[i][j] = true; + + for (const auto& [dx, dy] : dirs) { + int x = i; + int y = j; + while (isValid(maze, x + dx, y + dy)) { + x += dx; + y += dy; + } + if (dfs(maze, move(seen), x, y, destination)) + return true; + } + + return false; + } + + bool isValid(const vector>& maze, int x, int y) { + return 0 <= x && x < maze.size() && 0 <= y && y < maze[0].size() && + maze[x][y] == 0; + } +}; diff --git a/solutions/490. The Maze/490-2.java b/solutions/490. The Maze/490-2.java new file mode 100644 index 00000000000..96cb2df5c7a --- /dev/null +++ b/solutions/490. The Maze/490-2.java @@ -0,0 +1,34 @@ +class Solution { + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + boolean[][] seen = new boolean[maze.length][maze[0].length]; + return dfs(maze, seen, start[0], start[1], destination); + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private boolean dfs(int[][] maze, boolean[][] seen, int i, int j, int[] destination) { + if (i == destination[0] && j == destination[1]) + return true; + if (seen[i][j]) + return false; + + seen[i][j] = true; + + for (int[] dir : dirs) { + int x = i; + int y = j; + while (isValid(maze, x + dir[0], y + dir[1])) { + x += dir[0]; + y += dir[1]; + } + if (dfs(maze, seen, x, y, destination)) + return true; + } + + return false; + } + + private boolean isValid(int[][] maze, int x, int y) { + return 0 <= x && x < maze.length && 0 <= y && y < maze[0].length && maze[x][y] == 0; + } +} diff --git a/solutions/490. The Maze/490-2.py b/solutions/490. The Maze/490-2.py new file mode 100644 index 00000000000..0c0ac1a5470 --- /dev/null +++ b/solutions/490. The Maze/490-2.py @@ -0,0 +1,31 @@ +class Solution: + def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(maze) + n = len(maze[0]) + + seen = set() + + def isValid(x: int, y: int) -> bool: + return 0 <= x < m and 0 <= y < n and maze[x][y] == 0 + + def dfs(i: int, j: int) -> bool: + if [i, j] == destination: + return True + if (i, j) in seen: + return False + + seen.add((i, j)) + + for dx, dy in dirs: + x = i + y = j + while isValid(x + dx, y + dy): + x += dx + y += dy + if dfs(x, y): + return True + + return False + + return dfs(start[0], start[1]) diff --git a/solutions/490. The Maze/490.cpp b/solutions/490. The Maze/490.cpp new file mode 100644 index 00000000000..12dc7c16fa9 --- /dev/null +++ b/solutions/490. The Maze/490.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + bool hasPath(vector>& maze, vector& start, + vector& destination) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = maze.size(); + const int n = maze[0].size(); + queue> q{{{start[0], start[1]}}}; + vector> seen(m, vector(n)); + seen[start[0]][start[1]] = true; + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + int x = i; + int y = j; + while (isValid(maze, x + dx, y + dy)) { + x += dx; + y += dy; + } + if (x == destination[0] && y == destination[1]) + return true; + if (seen[x][y]) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + + return false; + } + + private: + bool isValid(const vector>& maze, int x, int y) { + return 0 <= x && x < maze.size() && 0 <= y && y < maze[0].size() && + maze[x][y] == 0; + } +}; diff --git a/solutions/490. The Maze/490.java b/solutions/490. The Maze/490.java new file mode 100644 index 00000000000..6cb65cca8e4 --- /dev/null +++ b/solutions/490. The Maze/490.java @@ -0,0 +1,35 @@ +class Solution { + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = maze.length; + final int n = maze[0].length; + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {start[0], start[1]})); + boolean[][] seen = new boolean[m][n]; + seen[start[0]][start[1]] = true; + + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + int x = i; + int y = j; + while (isValid(maze, x + dir[0], y + dir[1])) { + x += dir[0]; + y += dir[1]; + } + if (x == destination[0] && y == destination[1]) + return true; + if (seen[x][y]) + continue; + q.offer(new int[] {x, y}); + seen[x][y] = true; + } + } + + return false; + } + + private boolean isValid(int[][] maze, int x, int y) { + return 0 <= x && x < maze.length && 0 <= y && y < maze[0].length && maze[x][y] == 0; + } +} diff --git a/solutions/490. The Maze/490.py b/solutions/490. The Maze/490.py new file mode 100644 index 00000000000..0a81f5b9473 --- /dev/null +++ b/solutions/490. The Maze/490.py @@ -0,0 +1,27 @@ +class Solution: + def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(maze) + n = len(maze[0]) + q = collections.deque([(start[0], start[1])]) + seen = {(start[0], start[1])} + + def isValid(x: int, y: int) -> bool: + return 0 <= x < m and 0 <= y < n and maze[x][y] == 0 + + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + y = j + while isValid(x + dx, y + dy): + x += dx + y += dy + if [x, y] == destination: + return True + if (x, y) in seen: + continue + q.append((x, y)) + seen.add((x, y)) + + return False diff --git a/solutions/491. Increasing Subsequences/491.cpp b/solutions/491. Increasing Subsequences/491.cpp new file mode 100644 index 00000000000..2815b3dc84c --- /dev/null +++ b/solutions/491. Increasing Subsequences/491.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector> findSubsequences(vector& nums) { + vector> ans; + dfs(nums, 0, {}, ans); + return ans; + } + + private: + void dfs(const vector& nums, int s, vector&& path, + vector>& ans) { + if (path.size() > 1) + ans.push_back(path); + + unordered_set used; + + for (int i = s; i < nums.size(); ++i) { + if (used.contains(nums[i])) + continue; + if (path.empty() || nums[i] >= path.back()) { + used.insert(nums[i]); + path.push_back(nums[i]); + dfs(nums, i + 1, move(path), ans); + path.pop_back(); + } + } + } +}; diff --git a/solutions/491. Increasing Subsequences/491.java b/solutions/491. Increasing Subsequences/491.java new file mode 100644 index 00000000000..5b103dee50b --- /dev/null +++ b/solutions/491. Increasing Subsequences/491.java @@ -0,0 +1,25 @@ +class Solution { + public List> findSubsequences(int[] nums) { + List> ans = new LinkedList<>(); + dfs(nums, 0, new LinkedList<>(), ans); + return ans; + } + + private void dfs(int[] nums, int s, LinkedList path, List> ans) { + if (path.size() > 1) + ans.add(new LinkedList<>(path)); + + Set used = new HashSet<>(); + + for (int i = s; i < nums.length; ++i) { + if (used.contains(nums[i])) + continue; + if (path.isEmpty() || nums[i] >= path.getLast()) { + used.add(nums[i]); + path.addLast(nums[i]); + dfs(nums, i + 1, path, ans); + path.removeLast(); + } + } + } +} diff --git a/solutions/491. Increasing Subsequences/491.py b/solutions/491. Increasing Subsequences/491.py new file mode 100644 index 00000000000..255a1627ef7 --- /dev/null +++ b/solutions/491. Increasing Subsequences/491.py @@ -0,0 +1,19 @@ +class Solution: + def findSubsequences(self, nums: List[int]) -> List[List[int]]: + ans = [] + + def dfs(s: int, path: List[int]) -> None: + if len(path) > 1: + ans.append(path) + + used = set() + + for i in range(s, len(nums)): + if nums[i] in used: + continue + if not path or nums[i] >= path[-1]: + used.add(nums[i]) + dfs(i + 1, path + [nums[i]]) + + dfs(0, []) + return ans diff --git a/solutions/492. Construct the Rectangle/492.cpp b/solutions/492. Construct the Rectangle/492.cpp new file mode 100644 index 00000000000..f8e9ab83573 --- /dev/null +++ b/solutions/492. Construct the Rectangle/492.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + vector constructRectangle(int area) { + int width = sqrt(area); + + while (area % width) + --width; + + return {area / width, width}; + } +}; diff --git a/solutions/492. Construct the Rectangle/492.java b/solutions/492. Construct the Rectangle/492.java new file mode 100644 index 00000000000..8156f3d21bd --- /dev/null +++ b/solutions/492. Construct the Rectangle/492.java @@ -0,0 +1,10 @@ +class Solution { + public int[] constructRectangle(int area) { + int width = (int) Math.sqrt(area); + + while (area % width > 0) + --width; + + return new int[] {area / width, width}; + } +} diff --git a/solutions/493. Reverse Pairs/493-2.cpp b/solutions/493. Reverse Pairs/493-2.cpp new file mode 100644 index 00000000000..c397c0a2e13 --- /dev/null +++ b/solutions/493. Reverse Pairs/493-2.cpp @@ -0,0 +1,88 @@ +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) : n(nums.size()), tree(n * 4) { + build(nums, 0, 0, n - 1); + } + + // Adds val to nums[i]. + void add(int i, int val) { + add(0, 0, n - 1, i, val); + } + + // Returns sum(nums[i..j]). + int query(int i, int j) { + return query(0, 0, n - 1, i, j); + } + + private: + const int n; // the size of the input array + vector tree; // the segment tree + + void build(const vector& nums, int treeIndex, int lo, int hi) { + if (lo == hi) { + tree[treeIndex] = nums[lo]; + return; + } + const int mid = (lo + hi) / 2; + build(nums, 2 * treeIndex + 1, lo, mid); + build(nums, 2 * treeIndex + 2, mid + 1, hi); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + void add(int treeIndex, int lo, int hi, int i, int val) { + if (lo == hi) { + tree[treeIndex] += val; + return; + } + const int mid = (lo + hi) / 2; + if (i <= mid) + add(2 * treeIndex + 1, lo, mid, i, val); + else + add(2 * treeIndex + 2, mid + 1, hi, i, val); + tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); + } + + int query(int treeIndex, int lo, int hi, int i, int j) { + if (i <= lo && hi <= j) // [lo, hi] lies completely inside [i, j]. + return tree[treeIndex]; + if (j < lo || hi < i) // [lo, hi] lies completely outside [i, j]. + return 0; + const int mid = (lo + hi) / 2; + return merge(query(treeIndex * 2 + 1, lo, mid, i, j), + query(treeIndex * 2 + 2, mid + 1, hi, i, j)); + } + + // Merges the result of the left node and the right node. + int merge(int a, int b) const { + return a + b; + } +}; + +class Solution { + public: + int reversePairs(vector& nums) { + int ans = 0; + const unordered_map ranks = getRanks(nums); + SegmentTree tree(vector(ranks.size() + 1)); + + for (int i = nums.size() - 1; i >= 0; --i) { + const long num = nums[i]; + ans += tree.query(0, ranks.at(num) - 1); + tree.add(ranks.at(num * 2), 1); + } + + return ans; + } + + private: + unordered_map getRanks(const vector& nums) { + unordered_map ranks; + set sorted(nums.begin(), nums.end()); + for (const long num : nums) + sorted.insert(num * 2); + int rank = 0; + for (const long num : sorted) + ranks[num] = ++rank; + return ranks; + } +}; diff --git a/solutions/493. Reverse Pairs/493-3.cpp b/solutions/493. Reverse Pairs/493-3.cpp new file mode 100644 index 00000000000..3e8ecfa3c43 --- /dev/null +++ b/solutions/493. Reverse Pairs/493-3.cpp @@ -0,0 +1,95 @@ +struct SegmentTreeNode { + int lo; + int hi; + int sum; + SegmentTreeNode* left; + SegmentTreeNode* right; + SegmentTreeNode(int lo, int hi, int sum, SegmentTreeNode* left = nullptr, + SegmentTreeNode* right = nullptr) + : lo(lo), hi(hi), sum(sum), left(left), right(right) {} + ~SegmentTreeNode() { + delete left; + delete right; + left = nullptr; + right = nullptr; + } +}; + +class SegmentTree { + public: + explicit SegmentTree(const vector& nums) + : root(build(nums, 0, nums.size() - 1)) {} + + void add(int i, int val) { + add(root.get(), i, val); + } + + int query(int i, int j) const { + return query(root.get(), i, j); + } + + private: + std::unique_ptr root; + + SegmentTreeNode* build(const vector& nums, int lo, int hi) const { + if (lo == hi) + return new SegmentTreeNode(lo, hi, nums[lo]); + const int mid = (lo + hi) / 2; + auto left = build(nums, lo, mid); + auto right = build(nums, mid + 1, hi); + return new SegmentTreeNode(lo, hi, left->sum + right->sum, left, right); + } + + void add(SegmentTreeNode* root, int i, int val) { + if (root->lo == i && root->hi == i) { + root->sum += val; + return; + } + const int mid = (root->lo + root->hi) / 2; + if (i <= mid) + add(root->left, i, val); + else + add(root->right, i, val); + root->sum = root->left->sum + root->right->sum; + } + + int query(SegmentTreeNode* root, int i, int j) const { + if (root->lo == i && root->hi == j) + return root->sum; + const int mid = (root->lo + root->hi) / 2; + if (j <= mid) + return query(root->left, i, j); + if (i > mid) + return query(root->right, i, j); + return query(root->left, i, mid) + query(root->right, mid + 1, j); + } +}; + +class Solution { + public: + int reversePairs(vector& nums) { + int ans = 0; + const unordered_map ranks = getRanks(nums); + SegmentTree tree(vector(ranks.size() + 1)); + + for (int i = nums.size() - 1; i >= 0; --i) { + const long num = nums[i]; + ans += tree.query(0, ranks.at(num) - 1); + tree.add(ranks.at(num * 2), 1); + } + + return ans; + } + + private: + unordered_map getRanks(const vector& nums) { + unordered_map ranks; + set sorted(nums.begin(), nums.end()); + for (const long num : nums) + sorted.insert(num * 2); + int rank = 0; + for (const long num : sorted) + ranks[num] = ++rank; + return ranks; + } +}; diff --git a/solutions/493. Reverse Pairs/493-4.cpp b/solutions/493. Reverse Pairs/493-4.cpp new file mode 100644 index 00000000000..a815dff8233 --- /dev/null +++ b/solutions/493. Reverse Pairs/493-4.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + int reversePairs(vector& nums) { + int ans = 0; + mergeSort(nums, 0, nums.size() - 1, ans); + return ans; + } + + private: + void mergeSort(vector& nums, int l, int r, int& ans) { + if (l >= r) + return; + + const int m = (l + r) / 2; + mergeSort(nums, l, m, ans); + mergeSort(nums, m + 1, r, ans); + merge(nums, l, m, r, ans); + } + + void merge(vector& nums, int l, int m, int r, int& ans) { + const int lo = m + 1; + int hi = m + 1; // the first index s.t. nums[i] <= 2 * nums[hi] + + // For each index i in range [l, m], add hi - lo to `ans`. + for (int i = l; i <= m; ++i) { + while (hi <= r && nums[i] > 2L * nums[hi]) + ++hi; + ans += hi - lo; + } + + vector sorted(r - l + 1); + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + + while (i <= m && j <= r) + if (nums[i] < nums[j]) + sorted[k++] = nums[i++]; + else + sorted[k++] = nums[j++]; + + // Put the possible remaining left part into the sorted array. + while (i <= m) + sorted[k++] = nums[i++]; + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = nums[j++]; + + copy(sorted.begin(), sorted.end(), nums.begin() + l); + } +}; diff --git a/solutions/493. Reverse Pairs/493.cpp b/solutions/493. Reverse Pairs/493.cpp new file mode 100644 index 00000000000..17ba0869913 --- /dev/null +++ b/solutions/493. Reverse Pairs/493.cpp @@ -0,0 +1,56 @@ +class FenwickTree { + public: + FenwickTree(int n) : sums(n + 1) {} + + void add(int i, int delta) { + while (i < sums.size()) { + sums[i] += delta; + i += lowbit(i); + } + } + + int get(int i) const { + int sum = 0; + while (i > 0) { + sum += sums[i]; + i -= lowbit(i); + } + return sum; + } + + private: + vector sums; + + static inline int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + int reversePairs(vector& nums) { + int ans = 0; + const unordered_map ranks = getRanks(nums); + FenwickTree tree(ranks.size()); + + for (int i = nums.size() - 1; i >= 0; --i) { + const long num = nums[i]; + ans += tree.get(ranks.at(num) - 1); + tree.add(ranks.at(num * 2), 1); + } + + return ans; + } + + private: + unordered_map getRanks(const vector& nums) { + unordered_map ranks; + set sorted(nums.begin(), nums.end()); + for (const long num : nums) + sorted.insert(num * 2); + int rank = 0; + for (const long num : sorted) + ranks[num] = ++rank; + return ranks; + } +}; diff --git a/solutions/494. Target Sum/494-2.cpp b/solutions/494. Target Sum/494-2.cpp new file mode 100644 index 00000000000..6cbe88207eb --- /dev/null +++ b/solutions/494. Target Sum/494-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int findTargetSumWays(vector& nums, int target) { + const int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum < abs(target) || (sum + target) % 2 == 1) + return 0; + return knapsack(nums, (sum + target) / 2); + } + + private: + int knapsack(const vector& nums, int target) { + // dp[i] := the number of ways to sum to i by nums so far + vector dp(target + 1); + dp[0] = 1; + + for (const int num : nums) + for (int i = target; i >= num; --i) + dp[i] += dp[i - num]; + + return dp[target]; + } +}; diff --git a/solutions/494. Target Sum/494-2.java b/solutions/494. Target Sum/494-2.java new file mode 100644 index 00000000000..b61358e8601 --- /dev/null +++ b/solutions/494. Target Sum/494-2.java @@ -0,0 +1,20 @@ +class Solution { + public int findTargetSumWays(int[] nums, int target) { + final int sum = Arrays.stream(nums).sum(); + if (sum < Math.abs(target) || (sum + target) % 2 == 1) + return 0; + return knapsack(nums, (sum + target) / 2); + } + + private int knapsack(int[] nums, int target) { + // dp[i] := the number of ways to sum to i by nums so far + int[] dp = new int[target + 1]; + dp[0] = 1; + + for (final int num : nums) + for (int i = target; i >= num; --i) + dp[i] += dp[i - num]; + + return dp[target]; + } +} diff --git a/solutions/494. Target Sum/494-2.py b/solutions/494. Target Sum/494-2.py new file mode 100644 index 00000000000..13f91352c21 --- /dev/null +++ b/solutions/494. Target Sum/494-2.py @@ -0,0 +1,18 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + summ = sum(nums) + if summ < abs(target) or (summ + target) % 2 == 1: + return 0 + + def knapsack(nums: List[int], target: int) -> int: + # dp[i] := the number of ways to sum to i by nums so far + dp = [0] * (target + 1) + dp[0] = 1 + + for num in nums: + for i in range(target, num - 1, -1): + dp[i] += dp[i - num] + + return dp[target] + + return knapsack(nums, (summ + target) // 2) diff --git a/solutions/494. Target Sum/494.cpp b/solutions/494. Target Sum/494.cpp new file mode 100644 index 00000000000..689c5e210d0 --- /dev/null +++ b/solutions/494. Target Sum/494.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int findTargetSumWays(vector& nums, int target) { + const int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum < abs(target) || (sum + target) % 2 == 1) + return 0; + return knapsack(nums, (sum + target) / 2); + } + + private: + int knapsack(const vector& nums, int target) { + const int n = nums.size(); + // dp[i][j] := the number of ways to sum to j by nums[0..i) + vector> dp(n + 1, vector(target + 1)); + dp[0][0] = 1; + + for (int i = 1; i <= n; ++i) { + const int num = nums[i - 1]; + for (int j = 0; j <= target; ++j) + if (j < num) + dp[i][j] = dp[i - 1][j]; + else + dp[i][j] = dp[i - 1][j] + dp[i - 1][j - num]; + } + + return dp[n][target]; + } +}; diff --git a/solutions/494. Target Sum/494.java b/solutions/494. Target Sum/494.java new file mode 100644 index 00000000000..ec3e4e8abe5 --- /dev/null +++ b/solutions/494. Target Sum/494.java @@ -0,0 +1,26 @@ +class Solution { + public int findTargetSumWays(int[] nums, int target) { + final int sum = Arrays.stream(nums).sum(); + if (sum < Math.abs(target) || (sum + target) % 2 == 1) + return 0; + return knapsack(nums, (sum + target) / 2); + } + + private int knapsack(int[] nums, int target) { + final int n = nums.length; + // dp[i][j] := the number of ways to sum to j by nums[0..i) + int[][] dp = new int[n + 1][target + 1]; + dp[0][0] = 1; + + for (int i = 1; i <= n; ++i) { + final int num = nums[i - 1]; + for (int j = 0; j <= target; ++j) + if (j < num) + dp[i][j] = dp[i - 1][j]; + else + dp[i][j] = dp[i - 1][j] + dp[i - 1][j - num]; + } + + return dp[n][target]; + } +} diff --git a/solutions/494. Target Sum/494.py b/solutions/494. Target Sum/494.py new file mode 100644 index 00000000000..a8805c52344 --- /dev/null +++ b/solutions/494. Target Sum/494.py @@ -0,0 +1,17 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + summ = sum(nums) + if summ < abs(target) or (summ + target) % 2 == 1: + return 0 + + def knapsack(target: int) -> int: + # dp[i] := the number of ways to sum to i by nums so far + dp = [1] + [0] * summ + + for num in nums: + for j in range(summ, num - 1, -1): + dp[j] += dp[j - num] + + return dp[target] + + return knapsack((summ + target) // 2) diff --git a/solutions/495. Teemo Attacking/495.cpp b/solutions/495. Teemo Attacking/495.cpp new file mode 100644 index 00000000000..cd81766a6c0 --- /dev/null +++ b/solutions/495. Teemo Attacking/495.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int findPoisonedDuration(vector& timeSeries, int duration) { + if (duration == 0) + return 0; + + int ans = 0; + + for (int i = 0; i + 1 < timeSeries.size(); ++i) + ans += min(timeSeries[i + 1] - timeSeries[i], duration); + + return ans + duration; + } +}; diff --git a/solutions/495. Teemo Attacking/495.java b/solutions/495. Teemo Attacking/495.java new file mode 100644 index 00000000000..d97b834a39a --- /dev/null +++ b/solutions/495. Teemo Attacking/495.java @@ -0,0 +1,13 @@ +class Solution { + public int findPoisonedDuration(int[] timeSeries, int duration) { + if (duration == 0) + return 0; + + int ans = 0; + + for (int i = 0; i + 1 < timeSeries.length; ++i) + ans += Math.min(timeSeries[i + 1] - timeSeries[i], duration); + + return ans + duration; + } +} diff --git a/solutions/495. Teemo Attacking/495.py b/solutions/495. Teemo Attacking/495.py new file mode 100644 index 00000000000..ff74cf836e3 --- /dev/null +++ b/solutions/495. Teemo Attacking/495.py @@ -0,0 +1,11 @@ +class Solution: + def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: + if duration == 0: + return 0 + + ans = 0 + + for i in range(0, len(timeSeries) - 1): + ans += min(timeSeries[i + 1] - timeSeries[i], duration) + + return ans + duration diff --git a/solutions/496. Next Greater Element I/496.cpp b/solutions/496. Next Greater Element I/496.cpp new file mode 100644 index 00000000000..d9f362e1b6a --- /dev/null +++ b/solutions/496. Next Greater Element I/496.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + vector ans; + unordered_map numToNextGreater; + stack stack; // a decreasing stack + + for (const int num : nums2) { + while (!stack.empty() && stack.top() < num) + numToNextGreater[stack.top()] = num, stack.pop(); + stack.push(num); + } + + for (const int num : nums1) + if (const auto it = numToNextGreater.find(num); + it != numToNextGreater.cend()) + ans.push_back(it->second); + else + ans.push_back(-1); + + return ans; + } +}; diff --git a/solutions/496. Next Greater Element I/496.java b/solutions/496. Next Greater Element I/496.java new file mode 100644 index 00000000000..c2e13c9d478 --- /dev/null +++ b/solutions/496. Next Greater Element I/496.java @@ -0,0 +1,21 @@ +class Solution { + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + List ans = new ArrayList<>(); + Map numToNextGreater = new HashMap<>(); + Deque stack = new ArrayDeque<>(); // a decreasing stack + + for (final int num : nums2) { + while (!stack.isEmpty() && stack.peek() < num) + numToNextGreater.put(stack.pop(), num); + stack.push(num); + } + + for (final int num : nums1) + if (numToNextGreater.containsKey(num)) + ans.add(numToNextGreater.get(num)); + else + ans.add(-1); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/496. Next Greater Element I/496.py b/solutions/496. Next Greater Element I/496.py new file mode 100644 index 00000000000..19fcbd7efc9 --- /dev/null +++ b/solutions/496. Next Greater Element I/496.py @@ -0,0 +1,11 @@ +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + numToNextGreater = {} + stack = [] # a decreasing stack + + for num in nums2: + while stack and stack[-1] < num: + numToNextGreater[stack.pop()] = num + stack.append(num) + + return [numToNextGreater.get(num, -1) for num in nums1] diff --git a/solutions/497. Random Point in Non-overlapping Rectangles/497.cpp b/solutions/497. Random Point in Non-overlapping Rectangles/497.cpp new file mode 100644 index 00000000000..8c76789e04b --- /dev/null +++ b/solutions/497. Random Point in Non-overlapping Rectangles/497.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + Solution(vector>& rects) : rects(move(rects)) { + for (const vector& r : this->rects) + areas.push_back(getArea(r)); + partial_sum(areas.begin(), areas.end(), areas.begin()); + } + + vector pick() { + const int target = rand() % areas.back(); + const int index = ranges::upper_bound(areas, target) - areas.begin(); + const vector& r = rects[index]; + return {rand() % (r[2] - r[0] + 1) + r[0], + rand() % (r[3] - r[1] + 1) + r[1]}; + } + + private: + const vector> rects; + vector areas; + + int getArea(const vector& r) { + return (r[2] - r[0] + 1) * (r[3] - r[1] + 1); + } +}; diff --git a/solutions/497. Random Point in Non-overlapping Rectangles/497.java b/solutions/497. Random Point in Non-overlapping Rectangles/497.java new file mode 100644 index 00000000000..dd6647c22ed --- /dev/null +++ b/solutions/497. Random Point in Non-overlapping Rectangles/497.java @@ -0,0 +1,31 @@ +class Solution { + public Solution(int[][] rects) { + this.rects = rects; + areas = new int[rects.length]; + for (int i = 0; i < rects.length; ++i) + areas[i] = getArea(rects[i]) + (i > 0 ? areas[i - 1] : 0); + } + + public int[] pick() { + final int target = rand.nextInt(areas[areas.length - 1]); + final int index = firstGreater(areas, target); + final int[] r = rects[index]; + return new int[] { + rand.nextInt(r[2] - r[0] + 1) + r[0], + rand.nextInt(r[3] - r[1] + 1) + r[1], + }; + } + + private int[][] rects; + private int[] areas; + private Random rand = new Random(); + + private int getArea(int[] r) { + return (r[2] - r[0] + 1) * (r[3] - r[1] + 1); + } + + private int firstGreater(int[] A, int target) { + final int i = Arrays.binarySearch(A, target + 1); + return i < 0 ? -i - 1 : i; + } +} diff --git a/solutions/497. Random Point in Non-overlapping Rectangles/497.py b/solutions/497. Random Point in Non-overlapping Rectangles/497.py new file mode 100644 index 00000000000..b6f927dc564 --- /dev/null +++ b/solutions/497. Random Point in Non-overlapping Rectangles/497.py @@ -0,0 +1,10 @@ +class Solution: + def __init__(self, rects: List[List[int]]): + self.rects = rects + self.areas = list(itertools.accumulate( + [(x2 - x1 + 1) * (y2 - y1 + 1) for x1, y1, x2, y2 in rects])) + + def pick(self) -> List[int]: + index = bisect_right(self.areas, random.randint(0, self.areas[-1] - 1)) + x1, y1, x2, y2 = self.rects[index] + return [random.randint(x1, x2), random.randint(y1, y2)] diff --git a/solutions/498. Diagonal Traverse/498.cpp b/solutions/498. Diagonal Traverse/498.cpp new file mode 100644 index 00000000000..2e141f3b32a --- /dev/null +++ b/solutions/498. Diagonal Traverse/498.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector findDiagonalOrder(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + vector ans(m * n); + int d = 1; // left-bottom -> right-top + int row = 0; + int col = 0; + + for (int i = 0; i < m * n; ++i) { + ans[i] = matrix[row][col]; + row -= d; + col += d; + // out-of-bounds + if (row == m) + row = m - 1, col += 2, d = -d; + if (col == n) + col = n - 1, row += 2, d = -d; + if (row < 0) + row = 0, d = -d; + if (col < 0) + col = 0, d = -d; + } + + return ans; + } +}; diff --git a/solutions/498. Diagonal Traverse/498.java b/solutions/498. Diagonal Traverse/498.java new file mode 100644 index 00000000000..a214b0f08a9 --- /dev/null +++ b/solutions/498. Diagonal Traverse/498.java @@ -0,0 +1,37 @@ +class Solution { + public int[] findDiagonalOrder(int[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + int[] ans = new int[m * n]; + int d = 1; // left-bottom -> right-top + int row = 0; + int col = 0; + + for (int i = 0; i < m * n; ++i) { + ans[i] = matrix[row][col]; + row -= d; + col += d; + // out-of-bounds + if (row == m) { + row = m - 1; + col += 2; + d = -d; + } + if (col == n) { + col = n - 1; + row += 2; + d = -d; + } + if (row < 0) { + row = 0; + d = -d; + } + if (col < 0) { + col = 0; + d = -d; + } + } + + return ans; + } +} diff --git a/solutions/499. The Maze III/499.cpp b/solutions/499. The Maze III/499.cpp new file mode 100644 index 00000000000..f693fc9f5b7 --- /dev/null +++ b/solutions/499. The Maze III/499.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + string findShortestWay(vector>& maze, vector& ball, + vector& hole) { + string ans = "impossible"; + dfs(maze, ball[0], ball[1], hole, 0, 0, 0, INT_MAX, "", ans); + return ans; + } + + private: + void dfs(vector>& maze, int i, int j, const vector& hole, + int dx, int dy, int steps, int&& minSteps, string&& path, + string& ans) { + if (steps >= minSteps) + return; + + if (dx != 0 || dy != 0) { // Both are zeros for the initial ball position. + while (i + dx >= 0 && i + dx < maze.size() && j + dy >= 0 && + j + dy < maze[0].size() && maze[i + dx][j + dy] != 1) { + i += dx; + j += dy; + ++steps; + if (i == hole[0] && j == hole[1] && steps < minSteps) { + minSteps = steps; + ans = path; + } + } + } + + if (maze[i][j] == 0 || steps + 2 < maze[i][j]) { + maze[i][j] = steps + 2; // +2 because maze[i][j] == 0 || 1. + if (dx == 0) + dfs(maze, i, j, hole, 1, 0, steps, move(minSteps), path + "d", ans); + if (dy == 0) + dfs(maze, i, j, hole, 0, -1, steps, move(minSteps), path + "l", ans); + if (dy == 0) + dfs(maze, i, j, hole, 0, 1, steps, move(minSteps), path + "r", ans); + if (dx == 0) + dfs(maze, i, j, hole, -1, 0, steps, move(minSteps), path + "u", ans); + } + } +}; diff --git a/solutions/499. The Maze III/499.java b/solutions/499. The Maze III/499.java new file mode 100644 index 00000000000..c4cda0ca746 --- /dev/null +++ b/solutions/499. The Maze III/499.java @@ -0,0 +1,40 @@ +class Solution { + public String findShortestWay(int[][] maze, int[] ball, int[] hole) { + dfs(maze, ball[0], ball[1], hole, 0, 0, 0, ""); + return ans; + } + + private String ans = "impossible"; + private int minSteps = Integer.MAX_VALUE; + + private void dfs(int[][] maze, int i, int j, int[] hole, int dx, int dy, int steps, + final String path) { + if (steps >= minSteps) + return; + + if (dx != 0 || dy != 0) { // Both are zeros for the initial ball position. + while (i + dx >= 0 && i + dx < maze.length && j + dy >= 0 && j + dy < maze[0].length && + maze[i + dx][j + dy] != 1) { + i += dx; + j += dy; + ++steps; + if (i == hole[0] && j == hole[1] && steps < minSteps) { + minSteps = steps; + ans = path; + } + } + } + + if (maze[i][j] == 0 || steps + 2 < maze[i][j]) { + maze[i][j] = steps + 2; // +2 because maze[i][j] == 0 || 1. + if (dx == 0) + dfs(maze, i, j, hole, 1, 0, steps, path + "d"); + if (dy == 0) + dfs(maze, i, j, hole, 0, -1, steps, path + "l"); + if (dy == 0) + dfs(maze, i, j, hole, 0, 1, steps, path + "r"); + if (dx == 0) + dfs(maze, i, j, hole, -1, 0, steps, path + "u"); + } + } +} diff --git a/solutions/499. The Maze III/499.py b/solutions/499. The Maze III/499.py new file mode 100644 index 00000000000..40a2949110a --- /dev/null +++ b/solutions/499. The Maze III/499.py @@ -0,0 +1,34 @@ +class Solution: + def findShortestWay(self, maze: List[List[int]], ball: List[int], hole: List[int]) -> str: + ans = "impossible" + minSteps = math.inf + + def dfs(i: int, j: int, dx: int, dy: int, steps: int, path: str): + nonlocal ans + nonlocal minSteps + if steps >= minSteps: + return + + if dx != 0 or dy != 0: # Both are zeros for the initial ball position. + while 0 <= i + dx < len(maze) and 0 <= j + dy < len(maze[0]) \ + and maze[i + dx][j + dy] != 1: + i += dx + j += dy + steps += 1 + if i == hole[0] and j == hole[1] and steps < minSteps: + minSteps = steps + ans = path + + if maze[i][j] == 0 or steps + 2 < maze[i][j]: + maze[i][j] = steps + 2 # +2 because maze[i][j] == 0 || 1. + if dx == 0: + dfs(i, j, 1, 0, steps, path + 'd') + if dy == 0: + dfs(i, j, 0, -1, steps, path + 'l') + if dy == 0: + dfs(i, j, 0, 1, steps, path + 'r') + if dx == 0: + dfs(i, j, -1, 0, steps, path + 'u') + + dfs(ball[0], ball[1], 0, 0, 0, '') + return ans diff --git a/solutions/5. Longest Palindromic Substring/5-2.cpp b/solutions/5. Longest Palindromic Substring/5-2.cpp new file mode 100644 index 00000000000..c67814f8e53 --- /dev/null +++ b/solutions/5. Longest Palindromic Substring/5-2.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + string longestPalindrome(string s) { + // '@' and '$' signs serve as sentinels appended to each end to avoid bounds + // checking. + const string& t = join('@' + s + '$', '#'); + const int n = t.length(); + // t[i - maxExtends[i]..i) == + // t[i + 1..i + maxExtends[i]] + vector maxExtends(n); + int center = 0; + + for (int i = 1; i < n - 1; ++i) { + const int rightBoundary = center + maxExtends[center]; + const int mirrorIndex = center - (i - center); + maxExtends[i] = + rightBoundary > i && min(rightBoundary - i, maxExtends[mirrorIndex]); + + // Attempt to expand the palindrome centered at i. + while (t[i + 1 + maxExtends[i]] == t[i - 1 - maxExtends[i]]) + ++maxExtends[i]; + + // If a palindrome centered at i expand past `rightBoundary`, adjust + // center based on expanded palindrome. + if (i + maxExtends[i] > rightBoundary) + center = i; + } + + // Find `maxExtend` and `bestCenter`. + int maxExtend = 0; + int bestCenter = -1; + + for (int i = 0; i < n; ++i) + if (maxExtends[i] > maxExtend) { + maxExtend = maxExtends[i]; + bestCenter = i; + } + + const int l = (bestCenter - maxExtend) / 2; + const int r = (bestCenter + maxExtend) / 2; + return s.substr(l, r - l); + } + + private: + string join(const string& s, char c) { + string joined; + for (int i = 0; i < s.length(); ++i) { + joined += s[i]; + if (i != s.length() - 1) + joined += c; + } + return joined; + } +}; diff --git a/solutions/5. Longest Palindromic Substring/5-2.java b/solutions/5. Longest Palindromic Substring/5-2.java new file mode 100644 index 00000000000..909c3e97526 --- /dev/null +++ b/solutions/5. Longest Palindromic Substring/5-2.java @@ -0,0 +1,50 @@ +class Solution { + public String longestPalindrome(String s) { + // '@' and '$' signs serve as sentinels appended to each end to avoid bounds + // checking. + final String t = join('@' + s + '$', '#'); + final int n = t.length(); + // t[i - maxExtends[i]..i) == + // t[i + 1..i + maxExtends[i]] + int[] maxExtends = new int[n]; + int center = 0; + + for (int i = 1; i < n - 1; ++i) { + final int rightBoundary = center + maxExtends[center]; + final int mirrorIndex = center - (i - center); + maxExtends[i] = + rightBoundary > i && Math.min(rightBoundary - i, maxExtends[mirrorIndex]) > 0 ? 1 : 0; + + // Attempt to expand the palindrome centered at i. + while (t.charAt(i + 1 + maxExtends[i]) == t.charAt(i - 1 - maxExtends[i])) + ++maxExtends[i]; + + // If a palindrome centered at i expand past `rightBoundary`, adjust + // center based on expanded palindrome. + if (i + maxExtends[i] > rightBoundary) + center = i; + } + + // Find `maxExtend` and `bestCenter`. + int maxExtend = 0; + int bestCenter = -1; + + for (int i = 0; i < n; ++i) + if (maxExtends[i] > maxExtend) { + maxExtend = maxExtends[i]; + bestCenter = i; + } + + return s.substring((bestCenter - maxExtend) / 2, (bestCenter + maxExtend) / 2); + } + + private String join(final String s, char c) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); ++i) { + sb.append(s.charAt(i)); + if (i != s.length() - 1) + sb.append(c); + } + return sb.toString(); + } +} diff --git a/solutions/5. Longest Palindromic Substring/5-2.py b/solutions/5. Longest Palindromic Substring/5-2.py new file mode 100644 index 00000000000..d43f8e2c55a --- /dev/null +++ b/solutions/5. Longest Palindromic Substring/5-2.py @@ -0,0 +1,30 @@ +class Solution: + def longestPalindrome(self, s: str) -> str: + # '@' and '$' signs serve as sentinels appended to each end to avoid bounds + # checking. + t = '#'.join('@' + s + '$') + n = len(t) + # t[i - maxExtends[i]..i) == + # t[i + 1..i + maxExtends[i]] + maxExtends = [0] * n + center = 0 + + for i in range(1, n - 1): + rightBoundary = center + maxExtends[center] + mirrorIndex = center - (i - center) + maxExtends[i] = rightBoundary > i and \ + min(rightBoundary - i, maxExtends[mirrorIndex]) + + # Attempt to expand the palindrome centered at i. + while t[i + 1 + maxExtends[i]] == t[i - 1 - maxExtends[i]]: + maxExtends[i] += 1 + + # If a palindrome centered at i expand past `rightBoundary`, adjust + # center based on expanded palindrome. + if i + maxExtends[i] > rightBoundary: + center = i + + # Find `maxExtend` and `bestCenter`. + maxExtend, bestCenter = max((extend, i) + for i, extend in enumerate(maxExtends)) + return s[(bestCenter - maxExtend) // 2:(bestCenter + maxExtend) // 2] diff --git a/solutions/5. Longest Palindromic Substring/5.cpp b/solutions/5. Longest Palindromic Substring/5.cpp new file mode 100644 index 00000000000..eac6b54487e --- /dev/null +++ b/solutions/5. Longest Palindromic Substring/5.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + string longestPalindrome(string s) { + if (s.empty()) + return ""; + + // (start, end) indices of the longest palindrome in s + pair indices{0, 0}; + + for (int i = 0; i < s.length(); ++i) { + const auto [l1, r1] = extend(s, i, i); + if (r1 - l1 > indices.second - indices.first) + indices = {l1, r1}; + if (i + 1 < s.length() && s[i] == s[i + 1]) { + const auto [l2, r2] = extend(s, i, i + 1); + if (r2 - l2 > indices.second - indices.first) + indices = {l2, r2}; + } + } + + return s.substr(indices.first, indices.second - indices.first + 1); + } + + private: + // Returns the (start, end) indices of the longest palindrome extended from + // the substring s[i..j]. + pair extend(const string& s, int i, int j) { + for (; i >= 0 && j < s.length(); --i, ++j) + if (s[i] != s[j]) + break; + return {i + 1, j - 1}; + } +}; diff --git a/solutions/5. Longest Palindromic Substring/5.java b/solutions/5. Longest Palindromic Substring/5.java new file mode 100644 index 00000000000..d93a07e6228 --- /dev/null +++ b/solutions/5. Longest Palindromic Substring/5.java @@ -0,0 +1,31 @@ +class Solution { + public String longestPalindrome(String s) { + if (s.isEmpty()) + return ""; + + // (start, end) indices of the longest palindrome in s + int[] indices = {0, 0}; + + for (int i = 0; i < s.length(); ++i) { + int[] indices1 = extend(s, i, i); + if (indices1[1] - indices1[0] > indices[1] - indices[0]) + indices = indices1; + if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) { + int[] indices2 = extend(s, i, i + 1); + if (indices2[1] - indices2[0] > indices[1] - indices[0]) + indices = indices2; + } + } + + return s.substring(indices[0], indices[1] + 1); + } + + // Returns the (start, end) indices of the longest palindrome extended from + // the substring s[i..j]. + private int[] extend(final String s, int i, int j) { + for (; i >= 0 && j < s.length(); --i, ++j) + if (s.charAt(i) != s.charAt(j)) + break; + return new int[] {i + 1, j - 1}; + } +} diff --git a/solutions/5. Longest Palindromic Substring/5.py b/solutions/5. Longest Palindromic Substring/5.py new file mode 100644 index 00000000000..da0fc0cee00 --- /dev/null +++ b/solutions/5. Longest Palindromic Substring/5.py @@ -0,0 +1,30 @@ +class Solution: + def longestPalindrome(self, s: str) -> str: + if not s: + return '' + + # (start, end) indices of the longest palindrome in s + indices = [0, 0] + + def extend(s: str, i: int, j: int) -> Tuple[int, int]: + """ + Returns the (start, end) indices of the longest palindrome extended from + the substring s[i..j]. + """ + while i >= 0 and j < len(s): + if s[i] != s[j]: + break + i -= 1 + j += 1 + return i + 1, j - 1 + + for i in range(len(s)): + l1, r1 = extend(s, i, i) + if r1 - l1 > indices[1] - indices[0]: + indices = l1, r1 + if i + 1 < len(s) and s[i] == s[i + 1]: + l2, r2 = extend(s, i, i + 1) + if r2 - l2 > indices[1] - indices[0]: + indices = l2, r2 + + return s[indices[0]:indices[1] + 1] diff --git a/solutions/50. Pow(x, n)/50.cpp b/solutions/50. Pow(x, n)/50.cpp new file mode 100644 index 00000000000..7f93fd3ba4a --- /dev/null +++ b/solutions/50. Pow(x, n)/50.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + double myPow(double x, long n) { + if (n == 0) + return 1; + if (n < 0) + return 1 / myPow(x, -n); + if (n % 2 == 1) + return x * myPow(x, n - 1); + return myPow(x * x, n / 2); + } +}; diff --git a/solutions/50. Pow(x, n)/50.java b/solutions/50. Pow(x, n)/50.java new file mode 100644 index 00000000000..962bc875ad7 --- /dev/null +++ b/solutions/50. Pow(x, n)/50.java @@ -0,0 +1,11 @@ +class Solution { + public double myPow(double x, long n) { + if (n == 0) + return 1; + if (n < 0) + return 1 / myPow(x, -n); + if (n % 2 == 1) + return x * myPow(x, n - 1); + return myPow(x * x, n / 2); + } +} diff --git a/solutions/50. Pow(x, n)/50.py b/solutions/50. Pow(x, n)/50.py new file mode 100644 index 00000000000..eed0d448f61 --- /dev/null +++ b/solutions/50. Pow(x, n)/50.py @@ -0,0 +1,9 @@ +class Solution: + def myPow(self, x: float, n: int) -> float: + if n == 0: + return 1 + if n < 0: + return 1 / self.myPow(x, -n) + if n % 2 == 1: + return x * self.myPow(x, n - 1) + return self.myPow(x * x, n // 2) diff --git a/solutions/500. Keyboard Row/500.cpp b/solutions/500. Keyboard Row/500.cpp new file mode 100644 index 00000000000..53c187a1c35 --- /dev/null +++ b/solutions/500. Keyboard Row/500.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector findWords(vector& words) { + vector ans; + const vector rows{2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, + 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3}; + + for (const string& word : words) { + string lowerWord = word; + ranges::transform(lowerWord, lowerWord.begin(), ::tolower); + const int row = rows[lowerWord[0] - 'a']; + const bool isValid = ranges::all_of( + lowerWord, [&](int c) { return rows[c - 'a'] == row; }); + if (isValid) + ans.push_back(word); + } + + return ans; + } +}; diff --git a/solutions/500. Keyboard Row/500.java b/solutions/500. Keyboard Row/500.java new file mode 100644 index 00000000000..a76e8b60490 --- /dev/null +++ b/solutions/500. Keyboard Row/500.java @@ -0,0 +1,17 @@ +class Solution { + public String[] findWords(String[] words) { + List ans = new ArrayList<>(); + final int[] rows = {2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, + 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3}; + + for (final String word : words) { + final String lowerWord = word.toLowerCase(); + final int row = rows[lowerWord.charAt(0) - 'a']; + final boolean isValid = lowerWord.chars().allMatch(c -> rows[c - 'a'] == row); + if (isValid) + ans.add(word); + } + + return ans.toArray(new String[0]); + } +} diff --git a/solutions/500. Keyboard Row/500.py b/solutions/500. Keyboard Row/500.py new file mode 100644 index 00000000000..1309cce959b --- /dev/null +++ b/solutions/500. Keyboard Row/500.py @@ -0,0 +1,11 @@ +class Solution: + def findWords(self, words: List[str]) -> List[str]: + ans = [] + rows = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')] + + for word in words: + lowerWord = set(word.lower()) + if any(lowerWord <= row for row in rows): + ans.append(word) + + return ans diff --git a/solutions/501. Find Mode in Binary Search Tree/501.cpp b/solutions/501. Find Mode in Binary Search Tree/501.cpp new file mode 100644 index 00000000000..329a15585f7 --- /dev/null +++ b/solutions/501. Find Mode in Binary Search Tree/501.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + vector findMode(TreeNode* root) { + vector ans; + int count = 0; + int maxCount = 0; + + inorder(root, count, maxCount, ans); + return ans; + } + + private: + TreeNode* pred = nullptr; + + void inorder(TreeNode* root, int& count, int& maxCount, vector& ans) { + if (root == nullptr) + return; + + inorder(root->left, count, maxCount, ans); + updateCount(root, count, maxCount, ans); + inorder(root->right, count, maxCount, ans); + } + + void updateCount(TreeNode* root, int& count, int& maxCount, + vector& ans) { + if (pred && pred->val == root->val) + ++count; + else + count = 1; + + if (count > maxCount) { + maxCount = count; + ans = {root->val}; + } else if (count == maxCount) { + ans.push_back(root->val); + } + + pred = root; + } +}; diff --git a/solutions/501. Find Mode in Binary Search Tree/501.java b/solutions/501. Find Mode in Binary Search Tree/501.java new file mode 100644 index 00000000000..095eb62814b --- /dev/null +++ b/solutions/501. Find Mode in Binary Search Tree/501.java @@ -0,0 +1,39 @@ +class Solution { + public int[] findMode(TreeNode root) { + List ans = new ArrayList<>(); + // count[0] := currCount + // count[1] := maxCount + int[] count = new int[2]; + + inorder(root, count, ans); + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private TreeNode pred = null; + + private void inorder(TreeNode root, int[] count, List ans) { + if (root == null) + return; + + inorder(root.left, count, ans); + updateCount(root, count, ans); + inorder(root.right, count, ans); + } + + private void updateCount(TreeNode root, int[] count, List ans) { + if (pred != null && pred.val == root.val) + ++count[0]; + else + count[0] = 1; + + if (count[0] > count[1]) { + count[1] = count[0]; + ans.clear(); + ans.add(root.val); + } else if (count[0] == count[1]) { + ans.add(root.val); + } + + pred = root; + } +} diff --git a/solutions/501. Find Mode in Binary Search Tree/501.py b/solutions/501. Find Mode in Binary Search Tree/501.py new file mode 100644 index 00000000000..870dff774f5 --- /dev/null +++ b/solutions/501. Find Mode in Binary Search Tree/501.py @@ -0,0 +1,31 @@ +class Solution: + def findMode(self, root: Optional[TreeNode]) -> List[int]: + self.ans = [] + self.pred = None + self.count = 0 + self.maxCount = 0 + + def updateCount(root: Optional[TreeNode]) -> None: + if self.pred and self.pred.val == root.val: + self.count += 1 + else: + self.count = 1 + + if self.count > self.maxCount: + self.maxCount = self.count + self.ans = [root.val] + elif self.count == self.maxCount: + self.ans.append(root.val) + + self.pred = root + + def inorder(root: Optional[TreeNode]) -> None: + if not root: + return + + inorder(root.left) + updateCount(root) + inorder(root.right) + + inorder(root) + return self.ans diff --git a/solutions/502. IPO/502.cpp b/solutions/502. IPO/502.cpp new file mode 100644 index 00000000000..f6029f78a94 --- /dev/null +++ b/solutions/502. IPO/502.cpp @@ -0,0 +1,29 @@ +struct T { + int pro; + int cap; + T(int pro, int cap) : pro(pro), cap(cap) {} +}; + +class Solution { + public: + int findMaximizedCapital(int k, int W, vector& Profits, + vector& Capital) { + auto compareC = [](const T& a, const T& b) { return a.cap > b.cap; }; + auto compareP = [](const T& a, const T& b) { return a.pro < b.pro; }; + priority_queue, decltype(compareC)> minHeap(compareC); + priority_queue, decltype(compareP)> maxHeap(compareP); + + for (int i = 0; i < Capital.size(); ++i) + minHeap.emplace(Profits[i], Capital[i]); + + while (k--) { + while (!minHeap.empty() && minHeap.top().cap <= W) + maxHeap.push(minHeap.top()), minHeap.pop(); + if (maxHeap.empty()) + break; + W += maxHeap.top().pro, maxHeap.pop(); + } + + return W; + } +}; diff --git a/solutions/502. IPO/502.java b/solutions/502. IPO/502.java new file mode 100644 index 00000000000..9daacecf8bb --- /dev/null +++ b/solutions/502. IPO/502.java @@ -0,0 +1,28 @@ +class T { + public int pro; + public int cap; + public T(int pro, int cap) { + this.pro = pro; + this.cap = cap; + } +} + +class Solution { + public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) { + Queue minHeap = new PriorityQueue<>((a, b) -> a.cap - b.cap); + Queue maxHeap = new PriorityQueue<>((a, b) -> b.pro - a.pro); + + for (int i = 0; i < Capital.length; ++i) + minHeap.offer(new T(Profits[i], Capital[i])); + + while (k-- > 0) { + while (!minHeap.isEmpty() && minHeap.peek().cap <= W) + maxHeap.offer(minHeap.poll()); + if (maxHeap.isEmpty()) + break; + W += maxHeap.poll().pro; + } + + return W; + } +} diff --git a/solutions/503. Next Greater Element II/503.cpp b/solutions/503. Next Greater Element II/503.cpp new file mode 100644 index 00000000000..f2d5bc1d555 --- /dev/null +++ b/solutions/503. Next Greater Element II/503.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector nextGreaterElements(vector& nums) { + const int n = nums.size(); + vector ans(n, -1); + stack stack; // a decreasing stack storing indices + + for (int i = 0; i < n * 2; ++i) { + const int num = nums[i % n]; + while (!stack.empty() && nums[stack.top()] < num) + ans[stack.top()] = num, stack.pop(); + if (i < n) + stack.push(i); + } + + return ans; + } +}; diff --git a/solutions/503. Next Greater Element II/503.java b/solutions/503. Next Greater Element II/503.java new file mode 100644 index 00000000000..963bcc56308 --- /dev/null +++ b/solutions/503. Next Greater Element II/503.java @@ -0,0 +1,18 @@ +class Solution { + public int[] nextGreaterElements(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + Deque stack = new ArrayDeque<>(); // a decreasing stack storing indices + + for (int i = 0; i < n * 2; ++i) { + final int num = nums[i % n]; + while (!stack.isEmpty() && nums[stack.peek()] < num) + ans[stack.pop()] = num; + if (i < n) + stack.push(i); + } + + return ans; + } +} diff --git a/solutions/503. Next Greater Element II/503.py b/solutions/503. Next Greater Element II/503.py new file mode 100644 index 00000000000..2eab9282eda --- /dev/null +++ b/solutions/503. Next Greater Element II/503.py @@ -0,0 +1,14 @@ +class Solution: + def nextGreaterElements(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [-1] * n + stack = [] # a decreasing stack storing indices + + for i in range(n * 2): + num = nums[i % n] + while stack and nums[stack[-1]] < num: + ans[stack.pop()] = num + if i < n: + stack.append(i) + + return ans diff --git a/solutions/504. Base 7/504.cpp b/solutions/504. Base 7/504.cpp new file mode 100644 index 00000000000..8412b9f7be0 --- /dev/null +++ b/solutions/504. Base 7/504.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + string convertToBase7(int num) { + if (num < 0) + return "-" + convertToBase7(-num); + if (num < 7) + return to_string(num); + return convertToBase7(num / 7) + to_string(num % 7); + } +}; diff --git a/solutions/504. Base 7/504.java b/solutions/504. Base 7/504.java new file mode 100644 index 00000000000..840e3a70f99 --- /dev/null +++ b/solutions/504. Base 7/504.java @@ -0,0 +1,9 @@ +class Solution { + public String convertToBase7(int num) { + if (num < 0) + return "-" + convertToBase7(-num); + if (num < 7) + return String.valueOf(num); + return convertToBase7(num / 7) + String.valueOf(num % 7); + } +} diff --git a/solutions/505. The Maze II/505-2.cpp b/solutions/505. The Maze II/505-2.cpp new file mode 100644 index 00000000000..c0a346be3d2 --- /dev/null +++ b/solutions/505. The Maze II/505-2.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int shortestDistance(vector>& maze, vector& start, + vector& destination) { + vector> dist(maze.size(), vector(maze[0].size(), INT_MAX)); + dist[start[0]][start[1]] = 0; + + dfs(maze, dist, start[0], start[1], destination); + + return dist[destination[0]][destination[1]] == INT_MAX + ? -1 + : dist[destination[0]][destination[1]]; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + void dfs(vector>& maze, vector>& dist, int i, int j, + const vector& destination) { + if (i == destination[0] && j == destination[1]) + return; + + for (const auto& [dx, dy] : dirs) { + int x = i; + int y = j; + int steps = dist[i][j]; + while (isValid(maze, x + dx, y + dy)) { + x += dx; + y += dy; + ++steps; + } + if (steps < dist[x][y]) { + dist[x][y] = steps; + dfs(maze, dist, x, y, destination); + } + } + } + + bool isValid(const vector>& maze, int x, int y) { + return x >= 0 && x < maze.size() && y >= 0 && y < maze[0].size() && + maze[x][y] == 0; + } +}; diff --git a/solutions/505. The Maze II/505-2.java b/solutions/505. The Maze II/505-2.java new file mode 100644 index 00000000000..1abc6ce2934 --- /dev/null +++ b/solutions/505. The Maze II/505-2.java @@ -0,0 +1,39 @@ +class Solution { + public int shortestDistance(int[][] maze, int[] start, int[] destination) { + int[][] dist = new int[maze.length][maze[0].length]; + Arrays.stream(dist).forEach(row -> Arrays.fill(row, Integer.MAX_VALUE)); + dist[start[0]][start[1]] = 0; + + dfs(maze, dist, start[0], start[1], destination); + + return dist[destination[0]][destination[1]] == Integer.MAX_VALUE + ? -1 + : dist[destination[0]][destination[1]]; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private void dfs(int[][] maze, int[][] dist, int i, int j, int[] destination) { + if (i == destination[0] && j == destination[1]) + return; + + for (int[] dir : dirs) { + int x = i; + int y = j; + int steps = dist[i][j]; + while (isValid(maze, x + dir[0], y + dir[1])) { + x += dir[0]; + y += dir[1]; + ++steps; + } + if (steps < dist[x][y]) { + dist[x][y] = steps; + dfs(maze, dist, x, y, destination); + } + } + } + + private boolean isValid(int[][] maze, int x, int y) { + return x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x][y] == 0; + } +} diff --git a/solutions/505. The Maze II/505.cpp b/solutions/505. The Maze II/505.cpp new file mode 100644 index 00000000000..b11bf2f4613 --- /dev/null +++ b/solutions/505. The Maze II/505.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int shortestDistance(vector>& maze, vector& start, + vector& destination) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = maze.size(); + const int n = maze[0].size(); + queue> q{{{start[0], start[1]}}}; + vector> dist(m, vector(n, INT_MAX)); + dist[start[0]][start[1]] = 0; + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + int x = i; + int y = j; + int steps = dist[i][j]; + while (isValid(maze, x + dx, y + dy)) { + x += dx; + y += dy; + ++steps; + } + if (steps < dist[x][y]) { + dist[x][y] = steps; + if (x == destination[0] && y == destination[1]) + continue; + q.emplace(x, y); + } + } + } + + return dist[destination[0]][destination[1]] == INT_MAX + ? -1 + : dist[destination[0]][destination[1]]; + } + + private: + bool isValid(const vector>& maze, int x, int y) { + return x >= 0 && x < maze.size() && y >= 0 && y < maze[0].size() && + maze[x][y] == 0; + } +}; diff --git a/solutions/505. The Maze II/505.java b/solutions/505. The Maze II/505.java new file mode 100644 index 00000000000..3de78d33285 --- /dev/null +++ b/solutions/505. The Maze II/505.java @@ -0,0 +1,38 @@ +class Solution { + public int shortestDistance(int[][] maze, int[] start, int[] destination) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = maze.length; + final int n = maze[0].length; + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {start[0], start[1]})); + int[][] dist = new int[maze.length][maze[0].length]; + Arrays.stream(dist).forEach(row -> Arrays.fill(row, Integer.MAX_VALUE)); + dist[start[0]][start[1]] = 0; + + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + int x = i; + int y = j; + int steps = dist[i][j]; + while (isValid(maze, x + dir[0], y + dir[1])) { + x += dir[0]; + y += dir[1]; + ++steps; + } + if (steps < dist[x][y]) { + dist[x][y] = steps; + q.offer(new int[] {x, y}); + } + } + } + + return dist[destination[0]][destination[1]] == Integer.MAX_VALUE + ? -1 + : dist[destination[0]][destination[1]]; + } + + private boolean isValid(int[][] maze, int x, int y) { + return x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x][y] == 0; + } +} diff --git a/solutions/506. Relative Ranks/506.cpp b/solutions/506. Relative Ranks/506.cpp new file mode 100644 index 00000000000..dbfcadb8a3f --- /dev/null +++ b/solutions/506. Relative Ranks/506.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector findRelativeRanks(vector& nums) { + const int n = nums.size(); + vector ans(n); + vector indices(n); + + iota(indices.begin(), indices.end(), 0); + + ranges::sort(indices, + [&](const int a, const int b) { return nums[a] > nums[b]; }); + + for (int i = 0; i < n; ++i) + if (i == 0) + ans[indices[0]] = "Gold Medal"; + else if (i == 1) + ans[indices[1]] = "Silver Medal"; + else if (i == 2) + ans[indices[2]] = "Bronze Medal"; + else + ans[indices[i]] = to_string(i + 1); + + return ans; + } +}; diff --git a/solutions/506. Relative Ranks/506.java b/solutions/506. Relative Ranks/506.java new file mode 100644 index 00000000000..10eaddb5ab4 --- /dev/null +++ b/solutions/506. Relative Ranks/506.java @@ -0,0 +1,24 @@ +class Solution { + public String[] findRelativeRanks(int[] nums) { + final int n = nums.length; + String[] ans = new String[n]; + List indices = new ArrayList<>(); + + for (int i = 0; i < n; ++i) + indices.add(i); + + Collections.sort(indices, (a, b) -> nums[b] - nums[a]); + + for (int i = 0; i < n; ++i) + if (i == 0) + ans[indices.get(0)] = "Gold Medal"; + else if (i == 1) + ans[indices.get(1)] = "Silver Medal"; + else if (i == 2) + ans[indices.get(2)] = "Bronze Medal"; + else + ans[indices.get(i)] = String.valueOf(i + 1); + + return ans; + } +} diff --git a/solutions/507. Perfect Number/507.cpp b/solutions/507. Perfect Number/507.cpp new file mode 100644 index 00000000000..8e4f680a811 --- /dev/null +++ b/solutions/507. Perfect Number/507.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool checkPerfectNumber(int num) { + if (num == 1) + return false; + + int sum = 1; + + for (int i = 2; i <= sqrt(num); ++i) + if (num % i == 0) + sum += i + num / i; + + return sum == num; + } +}; diff --git a/solutions/507. Perfect Number/507.java b/solutions/507. Perfect Number/507.java new file mode 100644 index 00000000000..d772cceab9b --- /dev/null +++ b/solutions/507. Perfect Number/507.java @@ -0,0 +1,14 @@ +class Solution { + public boolean checkPerfectNumber(int num) { + if (num == 1) + return false; + + int sum = 1; + + for (int i = 2; i <= Math.sqrt(num); ++i) + if (num % i == 0) + sum += i + num / i; + + return sum == num; + } +} diff --git a/solutions/507. Perfect Number/507.py b/solutions/507. Perfect Number/507.py new file mode 100644 index 00000000000..a2e81da4ae1 --- /dev/null +++ b/solutions/507. Perfect Number/507.py @@ -0,0 +1,3 @@ +class Solution: + def checkPerfectNumber(self, num: int) -> bool: + return num in {6, 28, 496, 8128, 33550336} diff --git a/solutions/508. Most Frequent Subtree Sum/508.cpp b/solutions/508. Most Frequent Subtree Sum/508.cpp new file mode 100644 index 00000000000..186bd523c02 --- /dev/null +++ b/solutions/508. Most Frequent Subtree Sum/508.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector findFrequentTreeSum(TreeNode* root) { + vector ans; + unordered_map count; + int maxCount = 0; + + sumDownFrom(root, count); + + for (const auto& [_, freq] : count) + maxCount = max(maxCount, freq); + + for (const auto& [sum, freq] : count) + if (freq == maxCount) + ans.push_back(sum); + + return ans; + } + + private: + int sumDownFrom(TreeNode* root, unordered_map& count) { + if (root == nullptr) + return 0; + + const int sum = root->val + sumDownFrom(root->left, count) + + sumDownFrom(root->right, count); + ++count[sum]; + return sum; + } +}; diff --git a/solutions/508. Most Frequent Subtree Sum/508.java b/solutions/508. Most Frequent Subtree Sum/508.java new file mode 100644 index 00000000000..1bfba73b659 --- /dev/null +++ b/solutions/508. Most Frequent Subtree Sum/508.java @@ -0,0 +1,27 @@ +class Solution { + public int[] findFrequentTreeSum(TreeNode root) { + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + int maxCount = 0; + + sumDownFrom(root, count); + + for (final int freq : count.values()) + maxCount = Math.max(maxCount, freq); + + for (final int sum : count.keySet()) + if (count.get(sum) == maxCount) + ans.add(sum); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private int sumDownFrom(TreeNode root, Map count) { + if (root == null) + return 0; + + final int sum = root.val + sumDownFrom(root.left, count) + sumDownFrom(root.right, count); + count.merge(sum, 1, Integer::sum); + return sum; + } +} diff --git a/solutions/508. Most Frequent Subtree Sum/508.py b/solutions/508. Most Frequent Subtree Sum/508.py new file mode 100644 index 00000000000..779dd983ad0 --- /dev/null +++ b/solutions/508. Most Frequent Subtree Sum/508.py @@ -0,0 +1,18 @@ +class Solution: + def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + count = collections.Counter() + + def dfs(root: Optional[TreeNode]) -> int: + if not root: + return 0 + + summ = root.val + dfs(root.left) + dfs(root.right) + count[summ] += 1 + return summ + + dfs(root) + maxFreq = max(count.values()) + return [summ for summ in count if count[summ] == maxFreq] diff --git a/solutions/509. Fibonacci Number/509.cpp b/solutions/509. Fibonacci Number/509.cpp new file mode 100644 index 00000000000..a908544e395 --- /dev/null +++ b/solutions/509. Fibonacci Number/509.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int fib(int n) { + if (n < 2) + return n; + + vector dp{0, 0, 1}; + + for (int i = 2; i <= n; ++i) { + dp[0] = dp[1]; + dp[1] = dp[2]; + dp[2] = dp[0] + dp[1]; + } + + return dp.back(); + } +}; diff --git a/solutions/509. Fibonacci Number/509.java b/solutions/509. Fibonacci Number/509.java new file mode 100644 index 00000000000..c0debc34a59 --- /dev/null +++ b/solutions/509. Fibonacci Number/509.java @@ -0,0 +1,16 @@ +class Solution { + public int fib(int n) { + if (n < 2) + return n; + + int[] dp = {0, 0, 1}; + + for (int i = 2; i <= n; ++i) { + dp[0] = dp[1]; + dp[1] = dp[2]; + dp[2] = dp[0] + dp[1]; + } + + return dp[2]; + } +} diff --git a/solutions/509. Fibonacci Number/509.py b/solutions/509. Fibonacci Number/509.py new file mode 100644 index 00000000000..3864627fb4e --- /dev/null +++ b/solutions/509. Fibonacci Number/509.py @@ -0,0 +1,13 @@ +class Solution: + def fib(self, n: int) -> int: + if n < 2: + return n + + dp = [0, 0, 1] + + for i in range(2, n + 1): + dp[0] = dp[1] + dp[1] = dp[2] + dp[2] = dp[0] + dp[1] + + return dp[2] diff --git a/solutions/51. N-Queens/51.cpp b/solutions/51. N-Queens/51.cpp new file mode 100644 index 00000000000..3ebf3860559 --- /dev/null +++ b/solutions/51. N-Queens/51.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector> solveNQueens(int n) { + vector> ans; + dfs(n, 0, vector(n), vector(2 * n - 1), vector(2 * n - 1), + vector(n, string(n, '.')), ans); + return ans; + } + + private: + void dfs(int n, int i, vector&& cols, vector&& diag1, + vector&& diag2, vector&& board, + vector>& ans) { + if (i == n) { + ans.push_back(board); + return; + } + + for (int j = 0; j < n; ++j) { + if (cols[j] || diag1[i + j] || diag2[j - i + n - 1]) + continue; + board[i][j] = 'Q'; + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true; + dfs(n, i + 1, move(cols), move(diag1), move(diag2), move(board), ans); + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false; + board[i][j] = '.'; + } + } +}; diff --git a/solutions/51. N-Queens/51.java b/solutions/51. N-Queens/51.java new file mode 100644 index 00000000000..049168bee1c --- /dev/null +++ b/solutions/51. N-Queens/51.java @@ -0,0 +1,37 @@ +class Solution { + public List> solveNQueens(int n) { + List> ans = new ArrayList<>(); + char[][] board = new char[n][n]; + + for (int i = 0; i < n; ++i) + Arrays.fill(board[i], '.'); + + dfs(n, 0, new boolean[n], new boolean[2 * n - 1], new boolean[2 * n - 1], board, ans); + return ans; + } + + private void dfs(int n, int i, boolean[] cols, boolean[] diag1, boolean[] diag2, char[][] board, + List> ans) { + if (i == n) { + ans.add(construct(board)); + return; + } + + for (int j = 0; j < cols.length; ++j) { + if (cols[j] || diag1[i + j] || diag2[j - i + n - 1]) + continue; + board[i][j] = 'Q'; + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true; + dfs(n, i + 1, cols, diag1, diag2, board, ans); + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false; + board[i][j] = '.'; + } + } + + private List construct(char[][] board) { + List listBoard = new ArrayList<>(); + for (int i = 0; i < board.length; ++i) + listBoard.add(String.valueOf(board[i])); + return listBoard; + } +} diff --git a/solutions/51. N-Queens/51.py b/solutions/51. N-Queens/51.py new file mode 100644 index 00000000000..c9dc9e610aa --- /dev/null +++ b/solutions/51. N-Queens/51.py @@ -0,0 +1,21 @@ +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: + ans = [] + cols = [False] * n + diag1 = [False] * (2 * n - 1) + diag2 = [False] * (2 * n - 1) + + def dfs(i: int, board: List[int]) -> None: + if i == n: + ans.append(board) + return + + for j in range(n): + if cols[j] or diag1[i + j] or diag2[j - i + n - 1]: + continue + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True + dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)]) + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False + + dfs(0, []) + return ans diff --git a/solutions/510. Inorder Successor in BST II/510.cpp b/solutions/510. Inorder Successor in BST II/510.cpp new file mode 100644 index 00000000000..1d4bd574305 --- /dev/null +++ b/solutions/510. Inorder Successor in BST II/510.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + Node* inorderSuccessor(Node* node) { + // The successor is somewhere lower in the right subtree. + if (node->right) { + node = node->right; + while (node->left) + node = node->left; + return node; + } + + // The successor is somewhere upper in the tree. + while (node->parent && node->parent->left != node) + node = node->parent; + return node->parent; + } +}; diff --git a/solutions/510. Inorder Successor in BST II/510.java b/solutions/510. Inorder Successor in BST II/510.java new file mode 100644 index 00000000000..7f01dcbb95b --- /dev/null +++ b/solutions/510. Inorder Successor in BST II/510.java @@ -0,0 +1,16 @@ +class Solution { + public Node inorderSuccessor(Node node) { + // The successor is somewhere upper in the tree. + if (node.right == null) { + while (node.parent != null && node.parent.left != node) + node = node.parent; + return node.parent; + } + + // The successor is somewhere lower in the right subtree. + node = node.right; + while (node.left != null) + node = node.left; + return node; + } +} diff --git a/solutions/511. Game Play Analysis I/511.sql b/solutions/511. Game Play Analysis I/511.sql new file mode 100644 index 00000000000..70108f80612 --- /dev/null +++ b/solutions/511. Game Play Analysis I/511.sql @@ -0,0 +1,3 @@ +SELECT player_id, MIN(event_date) AS first_login +FROM Activity +GROUP BY 1; diff --git a/solutions/512. Game Play Analysis II/512.sql b/solutions/512. Game Play Analysis II/512.sql new file mode 100644 index 00000000000..3ad6431023c --- /dev/null +++ b/solutions/512. Game Play Analysis II/512.sql @@ -0,0 +1,7 @@ +SELECT DISTINCT + player_id, + FIRST_VALUE(device_id) OVER( + PARTITION by player_id + ORDER BY event_date + ) AS device_id +FROM Activity; diff --git a/solutions/513. Find Bottom Left Tree Value/513-2.cpp b/solutions/513. Find Bottom Left Tree Value/513-2.cpp new file mode 100644 index 00000000000..b6be28cf8a0 --- /dev/null +++ b/solutions/513. Find Bottom Left Tree Value/513-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int findBottomLeftValue(TreeNode* root) { + int ans = 0; + dfs(root, 1, 0, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int depth, int&& maxDepth, int& ans) { + if (root == nullptr) + return; + if (depth > maxDepth) { + maxDepth = depth; + ans = root->val; + } + + dfs(root->left, depth + 1, move(maxDepth), ans); + dfs(root->right, depth + 1, move(maxDepth), ans); + } +}; diff --git a/solutions/513. Find Bottom Left Tree Value/513-2.java b/solutions/513. Find Bottom Left Tree Value/513-2.java new file mode 100644 index 00000000000..4f665f94805 --- /dev/null +++ b/solutions/513. Find Bottom Left Tree Value/513-2.java @@ -0,0 +1,21 @@ +class Solution { + public int findBottomLeftValue(TreeNode root) { + dfs(root, 1); + return ans; + } + + private int ans = 0; + private int maxDepth = 0; + + private void dfs(TreeNode root, int depth) { + if (root == null) + return; + if (depth > maxDepth) { + maxDepth = depth; + ans = root.val; + } + + dfs(root.left, depth + 1); + dfs(root.right, depth + 1); + } +} diff --git a/solutions/513. Find Bottom Left Tree Value/513-2.py b/solutions/513. Find Bottom Left Tree Value/513-2.py new file mode 100644 index 00000000000..46a836a07f7 --- /dev/null +++ b/solutions/513. Find Bottom Left Tree Value/513-2.py @@ -0,0 +1,19 @@ +class Solution: + def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: + ans = 0 + maxDepth = 0 + + def dfs(root: Optional[TreeNode], depth: int) -> None: + nonlocal ans + nonlocal maxDepth + if not root: + return + if depth > maxDepth: + maxDepth = depth + ans = root.val + + dfs(root.left, depth + 1) + dfs(root.right, depth + 1) + + dfs(root, 1) + return ans diff --git a/solutions/513. Find Bottom Left Tree Value/513.cpp b/solutions/513. Find Bottom Left Tree Value/513.cpp new file mode 100644 index 00000000000..fed08ee7a59 --- /dev/null +++ b/solutions/513. Find Bottom Left Tree Value/513.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int findBottomLeftValue(TreeNode* root) { + queue q{{root}}; + TreeNode* node = nullptr; + + while (!q.empty()) { + node = q.front(); + q.pop(); + if (node->right) + q.push(node->right); + if (node->left) + q.push(node->left); + } + + return node->val; + } +}; diff --git a/solutions/513. Find Bottom Left Tree Value/513.java b/solutions/513. Find Bottom Left Tree Value/513.java new file mode 100644 index 00000000000..b8133d6d34f --- /dev/null +++ b/solutions/513. Find Bottom Left Tree Value/513.java @@ -0,0 +1,16 @@ +class Solution { + public int findBottomLeftValue(TreeNode root) { + Queue q = new ArrayDeque<>(Arrays.asList(root)); + TreeNode node = null; + + while (!q.isEmpty()) { + node = q.poll(); + if (node.right != null) + q.offer(node.right); + if (node.left != null) + q.offer(node.left); + } + + return node.val; + } +} diff --git a/solutions/513. Find Bottom Left Tree Value/513.py b/solutions/513. Find Bottom Left Tree Value/513.py new file mode 100644 index 00000000000..5fe9bcc7490 --- /dev/null +++ b/solutions/513. Find Bottom Left Tree Value/513.py @@ -0,0 +1,12 @@ +class Solution: + def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: + q = collections.deque([root]) + + while q: + root = q.popleft() + if root.right: + q.append(root.right) + if root.left: + q.append(root.left) + + return root.val diff --git a/solutions/514. Freedom Trail/514.cpp b/solutions/514. Freedom Trail/514.cpp new file mode 100644 index 00000000000..abd6d7cdbfa --- /dev/null +++ b/solutions/514. Freedom Trail/514.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int findRotateSteps(string ring, string key) { + return dfs(ring, key, 0, {}) + key.length(); + } + + private: + // Returns the number of rotates of ring to match key[index..n). + int dfs(const string& ring, const string& key, int index, + unordered_map&& mem) { + if (index == key.length()) + return 0; + // Add the index to prevent duplication. + const string hashKey = ring + to_string(index); + if (const auto it = mem.find(hashKey); it != mem.cend()) + return it->second; + + int ans = INT_MAX; + + // For each ring[i] == key[index], we rotate the ring to match the ring[i] + // with the key[index], then recursively match the newRing with the + // key[index + 1..n). + for (size_t i = 0; i < ring.length(); ++i) + if (ring[i] == key[index]) { + const int minRotates = min(i, ring.length() - i); + const string& newRing = ring.substr(i) + ring.substr(0, i); + const int remainingRotates = dfs(newRing, key, index + 1, move(mem)); + ans = min(ans, minRotates + remainingRotates); + } + + return mem[hashKey] = ans; + } +}; diff --git a/solutions/514. Freedom Trail/514.java b/solutions/514. Freedom Trail/514.java new file mode 100644 index 00000000000..bff53a27038 --- /dev/null +++ b/solutions/514. Freedom Trail/514.java @@ -0,0 +1,32 @@ +class Solution { + public int findRotateSteps(String ring, String key) { + Map mem = new HashMap<>(); + return dfs(ring, key, 0, mem) + key.length(); + } + + // Returns the number of rotates of ring to match key[index..n). + private int dfs(final String ring, final String key, int index, Map mem) { + if (index == key.length()) + return 0; + // Add the index to prevent duplication. + final String hashKey = ring + index; + if (mem.containsKey(hashKey)) + return mem.get(hashKey); + + int ans = Integer.MAX_VALUE; + + // For each ring[i] == key[index], we rotate the ring to match the ring[i] + // with the key[index], then recursively match the newRing with the + // key[index + 1..n). + for (int i = 0; i < ring.length(); ++i) + if (ring.charAt(i) == key.charAt(index)) { + final int minRotates = Math.min(i, ring.length() - i); + final String newRing = ring.substring(i) + ring.substring(0, i); + final int remainingRotates = dfs(newRing, key, index + 1, mem); + ans = Math.min(ans, minRotates + remainingRotates); + } + + mem.put(hashKey, ans); + return ans; + } +} diff --git a/solutions/514. Freedom Trail/514.py b/solutions/514. Freedom Trail/514.py new file mode 100644 index 00000000000..d3add3ade6e --- /dev/null +++ b/solutions/514. Freedom Trail/514.py @@ -0,0 +1,23 @@ +class Solution: + def findRotateSteps(self, ring: str, key: str) -> int: + @functools.lru_cache(None) + def dfs(ring: str, index: int) -> int: + """Returns the number of rotates of ring to match key[index..n).""" + if index == len(key): + return 0 + + ans = math.inf + + # For each ring[i] == key[index], we rotate the ring to match the ring[i] + # with the key[index], then recursively match the newRing with the + # key[index + 1..n). + for i, r in enumerate(ring): + if r == key[index]: + minRotates = min(i, len(ring) - i) + newRing = ring[i:] + ring[:i] + remainingRotates = dfs(newRing, index + 1) + ans = min(ans, minRotates + remainingRotates) + + return ans + + return dfs(ring, 0) + len(key) diff --git a/solutions/515. Find Largest Value in Each Tree Row/515-2.cpp b/solutions/515. Find Largest Value in Each Tree Row/515-2.cpp new file mode 100644 index 00000000000..403b5c90dba --- /dev/null +++ b/solutions/515. Find Largest Value in Each Tree Row/515-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector largestValues(TreeNode* root) { + vector ans; + dfs(root, 0, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int depth, vector& ans) { + if (root == nullptr) + return; + if (depth + 1 > ans.size()) + ans.push_back(root->val); + else + ans[depth] = max(ans[depth], root->val); + + dfs(root->left, depth + 1, ans); + dfs(root->right, depth + 1, ans); + } +}; diff --git a/solutions/515. Find Largest Value in Each Tree Row/515-2.java b/solutions/515. Find Largest Value in Each Tree Row/515-2.java new file mode 100644 index 00000000000..1dc7852e1ed --- /dev/null +++ b/solutions/515. Find Largest Value in Each Tree Row/515-2.java @@ -0,0 +1,19 @@ +class Solution { + public List largestValues(TreeNode root) { + List ans = new ArrayList<>(); + dfs(root, 0, ans); + return ans; + } + + private void dfs(TreeNode root, int depth, List ans) { + if (root == null) + return; + if (depth + 1 > ans.size()) + ans.add(root.val); + else + ans.set(depth, Math.max(ans.get(depth), root.val)); + + dfs(root.left, depth + 1, ans); + dfs(root.right, depth + 1, ans); + } +} diff --git a/solutions/515. Find Largest Value in Each Tree Row/515-2.py b/solutions/515. Find Largest Value in Each Tree Row/515-2.py new file mode 100644 index 00000000000..fb3d1bca4ef --- /dev/null +++ b/solutions/515. Find Largest Value in Each Tree Row/515-2.py @@ -0,0 +1,17 @@ +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + + def dfs(root: Optional[TreeNode], depth: int) -> None: + if not root: + return + if depth + 1 > len(ans): + ans.append(root.val) + else: + ans[depth] = max(ans[depth], root.val) + + dfs(root.left, depth + 1) + dfs(root.right, depth + 1) + + dfs(root, 0) + return ans diff --git a/solutions/515. Find Largest Value in Each Tree Row/515.cpp b/solutions/515. Find Largest Value in Each Tree Row/515.cpp new file mode 100644 index 00000000000..6305ba1ca69 --- /dev/null +++ b/solutions/515. Find Largest Value in Each Tree Row/515.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector largestValues(TreeNode* root) { + if (root == nullptr) + return {}; + + vector ans; + queue q{{root}}; + + while (!q.empty()) { + int mx = INT_MIN; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + mx = max(mx, node->val); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + ans.push_back(mx); + } + + return ans; + } +}; diff --git a/solutions/515. Find Largest Value in Each Tree Row/515.java b/solutions/515. Find Largest Value in Each Tree Row/515.java new file mode 100644 index 00000000000..a09012c984a --- /dev/null +++ b/solutions/515. Find Largest Value in Each Tree Row/515.java @@ -0,0 +1,24 @@ +class Solution { + public List largestValues(TreeNode root) { + if (root == null) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + int mx = Integer.MIN_VALUE; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + mx = Math.max(mx, node.val); + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + ans.add(mx); + } + + return ans; + } +} diff --git a/solutions/515. Find Largest Value in Each Tree Row/515.py b/solutions/515. Find Largest Value in Each Tree Row/515.py new file mode 100644 index 00000000000..7b6e2a7252e --- /dev/null +++ b/solutions/515. Find Largest Value in Each Tree Row/515.py @@ -0,0 +1,20 @@ +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + ans = [] + q = collections.deque([root]) + + while q: + mx = -math.inf + for _ in range(len(q)): + root = q.popleft() + mx = max(mx, root.val) + if root.left: + q.append(root.left) + if root.right: + q.append(root.right) + ans.append(mx) + + return ans diff --git a/solutions/516. Longest Palindromic Subsequence/516-2.cpp b/solutions/516. Longest Palindromic Subsequence/516-2.cpp new file mode 100644 index 00000000000..657025deded --- /dev/null +++ b/solutions/516. Longest Palindromic Subsequence/516-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int longestPalindromeSubseq(string s) { + const int n = s.length(); + // dp[i][j] := the length of LPS(s[i..j]) + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + if (s[i] == s[j]) + dp[i][j] = 2 + dp[i + 1][j - 1]; + else + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/516. Longest Palindromic Subsequence/516-2.java b/solutions/516. Longest Palindromic Subsequence/516-2.java new file mode 100644 index 00000000000..eae47a19680 --- /dev/null +++ b/solutions/516. Longest Palindromic Subsequence/516-2.java @@ -0,0 +1,21 @@ +class Solution { + public int longestPalindromeSubseq(String s) { + final int n = s.length(); + // dp[i][j] := the length of LPS(s[i..j]) + int[][] dp = new int[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + if (s.charAt(i) == s.charAt(j)) + dp[i][j] = 2 + dp[i + 1][j - 1]; + else + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/516. Longest Palindromic Subsequence/516-2.py b/solutions/516. Longest Palindromic Subsequence/516-2.py new file mode 100644 index 00000000000..3c798b5fad4 --- /dev/null +++ b/solutions/516. Longest Palindromic Subsequence/516-2.py @@ -0,0 +1,18 @@ +class Solution: + def longestPalindromeSubseq(self, s: str) -> int: + n = len(s) + # dp[i][j] := the length of LPS(s[i..j]) + dp = [[0] * n for _ in range(n)] + + for i in range(n): + dp[i][i] = 1 + + for d in range(1, n): + for i in range(n - d): + j = i + d + if s[i] == s[j]: + dp[i][j] = 2 + dp[i + 1][j - 1] + else: + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) + + return dp[0][n - 1] diff --git a/solutions/516. Longest Palindromic Subsequence/516.cpp b/solutions/516. Longest Palindromic Subsequence/516.cpp new file mode 100644 index 00000000000..0c3e6dbc6a6 --- /dev/null +++ b/solutions/516. Longest Palindromic Subsequence/516.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int longestPalindromeSubseq(string s) { + const int n = s.length(); + vector> mem(n, vector(n)); + return lps(s, 0, n - 1, mem); + } + + private: + // Returns the length of LPS(s[i..j]). + int lps(const string& s, int i, int j, vector>& mem) { + if (i > j) + return 0; + if (i == j) + return 1; + if (mem[i][j] > 0) + return mem[i][j]; + if (s[i] == s[j]) + return mem[i][j] = 2 + lps(s, i + 1, j - 1, mem); + return mem[i][j] = max(lps(s, i + 1, j, mem), lps(s, i, j - 1, mem)); + } +}; diff --git a/solutions/516. Longest Palindromic Subsequence/516.java b/solutions/516. Longest Palindromic Subsequence/516.java new file mode 100644 index 00000000000..327a21d652c --- /dev/null +++ b/solutions/516. Longest Palindromic Subsequence/516.java @@ -0,0 +1,20 @@ +class Solution { + public int longestPalindromeSubseq(String s) { + final int n = s.length(); + int[][] mem = new int[n][n]; + return lps(s, 0, n - 1, mem); + } + + // Returns the length of LPS(s[i..j]). + private int lps(String s, int i, int j, int[][] mem) { + if (i > j) + return 0; + if (i == j) + return 1; + if (mem[i][j] > 0) + return mem[i][j]; + if (s.charAt(i) == s.charAt(j)) + return mem[i][j] = 2 + lps(s, i + 1, j - 1, mem); + return mem[i][j] = Math.max(lps(s, i + 1, j, mem), lps(s, i, j - 1, mem)); + } +} diff --git a/solutions/516. Longest Palindromic Subsequence/516.py b/solutions/516. Longest Palindromic Subsequence/516.py new file mode 100644 index 00000000000..1b28bd5b901 --- /dev/null +++ b/solutions/516. Longest Palindromic Subsequence/516.py @@ -0,0 +1,14 @@ +class Solution: + def longestPalindromeSubseq(self, s: str) -> int: + @functools.lru_cache(None) + def dp(i: int, j: int) -> int: + """Returns the length of LPS(s[i..j]).""" + if i > j: + return 0 + if i == j: + return 1 + if s[i] == s[j]: + return 2 + dp(i + 1, j - 1) + return max(dp(i + 1, j), dp(i, j - 1)) + + return dp(0, len(s) - 1) diff --git a/solutions/517. Super Washing Machines/517.cpp b/solutions/517. Super Washing Machines/517.cpp new file mode 100644 index 00000000000..25dfd2c9fe7 --- /dev/null +++ b/solutions/517. Super Washing Machines/517.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findMinMoves(vector& machines) { + const int dresses = accumulate(machines.begin(), machines.end(), 0); + if (dresses % machines.size() != 0) + return -1; + + int ans = 0; + int inout = 0; + const int average = dresses / machines.size(); + + for (const int dress : machines) { + inout += dress - average; + ans = max({ans, abs(inout), dress - average}); + } + + return ans; + } +}; diff --git a/solutions/517. Super Washing Machines/517.java b/solutions/517. Super Washing Machines/517.java new file mode 100644 index 00000000000..3b6e4d637e5 --- /dev/null +++ b/solutions/517. Super Washing Machines/517.java @@ -0,0 +1,18 @@ +class Solution { + public int findMinMoves(int[] machines) { + int dresses = Arrays.stream(machines).sum(); + if (dresses % machines.length != 0) + return -1; + + int ans = 0; + int inout = 0; + final int average = dresses / machines.length; + + for (final int dress : machines) { + inout += dress - average; + ans = Math.max(ans, Math.max(Math.abs(inout), dress - average)); + } + + return ans; + } +} diff --git a/solutions/517. Super Washing Machines/517.py b/solutions/517. Super Washing Machines/517.py new file mode 100644 index 00000000000..f154905513d --- /dev/null +++ b/solutions/517. Super Washing Machines/517.py @@ -0,0 +1,16 @@ +class Solution: + def findMinMoves(self, machines: List[int]) -> int: + dresses = sum(machines) + + if dresses % len(machines) != 0: + return -1 + + ans = 0 + average = dresses // len(machines) + inout = 0 + + for dress in machines: + inout += dress - average + ans = max(ans, abs(inout), dress - average) + + return ans diff --git a/solutions/518. Coin Change 2/518.cpp b/solutions/518. Coin Change 2/518.cpp new file mode 100644 index 00000000000..1c365451492 --- /dev/null +++ b/solutions/518. Coin Change 2/518.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int change(int amount, vector& coins) { + vector dp(amount + 1); + dp[0] = 1; + + for (const int coin : coins) + for (int i = coin; i <= amount; ++i) + dp[i] += dp[i - coin]; + + return dp[amount]; + } +}; diff --git a/solutions/518. Coin Change 2/518.java b/solutions/518. Coin Change 2/518.java new file mode 100644 index 00000000000..cbbacd83221 --- /dev/null +++ b/solutions/518. Coin Change 2/518.java @@ -0,0 +1,12 @@ +class Solution { + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; + dp[0] = 1; + + for (final int coin : coins) + for (int i = coin; i <= amount; ++i) + dp[i] += dp[i - coin]; + + return dp[amount]; + } +} diff --git a/solutions/518. Coin Change 2/518.py b/solutions/518. Coin Change 2/518.py new file mode 100644 index 00000000000..1b2b6c9260b --- /dev/null +++ b/solutions/518. Coin Change 2/518.py @@ -0,0 +1,9 @@ +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + dp = [1] + [0] * amount + + for coin in coins: + for i in range(coin, amount + 1): + dp[i] += dp[i - coin] + + return dp[amount] diff --git a/solutions/519. Random Flip Matrix/519.cpp b/solutions/519. Random Flip Matrix/519.cpp new file mode 100644 index 00000000000..66994c0e211 --- /dev/null +++ b/solutions/519. Random Flip Matrix/519.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + Solution(int n_rows, int n_cols) + : rows(n_rows), cols(n_cols), total(n_rows * n_cols) {} + + vector flip() { + // All the candidates are used out. + if (used.size() == total) + return {}; + int index = rand() % total; + while (used.contains(index)) + index = ++index % total; + used.insert(index); + return {index / cols, index % cols}; + } + + void reset() { + used = {}; + } + + private: + unordered_set used; + int rows; + int cols; + int total; +}; diff --git a/solutions/519. Random Flip Matrix/519.java b/solutions/519. Random Flip Matrix/519.java new file mode 100644 index 00000000000..bdcb50b3c0d --- /dev/null +++ b/solutions/519. Random Flip Matrix/519.java @@ -0,0 +1,27 @@ +class Solution { + public Solution(int n_rows, int n_cols) { + this.rows = n_rows; + this.cols = n_cols; + this.total = n_rows * n_cols; + } + + public int[] flip() { + // All the candidates are used out. + if (used.size() == total) + return new int[] {}; + int index = new Random().nextInt(total); + while (used.contains(index)) + index = ++index % total; + used.add(index); + return new int[] {index / cols, index % cols}; + } + + public void reset() { + used.clear(); + } + + private Set used = new HashSet<>(); + private int rows; + private int cols; + private int total; +} diff --git a/solutions/52. N-Queens II/52.cpp b/solutions/52. N-Queens II/52.cpp new file mode 100644 index 00000000000..58a170f4656 --- /dev/null +++ b/solutions/52. N-Queens II/52.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int totalNQueens(int n) { + int ans = 0; + dfs(n, 0, vector(n), vector(2 * n - 1), vector(2 * n - 1), + ans); + return ans; + } + + private: + void dfs(int n, int i, vector&& cols, vector&& diag1, + vector&& diag2, int& ans) { + if (i == n) { + ++ans; + return; + } + + for (int j = 0; j < n; ++j) { + if (cols[j] || diag1[i + j] || diag2[j - i + n - 1]) + continue; + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true; + dfs(n, i + 1, move(cols), move(diag1), move(diag2), ans); + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false; + } + } +}; diff --git a/solutions/52. N-Queens II/52.java b/solutions/52. N-Queens II/52.java new file mode 100644 index 00000000000..759c69b4145 --- /dev/null +++ b/solutions/52. N-Queens II/52.java @@ -0,0 +1,23 @@ +class Solution { + public int totalNQueens(int n) { + dfs(n, 0, new boolean[n], new boolean[2 * n - 1], new boolean[2 * n - 1]); + return ans; + } + + private int ans = 0; + + private void dfs(int n, int i, boolean[] cols, boolean[] diag1, boolean[] diag2) { + if (i == n) { + ++ans; + return; + } + + for (int j = 0; j < cols.length; ++j) { + if (cols[j] || diag1[i + j] || diag2[j - i + n - 1]) + continue; + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true; + dfs(n, i + 1, cols, diag1, diag2); + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false; + } + } +} diff --git a/solutions/52. N-Queens II/52.py b/solutions/52. N-Queens II/52.py new file mode 100644 index 00000000000..a2d56bcf31a --- /dev/null +++ b/solutions/52. N-Queens II/52.py @@ -0,0 +1,22 @@ +class Solution: + def totalNQueens(self, n: int) -> int: + ans = 0 + cols = [False] * n + diag1 = [False] * (2 * n - 1) + diag2 = [False] * (2 * n - 1) + + def dfs(i: int) -> None: + nonlocal ans + if i == n: + ans += 1 + return + + for j in range(n): + if cols[j] or diag1[i + j] or diag2[j - i + n - 1]: + continue + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True + dfs(i + 1) + cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False + + dfs(0) + return ans diff --git a/solutions/520. Detect Capital/520.cpp b/solutions/520. Detect Capital/520.cpp new file mode 100644 index 00000000000..a663bb7e024 --- /dev/null +++ b/solutions/520. Detect Capital/520.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + bool detectCapitalUse(string word) { + for (int i = 1; i < word.length(); ++i) + if (isupper(word[1]) != isupper(word[i]) || + islower(word[0]) && isupper(word[i])) + return false; + return true; + } +}; diff --git a/solutions/520. Detect Capital/520.java b/solutions/520. Detect Capital/520.java new file mode 100644 index 00000000000..3929bad059c --- /dev/null +++ b/solutions/520. Detect Capital/520.java @@ -0,0 +1,6 @@ +class Solution { + public boolean detectCapitalUse(String word) { + return word.equals(word.toUpperCase()) || + word.substring(1).equals(word.substring(1).toLowerCase()); + } +} diff --git a/solutions/520. Detect Capital/520.py b/solutions/520. Detect Capital/520.py new file mode 100644 index 00000000000..6ea8933c9f1 --- /dev/null +++ b/solutions/520. Detect Capital/520.py @@ -0,0 +1,3 @@ +class Solution: + def detectCapitalUse(self, word: str) -> bool: + return word.isupper() or word.islower() or word.istitle() diff --git a/solutions/521. Longest Uncommon Subsequence I/521.cpp b/solutions/521. Longest Uncommon Subsequence I/521.cpp new file mode 100644 index 00000000000..ac74f4c64ee --- /dev/null +++ b/solutions/521. Longest Uncommon Subsequence I/521.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + int findLUSlength(string a, string b) { + return a == b ? -1 : max(a.length(), b.length()); + } +}; diff --git a/solutions/521. Longest Uncommon Subsequence I/521.java b/solutions/521. Longest Uncommon Subsequence I/521.java new file mode 100644 index 00000000000..df9f71880e6 --- /dev/null +++ b/solutions/521. Longest Uncommon Subsequence I/521.java @@ -0,0 +1,5 @@ +class Solution { + public int findLUSlength(String a, String b) { + return a.equals(b) ? -1 : Math.max(a.length(), b.length()); + } +} diff --git a/solutions/521. Longest Uncommon Subsequence I/521.py b/solutions/521. Longest Uncommon Subsequence I/521.py new file mode 100644 index 00000000000..ed45fdb6ca6 --- /dev/null +++ b/solutions/521. Longest Uncommon Subsequence I/521.py @@ -0,0 +1,3 @@ +class Solution: + def findLUSlength(self, a: str, b: str) -> int: + return -1 if a == b else max(len(a), len(b)) diff --git a/solutions/522. Longest Uncommon Subsequence II/522.cpp b/solutions/522. Longest Uncommon Subsequence II/522.cpp new file mode 100644 index 00000000000..947312105d3 --- /dev/null +++ b/solutions/522. Longest Uncommon Subsequence II/522.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int findLUSlength(vector& strs) { + unordered_set seen; + unordered_set duplicates; + + for (const string& str : strs) + if (seen.contains(str)) + duplicates.insert(str); + else + seen.insert(str); + + ranges::sort(strs, [](const string& a, const string& b) { + return a.length() > b.length(); + }); + + for (int i = 0; i < strs.size(); ++i) { + if (duplicates.contains(strs[i])) + continue; + bool isASubsequence = false; + for (int j = 0; j < i; ++j) + isASubsequence |= isSubsequence(strs[i], strs[j]); + if (!isASubsequence) + return strs[i].length(); + } + + return -1; + } + + private: + // Returns true if a is a subsequence of b. + bool isSubsequence(const string& a, const string& b) { + int i = 0; + for (const char c : b) + if (i < a.length() && c == a[i]) + ++i; + return i == a.length(); + }; +}; diff --git a/solutions/522. Longest Uncommon Subsequence II/522.java b/solutions/522. Longest Uncommon Subsequence II/522.java new file mode 100644 index 00000000000..e28464a853a --- /dev/null +++ b/solutions/522. Longest Uncommon Subsequence II/522.java @@ -0,0 +1,35 @@ +class Solution { + public int findLUSlength(String[] strs) { + Set seen = new HashSet<>(); + Set duplicates = new HashSet<>(); + + for (final String str : strs) + if (seen.contains(str)) + duplicates.add(str); + else + seen.add(str); + + Arrays.sort(strs, (a, b) -> b.length() - a.length()); + + for (int i = 0; i < strs.length; ++i) { + if (duplicates.contains(strs[i])) + continue; + boolean isASubsequence = false; + for (int j = 0; j < i; ++j) + isASubsequence |= isSubsequence(strs[i], strs[j]); + if (!isASubsequence) + return strs[i].length(); + } + + return -1; + } + + // Returns true if a is a subsequence of b. + private boolean isSubsequence(final String a, final String b) { + int i = 0; + for (final char c : b.toCharArray()) + if (i < a.length() && c == a.charAt(i)) + ++i; + return i == a.length(); + } +} diff --git a/solutions/522. Longest Uncommon Subsequence II/522.py b/solutions/522. Longest Uncommon Subsequence II/522.py new file mode 100644 index 00000000000..9a8b373714b --- /dev/null +++ b/solutions/522. Longest Uncommon Subsequence II/522.py @@ -0,0 +1,33 @@ +class Solution: + def findLUSlength(self, strs: List[str]) -> int: + def isSubsequence(a: str, b: str) -> bool: + i = 0 + j = 0 + + while i < len(a) and j < len(b): + if a[i] == b[j]: + i += 1 + j += 1 + + return i == len(a) + + seen = set() + duplicates = set() + + for s in strs: + if s in seen: + duplicates.add(s) + seen.add(s) + + strs.sort(key=lambda s: -len(s)) + + for i in range(len(strs)): + if strs[i] in duplicates: + continue + isASubsequence = False + for j in range(i): + isASubsequence |= isSubsequence(strs[i], strs[j]) + if not isASubsequence: + return len(strs[i]) + + return -1 diff --git a/solutions/523. Continuous Subarray Sum/523.cpp b/solutions/523. Continuous Subarray Sum/523.cpp new file mode 100644 index 00000000000..c8d9969a31e --- /dev/null +++ b/solutions/523. Continuous Subarray Sum/523.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool checkSubarraySum(vector& nums, int k) { + int prefix = 0; + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i]; + if (k != 0) + prefix %= k; + if (const auto it = prefixToIndex.find(prefix); + it != prefixToIndex.cend()) { + if (i - it->second > 1) + return true; + } else { + // Set a new key if it's absent because the previous index is better. + prefixToIndex[prefix] = i; + } + } + + return false; + } +}; diff --git a/solutions/523. Continuous Subarray Sum/523.java b/solutions/523. Continuous Subarray Sum/523.java new file mode 100644 index 00000000000..6d5217f58bf --- /dev/null +++ b/solutions/523. Continuous Subarray Sum/523.java @@ -0,0 +1,22 @@ +class Solution { + public boolean checkSubarraySum(int[] nums, int k) { + int prefix = 0; + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i]; + if (k != 0) + prefix %= k; + if (prefixToIndex.containsKey(prefix)) { + if (i - prefixToIndex.get(prefix) > 1) + return true; + } else { + // Set a new key if it's absent because the previous index is better. + prefixToIndex.put(prefix, i); + } + } + + return false; + } +} diff --git a/solutions/523. Continuous Subarray Sum/523.py b/solutions/523. Continuous Subarray Sum/523.py new file mode 100644 index 00000000000..d517d5719ac --- /dev/null +++ b/solutions/523. Continuous Subarray Sum/523.py @@ -0,0 +1,17 @@ +class Solution: + def checkSubarraySum(self, nums: List[int], k: int) -> bool: + prefix = 0 + prefixToIndex = {0: -1} + + for i, num in enumerate(nums): + prefix += num + if k != 0: + prefix %= k + if prefix in prefixToIndex: + if i - prefixToIndex[prefix] > 1: + return True + else: + # Set a new key if it's absent because the previous index is better. + prefixToIndex[prefix] = i + + return False diff --git a/solutions/524. Longest Word in Dictionary through Deleting/524.cpp b/solutions/524. Longest Word in Dictionary through Deleting/524.cpp new file mode 100644 index 00000000000..12392c4feef --- /dev/null +++ b/solutions/524. Longest Word in Dictionary through Deleting/524.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string findLongestWord(string s, vector& d) { + string ans; + + for (const string& word : d) + if (isSubsequence(word, s)) + if (word.length() > ans.length() || + word.length() == ans.length() && word.compare(ans) < 0) + ans = word; + + return ans; + } + + private: + // Returns true if a is a subsequence of b. + bool isSubsequence(const string& a, const string& b) { + int i = 0; + for (const char c : b) + if (i < a.length() && c == a[i]) + ++i; + return i == a.length(); + }; +}; diff --git a/solutions/524. Longest Word in Dictionary through Deleting/524.java b/solutions/524. Longest Word in Dictionary through Deleting/524.java new file mode 100644 index 00000000000..6ab04d8f19c --- /dev/null +++ b/solutions/524. Longest Word in Dictionary through Deleting/524.java @@ -0,0 +1,22 @@ +class Solution { + public String findLongestWord(String s, List d) { + String ans = ""; + + for (final String word : d) + if (isSubsequence(word, s)) + if (word.length() > ans.length() || + word.length() == ans.length() && word.compareTo(ans) < 0) + ans = word; + + return ans; + } + + // Returns true if a is a subsequence of b. + private boolean isSubsequence(final String a, final String b) { + int i = 0; + for (final char c : b.toCharArray()) + if (i < a.length() && c == a.charAt(i)) + ++i; + return i == a.length(); + } +} diff --git a/solutions/524. Longest Word in Dictionary through Deleting/524.py b/solutions/524. Longest Word in Dictionary through Deleting/524.py new file mode 100644 index 00000000000..0e7bb5b8208 --- /dev/null +++ b/solutions/524. Longest Word in Dictionary through Deleting/524.py @@ -0,0 +1,14 @@ +class Solution: + def findLongestWord(self, s: str, d: List[str]) -> str: + ans = '' + + for word in d: + i = 0 + for c in s: + if i < len(word) and c == word[i]: + i += 1 + if i == len(word): + if len(word) > len(ans) or len(word) == len(ans) and word < ans: + ans = word + + return ans diff --git a/solutions/525. Contiguous Array/525.cpp b/solutions/525. Contiguous Array/525.cpp new file mode 100644 index 00000000000..37aa1b52f2c --- /dev/null +++ b/solutions/525. Contiguous Array/525.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findMaxLength(vector& nums) { + int ans = 0; + int prefix = 0; + unordered_map prefixToIndex{{0, -1}}; + + for (int i = 0; i < nums.size(); ++i) { + prefix += nums[i] ? 1 : -1; + if (const auto it = prefixToIndex.find(prefix); + it != prefixToIndex.cend()) + ans = max(ans, i - it->second); + else + prefixToIndex[prefix] = i; + } + + return ans; + } +}; diff --git a/solutions/525. Contiguous Array/525.java b/solutions/525. Contiguous Array/525.java new file mode 100644 index 00000000000..6441c71e42d --- /dev/null +++ b/solutions/525. Contiguous Array/525.java @@ -0,0 +1,18 @@ +class Solution { + public int findMaxLength(int[] nums) { + int ans = 0; + int prefix = 0; + Map prefixToIndex = new HashMap<>(); + prefixToIndex.put(0, -1); + + for (int i = 0; i < nums.length; ++i) { + prefix += nums[i] == 1 ? 1 : -1; + if (prefixToIndex.containsKey(prefix)) + ans = Math.max(ans, i - prefixToIndex.get(prefix)); + else + prefixToIndex.put(prefix, i); + } + + return ans; + } +} diff --git a/solutions/525. Contiguous Array/525.py b/solutions/525. Contiguous Array/525.py new file mode 100644 index 00000000000..0c8208a606f --- /dev/null +++ b/solutions/525. Contiguous Array/525.py @@ -0,0 +1,11 @@ +class Solution: + def findMaxLength(self, nums: List[int]) -> int: + ans = 0 + prefix = 0 + prefixToIndex = {0: -1} + + for i, num in enumerate(nums): + prefix += 1 if num else -1 + ans = max(ans, i - prefixToIndex.setdefault(prefix, i)) + + return ans diff --git a/solutions/526. Beautiful Arrangement/526.cpp b/solutions/526. Beautiful Arrangement/526.cpp new file mode 100644 index 00000000000..d1c9a0e88d0 --- /dev/null +++ b/solutions/526. Beautiful Arrangement/526.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int countArrangement(int n) { + return dfs(n, 1, string(n + 1, 'x'), {}); + } + + private: + int dfs(int n, int num, string&& filled, unordered_map&& mem) { + if (num == n + 1) + return 1; + if (const auto it = mem.find(filled); it != mem.cend()) + return it->second; + + int count = 0; + + for (int i = 1; i <= n; ++i) + if (filled[i] == 'x' && (num % i == 0 || i % num == 0)) { + filled[i] = 'o'; + count += dfs(n, num + 1, move(filled), move(mem)); + filled[i] = 'x'; + } + + return mem[filled] = count; + } +}; diff --git a/solutions/526. Beautiful Arrangement/526.java b/solutions/526. Beautiful Arrangement/526.java new file mode 100644 index 00000000000..fcb5248e03d --- /dev/null +++ b/solutions/526. Beautiful Arrangement/526.java @@ -0,0 +1,29 @@ +class Solution { + public int countArrangement(int n) { + final String filled = "x".repeat(n + 1); + StringBuilder sb = new StringBuilder(filled); + Map mem = new HashMap<>(); + + return dfs(n, 1, sb, mem); + } + + private int dfs(int n, int num, StringBuilder sb, Map mem) { + if (num == n + 1) + return 1; + final String filled = sb.toString(); + if (mem.containsKey(filled)) + return mem.get(filled); + + int count = 0; + + for (int i = 1; i <= n; ++i) + if (sb.charAt(i) == 'x' && (num % i == 0 || i % num == 0)) { + sb.setCharAt(i, 'o'); + count += dfs(n, num + 1, sb, mem); + sb.setCharAt(i, 'x'); + } + + mem.put(filled, count); + return count; + } +} diff --git a/solutions/527. Word Abbreviation/527-2.cpp b/solutions/527. Word Abbreviation/527-2.cpp new file mode 100644 index 00000000000..b6090fbe5fd --- /dev/null +++ b/solutions/527. Word Abbreviation/527-2.cpp @@ -0,0 +1,54 @@ +struct IndexedWord { + string word; + int index; + IndexedWord(const string& word, int index) : word(word), index(index) {} +}; + +class Solution { + public: + vector wordsAbbreviation(vector& words) { + const int n = words.size(); + vector ans(n); + unordered_map> abbrevToIndexedWords; + + for (int i = 0; i < n; ++i) { + const string abbrev = getAbbrev(words[i], 0); + abbrevToIndexedWords[abbrev].emplace_back(words[i], i); + } + + for (auto& [_, indexedWords] : abbrevToIndexedWords) { + ranges::sort(indexedWords, [](const auto& a, const auto& b) { + return a.word < b.word; + }); + vector lcp(indexedWords.size()); + for (int i = 1; i < indexedWords.size(); ++i) { + const int k = + longestCommonPrefix(indexedWords[i - 1].word, indexedWords[i].word); + lcp[i - 1] = max(lcp[i - 1], k); + lcp[i] = k; + } + for (int i = 0; i < indexedWords.size(); ++i) + ans[indexedWords[i].index] = getAbbrev(indexedWords[i].word, lcp[i]); + } + + return ans; + } + + private: + string getAbbrev(const string& s, int prefixIndex) { + const int n = s.length(); + const int num = n - (prefixIndex + 1) - 1; + const int numLength = num < 10 ? 1 : num < 100 ? 2 : 3; + const int abbrevLength = (prefixIndex + 1) + numLength + 1; + if (abbrevLength >= n) + return s; + return s.substr(0, prefixIndex + 1) + to_string(num) + s.back(); + } + + int longestCommonPrefix(const string& s1, const string& s2) { + int i = 0; + while (i < s1.length() && i < s2.length() && s1[i] == s2[i]) + ++i; + return i; + } +}; diff --git a/solutions/527. Word Abbreviation/527-2.java b/solutions/527. Word Abbreviation/527-2.java new file mode 100644 index 00000000000..601d19c1c0a --- /dev/null +++ b/solutions/527. Word Abbreviation/527-2.java @@ -0,0 +1,52 @@ +class IndexedWord { + public String word; + public int index; + public IndexedWord(final String word, int index) { + this.word = word; + this.index = index; + } +} + +class Solution { + public List wordsAbbreviation(List words) { + String[] ans = new String[words.size()]; + Map> abbrevToIndexedWords = new HashMap<>(); + + for (int i = 0; i < words.size(); ++i) { + final String abbrev = getAbbrev(words.get(i), 0); + abbrevToIndexedWords.putIfAbsent(abbrev, new ArrayList<>()); + abbrevToIndexedWords.get(abbrev).add(new IndexedWord(words.get(i), i)); + } + + for (List indexedWords : abbrevToIndexedWords.values()) { + Collections.sort(indexedWords, (a, b) -> a.word.compareTo(b.word)); + int[] lcp = new int[indexedWords.size()]; + for (int i = 1; i < indexedWords.size(); ++i) { + final int k = longestCommonPrefix(indexedWords.get(i - 1).word, indexedWords.get(i).word); + lcp[i - 1] = Math.max(lcp[i - 1], k); + lcp[i] = k; + } + for (int i = 0; i < indexedWords.size(); ++i) + ans[indexedWords.get(i).index] = getAbbrev(indexedWords.get(i).word, lcp[i]); + } + + return Arrays.asList(ans); + } + + private String getAbbrev(final String s, int prefixIndex) { + final int n = s.length(); + final int num = n - (prefixIndex + 1) - 1; + final int numLength = num < 10 ? 1 : num < 100 ? 2 : 3; + final int abbrevLength = (prefixIndex + 1) + numLength + 1; + if (abbrevLength >= n) + return s; + return s.substring(0, prefixIndex + 1) + num + s.charAt(n - 1); + } + + private int longestCommonPrefix(final String s1, final String s2) { + int i = 0; + while (i < s1.length() && i < s2.length() && s1.charAt(i) == s2.charAt(i)) + ++i; + return i; + } +} diff --git a/solutions/527. Word Abbreviation/527-2.py b/solutions/527. Word Abbreviation/527-2.py new file mode 100644 index 00000000000..369c7d4c3ce --- /dev/null +++ b/solutions/527. Word Abbreviation/527-2.py @@ -0,0 +1,43 @@ +class IndexedWord: + def __init__(self, word: str, index: int): + self.word = word + self.index = index + + +class Solution: + def wordsAbbreviation(self, words: List[str]) -> List[str]: + n = len(words) + ans = [''] * n + + def getAbbrev(s: str, prefixIndex: int) -> str: + n = len(s) + num = n - (prefixIndex + 1) - 1 + numLength = 1 if num < 10 else (2 if num < 100 else 3) + abbrevLength = (prefixIndex + 1) + numLength + 1 + if abbrevLength >= n: + return s + return s[:prefixIndex + 1] + str(num) + s[-1] + + abbrevToIndexedWords = collections.defaultdict(list) + + for i, word in enumerate(words): + abbrev = getAbbrev(word, 0) + abbrevToIndexedWords[abbrev].append(IndexedWord(word, i)) + + def longestCommonPrefix(s1: str, s2: str) -> int: + i = 0 + while i < len(s1) and i < len(s2) and s1[i] == s2[i]: + i += 1 + return i + + for indexedWords in abbrevToIndexedWords.values(): + indexedWords.sort(key=lambda x: x.word) + lcp = [0] * len(indexedWords) + for i, (a, b) in enumerate(zip(indexedWords, indexedWords[1:])): + k = longestCommonPrefix(a.word, b.word) + lcp[i] = max(lcp[i], k) + lcp[i + 1] = k + for iw, l in zip(indexedWords, lcp): + ans[iw.index] = getAbbrev(iw.word, l) + + return ans diff --git a/solutions/527. Word Abbreviation/527-3.cpp b/solutions/527. Word Abbreviation/527-3.cpp new file mode 100644 index 00000000000..cba00f04d33 --- /dev/null +++ b/solutions/527. Word Abbreviation/527-3.cpp @@ -0,0 +1,70 @@ +struct IndexedWord { + string word; + int index; + IndexedWord(const string& word, int index) : word(word), index(index) {} +}; + +struct TrieNode { + vector> children; + int count = 0; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class Solution { + public: + vector wordsAbbreviation(vector& words) { + const int n = words.size(); + vector ans(n); + unordered_map> abbrevToIndexedWords; + + for (int i = 0; i < n; ++i) { + const string abbrev = getAbbrev(words[i], 0); + abbrevToIndexedWords[abbrev].emplace_back(words[i], i); + } + + for (auto& [_, indexedWords] : abbrevToIndexedWords) { + shared_ptr root = make_shared(); + for (const IndexedWord& iw : indexedWords) + insertWord(root, iw.word); + for (const IndexedWord& iw : indexedWords) { + const int index = firstUniqueIndex(root, iw.word); + ans[iw.index] = getAbbrev(iw.word, index); + } + } + + return ans; + } + + private: + string getAbbrev(const string& s, int prefixIndex) { + const int n = s.length(); + const int num = n - (prefixIndex + 1) - 1; + const int numLength = num < 10 ? 1 : num < 100 ? 2 : 3; + const int abbrevLength = (prefixIndex + 1) + numLength + 1; + if (abbrevLength >= n) + return s; + return s.substr(0, prefixIndex + 1) + to_string(num) + s.back(); + } + + void insertWord(shared_ptr root, const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + ++node->count; + } + } + + int firstUniqueIndex(shared_ptr root, const string& word) { + shared_ptr node = root; + for (int i = 0; i < word.length(); ++i) { + node = node->children[word[i] - 'a']; + if (node->count == 1) + return i; + } + return word.length(); + } +}; diff --git a/solutions/527. Word Abbreviation/527-3.java b/solutions/527. Word Abbreviation/527-3.java new file mode 100644 index 00000000000..5c0c6fb1eee --- /dev/null +++ b/solutions/527. Word Abbreviation/527-3.java @@ -0,0 +1,69 @@ +class IndexedWord { + public String word; + public int index; + public IndexedWord(final String word, int index) { + this.word = word; + this.index = index; + } +} + +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int count = 0; +} + +class Solution { + public List wordsAbbreviation(List words) { + String[] ans = new String[words.size()]; + Map> abbrevToIndexedWords = new HashMap<>(); + + for (int i = 0; i < words.size(); ++i) { + final String abbrev = getAbbrev(words.get(i), 0); + abbrevToIndexedWords.putIfAbsent(abbrev, new ArrayList<>()); + abbrevToIndexedWords.get(abbrev).add(new IndexedWord(words.get(i), i)); + } + + for (List indexedWords : abbrevToIndexedWords.values()) { + TrieNode root = new TrieNode(); + for (IndexedWord iw : indexedWords) + insertWord(root, iw.word); + for (IndexedWord iw : indexedWords) { + final int index = firstUniqueIndex(root, iw.word); + ans[iw.index] = getAbbrev(iw.word, index); + } + } + + return Arrays.asList(ans); + } + + private String getAbbrev(final String s, int prefixIndex) { + final int n = s.length(); + final int num = n - (prefixIndex + 1) - 1; + final int numLength = num < 10 ? 1 : num < 100 ? 2 : 3; + final int abbrevLength = (prefixIndex + 1) + numLength + 1; + if (abbrevLength >= n) + return s; + return s.substring(0, prefixIndex + 1) + num + s.charAt(n - 1); + } + + private void insertWord(TrieNode root, final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + ++node.count; + } + } + + private int firstUniqueIndex(TrieNode root, final String word) { + TrieNode node = root; + for (int i = 0; i < word.length(); ++i) { + node = node.children[word.charAt(i) - 'a']; + if (node.count == 1) + return i; + } + return word.length(); + } +} diff --git a/solutions/527. Word Abbreviation/527-3.py b/solutions/527. Word Abbreviation/527-3.py new file mode 100644 index 00000000000..ff014fbcfdc --- /dev/null +++ b/solutions/527. Word Abbreviation/527-3.py @@ -0,0 +1,55 @@ +class IndexedWord: + def __init__(self, word: str, index: int): + self.word = word + self.index = index + + +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode) + self.count = 0 + + +class Solution: + def wordsAbbreviation(self, words: List[str]) -> List[str]: + n = len(words) + ans = [''] * n + + def getAbbrev(s: str, prefixIndex: int) -> str: + n = len(s) + num = n - (prefixIndex + 1) - 1 + numLength = 1 if num < 10 else (2 if num < 100 else 3) + abbrevLength = (prefixIndex + 1) + numLength + 1 + if abbrevLength >= n: + return s + return s[:prefixIndex + 1] + str(num) + s[-1] + + abbrevToIndexedWords = collections.defaultdict(list) + + for i, word in enumerate(words): + abbrev = getAbbrev(word, 0) + abbrevToIndexedWords[abbrev].append(IndexedWord(word, i)) + + def insertWord(root: Optional[TrieNode], word: str) -> None: + node = root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.count += 1 + + def firstUniqueIndex(root: Optional[TrieNode], word: str) -> None: + node = root + for i, c in enumerate(word): + node = node.children[c] + if node.count == 1: + return i + return len(word) + + for indexedWords in abbrevToIndexedWords.values(): + root = TrieNode() + for iw in indexedWords: + insertWord(root, iw.word) + for iw in indexedWords: + index = firstUniqueIndex(root, iw.word) + ans[iw.index] = getAbbrev(iw.word, index) + + return ans diff --git a/solutions/527. Word Abbreviation/527.cpp b/solutions/527. Word Abbreviation/527.cpp new file mode 100644 index 00000000000..7315d755587 --- /dev/null +++ b/solutions/527. Word Abbreviation/527.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + vector wordsAbbreviation(vector& words) { + const int n = words.size(); + vector ans; + // prefix[i] := ans[i] takes words[i][0..prefix[i]] + vector prefix(n); + + for (const string& word : words) + ans.push_back(getAbbrev(word, 0)); + + for (int i = 0; i < n; ++i) { + while (true) { + vector dupeIndices; + for (int j = i + 1; j < n; ++j) + if (ans[i] == ans[j]) + dupeIndices.push_back(j); + if (dupeIndices.empty()) + break; + dupeIndices.push_back(i); + for (const int index : dupeIndices) + ans[index] = getAbbrev(words[index], ++prefix[index]); + } + } + + return ans; + } + + private: + string getAbbrev(const string& s, int prefixIndex) { + const int n = s.length(); + const int num = n - (prefixIndex + 1) - 1; + const int numLength = num < 10 ? 1 : num < 100 ? 2 : 3; + const int abbrevLength = (prefixIndex + 1) + numLength + 1; + if (abbrevLength >= n) + return s; + return s.substr(0, prefixIndex + 1) + to_string(num) + s.back(); + } +}; diff --git a/solutions/527. Word Abbreviation/527.java b/solutions/527. Word Abbreviation/527.java new file mode 100644 index 00000000000..7231c0cfacc --- /dev/null +++ b/solutions/527. Word Abbreviation/527.java @@ -0,0 +1,36 @@ +class Solution { + public List wordsAbbreviation(List words) { + final int n = words.size(); + List ans = new ArrayList<>(); + // prefix[i] := ans[i] takes words[i][0..prefix[i]] + int[] prefix = new int[n]; + + for (int i = 0; i < n; ++i) + ans.add(getAbbrev(words.get(i), 0)); + + for (int i = 0; i < n; ++i) + while (true) { + List dupeIndices = new ArrayList<>(); + for (int j = i + 1; j < n; ++j) + if (ans.get(i).equals(ans.get(j))) + dupeIndices.add(j); + if (dupeIndices.isEmpty()) + break; + dupeIndices.add(i); + for (final int dupeIndex : dupeIndices) + ans.set(dupeIndex, getAbbrev(words.get(dupeIndex), ++prefix[dupeIndex])); + } + + return ans; + } + + private String getAbbrev(final String s, int prefixIndex) { + final int n = s.length(); + final int num = n - (prefixIndex + 1) - 1; + final int numLength = num < 10 ? 1 : num < 100 ? 2 : 3; + final int abbrevLength = (prefixIndex + 1) + numLength + 1; + if (abbrevLength >= n) + return s; + return s.substring(0, prefixIndex + 1) + num + s.charAt(n - 1); + } +} diff --git a/solutions/527. Word Abbreviation/527.py b/solutions/527. Word Abbreviation/527.py new file mode 100644 index 00000000000..167897eddcc --- /dev/null +++ b/solutions/527. Word Abbreviation/527.py @@ -0,0 +1,31 @@ +class Solution: + def wordsAbbreviation(self, words: List[str]) -> List[str]: + n = len(words) + + def getAbbrev(s: str, prefixIndex: int) -> str: + n = len(s) + num = n - (prefixIndex + 1) - 1 + numLength = 1 if num < 10 else (2 if num < 100 else 3) + abbrevLength = (prefixIndex + 1) + numLength + 1 + if abbrevLength >= n: + return s + return s[:prefixIndex + 1] + str(num) + s[-1] + + ans = [getAbbrev(word, 0) for word in words] + # prefix[i] := ans[i] takes words[i][0..prefix[i]] + prefix = [0] * n + + for i in range(n): + while True: + dupeIndices = [] + for j in range(i + 1, n): + if ans[i] == ans[j]: + dupeIndices.append(j) + if not dupeIndices: + break + dupeIndices.append(i) + for index in dupeIndices: + prefix[index] += 1 + ans[index] = getAbbrev(words[index], prefix[index]) + + return ans diff --git a/solutions/528. Random Pick with Weight/528-2.cpp b/solutions/528. Random Pick with Weight/528-2.cpp new file mode 100644 index 00000000000..4a70f515944 --- /dev/null +++ b/solutions/528. Random Pick with Weight/528-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + Solution(vector& w) : prefix(w.size()) { + partial_sum(w.begin(), w.end(), prefix.begin()); + } + + int pickIndex() { + const int target = rand() % prefix.back(); + return ranges::upper_bound(prefix, target) - prefix.begin(); + } + + private: + vector prefix; +}; diff --git a/solutions/528. Random Pick with Weight/528-2.py b/solutions/528. Random Pick with Weight/528-2.py new file mode 100644 index 00000000000..325216f4c74 --- /dev/null +++ b/solutions/528. Random Pick with Weight/528-2.py @@ -0,0 +1,6 @@ +class Solution: + def __init__(self, w: List[int]): + self.prefix = list(itertools.accumulate(w)) + + def pickIndex(self) -> int: + return bisect_left(self.prefix, random.random() * self.prefix[-1]) diff --git a/solutions/528. Random Pick with Weight/528.cpp b/solutions/528. Random Pick with Weight/528.cpp new file mode 100644 index 00000000000..1b40a31c904 --- /dev/null +++ b/solutions/528. Random Pick with Weight/528.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + Solution(vector& w) : prefix(w.size()) { + partial_sum(w.begin(), w.end(), prefix.begin()); + } + + int pickIndex() { + const int target = rand() % prefix.back(); + int l = 0; + int r = prefix.size(); + + while (l < r) { + const int m = (l + r) / 2; + if (prefix[m] > target) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + vector prefix; +}; diff --git a/solutions/528. Random Pick with Weight/528.java b/solutions/528. Random Pick with Weight/528.java new file mode 100644 index 00000000000..9a2f153f9a5 --- /dev/null +++ b/solutions/528. Random Pick with Weight/528.java @@ -0,0 +1,26 @@ +class Solution { + public Solution(int[] w) { + prefix = w; + for (int i = 1; i < prefix.length; ++i) + prefix[i] += prefix[i - 1]; + } + + public int pickIndex() { + final int target = rand.nextInt(prefix[prefix.length - 1]); + int l = 0; + int r = prefix.length; + + while (l < r) { + final int m = (l + r) / 2; + if (prefix[m] > target) + r = m; + else + l = m + 1; + } + + return l; + } + + private int[] prefix; + private Random rand = new Random(); +} diff --git a/solutions/528. Random Pick with Weight/528.py b/solutions/528. Random Pick with Weight/528.py new file mode 100644 index 00000000000..6a2e2408a44 --- /dev/null +++ b/solutions/528. Random Pick with Weight/528.py @@ -0,0 +1,8 @@ +class Solution: + def __init__(self, w: List[int]): + self.prefix = list(itertools.accumulate(w)) + + def pickIndex(self) -> int: + target = random.randint(0, self.prefix[-1] - 1) + return bisect.bisect_right(range(len(self.prefix)), target, + key=lambda m: self.prefix[m]) diff --git a/solutions/529. Minesweeper/529.cpp b/solutions/529. Minesweeper/529.cpp new file mode 100644 index 00000000000..3df821c7540 --- /dev/null +++ b/solutions/529. Minesweeper/529.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + vector> updateBoard(vector>& board, + vector& click) { + const int i = click[0]; + const int j = click[1]; + if (board[i][j] == 'M') { + board[i][j] = 'X'; + return board; + } + + dfs(board, i, j); + return board; + } + + private: + static constexpr int dirs[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, + {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + + void dfs(vector>& board, int i, int j) { + if (i < 0 || i == board.size() || j < 0 || j == board[0].size()) + return; + if (board[i][j] != 'E') + return; + + const int minesCount = getMinesCount(board, i, j); + board[i][j] = minesCount == 0 ? 'B' : '0' + minesCount; + + if (minesCount == 0) + for (const auto& [dx, dy] : dirs) + dfs(board, i + dx, j + dy); + } + + int getMinesCount(const vector>& board, int i, int j) { + int minesCount = 0; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == board.size() || y < 0 || y == board[0].size()) + continue; + if (board[x][y] == 'M') + ++minesCount; + } + return minesCount; + } +}; diff --git a/solutions/529. Minesweeper/529.java b/solutions/529. Minesweeper/529.java new file mode 100644 index 00000000000..575cb3f92dd --- /dev/null +++ b/solutions/529. Minesweeper/529.java @@ -0,0 +1,43 @@ +class Solution { + public char[][] updateBoard(char[][] board, int[] click) { + final int i = click[0]; + final int j = click[1]; + if (board[i][j] == 'M') { + board[i][j] = 'X'; + return board; + } + + dfs(board, i, j); + return board; + } + + private static final int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, + {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + + private void dfs(char[][] board, int i, int j) { + if (i < 0 || i == board.length || j < 0 || j == board[0].length) + return; + if (board[i][j] != 'E') + return; + + final int minesCount = getMinesCount(board, i, j); + board[i][j] = minesCount == 0 ? 'B' : (char) ('0' + minesCount); + + if (minesCount == 0) + for (int[] dir : dirs) + dfs(board, i + dir[0], j + dir[1]); + } + + private int getMinesCount(char[][] board, int i, int j) { + int minesCount = 0; + for (final int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == board.length || y < 0 || y == board[0].length) + continue; + if (board[x][y] == 'M') + ++minesCount; + } + return minesCount; + } +} diff --git a/solutions/529. Minesweeper/529.py b/solutions/529. Minesweeper/529.py new file mode 100644 index 00000000000..393cd71b83c --- /dev/null +++ b/solutions/529. Minesweeper/529.py @@ -0,0 +1,36 @@ +class Solution: + def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: + i, j = click + if board[i][j] == 'M': + board[i][j] = 'X' + return board + + dirs = ((-1, -1), (-1, 0), (-1, 1), (0, -1), + (0, 1), (1, -1), (1, 0), (1, 1)) + + def getMinesCount(i: int, j: int) -> int: + minesCount = 0 + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == len(board) or y < 0 or y == len(board[0]): + continue + if board[x][y] == 'M': + minesCount += 1 + return minesCount + + def dfs(i: int, j: int) -> None: + if i < 0 or i == len(board) or j < 0 or j == len(board[0]): + return + if board[i][j] != 'E': + return + + minesCount = getMinesCount(i, j) + board[i][j] = 'B' if minesCount == 0 else str(minesCount) + + if minesCount == 0: + for dx, dy in dirs: + dfs(i + dx, j + dy) + + dfs(i, j) + return board diff --git a/solutions/53. Maximum Subarray/53-2.cpp b/solutions/53. Maximum Subarray/53-2.cpp new file mode 100644 index 00000000000..9df5c81db53 --- /dev/null +++ b/solutions/53. Maximum Subarray/53-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxSubArray(vector& nums) { + int ans = INT_MIN; + int sum = 0; + + for (const int num : nums) { + sum = max(num, sum + num); + ans = max(ans, sum); + } + + return ans; + } +}; diff --git a/solutions/53. Maximum Subarray/53-2.java b/solutions/53. Maximum Subarray/53-2.java new file mode 100644 index 00000000000..6f153eddfef --- /dev/null +++ b/solutions/53. Maximum Subarray/53-2.java @@ -0,0 +1,13 @@ +class Solution { + public int maxSubArray(int[] nums) { + int ans = Integer.MIN_VALUE; + int sum = 0; + + for (final int num : nums) { + sum = Math.max(num, sum + num); + ans = Math.max(ans, sum); + } + + return ans; + } +} diff --git a/solutions/53. Maximum Subarray/53-2.py b/solutions/53. Maximum Subarray/53-2.py new file mode 100644 index 00000000000..d5347cfdb0f --- /dev/null +++ b/solutions/53. Maximum Subarray/53-2.py @@ -0,0 +1,10 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + ans = -math.inf + summ = 0 + + for num in nums: + summ = max(num, summ + num) + ans = max(ans, summ) + + return ans diff --git a/solutions/53. Maximum Subarray/53-3.cpp b/solutions/53. Maximum Subarray/53-3.cpp new file mode 100644 index 00000000000..3a981d779a3 --- /dev/null +++ b/solutions/53. Maximum Subarray/53-3.cpp @@ -0,0 +1,35 @@ +struct T { + // the sum of the subarray starting from the first number + int maxSubarraySumLeft; + // the sum of the subarray ending in the last number + int maxSubarraySumRight; + int maxSubarraySum; + int sum; +}; + +class Solution { + public: + int maxSubArray(vector& nums) { + return divideAndConquer(nums, 0, nums.size() - 1).maxSubarraySum; + } + + private: + T divideAndConquer(const vector& nums, int l, int r) { + if (l == r) + return {nums[l], nums[l], nums[l], nums[l]}; + + const int m = (l + r) / 2; + const T t1 = divideAndConquer(nums, l, m); + const T t2 = divideAndConquer(nums, m + 1, r); + + const int maxSubarraySumLeft = + max(t1.maxSubarraySumLeft, t1.sum + t2.maxSubarraySumLeft); + const int maxSubarraySumRight = + max(t1.maxSubarraySumRight + t2.sum, t2.maxSubarraySumRight); + const int maxSubarraySum = + max({t1.maxSubarraySumRight + t2.maxSubarraySumLeft, t1.maxSubarraySum, + t2.maxSubarraySum}); + const int sum = t1.sum + t2.sum; + return {maxSubarraySumLeft, maxSubarraySumRight, maxSubarraySum, sum}; + } +}; diff --git a/solutions/53. Maximum Subarray/53-3.java b/solutions/53. Maximum Subarray/53-3.java new file mode 100644 index 00000000000..a18a9f1ed90 --- /dev/null +++ b/solutions/53. Maximum Subarray/53-3.java @@ -0,0 +1,29 @@ +class Solution { + public int maxSubArray(int[] nums) { + return divideAndConquer(nums, 0, nums.length - 1).maxSubarraySum; + } + + private T divideAndConquer(int[] nums, int l, int r) { + if (l == r) + return new T(nums[l], nums[l], nums[l], nums[l]); + + final int m = (l + r) / 2; + final T t1 = divideAndConquer(nums, l, m); + final T t2 = divideAndConquer(nums, m + 1, r); + + final int maxSubarraySumLeft = Math.max(t1.maxSubarraySumLeft, t1.sum + t2.maxSubarraySumLeft); + final int maxSubarraySumRight = + Math.max(t1.maxSubarraySumRight + t2.sum, t2.maxSubarraySumRight); + final int maxSubarraySum = Math.max(t1.maxSubarraySumRight + t2.maxSubarraySumLeft, + Math.max(t1.maxSubarraySum, t2.maxSubarraySum)); + final int sum = t1.sum + t2.sum; + return new T(maxSubarraySumLeft, maxSubarraySumRight, maxSubarraySum, sum); + } + + private record T( + // the sum of the subarray starting from the first number + int maxSubarraySumLeft, + // the sum of the subarray ending in the last number + int maxSubarraySumRight, // + int maxSubarraySum, int sum) {} +} diff --git a/solutions/53. Maximum Subarray/53-3.py b/solutions/53. Maximum Subarray/53-3.py new file mode 100644 index 00000000000..5cf5a4a5f7f --- /dev/null +++ b/solutions/53. Maximum Subarray/53-3.py @@ -0,0 +1,33 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True) +class T: + # the sum of the subarray starting from the first number + maxSubarraySumLeft: int + # the sum of the subarray ending in the last number + maxSubarraySumRight: int + maxSubarraySum: int + summ: int + + +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + def divideAndConquer(l: int, r: int) -> T: + if l == r: + return T(nums[l], nums[l], nums[l], nums[l]) + + m = (l + r) // 2 + t1 = divideAndConquer(l, m) + t2 = divideAndConquer(m + 1, r) + + maxSubarraySumLeft = max(t1.maxSubarraySumLeft, + t1.summ + t2.maxSubarraySumLeft) + maxSubarraySumRight = max( + t1.maxSubarraySumRight + t2.summ, t2.maxSubarraySumRight) + maxSubarraySum = max(t1.maxSubarraySumRight + + t2.maxSubarraySumLeft, t1.maxSubarraySum, t2.maxSubarraySum) + summ = t1.summ + t2.summ + return T(maxSubarraySumLeft, maxSubarraySumRight, maxSubarraySum, summ) + + return divideAndConquer(0, len(nums) - 1).maxSubarraySum diff --git a/solutions/53. Maximum Subarray/53.cpp b/solutions/53. Maximum Subarray/53.cpp new file mode 100644 index 00000000000..d41268c56b1 --- /dev/null +++ b/solutions/53. Maximum Subarray/53.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int maxSubArray(vector& nums) { + // dp[i] := the maximum sum subarray ending in i + vector dp(nums.size()); + + dp[0] = nums[0]; + for (int i = 1; i < nums.size(); ++i) + dp[i] = max(nums[i], dp[i - 1] + nums[i]); + + return ranges::max(dp); + } +}; diff --git a/solutions/53. Maximum Subarray/53.java b/solutions/53. Maximum Subarray/53.java new file mode 100644 index 00000000000..08ecd393aab --- /dev/null +++ b/solutions/53. Maximum Subarray/53.java @@ -0,0 +1,12 @@ +class Solution { + public int maxSubArray(int[] nums) { + // dp[i] := the maximum sum subarray ending in i + int[] dp = new int[nums.length]; + + dp[0] = nums[0]; + for (int i = 1; i < nums.length; ++i) + dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]); + + return Arrays.stream(dp).max().getAsInt(); + } +} diff --git a/solutions/53. Maximum Subarray/53.py b/solutions/53. Maximum Subarray/53.py new file mode 100644 index 00000000000..e1016da1e3c --- /dev/null +++ b/solutions/53. Maximum Subarray/53.py @@ -0,0 +1,10 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + # dp[i] := the maximum sum subarray ending in i + dp = [0] * len(nums) + + dp[0] = nums[0] + for i in range(1, len(nums)): + dp[i] = max(nums[i], dp[i - 1] + nums[i]) + + return max(dp) diff --git a/solutions/530. Minimum Absolute Difference in BST/530.cpp b/solutions/530. Minimum Absolute Difference in BST/530.cpp new file mode 100644 index 00000000000..be67a741fc6 --- /dev/null +++ b/solutions/530. Minimum Absolute Difference in BST/530.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + // Similar to 94. Binary Tree Inorder Traversal + int getMinimumDifference(TreeNode* root) { + int ans = INT_MAX; + int prev = -1; + stack stack; + + while (root || !stack.empty()) { + while (root) { + stack.push(root); + root = root->left; + } + root = stack.top(), stack.pop(); + if (prev >= 0) + ans = min(ans, root->val - prev); + prev = root->val; + root = root->right; + } + + return ans; + } +}; diff --git a/solutions/530. Minimum Absolute Difference in BST/530.java b/solutions/530. Minimum Absolute Difference in BST/530.java new file mode 100644 index 00000000000..504e6938fa0 --- /dev/null +++ b/solutions/530. Minimum Absolute Difference in BST/530.java @@ -0,0 +1,22 @@ +class Solution { + // Similar to 94. Binary Tree Inorder Traversal + public int getMinimumDifference(TreeNode root) { + int ans = Integer.MAX_VALUE; + int prev = -1; + Deque stack = new ArrayDeque<>(); + + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + root = stack.pop(); + if (prev >= 0) + ans = Math.min(ans, root.val - prev); + prev = root.val; + root = root.right; + } + + return ans; + } +} diff --git a/solutions/531. Lonely Pixel I/531.cpp b/solutions/531. Lonely Pixel I/531.cpp new file mode 100644 index 00000000000..2278ab44dce --- /dev/null +++ b/solutions/531. Lonely Pixel I/531.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int findLonelyPixel(vector>& picture) { + const int m = picture.size(); + const int n = picture[0].size(); + int ans = 0; + vector rows(m); // rows[i] := the number of B's in rows i + vector cols(n); // cols[i] := the number of B's in cols i + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (picture[i][j] == 'B') { + ++rows[i]; + ++cols[j]; + } + + for (int i = 0; i < m; ++i) + if (rows[i] == 1) // Only have to examine the rows if rows[i] == 1. + for (int j = 0; j < n; ++j) + // After meeting a 'B' in this rows, break and search the next row. + if (picture[i][j] == 'B') { + if (cols[j] == 1) + ++ans; + break; + } + + return ans; + } +}; diff --git a/solutions/531. Lonely Pixel I/531.java b/solutions/531. Lonely Pixel I/531.java new file mode 100644 index 00000000000..6ff6061be10 --- /dev/null +++ b/solutions/531. Lonely Pixel I/531.java @@ -0,0 +1,28 @@ +class Solution { + public int findLonelyPixel(char[][] picture) { + final int m = picture.length; + final int n = picture[0].length; + int ans = 0; + int[] rows = new int[m]; // rows[i] := the number of B's in rows i + int[] cols = new int[n]; // cols[i] := the number of B's in cols i + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (picture[i][j] == 'B') { + ++rows[i]; + ++cols[j]; + } + + for (int i = 0; i < m; ++i) + if (rows[i] == 1) // Only have to examine the rows if rows[i] == 1. + for (int j = 0; j < n; ++j) + // After meeting a 'B' in this rows, break and search the next row. + if (picture[i][j] == 'B') { + if (cols[j] == 1) + ++ans; + break; + } + + return ans; + } +} diff --git a/solutions/531. Lonely Pixel I/531.py b/solutions/531. Lonely Pixel I/531.py new file mode 100644 index 00000000000..1ff7fb8d197 --- /dev/null +++ b/solutions/531. Lonely Pixel I/531.py @@ -0,0 +1,24 @@ +class Solution: + def findLonelyPixel(self, picture: List[List[str]]) -> int: + m = len(picture) + n = len(picture[0]) + ans = 0 + rows = [0] * m # rows[i] := the number of B's in rows i + cols = [0] * n # cols[i] := the number of B's in cols i + + for i in range(m): + for j in range(n): + if picture[i][j] == 'B': + rows[i] += 1 + cols[j] += 1 + + for i in range(m): + if rows[i] == 1: # Only have to examine the rows if rows[i] == 1. + for j in range(n): + # After meeting a 'B' in this rows, break and search the next row. + if picture[i][j] == 'B': + if cols[j] == 1: + ans += 1 + break + + return ans diff --git a/solutions/532. K-diff Pairs in an Array/532.cpp b/solutions/532. K-diff Pairs in an Array/532.cpp new file mode 100644 index 00000000000..a5a90a55472 --- /dev/null +++ b/solutions/532. K-diff Pairs in an Array/532.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int findPairs(vector& nums, int k) { + int ans = 0; + unordered_map numToIndex; + + for (int i = 0; i < nums.size(); ++i) + numToIndex[nums[i]] = i; + + for (int i = 0; i < nums.size(); ++i) { + const int target = nums[i] + k; + if (const auto it = numToIndex.find(target); + it != numToIndex.cend() && it->second != i) { + ++ans; + numToIndex.erase(target); + } + } + + return ans; + } +}; diff --git a/solutions/532. K-diff Pairs in an Array/532.java b/solutions/532. K-diff Pairs in an Array/532.java new file mode 100644 index 00000000000..fe079ef75d2 --- /dev/null +++ b/solutions/532. K-diff Pairs in an Array/532.java @@ -0,0 +1,19 @@ +class Solution { + public int findPairs(int[] nums, int k) { + int ans = 0; + Map numToIndex = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) + numToIndex.put(nums[i], i); + + for (int i = 0; i < nums.length; ++i) { + final int target = nums[i] + k; + if (numToIndex.containsKey(target) && numToIndex.get(target) != i) { + ++ans; + numToIndex.remove(target); + } + } + + return ans; + } +} diff --git a/solutions/532. K-diff Pairs in an Array/532.py b/solutions/532. K-diff Pairs in an Array/532.py new file mode 100644 index 00000000000..0c3aa1a3519 --- /dev/null +++ b/solutions/532. K-diff Pairs in an Array/532.py @@ -0,0 +1,12 @@ +class Solution: + def findPairs(self, nums: List[int], k: int) -> int: + ans = 0 + numToIndex = {num: i for i, num in enumerate(nums)} + + for i, num in enumerate(nums): + target = num + k + if target in numToIndex and numToIndex[target] != i: + ans += 1 + del numToIndex[target] + + return ans diff --git a/solutions/533. Lonely Pixel II/533.cpp b/solutions/533. Lonely Pixel II/533.cpp new file mode 100644 index 00000000000..d1bb2795f2f --- /dev/null +++ b/solutions/533. Lonely Pixel II/533.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int findBlackPixel(vector>& picture, int target) { + const int m = picture.size(); + const int n = picture[0].size(); + int ans = 0; + vector rows(m); + vector cols(n); + vector rowStrings(m); + unordered_map countRowStrings; + + for (int i = 0; i < m; ++i) { + string s; + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B') { + ++rows[i]; + ++cols[j]; + } + s += picture[i][j]; + } + rowStrings[i] = s; + ++countRowStrings[s]; + } + + for (int i = 0; i < m; ++i) + if (rows[i] == target && countRowStrings[rowStrings[i]] == target) + for (int j = 0; j < n; ++j) + if (picture[i][j] == 'B' && cols[j] == target) + ++ans; + + return ans; + } +}; diff --git a/solutions/533. Lonely Pixel II/533.java b/solutions/533. Lonely Pixel II/533.java new file mode 100644 index 00000000000..2fde1cc424f --- /dev/null +++ b/solutions/533. Lonely Pixel II/533.java @@ -0,0 +1,32 @@ +class Solution { + public int findBlackPixel(char[][] picture, int target) { + final int m = picture.length; + final int n = picture[0].length; + int ans = 0; + int[] rows = new int[m]; + int[] cols = new int[n]; + String[] rowStrings = new String[m]; + Map countRowStrings = new HashMap<>(); + + for (int i = 0; i < m; ++i) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B') { + ++rows[i]; + ++cols[j]; + } + sb.append(picture[i][j]); + } + rowStrings[i] = sb.toString(); + countRowStrings.merge(rowStrings[i], 1, Integer::sum); + } + + for (int i = 0; i < m; ++i) + if (rows[i] == target && countRowStrings.get(rowStrings[i]) == target) + for (int j = 0; j < n; ++j) + if (picture[i][j] == 'B' && cols[j] == target) + ++ans; + + return ans; + } +} diff --git a/solutions/533. Lonely Pixel II/533.py b/solutions/533. Lonely Pixel II/533.py new file mode 100644 index 00000000000..cb19080c008 --- /dev/null +++ b/solutions/533. Lonely Pixel II/533.py @@ -0,0 +1,17 @@ +class Solution: + def findBlackPixel(self, picture: List[List[str]], target: int) -> int: + m = len(picture) + n = len(picture[0]) + ans = 0 + rows = [row.count('B') for row in picture] + cols = [col.count('B') for col in zip(*picture)] + rowStrings = [''.join(row) for row in picture] + countRowStrings = collections.Counter(rowStrings) + + for i, (row, stringRow) in enumerate(zip(rows, rowStrings)): + if row == target and countRowStrings[stringRow] == target: + for j, col in enumerate(cols): + if picture[i][j] == 'B' and col == target: + ans += 1 + + return ans diff --git a/solutions/534. Game Play Analysis III/534.sql b/solutions/534. Game Play Analysis III/534.sql new file mode 100644 index 00000000000..acb67f1bff7 --- /dev/null +++ b/solutions/534. Game Play Analysis III/534.sql @@ -0,0 +1,11 @@ +SELECT + Activity.player_id, + Activity.event_date, + SUM(PrevActivity.games_played) AS games_played_so_far +FROM Activity +INNER JOIN Activity AS PrevActivity + ON ( + Activity.player_id = PrevActivity.player_id + AND Activity.event_date >= PrevActivity.event_date) +GROUP BY 1, 2 +ORDER BY 1, 2; diff --git a/solutions/535. Encode and Decode TinyURL/535.cpp b/solutions/535. Encode and Decode TinyURL/535.cpp new file mode 100644 index 00000000000..2f519229f23 --- /dev/null +++ b/solutions/535. Encode and Decode TinyURL/535.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string encode(string longUrl) { + while (!urlToCode.contains(longUrl)) { + string code; + for (int i = 0; i < 6; ++i) + code += alphabets[rand() % alphabets.size()]; + if (!codeToUrl.contains(code)) { + codeToUrl[code] = longUrl; + urlToCode[longUrl] = code; + return "http://tinyurl.com/" + code; + } + } + + throw; + } + + string decode(string shortUrl) { + return codeToUrl[shortUrl.substr(19)]; + } + + private: + const string alphabets = + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + unordered_map urlToCode; + unordered_map codeToUrl; +}; diff --git a/solutions/535. Encode and Decode TinyURL/535.java b/solutions/535. Encode and Decode TinyURL/535.java new file mode 100644 index 00000000000..0989e94fff9 --- /dev/null +++ b/solutions/535. Encode and Decode TinyURL/535.java @@ -0,0 +1,29 @@ +public class Codec { + public String encode(String longUrl) { + while (!urlToCode.containsKey(longUrl)) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 6; ++i) { + final char nextChar = alphabets.charAt(rand.nextInt(alphabets.length())); + sb.append(nextChar); + } + final String code = sb.toString(); + if (!codeToUrl.containsKey(code)) { + codeToUrl.put(code, longUrl); + urlToCode.put(longUrl, code); + return "http://tinyurl.com/" + code; + } + } + + throw new IllegalArgumentException(); + } + + public String decode(String shortUrl) { + return codeToUrl.get(shortUrl.substring(19)); + } + + private static final String alphabets = + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private Map urlToCode = new HashMap<>(); + private Map codeToUrl = new HashMap<>(); + private Random rand = new Random(); +} diff --git a/solutions/535. Encode and Decode TinyURL/535.py b/solutions/535. Encode and Decode TinyURL/535.py new file mode 100644 index 00000000000..181dff1bf1b --- /dev/null +++ b/solutions/535. Encode and Decode TinyURL/535.py @@ -0,0 +1,15 @@ +class Codec: + alphabets = string.ascii_letters + '0123456789' + urlToCode = {} + codeToUrl = {} + + def encode(self, longUrl: str) -> str: + while longUrl not in self.urlToCode: + code = ''.join(random.choice(self.alphabets) for _ in range(6)) + if code not in self.codeToUrl: + self.codeToUrl[code] = longUrl + self.urlToCode[longUrl] = code + return 'http://tinyurl.com/' + self.urlToCode[longUrl] + + def decode(self, shortUrl: str) -> str: + return self.codeToUrl[shortUrl[-6:]] diff --git a/solutions/536. Construct Binary Tree from String/536-2.cpp b/solutions/536. Construct Binary Tree from String/536-2.cpp new file mode 100644 index 00000000000..1c5272d0b94 --- /dev/null +++ b/solutions/536. Construct Binary Tree from String/536-2.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + TreeNode* str2tree(string s) { + if (s.empty()) + return nullptr; + + stack stack; + + for (int l = 0, r = 0; r < s.length(); l = ++r) + if (s[r] == ')') { + stack.pop(); + } else if (isdigit(s[r]) || s[r] == '-') { + while (r + 1 < s.length() && isdigit(s[r + 1])) + ++r; + const int val = stoi(s.substr(l, r - l + 1)); + TreeNode* node = new TreeNode(val); + if (!stack.empty()) { + TreeNode* parent = stack.top(); + if (parent->left) + parent->right = node; + else + parent->left = node; + } + stack.push(node); + } + + return stack.top(); + } +}; diff --git a/solutions/536. Construct Binary Tree from String/536-2.java b/solutions/536. Construct Binary Tree from String/536-2.java new file mode 100644 index 00000000000..2651a743295 --- /dev/null +++ b/solutions/536. Construct Binary Tree from String/536-2.java @@ -0,0 +1,28 @@ +class Solution { + public TreeNode str2tree(String s) { + if (s.isEmpty()) + return null; + + Deque stack = new ArrayDeque<>(); + + for (int l = 0, r = 0; r < s.length(); l = ++r) + if (s.charAt(r) == ')') { + stack.pop(); + } else if (Character.isDigit(s.charAt(r)) || s.charAt(r) == '-') { + while (r + 1 < s.length() && Character.isDigit(s.charAt(r + 1))) + ++r; + final int val = Integer.parseInt(s.substring(l, r + 1)); + TreeNode node = new TreeNode(val); + if (!stack.isEmpty()) { + TreeNode parent = stack.peek(); + if (parent.left != null) + parent.right = node; + else + parent.left = node; + } + stack.push(node); + } + + return stack.peek(); + } +} diff --git a/solutions/536. Construct Binary Tree from String/536.cpp b/solutions/536. Construct Binary Tree from String/536.cpp new file mode 100644 index 00000000000..9875208de2e --- /dev/null +++ b/solutions/536. Construct Binary Tree from String/536.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + TreeNode* str2tree(string s) { + if (s.empty()) + return nullptr; + int i = 0; + return str2tree(s, i); + } + + private: + TreeNode* str2tree(const string& s, int& i) { + const int start = i; // the start index of `val` + if (s[i] == '-') + ++i; + while (i < s.length() && isdigit(s[i])) + ++i; + + const int val = stoi(s.substr(start, i - start)); + TreeNode* root = new TreeNode(val); + + // the left child + if (i < s.length() && s[i] == '(') { + ++i; // '(' + root->left = str2tree(s, i); + ++i; // ')' + } + + // the right child + if (i < s.length() && s[i] == '(') { + ++i; // '(' + root->right = str2tree(s, i); + ++i; // ')' + } + + return root; + } +}; diff --git a/solutions/536. Construct Binary Tree from String/536.java b/solutions/536. Construct Binary Tree from String/536.java new file mode 100644 index 00000000000..15d23135b04 --- /dev/null +++ b/solutions/536. Construct Binary Tree from String/536.java @@ -0,0 +1,36 @@ +class Solution { + public TreeNode str2tree(String s) { + if (s.isEmpty()) + return null; + return helper(s); + } + + private int i = 0; + + private TreeNode helper(final String s) { + final int start = i; // the start index of `val` + if (s.charAt(i) == '-') + ++i; + while (i < s.length() && Character.isDigit(s.charAt(i))) + ++i; + + final int val = Integer.parseInt(s.substring(start, i)); + TreeNode root = new TreeNode(val); + + // the left child + if (i < s.length() && s.charAt(i) == '(') { + ++i; // '(' + root.left = helper(s); + ++i; // ')' + } + + // the right child + if (i < s.length() && s.charAt(i) == '(') { + ++i; // '(' + root.right = helper(s); + ++i; // ')' + } + + return root; + } +} diff --git a/solutions/537. Complex Number Multiplication/537.cpp b/solutions/537. Complex Number Multiplication/537.cpp new file mode 100644 index 00000000000..3efc743ec80 --- /dev/null +++ b/solutions/537. Complex Number Multiplication/537.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + string complexNumberMultiply(string a, string b) { + const auto& [A, B] = getRealAndImag(a); + const auto& [C, D] = getRealAndImag(b); + return to_string(A * C - B * D) + "+" + to_string(A * D + B * C) + "i"; + } + + private: + pair getRealAndImag(const string& s) { + const string& real = s.substr(0, s.find_first_of('+')); + const string& imag = s.substr(s.find_first_of('+') + 1); + return {stoi(real), stoi(imag)}; + }; +}; diff --git a/solutions/537. Complex Number Multiplication/537.java b/solutions/537. Complex Number Multiplication/537.java new file mode 100644 index 00000000000..f945c4eb24f --- /dev/null +++ b/solutions/537. Complex Number Multiplication/537.java @@ -0,0 +1,14 @@ +class Solution { + public String complexNumberMultiply(String a, String b) { + int[] A = getRealAndImag(a); + int[] B = getRealAndImag(b); + return String.valueOf(A[0] * B[0] - A[1] * B[1]) + "+" + + String.valueOf(A[0] * B[1] + A[1] * B[0]) + "i"; + } + + private int[] getRealAndImag(final String s) { + final String real = s.substring(0, s.indexOf('+')); + final String imag = s.substring(s.indexOf('+') + 1, s.length() - 1); + return new int[] {Integer.valueOf(real), Integer.valueOf(imag)}; + } +} diff --git a/solutions/537. Complex Number Multiplication/537.py b/solutions/537. Complex Number Multiplication/537.py new file mode 100644 index 00000000000..889511ae228 --- /dev/null +++ b/solutions/537. Complex Number Multiplication/537.py @@ -0,0 +1,9 @@ +class Solution: + def complexNumberMultiply(self, a: str, b: str) -> str: + def getRealAndImag(s: str) -> tuple: + return int(s[:s.index('+')]), int(s[s.index('+') + 1:-1]) + + A, B = getRealAndImag(a) + C, D = getRealAndImag(b) + + return str(A * C - B * D) + '+' + str(A * D + B * C) + 'i' diff --git a/solutions/538. Convert BST to Greater Tree/538.cpp b/solutions/538. Convert BST to Greater Tree/538.cpp new file mode 100644 index 00000000000..2f03b1a2d05 --- /dev/null +++ b/solutions/538. Convert BST to Greater Tree/538.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + TreeNode* convertBST(TreeNode* root) { + int prefix = 0; + reversedInorder(root, prefix); + return root; + } + + private: + void reversedInorder(TreeNode* root, int& prefix) { + if (root == nullptr) + return; + + reversedInorder(root->right, prefix); + prefix += root->val; + root->val = prefix; + reversedInorder(root->left, prefix); + } +}; diff --git a/solutions/538. Convert BST to Greater Tree/538.java b/solutions/538. Convert BST to Greater Tree/538.java new file mode 100644 index 00000000000..8f3f26b10b0 --- /dev/null +++ b/solutions/538. Convert BST to Greater Tree/538.java @@ -0,0 +1,18 @@ +class Solution { + public TreeNode convertBST(TreeNode root) { + reversedInorder(root); + return root; + } + + private int prefix = 0; + + private void reversedInorder(TreeNode root) { + if (root == null) + return; + + reversedInorder(root.right); + prefix += root.val; + root.val = prefix; + reversedInorder(root.left); + } +} diff --git a/solutions/538. Convert BST to Greater Tree/538.py b/solutions/538. Convert BST to Greater Tree/538.py new file mode 100644 index 00000000000..4d605c68957 --- /dev/null +++ b/solutions/538. Convert BST to Greater Tree/538.py @@ -0,0 +1,16 @@ +class Solution: + def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + prefix = 0 + + def reversedInorder(root: Optional[TreeNode]) -> None: + nonlocal prefix + if not root: + return + + reversedInorder(root.right) + prefix += root.val + root.val = prefix + reversedInorder(root.left) + + reversedInorder(root) + return root diff --git a/solutions/539. Minimum Time Difference/539.cpp b/solutions/539. Minimum Time Difference/539.cpp new file mode 100644 index 00000000000..7c37f32c968 --- /dev/null +++ b/solutions/539. Minimum Time Difference/539.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int findMinDifference(vector& timePoints) { + int ans = 24 * 60; + int first = 24 * 60; + vector bucket(24 * 60); + + for (const string& time : timePoints) { + const int num = stoi(time.substr(0, 2)) * 60 + stoi(time.substr(3)); + first = min(first, num); + if (bucket[num]) + return 0; + bucket[num] = true; + } + + int prev = first; + + for (int i = first + 1; i < bucket.size(); ++i) + if (bucket[i]) { + ans = min(ans, i - prev); + prev = i; + } + + return min(ans, 24 * 60 - prev + first); + } +}; diff --git a/solutions/539. Minimum Time Difference/539.java b/solutions/539. Minimum Time Difference/539.java new file mode 100644 index 00000000000..1ccd34e386d --- /dev/null +++ b/solutions/539. Minimum Time Difference/539.java @@ -0,0 +1,26 @@ +class Solution { + public int findMinDifference(List timePoints) { + int ans = 24 * 60; + int first = 24 * 60; + boolean[] bucket = new boolean[24 * 60]; + + for (final String timePoint : timePoints) { + final int num = + Integer.valueOf(timePoint.substring(0, 2)) * 60 + Integer.valueOf(timePoint.substring(3)); + first = Math.min(first, num); + if (bucket[num]) + return 0; + bucket[num] = true; + } + + int prev = first; + + for (int i = first + 1; i < bucket.length; ++i) + if (bucket[i]) { + ans = Math.min(ans, i - prev); + prev = i; + } + + return Math.min(ans, 24 * 60 - prev + first); + } +} diff --git a/solutions/539. Minimum Time Difference/539.py b/solutions/539. Minimum Time Difference/539.py new file mode 100644 index 00000000000..374f44d7504 --- /dev/null +++ b/solutions/539. Minimum Time Difference/539.py @@ -0,0 +1,10 @@ +class Solution: + def findMinDifference(self, timePoints: List[str]) -> int: + ans = 24 * 60 + nums = sorted([int(timePoint[:2]) * 60 + int(timePoint[3:]) + for timePoint in timePoints]) + + for a, b in zip(nums, nums[1:]): + ans = min(ans, b - a) + + return min(ans, 24 * 60 - nums[-1] + nums[0]) diff --git a/solutions/54. Spiral Matrix/54.cpp b/solutions/54. Spiral Matrix/54.cpp new file mode 100644 index 00000000000..6c83bc33097 --- /dev/null +++ b/solutions/54. Spiral Matrix/54.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector spiralOrder(vector>& matrix) { + if (matrix.empty()) + return {}; + + const int m = matrix.size(); + const int n = matrix[0].size(); + vector ans; + int r1 = 0; + int c1 = 0; + int r2 = m - 1; + int c2 = n - 1; + + // Repeatedly add matrix[r1..r2][c1..c2] to `ans`. + while (ans.size() < m * n) { + for (int j = c1; j <= c2 && ans.size() < m * n; ++j) + ans.push_back(matrix[r1][j]); + for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i) + ans.push_back(matrix[i][c2]); + for (int j = c2; j >= c1 && ans.size() < m * n; --j) + ans.push_back(matrix[r2][j]); + for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i) + ans.push_back(matrix[i][c1]); + ++r1, ++c1, --r2, --c2; + } + + return ans; + } +}; diff --git a/solutions/54. Spiral Matrix/54.java b/solutions/54. Spiral Matrix/54.java new file mode 100644 index 00000000000..83180ecacdb --- /dev/null +++ b/solutions/54. Spiral Matrix/54.java @@ -0,0 +1,32 @@ +class Solution { + public List spiralOrder(int[][] matrix) { + if (matrix.length == 0) + return new ArrayList<>(); + + final int m = matrix.length; + final int n = matrix[0].length; + List ans = new ArrayList<>(); + int r1 = 0; + int c1 = 0; + int r2 = m - 1; + int c2 = n - 1; + + // Repeatedly add matrix[r1..r2][c1..c2] to `ans`. + while (ans.size() < m * n) { + for (int j = c1; j <= c2 && ans.size() < m * n; ++j) + ans.add(matrix[r1][j]); + for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i) + ans.add(matrix[i][c2]); + for (int j = c2; j >= c1 && ans.size() < m * n; --j) + ans.add(matrix[r2][j]); + for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i) + ans.add(matrix[i][c1]); + ++r1; + ++c1; + --r2; + --c2; + } + + return ans; + } +} diff --git a/solutions/54. Spiral Matrix/54.py b/solutions/54. Spiral Matrix/54.py new file mode 100644 index 00000000000..48a42407a16 --- /dev/null +++ b/solutions/54. Spiral Matrix/54.py @@ -0,0 +1,37 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + if not matrix: + return [] + + m = len(matrix) + n = len(matrix[0]) + ans = [] + r1 = 0 + c1 = 0 + r2 = m - 1 + c2 = n - 1 + + # Repeatedly add matrix[r1..r2][c1..c2] to `ans`. + while len(ans) < m * n: + j = c1 + while j <= c2 and len(ans) < m * n: + ans.append(matrix[r1][j]) + j += 1 + i = r1 + 1 + while i <= r2 - 1 and len(ans) < m * n: + ans.append(matrix[i][c2]) + i += 1 + j = c2 + while j >= c1 and len(ans) < m * n: + ans.append(matrix[r2][j]) + j -= 1 + i = r2 - 1 + while i >= r1 + 1 and len(ans) < m * n: + ans.append(matrix[i][c1]) + i -= 1 + r1 += 1 + c1 += 1 + r2 -= 1 + c2 -= 1 + + return ans diff --git a/solutions/540. Single Element in a Sorted Array/540.cpp b/solutions/540. Single Element in a Sorted Array/540.cpp new file mode 100644 index 00000000000..0413bffe4b2 --- /dev/null +++ b/solutions/540. Single Element in a Sorted Array/540.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int singleNonDuplicate(vector& nums) { + int l = 0; + int r = nums.size() - 1; + + while (l < r) { + int m = (l + r) / 2; + if (m % 2 == 1) + --m; + if (nums[m] == nums[m + 1]) + l = m + 2; + else + r = m; + } + + return nums[l]; + } +}; diff --git a/solutions/540. Single Element in a Sorted Array/540.java b/solutions/540. Single Element in a Sorted Array/540.java new file mode 100644 index 00000000000..b5267566d29 --- /dev/null +++ b/solutions/540. Single Element in a Sorted Array/540.java @@ -0,0 +1,18 @@ +class Solution { + public int singleNonDuplicate(int[] nums) { + int l = 0; + int r = nums.length - 1; + + while (l < r) { + int m = (l + r) / 2; + if (m % 2 == 1) + --m; + if (nums[m] == nums[m + 1]) + l = m + 2; + else + r = m; + } + + return nums[l]; + } +} diff --git a/solutions/540. Single Element in a Sorted Array/540.py b/solutions/540. Single Element in a Sorted Array/540.py new file mode 100644 index 00000000000..30dadd06ce2 --- /dev/null +++ b/solutions/540. Single Element in a Sorted Array/540.py @@ -0,0 +1,15 @@ +class Solution: + def singleNonDuplicate(self, nums: List[int]) -> int: + l = 0 + r = len(nums) - 1 + + while l < r: + m = (l + r) // 2 + if m % 2 == 1: + m -= 1 + if nums[m] == nums[m + 1]: + l = m + 2 + else: + r = m + + return nums[l] diff --git a/solutions/541. Reverse String II/541.cpp b/solutions/541. Reverse String II/541.cpp new file mode 100644 index 00000000000..4f11f8f75d4 --- /dev/null +++ b/solutions/541. Reverse String II/541.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + string reverseStr(string s, int k) { + for (size_t i = 0; i < s.length(); i += 2 * k) { + int l = i; + int r = min(i + k - 1, s.length() - 1); + while (l < r) + swap(s[l++], s[r--]); + } + + return s; + } +}; diff --git a/solutions/541. Reverse String II/541.java b/solutions/541. Reverse String II/541.java new file mode 100644 index 00000000000..adbb7de090c --- /dev/null +++ b/solutions/541. Reverse String II/541.java @@ -0,0 +1,18 @@ +class Solution { + public String reverseStr(String s, int k) { + StringBuilder sb = new StringBuilder(s); + + for (int i = 0; i < sb.length(); i += 2 * k) { + int l = i; + int r = Math.min(i + k - 1, sb.length() - 1); + while (l < r) { + sb.setCharAt(l, s.charAt(r)); + sb.setCharAt(r, s.charAt(l)); + ++l; + --r; + } + } + + return sb.toString(); + } +} diff --git a/solutions/541. Reverse String II/541.py b/solutions/541. Reverse String II/541.py new file mode 100644 index 00000000000..4025de16e7c --- /dev/null +++ b/solutions/541. Reverse String II/541.py @@ -0,0 +1,3 @@ +class Solution: + def reverseStr(self, s: str, k: int) -> str: + return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k) if s else "" diff --git a/solutions/542. 01 Matrix/542-2.cpp b/solutions/542. 01 Matrix/542-2.cpp new file mode 100644 index 00000000000..6ac7e62a117 --- /dev/null +++ b/solutions/542. 01 Matrix/542-2.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + vector> updateMatrix(vector>& mat) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = mat.size(); + const int n = mat[0].size(); + queue> q; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 0) + q.emplace(i, j); + else + mat[i][j] = INT_MAX; + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (mat[x][y] <= mat[i][j] + 1) + continue; + q.emplace(x, y); + mat[x][y] = mat[i][j] + 1; + } + } + + return mat; + } +}; diff --git a/solutions/542. 01 Matrix/542-2.java b/solutions/542. 01 Matrix/542-2.java new file mode 100644 index 00000000000..9613248e7e8 --- /dev/null +++ b/solutions/542. 01 Matrix/542-2.java @@ -0,0 +1,32 @@ +class Solution { + public int[][] updateMatrix(int[][] mat) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = mat.length; + final int n = mat[0].length; + Queue q = new ArrayDeque<>(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 0) + q.offer(new int[] {i, j}); + else + mat[i][j] = Integer.MAX_VALUE; + + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (mat[x][y] <= mat[i][j] + 1) + continue; + q.offer(new int[] {x, y}); + mat[x][y] = mat[i][j] + 1; + } + } + + return mat; + } +} diff --git a/solutions/542. 01 Matrix/542-2.py b/solutions/542. 01 Matrix/542-2.py new file mode 100644 index 00000000000..ed358e46ddc --- /dev/null +++ b/solutions/542. 01 Matrix/542-2.py @@ -0,0 +1,27 @@ +class Solution: + def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(mat) + n = len(mat[0]) + q = collections.deque() + + for i in range(m): + for j in range(n): + if mat[i][j] == 0: + q.append((i, j)) + else: + mat[i][j] = math.inf + + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if mat[x][y] <= mat[i][j] + 1: + continue + q.append((x, y)) + mat[x][y] = mat[i][j] + 1 + + return mat diff --git a/solutions/542. 01 Matrix/542.cpp b/solutions/542. 01 Matrix/542.cpp new file mode 100644 index 00000000000..9513c8fdeac --- /dev/null +++ b/solutions/542. 01 Matrix/542.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector> updateMatrix(vector>& mat) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = mat.size(); + const int n = mat[0].size(); + queue> q; + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 0) { + q.emplace(i, j); + seen[i][j] = true; + } + + while (!q.empty()) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + mat[x][y] = mat[i][j] + 1; + q.emplace(x, y); + seen[x][y] = true; + } + } + + return mat; + } +}; diff --git a/solutions/542. 01 Matrix/542.java b/solutions/542. 01 Matrix/542.java new file mode 100644 index 00000000000..cd6b4270bbf --- /dev/null +++ b/solutions/542. 01 Matrix/542.java @@ -0,0 +1,34 @@ +class Solution { + public int[][] updateMatrix(int[][] mat) { + final int[] dirs = new int[] {0, 1, 0, -1, 0}; + final int m = mat.length; + final int n = mat[0].length; + Queue q = new ArrayDeque<>(); + boolean[][] seen = new boolean[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 0) { + q.offer(new int[] {i, j}); + seen[i][j] = true; + } + + while (!q.isEmpty()) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + mat[x][y] = mat[i][j] + 1; + q.offer(new int[] {x, y}); + seen[x][y] = true; + } + } + + return mat; + } +} diff --git a/solutions/542. 01 Matrix/542.py b/solutions/542. 01 Matrix/542.py new file mode 100644 index 00000000000..0d0f84ec491 --- /dev/null +++ b/solutions/542. 01 Matrix/542.py @@ -0,0 +1,28 @@ +class Solution: + def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + m = len(mat) + n = len(mat[0]) + q = collections.deque() + seen = [[False] * n for _ in range(m)] + + for i in range(m): + for j in range(n): + if mat[i][j] == 0: + q.append((i, j)) + seen[i][j] = True + + while q: + i, j = q.popleft() + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + continue + if seen[x][y]: + continue + mat[x][y] = mat[i][j] + 1 + q.append((x, y)) + seen[x][y] = True + + return mat diff --git a/solutions/543. Diameter of Binary Tree/543.cpp b/solutions/543. Diameter of Binary Tree/543.cpp new file mode 100644 index 00000000000..2cae5bb2c6a --- /dev/null +++ b/solutions/543. Diameter of Binary Tree/543.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int diameterOfBinaryTree(TreeNode* root) { + int ans = 0; + maxDepth(root, ans); + return ans; + } + + private: + int maxDepth(TreeNode* root, int& ans) { + if (root == nullptr) + return 0; + + const int l = maxDepth(root->left, ans); + const int r = maxDepth(root->right, ans); + ans = max(ans, l + r); + return 1 + max(l, r); + } +}; diff --git a/solutions/543. Diameter of Binary Tree/543.java b/solutions/543. Diameter of Binary Tree/543.java new file mode 100644 index 00000000000..fae37c44de4 --- /dev/null +++ b/solutions/543. Diameter of Binary Tree/543.java @@ -0,0 +1,18 @@ +class Solution { + public int diameterOfBinaryTree(TreeNode root) { + maxDepth(root); + return ans; + } + + private int ans = 0; + + int maxDepth(TreeNode root) { + if (root == null) + return 0; + + final int l = maxDepth(root.left); + final int r = maxDepth(root.right); + ans = Math.max(ans, l + r); + return 1 + Math.max(l, r); + } +} diff --git a/solutions/543. Diameter of Binary Tree/543.py b/solutions/543. Diameter of Binary Tree/543.py new file mode 100644 index 00000000000..bb80329b2e2 --- /dev/null +++ b/solutions/543. Diameter of Binary Tree/543.py @@ -0,0 +1,16 @@ +class Solution: + def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def maxDepth(root: Optional[TreeNode]) -> int: + nonlocal ans + if not root: + return 0 + + l = maxDepth(root.left) + r = maxDepth(root.right) + ans = max(ans, l + r) + return 1 + max(l, r) + + maxDepth(root) + return ans diff --git a/solutions/544. Output Contest Matches/544-2.cpp b/solutions/544. Output Contest Matches/544-2.cpp new file mode 100644 index 00000000000..45ef7468bff --- /dev/null +++ b/solutions/544. Output Contest Matches/544-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string findContestMatch(int n) { + vector matches(n); + + for (int i = 0; i < n; ++i) + matches[i] = to_string(i + 1); + + while (n > 1) { + for (int i = 0; i < n / 2; ++i) + matches[i] = "(" + matches[i] + "," + matches[n - 1 - i] + ")"; + n /= 2; + } + + return matches[0]; + } +}; diff --git a/solutions/544. Output Contest Matches/544-2.java b/solutions/544. Output Contest Matches/544-2.java new file mode 100644 index 00000000000..f416a276de4 --- /dev/null +++ b/solutions/544. Output Contest Matches/544-2.java @@ -0,0 +1,16 @@ +class Solution { + public String findContestMatch(int n) { + String[] matches = new String[n]; + + for (int i = 0; i < n; ++i) + matches[i] = String.valueOf(i + 1); + + while (n > 1) { + for (int i = 0; i < n / 2; ++i) + matches[i] = "(" + matches[i] + "," + matches[n - 1 - i] + ")"; + n /= 2; + } + + return matches[0]; + } +} diff --git a/solutions/544. Output Contest Matches/544-2.py b/solutions/544. Output Contest Matches/544-2.py new file mode 100644 index 00000000000..14b5bc594f3 --- /dev/null +++ b/solutions/544. Output Contest Matches/544-2.py @@ -0,0 +1,10 @@ +class Solution: + def findContestMatch(self, n: int) -> str: + matches = [str(i + 1) for i in range(n)] + + while n > 1: + for i in range(n // 2): + matches[i] = '(' + matches[i] + ',' + matches[n - 1 - i] + ')' + n //= 2 + + return matches[0] diff --git a/solutions/544. Output Contest Matches/544.cpp b/solutions/544. Output Contest Matches/544.cpp new file mode 100644 index 00000000000..fbae4e945d5 --- /dev/null +++ b/solutions/544. Output Contest Matches/544.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + string findContestMatch(int n) { + vector matches(n); + + for (int i = 0; i < n; ++i) + matches[i] = to_string(i + 1); + + return generateMatches(matches); + } + + private: + string generateMatches(const vector& matches) { + if (matches.size() == 1) + return matches[0]; + + vector nextMatches; + + for (int i = 0; i < matches.size() / 2; ++i) + nextMatches.push_back("(" + matches[i] + "," + + matches[matches.size() - 1 - i] + ")"); + + return generateMatches(nextMatches); + } +}; diff --git a/solutions/544. Output Contest Matches/544.java b/solutions/544. Output Contest Matches/544.java new file mode 100644 index 00000000000..b369c16b203 --- /dev/null +++ b/solutions/544. Output Contest Matches/544.java @@ -0,0 +1,22 @@ +class Solution { + public String findContestMatch(int n) { + List matches = new ArrayList<>(); + + for (int i = 1; i <= n; ++i) + matches.add(String.valueOf(i)); + + return generateMatches(matches); + } + + private String generateMatches(List matches) { + if (matches.size() == 1) + return matches.get(0); + + List nextMatches = new ArrayList<>(); + + for (int i = 0; i < matches.size() / 2; ++i) + nextMatches.add("(" + matches.get(i) + "," + matches.get(matches.size() - 1 - i) + ")"); + + return generateMatches(nextMatches); + } +} diff --git a/solutions/544. Output Contest Matches/544.py b/solutions/544. Output Contest Matches/544.py new file mode 100644 index 00000000000..3e5bf443438 --- /dev/null +++ b/solutions/544. Output Contest Matches/544.py @@ -0,0 +1,15 @@ +class Solution: + def findContestMatch(self, n: int) -> str: + def generateMatches(matches: List[str]) -> str: + if len(matches) == 1: + return matches[0] + + nextMatches = [] + + for i in range(len(matches) // 2): + nextMatches.append( + '(' + matches[i] + ',' + matches[len(matches) - 1 - i] + ')') + + return generateMatches(nextMatches) + + return generateMatches([str(i + 1) for i in range(n)]) diff --git a/solutions/545. Boundary of Binary Tree/545.cpp b/solutions/545. Boundary of Binary Tree/545.cpp new file mode 100644 index 00000000000..d4f69f8aaa8 --- /dev/null +++ b/solutions/545. Boundary of Binary Tree/545.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector boundaryOfBinaryTree(TreeNode* root) { + if (root == nullptr) + return {}; + vector ans{root->val}; + dfs(root->left, true, false, ans); + dfs(root->right, false, true, ans); + return ans; + } + + private: + // 1. root->left is left boundary if root is left boundary. + // root->right if left boundary if root->left == nullptr. + // 2. Same applys for right boundary. + // 3. If root is left boundary, add it before 2 children - preorder. + // If root is right boundary, add it after 2 children - postorder. + // 4. A leaf that is neighter left/right boundary belongs to the bottom. + void dfs(TreeNode* root, bool lb, bool rb, vector& ans) { + if (root == nullptr) + return; + if (lb) + ans.push_back(root->val); + if (!lb && !rb && root->left == nullptr && root->right != nullptr) + ans.push_back(root->val); + + dfs(root->left, lb, rb && root->right == nullptr, ans); + dfs(root->right, lb && root->left == nullptr, rb, ans); + if (rb) + ans.push_back(root->val); + } +}; diff --git a/solutions/545. Boundary of Binary Tree/545.java b/solutions/545. Boundary of Binary Tree/545.java new file mode 100644 index 00000000000..e2da0c161a7 --- /dev/null +++ b/solutions/545. Boundary of Binary Tree/545.java @@ -0,0 +1,30 @@ +class Solution { + public List boundaryOfBinaryTree(TreeNode root) { + if (root == null) + return new ArrayList<>(); + List ans = new ArrayList<>(Arrays.asList(root.val)); + dfs(root.left, true, false, ans); + dfs(root.right, false, true, ans); + return ans; + } + + // 1. root.left is left boundary if root is left boundary. + // root.right if left boundary if root.left == nullptr. + // 2. Same applys for right boundary. + // 3. If root is left boundary, add it before 2 children - preorder. + // If root is right boundary, add it after 2 children - postorder. + // 4. A leaf that is neighter left/right boundary belongs to the bottom. + private void dfs(TreeNode root, boolean lb, boolean rb, List ans) { + if (root == null) + return; + if (lb) + ans.add(root.val); + if (!lb && !rb && root.left == null && root.right == null) + ans.add(root.val); + + dfs(root.left, lb, rb && root.right == null, ans); + dfs(root.right, lb && root.left == null, rb, ans); + if (rb) + ans.add(root.val); + } +} diff --git a/solutions/545. Boundary of Binary Tree/545.py b/solutions/545. Boundary of Binary Tree/545.py new file mode 100644 index 00000000000..4be656563d4 --- /dev/null +++ b/solutions/545. Boundary of Binary Tree/545.py @@ -0,0 +1,31 @@ +class Solution: + def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + ans = [root.val] + + def dfs(root: Optional[TreeNode], lb: bool, rb: bool): + """ + 1. root.left is left boundary if root is left boundary. + root.right if left boundary if root.left is None. + 2. Same applys for right boundary. + 3. If root is left boundary, add it before 2 children - preorder. + If root is right boundary, add it after 2 children - postorder. + 4. A leaf that is neighter left/right boundary belongs to the bottom. + """ + if not root: + return + if lb: + ans.append(root.val) + if not lb and not rb and not root.left and not root.right: + ans.append(root.val) + + dfs(root.left, lb, rb and not root.right) + dfs(root.right, lb and not root.left, rb) + if rb: + ans.append(root.val) + + dfs(root.left, True, False) + dfs(root.right, False, True) + return ans diff --git a/solutions/546. Remove Boxes/546.cpp b/solutions/546. Remove Boxes/546.cpp new file mode 100644 index 00000000000..6289cc66483 --- /dev/null +++ b/solutions/546. Remove Boxes/546.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int removeBoxes(vector& boxes) { + const int n = boxes.size(); + vector>> mem(n, vector>(n, vector(n))); + return removeBoxes(boxes, 0, n - 1, 0, mem); + } + + private: + // Returns the maximum score of boxes[i..j] if k boxes eqaul to boxes[j]. + int removeBoxes(const vector& boxes, int i, int j, int k, + vector>>& mem) { + if (i > j) + return 0; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + + int r = j; + int sameBoxes = k + 1; + while (r > 0 && boxes[r - 1] == boxes[r]) { + --r; + ++sameBoxes; + } + mem[i][j][k] = removeBoxes(boxes, i, r - 1, 0, mem) + sameBoxes * sameBoxes; + + for (int p = i; p < r; ++p) + if (boxes[p] == boxes[r]) + mem[i][j][k] = + max(mem[i][j][k], removeBoxes(boxes, i, p, sameBoxes, mem) + + removeBoxes(boxes, p + 1, r - 1, 0, mem)); + + return mem[i][j][k]; + } +}; diff --git a/solutions/546. Remove Boxes/546.java b/solutions/546. Remove Boxes/546.java new file mode 100644 index 00000000000..f9b65521963 --- /dev/null +++ b/solutions/546. Remove Boxes/546.java @@ -0,0 +1,30 @@ +class Solution { + public int removeBoxes(int[] boxes) { + final int n = boxes.length; + int[][][] mem = new int[n][n][n]; + return removeBoxes(boxes, 0, n - 1, 0, mem); + } + + // Returns the maximum score of boxes[i..j] if k boxes are equal to boxes[j] + private int removeBoxes(int[] boxes, int i, int j, int k, int[][][] mem) { + if (i > j) + return 0; + if (mem[i][j][k] > 0) + return mem[i][j][k]; + + int r = j; + int sameBoxes = k + 1; + while (r > 0 && boxes[r - 1] == boxes[r]) { + --r; + ++sameBoxes; + } + mem[i][j][k] = removeBoxes(boxes, i, r - 1, 0, mem) + sameBoxes * sameBoxes; + + for (int p = i; p < r; ++p) + if (boxes[p] == boxes[r]) + mem[i][j][k] = Math.max(mem[i][j][k], removeBoxes(boxes, i, p, sameBoxes, mem) + + removeBoxes(boxes, p + 1, r - 1, 0, mem)); + + return mem[i][j][k]; + } +} diff --git a/solutions/546. Remove Boxes/546.py b/solutions/546. Remove Boxes/546.py new file mode 100644 index 00000000000..ff9a16940c6 --- /dev/null +++ b/solutions/546. Remove Boxes/546.py @@ -0,0 +1,24 @@ +class Solution: + def removeBoxes(self, boxes: List[int]) -> int: + @functools.lru_cache(None) + def dp(i: int, j: int, k: int) -> int: + """ + Returns the maximum score of boxes[i..j] if k boxes equal to boxes[j]. + """ + if i > j: + return 0 + + r = j + sameBoxes = k + 1 + while r > 0 and boxes[r - 1] == boxes[r]: + r -= 1 + sameBoxes += 1 + res = dp(i, r - 1, 0) + sameBoxes * sameBoxes + + for p in range(i, r): + if boxes[p] == boxes[r]: + res = max(res, dp(i, p, sameBoxes) + dp(p + 1, r - 1, 0)) + + return res + + return dp(0, len(boxes) - 1, 0) diff --git a/solutions/547. Friend Circles/547.cpp b/solutions/547. Friend Circles/547.cpp new file mode 100644 index 00000000000..94276a438eb --- /dev/null +++ b/solutions/547. Friend Circles/547.cpp @@ -0,0 +1,50 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + int findCircleNum(vector>& isConnected) { + const int n = isConnected.size(); + UnionFind uf(n); + + for (int i = 0; i < n; ++i) + for (int j = i; j < n; ++j) + if (isConnected[i][j] == 1) + uf.unionByRank(i, j); + + return uf.getCount(); + } +}; diff --git a/solutions/547. Friend Circles/547.java b/solutions/547. Friend Circles/547.java new file mode 100644 index 00000000000..bbf4d331ff4 --- /dev/null +++ b/solutions/547. Friend Circles/547.java @@ -0,0 +1,51 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + public int getCount() { + return count; + } + + private int count; + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int findCircleNum(int[][] isConnected) { + final int n = isConnected.length; + UnionFind uf = new UnionFind(n); + + for (int i = 0; i < n; ++i) + for (int j = i; j < n; ++j) + if (isConnected[i][j] == 1) + uf.unionByRank(i, j); + + return uf.getCount(); + } +} diff --git a/solutions/547. Friend Circles/547.py b/solutions/547. Friend Circles/547.py new file mode 100644 index 00000000000..39e0e11d1b3 --- /dev/null +++ b/solutions/547. Friend Circles/547.py @@ -0,0 +1,37 @@ +class UnionFind: + def __init__(self, n: int): + self.count = n + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self._find(u) + j = self._find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + self.count -= 1 + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + n = len(isConnected) + uf = UnionFind(n) + + for i in range(n): + for j in range(i, n): + if isConnected[i][j] == 1: + uf.unionByRank(i, j) + + return uf.count diff --git a/solutions/548. Split Array with Equal Sum/548.cpp b/solutions/548. Split Array with Equal Sum/548.cpp new file mode 100644 index 00000000000..06bbc63ef83 --- /dev/null +++ b/solutions/548. Split Array with Equal Sum/548.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool splitArray(vector& nums) { + const int n = nums.size(); + if (n < 7) + return false; + + vector prefix(n); + + partial_sum(nums.begin(), nums.end(), prefix.begin()); + + for (int j = 3; j < n - 3; ++j) { + unordered_set seen; + for (int i = 1; i < j - 1; ++i) + if (prefix[i - 1] == prefix[j - 1] - prefix[i]) + seen.insert(prefix[i - 1]); + for (int k = j + 2; k < n - 1; ++k) + if (prefix[n - 1] - prefix[k] == prefix[k - 1] - prefix[j] && + seen.contains(prefix[k - 1] - prefix[j])) + return true; + } + + return false; + } +}; diff --git a/solutions/548. Split Array with Equal Sum/548.java b/solutions/548. Split Array with Equal Sum/548.java new file mode 100644 index 00000000000..a4dd0163da6 --- /dev/null +++ b/solutions/548. Split Array with Equal Sum/548.java @@ -0,0 +1,25 @@ +class Solution { + public boolean splitArray(int[] nums) { + final int n = nums.length; + if (n < 7) + return false; + + int[] prefix = new int[n]; + + for (int i = 0; i < n; ++i) + prefix[i] = i == 0 ? nums[0] : prefix[i - 1] + nums[i]; + + for (int j = 3; j < n - 3; ++j) { + HashSet seen = new HashSet<>(); + for (int i = 1; i < j - 1; ++i) + if (prefix[i - 1] == prefix[j - 1] - prefix[i]) + seen.add(prefix[i - 1]); + for (int k = j + 2; k < n - 1; ++k) + if (prefix[n - 1] - prefix[k] == prefix[k - 1] - prefix[j] && + seen.contains(prefix[k - 1] - prefix[j])) + return true; + } + + return false; + } +} diff --git a/solutions/549. Binary Tree Longest Consecutive Sequence II/549.cpp b/solutions/549. Binary Tree Longest Consecutive Sequence II/549.cpp new file mode 100644 index 00000000000..d5216049b1a --- /dev/null +++ b/solutions/549. Binary Tree Longest Consecutive Sequence II/549.cpp @@ -0,0 +1,41 @@ +struct T { + int inc; // the length of longest incrementing branch + int dec; // the length of longest decrementing branch +}; + +class Solution { + public: + int longestConsecutive(TreeNode* root) { + int ans = 0; + longestPath(root, ans); + return ans; + } + + private: + T longestPath(TreeNode* root, int& ans) { + if (root == nullptr) + return {0, 0}; + + int inc = 1; + int dec = 1; + + if (root->left) { + T l = longestPath(root->left, ans); + if (root->val + 1 == root->left->val) + inc = l.inc + 1; + else if (root->val - 1 == root->left->val) + dec = l.dec + 1; + } + + if (root->right) { + T r = longestPath(root->right, ans); + if (root->val + 1 == root->right->val) + inc = max(inc, r.inc + 1); + else if (root->val - 1 == root->right->val) + dec = max(dec, r.dec + 1); + } + + ans = max(ans, inc + dec - 1); + return {inc, dec}; + } +}; diff --git a/solutions/549. Binary Tree Longest Consecutive Sequence II/549.java b/solutions/549. Binary Tree Longest Consecutive Sequence II/549.java new file mode 100644 index 00000000000..686d596c0fa --- /dev/null +++ b/solutions/549. Binary Tree Longest Consecutive Sequence II/549.java @@ -0,0 +1,45 @@ +class T { + public int inc; // the length of longest incrementing branch + public int dec; // the length of longest decrementing branch + + public T(int inc, int dec) { + this.inc = inc; + this.dec = dec; + } +} + +class Solution { + public int longestConsecutive(TreeNode root) { + longestPath(root); + return ans; + } + + private int ans = 0; + + private T longestPath(TreeNode root) { + if (root == null) + return new T(0, 0); + + int inc = 1; + int dec = 1; + + if (root.left != null) { + T l = longestPath(root.left); + if (root.val + 1 == root.left.val) + inc = l.inc + 1; + else if (root.val - 1 == root.left.val) + dec = l.dec + 1; + } + + if (root.right != null) { + T r = longestPath(root.right); + if (root.val + 1 == root.right.val) + inc = Math.max(inc, r.inc + 1); + else if (root.val - 1 == root.right.val) + dec = Math.max(dec, r.dec + 1); + } + + ans = Math.max(ans, inc + dec - 1); + return new T(inc, dec); + } +} diff --git a/solutions/55. Jump Game/55.cpp b/solutions/55. Jump Game/55.cpp new file mode 100644 index 00000000000..ab3be3cc7a7 --- /dev/null +++ b/solutions/55. Jump Game/55.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + bool canJump(vector& nums) { + int i = 0; + + for (int reach = 0; i < nums.size() && i <= reach; ++i) + reach = max(reach, i + nums[i]); + + return i == nums.size(); + } +}; diff --git a/solutions/55. Jump Game/55.java b/solutions/55. Jump Game/55.java new file mode 100644 index 00000000000..3014032d2ea --- /dev/null +++ b/solutions/55. Jump Game/55.java @@ -0,0 +1,10 @@ +class Solution { + public boolean canJump(int[] nums) { + int i = 0; + + for (int reach = 0; i < nums.length && i <= reach; ++i) + reach = Math.max(reach, i + nums[i]); + + return i == nums.length; + } +} diff --git a/solutions/55. Jump Game/55.py b/solutions/55. Jump Game/55.py new file mode 100644 index 00000000000..dda6ee130c9 --- /dev/null +++ b/solutions/55. Jump Game/55.py @@ -0,0 +1,10 @@ +class Solution: + def canJump(self, nums: List[int]) -> bool: + i = 0 + reach = 0 + + while i < len(nums) and i <= reach: + reach = max(reach, i + nums[i]) + i += 1 + + return i == len(nums) diff --git a/solutions/550. Game Play Analysis IV/550.sql b/solutions/550. Game Play Analysis IV/550.sql new file mode 100644 index 00000000000..1c141d9e170 --- /dev/null +++ b/solutions/550. Game Play Analysis IV/550.sql @@ -0,0 +1,18 @@ +WITH + Players AS ( + SELECT player_id, MIN(event_date) AS first_login + FROM Activity + GROUP BY 1 + ) +SELECT ROUND( + COUNT(Players.player_id) / ( + SELECT COUNT(DISTINCT Activity.player_id) + FROM Activity + ), + 2 + ) AS fraction +FROM Players +INNER JOIN Activity + ON ( + Players.player_id = Activity.player_id + AND DATEDIFF(Players.first_login, Activity.event_date) = -1) diff --git a/solutions/551. Student Attendance Record I/551.cpp b/solutions/551. Student Attendance Record I/551.cpp new file mode 100644 index 00000000000..432bb3f2373 --- /dev/null +++ b/solutions/551. Student Attendance Record I/551.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool checkRecord(string s) { + int countA = 0; + int countL = 0; + + for (const char c : s) { + if (c == 'A' && ++countA > 1) + return false; + if (c != 'L') + countL = 0; + else if (++countL > 2) + return false; + } + + return true; + } +}; diff --git a/solutions/551. Student Attendance Record I/551.java b/solutions/551. Student Attendance Record I/551.java new file mode 100644 index 00000000000..7463f0f3b19 --- /dev/null +++ b/solutions/551. Student Attendance Record I/551.java @@ -0,0 +1,5 @@ +class Solution { + public boolean checkRecord(String s) { + return s.indexOf("A") == s.lastIndexOf("A") && !s.contains("LLL"); + } +} diff --git a/solutions/551. Student Attendance Record I/551.py b/solutions/551. Student Attendance Record I/551.py new file mode 100644 index 00000000000..009f4edc958 --- /dev/null +++ b/solutions/551. Student Attendance Record I/551.py @@ -0,0 +1,3 @@ +class Solution: + def checkRecord(self, s: str) -> bool: + return s.count('A') <= 1 and 'LLL' not in s diff --git a/solutions/552. Student Attendance Record II/552.cpp b/solutions/552. Student Attendance Record II/552.cpp new file mode 100644 index 00000000000..6735caa8903 --- /dev/null +++ b/solutions/552. Student Attendance Record II/552.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + int checkRecord(int n) { + constexpr int kMod = 1'000'000'007; + // dp[i][j] := the length so far with i A's and the last letters are j L's + vector> dp(2, vector(3)); + dp[0][0] = 1; + + while (n--) { + const auto prev(dp); + + // Append a P. + dp[0][0] = (prev[0][0] + prev[0][1] + prev[0][2]) % kMod; + + // Append an L. + dp[0][1] = prev[0][0]; + + // Append an L. + dp[0][2] = prev[0][1]; + + // Append an A or append a P. + dp[1][0] = (prev[0][0] + prev[0][1] + prev[0][2] + // + prev[1][0] + prev[1][1] + prev[1][2]) % + kMod; + + // Append an L. + dp[1][1] = prev[1][0]; + + // Append an L. + dp[1][2] = prev[1][1]; + } + + return accumulate(dp.begin(), dp.end(), 0, + [](int subtotal, vector& row) { + return (subtotal + accumulate(row.begin(), row.end(), 0L)) % kMod; + }); + } +}; diff --git a/solutions/552. Student Attendance Record II/552.java b/solutions/552. Student Attendance Record II/552.java new file mode 100644 index 00000000000..a31542c9271 --- /dev/null +++ b/solutions/552. Student Attendance Record II/552.java @@ -0,0 +1,35 @@ +class Solution { + public int checkRecord(int n) { + final int kMod = 1_000_000_007; + // dp[i][j] := the length so far with i A's and the last letters are j L's + long[][] dp = new long[2][3]; + dp[0][0] = 1; + + while (n-- > 0) { + long[][] prev = Arrays.stream(dp) + .map((long[] A) -> A.clone()) + .toArray((int length) -> new long[length][]); + + // Append a P. + dp[0][0] = (prev[0][0] + prev[0][1] + prev[0][2]) % kMod; + + // Append an L. + dp[0][1] = prev[0][0]; + + // Append an L. + dp[0][2] = prev[0][1]; + + // Append an A or append a P. + dp[1][0] = + (prev[0][0] + prev[0][1] + prev[0][2] + prev[1][0] + prev[1][1] + prev[1][2]) % kMod; + + // Append an L. + dp[1][1] = prev[1][0]; + + // Append an L. + dp[1][2] = prev[1][1]; + } + + return (int) ((dp[0][0] + dp[0][1] + dp[0][2] + dp[1][0] + dp[1][1] + dp[1][2]) % kMod); + } +} diff --git a/solutions/552. Student Attendance Record II/552.py b/solutions/552. Student Attendance Record II/552.py new file mode 100644 index 00000000000..e5780c8d435 --- /dev/null +++ b/solutions/552. Student Attendance Record II/552.py @@ -0,0 +1,30 @@ +class Solution: + def checkRecord(self, n: int) -> int: + kMod = 1_000_000_007 + # dp[i][j] := the length so far with i A's and the last letters are j L's + dp = [[0] * 3 for _ in range(2)] + dp[0][0] = 1 + + for _ in range(n): + prev = [A[:] for A in dp] + + # Append a P. + dp[0][0] = (prev[0][0] + prev[0][1] + prev[0][2]) % kMod + + # Append an L. + dp[0][1] = prev[0][0] + + # Append an L. + dp[0][2] = prev[0][1] + + # Append an A or append a P. + dp[1][0] = (prev[0][0] + prev[0][1] + prev[0][2] + + prev[1][0] + prev[1][1] + prev[1][2]) % kMod + + # Append an L. + dp[1][1] = prev[1][0] + + # Append an L. + dp[1][2] = prev[1][1] + + return (sum(dp[0]) + sum(dp[1])) % kMod diff --git a/solutions/553. Optimal Division/553.cpp b/solutions/553. Optimal Division/553.cpp new file mode 100644 index 00000000000..cb85037bb07 --- /dev/null +++ b/solutions/553. Optimal Division/553.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string optimalDivision(vector& nums) { + string ans = to_string(nums[0]); + + if (nums.size() == 1) + return ans; + if (nums.size() == 2) + return ans + "/" + to_string(nums[1]); + + ans += "/(" + to_string(nums[1]); + for (int i = 2; i < nums.size(); ++i) + ans += "/" + to_string(nums[i]); + ans += ")"; + return ans; + } +}; diff --git a/solutions/553. Optimal Division/553.java b/solutions/553. Optimal Division/553.java new file mode 100644 index 00000000000..0d32443fc3e --- /dev/null +++ b/solutions/553. Optimal Division/553.java @@ -0,0 +1,16 @@ +class Solution { + public String optimalDivision(int[] nums) { + StringBuilder sb = new StringBuilder(String.valueOf(nums[0])); + + if (nums.length == 1) + return sb.toString(); + if (nums.length == 2) + return sb.append('/').append(nums[1]).toString(); + + sb.append("/(").append(nums[1]); + for (int i = 2; i < nums.length; ++i) + sb.append('/').append(nums[i]); + sb.append(')'); + return sb.toString(); + } +} diff --git a/solutions/553. Optimal Division/553.py b/solutions/553. Optimal Division/553.py new file mode 100644 index 00000000000..ba75ab4ce05 --- /dev/null +++ b/solutions/553. Optimal Division/553.py @@ -0,0 +1,14 @@ +class Solution: + def optimalDivision(self, nums: List[int]) -> str: + ans = str(nums[0]) + + if len(nums) == 1: + return ans + if len(nums) == 2: + return ans + '/' + str(nums[1]) + + ans += '/(' + str(nums[1]) + for i in range(2, len(nums)): + ans += '/' + str(nums[i]) + ans += ')' + return ans diff --git a/solutions/554. Brick Wall/554.cpp b/solutions/554. Brick Wall/554.cpp new file mode 100644 index 00000000000..f7d8fc6dd74 --- /dev/null +++ b/solutions/554. Brick Wall/554.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int leastBricks(vector>& wall) { + int maxCount = 0; + unordered_map count; + + for (const vector& row : wall) { + int prefix = 0; + for (int i = 0; i < row.size() - 1; ++i) { + prefix += row[i]; + maxCount = max(maxCount, ++count[prefix]); + } + } + + return wall.size() - maxCount; + } +}; diff --git a/solutions/554. Brick Wall/554.java b/solutions/554. Brick Wall/554.java new file mode 100644 index 00000000000..7609e61fdb0 --- /dev/null +++ b/solutions/554. Brick Wall/554.java @@ -0,0 +1,16 @@ +class Solution { + public int leastBricks(List> wall) { + int maxFreq = 0; + Map count = new HashMap<>(); + + for (List row : wall) { + int prefix = 0; + for (int i = 0; i < row.size() - 1; ++i) { + prefix += row.get(i); + maxFreq = Math.max(maxFreq, count.merge(prefix, 1, Integer::sum)); + } + } + + return wall.size() - maxFreq; + } +} diff --git a/solutions/554. Brick Wall/554.py b/solutions/554. Brick Wall/554.py new file mode 100644 index 00000000000..b48c1196b54 --- /dev/null +++ b/solutions/554. Brick Wall/554.py @@ -0,0 +1,13 @@ +class Solution: + def leastBricks(self, wall: List[List[int]]) -> int: + maxFreq = 0 + count = collections.defaultdict(int) + + for row in wall: + prefix = 0 + for i in range(len(row) - 1): + prefix += row[i] + count[prefix] += 1 + maxFreq = max(maxFreq, count[prefix]) + + return len(wall) - maxFreq diff --git a/solutions/555. Split Concatenated Strings/555.cpp b/solutions/555. Split Concatenated Strings/555.cpp new file mode 100644 index 00000000000..61cb25be593 --- /dev/null +++ b/solutions/555. Split Concatenated Strings/555.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + string splitLoopedString(vector& strs) { + string ans; + vector sortedStrs; + + for (const string& s : strs) + sortedStrs.push_back(max(s, {s.rbegin(), s.rend()})); + + for (int i = 0; i < sortedStrs.size(); ++i) + for (const string& s : + {sortedStrs[i], {sortedStrs[i].rbegin(), sortedStrs[i].rend()}}) + for (int j = 0; j <= s.length(); ++j) + ans = max(ans, s.substr(j) + join(sortedStrs, i) + s.substr(0, j)); + + return ans; + } + + private: + string reversed(const string& s) { + string r = s; + reverse(r.begin(), r.end()); + return r; + } + + string join(const vector& sortedStrs, int i) { + string joined; + for (int j = i + 1; j < sortedStrs.size(); ++j) + joined += sortedStrs[j]; + for (int j = 0; j < i; ++j) + joined += sortedStrs[j]; + return joined; + } +}; diff --git a/solutions/555. Split Concatenated Strings/555.java b/solutions/555. Split Concatenated Strings/555.java new file mode 100644 index 00000000000..74dc273a18f --- /dev/null +++ b/solutions/555. Split Concatenated Strings/555.java @@ -0,0 +1,32 @@ +class Solution { + public String splitLoopedString(String[] strs) { + String ans = ""; + String[] sortedStrs = new String[strs.length]; + + for (int i = 0; i < strs.length; ++i) { + final String s = strs[i]; + final String r = new StringBuilder(s).reverse().toString(); + sortedStrs[i] = s.compareTo(r) > 0 ? s : r; + } + + for (int i = 0; i < sortedStrs.length; ++i) + for (final String s : + new String[] {sortedStrs[i], new StringBuilder(sortedStrs[i]).reverse().toString()}) + for (int j = 0; j <= s.length(); ++j) { + final String t = s.substring(j) + join(sortedStrs, i) + s.substring(0, j); + if (t.compareTo(ans) > 0) + ans = t; + } + + return ans; + } + + private String join(String[] sortedStrs, int i) { + StringBuilder sb = new StringBuilder(); + for (int j = i + 1; j < sortedStrs.length; ++j) + sb.append(sortedStrs[j]); + for (int j = 0; j < i; ++j) + sb.append(sortedStrs[j]); + return sb.toString(); + } +} diff --git a/solutions/555. Split Concatenated Strings/555.py b/solutions/555. Split Concatenated Strings/555.py new file mode 100644 index 00000000000..df0a7de35d3 --- /dev/null +++ b/solutions/555. Split Concatenated Strings/555.py @@ -0,0 +1,12 @@ +class Solution: + def splitLoopedString(self, strs: List[str]) -> str: + ans = '' + sortedStrs = [max(s, s[::-1]) for s in strs] + + for i, sortedStr in enumerate(sortedStrs): + for s in (sortedStr, sortedStr[::-1]): + for j in range(len(s) + 1): + ans = max( + ans, s[j:] + ''.join(sortedStrs[i + 1:] + sortedStrs[:i]) + s[:j]) + + return ans diff --git a/solutions/556. Next Greater Element III/556.cpp b/solutions/556. Next Greater Element III/556.cpp new file mode 100644 index 00000000000..252fb599dfd --- /dev/null +++ b/solutions/556. Next Greater Element III/556.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int nextGreaterElement(int n) { + const string& s = nextPermutation(to_string(n)); + const long ans = stol(s); + return ans > INT_MAX || ans <= n ? -1 : ans; + } + + private: + // Similar to 31. Next Permutation + string nextPermutation(string s) { + const int n = s.length(); + + int i; + for (i = n - 2; i >= 0; --i) + if (s[i] < s[i + 1]) + break; + + if (i >= 0) { + for (int j = n - 1; j > i; --j) + if (s[j] > s[i]) { + swap(s[i], s[j]); + break; + } + } + + reverse(s, i + 1, n - 1); + return s; + } + + void reverse(string& s, int l, int r) { + while (l < r) + swap(s[l++], s[r--]); + } +}; diff --git a/solutions/556. Next Greater Element III/556.java b/solutions/556. Next Greater Element III/556.java new file mode 100644 index 00000000000..a981e39989a --- /dev/null +++ b/solutions/556. Next Greater Element III/556.java @@ -0,0 +1,39 @@ +class Solution { + public int nextGreaterElement(int n) { + final String s = nextPermutation(String.valueOf(n).toCharArray()); + final long ans = Long.parseLong(s); + return ans > Integer.MAX_VALUE || ans <= (long) n ? -1 : (int) ans; + } + + // Similar to 31. Next Permutation + private String nextPermutation(char[] s) { + final int n = s.length; + + int i; + for (i = n - 2; i >= 0; --i) + if (s[i] < s[i + 1]) + break; + + if (i >= 0) { + for (int j = n - 1; j > i; --j) + if (s[j] > s[i]) { + swap(s, i, j); + break; + } + } + + reverse(s, i + 1, n - 1); + return new String(s); + } + + private void reverse(char[] s, int l, int r) { + while (l < r) + swap(s, l++, r--); + } + + private void swap(char[] s, int i, int j) { + final char temp = s[i]; + s[i] = s[j]; + s[j] = temp; + } +} diff --git a/solutions/556. Next Greater Element III/556.py b/solutions/556. Next Greater Element III/556.py new file mode 100644 index 00000000000..40136749f42 --- /dev/null +++ b/solutions/556. Next Greater Element III/556.py @@ -0,0 +1,27 @@ +class Solution: + def nextGreaterElement(self, n: int) -> int: + def nextPermutation(s: List[chr]) -> str: + i = len(s) - 2 + while i >= 0: + if s[i] < s[i + 1]: + break + i -= 1 + + if i >= 0: + for j in range(len(s) - 1, i, -1): + if s[j] > s[i]: + break + s[i], s[j] = s[j], s[i] + + reverse(s, i + 1, len(s) - 1) + return ''.join(s) + + def reverse(s: List[chr], l: int, r: int): + while l < r: + s[l], s[r] = s[r], s[l] + l += 1 + r -= 1 + + s = nextPermutation(list(str(n))) + ans = int(s) + return -1 if ans > 2**31 - 1 or ans <= n else ans diff --git a/solutions/557. Reverse Words in a String III/557.cpp b/solutions/557. Reverse Words in a String III/557.cpp new file mode 100644 index 00000000000..d01b3b97af1 --- /dev/null +++ b/solutions/557. Reverse Words in a String III/557.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + string reverseWords(string s) { + int i = 0; + int j = 0; + + while (i < s.length()) { + while (i < j || i < s.length() && s[i] == ' ') + ++i; + while (j < i || j < s.length() && s[j] != ' ') + ++j; + reverse(s.begin() + i, s.begin() + j); + } + + return s; + } +}; diff --git a/solutions/557. Reverse Words in a String III/557.java b/solutions/557. Reverse Words in a String III/557.java new file mode 100644 index 00000000000..1b1bbddda30 --- /dev/null +++ b/solutions/557. Reverse Words in a String III/557.java @@ -0,0 +1,25 @@ +class Solution { + public String reverseWords(String s) { + StringBuilder sb = new StringBuilder(s); + int i = 0; + int j = 0; + + while (i < sb.length()) { + while (i < j || i < sb.length() && sb.charAt(i) == ' ') + ++i; + while (j < i || j < sb.length() && sb.charAt(j) != ' ') + ++j; + reverse(sb, i, j - 1); + } + + return sb.toString(); + } + + private void reverse(StringBuilder sb, int l, int r) { + while (l < r) { + final char temp = sb.charAt(l); + sb.setCharAt(l++, sb.charAt(r)); + sb.setCharAt(r--, temp); + } + } +} diff --git a/solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.cpp b/solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.cpp new file mode 100644 index 00000000000..a4a8261ebcb --- /dev/null +++ b/solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + Node* intersect(Node* quadTree1, Node* quadTree2) { + if (quadTree1->isLeaf) + return quadTree1->val ? quadTree1 : quadTree2; + if (quadTree2->isLeaf) + return quadTree2->val ? quadTree2 : quadTree1; + + Node* topLeft = intersect(quadTree1->topLeft, quadTree2->topLeft); + Node* topRight = intersect(quadTree1->topRight, quadTree2->topRight); + Node* bottomLeft = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft); + Node* bottomRight = + intersect(quadTree1->bottomRight, quadTree2->bottomRight); + + if (topLeft->val == topRight->val && // + topLeft->val == bottomLeft->val && // + topLeft->val == bottomRight->val && // + topLeft->isLeaf && topRight->isLeaf && // + bottomLeft->isLeaf && bottomRight->isLeaf) + return new Node(topLeft->val, true); + return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); + } +}; diff --git a/solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.java b/solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.java new file mode 100644 index 00000000000..6bc98b5eecd --- /dev/null +++ b/solutions/558. Logical OR of Two Binary Grids Represented as Quad-Trees/558.java @@ -0,0 +1,21 @@ +class Solution { + public Node intersect(Node quadTree1, Node quadTree2) { + if (quadTree1.isLeaf) + return quadTree1.val ? quadTree1 : quadTree2; + if (quadTree2.isLeaf) + return quadTree2.val ? quadTree2 : quadTree1; + + Node topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft); + Node topRight = intersect(quadTree1.topRight, quadTree2.topRight); + Node bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft); + Node bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight); + + if (topLeft.val == topRight.val && // + topLeft.val == bottomLeft.val && // + topLeft.val == bottomRight.val && // + topLeft.isLeaf && topRight.isLeaf && // + bottomLeft.isLeaf && bottomRight.isLeaf) + return new Node(topLeft.val, true); + return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); + } +} diff --git a/solutions/559. Maximum Depth of N-ary Tree/559.cpp b/solutions/559. Maximum Depth of N-ary Tree/559.cpp new file mode 100644 index 00000000000..b556b4ba199 --- /dev/null +++ b/solutions/559. Maximum Depth of N-ary Tree/559.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxDepth(Node* root) { + if (root == nullptr) + return 0; + + int ans = 0; + + for (Node* child : root->children) + ans = max(ans, maxDepth(child)); + + return 1 + ans; + } +}; diff --git a/solutions/559. Maximum Depth of N-ary Tree/559.java b/solutions/559. Maximum Depth of N-ary Tree/559.java new file mode 100644 index 00000000000..45a487c6d17 --- /dev/null +++ b/solutions/559. Maximum Depth of N-ary Tree/559.java @@ -0,0 +1,13 @@ +class Solution { + public int maxDepth(Node root) { + if (root == null) + return 0; + + int ans = 0; + + for (Node child : root.children) + ans = Math.max(ans, maxDepth(child)); + + return 1 + ans; + } +} diff --git a/solutions/559. Maximum Depth of N-ary Tree/559.py b/solutions/559. Maximum Depth of N-ary Tree/559.py new file mode 100644 index 00000000000..54b0c2a73ee --- /dev/null +++ b/solutions/559. Maximum Depth of N-ary Tree/559.py @@ -0,0 +1,7 @@ +class Solution: + def maxDepth(self, root: 'Node') -> int: + if not root: + return 0 + if not root.children: + return 1 + return 1 + max(self.maxDepth(child) for child in root.children) diff --git a/solutions/56. Merge Intervals/56.cpp b/solutions/56. Merge Intervals/56.cpp new file mode 100644 index 00000000000..4f0b68b4db5 --- /dev/null +++ b/solutions/56. Merge Intervals/56.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector> merge(vector>& intervals) { + vector> ans; + + ranges::sort(intervals); + + for (const vector& interval : intervals) + if (ans.empty() || ans.back()[1] < interval[0]) + ans.push_back(interval); + else + ans.back()[1] = max(ans.back()[1], interval[1]); + + return ans; + } +}; diff --git a/solutions/56. Merge Intervals/56.java b/solutions/56. Merge Intervals/56.java new file mode 100644 index 00000000000..1f7dce94919 --- /dev/null +++ b/solutions/56. Merge Intervals/56.java @@ -0,0 +1,15 @@ +class Solution { + public int[][] merge(int[][] intervals) { + List ans = new ArrayList<>(); + + Arrays.sort(intervals, (a, b) -> (a[0] - b[0])); + + for (int[] interval : intervals) + if (ans.isEmpty() || ans.get(ans.size() - 1)[1] < interval[0]) + ans.add(interval); + else + ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], interval[1]); + + return ans.toArray(int[][] ::new); + } +} diff --git a/solutions/56. Merge Intervals/56.py b/solutions/56. Merge Intervals/56.py new file mode 100644 index 00000000000..a72f1b825cf --- /dev/null +++ b/solutions/56. Merge Intervals/56.py @@ -0,0 +1,11 @@ +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + ans = [] + + for interval in sorted(intervals): + if not ans or ans[-1][1] < interval[0]: + ans.append(interval) + else: + ans[-1][1] = max(ans[-1][1], interval[1]) + + return ans diff --git a/solutions/560. Subarray Sum Equals K/560.cpp b/solutions/560. Subarray Sum Equals K/560.cpp new file mode 100644 index 00000000000..0c2fd7d9872 --- /dev/null +++ b/solutions/560. Subarray Sum Equals K/560.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int subarraySum(vector& nums, int k) { + int ans = 0; + int prefix = 0; + unordered_map count{{0, 1}}; // {prefix sum: count} + + for (const int num : nums) { + prefix += num; + const int target = prefix - k; + if (const auto it = count.find(target); it != count.cend()) + ans += it->second; + ++count[prefix]; + } + + return ans; + } +}; diff --git a/solutions/560. Subarray Sum Equals K/560.java b/solutions/560. Subarray Sum Equals K/560.java new file mode 100644 index 00000000000..f2e4c6dd53c --- /dev/null +++ b/solutions/560. Subarray Sum Equals K/560.java @@ -0,0 +1,16 @@ +class Solution { + public int subarraySum(int[] nums, int k) { + int ans = 0; + int prefix = 0; + Map count = new HashMap<>(); + count.put(0, 1); + + for (final int num : nums) { + prefix += num; + ans += count.getOrDefault(prefix - k, 0); + count.merge(prefix, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/560. Subarray Sum Equals K/560.py b/solutions/560. Subarray Sum Equals K/560.py new file mode 100644 index 00000000000..c9622b56546 --- /dev/null +++ b/solutions/560. Subarray Sum Equals K/560.py @@ -0,0 +1,12 @@ +class Solution: + def subarraySum(self, nums: List[int], k: int) -> int: + ans = 0 + prefix = 0 + count = collections.Counter({0: 1}) + + for num in nums: + prefix += num + ans += count[prefix - k] + count[prefix] += 1 + + return ans diff --git a/solutions/561. Array Partition I/561.cpp b/solutions/561. Array Partition I/561.cpp new file mode 100644 index 00000000000..52fe812db55 --- /dev/null +++ b/solutions/561. Array Partition I/561.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int arrayPairSum(vector& nums) { + int ans = 0; + + ranges::sort(nums); + + for (int i = 0; i < nums.size(); i += 2) + ans += nums[i]; + + return ans; + } +}; diff --git a/solutions/561. Array Partition I/561.java b/solutions/561. Array Partition I/561.java new file mode 100644 index 00000000000..21e47fff1c0 --- /dev/null +++ b/solutions/561. Array Partition I/561.java @@ -0,0 +1,12 @@ +class Solution { + public int arrayPairSum(int[] nums) { + int ans = 0; + + Arrays.sort(nums); + + for (int i = 0; i < nums.length; i += 2) + ans += nums[i]; + + return ans; + } +} diff --git a/solutions/561. Array Partition I/561.py b/solutions/561. Array Partition I/561.py new file mode 100644 index 00000000000..1736c689515 --- /dev/null +++ b/solutions/561. Array Partition I/561.py @@ -0,0 +1,3 @@ +class Solution: + def arrayPairSum(self, nums: List[int]) -> int: + return sum(sorted(nums)[::2]) diff --git a/solutions/562. Longest Line of Consecutive One in Matrix/562.cpp b/solutions/562. Longest Line of Consecutive One in Matrix/562.cpp new file mode 100644 index 00000000000..56db9b50d60 --- /dev/null +++ b/solutions/562. Longest Line of Consecutive One in Matrix/562.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int longestLine(vector>& mat) { + const int m = mat.size(); + const int n = mat[0].size(); + int ans = 0; + // dp[i][j][0] := horizontal + // dp[i][j][1] := vertical + // dp[i][j][2] := diagonal + // dp[i][j][3] := anti-diagonal + vector>> dp(m, vector>(n, vector(4))); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 1) { + dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1; + dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1; + dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1; + dp[i][j][3] = (i > 0 && j < n - 1) ? dp[i - 1][j + 1][3] + 1 : 1; + ans = max(ans, ranges::max(dp[i][j])); + } + + return ans; + } +}; diff --git a/solutions/562. Longest Line of Consecutive One in Matrix/562.java b/solutions/562. Longest Line of Consecutive One in Matrix/562.java new file mode 100644 index 00000000000..bab71584cb4 --- /dev/null +++ b/solutions/562. Longest Line of Consecutive One in Matrix/562.java @@ -0,0 +1,25 @@ +class Solution { + public int longestLine(int[][] mat) { + final int m = mat.length; + final int n = mat[0].length; + int ans = 0; + // dp[i][j][0] := horizontal + // dp[i][j][1] := vertical + // dp[i][j][2] := diagonal + // dp[i][j][3] := anti-diagonal + int[][][] dp = new int[m][n][4]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (mat[i][j] == 1) { + dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1; + dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1; + dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1; + dp[i][j][3] = (i > 0 && j < n - 1) ? dp[i - 1][j + 1][3] + 1 : 1; + for (int k = 0; k < 4; ++k) + ans = Math.max(ans, dp[i][j][k]); + } + + return ans; + } +} diff --git a/solutions/562. Longest Line of Consecutive One in Matrix/562.py b/solutions/562. Longest Line of Consecutive One in Matrix/562.py new file mode 100644 index 00000000000..9de606a1fe0 --- /dev/null +++ b/solutions/562. Longest Line of Consecutive One in Matrix/562.py @@ -0,0 +1,21 @@ +class Solution: + def longestLine(self, mat: List[List[int]]) -> int: + m = len(mat) + n = len(mat[0]) + ans = 0 + # dp[i][j][0] := horizontal + # dp[i][j][1] := vertical + # dp[i][j][2] := diagonal + # dp[i][j][3] := anti-diagonal + dp = [[[0] * 4 for j in range(n)] for _ in range(m)] + + for i in range(m): + for j in range(n): + if mat[i][j] == 1: + dp[i][j][0] = dp[i][j - 1][0] + 1 if j > 0 else 1 + dp[i][j][1] = dp[i - 1][j][1] + 1 if i > 0 else 1 + dp[i][j][2] = dp[i - 1][j - 1][2] + 1 if i > 0 and j > 0 else 1 + dp[i][j][3] = dp[i - 1][j + 1][3] + 1 if i > 0 and j < n - 1 else 1 + ans = max(ans, max(dp[i][j])) + + return ans diff --git a/solutions/563. Binary Tree Tilt/563.cpp b/solutions/563. Binary Tree Tilt/563.cpp new file mode 100644 index 00000000000..a09095b1afa --- /dev/null +++ b/solutions/563. Binary Tree Tilt/563.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int findTilt(TreeNode* root) { + int ans = 0; + sum(root, ans); + return ans; + } + + private: + int sum(TreeNode* root, int& ans) { + if (root == nullptr) + return 0; + + const int l = sum(root->left, ans); + const int r = sum(root->right, ans); + ans += abs(l - r); + return root->val + l + r; + } +}; diff --git a/solutions/563. Binary Tree Tilt/563.java b/solutions/563. Binary Tree Tilt/563.java new file mode 100644 index 00000000000..38bc75be96d --- /dev/null +++ b/solutions/563. Binary Tree Tilt/563.java @@ -0,0 +1,18 @@ +class Solution { + public int findTilt(TreeNode root) { + sum(root); + return ans; + } + + private int ans = 0; + + private int sum(TreeNode root) { + if (root == null) + return 0; + + final int l = sum(root.left); + final int r = sum(root.right); + ans += Math.abs(l - r); + return root.val + l + r; + } +} diff --git a/solutions/563. Binary Tree Tilt/563.py b/solutions/563. Binary Tree Tilt/563.py new file mode 100644 index 00000000000..28598699d09 --- /dev/null +++ b/solutions/563. Binary Tree Tilt/563.py @@ -0,0 +1,16 @@ +class Solution: + def findTilt(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def summ(root: Optional[TreeNode]) -> None: + nonlocal ans + if not root: + return 0 + + l = summ(root.left) + r = summ(root.right) + ans += abs(l - r) + return root.val + l + r + + summ(root) + return ans diff --git a/solutions/564. Find the Closest Palindrome/564.cpp b/solutions/564. Find the Closest Palindrome/564.cpp new file mode 100644 index 00000000000..88a0ad73218 --- /dev/null +++ b/solutions/564. Find the Closest Palindrome/564.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + string nearestPalindromic(string n) { + const auto& [prevPalindrome, nextPalindrome] = getPalindromes(n); + return abs(prevPalindrome - stol(n)) <= abs(nextPalindrome - stol(n)) + ? to_string(prevPalindrome) + : to_string(nextPalindrome); + } + + private: + pair getPalindromes(const string& s) { + const long num = stol(s); + const int n = s.length(); + pair palindromes; + const string& half = s.substr(0, (n + 1) / 2); + const string& reversedHalf = reversed(half.substr(0, n / 2)); + const long candidate = stol(half + reversedHalf); + + if (candidate < num) + palindromes.first = candidate; + else { + const string& prevHalf = to_string(stol(half) - 1); + const string& reversedPrevHalf = reversed(prevHalf.substr(0, n / 2)); + if (n % 2 == 0 && stol(prevHalf) == 0) + palindromes.first = 9; + else if (n % 2 == 0 && (stol(prevHalf) + 1) % 10 == 0) + palindromes.first = stol(prevHalf + '9' + reversedPrevHalf); + else + palindromes.first = stol(prevHalf + reversedPrevHalf); + } + + if (candidate > num) + palindromes.second = candidate; + else { + const string& nextHalf = to_string(stol(half) + 1); + const string& reversedNextHalf = reversed(nextHalf.substr(0, n / 2)); + palindromes.second = stol(nextHalf + reversedNextHalf); + } + + return palindromes; + } + + string reversed(const string& s) { + return {s.rbegin(), s.rend()}; + } +}; diff --git a/solutions/564. Find the Closest Palindrome/564.java b/solutions/564. Find the Closest Palindrome/564.java new file mode 100644 index 00000000000..b41e2cd3d5f --- /dev/null +++ b/solutions/564. Find the Closest Palindrome/564.java @@ -0,0 +1,45 @@ +class Solution { + public String nearestPalindromic(String n) { + final long[] palindromes = getPalindromes(n); + return Math.abs(palindromes[0] - Long.parseLong(n)) <= + Math.abs(palindromes[1] - Long.parseLong(n)) + ? String.valueOf(palindromes[0]) + : String.valueOf(palindromes[1]); + } + + private long[] getPalindromes(final String s) { + final long num = Long.parseLong(s); + final int n = s.length(); + long[] palindromes = new long[2]; + final String half = s.substring(0, (n + 1) / 2); + final String reversedHalf = new StringBuilder(half.substring(0, n / 2)).reverse().toString(); + final long candidate = Long.parseLong(half + reversedHalf); + + if (candidate < num) + palindromes[0] = candidate; + else { + final String prevHalf = String.valueOf(Long.parseLong(half) - 1); + final String reversedPrevHalf = + new StringBuilder(prevHalf.substring(0, Math.min(prevHalf.length(), n / 2))) + .reverse() + .toString(); + if (n % 2 == 0 && Long.parseLong(prevHalf) == 0) + palindromes[0] = 9; + else if (n % 2 == 0 && (Long.parseLong(prevHalf) + 1) % 10 == 0) + palindromes[0] = Long.parseLong(prevHalf + '9' + reversedPrevHalf); + else + palindromes[0] = Long.parseLong(prevHalf + reversedPrevHalf); + } + + if (candidate > num) + palindromes[1] = candidate; + else { + final String nextHalf = String.valueOf(Long.parseLong(half) + 1); + final String reversedNextHalf = + new StringBuilder(nextHalf.substring(0, n / 2)).reverse().toString(); + palindromes[1] = Long.parseLong(nextHalf + reversedNextHalf); + } + + return palindromes; + } +} diff --git a/solutions/564. Find the Closest Palindrome/564.py b/solutions/564. Find the Closest Palindrome/564.py new file mode 100644 index 00000000000..8ab916c0023 --- /dev/null +++ b/solutions/564. Find the Closest Palindrome/564.py @@ -0,0 +1,33 @@ +class Solution: + def nearestPalindromic(self, n: str) -> str: + def getPalindromes(s: str) -> tuple: + num = int(s) + k = len(s) + palindromes = [] + half = s[0:(k + 1) // 2] + reversedHalf = half[:k // 2][::-1] + candidate = int(half + reversedHalf) + + if candidate < num: + palindromes.append(candidate) + else: + prevHalf = str(int(half) - 1) + reversedPrevHalf = prevHalf[:k // 2][::-1] + if k % 2 == 0 and int(prevHalf) == 0: + palindromes.append(9) + elif k % 2 == 0 and (int(prevHalf) + 1) % 10 == 0: + palindromes.append(int(prevHalf + '9' + reversedPrevHalf)) + else: + palindromes.append(int(prevHalf + reversedPrevHalf)) + + if candidate > num: + palindromes.append(candidate) + else: + nextHalf = str(int(half) + 1) + reversedNextHalf = nextHalf[:k // 2][::-1] + palindromes.append(int(nextHalf + reversedNextHalf)) + + return palindromes + + prevPalindrome, nextPalindrome = getPalindromes(n) + return str(prevPalindrome) if abs(prevPalindrome - int(n)) <= abs(nextPalindrome - int(n)) else str(nextPalindrome) diff --git a/solutions/565. Array Nesting/565.cpp b/solutions/565. Array Nesting/565.cpp new file mode 100644 index 00000000000..c5635f9f438 --- /dev/null +++ b/solutions/565. Array Nesting/565.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int arrayNesting(vector& nums) { + int ans = 0; + + for (const int num : nums) { + if (num == -1) + continue; + int index = num; + int count = 0; + while (nums[index] != -1) { + const int cache = index; + index = nums[index]; + nums[cache] = -1; + ++count; + } + ans = max(ans, count); + } + + return ans; + } +}; diff --git a/solutions/565. Array Nesting/565.java b/solutions/565. Array Nesting/565.java new file mode 100644 index 00000000000..03420189139 --- /dev/null +++ b/solutions/565. Array Nesting/565.java @@ -0,0 +1,21 @@ +class Solution { + public int arrayNesting(int[] nums) { + int ans = 0; + + for (final int num : nums) { + if (num == -1) + continue; + int index = num; + int count = 0; + while (nums[index] != -1) { + final int cache = index; + index = nums[index]; + nums[cache] = -1; + ++count; + } + ans = Math.max(ans, count); + } + + return ans; + } +} diff --git a/solutions/565. Array Nesting/565.py b/solutions/565. Array Nesting/565.py new file mode 100644 index 00000000000..195e852dd2c --- /dev/null +++ b/solutions/565. Array Nesting/565.py @@ -0,0 +1,17 @@ +class Solution: + def arrayNesting(self, nums: List[int]) -> int: + ans = 0 + + for num in nums: + if num == -1: + continue + index = num + count = 0 + while nums[index] != -1: + cache = index + index = nums[index] + nums[cache] = -1 + count += 1 + ans = max(ans, count) + + return ans diff --git a/solutions/566. Reshape the Matrix/566.cpp b/solutions/566. Reshape the Matrix/566.cpp new file mode 100644 index 00000000000..57764ee627b --- /dev/null +++ b/solutions/566. Reshape the Matrix/566.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector> matrixReshape(vector>& nums, int r, int c) { + if (nums.empty() || r * c != nums.size() * nums[0].size()) + return nums; + + vector> ans(r, vector(c)); + int k = 0; + + for (const vector& row : nums) + for (const int num : row) { + ans[k / c][k % c] = num; + ++k; + } + + return ans; + } +}; diff --git a/solutions/566. Reshape the Matrix/566.java b/solutions/566. Reshape the Matrix/566.java new file mode 100644 index 00000000000..a0022b17373 --- /dev/null +++ b/solutions/566. Reshape the Matrix/566.java @@ -0,0 +1,17 @@ +class Solution { + public int[][] matrixReshape(int[][] nums, int r, int c) { + if (nums.length == 0 || r * c != nums.length * nums[0].length) + return nums; + + int[][] ans = new int[r][c]; + int k = 0; + + for (int[] row : nums) + for (final int num : row) { + ans[k / c][k % c] = num; + ++k; + } + + return ans; + } +} diff --git a/solutions/566. Reshape the Matrix/566.py b/solutions/566. Reshape the Matrix/566.py new file mode 100644 index 00000000000..7e5ddfc1b46 --- /dev/null +++ b/solutions/566. Reshape the Matrix/566.py @@ -0,0 +1,14 @@ +class Solution: + def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: + if nums == [] or r * c != len(nums) * len(nums[0]): + return nums + + ans = [[0 for j in range(c)] for i in range(r)] + k = 0 + + for row in nums: + for num in row: + ans[k // c][k % c] = num + k += 1 + + return ans diff --git a/solutions/567. Permutation in String/567-2.cpp b/solutions/567. Permutation in String/567-2.cpp new file mode 100644 index 00000000000..fbfed5647ae --- /dev/null +++ b/solutions/567. Permutation in String/567-2.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool checkInclusion(string s1, string s2) { + vector count(26); + int required = s1.length(); + + for (const char c : s1) + ++count[c - 'a']; + + for (int r = 0; r < s2.length(); ++r) { + if (--count[s2[r] - 'a'] >= 0) + --required; + if (r >= s1.length()) // The window is oversized. + if (++count[s2[r - s1.length()] - 'a'] > 0) + ++required; + if (required == 0) + return true; + } + + return false; + } +}; diff --git a/solutions/567. Permutation in String/567-2.java b/solutions/567. Permutation in String/567-2.java new file mode 100644 index 00000000000..df334eb8d22 --- /dev/null +++ b/solutions/567. Permutation in String/567-2.java @@ -0,0 +1,21 @@ +class Solution { + public boolean checkInclusion(String s1, String s2) { + int[] count = new int[26]; + int required = s1.length(); + + for (final char c : s1.toCharArray()) + ++count[c - 'a']; + + for (int r = 0; r < s2.length(); ++r) { + if (--count[s2.charAt(r) - 'a'] >= 0) + --required; + if (r >= s1.length()) // The window is oversized. + if (++count[s2.charAt(r - s1.length()) - 'a'] > 0) + ++required; + if (required == 0) + return true; + } + + return false; + } +} diff --git a/solutions/567. Permutation in String/567-2.py b/solutions/567. Permutation in String/567-2.py new file mode 100644 index 00000000000..dd317004041 --- /dev/null +++ b/solutions/567. Permutation in String/567-2.py @@ -0,0 +1,17 @@ +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + count = collections.Counter(s1) + required = len(s1) + + for r, c in enumerate(s2): + count[c] -= 1 + if count[c] >= 0: + required -= 1 + if r >= len(s1): # The window is oversized. + count[s2[r - len(s1)]] += 1 + if count[s2[r - len(s1)]] > 0: + required += 1 + if required == 0: + return True + + return False diff --git a/solutions/567. Permutation in String/567.cpp b/solutions/567. Permutation in String/567.cpp new file mode 100644 index 00000000000..0674c7e4a31 --- /dev/null +++ b/solutions/567. Permutation in String/567.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + bool checkInclusion(string s1, string s2) { + vector count(26); + int required = s1.length(); + + for (const char c : s1) + ++count[c - 'a']; + + for (int l = 0, r = 0; r < s2.length(); ++r) { + if (--count[s2[r] - 'a'] >= 0) + --required; + while (required == 0) { + if (r - l + 1 == s1.length()) + return true; + if (++count[s2[l++] - 'a'] > 0) + ++required; + } + } + + return false; + } +}; diff --git a/solutions/567. Permutation in String/567.java b/solutions/567. Permutation in String/567.java new file mode 100644 index 00000000000..d33ff659b7b --- /dev/null +++ b/solutions/567. Permutation in String/567.java @@ -0,0 +1,22 @@ +class Solution { + public boolean checkInclusion(String s1, String s2) { + int[] count = new int[26]; + int required = s1.length(); + + for (final char c : s1.toCharArray()) + ++count[c - 'a']; + + for (int l = 0, r = 0; r < s2.length(); ++r) { + if (--count[s2.charAt(r) - 'a'] >= 0) + --required; + while (required == 0) { + if (r - l + 1 == s1.length()) + return true; + if (++count[s2.charAt(l++) - 'a'] > 0) + ++required; + } + } + + return false; + } +} diff --git a/solutions/568. Maximum Vacation Days/568-2.cpp b/solutions/568. Maximum Vacation Days/568-2.cpp new file mode 100644 index 00000000000..a77fe2dbe8d --- /dev/null +++ b/solutions/568. Maximum Vacation Days/568-2.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxVacationDays(vector>& flights, vector>& days) { + const int N = days.size(); + const int K = days[0].size(); + // dp[i][k] := the number of vacations that can be taken from the i-th city + // and the k-th week + vector> dp(N, vector(K + 1)); + + for (int k = K - 1; k >= 0; --k) + for (int i = 0; i < N; ++i) { + dp[i][k] = days[i][k] + dp[i][k + 1]; + for (int j = 0; j < N; ++j) + if (flights[i][j] == 1) + dp[i][k] = max(dp[i][k], days[j][k] + dp[j][k + 1]); + } + + return dp[0][0]; + } +}; diff --git a/solutions/568. Maximum Vacation Days/568-2.java b/solutions/568. Maximum Vacation Days/568-2.java new file mode 100644 index 00000000000..5e4e46c3371 --- /dev/null +++ b/solutions/568. Maximum Vacation Days/568-2.java @@ -0,0 +1,19 @@ +class Solution { + public int maxVacationDays(int[][] flights, int[][] days) { + final int N = days.length; + final int K = days[0].length; + // dp[i][k] := the number of vacations that can be taken from the i-th city + // and the k-th week + int[][] dp = new int[N][K + 1]; + + for (int k = K - 1; k >= 0; --k) + for (int i = 0; i < N; ++i) { + dp[i][k] = days[i][k] + dp[i][k + 1]; + for (int j = 0; j < N; ++j) + if (flights[i][j] == 1) + dp[i][k] = Math.max(dp[i][k], days[j][k] + dp[j][k + 1]); + } + + return dp[0][0]; + } +} diff --git a/solutions/568. Maximum Vacation Days/568-3.cpp b/solutions/568. Maximum Vacation Days/568-3.cpp new file mode 100644 index 00000000000..612d9434abf --- /dev/null +++ b/solutions/568. Maximum Vacation Days/568-3.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int maxVacationDays(vector>& flights, vector>& days) { + const int N = days.size(); + const int K = days[0].size(); + // dp[i] := the number of vacations that can be taken from the i-th city + vector dp(N); + + for (int k = K - 1; k >= 0; --k) { + vector newDp(N); + for (int i = 0; i < N; ++i) { + newDp[i] = days[i][k] + dp[i]; + for (int j = 0; j < N; ++j) + if (flights[i][j] == 1) + newDp[i] = max(newDp[i], days[j][k] + dp[j]); + } + dp = move(newDp); + } + + return dp[0]; + } +}; diff --git a/solutions/568. Maximum Vacation Days/568-3.java b/solutions/568. Maximum Vacation Days/568-3.java new file mode 100644 index 00000000000..af9608389fa --- /dev/null +++ b/solutions/568. Maximum Vacation Days/568-3.java @@ -0,0 +1,21 @@ +class Solution { + public int maxVacationDays(int[][] flights, int[][] days) { + final int N = days.length; + final int K = days[0].length; + // dp[i] := the number of vacations that can be taken from the i-th city + int[] dp = new int[N]; + + for (int k = K - 1; k >= 0; --k) { + int[] newDp = new int[N]; + for (int i = 0; i < N; ++i) { + newDp[i] = days[i][k] + dp[i]; + for (int j = 0; j < N; ++j) + if (flights[i][j] == 1) + newDp[i] = Math.max(newDp[i], days[j][k] + dp[j]); + } + dp = newDp; + } + + return dp[0]; + } +} diff --git a/solutions/568. Maximum Vacation Days/568.cpp b/solutions/568. Maximum Vacation Days/568.cpp new file mode 100644 index 00000000000..5a5929c08aa --- /dev/null +++ b/solutions/568. Maximum Vacation Days/568.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int maxVacationDays(vector>& flights, vector>& days) { + vector> mem(days.size(), vector(days[0].size(), INT_MIN)); + return maxVacationDays(flights, days, 0, 0, mem); + } + + private: + // Returns the number of vacations that can be taken from the i-th city and + // the k-th week. + int maxVacationDays(const vector>& flights, + const vector>& days, int i, int k, + vector>& mem) { + if (k == days[0].size()) + return 0; + if (mem[i][k] != INT_MIN) + return mem[i][k]; + + // Stay at the j-th city or fly from the i-th city to the j-th city. + for (int j = 0; j < flights.size(); ++j) + if (j == i || flights[i][j] == 1) + mem[i][k] = max(mem[i][k], days[j][k] + maxVacationDays(flights, days, + j, k + 1, mem)); + + return mem[i][k]; + } +}; diff --git a/solutions/568. Maximum Vacation Days/568.java b/solutions/568. Maximum Vacation Days/568.java new file mode 100644 index 00000000000..8ee862386fe --- /dev/null +++ b/solutions/568. Maximum Vacation Days/568.java @@ -0,0 +1,23 @@ +class Solution { + public int maxVacationDays(int[][] flights, int[][] days) { + int[][] mem = new int[days.length][days[0].length]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MIN_VALUE)); + return maxVacationDays(flights, days, 0, 0, mem); + } + + // Returns the number of vacations that can be taken from the i-th city and + // the k-th week. + private int maxVacationDays(int[][] flights, int[][] days, int i, int k, int[][] mem) { + if (k == days[0].length) + return 0; + if (mem[i][k] != Integer.MIN_VALUE) + return mem[i][k]; + + // Stay at the j-th city or fly from the i-th city to the j-th city. + for (int j = 0; j < flights.length; j++) + if (j == i || flights[i][j] == 1) + mem[i][k] = Math.max(mem[i][k], days[j][k] + maxVacationDays(flights, days, j, k + 1, mem)); + + return mem[i][k]; + } +} diff --git a/solutions/569. Median Employee Salary/569.sql b/solutions/569. Median Employee Salary/569.sql new file mode 100644 index 00000000000..43055d0d372 --- /dev/null +++ b/solutions/569. Median Employee Salary/569.sql @@ -0,0 +1,18 @@ +WITH + EmployeesWithRowNumberInCompany AS ( + SELECT + id, + company, + salary, + ROW_NUMBER() OVER( + PARTITION BY company + ORDER BY salary + ) AS `row_number`, + COUNT(*) OVER(PARTITION BY company) AS `count` + FROM Employee + ) +SELECT id, company, salary +FROM EmployeesWithRowNumberInCompany +WHERE + `row_number` >= `count` / 2 + AND `row_number` <= `count` / 2 + 1; diff --git a/solutions/57. Insert Interval/57.cpp b/solutions/57. Insert Interval/57.cpp new file mode 100644 index 00000000000..0605df20313 --- /dev/null +++ b/solutions/57. Insert Interval/57.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector> insert(vector>& intervals, + vector& newInterval) { + const int n = intervals.size(); + vector> ans; + int i = 0; + + while (i < n && intervals[i][1] < newInterval[0]) + ans.push_back(intervals[i++]); + + // Merge overlapping intervals. + while (i < n && intervals[i][0] <= newInterval[1]) { + newInterval[0] = min(newInterval[0], intervals[i][0]); + newInterval[1] = max(newInterval[1], intervals[i][1]); + ++i; + } + + ans.push_back(newInterval); + + while (i < n) + ans.push_back(intervals[i++]); + + return ans; + } +}; diff --git a/solutions/57. Insert Interval/57.java b/solutions/57. Insert Interval/57.java new file mode 100644 index 00000000000..64fd7b9accb --- /dev/null +++ b/solutions/57. Insert Interval/57.java @@ -0,0 +1,24 @@ +class Solution { + public int[][] insert(int[][] intervals, int[] newInterval) { + final int n = intervals.length; + List ans = new ArrayList<>(); + int i = 0; + + while (i < n && intervals[i][1] < newInterval[0]) + ans.add(intervals[i++]); + + // Merge overlapping intervals. + while (i < n && intervals[i][0] <= newInterval[1]) { + newInterval[0] = Math.min(newInterval[0], intervals[i][0]); + newInterval[1] = Math.max(newInterval[1], intervals[i][1]); + ++i; + } + + ans.add(newInterval); + + while (i < n) + ans.add(intervals[i++]); + + return ans.toArray(int[][] ::new); + } +} diff --git a/solutions/57. Insert Interval/57.py b/solutions/57. Insert Interval/57.py new file mode 100644 index 00000000000..d8c09c47a5a --- /dev/null +++ b/solutions/57. Insert Interval/57.py @@ -0,0 +1,23 @@ +class Solution: + def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + n = len(intervals) + ans = [] + i = 0 + + while i < n and intervals[i][1] < newInterval[0]: + ans.append(intervals[i]) + i += 1 + + # Merge overlapping intervals. + while i < n and intervals[i][0] <= newInterval[1]: + newInterval[0] = min(newInterval[0], intervals[i][0]) + newInterval[1] = max(newInterval[1], intervals[i][1]) + i += 1 + + ans.append(newInterval) + + while i < n: + ans.append(intervals[i]) + i += 1 + + return ans diff --git a/solutions/570. Managers with at Least 5 Direct Reports/570.sql b/solutions/570. Managers with at Least 5 Direct Reports/570.sql new file mode 100644 index 00000000000..8e2071d949b --- /dev/null +++ b/solutions/570. Managers with at Least 5 Direct Reports/570.sql @@ -0,0 +1,6 @@ +SELECT Manager.name +FROM Employee +INNER JOIN Employee AS Manager + ON (Employee.managerId = Manager.id) +GROUP BY Manager.id +HAVING COUNT(*) >= 5; diff --git a/solutions/571. Find Median Given Frequency of Numbers/571.sql b/solutions/571. Find Median Given Frequency of Numbers/571.sql new file mode 100644 index 00000000000..320e33f6807 --- /dev/null +++ b/solutions/571. Find Median Given Frequency of Numbers/571.sql @@ -0,0 +1,11 @@ +WITH + NumbersMetadata AS ( + SELECT + *, + SUM(frequency) OVER(ORDER BY num) AS running_frequency, + (SUM(frequency) OVER()) / 2 AS median_frequency + FROM Numbers + ) +SELECT AVG(num) AS median +FROM NumbersMetadata +WHERE median_frequency BETWEEN running_frequency - frequency AND running_frequency; diff --git a/solutions/572. Subtree of Another Tree/572.cpp b/solutions/572. Subtree of Another Tree/572.cpp new file mode 100644 index 00000000000..a62cf877e34 --- /dev/null +++ b/solutions/572. Subtree of Another Tree/572.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool isSubtree(TreeNode* s, TreeNode* t) { + if (s == nullptr) + return false; + if (isSameTree(s, t)) + return true; + return isSubtree(s->left, t) || isSubtree(s->right, t); + } + + private: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (!p || !q) + return p == q; + return p->val == q->val && // + isSameTree(p->left, q->left) && // + isSameTree(p->right, q->right); + } +}; diff --git a/solutions/572. Subtree of Another Tree/572.java b/solutions/572. Subtree of Another Tree/572.java new file mode 100644 index 00000000000..2e7357e0440 --- /dev/null +++ b/solutions/572. Subtree of Another Tree/572.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isSubtree(TreeNode s, TreeNode t) { + if (s == null) + return false; + if (isSameTree(s, t)) + return true; + return isSubtree(s.left, t) || isSubtree(s.right, t); + } + + private boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null || q == null) + return p == q; + return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} diff --git a/solutions/573. Squirrel Simulation/573.cpp b/solutions/573. Squirrel Simulation/573.cpp new file mode 100644 index 00000000000..14cf60fbfab --- /dev/null +++ b/solutions/573. Squirrel Simulation/573.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int minDistance(int height, int width, vector& tree, + vector& squirrel, vector>& nuts) { + int totDist = 0; + int maxSave = INT_MIN; + + for (const vector& nut : nuts) { + totDist += dist(nut, tree) * 2; + maxSave = max(maxSave, dist(nut, tree) - dist(nut, squirrel)); + } + + return totDist - maxSave; + } + + private: + int dist(const vector& a, const vector& b) { + return abs(a[0] - b[0]) + abs(a[1] - b[1]); + } +}; diff --git a/solutions/573. Squirrel Simulation/573.java b/solutions/573. Squirrel Simulation/573.java new file mode 100644 index 00000000000..e618191da23 --- /dev/null +++ b/solutions/573. Squirrel Simulation/573.java @@ -0,0 +1,17 @@ +class Solution { + public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) { + int totDist = 0; + int maxSave = Integer.MIN_VALUE; + + for (int[] nut : nuts) { + totDist += dist(nut, tree) * 2; + maxSave = Math.max(maxSave, dist(nut, tree) - dist(nut, squirrel)); + } + + return totDist - maxSave; + } + + private int dist(int[] a, int[] b) { + return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); + } +} diff --git a/solutions/573. Squirrel Simulation/573.py b/solutions/573. Squirrel Simulation/573.py new file mode 100644 index 00000000000..7a812eb2569 --- /dev/null +++ b/solutions/573. Squirrel Simulation/573.py @@ -0,0 +1,8 @@ +class Solution: + def minDistance(self, height: int, width: int, tree: List[int], squirrel: List[int], nuts: List[List[int]]) -> int: + def dist(a: List[int], b: List[int]) -> int: + return abs(a[0] - b[0]) + abs(a[1] - b[1]) + + totDist = sum(dist(nut, tree) for nut in nuts) * 2 + maxSave = max(dist(nut, tree) - dist(nut, squirrel) for nut in nuts) + return totDist - maxSave diff --git a/solutions/574. Winning Candidate/574.sql b/solutions/574. Winning Candidate/574.sql new file mode 100644 index 00000000000..78c32b841db --- /dev/null +++ b/solutions/574. Winning Candidate/574.sql @@ -0,0 +1,7 @@ +SELECT Candidate.name +FROM Candidate +INNER JOIN Vote + ON (Candidate.id = Vote.candidateId) +GROUP BY Candidate.id +ORDER BY COUNT(*) DESC +LIMIT 1; diff --git a/solutions/575. Distribute Candies/575.cpp b/solutions/575. Distribute Candies/575.cpp new file mode 100644 index 00000000000..b685965af48 --- /dev/null +++ b/solutions/575. Distribute Candies/575.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int distributeCandies(vector& candies) { + bitset<200001> bitset; + + for (const int candy : candies) + bitset.set(candy + 100000); + + return min(candies.size() / 2, bitset.contains()); + } +}; diff --git a/solutions/575. Distribute Candies/575.java b/solutions/575. Distribute Candies/575.java new file mode 100644 index 00000000000..73c95bc3d82 --- /dev/null +++ b/solutions/575. Distribute Candies/575.java @@ -0,0 +1,10 @@ +class Solution { + public int distributeCandies(int[] candies) { + BitSet bitset = new BitSet(200001); + + for (final int candy : candies) + bitset.set(candy + 100000); + + return Math.min(candies.length / 2, bitset.cardinality()); + } +} diff --git a/solutions/575. Distribute Candies/575.py b/solutions/575. Distribute Candies/575.py new file mode 100644 index 00000000000..2e3a80a31ba --- /dev/null +++ b/solutions/575. Distribute Candies/575.py @@ -0,0 +1,3 @@ +class Solution: + def distributeCandies(self, candies: List[int]) -> int: + return min(len(candies) // 2, len(set(candies))) diff --git a/solutions/576. Out of Boundary Paths/576-2.cpp b/solutions/576. Out of Boundary Paths/576-2.cpp new file mode 100644 index 00000000000..7404e66edf6 --- /dev/null +++ b/solutions/576. Out of Boundary Paths/576-2.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + constexpr int kMod = 1'000'000'007; + int ans = 0; + // dp[i][j] := the number of paths to move the ball (i, j) out-of-bounds + vector> dp(m, vector(n)); + dp[startRow][startColumn] = 1; + + while (maxMove--) { + vector> newDp(m, vector(n)); + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (dp[i][j] > 0) + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + ans = (ans + dp[i][j]) % kMod; + else + newDp[x][y] = (newDp[x][y] + dp[i][j]) % kMod; + } + dp = move(newDp); + } + + return ans; + } +}; diff --git a/solutions/576. Out of Boundary Paths/576-2.java b/solutions/576. Out of Boundary Paths/576-2.java new file mode 100644 index 00000000000..fda0059f8f1 --- /dev/null +++ b/solutions/576. Out of Boundary Paths/576-2.java @@ -0,0 +1,28 @@ +class Solution { + public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int kMod = 1_000_000_007; + int ans = 0; + // dp[i][j] := the number of paths to move the ball (i, j) out-of-bounds + int[][] dp = new int[m][n]; + dp[startRow][startColumn] = 1; + + while (maxMove-- > 0) { + int[][] newDp = new int[m][n]; + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (dp[i][j] > 0) + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + ans = (ans + dp[i][j]) % kMod; + else + newDp[x][y] = (newDp[x][y] + dp[i][j]) % kMod; + } + dp = newDp; + } + + return ans; + } +} diff --git a/solutions/576. Out of Boundary Paths/576-2.py b/solutions/576. Out of Boundary Paths/576-2.py new file mode 100644 index 00000000000..9af8d617b89 --- /dev/null +++ b/solutions/576. Out of Boundary Paths/576-2.py @@ -0,0 +1,24 @@ +class Solution: + def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + kMod = 1_000_000_007 + ans = 0 + # dp[i][j] := the number of paths to move the ball (i, j) out-of-bounds + dp = [[0] * n for _ in range(m)] + dp[startRow][startColumn] = 1 + + for _ in range(maxMove): + newDp = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + if dp[i][j] > 0: + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x == m or y < 0 or y == n: + ans = (ans + dp[i][j]) % kMod + else: + newDp[x][y] = (newDp[x][y] + dp[i][j]) % kMod + dp = newDp + + return ans diff --git a/solutions/576. Out of Boundary Paths/576.cpp b/solutions/576. Out of Boundary Paths/576.cpp new file mode 100644 index 00000000000..f34c33d316e --- /dev/null +++ b/solutions/576. Out of Boundary Paths/576.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + vector>> mem(maxMove + 1, + vector>(m, vector(n, -1))); + return findPaths(m, n, maxMove, startRow, startColumn, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of paths to move the ball at (i, j) out-of-bounds with k + // moves. + int findPaths(int m, int n, int k, int i, int j, + vector>>& mem) { + if (i < 0 || i == m || j < 0 || j == n) + return 1; + if (k == 0) + return 0; + if (mem[k][i][j] != -1) + return mem[k][i][j]; + return mem[k][i][j] = (findPaths(m, n, k - 1, i + 1, j, mem) * 1L + + findPaths(m, n, k - 1, i - 1, j, mem) + + findPaths(m, n, k - 1, i, j + 1, mem) + + findPaths(m, n, k - 1, i, j - 1, mem)) % + kMod; + } +}; diff --git a/solutions/576. Out of Boundary Paths/576.java b/solutions/576. Out of Boundary Paths/576.java new file mode 100644 index 00000000000..115106a314a --- /dev/null +++ b/solutions/576. Out of Boundary Paths/576.java @@ -0,0 +1,24 @@ +class Solution { + public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + Integer[][][] mem = new Integer[maxMove + 1][m][n]; + return findPaths(m, n, maxMove, startRow, startColumn, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of paths to move the ball at (i, j) out-of-bounds with k + // moves. + private int findPaths(int m, int n, int k, int i, int j, Integer[][][] mem) { + if (i < 0 || i == m || j < 0 || j == n) + return 1; + if (k == 0) + return 0; + if (mem[k][i][j] != null) + return mem[k][i][j]; + return mem[k][i][j] = (int) ((findPaths(m, n, k - 1, i + 1, j, mem) * 1L + + findPaths(m, n, k - 1, i - 1, j, mem) + + findPaths(m, n, k - 1, i, j + 1, mem) + + findPaths(m, n, k - 1, i, j - 1, mem)) % + kMod); + } +} diff --git a/solutions/576. Out of Boundary Paths/576.py b/solutions/576. Out of Boundary Paths/576.py new file mode 100644 index 00000000000..eae924daf2a --- /dev/null +++ b/solutions/576. Out of Boundary Paths/576.py @@ -0,0 +1,18 @@ +class Solution: + def findPaths(self, m, n, maxMove, startRow, startColumn): + kMod = 1000000007 + + @functools.lru_cache(None) + def dp(k: int, i: int, j: int) -> int: + """ + Returns the number of paths to move the ball at (i, j) out-of-bounds with + k moves. + """ + if i < 0 or i == m or j < 0 or j == n: + return 1 + if k == 0: + return 0 + return (dp(k - 1, i + 1, j) + dp(k - 1, i - 1, j) + + dp(k - 1, i, j + 1) + dp(k - 1, i, j - 1)) % kMod + + return dp(maxMove, startRow, startColumn) diff --git a/solutions/577. Employee Bonus/577.sql b/solutions/577. Employee Bonus/577.sql new file mode 100644 index 00000000000..82dd1c41100 --- /dev/null +++ b/solutions/577. Employee Bonus/577.sql @@ -0,0 +1,5 @@ +SELECT Employee.name, Bonus.bonus +FROM Employee +LEFT JOIN Bonus + USING (empId) +WHERE IFNULL(Bonus.bonus, 0) < 1000; diff --git a/solutions/578. Get Highest Answer Rate Question/578.sql b/solutions/578. Get Highest Answer Rate Question/578.sql new file mode 100644 index 00000000000..0852c311f31 --- /dev/null +++ b/solutions/578. Get Highest Answer Rate Question/578.sql @@ -0,0 +1,7 @@ +SELECT question_id AS survey_log +FROM SurveyLog +GROUP BY 1 +ORDER BY + COUNT(answer_id) / COUNT(*) DESC, + question_id ASC +LIMIT 1; diff --git a/solutions/579. Find Cumulative Salary of an Employee/579.sql b/solutions/579. Find Cumulative Salary of an Employee/579.sql new file mode 100644 index 00000000000..ede23422d24 --- /dev/null +++ b/solutions/579. Find Cumulative Salary of an Employee/579.sql @@ -0,0 +1,17 @@ +WITH + CurrMonth AS ( + SELECT + *, + MAX(month) OVER(PARTITION BY id) AS max_month + FROM Employee + ) +SELECT + CurrMonth.id, + CurrMonth.month, + SUM(PrevMonth.salary) AS salary +FROM CurrMonth +INNER JOIN Employee AS PrevMonth + ON (CurrMonth.id = PrevMonth.id AND CurrMonth.month - PrevMonth.month BETWEEN 0 AND 2) +WHERE CurrMonth.month != CurrMonth.max_month +GROUP BY 1, 2 +ORDER BY 1, 2 DESC; diff --git a/solutions/58. Length of Last Word/58.cpp b/solutions/58. Length of Last Word/58.cpp new file mode 100644 index 00000000000..649fdc09cd7 --- /dev/null +++ b/solutions/58. Length of Last Word/58.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int lengthOfLastWord(string s) { + int i = s.length() - 1; + + while (i >= 0 && s[i] == ' ') + --i; + const int lastIndex = i; + while (i >= 0 && s[i] != ' ') + --i; + + return lastIndex - i; + } +}; diff --git a/solutions/58. Length of Last Word/58.java b/solutions/58. Length of Last Word/58.java new file mode 100644 index 00000000000..ea66ba10eea --- /dev/null +++ b/solutions/58. Length of Last Word/58.java @@ -0,0 +1,13 @@ +class Solution { + public int lengthOfLastWord(String s) { + int i = s.length() - 1; + + while (i >= 0 && s.charAt(i) == ' ') + --i; + final int lastIndex = i; + while (i >= 0 && s.charAt(i) != ' ') + --i; + + return lastIndex - i; + } +} diff --git a/solutions/58. Length of Last Word/58.py b/solutions/58. Length of Last Word/58.py new file mode 100644 index 00000000000..16a6bd5d185 --- /dev/null +++ b/solutions/58. Length of Last Word/58.py @@ -0,0 +1,11 @@ +class Solution: + def lengthOfLastWord(self, s: str) -> int: + i = len(s) - 1 + + while i >= 0 and s[i] == ' ': + i -= 1 + lastIndex = i + while i >= 0 and s[i] != ' ': + i -= 1 + + return lastIndex - i diff --git a/solutions/580. Count Student Number in Departments/580.sql b/solutions/580. Count Student Number in Departments/580.sql new file mode 100644 index 00000000000..1a645edc0ee --- /dev/null +++ b/solutions/580. Count Student Number in Departments/580.sql @@ -0,0 +1,8 @@ +SELECT + Department.dept_name, + COUNT(Student.student_id) AS student_number +FROM Department +LEFT JOIN Student + USING (dept_id) +GROUP BY 1 +ORDER BY 2 DESC, 1; diff --git a/solutions/581. Shortest Unsorted Continuous Subarray/581.cpp b/solutions/581. Shortest Unsorted Continuous Subarray/581.cpp new file mode 100644 index 00000000000..cc9c6f4e593 --- /dev/null +++ b/solutions/581. Shortest Unsorted Continuous Subarray/581.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int findUnsortedSubarray(vector& nums) { + const int n = nums.size(); + int mn = INT_MAX; + int mx = INT_MIN; + bool meetDecrease = false; + bool meetIncrease = false; + + for (int i = 1; i < n; ++i) { + if (nums[i] < nums[i - 1]) + meetDecrease = true; + if (meetDecrease) + mn = min(mn, nums[i]); + } + + for (int i = n - 2; i >= 0; --i) { + if (nums[i] > nums[i + 1]) + meetIncrease = true; + if (meetIncrease) + mx = max(mx, nums[i]); + } + + int l; + for (l = 0; l < n; ++l) + if (nums[l] > mn) + break; + + int r; + for (r = n - 1; r >= 0; --r) + if (nums[r] < mx) + break; + + return l < r ? r - l + 1 : 0; + } +}; diff --git a/solutions/581. Shortest Unsorted Continuous Subarray/581.java b/solutions/581. Shortest Unsorted Continuous Subarray/581.java new file mode 100644 index 00000000000..66466a97c17 --- /dev/null +++ b/solutions/581. Shortest Unsorted Continuous Subarray/581.java @@ -0,0 +1,35 @@ +class Solution { + public int findUnsortedSubarray(int[] nums) { + final int n = nums.length; + int mn = Integer.MAX_VALUE; + int mx = Integer.MIN_VALUE; + boolean meetDecrease = false; + boolean meetIncrease = false; + + for (int i = 1; i < n; ++i) { + if (nums[i] < nums[i - 1]) + meetDecrease = true; + if (meetDecrease) + mn = Math.min(mn, nums[i]); + } + + for (int i = n - 2; i >= 0; --i) { + if (nums[i] > nums[i + 1]) + meetIncrease = true; + if (meetIncrease) + mx = Math.max(mx, nums[i]); + } + + int l = 0; + for (l = 0; l < n; ++l) + if (nums[l] > mn) + break; + + int r = 0; + for (r = n - 1; r >= 0; --r) + if (nums[r] < mx) + break; + + return l > r ? 0 : r - l + 1; + } +} diff --git a/solutions/581. Shortest Unsorted Continuous Subarray/581.py b/solutions/581. Shortest Unsorted Continuous Subarray/581.py new file mode 100644 index 00000000000..74833549940 --- /dev/null +++ b/solutions/581. Shortest Unsorted Continuous Subarray/581.py @@ -0,0 +1,29 @@ +class Solution: + def findUnsortedSubarray(self, nums: List[int]) -> int: + mn = math.inf + mx = -math.inf + flag = False + + for i in range(1, len(nums)): + if nums[i] < nums[i - 1]: + flag = True + if flag: + mn = min(mn, nums[i]) + + flag = False + + for i in reversed(range(len(nums) - 1)): + if nums[i] > nums[i + 1]: + flag = True + if flag: + mx = max(mx, nums[i]) + + for l in range(len(nums)): + if nums[l] > mn: + break + + for r, num in reversed(list(enumerate(nums))): + if num < mx: + break + + return 0 if l >= r else r - l + 1 diff --git a/solutions/582. Kill Process/582.cpp b/solutions/582. Kill Process/582.cpp new file mode 100644 index 00000000000..56f0859e7bd --- /dev/null +++ b/solutions/582. Kill Process/582.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector killProcess(vector& pid, vector& ppid, int kill) { + vector ans; + unordered_map> tree; + + for (int i = 0; i < pid.size(); ++i) { + if (ppid[i] == 0) + continue; + tree[ppid[i]].push_back(pid[i]); + } + + dfs(tree, kill, ans); + return ans; + } + + private: + void dfs(const unordered_map>& tree, int u, + vector& ans) { + ans.push_back(u); + if (!tree.contains(u)) + return; + for (const int v : tree.at(u)) + dfs(tree, v, ans); + } +}; diff --git a/solutions/582. Kill Process/582.java b/solutions/582. Kill Process/582.java new file mode 100644 index 00000000000..eeaa61cdf91 --- /dev/null +++ b/solutions/582. Kill Process/582.java @@ -0,0 +1,22 @@ +class Solution { + public List killProcess(List pid, List ppid, int kill) { + List ans = new ArrayList<>(); + Map> tree = new HashMap<>(); + + for (int i = 0; i < pid.size(); ++i) { + if (ppid.get(i) == 0) + continue; + tree.putIfAbsent(ppid.get(i), new ArrayList<>()); + tree.get(ppid.get(i)).add(pid.get(i)); + } + + dfs(tree, kill, ans); + return ans; + } + + private void dfs(Map> tree, int u, List ans) { + ans.add(u); + for (final int v : tree.getOrDefault(u, new ArrayList<>())) + dfs(tree, v, ans); + } +} diff --git a/solutions/582. Kill Process/582.py b/solutions/582. Kill Process/582.py new file mode 100644 index 00000000000..17cfaf64f99 --- /dev/null +++ b/solutions/582. Kill Process/582.py @@ -0,0 +1,17 @@ +class Solution: + def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: + ans = [] + tree = collections.defaultdict(list) + + for v, u in zip(pid, ppid): + if u == 0: + continue + tree[u].append(v) + + def dfs(u: int) -> None: + ans.append(u) + for v in tree.get(u, []): + dfs(v) + + dfs(kill) + return ans diff --git a/solutions/583. Delete Operation for Two Strings/583.cpp b/solutions/583. Delete Operation for Two Strings/583.cpp new file mode 100644 index 00000000000..e8788dd9a4f --- /dev/null +++ b/solutions/583. Delete Operation for Two Strings/583.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minDistance(string word1, string word2) { + const int k = lcs(word1, word2); + return (word1.length() - k) + (word2.length() - k); + } + + private: + int lcs(const string& a, const string& b) { + const int m = a.length(); + const int n = b.length(); + // dp[i][j] := the length of LCS(a[0..i), b[0..j)) + vector> dp(m + 1, vector(n + 1)); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (a[i - 1] == b[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 dp[m][n]; + } +}; diff --git a/solutions/583. Delete Operation for Two Strings/583.java b/solutions/583. Delete Operation for Two Strings/583.java new file mode 100644 index 00000000000..338404428aa --- /dev/null +++ b/solutions/583. Delete Operation for Two Strings/583.java @@ -0,0 +1,22 @@ +class Solution { + public int minDistance(String word1, String word2) { + final int k = lcs(word1, word2); + return (word1.length() - k) + (word2.length() - k); + } + + private int lcs(final String a, final String b) { + final int m = a.length(); + final int n = b.length(); + // dp[i][j] := the length of LCS(a[0..i), b[0..j)) + int[][] dp = new int[m + 1][n + 1]; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (a.charAt(i - 1) == b.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 dp[m][n]; + } +} diff --git a/solutions/583. Delete Operation for Two Strings/583.py b/solutions/583. Delete Operation for Two Strings/583.py new file mode 100644 index 00000000000..c4783b32ef6 --- /dev/null +++ b/solutions/583. Delete Operation for Two Strings/583.py @@ -0,0 +1,19 @@ +class Solution: + def minDistance(self, word1: str, word2: str) -> int: + k = self._lcs(word1, word2) + return (len(word1) - k) + (len(word2) - k) + + def _lcs(self, a: str, b: str) -> int: + m = len(a) + n = len(b) + # dp[i][j] := the length of LCS(a[0..i), b[0..j)) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(1, m + 1): + for j in range(1, n + 1): + if a[i - 1] == b[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 dp[m][n] diff --git a/solutions/584. Find Customer Referee/584.sql b/solutions/584. Find Customer Referee/584.sql new file mode 100644 index 00000000000..d5088d02808 --- /dev/null +++ b/solutions/584. Find Customer Referee/584.sql @@ -0,0 +1,3 @@ +SELECT name +FROM Customer +WHERE referee_id IS NULL OR referee_id != 2; diff --git a/solutions/585. Investments in 2016/585.sql b/solutions/585. Investments in 2016/585.sql new file mode 100644 index 00000000000..e19bfb210e8 --- /dev/null +++ b/solutions/585. Investments in 2016/585.sql @@ -0,0 +1,12 @@ +WITH + InsuranceWithCounts AS ( + SELECT + tiv_2016, + COUNT(*) OVER(PARTITION by tiv_2015) AS tiv_2015_count, + COUNT(*) OVER(PARTITION by lat, lon) AS city_count + FROM Insurance + ) +SELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016 +FROM InsuranceWithCounts +WHERE tiv_2015_count > 1 + AND city_count = 1; diff --git a/solutions/586. Customer Placing the Largest Number of Orders/586.sql b/solutions/586. Customer Placing the Largest Number of Orders/586.sql new file mode 100644 index 00000000000..78ac524f790 --- /dev/null +++ b/solutions/586. Customer Placing the Largest Number of Orders/586.sql @@ -0,0 +1,5 @@ +SELECT customer_number +FROM Orders +GROUP BY 1 +ORDER BY COUNT(*) DESC +LIMIT 1; diff --git a/solutions/587. Erect the Fence/587.cpp b/solutions/587. Erect the Fence/587.cpp new file mode 100644 index 00000000000..af3d451f51d --- /dev/null +++ b/solutions/587. Erect the Fence/587.cpp @@ -0,0 +1,44 @@ +// Monotone Chain +class Solution { + public: + vector> outerTrees(vector>& trees) { + vector> hull; + + ranges::sort(trees, [](const vector& a, const vector& b) { + return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]; + }); + + // Build the lower hull: left-to-right scan. + for (const vector& tree : trees) { + while (hull.size() > 1 && + cross(hull.back(), hull[hull.size() - 2], tree) > 0) + hull.pop_back(); + hull.push_back(tree); + } + hull.pop_back(); + + // Build the upper hull: right-to-left scan. + for (int i = trees.size() - 1; i >= 0; --i) { + while (hull.size() > 1 && + cross(hull.back(), hull[hull.size() - 2], trees[i]) > 0) + hull.pop_back(); + hull.push_back(trees[i]); + } + + // Remove the redundant elements from the stack. + ranges::sort(hull, [](const vector& a, const vector& b) { + return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]; + }); + hull.erase(unique(hull.begin(), hull.end(), + [](const vector& a, const vector& b) { + return a[0] == b[0] && a[1] == b[1]; + }), + hull.end()); + return hull; + } + + private: + int cross(const vector& p, const vector& q, const vector& r) { + return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); + } +}; diff --git a/solutions/587. Erect the Fence/587.java b/solutions/587. Erect the Fence/587.java new file mode 100644 index 00000000000..d3dd51d4c8c --- /dev/null +++ b/solutions/587. Erect the Fence/587.java @@ -0,0 +1,30 @@ +// Monotone Chain +class Solution { + public int[][] outerTrees(int[][] trees) { + Stack hull = new Stack<>(); + + Arrays.sort(trees, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + + // Build the lower hull: left-to-right scan. + for (int[] tree : trees) { + while (hull.size() > 1 && cross(hull.peek(), hull.get(hull.size() - 2), tree) > 0) + hull.pop(); + hull.push(tree); + } + hull.pop(); + + // Build the upper hull: right-to-left scan. + for (int i = trees.length - 1; i >= 0; --i) { + while (hull.size() > 1 && cross(hull.peek(), hull.get(hull.size() - 2), trees[i]) > 0) + hull.pop(); + hull.push(trees[i]); + } + + // Remove the redundant elements from the stack. + return new HashSet<>(hull).stream().toArray(int[][] ::new); + } + + private int cross(int[] p, int[] q, int[] r) { + return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); + } +} diff --git a/solutions/587. Erect the Fence/587.py b/solutions/587. Erect the Fence/587.py new file mode 100644 index 00000000000..b9fe6483cdf --- /dev/null +++ b/solutions/587. Erect the Fence/587.py @@ -0,0 +1,24 @@ +class Solution: + def outerTrees(self, trees: List[List[int]]) -> List[List[int]]: + hull = [] + + trees.sort(key=lambda x: (x[0], x[1])) + + def cross(p: List[int], q: List[int], r: List[int]) -> int: + return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) + + # Build the lower hull: left-to-right scan. + for tree in trees: + while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0: + hull.pop() + hull.append(tuple(tree)) + hull.pop() + + # Build the upper hull: right-to-left scan. + for tree in reversed(trees): + while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0: + hull.pop() + hull.append(tuple(tree)) + + # Remove the redundant elements from the stack. + return list(set(hull)) diff --git a/solutions/588. Design In-Memory File System/588.cpp b/solutions/588. Design In-Memory File System/588.cpp new file mode 100644 index 00000000000..98cfd5617d2 --- /dev/null +++ b/solutions/588. Design In-Memory File System/588.cpp @@ -0,0 +1,65 @@ +struct TrieNode { + map> children; // lexicographical + bool isFile = false; + string content; +}; + +class FileSystem { + public: + vector ls(string path) { + auto [node, lastDir] = createDirAndGetPair(path); + if (node->isFile) + return {lastDir}; + + vector ans; + + for (const auto& [file, _] : node->children) + ans.push_back(file); + + return ans; + } + + void mkdir(string path) { + createDirAndGetPair(path); + } + + void addContentToFile(string filePath, string content) { + shared_ptr node = createDirAndGetPair(filePath).first; + node->isFile = true; + node->content += content; + } + + string readContentFromFile(string filePath) { + shared_ptr node = createDirAndGetPair(filePath).first; + return node->content; + } + + private: + shared_ptr root = make_shared(); + + // e.g. createDirAndGetPair("/a//b") -> {TrieNode b, string "b"} + pair, string> createDirAndGetPair(const string& path) { + const vector dirs = getDirs(path); + shared_ptr node = root; + + for (const string& dir : dirs) { + if (!node->children.contains(dir)) + node->children[dir] = make_shared(); + node = node->children[dir]; + } + + return {node, dirs.empty() ? "" : dirs.back()}; + } + + // e.g. getDirs("/a//b") -> ["a", "b"] + vector getDirs(const string& path) { + vector dirs; + istringstream iss(path); + + for (string dir; getline(iss, dir, '/');) + if (!dir.empty()) // Make sure that "/a//b" == "/a/b". + dirs.push_back(dir); + + return dirs; + } +}; diff --git a/solutions/589. N-ary Tree Preorder Traversal/589.cpp b/solutions/589. N-ary Tree Preorder Traversal/589.cpp new file mode 100644 index 00000000000..9bfb7a406a4 --- /dev/null +++ b/solutions/589. N-ary Tree Preorder Traversal/589.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector preorder(Node* root) { + if (root == nullptr) + return {}; + + vector ans; + stack stack{{root}}; + + while (!stack.empty()) { + root = stack.top(), stack.pop(); + ans.push_back(root->val); + for (auto it = root->children.rbegin(); it != root->children.rend(); ++it) + stack.push(*it); + } + + return ans; + } +}; diff --git a/solutions/589. N-ary Tree Preorder Traversal/589.java b/solutions/589. N-ary Tree Preorder Traversal/589.java new file mode 100644 index 00000000000..9f4c9f9a924 --- /dev/null +++ b/solutions/589. N-ary Tree Preorder Traversal/589.java @@ -0,0 +1,19 @@ +class Solution { + public List preorder(Node root) { + if (root == null) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + Deque stack = new ArrayDeque<>(); + stack.push(root); + + while (!stack.isEmpty()) { + root = stack.pop(); + ans.add(root.val); + for (int i = root.children.size() - 1; i >= 0; --i) + stack.push(root.children.get(i)); + } + + return ans; + } +} diff --git a/solutions/59. Spiral Matrix II/59.cpp b/solutions/59. Spiral Matrix II/59.cpp new file mode 100644 index 00000000000..8d364a3db79 --- /dev/null +++ b/solutions/59. Spiral Matrix II/59.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector> generateMatrix(int n) { + vector> ans(n, vector(n)); + int count = 1; + + for (int mn = 0; mn < n / 2; ++mn) { + const int mx = n - mn - 1; + for (int i = mn; i < mx; ++i) + ans[mn][i] = count++; + for (int i = mn; i < mx; ++i) + ans[i][mx] = count++; + for (int i = mx; i > mn; --i) + ans[mx][i] = count++; + for (int i = mx; i > mn; --i) + ans[i][mn] = count++; + } + + if (n % 2 == 1) + ans[n / 2][n / 2] = count; + + return ans; + } +}; diff --git a/solutions/59. Spiral Matrix II/59.java b/solutions/59. Spiral Matrix II/59.java new file mode 100644 index 00000000000..119ff2d0168 --- /dev/null +++ b/solutions/59. Spiral Matrix II/59.java @@ -0,0 +1,23 @@ +class Solution { + public int[][] generateMatrix(int n) { + int[][] ans = new int[n][n]; + int count = 1; + + for (int mn = 0; mn < n / 2; ++mn) { + final int mx = n - mn - 1; + for (int i = mn; i < mx; ++i) + ans[mn][i] = count++; + for (int i = mn; i < mx; ++i) + ans[i][mx] = count++; + for (int i = mx; i > mn; --i) + ans[mx][i] = count++; + for (int i = mx; i > mn; --i) + ans[i][mn] = count++; + } + + if (n % 2 == 1) + ans[n / 2][n / 2] = count; + + return ans; + } +} diff --git a/solutions/59. Spiral Matrix II/59.py b/solutions/59. Spiral Matrix II/59.py new file mode 100644 index 00000000000..f65f8d993dc --- /dev/null +++ b/solutions/59. Spiral Matrix II/59.py @@ -0,0 +1,24 @@ +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + ans = [[0] * n for _ in range(n)] + count = 1 + + for mn in range(n // 2): + mx = n - mn - 1 + for i in range(mn, mx): + ans[mn][i] = count + count += 1 + for i in range(mn, mx): + ans[i][mx] = count + count += 1 + for i in range(mx, mn, -1): + ans[mx][i] = count + count += 1 + for i in range(mx, mn, -1): + ans[i][mn] = count + count += 1 + + if n % 2 == 1: + ans[n // 2][n // 2] = count + + return ans diff --git a/solutions/590. N-ary Tree Postorder Traversal/590.cpp b/solutions/590. N-ary Tree Postorder Traversal/590.cpp new file mode 100644 index 00000000000..17a952cbd77 --- /dev/null +++ b/solutions/590. N-ary Tree Postorder Traversal/590.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector postorder(Node* root) { + if (root == nullptr) + return {}; + + vector ans; + stack stack{{root}}; + + while (!stack.empty()) { + root = stack.top(), stack.pop(); + ans.push_back(root->val); + for (Node* child : root->children) + stack.push(child); + } + + reverse(ans.begin(), ans.end()); + return ans; + } +}; diff --git a/solutions/590. N-ary Tree Postorder Traversal/590.java b/solutions/590. N-ary Tree Postorder Traversal/590.java new file mode 100644 index 00000000000..a5cf20b54d5 --- /dev/null +++ b/solutions/590. N-ary Tree Postorder Traversal/590.java @@ -0,0 +1,20 @@ +class Solution { + public List postorder(Node root) { + if (root == null) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + Deque stack = new ArrayDeque<>(); + stack.push(root); + + while (!stack.isEmpty()) { + root = stack.pop(); + ans.add(root.val); + for (Node child : root.children) + stack.push(child); + } + + Collections.reverse(ans); + return ans; + } +} diff --git a/solutions/591. Tag Validator/591.cpp b/solutions/591. Tag Validator/591.cpp new file mode 100644 index 00000000000..c0e9dcd3f77 --- /dev/null +++ b/solutions/591. Tag Validator/591.cpp @@ -0,0 +1,69 @@ +class Solution { + public: + bool isValid(string code) { + if (code[0] != '<' || code.back() != '>') + return false; + + stack stack; + + for (int i = 0; i < code.length(); ++i) { + int closeIndex = 0; + if (stack.empty() && containsTag) + return false; + if (code[i] == '<') { + // It's inside a tag, so check if it's a cdata. + if (!stack.empty() && code[i + 1] == '!') { + closeIndex = code.find("]]>", i + 2); + if (closeIndex == string::npos || + !isValidCdata(code.substr(i + 2, closeIndex - i - 2))) + return false; + } else if (code[i + 1] == '/') { // the end tag + closeIndex = code.find('>', i + 2); + if (closeIndex == string::npos || + !isValidTagName(stack, code.substr(i + 2, closeIndex - i - 2), + true)) + return false; + } else { // the start tag + closeIndex = code.find('>', i + 1); + if (closeIndex == string::npos || + !isValidTagName(stack, code.substr(i + 1, closeIndex - i - 1), + false)) + return false; + } + i = closeIndex; + } + } + + return stack.empty() && containsTag; + } + + private: + bool containsTag = false; + + bool isValidCdata(const string& s) { + return s.find("[CDATA[") == 0; + } + + bool isValidTagName(stack& stack, const string& tagName, + bool isEndTag) { + if (tagName.empty() || tagName.length() > 9) + return false; + + for (const char c : tagName) + if (!isupper(c)) + return false; + + if (isEndTag) { + if (stack.empty()) + return false; + if (stack.top() != tagName) + return false; + stack.pop(); + return true; + } + + containsTag = true; + stack.push(tagName); + return true; + } +}; diff --git a/solutions/591. Tag Validator/591.java b/solutions/591. Tag Validator/591.java new file mode 100644 index 00000000000..6c80e24e07c --- /dev/null +++ b/solutions/591. Tag Validator/591.java @@ -0,0 +1,55 @@ +class Solution { + public boolean isValid(String code) { + if (code.charAt(0) != '<' || code.charAt(code.length() - 1) != '>') + return false; + + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < code.length(); ++i) { + int closeIndex = 0; + if (stack.isEmpty() && containsTag) + return false; + if (code.charAt(i) == '<') { + // It's inside a tag, so check if it's a cdata. + if (!stack.isEmpty() && code.charAt(i + 1) == '!') { + closeIndex = code.indexOf("]]>", i + 2); + if (closeIndex < 0 || !isValidCdata(code.substring(i + 2, closeIndex))) + return false; + } else if (code.charAt(i + 1) == '/') { // the end tag + closeIndex = code.indexOf('>', i + 2); + if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 2, closeIndex), true)) + return false; + } else { // the start tag + closeIndex = code.indexOf('>', i + 1); + if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 1, closeIndex), false)) + return false; + } + i = closeIndex; + } + } + + return stack.isEmpty() && containsTag; + } + + private boolean containsTag = false; + + private boolean isValidCdata(final String s) { + return s.indexOf("[CDATA[") == 0; + } + + private boolean isValidTagName(Deque stack, String tagName, boolean isEndTag) { + if (tagName.isEmpty() || tagName.length() > 9) + return false; + + for (final char c : tagName.toCharArray()) + if (!Character.isUpperCase(c)) + return false; + + if (isEndTag) + return !stack.isEmpty() && stack.pop().equals(tagName); + + containsTag = true; + stack.push(tagName); + return true; + } +} diff --git a/solutions/591. Tag Validator/591.py b/solutions/591. Tag Validator/591.py new file mode 100644 index 00000000000..ba239751b62 --- /dev/null +++ b/solutions/591. Tag Validator/591.py @@ -0,0 +1,47 @@ +class Solution: + def isValid(self, code: str) -> bool: + if code[0] != '<' or code[-1] != '>': + return False + + containsTag = False + stack = [] + + def isValidCdata(s: str) -> bool: + return s.find('[CDATA[') == 0 + + def isValidTagName(tagName: str, isEndTag: bool) -> bool: + nonlocal containsTag + if not tagName or len(tagName) > 9: + return False + if any(not c.isupper() for c in tagName): + return False + + if isEndTag: + return stack and stack.pop() == tagName + + containsTag = True + stack.append(tagName) + return True + + i = 0 + while i < len(code): + if not stack and containsTag: + return False + if code[i] == '<': + # It's inside a tag, so check if it's a cdata. + if stack and code[i + 1] == '!': + closeIndex = code.find(']]>', i + 2) + if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]): + return False + elif code[i + 1] == '/': # the end tag + closeIndex = code.find('>', i + 2) + if closeIndex == -1 or not isValidTagName(code[i + 2:closeIndex], True): + return False + else: # the start tag + closeIndex = code.find('>', i + 1) + if closeIndex == -1 or not isValidTagName(code[i + 1:closeIndex], False): + return False + i = closeIndex + i += 1 + + return not stack and containsTag diff --git a/solutions/592. Fraction Addition and Subtraction/592.cpp b/solutions/592. Fraction Addition and Subtraction/592.cpp new file mode 100644 index 00000000000..4d844de6f34 --- /dev/null +++ b/solutions/592. Fraction Addition and Subtraction/592.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string fractionAddition(string expression) { + istringstream iss(expression); + char _; + int a; + int b; + int A = 0; + int B = 1; + + // Init: A / B = 0 / 1 + // A / B + a / b = (Ab + aB) / Bb + // So, in each round, set A = Ab + aB, B = Bb. + while (iss >> a >> _ >> b) { + A = A * b + a * B; + B *= b; + const int g = abs(__gcd(A, B)); + A /= g; + B /= g; + } + + return to_string(A) + "/" + to_string(B); + } +}; diff --git a/solutions/592. Fraction Addition and Subtraction/592.java b/solutions/592. Fraction Addition and Subtraction/592.java new file mode 100644 index 00000000000..93a75e9c1a6 --- /dev/null +++ b/solutions/592. Fraction Addition and Subtraction/592.java @@ -0,0 +1,26 @@ +class Solution { + public String fractionAddition(String expression) { + Scanner sc = new Scanner(expression).useDelimiter("/|(?=[+-])"); + int A = 0; + int B = 1; + + // Init: A / B = 0 / 1 + // A / B + a / b = (Ab + aB) / Bb + // So, in each round, set A = Ab + aB, B = Bb. + while (sc.hasNext()) { + final int a = sc.nextInt(); + final int b = sc.nextInt(); + A = A * b + a * B; + B *= b; + final int g = gcd(A, B); + A /= g; + B /= g; + } + + return A + "/" + B; + } + + private int gcd(int a, int b) { + return a == 0 ? Math.abs(b) : gcd(b % a, a); + } +} diff --git a/solutions/592. Fraction Addition and Subtraction/592.py b/solutions/592. Fraction Addition and Subtraction/592.py new file mode 100644 index 00000000000..e8f5de27f2b --- /dev/null +++ b/solutions/592. Fraction Addition and Subtraction/592.py @@ -0,0 +1,14 @@ +class Solution: + def fractionAddition(self, expression: str) -> str: + ints = list(map(int, re.findall('[+-]?[0-9]+', expression))) + A = 0 + B = 1 + + for a, b in zip(ints[::2], ints[1::2]): + A = A * b + a * B + B *= b + g = math.gcd(A, B) + A //= g + B //= g + + return str(A) + '/' + str(B) diff --git a/solutions/593. Valid Square/593.cpp b/solutions/593. Valid Square/593.cpp new file mode 100644 index 00000000000..acd70e3ae85 --- /dev/null +++ b/solutions/593. Valid Square/593.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool validSquare(vector& p1, vector& p2, // + vector& p3, vector& p4) { + unordered_set distSet; + vector> points{p1, p2, p3, p4}; + + for (int i = 0; i < 4; ++i) + for (int j = i + 1; j < 4; ++j) + distSet.insert(dist(points[i], points[j])); + + return !distSet.contains(0) && distSet.size() == 2; + } + + private: + int dist(vector& p1, vector& p2) { + return (p1[0] - p2[0]) * (p1[0] - p2[0]) + + (p1[1] - p2[1]) * (p1[1] - p2[1]); + } +}; diff --git a/solutions/593. Valid Square/593.java b/solutions/593. Valid Square/593.java new file mode 100644 index 00000000000..c50a2392c26 --- /dev/null +++ b/solutions/593. Valid Square/593.java @@ -0,0 +1,16 @@ +class Solution { + public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { + Set distSet = new HashSet<>(); + int[][] points = {p1, p2, p3, p4}; + + for (int i = 0; i < 4; ++i) + for (int j = i + 1; j < 4; ++j) + distSet.add(dist(points[i], points[j])); + + return !distSet.contains(0) && distSet.size() == 2; + } + + private int dist(int[] p1, int[] p2) { + return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + } +} diff --git a/solutions/593. Valid Square/593.py b/solutions/593. Valid Square/593.py new file mode 100644 index 00000000000..4a3f07c7315 --- /dev/null +++ b/solutions/593. Valid Square/593.py @@ -0,0 +1,9 @@ +class Solution: + def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool: + def dist(p1: List[int], p2: List[int]) -> int: + return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + + distSet = set([dist(*pair) + for pair in list(itertools.combinations([p1, p2, p3, p4], 2))]) + + return 0 not in distSet and len(distSet) == 2 diff --git a/solutions/594. Longest Harmonious Subsequence/594.cpp b/solutions/594. Longest Harmonious Subsequence/594.cpp new file mode 100644 index 00000000000..9f27a96afa3 --- /dev/null +++ b/solutions/594. Longest Harmonious Subsequence/594.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int findLHS(vector& nums) { + int ans = 0; + unordered_map count; + + for (const int num : nums) + ++count[num]; + + for (const auto& [num, freq] : count) + if (const auto it = count.find(num + 1); it != count.cend()) + ans = max(ans, freq + it->second); + + return ans; + } +}; diff --git a/solutions/594. Longest Harmonious Subsequence/594.java b/solutions/594. Longest Harmonious Subsequence/594.java new file mode 100644 index 00000000000..a02deb84e7b --- /dev/null +++ b/solutions/594. Longest Harmonious Subsequence/594.java @@ -0,0 +1,15 @@ +class Solution { + public int findLHS(int[] nums) { + int ans = 0; + Map count = new HashMap<>(); + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (final int num : count.keySet()) + if (count.containsKey(num + 1)) + ans = Math.max(ans, count.get(num) + count.get(num + 1)); + + return ans; + } +} diff --git a/solutions/594. Longest Harmonious Subsequence/594.py b/solutions/594. Longest Harmonious Subsequence/594.py new file mode 100644 index 00000000000..f81a608e6a6 --- /dev/null +++ b/solutions/594. Longest Harmonious Subsequence/594.py @@ -0,0 +1,10 @@ +class Solution: + def findLHS(self, nums: List[int]) -> int: + ans = 0 + count = collections.Counter(nums) + + for num, freq in count.items(): + if num + 1 in count: + ans = max(ans, freq + count[num + 1]) + + return ans diff --git a/solutions/595. Big Countries/595.sql b/solutions/595. Big Countries/595.sql new file mode 100644 index 00000000000..dba4cb07e6a --- /dev/null +++ b/solutions/595. Big Countries/595.sql @@ -0,0 +1,3 @@ +SELECT name, population, area +FROM World +WHERE area >= 3000000 OR population >= 25000000; diff --git a/solutions/596. Classes More Than 5 Students/596.sql b/solutions/596. Classes More Than 5 Students/596.sql new file mode 100644 index 00000000000..ed38e23f8e0 --- /dev/null +++ b/solutions/596. Classes More Than 5 Students/596.sql @@ -0,0 +1,4 @@ +SELECT class +FROM Courses +GROUP BY 1 +HAVING COUNT(*) >= 5; diff --git a/solutions/597. Friend Requests I: Overall Acceptance Rate/597.sql b/solutions/597. Friend Requests I: Overall Acceptance Rate/597.sql new file mode 100644 index 00000000000..a0c14492ac4 --- /dev/null +++ b/solutions/597. Friend Requests I: Overall Acceptance Rate/597.sql @@ -0,0 +1,15 @@ +WITH + Request AS ( + SELECT COUNT(DISTINCT sender_id, send_to_id) AS `count` + FROM FriendRequest + ), + Accepted AS ( + SELECT IFNULL(COUNT(DISTINCT requester_id, accepter_id), 0) AS `count` + FROM RequestAccepted + ) +SELECT IF( + `Request`.count = 0, + 0, + ROUND(Accepted.`count` / Request.`count`, 2) + ) AS accept_rate +FROM Request, Accepted; diff --git a/solutions/598. Range Addition II/598.cpp b/solutions/598. Range Addition II/598.cpp new file mode 100644 index 00000000000..d373242d0d6 --- /dev/null +++ b/solutions/598. Range Addition II/598.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxCount(int m, int n, vector>& ops) { + int minY = m; + int minX = n; + + for (const vector& op : ops) { + minY = min(minY, op[0]); + minX = min(minX, op[1]); + } + + return minX * minY; + } +}; diff --git a/solutions/598. Range Addition II/598.java b/solutions/598. Range Addition II/598.java new file mode 100644 index 00000000000..05481024faf --- /dev/null +++ b/solutions/598. Range Addition II/598.java @@ -0,0 +1,13 @@ +class Solution { + public int maxCount(int m, int n, int[][] ops) { + int minY = m; + int minX = n; + + for (int[] op : ops) { + minY = Math.min(minY, op[0]); + minX = Math.min(minX, op[1]); + } + + return minX * minY; + } +} diff --git a/solutions/598. Range Addition II/598.py b/solutions/598. Range Addition II/598.py new file mode 100644 index 00000000000..01d257d55bd --- /dev/null +++ b/solutions/598. Range Addition II/598.py @@ -0,0 +1,10 @@ +class Solution: + def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int: + minY = m + minX = n + + for y, x in ops: + minY = min(minY, y) + minX = min(minX, x) + + return minX * minY diff --git a/solutions/599. Minimum Index Sum of Two Lists/599.cpp b/solutions/599. Minimum Index Sum of Two Lists/599.cpp new file mode 100644 index 00000000000..73caefde47e --- /dev/null +++ b/solutions/599. Minimum Index Sum of Two Lists/599.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector findRestaurant(vector& list1, vector& list2) { + vector ans; + unordered_map restaurantToIndex; + int minSum = INT_MAX; + + for (int i = 0; i < list1.size(); ++i) + restaurantToIndex[list1[i]] = i; + + for (int i = 0; i < list2.size(); ++i) { + const string& restaurant = list2[i]; + if (const auto it = restaurantToIndex.find(restaurant); + it != restaurantToIndex.cend()) { + const int sum = it->second + i; + if (sum < minSum) { + minSum = sum; + ans = {restaurant}; + } else if (sum == minSum) { + ans.push_back(restaurant); + } + } + } + + return ans; + } +}; diff --git a/solutions/599. Minimum Index Sum of Two Lists/599.java b/solutions/599. Minimum Index Sum of Two Lists/599.java new file mode 100644 index 00000000000..f796d9ae10b --- /dev/null +++ b/solutions/599. Minimum Index Sum of Two Lists/599.java @@ -0,0 +1,26 @@ +class Solution { + public String[] findRestaurant(String[] list1, String[] list2) { + List ans = new LinkedList<>(); + Map restaurantToIndex = new HashMap<>(); + int minSum = Integer.MAX_VALUE; + + for (int i = 0; i < list1.length; ++i) + restaurantToIndex.put(list1[i], i); + + for (int i = 0; i < list2.length; ++i) { + final String restaurant = list2[i]; + if (restaurantToIndex.containsKey(restaurant)) { + final int sum = restaurantToIndex.get(restaurant) + i; + if (sum < minSum) { + minSum = sum; + ans.clear(); + ans.add(restaurant); + } else if (sum == minSum) { + ans.add(restaurant); + } + } + } + + return ans.toArray(new String[0]); + } +} diff --git a/solutions/599. Minimum Index Sum of Two Lists/599.py b/solutions/599. Minimum Index Sum of Two Lists/599.py new file mode 100644 index 00000000000..d2758dcc870 --- /dev/null +++ b/solutions/599. Minimum Index Sum of Two Lists/599.py @@ -0,0 +1,17 @@ +class Solution: + def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: + ans = [] + restaurantToIndex = {restaurant: i for i, + restaurant in enumerate(list1)} + minSum = math.inf + + for i, restaurant in enumerate(list2): + if restaurant in restaurantToIndex: + summ = restaurantToIndex[restaurant] + i + if summ < minSum: + ans.clear() + if summ <= minSum: + ans.append(restaurant) + minSum = summ + + return ans diff --git a/solutions/6. ZigZag Conversion/6.cpp b/solutions/6. ZigZag Conversion/6.cpp new file mode 100644 index 00000000000..c60c4e0e45e --- /dev/null +++ b/solutions/6. ZigZag Conversion/6.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + string convert(string s, int numRows) { + string ans; + vector> rows(numRows); + int k = 0; + int direction = (numRows == 1) - 1; + + for (const char c : s) { + rows[k].push_back(c); + if (k == 0 || k == numRows - 1) + direction *= -1; + k += direction; + } + + for (const vector& row : rows) + for (const char c : row) + ans += c; + + return ans; + } +}; diff --git a/solutions/6. ZigZag Conversion/6.java b/solutions/6. ZigZag Conversion/6.java new file mode 100644 index 00000000000..775d78c056a --- /dev/null +++ b/solutions/6. ZigZag Conversion/6.java @@ -0,0 +1,24 @@ +class Solution { + public String convert(String s, int numRows) { + StringBuilder sb = new StringBuilder(); + List[] rows = new List[numRows]; + int k = 0; + int direction = numRows == 1 ? 0 : -1; + + for (int i = 0; i < numRows; ++i) + rows[i] = new ArrayList<>(); + + for (final char c : s.toCharArray()) { + rows[k].add(c); + if (k == 0 || k == numRows - 1) + direction *= -1; + k += direction; + } + + for (List row : rows) + for (final char c : row) + sb.append(c); + + return sb.toString(); + } +} diff --git a/solutions/6. ZigZag Conversion/6.py b/solutions/6. ZigZag Conversion/6.py new file mode 100644 index 00000000000..5fc2b5f3f0c --- /dev/null +++ b/solutions/6. ZigZag Conversion/6.py @@ -0,0 +1,13 @@ +class Solution: + def convert(self, s: str, numRows: int) -> str: + rows = [''] * numRows + k = 0 + direction = (numRows == 1) - 1 + + for c in s: + rows[k] += c + if k == 0 or k == numRows - 1: + direction *= -1 + k += direction + + return ''.join(rows) diff --git a/solutions/60. Permutation Sequence/60.cpp b/solutions/60. Permutation Sequence/60.cpp new file mode 100644 index 00000000000..3bd995cf2cb --- /dev/null +++ b/solutions/60. Permutation Sequence/60.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string getPermutation(int n, int k) { + string ans; + vector nums(n); + vector fact(n + 1, 1); // fact[i] := i! + + iota(nums.begin(), nums.end(), 1); + + for (int i = 2; i <= n; ++i) + fact[i] = fact[i - 1] * i; + + --k; // 0-indexed + + for (int i = n - 1; i >= 0; --i) { + const int j = k / fact[i]; + k %= fact[i]; + ans += to_string(nums[j]); + nums.erase(nums.begin() + j); + } + + return ans; + } +}; diff --git a/solutions/60. Permutation Sequence/60.java b/solutions/60. Permutation Sequence/60.java new file mode 100644 index 00000000000..62eae980a5b --- /dev/null +++ b/solutions/60. Permutation Sequence/60.java @@ -0,0 +1,25 @@ +class Solution { + public String getPermutation(int n, int k) { + StringBuilder sb = new StringBuilder(); + List nums = new ArrayList<>(); + int[] fact = new int[n + 1]; // fact[i] := i! + + for (int i = 1; i <= n; ++i) + nums.add(i); + + Arrays.fill(fact, 1); + for (int i = 2; i <= n; ++i) + fact[i] = fact[i - 1] * i; + + --k; // 0-indexed + + for (int i = n - 1; i >= 0; --i) { + final int j = k / fact[i]; + k %= fact[i]; + sb.append(nums.get(j)); + nums.remove(j); + } + + return sb.toString(); + } +} diff --git a/solutions/60. Permutation Sequence/60.py b/solutions/60. Permutation Sequence/60.py new file mode 100644 index 00000000000..0d9b514ba05 --- /dev/null +++ b/solutions/60. Permutation Sequence/60.py @@ -0,0 +1,18 @@ +class Solution: + def getPermutation(self, n: int, k: int) -> str: + ans = '' + nums = [i + 1 for i in range(n)] + fact = [1] * (n + 1) # fact[i] := i! + + for i in range(2, n + 1): + fact[i] = fact[i - 1] * i + + k -= 1 # 0-indexed + + for i in reversed(range(n)): + j = k // fact[i] + k %= fact[i] + ans += str(nums[j]) + nums.pop(j) + + return ans diff --git a/solutions/600. Non-negative Integers without Consecutive Ones/600.cpp b/solutions/600. Non-negative Integers without Consecutive Ones/600.cpp new file mode 100644 index 00000000000..88c961affcc --- /dev/null +++ b/solutions/600. Non-negative Integers without Consecutive Ones/600.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int findIntegers(int num) { + string bits; + for (; num; num >>= 1) + bits += to_string(num & 1); + + const int n = bits.length(); + vector zero(n, 1); + vector one(n, 1); + + for (int i = 1; i < n; ++i) { + zero[i] = zero[i - 1] + one[i - 1]; + one[i] = zero[i - 1]; + } + + int ans = zero[n - 1] + one[n - 1]; + + for (int i = n - 2; i >= 0; --i) { + // The numbers > num and <= 2^n - 1 are invalid. + if (bits[i] == '1' && bits[i + 1] == '1') + break; + if (bits[i] == '0' && bits[i + 1] == '0') + ans -= one[i]; + } + + return ans; + } +}; diff --git a/solutions/600. Non-negative Integers without Consecutive Ones/600.java b/solutions/600. Non-negative Integers without Consecutive Ones/600.java new file mode 100644 index 00000000000..2651c35de9b --- /dev/null +++ b/solutions/600. Non-negative Integers without Consecutive Ones/600.java @@ -0,0 +1,31 @@ +class Solution { + public int findIntegers(int num) { + StringBuilder bits = new StringBuilder(); + for (; num > 0; num >>= 1) + bits.append(num & 1); + + final int n = bits.length(); + int[] zero = new int[n]; + int[] one = new int[n]; + + zero[0] = 1; + one[0] = 1; + + for (int i = 1; i < n; ++i) { + zero[i] = zero[i - 1] + one[i - 1]; + one[i] = zero[i - 1]; + } + + int ans = zero[n - 1] + one[n - 1]; + + for (int i = n - 2; i >= 0; --i) { + // The numbers > num and <= 2^n - 1 are invalid. + if (bits.charAt(i) == '1' && bits.charAt(i + 1) == '1') + break; + if (bits.charAt(i) == '0' && bits.charAt(i + 1) == '0') + ans -= one[i]; + } + + return ans; + } +} diff --git a/solutions/601. Human Traffic of Stadium/601-2.sql b/solutions/601. Human Traffic of Stadium/601-2.sql new file mode 100644 index 00000000000..f4852a5cd51 --- /dev/null +++ b/solutions/601. Human Traffic of Stadium/601-2.sql @@ -0,0 +1,19 @@ +WITH + StadiumWithGroupId AS ( + SELECT + id, + visit_date, + people, + id - ROW_NUMBER() OVER(ORDER BY id) AS group_id + FROM Stadium + WHERE people >= 100 + ) +SELECT id, visit_date, people +FROM StadiumWithGroupId +WHERE group_id IN ( + SELECT group_id + FROM StadiumWithGroupId + GROUP BY group_id + HAVING COUNT(*) >= 3 + ) +ORDER BY visit_date; diff --git a/solutions/601. Human Traffic of Stadium/601.sql b/solutions/601. Human Traffic of Stadium/601.sql new file mode 100644 index 00000000000..e5e03081ca5 --- /dev/null +++ b/solutions/601. Human Traffic of Stadium/601.sql @@ -0,0 +1,24 @@ +WITH + StadiumNeighbors AS ( + SELECT + id, + visit_date, + people, + LAG(people, 1) OVER(ORDER BY id) AS prev_people_1, + LAG(people, 2) OVER(ORDER BY id) AS prev_people_2, + LEAD(people, 1) OVER(ORDER BY id) AS next_people_1, + LEAD(people, 2) OVER(ORDER BY id) AS next_people_2 + FROM Stadium + ) +SELECT + id, + visit_date, + people +FROM StadiumNeighbors +WHERE + people >= 100 AND ( + prev_people_1 >= 100 AND prev_people_2 >= 100 + OR prev_people_1 >= 100 AND next_people_1 >= 100 + OR next_people_1 >= 100 AND next_people_2 >= 100 + ) +ORDER BY visit_date; diff --git a/solutions/602. Friend Requests II: Who Has the Most Friends/602.sql b/solutions/602. Friend Requests II: Who Has the Most Friends/602.sql new file mode 100644 index 00000000000..f36a3c39e14 --- /dev/null +++ b/solutions/602. Friend Requests II: Who Has the Most Friends/602.sql @@ -0,0 +1,13 @@ +WITH + AllIds AS ( + SELECT requester_id AS id FROM RequestAccepted + UNION ALL + SELECT accepter_id FROM RequestAccepted + ) +SELECT + id, + COUNT(*) AS num +FROM AllIds +GROUP BY 1 +ORDER BY 2 DESC +LIMIT 1; diff --git a/solutions/603. Consecutive Available Seats/603.sql b/solutions/603. Consecutive Available Seats/603.sql new file mode 100644 index 00000000000..7c2f5adfbe9 --- /dev/null +++ b/solutions/603. Consecutive Available Seats/603.sql @@ -0,0 +1,12 @@ +WITH CinemaNeighbors AS ( + SELECT + *, + LAG(free) OVER(ORDER BY seat_id) AS prev_free, + LEAD(free) OVER(ORDER BY seat_id) AS next_free + FROM Cinema +) +SELECT seat_id +FROM CinemaNeighbors +WHERE free = 1 + AND (prev_free = 1 OR next_free = 1) +ORDER BY 1; diff --git a/solutions/604. Design Compressed String Iterator/604-2.cpp b/solutions/604. Design Compressed String Iterator/604-2.cpp new file mode 100644 index 00000000000..1f9083628b0 --- /dev/null +++ b/solutions/604. Design Compressed String Iterator/604-2.cpp @@ -0,0 +1,30 @@ +class StringIterator { + public: + StringIterator(string compressedString) { + int i = 0; // compressedString's index + while (i < compressedString.length()) { + const char c = compressedString[i++]; + int num = 0; + while (i < compressedString.length() && isdigit(compressedString[i])) + num = num * 10 + (compressedString[i++] - '0'); + q.emplace(c, num); + } + } + + char next() { + if (!hasNext()) + return ' '; + + const char c = q.front().first; + if (--q.front().second == 0) + q.pop(); + return c; + } + + bool hasNext() { + return !q.empty(); + } + + private: + queue> q; // (currentChar, num) +}; diff --git a/solutions/604. Design Compressed String Iterator/604-2.java b/solutions/604. Design Compressed String Iterator/604-2.java new file mode 100644 index 00000000000..884d465bd08 --- /dev/null +++ b/solutions/604. Design Compressed String Iterator/604-2.java @@ -0,0 +1,30 @@ +class StringIterator { + public StringIterator(String compressedString) { + int i = 0; // compressedString's index + while (i < compressedString.length()) { + final char c = compressedString.charAt(i++); + int num = 0; + while (i < compressedString.length() && Character.isDigit(compressedString.charAt(i))) + num = num * 10 + (compressedString.charAt(i++) - '0'); + q.offer(new Pair<>(c, num)); + } + } + + public char next() { + if (!hasNext()) + return ' '; + + final char c = q.peek().getKey(); + final int num = q.poll().getValue(); + if (num > 1) + q.addFirst(new Pair<>(c, num - 1)); + return c; + } + + public boolean hasNext() { + return !q.isEmpty(); + } + + // (currentChar, num) + private LinkedList> q = new LinkedList<>(); +} diff --git a/solutions/604. Design Compressed String Iterator/604-2.py b/solutions/604. Design Compressed String Iterator/604-2.py new file mode 100644 index 00000000000..39e3a35fd1c --- /dev/null +++ b/solutions/604. Design Compressed String Iterator/604-2.py @@ -0,0 +1,25 @@ +class StringIterator: + def __init__(self, compressedString: str): + self.q = collections.deque() # (currentChar, num) + + i = 0 # compressedString's index + while i < len(compressedString): + c = compressedString[i] + i += 1 + num = 0 + while i < len(compressedString) and compressedString[i].isdigit(): + num = num * 10 + (ord(compressedString[i]) - ord('0')) + i += 1 + self.q.append((c, num)) + + def next(self) -> str: + if not self.hasNext(): + return ' ' + + c, num = self.q.popleft() + if num > 1: + self.q.appendleft((c, num - 1)) + return c + + def hasNext(self) -> bool: + return self.q diff --git a/solutions/604. Design Compressed String Iterator/604.cpp b/solutions/604. Design Compressed String Iterator/604.cpp new file mode 100644 index 00000000000..c252f0678c6 --- /dev/null +++ b/solutions/604. Design Compressed String Iterator/604.cpp @@ -0,0 +1,28 @@ +class StringIterator { + public: + StringIterator(string compressedString) : s(compressedString) {} + + char next() { + if (!hasNext()) + return ' '; + + if (num == 0) { + currentChar = s[i++]; + while (i < s.length() && isdigit(s[i])) + num = num * 10 + (s[i++] - '0'); + } + + --num; + return currentChar; + } + + bool hasNext() { + return i < s.length() || num > 0; + } + + private: + const string s; + int i = 0; // s' index + int num = 0; // currentChar's count + char currentChar = ' '; +}; diff --git a/solutions/604. Design Compressed String Iterator/604.java b/solutions/604. Design Compressed String Iterator/604.java new file mode 100644 index 00000000000..7e162b9c562 --- /dev/null +++ b/solutions/604. Design Compressed String Iterator/604.java @@ -0,0 +1,28 @@ +class StringIterator { + public StringIterator(String compressedString) { + s = compressedString; + } + + public char next() { + if (!hasNext()) + return ' '; + + if (num == 0) { + currentChar = s.charAt(i++); + while (i < s.length() && Character.isDigit(s.charAt(i))) + num = num * 10 + (s.charAt(i++) - '0'); + } + + --num; + return currentChar; + } + + public boolean hasNext() { + return i < s.length() || num > 0; + } + + private final String s; + private int i = 0; // s' index + private int num = 0; // currentChar's count + private char currentChar = ' '; +} diff --git a/solutions/604. Design Compressed String Iterator/604.py b/solutions/604. Design Compressed String Iterator/604.py new file mode 100644 index 00000000000..340eb44aee5 --- /dev/null +++ b/solutions/604. Design Compressed String Iterator/604.py @@ -0,0 +1,23 @@ +class StringIterator: + def __init__(self, compressedString: str): + self.s = compressedString + self.i = 0 # s' index + self.num = 0 # currentChar's count + self.currentChar = ' ' + + def next(self) -> str: + if not self.hasNext(): + return ' ' + + if self.num == 0: + self.currentChar = self.s[self.i] + self.i += 1 + while self.i < len(self.s) and self.s[self.i].isdigit(): + self.num = self.num * 10 + (ord(self.s[self.i]) - ord('0')) + self.i += 1 + + self.num -= 1 + return self.currentChar + + def hasNext(self) -> bool: + return self.i < len(self.s) or self.num > 0 diff --git a/solutions/605. Can Place Flowers/605.cpp b/solutions/605. Can Place Flowers/605.cpp new file mode 100644 index 00000000000..88d8a5b4f7a --- /dev/null +++ b/solutions/605. Can Place Flowers/605.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool canPlaceFlowers(vector& flowerbed, int n) { + if (n == 0) + return true; + + for (int i = 0; i < flowerbed.size(); ++i) + if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && + (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) { + flowerbed[i] = 1; + if (--n == 0) + return true; + } + + return false; + } +}; diff --git a/solutions/605. Can Place Flowers/605.java b/solutions/605. Can Place Flowers/605.java new file mode 100644 index 00000000000..9de285a7288 --- /dev/null +++ b/solutions/605. Can Place Flowers/605.java @@ -0,0 +1,16 @@ +class Solution { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + if (n == 0) + return true; + + for (int i = 0; i < flowerbed.length; ++i) + if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && + (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) { + flowerbed[i] = 1; + if (--n == 0) + return true; + } + + return false; + } +} diff --git a/solutions/605. Can Place Flowers/605.py b/solutions/605. Can Place Flowers/605.py new file mode 100644 index 00000000000..23c2f3b1375 --- /dev/null +++ b/solutions/605. Can Place Flowers/605.py @@ -0,0 +1,10 @@ +class Solution: + def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: + for i, flower in enumerate(flowerbed): + if flower == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0): + flowerbed[i] = 1 + n -= 1 + if n <= 0: + return True + + return False diff --git a/solutions/606. Construct String from Binary Tree/606.cpp b/solutions/606. Construct String from Binary Tree/606.cpp new file mode 100644 index 00000000000..e40016b317b --- /dev/null +++ b/solutions/606. Construct String from Binary Tree/606.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + string tree2str(TreeNode* t) { + return dfs(t); + } + + private: + string dfs(TreeNode* root) { + if (root == nullptr) + return ""; + + const string& rootStr = to_string(root->val); + if (root->right) + return rootStr + "(" + dfs(root->left) + ")(" + dfs(root->right) + ")"; + if (root->left) + return rootStr + "(" + dfs(root->left) + ")"; + return rootStr + ""; + } +}; diff --git a/solutions/606. Construct String from Binary Tree/606.java b/solutions/606. Construct String from Binary Tree/606.java new file mode 100644 index 00000000000..a7f3f2ac509 --- /dev/null +++ b/solutions/606. Construct String from Binary Tree/606.java @@ -0,0 +1,15 @@ +class Solution { + public String tree2str(TreeNode t) { + return dfs(t); + } + + private String dfs(TreeNode root) { + if (root == null) + return ""; + if (root.right != null) + return root.val + "(" + dfs(root.left) + ")(" + dfs(root.right) + ")"; + if (root.left != null) + return root.val + "(" + dfs(root.left) + ")"; + return root.val + ""; + } +} diff --git a/solutions/606. Construct String from Binary Tree/606.py b/solutions/606. Construct String from Binary Tree/606.py new file mode 100644 index 00000000000..ee9b0401003 --- /dev/null +++ b/solutions/606. Construct String from Binary Tree/606.py @@ -0,0 +1,11 @@ +class Solution: + def tree2str(self, t: Optional[TreeNode]) -> str: + def dfs(root: Optional[TreeNode]) -> str: + if not root: + return '' + if root.right: + return str(root.val) + '(' + dfs(root.left) + ')(' + dfs(root.right) + ')' + if root.left: + return str(root.val) + '(' + dfs(root.left) + ')' + return str(root.val) + return dfs(t) diff --git a/solutions/607. Sales Person/607.sql b/solutions/607. Sales Person/607.sql new file mode 100644 index 00000000000..95f03f70051 --- /dev/null +++ b/solutions/607. Sales Person/607.sql @@ -0,0 +1,7 @@ +SELECT SalesPerson.name +FROM Orders +INNER JOIN Company + ON (Orders.com_id = Company.com_id AND Company.name = 'RED') +RIGHT JOIN SalesPerson + USING (sales_id) +WHERE Orders.sales_id IS NULL; diff --git a/solutions/608. Tree Node/608.sql b/solutions/608. Tree Node/608.sql new file mode 100644 index 00000000000..cd7a21fa236 --- /dev/null +++ b/solutions/608. Tree Node/608.sql @@ -0,0 +1,11 @@ +SELECT DISTINCT Parent.id, + ( + CASE + WHEN Parent.p_id IS NULL THEN 'Root' + WHEN Parent.p_id IS NOT NULL AND Child.p_id IS NOT NULL THEN 'Inner' + WHEN Parent.p_id IS NOT NULL AND Child.p_id IS NULL THEN 'Leaf' + END + ) AS type +FROM Tree AS Parent +LEFT JOIN Tree AS Child + ON (Parent.id = Child.p_id); diff --git a/solutions/609. Find Duplicate File in System/609.cpp b/solutions/609. Find Duplicate File in System/609.cpp new file mode 100644 index 00000000000..c14823edbdd --- /dev/null +++ b/solutions/609. Find Duplicate File in System/609.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector> findDuplicate(vector& paths) { + vector> ans; + unordered_map> contentToFilePaths; + + for (const string& path : paths) { + istringstream iss(path); + string rootPath; + iss >> rootPath; // "root/d1/d2/.../dm" + + string fileAndContent; + while (iss >> fileAndContent) { // "fn.txt(fn_content)" + const int l = fileAndContent.find('('); + const int r = fileAndContent.find(')'); + // "fn.txt" + const string file = fileAndContent.substr(0, l); + // "fn_content" + const string content = fileAndContent.substr(l + 1, r - l - 1); + // "root/d1/d2/.../dm/fn.txt" + const string filePath = rootPath + '/' + file; + contentToFilePaths[content].push_back(filePath); + } + } + + for (const auto& [_, filePaths] : contentToFilePaths) + if (filePaths.size() > 1) + ans.push_back(filePaths); + + return ans; + } +}; diff --git a/solutions/609. Find Duplicate File in System/609.java b/solutions/609. Find Duplicate File in System/609.java new file mode 100644 index 00000000000..5f44d36b4c7 --- /dev/null +++ b/solutions/609. Find Duplicate File in System/609.java @@ -0,0 +1,30 @@ +class Solution { + public List> findDuplicate(String[] paths) { + List> ans = new ArrayList<>(); + Map> contentToFilePaths = new HashMap<>(); + + for (final String path : paths) { + final String[] words = path.split(" "); + final String rootPath = words[0]; // "root/d1/d2/.../dm" + for (int i = 1; i < words.length; ++i) { + final String fileAndContent = words[i]; // "fn.txt(fn_content)" + final int l = fileAndContent.indexOf('('); + final int r = fileAndContent.indexOf(')'); + // "fn.txt" + final String file = fileAndContent.substring(0, l); + // "fn_content" + final String content = fileAndContent.substring(l + 1, r); + // "root/d1/d2/.../dm/fn.txt" + final String filePath = rootPath + '/' + file; + contentToFilePaths.putIfAbsent(content, new ArrayList<>()); + contentToFilePaths.get(content).add(filePath); + } + } + + for (List filePaths : contentToFilePaths.values()) + if (filePaths.size() > 1) + ans.add(filePaths); + + return ans; + } +} diff --git a/solutions/609. Find Duplicate File in System/609.py b/solutions/609. Find Duplicate File in System/609.py new file mode 100644 index 00000000000..d55cae01c05 --- /dev/null +++ b/solutions/609. Find Duplicate File in System/609.py @@ -0,0 +1,19 @@ +class Solution: + def findDuplicate(self, paths: List[str]) -> List[List[str]]: + contentToPathFiles = collections.defaultdict(list) + + for path in paths: + words = path.split(' ') + rootPath = words[0] # "root/d1/d2/.../dm" + for fileAndContent in words[1:]: # "fn.txt(fn_content)" + l = fileAndContent.find('(') + r = fileAndContent.find(')') + # "fn.txt" + file = fileAndContent[:l] + # "fn_content" + content = fileAndContent[l + 1:r] + # "root/d1/d2/.../dm/fn.txt" + filePath = rootPath + '/' + file + contentToPathFiles[content].append(filePath) + + return [filePath for filePath in contentToPathFiles.values() if len(filePath) > 1] diff --git a/solutions/61. Rotate List/61.cpp b/solutions/61. Rotate List/61.cpp new file mode 100644 index 00000000000..c6196ce2e94 --- /dev/null +++ b/solutions/61. Rotate List/61.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + ListNode* rotateRight(ListNode* head, int k) { + if (!head || !head->next || k == 0) + return head; + + ListNode* tail; + int length = 1; + for (tail = head; tail->next; tail = tail->next) + ++length; + tail->next = head; // Circle the list. + + const int t = length - k % length; + for (int i = 0; i < t; ++i) + tail = tail->next; + ListNode* newHead = tail->next; + tail->next = nullptr; + + return newHead; + } +}; diff --git a/solutions/61. Rotate List/61.java b/solutions/61. Rotate List/61.java new file mode 100644 index 00000000000..9adccf10944 --- /dev/null +++ b/solutions/61. Rotate List/61.java @@ -0,0 +1,20 @@ +class Solution { + public ListNode rotateRight(ListNode head, int k) { + if (head == null || head.next == null || k == 0) + return head; + + int length = 1; + ListNode tail = head; + for (; tail.next != null; tail = tail.next) + ++length; + tail.next = head; // Circle the list. + + final int t = length - k % length; + for (int i = 0; i < t; ++i) + tail = tail.next; + ListNode newHead = tail.next; + tail.next = null; + + return newHead; + } +} diff --git a/solutions/61. Rotate List/61.py b/solutions/61. Rotate List/61.py new file mode 100644 index 00000000000..8339276cdee --- /dev/null +++ b/solutions/61. Rotate List/61.py @@ -0,0 +1,19 @@ +class Solution: + def rotateRight(self, head: ListNode, k: int) -> ListNode: + if not head or not head.next or k == 0: + return head + + tail = head + length = 1 + while tail.next: + tail = tail.next + length += 1 + tail.next = head # Circle the list. + + t = length - k % length + for _ in range(t): + tail = tail.next + newHead = tail.next + tail.next = None + + return newHead diff --git a/solutions/610. Triangle Judgement/610.sql b/solutions/610. Triangle Judgement/610.sql new file mode 100644 index 00000000000..c57d94fd0b0 --- /dev/null +++ b/solutions/610. Triangle Judgement/610.sql @@ -0,0 +1,4 @@ +SELECT + *, + IF(x + y > z AND x + z > y AND y + z > x, 'Yes', 'No') AS triangle +FROM Triangle; diff --git a/solutions/611. Valid Triangle Number/611.cpp b/solutions/611. Valid Triangle Number/611.cpp new file mode 100644 index 00000000000..d5f0fe33333 --- /dev/null +++ b/solutions/611. Valid Triangle Number/611.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int triangleNumber(vector& nums) { + if (nums.size() < 3) + return 0; + + int ans = 0; + + ranges::sort(nums); + + for (int k = nums.size() - 1; k > 1; --k) { + int i = 0; + int j = k - 1; + while (i < j) + if (nums[i] + nums[j] > nums[k]) { + // (nums[i], nums[j], nums[k]) + // (nums[i + 1], nums[j], nums[k]) + // ... + // (nums[j - 1], nums[j], nums[k]) + ans += j - i; + --j; + } else { + ++i; + } + } + + return ans; + } +}; diff --git a/solutions/611. Valid Triangle Number/611.java b/solutions/611. Valid Triangle Number/611.java new file mode 100644 index 00000000000..dc4bc357936 --- /dev/null +++ b/solutions/611. Valid Triangle Number/611.java @@ -0,0 +1,28 @@ +class Solution { + public int triangleNumber(int[] nums) { + if (nums.length < 3) + return 0; + + int ans = 0; + + Arrays.sort(nums); + + for (int k = nums.length - 1; k > 1; --k) { + int i = 0; + int j = k - 1; + while (i < j) + if (nums[i] + nums[j] > nums[k]) { + // (nums[i], nums[j], nums[k]) + // (nums[i + 1], nums[j], nums[k]) + // ... + // (nums[j - 1], nums[j], nums[k]) + ans += j - i; + --j; + } else { + ++i; + } + } + + return ans; + } +} diff --git a/solutions/611. Valid Triangle Number/611.py b/solutions/611. Valid Triangle Number/611.py new file mode 100644 index 00000000000..6ee4f8bdde0 --- /dev/null +++ b/solutions/611. Valid Triangle Number/611.py @@ -0,0 +1,17 @@ +class Solution: + def triangleNumber(self, nums: List[int]) -> int: + ans = 0 + + nums.sort() + + for k in range(len(nums) - 1, 1, -1): + i = 0 + j = k - 1 + while i < j: + if nums[i] + nums[j] > nums[k]: + ans += j - i + j -= 1 + else: + i += 1 + + return ans diff --git a/solutions/612. Shortest Distance in a Plane/612.sql b/solutions/612. Shortest Distance in a Plane/612.sql new file mode 100644 index 00000000000..65d30ea5106 --- /dev/null +++ b/solutions/612. Shortest Distance in a Plane/612.sql @@ -0,0 +1,7 @@ +SELECT ROUND( + MIN(SQRT(POW(P1.x - P2.x, 2) + POW(P1.y - P2.y, 2))), + 2 + ) AS shortest +FROM Point2D AS P1 +LEFT JOIN Point2D AS P2 + ON (P1.x, P1.y) != (P2.x, P2.y); diff --git a/solutions/613. Shortest Distance in a Line/613.sql b/solutions/613. Shortest Distance in a Line/613.sql new file mode 100644 index 00000000000..60776880c4a --- /dev/null +++ b/solutions/613. Shortest Distance in a Line/613.sql @@ -0,0 +1,3 @@ +SELECT MIN(P1.x - P2.x) AS shortest +FROM Point AS P1, Point AS P2 +WHERE P1.x > P2.x; diff --git a/solutions/614. Second Degree Follower/614.sql b/solutions/614. Second Degree Follower/614.sql new file mode 100644 index 00000000000..21a0bb8d912 --- /dev/null +++ b/solutions/614. Second Degree Follower/614.sql @@ -0,0 +1,8 @@ +SELECT + Follower.follower, + COUNT(DISTINCT Followee.follower) AS num +FROM Follow AS Follower +INNER JOIN Follow AS Followee + ON (Follower.follower = Followee.followee) +GROUP BY 1 +ORDER BY 1; diff --git a/solutions/615. Average Salary: Departments VS Company/615.sql b/solutions/615. Average Salary: Departments VS Company/615.sql new file mode 100644 index 00000000000..79fe975817a --- /dev/null +++ b/solutions/615. Average Salary: Departments VS Company/615.sql @@ -0,0 +1,25 @@ +WITH + AvgSalary AS ( + SELECT DISTINCT + DATE_FORMAT(pay_date, '%Y-%m') AS pay_month, + Employee.department_id, + AVG(amount) OVER( + PARTITION BY Employee.department_id, + Salary.pay_date + ) AS department_avg_salary, + AVG(amount) OVER(PARTITION BY Salary.pay_date) AS company_avg_salary + FROM Salary + INNER JOIN Employee + USING (employee_id) + ) +SELECT DISTINCT + pay_month, + department_id, + ( + CASE + WHEN department_avg_salary > company_avg_salary THEN 'higher' + WHEN department_avg_salary < company_avg_salary THEN 'lower' + ELSE 'same' + END + ) AS comparison +FROM AvgSalary; diff --git a/solutions/616. Add Bold Tag in String/616-2.cpp b/solutions/616. Add Bold Tag in String/616-2.cpp new file mode 100644 index 00000000000..2e148553b46 --- /dev/null +++ b/solutions/616. Add Bold Tag in String/616-2.cpp @@ -0,0 +1,66 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(128) {} +}; + +class Solution { + public: + string addBoldTag(string s, vector& words) { + const int n = s.length(); + string ans; + // bold[i] := true if s[i] should be bolded + vector bold(n); + + for (const string& word : words) + insert(word); + + int boldEnd = -1; // `s[i..boldEnd]` should be bolded. + for (int i = 0; i < n; ++i) { + boldEnd = max(boldEnd, find(s, i)); + bold[i] = boldEnd >= i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // `s[i..j)` should be bolded. + ans += "" + s.substr(i, j - i) + ""; + i = j; + } else { + ans += s[i++]; + } + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + if (node->children[c] == nullptr) + node->children[c] = make_shared(); + node = node->children[c]; + } + node->isWord = true; + } + + int find(const string& s, int i) { + shared_ptr node = root; + int ans = -1; + for (int j = i; j < s.length(); ++j) { + if (node->children[s[j]] == nullptr) + return ans; + node = node->children[s[j]]; + if (node->isWord) + ans = j; + } + return ans; + } +}; diff --git a/solutions/616. Add Bold Tag in String/616-2.java b/solutions/616. Add Bold Tag in String/616-2.java new file mode 100644 index 00000000000..9fed1dd5d5e --- /dev/null +++ b/solutions/616. Add Bold Tag in String/616-2.java @@ -0,0 +1,63 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[128]; + public boolean isWord = false; +} + +class Solution { + public String addBoldTag(String s, String[] words) { + final int n = s.length(); + StringBuilder sb = new StringBuilder(); + // bold[i] := true if s[i] should be bolded + boolean[] bold = new boolean[n]; + + for (final String word : words) + insert(word); + + int boldEnd = -1; // `s[i..boldEnd]` should be bolded. + for (int i = 0; i < n; ++i) { + boldEnd = Math.max(boldEnd, find(s, i)); + bold[i] = boldEnd >= i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // s[i..j) should be bolded + sb.append("").append(s.substring(i, j)).append(""); + i = j; + } else { + sb.append(s.charAt(i++)); + } + + return sb.toString(); + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + if (node.children[c] == null) + node.children[c] = new TrieNode(); + node = node.children[c]; + } + node.isWord = true; + } + + private int find(final String s, int i) { + TrieNode node = root; + int ans = -1; + for (int j = i; j < s.length(); ++j) { + if (node.children[s.charAt(j)] == null) + return ans; + node = node.children[s.charAt(j)]; + if (node.isWord) + ans = j; + } + return ans; + } +} diff --git a/solutions/616. Add Bold Tag in String/616-2.py b/solutions/616. Add Bold Tag in String/616-2.py new file mode 100644 index 00000000000..0e011f98476 --- /dev/null +++ b/solutions/616. Add Bold Tag in String/616-2.py @@ -0,0 +1,54 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.isWord = False + + +class Solution: + def addBoldTag(self, s: str, words: List[str]) -> str: + n = len(s) + ans = [] + # bold[i] := True if s[i] should be bolded + bold = [0] * n + root = TrieNode() + + def insert(word: str) -> None: + node = root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + def find(s: str, i: int) -> int: + node = root + ans = -1 + for j in range(i, len(s)): + if s[j] not in node.children: + node.children[s[j]] = TrieNode() + node = node.children[s[j]] + if node.isWord: + ans = j + return ans + + for word in words: + insert(word) + + boldEnd = -1 # `s[i..boldEnd]` should be bolded. + for i in range(n): + boldEnd = max(boldEnd, find(s, i)) + bold[i] = boldEnd >= i + + # Construct the with bold tags + i = 0 + while i < n: + if bold[i]: + j = i + while j < n and bold[j]: + j += 1 + # `s[i..j)` should be bolded. + ans.append('' + s[i:j] + '') + i = j + else: + ans.append(s[i]) + i += 1 + + return ''.join(ans) diff --git a/solutions/616. Add Bold Tag in String/616-3.cpp b/solutions/616. Add Bold Tag in String/616-3.cpp new file mode 100644 index 00000000000..27c585be132 --- /dev/null +++ b/solutions/616. Add Bold Tag in String/616-3.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + string addBoldTag(string s, vector& words) { + string ans; + vector> intervals; + vector> merged; + + for (const string& word : words) { + const int n = word.length(); + for (int i = 0; i + n <= s.length(); ++i) + if (s.substr(i, n) == word) + intervals.emplace_back(i, i + n); + } + + if (intervals.empty()) + return s; + + ranges::sort(intervals); + + for (const pair& interval : intervals) + if (merged.empty() || merged.back().second < interval.first) + merged.push_back(interval); + else + merged.back().second = max(merged.back().second, interval.second); + + int prevEnd = 0; + + for (const auto& [startIndex, endIndex] : merged) { + ans += s.substr(prevEnd, startIndex - prevEnd); + ans += "" + s.substr(startIndex, endIndex - startIndex) + ""; + prevEnd = endIndex; + } + + if (!merged.empty()) + ans += s.substr(merged.back().second); + + return ans; + } +}; diff --git a/solutions/616. Add Bold Tag in String/616.cpp b/solutions/616. Add Bold Tag in String/616.cpp new file mode 100644 index 00000000000..0c855b0d98c --- /dev/null +++ b/solutions/616. Add Bold Tag in String/616.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + string addBoldTag(string s, vector& words) { + const int n = s.length(); + string ans; + // bold[i] := true if s[i] should be bolded + vector bold(n); + + int boldEnd = -1; // s[i:boldEnd] should be bolded + for (int i = 0; i < n; ++i) { + for (const string& word : words) + if (s.substr(i).find(word) == 0) // StartsWith + boldEnd = max(boldEnd, i + static_cast(word.length())); + bold[i] = boldEnd > i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // `s[i..j)` should be bolded. + ans += "" + s.substr(i, j - i) + ""; + i = j; + } else { + ans += s[i++]; + } + + return ans; + } +}; diff --git a/solutions/616. Add Bold Tag in String/616.java b/solutions/616. Add Bold Tag in String/616.java new file mode 100644 index 00000000000..8533f5352cb --- /dev/null +++ b/solutions/616. Add Bold Tag in String/616.java @@ -0,0 +1,32 @@ +class Solution { + public String addBoldTag(String s, String[] words) { + final int n = s.length(); + StringBuilder sb = new StringBuilder(); + // bold[i] := true if s[i] should be bolded + boolean[] bold = new boolean[n]; + + int boldEnd = -1; // s[i:boldEnd] should be bolded + for (int i = 0; i < n; ++i) { + for (final String word : words) + if (s.substring(i).startsWith(word)) + boldEnd = Math.max(boldEnd, i + word.length()); + bold[i] = boldEnd > i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // s[i..j) should be bolded + sb.append("").append(s.substring(i, j)).append(""); + i = j; + } else { + sb.append(s.charAt(i++)); + } + + return sb.toString(); + } +} diff --git a/solutions/616. Add Bold Tag in String/616.py b/solutions/616. Add Bold Tag in String/616.py new file mode 100644 index 00000000000..1dd6baa2bfe --- /dev/null +++ b/solutions/616. Add Bold Tag in String/616.py @@ -0,0 +1,29 @@ +class Solution: + def addBoldTag(self, s: str, words: List[str]) -> str: + n = len(s) + ans = [] + # bold[i] := True if s[i] should be bolded + bold = [0] * n + + boldEnd = -1 # s[i:boldEnd] should be bolded + for i in range(n): + for word in words: + if s[i:].startswith(word): + boldEnd = max(boldEnd, i + len(word)) + bold[i] = boldEnd > i + + # Construct the with bold tags + i = 0 + while i < n: + if bold[i]: + j = i + while j < n and bold[j]: + j += 1 + # `s[i..j)` should be bolded. + ans.append('' + s[i:j] + '') + i = j + else: + ans.append(s[i]) + i += 1 + + return ''.join(ans) diff --git a/solutions/617. Merge Two Binary Trees/617.cpp b/solutions/617. Merge Two Binary Trees/617.cpp new file mode 100644 index 00000000000..4d722c9f993 --- /dev/null +++ b/solutions/617. Merge Two Binary Trees/617.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { + if (root1 == nullptr && root2 == nullptr) + return nullptr; + const int val = (root1 == nullptr ? 0 : root1->val) + + (root2 == nullptr ? 0 : root2->val); + TreeNode* root = new TreeNode(val); + root->left = mergeTrees(root1 == nullptr ? nullptr : root1->left, + root2 == nullptr ? nullptr : root2->left); + root->right = mergeTrees(root1 == nullptr ? nullptr : root1->right, + root2 == nullptr ? nullptr : root2->right); + return root; + } +}; diff --git a/solutions/617. Merge Two Binary Trees/617.java b/solutions/617. Merge Two Binary Trees/617.java new file mode 100644 index 00000000000..776a5067fb2 --- /dev/null +++ b/solutions/617. Merge Two Binary Trees/617.java @@ -0,0 +1,11 @@ +class Solution { + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null && root2 == null) + return null; + final int val = (root1 == null ? 0 : root1.val) + (root2 == null ? 0 : root2.val); + TreeNode root = new TreeNode(val); + root.left = mergeTrees(root1 == null ? null : root1.left, root2 == null ? null : root2.left); + root.right = mergeTrees(root1 == null ? null : root1.right, root2 == null ? null : root2.right); + return root; + } +} diff --git a/solutions/617. Merge Two Binary Trees/617.py b/solutions/617. Merge Two Binary Trees/617.py new file mode 100644 index 00000000000..998c208a4d1 --- /dev/null +++ b/solutions/617. Merge Two Binary Trees/617.py @@ -0,0 +1,11 @@ +class Solution: + def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]: + if not root1 and not root2: + return None + val = (root1.val if root1 else 0) + (root2.val if root2 else 0) + root = TreeNode(val) + root.left = self.mergeTrees(root1.left if root1 else None, + root2.left if root2 else None) + root.right = self.mergeTrees(root1.right if root1 else None, + root2.right if root2 else None) + return root diff --git a/solutions/618. Students Report By Geography/618.sql b/solutions/618. Students Report By Geography/618.sql new file mode 100644 index 00000000000..ba0bc37f1b7 --- /dev/null +++ b/solutions/618. Students Report By Geography/618.sql @@ -0,0 +1,14 @@ +WITH + StudentWithIdInContinent AS ( + SELECT + *, + ROW_NUMBER() OVER(PARTITION BY continent ORDER BY name) AS id + FROM Student + ) +SELECT + MAX(CASE WHEN continent = 'America' THEN name END) AS America, + MAX(CASE WHEN continent = 'Asia' THEN name END) AS Asia, + MAX(CASE WHEN continent = 'Europe' THEN name END) AS Europe, + id +FROM StudentWithIdInContinent +GROUP BY id; diff --git a/solutions/619. Biggest Single Number/619.sql b/solutions/619. Biggest Single Number/619.sql new file mode 100644 index 00000000000..80c6044277b --- /dev/null +++ b/solutions/619. Biggest Single Number/619.sql @@ -0,0 +1,9 @@ +WITH + UniqueNumbers AS ( + SELECT num + FROM MyNumbers + GROUP BY 1 + HAVING COUNT(num) = 1 + ) +SELECT MAX(num) AS num +FROM UniqueNumbers; diff --git a/solutions/62. Unique Paths/62-2.cpp b/solutions/62. Unique Paths/62-2.cpp new file mode 100644 index 00000000000..3ce571d9f6f --- /dev/null +++ b/solutions/62. Unique Paths/62-2.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int uniquePaths(int m, int n) { + vector dp(n, 1); + + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + dp[j] += dp[j - 1]; + + return dp[n - 1]; + } +}; diff --git a/solutions/62. Unique Paths/62-2.java b/solutions/62. Unique Paths/62-2.java new file mode 100644 index 00000000000..993b585e06a --- /dev/null +++ b/solutions/62. Unique Paths/62-2.java @@ -0,0 +1,12 @@ +class Solution { + public int uniquePaths(int m, int n) { + int[] dp = new int[n]; + Arrays.fill(dp, 1); + + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + dp[j] += dp[j - 1]; + + return dp[n - 1]; + } +} diff --git a/solutions/62. Unique Paths/62-2.py b/solutions/62. Unique Paths/62-2.py new file mode 100644 index 00000000000..222166377b4 --- /dev/null +++ b/solutions/62. Unique Paths/62-2.py @@ -0,0 +1,9 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + dp = [1] * n + + for _ in range(1, m): + for j in range(1, n): + dp[j] += dp[j - 1] + + return dp[n - 1] diff --git a/solutions/62. Unique Paths/62.cpp b/solutions/62. Unique Paths/62.cpp new file mode 100644 index 00000000000..c986b531884 --- /dev/null +++ b/solutions/62. Unique Paths/62.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int uniquePaths(int m, int n) { + // dp[i][j] := the number of unique paths from (0, 0) to (i, j) + vector> dp(m, vector(n, 1)); + + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + + return dp[m - 1][n - 1]; + } +}; diff --git a/solutions/62. Unique Paths/62.java b/solutions/62. Unique Paths/62.java new file mode 100644 index 00000000000..8632f09dba3 --- /dev/null +++ b/solutions/62. Unique Paths/62.java @@ -0,0 +1,13 @@ +class Solution { + public int uniquePaths(int m, int n) { + // dp[i][j] := the number of unique paths from (0, 0) to (i, j) + int[][] dp = new int[m][n]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, 1)); + + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + + return dp[m - 1][n - 1]; + } +} diff --git a/solutions/62. Unique Paths/62.py b/solutions/62. Unique Paths/62.py new file mode 100644 index 00000000000..228d4c491cf --- /dev/null +++ b/solutions/62. Unique Paths/62.py @@ -0,0 +1,10 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + # dp[i][j] := the number of unique paths from (0, 0) to (i, j) + dp = [[1] * n for _ in range(m)] + + for i in range(1, m): + for j in range(1, n): + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + + return dp[-1][-1] diff --git a/solutions/620. Not Boring Movies/620.sql b/solutions/620. Not Boring Movies/620.sql new file mode 100644 index 00000000000..b98f06352cb --- /dev/null +++ b/solutions/620. Not Boring Movies/620.sql @@ -0,0 +1,6 @@ +SELECT * +FROM Cinema +WHERE + MOD(id, 2) = 1 + AND description != 'boring' +ORDER BY rating DESC; diff --git a/solutions/621. Task Scheduler/621.cpp b/solutions/621. Task Scheduler/621.cpp new file mode 100644 index 00000000000..2429f9f3d54 --- /dev/null +++ b/solutions/621. Task Scheduler/621.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int leastInterval(vector& tasks, int n) { + if (n == 0) + return tasks.size(); + + vector count(26); + + for (const char task : tasks) + ++count[task - 'A']; + + const int maxFreq = ranges::max(count); + // Put the most frequent task in the slot first. + const int maxFreqTaskOccupy = (maxFreq - 1) * (n + 1); + // Get the number of tasks with the same frequency as `maxFreq`, we'll + // append them after `maxFreqTaskOccupy`. + const int nMaxFreq = ranges::count(count, maxFreq); + // max( + // the most frequent task is frequent enough to force some idle slots, + // the most frequent task is not frequent enough to force idle slots + // ) + return max(maxFreqTaskOccupy + nMaxFreq, static_cast(tasks.size())); + } +}; diff --git a/solutions/621. Task Scheduler/621.java b/solutions/621. Task Scheduler/621.java new file mode 100644 index 00000000000..ce435d1b9e7 --- /dev/null +++ b/solutions/621. Task Scheduler/621.java @@ -0,0 +1,20 @@ +class Solution { + public int leastInterval(char[] tasks, int n) { + int[] count = new int[26]; + + for (final char task : tasks) + ++count[task - 'A']; + + final int maxFreq = Arrays.stream(count).max().getAsInt(); + // Put the most frequent task in the slot first. + final int maxFreqTaskOccupy = (maxFreq - 1) * (n + 1); + // Get the number of tasks with the same frequency as `maxFreq`, we'll + // append them after `maxFreqTaskOccupy`. + final int nMaxFreq = (int) Arrays.stream(count).filter(c -> c == maxFreq).count(); + // max( + // the most frequent task is frequent enough to force some idle slots, + // the most frequent task is not frequent enough to force idle slots + // ) + return Math.max(maxFreqTaskOccupy + nMaxFreq, tasks.length); + } +} diff --git a/solutions/621. Task Scheduler/621.py b/solutions/621. Task Scheduler/621.py new file mode 100644 index 00000000000..5eeb5476279 --- /dev/null +++ b/solutions/621. Task Scheduler/621.py @@ -0,0 +1,14 @@ +class Solution: + def leastInterval(self, tasks: List[str], n: int) -> int: + count = collections.Counter(tasks) + maxFreq = max(count.values()) + # Put the most frequent task in the slot first. + maxFreqTaskOccupy = (maxFreq - 1) * (n + 1) + # Get the number of tasks with same frequency as maxFreq, we'll append them after the + # `maxFreqTaskOccupy`. + nMaxFreq = sum(value == maxFreq for value in count.values()) + # max( + # the most frequent task is frequent enough to force some idle slots, + # the most frequent task is not frequent enough to force idle slots + # ) + return max(maxFreqTaskOccupy + nMaxFreq, len(tasks)) diff --git a/solutions/622. Design Circular Queue/622.cpp b/solutions/622. Design Circular Queue/622.cpp new file mode 100644 index 00000000000..2ef0a00342d --- /dev/null +++ b/solutions/622. Design Circular Queue/622.cpp @@ -0,0 +1,55 @@ +class MyCircularQueue { + public: + /** Initialize your data structure here. Set the size of the queue to be k. */ + MyCircularQueue(int k) : k(k), q(k), rear(k - 1) {} + + /** Insert an element into the circular queue. Return true if the operation is + * successful. */ + bool enQueue(int value) { + if (isFull()) + return false; + + rear = ++rear % k; + q[rear] = value; + ++size; + return true; + } + + /** Delete an element from the circular queue. Return true if the operation is + * successful. */ + bool deQueue() { + if (isEmpty()) + return false; + + front = ++front % k; + --size; + return true; + } + + /** Get the front item from the queue. */ + int Front() { + return isEmpty() ? -1 : q[front]; + } + + /** Get the last item from the queue. */ + int Rear() { + return isEmpty() ? -1 : q[rear]; + } + + /** Checks whether the circular queue is empty or not. */ + bool isEmpty() { + return size == 0; + } + + /** Checks whether the circular queue is full or not. */ + bool isFull() { + return size == k; + } + + private: + const int k; + vector q; + int size = 0; + int front = 0; + int rear; +}; diff --git a/solutions/622. Design Circular Queue/622.java b/solutions/622. Design Circular Queue/622.java new file mode 100644 index 00000000000..fa727f09ed1 --- /dev/null +++ b/solutions/622. Design Circular Queue/622.java @@ -0,0 +1,55 @@ +class MyCircularQueue { + /** Initialize your data structure here. Set the size of the queue to be k. */ + public MyCircularQueue(int k) { + this.k = k; + this.q = new int[k]; + this.rear = k - 1; + } + + /** Insert an element into the circular queue. Return true if the operation is successful. */ + public boolean enQueue(int value) { + if (isFull()) + return false; + + rear = ++rear % k; + q[rear] = value; + ++size; + return true; + } + + /** Delete an element from the circular queue. Return true if the operation is successful. */ + public boolean deQueue() { + if (isEmpty()) + return false; + + front = ++front % k; + --size; + return true; + } + + /** Get the front item from the queue. */ + public int Front() { + return isEmpty() ? -1 : q[front]; + } + + /** Get the last item from the queue. */ + public int Rear() { + return isEmpty() ? -1 : q[rear]; + } + + /** Checks whether the circular queue is empty or not. */ + public boolean isEmpty() { + return size == 0; + } + + /** Checks whether the circular queue is full or not. */ + public boolean isFull() { + return size == k; + } + + private final int k; + private int[] q; + private int size = 0; + private int front = 0; + private int rear; +} diff --git a/solutions/623. Add One Row to Tree/623.cpp b/solutions/623. Add One Row to Tree/623.cpp new file mode 100644 index 00000000000..4f38699c122 --- /dev/null +++ b/solutions/623. Add One Row to Tree/623.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + TreeNode* addOneRow(TreeNode* root, int v, int d) { + if (d == 1) { + TreeNode* newRoot = new TreeNode(v); + newRoot->left = root; + return newRoot; + } + + int depth = 0; + queue q{{root}}; + + while (!q.empty()) { + ++depth; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + if (depth == d - 1) { + TreeNode* cachedLeft = node->left; + TreeNode* cachedRight = node->right; + node->left = new TreeNode(v); + node->right = new TreeNode(v); + node->left->left = cachedLeft; + node->right->right = cachedRight; + } + } + if (depth == d - 1) + break; + } + + return root; + } +}; diff --git a/solutions/623. Add One Row to Tree/623.java b/solutions/623. Add One Row to Tree/623.java new file mode 100644 index 00000000000..900c276adc3 --- /dev/null +++ b/solutions/623. Add One Row to Tree/623.java @@ -0,0 +1,35 @@ +class Solution { + public TreeNode addOneRow(TreeNode root, int v, int d) { + if (d == 1) { + TreeNode newRoot = new TreeNode(v); + newRoot.left = root; + return newRoot; + } + + int depth = 0; + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + ++depth; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode node = q.poll(); + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + if (depth == d - 1) { + TreeNode cachedLeft = node.left; + TreeNode cachedRight = node.right; + node.left = new TreeNode(v); + node.right = new TreeNode(v); + node.left.left = cachedLeft; + node.right.right = cachedRight; + } + } + if (depth == d - 1) + break; + } + + return root; + } +} diff --git a/solutions/624. Maximum Distance in Arrays/624-2.py b/solutions/624. Maximum Distance in Arrays/624-2.py new file mode 100644 index 00000000000..1d4eece5f42 --- /dev/null +++ b/solutions/624. Maximum Distance in Arrays/624-2.py @@ -0,0 +1,12 @@ +class Solution: + def maxDistance(self, arrays: List[List[int]]) -> int: + min1, index_min1 = min((A[0], i) for i, A in enumerate(arrays)) + max1, index_max1 = max((A[-1], i) for i, A in enumerate(arrays)) + if index_min1 != index_max1: + return max1 - min1 + + min2, index_min2 = min((A[0], i) + for i, A in enumerate(arrays) if i != index_min1) + max2, index_min2 = max((A[-1], i) + for i, A in enumerate(arrays) if i != index_max1) + return max(max1 - min2, max2 - min1) diff --git a/solutions/624. Maximum Distance in Arrays/624.cpp b/solutions/624. Maximum Distance in Arrays/624.cpp new file mode 100644 index 00000000000..73063a94a3b --- /dev/null +++ b/solutions/624. Maximum Distance in Arrays/624.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int mxDistance(vector>& arrays) { + int ans = 0; + int mn = 10000; + int mx = -10000; + + for (const vector& A : arrays) { + ans = max({ans, A.back() - mn, mx - A.front()}); + mn = min(mn, A.front()); + mx = max(mx, A.back()); + } + + return ans; + } +}; diff --git a/solutions/624. Maximum Distance in Arrays/624.java b/solutions/624. Maximum Distance in Arrays/624.java new file mode 100644 index 00000000000..f20f4f5d358 --- /dev/null +++ b/solutions/624. Maximum Distance in Arrays/624.java @@ -0,0 +1,15 @@ +class Solution { + public int maxDistance(List> arrays) { + int ans = 0; + int mn = 10000; + int mx = -10000; + + for (List A : arrays) { + ans = Math.max(ans, Math.max(A.get(A.size() - 1) - mn, mx - A.get(0))); + mn = Math.min(mn, A.get(0)); + mx = Math.max(mx, A.get(A.size() - 1)); + } + + return ans; + } +} diff --git a/solutions/624. Maximum Distance in Arrays/624.py b/solutions/624. Maximum Distance in Arrays/624.py new file mode 100644 index 00000000000..edefe74554c --- /dev/null +++ b/solutions/624. Maximum Distance in Arrays/624.py @@ -0,0 +1,12 @@ +class Solution: + def maxDistance(self, arrays: List[List[int]]) -> int: + ans = 0 + mn = 10000 + mx = -10000 + + for A in arrays: + ans = max(ans, A[-1] - mn, mx - A[0]) + mn = min(mn, A[0]) + mx = max(mx, A[-1]) + + return ans diff --git a/solutions/625. Minimum Factorization/625.cpp b/solutions/625. Minimum Factorization/625.cpp new file mode 100644 index 00000000000..e4d5d99117c --- /dev/null +++ b/solutions/625. Minimum Factorization/625.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int smallestFactorization(int num) { + if (num == 1) + return 1; + + long ans = 0; + long base = 1; + + for (int i = 9; i > 1; --i) + while (num % i == 0) { + num /= i; + ans = base * i + ans; + base *= 10; + } + + return num == 1 && ans <= INT_MAX ? ans : 0; + } +}; diff --git a/solutions/625. Minimum Factorization/625.java b/solutions/625. Minimum Factorization/625.java new file mode 100644 index 00000000000..3ad0f07e91f --- /dev/null +++ b/solutions/625. Minimum Factorization/625.java @@ -0,0 +1,18 @@ +class Solution { + public int smallestFactorization(int num) { + if (num == 1) + return 1; + + long ans = 0; + long base = 1; + + for (int i = 9; i > 1; --i) + while (num % i == 0) { + num /= i; + ans = base * i + ans; + base *= 10; + } + + return num == 1 && ans <= Integer.MAX_VALUE ? (int) ans : 0; + } +} diff --git a/solutions/625. Minimum Factorization/625.py b/solutions/625. Minimum Factorization/625.py new file mode 100644 index 00000000000..43ead346629 --- /dev/null +++ b/solutions/625. Minimum Factorization/625.py @@ -0,0 +1,15 @@ +class Solution: + def smallestFactorization(self, num: int) -> int: + if num == 1: + return 1 + + ans = 0 + base = 1 + + for i in range(9, 1, -1): + while num % i == 0: + num //= i + ans = base * i + ans + base *= 10 + + return ans if num == 1 and ans < 2**31 - 1 else 0 diff --git a/solutions/626. Exchange Seats/626.sql b/solutions/626. Exchange Seats/626.sql new file mode 100644 index 00000000000..5905346f092 --- /dev/null +++ b/solutions/626. Exchange Seats/626.sql @@ -0,0 +1,4 @@ +SELECT + ROW_NUMBER() OVER(ORDER BY IF(MOD(id, 2) = 0, id - 1, id + 1)) AS id, + student +FROM Seat; diff --git a/solutions/627. Swap Salary/627.sql b/solutions/627. Swap Salary/627.sql new file mode 100644 index 00000000000..47258882833 --- /dev/null +++ b/solutions/627. Swap Salary/627.sql @@ -0,0 +1,2 @@ +UPDATE Salary +SET sex = IF(sex = 'm', 'f', 'm'); diff --git a/solutions/628. Maximum Product of Three Numbers/628-2.cpp b/solutions/628. Maximum Product of Three Numbers/628-2.cpp new file mode 100644 index 00000000000..cb0d25f9d09 --- /dev/null +++ b/solutions/628. Maximum Product of Three Numbers/628-2.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int maximumProduct(vector& nums) { + int min1 = INT_MAX; // the minimum + int min2 = INT_MAX; // the second minimum + int max1 = INT_MIN; // the maximum + int max2 = INT_MIN; // the second maximum + int max3 = INT_MIN; // the third maximum + + for (const int num : nums) { + if (num <= min1) { + min2 = min1; + min1 = num; + } else if (num <= min2) { + min2 = num; + } + if (num >= max1) { + max3 = max2; + max2 = max1; + max1 = num; + } else if (num >= max2) { + max3 = max2; + max2 = num; + } else if (num >= max3) { + max3 = num; + } + } + + return max(max1 * min1 * min2, max1 * max2 * max3); + } +}; diff --git a/solutions/628. Maximum Product of Three Numbers/628-2.java b/solutions/628. Maximum Product of Three Numbers/628-2.java new file mode 100644 index 00000000000..df310a08bac --- /dev/null +++ b/solutions/628. Maximum Product of Three Numbers/628-2.java @@ -0,0 +1,30 @@ +class Solution { + public int maximumProduct(int[] nums) { + int min1 = Integer.MAX_VALUE; // the minimum + int min2 = Integer.MAX_VALUE; // the second minimum + int max1 = Integer.MIN_VALUE; // the maximum + int max2 = Integer.MIN_VALUE; // the second maximum + int max3 = Integer.MIN_VALUE; // the third maximum + + for (final int num : nums) { + if (num <= min1) { + min2 = min1; + min1 = num; + } else if (num <= min2) { + min2 = num; + } + if (num >= max1) { + max3 = max2; + max2 = max1; + max1 = num; + } else if (num >= max2) { + max3 = max2; + max2 = num; + } else if (num >= max3) { + max3 = num; + } + } + + return max(max1 * min1 * min2, max1 * max2 * max3); + } +} diff --git a/solutions/628. Maximum Product of Three Numbers/628-2.py b/solutions/628. Maximum Product of Three Numbers/628-2.py new file mode 100644 index 00000000000..fac6a711772 --- /dev/null +++ b/solutions/628. Maximum Product of Three Numbers/628-2.py @@ -0,0 +1,26 @@ +class Solution: + def maximumProduct(self, nums: List[int]) -> int: + min1 = inf # the minimum + min2 = inf # the second minimum + max1 = -inf # the maximum + max2 = -inf # the second maximum + max3 = -inf # the third maximum + + for num in nums: + if num <= min1: + min2 = min1 + min1 = num + elif num <= min2: + min2 = num + + if num >= max1: + max3 = max2 + max2 = max1 + max1 = num + elif num >= max2: + max3 = max2 + max2 = num + elif num >= max3: + max3 = num + + return max(max1 * min1 * min2, max1 * max2 * max3) diff --git a/solutions/628. Maximum Product of Three Numbers/628.cpp b/solutions/628. Maximum Product of Three Numbers/628.cpp new file mode 100644 index 00000000000..a36e8cb3f7f --- /dev/null +++ b/solutions/628. Maximum Product of Three Numbers/628.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int maximumProduct(vector& nums) { + const int n = nums.size(); + ranges::sort(nums); + return max(nums[n - 1] * nums[0] * nums[1], + nums[n - 1] * nums[n - 2] * nums[n - 3]); + } +}; diff --git a/solutions/628. Maximum Product of Three Numbers/628.java b/solutions/628. Maximum Product of Three Numbers/628.java new file mode 100644 index 00000000000..836608cd3de --- /dev/null +++ b/solutions/628. Maximum Product of Three Numbers/628.java @@ -0,0 +1,7 @@ +class Solution { + public int maximumProduct(int[] nums) { + final int n = nums.length; + Arrays.sort(nums); + return Math.max(nums[n - 1] * nums[0] * nums[1], nums[n - 1] * nums[n - 2] * nums[n - 3]); + } +} diff --git a/solutions/628. Maximum Product of Three Numbers/628.py b/solutions/628. Maximum Product of Three Numbers/628.py new file mode 100644 index 00000000000..8cce9d8fa48 --- /dev/null +++ b/solutions/628. Maximum Product of Three Numbers/628.py @@ -0,0 +1,5 @@ +class Solution: + def maximumProduct(self, nums: List[int]) -> int: + nums.sort() + return max(nums[-1] * nums[0] * nums[1], + nums[-1] * nums[-2] * nums[-3]) diff --git a/solutions/629. K Inverse Pairs Array/629.cpp b/solutions/629. K Inverse Pairs Array/629.cpp new file mode 100644 index 00000000000..f1fabde330d --- /dev/null +++ b/solutions/629. K Inverse Pairs Array/629.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int kInversePairs(int n, int k) { + constexpr int kMod = 1'000'000'007; + // dp[i][j] := the number of permutations of numbers 1..i with j inverse + // pairs + vector> dp(n + 1, vector(k + 1)); + + // If there's no inverse pair, the permutation is unique "123..i". + for (int i = 0; i <= n; ++i) + dp[i][0] = 1; + + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) { + dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % kMod; + if (j - i >= 0) + dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + kMod) % kMod; + } + + return dp[n][k]; + } +}; diff --git a/solutions/629. K Inverse Pairs Array/629.java b/solutions/629. K Inverse Pairs Array/629.java new file mode 100644 index 00000000000..f0e6fafd6f6 --- /dev/null +++ b/solutions/629. K Inverse Pairs Array/629.java @@ -0,0 +1,20 @@ +class Solution { + public int kInversePairs(int n, int k) { + final int kMod = 1_000_000_007; + // dp[i][j] := the number of permutations of numbers 1..i with j inverse pairs + int[][] dp = new int[n + 1][k + 1]; + + // If there's no inverse pair, the permutation is unique "123..i". + for (int i = 0; i <= n; ++i) + dp[i][0] = 1; + + for (int i = 1; i <= n; ++i) + for (int j = 1; j <= k; ++j) { + dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % kMod; + if (j - i >= 0) + dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + kMod) % kMod; + } + + return dp[n][k]; + } +} diff --git a/solutions/629. K Inverse Pairs Array/629.py b/solutions/629. K Inverse Pairs Array/629.py new file mode 100644 index 00000000000..a7bd7ba5017 --- /dev/null +++ b/solutions/629. K Inverse Pairs Array/629.py @@ -0,0 +1,17 @@ +class Solution: + def kInversePairs(self, n: int, k: int) -> int: + kMod = 1_000_000_007 + # dp[i][j] := the number of permutations of numbers 1..i with j inverse pairs + dp = [[0] * (k + 1) for _ in range(n + 1)] + + # If there's no inverse pair, the permutation is unique '123..i' + for i in range(n + 1): + dp[i][0] = 1 + + for i in range(1, n + 1): + for j in range(1, k + 1): + dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % kMod + if j - i >= 0: + dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + kMod) % kMod + + return dp[n][k] diff --git a/solutions/63. Unique Paths II/63-2.cpp b/solutions/63. Unique Paths II/63-2.cpp new file mode 100644 index 00000000000..10ec25003a3 --- /dev/null +++ b/solutions/63. Unique Paths II/63-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + const int m = obstacleGrid.size(); + const int n = obstacleGrid[0].size(); + vector dp(n); + dp[0] = 1; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (obstacleGrid[i][j]) + dp[j] = 0; + else if (j > 0) + dp[j] += dp[j - 1]; + + return dp[n - 1]; + } +}; diff --git a/solutions/63. Unique Paths II/63-2.java b/solutions/63. Unique Paths II/63-2.java new file mode 100644 index 00000000000..40b87d3e96f --- /dev/null +++ b/solutions/63. Unique Paths II/63-2.java @@ -0,0 +1,17 @@ +class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + final int m = obstacleGrid.length; + final int n = obstacleGrid[0].length; + int[] dp = new int[n]; + dp[0] = 1; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (obstacleGrid[i][j] == 1) + dp[j] = 0; + else if (j > 0) + dp[j] += dp[j - 1]; + + return dp[n - 1]; + } +} diff --git a/solutions/63. Unique Paths II/63-2.py b/solutions/63. Unique Paths II/63-2.py new file mode 100644 index 00000000000..7ad58c5023d --- /dev/null +++ b/solutions/63. Unique Paths II/63-2.py @@ -0,0 +1,15 @@ +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + m = len(obstacleGrid) + n = len(obstacleGrid[0]) + dp = [0] * n + dp[0] = 1 + + for i in range(m): + for j in range(n): + if obstacleGrid[i][j]: + dp[j] = 0 + elif j > 0: + dp[j] += dp[j - 1] + + return dp[n - 1] diff --git a/solutions/63. Unique Paths II/63.cpp b/solutions/63. Unique Paths II/63.cpp new file mode 100644 index 00000000000..54b9f1efd95 --- /dev/null +++ b/solutions/63. Unique Paths II/63.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + const int m = obstacleGrid.size(); + const int n = obstacleGrid[0].size(); + // dp[i][j] := the number of unique paths from (0, 0) to (i, j) + vector> dp(m + 1, vector(n + 1, 0)); + dp[0][1] = 1; // Can also set dp[1][0] = 1. + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (!obstacleGrid[i - 1][j - 1]) + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + + return dp[m][n]; + } +}; diff --git a/solutions/63. Unique Paths II/63.java b/solutions/63. Unique Paths II/63.java new file mode 100644 index 00000000000..ec5f0254247 --- /dev/null +++ b/solutions/63. Unique Paths II/63.java @@ -0,0 +1,16 @@ +class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + final int m = obstacleGrid.length; + final int n = obstacleGrid[0].length; + // dp[i][j] := the number of unique paths from (0, 0) to (i, j) + long[][] dp = new long[m + 1][n + 1]; + dp[0][1] = 1; // Can also set dp[1][0] = 1. + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (obstacleGrid[i - 1][j - 1] == 0) + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + + return (int) dp[m][n]; + } +} diff --git a/solutions/63. Unique Paths II/63.py b/solutions/63. Unique Paths II/63.py new file mode 100644 index 00000000000..ee4d310623f --- /dev/null +++ b/solutions/63. Unique Paths II/63.py @@ -0,0 +1,14 @@ +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + m = len(obstacleGrid) + n = len(obstacleGrid[0]) + # dp[i][j] := the number of unique paths from (0, 0) to (i, j) + dp = [[0] * (n + 1) for _ in range(m + 1)] + dp[0][1] = 1 # Can also set dp[1][0] = 1. + + for i in range(1, m + 1): + for j in range(1, n + 1): + if obstacleGrid[i - 1][j - 1] == 0: + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + + return dp[m][n] diff --git a/solutions/630. Course Schedule III/630.cpp b/solutions/630. Course Schedule III/630.cpp new file mode 100644 index 00000000000..815065b0342 --- /dev/null +++ b/solutions/630. Course Schedule III/630.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int scheduleCourse(vector>& courses) { + int time = 0; + priority_queue maxHeap; + + ranges::sort(courses, + [](const auto& a, const auto& b) { return a[1] < b[1]; }); + + for (const vector& course : courses) { + const int duration = course[0]; + const int lastDay = course[1]; + maxHeap.push(duration); + time += duration; + // If the current course cannot be taken, check if it can be swapped with + // a previously taken course that has a larger duration to increase the + // time available to take upcoming courses. + if (time > lastDay) + time -= maxHeap.top(), maxHeap.pop(); + } + + return maxHeap.size(); + } +}; diff --git a/solutions/630. Course Schedule III/630.java b/solutions/630. Course Schedule III/630.java new file mode 100644 index 00000000000..a1106b43c21 --- /dev/null +++ b/solutions/630. Course Schedule III/630.java @@ -0,0 +1,22 @@ +class Solution { + public int scheduleCourse(int[][] courses) { + int time = 0; + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + Arrays.sort(courses, (a, b) -> (a[1] - b[1])); + + for (int[] course : courses) { + final int duration = course[0]; + final int lastDay = course[1]; + maxHeap.offer(duration); + time += course; + // If the current course cannot be taken, check if it can be swapped with + // a previously taken course that has a larger duration to increase the + // time available to take upcoming courses. + if (time > lastDay) + time -= maxHeap.poll(); + } + + return maxHeap.size(); + } +} diff --git a/solutions/630. Course Schedule III/630.py b/solutions/630. Course Schedule III/630.py new file mode 100644 index 00000000000..0cedd413cc4 --- /dev/null +++ b/solutions/630. Course Schedule III/630.py @@ -0,0 +1,15 @@ +class Solution: + def scheduleCourse(self, courses: List[List[int]]) -> int: + time = 0 + maxHeap = [] + + for duration, lastDay in sorted(courses, key=lambda x: x[1]): + heapq.heappush(maxHeap, -duration) + time += duration + # If the current course cannot be taken, check if it can be swapped with + # a previously taken course that has a larger duration to increase the + # time available to take upcoming courses. + if time > lastDay: + time += heapq.heappop(maxHeap) + + return len(maxHeap) diff --git a/solutions/631. Design Excel Sum Formula/631.cpp b/solutions/631. Design Excel Sum Formula/631.cpp new file mode 100644 index 00000000000..12387d9a6e5 --- /dev/null +++ b/solutions/631. Design Excel Sum Formula/631.cpp @@ -0,0 +1,59 @@ +struct Cell { + int val = 0; + unordered_map posCount; // {pos: count} +}; + +class Excel { + public: + Excel(int height, char width) + : width(width), sheet(height, vector(width)) {} + + void set(int row, char column, int val) { + getCell(row, column) = {val, {}}; + } + + int get(int row, char column) { + const Cell& cell = getCell(row, column); + if (cell.posCount.empty()) + return cell.val; + + int val = 0; + for (const auto& [pos, count] : cell.posCount) + val += get(pos / width + 1, pos % width + 'A') * count; + return val; + } + + int sum(int row, char column, vector numbers) { + getCell(row, column).posCount = parse(numbers); + return get(row, column); + } + + private: + int width; + vector> sheet; + + Cell& getCell(int row, char column) { + return sheet[row - 1][column - 'A']; + } + + unordered_map parse(const vector& numbers) { + unordered_map count; + for (const string& s : numbers) { + const auto [startRow, startCol, endRow, endCol] = parse(s); + for (int i = startRow - 1; i < endRow; ++i) + for (int j = startCol - 'A'; j < endCol - 'A' + 1; ++j) + ++count[i * width + j]; + } + return count; + } + + tuple parse(const string& s) { + if (s.find(':') == string::npos) + return {stoi(s.substr(1)), s[0], stoi(s.substr(1)), s[0]}; + + const int colonIndex = s.find_first_of(':'); + const string& l = s.substr(0, colonIndex); + const string& r = s.substr(colonIndex + 1); + return {stoi(l.substr(1)), l[0], stoi(r.substr(1)), r[0]}; + } +}; diff --git a/solutions/631. Design Excel Sum Formula/631.java b/solutions/631. Design Excel Sum Formula/631.java new file mode 100644 index 00000000000..770384495c1 --- /dev/null +++ b/solutions/631. Design Excel Sum Formula/631.java @@ -0,0 +1,70 @@ +class Cell { + public int val = 0; + public Map posCount = new HashMap<>(); // {pos, count} + public Cell(int val, Map posCount) { + this.val = val; + this.posCount = posCount; + } +} + +class Excel { + public Excel(int height, char width) { + this.width = width; + this.sheet = new Cell[height][width]; + + for (int i = 0; i < height; ++i) + for (int j = 0; j < width; ++j) + sheet[i][j] = new Cell(0, null); + } + + public void set(int row, char column, int val) { + sheet[row - 1][column - 'A'] = new Cell(val, null); + } + + public int get(int row, char column) { + Cell cell = sheet[row - 1][column - 'A']; + if (cell.posCount == null) + return cell.val; + + int val = 0; + for (Map.Entry entry : cell.posCount.entrySet()) { + final int pos = entry.getKey(); + final int count = entry.getValue(); + val += get(pos / width + 1, (char) ((pos % width) + 'A')) * count; + } + return val; + } + + public int sum(int row, char column, String[] numbers) { + sheet[row - 1][column - 'A'].posCount = parse(numbers); + return get(row, column); + } + + private int width; + private Cell[][] sheet; + + private Map parse(String[] numbers) { + Map count = new HashMap<>(); + + for (final String s : numbers) { + Pair tokens = parse(s); + final int startRow = Integer.parseInt(tokens.getKey().substring(1)); + final char startCol = tokens.getKey().charAt(0); + final int endRow = Integer.parseInt(tokens.getValue().substring(1)); + final char endCol = tokens.getValue().charAt(0); + for (int i = startRow - 1; i < endRow; ++i) + for (int j = startCol - 'A'; j < endCol - 'A' + 1; ++j) + count.merge(i * width + j, 1, Integer::sum); + } + + return count; + } + + private Pair parse(final String s) { + if (!s.contains(":")) + return new Pair<>(s, s); + + String[] tokens = s.split(":"); + return new Pair<>(tokens[0], tokens[1]); + } +} diff --git a/solutions/631. Design Excel Sum Formula/631.py b/solutions/631. Design Excel Sum Formula/631.py new file mode 100644 index 00000000000..73f701ef413 --- /dev/null +++ b/solutions/631. Design Excel Sum Formula/631.py @@ -0,0 +1,32 @@ +class Cell: + def __init__(self, val: int, posCount: Optional[Dict[Tuple[int, int], int]]): + self.val = val + self.posCount = posCount # {pos, count} + + +class Excel: + def __init__(self, height: int, width: str): + self.sheet = [[Cell(0, None) for i in range(height)] + for _ in range(ord(width) - ord('A') + 1)] + + def set(self, row: int, column: str, val: int) -> None: + self.sheet[row - 1][ord(column) - ord('A')] = Cell(val, None) + + def get(self, row: int, column: str) -> int: + cell = self.sheet[row - 1][ord(column) - ord('A')] + if cell.posCount: + return sum(self.get(*pos) * freq for pos, freq in cell.posCount.items()) + return cell.val + + def sum(self, row: int, column: str, numbers: List[str]) -> int: + self.sheet[row - 1][ord(column) - ord('A')].posCount = self._parse(numbers) + return self.get(row, column) + + def _parse(self, numbers: List[str]): + count = collections.Counter() + for n in numbers: + s, e = n.split(':')[0], n.split(':')[1] if ':' in n else n + for i in range(int(s[1:]), int(e[1:]) + 1): + for j in range(ord(s[0]) - ord('A'), ord(e[0]) - ord('A') + 1): + count[(i, chr(j + ord('A')))] += 1 + return count diff --git a/solutions/632. Smallest Range Covering Elements from K Lists/632.cpp b/solutions/632. Smallest Range Covering Elements from K Lists/632.cpp new file mode 100644 index 00000000000..6b86f66fd14 --- /dev/null +++ b/solutions/632. Smallest Range Covering Elements from K Lists/632.cpp @@ -0,0 +1,42 @@ +struct T { + int i; + int j; + int num; // nums[i][j] + T(int i, int j, int num) : i(i), j(j), num(num) {} +}; + +class Solution { + public: + vector smallestRange(vector>& nums) { + auto compare = [&](const T& a, const T& b) { return a.num > b.num; }; + priority_queue, decltype(compare)> minHeap(compare); + int mn = INT_MAX; + int mx = INT_MIN; + + for (int i = 0; i < nums.size(); ++i) { + const int num = nums[i][0]; + minHeap.emplace(i, 0, num); + mn = min(mn, num); + mx = max(mx, num); + } + + int minRange = mn; + int maxRange = mx; + + while (minHeap.size() == nums.size()) { + const auto [i, j, _] = minHeap.top(); + minHeap.pop(); + if (j + 1 < nums[i].size()) { + minHeap.emplace(i, j + 1, nums[i][j + 1]); + mx = max(mx, nums[i][j + 1]); + mn = minHeap.top().num; + if (mx - mn < maxRange - minRange) { + minRange = mn; + maxRange = mx; + } + } + } + + return {minRange, maxRange}; + } +}; diff --git a/solutions/632. Smallest Range Covering Elements from K Lists/632.java b/solutions/632. Smallest Range Covering Elements from K Lists/632.java new file mode 100644 index 00000000000..d6204ca3c36 --- /dev/null +++ b/solutions/632. Smallest Range Covering Elements from K Lists/632.java @@ -0,0 +1,44 @@ +class T { + public int i; + public int j; + public int num; // nums[i][j] + public T(int i, int j, int num) { + this.i = i; + this.j = j; + this.num = num; + } +} + +class Solution { + public int[] smallestRange(List> nums) { + Queue minHeap = new PriorityQueue<>((a, b) -> a.num - b.num); + int mn = Integer.MAX_VALUE; + int mx = Integer.MIN_VALUE; + + for (int i = 0; i < nums.size(); ++i) { + final int num = nums.get(i).get(0); + minHeap.offer(new T(i, 0, num)); + mn = Math.min(mn, num); + mx = Math.max(mx, num); + } + + int minRange = mn; + int maxRange = mx; + + while (minHeap.size() == nums.size()) { + final int i = minHeap.peek().i; + final int j = minHeap.poll().j; + if (j + 1 < nums.get(i).size()) { + minHeap.offer(new T(i, j + 1, nums.get(i).get(j + 1))); + mx = Math.max(mx, nums.get(i).get(j + 1)); + mn = minHeap.peek().num; + } + if (mx - mn < maxRange - minRange) { + minRange = mn; + maxRange = mx; + } + } + + return new int[] {minRange, maxRange}; + } +} diff --git a/solutions/632. Smallest Range Covering Elements from K Lists/632.py b/solutions/632. Smallest Range Covering Elements from K Lists/632.py new file mode 100644 index 00000000000..21b59cf1f9b --- /dev/null +++ b/solutions/632. Smallest Range Covering Elements from K Lists/632.py @@ -0,0 +1,19 @@ +class Solution: + def smallestRange(self, nums: List[List[int]]) -> List[int]: + minHeap = [(row[0], i, 0) for i, row in enumerate(nums)] + heapq.heapify(minHeap) + + maxRange = max(row[0] for row in nums) + minRange = heapq.nsmallest(1, minHeap)[0][0] + ans = [minRange, maxRange] + + while len(minHeap) == len(nums): + num, r, c = heapq.heappop(minHeap) + if c + 1 < len(nums[r]): + heapq.heappush(minHeap, (nums[r][c + 1], r, c + 1)) + maxRange = max(maxRange, nums[r][c + 1]) + minRange = heapq.nsmallest(1, minHeap)[0][0] + if maxRange - minRange < ans[1] - ans[0]: + ans[0], ans[1] = minRange, maxRange + + return ans diff --git a/solutions/633. Sum of Square Numbers/633.cpp b/solutions/633. Sum of Square Numbers/633.cpp new file mode 100644 index 00000000000..3de5a60d3a7 --- /dev/null +++ b/solutions/633. Sum of Square Numbers/633.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool judgeSquareSum(int c) { + unsigned l = 0; + unsigned r = sqrt(c); + + while (l <= r) { + const unsigned sum = l * l + r * r; + if (sum == c) + return true; + if (sum < c) + ++l; + else + --r; + } + + return false; + } +}; diff --git a/solutions/633. Sum of Square Numbers/633.java b/solutions/633. Sum of Square Numbers/633.java new file mode 100644 index 00000000000..a0c5c5e78d4 --- /dev/null +++ b/solutions/633. Sum of Square Numbers/633.java @@ -0,0 +1,18 @@ +class Solution { + public boolean judgeSquareSum(int c) { + int l = 0; + int r = (int) Math.sqrt(c); + + while (l <= r) { + final int sum = l * l + r * r; + if (sum == c) + return true; + if (sum < c) + ++l; + else + --r; + } + + return false; + } +} diff --git a/solutions/633. Sum of Square Numbers/633.py b/solutions/633. Sum of Square Numbers/633.py new file mode 100644 index 00000000000..37aeb053eca --- /dev/null +++ b/solutions/633. Sum of Square Numbers/633.py @@ -0,0 +1,15 @@ +class Solution: + def judgeSquareSum(self, c: int) -> bool: + l = 0 + r = math.isqrt(c) + + while l <= r: + summ = l * l + r * r + if summ == c: + return True + if summ < c: + l += 1 + else: + r -= 1 + + return False diff --git a/solutions/634. Find the Derangement of An Array/634-2.cpp b/solutions/634. Find the Derangement of An Array/634-2.cpp new file mode 100644 index 00000000000..32ca38c80e5 --- /dev/null +++ b/solutions/634. Find the Derangement of An Array/634-2.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int findDerangement(int n) { + constexpr int kMod = 1'000'000'007; + vector dp(n + 1); + + dp[0] = 1; + + for (int i = 2; i <= n; ++i) + dp[i] = (i - 1L) * (dp[i - 1] + dp[i - 2]) % kMod; + + return dp[n]; + } +}; diff --git a/solutions/634. Find the Derangement of An Array/634-2.java b/solutions/634. Find the Derangement of An Array/634-2.java new file mode 100644 index 00000000000..d0786627c77 --- /dev/null +++ b/solutions/634. Find the Derangement of An Array/634-2.java @@ -0,0 +1,13 @@ +class Solution { + public int findDerangement(int n) { + final int kMod = 1_000_000_007; + int[] dp = new int[n + 1]; + + dp[0] = 1; + + for (int i = 2; i <= n; ++i) + dp[i] = (int) ((i - 1L) * (dp[i - 1] + dp[i - 2]) % kMod); + + return dp[n]; + } +} diff --git a/solutions/634. Find the Derangement of An Array/634-2.py b/solutions/634. Find the Derangement of An Array/634-2.py new file mode 100644 index 00000000000..1321c09e2d5 --- /dev/null +++ b/solutions/634. Find the Derangement of An Array/634-2.py @@ -0,0 +1,9 @@ +class Solution: + def findDerangement(self, n: int) -> int: + kMod = 1_000_000_007 + dp = [1] + [0] * n + + for i in range(2, n + 1): + dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % kMod + + return dp[n] diff --git a/solutions/634. Find the Derangement of An Array/634.cpp b/solutions/634. Find the Derangement of An Array/634.cpp new file mode 100644 index 00000000000..0082a68e5cc --- /dev/null +++ b/solutions/634. Find the Derangement of An Array/634.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int findDerangement(int n) { + vector mem(n + 1); + return findDerangement(n, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + int findDerangement(int i, vector& mem) { + if (i == 0) + return 1; + if (i == 1) + return 0; + if (mem[i] > 0) + return mem[i]; + return mem[i] = (i - 1L) * + (findDerangement(i - 1, mem) + // + findDerangement(i - 2, mem)) % + kMod; + } +}; diff --git a/solutions/634. Find the Derangement of An Array/634.java b/solutions/634. Find the Derangement of An Array/634.java new file mode 100644 index 00000000000..a532ca6f93b --- /dev/null +++ b/solutions/634. Find the Derangement of An Array/634.java @@ -0,0 +1,21 @@ +class Solution { + public int findDerangement(int n) { + int[] mem = new int[n + 1]; + return findDerangement(n, mem); + } + + private static final int kMod = 1_000_000_007; + + private int findDerangement(int i, int[] mem) { + if (i == 0) + return 1; + if (i == 1) + return 0; + if (mem[i] > 0) + return mem[i]; + return mem[i] = (int) ((i - 1L) * + (findDerangement(i - 1, mem) + // + findDerangement(i - 2, mem)) % + kMod); + } +} diff --git a/solutions/634. Find the Derangement of An Array/634.py b/solutions/634. Find the Derangement of An Array/634.py new file mode 100644 index 00000000000..74bba485527 --- /dev/null +++ b/solutions/634. Find the Derangement of An Array/634.py @@ -0,0 +1,13 @@ +class Solution: + def findDerangement(self, n: int) -> int: + kMod = 1_000_000_007 + + @functools.lru_cache(None) + def dp(i: int) -> int: + if i == 0: + return 1 + if i == 1: + return 0 + return (i - 1) * (dp(i - 1) + dp(i - 2)) % kMod + + return dp(n) diff --git a/solutions/635. Design Log Storage System/635.cpp b/solutions/635. Design Log Storage System/635.cpp new file mode 100644 index 00000000000..31681c71684 --- /dev/null +++ b/solutions/635. Design Log Storage System/635.cpp @@ -0,0 +1,27 @@ +class LogSystem { + public: + void put(int id, string timestamp) { + idAndTimestamps.emplace_back(id, timestamp); + } + + vector retrieve(string start, string end, string granularity) { + vector ans; + const int index = granularityToIndices.at(granularity); + const string s = start.substr(0, index); + const string e = end.substr(0, index); + + for (const auto& [id, timestamp] : idAndTimestamps) { + const string& t = timestamp.substr(0, index); + if (s <= t && t <= e) + ans.push_back(id); + } + + return ans; + } + + private: + const unordered_map granularityToIndices{ + {"Year", 4}, {"Month", 7}, {"Day", 10}, + {"Hour", 13}, {"Minute", 16}, {"Second", 19}}; + vector> idAndTimestamps; +}; diff --git a/solutions/635. Design Log Storage System/635.java b/solutions/635. Design Log Storage System/635.java new file mode 100644 index 00000000000..0e00f8e4699 --- /dev/null +++ b/solutions/635. Design Log Storage System/635.java @@ -0,0 +1,33 @@ +class LogSystem { + public LogSystem() { + granularityToIndices.put("Year", 4); + granularityToIndices.put("Month", 7); + granularityToIndices.put("Day", 10); + granularityToIndices.put("Hour", 13); + granularityToIndices.put("Minute", 16); + granularityToIndices.put("Second", 19); + } + + public void put(int id, String timestamp) { + idAndTimestamps.add(new Pair<>(id, timestamp)); + } + + public List retrieve(String start, String end, String granularity) { + List ans = new ArrayList<>(); + final int index = granularityToIndices.get(granularity); + final String s = start.substring(0, index); + final String e = end.substring(0, index); + + for (Pair idAndTimestamp : idAndTimestamps) { + final String timestamp = idAndTimestamp.getValue(); + final String t = timestamp.substring(0, index); + if (t.compareTo(s) >= 0 && t.compareTo(e) <= 0) + ans.add(idAndTimestamp.getKey()); + } + + return ans; + } + + private Map granularityToIndices = new HashMap<>(); + private List> idAndTimestamps = new ArrayList<>(); +} diff --git a/solutions/635. Design Log Storage System/635.py b/solutions/635. Design Log Storage System/635.py new file mode 100644 index 00000000000..fe218daeb4b --- /dev/null +++ b/solutions/635. Design Log Storage System/635.py @@ -0,0 +1,15 @@ +class LogSystem: + def __init__(self): + self.granularityToIndices = {'Year': 4, 'Month': 7, 'Day': 10, + 'Hour': 13, 'Minute': 16, 'Second': 19} + self.idAndTimestamps = [] + + def put(self, id: int, timestamp: str) -> None: + self.idAndTimestamps.append((id, timestamp)) + + def retrieve(self, start: str, end: str, granularity: str) -> List[int]: + index = self.granularityToIndices[granularity] + s = start[:index] + e = end[:index] + return [id for id, timestamp in self.idAndTimestamps + if s <= timestamp[:index] <= e] diff --git a/solutions/636. Exclusive Time of Functions/636.cpp b/solutions/636. Exclusive Time of Functions/636.cpp new file mode 100644 index 00000000000..6a0214f778b --- /dev/null +++ b/solutions/636. Exclusive Time of Functions/636.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector exclusiveTime(int n, vector& logs) { + vector ans(n); + stack stack; // [oldest_id, ..., latest_id] + int prevTime; + + for (const string& log : logs) { + // Get the seperators' indices. + const int colon1 = log.find_first_of(':'); + const int colon2 = log.find_last_of(':'); + // Get the function_id, the label, and the timestamp. + const int id = stoi(log.substr(0, colon1)); // {function_id} + const char label = log[colon1 + 1]; // {"s" ("start") | "e" ("end") } + const int timestamp = stoi(log.substr(colon2 + 1)); // {timestamp} + if (label == 's') { + if (!stack.empty()) + ans[stack.top()] += timestamp - prevTime; + stack.push(id); + prevTime = timestamp; + } else { + ans[stack.top()] += timestamp - prevTime + 1, stack.pop(); + prevTime = timestamp + 1; + } + } + + return ans; + } +}; diff --git a/solutions/636. Exclusive Time of Functions/636.java b/solutions/636. Exclusive Time of Functions/636.java new file mode 100644 index 00000000000..9a57fd339da --- /dev/null +++ b/solutions/636. Exclusive Time of Functions/636.java @@ -0,0 +1,26 @@ +class Solution { + public int[] exclusiveTime(int n, List logs) { + int[] ans = new int[n]; + Deque stack = new ArrayDeque<>(); // [oldest_id, ..., latest_id] + int prevTime = -1; + + for (final String log : logs) { + final String[] splits = log.split(":"); + // Get the function_id, the label, and the timestamp. + final int id = Integer.parseInt(splits[0]); // {function_id} + final char label = splits[1].charAt(0); // {"s" ("start") | "e" ("end") } + final int timestamp = Integer.parseInt(splits[2]); // {timestamp} + if (label == 's') { + if (!stack.isEmpty()) + ans[stack.peek()] += timestamp - prevTime; + stack.push(id); + prevTime = timestamp; + } else { + ans[stack.pop()] += timestamp - prevTime + 1; + prevTime = timestamp + 1; + } + } + + return ans; + } +} diff --git a/solutions/637. Average of Levels in Binary Tree/637.cpp b/solutions/637. Average of Levels in Binary Tree/637.cpp new file mode 100644 index 00000000000..15bad8924f8 --- /dev/null +++ b/solutions/637. Average of Levels in Binary Tree/637.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector averageOfLevels(TreeNode* root) { + vector ans; + queue q{{root}}; + + while (!q.empty()) { + long sum = 0; + const int size = q.size(); + for (int i = 0; i < size; ++i) { + TreeNode* node = q.front(); + q.pop(); + sum += node->val; + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + ans.push_back(sum / (double)size); + } + + return ans; + } +}; diff --git a/solutions/637. Average of Levels in Binary Tree/637.java b/solutions/637. Average of Levels in Binary Tree/637.java new file mode 100644 index 00000000000..f7b0a265f5d --- /dev/null +++ b/solutions/637. Average of Levels in Binary Tree/637.java @@ -0,0 +1,22 @@ +class Solution { + public List averageOfLevels(TreeNode root) { + List ans = new ArrayList<>(); + Queue q = new ArrayDeque<>(Arrays.asList(root)); + + while (!q.isEmpty()) { + long sum = 0; + final int size = q.size(); + for (int i = 0; i < size; ++i) { + TreeNode node = q.poll(); + sum += node.val; + if (node.left != null) + q.offer(node.left); + if (node.right != null) + q.offer(node.right); + } + ans.add(sum / (double) size); + } + + return ans; + } +} diff --git a/solutions/638. Shopping Offers/638.cpp b/solutions/638. Shopping Offers/638.cpp new file mode 100644 index 00000000000..8be8dc6cde1 --- /dev/null +++ b/solutions/638. Shopping Offers/638.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int shoppingOffers(vector& price, vector>& special, + vector& needs) { + return dfs(price, special, needs, 0); + } + + private: + int dfs(const vector& price, const vector>& special, + vector& needs, int s) { + int ans = 0; + for (int i = 0; i < price.size(); ++i) + ans += price[i] * needs[i]; + + for (int i = s; i < special.size(); ++i) + if (isValid(special[i], needs)) { + // Use the special[i]. + for (int j = 0; j < needs.size(); ++j) + needs[j] -= special[i][j]; + ans = min(ans, special[i].back() + dfs(price, special, needs, i)); + // Unuse the special[i] (backtracking). + for (int j = 0; j < needs.size(); ++j) + needs[j] += special[i][j]; + } + + return ans; + } + + // Returns true if this special offer is a valid one. + bool isValid(const vector& offer, const vector& needs) { + for (int i = 0; i < needs.size(); ++i) + if (needs[i] < offer[i]) + return false; + return true; + } +}; diff --git a/solutions/638. Shopping Offers/638.java b/solutions/638. Shopping Offers/638.java new file mode 100644 index 00000000000..b24b6432daa --- /dev/null +++ b/solutions/638. Shopping Offers/638.java @@ -0,0 +1,34 @@ +class Solution { + public int shoppingOffers(List price, List> special, List needs) { + return dfs(price, special, needs, 0); + } + + private int dfs(List price, List> special, List needs, int s) { + int ans = 0; + for (int i = 0; i < needs.size(); ++i) + ans += needs.get(i) * price.get(i); + + for (int i = s; i < special.size(); ++i) { + List offer = special.get(i); + if (isValid(offer, needs)) { + // Use the special[i]. + for (int j = 0; j < needs.size(); ++j) + needs.set(j, needs.get(j) - offer.get(j)); + ans = Math.min(ans, offer.get(offer.size() - 1) + dfs(price, special, needs, i)); + // Unuse the special[i] (backtracking). + for (int j = 0; j < needs.size(); ++j) + needs.set(j, needs.get(j) + offer.get(j)); + } + } + + return ans; + } + + // Returns true if this special offer is a valid one. + private boolean isValid(List offer, List needs) { + for (int i = 0; i < needs.size(); ++i) + if (offer.get(i) > needs.get(i)) + return false; + return true; + } +} diff --git a/solutions/638. Shopping Offers/638.py b/solutions/638. Shopping Offers/638.py new file mode 100644 index 00000000000..ef1b56ba414 --- /dev/null +++ b/solutions/638. Shopping Offers/638.py @@ -0,0 +1,21 @@ +class Solution: + def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int: + def dfs(s: int) -> int: + ans = 0 + for i, need in enumerate(needs): + ans += need * price[i] + + for i in range(s, len(special)): + offer = special[i] + if all(offer[j] <= need for j, need in enumerate(needs)): + # Use the special[i]. + for j in range(len(needs)): + needs[j] -= offer[j] + ans = min(ans, offer[-1] + dfs(i)) + # Unuse the special[i] (backtracking). + for j in range(len(needs)): + needs[j] += offer[j] + + return ans + + return dfs(0) diff --git a/solutions/639. Decode Ways II/639-2.cpp b/solutions/639. Decode Ways II/639-2.cpp new file mode 100644 index 00000000000..b09131955a2 --- /dev/null +++ b/solutions/639. Decode Ways II/639-2.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + int numDecodings(string s) { + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + long prev2 = 1; + long prev1 = count(s[n - 1]); + + for (int i = n - 2; i >= 0; --i) { + long dp = count(s[i], s[i + 1]) * prev2 + count(s[i]) * prev1; + dp %= kMod; + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } + + private: + int count(char c) { + if (c == '*') + return 9; + return c != '0'; + } + + int count(char c1, char c2) { + if (c1 == '*' && c2 == '*') // c1c2: [11-19, 21-26] + return 15; + if (c1 == '*') { + if ('0' <= c2 && c2 <= '6') // c1: [1-2] + return 2; + else // c1: [1] + return 1; + } + if (c2 == '*') { + if (c1 == '1') // c2: [1-9] + return 9; + if (c1 == '2') // c2: [1-6] + return 6; + return 0; + } + return c1 == '1' || (c1 == '2' && c2 <= '6'); + } +}; diff --git a/solutions/639. Decode Ways II/639-2.java b/solutions/639. Decode Ways II/639-2.java new file mode 100644 index 00000000000..32f2f5b19f0 --- /dev/null +++ b/solutions/639. Decode Ways II/639-2.java @@ -0,0 +1,42 @@ +class Solution { + public int numDecodings(String s) { + final int kMod = 1_000_000_007; + final int n = s.length(); + long prev2 = 1; + long prev1 = count(s.charAt(n - 1)); + + for (int i = n - 2; i >= 0; --i) { + long dp = count(s.charAt(i), s.charAt(i + 1)) * prev2 + count(s.charAt(i)) * prev1; + dp %= kMod; + prev2 = prev1; + prev1 = dp; + } + + return (int) prev1; + } + + private int count(char c) { + if (c == '*') + return 9; + return c == '0' ? 0 : 1; + } + + private int count(char c1, char c2) { + if (c1 == '*' && c2 == '*') + return 15; // c1c2: [11-19, 21-26] + if (c1 == '*') { + if ('0' <= c2 && c2 <= '6') + return 2; // c1: [1-2] + else + return 1; // c1: [1] + } + if (c2 == '*') { + if (c1 == '1') + return 9; // c2: [1-9] + if (c1 == '2') + return 6; // c2: [1-6] + return 0; + } + return (c1 == '1' || (c1 == '2' && c2 <= '6')) ? 1 : 0; + } +} diff --git a/solutions/639. Decode Ways II/639.cpp b/solutions/639. Decode Ways II/639.cpp new file mode 100644 index 00000000000..3f1639f3ef5 --- /dev/null +++ b/solutions/639. Decode Ways II/639.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int numDecodings(string s) { + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + // dp[i] := the number of ways to decode s[i..n) + vector dp(n + 1); + dp.back() = 1; + dp[n - 1] = count(s[n - 1]); + + for (int i = n - 2; i >= 0; --i) { + dp[i] += count(s[i], s[i + 1]) * dp[i + 2]; + dp[i] += count(s[i]) * dp[i + 1]; + dp[i] %= kMod; + } + + return dp[0]; + } + + private: + int count(char c) { + if (c == '*') + return 9; + return c != '0'; + } + + int count(char c1, char c2) { + if (c1 == '*' && c2 == '*') // c1c2: [11-19, 21-26] + return 15; + if (c1 == '*') { + if ('0' <= c2 && c2 <= '6') // c1: [1-2] + return 2; + else // c1: [1] + return 1; + } + if (c2 == '*') { + if (c1 == '1') // c2: [1-9] + return 9; + if (c1 == '2') // c2: [1-6] + return 6; + return 0; + } + return c1 == '1' || (c1 == '2' && c2 <= '6'); + } +}; diff --git a/solutions/639. Decode Ways II/639.java b/solutions/639. Decode Ways II/639.java new file mode 100644 index 00000000000..2f226082261 --- /dev/null +++ b/solutions/639. Decode Ways II/639.java @@ -0,0 +1,43 @@ +class Solution { + public int numDecodings(String s) { + final int kMod = 1_000_000_007; + final int n = s.length(); + // dp[i] := the number of ways to decode s[i..n - 1] + long[] dp = new long[n + 1]; + dp[n] = 1; + dp[n - 1] = count(s.charAt(n - 1)); + + for (int i = n - 2; i >= 0; --i) { + dp[i] += count(s.charAt(i), s.charAt(i + 1)) * dp[i + 2]; + dp[i] += count(s.charAt(i)) * dp[i + 1]; + dp[i] %= kMod; + } + + return (int) dp[0]; + } + + private int count(char c) { + if (c == '*') + return 9; + return c == '0' ? 0 : 1; + } + + private int count(char c1, char c2) { + if (c1 == '*' && c2 == '*') + return 15; // c1c2: [11-19, 21-26] + if (c1 == '*') { + if ('0' <= c2 && c2 <= '6') + return 2; // c1: [1-2] + else + return 1; // c1: [1] + } + if (c2 == '*') { + if (c1 == '1') + return 9; // c2: [1-9] + if (c1 == '2') + return 6; // c2: [1-6] + return 0; + } + return (c1 == '1' || (c1 == '2' && c2 <= '6')) ? 1 : 0; + } +} diff --git a/solutions/64. Minimum Path Sum/64.cpp b/solutions/64. Minimum Path Sum/64.cpp new file mode 100644 index 00000000000..02fe07e9859 --- /dev/null +++ b/solutions/64. Minimum Path Sum/64.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int minPathSum(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i > 0 && j > 0) + grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]); + else if (i > 0) + grid[i][0] += grid[i - 1][0]; + else if (j > 0) + grid[0][j] += grid[0][j - 1]; + + return grid[m - 1][n - 1]; + } +}; diff --git a/solutions/64. Minimum Path Sum/64.java b/solutions/64. Minimum Path Sum/64.java new file mode 100644 index 00000000000..1b237e7d9b0 --- /dev/null +++ b/solutions/64. Minimum Path Sum/64.java @@ -0,0 +1,17 @@ +class Solution { + public int minPathSum(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (i > 0 && j > 0) + grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); + else if (i > 0) + grid[i][0] += grid[i - 1][0]; + else if (j > 0) + grid[0][j] += grid[0][j - 1]; + + return grid[m - 1][n - 1]; + } +} diff --git a/solutions/64. Minimum Path Sum/64.py b/solutions/64. Minimum Path Sum/64.py new file mode 100644 index 00000000000..ad9e5119167 --- /dev/null +++ b/solutions/64. Minimum Path Sum/64.py @@ -0,0 +1,15 @@ +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + + for i in range(m): + for j in range(n): + if i > 0 and j > 0: + grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]) + elif i > 0: + grid[i][0] += grid[i - 1][0] + elif j > 0: + grid[0][j] += grid[0][j - 1] + + return grid[m - 1][n - 1] diff --git a/solutions/640. Solve the Equation/640.cpp b/solutions/640. Solve the Equation/640.cpp new file mode 100644 index 00000000000..5e486e65e72 --- /dev/null +++ b/solutions/640. Solve the Equation/640.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + string solveEquation(string equation) { + const string lhsEquation = equation.substr(0, equation.find('=')); + const string rhsEquation = equation.substr(equation.find('=') + 1); + const auto& [lhsCoefficient, lhsConstant] = calculate(lhsEquation); + const auto& [rhsCoefficient, rhsConstant] = calculate(rhsEquation); + const int coefficient = lhsCoefficient - rhsCoefficient; + const int constant = rhsConstant - lhsConstant; + + if (coefficient == 0 && constant == 0) + return "Infinite solutions"; + if (coefficient == 0 && constant != 0) + return "No solution"; + return "x=" + to_string(constant / coefficient); + } + + private: + pair calculate(const string& s) { + int coefficient = 0; + int constant = 0; + int num = 0; + int sign = 1; + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + if (isdigit(c)) + num = num * 10 + (c - '0'); + else if (c == '+' || c == '-') { + constant += sign * num; + sign = c == '+' ? 1 : -1; + num = 0; + } else { + if (i > 0 && num == 0 && s[i - 1] == '0') + continue; + coefficient += num == 0 ? sign : sign * num; + num = 0; + } + } + + return {coefficient, constant + sign * num}; + } +}; diff --git a/solutions/640. Solve the Equation/640.java b/solutions/640. Solve the Equation/640.java new file mode 100644 index 00000000000..903919c65ef --- /dev/null +++ b/solutions/640. Solve the Equation/640.java @@ -0,0 +1,40 @@ +class Solution { + public String solveEquation(String equation) { + String[] equations = equation.split("="); + int[] lhs = calculate(equations[0]); + int[] rhs = calculate(equations[1]); + int coefficient = lhs[0] - rhs[0]; + int constant = rhs[1] - lhs[1]; + + if (coefficient == 0 && constant == 0) + return "Infinite solutions"; + if (coefficient == 0 && constant != 0) + return "No solution"; + return "x=" + constant / coefficient; + } + + private int[] calculate(final String s) { + int coefficient = 0; + int constant = 0; + int num = 0; + int sign = 1; + + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (Character.isDigit(c)) + num = num * 10 + (c - '0'); + else if (c == '+' || c == '-') { + constant += sign * num; + sign = c == '+' ? 1 : -1; + num = 0; + } else { + if (i > 0 && num == 0 && s.charAt(i - 1) == '0') + continue; + coefficient += num == 0 ? sign : sign * num; + num = 0; + } + } + + return new int[] {coefficient, constant + sign * num}; + } +} diff --git a/solutions/640. Solve the Equation/640.py b/solutions/640. Solve the Equation/640.py new file mode 100644 index 00000000000..72b59d4264e --- /dev/null +++ b/solutions/640. Solve the Equation/640.py @@ -0,0 +1,34 @@ +class Solution: + def solveEquation(self, equation: str) -> str: + def calculate(s: str) -> tuple: + coefficient = 0 + constant = 0 + num = 0 + sign = 1 + + for i, c in enumerate(s): + if c.isdigit(): + num = num * 10 + ord(c) - ord('0') + elif c in '+-': + constant += sign * num + sign = 1 if c == '+' else -1 + num = 0 + else: + if i > 0 and num == 0 and s[i - 1] == '0': + continue + coefficient += sign if num == 0 else sign * num + num = 0 + + return coefficient, constant + sign * num + + lhsEquation, rhsEquation = equation.split('=') + lhsCoefficient, lhsConstant = calculate(lhsEquation) + rhsCoefficient, rhsConstant = calculate(rhsEquation) + coefficient = lhsCoefficient - rhsCoefficient + constant = rhsConstant - lhsConstant + + if coefficient == 0 and constant == 0: + return "Infinite solutions" + if coefficient == 0 and constant != 0: + return "No solution" + return "x=" + str(constant // coefficient) diff --git a/solutions/641. Design Circular Deque/641.cpp b/solutions/641. Design Circular Deque/641.cpp new file mode 100644 index 00000000000..e5ad17c211d --- /dev/null +++ b/solutions/641. Design Circular Deque/641.cpp @@ -0,0 +1,78 @@ +class MyCircularDeque { + public: + /** Initialize your data structure here. Set the size of the deque to be k. */ + MyCircularDeque(int k) : k(k), q(k), rear(k - 1) {} + + /** Adds an item at the front of Deque. Return true if the operation is + * successful. */ + bool insertFront(int value) { + if (isFull()) + return false; + + front = (--front + k) % k; + q[front] = value; + ++size; + return true; + } + + /** Adds an item at the rear of Deque. Return true if the operation is + * successful. */ + bool insertLast(int value) { + if (isFull()) + return false; + + rear = ++rear % k; + q[rear] = value; + ++size; + return true; + } + + /** Deletes an item from the front of Deque. Return true if the operation is + * successful. */ + bool deleteFront() { + if (isEmpty()) + return false; + + front = ++front % k; + --size; + return true; + } + + /** Deletes an item from the rear of Deque. Return true if the operation is + * successful. */ + bool deleteLast() { + if (isEmpty()) + return false; + + rear = (--rear + k) % k; + --size; + return true; + } + + /** Get the front item from the deque. */ + int getFront() { + return isEmpty() ? -1 : q[front]; + } + + /** Get the last item from the deque. */ + int getRear() { + return isEmpty() ? -1 : q[rear]; + } + + /** Checks whether the circular deque is empty or not. */ + bool isEmpty() { + return size == 0; + } + + /** Checks whether the circular deque is full or not. */ + bool isFull() { + return size == k; + } + + private: + const int k; + vector q; + int size = 0; + int front = 0; + int rear; +}; diff --git a/solutions/641. Design Circular Deque/641.java b/solutions/641. Design Circular Deque/641.java new file mode 100644 index 00000000000..3fb40a7070d --- /dev/null +++ b/solutions/641. Design Circular Deque/641.java @@ -0,0 +1,76 @@ +class MyCircularDeque { + /** Initialize your data structure here. Set the size of the deque to be k. */ + public MyCircularDeque(int k) { + this.k = k; + this.q = new int[k]; + this.rear = k - 1; + } + + /** Adds an item at the front of Deque. Return true if the operation is successful. */ + public boolean insertFront(int value) { + if (isFull()) + return false; + + front = (--front + k) % k; + q[front] = value; + ++size; + return true; + } + + /** Adds an item at the rear of Deque. Return true if the operation is successful. */ + public boolean insertLast(int value) { + if (isFull()) + return false; + + rear = ++rear % k; + q[rear] = value; + ++size; + return true; + } + + /** Deletes an item from the front of Deque. Return true if the operation is successful. */ + public boolean deleteFront() { + if (isEmpty()) + return false; + + front = ++front % k; + --size; + return true; + } + + /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ + public boolean deleteLast() { + if (isEmpty()) + return false; + + rear = (--rear + k) % k; + --size; + return true; + } + + /** Get the front item from the deque. */ + public int getFront() { + return isEmpty() ? -1 : q[front]; + } + + /** Get the last item from the deque. */ + public int getRear() { + return isEmpty() ? -1 : q[rear]; + } + + /** Checks whether the circular deque is empty or not. */ + public boolean isEmpty() { + return size == 0; + } + + /** Checks whether the circular deque is full or not. */ + public boolean isFull() { + return size == k; + } + + private final int k; + private int[] q; + private int size = 0; + private int front = 0; + private int rear; +} diff --git a/solutions/642. Design Search Autocomplete System/642.java b/solutions/642. Design Search Autocomplete System/642.java new file mode 100644 index 00000000000..c95326dffbe --- /dev/null +++ b/solutions/642. Design Search Autocomplete System/642.java @@ -0,0 +1,73 @@ +class TrieNode implements Comparable { + public TrieNode[] children = new TrieNode[128]; + public String s = null; + public int time = 0; + public List top3 = new ArrayList<>(); + + public int compareTo(TrieNode o) { + if (this.time == o.time) + return this.s.compareTo(o.s); + return o.time - this.time; + } + + public void update(TrieNode node) { + if (!this.top3.contains(node)) + this.top3.add(node); + Collections.sort(top3); + if (top3.size() > 3) + top3.remove(top3.size() - 1); + } +} + +class AutocompleteSystem { + public AutocompleteSystem(String[] sentences, int[] times) { + for (int i = 0; i < sentences.length; ++i) + insert(sentences[i], times[i]); + } + + public List input(char c) { + if (c == '#') { + insert(sb.toString(), 1); + curr = root; + sb = new StringBuilder(); + return new ArrayList<>(); + } + + sb.append(c); + + if (curr != null) + curr = curr.children[c]; + if (curr == null) + return new ArrayList<>(); + + List ans = new ArrayList<>(); + + for (TrieNode node : curr.top3) + ans.add(node.s); + + return ans; + } + + private TrieNode root = new TrieNode(); + private TrieNode curr = root; + private StringBuilder sb = new StringBuilder(); + + private void insert(final String s, int time) { + TrieNode node = root; + for (final char c : s.toCharArray()) { + if (node.children[c] == null) + node.children[c] = new TrieNode(); + node = node.children[c]; + } + node.s = s; + node.time += time; + + // Walk the path again and update the node with leaf node + TrieNode leaf = node; + node = root; + for (final char c : s.toCharArray()) { + node = node.children[c]; + node.update(leaf); + } + } +} diff --git a/solutions/642. Design Search Autocomplete System/642.py b/solutions/642. Design Search Autocomplete System/642.py new file mode 100644 index 00000000000..ccf4819f698 --- /dev/null +++ b/solutions/642. Design Search Autocomplete System/642.py @@ -0,0 +1,56 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.s: Optional[str] = None + self.time = 0 + self.top3: List[TrieNode] = [] + + def __lt__(self, other): + if self.time == other.time: + return self.s < other.s + return self.time > other.time + + def update(self, node) -> None: + if node not in self.top3: + self.top3.append(node) + self.top3.sort() + if len(self.top3) > 3: + self.top3.pop() + + +class AutocompleteSystem: + def __init__(self, sentences: List[str], times: List[int]): + self.root = TrieNode() + self.curr = self.root + self.s: List[chr] = [] + + for sentence, time in zip(sentences, times): + self._insert(sentence, time) + + def input(self, c: str) -> List[str]: + if c == '#': + self._insert(''.join(self.s), 1) + self.curr = self.root + self.s = [] + return [] + + self.s.append(c) + + if self.curr: + self.curr = self.curr.children.get(c, None) + if not self.curr: + return [] + return [node.s for node in self.curr.top3] + + def _insert(self, sentence: str, time: int) -> None: + node = self.root + for c in sentence: + node = node.children.setdefault(c, TrieNode()) + node.s = sentence + node.time += time + + leaf = node + node: TrieNode = self.root + for c in sentence: + node = node.children[c] + node.update(leaf) diff --git a/solutions/643. Maximum Average Subarray I/643.cpp b/solutions/643. Maximum Average Subarray I/643.cpp new file mode 100644 index 00000000000..9130b317e93 --- /dev/null +++ b/solutions/643. Maximum Average Subarray I/643.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + double findMaxAverage(vector& nums, int k) { + double sum = accumulate(nums.begin(), nums.begin() + k, 0); + double ans = sum; + + for (int i = k; i < nums.size(); ++i) { + sum += nums[i] - nums[i - k]; + ans = max(ans, sum); + } + + return ans / k; + } +}; diff --git a/solutions/643. Maximum Average Subarray I/643.java b/solutions/643. Maximum Average Subarray I/643.java new file mode 100644 index 00000000000..67fe01151ed --- /dev/null +++ b/solutions/643. Maximum Average Subarray I/643.java @@ -0,0 +1,15 @@ +class Solution { + public double findMaxAverage(int[] nums, int k) { + double sum = 0; + for (int i = 0; i < k; ++i) + sum += nums[i]; + double ans = sum; + + for (int i = k; i < nums.length; ++i) { + sum += nums[i] - nums[i - k]; + ans = Math.max(ans, sum); + } + + return ans / k; + } +} diff --git a/solutions/643. Maximum Average Subarray I/643.py b/solutions/643. Maximum Average Subarray I/643.py new file mode 100644 index 00000000000..c4887be900d --- /dev/null +++ b/solutions/643. Maximum Average Subarray I/643.py @@ -0,0 +1,10 @@ +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + summ = sum(nums[:k]) + ans = summ + + for i in range(k, len(nums)): + summ += nums[i] - nums[i - k] + ans = max(ans, summ) + + return ans / k diff --git a/solutions/644. Maximum Average Subarray II/644.cpp b/solutions/644. Maximum Average Subarray II/644.cpp new file mode 100644 index 00000000000..700841033ca --- /dev/null +++ b/solutions/644. Maximum Average Subarray II/644.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + double findMaxAverage(vector& nums, int k) { + constexpr double kErr = 1e-5; + double l = ranges::min(nums); + double r = ranges::max(nums); + + while (r - l > kErr) { + const double m = (l + r) / 2; + if (check(nums, k, m)) + l = m; + else + r = m; + } + + return l; + } + + private: + // Returns true if there's a subarray, where its length >= k and its average + // sum >= m. + bool check(const vector& nums, int k, double m) { + double sum = 0; + double prevSum = 0; + double minPrevSum = 0; + + for (int i = 0; i < nums.size(); ++i) { + // Need to substract m for each `num` so that we can check if the sum of + // the subarray >= 0. + sum += nums[i] - m; + if (i >= k) { + prevSum += nums[i - k] - m; + minPrevSum = min(minPrevSum, prevSum); + } + if (i + 1 >= k && sum >= minPrevSum) + return true; + } + + return false; + }; +}; diff --git a/solutions/644. Maximum Average Subarray II/644.java b/solutions/644. Maximum Average Subarray II/644.java new file mode 100644 index 00000000000..d2e0129928e --- /dev/null +++ b/solutions/644. Maximum Average Subarray II/644.java @@ -0,0 +1,39 @@ +class Solution { + public double findMaxAverage(int[] nums, int k) { + final double kErr = 1e-5; + double l = (double) Arrays.stream(nums).min().getAsInt(); + double r = (double) Arrays.stream(nums).max().getAsInt(); + + while (r - l > kErr) { + final double m = (l + r) / 2; + if (check(nums, k, m)) + l = m; + else + r = m; + } + + return l; + } + + // Returns true if there's a subarray, where its length >= k and its average + // sum >= m. + private boolean check(int[] nums, int k, double m) { + double sum = 0; + double prevSum = 0; + double minPrevSum = 0; + + for (int i = 0; i < nums.length; ++i) { + // Need to substract m for each `num` so that we can check if the sum of + // the subarray >= 0. + sum += nums[i] - m; + if (i >= k) { + prevSum += nums[i - k] - m; + minPrevSum = Math.min(minPrevSum, prevSum); + } + if (i + 1 >= k && sum >= minPrevSum) + return true; + } + + return false; + } +} diff --git a/solutions/644. Maximum Average Subarray II/644.py b/solutions/644. Maximum Average Subarray II/644.py new file mode 100644 index 00000000000..78f9ebdcfce --- /dev/null +++ b/solutions/644. Maximum Average Subarray II/644.py @@ -0,0 +1,35 @@ +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + kErr = 1e-5 + l = min(nums) + r = max(nums) + + def check(m: float) -> bool: + """ + Returns True if there's a subarray, where its length >= k and its average + sum >= m. + """ + summ = 0 + prevSum = 0 + minPrevSum = 0 + + for i, num in enumerate(nums): + # Need to substract m for each `num` so that we can check if the sum of + # the subarray >= 0. + summ += num - m + if i >= k: + prevSum += nums[i - k] - m + minPrevSum = min(minPrevSum, prevSum) + if i + 1 >= k and summ >= minPrevSum: + return True + + return False + + while r - l > kErr: + m = (l + r) / 2 + if check(m): + l = m + else: + r = m + + return l diff --git a/solutions/645. Set Mismatch/645.cpp b/solutions/645. Set Mismatch/645.cpp new file mode 100644 index 00000000000..bb2b1b5c84b --- /dev/null +++ b/solutions/645. Set Mismatch/645.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector findErrorNums(vector& nums) { + int duplicate; + + for (const int num : nums) + if (nums[abs(num) - 1] < 0) + duplicate = abs(num); + else + nums[abs(num) - 1] *= -1; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] > 0) + return {duplicate, i + 1}; + + throw; + } +}; diff --git a/solutions/645. Set Mismatch/645.java b/solutions/645. Set Mismatch/645.java new file mode 100644 index 00000000000..3c5e1261297 --- /dev/null +++ b/solutions/645. Set Mismatch/645.java @@ -0,0 +1,18 @@ +class Solution { + public int[] findErrorNums(int[] nums) { + int duplicate = 0; + + for (final int num : nums) { + if (nums[Math.abs(num) - 1] < 0) + duplicate = Math.abs(num); + else + nums[Math.abs(num) - 1] *= -1; + } + + for (int i = 0; i < nums.length; ++i) + if (nums[i] > 0) + return new int[] {duplicate, i + 1}; + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/645. Set Mismatch/645.py b/solutions/645. Set Mismatch/645.py new file mode 100644 index 00000000000..a0fcb52c35a --- /dev/null +++ b/solutions/645. Set Mismatch/645.py @@ -0,0 +1,11 @@ +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + for num in nums: + if nums[abs(num) - 1] < 0: + duplicate = abs(num) + else: + nums[abs(num) - 1] *= -1 + + for i, num in enumerate(nums): + if num > 0: + return [duplicate, i + 1] diff --git a/solutions/646. Maximum Length of Pair Chain/646.cpp b/solutions/646. Maximum Length of Pair Chain/646.cpp new file mode 100644 index 00000000000..b95ffeebdb0 --- /dev/null +++ b/solutions/646. Maximum Length of Pair Chain/646.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int findLongestChain(vector>& pairs) { + int ans = 0; + int prevEnd = INT_MIN; + + ranges::sort(pairs, + [](const auto& a, const auto& b) { return a[1] < b[1]; }); + + for (const vector& pair : pairs) + if (pair[0] > prevEnd) { + ++ans; + prevEnd = pair[1]; + } + + return ans; + } +}; diff --git a/solutions/646. Maximum Length of Pair Chain/646.java b/solutions/646. Maximum Length of Pair Chain/646.java new file mode 100644 index 00000000000..672d4af8583 --- /dev/null +++ b/solutions/646. Maximum Length of Pair Chain/646.java @@ -0,0 +1,18 @@ +import java.util.Arrays; + +class Solution { + public int findLongestChain(int[][] pairs) { + int ans = 0; + int prevEnd = Integer.MIN_VALUE; + + Arrays.sort(pairs, (a, b) -> a[1] - b[1]); + + for (int[] pair : pairs) + if (pair[0] > prevEnd) { + ++ans; + prevEnd = pair[1]; + } + + return ans; + } +} diff --git a/solutions/646. Maximum Length of Pair Chain/646.py b/solutions/646. Maximum Length of Pair Chain/646.py new file mode 100644 index 00000000000..f23eba8de29 --- /dev/null +++ b/solutions/646. Maximum Length of Pair Chain/646.py @@ -0,0 +1,11 @@ +class Solution: + def findLongestChain(self, pairs: List[List[int]]) -> int: + ans = 0 + prevEnd = -math.inf + + for s, e in sorted(pairs, key=lambda x: x[1]): + if s > prevEnd: + ans += 1 + prevEnd = e + + return ans diff --git a/solutions/647. Palindromic Substrings/647.cpp b/solutions/647. Palindromic Substrings/647.cpp new file mode 100644 index 00000000000..c716b2a9e9f --- /dev/null +++ b/solutions/647. Palindromic Substrings/647.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int countSubstrings(string s) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) { + ans += extendPalindromes(s, i, i); + ans += extendPalindromes(s, i, i + 1); + } + + return ans; + } + + private: + int extendPalindromes(const string& s, int l, int r) { + int count = 0; + + while (l >= 0 && r < s.length() && s[l] == s[r]) { + ++count; + --l; + ++r; + } + + return count; + } +}; diff --git a/solutions/647. Palindromic Substrings/647.java b/solutions/647. Palindromic Substrings/647.java new file mode 100644 index 00000000000..ae4d4e3e007 --- /dev/null +++ b/solutions/647. Palindromic Substrings/647.java @@ -0,0 +1,24 @@ +class Solution { + public int countSubstrings(String s) { + int ans = 0; + + for (int i = 0; i < s.length(); ++i) { + ans += extendPalindromes(s, i, i); + ans += extendPalindromes(s, i, i + 1); + } + + return ans; + } + + private int extendPalindromes(final String s, int l, int r) { + int count = 0; + + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { + ++count; + --l; + ++r; + } + + return count; + } +} diff --git a/solutions/647. Palindromic Substrings/647.py b/solutions/647. Palindromic Substrings/647.py new file mode 100644 index 00000000000..900eadcd066 --- /dev/null +++ b/solutions/647. Palindromic Substrings/647.py @@ -0,0 +1,19 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + def extendPalindromes(l: int, r: int) -> int: + count = 0 + + while l >= 0 and r < len(s) and s[l] == s[r]: + count += 1 + l -= 1 + r += 1 + + return count + + ans = 0 + + for i in range(len(s)): + ans += extendPalindromes(i, i) + ans += extendPalindromes(i, i + 1) + + return ans diff --git a/solutions/648. Replace Words/648.cpp b/solutions/648. Replace Words/648.cpp new file mode 100644 index 00000000000..e7f01fb91cc --- /dev/null +++ b/solutions/648. Replace Words/648.cpp @@ -0,0 +1,49 @@ +struct TrieNode { + vector> children; + const string* word = nullptr; + TrieNode() : children(26) {} +}; + +class Solution { + public: + string replaceWords(vector& dictionary, string sentence) { + for (const string& word : dictionary) + insert(word); + + string ans; + istringstream iss(sentence); + + for (string s; iss >> s;) + ans += search(s) + ' '; + ans.pop_back(); + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->word = &word; + } + + string search(const string& word) { + shared_ptr node = root; + for (const char c : word) { + if (node->word) + return *node->word; + const int i = c - 'a'; + if (node->children[i] == nullptr) + return word; + node = node->children[i]; + } + return word; + } +}; diff --git a/solutions/648. Replace Words/648.java b/solutions/648. Replace Words/648.java new file mode 100644 index 00000000000..1b4b20a1e86 --- /dev/null +++ b/solutions/648. Replace Words/648.java @@ -0,0 +1,45 @@ +class TrieNode { + private TrieNode[] children = new TrieNode[26]; + private String word; +} + +class Solution { + public String replaceWords(List dictionary, String sentence) { + StringBuilder sb = new StringBuilder(); + + for (final String word : dictionary) + insert(word); + + final String[] words = sentence.split(" "); + for (final String word : words) + sb.append(' ').append(search(word)); + + return sb.substring(1).toString(); + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.word = word; + } + + private String search(final String word) { + TrieNode node = root; + for (char c : word.toCharArray()) { + if (node.word != null) + return node.word; + final int i = c - 'a'; + if (node.children[i] == null) + return word; + node = node.children[i]; + } + return word; + } +} diff --git a/solutions/648. Replace Words/648.py b/solutions/648. Replace Words/648.py new file mode 100644 index 00000000000..c361a2fe4dd --- /dev/null +++ b/solutions/648. Replace Words/648.py @@ -0,0 +1,28 @@ +class Solution: + def __init__(self): + self.root = {} + + def insert(self, word: str) -> None: + node = self.root + for c in word: + if c not in node: + node[c] = {} + node = node[c] + node['word'] = word + + def search(self, word: str) -> str: + node = self.root + for c in word: + if 'word' in node: + return node['word'] + if c not in node: + return word + node = node[c] + return word + + def replaceWords(self, dictionary: List[str], sentence: str) -> str: + for word in dictionary: + self.insert(word) + + words = sentence.split(' ') + return ' '.join([self.search(word) for word in words]) diff --git a/solutions/649. Dota2 Senate/649.cpp b/solutions/649. Dota2 Senate/649.cpp new file mode 100644 index 00000000000..55de142e845 --- /dev/null +++ b/solutions/649. Dota2 Senate/649.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string predictPartyVictory(string senate) { + const int n = senate.length(); + queue qR; + queue qD; + + for (int i = 0; i < n; ++i) + if (senate[i] == 'R') + qR.push(i); + else + qD.push(i); + + while (!qR.empty() && !qD.empty()) { + const int indexR = qR.front(); + qR.pop(); + const int indexD = qD.front(); + qD.pop(); + if (indexR < indexD) + qR.push(indexR + n); + else + qD.push(indexD + n); + } + + return qR.empty() ? "Dire" : "Radiant"; + } +}; diff --git a/solutions/65. Valid Number/65.cpp b/solutions/65. Valid Number/65.cpp new file mode 100644 index 00000000000..62604efda4e --- /dev/null +++ b/solutions/65. Valid Number/65.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + bool isNumber(string s) { + trim(s); + if (s.empty()) + return false; + + bool seenNum = false; + bool seenDot = false; + bool seenE = false; + + for (int i = 0; i < s.length(); ++i) { + switch (s[i]) { + case '.': + if (seenDot || seenE) + return false; + seenDot = true; + break; + case 'e': + case 'E': + if (seenE || !seenNum) + return false; + seenE = true; + seenNum = false; + break; + case '+': + case '-': + if (i > 0 && s[i - 1] != 'e' && s[i - 1] != 'E') + return false; + seenNum = false; + break; + default: + if (!isdigit(s[i])) + return false; + seenNum = true; + } + } + + return seenNum; + } + + private: + void trim(string& s) { + s.erase(0, s.find_first_not_of(' ')); + s.erase(s.find_last_not_of(' ') + 1); + } +}; diff --git a/solutions/65. Valid Number/65.java b/solutions/65. Valid Number/65.java new file mode 100644 index 00000000000..7494979aadb --- /dev/null +++ b/solutions/65. Valid Number/65.java @@ -0,0 +1,40 @@ +class Solution { + public boolean isNumber(String s) { + s = s.trim(); + if (s.isEmpty()) + return false; + + boolean seenNum = false; + boolean seenDot = false; + boolean seenE = false; + + for (int i = 0; i < s.length(); ++i) { + switch (s.charAt(i)) { + case '.': + if (seenDot || seenE) + return false; + seenDot = true; + break; + case 'e': + case 'E': + if (seenE || !seenNum) + return false; + seenE = true; + seenNum = false; + break; + case '+': + case '-': + if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') + return false; + seenNum = false; + break; + default: + if (!Character.isDigit(s.charAt(i))) + return false; + seenNum = true; + } + } + + return seenNum; + } +} diff --git a/solutions/65. Valid Number/65.py b/solutions/65. Valid Number/65.py new file mode 100644 index 00000000000..530761c732a --- /dev/null +++ b/solutions/65. Valid Number/65.py @@ -0,0 +1,30 @@ +class Solution: + def isNumber(self, s: str) -> bool: + s = s.strip() + if not s: + return False + + seenNum = False + seenDot = False + seenE = False + + for i, c in enumerate(s): + if c == '.': + if seenDot or seenE: + return False + seenDot = True + elif c == 'e' or c == 'E': + if seenE or not seenNum: + return False + seenE = True + seenNum = False + elif c in '+-': + if i > 0 and s[i - 1] not in 'eE': + return False + seenNum = False + else: + if not c.isdigit(): + return False + seenNum = True + + return seenNum diff --git a/solutions/650. 2 Keys Keyboard/650.cpp b/solutions/650. 2 Keys Keyboard/650.cpp new file mode 100644 index 00000000000..4b12495b7df --- /dev/null +++ b/solutions/650. 2 Keys Keyboard/650.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minSteps(int n) { + if (n <= 1) + return 0; + + // dp[i] := the minimum steps to get i 'A's + vector dp(n + 1); + + // Copy 'A', then paste 'A' i - 1 times. + iota(dp.begin(), dp.end(), 0); + + for (int i = 2; i <= n; ++i) + for (int j = i / 2; j > 2; --j) + if (i % j == 0) { + dp[i] = dp[j] + i / j; // Paste dp[j] i / j times. + break; + } + + return dp[n]; + } +}; diff --git a/solutions/650. 2 Keys Keyboard/650.java b/solutions/650. 2 Keys Keyboard/650.java new file mode 100644 index 00000000000..15097f6e1e5 --- /dev/null +++ b/solutions/650. 2 Keys Keyboard/650.java @@ -0,0 +1,17 @@ +class Solution { + public int minSteps(int n) { + // dp[i] := the minimum steps to get i 'A's + int[] dp = new int[n + 1]; + + for (int i = 2; i <= n; ++i) { + dp[i] = i; // Copy 'A', then paste 'A' i - 1 times. + for (int j = i / 2; j > 2; --j) + if (i % j == 0) { + dp[i] = dp[j] + i / j; // Paste dp[j] i / j times. + break; + } + } + + return dp[n]; + } +} diff --git a/solutions/650. 2 Keys Keyboard/650.py b/solutions/650. 2 Keys Keyboard/650.py new file mode 100644 index 00000000000..14e2e233dae --- /dev/null +++ b/solutions/650. 2 Keys Keyboard/650.py @@ -0,0 +1,16 @@ +class Solution: + def minSteps(self, n: int) -> int: + if n <= 1: + return 0 + + # dp[i] := the minimum steps to get i 'A's + # Copy 'A', then paste 'A' i - 1 times. + dp = [i for i in range(n + 1)] + + for i in range(2, n + 1): + for j in range(i // 2, 2, -1): + if i % j == 0: + dp[i] = dp[j] + i // j # Paste dp[j] i / j times. + break + + return dp[n] diff --git a/solutions/651. 4 Keys Keyboard/651-2.cpp b/solutions/651. 4 Keys Keyboard/651-2.cpp new file mode 100644 index 00000000000..fffe54ab6f0 --- /dev/null +++ b/solutions/651. 4 Keys Keyboard/651-2.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxA(int n) { + // dp[i] := the maximum 'A' can be printed with i pressings + vector dp(n + 1); + + // 'A' * i + iota(dp.begin(), dp.end(), 0); + + for (int i = 0; i <= n; ++i) + for (int j = 0; j <= i - 3; ++j) + dp[i] = max(dp[i], dp[j] * (i - j - 1)); + + return dp[n]; + } +}; diff --git a/solutions/651. 4 Keys Keyboard/651-2.java b/solutions/651. 4 Keys Keyboard/651-2.java new file mode 100644 index 00000000000..1dd7c30a5ca --- /dev/null +++ b/solutions/651. 4 Keys Keyboard/651-2.java @@ -0,0 +1,14 @@ +class Solution { + public int maxA(int n) { + // dp[i] := the maximum 'A' can be printed with i pressings + int[] dp = new int[n + 1]; + + for (int i = 0; i <= n; ++i) { + dp[i] = i; // 'A' * i + for (int j = 0; j <= i - 3; ++j) + dp[i] = Math.max(dp[i], dp[j] * (i - j - 1)); + } + + return dp[n]; + } +} diff --git a/solutions/651. 4 Keys Keyboard/651.cpp b/solutions/651. 4 Keys Keyboard/651.cpp new file mode 100644 index 00000000000..06499201063 --- /dev/null +++ b/solutions/651. 4 Keys Keyboard/651.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int maxA(int n) { + int ans = n; + + for (int i = 1; i <= n - 3; ++i) + ans = max(ans, maxA(i) * (n - 1 - i)); + + return ans; + } +}; diff --git a/solutions/651. 4 Keys Keyboard/651.java b/solutions/651. 4 Keys Keyboard/651.java new file mode 100644 index 00000000000..99997fbf195 --- /dev/null +++ b/solutions/651. 4 Keys Keyboard/651.java @@ -0,0 +1,10 @@ +class Solution { + public int maxA(int n) { + int ans = n; + + for (int i = 1; i <= n - 3; ++i) + ans = Math.max(ans, maxA(i) * (n - 1 - i)); + + return ans; + } +} diff --git a/solutions/652. Find Duplicate Subtrees/652.cpp b/solutions/652. Find Duplicate Subtrees/652.cpp new file mode 100644 index 00000000000..25eb2164363 --- /dev/null +++ b/solutions/652. Find Duplicate Subtrees/652.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector findDuplicateSubtrees(TreeNode* root) { + vector ans; + unordered_map count; + encode(root, count, ans); + return ans; + } + + private: + string encode(TreeNode* root, unordered_map& count, + vector& ans) { + if (root == nullptr) + return ""; + + const string encoded = to_string(root->val) + "#" + + encode(root->left, count, ans) + "#" + + encode(root->right, count, ans); + if (++count[encoded] == 2) + ans.push_back(root); + return encoded; + } +}; diff --git a/solutions/652. Find Duplicate Subtrees/652.java b/solutions/652. Find Duplicate Subtrees/652.java new file mode 100644 index 00000000000..0b00f060700 --- /dev/null +++ b/solutions/652. Find Duplicate Subtrees/652.java @@ -0,0 +1,19 @@ +class Solution { + public List findDuplicateSubtrees(TreeNode root) { + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + encode(root, count, ans); + return ans; + } + + private String encode(TreeNode root, Map count, List ans) { + if (root == null) + return ""; + + final String encoded = + root.val + "#" + encode(root.left, count, ans) + "#" + encode(root.right, count, ans); + if (count.merge(encoded, 1, Integer::sum) == 2) + ans.add(root); + return encoded; + } +} diff --git a/solutions/652. Find Duplicate Subtrees/652.py b/solutions/652. Find Duplicate Subtrees/652.py new file mode 100644 index 00000000000..e727e15e5fa --- /dev/null +++ b/solutions/652. Find Duplicate Subtrees/652.py @@ -0,0 +1,19 @@ +class Solution: + def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: + ans = [] + count = collections.Counter() + + def encode(root: Optional[TreeNode]) -> str: + if not root: + return '' + + encoded = str(root.val) + '#' + \ + encode(root.left) + '#' + \ + encode(root.right) + count[encoded] += 1 + if count[encoded] == 2: + ans.append(root) + return encoded + + encode(root) + return ans diff --git a/solutions/653. Two Sum IV - Input is a BST/653.cpp b/solutions/653. Two Sum IV - Input is a BST/653.cpp new file mode 100644 index 00000000000..4541dbe34dc --- /dev/null +++ b/solutions/653. Two Sum IV - Input is a BST/653.cpp @@ -0,0 +1,47 @@ +class BSTIterator { + public: + BSTIterator(TreeNode* root, bool leftToRight) : leftToRight(leftToRight) { + pushUntilNull(root); + } + + int next() { + TreeNode* root = stack.top(); + stack.pop(); + pushUntilNull(leftToRight ? root->right : root->left); + return root->val; + } + + private: + stack stack; + bool leftToRight; + + void pushUntilNull(TreeNode* root) { + while (root != nullptr) { + stack.push(root); + root = leftToRight ? root->left : root->right; + } + } +}; + +class Solution { + public: + bool findTarget(TreeNode* root, int k) { + if (root == nullptr) + return false; + + BSTIterator left(root, true); + BSTIterator right(root, false); + + for (int l = left.next(), r = right.next(); l < r;) { + const int sum = l + r; + if (sum == k) + return true; + if (sum < k) + l = left.next(); + else + r = right.next(); + } + + return false; + } +}; diff --git a/solutions/653. Two Sum IV - Input is a BST/653.java b/solutions/653. Two Sum IV - Input is a BST/653.java new file mode 100644 index 00000000000..804f1e563c7 --- /dev/null +++ b/solutions/653. Two Sum IV - Input is a BST/653.java @@ -0,0 +1,48 @@ +class BSTIterator { + public BSTIterator(TreeNode root, boolean leftToRight) { + this.leftToRight = leftToRight; + pushLeftsUntilNull(root); + } + + public int next() { + TreeNode root = stack.pop(); + pushLeftsUntilNull(leftToRight ? root.right : root.left); + return root.val; + } + + public boolean hasNext() { + return !stack.isEmpty(); + } + + private Deque stack = new ArrayDeque<>(); + private boolean leftToRight; + + private void pushLeftsUntilNull(TreeNode root) { + while (root != null) { + stack.push(root); + root = leftToRight ? root.left : root.right; + } + } +} + +class Solution { + public boolean findTarget(TreeNode root, int k) { + if (root == null) + return false; + + BSTIterator left = new BSTIterator(root, true); + BSTIterator right = new BSTIterator(root, false); + + for (int l = left.next(), r = right.next(); l < r;) { + final int sum = l + r; + if (sum == k) + return true; + if (sum < k) + l = left.next(); + else + r = right.next(); + } + + return false; + } +} diff --git a/solutions/653. Two Sum IV - Input is a BST/653.py b/solutions/653. Two Sum IV - Input is a BST/653.py new file mode 100644 index 00000000000..bb18e2ec0ab --- /dev/null +++ b/solutions/653. Two Sum IV - Input is a BST/653.py @@ -0,0 +1,40 @@ +class BSTIterator: + def __init__(self, root: Optional[TreeNode], leftToRight: bool): + self.stack = [] + self.leftToRight = leftToRight + self._pushUntilNone(root) + + def next(self) -> int: + node = self.stack.pop() + if self.leftToRight: + self._pushUntilNone(node.right) + else: + self._pushUntilNone(node.left) + return node.val + + def _pushUntilNone(self, root: Optional[TreeNode]): + while root: + self.stack.append(root) + root = root.left if self.leftToRight else root.right + + +class Solution: + def findTarget(self, root: Optional[TreeNode], k: int) -> bool: + if not root: + return False + + left = BSTIterator(root, True) + right = BSTIterator(root, False) + + l = left.next() + r = right.next() + while l < r: + summ = l + r + if summ == k: + return True + if summ < k: + l = left.next() + else: + r = right.next() + + return False diff --git a/solutions/654. Maximum Binary Tree/654.cpp b/solutions/654. Maximum Binary Tree/654.cpp new file mode 100644 index 00000000000..8596f90dc84 --- /dev/null +++ b/solutions/654. Maximum Binary Tree/654.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + TreeNode* constructMaximumBinaryTree(vector& nums) { + return build(nums, 0, nums.size() - 1); + } + + private: + TreeNode* build(const vector& nums, int i, int j) { + if (i > j) + return nullptr; + + const auto it = max_element(nums.begin() + i, nums.begin() + j + 1); + const int maxNum = *it; + const int maxIndex = it - nums.begin(); + + TreeNode* root = new TreeNode(maxNum); + root->left = build(nums, i, maxIndex - 1); + root->right = build(nums, maxIndex + 1, j); + return root; + } +}; diff --git a/solutions/654. Maximum Binary Tree/654.java b/solutions/654. Maximum Binary Tree/654.java new file mode 100644 index 00000000000..56317f62ee2 --- /dev/null +++ b/solutions/654. Maximum Binary Tree/654.java @@ -0,0 +1,20 @@ +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + return build(nums, 0, nums.length - 1); + } + + private TreeNode build(int[] nums, int i, int j) { + if (i > j) + return null; + + int maxIndex = i; + for (int k = i + 1; k <= j; ++k) + if (nums[k] > nums[maxIndex]) + maxIndex = k; + + TreeNode root = new TreeNode(nums[maxIndex]); + root.left = build(nums, i, maxIndex - 1); + root.right = build(nums, maxIndex + 1, j); + return root; + } +} diff --git a/solutions/654. Maximum Binary Tree/654.py b/solutions/654. Maximum Binary Tree/654.py new file mode 100644 index 00000000000..4d1666d9b37 --- /dev/null +++ b/solutions/654. Maximum Binary Tree/654.py @@ -0,0 +1,15 @@ +class Solution: + def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: + def build(i: int, j: int) -> Optional[TreeNode]: + if i > j: + return None + + maxNum = max(nums[i:j + 1]) + maxIndex = nums.index(maxNum) + + root = TreeNode(maxNum) + root.left = build(i, maxIndex - 1) + root.right = build(maxIndex + 1, j) + return root + + return build(0, len(nums) - 1) diff --git a/solutions/655. Print Binary Tree/655.cpp b/solutions/655. Print Binary Tree/655.cpp new file mode 100644 index 00000000000..7ab6794098e --- /dev/null +++ b/solutions/655. Print Binary Tree/655.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector> printTree(TreeNode* root) { + const int m = maxHeight(root); + const int n = pow(2, m) - 1; + vector> ans(m, vector(n)); + dfs(root, 0, 0, ans[0].size() - 1, ans); + return ans; + } + + private: + int maxHeight(TreeNode* root) { + if (root == nullptr) + return 0; + return 1 + max(maxHeight(root->left), maxHeight(root->right)); + } + + void dfs(TreeNode* root, int row, int left, int right, + vector>& ans) { + if (root == nullptr) + return; + + const int mid = (left + right) / 2; + ans[row][mid] = to_string(root->val); + dfs(root->left, row + 1, left, mid - 1, ans); + dfs(root->right, row + 1, mid + 1, right, ans); + } +}; diff --git a/solutions/655. Print Binary Tree/655.java b/solutions/655. Print Binary Tree/655.java new file mode 100644 index 00000000000..d500562014f --- /dev/null +++ b/solutions/655. Print Binary Tree/655.java @@ -0,0 +1,33 @@ +class Solution { + public List> printTree(TreeNode root) { + final int m = maxHeight(root); + final int n = (int) Math.pow(2, m) - 1; + List> ans = new ArrayList<>(); + List row = new ArrayList<>(); + + for (int i = 0; i < n; ++i) + row.add(""); + + for (int i = 0; i < m; ++i) + ans.add(new ArrayList<>(row)); + + dfs(root, 0, 0, n - 1, ans); + return ans; + } + + private int maxHeight(TreeNode root) { + if (root == null) + return 0; + return 1 + Math.max(maxHeight(root.left), maxHeight(root.right)); + } + + private void dfs(TreeNode root, int row, int left, int right, List> ans) { + if (root == null) + return; + + final int mid = (left + right) / 2; + ans.get(row).set(mid, Integer.toString(root.val)); + dfs(root.left, row + 1, left, mid - 1, ans); + dfs(root.right, row + 1, mid + 1, right, ans); + } +} diff --git a/solutions/655. Print Binary Tree/655.py b/solutions/655. Print Binary Tree/655.py new file mode 100644 index 00000000000..af80fbf2cf0 --- /dev/null +++ b/solutions/655. Print Binary Tree/655.py @@ -0,0 +1,21 @@ +class Solution: + def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: + def maxHeight(root: Optional[TreeNode]) -> int: + if not root: + return 0 + return 1 + max(maxHeight(root.left), maxHeight(root.right)) + + def dfs(root: Optional[TreeNode], row: int, left: int, right: int) -> None: + if not root: + return + + mid = (left + right) // 2 + ans[row][mid] = str(root.val) + dfs(root.left, row + 1, left, mid - 1) + dfs(root.right, row + 1, mid + 1, right) + + m = maxHeight(root) + n = pow(2, m) - 1 + ans = [[''] * n for _ in range(m)] + dfs(root, 0, 0, len(ans[0]) - 1) + return ans diff --git a/solutions/656. Coin Path/656-2.cpp b/solutions/656. Coin Path/656-2.cpp new file mode 100644 index 00000000000..d0200cd5bf1 --- /dev/null +++ b/solutions/656. Coin Path/656-2.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + vector cheapestJump(vector& coins, int maxJump) { + if (coins.back() == -1) + return {}; + + const int n = coins.size(); + // dp[i] := the minimum cost to jump from i to n - 1 + vector dp(n, INT_MAX); + vector next(n, -1); + + dp.back() = coins.back(); + + for (int i = n - 2; i >= 0; --i) { + if (coins[i] == -1) + continue; + for (int j = i + 1; j < min(i + maxJump + 1, n); ++j) { + if (dp[j] == INT_MAX) + continue; + const int cost = coins[i] + dp[j]; + if (cost < dp[i]) { + dp[i] = cost; + next[i] = j; + } + } + } + + if (dp[0] == INT_MAX) + return {}; + return constructPath(next, 0); + } + + private: + vector constructPath(const vector& next, int i) { + vector ans; + while (i != -1) { + ans.push_back(i + 1); // 1-indexed + i = next[i]; + } + return ans; + } +}; diff --git a/solutions/656. Coin Path/656-2.java b/solutions/656. Coin Path/656-2.java new file mode 100644 index 00000000000..6ba241bd044 --- /dev/null +++ b/solutions/656. Coin Path/656-2.java @@ -0,0 +1,43 @@ +class Solution { + public List cheapestJump(int[] coins, int maxJump) { + if (coins[coins.length - 1] == -1) + return new ArrayList<>(); + + final int n = coins.length; + // dp[i] := the minimum cost to jump from i to n - 1 + int[] dp = new int[n]; + int[] next = new int[n]; + + Arrays.fill(dp, Integer.MAX_VALUE); + Arrays.fill(next, -1); + + dp[n - 1] = coins[n - 1]; + + for (int i = n - 2; i >= 0; --i) { + if (coins[i] == -1) + continue; + for (int j = i + 1; j < Math.min(i + maxJump + 1, n); ++j) { + if (dp[j] == Integer.MAX_VALUE) + continue; + final int cost = coins[i] + dp[j]; + if (cost < dp[i]) { + dp[i] = cost; + next[i] = j; + } + } + } + + if (dp[0] == Integer.MAX_VALUE) + return new ArrayList<>(); + return constructPath(next, 0); + } + + private List constructPath(int[] next, int i) { + List ans = new ArrayList<>(); + while (i != -1) { + ans.add(i + 1); // 1-indexed + i = next[i]; + } + return ans; + } +} diff --git a/solutions/656. Coin Path/656-2.py b/solutions/656. Coin Path/656-2.py new file mode 100644 index 00000000000..3114628e219 --- /dev/null +++ b/solutions/656. Coin Path/656-2.py @@ -0,0 +1,33 @@ +class Solution: + def cheapestJump(self, coins: List[int], maxJump: int) -> List[int]: + if coins[-1] == -1: + return [] + + n = len(coins) + # dp[i] := the minimum cost to jump from i to n - 1 + dp = [math.inf] * n + next = [-1] * n + + dp[-1] = coins[-1] + + for i in reversed(range(n - 1)): + if coins[i] == -1: + continue + for j in range(i + 1, min(i + maxJump + 1, n)): + if dp[j] == math.inf: + continue + cost = coins[i] + dp[j] + if cost < dp[i]: + dp[i] = cost + next[i] = j + + if dp[0] == math.inf: + return [] + return self._constructPath(next, 0) + + def _constructPath(self, next: List[int], i: int) -> List[int]: + ans = [] + while i != -1: + ans.append(i + 1) # 1-indexed + i = next[i] + return ans diff --git a/solutions/656. Coin Path/656.cpp b/solutions/656. Coin Path/656.cpp new file mode 100644 index 00000000000..cf75c04710c --- /dev/null +++ b/solutions/656. Coin Path/656.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + vector cheapestJump(vector& coins, int maxJump) { + if (coins.back() == -1) + return {}; + + const int n = coins.size(); + vector next(n, -1); + vector mem(n, INT_MAX); + cheapestJump(coins, maxJump, 0, next); + + if (mem[0] == INT_MAX) + return {}; + return constructPath(next, 0); + } + + private: + // Returns the minimum cost to jump from i to n - 1. + int cheapestJump(const vector& coins, int maxJump, int i, + vector& next, vector& mem) { + if (i == coins.size() - 1) + return mem[i] = coins[i]; + if (mem[i] < INT_MAX) + return mem[i]; + if (coins[i] == -1) + return INT_MAX; + + for (int j = i + 1; j <= i + maxJump && j < coins.size(); ++j) { + const int res = cheapestJump(coins, maxJump, j, next, mem); + if (res == INT_MAX) + continue; + const int cost = coins[i] + res; + if (cost < mem[i]) { + mem[i] = cost; + next[i] = j; + } + } + + return mem[i]; + } + + vector constructPath(const vector& next, int i) { + vector ans; + while (i != -1) { + ans.push_back(i + 1); // 1-indexed + i = next[i]; + } + return ans; + } +}; diff --git a/solutions/656. Coin Path/656.java b/solutions/656. Coin Path/656.java new file mode 100644 index 00000000000..1cc38de33b1 --- /dev/null +++ b/solutions/656. Coin Path/656.java @@ -0,0 +1,49 @@ +class Solution { + public List cheapestJump(int[] coins, int maxJump) { + if (coins[coins.length - 1] == -1) + return new ArrayList<>(); + + int n = coins.length; + int[] next = new int[n]; + Arrays.fill(next, -1); + int[] mem = new int[n]; + Arrays.fill(mem, Integer.MAX_VALUE); + cheapestJump(coins, maxJump, 0, next, mem); + + if (mem[0] == Integer.MAX_VALUE) + return new ArrayList<>(); + return constructPath(next, 0); + } + + // Returns the minimum cost to jump from i to n - 1. + private int cheapestJump(int[] coins, int maxJump, int i, int[] next, int[] mem) { + if (i == coins.length - 1) + return mem[i] = coins[i]; + if (mem[i] < Integer.MAX_VALUE) + return mem[i]; + if (coins[i] == -1) + return Integer.MAX_VALUE; + + for (int j = i + 1; j <= Math.min(i + maxJump, coins.length - 1); ++j) { + final int res = cheapestJump(coins, maxJump, j, next, mem); + if (res == Integer.MAX_VALUE) + continue; + final int cost = coins[i] + res; + if (cost < mem[i]) { + mem[i] = cost; + next[i] = j; + } + } + + return mem[i]; + } + + private List constructPath(int[] next, int i) { + List ans = new ArrayList<>(); + while (i != -1) { + ans.add(i + 1); // 1-indexed + i = next[i]; + } + return ans; + } +} diff --git a/solutions/656. Coin Path/656.py b/solutions/656. Coin Path/656.py new file mode 100644 index 00000000000..fefafdb8cd5 --- /dev/null +++ b/solutions/656. Coin Path/656.py @@ -0,0 +1,41 @@ +class Solution: + def cheapestJump(self, coins: List[int], maxJump: int) -> List[int]: + if coins[-1] == -1: + return [] + + n = len(coins) + # dp[i] := the minimum cost to jump from i to n - 1 + dp = [math.inf] * n + next = [-1] * n + + def cheapestJump(i: int) -> int: + if i == len(coins) - 1: + dp[i] = coins[i] + return dp[i] + if dp[i] < math.inf: + return dp[i] + if coins[i] == -1: + return math.inf + + for j in range(i + 1, min(i + maxJump + 1, n)): + res = cheapestJump(j) + if res == math.inf: + continue + cost = coins[i] + res + if cost < dp[i]: + dp[i] = cost + next[i] = j + + return dp[i] + + cheapestJump(0) + if dp[0] == math.inf: + return [] + return self._constructPath(next, 0) + + def _constructPath(self, next: List[int], i: int) -> List[int]: + ans = [] + while i != -1: + ans.append(i + 1) # 1-indexed + i = next[i] + return ans diff --git a/solutions/657. Robot Return to Origin/657.cpp b/solutions/657. Robot Return to Origin/657.cpp new file mode 100644 index 00000000000..614a95db237 --- /dev/null +++ b/solutions/657. Robot Return to Origin/657.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + bool judgeCircle(string moves) { + int right = 0; + int up = 0; + + for (const char move : moves) { + switch (move) { + case 'R': + ++right; + break; + case 'L': + --right; + break; + case 'U': + ++up; + break; + case 'D': + --up; + break; + } + } + + return right == 0 && up == 0; + } +}; diff --git a/solutions/657. Robot Return to Origin/657.java b/solutions/657. Robot Return to Origin/657.java new file mode 100644 index 00000000000..ca696337512 --- /dev/null +++ b/solutions/657. Robot Return to Origin/657.java @@ -0,0 +1,25 @@ +class Solution { + public boolean judgeCircle(String moves) { + int right = 0; + int up = 0; + + for (final char move : moves.toCharArray()) { + switch (move) { + case 'R': + ++right; + break; + case 'L': + --right; + break; + case 'U': + ++up; + break; + case 'D': + --up; + break; + } + } + + return right == 0 && up == 0; + } +} diff --git a/solutions/657. Robot Return to Origin/657.py b/solutions/657. Robot Return to Origin/657.py new file mode 100644 index 00000000000..5ce8fc16ac9 --- /dev/null +++ b/solutions/657. Robot Return to Origin/657.py @@ -0,0 +1,3 @@ +class Solution: + def judgeCircle(self, moves: str) -> bool: + return moves.count('R') == moves.count('L') and moves.count('U') == moves.count('D') diff --git a/solutions/658. Find K Closest Elements/658.cpp b/solutions/658. Find K Closest Elements/658.cpp new file mode 100644 index 00000000000..ebe8d8c76ae --- /dev/null +++ b/solutions/658. Find K Closest Elements/658.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector findClosestElements(vector& arr, int k, int x) { + int l = 0; + int r = arr.size() - k; + + while (l < r) { + const int m = (l + r) / 2; + if (x - arr[m] <= arr[m + k] - x) + r = m; + else + l = m + 1; + } + + return {arr.begin() + l, arr.begin() + l + k}; + } +}; diff --git a/solutions/658. Find K Closest Elements/658.java b/solutions/658. Find K Closest Elements/658.java new file mode 100644 index 00000000000..75eec06c26e --- /dev/null +++ b/solutions/658. Find K Closest Elements/658.java @@ -0,0 +1,16 @@ +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + int l = 0; + int r = arr.length - k; + + while (l < r) { + final int m = (l + r) / 2; + if (x - arr[m] <= arr[m + k] - x) + r = m; + else + l = m + 1; + } + + return Arrays.stream(arr, l, l + k).boxed().collect(Collectors.toList()); + } +} diff --git a/solutions/658. Find K Closest Elements/658.py b/solutions/658. Find K Closest Elements/658.py new file mode 100644 index 00000000000..ac598942dd2 --- /dev/null +++ b/solutions/658. Find K Closest Elements/658.py @@ -0,0 +1,13 @@ +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + l = 0 + r = len(arr) - k + + while l < r: + m = (l + r) // 2 + if x - arr[m] <= arr[m + k] - x: + r = m + else: + l = m + 1 + + return arr[l:l + k] diff --git a/solutions/659. Split Array into Consecutive Subsequences/659.cpp b/solutions/659. Split Array into Consecutive Subsequences/659.cpp new file mode 100644 index 00000000000..811c3409530 --- /dev/null +++ b/solutions/659. Split Array into Consecutive Subsequences/659.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool isPossible(vector& nums) { + unordered_map count; + vector starts; // the start indices of each subsequence + vector ends; // the end indices of each subsequence + + for (const int num : nums) + ++count[num]; + + for (int i = 0; i < nums.size(); ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + const int num = nums[i]; + const int currCount = count[num]; + const int prevCount = count.contains(num - 1) ? count[num - 1] : 0; + const int nextCount = count.contains(num + 1) ? count[num + 1] : 0; + for (int j = 0; j < currCount - prevCount; ++j) + starts.push_back(num); + for (int j = 0; j < currCount - nextCount; ++j) + ends.push_back(num); + } + + for (int i = 0; i < starts.size(); ++i) + if (ends[i] - starts[i] < 2) + return false; + + return true; + } +}; diff --git a/solutions/659. Split Array into Consecutive Subsequences/659.java b/solutions/659. Split Array into Consecutive Subsequences/659.java new file mode 100644 index 00000000000..1fd1ec4b5e8 --- /dev/null +++ b/solutions/659. Split Array into Consecutive Subsequences/659.java @@ -0,0 +1,29 @@ +class Solution { + public boolean isPossible(int[] nums) { + Map count = new HashMap<>(); + List starts = new ArrayList<>(); // the start indices of each subsequence + List ends = new ArrayList<>(); // the end indices of each subsequence + + for (final int num : nums) + count.merge(num, 1, Integer::sum); + + for (int i = 0; i < nums.length; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + final int num = nums[i]; + final int currCount = count.get(num); + final int prevCount = count.getOrDefault(num - 1, 0); + final int nextCount = count.getOrDefault(num + 1, 0); + for (int j = 0; j < currCount - prevCount; ++j) + starts.add(num); + for (int j = 0; j < currCount - nextCount; ++j) + ends.add(num); + } + + for (int i = 0; i < starts.size(); ++i) + if (ends.get(i) - starts.get(i) < 2) + return false; + + return true; + } +} diff --git a/solutions/66. Plus One/66.cpp b/solutions/66. Plus One/66.cpp new file mode 100644 index 00000000000..8e9a7d03053 --- /dev/null +++ b/solutions/66. Plus One/66.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector plusOne(vector& digits) { + for (int i = digits.size() - 1; i >= 0; --i) { + if (digits[i] < 9) { + ++digits[i]; + return digits; + } + digits[i] = 0; + } + + digits.insert(digits.begin(), 1); + return digits; + } +}; diff --git a/solutions/66. Plus One/66.java b/solutions/66. Plus One/66.java new file mode 100644 index 00000000000..b860bfde9a5 --- /dev/null +++ b/solutions/66. Plus One/66.java @@ -0,0 +1,15 @@ +class Solution { + public int[] plusOne(int[] digits) { + for (int i = digits.length - 1; i >= 0; i--) { + if (digits[i] < 9) { + ++digits[i]; + return digits; + } + digits[i] = 0; + } + + int[] ans = new int[digits.length + 1]; + ans[0] = 1; + return ans; + } +} diff --git a/solutions/66. Plus One/66.py b/solutions/66. Plus One/66.py new file mode 100644 index 00000000000..f04703ba937 --- /dev/null +++ b/solutions/66. Plus One/66.py @@ -0,0 +1,9 @@ +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: + for i, d in reversed(list(enumerate(digits))): + if d < 9: + digits[i] += 1 + return digits + digits[i] = 0 + + return [1] + digits diff --git a/solutions/660. Remove 9/660.cpp b/solutions/660. Remove 9/660.cpp new file mode 100644 index 00000000000..77388a8b010 --- /dev/null +++ b/solutions/660. Remove 9/660.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int newInteger(int n) { + string ans; + while (n) { + ans = to_string(n % 9) + ans; + n /= 9; + } + return stoi(ans); + } +}; diff --git a/solutions/660. Remove 9/660.java b/solutions/660. Remove 9/660.java new file mode 100644 index 00000000000..20f42a78312 --- /dev/null +++ b/solutions/660. Remove 9/660.java @@ -0,0 +1,5 @@ +class Solution { + public int newInteger(int n) { + return Integer.parseInt(Integer.toString(n, 9)); + } +} diff --git a/solutions/660. Remove 9/660.py b/solutions/660. Remove 9/660.py new file mode 100644 index 00000000000..c27182ee4e0 --- /dev/null +++ b/solutions/660. Remove 9/660.py @@ -0,0 +1,7 @@ +class Solution: + def newInteger(self, n: int) -> int: + ans = [] + while n: + ans.append(str(n % 9)) + n //= 9 + return ''.join(reversed(ans)) diff --git a/solutions/661. Image Smoother/661.cpp b/solutions/661. Image Smoother/661.cpp new file mode 100644 index 00000000000..5c7ec57f818 --- /dev/null +++ b/solutions/661. Image Smoother/661.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector> imageSmoother(vector>& M) { + const int m = M.size(); + const int n = M[0].size(); + vector> ans(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + int ones = 0; + int count = 0; + for (int x = max(0, i - 1); x < min(m, i + 2); ++x) + for (int y = max(0, j - 1); y < min(n, j + 2); ++y) { + ones += M[x][y]; + ++count; + } + ans[i][j] = ones / count; + } + + return ans; + } +}; diff --git a/solutions/661. Image Smoother/661.java b/solutions/661. Image Smoother/661.java new file mode 100644 index 00000000000..71a84e9f69e --- /dev/null +++ b/solutions/661. Image Smoother/661.java @@ -0,0 +1,21 @@ +class Solution { + public int[][] imageSmoother(int[][] M) { + final int m = M.length; + final int n = M[0].length; + int ans[][] = new int[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + int ones = 0; + int count = 0; + for (int y = Math.max(0, i - 1); y < Math.min(m, i + 2); ++y) + for (int x = Math.max(0, j - 1); x < Math.min(n, j + 2); ++x) { + ones += M[y][x]; + ++count; + } + ans[i][j] = ones / count; + } + + return ans; + } +} diff --git a/solutions/661. Image Smoother/661.py b/solutions/661. Image Smoother/661.py new file mode 100644 index 00000000000..d3853201c68 --- /dev/null +++ b/solutions/661. Image Smoother/661.py @@ -0,0 +1,17 @@ +class Solution: + def imageSmoother(self, M: List[List[int]]) -> List[List[int]]: + m = len(M) + n = len(M[0]) + ans = [[0 for j in range(n)] for i in range(m)] + + for i in range(m): + for j in range(n): + ones = 0 + count = 0 + for y in range(max(0, i - 1), min(m, i + 2)): + for x in range(max(0, j - 1), min(n, j + 2)): + ones += M[y][x] + count += 1 + ans[i][j] = ones // count + + return ans diff --git a/solutions/662. Maximum Width of Binary Tree/662-2.cpp b/solutions/662. Maximum Width of Binary Tree/662-2.cpp new file mode 100644 index 00000000000..ba696cc9fe8 --- /dev/null +++ b/solutions/662. Maximum Width of Binary Tree/662-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int widthOfBinaryTree(TreeNode* root) { + if (root == nullptr) + return 0; + + long ans = 0; + dfs(root, 0, 1, {}, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int level, long index, vector&& startOfLevel, + long& ans) { + if (root == nullptr) + return; + if (startOfLevel.size() == level) + startOfLevel.push_back(index); + + ans = max(ans, index - startOfLevel[level] + 1); + dfs(root->left, level + 1, index * 2, move(startOfLevel), ans); + dfs(root->right, level + 1, index * 2 + 1, move(startOfLevel), ans); + } +}; diff --git a/solutions/662. Maximum Width of Binary Tree/662.cpp b/solutions/662. Maximum Width of Binary Tree/662.cpp new file mode 100644 index 00000000000..3da44b630af --- /dev/null +++ b/solutions/662. Maximum Width of Binary Tree/662.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int widthOfBinaryTree(TreeNode* root) { + if (root == nullptr) + return 0; + + int ans = 0; + queue> q{{{root, 1}}}; // {node, index} + + while (!q.empty()) { + const int offset = q.front().second * 2; + ans = max(ans, q.back().second - q.front().second + 1); + for (int sz = q.size(); sz > 0; --sz) { + const auto [node, index] = q.front(); + q.pop(); + if (node->left) + q.emplace(node->left, index * 2 - offset); + if (node->right) + q.emplace(node->right, index * 2 + 1 - offset); + } + } + + return ans; + } +}; diff --git a/solutions/662. Maximum Width of Binary Tree/662.java b/solutions/662. Maximum Width of Binary Tree/662.java new file mode 100644 index 00000000000..6c9c3dda3f8 --- /dev/null +++ b/solutions/662. Maximum Width of Binary Tree/662.java @@ -0,0 +1,25 @@ +class Solution { + public int widthOfBinaryTree(TreeNode root) { + if (root == null) + return 0; + + int ans = 0; + Deque> q = new ArrayDeque<>(); // {node, index} + q.offer(new Pair<>(root, 1)); + + while (!q.isEmpty()) { + final int offset = q.peekFirst().getValue() * 2; + ans = Math.max(ans, q.peekLast().getValue() - q.peekFirst().getValue() + 1); + for (int sz = q.size(); sz > 0; --sz) { + final TreeNode node = q.peekFirst().getKey(); + final int index = q.pollFirst().getValue(); + if (node.left != null) + q.offer(new Pair<>(node.left, index * 2 - offset)); + if (node.right != null) + q.offer(new Pair<>(node.right, index * 2 + 1 - offset)); + } + } + + return ans; + } +} diff --git a/solutions/663. Equal Tree Partition/663.cpp b/solutions/663. Equal Tree Partition/663.cpp new file mode 100644 index 00000000000..7132f5ebc11 --- /dev/null +++ b/solutions/663. Equal Tree Partition/663.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool checkEqualTree(TreeNode* root) { + if (root == nullptr) + return false; + + unordered_set seen; + const int sum = root->val + dfs(root->left, seen) + dfs(root->right, seen); + return sum % 2 == 0 && seen.contains(sum / 2); + } + + private: + int dfs(TreeNode* root, unordered_set& seen) { + if (root == nullptr) + return 0; + + const int sum = root->val + dfs(root->left, seen) + dfs(root->right, seen); + seen.insert(sum); + return sum; + } +}; diff --git a/solutions/663. Equal Tree Partition/663.java b/solutions/663. Equal Tree Partition/663.java new file mode 100644 index 00000000000..85e7e5c08d4 --- /dev/null +++ b/solutions/663. Equal Tree Partition/663.java @@ -0,0 +1,19 @@ +class Solution { + public boolean checkEqualTree(TreeNode root) { + if (root == null) + return false; + + Set seen = new HashSet<>(); + final int sum = root.val + dfs(root.left, seen) + dfs(root.right, seen); + return sum % 2 == 0 && seen.contains(sum / 2); + } + + private int dfs(TreeNode root, Set seen) { + if (root == null) + return 0; + + final int sum = root.val + dfs(root.left, seen) + dfs(root.right, seen); + seen.add(sum); + return sum; + } +} diff --git a/solutions/663. Equal Tree Partition/663.py b/solutions/663. Equal Tree Partition/663.py new file mode 100644 index 00000000000..409ae7107c0 --- /dev/null +++ b/solutions/663. Equal Tree Partition/663.py @@ -0,0 +1,17 @@ +class Solution: + def checkEqualTree(self, root: Optional[TreeNode]) -> bool: + if not root: + return False + + seen = set() + + def dfs(root: Optional[TreeNode]) -> int: + if not root: + return 0 + + summ = root.val + dfs(root.left) + dfs(root.right) + seen.add(summ) + return summ + + summ = root.val + dfs(root.left) + dfs(root.right) + return summ % 2 == 0 and summ // 2 in seen diff --git a/solutions/664. Strange Printer/664-2.cpp b/solutions/664. Strange Printer/664-2.cpp new file mode 100644 index 00000000000..6776b1d6c1b --- /dev/null +++ b/solutions/664. Strange Printer/664-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int strangePrinter(string s) { + if (s.empty()) + return 0; + + const int n = s.size(); + // dp[i][j] := the minimum number of turns to print s[i..j] + vector> dp(n, vector(n, n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int j = 0; j < n; ++j) + for (int i = j; i >= 0; --i) + for (int k = i; k < j; ++k) + dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] - (s[k] == s[j])); + + return dp[0][n - 1]; + } +}; diff --git a/solutions/664. Strange Printer/664-2.java b/solutions/664. Strange Printer/664-2.java new file mode 100644 index 00000000000..d983029aae9 --- /dev/null +++ b/solutions/664. Strange Printer/664-2.java @@ -0,0 +1,22 @@ +class Solution { + public int strangePrinter(String s) { + if (s.isEmpty()) + return 0; + + final int n = s.length(); + // dp[i][j] := the minimum number of turns to print s[i..j] + int[][] dp = new int[n][n]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int j = 0; j < n; ++j) + for (int i = j; i >= 0; --i) + for (int k = i; k < j; ++k) + dp[i][j] = + Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] - (s.charAt(k) == s.charAt(j) ? 1 : 0)); + + return dp[0][n - 1]; + } +} diff --git a/solutions/664. Strange Printer/664.cpp b/solutions/664. Strange Printer/664.cpp new file mode 100644 index 00000000000..db19e765167 --- /dev/null +++ b/solutions/664. Strange Printer/664.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int strangePrinter(string s) { + const int n = s.length(); + vector> mem(n, vector(n)); + return strangePrinter(s, 0, n - 1, mem); + } + + private: + // Returns the minimum number of turns to print s[i..j]. + int strangePrinter(const string& s, int i, int j, vector>& mem) { + if (i > j) + return 0; + if (mem[i][j] > 0) + return mem[i][j]; + + // Print s[i]. + mem[i][j] = strangePrinter(s, i + 1, j, mem) + 1; + + for (int k = i + 1; k <= j; ++k) + if (s[k] == s[i]) + mem[i][j] = min(mem[i][j], strangePrinter(s, i, k - 1, mem) + + strangePrinter(s, k + 1, j, mem)); + + return mem[i][j]; + } +}; diff --git a/solutions/664. Strange Printer/664.java b/solutions/664. Strange Printer/664.java new file mode 100644 index 00000000000..665d43e66db --- /dev/null +++ b/solutions/664. Strange Printer/664.java @@ -0,0 +1,25 @@ +class Solution { + public int strangePrinter(String s) { + final int n = s.length(); + int[][] mem = new int[n][n]; + return strangePrinter(s, 0, n - 1, mem); + } + + // Recursive helper method for strangePrinter + private int strangePrinter(String s, int i, int j, int[][] mem) { + if (i > j) + return 0; + if (mem[i][j] > 0) + return mem[i][j]; + + // Print s[i]. + mem[i][j] = strangePrinter(s, i + 1, j, mem) + 1; + + for (int k = i + 1; k <= j; k++) + if (s.charAt(k) == s.charAt(i)) + mem[i][j] = Math.min(mem[i][j], strangePrinter(s, i, k - 1, mem) + // + strangePrinter(s, k + 1, j, mem)); + + return mem[i][j]; + } +} diff --git a/solutions/665. Non-decreasing Array/665.cpp b/solutions/665. Non-decreasing Array/665.cpp new file mode 100644 index 00000000000..7e7d6bec017 --- /dev/null +++ b/solutions/665. Non-decreasing Array/665.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool checkPossibility(vector& nums) { + bool modified = false; + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] < nums[i - 1]) { + if (modified) + return false; + if (i == 1 || nums[i] >= nums[i - 2]) + nums[i - 1] = nums[i]; // Decrease the previous value. + else + nums[i] = nums[i - 1]; // Increase the current value. + modified = true; + } + + return true; + } +}; diff --git a/solutions/665. Non-decreasing Array/665.java b/solutions/665. Non-decreasing Array/665.java new file mode 100644 index 00000000000..8aa5003e6fd --- /dev/null +++ b/solutions/665. Non-decreasing Array/665.java @@ -0,0 +1,16 @@ +class Solution { + public boolean checkPossibility(int[] nums) { + int j = -1; + + for (int i = 0; i + 1 < nums.length; ++i) + if (nums[i] > nums[i + 1]) { + if (j != -1) + return false; + j = i; + } + + return j == -1 || j == 0 || j == nums.length - 2 || // + nums[j - 1] <= nums[j + 1] || // + nums[j] <= nums[j + 2]; + } +} diff --git a/solutions/665. Non-decreasing Array/665.py b/solutions/665. Non-decreasing Array/665.py new file mode 100644 index 00000000000..915b0fddc73 --- /dev/null +++ b/solutions/665. Non-decreasing Array/665.py @@ -0,0 +1,12 @@ +class Solution: + def checkPossibility(self, nums: List[int]) -> bool: + j = None + + for i in range(len(nums) - 1): + if nums[i] > nums[i + 1]: + if j is not None: + return False + j = i + + return j is None or j == 0 or j == len(nums) - 2 or \ + nums[j - 1] <= nums[j + 1] or nums[j] <= nums[j + 2] diff --git a/solutions/666. Path Sum IV/666.cpp b/solutions/666. Path Sum IV/666.cpp new file mode 100644 index 00000000000..6071abe9b88 --- /dev/null +++ b/solutions/666. Path Sum IV/666.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int pathSum(vector& nums) { + int ans = 0; + vector> tree(4, vector(8, -1)); + + for (const int num : nums) { + const int d = num / 100 - 1; + const int p = (num % 100) / 10 - 1; + const int v = num % 10; + tree[d][p] = v; + } + + dfs(tree, 0, 0, 0, ans); + return ans; + } + + private: + void dfs(const vector>& tree, int i, int j, int path, int& ans) { + if (tree[i][j] == -1) + return; + if (i == 3 || max(tree[i + 1][j * 2], tree[i + 1][j * 2 + 1]) == -1) { + ans += path + tree[i][j]; + return; + } + + dfs(tree, i + 1, j * 2, path + tree[i][j], ans); + dfs(tree, i + 1, j * 2 + 1, path + tree[i][j], ans); + } +}; diff --git a/solutions/666. Path Sum IV/666.java b/solutions/666. Path Sum IV/666.java new file mode 100644 index 00000000000..c77be5e24b5 --- /dev/null +++ b/solutions/666. Path Sum IV/666.java @@ -0,0 +1,30 @@ +class Solution { + public int pathSum(int[] nums) { + int[][] tree = new int[4][8]; + Arrays.stream(tree).forEach(A -> Arrays.fill(A, -1)); + + for (final int num : nums) { + final int d = num / 100 - 1; + final int p = (num % 100) / 10 - 1; + final int v = num % 10; + tree[d][p] = v; + } + + dfs(tree, 0, 0, 0); + return ans; + } + + private int ans = 0; + + private void dfs(int[][] tree, int i, int j, int path) { + if (tree[i][j] == -1) + return; + if (i == 3 || Math.max(tree[i + 1][j * 2], tree[i + 1][j * 2 + 1]) == -1) { + ans += path + tree[i][j]; + return; + } + + dfs(tree, i + 1, j * 2, path + tree[i][j]); + dfs(tree, i + 1, j * 2 + 1, path + tree[i][j]); + } +} diff --git a/solutions/666. Path Sum IV/666.py b/solutions/666. Path Sum IV/666.py new file mode 100644 index 00000000000..c4a8c226de6 --- /dev/null +++ b/solutions/666. Path Sum IV/666.py @@ -0,0 +1,24 @@ +class Solution: + def pathSum(self, nums: List[int]) -> int: + ans = 0 + tree = [[-1] * 8 for _ in range(4)] + + for num in nums: + d = num // 100 - 1 + p = (num % 100) // 10 - 1 + v = num % 10 + tree[d][p] = v + + def dfs(i: int, j: int, path: int) -> None: + nonlocal ans + if tree[i][j] == -1: + return + if i == 3 or max(tree[i + 1][j * 2], tree[i + 1][j * 2 + 1]) == -1: + ans += path + tree[i][j] + return + + dfs(i + 1, j * 2, path + tree[i][j]) + dfs(i + 1, j * 2 + 1, path + tree[i][j]) + + dfs(0, 0, 0) + return ans diff --git a/solutions/667. Beautiful Arrangement II/667.cpp b/solutions/667. Beautiful Arrangement II/667.cpp new file mode 100644 index 00000000000..5333ff1896d --- /dev/null +++ b/solutions/667. Beautiful Arrangement II/667.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector constructArray(int n, int k) { + vector ans; + + for (int i = 0; i < n - k; ++i) + ans.push_back(i + 1); + + for (int i = 0; i < k; ++i) + if (i % 2 == 0) + ans.push_back(n - i / 2); + else + ans.push_back(n - k + (i + 1) / 2); + + return ans; + } +}; diff --git a/solutions/667. Beautiful Arrangement II/667.java b/solutions/667. Beautiful Arrangement II/667.java new file mode 100644 index 00000000000..4b7531a9297 --- /dev/null +++ b/solutions/667. Beautiful Arrangement II/667.java @@ -0,0 +1,17 @@ +class Solution { + public int[] constructArray(int n, int k) { + int[] ans = new int[n]; + + for (int i = 0; i < n - k; ++i) + ans[i] = i + 1; + + for (int i = 0; i < k; ++i) { + if (i % 2 == 0) + ans[n - k + i] = n - i / 2; + else + ans[n - k + i] = n - k + (i + 1) / 2; + } + + return ans; + } +} diff --git a/solutions/667. Beautiful Arrangement II/667.py b/solutions/667. Beautiful Arrangement II/667.py new file mode 100644 index 00000000000..342c224f96e --- /dev/null +++ b/solutions/667. Beautiful Arrangement II/667.py @@ -0,0 +1,11 @@ +class Solution: + def constructArray(self, n: int, k: int) -> List[int]: + ans = list(range(1, n - k + 1)) + + for i in range(k): + if i % 2 == 0: + ans.append(n - i // 2) + else: + ans.append(n - k + (i + 1) // 2) + + return ans diff --git a/solutions/668. Kth Smallest Number in Multiplication Table/668.cpp b/solutions/668. Kth Smallest Number in Multiplication Table/668.cpp new file mode 100644 index 00000000000..9291328fc1e --- /dev/null +++ b/solutions/668. Kth Smallest Number in Multiplication Table/668.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int findKthNumber(int m, int n, int k) { + int l = 1; + int r = m * n; + + auto numsNoGreaterThan = [&](int target) { + int count = 0; + // For each row i, count the number of numbers <= target. + for (int i = 1; i <= m; ++i) + count += min(target / i, n); + return count; + }; + + while (l < r) { + const int mid = (l + r) / 2; + if (numsNoGreaterThan(mid) >= k) + r = mid; + else + l = mid + 1; + } + + return l; + } +}; diff --git a/solutions/668. Kth Smallest Number in Multiplication Table/668.java b/solutions/668. Kth Smallest Number in Multiplication Table/668.java new file mode 100644 index 00000000000..b2c23aee321 --- /dev/null +++ b/solutions/668. Kth Smallest Number in Multiplication Table/668.java @@ -0,0 +1,24 @@ +class Solution { + public int findKthNumber(int m, int n, int k) { + int l = 1; + int r = m * n; + + while (l < r) { + final int mid = (l + r) / 2; + if (numsNoGreaterThan(m, n, mid) >= k) + r = mid; + else + l = mid + 1; + } + + return l; + } + + private int numsNoGreaterThan(int m, int n, int target) { + int count = 0; + // For each row i, count the number of numbers <= target. + for (int i = 1; i <= m; ++i) + count += Math.min(target / i, n); + return count; + } +} diff --git a/solutions/669. Trim a Binary Search Tree/669.cpp b/solutions/669. Trim a Binary Search Tree/669.cpp new file mode 100644 index 00000000000..a33a22a9af8 --- /dev/null +++ b/solutions/669. Trim a Binary Search Tree/669.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + TreeNode* trimBST(TreeNode* root, int L, int R) { + if (root == nullptr) + return nullptr; + if (root->val < L) + return trimBST(root->right, L, R); + if (root->val > R) + return trimBST(root->left, L, R); + root->left = trimBST(root->left, L, R); + root->right = trimBST(root->right, L, R); + return root; + } +}; diff --git a/solutions/669. Trim a Binary Search Tree/669.java b/solutions/669. Trim a Binary Search Tree/669.java new file mode 100644 index 00000000000..784536b7675 --- /dev/null +++ b/solutions/669. Trim a Binary Search Tree/669.java @@ -0,0 +1,13 @@ +class Solution { + public TreeNode trimBST(TreeNode root, int low, int high) { + if (root == null) + return null; + if (root.val < low) + return trimBST(root.right, low, high); + if (root.val > high) + return trimBST(root.left, low, high); + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + return root; + } +} diff --git a/solutions/67. Add Binary/67.cpp b/solutions/67. Add Binary/67.cpp new file mode 100644 index 00000000000..2257613a0af --- /dev/null +++ b/solutions/67. Add Binary/67.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string addBinary(string a, string b) { + string ans; + int carry = 0; + int i = a.length() - 1; + int j = b.length() - 1; + + while (i >= 0 || j >= 0 || carry) { + if (i >= 0) + carry += a[i--] - '0'; + if (j >= 0) + carry += b[j--] - '0'; + ans += carry % 2 + '0'; + carry /= 2; + } + + reverse(ans.begin(), ans.end()); + return ans; + } +}; diff --git a/solutions/67. Add Binary/67.java b/solutions/67. Add Binary/67.java new file mode 100644 index 00000000000..3e6945ec422 --- /dev/null +++ b/solutions/67. Add Binary/67.java @@ -0,0 +1,19 @@ +class Solution { + public String addBinary(String a, String b) { + StringBuilder sb = new StringBuilder(); + int carry = 0; + int i = a.length() - 1; + int j = b.length() - 1; + + while (i >= 0 || j >= 0 || carry == 1) { + if (i >= 0) + carry += a.charAt(i--) - '0'; + if (j >= 0) + carry += b.charAt(j--) - '0'; + sb.append(carry % 2); + carry /= 2; + } + + return sb.reverse().toString(); + } +} diff --git a/solutions/67. Add Binary/67.py b/solutions/67. Add Binary/67.py new file mode 100644 index 00000000000..53e941c055d --- /dev/null +++ b/solutions/67. Add Binary/67.py @@ -0,0 +1,18 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + ans = [] + carry = 0 + i = len(a) - 1 + j = len(b) - 1 + + while i >= 0 or j >= 0 or carry: + if i >= 0: + carry += int(a[i]) + i -= 1 + if j >= 0: + carry += int(b[j]) + j -= 1 + ans.append(str(carry % 2)) + carry //= 2 + + return ''.join(reversed(ans)) diff --git a/solutions/670. Maximum Swap/670.cpp b/solutions/670. Maximum Swap/670.cpp new file mode 100644 index 00000000000..fe283f19859 --- /dev/null +++ b/solutions/670. Maximum Swap/670.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int maximumSwap(int num) { + string s = to_string(num); + vector lastIndex(10, -1); // {digit: last index} + + for (int i = 0; i < s.length(); ++i) + lastIndex[s[i] - '0'] = i; + + for (int i = 0; i < s.length(); ++i) + for (int d = 9; d > s[i] - '0'; --d) + if (lastIndex[d] > i) { + swap(s[i], s[lastIndex[d]]); + return stoi(s); + } + + return num; + } +}; diff --git a/solutions/670. Maximum Swap/670.java b/solutions/670. Maximum Swap/670.java new file mode 100644 index 00000000000..bb0c42c0c57 --- /dev/null +++ b/solutions/670. Maximum Swap/670.java @@ -0,0 +1,19 @@ +class Solution { + public int maximumSwap(int num) { + char[] s = Integer.toString(num).toCharArray(); + int[] lastIndex = new int[10]; // {digit: last index} + + for (int i = 0; i < s.length; ++i) + lastIndex[s[i] - '0'] = i; + + for (int i = 0; i < s.length; ++i) + for (int d = 9; d > s[i] - '0'; --d) + if (lastIndex[d] > i) { + s[lastIndex[d]] = s[i]; + s[i] = (char) ('0' + d); + return Integer.parseInt(new String(s)); + } + + return num; + } +} diff --git a/solutions/670. Maximum Swap/670.py b/solutions/670. Maximum Swap/670.py new file mode 100644 index 00000000000..b0404378d90 --- /dev/null +++ b/solutions/670. Maximum Swap/670.py @@ -0,0 +1,14 @@ +class Solution: + def maximumSwap(self, num: int) -> int: + s = list(str(num)) + dict = {c: i for i, c in enumerate(s)} + + for i, c in enumerate(s): + for digit in reversed(string.digits): + if digit <= c: + break + if digit in dict and dict[digit] > i: + s[i], s[dict[digit]] = digit, s[i] + return int(''.join(s)) + + return num diff --git a/solutions/671. Second Minimum Node In a Binary Tree/671.cpp b/solutions/671. Second Minimum Node In a Binary Tree/671.cpp new file mode 100644 index 00000000000..2304be95636 --- /dev/null +++ b/solutions/671. Second Minimum Node In a Binary Tree/671.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int findSecondMinimumValue(TreeNode* root) { + if (root == nullptr) + return -1; + return findSecondMinimumValue(root, root->val); + } + + private: + int findSecondMinimumValue(TreeNode* root, int mn) { + if (root == nullptr) + return -1; + if (root->val > mn) + return root->val; + + const int leftMin = findSecondMinimumValue(root->left, mn); + const int rightMin = findSecondMinimumValue(root->right, mn); + + if (leftMin == -1 || rightMin == -1) + return max(leftMin, rightMin); + return min(leftMin, rightMin); + } +}; diff --git a/solutions/671. Second Minimum Node In a Binary Tree/671.java b/solutions/671. Second Minimum Node In a Binary Tree/671.java new file mode 100644 index 00000000000..35ee9604223 --- /dev/null +++ b/solutions/671. Second Minimum Node In a Binary Tree/671.java @@ -0,0 +1,21 @@ +class Solution { + public int findSecondMinimumValue(TreeNode root) { + if (root == null) + return -1; + return findSecondMinimumValue(root, root.val); + } + + private int findSecondMinimumValue(TreeNode root, int mn) { + if (root == null) + return -1; + if (root.val > mn) + return root.val; + + final int leftMin = findSecondMinimumValue(root.left, mn); + final int rightMin = findSecondMinimumValue(root.right, mn); + + if (leftMin == -1 || rightMin == -1) + return Math.max(leftMin, rightMin); + return Math.min(leftMin, rightMin); + } +} diff --git a/solutions/672. Bulb Switcher II/672.cpp b/solutions/672. Bulb Switcher II/672.cpp new file mode 100644 index 00000000000..33029aaf13f --- /dev/null +++ b/solutions/672. Bulb Switcher II/672.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int flipLights(int n, int m) { + n = min(n, 3); + + if (m == 0) + return 1; + if (m == 1) + return vector{2, 3, 4}[n - 1]; + if (m == 2) + return vector{2, 4, 7}[n - 1]; + + return pow(2, n); + } +}; diff --git a/solutions/672. Bulb Switcher II/672.java b/solutions/672. Bulb Switcher II/672.java new file mode 100644 index 00000000000..45ef904b239 --- /dev/null +++ b/solutions/672. Bulb Switcher II/672.java @@ -0,0 +1,14 @@ +class Solution { + public int flipLights(int n, int m) { + n = Math.min(n, 3); + + if (m == 0) + return 1; + if (m == 1) + return new int[] {2, 3, 4}[n - 1]; + if (m == 2) + return new int[] {2, 4, 7}[n - 1]; + + return (int) Math.pow(2, n); + } +} diff --git a/solutions/672. Bulb Switcher II/672.py b/solutions/672. Bulb Switcher II/672.py new file mode 100644 index 00000000000..6dd14e2b453 --- /dev/null +++ b/solutions/672. Bulb Switcher II/672.py @@ -0,0 +1,12 @@ +class Solution: + def flipLights(self, n: int, m: int) -> int: + n = min(n, 3) + + if m == 0: + return 1 + if m == 1: + return [2, 3, 4][n - 1] + if m == 2: + return [2, 4, 7][n - 1] + + return [2, 4, 8][n - 1] diff --git a/solutions/673. Number of Longest Increasing Subsequence/673.cpp b/solutions/673. Number of Longest Increasing Subsequence/673.cpp new file mode 100644 index 00000000000..9284b3625eb --- /dev/null +++ b/solutions/673. Number of Longest Increasing Subsequence/673.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int findNumberOfLIS(vector& nums) { + const int n = nums.size(); + int ans = 0; + int maxLength = 0; + // length[i] := the length of LIS's ending in nums[i] + vector length(n, 1); + // count[i] := the number of LIS's ending in nums[i] + vector count(n, 1); + + // Calculate `length` and `count` arrays. + for (int i = 0; i < n; ++i) + for (int j = 0; j < i; ++j) + if (nums[j] < nums[i]) + if (length[i] < length[j] + 1) { + length[i] = length[j] + 1; + count[i] = count[j]; + } else if (length[i] == length[j] + 1) { + count[i] += count[j]; + } + + // Get the number of LIS. + for (int i = 0; i < n; ++i) + if (length[i] > maxLength) { + maxLength = length[i]; + ans = count[i]; + } else if (length[i] == maxLength) { + ans += count[i]; + } + + return ans; + } +}; diff --git a/solutions/673. Number of Longest Increasing Subsequence/673.java b/solutions/673. Number of Longest Increasing Subsequence/673.java new file mode 100644 index 00000000000..3919ada229b --- /dev/null +++ b/solutions/673. Number of Longest Increasing Subsequence/673.java @@ -0,0 +1,36 @@ +class Solution { + public int findNumberOfLIS(int[] nums) { + final int n = nums.length; + int ans = 0; + int maxLength = 0; + // length[i] := the length of the LIS ending in nums[i] + int[] length = new int[n]; + // count[i] := the number of LIS's ending in nums[i] + int[] count = new int[n]; + + Arrays.fill(length, 1); + Arrays.fill(count, 1); + + // Calculate the `length` and `count` arrays. + for (int i = 0; i < n; ++i) + for (int j = 0; j < i; ++j) + if (nums[j] < nums[i]) + if (length[i] < length[j] + 1) { + length[i] = length[j] + 1; + count[i] = count[j]; + } else if (length[i] == length[j] + 1) { + count[i] += count[j]; + } + + // Get the number of LIS. + for (int i = 0; i < n; ++i) + if (length[i] > maxLength) { + maxLength = length[i]; + ans = count[i]; + } else if (length[i] == maxLength) { + ans += count[i]; + } + + return ans; + } +} diff --git a/solutions/673. Number of Longest Increasing Subsequence/673.py b/solutions/673. Number of Longest Increasing Subsequence/673.py new file mode 100644 index 00000000000..26953aa454d --- /dev/null +++ b/solutions/673. Number of Longest Increasing Subsequence/673.py @@ -0,0 +1,28 @@ +class Solution: + def findNumberOfLIS(self, nums: List[int]) -> int: + ans = 0 + maxLength = 0 + # length[i] := the length of the LIS ending in nums[i] + length = [1] * len(nums) + # count[i] := the number of LIS's ending in nums[i] + count = [1] * len(nums) + + # Calculate the `length` and `count` arrays. + for i, num in enumerate(nums): + for j in range(i): + if nums[j] < num: + if length[i] < length[j] + 1: + length[i] = length[j] + 1 + count[i] = count[j] + elif length[i] == length[j] + 1: + count[i] += count[j] + + # Get the number of LIS. + for i, l in enumerate(length): + if l > maxLength: + maxLength = l + ans = count[i] + elif l == maxLength: + ans += count[i] + + return ans diff --git a/solutions/674. Longest Continuous Increasing Subsequence/674.cpp b/solutions/674. Longest Continuous Increasing Subsequence/674.cpp new file mode 100644 index 00000000000..15422154fd3 --- /dev/null +++ b/solutions/674. Longest Continuous Increasing Subsequence/674.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int findLengthOfLCIS(vector& nums) { + int ans = 0; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (r > 0 && nums[r] <= nums[r - 1]) + l = r; + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/674. Longest Continuous Increasing Subsequence/674.java b/solutions/674. Longest Continuous Increasing Subsequence/674.java new file mode 100644 index 00000000000..9335137f426 --- /dev/null +++ b/solutions/674. Longest Continuous Increasing Subsequence/674.java @@ -0,0 +1,13 @@ +class Solution { + public int findLengthOfLCIS(int[] nums) { + int ans = 0; + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (r > 0 && nums[r] <= nums[r - 1]) + l = r; + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/674. Longest Continuous Increasing Subsequence/674.py b/solutions/674. Longest Continuous Increasing Subsequence/674.py new file mode 100644 index 00000000000..3676c214ed3 --- /dev/null +++ b/solutions/674. Longest Continuous Increasing Subsequence/674.py @@ -0,0 +1,11 @@ +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + ans = 0 + j = 0 + + for i in range(len(nums)): + if i > 0 and nums[i] <= nums[i - 1]: + j = i + ans = max(ans, i - j + 1) + + return ans diff --git a/solutions/675. Cut Off Trees for Golf Event/675.cpp b/solutions/675. Cut Off Trees for Golf Event/675.cpp new file mode 100644 index 00000000000..0fd8121ec8a --- /dev/null +++ b/solutions/675. Cut Off Trees for Golf Event/675.cpp @@ -0,0 +1,71 @@ +struct T { + int i; + int j; + int height; + T(int i, int j, int height) : i(i), j(j), height(height) {} +}; + +class Solution { + public: + int cutOffTree(vector>& forest) { + auto compare = [&](const T& a, const T& b) { return a.height > b.height; }; + priority_queue, decltype(compare)> minHeap(compare); + + for (int i = 0; i < forest.size(); ++i) + for (int j = 0; j < forest[0].size(); ++j) + if (forest[i][j] > 1) + minHeap.emplace(i, j, forest[i][j]); + + int ans = 0; + int x = 0; + int y = 0; + + while (!minHeap.empty()) { + const auto [i, j, _] = minHeap.top(); + minHeap.pop(); + // Walk from (x, y) to (i, j). + const int steps = bfs(forest, x, y, i, j); + if (steps < 0) + return -1; + ans += steps; + x = i; + y = j; + } + + return ans; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + int bfs(const vector>& forest, int si, int sj, int ei, int ej) { + const int m = forest.size(); + const int n = forest[0].size(); + int steps = 0; + queue> q{{{si, sj}}}; + vector> seen(m, vector(n)); + seen[si][sj] = true; + + while (!q.empty()) { + for (int s = q.size(); s > 0; --s) { + const auto [i, j] = q.front(); + q.pop(); + if (i == ei && j == ej) + return steps; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y] || forest[x][y] == 0) + continue; + q.emplace(x, y); + seen[x][y] = true; + } + } + ++steps; + } + + return -1; + }; +}; diff --git a/solutions/675. Cut Off Trees for Golf Event/675.java b/solutions/675. Cut Off Trees for Golf Event/675.java new file mode 100644 index 00000000000..0bcc892bffa --- /dev/null +++ b/solutions/675. Cut Off Trees for Golf Event/675.java @@ -0,0 +1,72 @@ +class T { + public int i; + public int j; + public int height; + public T(int i, int j, int height) { + this.i = i; + this.j = j; + this.height = height; + } +} + +class Solution { + public int cutOffTree(List> forest) { + Queue minHeap = new PriorityQueue<>((a, b) -> a.height - b.height); + + for (int i = 0; i < forest.size(); ++i) + for (int j = 0; j < forest.get(0).size(); ++j) + if (forest.get(i).get(j) > 1) + minHeap.offer(new T(i, j, forest.get(i).get(j))); + + int ans = 0; + int x = 0; + int y = 0; + + while (!minHeap.isEmpty()) { + final int i = minHeap.peek().i; + final int j = minHeap.poll().j; + // Walk from (x, y) to (i, j). + final int steps = bfs(forest, x, y, i, j); + if (steps < 0) + return -1; + ans += steps; + x = i; + y = j; + } + + return ans; + } + + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private int bfs(List> forest, int si, int sj, int ei, int ej) { + final int m = forest.size(); + final int n = forest.get(0).size(); + int steps = 0; + Queue q = new ArrayDeque<>(Arrays.asList(new int[] {si, sj})); + boolean[][] seen = new boolean[m][n]; + seen[si][sj] = true; + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + if (i == ei && j == ej) + return steps; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (seen[x][y] || forest.get(x).get(y) == 0) + continue; + q.offer(new int[] {x, y}); + seen[x][y] = true; + } + } + ++steps; + } + + return -1; + }; +} diff --git a/solutions/676. Implement Magic Dictionary/676-2.cpp b/solutions/676. Implement Magic Dictionary/676-2.cpp new file mode 100644 index 00000000000..22ef8cacaee --- /dev/null +++ b/solutions/676. Implement Magic Dictionary/676-2.cpp @@ -0,0 +1,59 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class MagicDictionary { + public: + void buildDict(vector dictionary) { + for (const string& word : dictionary) + insert(word); + } + + bool search(string searchWord) { + shared_ptr node = root; + for (int i = 0; i < searchWord.length(); ++i) { + const int index = searchWord[i] - 'a'; + for (int j = 0; j < 26; ++j) { + if (j == index) + continue; + shared_ptr child = node->children[j]; + if (child == nullptr) + continue; + // Replace the searchWord[i] with ('a' + j), then check if + // searchWord[i + 1..n) matches `child`. + if (find(child, searchWord, i + 1)) + return true; + } + if (node->children[index] == nullptr) + return false; + node = node->children[index]; + } + return false; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->isWord = true; + } + + bool find(shared_ptr node, const string& word, int s) { + for (int i = s; i < word.length(); ++i) { + const int index = word[i] - 'a'; + if (node->children[index] == nullptr) + return false; + node = node->children[index]; + } + return node->isWord; + } +}; diff --git a/solutions/676. Implement Magic Dictionary/676-2.java b/solutions/676. Implement Magic Dictionary/676-2.java new file mode 100644 index 00000000000..8ad4f6a3e36 --- /dev/null +++ b/solutions/676. Implement Magic Dictionary/676-2.java @@ -0,0 +1,56 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class MagicDictionary { + public void buildDict(String[] dictionary) { + for (final String word : dictionary) + insert(word); + } + + public boolean search(String searchWord) { + TrieNode node = root; + for (int i = 0; i < searchWord.length(); ++i) { + final int index = searchWord.charAt(i) - 'a'; + for (int j = 0; j < 26; ++j) { + if (j == index) + continue; + TrieNode child = node.children[j]; + if (child == null) + continue; + // Replace the searchWord[i] with ('a' + j), then check if + // searchWord[i + 1..n) matches `child`. + if (find(child, searchWord, i + 1)) + return true; + } + if (node.children[index] == null) + return false; + node = node.children[index]; + } + return false; + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + private boolean find(TrieNode node, final String word, int s) { + for (int i = s; i < word.length(); ++i) { + final int index = word.charAt(i) - 'a'; + if (node.children[index] == null) + return false; + node = node.children[index]; + } + return node.isWord; + } +} diff --git a/solutions/676. Implement Magic Dictionary/676-2.py b/solutions/676. Implement Magic Dictionary/676-2.py new file mode 100644 index 00000000000..a849038bbac --- /dev/null +++ b/solutions/676. Implement Magic Dictionary/676-2.py @@ -0,0 +1,44 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode) + self.isWord = False + + +class MagicDictionary: + def __init__(self): + self.root = TrieNode() + + def buildDict(self, dictionary: List[str]) -> None: + for word in dictionary: + self._insert(word) + + def search(self, searchWord: str) -> bool: + node: TrieNode = self.root + for i, c in enumerate(searchWord): + for letter in string.ascii_lowercase: + if letter == c: + continue + child = node.children[letter] + if not child: + continue + # Replace the searchWord[i] with `letter`, then check if + # searchWord[i + 1..n) matches `child`. + if self._find(child, searchWord, i + 1): + return True + if not node.children[c]: + return False + node = node.children[c] + return False + + def _insert(self, word: str) -> None: + node: TrieNode = self.root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.isWord = True + + def _find(self, node: TrieNode, word: str, i: int) -> bool: + for c in word[i:]: + if c not in node.children: + return False + node = node.children[c] + return node.isWord diff --git a/solutions/676. Implement Magic Dictionary/676.cpp b/solutions/676. Implement Magic Dictionary/676.cpp new file mode 100644 index 00000000000..fb95b40492c --- /dev/null +++ b/solutions/676. Implement Magic Dictionary/676.cpp @@ -0,0 +1,27 @@ +class MagicDictionary { + public: + void buildDict(vector dictionary) { + for (const string& word : dictionary) + for (int i = 0; i < word.length(); ++i) { + const string replaced = getReplaced(word, i); + dict[replaced] = dict.contains(replaced) ? '*' : word[i]; + } + } + + bool search(string searchWord) { + for (int i = 0; i < searchWord.length(); ++i) { + const string replaced = getReplaced(searchWord, i); + if (const auto it = dict.find(replaced); + it != dict.cend() && it->second != searchWord[i]) + return true; + } + return false; + } + + private: + unordered_map dict; + + string getReplaced(const string& s, int i) { + return s.substr(0, i) + '*' + s.substr(i + 1); + } +}; diff --git a/solutions/676. Implement Magic Dictionary/676.java b/solutions/676. Implement Magic Dictionary/676.java new file mode 100644 index 00000000000..f6e919ec9f4 --- /dev/null +++ b/solutions/676. Implement Magic Dictionary/676.java @@ -0,0 +1,24 @@ +class MagicDictionary { + public void buildDict(String[] dictionary) { + for (final String word : dictionary) + for (int i = 0; i < word.length(); ++i) { + final String replaced = getReplaced(word, i); + dict.put(replaced, dict.containsKey(replaced) ? '*' : word.charAt(i)); + } + } + + public boolean search(String searchWord) { + for (int i = 0; i < searchWord.length(); ++i) { + final String replaced = getReplaced(searchWord, i); + if (dict.getOrDefault(replaced, searchWord.charAt(i)) != searchWord.charAt(i)) + return true; + } + return false; + } + + private Map dict = new HashMap<>(); + + private String getReplaced(final String s, int i) { + return s.substring(0, i) + '*' + s.substring(i + 1); + } +} diff --git a/solutions/676. Implement Magic Dictionary/676.py b/solutions/676. Implement Magic Dictionary/676.py new file mode 100644 index 00000000000..36a83c3b80e --- /dev/null +++ b/solutions/676. Implement Magic Dictionary/676.py @@ -0,0 +1,19 @@ +class MagicDictionary: + def __init__(self): + self.dict = {} + + def buildDict(self, dictionary: List[str]) -> None: + for word in dictionary: + for i, c in enumerate(word): + replaced = self._getReplaced(word, i) + self.dict[replaced] = '*' if replaced in self.dict else c + + def search(self, searchWord: str) -> bool: + for i, c in enumerate(searchWord): + replaced = self._getReplaced(searchWord, i) + if self.dict.get(replaced, c) != c: + return True + return False + + def _getReplaced(self, s: str, i: int) -> str: + return s[:i] + '*' + s[i + 1:] diff --git a/solutions/677. Map Sum Pairs/677.cpp b/solutions/677. Map Sum Pairs/677.cpp new file mode 100644 index 00000000000..aeb1974c7ab --- /dev/null +++ b/solutions/677. Map Sum Pairs/677.cpp @@ -0,0 +1,36 @@ +struct TrieNode { + vector> children; + int sum = 0; + TrieNode() : children(26) {} +}; + +class MapSum { + public: + void insert(string key, int val) { + const int diff = val - keyToVal[key]; + shared_ptr node = root; + for (const char c : key) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + node->sum += diff; + } + keyToVal[key] = val; + } + + int sum(string prefix) { + shared_ptr node = root; + for (const char c : prefix) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + return 0; + node = node->children[i]; + } + return node->sum; + } + + private: + shared_ptr root = make_shared(); + unordered_map keyToVal; +}; diff --git a/solutions/677. Map Sum Pairs/677.java b/solutions/677. Map Sum Pairs/677.java new file mode 100644 index 00000000000..008b59cbee3 --- /dev/null +++ b/solutions/677. Map Sum Pairs/677.java @@ -0,0 +1,33 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int sum = 0; +} + +class MapSum { + public void insert(String key, int val) { + final int diff = val - keyToVal.getOrDefault(key, 0); + TrieNode node = root; + for (final char c : key.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + node.sum += diff; + } + keyToVal.put(key, val); + } + + public int sum(String prefix) { + TrieNode node = root; + for (final char c : prefix.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + return 0; + node = node.children[i]; + } + return node.sum; + } + + private TrieNode root = new TrieNode(); + private Map keyToVal = new HashMap<>(); +} diff --git a/solutions/677. Map Sum Pairs/677.py b/solutions/677. Map Sum Pairs/677.py new file mode 100644 index 00000000000..5da51ce6e2f --- /dev/null +++ b/solutions/677. Map Sum Pairs/677.py @@ -0,0 +1,26 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.sum = 0 + + +class MapSum: + def __init__(self): + self.root = TrieNode() + self.keyToVal = {} + + def insert(self, key: str, val: int) -> None: + diff = val - self.keyToVal.get(key, 0) + node: TrieNode = self.root + for c in key: + node = node.children.setdefault(c, TrieNode()) + node.sum += diff + self.keyToVal[key] = val + + def sum(self, prefix: str) -> int: + node: TrieNode = self.root + for c in prefix: + if c not in node.children: + return 0 + node = node.children[c] + return node.sum diff --git a/solutions/678. Valid Parenthesis String/678.cpp b/solutions/678. Valid Parenthesis String/678.cpp new file mode 100644 index 00000000000..5fe861d1994 --- /dev/null +++ b/solutions/678. Valid Parenthesis String/678.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + bool checkValidString(const string& s) { + int low = 0; // the lower bound of the number of valid '('s + int high = 0; // the upper bound of the number of valid '('s + + for (const char c : s) { + switch (c) { + case '(': + ++low; + ++high; + break; + case ')': + low = max(0, --low); + --high; + break; + case '*': + low = max(0, --low); + ++high; + break; + } + if (high < 0) + return false; + } + + return low == 0; + } +}; diff --git a/solutions/678. Valid Parenthesis String/678.java b/solutions/678. Valid Parenthesis String/678.java new file mode 100644 index 00000000000..2f9e2af9f27 --- /dev/null +++ b/solutions/678. Valid Parenthesis String/678.java @@ -0,0 +1,27 @@ +class Solution { + public boolean checkValidString(final String s) { + int low = 0; // the lower bound of the number of valid '('s + int high = 0; // the upper bound of the number of valid '('s + + for (final char c : s.toCharArray()) { + switch (c) { + case '(': + ++low; + ++high; + break; + case ')': + low = Math.max(0, --low); + --high; + break; + case '*': + low = Math.max(0, --low); + ++high; + break; + } + if (high < 0) + return false; + } + + return low == 0; + } +} diff --git a/solutions/678. Valid Parenthesis String/678.py b/solutions/678. Valid Parenthesis String/678.py new file mode 100644 index 00000000000..04e3e00b6cb --- /dev/null +++ b/solutions/678. Valid Parenthesis String/678.py @@ -0,0 +1,21 @@ +class Solution: + def checkValidString(self, s: str) -> bool: + low = 0 + high = 0 + + for c in s: + if c == '(': + low += 1 + high += 1 + elif c == ')': + if low > 0: + low -= 1 + high -= 1 + else: + if low > 0: + low -= 1 + high += 1 + if high < 0: + return False + + return low == 0 diff --git a/solutions/679. 24 Game/679.cpp b/solutions/679. 24 Game/679.cpp new file mode 100644 index 00000000000..5b2e2a42faa --- /dev/null +++ b/solutions/679. 24 Game/679.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + bool judgePoint24(vector& nums) { + vector doubleNums; + + for (const int num : nums) + doubleNums.push_back(num); + + return dfs(doubleNums); + } + + private: + bool dfs(vector& nums) { + if (nums.size() == 1) + return abs(nums[0] - 24) < 0.001; + + for (int i = 0; i < nums.size(); ++i) + for (int j = 0; j < i; ++j) { + for (const double num : generate(nums[i], nums[j])) { + vector nextRound{num}; + for (int k = 0; k < nums.size(); ++k) { + if (k == i || k == j) // It is used in `generate()`. + continue; + nextRound.push_back(nums[k]); + } + if (dfs(nextRound)) + return true; + } + } + + return false; + } + + vector generate(double a, double b) { + return {a * b, a / b, b / a, a + b, a - b, b - a}; + } +}; diff --git a/solutions/679. 24 Game/679.java b/solutions/679. 24 Game/679.java new file mode 100644 index 00000000000..26a00923ef7 --- /dev/null +++ b/solutions/679. 24 Game/679.java @@ -0,0 +1,34 @@ +class Solution { + public boolean judgePoint24(int[] nums) { + List doubleNums = new ArrayList<>(); + + for (final int num : nums) + doubleNums.add((double) num); + + return dfs(doubleNums); + } + + private boolean dfs(List nums) { + if (nums.size() == 1) + return Math.abs(nums.get(0) - 24.0) < 0.001; + + for (int i = 0; i < nums.size(); ++i) + for (int j = i + 1; j < nums.size(); ++j) + for (final double num : generate(nums.get(i), nums.get(j))) { + List nextRound = new ArrayList<>(Arrays.asList(num)); + for (int k = 0; k < nums.size(); ++k) { + if (k == i || k == j) // It is used in `generate()`. + continue; + nextRound.add(nums.get(k)); + } + if (dfs(nextRound)) + return true; + } + + return false; + } + + private double[] generate(double a, double b) { + return new double[] {a * b, a / b, b / a, a + b, a - b, b - a}; + } +} diff --git a/solutions/679. 24 Game/679.py b/solutions/679. 24 Game/679.py new file mode 100644 index 00000000000..abdec026c0f --- /dev/null +++ b/solutions/679. 24 Game/679.py @@ -0,0 +1,26 @@ +class Solution: + def judgePoint24(self, nums: List[int]) -> bool: + def generate(a: float, b: float) -> List[float]: + return [a * b, + math.inf if b == 0 else a / b, + math.inf if a == 0 else b / a, + a + b, a - b, b - a] + + def dfs(nums: List[float]) -> bool: + if len(nums) == 1: + return abs(nums[0] - 24.0) < 0.001 + + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + for num in generate(nums[i], nums[j]): + nextRound = [num] + for k in range(len(nums)): + if k == i or k == j: + continue + nextRound.append(nums[k]) + if dfs(nextRound): + return True + + return False + + return dfs(nums) diff --git a/solutions/68. Text Justification/68.cpp b/solutions/68. Text Justification/68.cpp new file mode 100644 index 00000000000..14cacbcc913 --- /dev/null +++ b/solutions/68. Text Justification/68.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + vector fullJustify(vector& words, size_t maxWidth) { + vector ans; + vector row; + size_t rowLetters = 0; + + for (const string& word : words) { + // If we place the word in this row, it will exceed the maximum width. + // Therefore, we cannot put the word in this row and have to pad spaces + // for each word in this row. + if (rowLetters + row.size() + word.length() > maxWidth) { + const int spaces = maxWidth - rowLetters; + if (row.size() == 1) { + // Pad all the spaces after row[0]. + for (int i = 0; i < spaces; ++i) + row[0] += " "; + } else { + // Evenly pad all the spaces to each word (expect the last one) in + // this row. + for (int i = 0; i < spaces; ++i) + row[i % (row.size() - 1)] += " "; + } + ans.push_back(join(row, "")); + row.clear(); + rowLetters = 0; + } + row.push_back(word); + rowLetters += word.length(); + } + ans.push_back(ljust(join(row, " "), maxWidth)); + + return ans; + } + + private: + string join(const vector& words, const string& s) { + string joined; + for (int i = 0; i < words.size(); ++i) { + joined += words[i]; + if (i != words.size() - 1) + joined += s; + } + return joined; + } + + string ljust(string s, int width) { + for (int i = 0; i < s.length() - width; ++i) + s += " "; + return s; + } +}; diff --git a/solutions/68. Text Justification/68.java b/solutions/68. Text Justification/68.java new file mode 100644 index 00000000000..14c975af43d --- /dev/null +++ b/solutions/68. Text Justification/68.java @@ -0,0 +1,43 @@ +class Solution { + public List fullJustify(String[] words, int maxWidth) { + List ans = new ArrayList<>(); + List row = new ArrayList<>(); + int rowLetters = 0; + + for (final String word : words) { + // If we place the word in this row, it will exceed the maximum width. + // Therefore, we cannot put the word in this row and have to pad spaces + // for each word in this row. + if (rowLetters + row.size() + word.length() > maxWidth) { + final int spaces = maxWidth - rowLetters; + if (row.size() == 1) { + // Pad all the spaces after row[0]. + for (int i = 0; i < spaces; ++i) + row.get(0).append(" "); + } else { + // Evenly pad all the spaces to each word (expect the last one) in + // this row. + for (int i = 0; i < spaces; ++i) + row.get(i % (row.size() - 1)).append(" "); + } + final String joinedRow = + row.stream().map(StringBuilder::toString).collect(Collectors.joining("")); + ans.add(joinedRow); + row.clear(); + rowLetters = 0; + } + row.add(new StringBuilder(word)); + rowLetters += word.length(); + } + + final String lastRow = + row.stream().map(StringBuilder::toString).collect(Collectors.joining(" ")); + StringBuilder sb = new StringBuilder(lastRow); + final int spacesToBeAdded = maxWidth - sb.length(); + for (int i = 0; i < spacesToBeAdded; ++i) + sb.append(" "); + + ans.add(sb.toString()); + return ans; + } +} diff --git a/solutions/68. Text Justification/68.py b/solutions/68. Text Justification/68.py new file mode 100644 index 00000000000..8b4de0ba29a --- /dev/null +++ b/solutions/68. Text Justification/68.py @@ -0,0 +1,20 @@ +class Solution: + def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: + ans = [] + row = [] + rowLetters = 0 + + for word in words: + # If we place the word in this row, it will exceed the maximum width. + # Therefore, we cannot put the word in this row and have to pad spaces + # for each word in this row. + if rowLetters + len(word) + len(row) > maxWidth: + for i in range(maxWidth - rowLetters): + row[i % (len(row) - 1 or 1)] += ' ' + ans.append(''.join(row)) + row = [] + rowLetters = 0 + row.append(word) + rowLetters += len(word) + + return ans + [' '.join(row).ljust(maxWidth)] diff --git a/solutions/680. Valid Palindrome II/680.cpp b/solutions/680. Valid Palindrome II/680.cpp new file mode 100644 index 00000000000..d1119457cf6 --- /dev/null +++ b/solutions/680. Valid Palindrome II/680.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + bool validPalindrome(string s) { + for (int l = 0, r = s.length() - 1; l < r; ++l, --r) + if (s[l] != s[r]) + return validPalindrome(s, l + 1, r) || // + validPalindrome(s, l, r - 1); + return true; + } + + private: + bool validPalindrome(const string& s, int l, int r) { + while (l < r) + if (s[l++] != s[r--]) + return false; + return true; + } +}; diff --git a/solutions/680. Valid Palindrome II/680.java b/solutions/680. Valid Palindrome II/680.java new file mode 100644 index 00000000000..a95a63df1d6 --- /dev/null +++ b/solutions/680. Valid Palindrome II/680.java @@ -0,0 +1,15 @@ +class Solution { + public boolean validPalindrome(String s) { + for (int l = 0, r = s.length() - 1; l < r; ++l, --r) + if (s.charAt(l) != s.charAt(r)) + return validPalindrome(s, l + 1, r) || validPalindrome(s, l, r - 1); + return true; + } + + private boolean validPalindrome(final String s, int l, int r) { + while (l < r) + if (s.charAt(l++) != s.charAt(r--)) + return false; + return true; + } +} diff --git a/solutions/680. Valid Palindrome II/680.py b/solutions/680. Valid Palindrome II/680.py new file mode 100644 index 00000000000..82be08f472a --- /dev/null +++ b/solutions/680. Valid Palindrome II/680.py @@ -0,0 +1,12 @@ +class Solution: + def validPalindrome(self, s: str) -> bool: + def validPalindrome(l: int, r: int) -> bool: + return all(s[i] == s[r - i + l] for i in range(l, (l + r) // 2 + 1)) + + n = len(s) + + for i in range(n // 2): + if s[i] != s[~i]: + return validPalindrome(i + 1, n - 1 - i) or validPalindrome(i, n - 2 - i) + + return True diff --git a/solutions/681. Next Closest Time/681.cpp b/solutions/681. Next Closest Time/681.cpp new file mode 100644 index 00000000000..a0e2b6f30ad --- /dev/null +++ b/solutions/681. Next Closest Time/681.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + string nextClosestTime(string time) { + const set digitsSet{time[0], time[1], time[3], time[4]}; + string ans = time; + + ans[4] = nextClosest(digitsSet, ans[4], '9'); + if (time[4] < ans[4]) + return ans; + + ans[3] = nextClosest(digitsSet, ans[3], '5'); + if (time[3] < ans[3]) + return ans; + + ans[1] = nextClosest(digitsSet, ans[1], ans[0] == '2' ? '3' : '9'); + if (time[1] < ans[1]) + return ans; + + ans[0] = nextClosest(digitsSet, ans[0], '2'); + return ans; + } + + private: + char nextClosest(const set& digitsSet, char digit, char limit) { + auto it = digitsSet.upper_bound(digit); + return it == digitsSet.end() || *it > limit ? *digitsSet.begin() : *it; + } +}; diff --git a/solutions/681. Next Closest Time/681.java b/solutions/681. Next Closest Time/681.java new file mode 100644 index 00000000000..2b41c144e75 --- /dev/null +++ b/solutions/681. Next Closest Time/681.java @@ -0,0 +1,27 @@ +class Solution { + public String nextClosestTime(String time) { + char[] ans = time.toCharArray(); + Character[] digits = {ans[0], ans[1], ans[3], ans[4]}; + TreeSet digitsSet = new TreeSet(Arrays.asList(digits)); + + ans[4] = nextClosest(digitsSet, ans[4], '9'); + if (time.charAt(4) < ans[4]) + return new String(ans); + + ans[3] = nextClosest(digitsSet, ans[3], '5'); + if (time.charAt(3) < ans[3]) + return new String(ans); + + ans[1] = nextClosest(digitsSet, ans[1], ans[0] == '2' ? '3' : '9'); + if (time.charAt(1) < ans[1]) + return new String(ans); + + ans[0] = nextClosest(digitsSet, ans[0], '2'); + return new String(ans); + } + + private char nextClosest(TreeSet digitsSet, char digit, char limit) { + Character next = digitsSet.higher(digit); + return next == null || next > limit ? digitsSet.first() : next; + } +} diff --git a/solutions/681. Next Closest Time/681.py b/solutions/681. Next Closest Time/681.py new file mode 100644 index 00000000000..1edc5cb60a8 --- /dev/null +++ b/solutions/681. Next Closest Time/681.py @@ -0,0 +1,23 @@ +class Solution: + def nextClosestTime(self, time: str) -> str: + ans = list(time) + digits = sorted(ans) + + def nextClosest(digit: str, limit: str) -> chr: + next = bisect_right(digits, digit) + return digits[0] if next == 4 or digits[next] > limit else digits[next] + + ans[4] = nextClosest(ans[4], '9') + if time[4] < ans[4]: + return ''.join(ans) + + ans[3] = nextClosest(ans[3], '5') + if time[3] < ans[3]: + return ''.join(ans) + + ans[1] = nextClosest(ans[1], '3' if ans[0] == '2' else '9') + if time[1] < ans[1]: + return ''.join(ans) + + ans[0] = nextClosest(ans[0], '2') + return ''.join(ans) diff --git a/solutions/682. Baseball Game/682.cpp b/solutions/682. Baseball Game/682.cpp new file mode 100644 index 00000000000..85fce259d57 --- /dev/null +++ b/solutions/682. Baseball Game/682.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int calPoints(vector& operations) { + vector scores; + + for (const string& operation : operations) + if (operation == "+") + scores.push_back(scores.back() + scores[scores.size() - 2]); + else if (operation == "D") + scores.push_back(scores.back() * 2); + else if (operation == "C") + scores.pop_back(); + else + scores.push_back(stoi(operation)); + + return accumulate(scores.begin(), scores.end(), 0); + } +}; diff --git a/solutions/682. Baseball Game/682.java b/solutions/682. Baseball Game/682.java new file mode 100644 index 00000000000..73ec0d59800 --- /dev/null +++ b/solutions/682. Baseball Game/682.java @@ -0,0 +1,26 @@ +class Solution { + public int calPoints(String[] operations) { + Deque scores = new ArrayDeque<>(); + + for (final String operation : operations) { + switch (operation) { + case "+": + final int lastScore = scores.pop(); + final int secondLastScore = scores.peek(); + scores.push(lastScore); + scores.push(lastScore + secondLastScore); + break; + case "D": + scores.push(scores.peek() * 2); + break; + case "C": + scores.pop(); + break; + default: + scores.push(Integer.parseInt(operation)); + } + } + + return scores.stream().mapToInt(Integer::intValue).sum(); + } +} diff --git a/solutions/682. Baseball Game/682.py b/solutions/682. Baseball Game/682.py new file mode 100644 index 00000000000..ffa62861451 --- /dev/null +++ b/solutions/682. Baseball Game/682.py @@ -0,0 +1,16 @@ +class Solution: + def calPoints(self, operations: List[str]) -> int: + scores = [] + + for operation in operations: + match operation: + case '+': + scores.append(scores[-1] + scores[-2]) + case 'D': + scores.append(scores[-1] * 2) + case 'C': + scores.pop() + case default: + scores.append(int(operation)) + + return sum(scores) diff --git a/solutions/683. K Empty Slots/683.cpp b/solutions/683. K Empty Slots/683.cpp new file mode 100644 index 00000000000..70e71bcb70c --- /dev/null +++ b/solutions/683. K Empty Slots/683.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int kEmptySlots(vector& bulbs, int k) { + const int n = bulbs.size(); + int ans = INT_MAX; + // day[i] := the day when bulbs[i] is turned on + vector day(n); + + for (int i = 0; i < n; ++i) + day[bulbs[i] - 1] = i + 1; + + // Find a subarray of day[l..r], where its length is k + 2. + // For each l < i < r, day[i] > max(day[l], day[r]). + int l = 0; + int r = l + k + 1; + for (int i = 1; r < n; ++i) + if (i == r) { + ans = min(ans, max(day[l], day[r])); + l = i; + r = i + k + 1; + } else if (day[i] < max(day[l], day[r])) { + l = i; + r = i + k + 1; + } + + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/solutions/683. K Empty Slots/683.java b/solutions/683. K Empty Slots/683.java new file mode 100644 index 00000000000..ec79f7992c7 --- /dev/null +++ b/solutions/683. K Empty Slots/683.java @@ -0,0 +1,27 @@ +class Solution { + public int kEmptySlots(int[] bulbs, int k) { + final int n = bulbs.length; + int ans = Integer.MAX_VALUE; + // day[i] := the day when bulbs[i] is turned on + int[] day = new int[n]; + + for (int i = 0; i < n; ++i) + day[bulbs[i] - 1] = i + 1; + + // Find a subarray of day[l..r], where its length is k + 2. + // For each l < i < r, day[i] > max(day[l], day[r]). + int l = 0; + int r = l + k + 1; + for (int i = 1; r < n; ++i) + if (i == r) { + ans = Math.min(ans, Math.max(day[l], day[r])); + l = i; + r = i + k + 1; + } else if (day[i] < Math.max(day[l], day[r])) { + l = i; + r = i + k + 1; + } + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/solutions/683. K Empty Slots/683.py b/solutions/683. K Empty Slots/683.py new file mode 100644 index 00000000000..37a40baa076 --- /dev/null +++ b/solutions/683. K Empty Slots/683.py @@ -0,0 +1,26 @@ +class Solution: + def kEmptySlots(self, bulbs: List[int], k: int) -> int: + n = len(bulbs) + ans = math.inf + # day[i] := the day when bulbs[i] is turned on + day = [0] * n + + for i, bulb in enumerate(bulbs): + day[bulb - 1] = i + 1 + + # Find a subarray of day[l..r], where its length is k + 2. + # For each l < i < r, day[i] > max(day[l], day[r]). + l = 0 + r = l + k + 1 + i = 1 + while r < n: + if i == r: + ans = min(ans, max(day[l], day[r])) + l = i + r = i + k + 1 + elif day[i] < max(day[l], day[r]): + l = i + r = i + k + 1 + i += 1 + + return -1 if ans == math.inf else ans diff --git a/solutions/684. Redundant Connection/684.cpp b/solutions/684. Redundant Connection/684.cpp new file mode 100644 index 00000000000..488c23dd614 --- /dev/null +++ b/solutions/684. Redundant Connection/684.cpp @@ -0,0 +1,46 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + bool unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + return true; + } + + private: + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + vector findRedundantConnection(vector>& edges) { + UnionFind uf(edges.size() + 1); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + if (!uf.unionByRank(u, v)) + return edge; + } + + throw; + } +}; diff --git a/solutions/684. Redundant Connection/684.java b/solutions/684. Redundant Connection/684.java new file mode 100644 index 00000000000..fbbb9ab7531 --- /dev/null +++ b/solutions/684. Redundant Connection/684.java @@ -0,0 +1,46 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public boolean unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + return true; + } + + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int[] findRedundantConnection(int[][] edges) { + UnionFind uf = new UnionFind(edges.length + 1); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + if (!uf.unionByRank(u, v)) + return edge; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/684. Redundant Connection/684.py b/solutions/684. Redundant Connection/684.py new file mode 100644 index 00000000000..f2bc22f871f --- /dev/null +++ b/solutions/684. Redundant Connection/684.py @@ -0,0 +1,33 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> bool: + i = self._find(u) + j = self._find(v) + if i == j: + return False + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + return True + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: + uf = UnionFind(len(edges) + 1) + + for edge in edges: + u, v = edge + if not uf.unionByRank(u, v): + return edge diff --git a/solutions/685. Redundant Connection II/685.cpp b/solutions/685. Redundant Connection II/685.cpp new file mode 100644 index 00000000000..b619e72533e --- /dev/null +++ b/solutions/685. Redundant Connection II/685.cpp @@ -0,0 +1,71 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + bool unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + return true; + } + + private: + vector id; + vector rank; + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + vector findRedundantDirectedConnection(vector>& edges) { + vector ids(edges.size() + 1); + int nodeWithTwoParents = 0; + + for (const vector& edge : edges) { + const int v = edge[1]; + if (++ids[v] == 2) { + nodeWithTwoParents = v; + break; + } + } + + // If there is no edge with two ids, don't skip any edge. + if (nodeWithTwoParents == 0) + return findRedundantDirectedConnection(edges, -1); + + for (int i = edges.size() - 1; i >= 0; --i) + if (edges[i][1] == nodeWithTwoParents) + // Try to delete the edges[i]. + if (findRedundantDirectedConnection(edges, i).empty()) + return edges[i]; + + throw; + } + + vector findRedundantDirectedConnection(const vector>& edges, + int skippedEdgeIndex) { + UnionFind uf(edges.size() + 1); + + for (int i = 0; i < edges.size(); ++i) { + if (i == skippedEdgeIndex) + continue; + if (!uf.unionByRank(edges[i][0], edges[i][1])) + return edges[i]; + } + + return {}; + } +}; diff --git a/solutions/685. Redundant Connection II/685.java b/solutions/685. Redundant Connection II/685.java new file mode 100644 index 00000000000..93784ae84e0 --- /dev/null +++ b/solutions/685. Redundant Connection II/685.java @@ -0,0 +1,71 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public boolean unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return false; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + return true; + } + + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int[] findRedundantDirectedConnection(int[][] edges) { + int[] ids = new int[edges.length + 1]; + int nodeWithTwoParents = 0; + + for (int[] edge : edges) { + final int v = edge[1]; + if (++ids[v] == 2) { + nodeWithTwoParents = v; + break; + } + } + + // If there is no edge with two ids, don't skip any edge. + if (nodeWithTwoParents == 0) + return findRedundantDirectedConnection(edges, -1); + + for (int i = edges.length - 1; i >= 0; --i) + if (edges[i][1] == nodeWithTwoParents) + // Try to delete the edges[i]. + if (findRedundantDirectedConnection(edges, i).length == 0) + return edges[i]; + + throw new IllegalArgumentException(); + } + + private int[] findRedundantDirectedConnection(int[][] edges, int skippedEdgeIndex) { + UnionFind uf = new UnionFind(edges.length + 1); + + for (int i = 0; i < edges.length; ++i) { + if (i == skippedEdgeIndex) + continue; + if (!uf.unionByRank(edges[i][0], edges[i][1])) + return edges[i]; + } + + return new int[] {}; + } +} diff --git a/solutions/685. Redundant Connection II/685.py b/solutions/685. Redundant Connection II/685.py new file mode 100644 index 00000000000..7e8fcb7cf8a --- /dev/null +++ b/solutions/685. Redundant Connection II/685.py @@ -0,0 +1,56 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> bool: + i = self._find(u) + j = self._find(v) + if i == j: + return False + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + return True + + def _find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self._find(self.id[u]) + return self.id[u] + + +class Solution: + def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]: + ids = [0] * (len(edges) + 1) + nodeWithTwoParents = 0 + + for _, v in edges: + ids[v] += 1 + if ids[v] == 2: + nodeWithTwoParents = v + + def findRedundantDirectedConnection(skippedEdgeIndex: int) -> List[int]: + uf = UnionFind(len(edges) + 1) + + for i, edge in enumerate(edges): + if i == skippedEdgeIndex: + continue + if not uf.unionByRank(edge[0], edge[1]): + return edge + + return [] + + # If there is no edge with two ids, don't skip any edge. + if nodeWithTwoParents == 0: + return findRedundantDirectedConnection(-1) + + for i in reversed(range(len(edges))): + _, v = edges[i] + if v == nodeWithTwoParents: + # Try to delete the edges[i]. + if not findRedundantDirectedConnection(i): + return edges[i] diff --git a/solutions/686. Repeated String Match/686.cpp b/solutions/686. Repeated String Match/686.cpp new file mode 100644 index 00000000000..6736b4515b1 --- /dev/null +++ b/solutions/686. Repeated String Match/686.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int repeatedStringMatch(string a, string b) { + const int n = ceil((double)b.length() / a.length()); + string s; + + for (int i = 0; i < n; ++i) + s += a; + + if (s.find(b) != string::npos) + return n; + if ((s + a).find(b) != string::npos) + return n + 1; + return -1; + } +}; diff --git a/solutions/686. Repeated String Match/686.java b/solutions/686. Repeated String Match/686.java new file mode 100644 index 00000000000..a4f24486777 --- /dev/null +++ b/solutions/686. Repeated String Match/686.java @@ -0,0 +1,11 @@ +class Solution { + public int repeatedStringMatch(String A, String B) { + final int n = (int) Math.ceil((double) B.length() / (double) A.length()); + final String s = String.join("", Collections.nCopies(n, A)); + if (s.contains(B)) + return n; + if ((s + A).contains(B)) + return n + 1; + return -1; + } +} diff --git a/solutions/686. Repeated String Match/686.py b/solutions/686. Repeated String Match/686.py new file mode 100644 index 00000000000..b8b895142df --- /dev/null +++ b/solutions/686. Repeated String Match/686.py @@ -0,0 +1,9 @@ +class Solution: + def repeatedStringMatch(self, a: str, b: str) -> int: + n = math.ceil(len(b) / len(a)) + s = a * n + if b in s: + return n + if b in s + a: + return n + 1 + return -1 diff --git a/solutions/687. Longest Univalue Path/687.cpp b/solutions/687. Longest Univalue Path/687.cpp new file mode 100644 index 00000000000..ad200d1f517 --- /dev/null +++ b/solutions/687. Longest Univalue Path/687.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int longestUnivaluePath(TreeNode* root) { + int ans = 0; + longestUnivaluePathDownFrom(root, ans); + return ans; + } + + private: + int longestUnivaluePathDownFrom(TreeNode* root, int& ans) { + if (root == nullptr) + return 0; + + const int l = longestUnivaluePathDownFrom(root->left, ans); + const int r = longestUnivaluePathDownFrom(root->right, ans); + const int arrowLeft = + root->left && root->left->val == root->val ? l + 1 : 0; + const int arrowRight = + root->right && root->right->val == root->val ? r + 1 : 0; + ans = max(ans, arrowLeft + arrowRight); + return max(arrowLeft, arrowRight); + } +}; diff --git a/solutions/687. Longest Univalue Path/687.java b/solutions/687. Longest Univalue Path/687.java new file mode 100644 index 00000000000..f49e6c189ae --- /dev/null +++ b/solutions/687. Longest Univalue Path/687.java @@ -0,0 +1,20 @@ +class Solution { + public int longestUnivaluePath(TreeNode root) { + longestUnivaluePathDownFrom(root); + return ans; + } + + private int ans = 0; + + private int longestUnivaluePathDownFrom(TreeNode root) { + if (root == null) + return 0; + + final int l = longestUnivaluePathDownFrom(root.left); + final int r = longestUnivaluePathDownFrom(root.right); + final int arrowLeft = root.left != null && root.left.val == root.val ? l + 1 : 0; + final int arrowRight = root.right != null && root.right.val == root.val ? r + 1 : 0; + ans = Math.max(ans, arrowLeft + arrowRight); + return Math.max(arrowLeft, arrowRight); + } +} diff --git a/solutions/687. Longest Univalue Path/687.py b/solutions/687. Longest Univalue Path/687.py new file mode 100644 index 00000000000..7b07e38251b --- /dev/null +++ b/solutions/687. Longest Univalue Path/687.py @@ -0,0 +1,18 @@ +class Solution: + def longestUnivaluePath(self, root: Optional[TreeNode]) -> int: + ans = 0 + + def longestUnivaluePathDownFrom(root: Optional[TreeNode]) -> int: + nonlocal ans + if not root: + return 0 + + l = longestUnivaluePathDownFrom(root.left) + r = longestUnivaluePathDownFrom(root.right) + arrowLeft = l + 1 if root.left and root.left.val == root.val else 0 + arrowRight = r + 1 if root.right and root.right.val == root.val else 0 + ans = max(ans, arrowLeft + arrowRight) + return max(arrowLeft, arrowRight) + + longestUnivaluePathDownFrom(root) + return ans diff --git a/solutions/688. Knight Probability in Chessboard/688.cpp b/solutions/688. Knight Probability in Chessboard/688.cpp new file mode 100644 index 00000000000..8cf92a6e5a8 --- /dev/null +++ b/solutions/688. Knight Probability in Chessboard/688.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + double knightProbability(int n, int k, int row, int column) { + constexpr int dirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, + {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; + constexpr double kProb = 0.125; + // dp[i][j] := the probability to stand on (i, j) + vector> dp(n, vector(n)); + dp[row][column] = 1.0; + + for (int move = 0; move < k; ++move) { + vector> newDp(n, vector(n)); + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (dp[i][j] > 0.0) { + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x >= n || y < 0 || y >= n) + continue; + newDp[x][y] += dp[i][j] * kProb; + } + } + dp = std::move(newDp); + } + + return accumulate(dp.begin(), dp.end(), 0.0, + [](double subtotal, const vector& row) { + return subtotal + accumulate(row.begin(), row.end(), 0.0); + }); + } +}; diff --git a/solutions/688. Knight Probability in Chessboard/688.java b/solutions/688. Knight Probability in Chessboard/688.java new file mode 100644 index 00000000000..661b51f8b3f --- /dev/null +++ b/solutions/688. Knight Probability in Chessboard/688.java @@ -0,0 +1,27 @@ +class Solution { + public double knightProbability(int n, int k, int row, int column) { + final int[][] dirs = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; + final double kProb = 0.125; + // dp[i][j] := the probability to stand on (i, j) + double[][] dp = new double[n][n]; + dp[row][column] = 1.0; + + for (int move = 0; move < k; ++move) { + double[][] newDp = new double[n][n]; + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (dp[i][j] > 0.0) { + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x >= n || y < 0 || y >= n) + continue; + newDp[x][y] += dp[i][j] * kProb; + } + } + dp = newDp; + } + + return Arrays.stream(dp).flatMapToDouble(Arrays::stream).sum(); + } +} diff --git a/solutions/688. Knight Probability in Chessboard/688.py b/solutions/688. Knight Probability in Chessboard/688.py new file mode 100644 index 00000000000..245f8b9f305 --- /dev/null +++ b/solutions/688. Knight Probability in Chessboard/688.py @@ -0,0 +1,20 @@ +class Solution: + def knightProbability(self, n: int, k: int, row: int, column: int) -> float: + dirs = ((1, 2), (2, 1), (2, -1), (1, -2), + (-1, -2), (-2, -1), (-2, 1), (-1, 2)) + # dp[i][j] := the probability to stand on (i, j) + dp = [[0] * n for _ in range(n)] + dp[row][column] = 1.0 + + for _ in range(k): + newDp = [[0] * n for _ in range(n)] + for i in range(n): + for j in range(n): + for dx, dy in dirs: + x = i + dx + y = j + dy + if 0 <= x < n and 0 <= y < n: + newDp[i][j] += dp[x][y] + dp = newDp + + return sum(map(sum, dp)) / 8**k diff --git a/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.cpp b/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.cpp new file mode 100644 index 00000000000..38860b3bdf9 --- /dev/null +++ b/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + vector maxSumOfThreeSubarrays(vector& nums, int k) { + const int n = nums.size() - k + 1; + // sums[i] := sum(nums[i..i + k)) + vector sums(n); + // l[i] := the index in [0..i] that has the maximum sums[i] + vector l(n); + // r[i] := the index in [i..n) that has the maximum sums[i] + vector r(n); + + int sum = 0; + for (int i = 0; i < nums.size(); ++i) { + sum += nums[i]; + if (i >= k) + sum -= nums[i - k]; + if (i >= k - 1) + sums[i - k + 1] = sum; + } + + int maxIndex = 0; + for (int i = 0; i < n; ++i) { + if (sums[i] > sums[maxIndex]) + maxIndex = i; + l[i] = maxIndex; + } + + maxIndex = n - 1; + for (int i = n - 1; i >= 0; --i) { + if (sums[i] >= sums[maxIndex]) + maxIndex = i; + r[i] = maxIndex; + } + + vector ans{-1, -1, -1}; + + for (int i = k; i < n - k; ++i) + if (ans[0] == -1 || sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < + sums[l[i - k]] + sums[i] + sums[r[i + k]]) { + ans[0] = l[i - k]; + ans[1] = i; + ans[2] = r[i + k]; + } + + return ans; + } +}; diff --git a/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.java b/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.java new file mode 100644 index 00000000000..faac768521a --- /dev/null +++ b/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.java @@ -0,0 +1,46 @@ +class Solution { + public int[] maxSumOfThreeSubarrays(int[] nums, int k) { + final int n = nums.length - k + 1; + // sums[i] := sum(nums[i..i + k)) + int[] sums = new int[n]; + // l[i] := the index in [0..i] that has the maximum sums[i] + int[] l = new int[n]; + // r[i] := the index in [i..n) that has the maximum sums[i] + int[] r = new int[n]; + + int sum = 0; + for (int i = 0; i < nums.length; ++i) { + sum += nums[i]; + if (i >= k) + sum -= nums[i - k]; + if (i >= k - 1) + sums[i - k + 1] = sum; + } + + int maxIndex = 0; + for (int i = 0; i < n; ++i) { + if (sums[i] > sums[maxIndex]) + maxIndex = i; + l[i] = maxIndex; + } + + maxIndex = n - 1; + for (int i = n - 1; i >= 0; --i) { + if (sums[i] >= sums[maxIndex]) + maxIndex = i; + r[i] = maxIndex; + } + + int[] ans = {-1, -1, -1}; + + for (int i = k; i + k < n; ++i) + if (ans[0] == -1 || + sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < sums[l[i - k]] + sums[i] + sums[r[i + k]]) { + ans[0] = l[i - k]; + ans[1] = i; + ans[2] = r[i + k]; + } + + return ans; + } +} diff --git a/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.py b/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.py new file mode 100644 index 00000000000..3bd8daaee19 --- /dev/null +++ b/solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.py @@ -0,0 +1,40 @@ +class Solution: + def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: + n = len(nums) - k + 1 + # sums[i] := sum(nums[i..i + k)) + sums = [0] * n + # l[i] := the index in [0..i] that has the maximum sums[i] + l = [0] * n + # r[i] := the index in [i..n) that has the maximum sums[i] + r = [0] * n + + summ = 0 + for i, num in enumerate(nums): + summ += num + if i >= k: + summ -= nums[i - k] + if i >= k - 1: + sums[i - k + 1] = summ + + maxIndex = 0 + for i in range(n): + if sums[i] > sums[maxIndex]: + maxIndex = i + l[i] = maxIndex + + maxIndex = n - 1 + for i in range(n - 1, -1, -1): + if sums[i] >= sums[maxIndex]: + maxIndex = i + r[i] = maxIndex + + ans = [-1, -1, -1] + + for i in range(k, n - k): + if ans[0] == -1 or sums[ans[0]] + sums[ans[1]] + sums[ans[2]] <\ + sums[l[i - k]] + sums[i] + sums[r[i + k]]: + ans[0] = l[i - k] + ans[1] = i + ans[2] = r[i + k] + + return ans diff --git a/solutions/69. Sqrt(x)/69.cpp b/solutions/69. Sqrt(x)/69.cpp new file mode 100644 index 00000000000..836ba591fd8 --- /dev/null +++ b/solutions/69. Sqrt(x)/69.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int mySqrt(int x) { + unsigned l = 1; + unsigned r = x + 1u; + + while (l < r) { + const unsigned m = (l + r) / 2; + if (m > x / m) + r = m; + else + l = m + 1; + } + + // l := the minimum number s.t. l * l > x + return l - 1; + } +}; diff --git a/solutions/69. Sqrt(x)/69.java b/solutions/69. Sqrt(x)/69.java new file mode 100644 index 00000000000..e24dca4fd5f --- /dev/null +++ b/solutions/69. Sqrt(x)/69.java @@ -0,0 +1,17 @@ +class Solution { + public int mySqrt(long x) { + long l = 1; + long r = x + 1; + + while (l < r) { + final long m = (l + r) / 2; + if (m > x / m) + r = m; + else + l = m + 1; + } + + // l := the minimum number s.t. l * l > x + return (int) l - 1; + } +} diff --git a/solutions/69. Sqrt(x)/69.py b/solutions/69. Sqrt(x)/69.py new file mode 100644 index 00000000000..b4ef742623c --- /dev/null +++ b/solutions/69. Sqrt(x)/69.py @@ -0,0 +1,4 @@ +class Solution: + def mySqrt(self, x: int) -> int: + return bisect.bisect_right(range(x + 1), x, + key=lambda m: m * m) - 1 diff --git a/solutions/690. Employee Importance/690.cpp b/solutions/690. Employee Importance/690.cpp new file mode 100644 index 00000000000..9063952c062 --- /dev/null +++ b/solutions/690. Employee Importance/690.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int getImportance(vector employees, int id) { + unordered_map idToEmployee; + + for (Employee* employee : employees) + idToEmployee[employee->id] = employee; + + return dfs(id, idToEmployee); + } + + private: + int dfs(int id, const unordered_map& idToEmployee) { + int values = 0; + + for (const int subId : idToEmployee.at(id)->subordinates) + values += dfs(subId, idToEmployee); + + return idToEmployee.at(id)->importance + values; + } +}; diff --git a/solutions/690. Employee Importance/690.java b/solutions/690. Employee Importance/690.java new file mode 100644 index 00000000000..f05641b9426 --- /dev/null +++ b/solutions/690. Employee Importance/690.java @@ -0,0 +1,19 @@ +class Solution { + public int getImportance(List employees, int id) { + Map idToEmployee = new HashMap<>(); + + for (Employee employee : employees) + idToEmployee.put(employee.id, employee); + + return dfs(id, idToEmployee); + } + + private int dfs(int id, Map idToEmployee) { + int values = 0; + + for (final int subId : idToEmployee.get(id).subordinates) + values += dfs(subId, idToEmployee); + + return idToEmployee.get(id).importance + values; + } +} diff --git a/solutions/690. Employee Importance/690.py b/solutions/690. Employee Importance/690.py new file mode 100644 index 00000000000..d77c4761855 --- /dev/null +++ b/solutions/690. Employee Importance/690.py @@ -0,0 +1,11 @@ +class Solution: + def getImportance(self, employees: List['Employee'], id: int) -> int: + idToEmployee = {employee.id: employee for employee in employees} + + def dfs(id: int) -> int: + values = idToEmployee[id].importance + for subId in idToEmployee[id].subordinates: + values += dfs(subId) + return values + + return dfs(id) diff --git a/solutions/691. Stickers to Spell Word/691.cpp b/solutions/691. Stickers to Spell Word/691.cpp new file mode 100644 index 00000000000..b05642b9ac3 --- /dev/null +++ b/solutions/691. Stickers to Spell Word/691.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int minStickers(vector& stickers, string target) { + const int n = target.size(); + const int maxMask = 1 << n; + // dp[i] := the minimum number of stickers to spell out i, where i is the + // bit mask of target + vector dp(maxMask, INT_MAX); + dp[0] = 0; + + for (int mask = 0; mask < maxMask; ++mask) { + if (dp[mask] == INT_MAX) + continue; + // Try to expand from `mask` by using each sticker. + for (const string& sticker : stickers) { + int superMask = mask; + for (const char c : sticker) + for (int i = 0; i < n; ++i) + // Try to apply it on a missing letter. + if (c == target[i] && (superMask >> i & 1) == 0) { + superMask |= 1 << i; + break; + } + dp[superMask] = min(dp[superMask], dp[mask] + 1); + } + } + + return dp.back() == INT_MAX ? -1 : dp.back(); + } +}; diff --git a/solutions/691. Stickers to Spell Word/691.java b/solutions/691. Stickers to Spell Word/691.java new file mode 100644 index 00000000000..e64d344708b --- /dev/null +++ b/solutions/691. Stickers to Spell Word/691.java @@ -0,0 +1,30 @@ +class Solution { + public int minStickers(String[] stickers, String target) { + final int n = target.length(); + final int maxMask = 1 << n; + // dp[i] := the minimum number of stickers to spell out i, where i is the + // bit mask of target + int[] dp = new int[maxMask]; + Arrays.fill(dp, Integer.MAX_VALUE); + dp[0] = 0; + + for (int mask = 0; mask < maxMask; ++mask) { + if (dp[mask] == Integer.MAX_VALUE) + continue; + // Try to expand from `mask` by using each sticker. + for (final String sticker : stickers) { + int superMask = mask; + for (final char c : sticker.toCharArray()) + for (int i = 0; i < n; ++i) + // Try to apply it on a missing letter. + if (c == target.charAt(i) && (superMask >> i & 1) == 0) { + superMask |= 1 << i; + break; + } + dp[superMask] = Math.min(dp[superMask], dp[mask] + 1); + } + } + + return dp[maxMask - 1] == Integer.MAX_VALUE ? -1 : dp[maxMask - 1]; + } +} diff --git a/solutions/691. Stickers to Spell Word/691.py b/solutions/691. Stickers to Spell Word/691.py new file mode 100644 index 00000000000..17abe1fd934 --- /dev/null +++ b/solutions/691. Stickers to Spell Word/691.py @@ -0,0 +1,23 @@ +class Solution: + def minStickers(self, stickers: List[str], target: str) -> int: + maxMask = 1 << len(target) + # dp[i] := the minimum number of stickers to spell out i, where i is the + # bit mask of target + dp = [math.inf] * maxMask + dp[0] = 0 + + for mask in range(maxMask): + if dp[mask] == math.inf: + continue + # Try to expand from `mask` by using each sticker. + for sticker in stickers: + superMask = mask + for c in sticker: + for i, t in enumerate(target): + # Try to apply it on a missing letter. + if c == t and not (superMask >> i & 1): + superMask |= 1 << i + break + dp[superMask] = min(dp[superMask], dp[mask] + 1) + + return -1 if dp[-1] == math.inf else dp[-1] diff --git a/solutions/692. Top K Frequent Words/692-2.cpp b/solutions/692. Top K Frequent Words/692-2.cpp new file mode 100644 index 00000000000..76f7eb62b6e --- /dev/null +++ b/solutions/692. Top K Frequent Words/692-2.cpp @@ -0,0 +1,35 @@ +struct T { + string word; + int freq; + T(string word, int freq) : word(word), freq(freq) {} +}; + +class Solution { + public: + vector topKFrequent(vector& words, int k) { + vector ans; + unordered_map count; + // Words with higher frequency and lower alphabetical order are in the + // bottom of the heap because we'll pop words with lower frequency and + // higher alphabetical order if the heap's size > k. + auto compare = [](const T& a, const T& b) { + return a.freq == b.freq ? a.word < b.word : a.freq > b.freq; + }; + priority_queue, decltype(compare)> heap(compare); + + for (const string& word : words) + ++count[word]; + + for (const auto& [word, freq] : count) { + heap.emplace(word, freq); + if (heap.size() > k) + heap.pop(); + } + + while (!heap.empty()) + ans.push_back(heap.top().word), heap.pop(); + + reverse(ans.begin(), ans.end()); + return ans; + } +}; diff --git a/solutions/692. Top K Frequent Words/692-2.java b/solutions/692. Top K Frequent Words/692-2.java new file mode 100644 index 00000000000..c7bd7872178 --- /dev/null +++ b/solutions/692. Top K Frequent Words/692-2.java @@ -0,0 +1,35 @@ +class T { + public String word; + public int freq; + public T(String word, int freq) { + this.word = word; + this.freq = freq; + } +}; + +class Solution { + public List topKFrequent(String[] words, int k) { + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + // Words with higher frequency and lower alphabetical order are in the + // bottom of the heap because we'll pop words with lower frequency and + // higher alphabetical order if the heap's size > k. + Queue heap = new PriorityQueue<>( + (a, b) -> a.freq == b.freq ? b.word.compareTo(a.word) : a.freq - b.freq); + + for (final String word : words) + count.merge(word, 1, Integer::sum); + + for (final String word : count.keySet()) { + heap.offer(new T(word, count.get(word))); + if (heap.size() > k) + heap.poll(); + } + + while (!heap.isEmpty()) + ans.add(heap.poll().word); + + Collections.reverse(ans); + return ans; + } +} diff --git a/solutions/692. Top K Frequent Words/692-2.py b/solutions/692. Top K Frequent Words/692-2.py new file mode 100644 index 00000000000..2631c6bd00b --- /dev/null +++ b/solutions/692. Top K Frequent Words/692-2.py @@ -0,0 +1,28 @@ +class T: + def __init__(self, word: str, freq: int): + self.word = word + self.freq = freq + + def __lt__(self, other): + if self.freq == other.freq: + # Words with higher frequency and lower alphabetical order are in the + # bottom of the heap because we'll pop words with lower frequency and + # higher alphabetical order if the heap's size > k. + return self.word > other.word + return self.freq < other.freq + + +class Solution: + def topKFrequent(self, words: List[str], k: int) -> List[str]: + ans = [] + heap = [] + + for word, freq in collections.Counter(words).items(): + heapq.heappush(heap, T(word, freq)) + if len(heap) > k: + heapq.heappop(heap) + + while heap: + ans.append(heapq.heappop(heap).word) + + return ans[::-1] diff --git a/solutions/692. Top K Frequent Words/692.cpp b/solutions/692. Top K Frequent Words/692.cpp new file mode 100644 index 00000000000..bf70ede90c3 --- /dev/null +++ b/solutions/692. Top K Frequent Words/692.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector topKFrequent(vector& words, int k) { + const int n = words.size(); + vector ans; + vector> bucket(n + 1); + unordered_map count; + + for (const string& word : words) + ++count[word]; + + for (const auto& [word, freq] : count) + bucket[freq].push_back(word); + + for (int freq = n; freq > 0; --freq) { + ranges::sort(bucket[freq]); + for (const string& word : bucket[freq]) { + ans.push_back(word); + if (ans.size() == k) + return ans; + } + } + + throw; + } +}; diff --git a/solutions/692. Top K Frequent Words/692.java b/solutions/692. Top K Frequent Words/692.java new file mode 100644 index 00000000000..49de12322f5 --- /dev/null +++ b/solutions/692. Top K Frequent Words/692.java @@ -0,0 +1,30 @@ +class Solution { + public List topKFrequent(String[] words, int k) { + final int n = words.length; + List ans = new ArrayList<>(); + List[] bucket = new List[n + 1]; + Map count = new HashMap<>(); + + for (final String word : words) + count.merge(word, 1, Integer::sum); + + for (final String word : count.keySet()) { + final int freq = count.get(word); + if (bucket[freq] == null) + bucket[freq] = new ArrayList<>(); + bucket[freq].add(word); + } + + for (int freq = n; freq > 0; --freq) + if (bucket[freq] != null) { + Collections.sort(bucket[freq]); + for (final String word : bucket[freq]) { + ans.add(word); + if (ans.size() == k) + return ans; + } + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/692. Top K Frequent Words/692.py b/solutions/692. Top K Frequent Words/692.py new file mode 100644 index 00000000000..64378a2d232 --- /dev/null +++ b/solutions/692. Top K Frequent Words/692.py @@ -0,0 +1,13 @@ +class Solution: + def topKFrequent(self, words: List[str], k: int) -> List[str]: + ans = [] + bucket = [[] for _ in range(len(words) + 1)] + + for word, freq in collections.Counter(words).items(): + bucket[freq].append(word) + + for b in reversed(bucket): + for word in sorted(b): + ans.append(word) + if len(ans) == k: + return ans diff --git a/solutions/693. Binary Number with Alternating Bits/693.cpp b/solutions/693. Binary Number with Alternating Bits/693.cpp new file mode 100644 index 00000000000..e685c12b729 --- /dev/null +++ b/solutions/693. Binary Number with Alternating Bits/693.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool hasAlternatingBits(int n) { + // n = 0b010101 + // n >> 2 = 0b000101 + // n ^ (n >> 2) = 0b010000 = a + // a - 1 = 0b001111 + // a & (a - 1) = 0 + const int a = n ^ (n >> 2); + return (a & (a - 1)) == 0; + } +}; diff --git a/solutions/693. Binary Number with Alternating Bits/693.java b/solutions/693. Binary Number with Alternating Bits/693.java new file mode 100644 index 00000000000..0d37b839e2b --- /dev/null +++ b/solutions/693. Binary Number with Alternating Bits/693.java @@ -0,0 +1,11 @@ +class Solution { + public boolean hasAlternatingBits(int n) { + // n = 0b010101 + // n >> 2 = 0b000101 + // n ^ (n >> 2) = 0b010000 = a + // a - 1 = 0b001111 + // a & (a - 1) = 0 + final int a = n ^ (n >> 2); + return (a & (a - 1)) == 0; + } +} diff --git a/solutions/693. Binary Number with Alternating Bits/693.py b/solutions/693. Binary Number with Alternating Bits/693.py new file mode 100644 index 00000000000..dbd204919fe --- /dev/null +++ b/solutions/693. Binary Number with Alternating Bits/693.py @@ -0,0 +1,9 @@ +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + # n = 0b010101 + # n >> 2 = 0b000101 + # n ^ (n >> 2) = 0b010000 = a + # a - 1 = 0b001111 + # a & (a - 1) = 0 + a = n ^ (n >> 2) + return (a & (a - 1)) == 0 diff --git a/solutions/694. Number of Distinct Islands/694.cpp b/solutions/694. Number of Distinct Islands/694.cpp new file mode 100644 index 00000000000..969a9d796fc --- /dev/null +++ b/solutions/694. Number of Distinct Islands/694.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int numDistinctIslands(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + set>> islands; // all the different islands + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + vector> island; + dfs(grid, i, j, i, j, seen, island); + if (!island.empty()) + islands.insert(island); + } + + return islands.size(); + } + + private: + void dfs(const vector>& grid, int i, int j, int i0, int j0, + vector>& seen, vector>& island) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] == 0 || seen[i][j]) + return; + + seen[i][j] = true; + island.emplace_back(i - i0, j - j0); + + dfs(grid, i + 1, j, i0, j0, seen, island); + dfs(grid, i - 1, j, i0, j0, seen, island); + dfs(grid, i, j + 1, i0, j0, seen, island); + dfs(grid, i, j - 1, i0, j0, seen, island); + } +}; diff --git a/solutions/694. Number of Distinct Islands/694.java b/solutions/694. Number of Distinct Islands/694.java new file mode 100644 index 00000000000..9c820fce5df --- /dev/null +++ b/solutions/694. Number of Distinct Islands/694.java @@ -0,0 +1,34 @@ +class Solution { + public int numDistinctIslands(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + Set>> islands = new HashSet<>(); // all the different islands + boolean[][] seen = new boolean[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + List> island = new ArrayList<>(); + dfs(grid, i, j, i, j, seen, island); + if (!island.isEmpty()) + islands.add(island); + } + + return islands.size(); + } + + private void dfs(int[][] grid, int i, int j, int i0, int j0, boolean[][] seen, + List> island) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] == 0 || seen[i][j]) + return; + + seen[i][j] = true; + island.add(new Pair<>(i - i0, j - j0)); + + dfs(grid, i + 1, j, i0, j0, seen, island); + dfs(grid, i - 1, j, i0, j0, seen, island); + dfs(grid, i, j + 1, i0, j0, seen, island); + dfs(grid, i, j - 1, i0, j0, seen, island); + } +} diff --git a/solutions/694. Number of Distinct Islands/694.py b/solutions/694. Number of Distinct Islands/694.py new file mode 100644 index 00000000000..e5c32604779 --- /dev/null +++ b/solutions/694. Number of Distinct Islands/694.py @@ -0,0 +1,27 @@ +class Solution: + def numDistinctIslands(self, grid: List[List[int]]) -> int: + seen = set() + + def dfs(i: int, j: int, i0: int, j0: int): + if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]): + return + if grid[i][j] == 0 or (i, j) in seen: + return + + seen.add((i, j)) + island.append((i - i0, j - j0)) + dfs(i + 1, j, i0, j0) + dfs(i - 1, j, i0, j0) + dfs(i, j + 1, i0, j0) + dfs(i, j - 1, i0, j0) + + islands = set() # all the different islands + + for i in range(len(grid)): + for j in range(len(grid[0])): + island = [] + dfs(i, j, i, j) + if island: + islands.add(frozenset(island)) + + return len(islands) diff --git a/solutions/695. Max Area of Island/695.cpp b/solutions/695. Max Area of Island/695.cpp new file mode 100644 index 00000000000..72745086fef --- /dev/null +++ b/solutions/695. Max Area of Island/695.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int maxAreaOfIsland(vector>& grid) { + int ans = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + ans = max(ans, dfs(grid, i, j)); + + return ans; + } + + private: + int dfs(vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return 0; + if (grid[i][j] != 1) + return 0; + + grid[i][j] = 2; + + return 1 + // + dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + // + dfs(grid, i, j + 1) + dfs(grid, i, j - 1); + } +}; diff --git a/solutions/695. Max Area of Island/695.java b/solutions/695. Max Area of Island/695.java new file mode 100644 index 00000000000..ac880cd7c7e --- /dev/null +++ b/solutions/695. Max Area of Island/695.java @@ -0,0 +1,24 @@ +class Solution { + public int maxAreaOfIsland(int[][] grid) { + int ans = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + ans = Math.max(ans, dfs(grid, i, j)); + + return ans; + } + + private int dfs(int[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return 0; + if (grid[i][j] != 1) + return 0; + + grid[i][j] = 2; + + return 1 + // + dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + // + dfs(grid, i, j + 1) + dfs(grid, i, j - 1); + } +} diff --git a/solutions/695. Max Area of Island/695.py b/solutions/695. Max Area of Island/695.py new file mode 100644 index 00000000000..e775c00bd3a --- /dev/null +++ b/solutions/695. Max Area of Island/695.py @@ -0,0 +1,13 @@ +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + def dfs(i: int, j: int) -> int: + if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]): + return 0 + if grid[i][j] != 1: + return 0 + + grid[i][j] = 2 + + return 1 + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1) + + return max(dfs(i, j) for i in range(len(grid)) for j in range(len(grid[0]))) diff --git a/solutions/696. Count Binary Substrings/696.cpp b/solutions/696. Count Binary Substrings/696.cpp new file mode 100644 index 00000000000..3d99fc7fa7c --- /dev/null +++ b/solutions/696. Count Binary Substrings/696.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countBinarySubstrings(string s) { + int ans = 0; + int prevEquals = 0; + int currEquals = 1; + + for (int i = 0; i + 1 < s.length(); ++i) + if (s[i] == s[i + 1]) + ++currEquals; + else { + ans += min(prevEquals, currEquals); + prevEquals = currEquals; + currEquals = 1; + } + + return ans + min(prevEquals, currEquals); + } +}; diff --git a/solutions/696. Count Binary Substrings/696.java b/solutions/696. Count Binary Substrings/696.java new file mode 100644 index 00000000000..7dc2a209e76 --- /dev/null +++ b/solutions/696. Count Binary Substrings/696.java @@ -0,0 +1,18 @@ +class Solution { + public int countBinarySubstrings(String s) { + int ans = 0; + int prevEquals = 0; + int currEquals = 1; + + for (int i = 0; i + 1 < s.length(); ++i) + if (s.charAt(i) == s.charAt(i + 1)) + ++currEquals; + else { + ans += Math.min(prevEquals, currEquals); + prevEquals = currEquals; + currEquals = 1; + } + + return ans + Math.min(prevEquals, currEquals); + } +} diff --git a/solutions/696. Count Binary Substrings/696.py b/solutions/696. Count Binary Substrings/696.py new file mode 100644 index 00000000000..61cd45db9d9 --- /dev/null +++ b/solutions/696. Count Binary Substrings/696.py @@ -0,0 +1,15 @@ +class Solution: + def countBinarySubstrings(self, s: str) -> int: + ans = 0 + prevCount = 0 + equals = 1 + + for i in range(len(s) - 1): + if s[i] == s[i + 1]: + equals += 1 + else: + ans += min(prevCount, equals) + prevCount = equals + equals = 1 + + return ans + min(prevCount, equals) diff --git a/solutions/697. Degree of an Array/697.cpp b/solutions/697. Degree of an Array/697.cpp new file mode 100644 index 00000000000..33513693af1 --- /dev/null +++ b/solutions/697. Degree of an Array/697.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int findShortestSubArray(vector& nums) { + int ans = 0; + int degree = 0; + unordered_map debut; + unordered_map count; + + for (int i = 0; i < nums.size(); ++i) { + const int num = nums[i]; + if (!debut.contains(num)) + debut[num] = i; + if (++count[num] > degree) { + degree = count[num]; + ans = i - debut[num] + 1; + } else if (count[num] == degree) { + ans = min(ans, i - debut[num] + 1); + } + } + + return ans; + } +}; diff --git a/solutions/697. Degree of an Array/697.java b/solutions/697. Degree of an Array/697.java new file mode 100644 index 00000000000..176a1992f9d --- /dev/null +++ b/solutions/697. Degree of an Array/697.java @@ -0,0 +1,21 @@ +class Solution { + public int findShortestSubArray(int[] nums) { + int ans = 0; + int degree = 0; + Map debut = new HashMap<>(); + Map count = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + final int num = nums[i]; + debut.putIfAbsent(num, i); + if (count.merge(num, 1, Integer::sum) > degree) { + degree = count.get(num); + ans = i - debut.get(num) + 1; + } else if (count.get(num) == degree) { + ans = Math.min(ans, i - debut.get(num) + 1); + } + } + + return ans; + } +} diff --git a/solutions/697. Degree of an Array/697.py b/solutions/697. Degree of an Array/697.py new file mode 100644 index 00000000000..09055298c53 --- /dev/null +++ b/solutions/697. Degree of an Array/697.py @@ -0,0 +1,17 @@ +class Solution: + def findShortestSubArray(self, nums: List[int]) -> int: + ans = 0 + degree = 0 + debut = {} + count = collections.Counter() + + for i, num in enumerate(nums): + debut.setdefault(num, i) + count[num] += 1 + if count[num] > degree: + degree = count[num] + ans = i - debut[num] + 1 + elif count[num] == degree: + ans = min(ans, i - debut[num] + 1) + + return ans diff --git a/solutions/698. Partition to K Equal Sum Subsets/698.cpp b/solutions/698. Partition to K Equal Sum Subsets/698.cpp new file mode 100644 index 00000000000..7c66d489bc2 --- /dev/null +++ b/solutions/698. Partition to K Equal Sum Subsets/698.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + bool canPartitionKSubsets(vector& nums, int k) { + const int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % k != 0) + return false; + + const int target = sum / k; // the target sum of each subset + if (ranges::any_of(nums, [target](const int num) { return num > target; })) + return false; + + ranges::sort(nums, greater<>()); + return dfs(nums, 0, k, /*currSum=*/0, target, /*used=*/0); + } + + private: + bool dfs(const vector& nums, int s, int remainingGroups, int currSum, + const int subsetTargetSum, int used) { + if (remainingGroups == 0) + return true; + if (currSum > subsetTargetSum) + return false; + if (currSum == subsetTargetSum) // Find a valid group, so fresh start. + return dfs(nums, 0, remainingGroups - 1, 0, subsetTargetSum, used); + + for (int i = s; i < nums.size(); ++i) { + if (used >> i & 1) + continue; + if (dfs(nums, i + 1, remainingGroups, currSum + nums[i], subsetTargetSum, + used | 1 << i)) + return true; + } + + return false; + } +}; diff --git a/solutions/698. Partition to K Equal Sum Subsets/698.java b/solutions/698. Partition to K Equal Sum Subsets/698.java new file mode 100644 index 00000000000..9decb02c66e --- /dev/null +++ b/solutions/698. Partition to K Equal Sum Subsets/698.java @@ -0,0 +1,32 @@ +class Solution { + public boolean canPartitionKSubsets(int[] nums, int k) { + final int sum = Arrays.stream(nums).sum(); + if (sum % k != 0) + return false; + + final int target = sum / k; // the target sum of each subset + if (Arrays.stream(nums).anyMatch(num -> num > target)) + return false; + + return dfs(nums, 0, k, /*currSum=*/0, target, /*used=*/0); + } + + private boolean dfs(int[] nums, int s, int remainingGroups, int currSum, int subsetTargetSum, + int used) { + if (remainingGroups == 0) + return true; + if (currSum > subsetTargetSum) + return false; + if (currSum == subsetTargetSum) // Find a valid group, so fresh start. + return dfs(nums, 0, remainingGroups - 1, 0, subsetTargetSum, used); + + for (int i = s; i < nums.length; ++i) { + if ((used >> i & 1) == 1) + continue; + if (dfs(nums, i + 1, remainingGroups, currSum + nums[i], subsetTargetSum, used | 1 << i)) + return true; + } + + return false; + } +} diff --git a/solutions/698. Partition to K Equal Sum Subsets/698.py b/solutions/698. Partition to K Equal Sum Subsets/698.py new file mode 100644 index 00000000000..96c6aa86de3 --- /dev/null +++ b/solutions/698. Partition to K Equal Sum Subsets/698.py @@ -0,0 +1,28 @@ +class Solution: + def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: + summ = sum(nums) + if summ % k != 0: + return False + + target = summ // k # the target sum of each subset + if any(num > target for num in nums): + return False + + def dfs(s: int, remainingGroups: int, currSum: int, used: int) -> bool: + if remainingGroups == 0: + return True + if currSum > target: + return False + if currSum == target: # Find a valid group, so fresh start. + return dfs(0, remainingGroups - 1, 0, used) + + for i in range(s, len(nums)): + if used >> i & 1: + continue + if dfs(i + 1, remainingGroups, currSum + nums[i], used | 1 << i): + return True + + return False + + nums.sort(reverse=True) + return dfs(0, k, 0, 0) diff --git a/solutions/699. Falling Squares/699.cpp b/solutions/699. Falling Squares/699.cpp new file mode 100644 index 00000000000..b81c171398a --- /dev/null +++ b/solutions/699. Falling Squares/699.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + vector fallingSquares(vector>& positions) { + vector ans; + map, int> xsToHeight; // {(xStart, xEnd), height} + int maxHeight = INT_MIN; + + for (const vector& p : positions) { + const int left = p[0]; + const int sideLength = p[1]; + const int right = left + sideLength; + // Find the first range that intersects with [left, right). + auto it = xsToHeight.upper_bound({left, right}); + if (it != xsToHeight.begin() && (--it)->first.second <= left) + ++it; + int maxHeightInRange = 0; + vector> ranges; + while (it != xsToHeight.end() && it->first.first < right) { + const int l = it->first.first; + const int r = it->first.second; + const int h = it->second; + if (l < left) + ranges.emplace_back(l, left, h); + if (right < r) + ranges.emplace_back(right, r, h); + maxHeightInRange = max(maxHeightInRange, h); + it = xsToHeight.erase(it); + } + const int newHeight = maxHeightInRange + sideLength; + xsToHeight[{left, right}] = newHeight; + for (const auto& [l, r, h] : ranges) + xsToHeight[{l, r}] = h; + maxHeight = max(maxHeight, newHeight); + ans.push_back(maxHeight); + } + + return ans; + } +}; diff --git a/solutions/7. Reverse Integer/7.cpp b/solutions/7. Reverse Integer/7.cpp new file mode 100644 index 00000000000..ce6253fc2ec --- /dev/null +++ b/solutions/7. Reverse Integer/7.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int reverse(int x) { + long ans = 0; + + while (x != 0) { + ans = ans * 10 + x % 10; + x /= 10; + } + + return (ans < INT_MIN || ans > INT_MAX) ? 0 : ans; + } +}; diff --git a/solutions/7. Reverse Integer/7.java b/solutions/7. Reverse Integer/7.java new file mode 100644 index 00000000000..5e3036a0699 --- /dev/null +++ b/solutions/7. Reverse Integer/7.java @@ -0,0 +1,12 @@ +class Solution { + public int reverse(int x) { + long ans = 0; + + while (x != 0) { + ans = ans * 10 + x % 10; + x /= 10; + } + + return (ans < Integer.MIN_VALUE || ans > Integer.MAX_VALUE) ? 0 : (int) ans; + } +} diff --git a/solutions/7. Reverse Integer/7.py b/solutions/7. Reverse Integer/7.py new file mode 100644 index 00000000000..6b63f0d1bcd --- /dev/null +++ b/solutions/7. Reverse Integer/7.py @@ -0,0 +1,11 @@ +class Solution: + def reverse(self, x: int) -> int: + ans = 0 + sign = -1 if x < 0 else 1 + x *= sign + + while x: + ans = ans * 10 + x % 10 + x //= 10 + + return 0 if ans < -2**31 or ans > 2**31 - 1 else sign * ans diff --git a/solutions/70. Climbing Stairs/70-2.cpp b/solutions/70. Climbing Stairs/70-2.cpp new file mode 100644 index 00000000000..7d934c1b4f1 --- /dev/null +++ b/solutions/70. Climbing Stairs/70-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int climbStairs(int n) { + int prev1 = 1; // dp[i - 1] + int prev2 = 1; // dp[i - 2] + + for (int i = 2; i <= n; ++i) { + const int dp = prev1 + prev2; + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } +}; diff --git a/solutions/70. Climbing Stairs/70-2.java b/solutions/70. Climbing Stairs/70-2.java new file mode 100644 index 00000000000..f9c7033e402 --- /dev/null +++ b/solutions/70. Climbing Stairs/70-2.java @@ -0,0 +1,14 @@ +class Solution { + public int climbStairs(int n) { + int prev1 = 1; // dp[i - 1] + int prev2 = 1; // dp[i - 2] + + for (int i = 2; i <= n; ++i) { + final int dp = prev1 + prev2; + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } +} diff --git a/solutions/70. Climbing Stairs/70-2.py b/solutions/70. Climbing Stairs/70-2.py new file mode 100644 index 00000000000..d2e281d7e32 --- /dev/null +++ b/solutions/70. Climbing Stairs/70-2.py @@ -0,0 +1,11 @@ +class Solution: + def climbStairs(self, n: int) -> int: + prev1 = 1 # dp[i - 1] + prev2 = 1 # dp[i - 2] + + for _ in range(2, n + 1): + dp = prev1 + prev2 + prev2 = prev1 + prev1 = dp + + return prev1 diff --git a/solutions/70. Climbing Stairs/70.cpp b/solutions/70. Climbing Stairs/70.cpp new file mode 100644 index 00000000000..cb1a426a5ba --- /dev/null +++ b/solutions/70. Climbing Stairs/70.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int climbStairs(int n) { + // dp[i] := the number of ways to climb to the i-th stair + vector dp(n + 1); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; ++i) + dp[i] = dp[i - 1] + dp[i - 2]; + + return dp[n]; + } +}; diff --git a/solutions/70. Climbing Stairs/70.java b/solutions/70. Climbing Stairs/70.java new file mode 100644 index 00000000000..aa9601c5a41 --- /dev/null +++ b/solutions/70. Climbing Stairs/70.java @@ -0,0 +1,13 @@ +class Solution { + public int climbStairs(int n) { + // dp[i] := the number of ways to climb to the i-th stair + int[] dp = new int[n + 1]; + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; ++i) + dp[i] = dp[i - 1] + dp[i - 2]; + + return dp[n]; + } +} diff --git a/solutions/70. Climbing Stairs/70.py b/solutions/70. Climbing Stairs/70.py new file mode 100644 index 00000000000..3b8563193e9 --- /dev/null +++ b/solutions/70. Climbing Stairs/70.py @@ -0,0 +1,9 @@ +class Solution: + def climbStairs(self, n: int) -> int: + # dp[i] := the number of ways to climb to the i-th stair + dp = [1, 1] + [0] * (n - 1) + + for i in range(2, n + 1): + dp[i] = dp[i - 1] + dp[i - 2] + + return dp[n] diff --git a/solutions/700. Search in a Binary Search Tree/700.cpp b/solutions/700. Search in a Binary Search Tree/700.cpp new file mode 100644 index 00000000000..cb4a497de78 --- /dev/null +++ b/solutions/700. Search in a Binary Search Tree/700.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + TreeNode* searchBST(TreeNode* root, int val) { + if (root == nullptr) + return nullptr; + if (root->val == val) + return root; + if (root->val > val) + return searchBST(root->left, val); + return searchBST(root->right, val); + } +}; diff --git a/solutions/700. Search in a Binary Search Tree/700.java b/solutions/700. Search in a Binary Search Tree/700.java new file mode 100644 index 00000000000..f613eec4511 --- /dev/null +++ b/solutions/700. Search in a Binary Search Tree/700.java @@ -0,0 +1,11 @@ +public class Solution { + public TreeNode searchBST(TreeNode root, int val) { + if (root == null) + return null; + if (root.val == val) + return root; + if (root.val > val) + return searchBST(root.left, val); + return searchBST(root.right, val); + } +} diff --git a/solutions/700. Search in a Binary Search Tree/700.py b/solutions/700. Search in a Binary Search Tree/700.py new file mode 100644 index 00000000000..f51a15dae56 --- /dev/null +++ b/solutions/700. Search in a Binary Search Tree/700.py @@ -0,0 +1,9 @@ +class Solution: + def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: + return None + if root.val == val: + return root + if root.val > val: + return self.searchBST(root.left, val) + return self.searchBST(root.right, val) diff --git a/solutions/701. Insert into a Binary Search Tree/701.cpp b/solutions/701. Insert into a Binary Search Tree/701.cpp new file mode 100644 index 00000000000..440d2c3017b --- /dev/null +++ b/solutions/701. Insert into a Binary Search Tree/701.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + TreeNode* insertIntoBST(TreeNode* root, int val) { + if (root == nullptr) + return new TreeNode(val); + if (root->val > val) + root->left = insertIntoBST(root->left, val); + else + root->right = insertIntoBST(root->right, val); + return root; + } +}; diff --git a/solutions/701. Insert into a Binary Search Tree/701.java b/solutions/701. Insert into a Binary Search Tree/701.java new file mode 100644 index 00000000000..a4db0b64590 --- /dev/null +++ b/solutions/701. Insert into a Binary Search Tree/701.java @@ -0,0 +1,11 @@ +class Solution { + public TreeNode insertIntoBST(TreeNode root, int val) { + if (root == null) + return new TreeNode(val); + if (root.val > val) + root.left = insertIntoBST(root.left, val); + else + root.right = insertIntoBST(root.right, val); + return root; + } +} diff --git a/solutions/701. Insert into a Binary Search Tree/701.py b/solutions/701. Insert into a Binary Search Tree/701.py new file mode 100644 index 00000000000..475aff6b332 --- /dev/null +++ b/solutions/701. Insert into a Binary Search Tree/701.py @@ -0,0 +1,9 @@ +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: + return TreeNode(val) + if root.val > val: + root.left = self.insertIntoBST(root.left, val) + else: + root.right = self.insertIntoBST(root.right, val) + return root diff --git a/solutions/702. Search in a Sorted Array of Unknown Size/702.cpp b/solutions/702. Search in a Sorted Array of Unknown Size/702.cpp new file mode 100644 index 00000000000..c268285f2df --- /dev/null +++ b/solutions/702. Search in a Sorted Array of Unknown Size/702.cpp @@ -0,0 +1,26 @@ +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * int get(int index); + * }; + */ + +class Solution { + public: + int search(const ArrayReader& reader, int target) { + int l = 0; + int r = 10'000; + + while (l < r) { + const int m = (l + r) / 2; + if (reader.get(m) >= target) + r = m; + else + l = m + 1; + } + + return reader.get(l) == target ? l : -1; + } +}; diff --git a/solutions/702. Search in a Sorted Array of Unknown Size/702.java b/solutions/702. Search in a Sorted Array of Unknown Size/702.java new file mode 100644 index 00000000000..4f5194844ed --- /dev/null +++ b/solutions/702. Search in a Sorted Array of Unknown Size/702.java @@ -0,0 +1,24 @@ +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * public int get(int index) {} + * } + */ + +class Solution { + public int search(ArrayReader reader, int target) { + int l = 0; + int r = 10000; + + while (l < r) { + final int m = (l + r) / 2; + if (reader.get(m) >= target) + r = m; + else + l = m + 1; + } + + return reader.get(l) == target ? l : -1; + } +} diff --git a/solutions/702. Search in a Sorted Array of Unknown Size/702.py b/solutions/702. Search in a Sorted Array of Unknown Size/702.py new file mode 100644 index 00000000000..a920d1f48c1 --- /dev/null +++ b/solutions/702. Search in a Sorted Array of Unknown Size/702.py @@ -0,0 +1,12 @@ +# """ +# This is ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +# Class ArrayReader: +# def get(self, index: int) -> int: + +class Solution: + def search(self, reader: 'ArrayReader', target: int) -> int: + l = bisect.bisect_left(range(10**4), target, + key=lambda m: reader.get(m)) + return l if reader.get(l) == target else -1 diff --git a/solutions/703. Kth Largest Element in a Stream/703.cpp b/solutions/703. Kth Largest Element in a Stream/703.cpp new file mode 100644 index 00000000000..51730efeaaf --- /dev/null +++ b/solutions/703. Kth Largest Element in a Stream/703.cpp @@ -0,0 +1,22 @@ +class KthLargest { + public: + KthLargest(int k, vector& nums) : k(k) { + for (const int num : nums) + heapify(num); + } + + int add(int val) { + heapify(val); + return minHeap.top(); + } + + private: + const int k; + priority_queue, greater<>> minHeap; + + void heapify(int val) { + minHeap.push(val); + if (minHeap.size() > k) + minHeap.pop(); + } +}; diff --git a/solutions/703. Kth Largest Element in a Stream/703.java b/solutions/703. Kth Largest Element in a Stream/703.java new file mode 100644 index 00000000000..6f034e86da8 --- /dev/null +++ b/solutions/703. Kth Largest Element in a Stream/703.java @@ -0,0 +1,21 @@ +class KthLargest { + public KthLargest(int k, int[] nums) { + this.k = k; + for (final int num : nums) + heapify(num); + } + + public int add(int val) { + heapify(val); + return minHeap.peek(); + } + + private final int k; + private Queue minHeap = new PriorityQueue<>(); + + private void heapify(int val) { + minHeap.offer(val); + if (minHeap.size() > k) + minHeap.poll(); + } +} diff --git a/solutions/704. Binary Search/704.cpp b/solutions/704. Binary Search/704.cpp new file mode 100644 index 00000000000..3aa6239a06f --- /dev/null +++ b/solutions/704. Binary Search/704.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int search(vector& nums, int target) { + const auto it = ranges::lower_bound(nums, target); + return (it == nums.cend() || *it != target) ? -1 + : distance(nums.begin(), it); + } +}; diff --git a/solutions/704. Binary Search/704.java b/solutions/704. Binary Search/704.java new file mode 100644 index 00000000000..817efd77c67 --- /dev/null +++ b/solutions/704. Binary Search/704.java @@ -0,0 +1,6 @@ +class Solution { + public int search(int[] nums, int target) { + final int i = Arrays.binarySearch(nums, target); + return i < 0 ? -1 : i; + } +} diff --git a/solutions/704. Binary Search/704.py b/solutions/704. Binary Search/704.py new file mode 100644 index 00000000000..e751ae50e4c --- /dev/null +++ b/solutions/704. Binary Search/704.py @@ -0,0 +1,4 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + i = bisect.bisect_left(nums, target) + return -1 if i == len(nums) or nums[i] != target else i diff --git a/solutions/705. Design HashSet/705.cpp b/solutions/705. Design HashSet/705.cpp new file mode 100644 index 00000000000..cb3c4280313 --- /dev/null +++ b/solutions/705. Design HashSet/705.cpp @@ -0,0 +1,21 @@ +class MyHashSet { + public: + /** Initialize your data structure here. */ + MyHashSet() : set(1000001) {} + + void add(int key) { + set[key] = true; + } + + void remove(int key) { + set[key] = false; + } + + /** Returns true if this set contains the specified element */ + bool contains(int key) { + return set[key]; + } + + private: + vector set; +}; diff --git a/solutions/705. Design HashSet/705.java b/solutions/705. Design HashSet/705.java new file mode 100644 index 00000000000..b5225013e00 --- /dev/null +++ b/solutions/705. Design HashSet/705.java @@ -0,0 +1,21 @@ +class MyHashSet { + /** Initialize your data structure here. */ + public MyHashSet() { + set = new boolean[1000001]; + } + + public void add(int key) { + set[key] = true; + } + + public void remove(int key) { + set[key] = false; + } + + /** Returns true if this set contains the specified element */ + public boolean contains(int key) { + return set[key]; + } + + private boolean[] set = new boolean[1000001]; +} diff --git a/solutions/705. Design HashSet/705.py b/solutions/705. Design HashSet/705.py new file mode 100644 index 00000000000..1c267fa7c1b --- /dev/null +++ b/solutions/705. Design HashSet/705.py @@ -0,0 +1,12 @@ +class MyHashSet: + def __init__(self): + self.set = [False] * 1000001 + + def add(self, key: int) -> None: + self.set[key] = True + + def remove(self, key: int) -> None: + self.set[key] = False + + def contains(self, key: int) -> bool: + return self.set[key] diff --git a/solutions/706. Design HashMap/706.cpp b/solutions/706. Design HashMap/706.cpp new file mode 100644 index 00000000000..2761933f87b --- /dev/null +++ b/solutions/706. Design HashMap/706.cpp @@ -0,0 +1,36 @@ +class MyHashMap { + public: + MyHashMap() : lists(kSize) {} + + void put(int key, int value) { + auto& pairs = lists[key % kSize]; + for (auto& [k, v] : pairs) + if (k == key) { + v = value; + return; + } + pairs.emplace_back(key, value); + } + + int get(int key) { + const list>& pairs = lists[key % kSize]; + for (const auto& [k, v] : pairs) + if (k == key) + return v; + return -1; + } + + void remove(int key) { + auto& pairs = lists[key % kSize]; + for (auto it = pairs.begin(); it != pairs.end(); ++it) + if (it->first == key) { + pairs.erase(it); + return; + } + } + + private: + static constexpr int kSize = 10000; + // Each slot stores the (key, value) list. + vector>> lists; +}; diff --git a/solutions/706. Design HashMap/706.java b/solutions/706. Design HashMap/706.java new file mode 100644 index 00000000000..d01da368447 --- /dev/null +++ b/solutions/706. Design HashMap/706.java @@ -0,0 +1,34 @@ +class MyHashMap { + public MyHashMap() { + lists = new List[kSize]; + for (int i = 0; i < kSize; ++i) + lists[i] = new ArrayList<>(); + } + + public void put(int key, int value) { + for (int[] pair : lists[key % kSize]) + if (pair[0] == key) { + pair[1] = value; + return; + } + lists[key % kSize].add(new int[] {key, value}); + } + + public int get(int key) { + for (int[] pair : lists[key % kSize]) + if (pair[0] == key) + return pair[1]; + return -1; + } + + public void remove(int key) { + for (int i = 0; i < lists[key % kSize].size(); ++i) + if (lists[key % kSize].get(i)[0] == key) { + lists[key % kSize].remove(i); + return; + } + } + + private static final int kSize = 10000; + List[] lists; // Each slot stores the (key, value) list. +} diff --git a/solutions/707. Design Linked List/707.cpp b/solutions/707. Design Linked List/707.cpp new file mode 100644 index 00000000000..5bbc4d58f9f --- /dev/null +++ b/solutions/707. Design Linked List/707.cpp @@ -0,0 +1,62 @@ +class MyLinkedList { + struct ListNode { + int val; + ListNode* next; + ListNode(int x) : val(x), next(nullptr) {} + }; + + public: + int get(int index) { + if (index < 0 || index >= length) + return -1; + ListNode* curr = dummy.next; + for (int i = 0; i < index; ++i) + curr = curr->next; + return curr->val; + } + + void addAtHead(int val) { + ListNode* head = dummy.next; + ListNode* node = new ListNode(val); + node->next = head; + dummy.next = node; + ++length; + } + + void addAtTail(int val) { + ListNode* curr = &dummy; + while (curr->next) + curr = curr->next; + curr->next = new ListNode(val); + ++length; + } + + void addAtIndex(int index, int val) { + if (index > length) + return; + ListNode* curr = &dummy; + for (int i = 0; i < index; ++i) + curr = curr->next; + ListNode* cache = curr->next; + ListNode* node = new ListNode(val); + node->next = cache; + curr->next = node; + ++length; + } + + void deleteAtIndex(int index) { + if (index < 0 || index >= length) + return; + ListNode* curr = &dummy; + for (int i = 0; i < index; ++i) + curr = curr->next; + ListNode* cache = curr->next; + curr->next = cache->next; + --length; + delete cache; + } + + private: + int length = 0; + ListNode dummy = ListNode(0); +}; diff --git a/solutions/707. Design Linked List/707.java b/solutions/707. Design Linked List/707.java new file mode 100644 index 00000000000..32614e7b542 --- /dev/null +++ b/solutions/707. Design Linked List/707.java @@ -0,0 +1,62 @@ +class MyLinkedList { + private class ListNode { + int val; + ListNode next; + public ListNode(int val) { + this.val = val; + this.next = null; + } + } + + public int get(int index) { + if (index < 0 || index >= length) + return -1; + ListNode curr = dummy.next; + for (int i = 0; i < index; ++i) + curr = curr.next; + return curr.val; + } + + public void addAtHead(int val) { + ListNode head = dummy.next; + ListNode node = new ListNode(val); + node.next = head; + dummy.next = node; + ++length; + } + + public void addAtTail(int val) { + ListNode curr = dummy; + while (curr.next != null) + curr = curr.next; + curr.next = new ListNode(val); + ++length; + } + + public void addAtIndex(int index, int val) { + if (index > length) + return; + ListNode curr = dummy; + for (int i = 0; i < index; ++i) + curr = curr.next; + ListNode cache = curr.next; + ListNode node = new ListNode(val); + node.next = cache; + curr.next = node; + ++length; + } + + public void deleteAtIndex(int index) { + if (index < 0 || index >= length) + return; + ListNode curr = dummy; + for (int i = 0; i < index; ++i) + curr = curr.next; + ListNode cache = curr.next; + curr.next = cache.next; + --length; + } + + int length = 0; + ListNode dummy = new ListNode(0); +} diff --git a/solutions/707. Design Linked List/707.py b/solutions/707. Design Linked List/707.py new file mode 100644 index 00000000000..88de9b77025 --- /dev/null +++ b/solutions/707. Design Linked List/707.py @@ -0,0 +1,52 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class MyLinkedList: + def __init__(self): + self.length = 0 + self.dummy = ListNode(0) + + def get(self, index: int) -> int: + if index < 0 or index >= self.length: + return -1 + curr = self.dummy.next + for _ in range(index): + curr = curr.next + return curr.val + + def addAtHead(self, val: int) -> None: + curr = self.dummy.next + self.dummy.next = ListNode(val) + self.dummy.next.next = curr + self.length += 1 + + def addAtTail(self, val: int) -> None: + curr = self.dummy + while curr.next: + curr = curr.next + curr.next = ListNode(val) + self.length += 1 + + def addAtIndex(self, index: int, val: int) -> None: + if index > self.length: + return + curr = self.dummy + for _ in range(index): + curr = curr.next + temp = curr.next + curr.next = ListNode(val) + curr.next.next = temp + self.length += 1 + + def deleteAtIndex(self, index: int) -> None: + if index < 0 or index >= self.length: + return + curr = self.dummy + for _ in range(index): + curr = curr.next + temp = curr.next + curr.next = temp.next + self.length -= 1 diff --git a/solutions/708. Insert into a Sorted Circular Linked List/708.cpp b/solutions/708. Insert into a Sorted Circular Linked List/708.cpp new file mode 100644 index 00000000000..4a49ee0c3c6 --- /dev/null +++ b/solutions/708. Insert into a Sorted Circular Linked List/708.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + Node* insert(Node* head, int insertVal) { + if (head == nullptr) { + Node* newNode = new Node(insertVal); + newNode->next = newNode; + return newNode; + } + + Node* prev = head; + Node* curr = head->next; + + while (curr != head) { + // 1. the minimum <= insertVal <= the maximum + // 2. insertVal >= the maximum or insertVal <= the minimum + if ((prev->val <= insertVal && insertVal <= curr->val) || + // `prev` is the maximum and `curr` is the minimum + (prev->val > curr->val && + (insertVal >= prev->val || insertVal <= curr->val))) { + // Insert the node between `prev` and `curr`. + prev->next = new Node(insertVal, curr); + return head; + } + prev = prev->next; + curr = curr->next; + } + + // All the values in the list are identical. + prev->next = new Node(insertVal, curr); + return head; + } +}; diff --git a/solutions/708. Insert into a Sorted Circular Linked List/708.java b/solutions/708. Insert into a Sorted Circular Linked List/708.java new file mode 100644 index 00000000000..b2f37e63709 --- /dev/null +++ b/solutions/708. Insert into a Sorted Circular Linked List/708.java @@ -0,0 +1,30 @@ +class Solution { + public Node insert(Node head, int insertVal) { + if (head == null) { + Node newNode = new Node(insertVal); + newNode.next = newNode; + return newNode; + } + + Node prev = head; + Node curr = head.next; + + while (curr != head) { + // 1. the minimum <= insertVal <= the maximum + // 2. insertVal >= the maximum or insertVal <= the minimum + if ((prev.val <= insertVal && insertVal <= curr.val) || + // `prev` is the maximum and `curr` is the minimum + (prev.val > curr.val && (insertVal >= prev.val || insertVal <= curr.val))) { + // Insert the node between `prev` and `curr`. + prev.next = new Node(insertVal, curr); + return head; + } + prev = prev.next; + curr = curr.next; + } + + // All the values in the list are identical. + prev.next = new Node(insertVal, curr); + return head; + } +} diff --git a/solutions/709. To Lower Case/709.cpp b/solutions/709. To Lower Case/709.cpp new file mode 100644 index 00000000000..9475654d504 --- /dev/null +++ b/solutions/709. To Lower Case/709.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + string toLowerCase(string str) { + const int diff = 'A' - 'a'; + + for (char& c : str) + if (c >= 'A' && c <= 'Z') + c -= diff; + + return str; + } +}; diff --git a/solutions/709. To Lower Case/709.java b/solutions/709. To Lower Case/709.java new file mode 100644 index 00000000000..07cf36279f4 --- /dev/null +++ b/solutions/709. To Lower Case/709.java @@ -0,0 +1,13 @@ +class Solution { + public String toLowerCase(String str) { + final int diff = 'A' - 'a'; + + char[] ans = str.toCharArray(); + + for (int i = 0; i < ans.length; ++i) + if (ans[i] >= 'A' && ans[i] <= 'Z') + ans[i] -= diff; + + return new String(ans); + } +} diff --git a/solutions/709. To Lower Case/709.py b/solutions/709. To Lower Case/709.py new file mode 100644 index 00000000000..06277ff780e --- /dev/null +++ b/solutions/709. To Lower Case/709.py @@ -0,0 +1,3 @@ +class Solution: + def toLowerCase(self, str: str) -> str: + return ''.join(chr(ord(c) + 32) if 'A' <= c <= 'Z' else c for c in str) diff --git a/solutions/71. Simplify Path/71.cpp b/solutions/71. Simplify Path/71.cpp new file mode 100644 index 00000000000..500a67b913c --- /dev/null +++ b/solutions/71. Simplify Path/71.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string simplifyPath(string path) { + string ans; + istringstream iss(path); + vector stack; + + for (string dir; getline(iss, dir, '/');) { + if (dir.empty() || dir == ".") + continue; + if (dir == "..") { + if (!stack.empty()) + stack.pop_back(); + } else { + stack.push_back(dir); + } + } + + for (const string& s : stack) + ans += "/" + s; + + return ans.empty() ? "/" : ans; + } +}; diff --git a/solutions/71. Simplify Path/71.java b/solutions/71. Simplify Path/71.java new file mode 100644 index 00000000000..a18a08c5e53 --- /dev/null +++ b/solutions/71. Simplify Path/71.java @@ -0,0 +1,19 @@ +class Solution { + public String simplifyPath(String path) { + final String[] dirs = path.split("/"); + Stack stack = new Stack<>(); + + for (final String dir : dirs) { + if (dir.isEmpty() || dir.equals(".")) + continue; + if (dir.equals("..")) { + if (!stack.isEmpty()) + stack.pop(); + } else { + stack.push(dir); + } + } + + return "/" + String.join("/", stack); + } +} diff --git a/solutions/71. Simplify Path/71.py b/solutions/71. Simplify Path/71.py new file mode 100644 index 00000000000..aadf8da854c --- /dev/null +++ b/solutions/71. Simplify Path/71.py @@ -0,0 +1,14 @@ +class Solution: + def simplifyPath(self, path: str) -> str: + stack = [] + + for str in path.split('/'): + if str in ('', '.'): + continue + if str == '..': + if stack: + stack.pop() + else: + stack.append(str) + + return '/' + '/'.join(stack) diff --git a/solutions/710. Random Pick with Blacklist/710.cpp b/solutions/710. Random Pick with Blacklist/710.cpp new file mode 100644 index 00000000000..f0f4632ecad --- /dev/null +++ b/solutions/710. Random Pick with Blacklist/710.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + Solution(int n, vector& blacklist) : validRange(n - blacklist.size()) { + for (const int b : blacklist) + map[b] = -1; + + int maxAvailable = n - 1; + + for (const int b : blacklist) + if (b < validRange) { + // Find the slot that haven't been used. + while (map.contains(maxAvailable)) + --maxAvailable; + map[b] = maxAvailable--; + } + } + + int pick() { + const int num = rand() % validRange; + const auto it = map.find(num); + return it == map.cend() ? num : it->second; + } + + private: + const int validRange; + unordered_map map; +}; diff --git a/solutions/710. Random Pick with Blacklist/710.java b/solutions/710. Random Pick with Blacklist/710.java new file mode 100644 index 00000000000..a2d7bac71d8 --- /dev/null +++ b/solutions/710. Random Pick with Blacklist/710.java @@ -0,0 +1,27 @@ +class Solution { + public Solution(int n, int[] blacklist) { + validRange = n - blacklist.length; + + for (final int b : blacklist) + map.put(b, -1); + + int maxAvailable = n - 1; + + for (final int b : blacklist) + if (b < validRange) { + // Find the slot that haven't been used. + while (map.containsKey(maxAvailable)) + --maxAvailable; + map.put(b, maxAvailable--); + } + } + + public int pick() { + final int num = rand.nextInt(validRange); + return map.getOrDefault(num, num); + } + + private int validRange; + private Map map = new HashMap<>(); + private Random rand = new Random(); +} diff --git a/solutions/710. Random Pick with Blacklist/710.py b/solutions/710. Random Pick with Blacklist/710.py new file mode 100644 index 00000000000..bff87089d4a --- /dev/null +++ b/solutions/710. Random Pick with Blacklist/710.py @@ -0,0 +1,25 @@ +class Solution: + def __init__(self, n: int, blacklist: List[int]): + self.validRange = n - len(blacklist) + self.dict = {} + + maxAvailable = n - 1 + + for b in blacklist: + self.dict[b] = -1 + + for b in blacklist: + if b < self.validRange: + # Find the slot that haven't been used. + while maxAvailable in self.dict: + maxAvailable -= 1 + self.dict[b] = maxAvailable + maxAvailable -= 1 + + def pick(self) -> int: + value = random.randint(0, self.validRange - 1) + + if value in self.dict: + return self.dict[value] + + return value diff --git a/solutions/711. Number of Distinct Islands II/711.cpp b/solutions/711. Number of Distinct Islands II/711.cpp new file mode 100644 index 00000000000..df58a00c349 --- /dev/null +++ b/solutions/711. Number of Distinct Islands II/711.cpp @@ -0,0 +1,66 @@ +class Solution { + public: + int numDistinctIslands2(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + // all the islands with different shapes + set>> islands; + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + vector> island; + dfs(grid, i, j, seen, island); + if (!island.empty()) + islands.insert(normalize(island)); + } + + return islands.size(); + } + + private: + void dfs(const vector>& grid, int i, int j, + vector>& seen, vector>& island) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] == 0 || seen[i][j]) + return; + + seen[i][j] = true; + island.emplace_back(i, j); + + dfs(grid, i + 1, j, seen, island); + dfs(grid, i - 1, j, seen, island); + dfs(grid, i, j + 1, seen, island); + dfs(grid, i, j - 1, seen, island); + } + + vector> normalize(const vector>& island) { + // points[i] := 8 different rotations/reflections of an island + vector>> points(8); + + for (const auto& [i, j] : island) { + points[0].emplace_back(i, j); + points[1].emplace_back(i, -j); + points[2].emplace_back(-i, j); + points[3].emplace_back(-i, -j); + points[4].emplace_back(j, i); + points[5].emplace_back(j, -i); + points[6].emplace_back(-j, i); + points[7].emplace_back(-j, -i); + } + + for (vector>& p : points) + ranges::sort(p); + + // Normalize each p by substracting p[1..7] with p[0]. + for (vector>& p : points) { + for (int i = 1; i < island.size(); ++i) + p[i] = {p[i].first - p[0].first, p[i].second - p[0].second}; + p[0] = {0, 0}; + } + + ranges::sort(points); + return points[0]; + } +}; diff --git a/solutions/711. Number of Distinct Islands II/711.java b/solutions/711. Number of Distinct Islands II/711.java new file mode 100644 index 00000000000..a388b44e0cf --- /dev/null +++ b/solutions/711. Number of Distinct Islands II/711.java @@ -0,0 +1,81 @@ +class Solution { + public int numDistinctIslands2(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + // all the islands with different shapes + Set>> islands = new HashSet<>(); + boolean[][] seen = new boolean[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + List> island = new ArrayList<>(); + dfs(grid, i, j, seen, island); + if (!island.isEmpty()) + islands.add(normalize(island)); + } + + return islands.size(); + } + + private void dfs(int[][] grid, int i, int j, boolean[][] seen, + List> island) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] == 0 || seen[i][j]) + return; + + seen[i][j] = true; + island.add(new Pair<>(i, j)); + + dfs(grid, i + 1, j, seen, island); + dfs(grid, i - 1, j, seen, island); + dfs(grid, i, j + 1, seen, island); + dfs(grid, i, j - 1, seen, island); + } + + private List> normalize(List> island) { + // points[i] := 8 different rotations/reflections of an island + Pair[][] points = new Pair[8][island.size()]; + + for (int k = 0; k < island.size(); ++k) { + final int i = island.get(k).getKey(); + final int j = island.get(k).getValue(); + points[0][k] = new Pair<>(i, j); + points[1][k] = new Pair<>(i, -j); + points[2][k] = new Pair<>(-i, j); + points[3][k] = new Pair<>(-i, -j); + points[4][k] = new Pair<>(j, i); + points[5][k] = new Pair<>(j, -i); + points[6][k] = new Pair<>(-j, i); + points[7][k] = new Pair<>(-j, -i); + } + + for (Pair[] p : points) + Arrays.sort(p, + (a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue() - b.getValue() + : a.getKey() - b.getKey()); + + // Normalize each p by substracting p[1..7] with p[0]. + for (Pair[] p : points) { + for (int i = 1; i < island.size(); ++i) + p[i] = new Pair<>(p[i].getKey() - p[0].getKey(), p[i].getValue() - p[0].getValue()); + p[0] = new Pair<>(0, 0); + } + + Arrays.sort(points, new Comparator[]>() { + @Override + public int compare(Pair[] a, Pair[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i].getKey() != b[i].getKey()) + return a[i].getKey() - b[i].getKey(); + if (a[i].getValue() != b[i].getValue()) + return a[i].getValue() - b[i].getValue(); + } + return 0; + } + }); + + return Arrays.asList(points[0]); + } +} diff --git a/solutions/711. Number of Distinct Islands II/711.py b/solutions/711. Number of Distinct Islands II/711.py new file mode 100644 index 00000000000..92a7d3aee5a --- /dev/null +++ b/solutions/711. Number of Distinct Islands II/711.py @@ -0,0 +1,52 @@ +class Solution: + def numDistinctIslands2(self, grid: List[List[int]]) -> int: + seen = set() + + def dfs(i: int, j: int): + if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]): + return + if grid[i][j] == 0 or (i, j) in seen: + return + + seen.add((i, j)) + island.append((i, j)) + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1) + + def normalize(island: List[tuple]) -> List[tuple]: + # points[i] := 8 different rotations/reflections of an island + points = [[] for _ in range(8)] + + for i, j in island: + points[0].append((i, j)) + points[1].append((i, -j)) + points[2].append((-i, j)) + points[3].append((-i, -j)) + points[4].append((j, i)) + points[5].append((j, -i)) + points[6].append((-j, i)) + points[7].append((-j, -i)) + + points = [sorted(p) for p in points] + + # Normalize each p by substracting p[1..7] with p[0]. + for p in points: + for i in range(1, len(island)): + p[i] = (p[i][0] - p[0][0], + p[i][1] - p[0][1]) + p[0] = (0, 0) + + return sorted(points)[0] + + islands = set() # all the islands with different shapes + + for i in range(len(grid)): + for j in range(len(grid[0])): + island = [] + dfs(i, j) + if island: + islands.add(frozenset(normalize(island))) + + return len(islands) diff --git a/solutions/712. Minimum ASCII Delete Sum for Two Strings/712.cpp b/solutions/712. Minimum ASCII Delete Sum for Two Strings/712.cpp new file mode 100644 index 00000000000..856629da6ad --- /dev/null +++ b/solutions/712. Minimum ASCII Delete Sum for Two Strings/712.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minimumDeleteSum(string s1, string s2) { + const int m = s1.length(); + const int n = s2.length(); + // dp[i][j] := the minimum cost to make s1[0..i) and s2[0..j) equal + vector> dp(m + 1, vector(n + 1)); + + // Delete s1[i - 1]. + for (int i = 1; i <= m; ++i) + dp[i][0] = dp[i - 1][0] + s1[i - 1]; + + // Delete s2[j - 1]. + for (int j = 1; j <= n; ++j) + dp[0][j] = dp[0][j - 1] + s2[j - 1]; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (s1[i - 1] == s2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = min(dp[i - 1][j] + s1[i - 1], dp[i][j - 1] + s2[j - 1]); + + return dp[m][n]; + } +}; diff --git a/solutions/712. Minimum ASCII Delete Sum for Two Strings/712.java b/solutions/712. Minimum ASCII Delete Sum for Two Strings/712.java new file mode 100644 index 00000000000..4cf64ac4fa5 --- /dev/null +++ b/solutions/712. Minimum ASCII Delete Sum for Two Strings/712.java @@ -0,0 +1,25 @@ +class Solution { + public int minimumDeleteSum(String s1, String s2) { + final int m = s1.length(); + final int n = s2.length(); + // dp[i][j] := the minimum cost to make s1[0..i) and s2[0..j) equal + int[][] dp = new int[m + 1][n + 1]; + + // Delete s1[i - 1]. + for (int i = 1; i <= m; ++i) + dp[i][0] = dp[i - 1][0] + s1.charAt(i - 1); + + // Delete s2[j - 1]. + for (int j = 1; j <= n; ++j) + dp[0][j] = dp[0][j - 1] + s2.charAt(j - 1); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (s1.charAt(i - 1) == s2.charAt(j - 1)) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = Math.min(dp[i - 1][j] + s1.charAt(i - 1), dp[i][j - 1] + s2.charAt(j - 1)); + + return dp[m][n]; + } +} diff --git a/solutions/713. Subarray Product Less Than K/713.cpp b/solutions/713. Subarray Product Less Than K/713.cpp new file mode 100644 index 00000000000..0c860dadf62 --- /dev/null +++ b/solutions/713. Subarray Product Less Than K/713.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int numSubarrayProductLessThanK(vector& nums, int k) { + if (k <= 1) + return 0; + + int ans = 0; + int prod = 1; + + for (int l = 0, r = 0; r < nums.size(); ++r) { + prod *= nums[r]; + while (prod >= k) + prod /= nums[l++]; + ans += r - l + 1; + } + + return ans; + } +}; diff --git a/solutions/713. Subarray Product Less Than K/713.java b/solutions/713. Subarray Product Less Than K/713.java new file mode 100644 index 00000000000..d63f045eee7 --- /dev/null +++ b/solutions/713. Subarray Product Less Than K/713.java @@ -0,0 +1,18 @@ +class Solution { + public int numSubarrayProductLessThanK(int[] nums, int k) { + if (k <= 1) + return 0; + + int ans = 0; + int prod = 1; + + for (int l = 0, r = 0; r < nums.length; ++r) { + prod *= nums[r]; + while (prod >= k) + prod /= nums[l++]; + ans += r - l + 1; + } + + return ans; + } +} diff --git a/solutions/713. Subarray Product Less Than K/713.py b/solutions/713. Subarray Product Less Than K/713.py new file mode 100644 index 00000000000..845a911380b --- /dev/null +++ b/solutions/713. Subarray Product Less Than K/713.py @@ -0,0 +1,17 @@ +class Solution: + def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: + if k <= 1: + return 0 + + ans = 0 + prod = 1 + + j = 0 + for i, num in enumerate(nums): + prod *= num + while prod >= k: + prod /= nums[j] + j += 1 + ans += i - j + 1 + + return ans diff --git a/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.cpp b/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.cpp new file mode 100644 index 00000000000..90ed4e84c34 --- /dev/null +++ b/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int maxProfit(vector& prices, int fee) { + int sell = 0; + int hold = INT_MIN; + + for (const int price : prices) { + sell = max(sell, hold + price); + hold = max(hold, sell - price - fee); + } + + return sell; + } +}; diff --git a/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.java b/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.java new file mode 100644 index 00000000000..041f014489d --- /dev/null +++ b/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.java @@ -0,0 +1,13 @@ +class Solution { + public int maxProfit(int[] prices, int fee) { + int sell = 0; + int hold = Integer.MIN_VALUE; + + for (final int price : prices) { + sell = Math.max(sell, hold + price); + hold = Math.max(hold, sell - price - fee); + } + + return sell; + } +} diff --git a/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.py b/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.py new file mode 100644 index 00000000000..c31099720cd --- /dev/null +++ b/solutions/714. Best Time to Buy and Sell Stock with Transaction Fee/714.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + sell = 0 + hold = -math.inf + + for price in prices: + sell = max(sell, hold + price) + hold = max(hold, sell - price - fee) + + return sell diff --git a/solutions/715. Range Module/715-2.cpp b/solutions/715. Range Module/715-2.cpp new file mode 100644 index 00000000000..9ff0ce0d75d --- /dev/null +++ b/solutions/715. Range Module/715-2.cpp @@ -0,0 +1,51 @@ +class RangeModule { + public: + void addRange(int left, int right) { + const auto [l, r] = getOverlapRanges(left, right); + if (l == r) { // There's no overlap. + ranges[left] = right; // Add a new range. + return; + } + + auto last = r; + const int newLeft = min(l->first, left); + const int newRight = max((--last)->second, right); + ranges.erase(l, r); + ranges[newLeft] = newRight; // Add a new range. + } + + bool queryRange(int left, int right) { + auto it = ranges.upper_bound(left); + return it != ranges.begin() && (--it)->second >= right; + } + + void removeRange(int left, int right) { + const auto [l, r] = getOverlapRanges(left, right); + if (l == r) // There's no overlap. + return; + + auto last = r; + const int newLeft = min(l->first, left); + const int newRight = max((--last)->second, right); + ranges.erase(l, r); + // Add new ranges if needed. + if (newLeft < left) + ranges[newLeft] = left; + if (right < newRight) + ranges[right] = newRight; + } + + private: + using IT = map::iterator; + map ranges; + + pair getOverlapRanges(int left, int right) { + // Point to the first element with `second` >= `left`. + IT l = ranges.upper_bound(left); + // Point to the first element with `first` > `right`. + IT r = ranges.upper_bound(right); + if (l != ranges.begin() && (--l)->second < left) + ++l; + return {l, r}; + } +}; diff --git a/solutions/715. Range Module/715-2.java b/solutions/715. Range Module/715-2.java new file mode 100644 index 00000000000..77ebe9295f0 --- /dev/null +++ b/solutions/715. Range Module/715-2.java @@ -0,0 +1,33 @@ +class RangeModule { + public void addRange(int left, int right) { + Integer l = ranges.floorKey(left); + Integer r = ranges.floorKey(right); + + if (l != null && ranges.get(l) >= left) + left = l; + if (r != null && ranges.get(r) > right) + right = ranges.get(r); + + ranges.subMap(left, right).clear(); + ranges.put(left, right); + } + + public boolean queryRange(int left, int right) { + Integer l = ranges.floorKey(left); + return l == null ? false : ranges.get(l) >= right; + } + + public void removeRange(int left, int right) { + Integer l = ranges.floorKey(left); + Integer r = ranges.floorKey(right); + + if (r != null && ranges.get(r) > right) + ranges.put(right, ranges.get(r)); + if (l != null && ranges.get(l) > left) + ranges.put(l, left); + + ranges.subMap(left, right).clear(); + } + + private TreeMap ranges = new TreeMap<>(); +} diff --git a/solutions/715. Range Module/715-3.py b/solutions/715. Range Module/715-3.py new file mode 100644 index 00000000000..f56f1f1dbd7 --- /dev/null +++ b/solutions/715. Range Module/715-3.py @@ -0,0 +1,18 @@ +class RangeModule: + def __init__(self): + self.A = [] + + def addRange(self, left: int, right: int) -> None: + i = bisect_left(self.A, left) + j = bisect_right(self.A, right) + self.A[i:j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0) + + def queryRange(self, left: int, right: int) -> bool: + i = bisect_right(self.A, left) + j = bisect_left(self.A, right) + return i == j and i % 2 == 1 + + def removeRange(self, left: int, right: int) -> None: + i = bisect_left(self.A, left) + j = bisect_right(self.A, right) + self.A[i:j] = [left] * (i % 2 == 1) + [right] * (j % 2 == 1) diff --git a/solutions/715. Range Module/715.cpp b/solutions/715. Range Module/715.cpp new file mode 100644 index 00000000000..69dd9947006 --- /dev/null +++ b/solutions/715. Range Module/715.cpp @@ -0,0 +1,90 @@ +struct SegmentTreeNode { + int lo; + int hi; + bool tracked = false; + SegmentTreeNode* left; + SegmentTreeNode* right; + SegmentTreeNode(int lo, int hi, bool tracked, SegmentTreeNode* left = nullptr, + SegmentTreeNode* right = nullptr) + : lo(lo), hi(hi), tracked(tracked), left(left), right(right) {} + ~SegmentTreeNode() { + delete left; + delete right; + left = nullptr; + right = nullptr; + } +}; + +class SegmentTree { + public: + explicit SegmentTree() : root(make_unique(0, 1e9, false)) {} + + void addRange(int i, int j) { + update(root.get(), i, j, true); + } + + bool queryRange(int i, int j) { + return query(root.get(), i, j); + } + + void removeRange(int i, int j) { + update(root.get(), i, j, false); + } + + private: + std::unique_ptr root; + + void update(SegmentTreeNode* root, int i, int j, bool tracked) { + if (root->lo == i && root->hi == j) { + root->tracked = tracked; + root->left = nullptr; + root->right = nullptr; + return; + } + const int mid = root->lo + (root->hi - root->lo) / 2; + if (root->left == nullptr) { + root->left = new SegmentTreeNode(root->lo, mid, root->tracked); + root->right = new SegmentTreeNode(mid + 1, root->hi, root->tracked); + } + if (j <= mid) + update(root->left, i, j, tracked); + else if (i > mid) + update(root->right, i, j, tracked); + else { + update(root->left, i, mid, tracked); + update(root->right, mid + 1, j, tracked); + } + root->tracked = root->left->tracked && root->right->tracked; + } + + bool query(SegmentTreeNode* root, int i, int j) { + if (root->left == nullptr) + return root->tracked; + if (root->lo == i && root->hi == j) + return root->tracked; + const int mid = root->lo + (root->hi - root->lo) / 2; + if (j <= mid) + return query(root->left, i, j); + if (i > mid) + return query(root->right, i, j); + return query(root->left, i, mid) && query(root->right, mid + 1, j); + } +}; + +class RangeModule { + public: + void addRange(int left, int right) { + tree.addRange(left, right - 1); + } + + bool queryRange(int left, int right) { + return tree.queryRange(left, right - 1); + } + + void removeRange(int left, int right) { + tree.removeRange(left, right - 1); + } + + private: + SegmentTree tree; +}; diff --git a/solutions/716. Max Stack/716.cpp b/solutions/716. Max Stack/716.cpp new file mode 100644 index 00000000000..164239e3a1e --- /dev/null +++ b/solutions/716. Max Stack/716.cpp @@ -0,0 +1,40 @@ +class MaxStack { + public: + void push(int x) { + list.push_front(x); + keyToIterators[x].push_back(list.begin()); + } + + int pop() { + const int x = list.front(); + list.pop_front(); + auto& iterators = keyToIterators[x]; + iterators.pop_back(); + if (iterators.empty()) + keyToIterators.erase(x); + return x; + } + + int top() { + return list.front(); + } + + int peekMax() { + return keyToIterators.begin()->first; + } + + int popMax() { + const int x = peekMax(); + auto& iterators = keyToIterators.begin()->second; + auto it = iterators.back(); + list.erase(it); + iterators.pop_back(); + if (iterators.empty()) + keyToIterators.erase(keyToIterators.begin()); + return x; + } + + private: + std::list list; + map::iterator>, greater<>> keyToIterators; +}; diff --git a/solutions/717. 1-bit and 2-bit Characters/717.cpp b/solutions/717. 1-bit and 2-bit Characters/717.cpp new file mode 100644 index 00000000000..8e6490f898a --- /dev/null +++ b/solutions/717. 1-bit and 2-bit Characters/717.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool isOneBitCharacter(vector& bits) { + const int n = bits.size(); + + int i = 0; + while (i < n - 1) + if (bits[i] == 0) + i += 1; + else + i += 2; + + return i == n - 1; + } +}; diff --git a/solutions/717. 1-bit and 2-bit Characters/717.java b/solutions/717. 1-bit and 2-bit Characters/717.java new file mode 100644 index 00000000000..57eae2fe8ab --- /dev/null +++ b/solutions/717. 1-bit and 2-bit Characters/717.java @@ -0,0 +1,14 @@ +class Solution { + public boolean isOneBitCharacter(int[] bits) { + final int n = bits.length; + + int i = 0; + while (i < n - 1) + if (bits[i] == 0) + i += 1; + else + i += 2; + + return i == n - 1; + } +} diff --git a/solutions/717. 1-bit and 2-bit Characters/717.py b/solutions/717. 1-bit and 2-bit Characters/717.py new file mode 100644 index 00000000000..4f0caa7a9bf --- /dev/null +++ b/solutions/717. 1-bit and 2-bit Characters/717.py @@ -0,0 +1,7 @@ +class Solution: + def isOneBitCharacter(self, bits: List[int]) -> bool: + i = 0 + while i < len(bits) - 1: + i += bits[i] + 1 + + return i == len(bits) - 1 diff --git a/solutions/718. Maximum Length of Repeated Subarray/718-2.cpp b/solutions/718. Maximum Length of Repeated Subarray/718-2.cpp new file mode 100644 index 00000000000..e4b36d6aaa8 --- /dev/null +++ b/solutions/718. Maximum Length of Repeated Subarray/718-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int findLength(vector& nums1, vector& nums2) { + const int m = nums1.size(); + const int n = nums2.size(); + int ans = 0; + vector dp(n + 1); + + for (int i = m - 1; i >= 0; --i) + for (int j = 0; j < n; ++j) { // The order is important. + dp[j] = nums1[i] == nums2[j] ? dp[j + 1] + 1 : 0; + ans = max(ans, dp[j]); + } + + return ans; + } +}; diff --git a/solutions/718. Maximum Length of Repeated Subarray/718-2.java b/solutions/718. Maximum Length of Repeated Subarray/718-2.java new file mode 100644 index 00000000000..6fed189c6a8 --- /dev/null +++ b/solutions/718. Maximum Length of Repeated Subarray/718-2.java @@ -0,0 +1,16 @@ +class Solution { + public int findLength(int[] nums1, int[] nums2) { + final int m = nums1.length; + final int n = nums2.length; + int ans = 0; + int[] dp = new int[n + 1]; + + for (int i = m - 1; i >= 0; --i) + for (int j = 0; j < n; ++j) { // The order is important. + dp[j] = nums1[i] == nums2[j] ? dp[j + 1] + 1 : 0; + ans = Math.max(ans, dp[j]); + } + + return ans; + } +} diff --git a/solutions/718. Maximum Length of Repeated Subarray/718-2.py b/solutions/718. Maximum Length of Repeated Subarray/718-2.py new file mode 100644 index 00000000000..10abc213bde --- /dev/null +++ b/solutions/718. Maximum Length of Repeated Subarray/718-2.py @@ -0,0 +1,11 @@ +class Solution: + def findLength(self, nums1: List[int], nums2: List[int]) -> int: + ans = 0 + dp = [0] * (len(nums2) + 1) + + for a in reversed(nums1): + for j, b in enumerate(nums2): # The order is important. + dp[j] = dp[j + 1] + 1 if a == b else 0 + ans = max(ans, dp[j]) + + return ans diff --git a/solutions/718. Maximum Length of Repeated Subarray/718.cpp b/solutions/718. Maximum Length of Repeated Subarray/718.cpp new file mode 100644 index 00000000000..d86b04eeb81 --- /dev/null +++ b/solutions/718. Maximum Length of Repeated Subarray/718.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int findLength(vector& nums1, vector& nums2) { + const int m = nums1.size(); + const int n = nums2.size(); + int ans = 0; + // dp[i][j] := the maximum length of a subarray that appears in both + // nums1[i..m) and nums2[j..n) + vector> dp(m + 1, vector(n + 1)); + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) + if (nums1[i] == nums2[j]) { + dp[i][j] = dp[i + 1][j + 1] + 1; + ans = max(ans, dp[i][j]); + } + + return ans; + } +}; diff --git a/solutions/718. Maximum Length of Repeated Subarray/718.java b/solutions/718. Maximum Length of Repeated Subarray/718.java new file mode 100644 index 00000000000..a77f5b767d1 --- /dev/null +++ b/solutions/718. Maximum Length of Repeated Subarray/718.java @@ -0,0 +1,19 @@ +class Solution { + public int findLength(int[] nums1, int[] nums2) { + final int m = nums1.length; + final int n = nums2.length; + int ans = 0; + // dp[i][j] := the maximum length of a subarray that appears in both + // nums1[i..m) and nums2[j..n) + int[][] dp = new int[m + 1][n + 1]; + + for (int i = m - 1; i >= 0; --i) + for (int j = n - 1; j >= 0; --j) + if (nums1[i] == nums2[j]) { + dp[i][j] = dp[i + 1][j + 1] + 1; + ans = Math.max(ans, dp[i][j]); + } + + return ans; + } +} diff --git a/solutions/718. Maximum Length of Repeated Subarray/718.py b/solutions/718. Maximum Length of Repeated Subarray/718.py new file mode 100644 index 00000000000..5bf7d06d1f9 --- /dev/null +++ b/solutions/718. Maximum Length of Repeated Subarray/718.py @@ -0,0 +1,16 @@ +class Solution: + def findLength(self, nums1: List[int], nums2: List[int]) -> int: + m = len(nums1) + n = len(nums2) + ans = 0 + # dp[i][j] := the maximum length of a subarray that appears in both + # nums1[i..m) and nums2[j..n) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for i in reversed(range(m)): + for j in reversed(range(n)): + if nums1[i] == nums2[j]: + dp[i][j] = dp[i + 1][j + 1] + 1 + ans = max(ans, dp[i][j]) + + return ans diff --git a/solutions/719. Find K-th Smallest Pair Distance/719.cpp b/solutions/719. Find K-th Smallest Pair Distance/719.cpp new file mode 100644 index 00000000000..cbb80ca60ae --- /dev/null +++ b/solutions/719. Find K-th Smallest Pair Distance/719.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int smallestDistancePair(vector& nums, int k) { + ranges::sort(nums); + + int l = 0; + int r = nums.back() - nums.front(); + + while (l < r) { + const int m = (l + r) / 2; + if (numPairDistancesNoGreaterThan(nums, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + int numPairDistancesNoGreaterThan(const vector& nums, int m) { + int count = 0; + int j = 1; + // For each index i, find the first index j s.t. nums[j] > nums[i] + m, + // so numPairDistancesNoGreaterThan for the index i will be j - i - 1. + for (int i = 0; i < nums.size(); ++i) { + while (j < nums.size() && nums[j] <= nums[i] + m) + ++j; + count += j - i - 1; + } + return count; + } +}; diff --git a/solutions/719. Find K-th Smallest Pair Distance/719.java b/solutions/719. Find K-th Smallest Pair Distance/719.java new file mode 100644 index 00000000000..d9a69095479 --- /dev/null +++ b/solutions/719. Find K-th Smallest Pair Distance/719.java @@ -0,0 +1,31 @@ +class Solution { + public int smallestDistancePair(int[] nums, int k) { + Arrays.sort(nums); + + int l = 0; + int r = nums[nums.length - 1] - nums[0]; + + while (l < r) { + final int m = (l + r) / 2; + if (numPairDistancesNoGreaterThan(nums, m) >= k) + r = m; + else + l = m + 1; + } + + return l; + } + + private int numPairDistancesNoGreaterThan(int[] nums, int m) { + int count = 0; + int j = 1; + // For each index i, find the first index j s.t. nums[j] > nums[i] + m, + // so numPairDistancesNoGreaterThan for the index i will be j - i - 1. + for (int i = 0; i < nums.length; ++i) { + while (j < nums.length && nums[j] <= nums[i] + m) + ++j; + count += j - i - 1; + } + return count; + } +} diff --git a/solutions/719. Find K-th Smallest Pair Distance/719.py b/solutions/719. Find K-th Smallest Pair Distance/719.py new file mode 100644 index 00000000000..e9b20e50547 --- /dev/null +++ b/solutions/719. Find K-th Smallest Pair Distance/719.py @@ -0,0 +1,18 @@ +class Solution: + def smallestDistancePair(self, nums: List[int], k: int) -> int: + nums.sort() + + def numPairDistancesNoGreaterThan(m: int) -> int: + count = 0 + j = 1 + # For each index i, find the first index j s.t. nums[j] > nums[i] + m, + # so numPairDistancesNoGreaterThan for the index i will be j - i - 1. + for i, num in enumerate(nums): + while j < len(nums) and nums[j] <= num + m: + j += 1 + count += j - i - 1 + return count + + return bisect.bisect_left( + range(0, nums[-1] - nums[0]), k, + key=lambda m: numPairDistancesNoGreaterThan(m)) diff --git a/solutions/72. Edit Distance/72.cpp b/solutions/72. Edit Distance/72.cpp new file mode 100644 index 00000000000..c4f84c6539b --- /dev/null +++ b/solutions/72. Edit Distance/72.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minDistance(string word1, string word2) { + const int m = word1.length(); + const int n = word2.length(); + // dp[i][j] := the minimum number of operations to convert word1[0..i) to + // word2[0..j) + vector> dp(m + 1, vector(n + 1)); + + for (int i = 1; i <= m; ++i) + dp[i][0] = i; + + for (int j = 1; j <= n; ++j) + dp[0][j] = j; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (word1[i - 1] == word2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1; + + return dp[m][n]; + } +}; diff --git a/solutions/72. Edit Distance/72.java b/solutions/72. Edit Distance/72.java new file mode 100644 index 00000000000..dd1c68646cf --- /dev/null +++ b/solutions/72. Edit Distance/72.java @@ -0,0 +1,24 @@ +class Solution { + public int minDistance(String word1, String word2) { + final int m = word1.length(); + final int n = word2.length(); + // dp[i][j] := the minimum number of operations to convert word1[0..i) to + // word2[0..j) + int[][] dp = new int[m + 1][n + 1]; + + for (int i = 1; i <= m; ++i) + dp[i][0] = i; + + for (int j = 1; j <= n; ++j) + dp[0][j] = j; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (word1.charAt(i - 1) == word2.charAt(j - 1)) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; + + return dp[m][n]; + } +} diff --git a/solutions/72. Edit Distance/72.py b/solutions/72. Edit Distance/72.py new file mode 100644 index 00000000000..923dca020d2 --- /dev/null +++ b/solutions/72. Edit Distance/72.py @@ -0,0 +1,22 @@ +class Solution: + def minDistance(self, word1: str, word2: str) -> int: + m = len(word1) + n = len(word2) + # dp[i][j] := the minimum number of operations to convert word1[0..i) to + # word2[0..j) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(1, m + 1): + dp[i][0] = i + + for j in range(1, n + 1): + dp[0][j] = j + + for i in range(1, m + 1): + for j in range(1, n + 1): + if word1[i - 1] == word2[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + else: + dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1 + + return dp[m][n] diff --git a/solutions/720. Longest Word in Dictionary/720.cpp b/solutions/720. Longest Word in Dictionary/720.cpp new file mode 100644 index 00000000000..b7546f7579d --- /dev/null +++ b/solutions/720. Longest Word in Dictionary/720.cpp @@ -0,0 +1,41 @@ +struct TrieNode { + vector> children; + const string* word = nullptr; + TrieNode() : children(26) {} +}; + +class Solution { + public: + string longestWord(vector& words) { + for (const string& word : words) + insert(word); + return longestWordFrom(root); + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->word = &word; + } + + string longestWordFrom(shared_ptr node) { + string ans = node->word ? *node->word : ""; + + for (shared_ptr child : node->children) + if (child && child->word) { + string childWord = longestWordFrom(child); + if (childWord.length() > ans.length()) + ans = childWord; + } + + return ans; + } +}; diff --git a/solutions/720. Longest Word in Dictionary/720.java b/solutions/720. Longest Word in Dictionary/720.java new file mode 100644 index 00000000000..6ab733ff70b --- /dev/null +++ b/solutions/720. Longest Word in Dictionary/720.java @@ -0,0 +1,38 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public String word; +} + +class Solution { + public String longestWord(String[] words) { + for (final String word : words) + insert(word); + return longestWordFrom(root); + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.word = word; + } + + private String longestWordFrom(TrieNode node) { + String ans = node.word == null ? "" : node.word; + + for (TrieNode child : node.children) + if (child != null && child.word != null) { + String childWord = longestWordFrom(child); + if (childWord.length() > ans.length()) + ans = childWord; + } + + return ans; + } +} diff --git a/solutions/720. Longest Word in Dictionary/720.py b/solutions/720. Longest Word in Dictionary/720.py new file mode 100644 index 00000000000..aa4c2ea792a --- /dev/null +++ b/solutions/720. Longest Word in Dictionary/720.py @@ -0,0 +1,24 @@ +class Solution: + def longestWord(self, words: List[str]) -> str: + root = {} + + for word in words: + node = root + for c in word: + if c not in node: + node[c] = {} + node = node[c] + node['word'] = word + + def dfs(node: dict) -> str: + ans = node['word'] if 'word' in node else '' + + for child in node: + if 'word' in node[child] and len(node[child]['word']) > 0: + childWord = dfs(node[child]) + if len(childWord) > len(ans) or (len(childWord) == len(ans) and childWord < ans): + ans = childWord + + return ans + + return dfs(root) diff --git a/solutions/721. Accounts Merge/721.cpp b/solutions/721. Accounts Merge/721.cpp new file mode 100644 index 00000000000..9503a5bf7e2 --- /dev/null +++ b/solutions/721. Accounts Merge/721.cpp @@ -0,0 +1,63 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), sz(n, 1) { + iota(id.begin(), id.end(), 0); + } + + void unionBySize(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (sz[i] < sz[j]) { + sz[j] += sz[i]; + id[i] = j; + } else { + sz[i] += sz[j]; + id[j] = i; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector sz; +}; + +class Solution { + public: + vector> accountsMerge(vector>& accounts) { + vector> ans; + unordered_map emailToIndex; // {email: index} + unordered_map> indexToEmails; // {index: {emails}} + UnionFind uf(accounts.size()); + + for (int i = 0; i < accounts.size(); ++i) { + const string name = accounts[i][0]; + for (int j = 1; j < accounts[i].size(); ++j) { + const string email = accounts[i][j]; + const auto it = emailToIndex.find(email); + if (it == emailToIndex.end()) { + emailToIndex[email] = i; + } else { + uf.unionBySize(i, it->second); + } + } + } + + for (const auto& [email, index] : emailToIndex) + indexToEmails[uf.find(index)].insert(email); + + for (const auto& [index, emails] : indexToEmails) { + const string name = accounts[index][0]; + vector row{name}; + row.insert(row.end(), emails.begin(), emails.end()); + ans.push_back(row); + } + + return ans; + } +}; diff --git a/solutions/721. Accounts Merge/721.java b/solutions/721. Accounts Merge/721.java new file mode 100644 index 00000000000..29beb81a040 --- /dev/null +++ b/solutions/721. Accounts Merge/721.java @@ -0,0 +1,54 @@ +class UnionFind { + public UnionFind(List> accounts) { + for (List account : accounts) + for (int i = 1; i < account.size(); ++i) { + final String email = account.get(i); + id.putIfAbsent(email, email); + } + } + + public void union(final String u, final String v) { + id.put(find(u), find(v)); + } + + public String find(final String u) { + if (u != id.get(u)) + id.put(u, find(id.get(u))); + return id.get(u); + } + + private Map id = new HashMap<>(); +} + +class Solution { + public List> accountsMerge(List> accounts) { + List> ans = new ArrayList<>(); + Map emailToName = new HashMap<>(); + Map> idEmailToEmails = new HashMap<>(); + UnionFind uf = new UnionFind(accounts); + + for (final List account : accounts) + for (int i = 1; i < account.size(); ++i) + emailToName.putIfAbsent(account.get(i), account.get(0)); + + for (final List account : accounts) + for (int i = 2; i < account.size(); ++i) + uf.union(account.get(i), account.get(i - 1)); + + for (final List account : accounts) + for (int i = 1; i < account.size(); ++i) { + final String id = uf.find(account.get(i)); + idEmailToEmails.putIfAbsent(id, new TreeSet<>()); + idEmailToEmails.get(id).add(account.get(i)); + } + + for (final String idEmail : idEmailToEmails.keySet()) { + List emails = new ArrayList<>(idEmailToEmails.get(idEmail)); + final String name = emailToName.get(idEmail); + emails.add(0, name); + ans.add(emails); + } + + return ans; + } +} diff --git a/solutions/722. Remove Comments/722.cpp b/solutions/722. Remove Comments/722.cpp new file mode 100644 index 00000000000..e8198a2a6f7 --- /dev/null +++ b/solutions/722. Remove Comments/722.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + vector removeComments(vector& source) { + vector ans; + bool commenting = false; + string modified; + + for (const string& line : source) { + for (int i = 0; i < line.length();) { + if (i + 1 == line.length()) { + if (!commenting) + modified += line[i]; + ++i; + break; + } + const string& twoChars = line.substr(i, 2); + if (twoChars == "/*" && !commenting) { + commenting = true; + i += 2; + } else if (twoChars == "*/" && commenting) { + commenting = false; + i += 2; + } else if (twoChars == "//") { + if (!commenting) + break; + else + i += 2; + } else { + if (!commenting) + modified += line[i]; + ++i; + } + } + if (modified.length() > 0 && !commenting) { + ans.push_back(modified); + modified = ""; + } + } + + return ans; + } +}; diff --git a/solutions/722. Remove Comments/722.java b/solutions/722. Remove Comments/722.java new file mode 100644 index 00000000000..a50bb9b392b --- /dev/null +++ b/solutions/722. Remove Comments/722.java @@ -0,0 +1,41 @@ +class Solution { + public List removeComments(String[] source) { + List ans = new ArrayList<>(); + boolean commenting = false; + StringBuilder modified = new StringBuilder(); + + for (final String line : source) { + for (int i = 0; i < line.length();) { + if (i + 1 == line.length()) { + if (!commenting) + modified.append(line.charAt(i)); + ++i; + break; + } + String twoChars = line.substring(i, i + 2); + if (twoChars.equals("/*") && !commenting) { + commenting = true; + i += 2; + } else if (twoChars.equals("*/") && commenting) { + commenting = false; + i += 2; + } else if (twoChars.equals("//")) { + if (!commenting) + break; + else + i += 2; + } else { + if (!commenting) + modified.append(line.charAt(i)); + ++i; + } + } + if (modified.length() > 0 && !commenting) { + ans.add(modified.toString()); + modified.setLength(0); + } + } + + return ans; + } +} diff --git a/solutions/722. Remove Comments/722.py b/solutions/722. Remove Comments/722.py new file mode 100644 index 00000000000..a6882da9e2a --- /dev/null +++ b/solutions/722. Remove Comments/722.py @@ -0,0 +1,35 @@ +class Solution: + def removeComments(self, source: List[str]) -> List[str]: + ans = [] + commenting = False + modified = '' + + for line in source: + i = 0 + while i < len(line): + if i + 1 == len(line): + if not commenting: + modified += line[i] + i += 1 + break + twoChars = line[i:i + 2] + if twoChars == '/*' and not commenting: + commenting = True + i += 2 + elif twoChars == '*/' and commenting: + commenting = False + i += 2 + elif twoChars == '//': + if not commenting: + break + else: + i += 2 + else: + if not commenting: + modified += line[i] + i += 1 + if modified and not commenting: + ans.append(modified) + modified = '' + + return ans diff --git a/solutions/723. Candy Crush/723.cpp b/solutions/723. Candy Crush/723.cpp new file mode 100644 index 00000000000..b218c809039 --- /dev/null +++ b/solutions/723. Candy Crush/723.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + vector> candyCrush(vector>& board) { + const int m = board.size(); + const int n = board[0].size(); + bool haveCrushes = true; + + while (haveCrushes) { + haveCrushes = false; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + const int val = abs(board[i][j]); + if (val == 0) + continue; + // Crush the vertical candies. + if (j + 2 < n && abs(board[i][j + 1]) == val && + abs(board[i][j + 2]) == val) { + haveCrushes = true; + for (int k = j; k < j + 3; ++k) + board[i][k] = -val; + } + // Crush the horizontal candies. + if (i + 2 < m && abs(board[i + 1][j]) == val && + abs(board[i + 2][j]) == val) { + haveCrushes = true; + for (int k = i; k < i + 3; ++k) + board[k][j] = -val; + } + } + + if (haveCrushes) { + // For each column, drop the candies. + for (int j = 0; j < n; ++j) { + int nextIndex = m - 1; + for (int i = m - 1; i >= 0; --i) + if (board[i][j] > 0) + board[nextIndex--][j] = board[i][j]; + // Set board[0..nextIndex][j] to 0s. + for (int i = nextIndex; i >= 0; --i) + board[i][j] = 0; + } + } + } + + return board; + } +}; diff --git a/solutions/723. Candy Crush/723.java b/solutions/723. Candy Crush/723.java new file mode 100644 index 00000000000..fbfe2c6cba6 --- /dev/null +++ b/solutions/723. Candy Crush/723.java @@ -0,0 +1,45 @@ +class Solution { + public int[][] candyCrush(int[][] board) { + final int m = board.length; + final int n = board[0].length; + boolean haveCrushes = true; + + while (haveCrushes) { + haveCrushes = false; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) { + final int val = Math.abs(board[i][j]); + if (val == 0) + continue; + // Crush the vertical candies. + if (j + 2 < n && Math.abs(board[i][j + 1]) == val && Math.abs(board[i][j + 2]) == val) { + haveCrushes = true; + for (int k = j; k < j + 3; ++k) + board[i][k] = -val; + } + // Crush the horizontal candies. + if (i + 2 < m && Math.abs(board[i + 1][j]) == val && Math.abs(board[i + 2][j]) == val) { + haveCrushes = true; + for (int k = i; k < i + 3; ++k) + board[k][j] = -val; + } + } + + if (haveCrushes) { + // For each column, drop the candies. + for (int j = 0; j < n; ++j) { + int nextIndex = m - 1; + for (int i = m - 1; i >= 0; --i) + if (board[i][j] > 0) + board[nextIndex--][j] = board[i][j]; + // Set board[0..nextIndex][j] to 0s. + for (int i = nextIndex; i >= 0; --i) + board[i][j] = 0; + } + } + } + + return board; + } +} diff --git a/solutions/724. Find Pivot Index/724.cpp b/solutions/724. Find Pivot Index/724.cpp new file mode 100644 index 00000000000..af300790237 --- /dev/null +++ b/solutions/724. Find Pivot Index/724.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int pivotIndex(vector& nums) { + const int sum = accumulate(nums.begin(), nums.end(), 0); + int prefix = 0; + + for (int i = 0; i < nums.size(); ++i) { + if (prefix == sum - prefix - nums[i]) + return i; + prefix += nums[i]; + } + + return -1; + } +}; diff --git a/solutions/724. Find Pivot Index/724.java b/solutions/724. Find Pivot Index/724.java new file mode 100644 index 00000000000..57c4a787edc --- /dev/null +++ b/solutions/724. Find Pivot Index/724.java @@ -0,0 +1,14 @@ +class Solution { + public int pivotIndex(int[] nums) { + final int sum = Arrays.stream(nums).sum(); + int prefix = 0; + + for (int i = 0; i < nums.length; ++i) { + if (prefix == sum - prefix - nums[i]) + return i; + prefix += nums[i]; + } + + return -1; + } +} diff --git a/solutions/724. Find Pivot Index/724.py b/solutions/724. Find Pivot Index/724.py new file mode 100644 index 00000000000..b2eb4187001 --- /dev/null +++ b/solutions/724. Find Pivot Index/724.py @@ -0,0 +1,11 @@ +class Solution: + def pivotIndex(self, nums: List[int]) -> int: + summ = sum(nums) + prefix = 0 + + for i, num in enumerate(nums): + if prefix == summ - prefix - num: + return i + prefix += num + + return -1 diff --git a/solutions/725. Split Linked List in Parts/725.cpp b/solutions/725. Split Linked List in Parts/725.cpp new file mode 100644 index 00000000000..2579dea4d74 --- /dev/null +++ b/solutions/725. Split Linked List in Parts/725.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector splitListToParts(ListNode* root, int k) { + vector ans(k); + const int length = getLength(root); + const int subLength = length / k; + int remainder = length % k; + + ListNode* prev = nullptr; + ListNode* head = root; + + for (int i = 0; i < k; ++i, --remainder) { + ans[i] = head; + for (int j = 0; j < subLength + (remainder > 0); ++j) { + prev = head; + head = head->next; + } + if (prev != nullptr) + prev->next = nullptr; + } + + return ans; + } + + private: + int getLength(ListNode* root) { + int length = 0; + for (ListNode* curr = root; curr; curr = curr->next) + ++length; + return length; + } +}; diff --git a/solutions/725. Split Linked List in Parts/725.java b/solutions/725. Split Linked List in Parts/725.java new file mode 100644 index 00000000000..e5b13889f91 --- /dev/null +++ b/solutions/725. Split Linked List in Parts/725.java @@ -0,0 +1,30 @@ +class Solution { + public ListNode[] splitListToParts(ListNode root, int k) { + ListNode[] ans = new ListNode[k]; + final int length = getLength(root); + final int subLength = length / k; + int remainder = length % k; + + ListNode prev = null; + ListNode head = root; + + for (int i = 0; i < k; ++i, --remainder) { + ans[i] = head; + for (int j = 0; j < subLength + (remainder > 0 ? 1 : 0); ++j) { + prev = head; + head = head.next; + } + if (prev != null) + prev.next = null; + } + + return ans; + } + + private int getLength(ListNode root) { + int length = 0; + for (ListNode curr = root; curr != null; curr = curr.next) + ++length; + return length; + } +} diff --git a/solutions/725. Split Linked List in Parts/725.py b/solutions/725. Split Linked List in Parts/725.py new file mode 100644 index 00000000000..a48ac852163 --- /dev/null +++ b/solutions/725. Split Linked List in Parts/725.py @@ -0,0 +1,24 @@ +class Solution: + def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]: + ans = [[] for _ in range(k)] + length = 0 + curr = root + while curr: + length += 1 + curr = curr.next + subLength = length // k + remainder = length % k + + prev = None + head = root + + for i in range(k): + ans[i] = head + for j in range(subLength + (1 if remainder > 0 else 0)): + prev = head + head = head.next + if prev: + prev.next = None + remainder -= 1 + + return ans diff --git a/solutions/726. Number of Atoms/726.cpp b/solutions/726. Number of Atoms/726.cpp new file mode 100644 index 00000000000..d0a6ee4126d --- /dev/null +++ b/solutions/726. Number of Atoms/726.cpp @@ -0,0 +1,52 @@ +class Solution { + public: + string countOfAtoms(string formula) { + string ans; + int i = 0; + + for (const auto& [elem, freq] : parse(formula, i)) { + ans += elem; + if (freq > 1) + ans += to_string(freq); + } + + return ans; + } + + private: + map parse(const string& s, int& i) { + map count; + + while (i < s.length()) + if (s[i] == '(') { + for (const auto& [elem, freq] : parse(s, ++i)) + count[elem] += freq; + } else if (s[i] == ')') { + const int num = getNum(s, ++i); + for (auto&& [_, freq] : count) + freq *= num; + return count; // Return back to the previous scope. + } else { // `s[i]` must be uppercased. + const string& elem = getElem(s, i); + const int num = getNum(s, i); + count[elem] += num; + } + + return count; + } + + string getElem(const string& s, int& i) { + const int elemStart = i++; // `s[elemStart]` is uppercased. + while (i < s.length() && islower(s[i])) + ++i; + return s.substr(elemStart, i - elemStart); + } + + int getNum(const string& s, int& i) { + const int numStart = i; + while (i < s.length() && isdigit(s[i])) + ++i; + const string& numString = s.substr(numStart, i - numStart); + return numString.empty() ? 1 : stoi(numString); + } +}; diff --git a/solutions/726. Number of Atoms/726.java b/solutions/726. Number of Atoms/726.java new file mode 100644 index 00000000000..216ed059f58 --- /dev/null +++ b/solutions/726. Number of Atoms/726.java @@ -0,0 +1,56 @@ +class Solution { + public String countOfAtoms(String formula) { + StringBuilder sb = new StringBuilder(); + Map count = parse(formula); + + for (final String elem : count.keySet()) + sb.append(elem + (count.get(elem) == 1 ? "" : String.valueOf(count.get(elem)))); + + return sb.toString(); + } + + private int i = 0; + + private Map parse(String s) { + Map count = new TreeMap<>(); + + while (i < s.length()) + if (s.charAt(i) == '(') { + ++i; // Skip '(' + for (Map.Entry entry : parse(s).entrySet()) { + final String elem = entry.getKey(); + final int freq = entry.getValue(); + count.merge(elem, freq, Integer::sum); + } + } else if (s.charAt(i) == ')') { + ++i; // Skip ')' + final int num = getNum(s); + for (final String elem : count.keySet()) { + final int freq = count.get(elem); + count.put(elem, freq * num); + } + return count; // Return back to the previous scope. + } else { + final String elem = getElem(s); + final int num = getNum(s); + count.merge(elem, num, Integer::sum); + } + + return count; + } + + private String getElem(final String s) { + final int elemStart = i++; // `s[elemStart]` is uppercased. + while (i < s.length() && Character.isLowerCase(s.charAt(i))) + ++i; + return s.substring(elemStart, i); + } + + private int getNum(final String s) { + final int numStart = i; + while (i < s.length() && Character.isDigit(s.charAt(i))) + ++i; + final String numString = s.substring(numStart, i); + return numString.isEmpty() ? 1 : Integer.parseInt(numString); + } +} diff --git a/solutions/726. Number of Atoms/726.py b/solutions/726. Number of Atoms/726.py new file mode 100644 index 00000000000..3f078fb8637 --- /dev/null +++ b/solutions/726. Number of Atoms/726.py @@ -0,0 +1,47 @@ +class Solution: + def countOfAtoms(self, formula: str) -> str: + def parse() -> dict: + ans = collections.defaultdict(int) + + nonlocal i + while i < n: + if formula[i] == '(': + i += 1 + for elem, freq in parse().items(): + ans[elem] += freq + elif formula[i] == ')': + i += 1 + numStart = i + while i < n and formula[i].isdigit(): + i += 1 + factor = int(formula[numStart:i]) + for elem, freq in ans.items(): + ans[elem] *= factor + return ans + elif formula[i].isupper(): + elemStart = i + i += 1 + while i < n and formula[i].islower(): + i += 1 + elem = formula[elemStart:i] + numStart = i + while i < n and formula[i].isdigit(): + i += 1 + num = 1 if i == numStart else int( + formula[numStart:i]) + ans[elem] += num + + return ans + + n = len(formula) + + ans = "" + i = 0 + count = parse() + + for elem in sorted(count.keys()): + ans += elem + if count[elem] > 1: + ans += str(count[elem]) + + return ans diff --git a/solutions/727. Minimum Window Subsequence/727.cpp b/solutions/727. Minimum Window Subsequence/727.cpp new file mode 100644 index 00000000000..ac7c3d78fbd --- /dev/null +++ b/solutions/727. Minimum Window Subsequence/727.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + string minWindow(string s1, string s2) { + const int m = s2.length(); + const int n = s1.length(); + // dp[i][j] := the start index (1-indexed) of the minimum window of s2[0..i) + // and s1[0..j). + vector> dp(m + 1, vector(n + 1)); + + // Fill in the placeholder values. + for (int j = 0; j <= n; ++j) + dp[0][j] = j + 1; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (s2[i - 1] == s1[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = dp[i][j - 1]; + + int bestLeft = 0; + int minLength = INT_MAX; + + for (int j = 1; j <= n; ++j) + if (dp[m][j] > 0 && j - dp[m][j] + 1 < minLength) { + bestLeft = dp[m][j] - 1; + minLength = j - dp[m][j] + 1; + } + + return minLength == INT_MAX ? "" : s1.substr(bestLeft, minLength); + } +}; diff --git a/solutions/727. Minimum Window Subsequence/727.java b/solutions/727. Minimum Window Subsequence/727.java new file mode 100644 index 00000000000..ac5487df031 --- /dev/null +++ b/solutions/727. Minimum Window Subsequence/727.java @@ -0,0 +1,31 @@ +class Solution { + public String minWindow(String s1, String s2) { + final int m = s2.length(); + final int n = s1.length(); + // dp[i][j] := the start index (1-indexed) of the minimum window of s2[0..i) + // and s1[0..j). + int[][] dp = new int[m + 1][n + 1]; + + // Fill in the placeholder values. + for (int j = 0; j <= n; ++j) + dp[0][j] = j + 1; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + if (s2.charAt(i - 1) == s1.charAt(j - 1)) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = dp[i][j - 1]; + + int bestLeft = 0; + int minLength = Integer.MAX_VALUE; + + for (int j = 1; j <= n; ++j) + if (dp[m][j] > 0 && j - dp[m][j] + 1 < minLength) { + bestLeft = dp[m][j] - 1; + minLength = j - dp[m][j] + 1; + } + + return minLength == Integer.MAX_VALUE ? "" : s1.substring(bestLeft, bestLeft + minLength); + } +} diff --git a/solutions/728. Self Dividing Numbers/728.cpp b/solutions/728. Self Dividing Numbers/728.cpp new file mode 100644 index 00000000000..6d3b77c587b --- /dev/null +++ b/solutions/728. Self Dividing Numbers/728.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector selfDividingNumbers(int left, int right) { + vector ans; + + for (int num = left; num <= right; ++num) + if (selfDividingNumbers(num)) + ans.push_back(num); + + return ans; + } + + private: + bool selfDividingNumbers(int num) { + for (int n = num; n > 0; n /= 10) + if (n % 10 == 0 || num % (n % 10) != 0) + return false; + return true; + } +}; diff --git a/solutions/728. Self Dividing Numbers/728.java b/solutions/728. Self Dividing Numbers/728.java new file mode 100644 index 00000000000..78a2374de22 --- /dev/null +++ b/solutions/728. Self Dividing Numbers/728.java @@ -0,0 +1,18 @@ +class Solution { + public List selfDividingNumbers(int left, int right) { + List ans = new ArrayList<>(); + + for (int num = left; num <= right; ++num) + if (dividingNumber(num)) + ans.add(num); + + return ans; + } + + private boolean dividingNumber(int num) { + for (int n = num; n > 0; n /= 10) + if (n % 10 == 0 || num % (n % 10) != 0) + return false; + return true; + } +} diff --git a/solutions/728. Self Dividing Numbers/728.py b/solutions/728. Self Dividing Numbers/728.py new file mode 100644 index 00000000000..897d3814875 --- /dev/null +++ b/solutions/728. Self Dividing Numbers/728.py @@ -0,0 +1,3 @@ +class Solution: + def selfDividingNumbers(self, left: int, right: int) -> List[int]: + return [num for num in range(left, right + 1) if all(n != 0 and num % n == 0 for n in map(int, str(num)))] diff --git a/solutions/729. My Calendar I/729-2.cpp b/solutions/729. My Calendar I/729-2.cpp new file mode 100644 index 00000000000..5b59c046499 --- /dev/null +++ b/solutions/729. My Calendar I/729-2.cpp @@ -0,0 +1,16 @@ +class MyCalendar { + public: + bool book(int start, int end) { + auto lo = timeline.lower_bound(end); + + if (lo == timeline.begin() || (--lo)->second <= start) { + timeline[start] = end; + return true; + } + + return false; + } + + private: + map timeline; +}; diff --git a/solutions/729. My Calendar I/729-2.java b/solutions/729. My Calendar I/729-2.java new file mode 100644 index 00000000000..d56a419fad2 --- /dev/null +++ b/solutions/729. My Calendar I/729-2.java @@ -0,0 +1,14 @@ +class MyCalendar { + public boolean book(int start, int end) { + Integer low = timeline.lowerKey(end); + + if (low == null || timeline.get(low) <= start) { + timeline.put(start, end); + return true; + } + + return false; + } + + private TreeMap timeline = new TreeMap<>(); +} diff --git a/solutions/729. My Calendar I/729-3.py b/solutions/729. My Calendar I/729-3.py new file mode 100644 index 00000000000..ca92c8d1715 --- /dev/null +++ b/solutions/729. My Calendar I/729-3.py @@ -0,0 +1,40 @@ +class Node: + def __init__(self, start: int, end: int): + self.start = start + self.end = end + self.left = None + self.right = None + + +class Tree: + def __init__(self): + self.root = None + + def insert(self, node: Node, root: Node = None) -> bool: + if not root: + if not self.root: + self.root = node + return True + else: + root = self.root + + if node.start >= root.end: + if not root.right: + root.right = node + return True + return self.insert(node, root.right) + elif node.end <= root.start: + if not root.left: + root.left = node + return True + return self.insert(node, root.left) + else: + return False + + +class MyCalendar: + def __init__(self): + self.tree = Tree() + + def book(self, start: int, end: int) -> bool: + return self.tree.insert(Node(start, end)) diff --git a/solutions/729. My Calendar I/729.cpp b/solutions/729. My Calendar I/729.cpp new file mode 100644 index 00000000000..38096b7bcb9 --- /dev/null +++ b/solutions/729. My Calendar I/729.cpp @@ -0,0 +1,13 @@ +class MyCalendar { + public: + bool book(int start, int end) { + for (const auto& [s, e] : timeline) + if (max(start, s) < min(end, e)) + return false; + timeline.emplace_back(start, end); + return true; + } + + private: + vector> timeline; +}; diff --git a/solutions/729. My Calendar I/729.java b/solutions/729. My Calendar I/729.java new file mode 100644 index 00000000000..c27c88da53a --- /dev/null +++ b/solutions/729. My Calendar I/729.java @@ -0,0 +1,11 @@ +class MyCalendar { + public boolean book(int start, int end) { + for (int[] t : timeline) + if (Math.max(t[0], start) < Math.min(t[1], end)) + return false; + timeline.add(new int[] {start, end}); + return true; + } + + private List timeline = new ArrayList<>(); +} diff --git a/solutions/729. My Calendar I/729.py b/solutions/729. My Calendar I/729.py new file mode 100644 index 00000000000..323e79c2ced --- /dev/null +++ b/solutions/729. My Calendar I/729.py @@ -0,0 +1,10 @@ +class MyCalendar: + def __init__(self): + self.timeline = [] + + def book(self, start: int, end: int) -> bool: + for s, e in self.timeline: + if max(start, s) < min(end, e): + return False + self.timeline.append((start, end)) + return True diff --git a/solutions/73. Set Matrix Zeroes/73.cpp b/solutions/73. Set Matrix Zeroes/73.cpp new file mode 100644 index 00000000000..fbb1597fdb5 --- /dev/null +++ b/solutions/73. Set Matrix Zeroes/73.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + void setZeroes(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + bool shouldFillFirstRow = false; + bool shouldFillFirstCol = false; + + for (int j = 0; j < n; ++j) + if (matrix[0][j] == 0) { + shouldFillFirstRow = true; + break; + } + + for (int i = 0; i < m; ++i) + if (matrix[i][0] == 0) { + shouldFillFirstCol = true; + break; + } + + // Store the information in the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + + // Fill 0s for the matrix except the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][0] == 0 || matrix[0][j] == 0) + matrix[i][j] = 0; + + // Fill 0s for the first row if needed. + if (shouldFillFirstRow) + for (int j = 0; j < n; ++j) + matrix[0][j] = 0; + + // Fill 0s for the first column if needed. + if (shouldFillFirstCol) + for (int i = 0; i < m; ++i) + matrix[i][0] = 0; + } +}; diff --git a/solutions/73. Set Matrix Zeroes/73.java b/solutions/73. Set Matrix Zeroes/73.java new file mode 100644 index 00000000000..a0005dd1af9 --- /dev/null +++ b/solutions/73. Set Matrix Zeroes/73.java @@ -0,0 +1,44 @@ +class Solution { + public void setZeroes(int[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + boolean shouldFillFirstRow = false; + boolean shouldFillFirstCol = false; + + for (int j = 0; j < n; ++j) + if (matrix[0][j] == 0) { + shouldFillFirstRow = true; + break; + } + + for (int i = 0; i < m; ++i) + if (matrix[i][0] == 0) { + shouldFillFirstCol = true; + break; + } + + // Store the information in the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + + // Fill 0s for the matrix except the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][0] == 0 || matrix[0][j] == 0) + matrix[i][j] = 0; + + // Fill 0s for the first row if needed. + if (shouldFillFirstRow) + for (int j = 0; j < n; ++j) + matrix[0][j] = 0; + + // Fill 0s for the first column if needed. + if (shouldFillFirstCol) + for (int i = 0; i < m; ++i) + matrix[i][0] = 0; + } +} diff --git a/solutions/73. Set Matrix Zeroes/73.py b/solutions/73. Set Matrix Zeroes/73.py new file mode 100644 index 00000000000..1bee92672fe --- /dev/null +++ b/solutions/73. Set Matrix Zeroes/73.py @@ -0,0 +1,28 @@ +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + m = len(matrix) + n = len(matrix[0]) + shouldFillFirstRow = 0 in matrix[0] + shouldFillFirstCol = 0 in list(zip(*matrix))[0] + + # Store the information in the first row and the first column. + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] == 0: + matrix[i][0] = 0 + matrix[0][j] = 0 + + # Fill 0s for the matrix except the first row and the first column. + for i in range(1, m): + for j in range(1, n): + if matrix[i][0] == 0 or matrix[0][j] == 0: + matrix[i][j] = 0 + + # Fill 0s for the first row if needed. + if shouldFillFirstRow: + matrix[0] = [0] * n + + # Fill 0s for the first column if needed. + if shouldFillFirstCol: + for row in matrix: + row[0] = 0 diff --git a/solutions/730. Count Different Palindromic Subsequences/730.cpp b/solutions/730. Count Different Palindromic Subsequences/730.cpp new file mode 100644 index 00000000000..646fa8a497f --- /dev/null +++ b/solutions/730. Count Different Palindromic Subsequences/730.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int countPalindromicSubsequences(string s) { + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + // dp[i][j] := the number of different non-empty palindromic subsequences in + // s[i..j] + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + if (s[i] == s[j]) { + int lo = i + 1; + int hi = j - 1; + while (lo <= hi && s[lo] != s[i]) + ++lo; + while (lo <= hi && s[hi] != s[i]) + --hi; + if (lo > hi) + dp[i][j] = dp[i + 1][j - 1] * 2 + 2; + else if (lo == hi) + dp[i][j] = dp[i + 1][j - 1] * 2 + 1; + else + dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]; + } else { + dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; + } + dp[i][j] = (dp[i][j] + kMod) % kMod; + } + + return dp[0][n - 1]; + } +}; diff --git a/solutions/730. Count Different Palindromic Subsequences/730.java b/solutions/730. Count Different Palindromic Subsequences/730.java new file mode 100644 index 00000000000..286d25beb90 --- /dev/null +++ b/solutions/730. Count Different Palindromic Subsequences/730.java @@ -0,0 +1,36 @@ +class Solution { + public int countPalindromicSubsequences(String s) { + final int kMod = 1_000_000_007; + final int n = s.length(); + // dp[i][j] := the number of different non-empty palindromic subsequences in + // s[i..j] + int[][] dp = new int[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + if (s.charAt(i) == s.charAt(j)) { + int lo = i + 1; + int hi = j - 1; + while (lo <= hi && s.charAt(lo) != s.charAt(i)) + ++lo; + while (lo <= hi && s.charAt(hi) != s.charAt(i)) + --hi; + if (lo > hi) + dp[i][j] = dp[i + 1][j - 1] * 2 + 2; + else if (lo == hi) + dp[i][j] = dp[i + 1][j - 1] * 2 + 1; + else + dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]; + } else { + dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; + } + dp[i][j] = (int) ((dp[i][j] + kMod) % kMod); + } + + return dp[0][n - 1]; + } +} diff --git a/solutions/730. Count Different Palindromic Subsequences/730.py b/solutions/730. Count Different Palindromic Subsequences/730.py new file mode 100644 index 00000000000..d8bfcabe9b1 --- /dev/null +++ b/solutions/730. Count Different Palindromic Subsequences/730.py @@ -0,0 +1,32 @@ +class Solution: + def countPalindromicSubsequences(self, s: str) -> int: + kMod = 1_000_000_007 + n = len(s) + # dp[i][j] := the number of different non-empty palindromic subsequences in + # s[i..j] + dp = [[0] * n for _ in range(n)] + + for i in range(n): + dp[i][i] = 1 + + for d in range(1, n): + for i in range(n - d): + j = i + d + if s[i] == s[j]: + lo = i + 1 + hi = j - 1 + while lo <= hi and s[lo] != s[i]: + lo += 1 + while lo <= hi and s[hi] != s[i]: + hi -= 1 + if lo > hi: + dp[i][j] = dp[i + 1][j - 1] * 2 + 2 + elif lo == hi: + dp[i][j] = dp[i + 1][j - 1] * 2 + 1 + else: + dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1] + else: + dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + dp[i][j] = (dp[i][j] + kMod) % kMod + + return dp[0][n - 1] diff --git a/solutions/731. My Calendar II/731-2.cpp b/solutions/731. My Calendar II/731-2.cpp new file mode 100644 index 00000000000..5fa58e9fe12 --- /dev/null +++ b/solutions/731. My Calendar II/731-2.cpp @@ -0,0 +1,25 @@ +class MyCalendarTwo { + public: + bool book(int start, int end) { + ++timeline[start]; + --timeline[end]; + + int activeEvents = 0; + + for (const auto& [_, count] : timeline) { + activeEvents += count; + if (activeEvents > 2) { + if (--timeline[start] == 0) + timeline.erase(start); + if (++timeline[end] == 0) + timeline.erase(end); + return false; + } + } + + return true; + } + + private: + map timeline; +}; diff --git a/solutions/731. My Calendar II/731-2.java b/solutions/731. My Calendar II/731-2.java new file mode 100644 index 00000000000..607b47334d3 --- /dev/null +++ b/solutions/731. My Calendar II/731-2.java @@ -0,0 +1,23 @@ +class MyCalendarTwo { + public boolean book(int start, int end) { + timeline.merge(start, 1, Integer::sum); + timeline.merge(end, -1, Integer::sum); + + int activeEvents = 0; + + for (final int count : timeline.values()) { + activeEvents += count; + if (activeEvents > 2) { + if (timeline.merge(start, -1, Integer::sum) == 0) + timeline.remove(start); + if (timeline.merge(end, 1, Integer::sum) == 0) + timeline.remove(end); + return false; + } + } + + return true; + } + + private Map timeline = new TreeMap<>(); +} diff --git a/solutions/731. My Calendar II/731.cpp b/solutions/731. My Calendar II/731.cpp new file mode 100644 index 00000000000..1670f6efaa4 --- /dev/null +++ b/solutions/731. My Calendar II/731.cpp @@ -0,0 +1,22 @@ +class MyCalendarTwo { + public: + bool book(int start, int end) { + for (const auto& [s, e] : overlaps) + if (max(start, s) < min(end, e)) + return false; + + for (const auto& [s, e] : ranges) { + const int ss = max(start, s); + const int ee = min(end, e); + if (ss < ee) + overlaps.emplace_back(ss, ee); + } + + ranges.emplace_back(start, end); + return true; + } + + private: + vector> ranges; + vector> overlaps; +}; diff --git a/solutions/731. My Calendar II/731.java b/solutions/731. My Calendar II/731.java new file mode 100644 index 00000000000..c8e241f46e7 --- /dev/null +++ b/solutions/731. My Calendar II/731.java @@ -0,0 +1,20 @@ +class MyCalendarTwo { + public boolean book(int start, int end) { + for (int[] overlap : overlaps) + if (Math.max(start, overlap[0]) < Math.min(end, overlap[1])) + return false; + + for (int[] range : ranges) { + final int maxStart = Math.max(start, range[0]); + final int minEnd = Math.min(end, range[1]); + if (maxStart < minEnd) + overlaps.add(new int[] {maxStart, minEnd}); + } + + ranges.add(new int[] {start, end}); + return true; + } + + List ranges = new ArrayList<>(); + List overlaps = new ArrayList<>(); +} diff --git a/solutions/732. My Calendar III/732.cpp b/solutions/732. My Calendar III/732.cpp new file mode 100644 index 00000000000..dc5947c9f05 --- /dev/null +++ b/solutions/732. My Calendar III/732.cpp @@ -0,0 +1,20 @@ +class MyCalendarThree { + public: + int book(int start, int end) { + ++timeline[start]; + --timeline[end]; + + int ans = 0; + int activeEvents = 0; + + for (const auto& [_, count] : timeline) { + activeEvents += count; + ans = max(ans, activeEvents); + } + + return ans; + } + + private: + map timeline; +}; diff --git a/solutions/732. My Calendar III/732.java b/solutions/732. My Calendar III/732.java new file mode 100644 index 00000000000..8f6e1f791f5 --- /dev/null +++ b/solutions/732. My Calendar III/732.java @@ -0,0 +1,18 @@ +class MyCalendarThree { + public int book(int start, int end) { + timeline.merge(start, 1, Integer::sum); + timeline.merge(end, -1, Integer::sum); + + int ans = 0; + int activeEvents = 0; + + for (final int count : timeline.values()) { + activeEvents += count; + ans = Math.max(ans, activeEvents); + } + + return ans; + } + + private Map timeline = new TreeMap<>(); +} diff --git a/solutions/732. My Calendar III/732.py b/solutions/732. My Calendar III/732.py new file mode 100644 index 00000000000..a8abf17a10b --- /dev/null +++ b/solutions/732. My Calendar III/732.py @@ -0,0 +1,19 @@ +from sortedcontainers import SortedDict + + +class MyCalendarThree: + def __init__(self): + self.timeline = SortedDict() + + def book(self, start: int, end: int) -> int: + self.timeline[start] = self.timeline.get(start, 0) + 1 + self.timeline[end] = self.timeline.get(end, 0) - 1 + + ans = 0 + activeEvents = 0 + + for count in self.timeline.values(): + activeEvents += count + ans = max(ans, activeEvents) + + return ans diff --git a/solutions/733. Flood Fill/733.cpp b/solutions/733. Flood Fill/733.cpp new file mode 100644 index 00000000000..cacc17d7e09 --- /dev/null +++ b/solutions/733. Flood Fill/733.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector> floodFill(vector>& image, int sr, int sc, + int newColor) { + dfs(image, sr, sc, + vector>(image.size(), vector(image[0].size())), + image[sr][sc], newColor); + return image; + } + + private: + void dfs(vector>& image, int i, int j, + vector>&& seen, int startColor, int newColor) { + if (i < 0 || i == image.size() || j < 0 || j == image[0].size()) + return; + if (image[i][j] != startColor || seen[i][j]) + return; + + image[i][j] = newColor; + seen[i][j] = true; + + dfs(image, i + 1, j, move(seen), startColor, newColor); + dfs(image, i - 1, j, move(seen), startColor, newColor); + dfs(image, i, j + 1, move(seen), startColor, newColor); + dfs(image, i, j - 1, move(seen), startColor, newColor); + } +}; diff --git a/solutions/733. Flood Fill/733.java b/solutions/733. Flood Fill/733.java new file mode 100644 index 00000000000..17901fe03eb --- /dev/null +++ b/solutions/733. Flood Fill/733.java @@ -0,0 +1,22 @@ +class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { + boolean[][] seen = new boolean[image.length][image[0].length]; + dfs(image, sr, sc, seen, image[sr][sc], newColor); + return image; + } + + private void dfs(int[][] image, int i, int j, boolean[][] seen, int startColor, int newColor) { + if (i < 0 || i == image.length || j < 0 || j == image[0].length) + return; + if (image[i][j] != startColor || seen[i][j]) + return; + + image[i][j] = newColor; + seen[i][j] = true; + + dfs(image, i + 1, j, seen, startColor, newColor); + dfs(image, i - 1, j, seen, startColor, newColor); + dfs(image, i, j + 1, seen, startColor, newColor); + dfs(image, i, j - 1, seen, startColor, newColor); + } +} diff --git a/solutions/733. Flood Fill/733.py b/solutions/733. Flood Fill/733.py new file mode 100644 index 00000000000..2b4d7b4f9d6 --- /dev/null +++ b/solutions/733. Flood Fill/733.py @@ -0,0 +1,22 @@ +class Solution: + def floodFill(self, image: List[List[int]], + sr: int, sc: int, newColor: int) -> List[List[int]]: + startColor = image[sr][sc] + seen = set() + + def dfs(i: int, j: int) -> None: + if i < 0 or i == len(image) or j < 0 or j == len(image[0]): + return + if image[i][j] != startColor or (i, j) in seen: + return + + image[i][j] = newColor + seen.add((i, j)) + + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1) + + dfs(sr, sc) + return image diff --git a/solutions/734. Sentence Similarity/734.cpp b/solutions/734. Sentence Similarity/734.cpp new file mode 100644 index 00000000000..e40f6bccf10 --- /dev/null +++ b/solutions/734. Sentence Similarity/734.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + bool areSentencesSimilar(vector& sentence1, vector& sentence2, + vector>& similarPairs) { + if (sentence1.size() != sentence2.size()) + return false; + + // map[key] := all the similar words of key + unordered_map> map; + + for (const vector& pair : similarPairs) { + map[pair[1]].insert(pair[0]); + map[pair[0]].insert(pair[1]); + } + + for (int i = 0; i < sentence1.size(); ++i) { + if (sentence1[i] == sentence2[i]) + continue; + if (!map.contains(sentence1[i])) + return false; + if (!map[sentence1[i]].contains(sentence2[i])) + return false; + } + + return true; + } +}; diff --git a/solutions/734. Sentence Similarity/734.java b/solutions/734. Sentence Similarity/734.java new file mode 100644 index 00000000000..3e72b1c492d --- /dev/null +++ b/solutions/734. Sentence Similarity/734.java @@ -0,0 +1,28 @@ +class Solution { + public boolean areSentencesSimilar(String[] sentence1, String[] sentence2, + List> similarPairs) { + if (sentence1.length != sentence2.length) + return false; + + // map[key] := all the similar words of key + Map> map = new HashMap<>(); + + for (List pair : similarPairs) { + map.putIfAbsent(pair.get(0), new HashSet<>()); + map.putIfAbsent(pair.get(1), new HashSet<>()); + map.get(pair.get(1)).add(pair.get(0)); + map.get(pair.get(0)).add(pair.get(1)); + } + + for (int i = 0; i < sentence1.length; ++i) { + if (sentence1[i].equals(sentence2[i])) + continue; + if (!map.containsKey(sentence1[i])) + return false; + if (!map.get(sentence1[i]).contains(sentence2[i])) + return false; + } + + return true; + } +} diff --git a/solutions/734. Sentence Similarity/734.py b/solutions/734. Sentence Similarity/734.py new file mode 100644 index 00000000000..8750e5473a6 --- /dev/null +++ b/solutions/734. Sentence Similarity/734.py @@ -0,0 +1,21 @@ +class Solution: + def areSentencesSimilar(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool: + if len(sentence1) != len(sentence2): + return False + + # map[key] := all the similar words of key + map = collections.defaultdict(set) + + for a, b in similarPairs: + map[a].add(b) + map[b].add(a) + + for word1, word2 in zip(sentence1, sentence2): + if word1 == word2: + continue + if word1 not in map: + return False + if word2 not in map[word1]: + return False + + return True diff --git a/solutions/735. Asteroid Collision/735.cpp b/solutions/735. Asteroid Collision/735.cpp new file mode 100644 index 00000000000..d9143a32db7 --- /dev/null +++ b/solutions/735. Asteroid Collision/735.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector asteroidCollision(vector& asteroids) { + vector stack; + + for (const int a : asteroids) + if (a > 0) { + stack.push_back(a); + } else { // a < 0 + // Destroy the previous positive one(s). + while (!stack.empty() && stack.back() > 0 && stack.back() < -a) + stack.pop_back(); + if (stack.empty() || stack.back() < 0) + stack.push_back(a); + else if (stack.back() == -a) + stack.pop_back(); // Both asteroids explode. + else // stack[-1] > the current asteroid. + ; // Destroy the current asteroid, so do nothing. + } + + return stack; + } +}; diff --git a/solutions/735. Asteroid Collision/735.java b/solutions/735. Asteroid Collision/735.java new file mode 100644 index 00000000000..000659b3521 --- /dev/null +++ b/solutions/735. Asteroid Collision/735.java @@ -0,0 +1,22 @@ +class Solution { + public int[] asteroidCollision(int[] asteroids) { + Stack stack = new Stack<>(); + + for (final int a : asteroids) + if (a > 0) { + stack.push(a); + } else { // a < 0 + // Destroy the previous positive one(s). + while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -a) + stack.pop(); + if (stack.isEmpty() || stack.peek() < 0) + stack.push(a); + else if (stack.peek() == -a) + stack.pop(); // Both asteroids explode. + else // stack[-1] > the current asteroid. + ; // Destroy the current asteroid, so do nothing. + } + + return stack.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/solutions/735. Asteroid Collision/735.py b/solutions/735. Asteroid Collision/735.py new file mode 100644 index 00000000000..f56e17837f1 --- /dev/null +++ b/solutions/735. Asteroid Collision/735.py @@ -0,0 +1,19 @@ +class Solution: + def asteroidCollision(self, asteroids: List[int]) -> List[int]: + stack = [] + + for a in asteroids: + if a > 0: + stack.append(a) + else: # a < 0 + # Destroy the previous positive one(s). + while stack and stack[-1] > 0 and stack[-1] < -a: + stack.pop() + if not stack or stack[-1] < 0: + stack.append(a) + elif stack[-1] == -a: + stack.pop() # Both asteroids explode. + else: # stack[-1] > the current asteroid. + pass # Destroy the current asteroid, so do nothing. + + return stack diff --git a/solutions/736. Parse Lisp Expression/736.cpp b/solutions/736. Parse Lisp Expression/736.cpp new file mode 100644 index 00000000000..49e9cb95a4f --- /dev/null +++ b/solutions/736. Parse Lisp Expression/736.cpp @@ -0,0 +1,53 @@ +class Solution { + public: + int evaluate(string expression) { + return evaluate(expression, unordered_map()); + } + + private: + int evaluate(const string& e, unordered_map scope) { + if (isdigit(e[0]) || e[0] == '-') + return stoi(e); + if (const auto it = scope.find(e); it != scope.cend()) + return it->second; + + const int spaceIndex = e.find_first_of(' '); + const string nextExpression = + e.substr(spaceIndex + 1, e.length() - spaceIndex - 2); // -2: "()" + const vector tokens = split(nextExpression); + + // Note that e[0] == '('. + if (e[1] == 'm') // 'mult' + return evaluate(tokens[0], scope) * evaluate(tokens[1], scope); + if (e[1] == 'a') // 'add' + return evaluate(tokens[0], scope) + evaluate(tokens[1], scope); + + // 'let' + for (int i = 0; i + 1 < tokens.size(); i += 2) + scope[tokens[i]] = evaluate(tokens[i + 1], scope); + return evaluate(tokens.back(), scope); + }; + + vector split(const string& e) { + vector tokens; + string s; + int opened = 0; + + for (const char c : e) { + if (c == '(') + ++opened; + else if (c == ')') + --opened; + if (opened == 0 && c == ' ') { + tokens.push_back(s); + s = ""; + } else { + s += c; + } + } + + if (!s.empty()) + tokens.push_back(s); + return tokens; + } +}; diff --git a/solutions/736. Parse Lisp Expression/736.java b/solutions/736. Parse Lisp Expression/736.java new file mode 100644 index 00000000000..639df32e203 --- /dev/null +++ b/solutions/736. Parse Lisp Expression/736.java @@ -0,0 +1,53 @@ +class Solution { + public int evaluate(String expression) { + return evaluate(expression, new HashMap<>()); + } + + private int evaluate(final String e, Map prevScope) { + if (Character.isDigit(e.charAt(0)) || e.charAt(0) == '-') + return Integer.parseInt(e); + if (prevScope.containsKey(e)) + return prevScope.get(e); + + Map scope = new HashMap<>(); + scope.putAll(prevScope); + + final int spaceIndex = e.indexOf(' '); + // +1 and -1 because of "()". + final String nextExpression = e.substring(spaceIndex + 1, e.length() - 1); + List tokens = split(nextExpression); + + if (e.startsWith("(m")) // 'mult' + return evaluate(tokens.get(0), scope) * evaluate(tokens.get(1), scope); + if (e.startsWith("(a")) // 'add' + return evaluate(tokens.get(0), scope) + evaluate(tokens.get(1), scope); + + // 'let' + for (int i = 0; i < tokens.size() - 2; i += 2) + scope.put(tokens.get(i), evaluate(tokens.get(i + 1), scope)); + return evaluate(tokens.get(tokens.size() - 1), scope); + } + + private List split(final String s) { + List tokens = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + int opened = 0; + + for (char c : s.toCharArray()) { + if (c == '(') + ++opened; + else if (c == ')') + --opened; + if (opened == 0 && c == ' ') { + tokens.add(sb.toString()); + sb.setLength(0); + } else { + sb.append(c); + } + } + + if (sb.length() > 0) + tokens.add(sb.toString()); + return tokens; + } +} diff --git a/solutions/736. Parse Lisp Expression/736.py b/solutions/736. Parse Lisp Expression/736.py new file mode 100644 index 00000000000..8ba09a15316 --- /dev/null +++ b/solutions/736. Parse Lisp Expression/736.py @@ -0,0 +1,44 @@ +class Solution: + def evaluate(self, expression: str) -> int: + def evaluate(e: str, prevScope: dict) -> int: + if e[0].isdigit() or e[0] == '-': + return int(e) + if e in prevScope: + return prevScope[e] + + scope = prevScope.copy() + nextExpression = e[e.index(' ') + 1:-1] + tokens = parse(nextExpression) + + if e[1] == 'm': # 'mult' + return evaluate(tokens[0], scope) * evaluate(tokens[1], scope) + if e[1] == 'a': # 'add' + return evaluate(tokens[0], scope) + evaluate(tokens[1], scope) + + # 'let' + for i in range(0, len(tokens) - 2, 2): + scope[tokens[i]] = evaluate(tokens[i + 1], scope) + + return evaluate(tokens[-1], scope) + + def parse(e: str): + tokens = [] + s = '' + opened = 0 + + for c in e: + if c == '(': + opened += 1 + elif c == ')': + opened -= 1 + if opened == 0 and c == ' ': + tokens.append(s) + s = '' + else: + s += c + + if len(s) > 0: + tokens.append(s) + return tokens + + return evaluate(expression, {}) diff --git a/solutions/737. Sentence Similarity II/737.cpp b/solutions/737. Sentence Similarity II/737.cpp new file mode 100644 index 00000000000..8eb20d0fd1a --- /dev/null +++ b/solutions/737. Sentence Similarity II/737.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + bool areSentencesSimilarTwo(vector& words1, vector& words2, + vector>& pairs) { + if (words1.size() != words2.size()) + return false; + + // graph[key] := all the similar words of key + unordered_map> graph; + + for (const vector& pair : pairs) { + graph[pair[1]].insert(pair[0]); + graph[pair[0]].insert(pair[1]); + } + + for (int i = 0; i < words1.size(); ++i) { + if (words1[i] == words2[i]) + continue; + if (!graph.contains(words1[i])) + return false; + if (!dfs(graph, words1[i], words2[i], {})) + return false; + } + + return true; + } + + private: + bool dfs(const unordered_map>& graph, + const string& source, const string& target, + unordered_set&& seen) { + if (graph.at(source).contains(target)) + return true; + + seen.insert(source); + + for (const string& child : graph.at(source)) { + if (seen.contains(child)) + continue; + if (dfs(graph, child, target, move(seen))) + return true; + } + + return false; + } +}; diff --git a/solutions/737. Sentence Similarity II/737.java b/solutions/737. Sentence Similarity II/737.java new file mode 100644 index 00000000000..a7a678e4019 --- /dev/null +++ b/solutions/737. Sentence Similarity II/737.java @@ -0,0 +1,45 @@ +class Solution { + public boolean areSentencesSimilarTwo(String[] words1, String[] words2, + List> pairs) { + if (words1.length != words2.length) + return false; + + // graph[key] := all the similar words of key + Map> graph = new HashMap<>(); + + for (List pair : pairs) { + graph.putIfAbsent(pair.get(0), new HashSet<>()); + graph.putIfAbsent(pair.get(1), new HashSet<>()); + graph.get(pair.get(1)).add(pair.get(0)); + graph.get(pair.get(0)).add(pair.get(1)); + } + + for (int i = 0; i < words1.length; ++i) { + if (words1[i].equals(words2[i])) + continue; + if (!graph.containsKey(words1[i])) + return false; + if (!dfs(graph, words1[i], words2[i], new HashSet<>())) + return false; + } + + return true; + } + + private boolean dfs(Map> graph, final String source, final String target, + Set seen) { + if (graph.get(source).contains(target)) + return true; + + seen.add(source); + + for (final String child : graph.get(source)) { + if (seen.contains(child)) + continue; + if (dfs(graph, child, target, seen)) + return true; + } + + return false; + } +} diff --git a/solutions/737. Sentence Similarity II/737.py b/solutions/737. Sentence Similarity II/737.py new file mode 100644 index 00000000000..25d20214f5a --- /dev/null +++ b/solutions/737. Sentence Similarity II/737.py @@ -0,0 +1,35 @@ +class Solution: + def areSentencesSimilarTwo(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool: + if len(words1) != len(words2): + return False + + # graph[key] := all the similar words of key + graph = collections.defaultdict(set) + + for a, b in pairs: + graph[a].add(b) + graph[b].add(a) + + def dfs(word1: str, word2: str, seen: set) -> bool: + if word1 in graph[word2]: + return True + + seen.add(word1) + + for child in graph[word1]: + if child in seen: + continue + if dfs(child, word2, seen): + return True + + return False + + for word1, word2 in zip(words1, words2): + if word1 == word2: + continue + if word1 not in graph: + return False + if not dfs(word1, word2, set()): + return False + + return True diff --git a/solutions/738. Monotone Increasing Digits/738.cpp b/solutions/738. Monotone Increasing Digits/738.cpp new file mode 100644 index 00000000000..ad32b8ecd18 --- /dev/null +++ b/solutions/738. Monotone Increasing Digits/738.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int monotoneIncreasingDigits(int n) { + string s = to_string(n); + const int n = s.length(); + int k = n; // s[k..n) -> '9' + + for (int i = n - 1; i > 0; --i) + if (s[i] < s[i - 1]) { + --s[i - 1]; + k = i; + } + + for (int i = k; i < n; ++i) + s[i] = '9'; + + return stoi(s); + } +}; diff --git a/solutions/738. Monotone Increasing Digits/738.java b/solutions/738. Monotone Increasing Digits/738.java new file mode 100644 index 00000000000..171b74217ff --- /dev/null +++ b/solutions/738. Monotone Increasing Digits/738.java @@ -0,0 +1,18 @@ +class Solution { + public int monotoneIncreasingDigits(int n) { + char[] s = String.valueOf(n).toCharArray(); + final int n = s.length; + int k = n; // s[k..n) -> '9' + + for (int i = n - 1; i > 0; --i) + if (s[i] < s[i - 1]) { + --s[i - 1]; + k = i; + } + + for (int i = k; i < n; ++i) + s[i] = '9'; + + return Integer.parseInt(new String(s)); + } +} diff --git a/solutions/739. Daily Temperatures/739.cpp b/solutions/739. Daily Temperatures/739.cpp new file mode 100644 index 00000000000..53a53ec4179 --- /dev/null +++ b/solutions/739. Daily Temperatures/739.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector dailyTemperatures(vector& temperatures) { + vector ans(temperatures.size()); + stack stack; // a decreasing stack + + for (int i = 0; i < temperatures.size(); ++i) { + while (!stack.empty() && temperatures[stack.top()] < temperatures[i]) { + const int index = stack.top(); + stack.pop(); + ans[index] = i - index; + } + stack.push(i); + } + + return ans; + } +}; diff --git a/solutions/739. Daily Temperatures/739.java b/solutions/739. Daily Temperatures/739.java new file mode 100644 index 00000000000..a20456bf96f --- /dev/null +++ b/solutions/739. Daily Temperatures/739.java @@ -0,0 +1,16 @@ +class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int[] ans = new int[temperatures.length]; + Deque stack = new ArrayDeque<>(); // a decreasing stack + + for (int i = 0; i < temperatures.length; ++i) { + while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) { + final int index = stack.pop(); + ans[index] = i - index; + } + stack.push(i); + } + + return ans; + } +} diff --git a/solutions/739. Daily Temperatures/739.py b/solutions/739. Daily Temperatures/739.py new file mode 100644 index 00000000000..dfda41c622f --- /dev/null +++ b/solutions/739. Daily Temperatures/739.py @@ -0,0 +1,12 @@ +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + ans = [0] * len(temperatures) + stack = [] # a decreasing stack + + for i, temperature in enumerate(temperatures): + while stack and temperature > temperatures[stack[-1]]: + index = stack.pop() + ans[index] = i - index + stack.append(i) + + return ans diff --git a/solutions/74. Search a 2D Matrix/74.cpp b/solutions/74. Search a 2D Matrix/74.cpp new file mode 100644 index 00000000000..564423d4f7d --- /dev/null +++ b/solutions/74. Search a 2D Matrix/74.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + bool searchMatrix(vector>& matrix, int target) { + if (matrix.empty()) + return false; + + const int m = matrix.size(); + const int n = matrix[0].size(); + int l = 0; + int r = m * n; + + while (l < r) { + const int mid = (l + r) / 2; + const int i = mid / n; + const int j = mid % n; + if (matrix[i][j] == target) + return true; + if (matrix[i][j] < target) + l = mid + 1; + else + r = mid; + } + + return false; + } +}; diff --git a/solutions/74. Search a 2D Matrix/74.java b/solutions/74. Search a 2D Matrix/74.java new file mode 100644 index 00000000000..9f95496c390 --- /dev/null +++ b/solutions/74. Search a 2D Matrix/74.java @@ -0,0 +1,25 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + if (matrix.length == 0) + return false; + + final int m = matrix.length; + final int n = matrix[0].length; + int l = 0; + int r = m * n; + + while (l < r) { + final int mid = (l + r) / 2; + final int i = mid / n; + final int j = mid % n; + if (matrix[i][j] == target) + return true; + if (matrix[i][j] < target) + l = mid + 1; + else + r = mid; + } + + return false; + } +} diff --git a/solutions/74. Search a 2D Matrix/74.py b/solutions/74. Search a 2D Matrix/74.py new file mode 100644 index 00000000000..80a6fabcd1e --- /dev/null +++ b/solutions/74. Search a 2D Matrix/74.py @@ -0,0 +1,22 @@ +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + if not matrix: + return False + + m = len(matrix) + n = len(matrix[0]) + l = 0 + r = m * n + + while l < r: + mid = (l + r) // 2 + i = mid // n + j = mid % n + if matrix[i][j] == target: + return True + if matrix[i][j] < target: + l = mid + 1 + else: + r = mid + + return False diff --git a/solutions/740. Delete and Earn/740.cpp b/solutions/740. Delete and Earn/740.cpp new file mode 100644 index 00000000000..f5d579946f0 --- /dev/null +++ b/solutions/740. Delete and Earn/740.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int deleteAndEarn(vector& nums) { + // Reduce to 198. House Robber + vector bucket(10001); + + for (const int num : nums) + bucket[num] += num; + + int prev1 = 0; + int prev2 = 0; + + for (const int num : bucket) { + const int dp = max(prev1, prev2 + num); + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } +}; diff --git a/solutions/740. Delete and Earn/740.java b/solutions/740. Delete and Earn/740.java new file mode 100644 index 00000000000..b0faef9a7d7 --- /dev/null +++ b/solutions/740. Delete and Earn/740.java @@ -0,0 +1,20 @@ +class Solution { + public int deleteAndEarn(int[] nums) { + // Reduce to 198. House Robber + int[] bucket = new int[10001]; + + for (final int num : nums) + bucket[num] += num; + + int prev1 = 0; + int prev2 = 0; + + for (final int num : bucket) { + final int dp = Math.max(prev1, prev2 + num); + prev2 = prev1; + prev1 = dp; + } + + return prev1; + } +} diff --git a/solutions/741. Cherry Pickup/741-2.cpp b/solutions/741. Cherry Pickup/741-2.cpp new file mode 100644 index 00000000000..f408e7258f6 --- /dev/null +++ b/solutions/741. Cherry Pickup/741-2.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int cherryPickup(vector>& grid) { + const int n = grid.size(); + // dp[x1][y1][x2] := the maximum cherries we could pick from + // g[0][0] -> g[x1 - 1][y1 - 1] + g[0][0] -> g[x2 - 1][y2 - 1], + // where y2 = x1 + y1 - x2 (reducing states from 4 to 3) + vector>> dp( + n + 1, vector>(n + 1, vector(n + 1, -1))); + dp[1][1][1] = grid[0][0]; + + for (int x1 = 1; x1 <= n; ++x1) + for (int y1 = 1; y1 <= n; ++y1) + for (int x2 = 1; x2 <= n; ++x2) { + const int y2 = x1 + y1 - x2; + if (y2 < 1 || y2 > n) + continue; + if (grid[x1 - 1][y1 - 1] == -1 || grid[x2 - 1][y2 - 1] == -1) + continue; + const int ans = max({dp[x1 - 1][y1][x2], dp[x1 - 1][y1][x2 - 1], + dp[x1][y1 - 1][x2], dp[x1][y1 - 1][x2 - 1]}); + if (ans < 0) + continue; + dp[x1][y1][x2] = ans + grid[x1 - 1][y1 - 1]; + if (x1 != x2) + dp[x1][y1][x2] += grid[x2 - 1][y2 - 1]; + } + + return max(0, dp[n][n][n]); + } +}; diff --git a/solutions/741. Cherry Pickup/741-2.java b/solutions/741. Cherry Pickup/741-2.java new file mode 100644 index 00000000000..33b955477e7 --- /dev/null +++ b/solutions/741. Cherry Pickup/741-2.java @@ -0,0 +1,32 @@ +class Solution { + public int cherryPickup(int[][] grid) { + final int n = grid.length; + + // dp[x1][y1][x2] := the maximum cherries we could pick from + // g[0][0] -> g[x1 - 1][y1 - 1] + g[0][0] -> g[x2 - 1][y2 - 1], + // where y2 = x1 + y1 - x2 (reducing states from 4 to 3) + int[][][] dp = new int[n + 1][n + 1][n + 1]; + for (int[][] A : dp) + Arrays.stream(A).forEach(a -> Arrays.fill(a, -1)); + dp[1][1][1] = grid[0][0]; + + for (int x1 = 1; x1 <= n; ++x1) + for (int y1 = 1; y1 <= n; ++y1) + for (int x2 = 1; x2 <= n; ++x2) { + final int y2 = x1 + y1 - x2; + if (y2 < 1 || y2 > n) + continue; + if (grid[x1 - 1][y1 - 1] == -1 || grid[x2 - 1][y2 - 1] == -1) + continue; + final int ans = Math.max(Math.max(dp[x1 - 1][y1][x2], dp[x1 - 1][y1][x2 - 1]), + Math.max(dp[x1][y1 - 1][x2], dp[x1][y1 - 1][x2 - 1])); + if (ans < 0) + continue; + dp[x1][y1][x2] = ans + grid[x1 - 1][y1 - 1]; + if (x1 != x2) + dp[x1][y1][x2] += grid[x2 - 1][y2 - 1]; + } + + return Math.max(0, dp[n][n][n]); + } +} diff --git a/solutions/741. Cherry Pickup/741.cpp b/solutions/741. Cherry Pickup/741.cpp new file mode 100644 index 00000000000..34d4d17d54a --- /dev/null +++ b/solutions/741. Cherry Pickup/741.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int cherryPickup(vector>& grid) { + // The problem is identical as two people start picking cherries from + // grid[0][0] simultaneously. + const int n = grid.size(); + vector>> mem( + n + 1, vector>(n + 1, vector(n + 1, INT_MIN))); + return max(0, cherryPickup(grid, 0, 0, 0, mem)); + } + + private: + // Returns the maximum cherries we could pick from g[0][0] -> + // g[x1 - 1][y1 - 1] + g[0][0] -> g[x2 - 1][y2 - 1], where y2 = x1 + y1 - x2 + // (reducing states from 4 to 3). + int cherryPickup(const vector>& grid, int x1, int y1, int x2, + vector>>& mem) { + const int n = grid.size(); + const int y2 = x1 + y1 - x2; + if (x1 == n || y1 == n || x2 == n || y2 == n) + return -1; + if (x1 == n - 1 && y1 == n - 1) + return grid[x1][y1]; + if (grid[x1][y1] == -1 || grid[x2][y2] == -1) + return -1; + int& res = mem[x1][y1][x2]; + if (mem[x1][y1][x2] > INT_MIN) + return res; + + res = max({cherryPickup(grid, x1 + 1, y1, x2, mem), + cherryPickup(grid, x1 + 1, y1, x2 + 1, mem), + cherryPickup(grid, x1, y1 + 1, x2, mem), + cherryPickup(grid, x1, y1 + 1, x2 + 1, mem)}); + if (res == -1) + return res; + + res += grid[x1][y1]; // Pick some cherries. + if (x1 != x2) // Two people are on the different grids. + res += grid[x2][y2]; + + return res; + } +}; diff --git a/solutions/741. Cherry Pickup/741.java b/solutions/741. Cherry Pickup/741.java new file mode 100644 index 00000000000..2d79528d0f8 --- /dev/null +++ b/solutions/741. Cherry Pickup/741.java @@ -0,0 +1,39 @@ +class Solution { + public int cherryPickup(int[][] grid) { + // The problem is identical as two people start picking cherries from + // grid[0][0] simultaneously. + final int n = grid.length; + Integer[][][] mem = new Integer[n][n][n]; + return Math.max(0, cherryPickup(grid, 0, 0, 0, mem)); + } + + // Returns the maximum cherries we could pick from g[0][0] -> + // g[x1 - 1][y1 - 1] + g[0][0] -> g[x2 - 1][y2 - 1], where y2 = x1 + y1 - x2 + // (reducing states from 4 to 3). + private int cherryPickup(int[][] grid, int x1, int y1, int x2, Integer[][][] mem) { + final int n = grid.length; + final int y2 = x1 + y1 - x2; + if (x1 == n || y1 == n || x2 == n || y2 == n) + return -1; + if (x1 == n - 1 && y1 == n - 1) + return grid[x1][y1]; + if (grid[x1][y1] == -1 || grid[x2][y2] == -1) + return -1; + Integer res = mem[x1][y1][x2]; + if (res != null) + return res; + + res = Math.max(Math.max(cherryPickup(grid, x1 + 1, y1, x2, mem), // + cherryPickup(grid, x1 + 1, y1, x2 + 1, mem)), + Math.max(cherryPickup(grid, x1, y1 + 1, x2, mem), // + cherryPickup(grid, x1, y1 + 1, x2 + 1, mem))); + if (res == -1) + return mem[x1][y1][x2] = res; + + res += grid[x1][y1]; // Pick some cherries. + if (x1 != x2) // Two people are on the different grids. + res += grid[x2][y2]; + + return mem[x1][y1][x2] = res; + } +} diff --git a/solutions/742. Closest Leaf in a Binary Tree/742.cpp b/solutions/742. Closest Leaf in a Binary Tree/742.cpp new file mode 100644 index 00000000000..e9861cf89a8 --- /dev/null +++ b/solutions/742. Closest Leaf in a Binary Tree/742.cpp @@ -0,0 +1,56 @@ +class Solution { + public: + int findClosestLeaf(TreeNode* root, int k) { + int ans = -1; + int minDist = 1000; + // {node: distance to TreeNode(k)} + unordered_map nodeToDist; + + getDists(root, k, nodeToDist); + getClosestLeaf(root, 0, nodeToDist, minDist, ans); + + return ans; + } + + private: + void getDists(TreeNode* root, int k, + unordered_map& nodeToDist) { + if (root == nullptr) + return; + if (root->val == k) { + nodeToDist[root] = 0; + return; + } + + getDists(root->left, k, nodeToDist); + if (const auto it = nodeToDist.find(root->left); it != nodeToDist.cend()) { + // The TreeNode(k) is in the left subtree. + nodeToDist[root] = it->second + 1; + return; + } + + getDists(root->right, k, nodeToDist); + if (const auto it = nodeToDist.find(root->right); it != nodeToDist.cend()) + // The TreeNode(k) is in the right subtree. + nodeToDist[root] = it->second + 1; + } + + void getClosestLeaf(TreeNode* root, int dist, + unordered_map& nodeToDist, int& minDist, + int& ans) { + if (root == nullptr) + return; + if (nodeToDist.contains(root)) + dist = nodeToDist[root]; + if (root->left == nullptr && root->right == nullptr) { + if (dist < minDist) { + minDist = dist; + ans = root->val; + } + return; + } + + getClosestLeaf(root->left, dist + 1, nodeToDist, minDist, ans); + getClosestLeaf(root->right, dist + 1, nodeToDist, minDist, ans); + } +}; diff --git a/solutions/742. Closest Leaf in a Binary Tree/742.java b/solutions/742. Closest Leaf in a Binary Tree/742.java new file mode 100644 index 00000000000..8695f72fd64 --- /dev/null +++ b/solutions/742. Closest Leaf in a Binary Tree/742.java @@ -0,0 +1,54 @@ +class Solution { + public int findClosestLeaf(TreeNode root, int k) { + ans = -1; + minDist = 1000; + // {node: distance to TreeNode(k)} + Map nodeToDist = new HashMap<>(); + + getDists(root, k, nodeToDist); + getClosestLeaf(root, 0, nodeToDist); + + return ans; + } + + private int ans; + private int minDist; + + private void getDists(TreeNode root, int k, Map nodeToDist) { + if (root == null) + return; + if (root.val == k) { + nodeToDist.put(root, 0); + return; + } + + getDists(root.left, k, nodeToDist); + if (nodeToDist.containsKey(root.left)) { + // The TreeNode(k) is in the left subtree. + nodeToDist.put(root, nodeToDist.get(root.left) + 1); + return; + } + + getDists(root.right, k, nodeToDist); + if (nodeToDist.containsKey(root.right)) + // The TreeNode(k) is in the right subtree. + nodeToDist.put(root, nodeToDist.get(root.right) + 1); + } + + private void getClosestLeaf(TreeNode root, int dist, Map nodeToDist) { + if (root == null) + return; + if (nodeToDist.containsKey(root)) + dist = nodeToDist.get(root); + if (root.left == null && root.right == null) { + if (dist < minDist) { + minDist = dist; + ans = root.val; + } + return; + } + + getClosestLeaf(root.left, dist + 1, nodeToDist); + getClosestLeaf(root.right, dist + 1, nodeToDist); + } +} diff --git a/solutions/743. Network Delay Time/743.cpp b/solutions/743. Network Delay Time/743.cpp new file mode 100644 index 00000000000..bfde2e4bb3d --- /dev/null +++ b/solutions/743. Network Delay Time/743.cpp @@ -0,0 +1,40 @@ +class Solution { + public: + int networkDelayTime(vector>& times, int n, int k) { + vector>> graph(n); + + for (const vector& time : times) { + const int u = time[0] - 1; + const int v = time[1] - 1; + const int w = time[2]; + graph[u].emplace_back(v, w); + } + + return dijkstra(graph, k - 1); + } + + private: + int dijkstra(const vector>>& graph, int src) { + vector dist(graph.size(), INT_MAX); + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.emplace(dist[v], v); + } + } + + const int maxDist = ranges::max(dist); + return maxDist == INT_MAX ? -1 : maxDist; + } +}; diff --git a/solutions/743. Network Delay Time/743.java b/solutions/743. Network Delay Time/743.java new file mode 100644 index 00000000000..6818756a1f7 --- /dev/null +++ b/solutions/743. Network Delay Time/743.java @@ -0,0 +1,45 @@ +class Solution { + public int networkDelayTime(int[][] times, int n, int k) { + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] time : times) { + final int u = time[0] - 1; + final int v = time[1] - 1; + final int w = time[2]; + graph[u].add(new Pair<>(v, w)); + } + + return dijkstra(graph, k - 1); + } + + private int dijkstra(List>[] graph, int src) { + int[] dist = new int[graph.length]; + Arrays.fill(dist, Integer.MAX_VALUE); + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v]) { + dist[v] = d + w; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + final int maxDist = Arrays.stream(dist).max().getAsInt(); + return maxDist == Integer.MAX_VALUE ? -1 : maxDist; + } +} diff --git a/solutions/743. Network Delay Time/743.py b/solutions/743. Network Delay Time/743.py new file mode 100644 index 00000000000..f21b26aa479 --- /dev/null +++ b/solutions/743. Network Delay Time/743.py @@ -0,0 +1,26 @@ +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + graph = [[] for _ in range(n)] + + for u, v, w in times: + graph[u - 1].append((v - 1, w)) + + return self._dijkstra(graph, k - 1) + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> int: + dist = [math.inf] * len(graph) + + dist[src] = 0 + minHeap = [(dist[src], src)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + if d > dist[u]: + continue + for v, w in graph[u]: + if d + w < dist[v]: + dist[v] = d + w + heapq.heappush(minHeap, (dist[v], v)) + + maxDist = max(dist) + return maxDist if maxDist != math.inf else -1 diff --git a/solutions/744. Find Smallest Letter Greater Than Target/744.cpp b/solutions/744. Find Smallest Letter Greater Than Target/744.cpp new file mode 100644 index 00000000000..2cd4ffc91ec --- /dev/null +++ b/solutions/744. Find Smallest Letter Greater Than Target/744.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + char nextGreatestLetter(vector& letters, char target) { + int l = 0; + int r = letters.size(); + + while (l < r) { + const int m = (l + r) / 2; + if (letters[m] > target) + r = m; + else + l = m + 1; + } + + return letters[l % letters.size()]; + } +}; diff --git a/solutions/744. Find Smallest Letter Greater Than Target/744.java b/solutions/744. Find Smallest Letter Greater Than Target/744.java new file mode 100644 index 00000000000..5564eab4109 --- /dev/null +++ b/solutions/744. Find Smallest Letter Greater Than Target/744.java @@ -0,0 +1,16 @@ +class Solution { + public char nextGreatestLetter(char[] letters, char target) { + int l = 0; + int r = letters.length; + + while (l < r) { + final int m = (l + r) / 2; + if (letters[m] > target) + r = m; + else + l = m + 1; + } + + return letters[l % letters.length]; + } +} diff --git a/solutions/744. Find Smallest Letter Greater Than Target/744.py b/solutions/744. Find Smallest Letter Greater Than Target/744.py new file mode 100644 index 00000000000..06fb1e94a56 --- /dev/null +++ b/solutions/744. Find Smallest Letter Greater Than Target/744.py @@ -0,0 +1,5 @@ +class Solution: + def nextGreatestLetter(self, letters: List[str], target: str) -> str: + l = bisect.bisect_right(range(len(letters)), target, + key=lambda m: letters[m]) + return letters[l % len(letters)] diff --git a/solutions/745. Prefix and Suffix Search/745-2.cpp b/solutions/745. Prefix and Suffix Search/745-2.cpp new file mode 100644 index 00000000000..d57e9b43228 --- /dev/null +++ b/solutions/745. Prefix and Suffix Search/745-2.cpp @@ -0,0 +1,49 @@ +struct TrieNode { + vector> children; + int weight = -1; + TrieNode() : children(27) {} +}; + +class Trie { + public: + void insert(const string& word, int weight) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + node->weight = weight; + } + } + + int startsWith(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + return -1; + node = node->children[i]; + } + return node->weight; + } + + private: + shared_ptr root = make_shared(); +}; + +class WordFilter { + public: + WordFilter(vector& words) { + for (int i = 0; i < words.size(); ++i) + for (int j = 0; j <= words[i].length(); ++j) + trie.insert(words[i].substr(j) + '{' + words[i], i); + } + + int f(string prefix, string suffix) { + return trie.startsWith(suffix + '{' + prefix); + } + + private: + Trie trie; +}; diff --git a/solutions/745. Prefix and Suffix Search/745.cpp b/solutions/745. Prefix and Suffix Search/745.cpp new file mode 100644 index 00000000000..acc46193831 --- /dev/null +++ b/solutions/745. Prefix and Suffix Search/745.cpp @@ -0,0 +1,29 @@ +class WordFilter { + public: + WordFilter(vector& words) { + for (int i = 0; i < words.size(); ++i) { + const string& word = words[i]; + vector prefixes; + vector suffixes; + for (int j = 0; j <= word.length(); ++j) { + const string prefix = word.substr(0, j); + const string suffix = word.substr(j); + prefixes.push_back(prefix); + suffixes.push_back(suffix); + } + for (const string& prefix : prefixes) + for (const string& suffix : suffixes) + keyToIndex[prefix + '_' + suffix] = i; + } + } + + int f(string prefix, string suffix) { + const string key = prefix + '_' + suffix; + if (const auto it = keyToIndex.find(key); it != keyToIndex.cend()) + return it->second; + return -1; + } + + private: + unordered_map keyToIndex; +}; diff --git a/solutions/745. Prefix and Suffix Search/745.java b/solutions/745. Prefix and Suffix Search/745.java new file mode 100644 index 00000000000..bfc6107e9fc --- /dev/null +++ b/solutions/745. Prefix and Suffix Search/745.java @@ -0,0 +1,27 @@ +class WordFilter { + public WordFilter(String[] words) { + for (int i = 0; i < words.length; ++i) { + final String word = words[i]; + List prefixes = new ArrayList<>(); + List suffixes = new ArrayList<>(); + for (int j = 0; j <= word.length(); ++j) { + final String prefix = word.substring(0, j); + final String suffix = word.substring(j); + prefixes.add(prefix); + suffixes.add(suffix); + } + for (final String prefix : prefixes) + for (final String suffix : suffixes) + keyToIndex.put(prefix + '_' + suffix, i); + } + } + + public int f(String prefix, String suffix) { + final String key = prefix + '_' + suffix; + if (keyToIndex.containsKey(key)) + return keyToIndex.get(key); + return -1; + } + + private Map keyToIndex = new HashMap<>(); +} diff --git a/solutions/746. Min Cost Climbing Stairs/746.cpp b/solutions/746. Min Cost Climbing Stairs/746.cpp new file mode 100644 index 00000000000..0e9e67c5e84 --- /dev/null +++ b/solutions/746. Min Cost Climbing Stairs/746.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + int minCostClimbingStairs(vector& cost) { + const int n = cost.size(); + + for (int i = 2; i < n; ++i) + cost[i] += min(cost[i - 1], cost[i - 2]); + + return min(cost[n - 1], cost[n - 2]); + } +}; diff --git a/solutions/746. Min Cost Climbing Stairs/746.java b/solutions/746. Min Cost Climbing Stairs/746.java new file mode 100644 index 00000000000..c963aa3bc09 --- /dev/null +++ b/solutions/746. Min Cost Climbing Stairs/746.java @@ -0,0 +1,10 @@ +class Solution { + public int minCostClimbingStairs(int[] cost) { + final int n = cost.length; + + for (int i = 2; i < n; ++i) + cost[i] += Math.min(cost[i - 1], cost[i - 2]); + + return Math.min(cost[n - 1], cost[n - 2]); + } +} diff --git a/solutions/746. Min Cost Climbing Stairs/746.py b/solutions/746. Min Cost Climbing Stairs/746.py new file mode 100644 index 00000000000..8ca6afd34b5 --- /dev/null +++ b/solutions/746. Min Cost Climbing Stairs/746.py @@ -0,0 +1,8 @@ +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + cost.append(0) + + for i in range(2, len(cost)): + cost[i] += min(cost[i - 1], cost[i - 2]) + + return cost[-1] diff --git a/solutions/747. Largest Number At Least Twice of Others/747.cpp b/solutions/747. Largest Number At Least Twice of Others/747.cpp new file mode 100644 index 00000000000..818c6af5be0 --- /dev/null +++ b/solutions/747. Largest Number At Least Twice of Others/747.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int dominantIndex(vector& nums) { + int ans; + int mx = 0; + int secondMax = 0; + + for (int i = 0; i < nums.size(); ++i) + if (nums[i] > mx) { + secondMax = mx; + mx = nums[i]; + ans = i; + } else if (nums[i] > secondMax) { + secondMax = nums[i]; + } + + return mx >= 2 * secondMax ? ans : -1; + } +}; diff --git a/solutions/747. Largest Number At Least Twice of Others/747.java b/solutions/747. Largest Number At Least Twice of Others/747.java new file mode 100644 index 00000000000..c6878a0acba --- /dev/null +++ b/solutions/747. Largest Number At Least Twice of Others/747.java @@ -0,0 +1,18 @@ +class Solution { + public int dominantIndex(int[] nums) { + int ans = 0; + int mx = 0; + int secondMax = 0; + + for (int i = 0; i < nums.length; ++i) + if (nums[i] > mx) { + secondMax = mx; + mx = nums[i]; + ans = i; + } else if (nums[i] > secondMax) { + secondMax = nums[i]; + } + + return mx >= 2 * secondMax ? ans : -1; + } +} diff --git a/solutions/747. Largest Number At Least Twice of Others/747.py b/solutions/747. Largest Number At Least Twice of Others/747.py new file mode 100644 index 00000000000..a2d1de9bbd2 --- /dev/null +++ b/solutions/747. Largest Number At Least Twice of Others/747.py @@ -0,0 +1,14 @@ +class Solution: + def dominantIndex(self, nums: List[int]) -> int: + mx = 0 + secondMax = 0 + + for i, num in enumerate(nums): + if num > mx: + secondMax = mx + mx = num + ans = i + elif num > secondMax: + secondMax = num + + return ans if mx >= 2 * secondMax else -1 diff --git a/solutions/748. Shortest Completing Word/748.cpp b/solutions/748. Shortest Completing Word/748.cpp new file mode 100644 index 00000000000..9b8911679b4 --- /dev/null +++ b/solutions/748. Shortest Completing Word/748.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + string shortestCompletingWord(string licensePlate, vector& words) { + string ans(16, '.'); + vector count(26); + + for (const char c : licensePlate) + if (isalpha(c)) + ++count[tolower(c) - 'a']; + + for (const string& word : words) + if (word.length() < ans.length() && isComplete(count, getCount(word))) + ans = word; + + return ans; + } + + private: + // Returns true if c1 is a subset of c2. + bool isComplete(const vector& c1, const vector c2) { + for (int i = 0; i < 26; ++i) + if (c1[i] > c2[i]) + return false; + return true; + } + + vector getCount(const string& word) { + vector count(26); + for (const char c : word) + ++count[c - 'a']; + return count; + } +}; diff --git a/solutions/748. Shortest Completing Word/748.java b/solutions/748. Shortest Completing Word/748.java new file mode 100644 index 00000000000..fced1e0b548 --- /dev/null +++ b/solutions/748. Shortest Completing Word/748.java @@ -0,0 +1,31 @@ +class Solution { + public String shortestCompletingWord(String licensePlate, String[] words) { + String ans = "****************"; + int[] count = new int[26]; + + for (char c : licensePlate.toCharArray()) + if (Character.isLetter(c)) + ++count[Character.toLowerCase(c) - 'a']; + + for (final String word : words) + if (word.length() < ans.length() && isComplete(count, getCount(word))) + ans = word; + + return ans; + } + + // Returns true if c1 is a subset of c2. + private boolean isComplete(int[] c1, int[] c2) { + for (int i = 0; i < 26; ++i) + if (c1[i] > c2[i]) + return false; + return true; + } + + private int[] getCount(final String word) { + int[] count = new int[26]; + for (final char c : word.toCharArray()) + ++count[c - 'a']; + return count; + } +} diff --git a/solutions/748. Shortest Completing Word/748.py b/solutions/748. Shortest Completing Word/748.py new file mode 100644 index 00000000000..5e563450f45 --- /dev/null +++ b/solutions/748. Shortest Completing Word/748.py @@ -0,0 +1,18 @@ +class Solution: + def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: + def isMatch(word: str) -> bool: + wordCount = collections.Counter(word) + return False if any(wordCount[i] < count[i] for i in string.ascii_letters) else True + + ans = '*' * 16 + count = collections.defaultdict(int) + + for c in licensePlate: + if c.isalpha(): + count[c.lower()] += 1 + + for word in words: + if len(word) < len(ans) and isMatch(word): + ans = word + + return ans diff --git a/solutions/749. Contain Virus/749.cpp b/solutions/749. Contain Virus/749.cpp new file mode 100644 index 00000000000..51bf063c9a1 --- /dev/null +++ b/solutions/749. Contain Virus/749.cpp @@ -0,0 +1,85 @@ +struct Region { + // Given m = the number of rows and n = the number of columns, (x, y) will be + // hashed as x * n + y. + unordered_set infected; + unordered_set noninfected; + int wallsRequired = 0; +}; + +class Solution { + public: + int containVirus(vector>& isInfected) { + const int m = isInfected.size(); + const int n = isInfected[0].size(); + int ans = 0; + + while (true) { + vector regions; + vector> seen(m, vector(n)); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (isInfected[i][j] == 1 && !seen[i][j]) { + Region region; + // Use DFS to find all the regions (1s). + dfs(isInfected, i, j, region, seen); + if (!region.noninfected.empty()) + regions.push_back(region); + } + + if (regions.empty()) + break; // No region causes further infection. + + // Regions that infect the most neighbors will be sorted to the back of + // the array. + ranges::sort(regions, [](const Region& a, const Region& b) { + return a.noninfected.size() < b.noninfected.size(); + }); + + // Build walls around the region that infects the most neighbors. + Region mostInfectedRegion = regions.back(); + regions.pop_back(); + ans += mostInfectedRegion.wallsRequired; + + for (const int neighbor : mostInfectedRegion.infected) { + const int i = neighbor / n; + const int j = neighbor % n; + // The isInfected is now contained and won't be infected anymore. + isInfected[i][j] = 2; + } + + // For remaining regions, infect their neighbors. + for (const Region& region : regions) + for (const int neighbor : region.noninfected) { + const int i = neighbor / n; + const int j = neighbor % n; + isInfected[i][j] = 1; + } + } + + return ans; + } + + private: + void dfs(const vector>& isInfected, int i, int j, Region& region, + vector>& seen) { + if (i < 0 || i == isInfected.size() || j < 0 || j == isInfected[0].size()) + return; + if (seen[i][j] || isInfected[i][j] == 2) + return; + if (isInfected[i][j] == 0) { + region.noninfected.insert(i * isInfected[0].size() + j); + ++region.wallsRequired; + return; + } + + // isInfected[i][j] == 1 + seen[i][j] = true; + region.infected.insert(i * isInfected[0].size() + j); + + dfs(isInfected, i + 1, j, region, seen); + dfs(isInfected, i - 1, j, region, seen); + dfs(isInfected, i, j + 1, region, seen); + dfs(isInfected, i, j - 1, region, seen); + } +}; diff --git a/solutions/749. Contain Virus/749.java b/solutions/749. Contain Virus/749.java new file mode 100644 index 00000000000..c7e49d9225e --- /dev/null +++ b/solutions/749. Contain Virus/749.java @@ -0,0 +1,80 @@ +class Region { + // Given m = the number of rows and n = the number of columns, (x, y) will be + // hashed as x * n + y. + public Set infected = new HashSet<>(); + public Set noninfected = new HashSet<>(); + public int wallsRequired = 0; +}; + +class Solution { + public int containVirus(int[][] isInfected) { + final int m = isInfected.length; + final int n = isInfected[0].length; + int ans = 0; + + while (true) { + List regions = new ArrayList<>(); + boolean[][] seen = new boolean[m][n]; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (isInfected[i][j] == 1 && !seen[i][j]) { + Region region = new Region(); + // Use DFS to find all the regions (1s). + dfs(isInfected, i, j, region, seen); + if (!region.noninfected.isEmpty()) + regions.add(region); + } + + if (regions.isEmpty()) + break; // No region causes further infection. + + // Regions that infect the most neighbors will be sorted to the back of + // the array. + Collections.sort(regions, (a, b) -> a.noninfected.size() - b.noninfected.size()); + + // Build walls around the region that infects the most neighbors. + Region mostInfectedRegion = regions.get(regions.size() - 1); + regions.remove(regions.size() - 1); + ans += mostInfectedRegion.wallsRequired; + + for (final int neighbor : mostInfectedRegion.infected) { + final int i = neighbor / n; + final int j = neighbor % n; + // The isInfected is now contained and won't be infected anymore. + isInfected[i][j] = 2; + } + + // For remaining regions, infect their neighbors. + for (final Region region : regions) + for (final int neighbor : region.noninfected) { + final int i = neighbor / n; + final int j = neighbor % n; + isInfected[i][j] = 1; + } + } + + return ans; + } + + private void dfs(int[][] isInfected, int i, int j, Region region, boolean[][] seen) { + if (i < 0 || i == isInfected.length || j < 0 || j == isInfected[0].length) + return; + if (seen[i][j] || isInfected[i][j] == 2) + return; + if (isInfected[i][j] == 0) { + region.noninfected.add(i * isInfected[0].length + j); + ++region.wallsRequired; + return; + } + + // isInfected[i][j] == 1 + seen[i][j] = true; + region.infected.add(i * isInfected[0].length + j); + + dfs(isInfected, i + 1, j, region, seen); + dfs(isInfected, i - 1, j, region, seen); + dfs(isInfected, i, j + 1, region, seen); + dfs(isInfected, i, j - 1, region, seen); + } +} diff --git a/solutions/75. Sort Colors/75-2.cpp b/solutions/75. Sort Colors/75-2.cpp new file mode 100644 index 00000000000..12127d435bf --- /dev/null +++ b/solutions/75. Sort Colors/75-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + void sortColors(vector& nums) { + int l = 0; // The next 0 should be placed in l. + int r = nums.size() - 1; // The next 2 should be placed in r. + + for (int i = 0; i <= r;) + if (nums[i] == 0) + swap(nums[i++], nums[l++]); + else if (nums[i] == 1) + ++i; + else + // We may swap a 0 to index i, but we're still not sure whether this 0 + // is placed in the correct index, so we can't move pointer i. + swap(nums[i], nums[r--]); + } +}; diff --git a/solutions/75. Sort Colors/75-2.java b/solutions/75. Sort Colors/75-2.java new file mode 100644 index 00000000000..7634a41c72d --- /dev/null +++ b/solutions/75. Sort Colors/75-2.java @@ -0,0 +1,22 @@ +class Solution { + public void sortColors(int[] nums) { + int l = 0; // The next 0 should be placed in l. + int r = nums.length - 1; // THe next 2 should be placed in r. + + for (int i = 0; i <= r;) + if (nums[i] == 0) + swap(nums, i++, l++); + else if (nums[i] == 1) + ++i; + else + // We may swap a 0 to index i, but we're still not sure whether this 0 + // is placed in the correct index, so we can't move pointer i. + swap(nums, i, r--); + } + + private void swap(int[] nums, int i, int j) { + final int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/solutions/75. Sort Colors/75-2.py b/solutions/75. Sort Colors/75-2.py new file mode 100644 index 00000000000..2606e35d2aa --- /dev/null +++ b/solutions/75. Sort Colors/75-2.py @@ -0,0 +1,18 @@ +class Solution: + def sortColors(self, nums: List[int]) -> None: + l = 0 # The next 0 should be placed in l. + r = len(nums) - 1 # THe next 2 should be placed in r. + + i = 0 + while i <= r: + if nums[i] == 0: + nums[i], nums[l] = nums[l], nums[i] + i += 1 + l += 1 + elif nums[i] == 1: + i += 1 + else: + # We may swap a 0 to index i, but we're still not sure whether this 0 + # is placed in the correct index, so we can't move pointer i. + nums[i], nums[r] = nums[r], nums[i] + r -= 1 diff --git a/solutions/75. Sort Colors/75.cpp b/solutions/75. Sort Colors/75.cpp new file mode 100644 index 00000000000..6e748a309c5 --- /dev/null +++ b/solutions/75. Sort Colors/75.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + void sortColors(vector& nums) { + int zero = -1; + int one = -1; + int two = -1; + + for (const int num : nums) + if (num == 0) { + nums[++two] = 2; + nums[++one] = 1; + nums[++zero] = 0; + } else if (num == 1) { + nums[++two] = 2; + nums[++one] = 1; + } else { + nums[++two] = 2; + } + } +}; diff --git a/solutions/75. Sort Colors/75.java b/solutions/75. Sort Colors/75.java new file mode 100644 index 00000000000..d9498ef5ea9 --- /dev/null +++ b/solutions/75. Sort Colors/75.java @@ -0,0 +1,19 @@ +class Solution { + public void sortColors(int[] nums) { + int zero = -1; + int one = -1; + int two = -1; + + for (final int num : nums) + if (num == 0) { + nums[++two] = 2; + nums[++one] = 1; + nums[++zero] = 0; + } else if (num == 1) { + nums[++two] = 2; + nums[++one] = 1; + } else { + nums[++two] = 2; + } + } +} diff --git a/solutions/75. Sort Colors/75.py b/solutions/75. Sort Colors/75.py new file mode 100644 index 00000000000..ba1d7ea58af --- /dev/null +++ b/solutions/75. Sort Colors/75.py @@ -0,0 +1,22 @@ +class Solution: + def sortColors(self, nums: List[int]) -> None: + zero = -1 + one = -1 + two = -1 + + for num in nums: + if num == 0: + two += 1 + one += 1 + zero += 1 + nums[two] = 2 + nums[one] = 1 + nums[zero] = 0 + elif num == 1: + two += 1 + one += 1 + nums[two] = 2 + nums[one] = 1 + else: + two += 1 + nums[two] = 2 diff --git a/solutions/750. Number Of Corner Rectangles/750.cpp b/solutions/750. Number Of Corner Rectangles/750.cpp new file mode 100644 index 00000000000..7943872bc9a --- /dev/null +++ b/solutions/750. Number Of Corner Rectangles/750.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int countCornerRectangles(vector>& grid) { + int ans = 0; + + for (int row1 = 0; row1 < grid.size() - 1; ++row1) + for (int row2 = row1 + 1; row2 < grid.size(); ++row2) { + int count = 0; + for (int j = 0; j < grid[0].size(); ++j) + if (grid[row1][j] && grid[row2][j]) + ++count; + ans += count * (count - 1) / 2; + } + + return ans; + } +}; diff --git a/solutions/750. Number Of Corner Rectangles/750.java b/solutions/750. Number Of Corner Rectangles/750.java new file mode 100644 index 00000000000..7531c9600b0 --- /dev/null +++ b/solutions/750. Number Of Corner Rectangles/750.java @@ -0,0 +1,16 @@ +class Solution { + public int countCornerRectangles(int[][] grid) { + int ans = 0; + + for (int row1 = 0; row1 < grid.length - 1; ++row1) + for (int row2 = row1 + 1; row2 < grid.length; ++row2) { + int count = 0; + for (int j = 0; j < grid[0].length; ++j) + if (grid[row1][j] == 1 && grid[row2][j] == 1) + ++count; + ans += count * (count - 1) / 2; + } + + return ans; + } +} diff --git a/solutions/751. IP to CIDR/751.cpp b/solutions/751. IP to CIDR/751.cpp new file mode 100644 index 00000000000..d35d6c50acb --- /dev/null +++ b/solutions/751. IP to CIDR/751.cpp @@ -0,0 +1,61 @@ +class Solution { + public: + vector ipToCIDR(string ip, int n) { + vector ans; + long num = getNum(ip); + + while (n > 0) { + const long lowbit = num & -num; + const long count = lowbit == 0 ? maxLow(n) : firstFit(lowbit, n); + ans.push_back(getCIDR(num, getPrefix(count))); + n -= count; + num += count; + } + + return ans; + } + + private: + long getNum(const string& ip) { + istringstream iss(ip); + long num = 0; + for (string token; getline(iss, token, '.');) + num = num * 256 + stol(token); + return num; + } + + // Returns the maximum i s.t. 2^i < n. + int maxLow(int n) { + for (int i = 0; i < 32; ++i) + if (1 << i + 1 > n) + return 1 << i; + throw; + } + + long firstFit(long lowbit, long n) { + while (lowbit > n) + lowbit >>= 1; + return lowbit; + } + + string getCIDR(long num, long prefix) { + const long d = num & 255; + num >>= 8; + const long c = num & 255; + num >>= 8; + const long b = num & 255; + num >>= 8; + const long a = num & 255; + return to_string(a) + '.' + to_string(b) + '.' + to_string(c) + '.' + + to_string(d) + '/' + to_string(prefix); + } + + // e.g. count = 8 = 2^3 -> prefix = 32 - 3 = 29 + // count = 1 = 2^0 -> prefix = 32 - 0 = 32 + int getPrefix(long count) { + for (int i = 0; i < 32; ++i) + if (count == 1 << i) + return 32 - i; + throw; + } +}; diff --git a/solutions/751. IP to CIDR/751.java b/solutions/751. IP to CIDR/751.java new file mode 100644 index 00000000000..d4f61a029ad --- /dev/null +++ b/solutions/751. IP to CIDR/751.java @@ -0,0 +1,67 @@ +class Solution { + public List ipToCIDR(String ip, int n) { + List ans = new ArrayList<>(); + long num = getNum(ip.split("\\.")); + + while (n > 0) { + final long lowbit = num & -num; + final long count = lowbit == 0 ? maxLow(n) : firstFit(lowbit, n); + ans.add(getCIDR(num, getPrefix(count))); + n -= (int) count; + num += count; + } + + return ans; + } + + private long getNum(String[] x) { + long num = 0; + for (int i = 0; i < 4; ++i) + num = num * 256 + Long.parseLong(x[i]); + return num; + } + + // Returns the maximum i s.t. 2^i < n. + private int maxLow(int n) { + for (int i = 0; i < 32; ++i) + if (1 << i + 1 > n) + return 1 << i; + throw new IllegalArgumentException(); + } + + private long firstFit(long lowbit, long n) { + while (lowbit > n) + lowbit >>= 1; + return lowbit; + } + + private String getCIDR(long num, long prefix) { + final long d = num & 255; + num >>= 8; + final long c = num & 255; + num >>= 8; + final long b = num & 255; + num >>= 8; + final long a = num & 255; + return new StringBuilder() + .append(a) + .append(".") + .append(b) + .append(".") + .append(c) + .append(".") + .append(d) + .append("/") + .append(prefix) + .toString(); + } + + // e.g. count = 8 = 2^3 -> prefix = 32 - 3 = 29 + // count = 1 = 2^0 -> prefix = 32 - 0 = 32 + private int getPrefix(long count) { + for (int i = 0; i < 32; ++i) + if (count == 1 << i) + return 32 - i; + throw new IllegalArgumentException(); + } +} diff --git a/solutions/751. IP to CIDR/751.py b/solutions/751. IP to CIDR/751.py new file mode 100644 index 00000000000..7e64434d197 --- /dev/null +++ b/solutions/751. IP to CIDR/751.py @@ -0,0 +1,49 @@ +class Solution: + def ipToCIDR(self, ip: str, n: int) -> List[str]: + ans = [] + num = self._getNum(ip.split('.')) + + while n > 0: + lowbit = num & -num + count = self._maxLow(n) if lowbit == 0 else self._firstFit(lowbit, n) + ans.append(self._getCIDR(num, self._getPrefix(count))) + n -= count + num += count + + return ans + + def _getNum(self, x: List[str]) -> int: + num = 0 + for i in range(4): + num = num * 256 + int(x[i]) + return num + + def _maxLow(self, n: int) -> Optional[int]: + """Returns the maximum i s.t. 2^i < n.""" + for i in range(32): + if 1 << i + 1 > n: + return 1 << i + + def _firstFit(self, lowbit: int, n: int) -> int: + while lowbit > n: + lowbit >>= 1 + return lowbit + + def _getCIDR(self, num: int, prefix: int) -> str: + d = num & 255 + num >>= 8 + c = num & 255 + num >>= 8 + b = num & 255 + num >>= 8 + a = num & 255 + return '.'.join([str(s) for s in [a, b, c, d]]) + '/' + str(prefix) + + def _getPrefix(self, count: int) -> Optional[int]: + """ + e.g. count = 8 = 2^3 . prefix = 32 - 3 = 29 + count = 1 = 2^0 . prefix = 32 - 0 = 32 + """ + for i in range(32): + if count == 1 << i: + return 32 - i diff --git a/solutions/752. Open the Lock/752.cpp b/solutions/752. Open the Lock/752.cpp new file mode 100644 index 00000000000..78f5676be2f --- /dev/null +++ b/solutions/752. Open the Lock/752.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + int openLock(vector& deadends, string target) { + unordered_set seen{deadends.begin(), deadends.end()}; + if (seen.contains("0000")) + return -1; + if (target == "0000") + return 0; + + int ans = 0; + queue q{{"0000"}}; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + string word = q.front(); + q.pop(); + for (int i = 0; i < 4; ++i) { + const char cache = word[i]; + // Increase the i-th digit by 1. + word[i] = word[i] == '9' ? '0' : word[i] + 1; + if (word == target) + return ans; + if (!seen.contains(word)) { + q.push(word); + seen.insert(word); + } + word[i] = cache; + // Decrease the i-th digit by 1. + word[i] = word[i] == '0' ? '9' : word[i] - 1; + if (word == target) + return ans; + if (!seen.contains(word)) { + q.push(word); + seen.insert(word); + } + word[i] = cache; + } + } + } + + return -1; + } +}; diff --git a/solutions/752. Open the Lock/752.java b/solutions/752. Open the Lock/752.java new file mode 100644 index 00000000000..36de801e1e3 --- /dev/null +++ b/solutions/752. Open the Lock/752.java @@ -0,0 +1,44 @@ +class Solution { + public int openLock(String[] deadends, String target) { + Set seen = new HashSet<>(Arrays.asList(deadends)); + if (seen.contains("0000")) + return -1; + if (target.equals("0000")) + return 0; + + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList("0000")); + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + StringBuilder sb = new StringBuilder(q.poll()); + for (int i = 0; i < 4; ++i) { + final char cache = sb.charAt(i); + // Increase the i-th digit by 1. + sb.setCharAt(i, sb.charAt(i) == '9' ? '0' : (char) (sb.charAt(i) + 1)); + String word = sb.toString(); + if (word.equals(target)) + return ans; + if (!seen.contains(word)) { + q.offer(word); + seen.add(word); + } + sb.setCharAt(i, cache); + // Decrease the i-th digit by 1. + sb.setCharAt(i, sb.charAt(i) == '0' ? '9' : (char) (sb.charAt(i) - 1)); + word = sb.toString(); + if (word.equals(target)) + return ans; + if (!seen.contains(word)) { + q.offer(word); + seen.add(word); + } + sb.setCharAt(i, cache); + } + } + } + + return -1; + } +} diff --git a/solutions/753. Cracking the Safe/753.cpp b/solutions/753. Cracking the Safe/753.cpp new file mode 100644 index 00000000000..ebd62f99505 --- /dev/null +++ b/solutions/753. Cracking the Safe/753.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + string crackSafe(int n, int k) { + string ans(n, '0'); + dfs(pow(k, n), n, k, {ans}, ans); + return ans; + } + + private: + bool dfs(int passwordSize, int n, int k, unordered_set&& seen, + string& path) { + if (seen.size() == passwordSize) + return true; + + string prefix = path.substr(path.length() - n + 1); + + for (char c = '0'; c < '0' + k; ++c) { + prefix.push_back(c); + if (!seen.contains(prefix)) { + seen.insert(prefix); + path.push_back(c); + if (dfs(passwordSize, n, k, move(seen), path)) + return true; + path.pop_back(); + seen.erase(prefix); + } + prefix.pop_back(); + } + + return false; + } +}; diff --git a/solutions/753. Cracking the Safe/753.java b/solutions/753. Cracking the Safe/753.java new file mode 100644 index 00000000000..d735f8c740a --- /dev/null +++ b/solutions/753. Cracking the Safe/753.java @@ -0,0 +1,31 @@ +class Solution { + public String crackSafe(int n, int k) { + final String allZeros = "0".repeat(n); + StringBuilder sb = new StringBuilder(allZeros); + dfs((int) Math.pow(k, n), n, k, new HashSet<>(Arrays.asList(allZeros)), sb); + return sb.toString(); + } + + private boolean dfs(int passwordSize, int n, int k, Set seen, StringBuilder path) { + if (seen.size() == passwordSize) + return true; + + StringBuilder prefix = new StringBuilder(path.substring(path.length() - n + 1)); + + for (char c = '0'; c < '0' + k; ++c) { + prefix.append(c); + final String prefixStr = prefix.toString(); + if (!seen.contains(prefixStr)) { + seen.add(prefixStr); + path.append(c); + if (dfs(passwordSize, n, k, seen, path)) + return true; + path.deleteCharAt(path.length() - 1); + seen.remove(prefixStr); + } + prefix.deleteCharAt(prefix.length() - 1); + } + + return false; + } +} diff --git a/solutions/753. Cracking the Safe/753.py b/solutions/753. Cracking the Safe/753.py new file mode 100644 index 00000000000..c8b7ce00177 --- /dev/null +++ b/solutions/753. Cracking the Safe/753.py @@ -0,0 +1,21 @@ +class Solution: + def crackSafe(self, n: int, k: int) -> str: + passwordSize = k**n + path = '0' * n + seen = set() + seen.add(path) + + def dfs(path: str) -> str: + if len(seen) == passwordSize: + return path + + for c in map(str, range(k)): + node = path[-n + 1:] + c if n > 1 else c + if node not in seen: + seen.add(node) + res = dfs(path + c) + if res: + return res + seen.remove(node) + + return dfs(path) diff --git a/solutions/754. Reach a Number/754.cpp b/solutions/754. Reach a Number/754.cpp new file mode 100644 index 00000000000..1b87f680dfb --- /dev/null +++ b/solutions/754. Reach a Number/754.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int reachNumber(int target) { + const int newTarget = abs(target); + int ans = 0; + int pos = 0; + + while (pos < newTarget) + pos += ++ans; + while ((pos - newTarget) % 2 == 1) + pos += ++ans; + + return ans; + } +}; diff --git a/solutions/754. Reach a Number/754.java b/solutions/754. Reach a Number/754.java new file mode 100644 index 00000000000..f8a299e198f --- /dev/null +++ b/solutions/754. Reach a Number/754.java @@ -0,0 +1,14 @@ +class Solution { + public int reachNumber(int target) { + final int newTarget = Math.abs(target); + int ans = 0; + int pos = 0; + + while (pos < newTarget) + pos += ++ans; + while ((pos - newTarget) % 2 == 1) + pos += ++ans; + + return ans; + } +} diff --git a/solutions/754. Reach a Number/754.py b/solutions/754. Reach a Number/754.py new file mode 100644 index 00000000000..ed14154b07f --- /dev/null +++ b/solutions/754. Reach a Number/754.py @@ -0,0 +1,15 @@ +class Solution: + def reachNumber(self, target: int) -> int: + ans = 0 + pos = 0 + target = abs(target) + + while pos < target: + ans += 1 + pos += ans + + while (pos - target) % 2 == 1: + ans += 1 + pos += ans + + return ans diff --git a/solutions/755. Pour Water/755.cpp b/solutions/755. Pour Water/755.cpp new file mode 100644 index 00000000000..310764ef3f5 --- /dev/null +++ b/solutions/755. Pour Water/755.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector pourWater(vector& heights, int volume, int k) { + int i = k; + + while (volume-- > 0) { + while (i > 0 && heights[i] >= heights[i - 1]) + --i; + while (i + 1 < heights.size() && heights[i] >= heights[i + 1]) + ++i; + while (i > k && heights[i] == heights[i - 1]) + --i; + ++heights[i]; + } + + return heights; + } +}; diff --git a/solutions/755. Pour Water/755.java b/solutions/755. Pour Water/755.java new file mode 100644 index 00000000000..74d852587d3 --- /dev/null +++ b/solutions/755. Pour Water/755.java @@ -0,0 +1,17 @@ +class Solution { + public int[] pourWater(int[] heights, int volume, int k) { + int i = k; + + while (volume-- > 0) { + while (i > 0 && heights[i] >= heights[i - 1]) + --i; + while (i + 1 < heights.length && heights[i] >= heights[i + 1]) + ++i; + while (i > k && heights[i] == heights[i - 1]) + --i; + ++heights[i]; + } + + return heights; + } +} diff --git a/solutions/755. Pour Water/755.py b/solutions/755. Pour Water/755.py new file mode 100644 index 00000000000..ded1e66ef7d --- /dev/null +++ b/solutions/755. Pour Water/755.py @@ -0,0 +1,15 @@ +class Solution: + def pourWater(self, heights: List[int], volume: int, k: int) -> List[int]: + i = k + + while volume > 0: + volume -= 1 + while i > 0 and heights[i] >= heights[i - 1]: + i -= 1 + while i + 1 < len(heights) and heights[i] >= heights[i + 1]: + i += 1 + while i > k and heights[i] == heights[i - 1]: + i -= 1 + heights[i] += 1 + + return heights diff --git a/solutions/756. Pyramid Transition Matrix/756.cpp b/solutions/756. Pyramid Transition Matrix/756.cpp new file mode 100644 index 00000000000..33666f10b04 --- /dev/null +++ b/solutions/756. Pyramid Transition Matrix/756.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool pyramidTransition(string bottom, vector& allowed) { + unordered_map> prefixToBlocks; + + for (const string& a : allowed) + prefixToBlocks[a.substr(0, 2)].push_back(a[2]); + + return dfs(bottom, "", 0, prefixToBlocks); + } + + private: + bool dfs(const string& row, const string& nextRow, int i, + const unordered_map>& prefixToBlocks) { + if (row.length() == 1) + return true; + if (nextRow.length() + 1 == row.length()) + return dfs(nextRow, "", 0, prefixToBlocks); + + const string& prefix = row.substr(i, 2); + + if (const auto it = prefixToBlocks.find(prefix); + it != prefixToBlocks.cend()) + for (const char c : it->second) + if (dfs(row, nextRow + c, i + 1, prefixToBlocks)) + return true; + + return false; + } +}; diff --git a/solutions/756. Pyramid Transition Matrix/756.java b/solutions/756. Pyramid Transition Matrix/756.java new file mode 100644 index 00000000000..084803a1c0a --- /dev/null +++ b/solutions/756. Pyramid Transition Matrix/756.java @@ -0,0 +1,30 @@ +class Solution { + public boolean pyramidTransition(String bottom, List allowed) { + Map> prefixToBlocks = new HashMap<>(); + + for (final String a : allowed) { + final String lowerBlocks = a.substring(0, 2); + prefixToBlocks.putIfAbsent(lowerBlocks, new LinkedList<>()); + prefixToBlocks.get(lowerBlocks).add(a.charAt(2)); + } + + return dfs(bottom, "", 0, prefixToBlocks); + } + + private boolean dfs(final String row, final String nextRow, int i, + Map> prefixToBlocks) { + if (row.length() == 1) + return true; + if (nextRow.length() + 1 == row.length()) + return dfs(nextRow, "", 0, prefixToBlocks); + + final String prefix = row.substring(i, i + 2); + + if (prefixToBlocks.containsKey(prefix)) + for (final char c : prefixToBlocks.get(prefix)) + if (dfs(row, nextRow + c, i + 1, prefixToBlocks)) + return true; + + return false; + } +} diff --git a/solutions/756. Pyramid Transition Matrix/756.py b/solutions/756. Pyramid Transition Matrix/756.py new file mode 100644 index 00000000000..4389bc4668b --- /dev/null +++ b/solutions/756. Pyramid Transition Matrix/756.py @@ -0,0 +1,20 @@ +class Solution: + def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool: + prefixToBlocks = collections.defaultdict(list) + + for a in allowed: + prefixToBlocks[a[:2]].append(a[2]) + + def dfs(row: str, nextRow: str, i: int) -> bool: + if len(row) == 1: + return True + if len(nextRow) + 1 == len(row): + return dfs(nextRow, '', 0) + + for c in prefixToBlocks[row[i:i + 2]]: + if dfs(row, nextRow + c, i + 1): + return True + + return False + + return dfs(bottom, '', 0) diff --git a/solutions/757. Set Intersection Size At Least Two/757.cpp b/solutions/757. Set Intersection Size At Least Two/757.cpp new file mode 100644 index 00000000000..208bb0327c9 --- /dev/null +++ b/solutions/757. Set Intersection Size At Least Two/757.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int intersectionSizeTwo(vector>& intervals) { + int ans = 0; + int mx = -1; + int secondMax = -1; + + ranges::sort(intervals, [](const vector& a, const vector& b) { + return a[1] == b[1] ? a[0] > b[0] : a[1] < b[1]; + }); + + for (const vector& interval : intervals) { + const int a = interval[0]; + const int b = interval[1]; + // The maximum and the second maximum still satisfy. + if (mx >= a && secondMax >= a) + continue; + if (mx >= a) { // The maximum still satisfy. + secondMax = mx; + mx = b; // Add b to the set S. + ans += 1; + } else { // The maximum and the second maximum can't satisfy. + mx = b; // Add b to the set S. + secondMax = b - 1; // Add b - 1 to the set S. + ans += 2; + } + } + + return ans; + } +}; diff --git a/solutions/757. Set Intersection Size At Least Two/757.java b/solutions/757. Set Intersection Size At Least Two/757.java new file mode 100644 index 00000000000..cffb459668d --- /dev/null +++ b/solutions/757. Set Intersection Size At Least Two/757.java @@ -0,0 +1,28 @@ +class Solution { + public int intersectionSizeTwo(int[][] intervals) { + int ans = 0; + int mx = -1; + int secondMax = -1; + + Arrays.sort(intervals, (a, b) -> a[1] == b[1] ? b[0] - a[0] : a[1] - b[1]); + + for (int[] interval : intervals) { + final int a = interval[0]; + final int b = interval[1]; + // The maximum and the second maximum still satisfy. + if (mx >= a && secondMax >= a) + continue; + if (mx >= a) { // The maximum still satisfy. + secondMax = mx; + mx = b; // Add b to the set S. + ans += 1; + } else { // The maximum and the second maximum can't satisfy. + mx = b; // Add b to the set S. + secondMax = b - 1; // Add b - 1 to the set S. + ans += 2; + } + } + + return ans; + } +} diff --git a/solutions/758. Bold Words in String/758-2.cpp b/solutions/758. Bold Words in String/758-2.cpp new file mode 100644 index 00000000000..78519e90223 --- /dev/null +++ b/solutions/758. Bold Words in String/758-2.cpp @@ -0,0 +1,68 @@ +struct TrieNode { + vector> children; + bool isWord = false; + TrieNode() : children(26) {} +}; + +class Solution { + public: + string boldWords(vector& words, string s) { + const int n = s.length(); + string ans; + // bold[i] := true if s[i] should be bolded + vector bold(n); + + for (const string& word : words) + insert(word); + + int boldEnd = -1; // `s[i..boldEnd]` should be bolded. + for (int i = 0; i < n; ++i) { + boldEnd = max(boldEnd, find(s, i)); + bold[i] = boldEnd >= i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // `s[i..j)` should be bolded. + ans += "" + s.substr(i, j - i) + ""; + i = j; + } else { + ans += s[i++]; + } + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->isWord = true; + } + + int find(const string& s, int i) { + shared_ptr node = root; + int ans = -1; + for (int j = i; j < s.length(); ++j) { + const int index = s[j] - 'a'; + if (node->children[index] == nullptr) + return ans; + node = node->children[index]; + if (node->isWord) + ans = j; + } + return ans; + } +}; diff --git a/solutions/758. Bold Words in String/758-2.java b/solutions/758. Bold Words in String/758-2.java new file mode 100644 index 00000000000..60eeba34a78 --- /dev/null +++ b/solutions/758. Bold Words in String/758-2.java @@ -0,0 +1,65 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public boolean isWord = false; +} + +class Solution { + public String boldWords(String[] words, String s) { + final int n = s.length(); + StringBuilder sb = new StringBuilder(); + // bold[i] := true if s[i] should be bolded + boolean[] bold = new boolean[n]; + + for (final String word : words) + insert(word); + + int boldEnd = -1; // `s[i..boldEnd]` should be bolded. + for (int i = 0; i < n; ++i) { + boldEnd = Math.max(boldEnd, find(s, i)); + bold[i] = boldEnd >= i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // s[i..j) should be bolded + sb.append("").append(s.substring(i, j)).append(""); + i = j; + } else { + sb.append(s.charAt(i++)); + } + + return sb.toString(); + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.isWord = true; + } + + private int find(final String s, int i) { + TrieNode node = root; + int ans = -1; + for (int j = i; j < s.length(); ++j) { + final int index = s.charAt(j) - 'a'; + if (node.children[index] == null) + return ans; + node = node.children[index]; + if (node.isWord) + ans = j; + } + return ans; + } +} diff --git a/solutions/758. Bold Words in String/758-2.py b/solutions/758. Bold Words in String/758-2.py new file mode 100644 index 00000000000..d062221b5fc --- /dev/null +++ b/solutions/758. Bold Words in String/758-2.py @@ -0,0 +1,54 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.isWord = False + + +class Solution: + def boldWords(self, words: List[str], s: str) -> str: + n = len(s) + ans = [] + # bold[i] := True if s[i] should be bolded + bold = [0] * n + root = TrieNode() + + def insert(word: str) -> None: + node = root + for c in word: + if c not in node.children: + node.children[c] = TrieNode() + node = node.children[c] + node.isWord = True + + def find(s: str, i: int) -> int: + node = root + ans = -1 + for j in range(i, len(s)): + node = node.children.setdefault(s[j], TrieNode()) + if node.isWord: + ans = j + return ans + + for word in words: + insert(word) + + boldEnd = -1 # `s[i..boldEnd]` should be bolded. + for i in range(n): + boldEnd = max(boldEnd, find(s, i)) + bold[i] = boldEnd >= i + + # Construct the with bold tags + i = 0 + while i < n: + if bold[i]: + j = i + while j < n and bold[j]: + j += 1 + # `s[i..j)` should be bolded. + ans.append('' + s[i:j] + '') + i = j + else: + ans.append(s[i]) + i += 1 + + return ''.join(ans) diff --git a/solutions/758. Bold Words in String/758-3.cpp b/solutions/758. Bold Words in String/758-3.cpp new file mode 100644 index 00000000000..b7f1721cef2 --- /dev/null +++ b/solutions/758. Bold Words in String/758-3.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + string boldWords(vector& words, string s) { + string ans; + vector> intervals; + vector> merged; + + for (const string& word : words) { + const int n = word.length(); + for (int i = 0; i + n <= s.length(); ++i) + if (s.substr(i, n) == word) + intervals.emplace_back(i, i + n); + } + + if (intervals.empty()) + return s; + + ranges::sort(intervals); + + for (const pair& interval : intervals) + if (merged.empty() || merged.back().second < interval.first) + merged.push_back(interval); + else + merged.back().second = max(merged.back().second, interval.second); + + int prevEnd = 0; + + for (const auto& [startIndex, endIndex] : merged) { + ans += s.substr(prevEnd, startIndex - prevEnd); + ans += "" + s.substr(startIndex, endIndex - startIndex) + ""; + prevEnd = endIndex; + } + + if (!merged.empty()) + ans += s.substr(merged.back().second); + + return ans; + } +}; diff --git a/solutions/758. Bold Words in String/758.cpp b/solutions/758. Bold Words in String/758.cpp new file mode 100644 index 00000000000..edd10c81449 --- /dev/null +++ b/solutions/758. Bold Words in String/758.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + string boldWords(vector& words, string s) { + const int n = s.length(); + string ans; + // bold[i] := true if s[i] should be bolded + vector bold(n); + + int boldEnd = -1; // s[i:boldEnd] should be bolded + for (int i = 0; i < n; ++i) { + for (const string& word : words) + if (s.substr(i).find(word) == 0) + boldEnd = max(boldEnd, i + static_cast(word.length())); + bold[i] = boldEnd > i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // `s[i..j)` should be bolded. + ans += "" + s.substr(i, j - i) + ""; + i = j; + } else { + ans += s[i++]; + } + + return ans; + } +}; diff --git a/solutions/758. Bold Words in String/758.java b/solutions/758. Bold Words in String/758.java new file mode 100644 index 00000000000..6d29387c515 --- /dev/null +++ b/solutions/758. Bold Words in String/758.java @@ -0,0 +1,32 @@ +class Solution { + public String boldWords(String[] words, String s) { + final int n = s.length(); + StringBuilder sb = new StringBuilder(); + // bold[i] := true if s[i] should be bolded + boolean[] bold = new boolean[n]; + + int boldEnd = -1; // s[i:boldEnd] should be bolded + for (int i = 0; i < n; ++i) { + for (final String word : words) + if (s.substring(i).startsWith(word)) + boldEnd = Math.max(boldEnd, i + word.length()); + bold[i] = boldEnd > i; + } + + // Construct the string with the bold tags. + int i = 0; + while (i < n) + if (bold[i]) { + int j = i; + while (j < n && bold[j]) + ++j; + // s[i..j) should be bolded + sb.append("").append(s.substring(i, j)).append(""); + i = j; + } else { + sb.append(s.charAt(i++)); + } + + return sb.toString(); + } +} diff --git a/solutions/758. Bold Words in String/758.py b/solutions/758. Bold Words in String/758.py new file mode 100644 index 00000000000..ac88413cd98 --- /dev/null +++ b/solutions/758. Bold Words in String/758.py @@ -0,0 +1,29 @@ +class Solution: + def boldWords(self, words: List[str], s: str) -> str: + n = len(s) + ans = [] + # bold[i] := True if s[i] should be bolded + bold = [0] * n + + boldEnd = -1 # s[i:boldEnd] should be bolded + for i in range(n): + for word in words: + if s[i:].startswith(word): + boldEnd = max(boldEnd, i + len(word)) + bold[i] = boldEnd > i + + # Construct the string with the bold tags. + i = 0 + while i < n: + if bold[i]: + j = i + while j < n and bold[j]: + j += 1 + # s[i..j) should be bolded. + ans.append('' + s[i:j] + '') + i = j + else: + ans.append(s[i]) + i += 1 + + return ''.join(ans) diff --git a/solutions/759. Employee Free Time/759.cpp b/solutions/759. Employee Free Time/759.cpp new file mode 100644 index 00000000000..e190b1cfd6d --- /dev/null +++ b/solutions/759. Employee Free Time/759.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector employeeFreeTime(vector> schedule) { + vector ans; + vector intervals; + + for (const vector& s : schedule) + intervals.insert(intervals.end(), s.begin(), s.end()); + + ranges::sort(intervals, [](const auto& a, const auto& b) { + return a.start < b.start; + }); + + int prevEnd = intervals[0].end; + + for (const auto& [start, end] : intervals) { + if (start > prevEnd) + ans.emplace_back(prevEnd, start); + prevEnd = max(prevEnd, end); + } + + return ans; + } +}; diff --git a/solutions/759. Employee Free Time/759.java b/solutions/759. Employee Free Time/759.java new file mode 100644 index 00000000000..fca4f0ae5eb --- /dev/null +++ b/solutions/759. Employee Free Time/759.java @@ -0,0 +1,19 @@ +class Solution { + public List employeeFreeTime(List> schedule) { + List ans = new ArrayList<>(); + List intervals = new ArrayList<>(); + + schedule.forEach(s -> intervals.addAll(s)); + Collections.sort(intervals, (a, b) -> a.start - b.start); + + int prevEnd = intervals.get(0).end; + + for (Interval interval : intervals) { + if (interval.start > prevEnd) + ans.add(new Interval(prevEnd, interval.start)); + prevEnd = Math.max(prevEnd, interval.end); + } + + return ans; + } +} diff --git a/solutions/759. Employee Free Time/759.py b/solutions/759. Employee Free Time/759.py new file mode 100644 index 00000000000..674215758d9 --- /dev/null +++ b/solutions/759. Employee Free Time/759.py @@ -0,0 +1,18 @@ +class Solution: + def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]': + ans = [] + intervals = [] + + for s in schedule: + intervals.extend(s) + + intervals.sort(key=lambda x: x.start) + + prevEnd = intervals[0].end + + for interval in intervals: + if interval.start > prevEnd: + ans.append(Interval(prevEnd, interval.start)) + prevEnd = max(prevEnd, interval.end) + + return ans diff --git a/solutions/76. Minimum Window Substring/76.cpp b/solutions/76. Minimum Window Substring/76.cpp new file mode 100644 index 00000000000..635695cca33 --- /dev/null +++ b/solutions/76. Minimum Window Substring/76.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string minWindow(string s, string t) { + vector count(128); + int required = t.length(); + int bestLeft = -1; + int minLength = s.length() + 1; + + for (const char c : t) + ++count[c]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (--count[s[r]] >= 0) + --required; + while (required == 0) { + if (r - l + 1 < minLength) { + bestLeft = l; + minLength = r - l + 1; + } + if (++count[s[l++]] > 0) + ++required; + } + } + + return bestLeft == -1 ? "" : s.substr(bestLeft, minLength); + } +}; diff --git a/solutions/76. Minimum Window Substring/76.java b/solutions/76. Minimum Window Substring/76.java new file mode 100644 index 00000000000..cbaefa26f87 --- /dev/null +++ b/solutions/76. Minimum Window Substring/76.java @@ -0,0 +1,26 @@ +class Solution { + public String minWindow(String s, String t) { + int[] count = new int[128]; + int required = t.length(); + int bestLeft = -1; + int minLength = s.length() + 1; + + for (final char c : t.toCharArray()) + ++count[c]; + + for (int l = 0, r = 0; r < s.length(); ++r) { + if (--count[s.charAt(r)] >= 0) + --required; + while (required == 0) { + if (r - l + 1 < minLength) { + bestLeft = l; + minLength = r - l + 1; + } + if (++count[s.charAt(l++)] > 0) + ++required; + } + } + + return bestLeft == -1 ? "" : s.substring(bestLeft, bestLeft + minLength); + } +} diff --git a/solutions/76. Minimum Window Substring/76.py b/solutions/76. Minimum Window Substring/76.py new file mode 100644 index 00000000000..3a17b4d92c7 --- /dev/null +++ b/solutions/76. Minimum Window Substring/76.py @@ -0,0 +1,22 @@ +class Solution: + def minWindow(self, s: str, t: str) -> str: + count = collections.Counter(t) + required = len(t) + bestLeft = -1 + minLength = len(s) + 1 + + l = 0 + for r, c in enumerate(s): + count[c] -= 1 + if count[c] >= 0: + required -= 1 + while required == 0: + if r - l + 1 < minLength: + bestLeft = l + minLength = r - l + 1 + count[s[l]] += 1 + if count[s[l]] > 0: + required += 1 + l += 1 + + return '' if bestLeft == -1 else s[bestLeft: bestLeft + minLength] diff --git a/solutions/760. Find Anagram Mappings/760.cpp b/solutions/760. Find Anagram Mappings/760.cpp new file mode 100644 index 00000000000..2dc1e799807 --- /dev/null +++ b/solutions/760. Find Anagram Mappings/760.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector anagramMappings(vector& nums1, vector& nums2) { + vector ans; + unordered_map> numToIndices; + + for (int i = 0; i < nums2.size(); ++i) + numToIndices[nums2[i]].push(i); + + for (const int num : nums1) + ans.push_back(numToIndices[num].top()), numToIndices[num].pop(); + + return ans; + } +}; diff --git a/solutions/760. Find Anagram Mappings/760.java b/solutions/760. Find Anagram Mappings/760.java new file mode 100644 index 00000000000..8a2c7d513ab --- /dev/null +++ b/solutions/760. Find Anagram Mappings/760.java @@ -0,0 +1,16 @@ +class Solution { + public int[] anagramMappings(int[] nums1, int[] nums2) { + int[] ans = new int[nums1.length]; + Map> numToIndices = new HashMap<>(); + + for (int i = 0; i < nums2.length; ++i) { + numToIndices.putIfAbsent(nums2[i], new ArrayDeque<>()); + numToIndices.get(nums2[i]).push(i); + } + + for (int i = 0; i < nums1.length; ++i) + ans[i] = numToIndices.get(nums1[i]).pop(); + + return ans; + } +} diff --git a/solutions/760. Find Anagram Mappings/760.py b/solutions/760. Find Anagram Mappings/760.py new file mode 100644 index 00000000000..f43f9d3a613 --- /dev/null +++ b/solutions/760. Find Anagram Mappings/760.py @@ -0,0 +1,8 @@ +class Solution: + def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]: + numToIndices = collections.defaultdict(list) + + for i, num in enumerate(nums2): + numToIndices[num].append(i) + + return [numToIndices[num].pop() for num in nums1] diff --git a/solutions/761. Special Binary String/761.cpp b/solutions/761. Special Binary String/761.cpp new file mode 100644 index 00000000000..6d694b682b0 --- /dev/null +++ b/solutions/761. Special Binary String/761.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string makeLargestSpecial(string s) { + vector specials; + int count = 0; + + for (int i = 0, j = 0; j < s.length(); ++j) { + count += s[j] == '1' ? 1 : -1; + if (count == 0) { // Find a special string. + const string& inner = s.substr(i + 1, j - i - 1); + specials.push_back('1' + makeLargestSpecial(inner) + '0'); + i = j + 1; + } + } + + ranges::sort(specials, greater<>()); + return join(specials); + } + + private: + string join(const vector& specials) { + string joined; + for (const string& special : specials) + joined += special; + return joined; + } +}; diff --git a/solutions/761. Special Binary String/761.java b/solutions/761. Special Binary String/761.java new file mode 100644 index 00000000000..e4d2ec709a7 --- /dev/null +++ b/solutions/761. Special Binary String/761.java @@ -0,0 +1,17 @@ +class Solution { + public String makeLargestSpecial(String s) { + List specials = new ArrayList<>(); + int count = 0; + + for (int i = 0, j = 0; j < s.length(); ++j) { + count += s.charAt(j) == '1' ? 1 : -1; + if (count == 0) { + specials.add("1" + makeLargestSpecial(s.substring(i + 1, j)) + "0"); + i = j + 1; + } + } + + Collections.sort(specials, Collections.reverseOrder()); + return String.join("", specials); + } +} diff --git a/solutions/761. Special Binary String/761.py b/solutions/761. Special Binary String/761.py new file mode 100644 index 00000000000..9395b27e14b --- /dev/null +++ b/solutions/761. Special Binary String/761.py @@ -0,0 +1,14 @@ +class Solution: + def makeLargestSpecial(self, s: str) -> str: + specials = [] + count = 0 + + i = 0 + for j, c in enumerate(s): + count += 1 if c == '1' else -1 + if count == 0: + specials.append( + '1' + self.makeLargestSpecial(s[i + 1:j]) + '0') + i = j + 1 + + return ''.join(sorted(specials)[::-1]) diff --git a/solutions/762. Prime Number of Set Bits in Binary Representation/762.cpp b/solutions/762. Prime Number of Set Bits in Binary Representation/762.cpp new file mode 100644 index 00000000000..34443f51681 --- /dev/null +++ b/solutions/762. Prime Number of Set Bits in Binary Representation/762.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int countPrimeSetBits(int left, int right) { + // {2, 3, 5, 7, 11, 13, 17, 19}-th bits are 1s. + // 0b10100010100010101100 = 665772 + constexpr int magic = 665772; + int ans = 0; + + for (unsigned num = left; num <= right; ++num) + if (magic >> popcount(num) & 1) + ++ans; + + return ans; + } +}; diff --git a/solutions/762. Prime Number of Set Bits in Binary Representation/762.java b/solutions/762. Prime Number of Set Bits in Binary Representation/762.java new file mode 100644 index 00000000000..101397c22d9 --- /dev/null +++ b/solutions/762. Prime Number of Set Bits in Binary Representation/762.java @@ -0,0 +1,14 @@ +class Solution { + public int countPrimeSetBits(int left, int right) { + // {2, 3, 5, 7, 11, 13, 17, 19}-th bits are 1s. + // 0b10100010100010101100 = 665772 + final int magic = 665772; + int ans = 0; + + for (int num = left; num <= right; ++num) + if ((magic >> Integer.bitCount(num) & 1) == 1) + ++ans; + + return ans; + } +} diff --git a/solutions/763. Partition Labels/763.cpp b/solutions/763. Partition Labels/763.cpp new file mode 100644 index 00000000000..06315c84c46 --- /dev/null +++ b/solutions/763. Partition Labels/763.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector partitionLabels(string s) { + vector ans; + vector rightmost(26); + + for (int i = 0; i < s.length(); ++i) + rightmost[s[i] - 'a'] = i; + + int l = 0; // the leftmost index of the current running string + int r = 0; // the rightmost index of the current running string + + for (int i = 0; i < s.length(); ++i) { + r = max(r, rightmost[s[i] - 'a']); + if (r == i) { + ans.push_back(i - l + 1); + l = i + 1; + } + } + + return ans; + } +}; diff --git a/solutions/763. Partition Labels/763.java b/solutions/763. Partition Labels/763.java new file mode 100644 index 00000000000..813e3e5a819 --- /dev/null +++ b/solutions/763. Partition Labels/763.java @@ -0,0 +1,22 @@ +class Solution { + public List partitionLabels(String s) { + List ans = new ArrayList<>(); + int[] rightmost = new int[26]; + + for (int i = 0; i < s.length(); ++i) + rightmost[s.charAt(i) - 'a'] = i; + + int l = 0; // the leftmost index of the current running string + int r = 0; // the rightmost index of the current running string + + for (int i = 0; i < s.length(); ++i) { + r = Math.max(r, rightmost[s.charAt(i) - 'a']); + if (r == i) { + ans.add(i - l + 1); + l = i + 1; + } + } + + return ans; + } +} diff --git a/solutions/763. Partition Labels/763.py b/solutions/763. Partition Labels/763.py new file mode 100644 index 00000000000..48f1a27ce6d --- /dev/null +++ b/solutions/763. Partition Labels/763.py @@ -0,0 +1,15 @@ +class Solution: + def partitionLabels(self, s: str) -> List[int]: + ans = [] + letterToRightmostIndex = {c: i for i, c in enumerate(s)} + + l = 0 # the leftmost index of the current running string + r = 0 # the rightmost index of the current running string + + for i, c in enumerate(s): + r = max(r, letterToRightmostIndex[c]) + if i == r: + ans.append(r - l + 1) + l = r + 1 + + return ans diff --git a/solutions/764. Largest Plus Sign/764.cpp b/solutions/764. Largest Plus Sign/764.cpp new file mode 100644 index 00000000000..0750a8015be --- /dev/null +++ b/solutions/764. Largest Plus Sign/764.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int orderOfLargestPlusSign(int n, vector>& mines) { + vector> grid(n, vector(n, n)); + + for (const vector& mine : mines) + grid[mine[0]][mine[1]] = 0; + + // Extend the four directions. If meet 0, need to start over from 0. + for (int i = 0; i < n; ++i) { + for (int j = 0, leftToRight = 0; j < n; ++j) { + leftToRight = (grid[i][j] == 0 ? 0 : leftToRight + 1); + grid[i][j] = min(grid[i][j], leftToRight); + } + for (int j = n - 1, rightToLeft = 0; j >= 0; --j) { + rightToLeft = (grid[i][j] == 0 ? 0 : rightToLeft + 1); + grid[i][j] = min(grid[i][j], rightToLeft); + } + for (int j = 0, upToDown = 0; j < n; ++j) { + upToDown = (grid[j][i] == 0 ? 0 : upToDown + 1); + grid[j][i] = min(grid[j][i], upToDown); + } + for (int j = n - 1, downToUp = 0; j >= 0; --j) { + downToUp = (grid[j][i] == 0) ? 0 : downToUp + 1; + grid[j][i] = min(grid[j][i], downToUp); + } + } + + int ans = 0; + + for (const vector& row : grid) + ans = max(ans, ranges::max(row)); + + return ans; + } +}; diff --git a/solutions/764. Largest Plus Sign/764.java b/solutions/764. Largest Plus Sign/764.java new file mode 100644 index 00000000000..28a54e00960 --- /dev/null +++ b/solutions/764. Largest Plus Sign/764.java @@ -0,0 +1,36 @@ +class Solution { + public int orderOfLargestPlusSign(int n, int[][] mines) { + int[][] grid = new int[n][n]; + Arrays.stream(grid).forEach(row -> Arrays.fill(row, n)); + + for (int[] mine : mines) + grid[mine[0]][mine[1]] = 0; + + // Extend the four directions. If meet 0, need to start over from 0. + for (int i = 0; i < n; ++i) { + for (int j = 0, leftToRight = 0; j < n; ++j) { + leftToRight = (grid[i][j] == 0 ? 0 : leftToRight + 1); + grid[i][j] = Math.min(grid[i][j], leftToRight); + } + for (int j = n - 1, rightToLeft = 0; j >= 0; --j) { + rightToLeft = (grid[i][j] == 0 ? 0 : rightToLeft + 1); + grid[i][j] = Math.min(grid[i][j], rightToLeft); + } + for (int j = 0, upToDown = 0; j < n; ++j) { + upToDown = (grid[j][i] == 0 ? 0 : upToDown + 1); + grid[j][i] = Math.min(grid[j][i], upToDown); + } + for (int j = n - 1, downToUp = 0; j >= 0; --j) { + downToUp = (grid[j][i] == 0) ? 0 : downToUp + 1; + grid[j][i] = Math.min(grid[j][i], downToUp); + } + } + + int ans = 0; + + for (int[] row : grid) + ans = Math.max(ans, Arrays.stream(row).max().getAsInt()); + + return ans; + } +} diff --git a/solutions/765. Couples Holding Hands/765.cpp b/solutions/765. Couples Holding Hands/765.cpp new file mode 100644 index 00000000000..f14402f0a1b --- /dev/null +++ b/solutions/765. Couples Holding Hands/765.cpp @@ -0,0 +1,51 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + int minSwapsCouples(vector& row) { + const int n = row.size() / 2; + UnionFind uf(n); + + for (int i = 0; i < n; ++i) { + const int a = row[2 * i]; + const int b = row[2 * i + 1]; + uf.unionByRank(a / 2, b / 2); + } + + return n - uf.getCount(); + } +}; diff --git a/solutions/765. Couples Holding Hands/765.java b/solutions/765. Couples Holding Hands/765.java new file mode 100644 index 00000000000..92195ec1bab --- /dev/null +++ b/solutions/765. Couples Holding Hands/765.java @@ -0,0 +1,52 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + public int getCount() { + return count; + } + + private int count; + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int minSwapsCouples(int[] row) { + final int n = row.length / 2; + UnionFind uf = new UnionFind(n); + + for (int i = 0; i < n; ++i) { + final int a = row[2 * i]; + final int b = row[2 * i + 1]; + uf.unionByRank(a / 2, b / 2); + } + + return n - uf.getCount(); + } +} diff --git a/solutions/766. Toeplitz Matrix/766-2.cpp b/solutions/766. Toeplitz Matrix/766-2.cpp new file mode 100644 index 00000000000..6afb08bc69c --- /dev/null +++ b/solutions/766. Toeplitz Matrix/766-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool isToeplitzMatrix(vector>& matrix) { + if (matrix.empty()) + return true; + + const int m = matrix.size(); + const int n = matrix[0].size(); + vector buffer(n); + + // Load the row[0] to the buffer. + for (int j = 0; j < n; ++j) + buffer[j] = matrix[0][j]; + + // Roll the array. + for (int i = 1; i < m; ++i) { + for (int j = 0; j + 1 < n; ++j) + if (buffer[j] != matrix[i][j + 1]) + return false; + buffer = matrix[i]; + } + + return true; + } +}; diff --git a/solutions/766. Toeplitz Matrix/766-2.java b/solutions/766. Toeplitz Matrix/766-2.java new file mode 100644 index 00000000000..279cb3d02f6 --- /dev/null +++ b/solutions/766. Toeplitz Matrix/766-2.java @@ -0,0 +1,24 @@ +class Solution { + public boolean isToeplitzMatrix(int[][] matrix) { + if (matrix.length == 0) + return true; + + final int m = matrix.length; + final int n = matrix[0].length; + int[] buffer = new int[n]; + + // Load the row[0] to the buffer. + for (int j = 0; j < n; ++j) + buffer[j] = matrix[0][j]; + + // Roll the array. + for (int i = 1; i < m; ++i) { + for (int j = 0; j + 1 < n; ++j) + if (buffer[j] != matrix[i][j + 1]) + return false; + buffer = matrix[i]; + } + + return true; + } +} diff --git a/solutions/766. Toeplitz Matrix/766.cpp b/solutions/766. Toeplitz Matrix/766.cpp new file mode 100644 index 00000000000..e334254b578 --- /dev/null +++ b/solutions/766. Toeplitz Matrix/766.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + bool isToeplitzMatrix(vector>& matrix) { + for (int i = 0; i + 1 < matrix.size(); ++i) + for (int j = 0; j + 1 < matrix[0].size(); ++j) + if (matrix[i][j] != matrix[i + 1][j + 1]) + return false; + return true; + } +}; diff --git a/solutions/766. Toeplitz Matrix/766.java b/solutions/766. Toeplitz Matrix/766.java new file mode 100644 index 00000000000..4d064c2ec3c --- /dev/null +++ b/solutions/766. Toeplitz Matrix/766.java @@ -0,0 +1,9 @@ +class Solution { + public boolean isToeplitzMatrix(int[][] matrix) { + for (int i = 0; i + 1 < matrix.length; ++i) + for (int j = 0; j + 1 < matrix[0].length; ++j) + if (matrix[i][j] != matrix[i + 1][j + 1]) + return false; + return true; + } +} diff --git a/solutions/766. Toeplitz Matrix/766.py b/solutions/766. Toeplitz Matrix/766.py new file mode 100644 index 00000000000..6ab07441513 --- /dev/null +++ b/solutions/766. Toeplitz Matrix/766.py @@ -0,0 +1,8 @@ +class Solution: + def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: + for i in range(len(matrix) - 1): + for j in range(len(matrix[0]) - 1): + if matrix[i][j] != matrix[i + 1][j + 1]: + return False + + return True diff --git a/solutions/767. Reorganize String/767-2.cpp b/solutions/767. Reorganize String/767-2.cpp new file mode 100644 index 00000000000..2fa187eaa98 --- /dev/null +++ b/solutions/767. Reorganize String/767-2.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + string reorganizeString(string s) { + const int n = s.length(); + vector count(128); + char maxChar = 'a' - 1; + + for (const char c : s) + ++count[c]; + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c] > count[maxChar]) + maxChar = c; + + if (count[maxChar] > (n + 1) / 2) + return ""; + + string ans(n, ' '); + int i = 0; // ans' index + + auto fillIn = [&](char c) { + ans[i] = c; + i += 2; + if (i >= n) + i = 1; + }; + + // Fill in 0, 2, 4, ... indices with `maxCount` letters. + while (count[maxChar]-- > 0) + fillIn(maxChar); + + // Fill in the remaining letters. + for (char c = 'a'; c <= 'z'; ++c) + while (count[c] > 0) { + --count[c]; + fillIn(c); + } + + return ans; + } +}; diff --git a/solutions/767. Reorganize String/767-2.java b/solutions/767. Reorganize String/767-2.java new file mode 100644 index 00000000000..1d2ed19c103 --- /dev/null +++ b/solutions/767. Reorganize String/767-2.java @@ -0,0 +1,41 @@ +class Solution { + public String reorganizeString(String s) { + final int n = s.length(); + int[] count = new int[128]; + char maxChar = 'a' - 1; + + for (final char c : s.toCharArray()) + ++count[c]; + + for (char c = 'a'; c <= 'z'; ++c) + if (count[c] > count[maxChar]) + maxChar = c; + + if (count[maxChar] > (n + 1) / 2) + return ""; + + char[] ans = new char[n]; + + // Fill in 0, 2, 4, ... indices with `maxCount` letters. + while (count[maxChar]-- > 0) + fillIn(ans, maxChar); + + // Fill in the remaining letters. + for (char c = 'a'; c <= 'z'; ++c) + while (count[c] > 0) { + --count[c]; + fillIn(ans, c); + } + + return new String(ans); + } + + private int i = 0; // ans' index + + private void fillIn(char[] ans, char c) { + ans[i] = c; + i += 2; + if (i >= ans.length) + i = 1; + } +} diff --git a/solutions/767. Reorganize String/767-2.py b/solutions/767. Reorganize String/767-2.py new file mode 100644 index 00000000000..454dfd31cb1 --- /dev/null +++ b/solutions/767. Reorganize String/767-2.py @@ -0,0 +1,26 @@ +class Solution: + def reorganizeString(self, s: str) -> str: + n = len(s) + count = collections.Counter(s) + maxCount = max(count.values()) + + if maxCount > (n + 1) // 2: + return '' + + if maxCount == (n + 1) // 2: + maxLetter = max(count, key=count.get) + ans = [maxLetter if i % 2 == 0 else '' for i in range(n)] + del count[maxLetter] + i = 1 + else: + ans = [''] * n + i = 0 + + for c, freq in count.items(): + for _ in range(freq): + ans[i] = c + i += 2 + if i >= n: + i = 1 + + return ''.join(ans) diff --git a/solutions/767. Reorganize String/767.cpp b/solutions/767. Reorganize String/767.cpp new file mode 100644 index 00000000000..4d3786c1bdf --- /dev/null +++ b/solutions/767. Reorganize String/767.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + string reorganizeString(string s) { + unordered_map count; + int maxFreq = 0; + + for (const char c : s) + maxFreq = max(maxFreq, ++count[c]); + + if (maxFreq > (s.length() + 1) / 2) + return ""; + + string ans; + priority_queue> maxHeap; // (freq, c) + int prevFreq = 0; + char prevChar = '@'; + + for (const auto& [c, freq] : count) + maxHeap.emplace(freq, c); + + while (!maxHeap.empty()) { + // Get the letter with the maximum frequency. + const auto [freq, c] = maxHeap.top(); + maxHeap.pop(); + ans += c; + // Add the previous letter back s.t. any two adjacent characters are not + // the same. + if (prevFreq > 0) + maxHeap.emplace(prevFreq, prevChar); + prevFreq = freq - 1; + prevChar = c; + } + + return ans; + } +}; diff --git a/solutions/767. Reorganize String/767.java b/solutions/767. Reorganize String/767.java new file mode 100644 index 00000000000..a9c39355f1d --- /dev/null +++ b/solutions/767. Reorganize String/767.java @@ -0,0 +1,37 @@ +class Solution { + public String reorganizeString(String s) { + Map count = new HashMap<>(); + int maxFreq = 0; + + for (final char c : s.toCharArray()) + maxFreq = Math.max(maxFreq, count.merge(c, 1, Integer::sum)); + + if (maxFreq > (s.length() + 1) / 2) + return ""; + + StringBuilder sb = new StringBuilder(); + // (freq, c) + Queue> maxHeap = + new PriorityQueue<>((a, b) -> b.getKey() - a.getKey()); + int prevFreq = 0; + char prevChar = '@'; + + for (final char c : count.keySet()) + maxHeap.offer(new Pair<>(count.get(c), c)); + + while (!maxHeap.isEmpty()) { + // Get the letter with the maximum frequency. + final int freq = maxHeap.peek().getKey(); + final char c = maxHeap.poll().getValue(); + sb.append(c); + // Add the previous letter back s.t. any two adjacent characters are not + // the same. + if (prevFreq > 0) + maxHeap.offer(new Pair<>(prevFreq, prevChar)); + prevFreq = freq - 1; + prevChar = c; + } + + return sb.toString(); + } +} diff --git a/solutions/767. Reorganize String/767.py b/solutions/767. Reorganize String/767.py new file mode 100644 index 00000000000..330856c76a5 --- /dev/null +++ b/solutions/767. Reorganize String/767.py @@ -0,0 +1,24 @@ +class Solution: + def reorganizeString(self, s: str) -> str: + count = collections.Counter(s) + if max(count.values()) > (len(s) + 1) // 2: + return '' + + ans = [] + maxHeap = [(-freq, c) for c, freq in count.items()] + heapq.heapify(maxHeap) + prevFreq = 0 + prevChar = '@' + + while maxHeap: + # Get the letter with the maximum frequency. + freq, c = heapq.heappop(maxHeap) + ans.append(c) + # Add the previous letter back s.t. any two adjacent characters are not + # the same. + if prevFreq < 0: + heapq.heappush(maxHeap, (prevFreq, prevChar)) + prevFreq = freq + 1 + prevChar = c + + return ''.join(ans) diff --git a/solutions/768. Max Chunks To Make Sorted II/768.cpp b/solutions/768. Max Chunks To Make Sorted II/768.cpp new file mode 100644 index 00000000000..09cb254f151 --- /dev/null +++ b/solutions/768. Max Chunks To Make Sorted II/768.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maxChunksToSorted(vector& arr) { + const int n = arr.size(); + int ans = 0; + vector maxL(n); // l[i] := max(arr[0..i]) + vector minR(n); // r[i] := min(arr[i..n)) + + for (int i = 0; i < n; ++i) + maxL[i] = i == 0 ? arr[i] : max(arr[i], maxL[i - 1]); + + for (int i = n - 1; i >= 0; --i) + minR[i] = i == n - 1 ? arr[i] : min(arr[i], minR[i + 1]); + + for (int i = 0; i + 1 < n; ++i) + if (maxL[i] <= minR[i + 1]) + ++ans; + + return ans + 1; + } +}; diff --git a/solutions/768. Max Chunks To Make Sorted II/768.java b/solutions/768. Max Chunks To Make Sorted II/768.java new file mode 100644 index 00000000000..7edde78a2f4 --- /dev/null +++ b/solutions/768. Max Chunks To Make Sorted II/768.java @@ -0,0 +1,20 @@ +class Solution { + public int maxChunksToSorted(int[] arr) { + final int n = arr.length; + int ans = 0; + int[] maxL = new int[n]; // l[i] := max(arr[0..i]) + int[] minR = new int[n]; // r[i] := min(arr[i..n)) + + for (int i = 0; i < n; ++i) + maxL[i] = i == 0 ? arr[i] : Math.max(arr[i], maxL[i - 1]); + + for (int i = n - 1; i >= 0; --i) + minR[i] = i == n - 1 ? arr[i] : Math.min(arr[i], minR[i + 1]); + + for (int i = 0; i + 1 < n; ++i) + if (maxL[i] <= minR[i + 1]) + ++ans; + + return ans + 1; + } +} diff --git a/solutions/768. Max Chunks To Make Sorted II/768.py b/solutions/768. Max Chunks To Make Sorted II/768.py new file mode 100644 index 00000000000..56b52c6efeb --- /dev/null +++ b/solutions/768. Max Chunks To Make Sorted II/768.py @@ -0,0 +1,16 @@ +class Solution: + def maxChunksToSorted(self, arr: List[int]) -> int: + n = len(arr) + ans = 0 + mx = -math.inf + mn = [arr[-1]] * n + + for i in reversed(range(n - 1)): + mn[i] = min(mn[i + 1], arr[i]) + + for i in range(n - 1): + mx = max(mx, arr[i]) + if mx <= mn[i + 1]: + ans += 1 + + return ans + 1 diff --git a/solutions/769. Max Chunks To Make Sorted/769.cpp b/solutions/769. Max Chunks To Make Sorted/769.cpp new file mode 100644 index 00000000000..10898e970bb --- /dev/null +++ b/solutions/769. Max Chunks To Make Sorted/769.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int maxChunksToSorted(vector& arr) { + int ans = 0; + int mx = INT_MIN; + + for (int i = 0; i < arr.size(); ++i) { + mx = max(mx, arr[i]); + if (mx == i) + ++ans; + } + + return ans; + } +}; diff --git a/solutions/769. Max Chunks To Make Sorted/769.java b/solutions/769. Max Chunks To Make Sorted/769.java new file mode 100644 index 00000000000..1d99d5bfd37 --- /dev/null +++ b/solutions/769. Max Chunks To Make Sorted/769.java @@ -0,0 +1,14 @@ +class Solution { + public int maxChunksToSorted(int[] arr) { + int ans = 0; + int mx = Integer.MIN_VALUE; + + for (int i = 0; i < arr.length; ++i) { + mx = Math.max(mx, arr[i]); + if (mx == i) + ++ans; + } + + return ans; + } +} diff --git a/solutions/769. Max Chunks To Make Sorted/769.py b/solutions/769. Max Chunks To Make Sorted/769.py new file mode 100644 index 00000000000..dff2a620540 --- /dev/null +++ b/solutions/769. Max Chunks To Make Sorted/769.py @@ -0,0 +1,11 @@ +class Solution: + def maxChunksToSorted(self, arr: List[int]) -> int: + ans = 0 + mx = -math.inf + + for i, a in enumerate(arr): + mx = max(mx, a) + if mx == i: + ans += 1 + + return ans diff --git a/solutions/77. Combinations/77.cpp b/solutions/77. Combinations/77.cpp new file mode 100644 index 00000000000..fc90f5ece3e --- /dev/null +++ b/solutions/77. Combinations/77.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector> combine(int n, int k) { + vector> ans; + dfs(n, k, 1, {}, ans); + return ans; + } + + private: + void dfs(int n, int k, int s, vector&& path, vector>& ans) { + if (path.size() == k) { + ans.push_back(path); + return; + } + + for (int i = s; i <= n; ++i) { + path.push_back(i); + dfs(n, k, i + 1, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/77. Combinations/77.java b/solutions/77. Combinations/77.java new file mode 100644 index 00000000000..7ba3964b8e6 --- /dev/null +++ b/solutions/77. Combinations/77.java @@ -0,0 +1,20 @@ +class Solution { + public List> combine(int n, int k) { + List> ans = new ArrayList<>(); + dfs(n, k, 1, new ArrayList<>(), ans); + return ans; + } + + private void dfs(int n, int k, int s, List path, List> ans) { + if (path.size() == k) { + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = s; i <= n; ++i) { + path.add(i); + dfs(n, k, i + 1, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/77. Combinations/77.py b/solutions/77. Combinations/77.py new file mode 100644 index 00000000000..3c182388f9f --- /dev/null +++ b/solutions/77. Combinations/77.py @@ -0,0 +1,16 @@ +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: + ans = [] + + def dfs(s: int, path: List[int]) -> None: + if len(path) == k: + ans.append(path.copy()) + return + + for i in range(s, n + 1): + path.append(i) + dfs(i + 1, path) + path.pop() + + dfs(1, []) + return ans diff --git a/solutions/770. Basic Calculator IV/770.cpp b/solutions/770. Basic Calculator IV/770.cpp new file mode 100644 index 00000000000..341bd0bceb3 --- /dev/null +++ b/solutions/770. Basic Calculator IV/770.cpp @@ -0,0 +1,196 @@ +class Poly { + friend Poly operator+(const Poly& lhs, const Poly& rhs) { + Poly res(lhs); + for (const auto& [term, coef] : rhs.terms) + res.terms[term] += coef; + return res; + } + + friend Poly operator-(const Poly& lhs, const Poly& rhs) { + Poly res(lhs); + for (const auto& [term, coef] : rhs.terms) + res.terms[term] -= coef; + return res; + } + + friend Poly operator*(const Poly& lhs, const Poly& rhs) { + Poly res; + for (const auto& [a, aCoef] : lhs.terms) + for (const auto& [b, bCoef] : rhs.terms) + res.terms[merge(a, b)] += aCoef * bCoef; + return res; + } + + // Friend ostream& operator<<(ostream& os, const Poly& poly) { + // os << "{"; + // for (const auto& [term, coef] : poly.terms) + // os << term << ": " << coef << ", "; + // os << "}"; + // return os; + // } + + public: + vector toList() { + vector res; + vector keys; + for (const auto& [term, _] : terms) + keys.push_back(term); + ranges::sort(keys, [&](const string& a, const string& b) { + // the minimum degree is the last + if (a == "1") + return false; + if (b == "1") + return true; + const vector as = split(a, '*'); + const vector bs = split(b, '*'); + // the maximum degree is the first + // Break ties by their lexicographic orders. + return as.size() == bs.size() ? a < b : as.size() > bs.size(); + }); + auto concat = [&](const string& term) -> string { + if (term == "1") + return to_string(terms[term]); + return to_string(terms[term]) + '*' + term; + }; + for (const string& key : keys) + if (terms[key]) + res.push_back(concat(key)); + return res; + } + + Poly() = default; + Poly(const string& term, int coef) { + terms[term] = coef; + } + + private: + unordered_map terms; + + // e.g. merge("a*b", "a*c") -> "a*a*b*c" + static string merge(const string& a, const string& b) { + if (a == "1") + return b; + if (b == "1") + return a; + string res; + vector A = split(a, '*'); + vector B = split(b, '*'); + int i = 0; // A's index + int j = 0; // B's index + while (i < A.size() && j < B.size()) + if (A[i] < B[j]) + res += '*' + A[i++]; + else + res += '*' + B[j++]; + while (i < A.size()) + res += '*' + A[i++]; + while (j < B.size()) + res += '*' + B[j++]; + return res.substr(1); + } + + static vector split(const string& token, char c) { + vector vars; + istringstream iss(token); + for (string var; getline(iss, var, c);) + vars.push_back(var); + return vars; + } +}; + +class Solution { + public: + vector basicCalculatorIV(string expression, vector& evalvars, + vector& evalints) { + vector tokens = getTokens(expression); + unordered_map evalMap; + + for (int i = 0; i < evalvars.size(); ++i) + evalMap[evalvars[i]] = evalints[i]; + + for (string& token : tokens) + if (const auto it = evalMap.find(token); it != evalMap.cend()) + token = to_string(it->second); + + const vector& postfix = infixToPostfix(tokens); + return evaluate(postfix).toList(); + } + + private: + vector getTokens(const string& s) { + vector tokens; + int i = 0; + for (int j = 0; j < s.length(); ++j) + if (s[j] == ' ') { + if (i < j) + tokens.push_back(s.substr(i, j - i)); + i = j + 1; + } else if (string("()+-*").find(s[j]) != string::npos) { + if (i < j) + tokens.push_back(s.substr(i, j - i)); + tokens.push_back(s.substr(j, 1)); + i = j + 1; + } + if (i < s.length()) + tokens.push_back(s.substr(i)); + return tokens; + } + + bool isOperator(const string& token) { + return token == "+" || token == "-" || token == "*"; + } + + vector infixToPostfix(const vector& tokens) { + vector postfix; + stack ops; + + auto precedes = [](const string& prevOp, const string& currOp) -> bool { + if (prevOp == "(") + return false; + return prevOp == "*" || currOp == "+" || currOp == "-"; + }; + + for (const string& token : tokens) + if (token == "(") { + ops.push(token); + } else if (token == ")") { + while (ops.top() != "(") + postfix.push_back(ops.top()), ops.pop(); + ops.pop(); + } else if (isOperator(token)) { + while (!ops.empty() && precedes(ops.top(), token)) + postfix.push_back(ops.top()), ops.pop(); + ops.push(token); + } else { // isOperand(token) + postfix.push_back(token); + } + + while (!ops.empty()) + postfix.push_back(ops.top()), ops.pop(); + + return postfix; + } + + Poly evaluate(const vector& postfix) { + vector polys; + for (const string& token : postfix) + if (isOperator(token)) { + const Poly b = polys.back(); + polys.pop_back(); + const Poly a = polys.back(); + polys.pop_back(); + if (token == "+") + polys.push_back(a + b); + else if (token == "-") + polys.push_back(a - b); + else // token == "*" + polys.push_back(a * b); + } else if (token[0] == '-' || + ranges::all_of(token, [](char c) { return isdigit(c); })) { + polys.push_back(Poly("1", stoi(token))); + } else { + polys.push_back(Poly(token, 1)); + } + return polys[0]; + } +}; diff --git a/solutions/770. Basic Calculator IV/770.java b/solutions/770. Basic Calculator IV/770.java new file mode 100644 index 00000000000..fd2110dd13b --- /dev/null +++ b/solutions/770. Basic Calculator IV/770.java @@ -0,0 +1,182 @@ +class Poly { + public Poly add(Poly o) { + for (final String term : o.terms.keySet()) + terms.merge(term, o.terms.get(term), Integer::sum); + return this; + } + + public Poly minus(Poly o) { + for (final String term : o.terms.keySet()) + terms.merge(term, -o.terms.get(term), Integer::sum); + return this; + } + + public Poly mult(Poly o) { + Poly res = new Poly(); + for (final String a : terms.keySet()) + for (final String b : o.terms.keySet()) + res.terms.merge(merge(a, b), terms.get(a) * o.terms.get(b), Integer::sum); + return res; + } + + // @Override + // Public String toString() { + // StringBuilder sb = new StringBuilder(); + // sb.append("{"); + // for (final String term : terms.keySet()) + // sb.append(term).append(": ").append(terms.get(term)).append(", "); + // sb.append("}"); + // return sb.toString(); + // } + + public List toList() { + List res = new ArrayList<>(); + List keys = new ArrayList<>(terms.keySet()); + Collections.sort(keys, new Comparator() { + @Override + public int compare(final String a, final String b) { + // the minimum degree is the last + if (a.equals("1")) + return 1; + if (b.equals("1")) + return -1; + String[] as = a.split("\\*"); + String[] bs = b.split("\\*"); + // the maximum degree is the first + // Break ties by their lexicographic orders. + return as.length == bs.length ? a.compareTo(b) : bs.length - as.length; + } + }); + for (final String key : keys) + if (terms.get(key) != 0) + res.add(concat(key)); + return res; + } + + public Poly() {} + public Poly(final String term, int coef) { + terms.put(term, coef); + } + + private Map terms = new HashMap<>(); + + // e.g. merge("a*b", "a*c") -> "a*a*b*c" + private static String merge(final String a, final String b) { + if (a.equals("1")) + return b; + if (b.equals("1")) + return a; + StringBuilder sb = new StringBuilder(); + String[] A = a.split("\\*"); + String[] B = b.split("\\*"); + int i = 0; // A's index + int j = 0; // B's index + while (i < A.length && j < B.length) + if (A[i].compareTo(B[j]) < 0) + sb.append("*").append(A[i++]); + else + sb.append("*").append(B[j++]); + while (i < A.length) + sb.append("*").append(A[i++]); + while (j < B.length) + sb.append("*").append(B[j++]); + return sb.substring(1).toString(); + } + + private String concat(final String term) { + if (term.equals("1")) + return String.valueOf(terms.get(term)); + return new StringBuilder().append(terms.get(term)).append('*').append(term).toString(); + } +} + +class Solution { + public List basicCalculatorIV(String expression, String[] evalvars, int[] evalints) { + List tokens = getTokens(expression); + Map evalMap = new HashMap<>(); + + for (int i = 0; i < evalvars.length; ++i) + evalMap.put(evalvars[i], evalints[i]); + + for (int i = 0; i < tokens.size(); ++i) + if (evalMap.containsKey(tokens.get(i))) + tokens.set(i, String.valueOf(evalMap.get(tokens.get(i)))); + + List postfix = infixToPostfix(tokens); + return evaluate(postfix).toList(); + } + + private List getTokens(final String s) { + List tokens = new ArrayList<>(); + int i = 0; + for (int j = 0; j < s.length(); ++j) + if (s.charAt(j) == ' ') { + if (i < j) + tokens.add(s.substring(i, j)); + i = j + 1; + } else if ("()+-*".contains(s.substring(j, j + 1))) { + if (i < j) + tokens.add(s.substring(i, j)); + tokens.add(s.substring(j, j + 1)); + i = j + 1; + } + if (i < s.length()) + tokens.add(s.substring(i)); + return tokens; + } + + private boolean isOperator(final String token) { + return token.equals("+") || token.equals("-") || token.equals("*"); + } + + private boolean precedes(final String prevOp, final String currOp) { + if (prevOp.equals("(")) + return false; + return prevOp.equals("*") || currOp.equals("+") || currOp.equals("-"); + } + + private List infixToPostfix(List tokens) { + List postfix = new ArrayList<>(); + Deque ops = new ArrayDeque<>(); + + for (final String token : tokens) + if (token.equals("(")) { + ops.push(token); + } else if (token.equals(")")) { + while (!ops.peek().equals("(")) + postfix.add(ops.pop()); + ops.pop(); + } else if (isOperator(token)) { + while (!ops.isEmpty() && precedes(ops.peek(), token)) + postfix.add(ops.pop()); + ops.push(token); + } else { // isOperand(token) + postfix.add(token); + } + + while (!ops.isEmpty()) + postfix.add(ops.pop()); + + return postfix; + } + + private Poly evaluate(List postfix) { + LinkedList polys = new LinkedList<>(); + for (final String token : postfix) + if (isOperator(token)) { + final Poly b = polys.removeLast(); + final Poly a = polys.removeLast(); + if (token.equals("+")) + polys.add(a.add(b)); + else if (token.equals("-")) + polys.add(a.minus(b)); + else // token == "*" + polys.add(a.mult(b)); + } else if (token.charAt(0) == '-' || token.chars().allMatch(c -> Character.isDigit(c))) { + polys.add(new Poly("1", Integer.parseInt(token))); + } else { + polys.add(new Poly(token, 1)); + } + return polys.getFirst(); + } +} diff --git a/solutions/770. Basic Calculator IV/770.py b/solutions/770. Basic Calculator IV/770.py new file mode 100644 index 00000000000..fec4fb5eeec --- /dev/null +++ b/solutions/770. Basic Calculator IV/770.py @@ -0,0 +1,141 @@ +class Poly: + def __init__(self, term: str = None, coef: int = None): + if term and coef: + self.terms = collections.Counter({term: coef}) + else: + self.terms = collections.Counter() + + def __add__(self, other): + for term, coef in other.terms.items(): + self.terms[term] += coef + return self + + def __sub__(self, other): + for term, coef in other.terms.items(): + self.terms[term] -= coef + return self + + def __mul__(self, other): + res = Poly() + for a, aCoef in self.terms.items(): + for b, bCoef in other.terms.items(): + res.terms[self._merge(a, b)] += aCoef * bCoef + return res + + # Def __str__(self): + # res = [] + # for term, coef in self.terms.items(): + # res.append(term + ': ' + str(coef)) + # return '{' + ', '.join(res) + '}' + + def toList(self) -> List[str]: + for term in list(self.terms.keys()): + if not self.terms[term]: + del self.terms[term] + + def cmp(term: str) -> tuple: + # the minimum degree is the last + if term == '1': + return (0,) + var = term.split('*') + # the maximum degree is the first + # Break ties by their lexicographic orders. + return (-len(var), term) + + def concat(term: str) -> str: + if term == '1': + return str(self.terms[term]) + return str(self.terms[term]) + '*' + term + + terms = list(self.terms.keys()) + terms.sort(key=cmp) + return [concat(term) for term in terms] + + def _merge(self, a: str, b: str) -> str: + if a == '1': + return b + if b == '1': + return a + res = [] + A = a.split('*') + B = b.split('*') + i = 0 # A's index + j = 0 # B's index + while i < len(A) and j < len(B): + if A[i] < B[j]: + res.append(A[i]) + i += 1 + else: + res.append(B[j]) + j += 1 + return '*'.join(res + A[i:] + B[j:]) + + +class Solution: + def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]: + tokens = list(self._getTokens(expression)) + evalMap = {a: b for a, b in zip(evalvars, evalints)} + + for i, token in enumerate(tokens): + if token in evalMap: + tokens[i] = str(evalMap[token]) + + postfix = self._infixToPostfix(tokens) + return self._evaluate(postfix).toList() + + def _getTokens(self, s: str) -> Iterator[str]: + i = 0 + for j, c in enumerate(s): + if c == ' ': + if i < j: + yield s[i:j] + i = j + 1 + elif c in '()+-*': + if i < j: + yield s[i:j] + yield c + i = j + 1 + if i < len(s): + yield s[i:] + + def _infixToPostfix(self, tokens: List[str]) -> List[str]: + postfix = [] + ops = [] + + def precedes(prevOp: str, currOp: str) -> bool: + if prevOp == '(': + return False + return prevOp == '*' or currOp in '+-' + + for token in tokens: + if token == '(': + ops.append(token) + elif token == ')': + while ops[-1] != '(': + postfix.append(ops.pop()) + ops.pop() + elif token in '+-*': # isOperator(token) + while ops and precedes(ops[-1], token): + postfix.append(ops.pop()) + ops.append(token) + else: # isOperand(token) + postfix.append(token) + return postfix + ops[::-1] + + def _evaluate(self, postfix: List[str]) -> Poly: + polys: List[Poly] = [] + for token in postfix: + if token in '+-*': + b = polys.pop() + a = polys.pop() + if token == '+': + polys.append(a + b) + elif token == '-': + polys.append(a - b) + else: # token == '*' + polys.append(a * b) + elif token.lstrip('-').isnumeric(): + polys.append(Poly("1", int(token))) + else: + polys.append(Poly(token, 1)) + return polys[0] diff --git a/solutions/771. Jewels and Stones/771.cpp b/solutions/771. Jewels and Stones/771.cpp new file mode 100644 index 00000000000..ba73fbc3e9a --- /dev/null +++ b/solutions/771. Jewels and Stones/771.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int numJewelsInStones(string jewels, string stones) { + int ans = 0; + unordered_set jewelsSet(jewels.begin(), jewels.end()); + + for (const char stone : stones) + if (jewelsSet.contains(stone)) + ++ans; + + return ans; + } +}; diff --git a/solutions/771. Jewels and Stones/771.java b/solutions/771. Jewels and Stones/771.java new file mode 100644 index 00000000000..e1c58352dc4 --- /dev/null +++ b/solutions/771. Jewels and Stones/771.java @@ -0,0 +1,12 @@ +class Solution { + public int numJewelsInStones(String jewels, String stones) { + int ans = 0; + Set jewelsSet = jewels.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); + + for (final char stone : stones.toCharArray()) + if (jewelsSet.contains(stone)) + ++ans; + + return ans; + } +} diff --git a/solutions/771. Jewels and Stones/771.py b/solutions/771. Jewels and Stones/771.py new file mode 100644 index 00000000000..d5087787b4c --- /dev/null +++ b/solutions/771. Jewels and Stones/771.py @@ -0,0 +1,4 @@ +class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + jewelsSet = set(jewels) + return sum(stone in jewelsSet for stone in stones) diff --git a/solutions/772. Basic Calculator III/772.cpp b/solutions/772. Basic Calculator III/772.cpp new file mode 100644 index 00000000000..b98525b9bee --- /dev/null +++ b/solutions/772. Basic Calculator III/772.cpp @@ -0,0 +1,63 @@ +class Solution { + public: + int calculate(string s) { + stack nums; + stack ops; + bool hasPrevNum = false; + + auto calc = [&]() { + const int b = nums.top(); + nums.pop(); + const int a = nums.top(); + nums.pop(); + const char op = ops.top(); + ops.pop(); + if (op == '+') + nums.push(a + b); + else if (op == '-') + nums.push(a - b); + else if (op == '*') + nums.push(a * b); + else // op == '/' + nums.push(a / b); + }; + + for (int i = 0; i < s.length(); ++i) { + const char c = s[i]; + if (isdigit(c)) { + int num = c - '0'; + while (i + 1 < s.length() && isdigit(s[i + 1])) + num = num * 10 + (s[i++ + 1] - '0'); + nums.push(num); + hasPrevNum = true; + } else if (c == '(') { + ops.push('('); + hasPrevNum = false; + } else if (c == ')') { + while (ops.top() != '(') + calc(); + ops.pop(); // Pop '('. + } else if (c == '+' || c == '-' || c == '*' || c == '/') { + if (!hasPrevNum) + nums.push(0); + while (!ops.empty() && precedes(ops.top(), c)) + calc(); + ops.push(c); + } + } + + while (!ops.empty()) + calc(); + + return nums.top(); + } + + private: + // Returns true if the previous character is a operator and the priority of + // the previous operator >= the priority of the current character (operator). + bool precedes(char prev, char curr) { + if (prev == '(') + return false; + return prev == '*' || prev == '/' || curr == '+' || curr == '-'; + } +}; diff --git a/solutions/772. Basic Calculator III/772.java b/solutions/772. Basic Calculator III/772.java new file mode 100644 index 00000000000..954cfab099f --- /dev/null +++ b/solutions/772. Basic Calculator III/772.java @@ -0,0 +1,58 @@ +class Solution { + public int calculate(String s) { + Deque nums = new ArrayDeque<>(); + Deque ops = new ArrayDeque<>(); + boolean hasPrevNum = false; + + for (int i = 0; i < s.length(); ++i) { + final char c = s.charAt(i); + if (Character.isDigit(c)) { + int num = c - '0'; + while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) + num = num * 10 + (s.charAt(i++ + 1) - '0'); + nums.push(num); + hasPrevNum = true; + } else if (c == '(') { + ops.push('('); + hasPrevNum = false; + } else if (c == ')') { + while (ops.peek() != '(') + calc(nums, ops); + ops.pop(); // Pop '('. + } else if (c == '+' || c == '-' || c == '*' || c == '/') { + if (!hasPrevNum) + nums.push(0); + while (!ops.isEmpty() && precedes(ops.peek(), c)) + calc(nums, ops); + ops.push(c); + } + } + + while (!ops.isEmpty()) + calc(nums, ops); + + return nums.peek(); + } + + private void calc(Deque nums, Deque ops) { + final int b = nums.pop(); + final int a = nums.pop(); + final char op = ops.pop(); + if (op == '+') + nums.push(a + b); + else if (op == '-') + nums.push(a - b); + else if (op == '*') + nums.push(a * b); + else // op == '/' + nums.push(a / b); + } + + // Returns true if the previous character is a operator and the priority of + // the previous operator >= the priority of the current character (operator). + private boolean precedes(char prev, char curr) { + if (prev == '(') + return false; + return prev == '*' || prev == '/' || curr == '+' || curr == '-'; + } +} diff --git a/solutions/772. Basic Calculator III/772.py b/solutions/772. Basic Calculator III/772.py new file mode 100644 index 00000000000..82012c2b414 --- /dev/null +++ b/solutions/772. Basic Calculator III/772.py @@ -0,0 +1,58 @@ +class Solution: + def calculate(self, s: str) -> int: + nums = [] + ops = [] + + def calc(): + b = nums.pop() + a = nums.pop() + op = ops.pop() + if op == '+': + nums.append(a + b) + elif op == '-': + nums.append(a - b) + elif op == '*': + nums.append(a * b) + else: # op == '/' + nums.append(int(a / b)) + + def precedes(prev: str, curr: str) -> bool: + """ + Returns True if the previous character is a operator and the priority of + the previous operator >= the priority of the current character (operator). + """ + if prev == '(': + return False + return prev in '*/' or curr in '+-' + + i = 0 + hasPrevNum = False + + while i < len(s): + c = s[i] + if c.isdigit(): + num = ord(c) - ord('0') + while i + 1 < len(s) and s[i + 1].isdigit(): + num = num * 10 + (ord(s[i + 1]) - ord('0')) + i += 1 + nums.append(num) + hasPrevNum = True + elif c == '(': + ops.append('(') + hasPrevNum = False + elif c == ')': + while ops[-1] != '(': + calc() + ops.pop() # Pop '(' + elif c in '+-*/': + if not hasPrevNum: # Handle input like "-1-(-1)" + num.append(0) + while ops and precedes(ops[-1], c): + calc() + ops.append(c) + i += 1 + + while ops: + calc() + + return nums.pop() diff --git a/solutions/773. Sliding Puzzle/773.cpp b/solutions/773. Sliding Puzzle/773.cpp new file mode 100644 index 00000000000..79a19d97e4f --- /dev/null +++ b/solutions/773. Sliding Puzzle/773.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + int slidingPuzzle(vector>& board) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + constexpr int m = 2; + constexpr int n = 3; + const string goal = "123450"; + int steps = 0; + string start; + + // Hash the 2D vector into a string. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + start += '0' + board[i][j]; + + if (start == goal) + return 0; + + queue q{{start}}; + unordered_set seen{start}; + + while (!q.empty()) { + ++steps; + for (int sz = q.size(); sz > 0; --sz) { + string s = q.front(); + q.pop(); + const int zeroIndex = s.find('0'); + const int i = zeroIndex / n; + const int j = zeroIndex % n; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + const int swappedIndex = x * n + y; + swap(s[zeroIndex], s[swappedIndex]); + if (s == goal) + return steps; + if (!seen.contains(s)) { + q.push(s); + seen.insert(s); + } + swap(s[zeroIndex], s[swappedIndex]); + } + } + } + + return -1; + } +}; diff --git a/solutions/773. Sliding Puzzle/773.java b/solutions/773. Sliding Puzzle/773.java new file mode 100644 index 00000000000..81013a8acd7 --- /dev/null +++ b/solutions/773. Sliding Puzzle/773.java @@ -0,0 +1,51 @@ +class Solution { + public int slidingPuzzle(int[][] board) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = 2; + final int n = 3; + final String goal = "123450"; + int steps = 0; + StringBuilder startSb = new StringBuilder(); + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + startSb.append((char) ('0' + board[i][j])); + + final String start = startSb.toString(); + + if (start.equals(goal)) + return 0; + + Queue q = new ArrayDeque<>(Arrays.asList(start)); + Set seen = new HashSet<>(Arrays.asList(start)); + + while (!q.isEmpty()) { + ++steps; + for (int sz = q.size(); sz > 0; --sz) { + final String s = q.poll(); + final int zeroIndex = s.indexOf("0"); + final int i = zeroIndex / n; + final int j = zeroIndex % n; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + final int swappedIndex = x * n + y; + StringBuilder sb = new StringBuilder(s); + sb.setCharAt(zeroIndex, s.charAt(swappedIndex)); + sb.setCharAt(swappedIndex, s.charAt(zeroIndex)); + final String t = sb.toString(); + if (t.equals(goal)) + return steps; + if (!seen.contains(t)) { + q.offer(t); + seen.add(t); + } + } + } + } + + return -1; + } +} diff --git a/solutions/774. Minimize Max Distance to Gas Station/774.cpp b/solutions/774. Minimize Max Distance to Gas Station/774.cpp new file mode 100644 index 00000000000..351877df0db --- /dev/null +++ b/solutions/774. Minimize Max Distance to Gas Station/774.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + double minmaxGasDist(vector& stations, int k) { + constexpr double kErr = 1e-6; + double l = 0; + double r = stations.back() - stations[0]; + + while (r - l > kErr) { + const double m = (l + r) / 2; + if (check(stations, k, m)) + r = m; + else + l = m; + } + + return l; + } + + private: + // Returns true if can use <= k gas stations to ensure that each adjacent + // distance between gas stations <= m. + bool check(const vector& stations, int k, double m) { + for (int i = 1; i < stations.size(); ++i) { + const int diff = stations[i] - stations[i - 1]; + if (diff > m) { + k -= ceil(diff / m) - 1; + if (k < 0) + return false; + } + } + return true; + }; +}; diff --git a/solutions/774. Minimize Max Distance to Gas Station/774.java b/solutions/774. Minimize Max Distance to Gas Station/774.java new file mode 100644 index 00000000000..cc57f3a6588 --- /dev/null +++ b/solutions/774. Minimize Max Distance to Gas Station/774.java @@ -0,0 +1,31 @@ +class Solution { + public double minmaxGasDist(int[] stations, int k) { + final double kErr = 1e-6; + double l = 0; + double r = stations[stations.length - 1] - stations[0]; + + while (r - l > kErr) { + final double m = (l + r) / 2; + if (check(stations, k, m)) + r = m; + else + l = m; + } + + return l; + } + + // Returns true if can use <= k gas stations to ensure that each adjacent + // distance between gas stations <= m. + private boolean check(int[] stations, int k, double m) { + for (int i = 1; i < stations.length; ++i) { + final int diff = stations[i] - stations[i - 1]; + if (diff > m) { + k -= Math.ceil(diff / m) - 1; + if (k < 0) + return false; + } + } + return true; + }; +} diff --git a/solutions/774. Minimize Max Distance to Gas Station/774.py b/solutions/774. Minimize Max Distance to Gas Station/774.py new file mode 100644 index 00000000000..0e430c6e128 --- /dev/null +++ b/solutions/774. Minimize Max Distance to Gas Station/774.py @@ -0,0 +1,27 @@ +class Solution: + def minmaxGasDist(self, stations: List[int], k: int) -> float: + kErr = 1e-6 + l = 0 + r = stations[-1] - stations[0] + + def possible(k: int, m: float) -> bool: + """ + Returns True if can use <= k gas stations to ensure that each adjacent + distance between gas stations <= m. + """ + for a, b in zip(stations, stations[1:]): + diff = b - a + if diff > m: + k -= math.ceil(diff / m) - 1 + if k < 0: + return False + return True + + while r - l > kErr: + m = (l + r) / 2 + if possible(k, m): + r = m + else: + l = m + + return l diff --git a/solutions/775. Global and Local Inversions/775-2.cpp b/solutions/775. Global and Local Inversions/775-2.cpp new file mode 100644 index 00000000000..912e3526a36 --- /dev/null +++ b/solutions/775. Global and Local Inversions/775-2.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + bool isIdealPermutation(vector& nums) { + for (int i = 0; i < nums.size(); ++i) + if (abs(nums[i] - i) > 1) + return false; + return true; + } +}; diff --git a/solutions/775. Global and Local Inversions/775-2.java b/solutions/775. Global and Local Inversions/775-2.java new file mode 100644 index 00000000000..3a5c0ba938c --- /dev/null +++ b/solutions/775. Global and Local Inversions/775-2.java @@ -0,0 +1,8 @@ +class Solution { + public boolean isIdealPermutation(int[] nums) { + for (int i = 0; i < nums.length; ++i) + if (Math.abs(nums[i] - i) > 1) + return false; + return true; + } +} diff --git a/solutions/775. Global and Local Inversions/775-2.py b/solutions/775. Global and Local Inversions/775-2.py new file mode 100644 index 00000000000..938118d8f36 --- /dev/null +++ b/solutions/775. Global and Local Inversions/775-2.py @@ -0,0 +1,6 @@ +class Solution: + def isIdealPermutation(self, nums: List[int]) -> bool: + for i, num in enumerate(nums): + if abs(num - i) > 1: + return False + return True diff --git a/solutions/775. Global and Local Inversions/775.cpp b/solutions/775. Global and Local Inversions/775.cpp new file mode 100644 index 00000000000..f703cb279ca --- /dev/null +++ b/solutions/775. Global and Local Inversions/775.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + bool isIdealPermutation(vector& nums) { + int mx = -1; // the number that is most likely > nums[i + 2] + + for (int i = 0; i + 2 < nums.size(); ++i) { + mx = max(mx, nums[i]); + if (mx > nums[i + 2]) + return false; + } + + return true; + } +}; diff --git a/solutions/775. Global and Local Inversions/775.java b/solutions/775. Global and Local Inversions/775.java new file mode 100644 index 00000000000..1e71ffd4bb3 --- /dev/null +++ b/solutions/775. Global and Local Inversions/775.java @@ -0,0 +1,13 @@ +class Solution { + public boolean isIdealPermutation(int[] nums) { + int mx = -1; // the number that is most likely > nums[i + 2] + + for (int i = 0; i + 2 < nums.length; ++i) { + mx = Math.max(mx, nums[i]); + if (mx > nums[i + 2]) + return false; + } + + return true; + } +} diff --git a/solutions/775. Global and Local Inversions/775.py b/solutions/775. Global and Local Inversions/775.py new file mode 100644 index 00000000000..6655fc1340f --- /dev/null +++ b/solutions/775. Global and Local Inversions/775.py @@ -0,0 +1,10 @@ +class Solution: + def isIdealPermutation(self, nums: List[int]) -> bool: + mx = -1 # the number that is most likely > nums[i + 2] + + for i in range(len(nums) - 2): + mx = max(mx, nums[i]) + if mx > nums[i + 2]: + return False + + return True diff --git a/solutions/776. Split BST/776.cpp b/solutions/776. Split BST/776.cpp new file mode 100644 index 00000000000..5408523a649 --- /dev/null +++ b/solutions/776. Split BST/776.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector splitBST(TreeNode* root, int target) { + if (root == nullptr) + return {nullptr, nullptr}; + if (root->val > target) { + const vector res = splitBST(root->left, target); + root->left = res[1]; + return {res[0], root}; + } else { // root->val <= target + const vector res = splitBST(root->right, target); + root->right = res[0]; + return {root, res[1]}; + } + } +}; diff --git a/solutions/776. Split BST/776.java b/solutions/776. Split BST/776.java new file mode 100644 index 00000000000..f559585d33a --- /dev/null +++ b/solutions/776. Split BST/776.java @@ -0,0 +1,15 @@ +class Solution { + public TreeNode[] splitBST(TreeNode root, int target) { + if (root == null) + return new TreeNode[] {null, null}; + if (root.val > target) { + TreeNode[] res = splitBST(root.left, target); + root.left = res[1]; + return new TreeNode[] {res[0], root}; + } else { // root.val <= target + TreeNode[] res = splitBST(root.right, target); + root.right = res[0]; + return new TreeNode[] {root, res[1]}; + } + } +} diff --git a/solutions/776. Split BST/776.py b/solutions/776. Split BST/776.py new file mode 100644 index 00000000000..e7579cac886 --- /dev/null +++ b/solutions/776. Split BST/776.py @@ -0,0 +1,12 @@ +class Solution: + def splitBST(self, root: Optional[TreeNode], target: int) -> List[Optional[TreeNode]]: + if not root: + return None, None + if root.val > target: + left, right = self.splitBST(root.left, target) + root.left = right + return left, root + else: # root.val <= target + left, right = self.splitBST(root.right, target) + root.right = left + return root, right diff --git a/solutions/777. Swap Adjacent in LR String/777.cpp b/solutions/777. Swap Adjacent in LR String/777.cpp new file mode 100644 index 00000000000..df91398cc0d --- /dev/null +++ b/solutions/777. Swap Adjacent in LR String/777.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + bool canTransform(string start, string end) { + if (removeX(start) != removeX(end)) + return false; + + int i = 0; // start's index + int j = 0; // end's index + + while (i < start.length() && j < end.length()) { + while (i < start.length() && start[i] == 'X') + ++i; + while (j < end.length() && end[j] == 'X') + ++j; + if (i == start.length() && j == end.length()) + return true; + if (i == start.length() || j == end.length()) + return false; + // L can only move to left. + if (start[i] == 'L' && i < j) + return false; + // R can only move to right. + if (start[i] == 'R' && i > j) + return false; + ++i; + ++j; + } + + return true; + } + + private: + string removeX(const string& s) { + string t = s; + std::erase(t, 'X'); + return t; + } +}; diff --git a/solutions/777. Swap Adjacent in LR String/777.java b/solutions/777. Swap Adjacent in LR String/777.java new file mode 100644 index 00000000000..ab38f37c468 --- /dev/null +++ b/solutions/777. Swap Adjacent in LR String/777.java @@ -0,0 +1,30 @@ +class Solution { + public boolean canTransform(String start, String end) { + if (!start.replace("X", "").equals(end.replace("X", ""))) + return false; + + int i = 0; // start's index + int j = 0; // end's index + + while (i < start.length() && j < end.length()) { + while (i < start.length() && start.charAt(i) == 'X') + ++i; + while (j < end.length() && end.charAt(j) == 'X') + ++j; + if (i == start.length() && j == end.length()) + return true; + if (i == start.length() || j == end.length()) + return false; + // L can only move to left. + if (start.charAt(i) == 'L' && i < j) + return false; + // R can only move to right. + if (start.charAt(i) == 'R' && i > j) + return false; + ++i; + ++j; + } + + return true; + } +} diff --git a/solutions/777. Swap Adjacent in LR String/777.py b/solutions/777. Swap Adjacent in LR String/777.py new file mode 100644 index 00000000000..f5525f0a4b3 --- /dev/null +++ b/solutions/777. Swap Adjacent in LR String/777.py @@ -0,0 +1,27 @@ +class Solution: + def canTransform(self, start: str, end: str) -> bool: + if start.replace('X', '') != end.replace('X', ''): + return False + + i = 0 # start's index + j = 0 # end's index + + while i < len(start) and j < len(end): + while i < len(start) and start[i] == 'X': + i += 1 + while j < len(end) and end[j] == 'X': + j += 1 + if i == len(start) and j == len(end): + return True + if i == len(start) or j == len(end): + return False + # L can only move to left. + if start[i] == 'L' and i < j: + return False + # R can only move to right. + if start[i] == 'R' and i > j: + return False + i += 1 + j += 1 + + return True diff --git a/solutions/778. Swim in Rising Water/778.cpp b/solutions/778. Swim in Rising Water/778.cpp new file mode 100644 index 00000000000..6e3ac2a9c48 --- /dev/null +++ b/solutions/778. Swim in Rising Water/778.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int swimInWater(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int n = grid.size(); + int ans = grid[0][0]; + using T = tuple; // (grid[i][j], i, j) + priority_queue, greater<>> minHeap; + vector> seen(n, vector(n)); + + minHeap.emplace(grid[0][0], 0, 0); + seen[0][0] = true; + + while (!minHeap.empty()) { + const auto [height, i, j] = minHeap.top(); + minHeap.pop(); + ans = max(ans, height); + if (i == n - 1 && j == n - 1) + break; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + minHeap.emplace(grid[x][y], x, y); + seen[x][y] = true; + } + } + + return ans; + } +}; diff --git a/solutions/778. Swim in Rising Water/778.java b/solutions/778. Swim in Rising Water/778.java new file mode 100644 index 00000000000..4b26ce9f40d --- /dev/null +++ b/solutions/778. Swim in Rising Water/778.java @@ -0,0 +1,34 @@ +class Solution { + public int swimInWater(int[][] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int n = grid.length; + int ans = grid[0][0]; + // (grid[i][j], i, j) + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + boolean[][] seen = new boolean[n][n]; + + minHeap.offer(new int[] {grid[0][0], 0, 0}); + seen[0][0] = true; + + while (!minHeap.isEmpty()) { + final int height = minHeap.peek()[0]; + final int i = minHeap.peek()[1]; + final int j = minHeap.poll()[2]; + ans = Math.max(ans, height); + if (i == n - 1 && j == n - 1) + break; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (seen[x][y]) + continue; + minHeap.offer(new int[] {grid[x][y], x, y}); + seen[x][y] = true; + } + } + + return ans; + } +} diff --git a/solutions/779. K-th Symbol in Grammar/779.cpp b/solutions/779. K-th Symbol in Grammar/779.cpp new file mode 100644 index 00000000000..1555329dcf3 --- /dev/null +++ b/solutions/779. K-th Symbol in Grammar/779.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int kthGrammar(int n, int k) { + if (n == 1) + return 0; + if (k % 2 == 1) + return kthGrammar(n - 1, (k + 1) / 2) != 0; // the left node + return kthGrammar(n - 1, k / 2) == 0; // the right node + } +}; diff --git a/solutions/779. K-th Symbol in Grammar/779.java b/solutions/779. K-th Symbol in Grammar/779.java new file mode 100644 index 00000000000..206a602df0f --- /dev/null +++ b/solutions/779. K-th Symbol in Grammar/779.java @@ -0,0 +1,9 @@ +class Solution { + public int kthGrammar(int n, int k) { + if (n == 1) + return 0; + if (k % 2 == 1) + return kthGrammar(n - 1, (k + 1) / 2) == 0 ? 0 : 1; // the left node + return kthGrammar(n - 1, k / 2) == 0 ? 1 : 0; // the right node + } +} diff --git a/solutions/78. Subsets/78.cpp b/solutions/78. Subsets/78.cpp new file mode 100644 index 00000000000..a23759c0ef5 --- /dev/null +++ b/solutions/78. Subsets/78.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + vector> subsets(vector& nums) { + vector> ans; + dfs(nums, 0, {}, ans); + return ans; + } + + private: + void dfs(const vector& nums, int s, vector&& path, + vector>& ans) { + ans.push_back(path); + + for (int i = s; i < nums.size(); ++i) { + path.push_back(nums[i]); + dfs(nums, i + 1, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/78. Subsets/78.java b/solutions/78. Subsets/78.java new file mode 100644 index 00000000000..106e12cb1df --- /dev/null +++ b/solutions/78. Subsets/78.java @@ -0,0 +1,17 @@ +class Solution { + public List> subsets(int[] nums) { + List> ans = new ArrayList<>(); + dfs(nums, 0, new ArrayList<>(), ans); + return ans; + } + + private void dfs(int[] nums, int s, List path, List> ans) { + ans.add(new ArrayList<>(path)); + + for (int i = s; i < nums.length; ++i) { + path.add(nums[i]); + dfs(nums, i + 1, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/78. Subsets/78.py b/solutions/78. Subsets/78.py new file mode 100644 index 00000000000..fc1cd0da6bd --- /dev/null +++ b/solutions/78. Subsets/78.py @@ -0,0 +1,12 @@ +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + ans = [] + + def dfs(s: int, path: List[int]) -> None: + ans.append(path) + + for i in range(s, len(nums)): + dfs(i + 1, path + [nums[i]]) + + dfs(0, []) + return ans diff --git a/solutions/780. Reaching Points/780.cpp b/solutions/780. Reaching Points/780.cpp new file mode 100644 index 00000000000..3ffd0f9c2c2 --- /dev/null +++ b/solutions/780. Reaching Points/780.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + bool reachingPoints(int sx, int sy, int tx, int ty) { + while (sx < tx && sy < ty) + if (tx > ty) + tx %= ty; + else + ty %= tx; + + return sx == tx && sy <= ty && (ty - sy) % sx == 0 || + sy == ty && sx <= tx && (tx - sx) % sy == 0; + } +}; diff --git a/solutions/780. Reaching Points/780.java b/solutions/780. Reaching Points/780.java new file mode 100644 index 00000000000..aca5c8b2b97 --- /dev/null +++ b/solutions/780. Reaching Points/780.java @@ -0,0 +1,13 @@ +class Solution { + public boolean reachingPoints(int sx, int sy, int tx, int ty) { + while (sx < tx && sy < ty) + if (tx > ty) + tx %= ty; + else + ty %= tx; + + return // + sx == tx && sy <= ty && (ty - sy) % tx == 0 || // + sy == ty && sx <= tx && (tx - sx) % ty == 0; + } +} diff --git a/solutions/780. Reaching Points/780.py b/solutions/780. Reaching Points/780.py new file mode 100644 index 00000000000..131b6302acc --- /dev/null +++ b/solutions/780. Reaching Points/780.py @@ -0,0 +1,7 @@ +class Solution: + def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: + while sx < tx and sy < ty: + tx, ty = tx % ty, ty % tx + + return sx == tx and sy <= ty and (ty - sy) % tx == 0 or \ + sy == ty and sx <= tx and (tx - sx) % ty == 0 diff --git a/solutions/781. Rabbits in Forest/781.cpp b/solutions/781. Rabbits in Forest/781.cpp new file mode 100644 index 00000000000..f99ec48a4a2 --- /dev/null +++ b/solutions/781. Rabbits in Forest/781.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int numRabbits(vector& answers) { + int ans = 0; + vector count(1000); + + for (const int answer : answers) { + if (count[answer] % (answer + 1) == 0) + ans += answer + 1; + ++count[answer]; + } + + return ans; + } +}; diff --git a/solutions/781. Rabbits in Forest/781.java b/solutions/781. Rabbits in Forest/781.java new file mode 100644 index 00000000000..8e4b4caf5e9 --- /dev/null +++ b/solutions/781. Rabbits in Forest/781.java @@ -0,0 +1,14 @@ +class Solution { + public int numRabbits(int[] answers) { + int ans = 0; + int[] count = new int[1000]; + + for (final int answer : answers) { + if (count[answer] % (answer + 1) == 0) + ans += answer + 1; + ++count[answer]; + } + + return ans; + } +} diff --git a/solutions/781. Rabbits in Forest/781.py b/solutions/781. Rabbits in Forest/781.py new file mode 100644 index 00000000000..5e6d92d8c25 --- /dev/null +++ b/solutions/781. Rabbits in Forest/781.py @@ -0,0 +1,11 @@ +class Solution: + def numRabbits(self, answers: List[int]) -> int: + ans = 0 + count = collections.Counter() + + for answer in answers: + if count[answer] % (answer + 1) == 0: + ans += answer + 1 + count[answer] += 1 + + return ans diff --git a/solutions/782. Transform to Chessboard/782.cpp b/solutions/782. Transform to Chessboard/782.cpp new file mode 100644 index 00000000000..99461bc6e1f --- /dev/null +++ b/solutions/782. Transform to Chessboard/782.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int movesToChessboard(vector>& board) { + const int n = board.size(); + int rowSum = 0; + int colSum = 0; + int rowSwaps = 0; + int colSwaps = 0; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j] == 1) + return -1; + + for (int i = 0; i < n; ++i) { + rowSum += board[0][i]; + colSum += board[i][0]; + } + + if (rowSum != n / 2 && rowSum != (n + 1) / 2) + return -1; + if (colSum != n / 2 && colSum != (n + 1) / 2) + return -1; + + for (int i = 0; i < n; ++i) { + rowSwaps += board[i][0] == (i & 1); + colSwaps += board[0][i] == (i & 1); + } + + if (n % 2 == 1) { + if (rowSwaps % 2 == 1) + rowSwaps = n - rowSwaps; + if (colSwaps % 2 == 1) + colSwaps = n - colSwaps; + } else { + rowSwaps = min(rowSwaps, n - rowSwaps); + colSwaps = min(colSwaps, n - colSwaps); + } + + return (rowSwaps + colSwaps) / 2; + } +}; diff --git a/solutions/782. Transform to Chessboard/782.java b/solutions/782. Transform to Chessboard/782.java new file mode 100644 index 00000000000..d81c7c1a181 --- /dev/null +++ b/solutions/782. Transform to Chessboard/782.java @@ -0,0 +1,43 @@ +class Solution { + public int movesToChessboard(int[][] board) { + final int n = board.length; + int rowSum = 0; + int colSum = 0; + int rowSwaps = 0; + int colSwaps = 0; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if ((board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) == 1) + return -1; + + for (int i = 0; i < n; ++i) { + rowSum += board[0][i]; + colSum += board[i][0]; + } + + if (rowSum != n / 2 && rowSum != (n + 1) / 2) + return -1; + if (colSum != n / 2 && colSum != (n + 1) / 2) + return -1; + + for (int i = 0; i < n; ++i) { + if (board[i][0] == (i & 1)) + ++rowSwaps; + if (board[0][i] == (i & 1)) + ++colSwaps; + } + + if (n % 2 == 1) { + if (rowSwaps % 2 == 1) + rowSwaps = n - rowSwaps; + if (colSwaps % 2 == 1) + colSwaps = n - colSwaps; + } else { + rowSwaps = Math.min(rowSwaps, n - rowSwaps); + colSwaps = Math.min(colSwaps, n - colSwaps); + } + + return (rowSwaps + colSwaps) / 2; + } +} diff --git a/solutions/782. Transform to Chessboard/782.py b/solutions/782. Transform to Chessboard/782.py new file mode 100644 index 00000000000..90552c4ece2 --- /dev/null +++ b/solutions/782. Transform to Chessboard/782.py @@ -0,0 +1,28 @@ +class Solution: + def movesToChessboard(self, board: List[List[int]]) -> int: + n = len(board) + + if any(board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j] for i in range(n) for j in range(n)): + return -1 + + rowSum = sum(board[0]) + colSum = sum(board[i][0] for i in range(n)) + + if rowSum != n // 2 and rowSum != (n + 1) // 2: + return -1 + if colSum != n // 2 and colSum != (n + 1) // 2: + return -1 + + rowSwaps = sum(board[i][0] == (i & 1) for i in range(n)) + colSwaps = sum(board[0][i] == (i & 1) for i in range(n)) + + if n % 2 == 1: + if rowSwaps % 2 == 1: + rowSwaps = n - rowSwaps + if colSwaps % 2 == 1: + colSwaps = n - colSwaps + else: + rowSwaps = min(rowSwaps, n - rowSwaps) + colSwaps = min(colSwaps, n - colSwaps) + + return (rowSwaps + colSwaps) // 2 diff --git a/solutions/783. Minimum Distance Between BST Nodes/783.cpp b/solutions/783. Minimum Distance Between BST Nodes/783.cpp new file mode 100644 index 00000000000..2d091077614 --- /dev/null +++ b/solutions/783. Minimum Distance Between BST Nodes/783.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minDiffInBST(TreeNode* root) { + int ans = INT_MAX; + inorder(root, ans); + return ans; + } + + private: + int pred = -1; + + void inorder(TreeNode* root, int& ans) { + if (root == nullptr) + return; + + inorder(root->left, ans); + if (pred >= 0) + ans = min(ans, root->val - pred); + pred = root->val; + inorder(root->right, ans); + } +}; diff --git a/solutions/783. Minimum Distance Between BST Nodes/783.java b/solutions/783. Minimum Distance Between BST Nodes/783.java new file mode 100644 index 00000000000..061feef31a7 --- /dev/null +++ b/solutions/783. Minimum Distance Between BST Nodes/783.java @@ -0,0 +1,20 @@ +class Solution { + public int minDiffInBST(TreeNode root) { + inorder(root); + return ans; + } + + private int ans = Integer.MAX_VALUE; + private Integer pred = null; + + private void inorder(TreeNode root) { + if (root == null) + return; + + inorder(root.left); + if (pred != null) + ans = Math.min(ans, root.val - pred); + pred = root.val; + inorder(root.right); + } +} diff --git a/solutions/784. Letter Case Permutation/784.cpp b/solutions/784. Letter Case Permutation/784.cpp new file mode 100644 index 00000000000..cc8d22e9fe8 --- /dev/null +++ b/solutions/784. Letter Case Permutation/784.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + vector letterCasePermutation(string s) { + vector ans; + dfs(s, 0, ans); + return ans; + } + + private: + void dfs(string& s, int i, vector& ans) { + if (i == s.length()) { + ans.push_back(s); + return; + } + if (isdigit(s[i])) { + dfs(s, i + 1, ans); + return; + } + + s[i] = tolower(s[i]); + dfs(s, i + 1, ans); + s[i] = toupper(s[i]); + dfs(s, i + 1, ans); + } +}; diff --git a/solutions/784. Letter Case Permutation/784.java b/solutions/784. Letter Case Permutation/784.java new file mode 100644 index 00000000000..2c1bb18df78 --- /dev/null +++ b/solutions/784. Letter Case Permutation/784.java @@ -0,0 +1,23 @@ +class Solution { + public List letterCasePermutation(String s) { + List ans = new ArrayList<>(); + dfs(new StringBuilder(s), 0, ans); + return ans; + } + + private void dfs(StringBuilder sb, int i, List ans) { + if (i == sb.length()) { + ans.add(sb.toString()); + return; + } + if (Character.isDigit(sb.charAt(i))) { + dfs(sb, i + 1, ans); + return; + } + + sb.setCharAt(i, Character.toLowerCase(sb.charAt(i))); + dfs(sb, i + 1, ans); + sb.setCharAt(i, Character.toUpperCase(sb.charAt(i))); + dfs(sb, i + 1, ans); + } +} diff --git a/solutions/785. Is Graph Bipartite?/785-2.cpp b/solutions/785. Is Graph Bipartite?/785-2.cpp new file mode 100644 index 00000000000..3a525a8afac --- /dev/null +++ b/solutions/785. Is Graph Bipartite?/785-2.cpp @@ -0,0 +1,33 @@ +enum class Color { kWhite, kRed, kGreen }; + +class Solution { + public: + bool isBipartite(vector>& graph) { + vector colors(graph.size(), Color::kWhite); + + for (int i = 0; i < graph.size(); ++i) + if (colors[i] == Color::kWhite && + !isValidColor(graph, i, colors, Color::kRed)) + return false; + + return true; + } + + private: + bool isValidColor(const vector>& graph, int u, + vector& colors, Color color) { + // The painted color should be same as `color`. + if (colors[u] != Color::kWhite) + return colors[u] == color; + + colors[u] = Color::kRed; + + // All the children should have valid colors. + for (const int v : graph[u]) + if (!isValidColor(graph, v, colors, + color == Color::kRed ? Color::kGreen : Color::kRed)) + return false; + + return true; + } +}; diff --git a/solutions/785. Is Graph Bipartite?/785-2.java b/solutions/785. Is Graph Bipartite?/785-2.java new file mode 100644 index 00000000000..5f42648ca1f --- /dev/null +++ b/solutions/785. Is Graph Bipartite?/785-2.java @@ -0,0 +1,29 @@ +enum Color { kWhite, kRed, kGreen } + +class Solution { + public boolean isBipartite(int[][] graph) { + Color[] colors = new Color[graph.length]; + Arrays.fill(colors, Color.kWhite); + + for (int i = 0; i < graph.length; ++i) + if (colors[i] == Color.kWhite && !isValidColor(graph, i, colors, Color.kRed)) + return false; + + return true; + } + + private boolean isValidColor(int[][] graph, int u, Color[] colors, Color color) { + // The painted color should be same as `color`. + if (colors[u] != Color.kWhite) + return colors[u] == color; + + colors[u] = color; + + // All the children should have valid colors. + for (final int v : graph[u]) + if (!isValidColor(graph, v, colors, color == Color.kRed ? Color.kGreen : Color.kRed)) + return false; + + return true; + } +} diff --git a/solutions/785. Is Graph Bipartite?/785-2.py b/solutions/785. Is Graph Bipartite?/785-2.py new file mode 100644 index 00000000000..88572786802 --- /dev/null +++ b/solutions/785. Is Graph Bipartite?/785-2.py @@ -0,0 +1,26 @@ +from enum import Enum + + +class Color(Enum): + kWhite = 0 + kRed = 1 + kGreen = 2 + + +class Solution: + def isBipartite(self, graph: List[List[int]]) -> bool: + colors = [Color.kWhite] * len(graph) + + def isValidColor(u: int, color: Color) -> bool: + # The painted color should be same as `color`. + if colors[u] != Color.kWhite: + return colors[u] == color + + colors[u] = color + + # All the children should have valid colors. + childrenColor = Color.kRed if colors[u] == Color.kGreen else Color.kGreen + return all(isValidColor(v, childrenColor) for v in graph[u]) + + return all(colors[i] != Color.kWhite or isValidColor(i, Color.kRed) + for i in range(len(graph))) diff --git a/solutions/785. Is Graph Bipartite?/785.cpp b/solutions/785. Is Graph Bipartite?/785.cpp new file mode 100644 index 00000000000..3659695b937 --- /dev/null +++ b/solutions/785. Is Graph Bipartite?/785.cpp @@ -0,0 +1,32 @@ +enum class Color { kWhite, kRed, kGreen }; + +class Solution { + public: + bool isBipartite(vector>& graph) { + vector colors(graph.size(), Color::kWhite); + + for (int i = 0; i < graph.size(); ++i) { + // This node has been colored, so do nothing. + if (colors[i] != Color::kWhite) + continue; + // Always paint red for a white node. + colors[i] = Color::kRed; + // BFS. + queue q{{i}}; + while (!q.empty()) { + const int u = q.front(); + q.pop(); + for (const int v : graph[u]) { + if (colors[v] == colors[u]) + return false; + if (colors[v] == Color::kWhite) { + colors[v] = colors[u] == Color::kRed ? Color::kGreen : Color::kRed; + q.push(v); + } + } + } + } + + return true; + } +}; diff --git a/solutions/785. Is Graph Bipartite?/785.java b/solutions/785. Is Graph Bipartite?/785.java new file mode 100644 index 00000000000..32d639f94ba --- /dev/null +++ b/solutions/785. Is Graph Bipartite?/785.java @@ -0,0 +1,33 @@ +enum Color { kWhite, kRed, kGreen } + +class Solution { + public boolean isBipartite(int[][] graph) { + Color[] colors = new Color[graph.length]; + Arrays.fill(colors, Color.kWhite); + + for (int i = 0; i < graph.length; ++i) { + // This node has been colored, so do nothing. + if (colors[i] != Color.kWhite) + continue; + // Always paint red for a white node. + colors[i] = Color.kRed; + // BFS. + Queue q = new ArrayDeque<>(Arrays.asList(i)); + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.poll(); + for (final int v : graph[u]) { + if (colors[v] == colors[u]) + return false; + if (colors[v] == Color.kWhite) { + colors[v] = colors[u] == Color.kRed ? Color.kGreen : Color.kRed; + q.offer(v); + } + } + } + } + } + + return true; + } +} diff --git a/solutions/785. Is Graph Bipartite?/785.py b/solutions/785. Is Graph Bipartite?/785.py new file mode 100644 index 00000000000..84e311347bd --- /dev/null +++ b/solutions/785. Is Graph Bipartite?/785.py @@ -0,0 +1,31 @@ +from enum import Enum + + +class Color(Enum): + kWhite = 0 + kRed = 1 + kGreen = 2 + + +class Solution: + def isBipartite(self, graph: List[List[int]]) -> bool: + colors = [Color.kWhite] * len(graph) + + for i in range(len(graph)): + # This node has been colored, so do nothing. + if colors[i] != Color.kWhite: + continue + # Always paint red for a white node. + colors[i] = Color.kRed + # BFS. + q = collections.deque([i]) + while q: + u = q.popleft() + for v in graph[u]: + if colors[v] == colors[u]: + return False + if colors[v] == Color.kWhite: + colors[v] = Color.kRed if colors[u] == Color.kGreen else Color.kGreen + q.append(v) + + return True diff --git a/solutions/786. K-th Smallest Prime Fraction/786.cpp b/solutions/786. K-th Smallest Prime Fraction/786.cpp new file mode 100644 index 00000000000..c844d3f7124 --- /dev/null +++ b/solutions/786. K-th Smallest Prime Fraction/786.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + vector kthSmallestPrimeFraction(vector& arr, int k) { + const int n = arr.size(); + double l = 0.0; + double r = 1.0; + + while (l < r) { + const double m = (l + r) / 2.0; + int fractionsNoGreaterThanM = 0; + int p = 0; + int q = 1; + + // For each index i, find the first index j s.t. arr[i] / arr[j] <= m, + // so fractionsNoGreaterThanM for index i will be n - j. + for (int i = 0, j = 1; i < n; ++i) { + while (j < n && arr[i] > m * arr[j]) + ++j; + if (j == n) + break; + fractionsNoGreaterThanM += n - j; + if (p * arr[j] < q * arr[i]) { + p = arr[i]; + q = arr[j]; + } + } + + if (fractionsNoGreaterThanM == k) + return {p, q}; + if (fractionsNoGreaterThanM > k) + r = m; + else + l = m; + } + + throw; + } +}; diff --git a/solutions/786. K-th Smallest Prime Fraction/786.java b/solutions/786. K-th Smallest Prime Fraction/786.java new file mode 100644 index 00000000000..1f87adee081 --- /dev/null +++ b/solutions/786. K-th Smallest Prime Fraction/786.java @@ -0,0 +1,37 @@ +class Solution { + public int[] kthSmallestPrimeFraction(int[] arr, int k) { + final int n = arr.length; + double l = 0.0; + double r = 1.0; + + while (l < r) { + final double m = (l + r) / 2.0; + int fractionsNoGreaterThanM = 0; + int p = 0; + int q = 1; + + // For each index i, find the first index j s.t. arr[i] / arr[j] <= m, + // so fractionsNoGreaterThanM for index i will be n - j. + for (int i = 0, j = 1; i < n; ++i) { + while (j < n && arr[i] > m * arr[j]) + ++j; + if (j == n) + break; + fractionsNoGreaterThanM += n - j; + if (p * arr[j] < q * arr[i]) { + p = arr[i]; + q = arr[j]; + } + } + + if (fractionsNoGreaterThanM == k) + return new int[] {p, q}; + if (fractionsNoGreaterThanM > k) + r = m; + else + l = m; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/786. K-th Smallest Prime Fraction/786.py b/solutions/786. K-th Smallest Prime Fraction/786.py new file mode 100644 index 00000000000..fc857284622 --- /dev/null +++ b/solutions/786. K-th Smallest Prime Fraction/786.py @@ -0,0 +1,29 @@ +class Solution: + def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: + n = len(arr) + ans = [0, 1] + l = 0 + r = 1 + + while True: + m = (l + r) / 2 + ans[0] = 0 + count = 0 + j = 1 + + for i in range(n): + while j < n and arr[i] > m * arr[j]: + j += 1 + count += n - j + if j == n: + break + if ans[0] * arr[j] < ans[1] * arr[i]: + ans[0] = arr[i] + ans[1] = arr[j] + + if count < k: + l = m + elif count > k: + r = m + else: + return ans diff --git a/solutions/787. Cheapest Flights Within K Stops/787.cpp b/solutions/787. Cheapest Flights Within K Stops/787.cpp new file mode 100644 index 00000000000..4f5a94238eb --- /dev/null +++ b/solutions/787. Cheapest Flights Within K Stops/787.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, + int k) { + vector>> graph(n); + + for (const vector& flight : flights) { + const int u = flight[0]; + const int v = flight[1]; + const int w = flight[2]; + graph[u].emplace_back(v, w); + } + + return dijkstra(graph, src, dst, k); + } + + private: + int dijkstra(const vector>>& graph, int src, int dst, + int k) { + vector> dist(graph.size(), vector(k + 2, INT_MAX)); + using T = tuple; // (d, u, stops) + priority_queue, greater<>> minHeap; + + dist[src][k + 1] = 0; + minHeap.emplace(dist[src][k + 1], src, k + 1); + + while (!minHeap.empty()) { + const auto [d, u, stops] = minHeap.top(); + minHeap.pop(); + if (u == dst) + return d; + if (stops == 0 || d > dist[u][stops]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w < dist[v][stops - 1]) { + dist[v][stops - 1] = d + w; + minHeap.emplace(dist[v][stops - 1], v, stops - 1); + } + } + + return -1; + } +}; diff --git a/solutions/787. Cheapest Flights Within K Stops/787.java b/solutions/787. Cheapest Flights Within K Stops/787.java new file mode 100644 index 00000000000..f56ece42757 --- /dev/null +++ b/solutions/787. Cheapest Flights Within K Stops/787.java @@ -0,0 +1,47 @@ +class Solution { + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + List>[] graph = new List[n]; + + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + for (int[] flight : flights) { + final int u = flight[0]; + final int v = flight[1]; + final int w = flight[2]; + graph[u].add(new Pair<>(v, w)); + } + + return dijkstra(graph, src, dst, k); + } + + private int dijkstra(List>[] graph, int src, int dst, int k) { + int[][] dist = new int[graph.length][k + 2]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + // (d, u, stops) + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + + dist[src][k + 1] = 0; + minHeap.offer(new int[] {dist[src][k + 1], src, k + 1}); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek()[0]; + final int u = minHeap.peek()[1]; + final int stops = minHeap.poll()[2]; + if (u == dst) + return d; + if (stops == 0 || d > dist[u][stops]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w < dist[v][stops - 1]) { + dist[v][stops - 1] = d + w; + minHeap.offer(new int[] {dist[v][stops - 1], v, stops - 1}); + } + } + } + + return -1; + } +} diff --git a/solutions/787. Cheapest Flights Within K Stops/787.py b/solutions/787. Cheapest Flights Within K Stops/787.py new file mode 100644 index 00000000000..cee4b5e7224 --- /dev/null +++ b/solutions/787. Cheapest Flights Within K Stops/787.py @@ -0,0 +1,27 @@ +class Solution: + def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: + graph = [[] for _ in range(n)] + + for u, v, w in flights: + graph[u].append((v, w)) + + return self._dijkstra(graph, src, dst, k) + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int, k: int) -> int: + dist = [[math.inf for _ in range(k + 2)] for _ in range(len(graph))] + + dist[src][k + 1] = 0 + minHeap = [(dist[src][k + 1], src, k + 1)] # (d, u, stops) + + while minHeap: + d, u, stops = heapq.heappop(minHeap) + if u == dst: + return d + if stops == 0 or d > dist[u][stops]: + continue + for v, w in graph[u]: + if d + w < dist[v][stops - 1]: + dist[v][stops - 1] = d + w + heapq.heappush(minHeap, (dist[v][stops - 1], v, stops - 1)) + + return -1 diff --git a/solutions/788. Rotated Digits/788.cpp b/solutions/788. Rotated Digits/788.cpp new file mode 100644 index 00000000000..841c6378df7 --- /dev/null +++ b/solutions/788. Rotated Digits/788.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int rotatedDigits(int n) { + int ans = 0; + + for (int i = 1; i <= n; ++i) + if (isGoodNumber(i)) + ++ans; + + return ans; + } + + private: + bool isGoodNumber(int i) { + bool isRotated = false; + + for (const char c : to_string(i)) { + if (c == '0' || c == '1' || c == '8') + continue; + if (c == '2' || c == '5' || c == '6' || c == '9') + isRotated = true; + else + return false; + } + + return isRotated; + } +}; diff --git a/solutions/788. Rotated Digits/788.java b/solutions/788. Rotated Digits/788.java new file mode 100644 index 00000000000..e7abfcf78cb --- /dev/null +++ b/solutions/788. Rotated Digits/788.java @@ -0,0 +1,26 @@ +class Solution { + public int rotatedDigits(int n) { + int ans = 0; + + for (int i = 1; i <= n; ++i) + if (isGoodNumber(i)) + ++ans; + + return ans; + } + + private boolean isGoodNumber(int i) { + boolean isRotated = false; + + for (final char c : String.valueOf(i).toCharArray()) { + if (c == '0' || c == '1' || c == '8') + continue; + if (c == '2' || c == '5' || c == '6' || c == '9') + isRotated = true; + else + return false; + } + + return isRotated; + } +} diff --git a/solutions/788. Rotated Digits/788.py b/solutions/788. Rotated Digits/788.py new file mode 100644 index 00000000000..e127a737348 --- /dev/null +++ b/solutions/788. Rotated Digits/788.py @@ -0,0 +1,16 @@ +class Solution: + def rotatedDigits(self, n: int) -> int: + def isGoodNumber(i: int) -> bool: + isRotated = False + + for c in str(i): + if c == '0' or c == '1' or c == '8': + continue + if c == '2' or c == '5' or c == '6' or c == '9': + isRotated = True + else: + return False + + return isRotated + + return sum(isGoodNumber(i) for i in range(1, n + 1)) diff --git a/solutions/789. Escape The Ghosts/789.cpp b/solutions/789. Escape The Ghosts/789.cpp new file mode 100644 index 00000000000..d06cc268000 --- /dev/null +++ b/solutions/789. Escape The Ghosts/789.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool escapeGhosts(vector>& ghosts, vector& target) { + const int d = abs(target[0]) + abs(target[1]); + + for (const vector& ghost : ghosts) + if (d >= abs(ghost[0] - target[0]) + abs(ghost[1] - target[1])) + return false; + + return true; + } +}; diff --git a/solutions/789. Escape The Ghosts/789.java b/solutions/789. Escape The Ghosts/789.java new file mode 100644 index 00000000000..b71f868f486 --- /dev/null +++ b/solutions/789. Escape The Ghosts/789.java @@ -0,0 +1,11 @@ +class Solution { + public boolean escapeGhosts(int[][] ghosts, int[] target) { + final int d = Math.abs(target[0]) + Math.abs(target[1]); + + for (int[] ghost : ghosts) + if (d >= Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1])) + return false; + + return true; + } +} diff --git a/solutions/789. Escape The Ghosts/789.py b/solutions/789. Escape The Ghosts/789.py new file mode 100644 index 00000000000..96519f02616 --- /dev/null +++ b/solutions/789. Escape The Ghosts/789.py @@ -0,0 +1,6 @@ +class Solution: + def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: + ghostSteps = min(abs(x - target[0]) + + abs(y - target[1]) for x, y in ghosts) + + return abs(target[0]) + abs(target[1]) < ghostSteps diff --git a/solutions/79. Word Search/79.cpp b/solutions/79. Word Search/79.cpp new file mode 100644 index 00000000000..8460a8692f6 --- /dev/null +++ b/solutions/79. Word Search/79.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + bool exist(vector>& board, string word) { + for (int i = 0; i < board.size(); ++i) + for (int j = 0; j < board[0].size(); ++j) + if (dfs(board, word, i, j, 0)) + return true; + return false; + } + + private: + bool dfs(vector>& board, const string& word, int i, int j, + int s) { + if (i < 0 || i == board.size() || j < 0 || j == board[0].size()) + return false; + if (board[i][j] != word[s] || board[i][j] == '*') + return false; + if (s == word.length() - 1) + return true; + + const char cache = board[i][j]; + board[i][j] = '*'; + const bool isExist = dfs(board, word, i + 1, j, s + 1) || + dfs(board, word, i - 1, j, s + 1) || + dfs(board, word, i, j + 1, s + 1) || + dfs(board, word, i, j - 1, s + 1); + board[i][j] = cache; + + return isExist; + } +}; diff --git a/solutions/79. Word Search/79.java b/solutions/79. Word Search/79.java new file mode 100644 index 00000000000..b86a2761f03 --- /dev/null +++ b/solutions/79. Word Search/79.java @@ -0,0 +1,28 @@ +class Solution { + public boolean exist(char[][] board, String word) { + for (int i = 0; i < board.length; ++i) + for (int j = 0; j < board[0].length; ++j) + if (dfs(board, word, i, j, 0)) + return true; + return false; + } + + private boolean dfs(char[][] board, String word, int i, int j, int s) { + if (i < 0 || i == board.length || j < 0 || j == board[0].length) + return false; + if (board[i][j] != word.charAt(s) || board[i][j] == '*') + return false; + if (s == word.length() - 1) + return true; + + final char cache = board[i][j]; + board[i][j] = '*'; + final boolean isExist = dfs(board, word, i + 1, j, s + 1) || // + dfs(board, word, i - 1, j, s + 1) || // + dfs(board, word, i, j + 1, s + 1) || // + dfs(board, word, i, j - 1, s + 1); + board[i][j] = cache; + + return isExist; + } +} diff --git a/solutions/79. Word Search/79.py b/solutions/79. Word Search/79.py new file mode 100644 index 00000000000..c577941d6d7 --- /dev/null +++ b/solutions/79. Word Search/79.py @@ -0,0 +1,25 @@ +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + m = len(board) + n = len(board[0]) + + def dfs(i: int, j: int, s: int) -> bool: + if i < 0 or i == m or j < 0 or j == n: + return False + if board[i][j] != word[s] or board[i][j] == '*': + return False + if s == len(word) - 1: + return True + + cache = board[i][j] + board[i][j] = '*' + isExist = \ + dfs(i + 1, j, s + 1) or \ + dfs(i - 1, j, s + 1) or \ + dfs(i, j + 1, s + 1) or \ + dfs(i, j - 1, s + 1) + board[i][j] = cache + + return isExist + + return any(dfs(i, j, 0) for i in range(m) for j in range(n)) diff --git a/solutions/790. Domino and Tromino Tiling/790.cpp b/solutions/790. Domino and Tromino Tiling/790.cpp new file mode 100644 index 00000000000..18ee6c5e713 --- /dev/null +++ b/solutions/790. Domino and Tromino Tiling/790.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int numTilings(int n) { + constexpr int kMod = 1'000'000'007; + vector dp(1001); + dp[1] = 1; + dp[2] = 2; + dp[3] = 5; + + for (int i = 4; i <= n; ++i) + dp[i] = (2 * dp[i - 1] + dp[i - 3]) % kMod; + + return dp[n]; + } +}; diff --git a/solutions/790. Domino and Tromino Tiling/790.java b/solutions/790. Domino and Tromino Tiling/790.java new file mode 100644 index 00000000000..277344cfea2 --- /dev/null +++ b/solutions/790. Domino and Tromino Tiling/790.java @@ -0,0 +1,14 @@ +class Solution { + public int numTilings(int n) { + final int kMod = 1_000_000_007; + long[] dp = new long[1001]; + dp[1] = 1; + dp[2] = 2; + dp[3] = 5; + + for (int i = 4; i <= n; ++i) + dp[i] = (2 * dp[i - 1] + dp[i - 3]) % kMod; + + return (int) dp[n]; + } +} diff --git a/solutions/790. Domino and Tromino Tiling/790.py b/solutions/790. Domino and Tromino Tiling/790.py new file mode 100644 index 00000000000..00b49690749 --- /dev/null +++ b/solutions/790. Domino and Tromino Tiling/790.py @@ -0,0 +1,9 @@ +class Solution: + def numTilings(self, n: int) -> int: + kMod = 1_000_000_007 + dp = [0, 1, 2, 5] + [0] * 997 + + for i in range(4, n + 1): + dp[i] = 2 * dp[i - 1] + dp[i - 3] + + return dp[n] % kMod diff --git a/solutions/791. Custom Sort String/791.cpp b/solutions/791. Custom Sort String/791.cpp new file mode 100644 index 00000000000..a43a07d5576 --- /dev/null +++ b/solutions/791. Custom Sort String/791.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string customSortString(string order, string s) { + string ans; + vector count(128); + + for (const char c : s) + ++count[c]; + + for (const char c : order) + while (count[c]-- > 0) + ans += c; + + for (char c = 'a'; c <= 'z'; ++c) + while (count[c]-- > 0) + ans += c; + + return ans; + } +}; diff --git a/solutions/791. Custom Sort String/791.java b/solutions/791. Custom Sort String/791.java new file mode 100644 index 00000000000..7b99488f1dc --- /dev/null +++ b/solutions/791. Custom Sort String/791.java @@ -0,0 +1,19 @@ +class Solution { + public String customSortString(final String order, final String s) { + StringBuilder sb = new StringBuilder(); + int[] count = new int[128]; + + for (final char c : s.toCharArray()) + ++count[c]; + + for (final char c : order.toCharArray()) + while (count[c]-- > 0) + sb.append(c); + + for (char c = 'a'; c <= 'z'; ++c) + while (count[c]-- > 0) + sb.append(c); + + return sb.toString(); + } +} diff --git a/solutions/791. Custom Sort String/791.py b/solutions/791. Custom Sort String/791.py new file mode 100644 index 00000000000..14905a2142f --- /dev/null +++ b/solutions/791. Custom Sort String/791.py @@ -0,0 +1,18 @@ +class Solution: + def customSortString(self, order: str, s: str) -> str: + ans = "" + count = [0] * 26 + + for c in s: + count[ord(c) - ord('a')] += 1 + + for c in order: + while count[ord(c) - ord('a')] > 0: + ans += c + count[ord(c) - ord('a')] -= 1 + + for c in string.ascii_lowercase: + for _ in range(count[ord(c) - ord('a')]): + ans += c + + return ans diff --git a/solutions/792. Number of Matching Subsequences/792-2.cpp b/solutions/792. Number of Matching Subsequences/792-2.cpp new file mode 100644 index 00000000000..fedb18f0811 --- /dev/null +++ b/solutions/792. Number of Matching Subsequences/792-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int numMatchingSubseq(string s, vector& words) { + int ans = 0; + // [(i, j)] := words[i] and the letter words[i][j] is waiting for + vector>> bucket(26); + + // For each word, it's waiting for word[0]. + for (int i = 0; i < words.size(); ++i) + bucket[words[i][0] - 'a'].emplace_back(i, 0); + + for (const char c : s) { + // Let prevBucket = bucket[c] and clear bucket[c]. + vector> prevBucket; + swap(prevBucket, bucket[c - 'a']); + for (auto& [i, j] : prevBucket) + // All the letters in words[i] are matched. + if (++j == words[i].length()) + ++ans; + else + bucket[words[i][j] - 'a'].emplace_back(i, j); + } + + return ans; + } +}; diff --git a/solutions/792. Number of Matching Subsequences/792-2.java b/solutions/792. Number of Matching Subsequences/792-2.java new file mode 100644 index 00000000000..0c36a552266 --- /dev/null +++ b/solutions/792. Number of Matching Subsequences/792-2.java @@ -0,0 +1,31 @@ +class Solution { + public int numMatchingSubseq(String s, String[] words) { + int ans = 0; + // [(i, j)] := words[i] and the letter words[i][j] is waiting for + List>[] bucket = new List[26]; + + for (int i = 0; i < 26; ++i) + bucket[i] = new ArrayList<>(); + + // For each word, it's waiting for word[0]. + for (int i = 0; i < words.length; ++i) + bucket[words[i].charAt(0) - 'a'].add(new Pair<>(i, 0)); + + for (final char c : s.toCharArray()) { + // Let prevBucket = bucket[c] and clear bucket[c]. + List> prevBucket = bucket[c - 'a']; + bucket[c - 'a'] = new ArrayList<>(); + for (Pair pair : prevBucket) { + final int i = pair.getKey(); + final int j = pair.getValue() + 1; + // All the letters in words[i] are matched. + if (j == words[i].length()) + ++ans; + else + bucket[words[i].charAt(j) - 'a'].add(new Pair<>(i, j)); + } + } + + return ans; + } +} diff --git a/solutions/792. Number of Matching Subsequences/792-2.py b/solutions/792. Number of Matching Subsequences/792-2.py new file mode 100644 index 00000000000..cb96e689fe1 --- /dev/null +++ b/solutions/792. Number of Matching Subsequences/792-2.py @@ -0,0 +1,23 @@ +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + ans = 0 + # [(i, j)] := words[i] and the letter words[i][j] is waiting for + bucket = [[] for _ in range(26)] + + # For each word, it's waiting for word[0]. + for i, word in enumerate(words): + bucket[ord(word[0]) - ord('a')].append((i, 0)) + + for c in s: + # Let prevBucket = bucket[c] and clear bucket[c]. + index = ord(c) - ord('a') + prevBucket = bucket[index] + bucket[index] = [] + for i, j in prevBucket: + j += 1 + if j == len(words[i]): # All the letters in words[i] are matched. + ans += 1 + else: + bucket[ord(words[i][j]) - ord('a')].append((i, j)) + + return ans diff --git a/solutions/792. Number of Matching Subsequences/792.cpp b/solutions/792. Number of Matching Subsequences/792.cpp new file mode 100644 index 00000000000..5d9abc5c292 --- /dev/null +++ b/solutions/792. Number of Matching Subsequences/792.cpp @@ -0,0 +1,43 @@ +struct TrieNode { + vector> children; + int count = 0; + TrieNode() : children(26) {} +}; + +class Solution { + public: + int numMatchingSubseq(string s, vector& words) { + for (const string& word : words) + insert(word); + return dfs(s, 0, root); + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + ++node->count; + } + + int dfs(const string& s, int i, shared_ptr node) { + int ans = node->count; + if (i >= s.length()) + return ans; + + for (int j = 0; j < 26; ++j) + if (node->children[j]) { + const int index = s.find('a' + j, i); + if (index != -1) + ans += dfs(s, index + 1, node->children[j]); + } + + return ans; + } +}; diff --git a/solutions/792. Number of Matching Subsequences/792.java b/solutions/792. Number of Matching Subsequences/792.java new file mode 100644 index 00000000000..f8fe4b2afaa --- /dev/null +++ b/solutions/792. Number of Matching Subsequences/792.java @@ -0,0 +1,40 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int count = 0; +} + +class Solution { + public int numMatchingSubseq(String s, String[] words) { + for (final String word : words) + insert(word); + return dfs(s, 0, root); + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + ++node.count; + } + + private int dfs(final String s, int i, TrieNode node) { + int ans = node.count; + if (i >= s.length()) + return ans; + + for (int j = 0; j < 26; ++j) + if (node.children[j] != null) { + final int index = s.indexOf('a' + j, i); + if (index != -1) + ans += dfs(s, index + 1, node.children[j]); + } + + return ans; + } +} diff --git a/solutions/792. Number of Matching Subsequences/792.py b/solutions/792. Number of Matching Subsequences/792.py new file mode 100644 index 00000000000..32e7e18199a --- /dev/null +++ b/solutions/792. Number of Matching Subsequences/792.py @@ -0,0 +1,32 @@ +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + root = {} + + def insert(word: str) -> None: + node = root + for c in word: + if c not in node: + node[c] = {'count': 0} + node = node[c] + node['count'] += 1 + + for word in words: + insert(word) + + def dfs(s: str, i: int, node: dict) -> int: + ans = node['count'] if 'count' in node else 0 + + if i >= len(s): + return ans + + for c in string.ascii_lowercase: + if c in node: + try: + index = s.index(c, i) + ans += dfs(s, index + 1, node[c]) + except ValueError: + continue + + return ans + + return dfs(s, 0, root) diff --git a/solutions/793. Preimage Size of Factorial Zeroes Function/793.cpp b/solutions/793. Preimage Size of Factorial Zeroes Function/793.cpp new file mode 100644 index 00000000000..950039c113b --- /dev/null +++ b/solutions/793. Preimage Size of Factorial Zeroes Function/793.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + int preimageSizeFZF(int k) { + long l = 0; + long r = 5L * k; + + while (l < r) { + const long m = (l + r) / 2; + if (trailingZeroes(m) >= k) + r = m; + else + l = m + 1; + } + + return trailingZeroes(l) == k ? 5 : 0; + } + + private: + // Same as 172. Factorial Trailing Zeroes + int trailingZeroes(long n) { + return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); + } +}; diff --git a/solutions/793. Preimage Size of Factorial Zeroes Function/793.java b/solutions/793. Preimage Size of Factorial Zeroes Function/793.java new file mode 100644 index 00000000000..af2dc38dd58 --- /dev/null +++ b/solutions/793. Preimage Size of Factorial Zeroes Function/793.java @@ -0,0 +1,21 @@ +class Solution { + public int preimageSizeFZF(int k) { + long l = 0; + long r = 5 * (long) k; + + while (l < r) { + final long m = (l + r) / 2; + if (trailingZeroes(m) >= k) + r = m; + else + l = m + 1; + } + + return trailingZeroes(l) == k ? 5 : 0; + } + + // Same as 172. Factorial Trailing Zeroes + private int trailingZeroes(long n) { + return n == 0 ? 0 : (int) (n / 5 + trailingZeroes(n / 5)); + } +} diff --git a/solutions/794. Valid Tic-Tac-Toe State/794.cpp b/solutions/794. Valid Tic-Tac-Toe State/794.cpp new file mode 100644 index 00000000000..eecd683a0d2 --- /dev/null +++ b/solutions/794. Valid Tic-Tac-Toe State/794.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + bool validTicTacToe(vector& board) { + const int countX = sum(board, 'X'); + const int countO = sum(board, 'O'); + + if (countX < countO || countX - countO > 1) + return false; + if (isWinned(board, 'X') && countX == countO || + isWinned(board, 'O') && countX != countO) + return false; + + return true; + } + + private: + int sum(const vector& board, char c) { + int ans = 0; + + for (const string& row : board) + ans += ranges::count(row, c); + + return ans; + } + + bool isWinned(const vector& board, char c) { + vector rotated = rotate(board); + + auto equalsToThree = [&c](const string& row) { + return ranges::count(row, c) == 3; + }; + + return ranges::any_of(board, equalsToThree) || + ranges::any_of(rotated, equalsToThree) || + board[0][0] == c && board[1][1] == c && board[2][2] == c || + board[0][2] == c && board[1][1] == c && board[2][0] == c; + } + + vector rotate(const vector& board) { + vector rotated(3); + + for (const string& row : board) + for (int i = 0; i < 3; ++i) + rotated[i].push_back(row[i]); + + return rotated; + } +}; diff --git a/solutions/794. Valid Tic-Tac-Toe State/794.java b/solutions/794. Valid Tic-Tac-Toe State/794.java new file mode 100644 index 00000000000..c12a73e3c06 --- /dev/null +++ b/solutions/794. Valid Tic-Tac-Toe State/794.java @@ -0,0 +1,42 @@ +class Solution { + public boolean validTicTacToe(String[] board) { + final int countX = sum(board, 'X'); + final int countO = sum(board, 'O'); + + if (countX < countO || countX - countO > 1) + return false; + if (isWinned(board, 'X') && countX == countO || // + isWinned(board, 'O') && countX != countO) + return false; + + return true; + } + + private int sum(final String[] board, char c) { + int ans = 0; + + for (final String row : board) + ans += row.chars().filter(i -> i == c).count(); + + return ans; + } + + private boolean isWinned(final String[] board, char c) { + String[] rotated = rotate(board); + + return Arrays.stream(board).anyMatch(row -> row.chars().filter(i -> i == c).count() == 3) || + Arrays.stream(rotated).anyMatch(row -> row.chars().filter(i -> i == c).count() == 3) || + board[0].charAt(0) == c && board[1].charAt(1) == c && board[2].charAt(2) == c || + board[0].charAt(2) == c && board[1].charAt(1) == c && board[2].charAt(0) == c; + } + + private String[] rotate(final String[] board) { + String[] rotated = new String[3]; + + for (final String row : board) + for (int i = 0; i < 3; ++i) + rotated[i] += row.charAt(i); + + return rotated; + } +} diff --git a/solutions/794. Valid Tic-Tac-Toe State/794.py b/solutions/794. Valid Tic-Tac-Toe State/794.py new file mode 100644 index 00000000000..332d3597d4b --- /dev/null +++ b/solutions/794. Valid Tic-Tac-Toe State/794.py @@ -0,0 +1,17 @@ +class Solution: + def validTicTacToe(self, board: List[str]) -> bool: + def isWin(c: str) -> bool: + return any(row.count(c) == 3 for row in board) or \ + any(row.count(c) == 3 for row in list(zip(*board))) or \ + all(board[i][i] == c for i in range(3)) or \ + all(board[i][2 - i] == c for i in range(3)) + + countX = sum(row.count('X') for row in board) + countO = sum(row.count('O') for row in board) + + if countX < countO or countX - countO > 1: + return False + if isWin('X') and countX == countO or isWin('O') and countX != countO: + return False + + return True diff --git a/solutions/795. Number of Subarrays with Bounded Maximum/795.cpp b/solutions/795. Number of Subarrays with Bounded Maximum/795.cpp new file mode 100644 index 00000000000..97307a71534 --- /dev/null +++ b/solutions/795. Number of Subarrays with Bounded Maximum/795.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int numSubarrayBoundedMax(vector& nums, int left, int right) { + int ans = 0; + int l = -1; + int r = -1; + + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] > right) // Handle the reset value. + l = i; + if (nums[i] >= left) // Handle the reset and the needed value. + r = i; + ans += r - l; + } + + return ans; + } +}; diff --git a/solutions/795. Number of Subarrays with Bounded Maximum/795.java b/solutions/795. Number of Subarrays with Bounded Maximum/795.java new file mode 100644 index 00000000000..73eeb0e3087 --- /dev/null +++ b/solutions/795. Number of Subarrays with Bounded Maximum/795.java @@ -0,0 +1,17 @@ +class Solution { + public int numSubarrayBoundedMax(int[] nums, int left, int right) { + int ans = 0; + int l = -1; + int r = -1; + + for (int i = 0; i < nums.length; ++i) { + if (nums[i] > right) // Handle the reset value. + l = i; + if (nums[i] >= left) // Handle the reset and the needed value. + r = i; + ans += r - l; + } + + return ans; + } +} diff --git a/solutions/795. Number of Subarrays with Bounded Maximum/795.py b/solutions/795. Number of Subarrays with Bounded Maximum/795.py new file mode 100644 index 00000000000..169bde7406a --- /dev/null +++ b/solutions/795. Number of Subarrays with Bounded Maximum/795.py @@ -0,0 +1,14 @@ +class Solution: + def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: + ans = 0 + l = -1 + r = -1 + + for i, num in enumerate(nums): + if num > right: # Handle the reset value. + l = i + if num >= left: # Handle the reset and the needed value. + r = i + ans += r - l + + return ans diff --git a/solutions/796. Rotate String/796.cpp b/solutions/796. Rotate String/796.cpp new file mode 100644 index 00000000000..215e350bee3 --- /dev/null +++ b/solutions/796. Rotate String/796.cpp @@ -0,0 +1,6 @@ +class Solution { + public: + bool rotateString(string s, string goal) { + return s.length() == goal.length() && (s + s).find(goal) != string::npos; + } +}; diff --git a/solutions/796. Rotate String/796.java b/solutions/796. Rotate String/796.java new file mode 100644 index 00000000000..51491db1668 --- /dev/null +++ b/solutions/796. Rotate String/796.java @@ -0,0 +1,5 @@ +class Solution { + public boolean rotateString(String s, String goal) { + return s.length() == goal.length() && (s + s).contains(goal); + } +} diff --git a/solutions/796. Rotate String/796.py b/solutions/796. Rotate String/796.py new file mode 100644 index 00000000000..404a66e6f8d --- /dev/null +++ b/solutions/796. Rotate String/796.py @@ -0,0 +1,3 @@ +class Solution: + def rotateString(self, s: str, goal: str) -> bool: + return len(s) == len(goal) and goal in s + s diff --git a/solutions/797. All Paths From Source to Target/797.cpp b/solutions/797. All Paths From Source to Target/797.cpp new file mode 100644 index 00000000000..323c1e958b7 --- /dev/null +++ b/solutions/797. All Paths From Source to Target/797.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector> allPathsSourceTarget(vector>& graph) { + vector> ans; + dfs(graph, 0, {0}, ans); + return ans; + } + + private: + void dfs(const vector>& graph, int u, vector&& path, + vector>& ans) { + if (u == graph.size() - 1) { + ans.push_back(path); + return; + } + + for (const int v : graph[u]) { + path.push_back(v); + dfs(graph, v, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/797. All Paths From Source to Target/797.java b/solutions/797. All Paths From Source to Target/797.java new file mode 100644 index 00000000000..a9e3fbea893 --- /dev/null +++ b/solutions/797. All Paths From Source to Target/797.java @@ -0,0 +1,20 @@ +class Solution { + public List> allPathsSourceTarget(int[][] graph) { + List> ans = new ArrayList<>(); + dfs(graph, 0, new ArrayList<>(Arrays.asList(0)), ans); + return ans; + } + + private void dfs(int[][] graph, int u, List path, List> ans) { + if (u == graph.length - 1) { + ans.add(new ArrayList<>(path)); + return; + } + + for (final int v : graph[u]) { + path.add(v); + dfs(graph, v, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/797. All Paths From Source to Target/797.py b/solutions/797. All Paths From Source to Target/797.py new file mode 100644 index 00000000000..ee36509afd0 --- /dev/null +++ b/solutions/797. All Paths From Source to Target/797.py @@ -0,0 +1,14 @@ +class Solution: + def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: + ans = [] + + def dfs(u: int, path: List[int]) -> None: + if u == len(graph) - 1: + ans.append(path) + return + + for v in graph[u]: + dfs(v, path + [v]) + + dfs(0, [0]) + return ans diff --git a/solutions/798. Smallest Rotation with Highest Score/798.cpp b/solutions/798. Smallest Rotation with Highest Score/798.cpp new file mode 100644 index 00000000000..6fb690d02b7 --- /dev/null +++ b/solutions/798. Smallest Rotation with Highest Score/798.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int bestRotation(vector& nums) { + const int n = nums.size(); + // rotate[i] := the number of points lost after rotating left i times + vector rotate(n); + + // Rotating i - nums[i] times makes nums[i] == its new index. + // So, rotating i - nums[i] + 1 times will "start" to make nums[i] > its + // index, which is the starting index to lose point. + for (int i = 0; i < n; ++i) + --rotate[(i - nums[i] + 1 + n) % n]; + + // Each time of the rotation, make index 0 to index n - 1 to get 1 point. + for (int i = 1; i < n; ++i) + rotate[i] += rotate[i - 1] + 1; + + return distance(rotate.begin(), ranges::max_element(rotate)); + } +}; diff --git a/solutions/798. Smallest Rotation with Highest Score/798.java b/solutions/798. Smallest Rotation with Highest Score/798.java new file mode 100644 index 00000000000..f39ab72ae01 --- /dev/null +++ b/solutions/798. Smallest Rotation with Highest Score/798.java @@ -0,0 +1,28 @@ +class Solution { + public int bestRotation(int[] nums) { + final int n = nums.length; + // rotate[i] := the number of points lost after rotating left i times + int[] rotate = new int[n]; + + // Rotating i - nums[i] times makes nums[i] == its new index. + // So, rotating i - nums[i] + 1 times will "start" to make nums[i] > its + // index, which is the starting index to lose point. + for (int i = 0; i < n; ++i) + --rotate[(i - nums[i] + 1 + n) % n]; + + // Each time of the rotation, make index 0 to index n - 1 to get 1 point. + for (int i = 1; i < n; ++i) + rotate[i] += rotate[i - 1] + 1; + + int mx = Integer.MIN_VnumsLUE; + int maxIndex = 0; + + for (int i = 0; i < n; ++i) + if (rotate[i] > mx) { + mx = rotate[i]; + maxIndex = i; + } + + return maxIndex; + } +} diff --git a/solutions/799. Champagne Tower/799-2.cpp b/solutions/799. Champagne Tower/799-2.cpp new file mode 100644 index 00000000000..51f0b78d73f --- /dev/null +++ b/solutions/799. Champagne Tower/799-2.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + double champagneTower(int poured, int query_row, int query_glass) { + vector dp(query_row + 1); + dp[0] = poured; + + for (int i = 0; i < query_row; ++i) { + vector newDp(query_row + 1); + for (int j = 0; j <= i; ++j) + if (dp[j] > 1) { + newDp[j] += (dp[j] - 1) / 2.0; + newDp[j + 1] += (dp[j] - 1) / 2.0; + } + dp = move(newDp); + } + + return min(1.0, dp[query_glass]); + } +}; diff --git a/solutions/799. Champagne Tower/799-2.java b/solutions/799. Champagne Tower/799-2.java new file mode 100644 index 00000000000..b589dd1058e --- /dev/null +++ b/solutions/799. Champagne Tower/799-2.java @@ -0,0 +1,18 @@ +class Solution { + public double champagneTower(int poured, int query_row, int query_glass) { + double[] dp = new double[query_row + 1]; + dp[0] = poured; + + for (int i = 0; i < query_row; ++i) { + double[] newDp = new double[query_row + 1]; + for (int j = 0; j <= i; ++j) + if (dp[j] > 1) { + newDp[j] += (dp[j] - 1) / 2.0; + newDp[j + 1] += (dp[j] - 1) / 2.0; + } + dp = newDp; + } + + return Math.min(1.0, dp[query_glass]); + } +} diff --git a/solutions/799. Champagne Tower/799.cpp b/solutions/799. Champagne Tower/799.cpp new file mode 100644 index 00000000000..853a2b5084c --- /dev/null +++ b/solutions/799. Champagne Tower/799.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + double champagneTower(int poured, int query_row, int query_glass) { + vector> dp(query_row + 1, vector(query_row + 1)); + dp[0][0] = poured; + + for (int i = 0; i < query_row; ++i) + for (int j = 0; j <= i; ++j) + if (dp[i][j] > 1) { + dp[i + 1][j] += (dp[i][j] - 1) / 2.0; + dp[i + 1][j + 1] += (dp[i][j] - 1) / 2.0; + } + + return min(1.0, dp[query_row][query_glass]); + } +}; diff --git a/solutions/799. Champagne Tower/799.java b/solutions/799. Champagne Tower/799.java new file mode 100644 index 00000000000..95b04a28501 --- /dev/null +++ b/solutions/799. Champagne Tower/799.java @@ -0,0 +1,15 @@ +class Solution { + public double champagneTower(int poured, int query_row, int query_glass) { + double[][] dp = new double[query_row + 1][query_row + 1]; + dp[0][0] = poured; + + for (int i = 0; i < query_row; ++i) + for (int j = 0; j <= i; ++j) + if (dp[i][j] > 1) { + dp[i + 1][j] += (dp[i][j] - 1) / 2.0; + dp[i + 1][j + 1] += (dp[i][j] - 1) / 2.0; + } + + return Math.min(1.0, dp[query_row][query_glass]); + } +} diff --git a/solutions/8. String to Integer (atoi)/8.cpp b/solutions/8. String to Integer (atoi)/8.cpp new file mode 100644 index 00000000000..21f1a223f72 --- /dev/null +++ b/solutions/8. String to Integer (atoi)/8.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + int myAtoi(string s) { + trim(s); + if (s.empty()) + return 0; + + const int sign = s[0] == '-' ? -1 : 1; + if (s[0] == '+' || s[0] == '-') + s = s.substr(1); + + long num = 0; + + for (const char c : s) { + if (!isdigit(c)) + break; + num = num * 10 + (c - '0'); + if (sign * num < INT_MIN) + return INT_MIN; + if (sign * num > INT_MAX) + return INT_MAX; + } + + return sign * num; + } + + private: + void trim(string& s) { + s.erase(0, s.find_first_not_of(' ')); + s.erase(s.find_last_not_of(' ') + 1); + } +}; diff --git a/solutions/8. String to Integer (atoi)/8.java b/solutions/8. String to Integer (atoi)/8.java new file mode 100644 index 00000000000..1eb01a98cca --- /dev/null +++ b/solutions/8. String to Integer (atoi)/8.java @@ -0,0 +1,25 @@ +class Solution { + public int myAtoi(String s) { + s = s.strip(); + if (s.isEmpty()) + return 0; + + final int sign = s.charAt(0) == '-' ? -1 : 1; + if (s.charAt(0) == '+' || s.charAt(0) == '-') + s = s.substring(1); + + long num = 0; + + for (final char c : s.toCharArray()) { + if (!Character.isDigit(c)) + break; + num = num * 10 + (c - '0'); + if (sign * num <= Integer.MIN_VALUE) + return Integer.MIN_VALUE; + if (sign * num >= Integer.MAX_VALUE) + return Integer.MAX_VALUE; + } + + return sign * (int) num; + } +} diff --git a/solutions/8. String to Integer (atoi)/8.py b/solutions/8. String to Integer (atoi)/8.py new file mode 100644 index 00000000000..7f79c33f428 --- /dev/null +++ b/solutions/8. String to Integer (atoi)/8.py @@ -0,0 +1,22 @@ +class Solution: + def myAtoi(self, s: str) -> int: + s = s.strip() + if not s: + return 0 + + sign = -1 if s[0] == '-' else 1 + if s[0] in {'-', '+'}: + s = s[1:] + + num = 0 + + for c in s: + if not c.isdigit(): + break + num = num * 10 + ord(c) - ord('0') + if sign * num <= -2**31: + return -2**31 + if sign * num >= 2**31 - 1: + return 2**31 - 1 + + return sign * num diff --git a/solutions/80. Remove Duplicates from Sorted Array II/80.cpp b/solutions/80. Remove Duplicates from Sorted Array II/80.cpp new file mode 100644 index 00000000000..e634b1a73e1 --- /dev/null +++ b/solutions/80. Remove Duplicates from Sorted Array II/80.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int removeDuplicates(vector& nums) { + int i = 0; + + for (const int num : nums) + if (i < 2 || num > nums[i - 2]) + nums[i++] = num; + + return i; + } +}; diff --git a/solutions/80. Remove Duplicates from Sorted Array II/80.java b/solutions/80. Remove Duplicates from Sorted Array II/80.java new file mode 100644 index 00000000000..ae0bf9f5d25 --- /dev/null +++ b/solutions/80. Remove Duplicates from Sorted Array II/80.java @@ -0,0 +1,11 @@ +class Solution { + public int removeDuplicates(int[] nums) { + int i = 0; + + for (final int num : nums) + if (i < 2 || num > nums[i - 2]) + nums[i++] = num; + + return i; + } +} diff --git a/solutions/80. Remove Duplicates from Sorted Array II/80.py b/solutions/80. Remove Duplicates from Sorted Array II/80.py new file mode 100644 index 00000000000..a3fb1a56032 --- /dev/null +++ b/solutions/80. Remove Duplicates from Sorted Array II/80.py @@ -0,0 +1,10 @@ +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + i = 0 + + for num in nums: + if i < 2 or num != nums[i - 2]: + nums[i] = num + i += 1 + + return i diff --git a/solutions/800. Similar RGB Color/800.cpp b/solutions/800. Similar RGB Color/800.cpp new file mode 100644 index 00000000000..fb4b58803ca --- /dev/null +++ b/solutions/800. Similar RGB Color/800.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + string similarRGB(string color) { + const vector kShorthands = {"00", "11", "22", "33", "44", "55", + "66", "77", "88", "99", "aa", "bb", + "cc", "dd", "ee", "ff"}; + string ans = "#"; + + for (int i = 1; i < color.length(); i += 2) { + const int currValue = stoi(color.substr(i, 2), 0, 16); + ans += findClosestShorthand(kShorthands, currValue); + } + + return ans; + } + + private: + static constexpr int maxSimilarity = 255 * 255; + + string findClosestShorthand(const vector& shorthands, + int targetValue) { + string closest = shorthands[0]; + int minSimilarity = maxSimilarity; + + for (const string& shorthand : shorthands) { + const int shorthandValue = stoi(shorthand, 0, 16); + const int similarity = pow((targetValue - shorthandValue), 2); + if (similarity < minSimilarity) { + closest = shorthand; + minSimilarity = similarity; + } + } + + return closest; + } +}; diff --git a/solutions/800. Similar RGB Color/800.java b/solutions/800. Similar RGB Color/800.java new file mode 100644 index 00000000000..3da715d6b6f --- /dev/null +++ b/solutions/800. Similar RGB Color/800.java @@ -0,0 +1,33 @@ +class Solution { + public String similarRGB(String color) { + String[] kShorthands = {"00", "11", "22", "33", "44", "55", "66", "77", + "88", "99", "aa", "bb", "cc", "dd", "ee", "ff"}; + StringBuilder ans = new StringBuilder("#"); + + for (int i = 1; i < color.length(); i += 2) { + final int currValue = Integer.parseInt(color.substring(i, i + 2), 16); + String closestShorthand = findClosestShorthand(currValue, kShorthands); + ans.append(closestShorthand); + } + + return ans.toString(); + } + + private static final int maxSimilarity = 255 * 255; + + private String findClosestShorthand(int targetValue, String[] shorthands) { + String closest = shorthands[0]; + int minSimilarity = Integer.MAX_VALUE; + + for (final String shorthand : shorthands) { + final int shorthandValue = Integer.parseInt(shorthand, 16); + final int similarity = (targetValue - shorthandValue) * (targetValue - shorthandValue); + if (similarity < minSimilarity) { + closest = shorthand; + minSimilarity = similarity; + } + } + + return closest; + } +} diff --git a/solutions/800. Similar RGB Color/800.py b/solutions/800. Similar RGB Color/800.py new file mode 100644 index 00000000000..7322874bdf7 --- /dev/null +++ b/solutions/800. Similar RGB Color/800.py @@ -0,0 +1,13 @@ +class Solution: + def similarRGB(self, color: str) -> str: + kShorthands = ['00', '11', '22', '33', '44', '55', '66', '77', '88', '99', + 'aa', 'bb', 'cc', 'dd', 'ee', 'ff'] + ans = ['#'] + + for i in range(1, len(color), 2): + currValue = int(color[i:i + 2], 16) + closestShorthand = min(kShorthands, + key=lambda shorthand: (currValue - int(shorthand, 16))**2) + ans.append(closestShorthand) + + return ''.join(ans) diff --git a/solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.cpp b/solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.cpp new file mode 100644 index 00000000000..60e348f301b --- /dev/null +++ b/solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minSwap(vector& nums1, vector& nums2) { + int keepAt = 0; + int swapAt = 1; + int prevKeepAt = 0; + int prevSwapAt = 1; + + for (int i = 1; i < nums1.size(); ++i) { + keepAt = INT_MAX; + swapAt = INT_MAX; + if (nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1]) { + keepAt = prevKeepAt; + swapAt = prevSwapAt + 1; + } + if (nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]) { + keepAt = min(keepAt, prevSwapAt); + swapAt = min(swapAt, prevKeepAt + 1); + } + prevKeepAt = keepAt; + prevSwapAt = swapAt; + } + + return min(keepAt, swapAt); + } +}; diff --git a/solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.java b/solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.java new file mode 100644 index 00000000000..0bacc5dc376 --- /dev/null +++ b/solutions/801. Minimum Swaps To Make Sequences Increasing/801-2.java @@ -0,0 +1,25 @@ +class Solution { + public int minSwap(int[] nums1, int[] nums2) { + int keepAt = 0; + int swapAt = 1; + int prevKeepAt = 0; + int prevSwapAt = 1; + + for (int i = 1; i < nums1.length; ++i) { + keepAt = Integer.MAX_VALUE; + swapAt = Integer.MAX_VALUE; + if (nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1]) { + keepAt = prevKeepAt; + swapAt = prevSwapAt + 1; + } + if (nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]) { + keepAt = Math.min(keepAt, prevSwapAt); + swapAt = Math.min(swapAt, prevKeepAt + 1); + } + prevKeepAt = keepAt; + prevSwapAt = swapAt; + } + + return Math.min(keepAt, swapAt); + } +} diff --git a/solutions/801. Minimum Swaps To Make Sequences Increasing/801.cpp b/solutions/801. Minimum Swaps To Make Sequences Increasing/801.cpp new file mode 100644 index 00000000000..65bc9c30224 --- /dev/null +++ b/solutions/801. Minimum Swaps To Make Sequences Increasing/801.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minSwap(vector& nums1, vector& nums2) { + vector keepAt(nums1.size(), INT_MAX); + vector swapAt(nums1.size(), INT_MAX); + keepAt[0] = 0; + swapAt[0] = 1; + + for (int i = 1; i < nums1.size(); ++i) { + if (nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1]) { + keepAt[i] = keepAt[i - 1]; + swapAt[i] = swapAt[i - 1] + 1; + } + if (nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]) { + keepAt[i] = min(keepAt[i], swapAt[i - 1]); + swapAt[i] = min(swapAt[i], keepAt[i - 1] + 1); + } + } + + return min(keepAt.back(), swapAt.back()); + } +}; diff --git a/solutions/801. Minimum Swaps To Make Sequences Increasing/801.java b/solutions/801. Minimum Swaps To Make Sequences Increasing/801.java new file mode 100644 index 00000000000..c89043f0c72 --- /dev/null +++ b/solutions/801. Minimum Swaps To Make Sequences Increasing/801.java @@ -0,0 +1,24 @@ +class Solution { + public int minSwap(int[] nums1, int[] nums2) { + final int n = nums1.length; + int[] keepAt = new int[n]; + int[] swapAt = new int[n]; + Arrays.fill(keepAt, Integer.MAX_VALUE); + Arrays.fill(swapAt, Integer.MAX_VALUE); + keepAt[0] = 0; + swapAt[0] = 1; + + for (int i = 1; i < n; ++i) { + if (nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1]) { + keepAt[i] = keepAt[i - 1]; + swapAt[i] = swapAt[i - 1] + 1; + } + if (nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]) { + keepAt[i] = Math.min(keepAt[i], swapAt[i - 1]); + swapAt[i] = Math.min(swapAt[i], keepAt[i - 1] + 1); + } + } + + return Math.min(keepAt[n - 1], swapAt[n - 1]); + } +} diff --git a/solutions/801. Minimum Swaps To Make Sequences Increasing/801.py b/solutions/801. Minimum Swaps To Make Sequences Increasing/801.py new file mode 100644 index 00000000000..8fbf5180a67 --- /dev/null +++ b/solutions/801. Minimum Swaps To Make Sequences Increasing/801.py @@ -0,0 +1,16 @@ +class Solution: + def minSwap(self, nums1: List[int], nums2: List[int]) -> int: + keepAt = [math.inf] * len(nums1) + swapAt = [math.inf] * len(nums1) + keepAt[0] = 0 + swapAt[0] = 1 + + for i in range(1, len(nums1)): + if nums1[i] > nums1[i - 1] and nums2[i] > nums2[i - 1]: + keepAt[i] = keepAt[i - 1] + swapAt[i] = swapAt[i - 1] + 1 + if nums1[i] > nums2[i - 1] and nums2[i] > nums1[i - 1]: + keepAt[i] = min(keepAt[i], swapAt[i - 1]) + swapAt[i] = min(swapAt[i], keepAt[i - 1] + 1) + + return min(keepAt[-1], swapAt[-1]) diff --git a/solutions/802. Find Eventual Safe States/802.cpp b/solutions/802. Find Eventual Safe States/802.cpp new file mode 100644 index 00000000000..6d5912e2992 --- /dev/null +++ b/solutions/802. Find Eventual Safe States/802.cpp @@ -0,0 +1,32 @@ +enum class State { kInit, kVisiting, kVisited }; + +class Solution { + public: + vector eventualSafeNodes(vector>& graph) { + vector ans; + vector states(graph.size()); + + for (int i = 0; i < graph.size(); ++i) + if (!hasCycle(graph, i, states)) + ans.push_back(i); + + return ans; + } + + private: + bool hasCycle(const vector>& graph, int u, + vector& states) { + if (states[u] == State::kVisiting) + return true; + if (states[u] == State::kVisited) + return false; + + states[u] = State::kVisiting; + for (const int v : graph[u]) + if (hasCycle(graph, v, states)) + return true; + states[u] = State::kVisited; + + return false; + } +}; diff --git a/solutions/802. Find Eventual Safe States/802.java b/solutions/802. Find Eventual Safe States/802.java new file mode 100644 index 00000000000..49a58277817 --- /dev/null +++ b/solutions/802. Find Eventual Safe States/802.java @@ -0,0 +1,29 @@ +enum State { kInit, kVisiting, kVisited } + +class Solution { + public List eventualSafeNodes(int[][] graph) { + List ans = new ArrayList<>(); + State[] states = new State[graph.length]; + + for (int i = 0; i < graph.length; ++i) + if (!hasCycle(graph, i, states)) + ans.add(i); + + return ans; + } + + private boolean hasCycle(int[][] graph, int u, State[] states) { + if (states[u] == State.kVisiting) + return true; + if (states[u] == State.kVisited) + return false; + + states[u] = State.kVisiting; + for (final int v : graph[u]) + if (hasCycle(graph, v, states)) + return true; + states[u] = State.kVisited; + + return false; + } +} diff --git a/solutions/802. Find Eventual Safe States/802.py b/solutions/802. Find Eventual Safe States/802.py new file mode 100644 index 00000000000..2c2c1fe33a3 --- /dev/null +++ b/solutions/802. Find Eventual Safe States/802.py @@ -0,0 +1,25 @@ +from enum import Enum + + +class State(Enum): + kInit = 0 + kVisiting = 1 + kVisited = 2 + + +class Solution: + def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: + states = [State.kInit] * len(graph) + + def hasCycle(u: int) -> bool: + if states[u] == State.kVisiting: + return True + if states[u] == State.kVisited: + return False + + states[u] = State.kVisiting + if any(hasCycle(v) for v in graph[u]): + return True + states[u] = State.kVisited + + return [i for i in range(len(graph)) if not hasCycle(i)] diff --git a/solutions/803. Bricks Falling When Hit/803.cpp b/solutions/803. Bricks Falling When Hit/803.cpp new file mode 100644 index 00000000000..e85e8cc55b7 --- /dev/null +++ b/solutions/803. Bricks Falling When Hit/803.cpp @@ -0,0 +1,102 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), sz(n, 1) { + iota(id.begin(), id.end(), 0); + } + + void unionBySize(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (sz[i] < sz[j]) { + sz[j] += sz[i]; + id[i] = j; + } else { + sz[i] += sz[j]; + id[j] = i; + } + } + + int getStableSize() { + // Bricks connected with 0 (top) are stable. + return sz[find(0)]; + } + + private: + vector id; + vector sz; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + vector hitBricks(vector>& grid, vector>& hits) { + m = grid.size(); + n = grid[0].size(); + + UnionFind uf(m * n + 1); // 0 := top (stable) + + // Mark cells to hit as 2. + for (const vector& hit : hits) { + const int i = hit[0]; + const int j = hit[1]; + if (grid[i][j] == 1) + grid[i][j] = 2; + } + + // Union all the 1s. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + unionNeighbors(grid, uf, i, j); + + vector ans(hits.size()); + int stableSize = uf.getStableSize(); + + for (int i = hits.size() - 1; i >= 0; --i) { + const int x = hits[i][0]; + const int y = hits[i][1]; + if (grid[x][y] == 2) { // cells marked from 1 to 2 + grid[x][y] = 1; // Unhit and restore it back to 1. + unionNeighbors(grid, uf, x, y); + const int newStableSize = uf.getStableSize(); + if (newStableSize > stableSize) + ans[i] = newStableSize - stableSize - 1; // 1 := the hit cell + stableSize = newStableSize; + } + } + + return ans; + } + + private: + static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int m; + int n; + + void unionNeighbors(const vector>& grid, UnionFind& uf, int i, + int j) { + const int hash = getHash(i, j); + + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] != 1) + continue; + uf.unionBySize(hash, getHash(x, y)); + } + + if (i == 0) + uf.unionBySize(hash, 0); + } + + int getHash(int i, int j) { + return i * n + j + 1; + } +}; diff --git a/solutions/803. Bricks Falling When Hit/803.java b/solutions/803. Bricks Falling When Hit/803.java new file mode 100644 index 00000000000..86c392bff30 --- /dev/null +++ b/solutions/803. Bricks Falling When Hit/803.java @@ -0,0 +1,100 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + sz = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + Arrays.fill(sz, 1); + } + + public void unionBySize(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (sz[i] < sz[j]) { + sz[j] += sz[i]; + id[i] = j; + } else { + sz[i] += sz[j]; + id[j] = i; + } + } + + public int getStableSize() { + // Bricks connected with 0 (top) are stable. + return sz[find(0)]; + } + + private int[] id; + private int[] sz; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} +class Solution { + public int[] hitBricks(int[][] grid, int[][] hits) { + this.m = grid.length; + this.n = grid[0].length; + + UnionFind uf = new UnionFind(m * n + 1); // 0 := top (stable) + + // Mark cells to hit as 2. + for (int[] hit : hits) { + final int i = hit[0]; + final int j = hit[1]; + if (grid[i][j] == 1) + grid[i][j] = 2; + } + + // Union all the 1s. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + unionNeighbors(grid, uf, i, j); + + int[] ans = new int[hits.length]; + int stableSize = uf.getStableSize(); + + for (int i = hits.length - 1; i >= 0; --i) { + final int x = hits[i][0]; + final int y = hits[i][1]; + if (grid[x][y] == 2) { // cells marked from 1 to 2 + grid[x][y] = 1; // Unhit and restore it back to 1. + unionNeighbors(grid, uf, x, y); + final int newStableSize = uf.getStableSize(); + if (newStableSize > stableSize) + ans[i] = newStableSize - stableSize - 1; // 1 := the hit cell + stableSize = newStableSize; + } + } + + return ans; + } + + private int m; + private int n; + private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + private void unionNeighbors(int[][] grid, UnionFind uf, int i, int j) { + final int hash = getHash(i, j); + + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] != 1) + continue; + uf.unionBySize(hash, getHash(x, y)); + } + + if (i == 0) + uf.unionBySize(hash, 0); + } + + private int getHash(int i, int j) { + return i * n + j + 1; + } +} diff --git a/solutions/804. Unique Morse Code Words/804.cpp b/solutions/804. Unique Morse Code Words/804.cpp new file mode 100644 index 00000000000..8f46458707b --- /dev/null +++ b/solutions/804. Unique Morse Code Words/804.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int uniqueMorseRepresentations(vector& words) { + const vector morse{ + ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", + ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", + "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; + unordered_set transformations; + + for (const string& word : words) { + string transformation; + for (const char c : word) + transformation += morse[c - 'a']; + transformations.insert(transformation); + } + + return transformations.size(); + } +}; diff --git a/solutions/804. Unique Morse Code Words/804.java b/solutions/804. Unique Morse Code Words/804.java new file mode 100644 index 00000000000..b3e209d7ea4 --- /dev/null +++ b/solutions/804. Unique Morse Code Words/804.java @@ -0,0 +1,17 @@ +class Solution { + public int uniqueMorseRepresentations(String[] words) { + final String[] morse = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", + ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", + "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; + Set transformations = new HashSet<>(); + + for (final String word : words) { + StringBuilder transformation = new StringBuilder(); + for (final char c : word.toCharArray()) + transformation.append(morse[c - 'a']); + transformations.add(transformation.toString()); + } + + return transformations.size(); + } +} diff --git a/solutions/804. Unique Morse Code Words/804.py b/solutions/804. Unique Morse Code Words/804.py new file mode 100644 index 00000000000..c00bb5889f7 --- /dev/null +++ b/solutions/804. Unique Morse Code Words/804.py @@ -0,0 +1,11 @@ +class Solution: + def uniqueMorseRepresentations(self, words: List[str]) -> int: + morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", + "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."] + transformations = set() + + for word in words: + transformation = ''.join(morse[ord(c) - ord('a')] for c in word) + transformations.add(transformation) + + return len(transformations) diff --git a/solutions/805. Split Array With Same Average/805.cpp b/solutions/805. Split Array With Same Average/805.cpp new file mode 100644 index 00000000000..5f3427851fd --- /dev/null +++ b/solutions/805. Split Array With Same Average/805.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + bool splitArraySameAverage(vector& nums) { + const int n = nums.size(); + const int sum = accumulate(nums.begin(), nums.end(), 0); + if (!isPossible(sum, n)) + return false; + + vector> sums(n / 2 + 1); + sums[0].insert(0); + + for (const int num : nums) + for (int i = n / 2; i > 0; --i) + for (const int val : sums[i - 1]) + sums[i].insert(num + val); + + for (int i = 1; i < n / 2 + 1; ++i) + if (i * sum % n == 0 && sums[i].contains(i * sum / n)) + return true; + + return false; + } + + private: + bool isPossible(int sum, int n) { + for (int i = 1; i < n / 2 + 1; ++i) + if (i * sum % n == 0) + return true; + return false; + } +}; diff --git a/solutions/805. Split Array With Same Average/805.java b/solutions/805. Split Array With Same Average/805.java new file mode 100644 index 00000000000..1e0b5d57b6e --- /dev/null +++ b/solutions/805. Split Array With Same Average/805.java @@ -0,0 +1,32 @@ +class Solution { + public boolean splitArraySameAverage(int[] nums) { + final int n = nums.length; + final int sum = Arrays.stream(nums).sum(); + if (!isPossible(sum, n)) + return false; + + List> sums = new ArrayList<>(); + + for (int i = 0; i < n / 2 + 1; ++i) + sums.add(new HashSet<>()); + sums.get(0).add(0); + + for (final int num : nums) + for (int i = n / 2; i > 0; --i) + for (final int val : sums.get(i - 1)) + sums.get(i).add(num + val); + + for (int i = 1; i < n / 2 + 1; ++i) + if (i * sum % n == 0 && sums.get(i).contains(i * sum / n)) + return true; + + return false; + } + + private boolean isPossible(int sum, int n) { + for (int i = 1; i < n / 2 + 1; ++i) + if (i * sum % n == 0) + return true; + return false; + } +} diff --git a/solutions/805. Split Array With Same Average/805.py b/solutions/805. Split Array With Same Average/805.py new file mode 100644 index 00000000000..1be1f3d3186 --- /dev/null +++ b/solutions/805. Split Array With Same Average/805.py @@ -0,0 +1,20 @@ +class Solution: + def splitArraySameAverage(self, nums: List[int]) -> bool: + n = len(nums) + summ = sum(nums) + if not any(i * summ % n == 0 for i in range(1, n // 2 + 1)): + return False + + sums = [set() for _ in range(n // 2 + 1)] + sums[0].add(0) + + for num in nums: + for i in range(n // 2, 0, -1): + for val in sums[i - 1]: + sums[i].add(num + val) + + for i in range(1, n // 2 + 1): + if i * summ % n == 0 and i * summ // n in sums[i]: + return True + + return False diff --git a/solutions/806. Number of Lines To Write String/806.cpp b/solutions/806. Number of Lines To Write String/806.cpp new file mode 100644 index 00000000000..11882d8546b --- /dev/null +++ b/solutions/806. Number of Lines To Write String/806.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector numberOfLines(vector& widths, string s) { + int numLines = 1; + int runningWidth = 0; + + for (const char c : s) { + const int width = widths[c - 'a']; + if (runningWidth + width <= 100) { + runningWidth += width; + } else { + ++numLines; + runningWidth = width; + } + } + + return {numLines, runningWidth}; + } +}; diff --git a/solutions/806. Number of Lines To Write String/806.java b/solutions/806. Number of Lines To Write String/806.java new file mode 100644 index 00000000000..f876f2f0b92 --- /dev/null +++ b/solutions/806. Number of Lines To Write String/806.java @@ -0,0 +1,18 @@ +class Solution { + public int[] numberOfLines(int[] widths, String s) { + int numLines = 1; + int runningWidth = 0; + + for (final char c : s.toCharArray()) { + final int width = widths[c - 'a']; + if (runningWidth + width <= 100) { + runningWidth += width; + } else { + ++numLines; + runningWidth = width; + } + } + + return new int[] {numLines, runningWidth}; + } +} diff --git a/solutions/806. Number of Lines To Write String/806.py b/solutions/806. Number of Lines To Write String/806.py new file mode 100644 index 00000000000..c8fddb7423a --- /dev/null +++ b/solutions/806. Number of Lines To Write String/806.py @@ -0,0 +1,14 @@ +class Solution: + def numberOfLines(self, widths: List[int], s: str) -> List[int]: + numLines = 1 + runningWidth = 0 + + for c in s: + width = widths[ord(c) - ord('a')] + if runningWidth + width <= 100: + runningWidth += width + else: + numLines += 1 + runningWidth = width + + return [numLines, runningWidth] diff --git a/solutions/807. Max Increase to Keep City Skyline/807.cpp b/solutions/807. Max Increase to Keep City Skyline/807.cpp new file mode 100644 index 00000000000..fe7a9f3402d --- /dev/null +++ b/solutions/807. Max Increase to Keep City Skyline/807.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int maxIncreaseKeepingSkyline(vector>& grid) { + const int n = grid.size(); + int ans = 0; + vector rowMax(n); + vector colMax(n); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + rowMax[i] = max(rowMax[i], grid[i][j]); + colMax[j] = max(colMax[j], grid[i][j]); + } + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + ans += min(rowMax[i], colMax[j]) - grid[i][j]; + + return ans; + } +}; diff --git a/solutions/807. Max Increase to Keep City Skyline/807.java b/solutions/807. Max Increase to Keep City Skyline/807.java new file mode 100644 index 00000000000..77b68a75427 --- /dev/null +++ b/solutions/807. Max Increase to Keep City Skyline/807.java @@ -0,0 +1,20 @@ +class Solution { + public int maxIncreaseKeepingSkyline(int[][] grid) { + final int n = grid.length; + int ans = 0; + int[] rowMax = new int[n]; + int[] colMax = new int[n]; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + rowMax[i] = Math.max(rowMax[i], grid[i][j]); + colMax[j] = Math.max(colMax[j], grid[i][j]); + } + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + ans += Math.min(rowMax[i], colMax[j]) - grid[i][j]; + + return ans; + } +} diff --git a/solutions/807. Max Increase to Keep City Skyline/807.py b/solutions/807. Max Increase to Keep City Skyline/807.py new file mode 100644 index 00000000000..902dfa4cd5b --- /dev/null +++ b/solutions/807. Max Increase to Keep City Skyline/807.py @@ -0,0 +1,5 @@ +class Solution: + def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: + rowMax = list(map(max, grid)) + colMax = list(map(max, zip(*grid))) + return sum(min(i, j) for i in rowMax for j in colMax) - sum(map(sum, grid)) diff --git a/solutions/808. Soup Servings/808.cpp b/solutions/808. Soup Servings/808.cpp new file mode 100644 index 00000000000..c272db9960c --- /dev/null +++ b/solutions/808. Soup Servings/808.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + double soupServings(int n) { + return n >= 4800 ? 1.0 : dfs((n + 24) / 25, (n + 24) / 25); + } + + private: + vector> mem = + vector>(4800 / 25, vector(4800 / 25)); + + double dfs(int a, int b) { + if (a <= 0 && b <= 0) + return 0.5; + if (a <= 0) + return 1.0; + if (b <= 0) + return 0.0; + if (mem[a][b] > 0) + return mem[a][b]; + return mem[a][b] = 0.25 * (dfs(a - 4, b) + dfs(a - 3, b - 1) + + dfs(a - 2, b - 2) + dfs(a - 1, b - 3)); + } +}; diff --git a/solutions/808. Soup Servings/808.java b/solutions/808. Soup Servings/808.java new file mode 100644 index 00000000000..2154a5a3b98 --- /dev/null +++ b/solutions/808. Soup Servings/808.java @@ -0,0 +1,20 @@ +class Solution { + public double soupServings(int n) { + return n >= 4800 ? 1.0 : dfs((n + 24) / 25, (n + 24) / 25); + } + + private double[][] mem = new double[4800 / 25][4800 / 25]; + + private double dfs(int a, int b) { + if (a <= 0 && b <= 0) + return 0.5; + if (a <= 0) + return 1.0; + if (b <= 0) + return 0.0; + if (mem[a][b] > 0) + return mem[a][b]; + return mem[a][b] = + 0.25 * (dfs(a - 4, b) + dfs(a - 3, b - 1) + dfs(a - 2, b - 2) + dfs(a - 1, b - 3)); + } +} diff --git a/solutions/808. Soup Servings/808.py b/solutions/808. Soup Servings/808.py new file mode 100644 index 00000000000..f6ca915ddaa --- /dev/null +++ b/solutions/808. Soup Servings/808.py @@ -0,0 +1,16 @@ +class Solution: + def soupServings(self, n: int) -> float: + @functools.lru_cache(None) + def dfs(a: int, b: int) -> float: + if a <= 0 and b <= 0: + return 0.5 + if a <= 0: + return 1.0 + if b <= 0: + return 0.0 + return 0.25 * (dfs(a - 4, b) + + dfs(a - 3, b - 1) + + dfs(a - 2, b - 2) + + dfs(a - 1, b - 3)) + + return 1 if n >= 4800 else dfs((n + 24) // 25, (n + 24) // 25) diff --git a/solutions/809. Expressive Words/809.cpp b/solutions/809. Expressive Words/809.cpp new file mode 100644 index 00000000000..0b483de4b70 --- /dev/null +++ b/solutions/809. Expressive Words/809.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int expressiveWords(string s, vector& words) { + int ans = 0; + + for (const string& word : words) + if (isStretchy(s, word)) + ++ans; + + return ans; + } + + private: + bool isStretchy(const string& s, const string& word) { + const int n = s.length(); + const int m = word.length(); + + int j = 0; + for (int i = 0; i < n; ++i) + if (j < m && s[i] == word[j]) + ++j; + else if (i > 1 && s[i] == s[i - 1] && s[i - 1] == s[i - 2]) + continue; + else if (0 < i && i + 1 < n && s[i - 1] == s[i] && s[i] == s[i + 1]) + continue; + else + return false; + + return j == m; + } +}; diff --git a/solutions/809. Expressive Words/809.java b/solutions/809. Expressive Words/809.java new file mode 100644 index 00000000000..aa5be6d6dcf --- /dev/null +++ b/solutions/809. Expressive Words/809.java @@ -0,0 +1,30 @@ +class Solution { + public int expressiveWords(String s, String[] words) { + int ans = 0; + + for (final String word : words) + if (isStretchy(s, word)) + ++ans; + + return ans; + } + + private boolean isStretchy(final String s, final String word) { + final int n = s.length(); + final int m = word.length(); + + int j = 0; + for (int i = 0; i < n; ++i) + if (j < m && s.charAt(i) == word.charAt(j)) + ++j; + else if (i > 1 && s.charAt(i) == s.charAt(i - 1) && s.charAt(i - 1) == s.charAt(i - 2)) + continue; + else if (0 < i && i + 1 < n && s.charAt(i - 1) == s.charAt(i) && + s.charAt(i) == s.charAt(i + 1)) + continue; + else + return false; + + return j == m; + } +} diff --git a/solutions/809. Expressive Words/809.py b/solutions/809. Expressive Words/809.py new file mode 100644 index 00000000000..b77f82ca879 --- /dev/null +++ b/solutions/809. Expressive Words/809.py @@ -0,0 +1,20 @@ +class Solution: + def expressiveWords(self, s: str, words: List[str]) -> int: + def isStretchy(word: str) -> bool: + n = len(s) + m = len(word) + + j = 0 + for i in range(n): + if j < m and s[i] == word[j]: + j += 1 + elif i > 1 and s[i] == s[i - 1] == s[i - 2]: + continue + elif 0 < i < n - 1 and s[i - 1] == s[i] == s[i + 1]: + continue + else: + return False + + return j == m + + return sum(isStretchy(word) for word in words) diff --git a/solutions/81. Search in Rotated Sorted Array II/81.cpp b/solutions/81. Search in Rotated Sorted Array II/81.cpp new file mode 100644 index 00000000000..0897c5e6f54 --- /dev/null +++ b/solutions/81. Search in Rotated Sorted Array II/81.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + bool search(vector& nums, int target) { + int l = 0; + int r = nums.size() - 1; + + while (l <= r) { + const int m = (l + r) / 2; + if (nums[m] == target) + return true; + if (nums[l] == nums[m] && nums[m] == nums[r]) { + ++l; + --r; + } else if (nums[l] <= nums[m]) { // nums[l..m] are sorted + if (nums[l] <= target && target < nums[m]) + r = m - 1; + else + l = m + 1; + } else { // nums[m..n - 1] are sorted + if (nums[m] < target && target <= nums[r]) + l = m + 1; + else + r = m - 1; + } + } + + return false; + } +}; diff --git a/solutions/81. Search in Rotated Sorted Array II/81.java b/solutions/81. Search in Rotated Sorted Array II/81.java new file mode 100644 index 00000000000..d9d800ef996 --- /dev/null +++ b/solutions/81. Search in Rotated Sorted Array II/81.java @@ -0,0 +1,28 @@ +class Solution { + public boolean search(int[] nums, int target) { + int l = 0; + int r = nums.length - 1; + + while (l <= r) { + final int m = (l + r) / 2; + if (nums[m] == target) + return true; + if (nums[l] == nums[m] && nums[m] == nums[r]) { + ++l; + --r; + } else if (nums[l] <= nums[m]) { // nums[l..m] are sorted + if (nums[l] <= target && target < nums[m]) + r = m - 1; + else + l = m + 1; + } else { // nums[m..n - 1] are sorted + if (nums[m] < target && target <= nums[r]) + l = m + 1; + else + r = m - 1; + } + } + + return false; + } +} diff --git a/solutions/81. Search in Rotated Sorted Array II/81.py b/solutions/81. Search in Rotated Sorted Array II/81.py new file mode 100644 index 00000000000..94eb27c7ec7 --- /dev/null +++ b/solutions/81. Search in Rotated Sorted Array II/81.py @@ -0,0 +1,24 @@ +class Solution: + def search(self, nums: List[int], target: int) -> bool: + l = 0 + r = len(nums) - 1 + + while l <= r: + m = (l + r) // 2 + if nums[m] == target: + return True + if nums[l] == nums[m] == nums[r]: + l += 1 + r -= 1 + elif nums[l] <= nums[m]: # nums[l..m] are sorted + if nums[l] <= target < nums[m]: + r = m - 1 + else: + l = m + 1 + else: # nums[m..n - 1] are sorted + if nums[m] < target <= nums[r]: + l = m + 1 + else: + r = m - 1 + + return False diff --git a/solutions/810. Chalkboard XOR Game/810.cpp b/solutions/810. Chalkboard XOR Game/810.cpp new file mode 100644 index 00000000000..5e85f4e32b1 --- /dev/null +++ b/solutions/810. Chalkboard XOR Game/810.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + bool xorGame(vector& nums) { + const int xors = accumulate(nums.begin(), nums.end(), 0, bit_xor()); + return xors == 0 || nums.size() % 2 == 0; + } +}; diff --git a/solutions/810. Chalkboard XOR Game/810.java b/solutions/810. Chalkboard XOR Game/810.java new file mode 100644 index 00000000000..2a0b23ffed4 --- /dev/null +++ b/solutions/810. Chalkboard XOR Game/810.java @@ -0,0 +1,6 @@ +class Solution { + public boolean xorGame(int[] nums) { + final int xors = Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt(); + return xors == 0 || nums.length % 2 == 0; + } +} diff --git a/solutions/810. Chalkboard XOR Game/810.py b/solutions/810. Chalkboard XOR Game/810.py new file mode 100644 index 00000000000..efa98b8cdd2 --- /dev/null +++ b/solutions/810. Chalkboard XOR Game/810.py @@ -0,0 +1,3 @@ +class Solution: + def xorGame(self, nums: List[int]) -> bool: + return functools.reduce(operator.xor, nums) == 0 or len(nums) % 2 == 0 diff --git a/solutions/811. Subdomain Visit Count/811.cpp b/solutions/811. Subdomain Visit Count/811.cpp new file mode 100644 index 00000000000..6b9e15ec17e --- /dev/null +++ b/solutions/811. Subdomain Visit Count/811.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector subdomainVisits(vector& cpdomains) { + vector ans; + unordered_map count; + + for (const string& cpdomain : cpdomains) { + const int space = cpdomain.find(' '); + const int num = stoi(cpdomain.substr(0, space)); + const string& domain = cpdomain.substr(space + 1); + count[domain] += num; + for (int i = 0; i < domain.length(); ++i) + if (domain[i] == '.') + count[domain.substr(i + 1)] += num; + } + + for (const auto& [subdomain, freq] : count) + ans.push_back(to_string(freq) + ' ' + subdomain); + + return ans; + } +}; diff --git a/solutions/811. Subdomain Visit Count/811.java b/solutions/811. Subdomain Visit Count/811.java new file mode 100644 index 00000000000..324b4a1793c --- /dev/null +++ b/solutions/811. Subdomain Visit Count/811.java @@ -0,0 +1,23 @@ +class Solution { + public List subdomainVisits(String[] cpdomains) { + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + + for (final String cpdomain : cpdomains) { + final int space = cpdomain.indexOf(' '); + final int num = Integer.valueOf(cpdomain.substring(0, space)); + final String domain = cpdomain.substring(space + 1); + count.merge(domain, num, Integer::sum); + for (int i = 0; i < domain.length(); ++i) + if (domain.charAt(i) == '.') { + String subdomain = domain.substring(i + 1); + count.merge(subdomain, num, Integer::sum); + } + } + + for (final String subdomain : count.keySet()) + ans.add(String.valueOf(count.get(subdomain)) + ' ' + subdomain); + + return ans; + } +} diff --git a/solutions/811. Subdomain Visit Count/811.py b/solutions/811. Subdomain Visit Count/811.py new file mode 100644 index 00000000000..de0ab858fde --- /dev/null +++ b/solutions/811. Subdomain Visit Count/811.py @@ -0,0 +1,12 @@ +class Solution: + def subdomainVisits(self, cpdomains: List[str]) -> List[str]: + ans = [] + count = collections.Counter() + + for cpdomain in cpdomains: + num, domains = cpdomain.split() + num, domains = int(num), domains.split('.') + for i in reversed(range(len(domains))): + count['.'.join(domains[i:])] += num + + return [str(freq) + ' ' + domain for domain, freq in count.items()] diff --git a/solutions/812. Largest Triangle Area/812.cpp b/solutions/812. Largest Triangle Area/812.cpp new file mode 100644 index 00000000000..98d54bbe866 --- /dev/null +++ b/solutions/812. Largest Triangle Area/812.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + double largestTriangleArea(vector>& points) { + double ans = 0; + + for (const vector& A : points) + for (const vector& B : points) + for (const vector& C : points) + ans = max(ans, 0.5 * abs((B[0] - A[0]) * (C[1] - A[1]) - + (C[0] - A[0]) * (B[1] - A[1]))); + + return ans; + } +}; diff --git a/solutions/812. Largest Triangle Area/812.java b/solutions/812. Largest Triangle Area/812.java new file mode 100644 index 00000000000..1916d06775b --- /dev/null +++ b/solutions/812. Largest Triangle Area/812.java @@ -0,0 +1,13 @@ +class Solution { + public double largestTriangleArea(int[][] points) { + double ans = 0; + + for (int[] A : points) + for (int[] B : points) + for (int[] C : points) + ans = Math.max(ans, 0.5 * Math.abs((B[0] - A[0]) * (C[1] - A[1]) - // + (C[0] - A[0]) * (B[1] - A[1]))); + + return ans; + } +} diff --git a/solutions/812. Largest Triangle Area/812.py b/solutions/812. Largest Triangle Area/812.py new file mode 100644 index 00000000000..59fc1b9cc2b --- /dev/null +++ b/solutions/812. Largest Triangle Area/812.py @@ -0,0 +1,11 @@ +class Solution: + def largestTriangleArea(self, points: List[List[int]]) -> float: + ans = 0 + + for Ax, Ay in points: + for Bx, By in points: + for Cx, Cy in points: + ans = max(ans, 0.5 * abs((Bx - Ax) * (Cy - Ay) - + (Cx - Ax) * (By - Ay))) + + return ans diff --git a/solutions/813. Largest Sum of Averages/813-2.cpp b/solutions/813. Largest Sum of Averages/813-2.cpp new file mode 100644 index 00000000000..186615f8f4b --- /dev/null +++ b/solutions/813. Largest Sum of Averages/813-2.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + double largestSumOfAverages(vector& nums, int K) { + const int n = nums.size(); + // dp[i][k] := the maximum score to partition the first i nums into k groups + vector> dp(n + 1, vector(K + 1)); + vector prefix(n + 1); + + partial_sum(nums.begin(), nums.end(), prefix.begin() + 1); + + for (int i = 1; i <= n; ++i) + dp[i][1] = prefix[i] / i; + + for (int k = 2; k <= K; ++k) + for (int i = k; i <= n; ++i) + for (int j = k - 1; j < i; ++j) { + const double average = (prefix[i] - prefix[j]) / (i - j); + dp[i][k] = max(dp[i][k], dp[j][k - 1] + average); + } + + return dp[n][K]; + } +}; diff --git a/solutions/813. Largest Sum of Averages/813-2.java b/solutions/813. Largest Sum of Averages/813-2.java new file mode 100644 index 00000000000..5069b060fcc --- /dev/null +++ b/solutions/813. Largest Sum of Averages/813-2.java @@ -0,0 +1,22 @@ +class Solution { + public double largestSumOfAverages(int[] nums, int K) { + final int n = nums.length; + // dp[i][k] := the maximum score to partition the first i nums into k groups + double[][] dp = new double[n + 1][K + 1]; + double[] prefix = new double[n + 1]; + + for (int i = 1; i <= n; ++i) { + prefix[i] = nums[i - 1] + prefix[i - 1]; + dp[i][1] = prefix[i] / i; + } + + for (int k = 2; k <= K; ++k) + for (int i = k; i <= n; ++i) + for (int j = k - 1; j < i; ++j) { + final double average = (prefix[i] - prefix[j]) / (i - j); + dp[i][k] = Math.max(dp[i][k], dp[j][k - 1] + average); + } + + return dp[n][K]; + } +} diff --git a/solutions/813. Largest Sum of Averages/813.cpp b/solutions/813. Largest Sum of Averages/813.cpp new file mode 100644 index 00000000000..fffb5e27f3e --- /dev/null +++ b/solutions/813. Largest Sum of Averages/813.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + double largestSumOfAverages(vector& nums, int k) { + const int n = nums.size(); + vector> mem(n + 1, vector(k + 1)); + vector prefix(n + 1); + partial_sum(nums.begin(), nums.end(), prefix.begin() + 1); + return largestSumOfAverages(nums, n, k, prefix, mem); + } + + private: + // Returns the maximum score to partition the first i numbers into k groups. + double largestSumOfAverages(const vector& nums, int i, int k, + const vector& prefix, + vector>& mem) { + if (k == 1) + return prefix[i] / i; + if (mem[i][k] > 0) + return mem[i][k]; + + // Try all the possible partitions. + for (int j = k - 1; j < i; ++j) + mem[i][k] = + max(mem[i][k], largestSumOfAverages(nums, j, k - 1, prefix, mem) + + (prefix[i] - prefix[j]) / (i - j)); + + return mem[i][k]; + } +}; diff --git a/solutions/813. Largest Sum of Averages/813.java b/solutions/813. Largest Sum of Averages/813.java new file mode 100644 index 00000000000..ea1742e7569 --- /dev/null +++ b/solutions/813. Largest Sum of Averages/813.java @@ -0,0 +1,27 @@ +class Solution { + public double largestSumOfAverages(int[] nums, int k) { + final int n = nums.length; + double[][] mem = new double[n + 1][k + 1]; + double[] prefix = new double[n + 1]; + + for (int i = 0; i < n; i++) + prefix[i + 1] = prefix[i] + nums[i]; + + return largestSumOfAverages(nums, n, k, prefix, mem); + } + + // Returns the maximum score to partition the first i numbers into k groups. + private double largestSumOfAverages(int[] nums, int i, int k, double[] prefix, double[][] mem) { + if (k == 1) + return prefix[i] / i; + if (mem[i][k] > 0) + return mem[i][k]; + + // Try all the possible partitions. + for (int j = k - 1; j < i; ++j) + mem[i][k] = Math.max(mem[i][k], largestSumOfAverages(nums, j, k - 1, prefix, mem) + + (prefix[i] - prefix[j]) / (i - j)); + + return mem[i][k]; + } +} diff --git a/solutions/814. Binary Tree Pruning/814.cpp b/solutions/814. Binary Tree Pruning/814.cpp new file mode 100644 index 00000000000..a0ca8d26c82 --- /dev/null +++ b/solutions/814. Binary Tree Pruning/814.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + TreeNode* pruneTree(TreeNode* root) { + if (root == nullptr) + return nullptr; + root->left = pruneTree(root->left); + root->right = pruneTree(root->right); + if (root->left == nullptr && root->right == nullptr && root->val == 0) + return nullptr; + return root; + } +}; diff --git a/solutions/814. Binary Tree Pruning/814.java b/solutions/814. Binary Tree Pruning/814.java new file mode 100644 index 00000000000..ecc0245b22f --- /dev/null +++ b/solutions/814. Binary Tree Pruning/814.java @@ -0,0 +1,11 @@ +class Solution { + public TreeNode pruneTree(TreeNode root) { + if (root == null) + return null; + root.left = pruneTree(root.left); + root.right = pruneTree(root.right); + if (root.left == null && root.right == null && root.val == 0) + return null; + return root; + } +} diff --git a/solutions/814. Binary Tree Pruning/814.py b/solutions/814. Binary Tree Pruning/814.py new file mode 100644 index 00000000000..bb6bf6dee9a --- /dev/null +++ b/solutions/814. Binary Tree Pruning/814.py @@ -0,0 +1,9 @@ +class Solution: + def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: + return None + root.left = self.pruneTree(root.left) + root.right = self.pruneTree(root.right) + if not root.left and not root.right and not root.val: + return None + return root diff --git a/solutions/815. Bus Routes/815.cpp b/solutions/815. Bus Routes/815.cpp new file mode 100644 index 00000000000..380f4719eac --- /dev/null +++ b/solutions/815. Bus Routes/815.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + int numBusesToDestination(vector>& routes, int source, + int target) { + if (source == target) + return 0; + + unordered_map> graph; // {route: [buses]} + unordered_set usedBuses; + + for (int i = 0; i < routes.size(); ++i) + for (const int route : routes[i]) + graph[route].push_back(i); + + int ans = 0; + queue q{{source}}; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const int route = q.front(); + q.pop(); + for (const int bus : graph[route]) + if (usedBuses.insert(bus).second) + for (const int nextRoute : routes[bus]) { + if (nextRoute == target) + return ans; + q.push(nextRoute); + } + } + } + + return -1; + } +}; diff --git a/solutions/815. Bus Routes/815.java b/solutions/815. Bus Routes/815.java new file mode 100644 index 00000000000..787769e016a --- /dev/null +++ b/solutions/815. Bus Routes/815.java @@ -0,0 +1,33 @@ +class Solution { + public int numBusesToDestination(int[][] routes, int source, int target) { + if (source == target) + return 0; + + Map> graph = new HashMap<>(); // {route: [buses]} + Set usedBuses = new HashSet<>(); + + for (int i = 0; i < routes.length; ++i) + for (final int route : routes[i]) { + graph.putIfAbsent(route, new ArrayList<>()); + graph.get(route).add(i); + } + + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(source)); + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + for (final int bus : graph.get(q.poll())) + if (usedBuses.add(bus)) + for (final int nextRoute : routes[bus]) { + if (nextRoute == target) + return ans; + q.offer(nextRoute); + } + } + } + + return -1; + } +} diff --git a/solutions/815. Bus Routes/815.py b/solutions/815. Bus Routes/815.py new file mode 100644 index 00000000000..69f032bbb57 --- /dev/null +++ b/solutions/815. Bus Routes/815.py @@ -0,0 +1,28 @@ +class Solution: + def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int: + if source == target: + return 0 + + graph = collections.defaultdict(list) + usedBuses = set() + + for i in range(len(routes)): + for route in routes[i]: + graph[route].append(i) + + ans = 0 + q = collections.deque([source]) + + while q: + ans += 1 + for _ in range(len(q)): + for bus in graph[q.popleft()]: + if bus in usedBuses: + continue + usedBuses.add(bus) + for nextRoute in routes[bus]: + if nextRoute == target: + return ans + q.append(nextRoute) + + return -1 diff --git a/solutions/816. Ambiguous Coordinates/816.cpp b/solutions/816. Ambiguous Coordinates/816.cpp new file mode 100644 index 00000000000..5d7b14c29bd --- /dev/null +++ b/solutions/816. Ambiguous Coordinates/816.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector ambiguousCoordinates(string s) { + vector ans; + s = s.substr(1, s.length() - 2); + + for (int i = 1; i < s.length(); ++i) + for (const string& x : splits(s.substr(0, i))) + for (const string& y : splits(s.substr(i))) + ans.push_back('(' + x + ", " + y + ')'); + + return ans; + } + + private: + vector splits(const string& s) { + if (s.empty() || s.length() > 1 && s.front() == '0' && s.back() == '0') + return {}; + if (s.back() == '0') + return {s}; + if (s.front() == '0') + return {"0." + s.substr(1)}; + + vector candidates{s}; + for (int i = 1; i < s.length(); ++i) + candidates.push_back(s.substr(0, i) + '.' + s.substr(i)); + return candidates; + } +}; diff --git a/solutions/816. Ambiguous Coordinates/816.java b/solutions/816. Ambiguous Coordinates/816.java new file mode 100644 index 00000000000..65e02afd9db --- /dev/null +++ b/solutions/816. Ambiguous Coordinates/816.java @@ -0,0 +1,27 @@ +class Solution { + public List ambiguousCoordinates(String s) { + List ans = new ArrayList<>(); + s = s.substring(1, s.length() - 1); + + for (int i = 1; i < s.length(); ++i) + for (final String x : splits(s.substring(0, i))) + for (final String y : splits(s.substring(i))) + ans.add("(" + x + ", " + y + ")"); + + return ans; + } + + private List splits(final String s) { + if (s.isEmpty() || s.length() > 1 && s.charAt(0) == '0' && s.charAt(s.length() - 1) == '0') + return new ArrayList<>(); + if (s.charAt(s.length() - 1) == '0') + return new ArrayList<>(Arrays.asList(s)); + if (s.charAt(0) == '0') + return new ArrayList<>(Arrays.asList("0." + s.substring(1))); + + List res = new ArrayList<>(Arrays.asList(s)); + for (int i = 1; i < s.length(); ++i) + res.add(s.substring(0, i) + "." + s.substring(i)); + return res; + } +} diff --git a/solutions/816. Ambiguous Coordinates/816.py b/solutions/816. Ambiguous Coordinates/816.py new file mode 100644 index 00000000000..809e7a6e2e9 --- /dev/null +++ b/solutions/816. Ambiguous Coordinates/816.py @@ -0,0 +1,20 @@ +class Solution: + def ambiguousCoordinates(self, s: str) -> List[str]: + def splits(s: str) -> List[str]: + if not s or len(s) > 1 and s[0] == s[-1] == '0': + return [] + if s[-1] == '0': + return [s] + if s[0] == '0': + return [s[0] + '.' + s[1:]] + return [s] + [s[:i] + '.' + s[i:] for i in range(1, len(s))] + + ans = [] + s = s[1:-1] + + for i in range(1, len(s)): + for x in splits(s[:i]): + for y in splits(s[i:]): + ans.append('(%s, %s)' % (x, y)) + + return ans diff --git a/solutions/817. Linked List Components/817.cpp b/solutions/817. Linked List Components/817.cpp new file mode 100644 index 00000000000..ac60a33317a --- /dev/null +++ b/solutions/817. Linked List Components/817.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + int numComponents(ListNode* head, vector& nums) { + int ans = 0; + unordered_set setNums{nums.begin(), nums.end()}; + + for (; head; head = head->next) + if (setNums.contains(head->val) && + (!head->next || !setNums.contains(head->next->val))) + ++ans; + + return ans; + } +}; diff --git a/solutions/817. Linked List Components/817.java b/solutions/817. Linked List Components/817.java new file mode 100644 index 00000000000..9ac03f2249d --- /dev/null +++ b/solutions/817. Linked List Components/817.java @@ -0,0 +1,15 @@ +class Solution { + public int numComponents(ListNode head, int[] nums) { + int ans = 0; + Set setNums = new HashSet<>(); + + for (final int g : nums) + setNums.add(g); + + for (; head != null; head = head.next) + if (setNums.contains(head.val) && (head.next == null || !setNums.contains(head.next.val))) + ++ans; + + return ans; + } +} diff --git a/solutions/817. Linked List Components/817.py b/solutions/817. Linked List Components/817.py new file mode 100644 index 00000000000..7eb242b0e72 --- /dev/null +++ b/solutions/817. Linked List Components/817.py @@ -0,0 +1,11 @@ +class Solution: + def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int: + ans = 0 + numsSet = set(nums) + + while head: + if head.val in numsSet and (head.next == None or head.next.val not in numsSet): + ans += 1 + head = head.next + + return ans diff --git a/solutions/818. Race Car/818.cpp b/solutions/818. Race Car/818.cpp new file mode 100644 index 00000000000..53b9f77589b --- /dev/null +++ b/solutions/818. Race Car/818.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int racecar(int target) { + vector mem(target + 1, -1); + return racecar(target, mem); + } + + private: + int racecar(int i, vector& mem) { + if (mem[i] >= 0) + return mem[i]; + + int res = INT_MAX; + int x = 1; // xA := (2^x - 1) unit distance + int j = (1 << x) - 1; // j = 2^x - 1, k = 2^y - 1 + + // (xA + 1R) + (yA + 1R) + racecar(i - (j - k)) + for (; j < i; j = (1 << ++x) - 1) + for (int y = 0, k = 0; k < j; k = (1 << ++y) - 1) + res = min(res, (x + 1) + (y + 1) + racecar(i - (j - k), mem)); + + // xA || (xA + 1R) + racecar(j - i) + return mem[i] = min(res, i == j ? x : x + 1 + racecar(j - i, mem)); + } +}; diff --git a/solutions/818. Race Car/818.java b/solutions/818. Race Car/818.java new file mode 100644 index 00000000000..5963368f56c --- /dev/null +++ b/solutions/818. Race Car/818.java @@ -0,0 +1,24 @@ +class Solution { + public int racecar(int target) { + int[] mem = new int[target + 1]; + Arrays.fill(mem, -1); + return racecar(target, mem); + } + + private int racecar(int i, int[] mem) { + if (mem[i] >= 0) + return mem[i]; + + int res = Integer.MAX_VALUE; + int x = 1; // xA := (2^x - 1) unit distance + int j = (1 << x) - 1; // j = 2^x - 1, k = 2^y - 1 + + // (xA + 1R) + (yA + 1R) + racecar(i - (j - k)) + for (; j < i; j = (1 << ++x) - 1) + for (int y = 0, k = 0; k < j; k = (1 << ++y) - 1) + res = Math.min(res, (x + 1) + (y + 1) + racecar(i - (j - k), mem)); + + // xA || (xA + 1R) + racecar(j - i) + return mem[i] = Math.min(res, i == j ? x : x + 1 + racecar(j - i, mem)); + } +} diff --git a/solutions/819. Most Common Word/819.cpp b/solutions/819. Most Common Word/819.cpp new file mode 100644 index 00000000000..4ad8b1eceeb --- /dev/null +++ b/solutions/819. Most Common Word/819.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string mostCommonWord(string paragraph, vector& banned) { + string ans; + int maxCount = 0; + unordered_map count; + unordered_set bannedSet{banned.begin(), banned.end()}; + + // Make the paragraph lowercased and remove all the punctuations. + for (char& c : paragraph) + c = isalpha(c) ? tolower(c) : ' '; + + istringstream iss(paragraph); + + for (string word; iss >> word;) + if (!bannedSet.contains(word)) + ++count[word]; + + for (const auto& [word, freq] : count) + if (freq > maxCount) { + maxCount = freq; + ans = word; + } + + return ans; + } +}; diff --git a/solutions/819. Most Common Word/819.java b/solutions/819. Most Common Word/819.java new file mode 100644 index 00000000000..26cc55b1aeb --- /dev/null +++ b/solutions/819. Most Common Word/819.java @@ -0,0 +1,15 @@ +class Solution { + public String mostCommonWord(String paragraph, String[] banned) { + Pair ans = new Pair<>("", 0); + Set bannedSet = new HashSet<>(Arrays.asList(banned)); + Map count = new HashMap<>(); + String[] words = paragraph.replaceAll("\\W+", " ").toLowerCase().split("\\s+"); + + for (final String word : words) + if (!bannedSet.contains(word)) + if (count.merge(word, 1, Integer::sum) > ans.getValue()) + ans = new Pair<>(word, count.get(word)); + + return ans.getKey(); + } +} diff --git a/solutions/819. Most Common Word/819.py b/solutions/819. Most Common Word/819.py new file mode 100644 index 00000000000..8de0bc08701 --- /dev/null +++ b/solutions/819. Most Common Word/819.py @@ -0,0 +1,5 @@ +class Solution: + def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: + banned = set(banned) + words = re.findall(r'\w+', paragraph.lower()) + return collections.Counter(word for word in words if word not in banned).most_common(1)[0][0] diff --git a/solutions/82. Remove Duplicates from Sorted List II/82.cpp b/solutions/82. Remove Duplicates from Sorted List II/82.cpp new file mode 100644 index 00000000000..8144bab376d --- /dev/null +++ b/solutions/82. Remove Duplicates from Sorted List II/82.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode dummy(0, head); + ListNode* prev = &dummy; + + while (head) { + while (head->next && head->val == head->next->val) + head = head->next; + if (prev->next == head) + prev = prev->next; + else + prev->next = head->next; + head = head->next; + } + + return dummy.next; + } +}; diff --git a/solutions/82. Remove Duplicates from Sorted List II/82.java b/solutions/82. Remove Duplicates from Sorted List II/82.java new file mode 100644 index 00000000000..7387a595c60 --- /dev/null +++ b/solutions/82. Remove Duplicates from Sorted List II/82.java @@ -0,0 +1,18 @@ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode prev = dummy; + + while (head != null) { + while (head.next != null && head.val == head.next.val) + head = head.next; + if (prev.next == head) + prev = prev.next; + else + prev.next = head.next; + head = head.next; + } + + return dummy.next; + } +} diff --git a/solutions/82. Remove Duplicates from Sorted List II/82.py b/solutions/82. Remove Duplicates from Sorted List II/82.py new file mode 100644 index 00000000000..093246b92ca --- /dev/null +++ b/solutions/82. Remove Duplicates from Sorted List II/82.py @@ -0,0 +1,15 @@ +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + dummy = ListNode(0, head) + prev = dummy + + while head: + while head.next and head.val == head.next.val: + head = head.next + if prev.next == head: + prev = prev.next + else: + prev.next = head.next + head = head.next + + return dummy.next diff --git a/solutions/820. Short Encoding of Words/820-2.cpp b/solutions/820. Short Encoding of Words/820-2.cpp new file mode 100644 index 00000000000..9acc83a99b7 --- /dev/null +++ b/solutions/820. Short Encoding of Words/820-2.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int minimumLengthEncoding(vector& words) { + unordered_set wordsSet(words.begin(), words.end()); + + for (const string& word : words) { + const string_view sv(word); + for (int i = 1; i < word.length(); ++i) + wordsSet.erase(sv.substr(i)); + } + + return accumulate(wordsSet.begin(), wordsSet.end(), 0, + [](int subtotal, const auto& sv) { + return subtotal + sv.length() + 1; + }); + } +}; diff --git a/solutions/820. Short Encoding of Words/820.cpp b/solutions/820. Short Encoding of Words/820.cpp new file mode 100644 index 00000000000..4e837b76ba6 --- /dev/null +++ b/solutions/820. Short Encoding of Words/820.cpp @@ -0,0 +1,37 @@ +struct TrieNode { + vector> children; + int depth = 0; + TrieNode() : children(26) {} +}; + +class Solution { + public: + int minimumLengthEncoding(vector& words) { + int ans = 0; + shared_ptr root = make_shared(); + vector> heads; + + for (const string& word : unordered_set(words.begin(), words.end())) + heads.push_back(insert(root, word)); + + for (shared_ptr head : heads) + if (ranges::all_of(head->children, + [](const auto& child) { return child == nullptr; })) + ans += head->depth + 1; + + return ans; + } + + private: + shared_ptr insert(shared_ptr root, const string& word) { + shared_ptr node = root; + for (const char c : string(word.rbegin(), word.rend())) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->depth = word.length(); + return node; + } +}; diff --git a/solutions/820. Short Encoding of Words/820.java b/solutions/820. Short Encoding of Words/820.java new file mode 100644 index 00000000000..d629f3a0547 --- /dev/null +++ b/solutions/820. Short Encoding of Words/820.java @@ -0,0 +1,33 @@ +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public int depth = 0; +} + +class Solution { + public int minimumLengthEncoding(String[] words) { + int ans = 0; + TrieNode root = new TrieNode(); + List heads = new ArrayList<>(); + + for (final String word : new HashSet<>(Arrays.asList(words))) + heads.add(insert(root, word)); + + for (TrieNode head : heads) + if (Arrays.stream(head.children).allMatch(child -> child == null)) + ans += head.depth + 1; + + return ans; + } + + private TrieNode insert(TrieNode root, final String word) { + TrieNode node = root; + for (final char c : new StringBuilder(word).reverse().toString().toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.depth = word.length(); + return node; + } +} diff --git a/solutions/820. Short Encoding of Words/820.py b/solutions/820. Short Encoding of Words/820.py new file mode 100644 index 00000000000..9f266157873 --- /dev/null +++ b/solutions/820. Short Encoding of Words/820.py @@ -0,0 +1,23 @@ +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.depth = 0 + + +class Solution: + def minimumLengthEncoding(self, words: List[str]) -> int: + root = TrieNode() + leaves = [] + + def insert(word: str) -> TrieNode: + node = root + for c in reversed(word): + node = node.children.setdefault(c, TrieNode()) + node.depth = len(word) + return node + + for word in set(words): + leaves.append(insert(word)) + + return sum(leaf.depth + 1 for leaf in leaves + if not len(leaf.children)) diff --git a/solutions/821. Shortest Distance to a Character/821.cpp b/solutions/821. Shortest Distance to a Character/821.cpp new file mode 100644 index 00000000000..e1c26ea6200 --- /dev/null +++ b/solutions/821. Shortest Distance to a Character/821.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + vector shortestToChar(string s, char c) { + const int n = s.length(); + vector ans(n); + int prev = -n; + + for (int i = 0; i < n; ++i) { + if (s[i] == c) + prev = i; + ans[i] = i - prev; + } + + for (int i = prev - 1; i >= 0; --i) { + if (s[i] == c) + prev = i; + ans[i] = min(ans[i], prev - i); + } + + return ans; + } +}; diff --git a/solutions/821. Shortest Distance to a Character/821.java b/solutions/821. Shortest Distance to a Character/821.java new file mode 100644 index 00000000000..f0ee4476abe --- /dev/null +++ b/solutions/821. Shortest Distance to a Character/821.java @@ -0,0 +1,21 @@ +class Solution { + public int[] shortestToChar(String s, char c) { + final int n = s.length(); + int[] ans = new int[n]; + int prev = -n; + + for (int i = 0; i < n; ++i) { + if (s[i] == c) + prev = i; + ans[i] = i - prev; + } + + for (int i = prev - 1; i >= 0; --i) { + if (s[i] == c) + prev = i; + ans[i] = Math.min(ans[i], prev - i); + } + + return ans; + } +} diff --git a/solutions/821. Shortest Distance to a Character/821.py b/solutions/821. Shortest Distance to a Character/821.py new file mode 100644 index 00000000000..39f121a930f --- /dev/null +++ b/solutions/821. Shortest Distance to a Character/821.py @@ -0,0 +1,17 @@ +class Solution: + def shortestToChar(self, s: str, c: str) -> List[int]: + n = len(s) + ans = [0] * n + prev = -n + + for i in range(n): + if s[i] == c: + prev = i + ans[i] = i - prev + + for i in range(prev - 1, -1, -1): + if s[i] == c: + prev = i + ans[i] = min(ans[i], prev - i) + + return ans diff --git a/solutions/822. Card Flipping Game/822.cpp b/solutions/822. Card Flipping Game/822.cpp new file mode 100644 index 00000000000..4114ab555f6 --- /dev/null +++ b/solutions/822. Card Flipping Game/822.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int flipgame(vector& fronts, vector& backs) { + constexpr int kMax = 2001; + int ans = kMax; + unordered_set same; + + for (int i = 0; i < fronts.size(); ++i) + if (fronts[i] == backs[i]) + same.insert(fronts[i]); + + for (const int front : fronts) + if (!same.contains(front)) + ans = min(ans, front); + + for (const int back : backs) + if (!same.contains(back)) + ans = min(ans, back); + + return ans == kMax ? 0 : ans; + } +}; diff --git a/solutions/822. Card Flipping Game/822.java b/solutions/822. Card Flipping Game/822.java new file mode 100644 index 00000000000..de4771055eb --- /dev/null +++ b/solutions/822. Card Flipping Game/822.java @@ -0,0 +1,21 @@ +class Solution { + public int flipgame(int[] fronts, int[] backs) { + final int kMax = 2001; + int ans = kMax; + Set same = new HashSet<>(); + + for (int i = 0; i < fronts.length; ++i) + if (fronts[i] == backs[i]) + same.add(fronts[i]); + + for (final int front : fronts) + if (!same.contains(front)) + ans = Math.min(ans, front); + + for (final int back : backs) + if (!same.contains(back)) + ans = Math.min(ans, back); + + return ans == kMax ? 0 : ans; + } +} diff --git a/solutions/822. Card Flipping Game/822.py b/solutions/822. Card Flipping Game/822.py new file mode 100644 index 00000000000..4f861e0666a --- /dev/null +++ b/solutions/822. Card Flipping Game/822.py @@ -0,0 +1,7 @@ +class Solution: + def flipgame(self, fronts: List[int], backs: List[int]) -> int: + same = {front + for front, back in zip(fronts, backs) + if front == back} + return min([num for num in fronts + backs + if num not in same] or [0]) diff --git a/solutions/823. Binary Trees With Factors/823.cpp b/solutions/823. Binary Trees With Factors/823.cpp new file mode 100644 index 00000000000..b8f599286b4 --- /dev/null +++ b/solutions/823. Binary Trees With Factors/823.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int numFactoredBinaryTrees(vector& arr) { + constexpr int kMod = 1'000'000'007; + const int n = arr.size(); + // dp[i] := the number of binary trees with arr[i] as the root + vector dp(n, 1); + unordered_map numToIndex; + + ranges::sort(arr); + + for (int i = 0; i < n; ++i) + numToIndex[arr[i]] = i; + + for (int i = 0; i < n; ++i) // arr[i] is the root + for (int j = 0; j < i; ++j) + if (arr[i] % arr[j] == 0) { // arr[j] is the left subtree + const int right = arr[i] / arr[j]; + if (const auto it = numToIndex.find(right); it != numToIndex.cend()) { + dp[i] += dp[j] * dp[it->second]; + dp[i] %= kMod; + } + } + + return accumulate(dp.begin(), dp.end(), 0L) % kMod; + } +}; diff --git a/solutions/823. Binary Trees With Factors/823.java b/solutions/823. Binary Trees With Factors/823.java new file mode 100644 index 00000000000..7df139424ee --- /dev/null +++ b/solutions/823. Binary Trees With Factors/823.java @@ -0,0 +1,27 @@ +class Solution { + public int numFactoredBinaryTrees(int[] arr) { + final int kMod = 1_000_000_007; + final int n = arr.length; + // dp[i] := the number of binary trees with arr[i] as the root + long[] dp = new long[n]; + Map numToIndex = new HashMap<>(); + + Arrays.sort(arr); + Arrays.fill(dp, 1); + + for (int i = 0; i < n; ++i) + numToIndex.put(arr[i], i); + + for (int i = 0; i < n; ++i) // arr[i] is the root + for (int j = 0; j < i; ++j) + if (arr[i] % arr[j] == 0) { // arr[j] is the left subtree + final int right = arr[i] / arr[j]; + if (numToIndex.containsKey(right)) { + dp[i] += dp[j] * dp[numToIndex.get(right)]; + dp[i] %= kMod; + } + } + + return (int) (Arrays.stream(dp).sum() % kMod); + } +} diff --git a/solutions/823. Binary Trees With Factors/823.py b/solutions/823. Binary Trees With Factors/823.py new file mode 100644 index 00000000000..4c2b48d9f43 --- /dev/null +++ b/solutions/823. Binary Trees With Factors/823.py @@ -0,0 +1,18 @@ +class Solution: + def numFactoredBinaryTrees(self, arr: List[int]) -> int: + kMod = 1_000_000_007 + n = len(arr) + # dp[i] := the number of binary trees with arr[i] as the root + dp = [1] * n + arr.sort() + numToIndex = {a: i for i, a in enumerate(arr)} + + for i, root in enumerate(arr): # arr[i] is the root + for j in range(i): + if root % arr[j] == 0: # arr[j] is the left subtree + right = root // arr[j] + if right in numToIndex: + dp[i] += dp[j] * dp[numToIndex[right]] + dp[i] %= kMod + + return sum(dp) % kMod diff --git a/solutions/824. Goat Latin/824.cpp b/solutions/824. Goat Latin/824.cpp new file mode 100644 index 00000000000..d5110544c99 --- /dev/null +++ b/solutions/824. Goat Latin/824.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + string toGoatLatin(string sentence) { + string ans; + istringstream iss(sentence); + + int i = 1; + for (string word; iss >> word;) { + if (i > 1) + ans += ' '; + if (isVowel(word[0])) + ans += word; + else + ans += word.substr(1) + word[0]; + ans += "ma" + string(i++, 'a'); + } + + return ans; + } + + private: + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/824. Goat Latin/824.java b/solutions/824. Goat Latin/824.java new file mode 100644 index 00000000000..0a47aeb306b --- /dev/null +++ b/solutions/824. Goat Latin/824.java @@ -0,0 +1,22 @@ +class Solution { + public String toGoatLatin(String sentence) { + StringBuilder sb = new StringBuilder(); + + int i = 1; + for (final String word : sentence.split(" ")) { + if (i > 1) + sb.append(" "); + if (isVowel(word.charAt(0))) + sb.append(word); + else + sb.append(word.substring(1) + word.charAt(0)); + sb.append("ma").append("a".repeat(i++)); + } + + return sb.toString(); + } + + private boolean isVowel(char c) { + return "aeiouAEIOU".indexOf(c) != -1; + } +} diff --git a/solutions/824. Goat Latin/824.py b/solutions/824. Goat Latin/824.py new file mode 100644 index 00000000000..267a09e18ad --- /dev/null +++ b/solutions/824. Goat Latin/824.py @@ -0,0 +1,17 @@ +class Solution: + def toGoatLatin(self, sentence: str) -> str: + ans = [] + kVowels = 'aeiouAEIOU' + + i = 1 + for word in sentence.split(): + if i > 1: + ans.append(' ') + if word[0] in kVowels: + ans.append(word) + else: + ans.append(word[1:] + word[0]) + ans.append('ma' + 'a' * i) + i += 1 + + return ''.join(ans) diff --git a/solutions/825. Friends Of Appropriate Ages/825.cpp b/solutions/825. Friends Of Appropriate Ages/825.cpp new file mode 100644 index 00000000000..b448821f28f --- /dev/null +++ b/solutions/825. Friends Of Appropriate Ages/825.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int numFriendRequests(vector& ages) { + int ans = 0; + unordered_map count; + + for (const int age : ages) + ++count[age]; + + for (const auto& [ageA, countA] : count) + for (const auto& [ageB, countB] : count) + if (request(ageA, ageB)) + if (ageA == ageB) + ans += countA * (countB - 1); + else + ans += countA * countB; + + return ans; + } + + private: + bool request(int ageA, int ageB) { + return !(ageB <= 0.5 * ageA + 7 || ageB > ageA || ageB > 100 && ageA < 100); + } +}; diff --git a/solutions/825. Friends Of Appropriate Ages/825.java b/solutions/825. Friends Of Appropriate Ages/825.java new file mode 100644 index 00000000000..c28be993a52 --- /dev/null +++ b/solutions/825. Friends Of Appropriate Ages/825.java @@ -0,0 +1,26 @@ +class Solution { + public int numFriendRequests(int[] ages) { + int ans = 0; + int[] count = new int[121]; + + for (final int age : ages) + ++count[age]; + + for (int ageA = 1; ageA <= 120; ++ageA) + for (int ageB = 1; ageB <= 120; ++ageB) { + final int countA = count[ageA]; + final int countB = count[ageB]; + if (countA > 0 && countB > 0 && request(ageA, ageB)) + if (ageA == ageB) + ans += countA * (countB - 1); + else + ans += countA * countB; + } + + return ans; + } + + private boolean request(int ageA, int ageB) { + return !(ageB <= 0.5 * ageA + 7 || ageB > ageA || ageB > 100 && ageA < 100); + } +} diff --git a/solutions/825. Friends Of Appropriate Ages/825.py b/solutions/825. Friends Of Appropriate Ages/825.py new file mode 100644 index 00000000000..bf0b302ec21 --- /dev/null +++ b/solutions/825. Friends Of Appropriate Ages/825.py @@ -0,0 +1,16 @@ +class Solution: + def numFriendRequests(self, ages: List[int]) -> int: + ans = 0 + count = [0] * 121 + + for age in ages: + count[age] += 1 + + for i in range(15, 121): + ans += count[i] * (count[i] - 1) + + for i in range(15, 121): + for j in range(i // 2 + 8, i): + ans += count[i] * count[j] + + return ans diff --git a/solutions/826. Most Profit Assigning Work/826.cpp b/solutions/826. Most Profit Assigning Work/826.cpp new file mode 100644 index 00000000000..1c2331013c4 --- /dev/null +++ b/solutions/826. Most Profit Assigning Work/826.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int maxProfitAssignment(vector& difficulty, vector& profit, + vector& worker) { + int ans = 0; + vector> jobs; + + for (int i = 0; i < difficulty.size(); ++i) + jobs.emplace_back(difficulty[i], profit[i]); + + ranges::sort(jobs); + ranges::sort(worker); + + int i = 0; + int maxProfit = 0; + + for (const int w : worker) { + for (; i < jobs.size() && w >= jobs[i].first; ++i) + maxProfit = max(maxProfit, jobs[i].second); + ans += maxProfit; + } + + return ans; + } +}; diff --git a/solutions/826. Most Profit Assigning Work/826.java b/solutions/826. Most Profit Assigning Work/826.java new file mode 100644 index 00000000000..9d4f105f153 --- /dev/null +++ b/solutions/826. Most Profit Assigning Work/826.java @@ -0,0 +1,23 @@ +class Solution { + public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) { + int ans = 0; + List> jobs = new ArrayList<>(); + + for (int i = 0; i < difficulty.length; ++i) + jobs.add(new Pair<>(difficulty[i], profit[i])); + + Collections.sort(jobs, Comparator.comparing(Pair::getKey)); + Arrays.sort(worker); + + int i = 0; + int maxProfit = 0; + + for (final int w : worker) { + for (; i < jobs.size() && w >= jobs.get(i).getKey(); ++i) + maxProfit = Math.max(maxProfit, jobs.get(i).getValue()); + ans += maxProfit; + } + + return ans; + } +} diff --git a/solutions/826. Most Profit Assigning Work/826.py b/solutions/826. Most Profit Assigning Work/826.py new file mode 100644 index 00000000000..ee55a3bd75d --- /dev/null +++ b/solutions/826. Most Profit Assigning Work/826.py @@ -0,0 +1,16 @@ +class Solution: + def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: + ans = 0 + jobs = sorted(zip(difficulty, profit)) + worker.sort(reverse=1) + + i = 0 + maxProfit = 0 + + for w in sorted(worker): + while i < len(jobs) and w >= jobs[i][0]: + maxProfit = max(maxProfit, jobs[i][1]) + i += 1 + ans += maxProfit + + return ans diff --git a/solutions/827. Making A Large Island/827.cpp b/solutions/827. Making A Large Island/827.cpp new file mode 100644 index 00000000000..9f954b1ecab --- /dev/null +++ b/solutions/827. Making A Large Island/827.cpp @@ -0,0 +1,54 @@ +class Solution { + public: + int largestIsland(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int maxSize = 0; + // sizes[i] := the size of the i-th connected component (starting from 2) + vector sizes{0, 0}; + + // For each 1 in the grid, paint all the connected 1s with the next + // available color (2, 3, and so on). Also, remember the size of the island + // we just painted with that color. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + sizes.push_back(paint(grid, i, j, sizes.size())); // Paint 2, 3, ... + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0) { + const unordered_set neighborIds{ + getId(grid, i + 1, j), getId(grid, i - 1, j), + getId(grid, i, j + 1), getId(grid, i, j - 1)}; + maxSize = max(maxSize, 1 + getSize(neighborIds, sizes)); + } + + return maxSize == 0 ? m * n : maxSize; + } + + private: + int paint(vector>& grid, int i, int j, int id) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return 0; + if (grid[i][j] != 1) + return 0; + grid[i][j] = id; // grid[i][j] is part of the id-th connected component. + return 1 + paint(grid, i + 1, j, id) + paint(grid, i - 1, j, id) + + paint(grid, i, j + 1, id) + paint(grid, i, j - 1, id); + } + + // Gets the id of grid[i][j] and returns 0 if it's out-of-bounds. + int getId(const vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return 0; // Invalid + return grid[i][j]; + } + + int getSize(const unordered_set& neighborIds, const vector& sizes) { + int size = 0; + for (const int neighborId : neighborIds) + size += sizes[neighborId]; + return size; + } +}; diff --git a/solutions/827. Making A Large Island/827.java b/solutions/827. Making A Large Island/827.java new file mode 100644 index 00000000000..fe14f2584da --- /dev/null +++ b/solutions/827. Making A Large Island/827.java @@ -0,0 +1,53 @@ +class Solution { + public int largestIsland(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int maxSize = 0; + // sizes[i] := the size of the i-th connected component (starting from 2) + List sizes = new ArrayList<>(Arrays.asList(0, 0)); + + // For each 1 in the grid, paint all the connected 1s with the next + // available color (2, 3, and so on). Also, remember the size of the island + // we just painted with that color. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { + sizes.add(paint(grid, i, j, sizes.size())); // Paint 2, 3, ... + } + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 0) { + Set neighborIds = + new HashSet<>(Arrays.asList(getId(grid, i - 1, j), getId(grid, i + 1, j), + getId(grid, i, j + 1), getId(grid, i, j - 1))); + maxSize = Math.max(maxSize, 1 + getSize(grid, neighborIds, sizes)); + } + + return maxSize == 0 ? m * n : maxSize; + } + + private int paint(int[][] grid, int i, int j, int id) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return 0; + if (grid[i][j] != 1) + return 0; + grid[i][j] = id; // grid[i][j] is part of the id-th connected component. + return 1 + paint(grid, i + 1, j, id) + paint(grid, i - 1, j, id) + paint(grid, i, j + 1, id) + + paint(grid, i, j - 1, id); + } + + // Gets the id of grid[i][j] and returns 0 if it's out-of-bounds. + private int getId(int[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return 0; // Invalid + return grid[i][j]; + } + + private int getSize(int[][] grid, Set neighborIds, List sizes) { + int size = 0; + for (final int neighborId : neighborIds) + size += sizes.get(neighborId); + return size; + } +} diff --git a/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.cpp b/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.cpp new file mode 100644 index 00000000000..b173a7c36ac --- /dev/null +++ b/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int uniqueLetterString(string s) { + const int n = s.length(); + int ans = 0; + // lastSeen[c] := the index of the last time ('a' + i) appeared + vector lastSeen(26, -1); + // prevSeen[c] := the previous index of the last time ('a' + i) appeared + vector prevLastSeen(26, -1); + + for (int i = 0; i < n; ++i) { + const int c = s[i] - 'A'; + if (lastSeen[c] != -1) + ans += (i - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c]); + prevLastSeen[c] = lastSeen[c]; + lastSeen[c] = i; + } + + for (int c = 0; c < 26; ++c) + ans += (n - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c]); + + return ans; + } +}; diff --git a/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.java b/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.java new file mode 100644 index 00000000000..c83d7d0e205 --- /dev/null +++ b/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.java @@ -0,0 +1,25 @@ +class Solution { + public int uniqueLetterString(String s) { + int n = s.length(); + int ans = 0; + // lastSeen[c] := the index of the last time ('a' + i) appeared + int[] lastSeen = new int[26]; + // prevSeen[c] := the previous index of the last time ('a' + i) appeared + int[] prevLastSeen = new int[26]; + Arrays.fill(lastSeen, -1); + Arrays.fill(prevLastSeen, -1); + + for (int i = 0; i < n; ++i) { + final int c = s.charAt(i) - 'A'; + if (lastSeen[c] != -1) + ans += (i - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c]); + prevLastSeen[c] = lastSeen[c]; + lastSeen[c] = i; + } + + for (int c = 0; c < 26; ++c) + ans += (n - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c]); + + return ans; + } +} diff --git a/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.py b/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.py new file mode 100644 index 00000000000..d00301c138f --- /dev/null +++ b/solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.py @@ -0,0 +1,18 @@ +class Solution: + def uniqueLetterString(self, s: str) -> int: + ans = 0 + # lastSeen[c] := the index of the last time ('a' + i) appeared + lastSeen = collections.defaultdict(lambda: -1) + # prevSeen[c] := the previous index of the last time ('a' + i) appeared + prevLastSeen = collections.defaultdict(lambda: -1) + + for i, c in enumerate(s): + if c in lastSeen: + ans += (i - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c]) + prevLastSeen[c] = lastSeen[c] + lastSeen[c] = i + + for c in string.ascii_uppercase: + ans += (len(s) - lastSeen[c]) * (lastSeen[c] - prevLastSeen[c]) + + return ans diff --git a/solutions/828. Count Unique Characters of All Substrings of a Given String/828.cpp b/solutions/828. Count Unique Characters of All Substrings of a Given String/828.cpp new file mode 100644 index 00000000000..c5fe1ec8572 --- /dev/null +++ b/solutions/828. Count Unique Characters of All Substrings of a Given String/828.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int uniqueLetterString(string s) { + int ans = 0; + // the number of unique letters in all the substrings ending in the index so + // far + int dp = 0; + vector lastCount(26); + vector lastSeen(26, -1); + + for (int i = 0; i < s.length(); ++i) { + const int c = s[i] - 'A'; + const int newCount = i - lastSeen[c]; + // Substract the duplicates. + dp -= lastCount[c]; + // Add count of s[lastSeen[c] + 1..i], s[lastSeen[c] + 2..i], ..., s[i]. + dp += newCount; + lastCount[c] = newCount; + lastSeen[c] = i; + ans += dp; + } + + return ans; + } +}; diff --git a/solutions/828. Count Unique Characters of All Substrings of a Given String/828.java b/solutions/828. Count Unique Characters of All Substrings of a Given String/828.java new file mode 100644 index 00000000000..3a56fb13418 --- /dev/null +++ b/solutions/828. Count Unique Characters of All Substrings of a Given String/828.java @@ -0,0 +1,25 @@ +class Solution { + public int uniqueLetterString(String s) { + int ans = 0; + // the number of unique letters in all the substrings ending in the index so + // far + int dp = 0; + int[] lastCount = new int[26]; + int[] lastSeen = new int[26]; + Arrays.fill(lastSeen, -1); + + for (int i = 0; i < s.length(); ++i) { + final int c = s.charAt(i) - 'A'; + final int newCount = i - lastSeen[c]; + // Substract the duplicates. + dp -= lastCount[c]; + // Add count of s[lastSeen[c] + 1..i], s[lastSeen[c] + 2..i], ..., s[i]. + dp += newCount; + lastCount[c] = newCount; + lastSeen[c] = i; + ans += dp; + } + + return ans; + } +} diff --git a/solutions/828. Count Unique Characters of All Substrings of a Given String/828.py b/solutions/828. Count Unique Characters of All Substrings of a Given String/828.py new file mode 100644 index 00000000000..771f907a6db --- /dev/null +++ b/solutions/828. Count Unique Characters of All Substrings of a Given String/828.py @@ -0,0 +1,20 @@ +class Solution: + def uniqueLetterString(self, s: str) -> int: + ans = 0 + # the number of unique letters in all the substrings ending in the index so + # far + dp = 0 + lastCount = {} + lastSeen = {} + + for i, c in enumerate(s): + newCount = i - lastSeen.get(c, -1) + # Substract the duplicates. + dp -= lastCount.get(c, 0) + # Add count of s[lastSeen[c] + 1..i], s[lastSeen[c] + 2..i], ..., s[i]. + dp += newCount + lastCount[c] = newCount + lastSeen[c] = i + ans += dp + + return ans diff --git a/solutions/829. Consecutive Numbers Sum/829.cpp b/solutions/829. Consecutive Numbers Sum/829.cpp new file mode 100644 index 00000000000..df65a94bf19 --- /dev/null +++ b/solutions/829. Consecutive Numbers Sum/829.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + int consecutiveNumbersSum(int n) { + int ans = 0; + for (int i = 1, triangleNum = i; triangleNum <= n; ++i, triangleNum += i) + if ((n - triangleNum) % i == 0) + ++ans; + return ans; + } +}; diff --git a/solutions/829. Consecutive Numbers Sum/829.java b/solutions/829. Consecutive Numbers Sum/829.java new file mode 100644 index 00000000000..cdf9f3b02a0 --- /dev/null +++ b/solutions/829. Consecutive Numbers Sum/829.java @@ -0,0 +1,9 @@ +class Solution { + public int consecutiveNumbersSum(int n) { + int ans = 0; + for (int i = 1, triangleNum = i; triangleNum <= n; ++i, triangleNum += i) + if ((n - triangleNum) % i == 0) + ++ans; + return ans; + } +} diff --git a/solutions/829. Consecutive Numbers Sum/829.py b/solutions/829. Consecutive Numbers Sum/829.py new file mode 100644 index 00000000000..d1abd6e275c --- /dev/null +++ b/solutions/829. Consecutive Numbers Sum/829.py @@ -0,0 +1,11 @@ +class Solution: + def consecutiveNumbersSum(self, n: int) -> int: + ans = 0 + i = 1 + triangleNum = 1 + while triangleNum <= n: + if (n - triangleNum) % i == 0: + ans += 1 + i += 1 + triangleNum += i + return ans diff --git a/solutions/83. Remove Duplicates from Sorted List/83.cpp b/solutions/83. Remove Duplicates from Sorted List/83.cpp new file mode 100644 index 00000000000..926de8c046e --- /dev/null +++ b/solutions/83. Remove Duplicates from Sorted List/83.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* curr = head; + + while (curr) { + while (curr->next && curr->val == curr->next->val) + curr->next = curr->next->next; + curr = curr->next; + } + + return head; + } +}; diff --git a/solutions/83. Remove Duplicates from Sorted List/83.java b/solutions/83. Remove Duplicates from Sorted List/83.java new file mode 100644 index 00000000000..d5af71abb47 --- /dev/null +++ b/solutions/83. Remove Duplicates from Sorted List/83.java @@ -0,0 +1,13 @@ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode curr = head; + + while (curr != null) { + while (curr.next != null && curr.val == curr.next.val) + curr.next = curr.next.next; + curr = curr.next; + } + + return head; + } +} diff --git a/solutions/83. Remove Duplicates from Sorted List/83.py b/solutions/83. Remove Duplicates from Sorted List/83.py new file mode 100644 index 00000000000..24d5ca4ee17 --- /dev/null +++ b/solutions/83. Remove Duplicates from Sorted List/83.py @@ -0,0 +1,10 @@ +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + curr = head + + while curr: + while curr.next and curr.val == curr.next.val: + curr.next = curr.next.next + curr = curr.next + + return head diff --git a/solutions/830. Positions of Large Groups/830.cpp b/solutions/830. Positions of Large Groups/830.cpp new file mode 100644 index 00000000000..127d58de119 --- /dev/null +++ b/solutions/830. Positions of Large Groups/830.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector> largeGroupPositions(string s) { + const int n = s.length(); + vector> ans; + + for (int i = 0, j = 0; i < n; i = j) { + while (j < n && s[j] == s[i]) + ++j; + if (j - i >= 3) + ans.push_back({i, j - 1}); + } + + return ans; + } +}; diff --git a/solutions/830. Positions of Large Groups/830.java b/solutions/830. Positions of Large Groups/830.java new file mode 100644 index 00000000000..067a6dcebb8 --- /dev/null +++ b/solutions/830. Positions of Large Groups/830.java @@ -0,0 +1,15 @@ +class Solution { + public List> largeGroupPositions(String s) { + final int n = s.length(); + List> ans = new ArrayList<>(); + + for (int i = 0, j = 0; i < n; i = j) { + while (j < n && s.charAt(j) == s.charAt(i)) + ++j; + if (j - i >= 3) + ans.add(Arrays.asList(i, j - 1)); + } + + return ans; + } +} diff --git a/solutions/830. Positions of Large Groups/830.py b/solutions/830. Positions of Large Groups/830.py new file mode 100644 index 00000000000..572ce49dee7 --- /dev/null +++ b/solutions/830. Positions of Large Groups/830.py @@ -0,0 +1,15 @@ +class Solution: + def largeGroupPositions(self, s: str) -> List[List[int]]: + n = len(s) + ans = [] + i = 0 + j = 0 + + while i < n: + while j < n and s[j] == s[i]: + j += 1 + if j - i >= 3: + ans.append([i, j - 1]) + i = j + + return ans diff --git a/solutions/831. Masking Personal Information/831.cpp b/solutions/831. Masking Personal Information/831.cpp new file mode 100644 index 00000000000..d222527baf2 --- /dev/null +++ b/solutions/831. Masking Personal Information/831.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string maskPII(string s) { + const int atIndex = s.find('@'); + if (atIndex != string::npos) { + ranges::transform(s, s.begin(), ::tolower); + return s.substr(0, 1) + "*****" + s.substr(atIndex - 1); + } + + string ans; + for (const char c : s) + if (isdigit(c)) + ans += c; + + if (ans.length() == 10) + return "***-***-" + ans.substr(ans.length() - 4); + return '+' + string(ans.length() - 10, '*') + "-***-***-" + + ans.substr(ans.length() - 4); + } +}; diff --git a/solutions/831. Masking Personal Information/831.java b/solutions/831. Masking Personal Information/831.java new file mode 100644 index 00000000000..e6bb6b8e01e --- /dev/null +++ b/solutions/831. Masking Personal Information/831.java @@ -0,0 +1,19 @@ +class Solution { + public String maskPII(String s) { + final int atIndex = s.indexOf('@'); + if (atIndex > 0) { + s = s.toLowerCase(); + return s.charAt(0) + "*****" + s.substring(atIndex - 1); + } + + StringBuilder sb = new StringBuilder(); + for (final char c : s.toCharArray()) + if (Character.isDigit(c)) + sb.append(c); + + if (sb.length() == 10) + return "***-***-" + sb.substring(sb.length() - 4).toString(); + return '+' + "*".repeat(sb.length() - 10) + "-***-***-" + + sb.substring(sb.length() - 4).toString(); + } +} diff --git a/solutions/831. Masking Personal Information/831.py b/solutions/831. Masking Personal Information/831.py new file mode 100644 index 00000000000..7141483aff7 --- /dev/null +++ b/solutions/831. Masking Personal Information/831.py @@ -0,0 +1,12 @@ +class Solution: + def maskPII(self, s: str) -> str: + atIndex = s.find('@') + if atIndex != -1: + s = s.lower() + return s[0] + '*' * 5 + s[atIndex - 1:] + + ans = ''.join(c for c in s if c.isdigit()) + + if len(ans) == 10: + return '***-***-' + ans[-4:] + return '+' + '*' * (len(ans) - 10) + '-***-***-' + ans[-4:] diff --git a/solutions/832. Flipping an Image/832.cpp b/solutions/832. Flipping an Image/832.cpp new file mode 100644 index 00000000000..aa2514aeff2 --- /dev/null +++ b/solutions/832. Flipping an Image/832.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector> flipAndInvertImage(vector>& A) { + const int n = A.size(); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < (n + 1) / 2; ++j) { + const int temp = A[i][j]; + A[i][j] = A[i][n - j - 1] ^ 1; + A[i][n - j - 1] = temp ^ 1; + } + + return A; + } +}; diff --git a/solutions/832. Flipping an Image/832.java b/solutions/832. Flipping an Image/832.java new file mode 100644 index 00000000000..b3276bc225e --- /dev/null +++ b/solutions/832. Flipping an Image/832.java @@ -0,0 +1,14 @@ +class Solution { + public int[][] flipAndInvertImage(int[][] A) { + final int n = A.length; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < (n + 1) / 2; ++j) { + final int temp = A[i][j]; + A[i][j] = A[i][n - j - 1] ^ 1; + A[i][n - j - 1] = temp ^ 1; + } + + return A; + } +} diff --git a/solutions/832. Flipping an Image/832.py b/solutions/832. Flipping an Image/832.py new file mode 100644 index 00000000000..b7a2362eada --- /dev/null +++ b/solutions/832. Flipping an Image/832.py @@ -0,0 +1,9 @@ +class Solution: + def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: + n = len(A) + + for i in range(n): + for j in range((n + 2) // 2): + A[i][j], A[i][n - j - 2] = A[i][n - j - 1] ^ 2, A[i][j] ^ 1 + + return A diff --git a/solutions/833. Find And Replace in String/833.cpp b/solutions/833. Find And Replace in String/833.cpp new file mode 100644 index 00000000000..31b7ff0b691 --- /dev/null +++ b/solutions/833. Find And Replace in String/833.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + string findReplaceString(string s, vector& indices, + vector& sources, vector& targets) { + vector> sortedIndices; + + for (int i = 0; i < indices.size(); ++i) + sortedIndices.emplace_back(indices[i], i); + + ranges::sort(sortedIndices, greater<>()); + + for (const auto& [index, i] : sortedIndices) { + const string& source = sources[i]; + const string& target = targets[i]; + if (s.substr(index, source.length()) == source) + s = s.substr(0, index) + target + s.substr(index + source.length()); + } + + return s; + } +}; diff --git a/solutions/833. Find And Replace in String/833.java b/solutions/833. Find And Replace in String/833.java new file mode 100644 index 00000000000..ede379eab2f --- /dev/null +++ b/solutions/833. Find And Replace in String/833.java @@ -0,0 +1,21 @@ +class Solution { + public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) { + List> sortedIndices = new ArrayList<>(); + + for (int i = 0; i < indices.length; ++i) + sortedIndices.add(new Pair<>(indices[i], i)); + + Collections.sort(sortedIndices, (a, b) -> b.getKey() - a.getKey()); + + for (Pair sortedIndex : sortedIndices) { + final int index = sortedIndex.getKey(); + final int i = sortedIndex.getValue(); + final String source = sources[i]; + final String target = targets[i]; + if (s.substring(index, index + source.length()).equals(source)) + s = s.substring(0, index) + target + s.substring(index + source.length()); + } + + return s; + } +} diff --git a/solutions/833. Find And Replace in String/833.py b/solutions/833. Find And Replace in String/833.py new file mode 100644 index 00000000000..84e0d1ecb14 --- /dev/null +++ b/solutions/833. Find And Replace in String/833.py @@ -0,0 +1,7 @@ +class Solution: + def findReplaceString(self, s: str, indexes: List[int], + sources: List[str], targets: List[str]) -> str: + for index, source, target in sorted(zip(indexes, sources, targets), reverse=True): + if s[index:index + len(source)] == source: + s = s[:index] + target + s[index + len(source):] + return s diff --git a/solutions/834. Sum of Distances in Tree/834.cpp b/solutions/834. Sum of Distances in Tree/834.cpp new file mode 100644 index 00000000000..b3fdc582069 --- /dev/null +++ b/solutions/834. Sum of Distances in Tree/834.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + vector sumOfDistancesInTree(int n, vector>& edges) { + vector ans(n); + vector count(n, 1); + vector> tree(n); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + tree[u].insert(v); + tree[v].insert(u); + } + + postorder(tree, 0, -1, count, ans); + preorder(tree, 0, -1, count, ans); + return ans; + } + + private: + void postorder(const vector>& tree, int node, int parent, + vector& count, vector& ans) { + for (const int child : tree[node]) { + if (child == parent) + continue; + postorder(tree, child, node, count, ans); + count[node] += count[child]; + ans[node] += ans[child] + count[child]; + } + } + + void preorder(const vector>& tree, int node, int parent, + vector& count, vector& ans) { + for (const int child : tree[node]) { + if (child == parent) + continue; + // count[child] nodes are 1 step closer from child than parent. + // (n - count[child]) nodes are 1 step farther from child than parent. + ans[child] = ans[node] - count[child] + (tree.size() - count[child]); + preorder(tree, child, node, count, ans); + } + } +}; diff --git a/solutions/834. Sum of Distances in Tree/834.java b/solutions/834. Sum of Distances in Tree/834.java new file mode 100644 index 00000000000..546175984f3 --- /dev/null +++ b/solutions/834. Sum of Distances in Tree/834.java @@ -0,0 +1,44 @@ +class Solution { + public int[] sumOfDistancesInTree(int n, int[][] edges) { + int[] ans = new int[n]; + int[] count = new int[n]; + Set[] tree = new Set[n]; + + Arrays.fill(count, 1); + + for (int i = 0; i < n; ++i) + tree[i] = new HashSet<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + postorder(tree, 0, -1, count, ans); + preorder(tree, 0, -1, count, ans); + return ans; + } + + private void postorder(Set[] tree, int node, int parent, int[] count, int[] ans) { + for (final int child : tree[node]) { + if (child == parent) + continue; + postorder(tree, child, node, count, ans); + count[node] += count[child]; + ans[node] += ans[child] + count[child]; + } + } + + private void preorder(Set[] tree, int node, int parent, int[] count, int[] ans) { + for (final int child : tree[node]) { + if (child == parent) + continue; + // count[child] nodes are 1 step closer from child than parent. + // (n - count[child]) nodes are 1 step farther from child than parent. + ans[child] = ans[node] - count[child] + (tree.length - count[child]); + preorder(tree, child, node, count, ans); + } + } +} diff --git a/solutions/834. Sum of Distances in Tree/834.py b/solutions/834. Sum of Distances in Tree/834.py new file mode 100644 index 00000000000..d44f7a78db7 --- /dev/null +++ b/solutions/834. Sum of Distances in Tree/834.py @@ -0,0 +1,30 @@ +class Solution: + def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]: + ans = [0] * n + count = [1] * n + tree = collections.defaultdict(set) + + for u, v in edges: + tree[u].add(v) + tree[v].add(u) + + def postorder(node, parent=None): + for child in tree[node]: + if child == parent: + continue + postorder(child, node) + count[node] += count[child] + ans[node] += ans[child] + count[child] + + def preorder(node, parent=None): + for child in tree[node]: + if child == parent: + continue + # count[child] nodes are 1 step closer from child than parent. + # (n - count[child]) nodes are 1 step farther from child than parent. + ans[child] = ans[node] - count[child] + (n - count[child]) + preorder(child, node) + + postorder(0) + preorder(0) + return ans diff --git a/solutions/835. Image Overlap/835.cpp b/solutions/835. Image Overlap/835.cpp new file mode 100644 index 00000000000..a5ba1154934 --- /dev/null +++ b/solutions/835. Image Overlap/835.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int largestOverlap(vector>& img1, vector>& img2) { + constexpr int kMagic = 100; + const int n = img1.size(); + int ans = 0; + vector> ones1; + vector> ones2; + unordered_map offsetCount; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + if (img1[i][j] == 1) + ones1.emplace_back(i, j); + if (img2[i][j] == 1) + ones2.emplace_back(i, j); + } + + for (const auto& [ax, ay] : ones1) + for (const auto& [bx, by] : ones2) + ++offsetCount[(ax - bx) * kMagic + (ay - by)]; + + for (const auto& [_, count] : offsetCount) + ans = max(ans, count); + + return ans; + } +}; diff --git a/solutions/835. Image Overlap/835.java b/solutions/835. Image Overlap/835.java new file mode 100644 index 00000000000..f8724d69e4f --- /dev/null +++ b/solutions/835. Image Overlap/835.java @@ -0,0 +1,29 @@ +class Solution { + public int largestOverlap(int[][] img1, int[][] img2) { + final int kMagic = 100; + final int n = img1.length; + int ans = 0; + List ones1 = new ArrayList<>(); + List ones2 = new ArrayList<>(); + Map offsetCount = new HashMap<>(); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + if (img1[i][j] == 1) + ones1.add(new int[] {i, j}); + if (img2[i][j] == 1) + ones2.add(new int[] {i, j}); + } + + for (int[] a : ones1) + for (int[] b : ones2) { + final int key = (a[0] - b[0]) * kMagic + a[1] - b[1]; + offsetCount.merge(key, 1, Integer::sum); + } + + for (final int count : offsetCount.values()) + ans = Math.max(ans, count); + + return ans; + } +} diff --git a/solutions/835. Image Overlap/835.py b/solutions/835. Image Overlap/835.py new file mode 100644 index 00000000000..446be67185f --- /dev/null +++ b/solutions/835. Image Overlap/835.py @@ -0,0 +1,18 @@ +class Solution: + def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: + kMagic = 100 + ones1 = [(i, j) + for i, row in enumerate(img1) + for j, num in enumerate(row) + if num == 1] + ones2 = [(i, j) + for i, row in enumerate(img2) + for j, num in enumerate(row) + if num == 1] + offsetCount = collections.Counter() + + for ax, ay in ones1: + for bx, by in ones2: + offsetCount[(ax - bx) * kMagic + (ay - by)] += 1 + + return max(offsetCount.values()) if offsetCount else 0 diff --git a/solutions/836. Rectangle Overlap/836.cpp b/solutions/836. Rectangle Overlap/836.cpp new file mode 100644 index 00000000000..db47e46a240 --- /dev/null +++ b/solutions/836. Rectangle Overlap/836.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + bool isRectangleOverlap(vector& rec1, vector& rec2) { + return rec1[0] < rec2[2] && rec2[0] < rec1[2] && // + rec1[1] < rec2[3] && rec2[1] < rec1[3]; + } +}; diff --git a/solutions/836. Rectangle Overlap/836.java b/solutions/836. Rectangle Overlap/836.java new file mode 100644 index 00000000000..ca4b1913042 --- /dev/null +++ b/solutions/836. Rectangle Overlap/836.java @@ -0,0 +1,7 @@ +class Solution { + public boolean isRectangleOverlap(int[] rec1, int[] rec2) { + return // + rec1[0] < rec2[2] && rec2[0] < rec1[2] && // + rec1[1] < rec2[3] && rec2[1] < rec1[3]; + } +} diff --git a/solutions/836. Rectangle Overlap/836.py b/solutions/836. Rectangle Overlap/836.py new file mode 100644 index 00000000000..cefb2aee1ee --- /dev/null +++ b/solutions/836. Rectangle Overlap/836.py @@ -0,0 +1,3 @@ +class Solution: + def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: + return rec1[0] < rec2[2] and rec2[0] < rec1[2] and rec1[1] < rec2[3] and rec2[1] < rec1[3] diff --git a/solutions/837. New 21 Game/837.cpp b/solutions/837. New 21 Game/837.cpp new file mode 100644 index 00000000000..6bd32daff2e --- /dev/null +++ b/solutions/837. New 21 Game/837.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + double new21Game(int n, int k, int maxPts) { + // When the game ends, the point is in [k..k - 1 maxPts]. + // P = 1, if n >= k - 1 + maxPts + // P = 0, if n < k (note that the constraints already have k <= n) + if (k == 0 || n >= k - 1 + maxPts) + return 1.0; + + double ans = 0.0; + vector dp(n + 1); // dp[i] := the probability to have i points + dp[0] = 1.0; + double windowSum = dp[0]; // P(i - 1) + P(i - 2) + ... + P(i - maxPts) + + for (int i = 1; i <= n; ++i) { + // The probability to get i points is + // P(i) = [P(i - 1) + P(i - 2) + ... + P(i - maxPts)] / maxPts + dp[i] = windowSum / maxPts; + if (i < k) + windowSum += dp[i]; + else // The game ends. + ans += dp[i]; + if (i - maxPts >= 0) + windowSum -= dp[i - maxPts]; + } + + return ans; + } +}; diff --git a/solutions/837. New 21 Game/837.java b/solutions/837. New 21 Game/837.java new file mode 100644 index 00000000000..e938a79b967 --- /dev/null +++ b/solutions/837. New 21 Game/837.java @@ -0,0 +1,28 @@ +class Solution { + public double new21Game(int n, int k, int maxPts) { + // When the game ends, the point is in [k..k - 1 maxPts]. + // P = 1, if n >= k - 1 + maxPts + // P = 0, if n < k (note that the constraints already have k <= n) + if (k == 0 || n >= k - 1 + maxPts) + return 1.0; + + double ans = 0.0; + double[] dp = new double[n + 1]; // dp[i] := the probability to have i points + dp[0] = 1.0; + double windowSum = dp[0]; // P(i - 1) + P(i - 2) + ... + P(i - maxPts) + + for (int i = 1; i <= n; ++i) { + // The probability to get i points is + // P(i) = [P(i - 1) + P(i - 2) + ... + P(i - maxPts)] / maxPts + dp[i] = windowSum / maxPts; + if (i < k) + windowSum += dp[i]; + else // The game ends. + ans += dp[i]; + if (i - maxPts >= 0) + windowSum -= dp[i - maxPts]; + } + + return ans; + } +} diff --git a/solutions/837. New 21 Game/837.py b/solutions/837. New 21 Game/837.py new file mode 100644 index 00000000000..0e570f4ebd1 --- /dev/null +++ b/solutions/837. New 21 Game/837.py @@ -0,0 +1,24 @@ +class Solution: + def new21Game(self, n: int, k: int, maxPts: int) -> float: + # When the game ends, the point is in [k..k - 1 maxPts]. + # P = 1, if n >= k - 1 + maxPts + # P = 0, if n < k (note that the constraints already have k <= n) + if k == 0 or n >= k - 1 + maxPts: + return 1.0 + + ans = 0.0 + dp = [1.0] + [0] * n # dp[i] := the probability to have i points + windowSum = dp[0] # P(i - 1) + P(i - 2) + ... + P(i - maxPts) + + for i in range(1, n + 1): + # The probability to get i points is + # P(i) = [P(i - 1) + P(i - 2) + ... + P(i - maxPts)] / maxPts + dp[i] = windowSum / maxPts + if i < k: + windowSum += dp[i] + else: # The game ends. + ans += dp[i] + if i - maxPts >= 0: + windowSum -= dp[i - maxPts] + + return ans diff --git a/solutions/838. Push Dominoes/838.cpp b/solutions/838. Push Dominoes/838.cpp new file mode 100644 index 00000000000..0959350fd01 --- /dev/null +++ b/solutions/838. Push Dominoes/838.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + string pushDominoes(string dominoes) { + int L = -1; + int R = -1; + + for (int i = 0; i <= dominoes.length(); ++i) + if (i == dominoes.length() || dominoes[i] == 'R') { + if (L < R) + while (R < i) + dominoes[R++] = 'R'; + R = i; + } else if (dominoes[i] == 'L') { + if (R < L || L == -1 && R == -1) { + if (L == -1 && R == -1) + ++L; + while (L < i) + dominoes[L++] = 'L'; + } else { + int l = R + 1; + int r = i - 1; + while (l < r) { + dominoes[l++] = 'R'; + dominoes[r--] = 'L'; + } + } + L = i; + } + + return dominoes; + } +}; diff --git a/solutions/838. Push Dominoes/838.java b/solutions/838. Push Dominoes/838.java new file mode 100644 index 00000000000..3656ff27631 --- /dev/null +++ b/solutions/838. Push Dominoes/838.java @@ -0,0 +1,32 @@ +class Solution { + public String pushDominoes(String dominoes) { + char[] s = dominoes.toCharArray(); + int L = -1; + int R = -1; + + for (int i = 0; i <= dominoes.length(); ++i) + if (i == dominoes.length() || s[i] == 'R') { + if (L < R) + while (R < i) + s[R++] = 'R'; + R = i; + } else if (s[i] == 'L') { + if (R < L || L == -1 && R == -1) { + if (L == -1 && R == -1) + ++L; + while (L < i) + s[L++] = 'L'; + } else { + int l = R + 1; + int r = i - 1; + while (l < r) { + s[l++] = 'R'; + s[r--] = 'L'; + } + } + L = i; + } + + return new String(s); + } +} diff --git a/solutions/838. Push Dominoes/838.py b/solutions/838. Push Dominoes/838.py new file mode 100644 index 00000000000..c68fc8a72be --- /dev/null +++ b/solutions/838. Push Dominoes/838.py @@ -0,0 +1,31 @@ +class Solution: + def pushDominoes(self, dominoes: str) -> str: + ans = list(dominoes) + L = -1 + R = -1 + + for i in range(len(dominoes) + 1): + if i == len(dominoes) or dominoes[i] == 'R': + if L < R: + while R < i: + ans[R] = 'R' + R += 1 + R = i + elif dominoes[i] == 'L': + if R < L or (L, R) == (-1, -1): + if (L, R) == (-1, -1): + L += 1 + while L < i: + ans[L] = 'L' + L += 1 + else: + l = R + 1 + r = i - 1 + while l < r: + ans[l] = 'R' + ans[r] = 'L' + l += 1 + r -= 1 + L = i + + return ''.join(ans) diff --git a/solutions/839. Similar String Groups/839-2.cpp b/solutions/839. Similar String Groups/839-2.cpp new file mode 100644 index 00000000000..dd882ec5a47 --- /dev/null +++ b/solutions/839. Similar String Groups/839-2.cpp @@ -0,0 +1,58 @@ +class UnionFind { + public: + UnionFind(int n) : count(n), id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + int getCount() const { + return count; + } + + private: + int count; + vector id; + vector rank; + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } +}; + +class Solution { + public: + int numSimilarGroups(vector& A) { + UnionFind uf(A.size()); + + for (int i = 1; i < A.size(); ++i) + for (int j = 0; j < i; ++j) + if (isSimilar(A[i], A[j])) + uf.unionByRank(i, j); + + return uf.getCount(); + } + + private: + bool isSimilar(const string& X, const string& Y) { + int diff = 0; + for (int i = 0; i < X.length(); ++i) + if (X[i] != Y[i] && ++diff > 2) + return false; + return true; + } +}; diff --git a/solutions/839. Similar String Groups/839-2.java b/solutions/839. Similar String Groups/839-2.java new file mode 100644 index 00000000000..7e866fb57d2 --- /dev/null +++ b/solutions/839. Similar String Groups/839-2.java @@ -0,0 +1,58 @@ +class UnionFind { + public UnionFind(int n) { + count = n; + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + --count; + } + + public int getCount() { + return count; + } + + private int count; + private int[] id; + private int[] rank; + + private int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } +} + +class Solution { + public int numSimilarGroups(String[] A) { + UnionFind uf = new UnionFind(A.length); + + for (int i = 1; i < A.length; ++i) + for (int j = 0; j < i; ++j) + if (isSimilar(A[i], A[j])) + uf.unionByRank(i, j); + + return uf.getCount(); + } + + private boolean isSimilar(final String X, final String Y) { + int diff = 0; + for (int i = 0; i < X.length(); ++i) + if (X.charAt(i) != Y.charAt(i) && ++diff > 2) + return false; + return true; + } +} diff --git a/solutions/839. Similar String Groups/839.cpp b/solutions/839. Similar String Groups/839.cpp new file mode 100644 index 00000000000..eadaa456e77 --- /dev/null +++ b/solutions/839. Similar String Groups/839.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int numSimilarGroups(vector& strs) { + int ans = 0; + vector seen(strs.size()); + + for (int i = 0; i < strs.size(); ++i) + if (!seen[i]) { + dfs(strs, i, seen); + ++ans; + } + + return ans; + } + + private: + void dfs(const vector& strs, int i, vector& seen) { + seen[i] = true; + for (int j = 0; j < strs.size(); ++j) + if (!seen[j] && isSimilar(strs[i], strs[j])) + dfs(strs, j, seen); + } + + bool isSimilar(const string& X, const string& Y) { + int diff = 0; + for (int i = 0; i < X.length(); ++i) + if (X[i] != Y[i] && ++diff > 2) + return false; + return true; + } +}; diff --git a/solutions/839. Similar String Groups/839.java b/solutions/839. Similar String Groups/839.java new file mode 100644 index 00000000000..7a7a4bb849a --- /dev/null +++ b/solutions/839. Similar String Groups/839.java @@ -0,0 +1,29 @@ +class Solution { + public int numSimilarGroups(String[] strs) { + int ans = 0; + boolean[] seen = new boolean[strs.length]; + + for (int i = 0; i < strs.length; ++i) + if (!seen[i]) { + dfs(strs, i, seen); + ++ans; + } + + return ans; + } + + private void dfs(final String[] strs, int i, boolean[] seen) { + seen[i] = true; + for (int j = 0; j < strs.length; ++j) + if (!seen[j] && isSimilar(strs[i], strs[j])) + dfs(strs, j, seen); + } + + private boolean isSimilar(final String X, final String Y) { + int diff = 0; + for (int i = 0; i < X.length(); ++i) + if (X.charAt(i) != Y.charAt(i) && ++diff > 2) + return false; + return true; + } +} diff --git a/solutions/84. Largest Rectangle in Histogram/84.cpp b/solutions/84. Largest Rectangle in Histogram/84.cpp new file mode 100644 index 00000000000..9ce7fe967f6 --- /dev/null +++ b/solutions/84. Largest Rectangle in Histogram/84.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int largestRectangleArea(vector& heights) { + int ans = 0; + stack stack; + + for (int i = 0; i <= heights.size(); ++i) { + while (!stack.empty() && + (i == heights.size() || heights[stack.top()] > heights[i])) { + const int h = heights[stack.top()]; + stack.pop(); + const int w = stack.empty() ? i : i - stack.top() - 1; + ans = max(ans, h * w); + } + stack.push(i); + } + + return ans; + } +}; diff --git a/solutions/84. Largest Rectangle in Histogram/84.java b/solutions/84. Largest Rectangle in Histogram/84.java new file mode 100644 index 00000000000..4bf63fd0e73 --- /dev/null +++ b/solutions/84. Largest Rectangle in Histogram/84.java @@ -0,0 +1,17 @@ +class Solution { + public int largestRectangleArea(int[] heights) { + int ans = 0; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i <= heights.length; ++i) { + while (!stack.isEmpty() && (i == heights.length || heights[stack.peek()] > heights[i])) { + final int h = heights[stack.pop()]; + final int w = stack.isEmpty() ? i : i - stack.peek() - 1; + ans = Math.max(ans, h * w); + } + stack.push(i); + } + + return ans; + } +} diff --git a/solutions/84. Largest Rectangle in Histogram/84.py b/solutions/84. Largest Rectangle in Histogram/84.py new file mode 100644 index 00000000000..e5a41391dfe --- /dev/null +++ b/solutions/84. Largest Rectangle in Histogram/84.py @@ -0,0 +1,13 @@ +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + ans = 0 + stack = [] + + for i in range(len(heights) + 1): + while stack and (i == len(heights) or heights[stack[-1]] > heights[i]): + h = heights[stack.pop()] + w = i - stack[-1] - 1 if stack else i + ans = max(ans, h * w) + stack.append(i) + + return ans diff --git a/solutions/840. Magic Squares In Grid/840.cpp b/solutions/840. Magic Squares In Grid/840.cpp new file mode 100644 index 00000000000..efa3f09a7af --- /dev/null +++ b/solutions/840. Magic Squares In Grid/840.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int numMagicSquaresInside(vector>& grid) { + int ans = 0; + + for (int i = 0; i + 2 < grid.size(); ++i) + for (int j = 0; j + 2 < grid[0].size(); ++j) + if (grid[i][j] % 2 == 0 && grid[i + 1][j + 1] == 5) + ans += isMagic(grid, i, j); + + return ans; + } + + private: + int isMagic(const vector>& grid, int i, int j) { + string s; + + for (const int num : {0, 1, 2, 5, 8, 7, 6, 3}) + s += to_string(grid[i + num / 3][j + num % 3]); + + return string("4381672943816729").find(s) != string::npos || + string("9276183492761834").find(s) != string::npos; + } +}; diff --git a/solutions/840. Magic Squares In Grid/840.java b/solutions/840. Magic Squares In Grid/840.java new file mode 100644 index 00000000000..ab7b8941e5f --- /dev/null +++ b/solutions/840. Magic Squares In Grid/840.java @@ -0,0 +1,24 @@ +class Solution { + public int numMagicSquaresInside(int[][] grid) { + int ans = 0; + + for (int i = 0; i + 2 < grid.length; ++i) + for (int j = 0; j + 2 < grid[0].length; ++j) + if (grid[i][j] % 2 == 0 && grid[i + 1][j + 1] == 5) + if (isMagic(grid, i, j)) + ++ans; + + return ans; + } + + private boolean isMagic(int[][] grid, int i, int j) { + String s = new String(""); + + for (final int num : new int[] {0, 1, 2, 5, 8, 7, 6, 3}) + s += Integer.toString(grid[i + num / 3][j + num % 3]); + + return // + new String("4381672943816729").contains(s) || // + new String("9276183492761834").contains(s); + } +} diff --git a/solutions/840. Magic Squares In Grid/840.py b/solutions/840. Magic Squares In Grid/840.py new file mode 100644 index 00000000000..9039f06809f --- /dev/null +++ b/solutions/840. Magic Squares In Grid/840.py @@ -0,0 +1,15 @@ +class Solution: + def numMagicSquaresInside(self, grid: List[List[int]]) -> int: + def isMagic(i: int, j: int) -> int: + s = "".join(str(grid[i + num // 3][j + num % 3]) + for num in [0, 1, 2, 5, 8, 7, 6, 3]) + return s in "43816729" * 2 or s in "43816729"[::-1] * 2 + + ans = 0 + + for i in range(len(grid) - 2): + for j in range(len(grid[0]) - 2): + if grid[i][j] % 2 == 0 and grid[i + 1][j + 1] == 5: + ans += isMagic(i, j) + + return ans diff --git a/solutions/841. Keys and Rooms/841.cpp b/solutions/841. Keys and Rooms/841.cpp new file mode 100644 index 00000000000..6ad32a51348 --- /dev/null +++ b/solutions/841. Keys and Rooms/841.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + bool canVisitAllRooms(vector>& rooms) { + vector seen(rooms.size()); + dfs(rooms, 0, seen); + return ranges::all_of(seen, [](int s) { return s == true; }); + } + + private: + void dfs(const vector>& rooms, int node, vector& seen) { + seen[node] = true; + for (const int child : rooms[node]) + if (!seen[child]) + dfs(rooms, child, seen); + } +}; diff --git a/solutions/841. Keys and Rooms/841.java b/solutions/841. Keys and Rooms/841.java new file mode 100644 index 00000000000..c9b3c88542e --- /dev/null +++ b/solutions/841. Keys and Rooms/841.java @@ -0,0 +1,14 @@ +class Solution { + public boolean canVisitAllRooms(List> rooms) { + int[] seen = new int[rooms.size()]; + dfs(rooms, 0, seen); + return Arrays.stream(seen).allMatch(a -> a == 1); + } + + private void dfs(List> rooms, int node, int[] seen) { + seen[node] = 1; + for (final int child : rooms.get(node)) + if (seen[child] == 0) + dfs(rooms, child, seen); + } +} diff --git a/solutions/841. Keys and Rooms/841.py b/solutions/841. Keys and Rooms/841.py new file mode 100644 index 00000000000..8c5346ba57f --- /dev/null +++ b/solutions/841. Keys and Rooms/841.py @@ -0,0 +1,12 @@ +class Solution: + def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: + seen = [False] * len(rooms) + + def dfs(node: int) -> None: + seen[node] = True + for child in rooms[node]: + if not seen[child]: + dfs(child) + + dfs(0) + return all(seen) diff --git a/solutions/842. Split Array into Fibonacci Sequence/842.cpp b/solutions/842. Split Array into Fibonacci Sequence/842.cpp new file mode 100644 index 00000000000..2769a4de6bc --- /dev/null +++ b/solutions/842. Split Array into Fibonacci Sequence/842.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + vector splitIntoFibonacci(string num) { + vector ans; + dfs(num, 0, ans); + return ans; + } + + private: + bool dfs(const string& num, int s, vector& ans) { + if (s == num.length() && ans.size() >= 3) + return true; + + for (int i = s; i < num.length(); ++i) { + if (num[s] == '0' && i > s) + break; + const long val = stol(num.substr(s, i + 1 - s)); + if (val > INT_MAX) + break; + if (ans.size() >= 2 && + val > ans[ans.size() - 2] + static_cast(ans.back())) + break; + if (ans.size() <= 1 || + val == ans[ans.size() - 2] + static_cast(ans.back())) { + ans.push_back(val); + if (dfs(num, i + 1, ans)) + return true; + ans.pop_back(); + } + } + + return false; + } +}; diff --git a/solutions/842. Split Array into Fibonacci Sequence/842.java b/solutions/842. Split Array into Fibonacci Sequence/842.java new file mode 100644 index 00000000000..a58aeb7773d --- /dev/null +++ b/solutions/842. Split Array into Fibonacci Sequence/842.java @@ -0,0 +1,30 @@ +class Solution { + public List splitIntoFibonacci(String num) { + List ans = new ArrayList<>(); + dfs(num, 0, ans); + return ans; + } + + private boolean dfs(final String num, int s, List ans) { + if (s == num.length() && ans.size() >= 3) + return true; + + for (int i = s; i < num.length(); ++i) { + if (num.charAt(s) == '0' && i > s) + break; + final long val = Long.valueOf(num.substring(s, i + 1)); + if (val > Integer.MAX_VALUE) + break; + if (ans.size() >= 2 && val > ans.get(ans.size() - 2) + ans.get(ans.size() - 1)) + break; + if (ans.size() <= 1 || val == ans.get(ans.size() - 2) + ans.get(ans.size() - 1)) { + ans.add((int) val); + if (dfs(num, i + 1, ans)) + return true; + ans.remove(ans.size() - 1); + } + } + + return false; + } +} diff --git a/solutions/843. Guess the Word/843.cpp b/solutions/843. Guess the Word/843.cpp new file mode 100644 index 00000000000..aa4d1f0a307 --- /dev/null +++ b/solutions/843. Guess the Word/843.cpp @@ -0,0 +1,35 @@ +/** + * // This is the Master's API interface. + * // You should not implement it, or speculate about its implementation + * class Master { + * public: + * int guess(string word); + * }; + */ +class Solution { + public: + void findSecretWord(vector& wordlist, Master& master) { + srand(time(nullptr)); + + for (int i = 0; i < 10; ++i) { + const string& guessedWord = wordlist[rand() % wordlist.size()]; + const int matches = master.guess(guessedWord); + if (matches == 6) + break; + vector updated; + for (const string& word : wordlist) + if (getMatches(guessedWord, word) == matches) + updated.push_back(word); + wordlist = move(updated); + } + } + + private: + int getMatches(const string& s1, const string& s2) { + int matches = 0; + for (int i = 0; i < s1.length(); ++i) + if (s1[i] == s2[i]) + ++matches; + return matches; + } +}; diff --git a/solutions/843. Guess the Word/843.java b/solutions/843. Guess the Word/843.java new file mode 100644 index 00000000000..83401545505 --- /dev/null +++ b/solutions/843. Guess the Word/843.java @@ -0,0 +1,32 @@ +/** + * // This is the Master's API interface. + * // You should not implement it, or speculate about its implementation + * interface Master { + * public int guess(String word) {} + * } + */ +class Solution { + public void findSecretWord(String[] wordlist, Master master) { + Random rand = new Random(); + + for (int i = 0; i < 10; ++i) { + final String guessedWord = wordlist[rand.nextInt(wordlist.length)]; + final int matches = master.guess(guessedWord); + if (matches == 6) + break; + List updated = new ArrayList<>(); + for (final String word : wordlist) + if (getMatches(guessedWord, word) == matches) + updated.add(word); + wordlist = updated.toArray(new String[0]); + } + } + + private int getMatches(final String s1, final String s2) { + int matches = 0; + for (int i = 0; i < s1.length(); ++i) + if (s1.charAt(i) == s2.charAt(i)) + ++matches; + return matches; + } +} diff --git a/solutions/843. Guess the Word/843.py b/solutions/843. Guess the Word/843.py new file mode 100644 index 00000000000..996132a56d3 --- /dev/null +++ b/solutions/843. Guess the Word/843.py @@ -0,0 +1,24 @@ +# """ +# This is Master's API interface. +# You should not implement it, or speculate about its implementation +# """ +# Class Master: +# def guess(self, word: str) -> int: + +class Solution: + def findSecretWord(self, wordlist: List[str], master: 'Master') -> None: + def getMatches(s1: str, s2: str) -> int: + matches = 0 + for c1, c2 in zip(s1, s2): + if c1 == c2: + matches += 1 + return matches + + for _ in range(10): + guessedWord = wordlist[random.randint(0, len(wordlist) - 1)] + matches = master.guess(guessedWord) + if matches == 6: + break + wordlist = [ + word for word in wordlist + if getMatches(guessedWord, word) == matches] diff --git a/solutions/844. Backspace String Compare/844-2.cpp b/solutions/844. Backspace String Compare/844-2.cpp new file mode 100644 index 00000000000..10ad72f1c85 --- /dev/null +++ b/solutions/844. Backspace String Compare/844-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + bool backspaceCompare(string s, string t) { + int i = s.length() - 1; // s' index + int j = t.length() - 1; // t's index + + while (true) { + // Delete characters of s if needed. + int backspace = 0; + while (i >= 0 && (s[i] == '#' || backspace > 0)) { + backspace += s[i] == '#' ? 1 : -1; + --i; + } + // Delete characters of t if needed. + backspace = 0; + while (j >= 0 && (t[j] == '#' || backspace > 0)) { + backspace += t[j] == '#' ? 1 : -1; + --j; + } + if (i >= 0 && j >= 0 && s[i] == t[j]) { + --i; + --j; + } else { + break; + } + } + + return i == -1 && j == -1; + } +}; diff --git a/solutions/844. Backspace String Compare/844-2.java b/solutions/844. Backspace String Compare/844-2.java new file mode 100644 index 00000000000..c6a980bb66f --- /dev/null +++ b/solutions/844. Backspace String Compare/844-2.java @@ -0,0 +1,29 @@ +class Solution { + public boolean backspaceCompare(String s, String t) { + int i = s.length() - 1; // s' index + int j = t.length() - 1; // t's index + + while (true) { + // Delete characters of s if needed. + int backspace = 0; + while (i >= 0 && (s.charAt(i) == '#' || backspace > 0)) { + backspace += s.charAt(i) == '#' ? 1 : -1; + --i; + } + // Delete characters of t if needed. + backspace = 0; + while (j >= 0 && (t.charAt(j) == '#' || backspace > 0)) { + backspace += t.charAt(j) == '#' ? 1 : -1; + --j; + } + if (i >= 0 && j >= 0 && s.charAt(i) == t.charAt(j)) { + --i; + --j; + } else { + break; + } + } + + return i == -1 && j == -1; + } +} diff --git a/solutions/844. Backspace String Compare/844-2.py b/solutions/844. Backspace String Compare/844-2.py new file mode 100644 index 00000000000..209438c01e0 --- /dev/null +++ b/solutions/844. Backspace String Compare/844-2.py @@ -0,0 +1,23 @@ +class Solution: + def backspaceCompare(self, s: str, t: str) -> bool: + i = len(s) - 1 # s' index + j = len(t) - 1 # t's index + + while True: + # Delete characters of s if needed. + backspace = 0 + while i >= 0 and (s[i] == '#' or backspace > 0): + backspace += 1 if s[i] == '#' else -1 + i -= 1 + # Delete characters of t if needed. + backspace = 0 + while j >= 0 and (t[j] == '#' or backspace > 0): + backspace += 1 if t[j] == '#' else -1 + j -= 1 + if i >= 0 and j >= 0 and s[i] == t[j]: + i -= 1 + j -= 1 + else: + break + + return i == -1 and j == -1 diff --git a/solutions/844. Backspace String Compare/844.cpp b/solutions/844. Backspace String Compare/844.cpp new file mode 100644 index 00000000000..eb84bf2e8f7 --- /dev/null +++ b/solutions/844. Backspace String Compare/844.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool backspaceCompare(string s, string t) { + return backspace(s) == backspace(t); + } + + private: + string backspace(const string& s) { + string stack; + for (const char c : s) + if (c != '#') + stack.push_back(c); + else if (!stack.empty()) + stack.pop_back(); + return stack; + } +}; diff --git a/solutions/844. Backspace String Compare/844.java b/solutions/844. Backspace String Compare/844.java new file mode 100644 index 00000000000..ddca46345ba --- /dev/null +++ b/solutions/844. Backspace String Compare/844.java @@ -0,0 +1,15 @@ +class Solution { + public boolean backspaceCompare(String s, String t) { + return backspace(s).equals(backspace(t)); + } + + private String backspace(final String s) { + StringBuilder sb = new StringBuilder(); + for (final char c : s.toCharArray()) + if (c != '#') + sb.append(c); + else if (sb.length() != 0) + sb.deleteCharAt(sb.length() - 1); + return sb.toString(); + } +} diff --git a/solutions/844. Backspace String Compare/844.py b/solutions/844. Backspace String Compare/844.py new file mode 100644 index 00000000000..dca90cec180 --- /dev/null +++ b/solutions/844. Backspace String Compare/844.py @@ -0,0 +1,12 @@ +class Solution: + def backspaceCompare(self, s: str, t: str) -> bool: + def backspace(s: str) -> str: + stack = [] + for c in s: + if c != '#': + stack.append(c) + elif stack: + stack.pop() + return stack + + return backspace(s) == backspace(t) diff --git a/solutions/845. Longest Mountain in Array/845.cpp b/solutions/845. Longest Mountain in Array/845.cpp new file mode 100644 index 00000000000..015ed2f098d --- /dev/null +++ b/solutions/845. Longest Mountain in Array/845.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + int longestMountain(vector& arr) { + int ans = 0; + + for (int i = 0; i + 1 < arr.size();) { + while (i + 1 < arr.size() && arr[i] == arr[i + 1]) + ++i; + + int increasing = 0; + int decreasing = 0; + + while (i + 1 < arr.size() && arr[i] < arr[i + 1]) { + ++increasing; + ++i; + } + + while (i + 1 < arr.size() && arr[i] > arr[i + 1]) { + ++decreasing; + ++i; + } + + if (increasing > 0 && decreasing > 0) + ans = max(ans, increasing + decreasing + 1); + } + + return ans; + } +}; diff --git a/solutions/845. Longest Mountain in Array/845.java b/solutions/845. Longest Mountain in Array/845.java new file mode 100644 index 00000000000..91849f9c71a --- /dev/null +++ b/solutions/845. Longest Mountain in Array/845.java @@ -0,0 +1,28 @@ +class Solution { + public int longestMountain(int[] arr) { + int ans = 0; + + for (int i = 0; i + 1 < arr.length;) { + while (i + 1 < arr.length && arr[i] == arr[i + 1]) + ++i; + + int increasing = 0; + int decreasing = 0; + + while (i + 1 < arr.length && arr[i] < arr[i + 1]) { + ++increasing; + ++i; + } + + while (i + 1 < arr.length && arr[i] > arr[i + 1]) { + ++decreasing; + ++i; + } + + if (increasing > 0 && decreasing > 0) + ans = Math.max(ans, increasing + decreasing + 1); + } + + return ans; + } +} diff --git a/solutions/845. Longest Mountain in Array/845.py b/solutions/845. Longest Mountain in Array/845.py new file mode 100644 index 00000000000..7c0eedac4fa --- /dev/null +++ b/solutions/845. Longest Mountain in Array/845.py @@ -0,0 +1,24 @@ +class Solution: + def longestMountain(self, arr: List[int]) -> int: + ans = 0 + i = 0 + + while i + 1 < len(arr): + while i + 1 < len(arr) and arr[i] == arr[i + 1]: + i += 1 + + increasing = 0 + decreasing = 0 + + while i + 1 < len(arr) and arr[i] < arr[i + 1]: + increasing += 1 + i += 1 + + while i + 1 < len(arr) and arr[i] > arr[i + 1]: + decreasing += 1 + i += 1 + + if increasing > 0 and decreasing > 0: + ans = max(ans, increasing + decreasing + 1) + + return ans diff --git a/solutions/846. Hand of Straights/846.cpp b/solutions/846. Hand of Straights/846.cpp new file mode 100644 index 00000000000..440d0d64da3 --- /dev/null +++ b/solutions/846. Hand of Straights/846.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool isNStraightHand(vector& hand, int groupSize) { + map count; + + for (const int card : hand) + ++count[card]; + + for (const auto& [start, _] : count) { + const int value = count[start]; + if (value > 0) + for (int i = start; i < start + groupSize; ++i) { + count[i] -= value; + if (count[i] < 0) + return false; + } + } + + return true; + } +}; diff --git a/solutions/846. Hand of Straights/846.java b/solutions/846. Hand of Straights/846.java new file mode 100644 index 00000000000..d19b99c8ad5 --- /dev/null +++ b/solutions/846. Hand of Straights/846.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isNStraightHand(int[] hand, int groupSize) { + TreeMap count = new TreeMap<>(); + + for (final int card : hand) + count.merge(card, 1, Integer::sum); + + for (final int start : count.keySet()) { + final int value = count.getOrDefault(start, 0); + if (value > 0) + for (int i = start; i < start + groupSize; ++i) + if (count.merge(i, -value, Integer::sum) < 0) + return false; + } + + return true; + } +} diff --git a/solutions/846. Hand of Straights/846.py b/solutions/846. Hand of Straights/846.py new file mode 100644 index 00000000000..18bc63aab16 --- /dev/null +++ b/solutions/846. Hand of Straights/846.py @@ -0,0 +1,13 @@ +class Solution: + def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: + count = collections.Counter(hand) + + for start in sorted(count): + value = count[start] + if value > 0: + for i in range(start, start + groupSize): + count[i] -= value + if count[i] < 0: + return False + + return True diff --git a/solutions/847. Shortest Path Visiting All Nodes/847.cpp b/solutions/847. Shortest Path Visiting All Nodes/847.cpp new file mode 100644 index 00000000000..a9466185ed4 --- /dev/null +++ b/solutions/847. Shortest Path Visiting All Nodes/847.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int shortestPathLength(vector>& graph) { + const int n = graph.size(); + const int goal = (1 << n) - 1; + + int ans = 0; + queue> q; // (u, state) + vector> seen(n, vector(1 << n)); + + for (int i = 0; i < n; ++i) + q.emplace(i, 1 << i); + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + const auto [u, state] = q.front(); + q.pop(); + if (state == goal) + return ans; + if (seen[u][state]) + continue; + seen[u][state] = true; + for (const int v : graph[u]) + q.emplace(v, state | (1 << v)); + } + ++ans; + } + + return -1; + } +}; diff --git a/solutions/847. Shortest Path Visiting All Nodes/847.java b/solutions/847. Shortest Path Visiting All Nodes/847.java new file mode 100644 index 00000000000..b09201dcd09 --- /dev/null +++ b/solutions/847. Shortest Path Visiting All Nodes/847.java @@ -0,0 +1,30 @@ +class Solution { + public int shortestPathLength(int[][] graph) { + final int n = graph.length; + final int goal = (1 << n) - 1; + + int ans = 0; + Queue> q = new ArrayDeque<>(); // (u, state) + boolean[][] seen = new boolean[n][1 << n]; + + for (int i = 0; i < n; ++i) + q.offer(new Pair<>(i, 1 << i)); + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final int u = q.peek().getKey(); + final int state = q.poll().getValue(); + if (state == goal) + return ans; + if (seen[u][state]) + continue; + seen[u][state] = true; + for (final int v : graph[u]) + q.offer(new Pair<>(v, state | (1 << v))); + } + ++ans; + } + + return -1; + } +} diff --git a/solutions/847. Shortest Path Visiting All Nodes/847.py b/solutions/847. Shortest Path Visiting All Nodes/847.py new file mode 100644 index 00000000000..9e58092dad6 --- /dev/null +++ b/solutions/847. Shortest Path Visiting All Nodes/847.py @@ -0,0 +1,25 @@ +class Solution: + def shortestPathLength(self, graph: List[List[int]]) -> int: + n = len(graph) + goal = (1 << n) - 1 + + ans = 0 + q = collections.deque() # (u, state) + seen = set() + + for i in range(n): + q.append((i, 1 << i)) + + while q: + for _ in range(len(q)): + u, state = q.popleft() + if state == goal: + return ans + if (u, state) in seen: + continue + seen.add((u, state)) + for v in graph[u]: + q.append((v, state | (1 << v))) + ans += 1 + + return -1 diff --git a/solutions/848. Shifting Letters/848.cpp b/solutions/848. Shifting Letters/848.cpp new file mode 100644 index 00000000000..84fac34e8f2 --- /dev/null +++ b/solutions/848. Shifting Letters/848.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string shiftingLetters(string s, vector& shifts) { + string ans; + + for (int i = shifts.size() - 2; i >= 0; --i) + shifts[i] = (shifts[i] + shifts[i + 1]) % 26; + + for (int i = 0; i < s.length(); ++i) + ans += (s[i] - 'a' + shifts[i]) % 26 + 'a'; + + return ans; + } +}; diff --git a/solutions/848. Shifting Letters/848.java b/solutions/848. Shifting Letters/848.java new file mode 100644 index 00000000000..9e6ca8adb80 --- /dev/null +++ b/solutions/848. Shifting Letters/848.java @@ -0,0 +1,13 @@ +class Solution { + public String shiftingLetters(String s, int[] shifts) { + StringBuilder sb = new StringBuilder(); + + for (int i = shifts.length - 2; i >= 0; --i) + shifts[i] = (shifts[i] + shifts[i + 1]) % 26; + + for (int i = 0; i < s.length(); ++i) + sb.append((char) ((s.charAt(i) - 'a' + shifts[i]) % 26 + 'a')); + + return sb.toString(); + } +} diff --git a/solutions/848. Shifting Letters/848.py b/solutions/848. Shifting Letters/848.py new file mode 100644 index 00000000000..26867037c09 --- /dev/null +++ b/solutions/848. Shifting Letters/848.py @@ -0,0 +1,11 @@ +class Solution: + def shiftingLetters(self, s: str, shifts: List[int]) -> str: + ans = [] + + for i in reversed(range(len(shifts) - 1)): + shifts[i] += shifts[i + 1] + + for c, shift in zip(s, shifts): + ans.append(chr((ord(c) - ord('a') + shift) % 26 + ord('a'))) + + return ''.join(ans) diff --git a/solutions/849. Maximize Distance to Closest Person/849.cpp b/solutions/849. Maximize Distance to Closest Person/849.cpp new file mode 100644 index 00000000000..2d48a637082 --- /dev/null +++ b/solutions/849. Maximize Distance to Closest Person/849.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int maxDistToClosest(vector& seats) { + const int n = seats.size(); + int ans = 0; + int j = -1; + + for (int i = 0; i < n; ++i) + if (seats[i] == 1) { + ans = j == -1 ? i : max(ans, (i - j) / 2); + j = i; + } + + return max(ans, n - j - 1); + } +}; diff --git a/solutions/849. Maximize Distance to Closest Person/849.java b/solutions/849. Maximize Distance to Closest Person/849.java new file mode 100644 index 00000000000..2a84e41da6f --- /dev/null +++ b/solutions/849. Maximize Distance to Closest Person/849.java @@ -0,0 +1,15 @@ +class Solution { + public int maxDistToClosest(int[] seats) { + final int n = seats.length; + int ans = 0; + int j = -1; + + for (int i = 0; i < n; ++i) + if (seats[i] == 1) { + ans = j == -1 ? i : Math.max(ans, (i - j) / 2); + j = i; + } + + return Math.max(ans, n - j - 1); + } +} diff --git a/solutions/849. Maximize Distance to Closest Person/849.py b/solutions/849. Maximize Distance to Closest Person/849.py new file mode 100644 index 00000000000..3268b42c753 --- /dev/null +++ b/solutions/849. Maximize Distance to Closest Person/849.py @@ -0,0 +1,12 @@ +class Solution: + def maxDistToClosest(self, seats: List[int]) -> int: + n = len(seats) + ans = 0 + j = -1 + + for i in range(n): + if seats[i] == 1: + ans = i if j == -1 else max(ans, (i - j) // 2) + j = i + + return max(ans, n - j - 1) diff --git a/solutions/85. Maximal Rectangle/85.cpp b/solutions/85. Maximal Rectangle/85.cpp new file mode 100644 index 00000000000..8e4ec722b79 --- /dev/null +++ b/solutions/85. Maximal Rectangle/85.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int maximalRectangle(vector>& matrix) { + if (matrix.empty()) + return 0; + + int ans = 0; + vector hist(matrix[0].size()); + + for (const vector& row : matrix) { + for (int i = 0; i < row.size(); ++i) + hist[i] = row[i] == '0' ? 0 : hist[i] + 1; + ans = max(ans, largestRectangleArea(hist)); + } + + return ans; + } + + private: + int largestRectangleArea(const vector& heights) { + int ans = 0; + stack stack; + + for (int i = 0; i <= heights.size(); ++i) { + while (!stack.empty() && + (i == heights.size() || heights[stack.top()] > heights[i])) { + const int h = heights[stack.top()]; + stack.pop(); + const int w = stack.empty() ? i : i - stack.top() - 1; + ans = max(ans, h * w); + } + stack.push(i); + } + + return ans; + } +}; diff --git a/solutions/85. Maximal Rectangle/85.java b/solutions/85. Maximal Rectangle/85.java new file mode 100644 index 00000000000..c287c9cf539 --- /dev/null +++ b/solutions/85. Maximal Rectangle/85.java @@ -0,0 +1,33 @@ +class Solution { + public int maximalRectangle(char[][] matrix) { + if (matrix.length == 0) + return 0; + + int ans = 0; + int[] hist = new int[matrix[0].length]; + + for (char[] row : matrix) { + for (int i = 0; i < row.length; ++i) + hist[i] = row[i] == '0' ? 0 : hist[i] + 1; + ans = Math.max(ans, largestRectangleArea(hist)); + } + + return ans; + } + + private int largestRectangleArea(int[] heights) { + int ans = 0; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i <= heights.length; ++i) { + while (!stack.isEmpty() && (i == heights.length || heights[stack.peek()] > heights[i])) { + final int h = heights[stack.pop()]; + final int w = stack.isEmpty() ? i : i - stack.peek() - 1; + ans = Math.max(ans, h * w); + } + stack.push(i); + } + + return ans; + } +} diff --git a/solutions/85. Maximal Rectangle/85.py b/solutions/85. Maximal Rectangle/85.py new file mode 100644 index 00000000000..5a1b4331cb2 --- /dev/null +++ b/solutions/85. Maximal Rectangle/85.py @@ -0,0 +1,27 @@ +class Solution: + def maximalRectangle(self, matrix: List[List[str]]) -> int: + if not matrix: + return 0 + + ans = 0 + hist = [0] * len(matrix[0]) + + def largestRectangleArea(heights: List[int]) -> int: + ans = 0 + stack = [] + + for i in range(len(heights) + 1): + while stack and (i == len(heights) or heights[stack[-1]] > heights[i]): + h = heights[stack.pop()] + w = i - stack[-1] - 1 if stack else i + ans = max(ans, h * w) + stack.append(i) + + return ans + + for row in matrix: + for i, num in enumerate(row): + hist[i] = 0 if num == '0' else hist[i] + 1 + ans = max(ans, largestRectangleArea(hist)) + + return ans diff --git a/solutions/850. Rectangle Area II/850.cpp b/solutions/850. Rectangle Area II/850.cpp new file mode 100644 index 00000000000..16929713258 --- /dev/null +++ b/solutions/850. Rectangle Area II/850.cpp @@ -0,0 +1,62 @@ +struct Event { + int x; + int y1; + int y2; + char type; + Event(int x, int y1, int y2, char type) : x(x), y1(y1), y2(y2), type(type) {} +}; + +class Solution { + public: + int rectangleArea(vector>& rectangles) { + constexpr int kMod = 1'000'000'007; + + vector events; + + for (const vector& r : rectangles) { + events.emplace_back(r[0], r[1], r[3], 's'); + events.emplace_back(r[2], r[1], r[3], 'e'); + } + + ranges::sort(events, + [](const auto& a, const auto& b) { return a.x < b.x; }); + + long ans = 0; + int prevX = 0; + vector> yPairs; + + for (const auto& [currX, y1, y2, type] : events) { + if (currX > prevX) { + const int width = currX - prevX; + ans = (ans + width * getHeight(yPairs)) % kMod; + prevX = currX; + } + if (type == 's') { + yPairs.emplace_back(y1, y2); + ranges::sort(yPairs); + } else { // type == 'e' + const auto it = + find(yPairs.begin(), yPairs.end(), pair(y1, y2)); + yPairs.erase(it); + } + } + + return ans % kMod; + } + + private: + long getHeight(const vector>& yPairs) { + int height = 0; + int prevY = 0; + + for (const auto& [y1, y2] : yPairs) { + prevY = max(prevY, y1); + if (y2 > prevY) { + height += y2 - prevY; + prevY = y2; + } + } + + return height; + } +}; diff --git a/solutions/850. Rectangle Area II/850.java b/solutions/850. Rectangle Area II/850.java new file mode 100644 index 00000000000..76a2707bb56 --- /dev/null +++ b/solutions/850. Rectangle Area II/850.java @@ -0,0 +1,63 @@ +class Event { + public int x; + public int y1; + public int y2; + public char type; + public Event(int x, int y1, int y2, char type) { + this.x = x; + this.y1 = y1; + this.y2 = y2; + this.type = type; + } +} + +class Solution { + public int rectangleArea(int[][] rectangles) { + final int kMod = 1_000_000_007; + List events = new ArrayList<>(); + + for (int[] r : rectangles) { + events.add(new Event(r[0], r[1], r[3], 's')); + events.add(new Event(r[2], r[1], r[3], 'e')); + } + + Collections.sort(events, (a, b) -> a.x - b.x); + + long ans = 0; + int prevX = 0; + List> yPairs = new ArrayList<>(); + + for (Event e : events) { + if (e.x > prevX) { + final int width = e.x - prevX; + ans = (ans + width * getHeight(yPairs)) % kMod; + prevX = e.x; + } + if (e.type == 's') { + yPairs.add(new Pair<>(e.y1, e.y2)); + Collections.sort(yPairs, Comparator.comparing(Pair::getKey)); + } else { // type == 'e' + yPairs.remove(new Pair<>(e.y1, e.y2)); + } + } + + return (int) (ans % kMod); + } + + private long getHeight(List> yPairs) { + int height = 0; + int prevY = 0; + + for (Pair pair : yPairs) { + final int y1 = pair.getKey(); + final int y2 = pair.getValue(); + prevY = Math.max(prevY, y1); + if (y2 > prevY) { + height += y2 - prevY; + prevY = y2; + } + } + + return height; + } +} diff --git a/solutions/850. Rectangle Area II/850.py b/solutions/850. Rectangle Area II/850.py new file mode 100644 index 00000000000..b1d1d96f9e1 --- /dev/null +++ b/solutions/850. Rectangle Area II/850.py @@ -0,0 +1,38 @@ +class Solution: + def rectangleArea(self, rectangles: List[List[int]]) -> int: + events = [] + + for x1, y1, x2, y2 in rectangles: + events.append((x1, y1, y2, 's')) + events.append((x2, y1, y2, 'e')) + + events.sort(key=lambda x: x[0]) + + ans = 0 + prevX = 0 + yPairs = [] + + def getHeight(yPairs: List[Tuple[int, int]]) -> int: + height = 0 + prevY = 0 + + for y1, y2 in yPairs: + prevY = max(prevY, y1) + if y2 > prevY: + height += y2 - prevY + prevY = y2 + + return height + + for currX, y1, y2, type in events: + if currX > prevX: + width = currX - prevX + ans += width * getHeight(yPairs) + prevX = currX + if type == 's': + yPairs.append((y1, y2)) + yPairs.sort() + else: # type == 'e' + yPairs.remove((y1, y2)) + + return ans % (10**9 + 7) diff --git a/solutions/851. Loud and Rich/851.cpp b/solutions/851. Loud and Rich/851.cpp new file mode 100644 index 00000000000..478be601b2a --- /dev/null +++ b/solutions/851. Loud and Rich/851.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + vector loudAndRich(vector>& richer, vector& quiet) { + const int n = quiet.size(); + vector ans(n, -1); + vector> graph(n); + + for (const vector& r : richer) { + const int u = r[1]; + const int v = r[0]; + graph[u].push_back(v); + } + + for (int i = 0; i < n; ++i) + dfs(graph, i, quiet, ans); + + return ans; + } + + private: + int dfs(const vector>& graph, int u, const vector& quiet, + vector& ans) { + if (ans[u] != -1) + return ans[u]; + + ans[u] = u; + + for (const int v : graph[u]) { + const int res = dfs(graph, v, quiet, ans); + if (quiet[res] < quiet[ans[u]]) + ans[u] = res; + } + + return ans[u]; + } +}; diff --git a/solutions/851. Loud and Rich/851.java b/solutions/851. Loud and Rich/851.java new file mode 100644 index 00000000000..95d5bac4474 --- /dev/null +++ b/solutions/851. Loud and Rich/851.java @@ -0,0 +1,38 @@ +class Solution { + public int[] loudAndRich(int[][] richer, int[] quiet) { + final int n = quiet.length; + int[] ans = new int[n]; + List[] graph = new List[n]; + + Arrays.fill(ans, -1); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] r : richer) { + final int u = r[1]; + final int v = r[0]; + graph[u].add(v); + } + + for (int i = 0; i < n; ++i) + dfs(graph, i, quiet, ans); + + return ans; + } + + private int dfs(List[] graph, int u, int[] quiet, int[] ans) { + if (ans[u] != -1) + return ans[u]; + + ans[u] = u; + + for (final int v : graph[u]) { + final int res = dfs(graph, v, quiet, ans); + if (quiet[res] < quiet[ans[u]]) + ans[u] = res; + } + + return ans[u]; + } +} diff --git a/solutions/851. Loud and Rich/851.py b/solutions/851. Loud and Rich/851.py new file mode 100644 index 00000000000..33eb1e23d2d --- /dev/null +++ b/solutions/851. Loud and Rich/851.py @@ -0,0 +1,19 @@ +class Solution: + def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: + graph = [[] for _ in range(len(quiet))] + + for v, u in richer: + graph[u].append(v) + + @functools.lru_cache(None) + def dfs(u: int) -> int: + ans = u + + for v in graph[u]: + res = dfs(v) + if quiet[res] < quiet[ans]: + ans = res + + return ans + + return map(dfs, range(len(graph))) diff --git a/solutions/852. Peak Index in a Mountain Array/852.cpp b/solutions/852. Peak Index in a Mountain Array/852.cpp new file mode 100644 index 00000000000..6683ce289d0 --- /dev/null +++ b/solutions/852. Peak Index in a Mountain Array/852.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int peakIndexInMountainArray(vector& arr) { + int l = 0; + int r = arr.size() - 1; + + while (l < r) { + const int m = (l + r) / 2; + if (arr[m] >= arr[m + 1]) + r = m; + else + l = m + 1; + } + + return l; + } +}; diff --git a/solutions/852. Peak Index in a Mountain Array/852.java b/solutions/852. Peak Index in a Mountain Array/852.java new file mode 100644 index 00000000000..a38c182657c --- /dev/null +++ b/solutions/852. Peak Index in a Mountain Array/852.java @@ -0,0 +1,16 @@ +class Solution { + public int peakIndexInMountainArray(int[] arr) { + int l = 0; + int r = arr.length - 1; + + while (l < r) { + final int m = (l + r) / 2; + if (arr[m] >= arr[m + 1]) + r = m; + else + l = m + 1; + } + + return l; + } +} diff --git a/solutions/852. Peak Index in a Mountain Array/852.py b/solutions/852. Peak Index in a Mountain Array/852.py new file mode 100644 index 00000000000..0d41e02e869 --- /dev/null +++ b/solutions/852. Peak Index in a Mountain Array/852.py @@ -0,0 +1,13 @@ +class Solution: + def peakIndexInMountainArray(self, arr: List[int]) -> int: + l = 0 + r = len(arr) - 1 + + while l < r: + m = (l + r) // 2 + if arr[m] >= arr[m + 1]: + r = m + else: + l = m + 1 + + return l diff --git a/solutions/853. Car Fleet/853.cpp b/solutions/853. Car Fleet/853.cpp new file mode 100644 index 00000000000..bdc0e3c71f2 --- /dev/null +++ b/solutions/853. Car Fleet/853.cpp @@ -0,0 +1,29 @@ +struct Car { + int pos; + double time; // the time to reach the target +}; + +class Solution { + public: + int carFleet(int target, vector& position, vector& speed) { + int ans = 0; + vector cars(position.size()); + + for (int i = 0; i < position.size(); ++i) + cars[i] = {position[i], (double)(target - position[i]) / speed[i]}; + + ranges::sort(cars, + [](const auto& a, const auto& b) { return a.pos > b.pos; }); + + double maxTime = 0; // the time of the slowest car to reach the target + + for (const Car& car : cars) + // A car needs more time to reach the target, so it becomes the slowest. + if (car.time > maxTime) { + maxTime = car.time; + ++ans; + } + + return ans; + } +}; diff --git a/solutions/853. Car Fleet/853.java b/solutions/853. Car Fleet/853.java new file mode 100644 index 00000000000..a9b1745a796 --- /dev/null +++ b/solutions/853. Car Fleet/853.java @@ -0,0 +1,32 @@ +class Car { + public int pos; + public double time; + + public Car(int pos, double time) { + this.pos = pos; + this.time = time; + } +} + +class Solution { + public int carFleet(int target, int[] position, int[] speed) { + int ans = 0; + Car[] cars = new Car[position.length]; + + for (int i = 0; i < position.length; ++i) + cars[i] = new Car(position[i], (double) (target - position[i]) / speed[i]); + + Arrays.sort(cars, (a, b) -> b.pos - a.pos); + + double maxTime = 0; // the time of the slowest car to reach the target + + for (Car car : cars) + // A car needs more time to reach the target, so it becomes the slowest. + if (car.time > maxTime) { + maxTime = car.time; + ++ans; + } + + return ans; + } +} diff --git a/solutions/853. Car Fleet/853.py b/solutions/853. Car Fleet/853.py new file mode 100644 index 00000000000..e65cdd3642d --- /dev/null +++ b/solutions/853. Car Fleet/853.py @@ -0,0 +1,15 @@ +class Solution: + def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: + ans = 0 + times = [ + float(target - p) / s for p, s in sorted(zip(position, speed), + reverse=True)] + maxTime = 0 # the time of the slowest car to reach the target + + for time in times: + # A car needs more time to reach the target, so it becomes the slowest. + if time > maxTime: + maxTime = time + ans += 1 + + return ans diff --git a/solutions/854. K-Similar Strings/854.cpp b/solutions/854. K-Similar Strings/854.cpp new file mode 100644 index 00000000000..9a7e3ba763e --- /dev/null +++ b/solutions/854. K-Similar Strings/854.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int kSimilarity(string s1, string s2) { + int ans = 0; + queue q{{s1}}; + unordered_set seen{{s1}}; + + while (!q.empty()) { + for (int sz = q.size(); sz > 0; --sz) { + string curr = q.front(); + q.pop(); + if (curr == s2) + return ans; + for (const string& child : getChildren(curr, s2)) { + if (seen.contains(child)) + continue; + q.push(child); + seen.insert(child); + } + } + ++ans; + } + + return -1; + } + + private: + vector getChildren(string& curr, const string& target) { + vector children; + int i = 0; // the first index s.t. curr[i] != target[i] + while (curr[i] == target[i]) + ++i; + + for (int j = i + 1; j < curr.length(); ++j) + if (curr[j] == target[i]) { + swap(curr[i], curr[j]); + children.push_back(curr); + swap(curr[i], curr[j]); + } + + return children; + } +}; diff --git a/solutions/854. K-Similar Strings/854.java b/solutions/854. K-Similar Strings/854.java new file mode 100644 index 00000000000..03dae4449b5 --- /dev/null +++ b/solutions/854. K-Similar Strings/854.java @@ -0,0 +1,47 @@ +class Solution { + public int kSimilarity(String s1, String s2) { + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(s1)); + Set seen = new HashSet<>(Arrays.asList(s1)); + + while (!q.isEmpty()) { + for (int sz = q.size(); sz > 0; --sz) { + final String curr = q.poll(); + if (curr.equals(s2)) + return ans; + for (final String child : getChildren(curr, s2)) { + if (seen.contains(child)) + continue; + q.offer(child); + seen.add(child); + } + } + ++ans; + } + + return -1; + } + + private List getChildren(final String curr, final String target) { + List children = new ArrayList<>(); + char[] charArray = curr.toCharArray(); + int i = 0; // the first index s.t. curr.charAt(i) != target.charAt(i) + while (curr.charAt(i) == target.charAt(i)) + ++i; + + for (int j = i + 1; j < charArray.length; ++j) + if (curr.charAt(j) == target.charAt(i)) { + swap(charArray, i, j); + children.add(String.valueOf(charArray)); + swap(charArray, i, j); + } + + return children; + } + + private void swap(char[] charArray, int i, int j) { + final char temp = charArray[i]; + charArray[i] = charArray[j]; + charArray[j] = temp; + } +} diff --git a/solutions/854. K-Similar Strings/854.py b/solutions/854. K-Similar Strings/854.py new file mode 100644 index 00000000000..554315399b0 --- /dev/null +++ b/solutions/854. K-Similar Strings/854.py @@ -0,0 +1,34 @@ +class Solution: + def kSimilarity(self, s1: str, s2: str) -> int: + ans = 0 + q = collections.deque([s1]) + seen = {s1} + + while q: + for _ in range(len(q)): + curr = q.popleft() + if curr == s2: + return ans + for child in self._getChildren(curr, s2): + if child in seen: + continue + q.append(child) + seen.add(child) + ans += 1 + + return -1 + + def _getChildren(self, curr: str, target: str) -> List[str]: + children = [] + s = list(curr) + i = 0 # the first index s.t. curr[i] != target[i] + while curr[i] == target[i]: + i += 1 + + for j in range(i + 1, len(s)): + if s[j] == target[i]: + s[i], s[j] = s[j], s[i] + children.append(''.join(s)) + s[i], s[j] = s[j], s[i] + + return children diff --git a/solutions/855. Exam Room/855.cpp b/solutions/855. Exam Room/855.cpp new file mode 100644 index 00000000000..d8b1d40f4c5 --- /dev/null +++ b/solutions/855. Exam Room/855.cpp @@ -0,0 +1,46 @@ +class ExamRoom { + public: + ExamRoom(int n) : n(n) {} + + int seat() { + if (students.empty()) { + students.push_back(0); + map[0] = students.begin(); + return 0; + } + + int prevStudent = -1; + int maxDistToClosest = 0; + int val = 0; // the inserted value + list::iterator pos; // the inserted position + + for (auto it = students.begin(); it != students.end(); ++it) { + if (prevStudent == -1) { // We haven't insert anything before. + maxDistToClosest = *it; // the distance between it and the begining + pos = it; + } else if ((*it - prevStudent) / 2 > maxDistToClosest) { + maxDistToClosest = (*it - prevStudent) / 2; + val = (*it + prevStudent) / 2; + pos = it; + } + prevStudent = *it; + } + + if (n - 1 - students.back() > maxDistToClosest) { + pos = students.end(); + val = n - 1; + } + + map[val] = students.insert(pos, val); + return val; + } + + void leave(int p) { + students.erase(map[p]); + } + + private: + const int n; + list students; + unordered_map::iterator> map; // {p: student iterator} +}; diff --git a/solutions/855. Exam Room/855.java b/solutions/855. Exam Room/855.java new file mode 100644 index 00000000000..6cbafefce0b --- /dev/null +++ b/solutions/855. Exam Room/855.java @@ -0,0 +1,74 @@ +class Node { + public Node prev; + public Node next; + public int value; + + public Node(int value) { + this.value = value; + } +} + +class ExamRoom { + public ExamRoom(int n) { + this.n = n; + join(head, tail); + } + + public int seat() { + if (head.next == tail) { + Node node = new Node(0); + join(head, node); + join(node, tail); + map.put(0, node); + return 0; + } + + int prevStudent = -1; + int maxDistToClosest = 0; + int val = 0; // the inserted value + Node pos = null; // the inserted position + + for (Node node = head; node != tail; node = node.next) { + if (prevStudent == -1) { // We haven't insert anything before. + maxDistToClosest = node.value; // the distance between it and the begining + pos = node; + } else if ((node.value - prevStudent) / 2 > maxDistToClosest) { + maxDistToClosest = (node.value - prevStudent) / 2; + val = (node.value + prevStudent) / 2; + pos = node; + } + prevStudent = node.value; + } + + if (n - 1 - tail.prev.value > maxDistToClosest) { + pos = tail; + val = n - 1; + } + + Node insertedNode = new Node(val); + join(pos.prev, insertedNode); + join(insertedNode, pos); + + map.put(val, insertedNode); + return val; + } + + public void leave(int p) { + Node removedNode = map.get(p); + join(removedNode.prev, removedNode.next); + } + + private int n; + private Node head = new Node(-1); + private Node tail = new Node(-1); + private Map map = new HashMap<>(); // {p: student iterator} + + private void join(Node node1, Node node2) { + node1.next = node2; + node2.prev = node1; + } + + private void remove(Node node) { + join(node.prev, node.next); + } +} diff --git a/solutions/856. Score of Parentheses/856.cpp b/solutions/856. Score of Parentheses/856.cpp new file mode 100644 index 00000000000..e1966b5950b --- /dev/null +++ b/solutions/856. Score of Parentheses/856.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int scoreOfParentheses(string s) { + int ans = 0; + int layer = 0; + + for (int i = 0; i + 1 < s.length(); ++i) { + const char a = s[i]; + const char b = s[i + 1]; + if (a == '(' && b == ')') + ans += 1 << layer; + layer += a == '(' ? 1 : -1; + } + + return ans; + } +}; diff --git a/solutions/856. Score of Parentheses/856.java b/solutions/856. Score of Parentheses/856.java new file mode 100644 index 00000000000..0fa85b05d31 --- /dev/null +++ b/solutions/856. Score of Parentheses/856.java @@ -0,0 +1,16 @@ +class Solution { + public int scoreOfParentheses(String s) { + int ans = 0; + int layer = 0; + + for (int i = 0; i + 1 < s.length(); ++i) { + final char a = s.charAt(i); + final char b = s.charAt(i + 1); + if (a == '(' && b == ')') + ans += 1 << layer; + layer += a == '(' ? 1 : -1; + } + + return ans; + } +} diff --git a/solutions/856. Score of Parentheses/856.py b/solutions/856. Score of Parentheses/856.py new file mode 100644 index 00000000000..101bbc91513 --- /dev/null +++ b/solutions/856. Score of Parentheses/856.py @@ -0,0 +1,11 @@ +class Solution: + def scoreOfParentheses(self, s: str) -> int: + ans = 0 + layer = 0 + + for a, b in itertools.pairwise(s): + if a + b == '()': + ans += 1 << layer + layer += 1 if a == '(' else -1 + + return ans diff --git a/solutions/857. Minimum Cost to Hire K Workers/857.cpp b/solutions/857. Minimum Cost to Hire K Workers/857.cpp new file mode 100644 index 00000000000..d50ec386da8 --- /dev/null +++ b/solutions/857. Minimum Cost to Hire K Workers/857.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + double mincostToHireWorkers(vector& quality, vector& wage, int k) { + double ans = DBL_MAX; + int qualitySum = 0; + // (wagePerQuality, quality) sorted by wagePerQuality + vector> workers; + priority_queue maxHeap; + + for (int i = 0; i < quality.size(); ++i) + workers.emplace_back((double)wage[i] / quality[i], quality[i]); + + ranges::sort(workers); + + for (const auto& [wagePerQuality, q] : workers) { + maxHeap.push(q); + qualitySum += q; + if (maxHeap.size() > k) + qualitySum -= maxHeap.top(), maxHeap.pop(); + if (maxHeap.size() == k) + ans = min(ans, qualitySum * wagePerQuality); + } + + return ans; + } +}; diff --git a/solutions/857. Minimum Cost to Hire K Workers/857.java b/solutions/857. Minimum Cost to Hire K Workers/857.java new file mode 100644 index 00000000000..4cd10c233fa --- /dev/null +++ b/solutions/857. Minimum Cost to Hire K Workers/857.java @@ -0,0 +1,27 @@ +class Solution { + public double mincostToHireWorkers(int[] quality, int[] wage, int k) { + double ans = Double.MAX_VALUE; + int qualitySum = 0; + // (wagePerQuality, quality) sorted by wagePerQuality + Pair[] workers = new Pair[quality.length]; + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + for (int i = 0; i < quality.length; ++i) + workers[i] = new Pair<>((double) wage[i] / quality[i], quality[i]); + + Arrays.sort(workers, (a, b) -> Double.compare(a.getKey(), b.getKey())); + + for (Pair worker : workers) { + final double wagePerQuality = worker.getKey(); + final int q = worker.getValue(); + maxHeap.offer(q); + qualitySum += q; + if (maxHeap.size() > k) + qualitySum -= maxHeap.poll(); + if (maxHeap.size() == k) + ans = Math.min(ans, qualitySum * wagePerQuality); + } + + return ans; + } +} diff --git a/solutions/857. Minimum Cost to Hire K Workers/857.py b/solutions/857. Minimum Cost to Hire K Workers/857.py new file mode 100644 index 00000000000..c19006e0f2e --- /dev/null +++ b/solutions/857. Minimum Cost to Hire K Workers/857.py @@ -0,0 +1,17 @@ +class Solution: + def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float: + ans = math.inf + qualitySum = 0 + # (wagePerQuality, quality) sorted by wagePerQuality + workers = sorted((w / q, q) for q, w in zip(quality, wage)) + maxHeap = [] + + for wagePerQuality, q in workers: + heapq.heappush(maxHeap, -q) + qualitySum += q + if len(maxHeap) > k: + qualitySum += heapq.heappop(maxHeap) + if len(maxHeap) == k: + ans = min(ans, qualitySum * wagePerQuality) + + return ans diff --git a/solutions/858. Mirror Reflection/858.cpp b/solutions/858. Mirror Reflection/858.cpp new file mode 100644 index 00000000000..c8622723178 --- /dev/null +++ b/solutions/858. Mirror Reflection/858.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int mirrorReflection(int p, int q) { + while (p % 2 == 0 && q % 2 == 0) { + p /= 2; + q /= 2; + } + + if (p % 2 == 0) + return 2; + if (q % 2 == 0) + return 0; + return 1; + } +}; diff --git a/solutions/858. Mirror Reflection/858.java b/solutions/858. Mirror Reflection/858.java new file mode 100644 index 00000000000..522a6b27d35 --- /dev/null +++ b/solutions/858. Mirror Reflection/858.java @@ -0,0 +1,14 @@ +class Solution { + public int mirrorReflection(int p, int q) { + while (p % 2 == 0 && q % 2 == 0) { + p /= 2; + q /= 2; + } + + if (p % 2 == 0) + return 2; + if (q % 2 == 0) + return 0; + return 1; + } +} diff --git a/solutions/858. Mirror Reflection/858.py b/solutions/858. Mirror Reflection/858.py new file mode 100644 index 00000000000..87bab5343b8 --- /dev/null +++ b/solutions/858. Mirror Reflection/858.py @@ -0,0 +1,11 @@ +class Solution: + def mirrorReflection(self, p: int, q: int) -> int: + while p % 2 == 0 and q % 2 == 0: + p //= 2 + q //= 2 + + if p % 2 == 0: + return 2 + if q % 2 == 0: + return 0 + return 1 diff --git a/solutions/859. Buddy Strings/859.cpp b/solutions/859. Buddy Strings/859.cpp new file mode 100644 index 00000000000..90288f4bcb5 --- /dev/null +++ b/solutions/859. Buddy Strings/859.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + bool buddyStrings(string s, string goal) { + if (s.length() != goal.length()) + return false; + if (s == goal && hasDuplicateLetters(s)) + return true; + + vector diffIndices; + + for (int i = 0; i < s.length(); ++i) + if (s[i] != goal[i]) + diffIndices.push_back(i); + + return diffIndices.size() == 2 && + s[diffIndices[0]] == goal[diffIndices[1]] && + s[diffIndices[1]] == goal[diffIndices[0]]; + } + + private: + bool hasDuplicateLetters(const string& s) { + vector count(26); + for (const char c : s) + ++count[c - 'a']; + return ranges::any_of(count, [](int freq) { return freq > 1; }); + } +}; diff --git a/solutions/859. Buddy Strings/859.java b/solutions/859. Buddy Strings/859.java new file mode 100644 index 00000000000..7fea4f94948 --- /dev/null +++ b/solutions/859. Buddy Strings/859.java @@ -0,0 +1,25 @@ +class Solution { + public boolean buddyStrings(String s, String goal) { + if (s.length() != goal.length()) + return false; + if (s.equals(goal) && hasDuplicateLetters(s)) + return true; + + List diffIndices = new ArrayList<>(); + + for (int i = 0; i < s.length(); ++i) + if (s.charAt(i) != goal.charAt(i)) + diffIndices.add(i); + + return diffIndices.size() == 2 && + s.charAt(diffIndices.get(0)) == goal.charAt(diffIndices.get(1)) && + s.charAt(diffIndices.get(1)) == goal.charAt(diffIndices.get(0)); + } + + private boolean hasDuplicateLetters(String s) { + int[] count = new int[26]; + for (char c : s.toCharArray()) + ++count[c - 'a']; + return Arrays.stream(count).anyMatch(freq -> freq > 1); + } +} diff --git a/solutions/859. Buddy Strings/859.py b/solutions/859. Buddy Strings/859.py new file mode 100644 index 00000000000..39bf9ad4012 --- /dev/null +++ b/solutions/859. Buddy Strings/859.py @@ -0,0 +1,11 @@ +class Solution: + def buddyStrings(self, s: str, goal: str) -> bool: + if len(s) != len(goal): + return False + if s == goal and len(set(s)) < len(s): + return True + diffIndices = [i for i, (a, b) in enumerate(zip(s, goal)) + if a != b] + return len(diffIndices) == 2 and \ + s[diffIndices[0]] == goal[diffIndices[1]] and \ + s[diffIndices[1]] == goal[diffIndices[0]] diff --git a/solutions/86. Partition List/86.cpp b/solutions/86. Partition List/86.cpp new file mode 100644 index 00000000000..cab372ebd08 --- /dev/null +++ b/solutions/86. Partition List/86.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + ListNode* partition(ListNode* head, int x) { + ListNode beforeHead(0); + ListNode afterHead(0); + ListNode* before = &beforeHead; + ListNode* after = &afterHead; + + for (; head; head = head->next) + if (head->val < x) { + before->next = head; + before = head; + } else { + after->next = head; + after = head; + } + + after->next = nullptr; + before->next = afterHead.next; + + return beforeHead.next; + }; +}; diff --git a/solutions/86. Partition List/86.java b/solutions/86. Partition List/86.java new file mode 100644 index 00000000000..d7287330701 --- /dev/null +++ b/solutions/86. Partition List/86.java @@ -0,0 +1,22 @@ +class Solution { + public ListNode partition(ListNode head, int x) { + ListNode beforeHead = new ListNode(0); + ListNode afterHead = new ListNode(0); + ListNode before = beforeHead; + ListNode after = afterHead; + + for (; head != null; head = head.next) + if (head.val < x) { + before.next = head; + before = head; + } else { + after.next = head; + after = head; + } + + after.next = null; + before.next = afterHead.next; + + return beforeHead.next; + } +} diff --git a/solutions/86. Partition List/86.py b/solutions/86. Partition List/86.py new file mode 100644 index 00000000000..e734346625d --- /dev/null +++ b/solutions/86. Partition List/86.py @@ -0,0 +1,20 @@ +class Solution: + def partition(self, head: ListNode, x: int) -> ListNode: + beforeHead = ListNode(0) + afterHead = ListNode(0) + before = beforeHead + after = afterHead + + while head: + if head.val < x: + before.next = head + before = head + else: + after.next = head + after = head + head = head.next + + after.next = None + before.next = afterHead.next + + return beforeHead.next diff --git a/solutions/860. Lemonade Change/860.cpp b/solutions/860. Lemonade Change/860.cpp new file mode 100644 index 00000000000..7d22a172c75 --- /dev/null +++ b/solutions/860. Lemonade Change/860.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + bool lemonadeChange(vector& bills) { + int count5 = 0; + int count10 = 0; + + for (const int bill : bills) { + if (bill == 5) { + ++count5; + } else if (bill == 10) { + --count5; + ++count10; + } else { // bill == 20 + if (count10 > 0) { + --count10; + --count5; + } else { + count5 -= 3; + } + } + if (count5 < 0) + return false; + } + + return true; + } +}; diff --git a/solutions/860. Lemonade Change/860.java b/solutions/860. Lemonade Change/860.java new file mode 100644 index 00000000000..aad979ea831 --- /dev/null +++ b/solutions/860. Lemonade Change/860.java @@ -0,0 +1,26 @@ +class Solution { + public boolean lemonadeChange(int[] bills) { + int count5 = 0; + int count10 = 0; + + for (final int bill : bills) { + if (bill == 5) { + ++count5; + } else if (bill == 10) { + --count5; + ++count10; + } else { // bill == 20 + if (count10 > 0) { + --count10; + --count5; + } else { + count5 -= 3; + } + } + if (count5 < 0) + return false; + } + + return true; + } +} diff --git a/solutions/860. Lemonade Change/860.py b/solutions/860. Lemonade Change/860.py new file mode 100644 index 00000000000..83700fb3ae9 --- /dev/null +++ b/solutions/860. Lemonade Change/860.py @@ -0,0 +1,21 @@ +class Solution: + def lemonadeChange(self, bills: List[int]) -> bool: + count5 = 0 + count10 = 0 + + for bill in bills: + if bill == 5: + count5 += 1 + elif bill == 10: + count5 -= 1 + count10 += 1 + else: # bill == 20 + if count10 > 0: + count10 -= 1 + count5 -= 1 + else: + count5 -= 3 + if count5 < 0: + return False + + return True diff --git a/solutions/861. Score After Flipping Matrix/861-2.cpp b/solutions/861. Score After Flipping Matrix/861-2.cpp new file mode 100644 index 00000000000..c9d428ca11d --- /dev/null +++ b/solutions/861. Score After Flipping Matrix/861-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int matrixScore(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = m; // All the cells in the first column are 1. + + for (int j = 1; j < n; ++j) { + int onesCount = 0; + for (int i = 0; i < m; ++i) + // The best strategy is flipping the rows with a leading 0.. + onesCount += grid[i][j] == grid[i][0]; + ans = ans * 2 + max(onesCount, m - onesCount); + } + + return ans; + } +}; diff --git a/solutions/861. Score After Flipping Matrix/861-2.java b/solutions/861. Score After Flipping Matrix/861-2.java new file mode 100644 index 00000000000..b91df5119ed --- /dev/null +++ b/solutions/861. Score After Flipping Matrix/861-2.java @@ -0,0 +1,17 @@ +class Solution { + public int matrixScore(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = m; // All the cells in the first column are 1. + + for (int j = 1; j < n; ++j) { + int onesCount = 0; + for (int i = 0; i < m; ++i) + // The best strategy is flipping the rows with a leading 0.. + onesCount += grid[i][j] == grid[i][0] ? 1 : 0; + ans = ans * 2 + Math.max(onesCount, m - onesCount); + } + + return ans; + } +} diff --git a/solutions/861. Score After Flipping Matrix/861-2.py b/solutions/861. Score After Flipping Matrix/861-2.py new file mode 100644 index 00000000000..6b2cb8a81fd --- /dev/null +++ b/solutions/861. Score After Flipping Matrix/861-2.py @@ -0,0 +1,12 @@ +class Solution: + def matrixScore(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + ans = m # All the cells in the first column are 1. + + for j in range(1, n): + # The best strategy is flipping the rows with a leading 0.. + onesCount = sum(grid[i][j] == grid[i][0] for i in range(m)) + ans = ans * 2 + max(onesCount, m - onesCount) + + return ans diff --git a/solutions/861. Score After Flipping Matrix/861.cpp b/solutions/861. Score After Flipping Matrix/861.cpp new file mode 100644 index 00000000000..2588dcb3842 --- /dev/null +++ b/solutions/861. Score After Flipping Matrix/861.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + int matrixScore(vector>& grid) { + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + + // Flip the rows with a leading 0. + for (auto& row : grid) + if (row[0] == 0) + flip(row); + + // Flip the columns with 1s < 0s. + for (int j = 0; j < n; ++j) + if (onesColCount(grid, j) * 2 < m) + flipCol(grid, j); + + // Add a binary number for each row. + for (const vector& row : grid) + ans += binary(row); + + return ans; + } + + private: + void flip(vector& row) { + for (int i = 0; i < row.size(); ++i) + row[i] ^= 1; + } + + int onesColCount(const vector>& grid, int j) { + int ones = 0; + for (int i = 0; i < grid.size(); ++i) + ones += grid[i][j]; + return ones; + } + + void flipCol(vector>& grid, int j) { + for (int i = 0; i < grid.size(); ++i) + grid[i][j] ^= 1; + } + + int binary(const vector& row) { + int res = row[0]; + for (int j = 1; j < row.size(); ++j) + res = res * 2 + row[j]; + return res; + } +}; diff --git a/solutions/861. Score After Flipping Matrix/861.java b/solutions/861. Score After Flipping Matrix/861.java new file mode 100644 index 00000000000..ddefc7bf40f --- /dev/null +++ b/solutions/861. Score After Flipping Matrix/861.java @@ -0,0 +1,47 @@ +class Solution { + public int matrixScore(int[][] grid) { + final int m = grid.length; + final int n = grid[0].length; + int ans = 0; + + // Flip the rows with a leading 0. + for (int[] row : grid) + if (row[0] == 0) + flip(row); + + // Flip the columns with 1s < 0s. + for (int j = 0; j < n; ++j) + if (onesColCount(grid, j) * 2 < m) + flipCol(grid, j); + + // Add a binary number for each row. + for (int[] row : grid) + ans += binary(row); + + return ans; + } + + private void flip(int[] row) { + for (int i = 0; i < row.length; ++i) + row[i] ^= 1; + } + + private int onesColCount(int[][] grid, int j) { + int ones = 0; + for (int i = 0; i < grid.length; ++i) + ones += grid[i][j]; + return ones; + } + + private void flipCol(int[][] grid, int j) { + for (int i = 0; i < grid.length; ++i) + grid[i][j] ^= 1; + } + + private int binary(int[] row) { + int res = row[0]; + for (int j = 1; j < row.length; ++j) + res = res * 2 + row[j]; + return res; + } +} diff --git a/solutions/861. Score After Flipping Matrix/861.py b/solutions/861. Score After Flipping Matrix/861.py new file mode 100644 index 00000000000..56794df17ba --- /dev/null +++ b/solutions/861. Score After Flipping Matrix/861.py @@ -0,0 +1,28 @@ +class Solution: + def matrixScore(self, grid: List[List[int]]) -> int: + # Flip the rows with a leading 0. + for row in grid: + if row[0] == 0: + self._flip(row) + + # Flip the columns with 1s < 0s. + for j, col in enumerate(list(zip(*grid))): + if sum(col) * 2 < len(grid): + self._flipCol(grid, j) + + # Add a binary number for each row. + return sum(self._binary(row) for row in grid) + + def _flip(self, row: List[int]) -> None: + for i in range(len(row)): + row[i] ^= 1 + + def _flipCol(self, grid: List[List[int]], j: int) -> None: + for i in range(len(grid)): + grid[i][j] ^= 1 + + def _binary(self, row: List[int]) -> int: + res = row[0] + for j in range(1, len(row)): + res = res * 2 + row[j] + return res diff --git a/solutions/862. Shortest Subarray with Sum at Least K/862.cpp b/solutions/862. Shortest Subarray with Sum at Least K/862.cpp new file mode 100644 index 00000000000..55dc95fe93c --- /dev/null +++ b/solutions/862. Shortest Subarray with Sum at Least K/862.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int shortestSubarray(vector& nums, int k) { + const int n = nums.size(); + int ans = n + 1; + deque dq; + vector prefix{0}; + + for (int i = 0; i < n; ++i) + prefix.push_back(prefix.back() + nums[i]); + + for (int i = 0; i < n + 1; ++i) { + while (!dq.empty() && prefix[i] - prefix[dq.front()] >= k) + ans = min(ans, i - dq.front()), dq.pop_front(); + while (!dq.empty() && prefix[i] <= prefix[dq.back()]) + dq.pop_back(); + dq.push_back(i); + } + + return ans <= n ? ans : -1; + } +}; diff --git a/solutions/862. Shortest Subarray with Sum at Least K/862.java b/solutions/862. Shortest Subarray with Sum at Least K/862.java new file mode 100644 index 00000000000..dd3803f333b --- /dev/null +++ b/solutions/862. Shortest Subarray with Sum at Least K/862.java @@ -0,0 +1,21 @@ +class Solution { + public int shortestSubarray(int[] nums, int k) { + final int n = nums.length; + int ans = n + 1; + Deque dq = new ArrayDeque<>(); + long[] prefix = new long[n + 1]; + + for (int i = 0; i < n; ++i) + prefix[i + 1] = (long) nums[i] + prefix[i]; + + for (int i = 0; i < n + 1; ++i) { + while (!dq.isEmpty() && prefix[i] - prefix[dq.getFirst()] >= k) + ans = Math.min(ans, i - dq.pollFirst()); + while (!dq.isEmpty() && prefix[i] <= prefix[dq.getLast()]) + dq.pollLast(); + dq.addLast(i); + } + + return ans <= n ? ans : -1; + } +} diff --git a/solutions/862. Shortest Subarray with Sum at Least K/862.py b/solutions/862. Shortest Subarray with Sum at Least K/862.py new file mode 100644 index 00000000000..aa1e9aa70e2 --- /dev/null +++ b/solutions/862. Shortest Subarray with Sum at Least K/862.py @@ -0,0 +1,15 @@ +class Solution: + def shortestSubarray(self, nums: List[int], k: int) -> int: + n = len(nums) + ans = n + 1 + dq = collections.deque() + prefix = [0] + list(itertools.accumulate(nums)) + + for i in range(n + 1): + while dq and prefix[i] - prefix[dq[0]] >= k: + ans = min(ans, i - dq.popleft()) + while dq and prefix[i] <= prefix[dq[-1]]: + dq.pop() + dq.append(i) + + return ans if ans <= n else -1 diff --git a/solutions/863. All Nodes Distance K in Binary Tree/863.cpp b/solutions/863. All Nodes Distance K in Binary Tree/863.cpp new file mode 100644 index 00000000000..b86b6fcd1cd --- /dev/null +++ b/solutions/863. All Nodes Distance K in Binary Tree/863.cpp @@ -0,0 +1,47 @@ +class Solution { + public: + vector distanceK(TreeNode* root, TreeNode* target, int k) { + vector ans; + unordered_map nodeToDist; // {node: distance to target} + + getDists(root, target, nodeToDist); + dfs(root, k, 0, nodeToDist, ans); + return ans; + } + + private: + void getDists(TreeNode* root, TreeNode* target, + unordered_map& nodeToDist) { + if (root == nullptr) + return; + if (root == target) { + nodeToDist[root] = 0; + return; + } + + getDists(root->left, target, nodeToDist); + if (const auto it = nodeToDist.find(root->left); it != nodeToDist.cend()) { + // The target is in the left subtree. + nodeToDist[root] = it->second + 1; + return; + } + + getDists(root->right, target, nodeToDist); + if (const auto it = nodeToDist.find(root->right); it != nodeToDist.cend()) + // The target is in the right subtree. + nodeToDist[root] = it->second + 1; + } + + void dfs(TreeNode* root, int k, int dist, + unordered_map& nodeToDist, vector& ans) { + if (root == nullptr) + return; + if (const auto it = nodeToDist.find(root); it != nodeToDist.cend()) + dist = it->second; + if (dist == k) + ans.push_back(root->val); + + dfs(root->left, k, dist + 1, nodeToDist, ans); + dfs(root->right, k, dist + 1, nodeToDist, ans); + } +}; diff --git a/solutions/863. All Nodes Distance K in Binary Tree/863.java b/solutions/863. All Nodes Distance K in Binary Tree/863.java new file mode 100644 index 00000000000..439d9b1e561 --- /dev/null +++ b/solutions/863. All Nodes Distance K in Binary Tree/863.java @@ -0,0 +1,45 @@ +class Solution { + public List distanceK(TreeNode root, TreeNode target, int k) { + List ans = new ArrayList<>(); + Map nodeToDist = new HashMap<>(); // {node: distance to target} + + getDists(root, target, nodeToDist); + dfs(root, k, 0, nodeToDist, ans); + + return ans; + } + + private void getDists(TreeNode root, TreeNode target, Map nodeToDist) { + if (root == null) + return; + if (root == target) { + nodeToDist.put(root, 0); + return; + } + + getDists(root.left, target, nodeToDist); + if (nodeToDist.containsKey(root.left)) { + // The target is in the left subtree. + nodeToDist.put(root, nodeToDist.get(root.left) + 1); + return; + } + + getDists(root.right, target, nodeToDist); + if (nodeToDist.containsKey(root.right)) + // The target is in the right subtree. + nodeToDist.put(root, nodeToDist.get(root.right) + 1); + } + + private void dfs(TreeNode root, int k, int dist, Map nodeToDist, + List ans) { + if (root == null) + return; + if (nodeToDist.containsKey(root)) + dist = nodeToDist.get(root); + if (dist == k) + ans.add(root.val); + + dfs(root.left, k, dist + 1, nodeToDist, ans); + dfs(root.right, k, dist + 1, nodeToDist, ans); + } +} diff --git a/solutions/864. Shortest Path to Get All Keys/864.cpp b/solutions/864. Shortest Path to Get All Keys/864.cpp new file mode 100644 index 00000000000..f6e473398e2 --- /dev/null +++ b/solutions/864. Shortest Path to Get All Keys/864.cpp @@ -0,0 +1,67 @@ +struct T { + int i; + int j; + int keys; // the keys in the bitmask + T(int i, int j, int keys) : i(i), j(j), keys(keys) {} +}; + +class Solution { + public: + int shortestPathAllKeys(vector& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].length(); + const int keysCount = getKeysCount(grid); + const int kKeys = (1 << keysCount) - 1; + const vector start = getStart(grid); + int ans = 0; + queue q{{{start[0], start[1], 0}}}; + vector>> seen( + m, vector>(n, vector(kKeys))); + seen[start[0]][start[1]][0] = true; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j, keys] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + const char c = grid[x][y]; + if (c == '#') + continue; + const int newKeys = 'a' <= c && c <= 'f' ? keys | 1 << c - 'a' : keys; + if (newKeys == kKeys) + return ans; + if (seen[x][y][newKeys]) + continue; + if ('A' <= c && c <= 'F' && (newKeys >> c - 'A' & 1) == 0) + continue; + q.emplace(x, y, newKeys); + seen[x][y][newKeys] = true; + } + } + } + + return -1; + } + + private: + int getKeysCount(const vector& grid) { + int count = 0; + for (const string& s : grid) + count += ranges::count_if(s, [](char c) { return 'a' <= c && c <= 'f'; }); + return count; + } + + vector getStart(const vector& grid) { + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].length(); ++j) + if (grid[i][j] == '@') + return {i, j}; + throw; + } +}; diff --git a/solutions/864. Shortest Path to Get All Keys/864.java b/solutions/864. Shortest Path to Get All Keys/864.java new file mode 100644 index 00000000000..3cbc2156100 --- /dev/null +++ b/solutions/864. Shortest Path to Get All Keys/864.java @@ -0,0 +1,69 @@ +class T { + public int i; + public int j; + public int keys; // the keys in the bitmask + public T(int i, int j, int keys) { + this.i = i; + this.j = j; + this.keys = keys; + } +} + +class Solution { + public int shortestPathAllKeys(String[] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int m = grid.length; + final int n = grid[0].length(); + final int keysCount = getKeysCount(grid); + final int kKeys = (1 << keysCount) - 1; + final int[] start = getStart(grid); + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(new T(start[0], start[1], 0))); + boolean[][][] seen = new boolean[m][n][kKeys]; + seen[start[0]][start[1]][0] = true; + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek().i; + final int j = q.peek().j; + final int keys = q.poll().keys; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == m || y < 0 || y == n) + continue; + final char c = grid[x].charAt(y); + if (c == '#') + continue; + final int newKeys = 'a' <= c && c <= 'f' ? keys | 1 << c - 'a' : keys; + if (newKeys == kKeys) + return ans; + if (seen[x][y][newKeys]) + continue; + if ('A' <= c && c <= 'F' && (newKeys >> c - 'A' & 1) == 0) + continue; + q.offer(new T(x, y, newKeys)); + seen[x][y][newKeys] = true; + } + } + } + + return -1; + } + + private int getKeysCount(String[] grid) { + int count = 0; + for (final String s : grid) + count += (int) s.chars().filter(c -> 'a' <= c && c <= 'f').count(); + return count; + } + + private int[] getStart(String[] grid) { + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length(); ++j) + if (grid[i].charAt(j) == '@') + return new int[] {i, j}; + throw new IllegalArgumentException(); + } +} diff --git a/solutions/865. Smallest Subtree with all the Deepest Nodes/865.cpp b/solutions/865. Smallest Subtree with all the Deepest Nodes/865.cpp new file mode 100644 index 00000000000..6208ed66209 --- /dev/null +++ b/solutions/865. Smallest Subtree with all the Deepest Nodes/865.cpp @@ -0,0 +1,25 @@ +struct T { + TreeNode* lca; + int depth; +}; + +class Solution { + public: + TreeNode* subtreeWithAllDeepest(TreeNode* root) { + return dfs(root).lca; + } + + private: + T dfs(TreeNode* root) { + if (root == nullptr) + return {nullptr, 0}; + + const T left = dfs(root->left); + const T right = dfs(root->right); + if (left.depth > right.depth) + return {left.lca, left.depth + 1}; + if (left.depth < right.depth) + return {right.lca, right.depth + 1}; + return {root, left.depth + 1}; + } +}; diff --git a/solutions/865. Smallest Subtree with all the Deepest Nodes/865.java b/solutions/865. Smallest Subtree with all the Deepest Nodes/865.java new file mode 100644 index 00000000000..e25d2f38e04 --- /dev/null +++ b/solutions/865. Smallest Subtree with all the Deepest Nodes/865.java @@ -0,0 +1,28 @@ +class T { + public TreeNode lca; + public int depth; + + public T(TreeNode lca, int depth) { + this.lca = lca; + this.depth = depth; + } +}; + +class Solution { + public TreeNode subtreeWithAllDeepest(TreeNode root) { + return dfs(root).lca; + } + + private T dfs(TreeNode root) { + if (root == null) + return new T(null, 0); + + T l = dfs(root.left); + T r = dfs(root.right); + if (left.depth > right.depth) + return new T(left.lca, left.depth + 1); + if (left.depth < right.depth) + return new T(right.lca, right.depth + 1); + return new T(root, left.depth + 1); + } +} diff --git a/solutions/866. Prime Palindrome/866.cpp b/solutions/866. Prime Palindrome/866.cpp new file mode 100644 index 00000000000..18c2f60f6c7 --- /dev/null +++ b/solutions/866. Prime Palindrome/866.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + int primePalindrome(int n) { + if (n <= 2) + return 2; + if (n == 3) + return 3; + if (n <= 5) + return 5; + if (n <= 7) + return 7; + if (n <= 11) + return 11; + + int nLength = to_string(n).length(); + + while (true) { + for (const int num : getPalindromes(nLength)) + if (num >= n && isPrime(num)) + return num; + ++nLength; + } + + throw; + } + + private: + vector getPalindromes(int n) { + vector palindromes; + const int length = n / 2; + + for (int i = pow(10, length - 1); i < pow(10, length); ++i) { + const string s = to_string(i); + string reversedS = s; + reverse(reversedS.begin(), reversedS.end()); + for (int j = 0; j < 10; ++j) + palindromes.push_back(stoi(s + to_string(j) + reversedS)); + } + + return palindromes; + } + + bool isPrime(int num) { + for (int i = 2; i < sqrt(num) + 1; ++i) + if (num % i == 0) + return false; + return true; + } +}; diff --git a/solutions/866. Prime Palindrome/866.java b/solutions/866. Prime Palindrome/866.java new file mode 100644 index 00000000000..1a4c6a87250 --- /dev/null +++ b/solutions/866. Prime Palindrome/866.java @@ -0,0 +1,44 @@ +class Solution { + public int primePalindrome(int n) { + if (n <= 2) + return 2; + if (n == 3) + return 3; + if (n <= 5) + return 5; + if (n <= 7) + return 7; + if (n <= 11) + return 11; + + int nLength = String.valueOf(n).length(); + + while (true) { + for (final int num : getPalindromes(nLength)) + if (num >= n && isPrime(num)) + return num; + ++nLength; + } + } + + private List getPalindromes(int n) { + List palindromes = new ArrayList<>(); + int length = n / 2; + + for (int i = (int) Math.pow(10, length - 1); i < (int) Math.pow(10, length); ++i) { + String s = String.valueOf(i); + String reversedS = new StringBuilder(s).reverse().toString(); + for (int j = 0; j < 10; ++j) + palindromes.add(Integer.valueOf(s + String.valueOf(j) + reversedS)); + } + + return palindromes; + } + + private boolean isPrime(int num) { + for (int i = 2; i < (int) Math.sqrt(num) + 1; ++i) + if (num % i == 0) + return false; + return true; + } +} diff --git a/solutions/866. Prime Palindrome/866.py b/solutions/866. Prime Palindrome/866.py new file mode 100644 index 00000000000..d2001d77267 --- /dev/null +++ b/solutions/866. Prime Palindrome/866.py @@ -0,0 +1,30 @@ +class Solution: + def primePalindrome(self, n: int) -> int: + def getPalindromes(n: int) -> int: + length = n // 2 + for i in range(10**(length - 1), 10**length): + s = str(i) + for j in range(10): + yield int(s + str(j) + s[::-1]) + + def isPrime(num: int) -> bool: + return not any(num % i == 0 for i in range(2, int(num**0.5 + 1))) + + if n <= 2: + return 2 + if n == 3: + return 3 + if n <= 5: + return 5 + if n <= 7: + return 7 + if n <= 11: + return 11 + + nLength = len(str(n)) + + while True: + for num in getPalindromes(nLength): + if num >= n and isPrime(num): + return num + nLength += 1 diff --git a/solutions/867. Transpose Matrix/867.cpp b/solutions/867. Transpose Matrix/867.cpp new file mode 100644 index 00000000000..75158e4b2ca --- /dev/null +++ b/solutions/867. Transpose Matrix/867.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector> transpose(vector>& A) { + vector> ans(A[0].size(), vector(A.size())); + + for (int i = 0; i < A.size(); ++i) + for (int j = 0; j < A[0].size(); ++j) + ans[j][i] = A[i][j]; + + return ans; + } +}; diff --git a/solutions/867. Transpose Matrix/867.java b/solutions/867. Transpose Matrix/867.java new file mode 100644 index 00000000000..020edb7a407 --- /dev/null +++ b/solutions/867. Transpose Matrix/867.java @@ -0,0 +1,11 @@ +class Solution { + public int[][] transpose(int[][] A) { + int[][] ans = new int[A[0].length][A.length]; + + for (int i = 0; i < A.length; ++i) + for (int j = 0; j < A[0].length; ++j) + ans[j][i] = A[i][j]; + + return ans; + } +} diff --git a/solutions/867. Transpose Matrix/867.py b/solutions/867. Transpose Matrix/867.py new file mode 100644 index 00000000000..c80ee4aa112 --- /dev/null +++ b/solutions/867. Transpose Matrix/867.py @@ -0,0 +1,9 @@ +class Solution: + def transpose(self, A: List[List[int]]) -> List[List[int]]: + ans = [[0] * len(A) for _ in range(len(A[0]))] + + for i in range(len(A)): + for j in range(len(A[0])): + ans[j][i] = A[i][j] + + return ans diff --git a/solutions/868. Binary Gap/868.cpp b/solutions/868. Binary Gap/868.cpp new file mode 100644 index 00000000000..e806f4784e4 --- /dev/null +++ b/solutions/868. Binary Gap/868.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int binaryGap(int n) { + int ans = 0; + + // d := the distance between any two 1s + for (int d = -32; n; n /= 2, ++d) + if (n % 2 == 1) { + ans = max(ans, d); + d = 0; + } + + return ans; + } +}; diff --git a/solutions/868. Binary Gap/868.java b/solutions/868. Binary Gap/868.java new file mode 100644 index 00000000000..29d414f7e4b --- /dev/null +++ b/solutions/868. Binary Gap/868.java @@ -0,0 +1,14 @@ +class Solution { + public int binaryGap(int n) { + int ans = 0; + + // d := the distance between any two 1s + for (int d = -32; n > 0; n /= 2, ++d) + if (n % 2 == 1) { + ans = Math.max(ans, d); + d = 0; + } + + return ans; + } +} diff --git a/solutions/868. Binary Gap/868.py b/solutions/868. Binary Gap/868.py new file mode 100644 index 00000000000..370a6545b4f --- /dev/null +++ b/solutions/868. Binary Gap/868.py @@ -0,0 +1,13 @@ +class Solution: + def binaryGap(self, n: int) -> int: + ans = 0 + d = -32 # the distance between any two 1s + + while n: + if n % 2 == 1: + ans = max(ans, d) + d = 0 + n //= 2 + d += 1 + + return ans diff --git a/solutions/869. Reordered Power of 2/869.cpp b/solutions/869. Reordered Power of 2/869.cpp new file mode 100644 index 00000000000..1201622d71e --- /dev/null +++ b/solutions/869. Reordered Power of 2/869.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool reorderedPowerOf2(int n) { + int count = counter(n); + + for (int i = 0; i < 30; ++i) + if (counter(1 << i) == count) + return true; + + return false; + } + + private: + int counter(int n) { + int count = 0; + + for (; n > 0; n /= 10) + count += pow(10, n % 10); + + return count; + } +}; diff --git a/solutions/869. Reordered Power of 2/869.java b/solutions/869. Reordered Power of 2/869.java new file mode 100644 index 00000000000..9ceaeafafc5 --- /dev/null +++ b/solutions/869. Reordered Power of 2/869.java @@ -0,0 +1,20 @@ +class Solution { + public boolean reorderedPowerOf2(int n) { + int count = counter(n); + + for (int i = 0; i < 30; ++i) + if (counter(1 << i) == count) + return true; + + return false; + } + + private int counter(int n) { + int count = 0; + + for (; n > 0; n /= 10) + count += Math.pow(10, n % 10); + + return count; + } +} diff --git a/solutions/869. Reordered Power of 2/869.py b/solutions/869. Reordered Power of 2/869.py new file mode 100644 index 00000000000..5e6acab0ff9 --- /dev/null +++ b/solutions/869. Reordered Power of 2/869.py @@ -0,0 +1,4 @@ +class Solution: + def reorderedPowerOf2(self, n: int) -> bool: + count = collections.Counter(str(n)) + return any(Counter(str(1 << i)) == count for i in range(30)) diff --git a/solutions/87. Scramble String/87.cpp b/solutions/87. Scramble String/87.cpp new file mode 100644 index 00000000000..14290d7505d --- /dev/null +++ b/solutions/87. Scramble String/87.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + bool isScramble(string s1, string s2) { + if (s1 == s2) + return true; + const string hashKey = s1 + '+' + s2; + if (const auto it = mem.find(hashKey); it != mem.cend()) + return it->second; + + vector count(128); + + for (int i = 0; i < s1.length(); ++i) { + ++count[s1[i]]; + --count[s2[i]]; + } + + if (ranges::any_of(count, [](int c) { return c != 0; })) + return mem[hashKey] = false; + + for (int i = 1; i < s1.length(); ++i) { + if (isScramble(s1.substr(0, i), s2.substr(0, i)) && + isScramble(s1.substr(i), s2.substr(i))) + return mem[hashKey] = true; + if (isScramble(s1.substr(0, i), s2.substr(s2.length() - i)) && + isScramble(s1.substr(i), s2.substr(0, s2.length() - i))) + return mem[hashKey] = true; + } + + return mem[hashKey] = false; + } + + private: + unordered_map mem; +}; diff --git a/solutions/87. Scramble String/87.java b/solutions/87. Scramble String/87.java new file mode 100644 index 00000000000..1febcac7214 --- /dev/null +++ b/solutions/87. Scramble String/87.java @@ -0,0 +1,40 @@ +class Solution { + public boolean isScramble(String s1, String s2) { + if (s1.equals(s2)) + return true; + final String hashKey = s1 + "+" + s2; + if (mem.containsKey(hashKey)) + return mem.get(hashKey); + + int[] count = new int[128]; + + for (int i = 0; i < s1.length(); ++i) { + ++count[s1.charAt(i)]; + --count[s2.charAt(i)]; + } + + for (final int freq : count) + if (freq != 0) { + mem.put(hashKey, false); + return false; + } + + for (int i = 1; i < s1.length(); ++i) { + if (isScramble(s1.substring(0, i), s2.substring(0, i)) && + isScramble(s1.substring(i), s2.substring(i))) { + mem.put(hashKey, true); + return true; + } + if (isScramble(s1.substring(0, i), s2.substring(s2.length() - i)) && + isScramble(s1.substring(i), s2.substring(0, s2.length() - i))) { + mem.put(hashKey, true); + return true; + } + } + + mem.put(hashKey, false); + return false; + } + + private Map mem = new HashMap<>(); +} diff --git a/solutions/87. Scramble String/87.py b/solutions/87. Scramble String/87.py new file mode 100644 index 00000000000..776fba83aff --- /dev/null +++ b/solutions/87. Scramble String/87.py @@ -0,0 +1,15 @@ +class Solution: + @functools.lru_cache(None) + def isScramble(self, s1: str, s2: str) -> bool: + if s1 == s2: + return True + if collections.Counter(s1) != collections.Counter(s2): + return False + + for i in range(1, len(s1)): + if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]): + return True + if self.isScramble(s1[:i], s2[len(s2) - i:]) and self.isScramble(s1[i:], s2[:len(s2) - i]): + return True + + return False diff --git a/solutions/870. Advantage Shuffle/870.cpp b/solutions/870. Advantage Shuffle/870.cpp new file mode 100644 index 00000000000..0d819c26896 --- /dev/null +++ b/solutions/870. Advantage Shuffle/870.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + vector advantageCount(vector& nums1, vector& nums2) { + multiset set{nums1.begin(), nums1.end()}; + + for (int i = 0; i < nums2.size(); ++i) { + const auto p = + *set.rbegin() <= nums2[i] ? set.begin() : set.upper_bound(nums2[i]); + nums1[i] = *p; + set.erase(p); + } + + return nums1; + } +}; diff --git a/solutions/870. Advantage Shuffle/870.java b/solutions/870. Advantage Shuffle/870.java new file mode 100644 index 00000000000..5675ba7b8f9 --- /dev/null +++ b/solutions/870. Advantage Shuffle/870.java @@ -0,0 +1,19 @@ +class Solution { + public int[] advantageCount(int[] nums1, int[] nums2) { + TreeMap map = new TreeMap<>(); + + for (final int num : nums1) + map.merge(num, 1, Integer::sum); + + for (int i = 0; i < nums2.length; i++) { + Integer key = map.higherKey(nums2[i]); + if (key == null) + key = map.firstKey(); + if (map.merge(key, -1, Integer::sum) == 0) + map.remove(key); + nums1[i] = key; + } + + return nums1; + } +} diff --git a/solutions/870. Advantage Shuffle/870.py b/solutions/870. Advantage Shuffle/870.py new file mode 100644 index 00000000000..73e05e8bef3 --- /dev/null +++ b/solutions/870. Advantage Shuffle/870.py @@ -0,0 +1,13 @@ +from sortedcontainers import SortedList + + +class Solution: + def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]: + sl = SortedList(nums1) + + for i, num in enumerate(nums2): + index = 0 if sl[-1] <= num else sl.bisect_right(num) + nums1[i] = sl[index] + del sl[index] + + return nums1 diff --git a/solutions/871. Minimum Number of Refueling Stops/871-2.cpp b/solutions/871. Minimum Number of Refueling Stops/871-2.cpp new file mode 100644 index 00000000000..fb24e7accff --- /dev/null +++ b/solutions/871. Minimum Number of Refueling Stops/871-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + int ans = 0; + int i = 0; // stations' index + int curr = startFuel; + priority_queue maxHeap; + + while (curr < target) { + // Add all the reachable stops to maxHeap + while (i < stations.size() && curr >= stations[i][0]) + maxHeap.push(stations[i++][1]); + if (maxHeap.empty()) // Can't be refueled. + return -1; + curr += maxHeap.top(), maxHeap.pop(); // Pop out the largest gas. + ++ans; // Then, refuel once. + } + + return ans; + } +}; diff --git a/solutions/871. Minimum Number of Refueling Stops/871-2.java b/solutions/871. Minimum Number of Refueling Stops/871-2.java new file mode 100644 index 00000000000..9359001e293 --- /dev/null +++ b/solutions/871. Minimum Number of Refueling Stops/871-2.java @@ -0,0 +1,20 @@ +class Solution { + public int minRefuelStops(int target, int startFuel, int[][] stations) { + int ans = 0; + int i = 0; // stations' index + int curr = startFuel; + Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + while (curr < target) { + // Add all the reachable stops to maxHeap + while (i < stations.length && curr >= stations[i][0]) + maxHeap.offer(stations[i++][1]); + if (maxHeap.isEmpty()) // Can't be refueled. + return -1; + curr += maxHeap.poll(); // Pop out the largest gas. + ++ans; // Then, refuel once. + } + + return ans; + } +} diff --git a/solutions/871. Minimum Number of Refueling Stops/871-2.py b/solutions/871. Minimum Number of Refueling Stops/871-2.py new file mode 100644 index 00000000000..539d033c571 --- /dev/null +++ b/solutions/871. Minimum Number of Refueling Stops/871-2.py @@ -0,0 +1,18 @@ +class Solution: + def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: + ans = 0 + i = 0 # station's index + curr = startFuel + maxHeap = [] + + while curr < target: + # Add all the reachable stops to maxHeap + while i < len(stations) and stations[i][0] <= curr: + heapq.heappush(maxHeap, -stations[i][1]) + i += 1 + if not maxHeap: # Can't be refueled. + return -1 + curr -= heapq.heappop(maxHeap) # Pop out the largest gas. + ans += 1 # Then, refuel once. + + return ans diff --git a/solutions/871. Minimum Number of Refueling Stops/871.cpp b/solutions/871. Minimum Number of Refueling Stops/871.cpp new file mode 100644 index 00000000000..b12f63e78d3 --- /dev/null +++ b/solutions/871. Minimum Number of Refueling Stops/871.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + // dp[i] := the farthest position we can reach with i refuels + vector dp(stations.size() + 1); + dp[0] = startFuel; + + for (int i = 0; i < stations.size(); ++i) + for (int j = i + 1; j > 0; --j) + if (dp[j - 1] >= stations[i][0]) + dp[j] = max(dp[j], dp[j - 1] + stations[i][1]); + + for (int i = 0; i < dp.size(); ++i) + if (dp[i] >= target) + return i; + + return -1; + } +}; diff --git a/solutions/871. Minimum Number of Refueling Stops/871.java b/solutions/871. Minimum Number of Refueling Stops/871.java new file mode 100644 index 00000000000..2610b80c8c6 --- /dev/null +++ b/solutions/871. Minimum Number of Refueling Stops/871.java @@ -0,0 +1,18 @@ +class Solution { + public int minRefuelStops(int target, int startFuel, int[][] stations) { + // dp[i] := the farthest position we can reach with i refuels + long dp[] = new long[stations.length + 1]; + dp[0] = startFuel; + + for (int i = 0; i < stations.length; ++i) + for (int j = i + 1; j > 0; --j) + if (dp[j - 1] >= stations[i][0]) + dp[j] = Math.max(dp[j], dp[j - 1] + stations[i][1]); + + for (int i = 0; i < dp.length; ++i) + if (dp[i] >= target) + return i; + + return -1; + } +} diff --git a/solutions/871. Minimum Number of Refueling Stops/871.py b/solutions/871. Minimum Number of Refueling Stops/871.py new file mode 100644 index 00000000000..62242fcf3db --- /dev/null +++ b/solutions/871. Minimum Number of Refueling Stops/871.py @@ -0,0 +1,15 @@ +class Solution: + def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: + # dp[i] := the farthest position we can reach w / i refuels + dp = [startFuel] + [0] * len(stations) + + for i, station in enumerate(stations): + for j in range(i + 1, 0, -1): + if dp[j - 1] >= station[0]: + dp[j] = max(dp[j], dp[j - 1] + station[1]) + + for i, d in enumerate(dp): + if d >= target: + return i + + return -1 diff --git a/solutions/872. Leaf-Similar Trees/872.cpp b/solutions/872. Leaf-Similar Trees/872.cpp new file mode 100644 index 00000000000..93067ef6646 --- /dev/null +++ b/solutions/872. Leaf-Similar Trees/872.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool leafSimilar(TreeNode* root1, TreeNode* root2) { + vector leaves1; + vector leaves2; + dfs(root1, leaves1); + dfs(root2, leaves2); + return leaves1 == leaves2; + } + + void dfs(TreeNode* root, vector& leaves) { + if (root == nullptr) + return; + if (root->left == nullptr && root->right == nullptr) { + leaves.push_back(root->val); + return; + } + + dfs(root->left, leaves); + dfs(root->right, leaves); + } +}; diff --git a/solutions/872. Leaf-Similar Trees/872.java b/solutions/872. Leaf-Similar Trees/872.java new file mode 100644 index 00000000000..4cb991ea3f3 --- /dev/null +++ b/solutions/872. Leaf-Similar Trees/872.java @@ -0,0 +1,21 @@ +class Solution { + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + List leaves1 = new ArrayList<>(); + List leaves2 = new ArrayList<>(); + dfs(root1, leaves1); + dfs(root2, leaves2); + return leaves1.equals(leaves2); + } + + public void dfs(TreeNode node, List leaves) { + if (node == null) + return; + if (node.left == null && node.right == null) { + leaves.add(node.val); + return; + } + + dfs(node.left, leaves); + dfs(node.right, leaves); + } +} diff --git a/solutions/872. Leaf-Similar Trees/872.py b/solutions/872. Leaf-Similar Trees/872.py new file mode 100644 index 00000000000..8cffc418a72 --- /dev/null +++ b/solutions/872. Leaf-Similar Trees/872.py @@ -0,0 +1,13 @@ +class Solution: + def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: + def dfs(root: Optional[TreeNode]) -> None: + if not root: + return + if not root.left and not root.right: + yield root.val + return + + yield from dfs(root.left) + yield from dfs(root.right) + + return list(dfs(root1)) == list(dfs(root2)) diff --git a/solutions/873. Length of Longest Fibonacci Subsequence/873.cpp b/solutions/873. Length of Longest Fibonacci Subsequence/873.cpp new file mode 100644 index 00000000000..0d173a1c559 --- /dev/null +++ b/solutions/873. Length of Longest Fibonacci Subsequence/873.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int lenLongestFibSubseq(vector& arr) { + const int n = arr.size(); + int ans = 0; + vector> dp(n, vector(n, 2)); + unordered_map numToIndex; + + for (int i = 0; i < n; ++i) + numToIndex[arr[i]] = i; + + for (int j = 0; j < n; ++j) + for (int k = j + 1; k < n; ++k) { + const int ai = arr[k] - arr[j]; + if (ai < arr[j] && numToIndex.contains(ai)) { + const int i = numToIndex[ai]; + dp[j][k] = dp[i][j] + 1; + ans = max(ans, dp[j][k]); + } + } + + return ans; + } +}; diff --git a/solutions/873. Length of Longest Fibonacci Subsequence/873.java b/solutions/873. Length of Longest Fibonacci Subsequence/873.java new file mode 100644 index 00000000000..e373567671d --- /dev/null +++ b/solutions/873. Length of Longest Fibonacci Subsequence/873.java @@ -0,0 +1,24 @@ +class Solution { + public int lenLongestFibSubseq(int[] arr) { + final int n = arr.length; + int ans = 0; + int[][] dp = new int[n][n]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, 2)); + Map numToIndex = new HashMap<>(); + + for (int i = 0; i < n; ++i) + numToIndex.put(arr[i], i); + + for (int j = 0; j < n; ++j) + for (int k = j + 1; k < n; ++k) { + final int ai = arr[k] - arr[j]; + if (ai < arr[j] && numToIndex.containsKey(ai)) { + final int i = numToIndex.get(ai); + dp[j][k] = dp[i][j] + 1; + ans = Math.max(ans, dp[j][k]); + } + } + + return ans; + } +} diff --git a/solutions/873. Length of Longest Fibonacci Subsequence/873.py b/solutions/873. Length of Longest Fibonacci Subsequence/873.py new file mode 100644 index 00000000000..b76e440151b --- /dev/null +++ b/solutions/873. Length of Longest Fibonacci Subsequence/873.py @@ -0,0 +1,16 @@ +class Solution: + def lenLongestFibSubseq(self, arr: List[int]) -> int: + n = len(arr) + ans = 0 + numToIndex = {a: i for i, a in enumerate(arr)} + dp = [[2] * n for _ in range(n)] + + for j in range(n): + for k in range(j + 1, n): + ai = arr[k] - arr[j] + if ai < arr[j] and ai in numToIndex: + i = numToIndex[ai] + dp[j][k] = dp[i][j] + 1 + ans = max(ans, dp[j][k]) + + return ans diff --git a/solutions/874. Walking Robot Simulation/874.cpp b/solutions/874. Walking Robot Simulation/874.cpp new file mode 100644 index 00000000000..012805939eb --- /dev/null +++ b/solutions/874. Walking Robot Simulation/874.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + int robotSim(vector& commands, vector>& obstacles) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int ans = 0; + int d = 0; // 0 := north, 1 := east, 2 := south, 3 := west + int x = 0; // the start x + int y = 0; // the start y + unordered_set, PairHash> obstaclesSet; + + for (const vector& o : obstacles) + obstaclesSet.insert({o[0], o[1]}); + + for (const int c : commands) { + if (c == -1) { + d = (d + 1) % 4; + } else if (c == -2) { + d = (d + 3) % 4; + } else { + for (int step = 0; step < c; ++step) { + if (obstaclesSet.contains({x + dirs[d], y + dirs[d + 1]})) + break; + x += dirs[d]; + y += dirs[d + 1]; + } + } + ans = max(ans, x * x + y * y); + } + + return ans; + } + + private: + struct PairHash { + size_t operator()(const pair& p) const { + return p.first ^ p.second; + } + }; +}; diff --git a/solutions/874. Walking Robot Simulation/874.java b/solutions/874. Walking Robot Simulation/874.java new file mode 100644 index 00000000000..b78e0ea1af0 --- /dev/null +++ b/solutions/874. Walking Robot Simulation/874.java @@ -0,0 +1,31 @@ +class Solution { + public int robotSim(int[] commands, int[][] obstacles) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int ans = 0; + int d = 0; // 0 := north, 1 := east, 2 := south, 3 := west + int x = 0; // the start x + int y = 0; // the start y + Set> obstaclesSet = new HashSet<>(); + + for (int[] o : obstacles) + obstaclesSet.add(new Pair<>(o[0], o[1])); + + for (final int c : commands) { + if (c == -1) { + d = (d + 1) % 4; + } else if (c == -2) { + d = (d + 3) % 4; + } else { + for (int step = 0; step < c; ++step) { + if (obstaclesSet.contains(new Pair<>(x + dirs[d], y + dirs[d + 1]))) + break; + x += dirs[d]; + y += dirs[d + 1]; + } + } + ans = Math.max(ans, x * x + y * y); + } + + return ans; + } +} diff --git a/solutions/874. Walking Robot Simulation/874.py b/solutions/874. Walking Robot Simulation/874.py new file mode 100644 index 00000000000..18954abd129 --- /dev/null +++ b/solutions/874. Walking Robot Simulation/874.py @@ -0,0 +1,24 @@ +class Solution: + def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: + dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) + ans = 0 + d = 0 # 0 := north, 1 := east, 2 := south, 3 := west + x = 0 # the start x + y = 0 # the start y + obstaclesSet = {(x, y) for x, y in obstacles} + + for c in commands: + if c == -1: + d = (d + 1) % 4 + elif c == -2: + d = (d + 3) % 4 + else: + for _ in range(c): + if (x + dirs[d], y + dirs[d + 1]) in obstaclesSet: + break + x += dirs[d] + y += dirs[d + 1] + + ans = max(ans, x * x + y * y) + + return ans diff --git a/solutions/875. Koko Eating Bananas/875.cpp b/solutions/875. Koko Eating Bananas/875.cpp new file mode 100644 index 00000000000..eee01c00b5e --- /dev/null +++ b/solutions/875. Koko Eating Bananas/875.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minEatingSpeed(vector& piles, int h) { + int l = 1; + int r = ranges::max(piles); + + while (l < r) { + const int m = (l + r) / 2; + if (eatHours(piles, m) <= h) + r = m; + else + l = m + 1; + } + + return l; + } + + private: + // Returns the hours to eat all the piles with speed m. + int eatHours(const vector& piles, int m) { + return accumulate(piles.begin(), piles.end(), 0, + [&](int subtotal, int pile) { + return subtotal + (pile - 1) / m + 1; // ceil(pile / m) + }); + } +}; diff --git a/solutions/875. Koko Eating Bananas/875.java b/solutions/875. Koko Eating Bananas/875.java new file mode 100644 index 00000000000..4d3e0c318ce --- /dev/null +++ b/solutions/875. Koko Eating Bananas/875.java @@ -0,0 +1,22 @@ +class Solution { + public int minEatingSpeed(int[] piles, int h) { + int l = 1; + int r = Arrays.stream(piles).max().getAsInt(); + + while (l < r) { + final int m = (l + r) / 2; + if (eatHours(piles, m) <= h) + r = m; + else + l = m + 1; + } + + return l; + } + + // Returns the hours to eat all the piles with speed m. + private int eatHours(int[] piles, int m) { + return Arrays.stream(piles).reduce( + 0, (subtotal, pile) -> subtotal + (pile - 1) / m + 1); // ceil(pile / m) + } +} diff --git a/solutions/875. Koko Eating Bananas/875.py b/solutions/875. Koko Eating Bananas/875.py new file mode 100644 index 00000000000..bc7519b7ec8 --- /dev/null +++ b/solutions/875. Koko Eating Bananas/875.py @@ -0,0 +1,7 @@ +class Solution: + def minEatingSpeed(self, piles: List[int], h: int) -> int: + def eatHours(m: int) -> bool: + """Returns True if Koko can eat all piles with speed m.""" + return sum((pile - 1) // m + 1 for pile in piles) <= h + return bisect.bisect_left(range(1, max(piles)), True, + key=lambda m: eatHours(m)) + 1 diff --git a/solutions/876. Middle of the Linked List/876.cpp b/solutions/876. Middle of the Linked List/876.cpp new file mode 100644 index 00000000000..2c6f48dbcae --- /dev/null +++ b/solutions/876. Middle of the Linked List/876.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + ListNode* middleNode(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head; + + while (fast != nullptr && fast->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + } + + return slow; + } +}; diff --git a/solutions/876. Middle of the Linked List/876.java b/solutions/876. Middle of the Linked List/876.java new file mode 100644 index 00000000000..bbbf796af95 --- /dev/null +++ b/solutions/876. Middle of the Linked List/876.java @@ -0,0 +1,13 @@ +class Solution { + public ListNode middleNode(ListNode head) { + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + return slow; + } +} diff --git a/solutions/876. Middle of the Linked List/876.py b/solutions/876. Middle of the Linked List/876.py new file mode 100644 index 00000000000..d455b070045 --- /dev/null +++ b/solutions/876. Middle of the Linked List/876.py @@ -0,0 +1,10 @@ +class Solution: + def middleNode(self, head: ListNode) -> ListNode: + slow = head + fast = head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + return slow diff --git a/solutions/877. Stone Game/877-2.cpp b/solutions/877. Stone Game/877-2.cpp new file mode 100644 index 00000000000..1d44a22068a --- /dev/null +++ b/solutions/877. Stone Game/877-2.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool stoneGame(vector& piles) { + const int n = piles.size(); + vector dp = piles; + + for (int d = 1; d < n; ++d) + for (int j = n - 1; j - d >= 0; --j) { + const int i = j - d; + dp[j] = max(piles[i] - dp[j], piles[j] - dp[j - 1]); + } + + return dp[n - 1] > 0; + } +}; diff --git a/solutions/877. Stone Game/877-2.java b/solutions/877. Stone Game/877-2.java new file mode 100644 index 00000000000..9a82812215c --- /dev/null +++ b/solutions/877. Stone Game/877-2.java @@ -0,0 +1,14 @@ +class Solution { + public boolean stoneGame(int[] piles) { + final int n = piles.length; + int[] dp = piles.clone(); + + for (int d = 1; d < n; ++d) + for (int j = n - 1; j - d >= 0; --j) { + final int i = j - d; + dp[j] = Math.max(piles[i] - dp[j], piles[j] - dp[j - 1]); + } + + return dp[n - 1] > 0; + } +} diff --git a/solutions/877. Stone Game/877-2.py b/solutions/877. Stone Game/877-2.py new file mode 100644 index 00000000000..a0a925a228a --- /dev/null +++ b/solutions/877. Stone Game/877-2.py @@ -0,0 +1,11 @@ +class Solution: + def stoneGame(self, piles: List[int]) -> bool: + n = len(piles) + dp = piles.copy() + + for d in range(1, n): + for j in range(n - 1, d - 1, -1): + i = j - d + dp[j] = max(piles[i] - dp[j], piles[j] - dp[j - 1]) + + return dp[n - 1] > 0 diff --git a/solutions/877. Stone Game/877.cpp b/solutions/877. Stone Game/877.cpp new file mode 100644 index 00000000000..121d90fd5f9 --- /dev/null +++ b/solutions/877. Stone Game/877.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + bool stoneGame(vector& piles) { + const int n = piles.size(); + // dp[i][j] := the maximum stones you can get more than your opponent in + // piles[i..j] + vector> dp(n, vector(n)); + + for (int i = 0; i < n; ++i) + dp[i][i] = piles[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + const int j = i + d; + dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]); + } + + return dp[0][n - 1] > 0; + } +}; diff --git a/solutions/877. Stone Game/877.java b/solutions/877. Stone Game/877.java new file mode 100644 index 00000000000..0499b4ae402 --- /dev/null +++ b/solutions/877. Stone Game/877.java @@ -0,0 +1,18 @@ +class Solution { + public boolean stoneGame(int[] piles) { + final int n = piles.length; + // dp[i][j] := the maximum stones you can get more than your opponent in piles[i..j] + int[][] dp = new int[n][n]; + + for (int i = 0; i < n; ++i) + dp[i][i] = piles[i]; + + for (int d = 1; d < n; ++d) + for (int i = 0; i + d < n; ++i) { + final int j = i + d; + dp[i][j] = Math.max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]); + } + + return dp[0][n - 1] > 0; + } +} diff --git a/solutions/877. Stone Game/877.py b/solutions/877. Stone Game/877.py new file mode 100644 index 00000000000..6cd9c1c5691 --- /dev/null +++ b/solutions/877. Stone Game/877.py @@ -0,0 +1,16 @@ +class Solution: + def stoneGame(self, piles: List[int]) -> bool: + n = len(piles) + # dp[i][j] := the maximum stones you can get more than your opponent in piles[i..j] + dp = [[0] * n for _ in range(n)] + + for i, pile in enumerate(piles): + dp[i][i] = pile + + for d in range(1, n): + for i in range(n - d): + j = i + d + dp[i][j] = max(piles[i] - dp[i + 1][j], + piles[j] - dp[i][j - 1]) + + return dp[0][n - 1] > 0 diff --git a/solutions/878. Nth Magical Number/878.cpp b/solutions/878. Nth Magical Number/878.cpp new file mode 100644 index 00000000000..450f06fef4e --- /dev/null +++ b/solutions/878. Nth Magical Number/878.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int nthMagicalNumber(long n, long a, long b) { + constexpr int kMod = 1'000'000'007; + const long lcm = a * b / __gcd(a, b); + long l = min(a, b); + long r = min(a, b) * n; + + while (l < r) { + const long m = (l + r) / 2; + if (m / a + m / b - m / lcm >= n) + r = m; + else + l = m + 1; + } + + return l % kMod; + } +}; diff --git a/solutions/878. Nth Magical Number/878.java b/solutions/878. Nth Magical Number/878.java new file mode 100644 index 00000000000..7e682f3bcbf --- /dev/null +++ b/solutions/878. Nth Magical Number/878.java @@ -0,0 +1,22 @@ +class Solution { + public int nthMagicalNumber(long n, long a, long b) { + final int kMod = 1_000_000_007; + final long lcm = a * b / gcd(a, b); + long l = Math.min(a, b); + long r = Math.min(a, b) * n; + + while (l < r) { + final long m = (l + r) / 2; + if (m / a + m / b - m / lcm >= n) + r = m; + else + l = m + 1; + } + + return (int) (l % kMod); + } + + private long gcd(long a, long b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/solutions/878. Nth Magical Number/878.py b/solutions/878. Nth Magical Number/878.py new file mode 100644 index 00000000000..b1c0b7c0188 --- /dev/null +++ b/solutions/878. Nth Magical Number/878.py @@ -0,0 +1,6 @@ +class Solution: + def nthMagicalNumber(self, n: int, a: int, b: int) -> int: + lcm = a * b // math.gcd(a, b) + l = bisect.bisect_left(range(min(a, b), min(a, b) * n), n, + key=lambda m: m // a + m // b - m // lcm) + min(a, b) + return l % (10**9 + 7) diff --git a/solutions/879. Profitable Schemes/879-2.cpp b/solutions/879. Profitable Schemes/879-2.cpp new file mode 100644 index 00000000000..144b0a706c3 --- /dev/null +++ b/solutions/879. Profitable Schemes/879-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int profitableSchemes(int n, int minProfit, vector& group, + vector& profit) { + constexpr int kMod = 1'000'000'007; + // dp[i][j] := the number of schemes, where <= i members, generating + // >= j profits + vector> dp(n + 1, vector(minProfit + 1)); + + for (int i = 0; i <= n; ++i) + dp[i][0] = 1; + + for (int k = 1; k <= group.size(); ++k) { + const int g = group[k - 1]; + const int p = profit[k - 1]; + for (int i = n; i >= g; --i) + for (int j = minProfit; j >= 0; --j) { + dp[i][j] += dp[i - g][max(0, j - p)]; + dp[i][j] %= kMod; + } + } + + return dp[n][minProfit]; + } +}; diff --git a/solutions/879. Profitable Schemes/879-2.java b/solutions/879. Profitable Schemes/879-2.java new file mode 100644 index 00000000000..e9e64a90a96 --- /dev/null +++ b/solutions/879. Profitable Schemes/879-2.java @@ -0,0 +1,23 @@ +class Solution { + public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { + final int kMod = 1_000_000_007; + // dp[i][j] := the number of schemes, where <= i members, generating + // >= j profits + int[][] dp = new int[n + 1][minProfit + 1]; + + for (int i = 0; i <= n; ++i) + dp[i][0] = 1; + + for (int k = 1; k <= group.length; ++k) { + final int g = group[k - 1]; + final int p = profit[k - 1]; + for (int i = n; i >= g; --i) + for (int j = minProfit; j >= 0; --j) { + dp[i][j] += dp[i - g][Math.max(0, j - p)]; + dp[i][j] %= kMod; + } + } + + return dp[n][minProfit]; + } +} diff --git a/solutions/879. Profitable Schemes/879.cpp b/solutions/879. Profitable Schemes/879.cpp new file mode 100644 index 00000000000..0755ad704d5 --- /dev/null +++ b/solutions/879. Profitable Schemes/879.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int profitableSchemes(int n, int minProfit, vector& group, + vector& profit) { + constexpr int kMod = 1'000'000'007; + // dp[k][i][j] := the number of schemes, where the first k crimes are + // committed by <= i members, generating >= j profits + vector>> dp( + group.size() + 1, + vector>(n + 1, vector(minProfit + 1))); + + // No crimes, no profits, and any number of members. + for (int i = 0; i <= n; ++i) + dp[0][i][0] = 1; + + for (int k = 1; k <= group.size(); ++k) { + const int g = group[k - 1]; + const int p = profit[k - 1]; + for (int i = 0; i <= n; ++i) + for (int j = 0; j <= minProfit; ++j) + if (i < g) { + dp[k][i][j] = dp[k - 1][i][j]; + } else { + dp[k][i][j] = dp[k - 1][i][j] + dp[k - 1][i - g][max(0, j - p)]; + dp[k][i][j] %= kMod; + } + } + + return dp[group.size()][n][minProfit]; + } +}; diff --git a/solutions/879. Profitable Schemes/879.java b/solutions/879. Profitable Schemes/879.java new file mode 100644 index 00000000000..d5a4b1f3338 --- /dev/null +++ b/solutions/879. Profitable Schemes/879.java @@ -0,0 +1,27 @@ +class Solution { + public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { + final int kMod = 1_000_000_007; + // dp[k][i][j] := the number of schemes, where the first k crimes are + // committed by <= i members, generating >= j profits + int[][][] dp = new int[group.length + 1][n + 1][minProfit + 1]; + + // No crimes, no profits, and any number of members. + for (int i = 0; i <= n; ++i) + dp[0][i][0] = 1; + + for (int k = 1; k <= group.length; ++k) { + final int g = group[k - 1]; + final int p = profit[k - 1]; + for (int i = 0; i <= n; ++i) + for (int j = 0; j <= minProfit; ++j) + if (i < g) { + dp[k][i][j] = dp[k - 1][i][j]; + } else { + dp[k][i][j] = dp[k - 1][i][j] + dp[k - 1][i - g][Math.max(0, j - p)]; + dp[k][i][j] %= kMod; + } + } + + return dp[group.length][n][minProfit]; + } +} diff --git a/solutions/88. Merge Sorted Array/88.cpp b/solutions/88. Merge Sorted Array/88.cpp new file mode 100644 index 00000000000..ded36d91be0 --- /dev/null +++ b/solutions/88. Merge Sorted Array/88.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int i = m - 1; // nums1's index (the actual nums) + int j = n - 1; // nums2's index + int k = m + n - 1; // nums1's index (the next filled position) + + while (j >= 0) + if (i >= 0 && nums1[i] > nums2[j]) + nums1[k--] = nums1[i--]; + else + nums1[k--] = nums2[j--]; + } +}; diff --git a/solutions/88. Merge Sorted Array/88.java b/solutions/88. Merge Sorted Array/88.java new file mode 100644 index 00000000000..b56fd4e4a65 --- /dev/null +++ b/solutions/88. Merge Sorted Array/88.java @@ -0,0 +1,13 @@ +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int i = m - 1; // nums1's index (the actual nums) + int j = n - 1; // nums2's index + int k = m + n - 1; // nums1's index (the next filled position) + + while (j >= 0) + if (i >= 0 && nums1[i] > nums2[j]) + nums1[k--] = nums1[i--]; + else + nums1[k--] = nums2[j--]; + } +} diff --git a/solutions/88. Merge Sorted Array/88.py b/solutions/88. Merge Sorted Array/88.py new file mode 100644 index 00000000000..84b5e9d2e08 --- /dev/null +++ b/solutions/88. Merge Sorted Array/88.py @@ -0,0 +1,15 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + i = m - 1 # nums1's index (the actual nums) + j = n - 1 # nums2's index + k = m + n - 1 # nums1's index (the next filled position) + + while j >= 0: + if i >= 0 and nums1[i] > nums2[j]: + nums1[k] = nums1[i] + k -= 1 + i -= 1 + else: + nums1[k] = nums2[j] + k -= 1 + j -= 1 diff --git a/solutions/880. Decoded String at Index/880.cpp b/solutions/880. Decoded String at Index/880.cpp new file mode 100644 index 00000000000..2cb3c868a7a --- /dev/null +++ b/solutions/880. Decoded String at Index/880.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + string decodeAtIndex(string s, int k) { + long size = 0; // the length of the decoded `s` + + for (const char c : s) + if (isdigit(c)) + size *= c - '0'; + else + ++size; + + for (int i = s.length() - 1; i >= 0; --i) { + k %= size; + if (k == 0 && isalpha(s[i])) + return string(1, s[i]); + if (isdigit(s[i])) + size /= s[i] - '0'; + else + --size; + } + + throw; + } +}; diff --git a/solutions/880. Decoded String at Index/880.java b/solutions/880. Decoded String at Index/880.java new file mode 100644 index 00000000000..36156a412c3 --- /dev/null +++ b/solutions/880. Decoded String at Index/880.java @@ -0,0 +1,23 @@ +class Solution { + public String decodeAtIndex(String s, int k) { + long size = 0; // the length of the decoded `s` + + for (final char c : s.toCharArray()) + if (Character.isDigit(c)) + size *= c - '0'; + else + ++size; + + for (int i = s.length() - 1; i >= 0; --i) { + k %= size; + if (k == 0 && Character.isAlphabetic(s.charAt(i))) + return s.substring(i, i + 1); + if (Character.isDigit(s.charAt(i))) + size /= s.charAt(i) - '0'; + else + --size; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/880. Decoded String at Index/880.py b/solutions/880. Decoded String at Index/880.py new file mode 100644 index 00000000000..f4f2f403e98 --- /dev/null +++ b/solutions/880. Decoded String at Index/880.py @@ -0,0 +1,18 @@ +class Solution: + def decodeAtIndex(self, s: str, k: int) -> str: + size = 0 + + for c in s: + if c.isdigit(): + size *= int(c) + else: + size += 1 + + for c in reversed(s): + k %= size + if k == 0 and c.isalpha(): + return c + if c.isdigit(): + size //= int(c) + else: + size -= 1 diff --git a/solutions/881. Boats to Save People/881.cpp b/solutions/881. Boats to Save People/881.cpp new file mode 100644 index 00000000000..e01cc5c3a20 --- /dev/null +++ b/solutions/881. Boats to Save People/881.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int numRescueBoats(vector& people, int limit) { + int ans = 0; + + ranges::sort(people); + + for (int i = 0, j = people.size() - 1; i <= j; ++ans) { + const int remain = limit - people[j--]; + if (people[i] <= remain) + ++i; + } + + return ans; + } +}; diff --git a/solutions/881. Boats to Save People/881.java b/solutions/881. Boats to Save People/881.java new file mode 100644 index 00000000000..c762e7420c1 --- /dev/null +++ b/solutions/881. Boats to Save People/881.java @@ -0,0 +1,15 @@ +class Solution { + public int numRescueBoats(int[] people, int limit) { + int ans = 0; + + Arrays.sort(people); + + for (int i = 0, j = people.length - 1; i <= j; ++ans) { + final int remain = limit - people[j--]; + if (people[i] <= remain) + ++i; + } + + return ans; + } +} diff --git a/solutions/881. Boats to Save People/881.py b/solutions/881. Boats to Save People/881.py new file mode 100644 index 00000000000..6b11be4e964 --- /dev/null +++ b/solutions/881. Boats to Save People/881.py @@ -0,0 +1,16 @@ +class Solution: + def numRescueBoats(self, people: List[int], limit: int) -> int: + ans = 0 + i = 0 + j = len(people) - 1 + + people.sort() + + while i <= j: + remain = limit - people[j] + j -= 1 + if people[i] <= remain: + i += 1 + ans += 1 + + return ans diff --git a/solutions/882. Reachable Nodes In Subdivided Graph/882.cpp b/solutions/882. Reachable Nodes In Subdivided Graph/882.cpp new file mode 100644 index 00000000000..c49b389aab2 --- /dev/null +++ b/solutions/882. Reachable Nodes In Subdivided Graph/882.cpp @@ -0,0 +1,58 @@ +class Solution { + public: + int reachableNodes(vector>& edges, int maxMoves, int n) { + vector>> graph(n); + vector dist(graph.size(), maxMoves + 1); + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int cnt = edge[2]; + graph[u].emplace_back(v, cnt); + graph[v].emplace_back(u, cnt); + } + + const int reachableNodes = dijkstra(graph, 0, maxMoves, dist); + int reachableSubnodes = 0; + + for (const vector& edge : edges) { + const int u = edge[0]; + const int v = edge[1]; + const int cnt = edge[2]; + // the number of reachable nodes of `edge` from `u` + const int a = dist[u] > maxMoves ? 0 : min(maxMoves - dist[u], cnt); + // the number of reachable nodes of `edge` from `v` + const int b = dist[v] > maxMoves ? 0 : min(maxMoves - dist[v], cnt); + reachableSubnodes += min(a + b, cnt); + } + + return reachableNodes + reachableSubnodes; + } + + private: + int dijkstra(const vector>>& graph, int src, + int maxMoves, vector& dist) { + using P = pair; // (d, u) + priority_queue, greater<>> minHeap; + + dist[src] = 0; + minHeap.emplace(dist[src], src); + + while (!minHeap.empty()) { + const auto [d, u] = minHeap.top(); + minHeap.pop(); + // Already took `maxMoves` to reach `u`, so can't explore anymore. + if (d >= maxMoves) + break; + if (d > dist[u]) + continue; + for (const auto& [v, w] : graph[u]) + if (d + w + 1 < dist[v]) { + dist[v] = d + w + 1; + minHeap.emplace(dist[v], v); + } + } + + return ranges::count_if(dist, [&](int d) { return d <= maxMoves; }); + } +}; diff --git a/solutions/882. Reachable Nodes In Subdivided Graph/882.java b/solutions/882. Reachable Nodes In Subdivided Graph/882.java new file mode 100644 index 00000000000..09a3479a309 --- /dev/null +++ b/solutions/882. Reachable Nodes In Subdivided Graph/882.java @@ -0,0 +1,63 @@ +class Solution { + public int reachableNodes(int[][] edges, int maxMoves, int n) { + List>[] graph = new List[n]; + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); // (d, u) + int[] dist = new int[n]; + Arrays.fill(dist, maxMoves + 1); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int cnt = edge[2]; + graph[u].add(new Pair<>(v, cnt)); + graph[v].add(new Pair<>(u, cnt)); + } + + final int reachableNodes = dijkstra(graph, 0, maxMoves, dist); + int reachableSubnodes = 0; + + for (int[] edge : edges) { + final int u = edge[0]; + final int v = edge[1]; + final int cnt = edge[2]; + // the number of reachable nodes of `edge` from `u` + final int a = dist[u] > maxMoves ? 0 : Math.min(maxMoves - dist[u], cnt); + // the number of reachable nodes of `edge` from `v` + final int b = dist[v] > maxMoves ? 0 : Math.min(maxMoves - dist[v], cnt); + reachableSubnodes += Math.min(a + b, cnt); + } + + return reachableNodes + reachableSubnodes; + } + + private int dijkstra(List>[] graph, int src, int maxMoves, int[] dist) { + // (d, u) + Queue> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + + dist[src] = 0; + minHeap.offer(new Pair<>(dist[src], src)); + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek().getKey(); + final int u = minHeap.poll().getValue(); + // Already took `maxMoves` to reach `u`, so can't explore anymore. + if (d >= maxMoves) + break; + if (d > dist[u]) + continue; + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + if (d + w + 1 < dist[v]) { + dist[v] = d + w + 1; + minHeap.offer(new Pair<>(dist[v], v)); + } + } + } + + return (int) Arrays.stream(dist).filter(d -> d <= maxMoves).count(); + } +} diff --git a/solutions/882. Reachable Nodes In Subdivided Graph/882.py b/solutions/882. Reachable Nodes In Subdivided Graph/882.py new file mode 100644 index 00000000000..9cff1f49a4d --- /dev/null +++ b/solutions/882. Reachable Nodes In Subdivided Graph/882.py @@ -0,0 +1,39 @@ +class Solution: + def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int: + graph = [[] for _ in range(n)] + dist = [maxMoves + 1] * n + + for u, v, cnt in edges: + graph[u].append((v, cnt)) + graph[v].append((u, cnt)) + + reachableNodes = self._dijkstra(graph, 0, maxMoves, dist) + reachableSubnodes = 0 + + for u, v, cnt in edges: + # the number of reachable nodes of (u, v) from `u` + a = 0 if dist[u] > maxMoves else min(maxMoves - dist[u], cnt) + # the number of reachable nodes of (u, v) from `v` + b = 0 if dist[v] > maxMoves else min(maxMoves - dist[v], cnt) + reachableSubnodes += min(a + b, cnt) + + return reachableNodes + reachableSubnodes + + def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, maxMoves: int, dist: List[int]) -> int: + dist[src] = 0 + minHeap = [(dist[src], src)] # (d, u) + + while minHeap: + d, u = heapq.heappop(minHeap) + # Already took `maxMoves` to reach `u`, so can't explore anymore. + if dist[u] >= maxMoves: + break + if d > dist[u]: + continue + for v, w in graph[u]: + newDist = d + w + 1 + if newDist < dist[v]: + dist[v] = newDist + heapq.heappush(minHeap, (newDist, v)) + + return sum(d <= maxMoves for d in dist) diff --git a/solutions/883. Projection Area of 3D Shapes/883.cpp b/solutions/883. Projection Area of 3D Shapes/883.cpp new file mode 100644 index 00000000000..1e0c37dcac3 --- /dev/null +++ b/solutions/883. Projection Area of 3D Shapes/883.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int projectionArea(vector>& grid) { + int ans = 0; + + for (int i = 0; i < grid.size(); ++i) { + int maxOfRow = 0; + int maxOfCol = 0; + for (int j = 0; j < grid.size(); ++j) { + maxOfRow = max(maxOfRow, grid[i][j]); + maxOfCol = max(maxOfCol, grid[j][i]); + if (grid[i][j]) + ++ans; + } + ans += maxOfRow + maxOfCol; + } + + return ans; + } +}; diff --git a/solutions/883. Projection Area of 3D Shapes/883.java b/solutions/883. Projection Area of 3D Shapes/883.java new file mode 100644 index 00000000000..79f3b602f29 --- /dev/null +++ b/solutions/883. Projection Area of 3D Shapes/883.java @@ -0,0 +1,19 @@ +class Solution { + public int projectionArea(int[][] grid) { + int ans = 0; + + for (int i = 0; i < grid.length; ++i) { + int maxOfRow = 0; + int maxOfCol = 0; + for (int j = 0; j < grid.length; ++j) { + maxOfRow = Math.max(maxOfRow, grid[i][j]); + maxOfCol = Math.max(maxOfCol, grid[j][i]); + if (grid[i][j] > 0) + ++ans; + } + ans += maxOfRow + maxOfCol; + } + + return ans; + } +} diff --git a/solutions/883. Projection Area of 3D Shapes/883.py b/solutions/883. Projection Area of 3D Shapes/883.py new file mode 100644 index 00000000000..8a0b8422cc5 --- /dev/null +++ b/solutions/883. Projection Area of 3D Shapes/883.py @@ -0,0 +1,3 @@ +class Solution: + def projectionArea(self, grid: List[List[int]]) -> int: + return sum(a > 0 for row in grid for a in row) + sum(max(row) for row in grid) + sum(max(col) for col in zip(*grid)) diff --git a/solutions/884. Uncommon Words from Two Sentences/884.cpp b/solutions/884. Uncommon Words from Two Sentences/884.cpp new file mode 100644 index 00000000000..8cccfbccc11 --- /dev/null +++ b/solutions/884. Uncommon Words from Two Sentences/884.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector uncommonFromSentences(string A, string B) { + vector ans; + unordered_map count; + istringstream iss(A + ' ' + B); + + while (iss >> A) + ++count[A]; + + for (const auto& [word, freq] : count) + if (freq == 1) + ans.push_back(word); + + return ans; + } +}; diff --git a/solutions/884. Uncommon Words from Two Sentences/884.java b/solutions/884. Uncommon Words from Two Sentences/884.java new file mode 100644 index 00000000000..f89e9af079c --- /dev/null +++ b/solutions/884. Uncommon Words from Two Sentences/884.java @@ -0,0 +1,15 @@ +class Solution { + public String[] uncommonFromSentences(String A, String B) { + List ans = new ArrayList<>(); + Map count = new HashMap<>(); + + for (final String word : (A + ' ' + B).split(" ")) + count.merge(word, 1, Integer::sum); + + for (final String word : count.keySet()) + if (count.get(word) == 1) + ans.add(word); + + return ans.toArray(new String[0]); + } +} diff --git a/solutions/884. Uncommon Words from Two Sentences/884.py b/solutions/884. Uncommon Words from Two Sentences/884.py new file mode 100644 index 00000000000..25d8ee68b01 --- /dev/null +++ b/solutions/884. Uncommon Words from Two Sentences/884.py @@ -0,0 +1,4 @@ +class Solution: + def uncommonFromSentences(self, A: str, B: str) -> List[str]: + count = collections.Counter((A + ' ' + B).split()) + return [word for word, freq in count.items() if freq == 1] diff --git a/solutions/885. Spiral Matrix III/885.cpp b/solutions/885. Spiral Matrix III/885.cpp new file mode 100644 index 00000000000..74fc9f7c1fe --- /dev/null +++ b/solutions/885. Spiral Matrix III/885.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector> spiralMatrixIII(int rows, int cols, int rStart, + int cStart) { + const vector dx{1, 0, -1, 0}; + const vector dy{0, 1, 0, -1}; + vector> ans{{rStart, cStart}}; + + for (int i = 0; ans.size() < rows * cols; ++i) + for (int step = 0; step < i / 2 + 1; ++step) { + rStart += dy[i % 4]; + cStart += dx[i % 4]; + if (0 <= rStart && rStart < rows && 0 <= cStart && cStart < cols) + ans.push_back({rStart, cStart}); + } + + return ans; + } +}; diff --git a/solutions/885. Spiral Matrix III/885.java b/solutions/885. Spiral Matrix III/885.java new file mode 100644 index 00000000000..26bb22dd390 --- /dev/null +++ b/solutions/885. Spiral Matrix III/885.java @@ -0,0 +1,17 @@ +class Solution { + public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { + final int[] dx = {1, 0, -1, 0}; + final int[] dy = {0, 1, 0, -1}; + List ans = new ArrayList<>(Arrays.asList(new int[] {rStart, cStart})); + + for (int i = 0; ans.size() < rows * cols; ++i) + for (int step = 0; step < i / 2 + 1; ++step) { + rStart += dy[i % 4]; + cStart += dx[i % 4]; + if (0 <= rStart && rStart < rows && 0 <= cStart && cStart < cols) + ans.add(new int[] {rStart, cStart}); + } + + return ans.stream().toArray(int[][] ::new); + } +} diff --git a/solutions/885. Spiral Matrix III/885.py b/solutions/885. Spiral Matrix III/885.py new file mode 100644 index 00000000000..8abbbb6a27d --- /dev/null +++ b/solutions/885. Spiral Matrix III/885.py @@ -0,0 +1,16 @@ +class Solution: + def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]: + dx = [1, 0, -1, 0] + dy = [0, 1, 0, -1] + ans = [[rStart, cStart]] + i = 0 + + while len(ans) < rows * cols: + for _ in range(i // 2 + 1): + rStart += dy[i % 4] + cStart += dx[i % 4] + if 0 <= rStart < rows and 0 <= cStart < cols: + ans.append([rStart, cStart]) + i += 1 + + return ans diff --git a/solutions/886. Possible Bipartition/886.cpp b/solutions/886. Possible Bipartition/886.cpp new file mode 100644 index 00000000000..2b523e319c8 --- /dev/null +++ b/solutions/886. Possible Bipartition/886.cpp @@ -0,0 +1,42 @@ +enum Color { kWhite, kRed, kGreen }; + +class Solution { + public: + bool possibleBipartition(int n, vector>& dislikes) { + vector> graph(n + 1); + vector colors(n + 1, Color::kWhite); + + for (const vector& d : dislikes) { + const int u = d[0]; + const int v = d[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + // Reduce to 785. Is Graph Bipartite? + for (int i = 1; i <= n; ++i) + if (colors[i] == Color::kWhite && + !isValidColor(graph, i, colors, Color::kRed)) + return false; + + return true; + } + + private: + bool isValidColor(const vector>& graph, int u, + vector& colors, Color color) { + // Always paint red for a white node. + if (colors[u] != Color::kWhite) + return colors[u] == color; + + colors[u] = color; // Always paint the node with `color`. + + // All the children should have valid colors. + for (const int v : graph[u]) + if (!isValidColor(graph, v, colors, + color == Color::kRed ? Color::kGreen : Color::kRed)) + return false; + + return true; + } +}; diff --git a/solutions/886. Possible Bipartition/886.java b/solutions/886. Possible Bipartition/886.java new file mode 100644 index 00000000000..a58545eb159 --- /dev/null +++ b/solutions/886. Possible Bipartition/886.java @@ -0,0 +1,41 @@ +enum Color { kWhite, kRed, kGreen } + +class Solution { + public boolean possibleBipartition(int n, int[][] dislikes) { + List[] graph = new List[n + 1]; + Color[] colors = new Color[n + 1]; + Arrays.fill(colors, Color.kWhite); + + for (int i = 1; i <= n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] d : dislikes) { + final int u = d[0]; + final int v = d[1]; + graph[u].add(v); + graph[v].add(u); + } + + // Reduce to 785. Is Graph Bipartite? + for (int i = 1; i <= n; ++i) + if (colors[i] == Color.kWhite && !isValidColor(graph, i, colors, Color.kRed)) + return false; + + return true; + } + + private boolean isValidColor(List[] graph, int u, Color[] colors, Color color) { + // Always paint red for a white node. + if (colors[u] != Color.kWhite) + return colors[u] == color; + + colors[u] = color; // Always paint the node with `color`. + + // All the children should have valid colors. + for (final int v : graph[u]) + if (!isValidColor(graph, v, colors, color == Color.kRed ? Color.kGreen : Color.kRed)) + return false; + + return true; + } +} diff --git a/solutions/886. Possible Bipartition/886.py b/solutions/886. Possible Bipartition/886.py new file mode 100644 index 00000000000..761c666eddc --- /dev/null +++ b/solutions/886. Possible Bipartition/886.py @@ -0,0 +1,32 @@ +from enum import Enum + + +class Color(Enum): + kWhite = 0 + kRed = 1 + kGreen = 2 + + +class Solution: + def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: + graph = [[] for _ in range(n + 1)] + colors = [Color.kWhite] * (n + 1) + + for u, v in dislikes: + graph[u].append(v) + graph[v].append(u) + + # Reduce to 785. Is Graph Bipartite? + def isValidColor(u: int, color: Color) -> bool: + # Always paint red for a white node. + if colors[u] != Color.kWhite: + return colors[u] == color + + colors[u] = color # Always paint the node with `color`. + + # All the children should have valid colors. + childrenColor = Color.kRed if colors[u] == Color.kGreen else Color.kGreen + return all(isValidColor(v, childrenColor) for v in graph[u]) + + return all(colors[i] != Color.kWhite or isValidColor(i, Color.kRed) + for i in range(1, n + 1)) diff --git a/solutions/887. Super Egg Drop/887-2.cpp b/solutions/887. Super Egg Drop/887-2.cpp new file mode 100644 index 00000000000..25d926bb758 --- /dev/null +++ b/solutions/887. Super Egg Drop/887-2.cpp @@ -0,0 +1,43 @@ +class Solution { + public: + int superEggDrop(int k, int n) { + vector> mem(k + 1, vector(n + 1, -1)); + return drop(k, n, mem); + } + + private: + // Returns the minimum number of moves to know f with k eggs and n floors. + int drop(int k, int n, vector>& mem) { + if (k == 0) // no eggs -> done + return 0; + if (k == 1) // one egg -> drop from 1-th floor to n-th floor + return n; + if (n == 0) // no floor -> done + return 0; + if (n == 1) // one floor -> drop from that floor + return 1; + if (mem[k][n] != -1) + return mem[k][n]; + + // broken[i] := drop(k - 1, i - 1) is increasing with i + // unbroken[i] := drop(k, n - i) is decreasing with i + // mem[k][n] := 1 + min(max(broken[i], unbroken[i])), 1 <= i <= n + // Find the first index i s.t broken[i] >= unbroken[i], which minimizes + // max(broken[i], unbroken[i]). + + int l = 1; + int r = n + 1; + + while (l < r) { + const int m = (l + r) / 2; + const int broken = drop(k - 1, m - 1, mem); + const int unbroken = drop(k, n - m, mem); + if (broken >= unbroken) + r = m; + else + l = m + 1; + } + + return mem[k][n] = 1 + drop(k - 1, l - 1, mem); + } +}; diff --git a/solutions/887. Super Egg Drop/887-2.java b/solutions/887. Super Egg Drop/887-2.java new file mode 100644 index 00000000000..a1fe6ccef0c --- /dev/null +++ b/solutions/887. Super Egg Drop/887-2.java @@ -0,0 +1,36 @@ +class Solution { + public int superEggDrop(int k, int n) { + int[][] mem = new int[k + 1][n + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, -1)); + return drop(k, n, mem); + } + + // Returns the minimum number of moves to know f with k eggs and n floors. + private int drop(int k, int n, int[][] mem) { + if (k == 0) // no eggs -> done + return 0; + if (k == 1) // one egg -> drop from 1-th floor to n-th floor + return n; + if (n == 0) // no floor -> done + return 0; + if (n == 1) // one floor -> drop from that floor + return 1; + if (mem[k][n] != -1) + return mem[k][n]; + + int l = 1; + int r = n + 1; + + while (l < r) { + final int m = (l + r) / 2; + final int broken = drop(k - 1, m - 1, mem); + final int unbroken = drop(k, n - m, mem); + if (broken >= unbroken) + r = m; + else + l = m + 1; + } + + return mem[k][n] = 1 + drop(k - 1, l - 1, mem); + } +} diff --git a/solutions/887. Super Egg Drop/887-3.cpp b/solutions/887. Super Egg Drop/887-3.cpp new file mode 100644 index 00000000000..e62a1a93dda --- /dev/null +++ b/solutions/887. Super Egg Drop/887-3.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int superEggDrop(int k, int n) { + int moves = 0; + vector> dp(n + 1, vector(k + 1)); + + while (dp[moves][k] < n) { + ++moves; + for (int eggs = 1; eggs <= k; ++eggs) + dp[moves][eggs] = dp[moves - 1][eggs - 1] + dp[moves - 1][eggs] + 1; + } + + return moves; + } +}; diff --git a/solutions/887. Super Egg Drop/887-3.java b/solutions/887. Super Egg Drop/887-3.java new file mode 100644 index 00000000000..aba3720d618 --- /dev/null +++ b/solutions/887. Super Egg Drop/887-3.java @@ -0,0 +1,14 @@ +class Solution { + public int superEggDrop(int k, int n) { + int moves = 0; + int[][] dp = new int[n + 1][k + 1]; + + while (dp[moves][k] < n) { + ++moves; + for (int eggs = 1; eggs <= k; ++eggs) + dp[moves][eggs] = dp[moves - 1][eggs - 1] + dp[moves - 1][eggs] + 1; + } + + return moves; + } +} diff --git a/solutions/887. Super Egg Drop/887-3.py b/solutions/887. Super Egg Drop/887-3.py new file mode 100644 index 00000000000..16acdff4dee --- /dev/null +++ b/solutions/887. Super Egg Drop/887-3.py @@ -0,0 +1,12 @@ +class Solution: + def superEggDrop(self, k: int, n: int) -> int: + moves = 0 + dp = [[0] * (k + 1) for _ in range(n + 1)] + + while dp[moves][k] < n: + moves += 1 + for eggs in range(1, k + 1): + dp[moves][eggs] = dp[moves - 1][eggs - 1] + \ + dp[moves - 1][eggs] + 1 + + return moves diff --git a/solutions/887. Super Egg Drop/887.cpp b/solutions/887. Super Egg Drop/887.cpp new file mode 100644 index 00000000000..dfe62ef443f --- /dev/null +++ b/solutions/887. Super Egg Drop/887.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int superEggDrop(int k, int n) { + vector> mem(k + 1, vector(n + 1, INT_MAX)); + return drop(k, n, mem); + } + + private: + // Returns the minimum number of moves to know f with k eggs and n floors. + int drop(int k, int n, vector>& mem) { + if (k == 0) // no eggs -> done + return 0; + if (k == 1) // one egg -> drop from 1-th floor to n-th floor + return n; + if (n == 0) // no floor -> done + return 0; + if (n == 1) // one floor -> drop from that floor + return 1; + if (mem[k][n] != INT_MAX) + return mem[k][n]; + + for (int i = 1; i <= n; ++i) { + const int broken = drop(k - 1, i - 1, mem); + const int unbroken = drop(k, n - i, mem); + mem[k][n] = min(mem[k][n], 1 + max(broken, unbroken)); + } + + return mem[k][n]; + } +}; diff --git a/solutions/887. Super Egg Drop/887.java b/solutions/887. Super Egg Drop/887.java new file mode 100644 index 00000000000..fb99e79c743 --- /dev/null +++ b/solutions/887. Super Egg Drop/887.java @@ -0,0 +1,29 @@ +class Solution { + public int superEggDrop(int k, int n) { + int[][] mem = new int[k + 1][n + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + return drop(k, n, mem); + } + + // Returns the minimum number of moves to know f with k eggs and n floors. + private int drop(int k, int n, int[][] mem) { + if (k == 0) // no eggs -> done + return 0; + if (k == 1) // one egg -> drop from 1st floor to nth floor + return n; + if (n == 0) // no floor -> done + return 0; + if (n == 1) // one floor -> drop from that floor + return 1; + if (mem[k][n] != Integer.MAX_VALUE) + return mem[k][n]; + + for (int i = 1; i <= n; ++i) { + final int broken = drop(k - 1, i - 1, mem); + final int unbroken = drop(k, n - i, mem); + mem[k][n] = Math.min(mem[k][n], 1 + Math.max(broken, unbroken)); + } + + return mem[k][n]; + } +} diff --git a/solutions/888. Fair Candy Swap/888.cpp b/solutions/888. Fair Candy Swap/888.cpp new file mode 100644 index 00000000000..56cdad388dd --- /dev/null +++ b/solutions/888. Fair Candy Swap/888.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector fairCandySwap(vector& aliceSizes, vector& bobSizes) { + const int diff = (accumulate(aliceSizes.begin(), aliceSizes.end(), 0) - + accumulate(bobSizes.begin(), bobSizes.end(), 0)) / + 2; + const unordered_set bobSizesSet{bobSizes.begin(), bobSizes.end()}; + + for (const int aliceSize : aliceSizes) { + const int target = aliceSize - diff; + if (bobSizesSet.contains(target)) + return {aliceSize, target}; + } + + throw; + } +}; diff --git a/solutions/888. Fair Candy Swap/888.java b/solutions/888. Fair Candy Swap/888.java new file mode 100644 index 00000000000..fd7af7b9046 --- /dev/null +++ b/solutions/888. Fair Candy Swap/888.java @@ -0,0 +1,14 @@ +class Solution { + public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { + final int diff = (Arrays.stream(aliceSizes).sum() - Arrays.stream(bobSizes).sum()) / 2; + Set bobSizesSet = Arrays.stream(bobSizes).boxed().collect(Collectors.toSet()); + + for (final int aliceSize : aliceSizes) { + final int target = aliceSize - diff; + if (bobSizesSet.contains(target)) + return new int[] {aliceSize, target}; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/888. Fair Candy Swap/888.py b/solutions/888. Fair Candy Swap/888.py new file mode 100644 index 00000000000..2829f1a0d8e --- /dev/null +++ b/solutions/888. Fair Candy Swap/888.py @@ -0,0 +1,9 @@ +class Solution: + def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]: + diff = (sum(aliceSizes) - sum(bobSizes)) // 2 + bobSizesSet = set(bobSizes) + + for aliceSize in aliceSizes: + target = aliceSize - diff + if target in bobSizesSet: + return [aliceSize, target] diff --git a/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.cpp b/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.cpp new file mode 100644 index 00000000000..ffe3cef6cea --- /dev/null +++ b/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + TreeNode* constructFromPrePost(vector& pre, vector& post) { + unordered_map postToIndex; + + for (int i = 0; i < post.size(); ++i) + postToIndex[post[i]] = i; + + return build(pre, 0, pre.size() - 1, post, 0, post.size() - 1, postToIndex); + } + + private: + TreeNode* build(const vector& pre, int preStart, int preEnd, + const vector& post, int postStart, int postEnd, + const unordered_map& postToIndex) { + if (preStart > preEnd) + return nullptr; + if (preStart == preEnd) + return new TreeNode(pre[preStart]); + + const int rootVal = pre[preStart]; + const int leftRootVal = pre[preStart + 1]; + const int leftRootPostIndex = postToIndex.at(leftRootVal); + const int leftSize = leftRootPostIndex - postStart + 1; + + TreeNode* root = new TreeNode(rootVal); + root->left = build(pre, preStart + 1, preStart + leftSize, post, postStart, + leftRootPostIndex, postToIndex); + root->right = build(pre, preStart + leftSize + 1, preEnd, post, + leftRootPostIndex + 1, postEnd - 1, postToIndex); + return root; + } +}; diff --git a/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.java b/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.java new file mode 100644 index 00000000000..cfb9c5de815 --- /dev/null +++ b/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.java @@ -0,0 +1,30 @@ +class Solution { + public TreeNode constructFromPrePost(int[] pre, int[] post) { + Map postToIndex = new HashMap<>(); + + for (int i = 0; i < post.length; ++i) + postToIndex.put(post[i], i); + + return build(pre, 0, pre.length - 1, post, 0, post.length - 1, postToIndex); + } + + private TreeNode build(int[] pre, int preStart, int preEnd, int[] post, int postStart, + int postEnd, Map postToIndex) { + if (preStart > preEnd) + return null; + if (preStart == preEnd) + return new TreeNode(pre[preStart]); + + final int rootVal = pre[preStart]; + final int leftRootVal = pre[preStart + 1]; + final int leftRootPostIndex = postToIndex.get(leftRootVal); + final int leftSize = leftRootPostIndex - postStart + 1; + + TreeNode root = new TreeNode(rootVal); + root.left = build(pre, preStart + 1, preStart + leftSize, post, postStart, leftRootPostIndex, + postToIndex); + root.right = build(pre, preStart + leftSize + 1, preEnd, post, leftRootPostIndex + 1, + postEnd - 1, postToIndex); + return root; + } +} diff --git a/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.py b/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.py new file mode 100644 index 00000000000..338483ef3e2 --- /dev/null +++ b/solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.py @@ -0,0 +1,23 @@ +class Solution: + def constructFromPrePost(self, pre: List[int], post: List[int]) -> Optional[TreeNode]: + postToIndex = {num: i for i, num in enumerate(post)} + + def build(preStart: int, preEnd: int, postStart: int, postEnd: int) -> Optional[TreeNode]: + if preStart > preEnd: + return None + if preStart == preEnd: + return TreeNode(pre[preStart]) + + rootVal = pre[preStart] + leftRootVal = pre[preStart + 1] + leftRootPostIndex = postToIndex[leftRootVal] + leftSize = leftRootPostIndex - postStart + 1 + + root = TreeNode(rootVal) + root.left = build(preStart + 1, preStart + leftSize, + postStart, leftRootPostIndex) + root.right = build(preStart + leftSize + 1, preEnd, + leftRootPostIndex + 1, postEnd - 1) + return root + + return build(0, len(pre) - 1, 0, len(post) - 1) diff --git a/solutions/89. Gray Code/89.cpp b/solutions/89. Gray Code/89.cpp new file mode 100644 index 00000000000..25d7b834230 --- /dev/null +++ b/solutions/89. Gray Code/89.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + vector grayCode(int n) { + vector ans{0}; + + for (int i = 0; i < n; ++i) + for (int j = ans.size() - 1; j >= 0; --j) + ans.push_back(ans[j] | 1 << i); + + return ans; + } +}; diff --git a/solutions/89. Gray Code/89.java b/solutions/89. Gray Code/89.java new file mode 100644 index 00000000000..50b1aa0e8fa --- /dev/null +++ b/solutions/89. Gray Code/89.java @@ -0,0 +1,12 @@ +class Solution { + public List grayCode(int n) { + List ans = new ArrayList<>(); + ans.add(0); + + for (int i = 0; i < n; ++i) + for (int j = ans.size() - 1; j >= 0; --j) + ans.add(ans.get(j) | 1 << i); + + return ans; + } +} diff --git a/solutions/89. Gray Code/89.py b/solutions/89. Gray Code/89.py new file mode 100644 index 00000000000..6b388efa1f7 --- /dev/null +++ b/solutions/89. Gray Code/89.py @@ -0,0 +1,9 @@ +class Solution: + def grayCode(self, n: int) -> List[int]: + ans = [0] + + for i in range(n): + for j in reversed(range(len(ans))): + ans.append(ans[j] | 1 << i) + + return ans diff --git a/solutions/890. Find and Replace Pattern/890.cpp b/solutions/890. Find and Replace Pattern/890.cpp new file mode 100644 index 00000000000..2ad2f499b86 --- /dev/null +++ b/solutions/890. Find and Replace Pattern/890.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector findAndReplacePattern(vector& words, string pattern) { + vector ans; + + for (const string& word : words) + if (isIsomorphic(word, pattern)) + ans.push_back(word); + + return ans; + } + + private: + bool isIsomorphic(const string& w, const string& p) { + vector map_w(128); + vector map_p(128); + + for (int i = 0; i < w.length(); ++i) { + if (map_w[w[i]] != map_p[p[i]]) + return false; + map_w[w[i]] = i + 1; + map_p[p[i]] = i + 1; + } + + return true; + } +}; diff --git a/solutions/890. Find and Replace Pattern/890.java b/solutions/890. Find and Replace Pattern/890.java new file mode 100644 index 00000000000..56ea015a1b1 --- /dev/null +++ b/solutions/890. Find and Replace Pattern/890.java @@ -0,0 +1,22 @@ +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List ans = new ArrayList<>(); + + for (final String word : words) + if (isIsomorphic(word, pattern)) + ans.add(word); + + return ans; + } + + private boolean isIsomorphic(final String w, final String p) { + Map map_w = new HashMap<>(); + Map map_p = new HashMap<>(); + + for (Integer i = 0; i < w.length(); ++i) + if (map_w.put(w.charAt(i), i) != map_p.put(p.charAt(i), i)) + return false; + + return true; + } +} diff --git a/solutions/890. Find and Replace Pattern/890.py b/solutions/890. Find and Replace Pattern/890.py new file mode 100644 index 00000000000..fce9f4e9ccf --- /dev/null +++ b/solutions/890. Find and Replace Pattern/890.py @@ -0,0 +1,5 @@ +class Solution: + def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: + def isIsomorphic(w: str, p: str) -> bool: + return [*map(w.index, w)] == [*map(p.index, p)] + return [word for word in words if isIsomorphic(word, pattern)] diff --git a/solutions/891. Sum of Subsequence Widths/891.cpp b/solutions/891. Sum of Subsequence Widths/891.cpp new file mode 100644 index 00000000000..3d05ca96718 --- /dev/null +++ b/solutions/891. Sum of Subsequence Widths/891.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int sumSubseqWidths(vector& nums) { + constexpr int kMod = 1'000'000'007; + const int n = nums.size(); + long ans = 0; + long exp = 1; + + ranges::sort(nums); + + for (int i = 0; i < n; ++i, exp = exp * 2 % kMod) { + ans += (nums[i] - nums[n - 1 - i]) * exp; + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/891. Sum of Subsequence Widths/891.java b/solutions/891. Sum of Subsequence Widths/891.java new file mode 100644 index 00000000000..3bea6b73947 --- /dev/null +++ b/solutions/891. Sum of Subsequence Widths/891.java @@ -0,0 +1,17 @@ +class Solution { + public int sumSubseqWidths(int[] nums) { + final int kMod = 1_000_000_007; + final int n = nums.length; + long ans = 0; + long exp = 1; + + Arrays.sort(nums); + + for (int i = 0; i < n; ++i, exp = exp * 2 % kMod) { + ans += (nums[i] - nums[n - 1 - i]) * exp; + ans %= kMod; + } + + return (int) ans; + } +} diff --git a/solutions/891. Sum of Subsequence Widths/891.py b/solutions/891. Sum of Subsequence Widths/891.py new file mode 100644 index 00000000000..114fc07f90e --- /dev/null +++ b/solutions/891. Sum of Subsequence Widths/891.py @@ -0,0 +1,15 @@ +class Solution: + def sumSubseqWidths(self, nums: List[int]) -> int: + kMod = 1_000_000_007 + n = len(nums) + ans = 0 + exp = 1 + + nums.sort() + + for i in range(n): + ans += (nums[i] - nums[n - 1 - i]) * exp + ans %= kMod + exp = exp * 2 % kMod + + return ans diff --git a/solutions/892. Surface Area of 3D Shapes/892.cpp b/solutions/892. Surface Area of 3D Shapes/892.cpp new file mode 100644 index 00000000000..03ad988a3fd --- /dev/null +++ b/solutions/892. Surface Area of 3D Shapes/892.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int surfaceArea(vector>& grid) { + int ans = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid.size(); ++j) { + if (grid[i][j]) + ans += grid[i][j] * 4 + 2; + if (i > 0) + ans -= min(grid[i][j], grid[i - 1][j]) * 2; + if (j > 0) + ans -= min(grid[i][j], grid[i][j - 1]) * 2; + } + + return ans; + } +}; diff --git a/solutions/892. Surface Area of 3D Shapes/892.java b/solutions/892. Surface Area of 3D Shapes/892.java new file mode 100644 index 00000000000..6f4ba9fea4e --- /dev/null +++ b/solutions/892. Surface Area of 3D Shapes/892.java @@ -0,0 +1,17 @@ +class Solution { + public int surfaceArea(int[][] grid) { + int ans = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid.length; ++j) { + if (grid[i][j] > 0) + ans += grid[i][j] * 4 + 2; + if (i > 0) + ans -= Math.min(grid[i][j], grid[i - 1][j]) * 2; + if (j > 0) + ans -= Math.min(grid[i][j], grid[i][j - 1]) * 2; + } + + return ans; + } +} diff --git a/solutions/892. Surface Area of 3D Shapes/892.py b/solutions/892. Surface Area of 3D Shapes/892.py new file mode 100644 index 00000000000..4a8f59aa811 --- /dev/null +++ b/solutions/892. Surface Area of 3D Shapes/892.py @@ -0,0 +1,14 @@ +class Solution: + def surfaceArea(self, grid: List[List[int]]) -> int: + ans = 0 + + for i in range(len(grid)): + for j in range(len(grid)): + if grid[i][j]: + ans += grid[i][j] * 4 + 2 + if i > 0: + ans -= min(grid[i][j], grid[i - 1][j]) * 2 + if j > 0: + ans -= min(grid[i][j], grid[i][j - 1]) * 2 + + return ans diff --git a/solutions/893. Groups of Special-Equivalent Strings/893.cpp b/solutions/893. Groups of Special-Equivalent Strings/893.cpp new file mode 100644 index 00000000000..5309ec10b52 --- /dev/null +++ b/solutions/893. Groups of Special-Equivalent Strings/893.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int numSpecialEquivGroups(vector& words) { + unordered_set set; + + for (const string& word : words) { + string even; + string odd; + for (int i = 0; i < word.length(); ++i) + if (i % 2 == 0) + even += word[i]; + else + odd += word[i]; + ranges::sort(even); + ranges::sort(odd); + set.insert(even + odd); + } + + return set.size(); + } +}; diff --git a/solutions/893. Groups of Special-Equivalent Strings/893.java b/solutions/893. Groups of Special-Equivalent Strings/893.java new file mode 100644 index 00000000000..3bceffd3140 --- /dev/null +++ b/solutions/893. Groups of Special-Equivalent Strings/893.java @@ -0,0 +1,22 @@ +class Solution { + public int numSpecialEquivGroups(String[] words) { + Set set = new HashSet<>(); + + for (final String word : words) { + String even = ""; + String odd = ""; + for (int i = 0; i < word.length(); ++i) + if (i % 2 == 0) + even += word.charAt(i); + else + odd += word.charAt(i); + char[] evenCharArray = even.toCharArray(); + char[] oddCharArray = odd.toCharArray(); + Arrays.sort(evenCharArray); + Arrays.sort(oddCharArray); + set.add(new String(evenCharArray) + new String(oddCharArray)); + } + + return set.size(); + } +} diff --git a/solutions/893. Groups of Special-Equivalent Strings/893.py b/solutions/893. Groups of Special-Equivalent Strings/893.py new file mode 100644 index 00000000000..71a4d7f819d --- /dev/null +++ b/solutions/893. Groups of Special-Equivalent Strings/893.py @@ -0,0 +1,4 @@ +class Solution: + def numSpecialEquivGroups(self, words: List[str]) -> int: + return len({''.join(sorted(word[::2])) + ''.join(sorted(word[1::2])) + for word in words}) diff --git a/solutions/894. All Possible Full Binary Trees/894.cpp b/solutions/894. All Possible Full Binary Trees/894.cpp new file mode 100644 index 00000000000..8b827ee92ee --- /dev/null +++ b/solutions/894. All Possible Full Binary Trees/894.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector allPossibleFBT(int n) { + if (n % 2 == 0) + return {}; + if (n == 1) + return {new TreeNode(0)}; + if (const auto it = mem.find(n); it != mem.cend()) + return it->second; + + vector ans; + + for (int leftCount = 0; leftCount < n; ++leftCount) { + const int rightCount = n - 1 - leftCount; + for (TreeNode* left : allPossibleFBT(leftCount)) + for (TreeNode* right : allPossibleFBT(rightCount)) { + ans.push_back(new TreeNode(0)); + ans.back()->left = left; + ans.back()->right = right; + } + } + + return mem[n] = ans; + } + + private: + unordered_map> mem; +}; diff --git a/solutions/894. All Possible Full Binary Trees/894.java b/solutions/894. All Possible Full Binary Trees/894.java new file mode 100644 index 00000000000..67de6f68a9f --- /dev/null +++ b/solutions/894. All Possible Full Binary Trees/894.java @@ -0,0 +1,27 @@ +class Solution { + public List allPossibleFBT(int n) { + if (n % 2 == 0) + return new ArrayList<>(); + if (n == 1) + return Arrays.asList(new TreeNode(0)); + if (mem.containsKey(n)) + return mem.get(n); + + List ans = new ArrayList<>(); + + for (int leftCount = 0; leftCount < n; ++leftCount) { + final int rightCount = n - 1 - leftCount; + for (TreeNode left : allPossibleFBT(leftCount)) + for (TreeNode right : allPossibleFBT(rightCount)) { + ans.add(new TreeNode(0)); + ans.get(ans.size() - 1).left = left; + ans.get(ans.size() - 1).right = right; + } + } + + mem.put(n, ans); + return ans; + } + + private Map> mem = new HashMap<>(); +} diff --git a/solutions/894. All Possible Full Binary Trees/894.py b/solutions/894. All Possible Full Binary Trees/894.py new file mode 100644 index 00000000000..d3053ca742a --- /dev/null +++ b/solutions/894. All Possible Full Binary Trees/894.py @@ -0,0 +1,19 @@ +class Solution: + @functools.lru_cache(None) + def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]: + if n % 2 == 0: + return [] + if n == 1: + return [TreeNode(0)] + + ans = [] + + for leftCount in range(n): + rightCount = n - 1 - leftCount + for left in self.allPossibleFBT(leftCount): + for right in self.allPossibleFBT(rightCount): + ans.append(TreeNode(0)) + ans[-1].left = left + ans[-1].right = right + + return ans diff --git a/solutions/895. Maximum Frequency Stack/895.cpp b/solutions/895. Maximum Frequency Stack/895.cpp new file mode 100644 index 00000000000..d89795e3a93 --- /dev/null +++ b/solutions/895. Maximum Frequency Stack/895.cpp @@ -0,0 +1,21 @@ +class FreqStack { + public: + void push(int val) { + countToStack[++count[val]].push(val); + maxFreq = max(maxFreq, count[val]); + } + + int pop() { + const int val = countToStack[maxFreq].top(); + countToStack[maxFreq].pop(); + --count[val]; + if (countToStack[maxFreq].empty()) + --maxFreq; + return val; + } + + private: + int maxFreq = 0; + unordered_map count; + unordered_map> countToStack; +}; diff --git a/solutions/895. Maximum Frequency Stack/895.java b/solutions/895. Maximum Frequency Stack/895.java new file mode 100644 index 00000000000..ee48b3fba40 --- /dev/null +++ b/solutions/895. Maximum Frequency Stack/895.java @@ -0,0 +1,20 @@ +class FreqStack { + public void push(int val) { + count.merge(val, 1, Integer::sum); + countToStack.putIfAbsent(count.get(val), new ArrayDeque<>()); + countToStack.get(count.get(val)).push(val); + maxFreq = Math.max(maxFreq, count.get(val)); + } + + public int pop() { + final int val = countToStack.get(maxFreq).pop(); + count.merge(val, -1, Integer::sum); + if (countToStack.get(maxFreq).isEmpty()) + --maxFreq; + return val; + } + + private int maxFreq = 0; + private Map count = new HashMap<>(); + private Map> countToStack = new HashMap<>(); +} diff --git a/solutions/895. Maximum Frequency Stack/895.py b/solutions/895. Maximum Frequency Stack/895.py new file mode 100644 index 00000000000..03fd30dbd24 --- /dev/null +++ b/solutions/895. Maximum Frequency Stack/895.py @@ -0,0 +1,17 @@ +class FreqStack: + def __init__(self): + self.maxFreq = 0 + self.count = collections.Counter() + self.countToStack = collections.defaultdict(list) + + def push(self, val: int) -> None: + self.count[val] += 1 + self.countToStack[self.count[val]].append(val) + self.maxFreq = max(self.maxFreq, self.count[val]) + + def pop(self) -> int: + val = self.countToStack[self.maxFreq].pop() + self.count[val] -= 1 + if not self.countToStack[self.maxFreq]: + self.maxFreq -= 1 + return val diff --git a/solutions/896. Monotonic Array/896.cpp b/solutions/896. Monotonic Array/896.cpp new file mode 100644 index 00000000000..e5d51b308de --- /dev/null +++ b/solutions/896. Monotonic Array/896.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + bool isMonotonic(vector& nums) { + bool increasing = true; + bool decreasing = true; + + for (int i = 1; i < nums.size(); ++i) { + increasing &= nums[i] >= nums[i - 1]; + decreasing &= nums[i] <= nums[i - 1]; + } + + return increasing || decreasing; + } +}; diff --git a/solutions/896. Monotonic Array/896.java b/solutions/896. Monotonic Array/896.java new file mode 100644 index 00000000000..7b363bfadbb --- /dev/null +++ b/solutions/896. Monotonic Array/896.java @@ -0,0 +1,13 @@ +class Solution { + public boolean isMonotonic(int[] nums) { + boolean increasing = true; + boolean decreasing = true; + + for (int i = 1; i < nums.length; ++i) { + increasing &= nums[i] >= nums[i - 1]; + decreasing &= nums[i] <= nums[i - 1]; + } + + return increasing || decreasing; + } +} diff --git a/solutions/896. Monotonic Array/896.py b/solutions/896. Monotonic Array/896.py new file mode 100644 index 00000000000..c56fb70c5c0 --- /dev/null +++ b/solutions/896. Monotonic Array/896.py @@ -0,0 +1,10 @@ +class Solution: + def isMonotonic(self, nums: List[int]) -> bool: + increasing = True + decreasing = True + + for i in range(1, len(nums)): + increasing &= nums[i - 1] <= nums[i] + decreasing &= nums[i - 1] >= nums[i] + + return increasing or decreasing diff --git a/solutions/897. Increasing Order Search Tree/897.cpp b/solutions/897. Increasing Order Search Tree/897.cpp new file mode 100644 index 00000000000..358293cbd2f --- /dev/null +++ b/solutions/897. Increasing Order Search Tree/897.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + TreeNode* increasingBST(TreeNode* root, TreeNode* tail = nullptr) { + if (root == nullptr) + return tail; + + TreeNode* ans = increasingBST(root->left, root); + root->left = nullptr; + root->right = increasingBST(root->right, tail); + return ans; + } +}; diff --git a/solutions/897. Increasing Order Search Tree/897.java b/solutions/897. Increasing Order Search Tree/897.java new file mode 100644 index 00000000000..401a6fb108a --- /dev/null +++ b/solutions/897. Increasing Order Search Tree/897.java @@ -0,0 +1,15 @@ +class Solution { + public TreeNode increasingBST(TreeNode root) { + return increasingBST(root, null); + } + + private TreeNode increasingBST(TreeNode root, TreeNode tail) { + if (root == null) + return tail; + + TreeNode ans = increasingBST(root.left, root); + root.left = null; + root.right = increasingBST(root.right, tail); + return ans; + } +} diff --git a/solutions/897. Increasing Order Search Tree/897.py b/solutions/897. Increasing Order Search Tree/897.py new file mode 100644 index 00000000000..1ccfc449461 --- /dev/null +++ b/solutions/897. Increasing Order Search Tree/897.py @@ -0,0 +1,9 @@ +class Solution: + def increasingBST(self, root: TreeNode, tail: TreeNode = None) -> TreeNode: + if not root: + return tail + + res = self.increasingBST(root.left, root) + root.left = None + root.right = self.increasingBST(root.right, tail) + return res diff --git a/solutions/898. Bitwise ORs of Subarrays/898.cpp b/solutions/898. Bitwise ORs of Subarrays/898.cpp new file mode 100644 index 00000000000..2aef4fbf975 --- /dev/null +++ b/solutions/898. Bitwise ORs of Subarrays/898.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int subarrayBitwiseORs(vector& arr) { + vector s; + int l = 0; + + for (const int a : arr) { + const int r = s.size(); + s.push_back(a); + // s[l..r) are values generated in the previous iteration + for (int i = l; i < r; ++i) + if (s.back() != (s[i] | a)) + s.push_back(s[i] | a); + l = r; + } + + return unordered_set(s.begin(), s.end()).size(); + } +}; diff --git a/solutions/898. Bitwise ORs of Subarrays/898.java b/solutions/898. Bitwise ORs of Subarrays/898.java new file mode 100644 index 00000000000..4b45709b0f3 --- /dev/null +++ b/solutions/898. Bitwise ORs of Subarrays/898.java @@ -0,0 +1,18 @@ +class Solution { + public int subarrayBitwiseORs(int[] arr) { + List s = new ArrayList<>(); + int l = 0; + + for (final int a : arr) { + final int r = s.size(); + s.add(a); + // s[l..r) are values generated in the previous iteration + for (int i = l; i < r; ++i) + if (s.get(s.size() - 1) != (s.get(i) | a)) + s.add(s.get(i) | a); + l = r; + } + + return new HashSet<>(s).size(); + } +} diff --git a/solutions/899. Orderly Queue/899.cpp b/solutions/899. Orderly Queue/899.cpp new file mode 100644 index 00000000000..1cd326066c9 --- /dev/null +++ b/solutions/899. Orderly Queue/899.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + string orderlyQueue(string s, int k) { + if (k > 1) { + ranges::sort(s); + return s; + } + + string ans = s; + + for (int i = 1; i < s.length(); ++i) + ans = min(ans, s.substr(i) + s.substr(0, i)); + + return ans; + } +}; diff --git a/solutions/899. Orderly Queue/899.java b/solutions/899. Orderly Queue/899.java new file mode 100644 index 00000000000..e404a2364b5 --- /dev/null +++ b/solutions/899. Orderly Queue/899.java @@ -0,0 +1,19 @@ +class Solution { + public String orderlyQueue(String s, int k) { + if (k > 1) { + char[] chars = s.toCharArray(); + Arrays.sort(chars); + return String.valueOf(chars); + } + + String ans = s; + + for (int i = 1; i < s.length(); ++i) { + String t = s.substring(i) + s.substring(0, i); + if (ans.compareTo(t) > 0) + ans = t; + } + + return ans; + } +} diff --git a/solutions/899. Orderly Queue/899.py b/solutions/899. Orderly Queue/899.py new file mode 100644 index 00000000000..48e877f24ee --- /dev/null +++ b/solutions/899. Orderly Queue/899.py @@ -0,0 +1,4 @@ +class Solution: + def orderlyQueue(self, s: str, k: int) -> str: + return ''.join(sorted(s)) if k > 1 \ + else min(s[i:] + s[:i] for i in range(len(s))) diff --git a/solutions/9. Palindrome Number/9.cpp b/solutions/9. Palindrome Number/9.cpp new file mode 100644 index 00000000000..d5a1e988527 --- /dev/null +++ b/solutions/9. Palindrome Number/9.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool isPalindrome(int x) { + if (x < 0) + return false; + + long reversed = 0; + int y = x; + + while (y > 0) { + reversed = reversed * 10 + y % 10; + y /= 10; + } + + return reversed == x; + } +}; diff --git a/solutions/9. Palindrome Number/9.java b/solutions/9. Palindrome Number/9.java new file mode 100644 index 00000000000..2966c2781be --- /dev/null +++ b/solutions/9. Palindrome Number/9.java @@ -0,0 +1,16 @@ +class Solution { + public boolean isPalindrome(int x) { + if (x < 0) + return false; + + long reversed = 0; + int y = x; + + while (y > 0) { + reversed = reversed * 10 + y % 10; + y /= 10; + } + + return reversed == x; + } +} diff --git a/solutions/9. Palindrome Number/9.py b/solutions/9. Palindrome Number/9.py new file mode 100644 index 00000000000..8bdf799e4c0 --- /dev/null +++ b/solutions/9. Palindrome Number/9.py @@ -0,0 +1,13 @@ +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + + rev = 0 + y = x + + while y: + rev = rev * 10 + y % 10 + y //= 10 + + return rev == x diff --git a/solutions/90. Subsets II/90.cpp b/solutions/90. Subsets II/90.cpp new file mode 100644 index 00000000000..912d7c40be8 --- /dev/null +++ b/solutions/90. Subsets II/90.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector> subsetsWithDup(vector& nums) { + vector> ans; + ranges::sort(nums); + dfs(nums, 0, {}, ans); + return ans; + } + + private: + void dfs(const vector& nums, int s, vector&& path, + vector>& ans) { + ans.push_back(path); + + for (int i = s; i < nums.size(); ++i) { + if (i > s && nums[i] == nums[i - 1]) + continue; + path.push_back(nums[i]); + dfs(nums, i + 1, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/90. Subsets II/90.java b/solutions/90. Subsets II/90.java new file mode 100644 index 00000000000..f7d1615a38d --- /dev/null +++ b/solutions/90. Subsets II/90.java @@ -0,0 +1,20 @@ +class Solution { + public List> subsetsWithDup(int[] nums) { + List> ans = new ArrayList<>(); + Arrays.sort(nums); + dfs(nums, 0, new ArrayList<>(), ans); + return ans; + } + + private void dfs(int[] nums, int s, List path, List> ans) { + ans.add(new ArrayList<>(path)); + + for (int i = s; i < nums.length; ++i) { + if (i > s && nums[i] == nums[i - 1]) + continue; + path.add(nums[i]); + dfs(nums, i + 1, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/90. Subsets II/90.py b/solutions/90. Subsets II/90.py new file mode 100644 index 00000000000..0c86e6757a2 --- /dev/null +++ b/solutions/90. Subsets II/90.py @@ -0,0 +1,17 @@ +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + ans = [] + + def dfs(s: int, path: List[int]) -> None: + ans.append(path) + if s == len(nums): + return + + for i in range(s, len(nums)): + if i > s and nums[i] == nums[i - 1]: + continue + dfs(i + 1, path + [nums[i]]) + + nums.sort() + dfs(0, []) + return ans diff --git a/solutions/900. RLE Iterator/900.cpp b/solutions/900. RLE Iterator/900.cpp new file mode 100644 index 00000000000..74cd67c2742 --- /dev/null +++ b/solutions/900. RLE Iterator/900.cpp @@ -0,0 +1,21 @@ +class RLEIterator { + public: + RLEIterator(vector& encoding) : encoding(encoding) {} + + int next(int n) { + while (index < encoding.size() && encoding[index] < n) { + n -= encoding[index]; + index += 2; + } + + if (index == encoding.size()) + return -1; + + encoding[index] -= n; + return encoding[index + 1]; + } + + private: + int index = 0; + vector encoding; +}; diff --git a/solutions/900. RLE Iterator/900.java b/solutions/900. RLE Iterator/900.java new file mode 100644 index 00000000000..aa6bddcd3f5 --- /dev/null +++ b/solutions/900. RLE Iterator/900.java @@ -0,0 +1,21 @@ +class RLEIterator { + public RLEIterator(int[] encoding) { + this.encoding = encoding; + } + + public int next(int n) { + while (index < encoding.length && encoding[index] < n) { + n -= encoding[index]; + index += 2; + } + + if (index == encoding.length) + return -1; + + encoding[index] -= n; + return encoding[index + 1]; + } + + private int index = 0; + private int[] encoding; +} diff --git a/solutions/900. RLE Iterator/900.py b/solutions/900. RLE Iterator/900.py new file mode 100644 index 00000000000..d82dde2e323 --- /dev/null +++ b/solutions/900. RLE Iterator/900.py @@ -0,0 +1,15 @@ +class RLEIterator: + def __init__(self, encoding: List[int]): + self.encoding = encoding + self.index = 0 + + def next(self, n: int) -> int: + while self.index < len(self.encoding) and self.encoding[self.index] < n: + n -= self.encoding[self.index] + self.index += 2 + + if self.index == len(self.encoding): + return -1 + + self.encoding[self.index] -= n + return self.encoding[self.index + 1] diff --git a/solutions/901. Online Stock Span/901.cpp b/solutions/901. Online Stock Span/901.cpp new file mode 100644 index 00000000000..8d67e382a72 --- /dev/null +++ b/solutions/901. Online Stock Span/901.cpp @@ -0,0 +1,13 @@ +class StockSpanner { + public: + int next(int price) { + int span = 1; + while (!stack.empty() && stack.top().first <= price) + span += stack.top().second, stack.pop(); + stack.emplace(price, span); + return span; + } + + private: + stack> stack; // (price, span) +}; diff --git a/solutions/901. Online Stock Span/901.java b/solutions/901. Online Stock Span/901.java new file mode 100644 index 00000000000..0fbb5ba0561 --- /dev/null +++ b/solutions/901. Online Stock Span/901.java @@ -0,0 +1,12 @@ +class StockSpanner { + public int next(int price) { + int span = 1; + while (!stack.isEmpty() && stack.peek().getKey() <= price) + span += stack.pop().getValue(); + stack.push(new Pair<>(price, span)); + return span; + } + + // (price, span) + private Stack> stack = new Stack<>(); +} diff --git a/solutions/901. Online Stock Span/901.py b/solutions/901. Online Stock Span/901.py new file mode 100644 index 00000000000..bf042064d6f --- /dev/null +++ b/solutions/901. Online Stock Span/901.py @@ -0,0 +1,10 @@ +class StockSpanner: + def __init__(self): + self.stack = [] # (price, span) + + def next(self, price: int) -> int: + span = 1 + while self.stack and self.stack[-1][0] <= price: + span += self.stack.pop()[1] + self.stack.append((price, span)) + return span diff --git a/solutions/902. Numbers At Most N Given Digit Set/902.cpp b/solutions/902. Numbers At Most N Given Digit Set/902.cpp new file mode 100644 index 00000000000..289c665cf47 --- /dev/null +++ b/solutions/902. Numbers At Most N Given Digit Set/902.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int atMostNGivenDigitSet(vector& digits, int n) { + int ans = 0; + const string num = to_string(n); + + for (int i = 1; i < num.length(); ++i) + ans += pow(digits.size(), i); + + for (int i = 0; i < num.length(); ++i) { + bool dHasSameNum = false; + for (const string& digit : digits) { + if (digit[0] < num[i]) + ans += pow(digits.size(), num.length() - i - 1); + else if (digit[0] == num[i]) + dHasSameNum = true; + } + if (!dHasSameNum) + return ans; + } + + return ans + 1; + } +}; diff --git a/solutions/902. Numbers At Most N Given Digit Set/902.java b/solutions/902. Numbers At Most N Given Digit Set/902.java new file mode 100644 index 00000000000..14b59555cb6 --- /dev/null +++ b/solutions/902. Numbers At Most N Given Digit Set/902.java @@ -0,0 +1,23 @@ +class Solution { + public int atMostNGivenDigitSet(String[] digits, int n) { + int ans = 0; + final String num = String.valueOf(n); + + for (int i = 1; i < num.length(); ++i) + ans += (int) Math.pow(digits.length, i); + + for (int i = 0; i < num.length(); ++i) { + boolean dHasSameNum = false; + for (final String digit : digits) { + if (digit.charAt(0) < num.charAt(i)) + ans += (int) Math.pow(digits.length, num.length() - i - 1); + else if (digit.charAt(0) == num.charAt(i)) + dHasSameNum = true; + } + if (!dHasSameNum) + return ans; + } + + return ans + 1; + } +} diff --git a/solutions/902. Numbers At Most N Given Digit Set/902.py b/solutions/902. Numbers At Most N Given Digit Set/902.py new file mode 100644 index 00000000000..780fcd85541 --- /dev/null +++ b/solutions/902. Numbers At Most N Given Digit Set/902.py @@ -0,0 +1,19 @@ +class Solution: + def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: + ans = 0 + num = str(n) + + for i in range(1, len(num)): + ans += pow(len(digits), i) + + for i, c in enumerate(num): + dHasSameNum = False + for digit in digits: + if digit[0] < c: + ans += pow(len(digits), len(num) - i - 1) + elif digit[0] == c: + dHasSameNum = True + if not dHasSameNum: + return ans + + return ans + 1 diff --git a/solutions/903. Valid Permutations for DI Sequence/903-2.cpp b/solutions/903. Valid Permutations for DI Sequence/903-2.cpp new file mode 100644 index 00000000000..0d1dca02bc3 --- /dev/null +++ b/solutions/903. Valid Permutations for DI Sequence/903-2.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + int numPermsDISequence(string s) { + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + vector dp(n + 1); + + // When there's only one digit, the number of permutations is 1. + for (int j = 0; j <= n; ++j) + dp[j] = 1; + + for (int i = 1; i <= n; ++i) { + vector newDp(n + 1); + if (s[i - 1] == 'I') { // s[i - 1] == 'I' + // Calculate the postfix sum to prevent duplicate calculation. + int postfixsum = 0; + for (int j = n - i; j >= 0; --j) { + postfixsum = (postfixsum + dp[j + 1]) % kMod; + newDp[j] = postfixsum; + } + } else { // s[i - 1] == 'D' + // Calculate the prefix sum to prevent duplicate calculation. + int prefix = 0; + for (int j = 0; j <= n - i; ++j) { + prefix = (prefix + dp[j]) % kMod; + newDp[j] = prefix; + } + } + dp = move(newDp); + } + + return dp[0]; + } +}; diff --git a/solutions/903. Valid Permutations for DI Sequence/903-2.java b/solutions/903. Valid Permutations for DI Sequence/903-2.java new file mode 100644 index 00000000000..45b47e04a95 --- /dev/null +++ b/solutions/903. Valid Permutations for DI Sequence/903-2.java @@ -0,0 +1,33 @@ +class Solution { + public int numPermsDISequence(String s) { + final int kMod = 1_000_000_007; + final int n = s.length(); + int[] dp = new int[n + 1]; + + // When there's only one digit, the number of permutations is 1. + for (int j = 0; j <= n; ++j) + dp[j] = 1; + + for (int i = 1; i <= n; ++i) { + int[] newDp = new int[n + 1]; + if (s.charAt(i - 1) == 'I') { // s[i - 1] == 'I' + // Calculate the postfix sum to prevent duplicate calculation. + int postfixsum = 0; + for (int j = n - i; j >= 0; --j) { + postfixsum = (postfixsum + dp[j + 1]) % kMod; + newDp[j] = postfixsum; + } + } else { // s[i - 1] == 'D' + // Calculate the prefix sum to prevent duplicate calculation. + int prefix = 0; + for (int j = 0; j <= n - i; ++j) { + prefix = (prefix + dp[j]) % kMod; + newDp[j] = prefix; + } + } + dp = newDp; + } + + return dp[0]; + } +} diff --git a/solutions/903. Valid Permutations for DI Sequence/903.cpp b/solutions/903. Valid Permutations for DI Sequence/903.cpp new file mode 100644 index 00000000000..a27f6919f97 --- /dev/null +++ b/solutions/903. Valid Permutations for DI Sequence/903.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int numPermsDISequence(string s) { + constexpr int kMod = 1'000'000'007; + const int n = s.length(); + // dp[i][j] := the number of valid permutations with i + 1 digits, where + // s[i] is j-th Digit of remaining digits + vector> dp(n + 1, vector(n + 1)); + + // When there's only one digit, the number of permutations is 1. + for (int j = 0; j <= n; ++j) + dp[0][j] = 1; + + for (int i = 1; i <= n; ++i) + if (s[i - 1] == 'I') { // s[i - 1] == 'I' + // Calculate the postfix sum to prevent duplicate calculation. + int postfixsum = 0; + for (int j = n - i; j >= 0; --j) { + postfixsum = (postfixsum + dp[i - 1][j + 1]) % kMod; + dp[i][j] = postfixsum; + } + } else { // s[i - 1] == 'D' + // Calculate the prefix sum to prevent duplicate calculation. + int prefix = 0; + for (int j = 0; j <= n - i; ++j) { + prefix = (prefix + dp[i - 1][j]) % kMod; + dp[i][j] = prefix; + } + } + + return dp[n][0]; + } +}; diff --git a/solutions/903. Valid Permutations for DI Sequence/903.java b/solutions/903. Valid Permutations for DI Sequence/903.java new file mode 100644 index 00000000000..67a25a28f01 --- /dev/null +++ b/solutions/903. Valid Permutations for DI Sequence/903.java @@ -0,0 +1,32 @@ +class Solution { + public int numPermsDISequence(String s) { + final int kMod = 1_000_000_007; + final int n = s.length(); + // dp[i][j] := the number of valid permutations with i + 1 digits, where s[i] is j-th + // Digit of remaining digits + int[][] dp = new int[n + 1][n + 1]; + + // When there's only one digit, the number of permutations is 1. + for (int j = 0; j <= n; ++j) + dp[0][j] = 1; + + for (int i = 1; i <= n; ++i) + if (s.charAt(i - 1) == 'I') { // s[i - 1] == 'I' + // Calculate the postfix sum to prevent duplicate calculation. + int postfixsum = 0; + for (int j = n - i; j >= 0; --j) { + postfixsum = (postfixsum + dp[i - 1][j + 1]) % kMod; + dp[i][j] = postfixsum; + } + } else { // s[i - 1] == 'D' + // Calculate the prefix sum to prevent duplicate calculation. + int prefix = 0; + for (int j = 0; j <= n - i; ++j) { + prefix = (prefix + dp[i - 1][j]) % kMod; + dp[i][j] = prefix; + } + } + + return dp[n][0]; + } +} diff --git a/solutions/904. Fruit Into Baskets/904.cpp b/solutions/904. Fruit Into Baskets/904.cpp new file mode 100644 index 00000000000..afba04405ec --- /dev/null +++ b/solutions/904. Fruit Into Baskets/904.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int totalFruit(vector& fruits) { + int ans = 0; + unordered_map count; + + for (int l = 0, r = 0; r < fruits.size(); ++r) { + ++count[fruits[r]]; + while (count.size() > 2) { + if (--count[fruits[l]] == 0) + count.erase(fruits[l]); + ++l; + } + ans = max(ans, r - l + 1); + } + + return ans; + } +}; diff --git a/solutions/904. Fruit Into Baskets/904.java b/solutions/904. Fruit Into Baskets/904.java new file mode 100644 index 00000000000..6266c4ae5bf --- /dev/null +++ b/solutions/904. Fruit Into Baskets/904.java @@ -0,0 +1,18 @@ +class Solution { + public int totalFruit(int[] fruits) { + int ans = 0; + Map count = new HashMap<>(); + + for (int l = 0, r = 0; r < fruits.length; ++r) { + count.merge(fruits[r], 1, Integer::sum); + while (count.size() > 2) { + count.merge(fruits[l], -1, Integer::sum); + count.remove(fruits[l], 0); + ++l; + } + ans = Math.max(ans, r - l + 1); + } + + return ans; + } +} diff --git a/solutions/904. Fruit Into Baskets/904.py b/solutions/904. Fruit Into Baskets/904.py new file mode 100644 index 00000000000..58827459080 --- /dev/null +++ b/solutions/904. Fruit Into Baskets/904.py @@ -0,0 +1,16 @@ +class Solution: + def totalFruit(self, fruits: List[int]) -> int: + ans = 0 + count = collections.defaultdict(int) + + l = 0 + for r, fruit in enumerate(fruits): + count[fruit] += 1 + while len(count) > 2: + count[fruits[l]] -= 1 + if count[fruits[l]] == 0: + del count[fruits[l]] + l += 1 + ans = max(ans, r - l + 1) + + return ans diff --git a/solutions/905. Sort Array By Parity/905.cpp b/solutions/905. Sort Array By Parity/905.cpp new file mode 100644 index 00000000000..372e696124a --- /dev/null +++ b/solutions/905. Sort Array By Parity/905.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector sortArrayByParity(vector& nums) { + int l = 0; + int r = nums.size() - 1; + + while (l < r) { + if (nums[l] % 2 == 1 && nums[r] % 2 == 0) + swap(nums[l], nums[r]); + if (nums[l] % 2 == 0) + ++l; + if (nums[r] % 2 == 1) + --r; + } + + return nums; + } +}; diff --git a/solutions/905. Sort Array By Parity/905.java b/solutions/905. Sort Array By Parity/905.java new file mode 100644 index 00000000000..99c558b2b35 --- /dev/null +++ b/solutions/905. Sort Array By Parity/905.java @@ -0,0 +1,20 @@ +class Solution { + public int[] sortArrayByParity(int[] nums) { + int l = 0; + int r = nums.length - 1; + + while (l < r) { + if (nums[l] % 2 == 1 && nums[r] % 2 == 0) { + int temp = nums[l]; + nums[l] = nums[r]; + nums[r] = temp; + } + if (nums[l] % 2 == 0) + ++l; + if (nums[r] % 2 == 1) + --r; + } + + return nums; + } +} diff --git a/solutions/905. Sort Array By Parity/905.py b/solutions/905. Sort Array By Parity/905.py new file mode 100644 index 00000000000..ad2dcb9b2c1 --- /dev/null +++ b/solutions/905. Sort Array By Parity/905.py @@ -0,0 +1,14 @@ +class Solution: + def sortArrayByParity(self, nums: List[int]) -> List[int]: + l = 0 + r = len(nums) - 1 + + while l < r: + if nums[l] % 2 == 1 and nums[r] % 2 == 0: + nums[l], nums[r] = nums[r], nums[l] + if nums[l] % 2 == 0: + l += 1 + if nums[r] % 2 == 1: + r -= 1 + + return nums diff --git a/solutions/906. Super Palindromes/906.cpp b/solutions/906. Super Palindromes/906.cpp new file mode 100644 index 00000000000..bb5879b4c83 --- /dev/null +++ b/solutions/906. Super Palindromes/906.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + int superpalindromesInRange(string left, string right) { + int ans = 0; + const long l = stoll(left); + const long r = stoll(right); + + for (long i = sqrt(l); i * i <= r;) { + const long palindrome = nextPalindrome(i); + const long squared = palindrome * palindrome; + if (squared <= r && isPalindrome(squared)) + ++ans; + i = palindrome + 1; + } + + return ans; + } + + private: + long nextPalindrome(int num) { + const string s = to_string(num); + const int n = s.length(); + string half = s.substr(0, (n + 1) / 2); + string reversedHalf = reversed(half.substr(0, n / 2)); + const long candidate = stoll(half + reversedHalf); + if (candidate >= num) + return candidate; + half = to_string(stoll(half) + 1); + reversedHalf = reversed(half.substr(0, n / 2)); + return stoll(half + reversedHalf); + } + + string reversed(const string& s) { + return {s.rbegin(), s.rend()}; + } + + bool isPalindrome(long num) { + const string s = to_string(num); + int l = 0; + int r = s.length() - 1; + while (l < r) + if (s[l++] != s[r--]) + return false; + return true; + } +}; diff --git a/solutions/906. Super Palindromes/906.java b/solutions/906. Super Palindromes/906.java new file mode 100644 index 00000000000..af1055522c2 --- /dev/null +++ b/solutions/906. Super Palindromes/906.java @@ -0,0 +1,44 @@ +class Solution { + public int superpalindromesInRange(String left, String right) { + int ans = 0; + Long l = Long.valueOf(left); + Long r = Long.valueOf(right); + + for (long i = (long) Math.sqrt(l); i * i <= r;) { + long palindrome = nextPalindrome(i); + long squared = palindrome * palindrome; + if (squared <= r && isPalindrome(squared)) + ++ans; + i = palindrome + 1; + } + + return ans; + } + + private long nextPalindrome(long num) { + final String s = String.valueOf(num); + final int n = s.length(); + + String half = s.substring(0, (n + 1) / 2); + String reversedHalf = new StringBuilder(half.substring(0, n / 2)).reverse().toString(); + final long candidate = Long.valueOf(half + reversedHalf); + if (candidate >= num) + return candidate; + + half = String.valueOf(Long.valueOf(half) + 1); + reversedHalf = new StringBuilder(half.substring(0, n / 2)).reverse().toString(); + return Long.valueOf(half + reversedHalf); + } + + private boolean isPalindrome(long num) { + final String s = String.valueOf(num); + int l = 0; + int r = s.length() - 1; + + while (l < r) + if (s.charAt(l++) != s.charAt(r--)) + return false; + + return true; + } +} diff --git a/solutions/906. Super Palindromes/906.py b/solutions/906. Super Palindromes/906.py new file mode 100644 index 00000000000..c4835028ff7 --- /dev/null +++ b/solutions/906. Super Palindromes/906.py @@ -0,0 +1,42 @@ +class Solution: + def superpalindromesInRange(self, left: str, right: str) -> int: + def nextPalindrome(num: int) -> int: + s = str(num) + n = len(s) + + half = s[0:(n + 1) // 2] + reversedHalf = half[:n // 2][::-1] + candidate = int(half + reversedHalf) + if candidate >= num: + return candidate + + half = str(int(half) + 1) + reversedHalf = half[:n // 2][::-1] + return int(half + reversedHalf) + + def isPalindrome(num: int) -> bool: + s = str(num) + l = 0 + r = len(s) - 1 + + while l < r: + if s[l] != s[r]: + return False + l += 1 + r -= 1 + + return True + + ans = 0 + l = int(left) + r = int(right) + i = math.isqrt(l) + + while i * i <= r: + palindrome = nextPalindrome(i) + squared = palindrome**2 + if squared <= r and isPalindrome(squared): + ans += 1 + i = palindrome + 1 + + return ans diff --git a/solutions/907. Sum of Subarray Minimums/907.cpp b/solutions/907. Sum of Subarray Minimums/907.cpp new file mode 100644 index 00000000000..15c2006908c --- /dev/null +++ b/solutions/907. Sum of Subarray Minimums/907.cpp @@ -0,0 +1,31 @@ +class Solution { + public: + int sumSubarrayMins(vector& arr) { + constexpr int kMod = 1'000'000'007; + const int n = arr.size(); + long ans = 0; + // prevMin[i] := index k s.t. arr[k] is the previous minimum in arr[:i] + vector prevMin(n, -1); + // nextMin[i] := index k s.t. arr[k] is the next minimum in arr[i + 1:] + vector nextMin(n, n); + stack stack; + + for (int i = 0; i < n; ++i) { + while (!stack.empty() && arr[stack.top()] > arr[i]) { + const int index = stack.top(); + stack.pop(); + nextMin[index] = i; + } + if (!stack.empty()) + prevMin[i] = stack.top(); + stack.push(i); + } + + for (int i = 0; i < n; ++i) { + ans += static_cast(arr[i]) * (i - prevMin[i]) * (nextMin[i] - i); + ans %= kMod; + } + + return ans; + } +}; diff --git a/solutions/907. Sum of Subarray Minimums/907.java b/solutions/907. Sum of Subarray Minimums/907.java new file mode 100644 index 00000000000..13c1d8c98b5 --- /dev/null +++ b/solutions/907. Sum of Subarray Minimums/907.java @@ -0,0 +1,32 @@ +class Solution { + public int sumSubarrayMins(int[] arr) { + final int kMod = 1_000_000_007; + final int n = arr.length; + long ans = 0; + // prevMin[i] := index k s.t. arr[k] is the previous minimum in arr[:i] + int[] prevMin = new int[n]; + // nextMin[i] := index k s.t. arr[k] is the next minimum in arr[i + 1:] + int[] nextMin = new int[n]; + Deque stack = new ArrayDeque<>(); + + Arrays.fill(prevMin, -1); + Arrays.fill(nextMin, n); + + for (int i = 0; i < arr.length; ++i) { + while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) { + final int index = stack.pop(); + nextMin[index] = i; + } + if (!stack.isEmpty()) + prevMin[i] = stack.peek(); + stack.push(i); + } + + for (int i = 0; i < arr.length; ++i) { + ans += (long) arr[i] * (i - prevMin[i]) * (nextMin[i] - i); + ans %= kMod; + } + + return (int) ans; + } +} diff --git a/solutions/907. Sum of Subarray Minimums/907.py b/solutions/907. Sum of Subarray Minimums/907.py new file mode 100644 index 00000000000..f3aad7e06f7 --- /dev/null +++ b/solutions/907. Sum of Subarray Minimums/907.py @@ -0,0 +1,24 @@ +class Solution: + def sumSubarrayMins(self, arr: List[int]) -> int: + kMod = 1_000_000_007 + n = len(arr) + ans = 0 + # prevMin[i] := index k s.t. arr[k] is the previous minimum in arr[:i] + prevMin = [-1] * n + # nextMin[i] := index k s.t. arr[k] is the next minimum in arr[i + 1:] + nextMin = [n] * n + stack = [] + + for i, a in enumerate(arr): + while stack and arr[stack[-1]] > a: + index = stack.pop() + nextMin[index] = i + if stack: + prevMin[i] = stack[-1] + stack.append(i) + + for i, a in enumerate(arr): + ans += a * (i - prevMin[i]) * (nextMin[i] - i) + ans %= kMod + + return ans diff --git a/solutions/908. Smallest Range I/908.cpp b/solutions/908. Smallest Range I/908.cpp new file mode 100644 index 00000000000..88560879c59 --- /dev/null +++ b/solutions/908. Smallest Range I/908.cpp @@ -0,0 +1,8 @@ +class Solution { + public: + int smallestRangeI(vector& nums, int k) { + const int mx = ranges::max(nums); + const int mn = ranges::min(nums); + return max(0, mx - mn - 2 * k); + } +}; diff --git a/solutions/908. Smallest Range I/908.java b/solutions/908. Smallest Range I/908.java new file mode 100644 index 00000000000..37a5d55da88 --- /dev/null +++ b/solutions/908. Smallest Range I/908.java @@ -0,0 +1,7 @@ +class Solution { + public int smallestRangeI(int[] nums, int k) { + final int mx = Arrays.stream(nums).max().getAsInt(); + final int mn = Arrays.stream(nums).min().getAsInt(); + return Math.max(0, mx - mn - 2 * k); + } +} diff --git a/solutions/908. Smallest Range I/908.py b/solutions/908. Smallest Range I/908.py new file mode 100644 index 00000000000..ec0e34a63ab --- /dev/null +++ b/solutions/908. Smallest Range I/908.py @@ -0,0 +1,3 @@ +class Solution: + def smallestRangeI(self, nums: List[int], k: int) -> int: + return max(0, max(nums) - min(nums) - 2 * k) diff --git a/solutions/909. Snakes and Ladders/909.cpp b/solutions/909. Snakes and Ladders/909.cpp new file mode 100644 index 00000000000..a1d7e6bd99d --- /dev/null +++ b/solutions/909. Snakes and Ladders/909.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int snakesAndLadders(vector>& board) { + const int n = board.size(); + int ans = 0; + queue q{{1}}; + vector seen(1 + n * n); + vector A(1 + n * n); // 2D -> 1D + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + A[(n - 1 - i) * n + ((n - i) % 2 == 0 ? n - j : j + 1)] = board[i][j]; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const int curr = q.front(); + q.pop(); + for (int next = curr + 1; next <= min(curr + 6, n * n); ++next) { + const int dest = A[next] > 0 ? A[next] : next; + if (dest == n * n) + return ans; + if (seen[dest]) + continue; + q.push(dest); + seen[dest] = true; + } + } + } + + return -1; + } +}; diff --git a/solutions/909. Snakes and Ladders/909.java b/solutions/909. Snakes and Ladders/909.java new file mode 100644 index 00000000000..3a76f537b4e --- /dev/null +++ b/solutions/909. Snakes and Ladders/909.java @@ -0,0 +1,31 @@ +class Solution { + public int snakesAndLadders(int[][] board) { + final int n = board.length; + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList(1)); + boolean[] seen = new boolean[1 + n * n]; + int[] A = new int[1 + n * n]; // 2D -> 1D + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + A[(n - 1 - i) * n + ((n - i) % 2 == 0 ? n - j : j + 1)] = board[i][j]; + + while (!q.isEmpty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + final int curr = q.poll(); + for (int next = curr + 1; next <= Math.min(curr + 6, n * n); ++next) { + final int dest = A[next] > 0 ? A[next] : next; + if (dest == n * n) + return ans; + if (seen[dest]) + continue; + q.offer(dest); + seen[dest] = true; + } + } + } + + return -1; + } +} diff --git a/solutions/909. Snakes and Ladders/909.py b/solutions/909. Snakes and Ladders/909.py new file mode 100644 index 00000000000..bc76febf00c --- /dev/null +++ b/solutions/909. Snakes and Ladders/909.py @@ -0,0 +1,26 @@ +class Solution: + def snakesAndLadders(self, board: List[List[int]]) -> int: + n = len(board) + ans = 0 + q = collections.deque([1]) + seen = set() + A = [0] * (1 + n * n) # 2D -> 1D + + for i in range(n): + for j in range(n): + A[(n - 1 - i) * n + (n - j if (n - i) % 2 == 0 else j + 1)] = board[i][j] + + while q: + ans += 1 + for _ in range(len(q)): + curr = q.popleft() + for next in range(curr + 1, min(curr + 6, n * n) + 1): + dest = A[next] if A[next] > 0 else next + if dest == n * n: + return ans + if dest in seen: + continue + q.append(dest) + seen.add(dest) + + return -1 diff --git a/solutions/91. Decode Ways/91.cpp b/solutions/91. Decode Ways/91.cpp new file mode 100644 index 00000000000..f559abf401d --- /dev/null +++ b/solutions/91. Decode Ways/91.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + int numDecodings(string s) { + const int n = s.length(); + // dp[i] := the number of ways to decode s[i..n) + vector dp(n + 1); + dp[n] = 1; // "" + dp[n - 1] = isValid(s[n - 1]); + + for (int i = n - 2; i >= 0; --i) { + if (isValid(s[i])) + dp[i] += dp[i + 1]; + if (isValid(s[i], s[i + 1])) + dp[i] += dp[i + 2]; + } + + return dp[0]; + } + + private: + bool isValid(char c) { + return c != '0'; + } + + bool isValid(char c1, char c2) { + return c1 == '1' || c1 == '2' && c2 < '7'; + } +}; diff --git a/solutions/91. Decode Ways/91.java b/solutions/91. Decode Ways/91.java new file mode 100644 index 00000000000..70d46ba7fdc --- /dev/null +++ b/solutions/91. Decode Ways/91.java @@ -0,0 +1,26 @@ +class Solution { + public int numDecodings(String s) { + final int n = s.length(); + // dp[i] := the number of ways to decode s[i..n) + int[] dp = new int[n + 1]; + dp[n] = 1; // "" + dp[n - 1] = isValid(s.charAt(n - 1)) ? 1 : 0; + + for (int i = n - 2; i >= 0; --i) { + if (isValid(s.charAt(i))) + dp[i] += dp[i + 1]; + if (isValid(s.charAt(i), s.charAt(i + 1))) + dp[i] += dp[i + 2]; + } + + return dp[0]; + } + + private boolean isValid(char c) { + return c != '0'; + } + + private boolean isValid(char c1, char c2) { + return c1 == '1' || c1 == '2' && c2 < '7'; + } +} diff --git a/solutions/91. Decode Ways/91.py b/solutions/91. Decode Ways/91.py new file mode 100644 index 00000000000..983eceb9f76 --- /dev/null +++ b/solutions/91. Decode Ways/91.py @@ -0,0 +1,21 @@ +class Solution: + def numDecodings(self, s: str) -> int: + n = len(s) + # dp[i] := the number of ways to decode s[i..n) + dp = [0] * n + [1] + + def isValid(a: str, b=None) -> bool: + if b: + return a == '1' or a == '2' and b < '7' + return a != '0' + + if isValid(s[-1]): + dp[n - 1] = 1 + + for i in reversed(range(n - 1)): + if isValid(s[i]): + dp[i] += dp[i + 1] + if isValid(s[i], s[i + 1]): + dp[i] += dp[i + 2] + + return dp[0] diff --git a/solutions/910. Smallest Range II/910.cpp b/solutions/910. Smallest Range II/910.cpp new file mode 100644 index 00000000000..46b0ef158f1 --- /dev/null +++ b/solutions/910. Smallest Range II/910.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int smallestRangeII(vector& nums, int k) { + ranges::sort(nums); + + int ans = nums.back() - nums.front(); + const int left = nums.front() + k; + const int right = nums.back() - k; + + for (int i = 0; i + 1 < nums.size(); ++i) { + const int mn = min(left, nums[i + 1] - k); + const int mx = max(right, nums[i] + k); + ans = min(ans, mx - mn); + } + + return ans; + } +}; diff --git a/solutions/910. Smallest Range II/910.java b/solutions/910. Smallest Range II/910.java new file mode 100644 index 00000000000..94bbce0fabc --- /dev/null +++ b/solutions/910. Smallest Range II/910.java @@ -0,0 +1,17 @@ +class Solution { + public int smallestRangeII(int[] nums, int k) { + Arrays.sort(nums); + + int ans = nums[nums.length - 1] - nums[0]; + final int left = nums[0] + k; + final int right = nums[nums.length - 1] - k; + + for (int i = 0; i + 1 < nums.length; ++i) { + final int mn = Math.min(left, nums[i + 1] - k); + final int mx = Math.max(right, nums[i] + k); + ans = Math.min(ans, mx - mn); + } + + return ans; + } +} diff --git a/solutions/910. Smallest Range II/910.py b/solutions/910. Smallest Range II/910.py new file mode 100644 index 00000000000..12b6437fe7c --- /dev/null +++ b/solutions/910. Smallest Range II/910.py @@ -0,0 +1,14 @@ +class Solution: + def smallestRangeII(self, nums: List[int], k: int) -> int: + nums.sort() + + ans = nums[-1] - nums[0] + left = nums[0] + k + right = nums[-1] - k + + for a, b in itertools.pairwise(nums): + mn = min(left, b - k) + mx = max(right, a + k) + ans = min(ans, mx - mn) + + return ans diff --git a/solutions/911. Online Election/911.cpp b/solutions/911. Online Election/911.cpp new file mode 100644 index 00000000000..9b3301d6295 --- /dev/null +++ b/solutions/911. Online Election/911.cpp @@ -0,0 +1,22 @@ +class TopVotedCandidate { + public: + TopVotedCandidate(vector& persons, vector& times) : times(times) { + unordered_map count; // {person: voted} + int lead = -1; + + for (int i = 0; i < persons.size(); ++i) { + if (++count[persons[i]] >= count[lead]) + lead = persons[i]; + timeToLead[times[i]] = lead; + } + } + + int q(int t) { + auto it = --ranges::upper_bound(times, t); + return timeToLead[*it]; + } + + private: + const vector times; + unordered_map timeToLead; +}; diff --git a/solutions/911. Online Election/911.java b/solutions/911. Online Election/911.java new file mode 100644 index 00000000000..df98446e69e --- /dev/null +++ b/solutions/911. Online Election/911.java @@ -0,0 +1,21 @@ +class TopVotedCandidate { + public TopVotedCandidate(int[] persons, int[] times) { + this.times = times; + int lead = -1; + Map count = new HashMap<>(); // {person: voted} + + for (int i = 0; i < persons.length; ++i) { + if (count.merge(persons[i], 1, Integer::sum) >= count.getOrDefault(lead, 0)) + lead = persons[i]; + timeToLead.put(times[i], lead); + } + } + + public int q(int t) { + final int i = Arrays.binarySearch(times, t); + return i < 0 ? timeToLead.get(times[-i - 2]) : timeToLead.get(times[i]); + } + + private final int[] times; + private Map timeToLead = new HashMap<>(); +} diff --git a/solutions/911. Online Election/911.py b/solutions/911. Online Election/911.py new file mode 100644 index 00000000000..11c6ee728f7 --- /dev/null +++ b/solutions/911. Online Election/911.py @@ -0,0 +1,16 @@ +class TopVotedCandidate: + def __init__(self, persons: List[int], times: List[int]): + self.times = times + self.timeToLead = {} + count = collections.Counter() # {person: voted} + lead = -1 + + for person, time in zip(persons, times): + count[person] += 1 + if count[person] >= count[lead]: + lead = person + self.timeToLead[time] = lead + + def q(self, t: int) -> int: + i = bisect_right(self.times, t) + return self.timeToLead[self.times[i - 1]] diff --git a/solutions/912. Sort an Array/912-2.cpp b/solutions/912. Sort an Array/912-2.cpp new file mode 100644 index 00000000000..d1e38550e5b --- /dev/null +++ b/solutions/912. Sort an Array/912-2.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + vector sortArray(vector& nums) { + heapSort(nums); + return nums; + } + + private: + void heapSort(vector& A) { + buildMaxHeap(A); + int heapSize = A.size(); + for (int i = A.size() - 1; i > 0; --i) { + swap(A[i], A[0]); + --heapSize; + maxHeapify(A, 0, heapSize); + } + } + + void buildMaxHeap(vector& A) { + for (int i = A.size() / 2; i >= 0; --i) + maxHeapify(A, i, A.size()); + } + + void maxHeapify(vector& A, int i, int heapSize) { + const int l = 2 * i + 1; + const int r = 2 * i + 2; + int largest = i; + if (l < heapSize && A[largest] < A[l]) + largest = l; + if (r < heapSize && A[largest] < A[r]) + largest = r; + if (largest != i) { + swap(A[largest], A[i]); + maxHeapify(A, largest, heapSize); + } + } +}; diff --git a/solutions/912. Sort an Array/912-2.java b/solutions/912. Sort an Array/912-2.java new file mode 100644 index 00000000000..1bc9a5a1a02 --- /dev/null +++ b/solutions/912. Sort an Array/912-2.java @@ -0,0 +1,41 @@ +class Solution { + public int[] sortArray(int[] nums) { + heapSort(nums); + return nums; + } + + private void heapSort(int[] A) { + buildMaxHeap(A); + int heapSize = A.length; + for (int i = A.length - 1; i > 0; --i) { + swap(A, i, 0); + --heapSize; + maxHeapify(A, 0, heapSize); + } + } + + private void buildMaxHeap(int[] A) { + for (int i = A.length / 2; i >= 0; --i) + maxHeapify(A, i, A.length); + } + + private void maxHeapify(int[] A, int i, int heapSize) { + final int l = 2 * i + 1; + final int r = 2 * i + 2; + int largest = i; + if (l < heapSize && A[largest] < A[l]) + largest = l; + if (r < heapSize && A[largest] < A[r]) + largest = r; + if (largest != i) { + swap(A, largest, i); + maxHeapify(A, largest, heapSize); + } + } + + private void swap(int[] A, int i, int j) { + final int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} diff --git a/solutions/912. Sort an Array/912-2.py b/solutions/912. Sort an Array/912-2.py new file mode 100644 index 00000000000..93561e8e5b1 --- /dev/null +++ b/solutions/912. Sort an Array/912-2.py @@ -0,0 +1,28 @@ +class Solution: + def sortArray(self, nums: List[int]) -> List[int]: + def heapSort(A: List[int]) -> None: + def maxHeapify(A: List[int], i: int, heapSize: int) -> None: + l = 2 * i + 1 + r = 2 * i + 2 + largest = i + if l < heapSize and A[largest] < A[l]: + largest = l + if r < heapSize and A[largest] < A[r]: + largest = r + if largest != i: + A[largest], A[i] = A[i], A[largest] + maxHeapify(A, largest, heapSize) + + def buildMaxHeap(A: List[int]) -> None: + for i in range(len(A) // 2, -1, -1): + maxHeapify(A, i, len(A)) + + buildMaxHeap(A) + heapSize = len(A) + for i in reversed(range(1, len(A))): + A[i], A[0] = A[0], A[i] + heapSize -= 1 + maxHeapify(A, 0, heapSize) + + heapSort(nums) + return nums diff --git a/solutions/912. Sort an Array/912-3.cpp b/solutions/912. Sort an Array/912-3.cpp new file mode 100644 index 00000000000..5eef624b9c9 --- /dev/null +++ b/solutions/912. Sort an Array/912-3.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector sortArray(vector& nums) { + quickSort(nums, 0, nums.size() - 1); + return nums; + } + + private: + void quickSort(vector& A, int l, int r) { + if (l >= r) + return; + + const int m = partition(A, l, r); + quickSort(A, l, m - 1); + quickSort(A, m + 1, r); + } + + int partition(vector& A, int l, int r) { + const int randIndex = rand() % (r - l + 1) + l; + swap(A[randIndex], A[r]); + const int pivot = A[r]; + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (A[i] <= pivot) + swap(A[nextSwapped++], A[i]); + swap(A[nextSwapped], A[r]); + return nextSwapped; + } +}; diff --git a/solutions/912. Sort an Array/912-3.java b/solutions/912. Sort an Array/912-3.java new file mode 100644 index 00000000000..25aa88d4aa6 --- /dev/null +++ b/solutions/912. Sort an Array/912-3.java @@ -0,0 +1,33 @@ +class Solution { + public int[] sortArray(int[] nums) { + quickSort(nums, 0, nums.length - 1); + return nums; + } + + private void quickSort(int[] A, int l, int r) { + if (l >= r) + return; + + final int m = partition(A, l, r); + quickSort(A, l, m - 1); + quickSort(A, m + 1, r); + } + + private int partition(int[] A, int l, int r) { + final int randIndex = new Random().nextInt(r - l + 1) + l; + swap(A, randIndex, r); + final int pivot = A[r]; + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (A[i] <= pivot) + swap(A, nextSwapped++, i); + swap(A, nextSwapped, r); + return nextSwapped; + } + + private void swap(int[] A, int i, int j) { + final int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} diff --git a/solutions/912. Sort an Array/912-3.py b/solutions/912. Sort an Array/912-3.py new file mode 100644 index 00000000000..3ddd16992cc --- /dev/null +++ b/solutions/912. Sort an Array/912-3.py @@ -0,0 +1,24 @@ +class Solution: + def sortArray(self, nums: List[int]) -> List[int]: + def quickSort(A: List[int], l: int, r: int) -> None: + if l >= r: + return + + def partition(A: List[int], l: int, r: int) -> int: + randIndex = random.randint(0, r - l) + l + A[randIndex], A[r] = A[r], A[randIndex] + pivot = A[r] + nextSwapped = l + for i in range(l, r): + if A[i] <= pivot: + A[nextSwapped], A[i] = A[i], A[nextSwapped] + nextSwapped += 1 + A[nextSwapped], A[r] = A[r], A[nextSwapped] + return nextSwapped + + m = partition(A, l, r) + quickSort(A, l, m - 1) + quickSort(A, m + 1, r) + + quickSort(nums, 0, len(nums) - 1) + return nums diff --git a/solutions/912. Sort an Array/912.cpp b/solutions/912. Sort an Array/912.cpp new file mode 100644 index 00000000000..842364a3125 --- /dev/null +++ b/solutions/912. Sort an Array/912.cpp @@ -0,0 +1,41 @@ +class Solution { + public: + vector sortArray(vector& nums) { + mergeSort(nums, 0, nums.size() - 1); + return nums; + } + + private: + void mergeSort(vector& A, int l, int r) { + if (l >= r) + return; + + const int m = (l + r) / 2; + mergeSort(A, l, m); + mergeSort(A, m + 1, r); + merge(A, l, m, r); + } + + void merge(vector& A, int l, int m, int r) { + vector sorted(r - l + 1); + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + + while (i <= m && j <= r) + if (A[i] < A[j]) + sorted[k++] = A[i++]; + else + sorted[k++] = A[j++]; + + // Put the possible remaining left part into the sorted array. + while (i <= m) + sorted[k++] = A[i++]; + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = A[j++]; + + copy(sorted.begin(), sorted.end(), A.begin() + l); + } +}; diff --git a/solutions/912. Sort an Array/912.java b/solutions/912. Sort an Array/912.java new file mode 100644 index 00000000000..cbe7a12b1b4 --- /dev/null +++ b/solutions/912. Sort an Array/912.java @@ -0,0 +1,39 @@ +class Solution { + public int[] sortArray(int[] nums) { + mergeSort(nums, 0, nums.length - 1); + return nums; + } + + private void mergeSort(int[] A, int l, int r) { + if (l >= r) + return; + + final int m = (l + r) / 2; + mergeSort(A, l, m); + mergeSort(A, m + 1, r); + merge(A, l, m, r); + } + + private void merge(int[] A, int l, int m, int r) { + int[] sorted = new int[r - l + 1]; + int k = 0; // sorted's index + int i = l; // left's index + int j = m + 1; // right's index + + while (i <= m && j <= r) + if (A[i] < A[j]) + sorted[k++] = A[i++]; + else + sorted[k++] = A[j++]; + + // Put the possible remaining left part into the sorted array. + while (i <= m) + sorted[k++] = A[i++]; + + // Put the possible remaining right part into the sorted array. + while (j <= r) + sorted[k++] = A[j++]; + + System.arraycopy(sorted, 0, A, l, sorted.length); + } +} diff --git a/solutions/912. Sort an Array/912.py b/solutions/912. Sort an Array/912.py new file mode 100644 index 00000000000..b52b60f450d --- /dev/null +++ b/solutions/912. Sort an Array/912.py @@ -0,0 +1,43 @@ +class Solution: + def sortArray(self, nums: List[int]) -> List[int]: + def mergeSort(A: List[int], l: int, r: int) -> None: + if l >= r: + return + + def merge(A: List[int], l: int, m: int, r: int) -> None: + sorted = [0] * (r - l + 1) + k = 0 # sorted's index + i = l # left's index + j = m + 1 # right's index + + while i <= m and j <= r: + if A[i] < A[j]: + sorted[k] = A[i] + k += 1 + i += 1 + else: + sorted[k] = A[j] + k += 1 + j += 1 + + # Put the possible remaining left part into the sorted array. + while i <= m: + sorted[k] = A[i] + k += 1 + i += 1 + + # Put the possible remaining right part into the sorted array. + while j <= r: + sorted[k] = A[j] + k += 1 + j += 1 + + A[l:l + len(sorted)] = sorted + + m = (l + r) // 2 + mergeSort(A, l, m) + mergeSort(A, m + 1, r) + merge(A, l, m, r) + + mergeSort(nums, 0, len(nums) - 1) + return nums diff --git a/solutions/913. Cat and Mouse/913.cpp b/solutions/913. Cat and Mouse/913.cpp new file mode 100644 index 00000000000..e2a94a76b28 --- /dev/null +++ b/solutions/913. Cat and Mouse/913.cpp @@ -0,0 +1,58 @@ +enum class State { kDraw, kMouseWin, kCatWin }; + +class Solution { + public: + int catMouseGame(vector>& graph) { + const int n = graph.size(); + // result of (cat, mouse, move) + // move := 0 (mouse) / 1 (cat) + vector>> states( + n, vector>(n, vector(2))); + vector>> outDegree( + n, vector>(n, vector(2))); + queue> q; // (cat, mouse, move, state) + + for (int cat = 0; cat < n; ++cat) + for (int mouse = 0; mouse < n; ++mouse) { + outDegree[cat][mouse][0] = graph[mouse].size(); + outDegree[cat][mouse][1] = + graph[cat].size() - ranges::count(graph[cat], 0); + } + + // Start from the states s.t. the winner can be determined. + for (int cat = 1; cat < n; ++cat) + for (int move = 0; move < 2; ++move) { + // Mouse is in the hole. + states[cat][0][move] = State::kMouseWin; + q.emplace(cat, 0, move, State::kMouseWin); + // Cat catches mouse. + states[cat][cat][move] = State::kCatWin; + q.emplace(cat, cat, move, State::kCatWin); + } + + while (!q.empty()) { + const auto [cat, mouse, move, state] = q.front(); + q.pop(); + if (cat == 2 && mouse == 1 && move == 0) + return static_cast(state); + const int prevMove = move ^ 1; + for (const int prev : graph[prevMove ? cat : mouse]) { + const int prevCat = prevMove ? prev : cat; + if (prevCat == 0) // invalid + continue; + const int prevMouse = prevMove ? mouse : prev; + // The state has been determined. + if (states[prevCat][prevMouse][prevMove] != State::kDraw) + continue; + if (prevMove == 0 && state == State::kMouseWin || + prevMove == 1 && state == State::kCatWin || + --outDegree[prevCat][prevMouse][prevMove] == 0) { + states[prevCat][prevMouse][prevMove] = state; + q.emplace(prevCat, prevMouse, prevMove, state); + } + } + } + + return static_cast(states[2][1][0]); + } +}; diff --git a/solutions/913. Cat and Mouse/913.java b/solutions/913. Cat and Mouse/913.java new file mode 100644 index 00000000000..48b75a73911 --- /dev/null +++ b/solutions/913. Cat and Mouse/913.java @@ -0,0 +1,57 @@ +enum State { kDraw, kMouseWin, kCatWin } + +class Solution { + public int catMouseGame(int[][] graph) { + final int n = graph.length; + // result of (cat, mouse, move) + // move := 0 (mouse) / 1 (cat) + int[][][] states = new int[n][n][2]; + int[][][] outDegree = new int[n][n][2]; + Queue q = new ArrayDeque<>(); + + for (int cat = 0; cat < n; ++cat) + for (int mouse = 0; mouse < n; ++mouse) { + outDegree[cat][mouse][0] = graph[mouse].length; + outDegree[cat][mouse][1] = + graph[cat].length - (Arrays.stream(graph[cat]).anyMatch(v -> v == 0) ? 1 : 0); + } + + // Start from the states s.t. the winner can be determined. + for (int cat = 1; cat < n; ++cat) + for (int move = 0; move < 2; ++move) { + // Mouse is in the hole. + states[cat][0][move] = State.kMouseWin.ordinal(); + q.offer(new int[] {cat, 0, move, State.kMouseWin.ordinal()}); + // Cat catches mouse. + states[cat][cat][move] = State.kCatWin.ordinal(); + q.offer(new int[] {cat, cat, move, State.kCatWin.ordinal()}); + } + + while (!q.isEmpty()) { + final int cat = q.peek()[0]; + final int mouse = q.peek()[1]; + final int move = q.peek()[2]; + final int state = q.poll()[3]; + if (cat == 2 && mouse == 1 && move == 0) + return state; + final int prevMove = move ^ 1; + for (final int prev : graph[prevMove == 0 ? mouse : cat]) { + final int prevCat = prevMove == 0 ? cat : prev; + if (prevCat == 0) // invalid + continue; + final int prevMouse = prevMove == 0 ? prev : mouse; + // The state has been determined. + if (states[prevCat][prevMouse][prevMove] > 0) + continue; + if (prevMove == 0 && state == State.kMouseWin.ordinal() || + prevMove == 1 && state == State.kCatWin.ordinal() || + --outDegree[prevCat][prevMouse][prevMove] == 0) { + states[prevCat][prevMouse][prevMove] = state; + q.offer(new int[] {prevCat, prevMouse, prevMove, state}); + } + } + } + + return states[2][1][0]; + } +} diff --git a/solutions/913. Cat and Mouse/913.py b/solutions/913. Cat and Mouse/913.py new file mode 100644 index 00000000000..c799d93b533 --- /dev/null +++ b/solutions/913. Cat and Mouse/913.py @@ -0,0 +1,57 @@ +from enum import IntEnum + + +class State(IntEnum): + kDraw = 0 + kMouseWin = 1 + kCatWin = 2 + + +class Solution: + def catMouseGame(self, graph: List[List[int]]) -> int: + n = len(graph) + # result of (cat, mouse, move) + # move := 0 (mouse) // 1 (cat) + states = [[[0] * 2 for i in range(n)] for j in range(n)] + outDegree = [[[0] * 2 for i in range(n)] for j in range(n)] + q = collections.deque() # (cat, mouse, move, state) + + for cat in range(n): + for mouse in range(n): + outDegree[cat][mouse][0] = len(graph[mouse]) + outDegree[cat][mouse][1] = len(graph[cat]) - graph[cat].count(0) + + # Start from the states s.t. the winner can be determined. + for cat in range(1, n): + for move in range(2): + # Mouse is in the hole. + states[cat][0][move] = int(State.kMouseWin) + q.append((cat, 0, move, int(State.kMouseWin))) + # Cat catches mouse. + states[cat][cat][move] = int(State.kCatWin) + q.append((cat, cat, move, int(State.kCatWin))) + + while q: + cat, mouse, move, state = q.popleft() + if cat == 2 and mouse == 1 and move == 0: + return state + prevMove = move ^ 1 + for prev in graph[cat if prevMove else mouse]: + prevCat = prev if prevMove else cat + if prevCat == 0: # invalid + continue + prevMouse = mouse if prevMove else prev + # The state has been determined. + if states[prevCat][prevMouse][prevMove]: + continue + if prevMove == 0 and state == int(State.kMouseWin) or \ + prevMove == 1 and state == int(State.kCatWin): + states[prevCat][prevMouse][prevMove] = state + q.append((prevCat, prevMouse, prevMove, state)) + else: + outDegree[prevCat][prevMouse][prevMove] -= 1 + if outDegree[prevCat][prevMouse][prevMove] == 0: + states[prevCat][prevMouse][prevMove] = state + q.append((prevCat, prevMouse, prevMove, state)) + + return states[2][1][0] diff --git a/solutions/914. X of a Kind in a Deck of Cards/914.cpp b/solutions/914. X of a Kind in a Deck of Cards/914.cpp new file mode 100644 index 00000000000..5f0f9612cc1 --- /dev/null +++ b/solutions/914. X of a Kind in a Deck of Cards/914.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool hasGroupsSizeX(vector& deck) { + unordered_map count; + int gcd = 0; + + for (const int d : deck) + ++count[d]; + + for (const auto& [_, value] : count) + gcd = __gcd(gcd, value); + + return gcd >= 2; + } +}; diff --git a/solutions/914. X of a Kind in a Deck of Cards/914.java b/solutions/914. X of a Kind in a Deck of Cards/914.java new file mode 100644 index 00000000000..052e1dddcd7 --- /dev/null +++ b/solutions/914. X of a Kind in a Deck of Cards/914.java @@ -0,0 +1,18 @@ +class Solution { + public boolean hasGroupsSizeX(int[] deck) { + Map count = new HashMap<>(); + int gcd = 0; + + for (final int d : deck) + count.merge(d, 1, Integer::sum); + + for (final int value : count.values()) + gcd = __gcd(gcd, value); + + return gcd >= 2; + } + + private int __gcd(int a, int b) { + return b > 0 ? __gcd(b, a % b) : a; + } +} diff --git a/solutions/914. X of a Kind in a Deck of Cards/914.py b/solutions/914. X of a Kind in a Deck of Cards/914.py new file mode 100644 index 00000000000..2477ebfe817 --- /dev/null +++ b/solutions/914. X of a Kind in a Deck of Cards/914.py @@ -0,0 +1,4 @@ +class Solution: + def hasGroupsSizeX(self, deck: List[int]) -> bool: + count = collections.Counter(deck) + return functools.reduce(math.gcd, count.values()) >= 2 diff --git a/solutions/915. Partition Array into Disjoint Intervals/915.cpp b/solutions/915. Partition Array into Disjoint Intervals/915.cpp new file mode 100644 index 00000000000..3d54679c59a --- /dev/null +++ b/solutions/915. Partition Array into Disjoint Intervals/915.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int partitionDisjoint(vector& nums) { + const int n = nums.size(); + vector mn(n); + mn[n - 1] = nums[n - 1]; + int mx = INT_MIN; + + for (int i = n - 2; i >= 0; --i) + mn[i] = min(mn[i + 1], nums[i]); + + for (int i = 0; i < n; ++i) { + mx = max(mx, nums[i]); + if (mx <= mn[i + 1]) + return i + 1; + } + + throw; + } +}; diff --git a/solutions/915. Partition Array into Disjoint Intervals/915.java b/solutions/915. Partition Array into Disjoint Intervals/915.java new file mode 100644 index 00000000000..26aeb13a6ea --- /dev/null +++ b/solutions/915. Partition Array into Disjoint Intervals/915.java @@ -0,0 +1,19 @@ +class Solution { + public int partitionDisjoint(int[] nums) { + final int n = nums.length; + int[] mn = new int[n]; + mn[n - 1] = nums[n - 1]; + int mx = Integer.MIN_VALUE; + + for (int i = n - 2; i >= 0; --i) + mn[i] = Math.min(mn[i + 1], nums[i]); + + for (int i = 0; i < n; ++i) { + mx = Math.max(mx, nums[i]); + if (mx <= mn[i + 1]) + return i + 1; + } + + throw new IllegalArgumentException(); + } +} diff --git a/solutions/915. Partition Array into Disjoint Intervals/915.py b/solutions/915. Partition Array into Disjoint Intervals/915.py new file mode 100644 index 00000000000..8b1b05b2d85 --- /dev/null +++ b/solutions/915. Partition Array into Disjoint Intervals/915.py @@ -0,0 +1,13 @@ +class Solution: + def partitionDisjoint(self, nums: List[int]) -> int: + n = len(nums) + mn = [0] * (n - 1) + [nums[-1]] + mx = -math.inf + + for i in range(n - 2, - 1, -1): + mn[i] = min(mn[i + 1], nums[i]) + + for i, num in enumerate(nums): + mx = max(mx, num) + if mx <= mn[i + 1]: + return i + 1 diff --git a/solutions/916. Word Subsets/916.cpp b/solutions/916. Word Subsets/916.cpp new file mode 100644 index 00000000000..a4e8e4cabc5 --- /dev/null +++ b/solutions/916. Word Subsets/916.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + vector wordSubsets(vector& A, vector& B) { + vector ans; + vector countB(26); + + for (const string& b : B) { + vector temp = counter(b); + for (int i = 0; i < 26; ++i) + countB[i] = max(countB[i], temp[i]); + } + + for (const string& a : A) + if (isUniversal(counter(a), countB)) + ans.push_back(a); + + return ans; + } + + private: + vector counter(const string& s) { + vector count(26); + for (char c : s) + ++count[c - 'a']; + return count; + } + + bool isUniversal(vector countA, vector& countB) { + for (int i = 0; i < 26; ++i) + if (countA[i] < countB[i]) + return false; + return true; + } +}; diff --git a/solutions/916. Word Subsets/916.java b/solutions/916. Word Subsets/916.java new file mode 100644 index 00000000000..6e249c43fba --- /dev/null +++ b/solutions/916. Word Subsets/916.java @@ -0,0 +1,32 @@ +class Solution { + public List wordSubsets(String[] A, String[] B) { + List ans = new ArrayList<>(); + int[] countB = new int[26]; + + for (final String b : B) { + int[] temp = counter(b); + for (int i = 0; i < 26; ++i) + countB[i] = Math.max(countB[i], temp[i]); + } + + for (final String a : A) + if (isUniversal(counter(a), countB)) + ans.add(a); + + return ans; + } + + private int[] counter(final String s) { + int[] count = new int[26]; + for (char c : s.toCharArray()) + ++count[c - 'a']; + return count; + } + + private boolean isUniversal(int[] countA, int[] countB) { + for (int i = 0; i < 26; ++i) + if (countA[i] < countB[i]) + return false; + return true; + } +} diff --git a/solutions/916. Word Subsets/916.py b/solutions/916. Word Subsets/916.py new file mode 100644 index 00000000000..b13ccecd812 --- /dev/null +++ b/solutions/916. Word Subsets/916.py @@ -0,0 +1,8 @@ +class Solution: + def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: + count = collections.Counter() + + for b in B: + count = count | collections.Counter(b) + + return [a for a in A if collections.Counter(a) & count == count] diff --git a/solutions/917. Reverse Only Letters/917.cpp b/solutions/917. Reverse Only Letters/917.cpp new file mode 100644 index 00000000000..27436fedf37 --- /dev/null +++ b/solutions/917. Reverse Only Letters/917.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + string reverseOnlyLetters(string s) { + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + while (i < j && !isalpha(s[i])) + ++i; + while (i < j && !isalpha(s[j])) + --j; + swap(s[i], s[j]); + } + return s; + } +}; diff --git a/solutions/917. Reverse Only Letters/917.java b/solutions/917. Reverse Only Letters/917.java new file mode 100644 index 00000000000..6afefde2394 --- /dev/null +++ b/solutions/917. Reverse Only Letters/917.java @@ -0,0 +1,16 @@ +class Solution { + public String reverseOnlyLetters(String s) { + StringBuilder sb = new StringBuilder(s); + + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + while (i < j && !Character.isLetter(s.charAt(i))) + ++i; + while (i < j && !Character.isLetter(s.charAt(j))) + --j; + sb.setCharAt(i, s.charAt(j)); + sb.setCharAt(j, s.charAt(i)); + } + + return sb.toString(); + } +} diff --git a/solutions/917. Reverse Only Letters/917.py b/solutions/917. Reverse Only Letters/917.py new file mode 100644 index 00000000000..421c4cbaaca --- /dev/null +++ b/solutions/917. Reverse Only Letters/917.py @@ -0,0 +1,16 @@ +class Solution: + def reverseOnlyLetters(self, s: str) -> str: + ans = list(s) + i = 0 + j = len(s) - 1 + + while i < j: + while i < j and not s[i].isalpha(): + i += 1 + while i < j and not s[j].isalpha(): + j -= 1 + ans[i], ans[j] = ans[j], ans[i] + i += 1 + j -= 1 + + return ''.join(ans) diff --git a/solutions/918. Maximum Sum Circular Subarray/918.cpp b/solutions/918. Maximum Sum Circular Subarray/918.cpp new file mode 100644 index 00000000000..32d42a1f621 --- /dev/null +++ b/solutions/918. Maximum Sum Circular Subarray/918.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int maxSubarraySumCircular(vector& nums) { + int totalSum = 0; + int currMaxSum = 0; + int currMinSum = 0; + int maxSum = INT_MIN; + int minSum = INT_MAX; + + for (const int num : nums) { + totalSum += num; + currMaxSum = max(currMaxSum + num, num); + currMinSum = min(currMinSum + num, num); + maxSum = max(maxSum, currMaxSum); + minSum = min(minSum, currMinSum); + } + + return maxSum < 0 ? maxSum : max(maxSum, totalSum - minSum); + } +}; diff --git a/solutions/918. Maximum Sum Circular Subarray/918.java b/solutions/918. Maximum Sum Circular Subarray/918.java new file mode 100644 index 00000000000..f6af272ceff --- /dev/null +++ b/solutions/918. Maximum Sum Circular Subarray/918.java @@ -0,0 +1,19 @@ +class Solution { + public int maxSubarraySumCircular(int[] nums) { + int totalSum = 0; + int currMaxSum = 0; + int currMinSum = 0; + int maxSum = Integer.MIN_VALUE; + int minSum = Integer.MAX_VALUE; + + for (final int num : nums) { + totalSum += num; + currMaxSum = Math.max(currMaxSum + num, num); + currMinSum = Math.min(currMinSum + num, num); + maxSum = Math.max(maxSum, currMaxSum); + minSum = Math.min(minSum, currMinSum); + } + + return maxSum < 0 ? maxSum : Math.max(maxSum, totalSum - minSum); + } +} diff --git a/solutions/918. Maximum Sum Circular Subarray/918.py b/solutions/918. Maximum Sum Circular Subarray/918.py new file mode 100644 index 00000000000..ea8a5d7f786 --- /dev/null +++ b/solutions/918. Maximum Sum Circular Subarray/918.py @@ -0,0 +1,16 @@ +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + totalSum = 0 + currMaxSum = 0 + currMinSum = 0 + maxSum = -math.inf + minSum = math.inf + + for num in nums: + totalSum += num + currMaxSum = max(currMaxSum + num, num) + currMinSum = min(currMinSum + num, num) + maxSum = max(maxSum, currMaxSum) + minSum = min(minSum, currMinSum) + + return maxSum if maxSum < 0 else max(maxSum, totalSum - minSum) diff --git a/solutions/919. Complete Binary Tree Inserter/919.cpp b/solutions/919. Complete Binary Tree Inserter/919.cpp new file mode 100644 index 00000000000..4f610d6c240 --- /dev/null +++ b/solutions/919. Complete Binary Tree Inserter/919.cpp @@ -0,0 +1,31 @@ +class CBTInserter { + public: + CBTInserter(TreeNode* root) { + tree.push_back(root); + for (int i = 0; i < tree.size(); ++i) { + TreeNode* node = tree[i]; + if (node->left) + tree.push_back(node->left); + if (node->right) + tree.push_back(node->right); + } + } + + int insert(int v) { + const int n = tree.size(); + tree.push_back(new TreeNode(v)); + auto& parent = tree[(n - 1) / 2]; + if (n % 2 == 1) + parent->left = tree.back(); + else + parent->right = tree.back(); + return parent->val; + } + + TreeNode* get_root() { + return tree[0]; + } + + private: + vector tree; +}; diff --git a/solutions/919. Complete Binary Tree Inserter/919.java b/solutions/919. Complete Binary Tree Inserter/919.java new file mode 100644 index 00000000000..bfabbf382f7 --- /dev/null +++ b/solutions/919. Complete Binary Tree Inserter/919.java @@ -0,0 +1,30 @@ +class CBTInserter { + public CBTInserter(TreeNode root) { + tree.add(root); + for (int i = 0; i < tree.size(); ++i) { + TreeNode node = tree.get(i); + if (node.left != null) + tree.add(node.left); + if (node.right != null) + tree.add(node.right); + } + } + + public int insert(int v) { + final int n = tree.size(); + TreeNode node = new TreeNode(v); + TreeNode parent = tree.get((n - 1) / 2); + tree.add(node); + if (n % 2 == 1) + parent.left = node; + else + parent.right = node; + return parent.val; + } + + public TreeNode get_root() { + return tree.get(0); + } + + private List tree = new ArrayList<>(); +} diff --git a/solutions/919. Complete Binary Tree Inserter/919.py b/solutions/919. Complete Binary Tree Inserter/919.py new file mode 100644 index 00000000000..4f00c2c0986 --- /dev/null +++ b/solutions/919. Complete Binary Tree Inserter/919.py @@ -0,0 +1,21 @@ +class CBTInserter: + def __init__(self, root: Optional[TreeNode]): + self.tree = [root] + for node in self.tree: + if node.left: + self.tree.append(node.left) + if node.right: + self.tree.append(node.right) + + def insert(self, v: int) -> int: + n = len(self.tree) + self.tree.append(TreeNode(v)) + parent = self.tree[(n - 1) // 2] + if n % 2 == 1: + parent.left = self.tree[-1] + else: + parent.right = self.tree[-1] + return parent.val + + def get_root(self) -> Optional[TreeNode]: + return self.tree[0] diff --git a/solutions/92. Reverse Linked List II/92-2.cpp b/solutions/92. Reverse Linked List II/92-2.cpp new file mode 100644 index 00000000000..6d2daa0fb4a --- /dev/null +++ b/solutions/92. Reverse Linked List II/92-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + ListNode* reverseBetween(ListNode* head, int m, int n) { + if (!head || m == n) + return head; + + ListNode dummy(0, head); + ListNode* prev = &dummy; + + for (int i = 0; i < m - 1; ++i) + prev = prev->next; // Point to the node before the sublist [m, n]. + + ListNode* tail = prev->next; // Be the tail of the sublist [m, n] + + // Reverse the sublist [m, n] one by one. + for (int i = 0; i < n - m; ++i) { + ListNode* cache = tail->next; + tail->next = cache->next; + cache->next = prev->next; + prev->next = cache; + } + + return dummy.next; + } +}; diff --git a/solutions/92. Reverse Linked List II/92-2.java b/solutions/92. Reverse Linked List II/92-2.java new file mode 100644 index 00000000000..2d2ec48f84a --- /dev/null +++ b/solutions/92. Reverse Linked List II/92-2.java @@ -0,0 +1,24 @@ +class Solution { + public ListNode reverseBetween(ListNode head, int m, int n) { + if (head == null || m == n) + return head; + + ListNode dummy = new ListNode(0, head); + ListNode prev = dummy; + + for (int i = 0; i < m - 1; ++i) + prev = prev.next; // Point to the node before the sublist [m, n]. + + ListNode tail = prev.next; // Be the tail of the sublist [m, n]. + + // Reverse the sublist [m, n] one by one. + for (int i = 0; i < n - m; ++i) { + ListNode cache = tail.next; + tail.next = cache.next; + cache.next = prev.next; + prev.next = cache; + } + + return dummy.next; + } +} diff --git a/solutions/92. Reverse Linked List II/92-2.py b/solutions/92. Reverse Linked List II/92-2.py new file mode 100644 index 00000000000..79b0e94cb71 --- /dev/null +++ b/solutions/92. Reverse Linked List II/92-2.py @@ -0,0 +1,21 @@ +class Solution: + def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: + if not head and m == n: + return head + + dummy = ListNode(0, head) + prev = dummy + + for _ in range(m - 1): + prev = prev.next # Point to the node before the sublist [m, n]. + + tail = prev.next # Be the tail of the sublist [m, n]. + + # Reverse the sublist [m, n] one by one. + for _ in range(n - m): + cache = tail.next + tail.next = cache.next + cache.next = prev.next + prev.next = cache + + return dummy.next diff --git a/solutions/92. Reverse Linked List II/92.cpp b/solutions/92. Reverse Linked List II/92.cpp new file mode 100644 index 00000000000..d68b1679cab --- /dev/null +++ b/solutions/92. Reverse Linked List II/92.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + ListNode* reverseBetween(ListNode* head, int left, int right) { + if (left == 1) + return reverseN(head, right); + + head->next = reverseBetween(head->next, left - 1, right - 1); + + return head; + } + + private: + ListNode* reverseN(ListNode* head, int n) { + if (n == 1) + return head; + + ListNode* newHead = reverseN(head->next, n - 1); + ListNode* headNext = head->next; + head->next = headNext->next; + headNext->next = head; + + return newHead; + } +}; diff --git a/solutions/92. Reverse Linked List II/92.java b/solutions/92. Reverse Linked List II/92.java new file mode 100644 index 00000000000..233c236370a --- /dev/null +++ b/solutions/92. Reverse Linked List II/92.java @@ -0,0 +1,22 @@ +class Solution { + public ListNode reverseBetween(ListNode head, int left, int right) { + if (left == 1) + return reverseN(head, right); + + head.next = reverseBetween(head.next, left - 1, right - 1); + + return head; + } + + private ListNode reverseN(ListNode head, int n) { + if (n == 1) + return head; + + ListNode newHead = reverseN(head.next, n - 1); + ListNode headNext = head.next; + head.next = headNext.next; + headNext.next = head; + + return newHead; + } +} diff --git a/solutions/92. Reverse Linked List II/92.py b/solutions/92. Reverse Linked List II/92.py new file mode 100644 index 00000000000..bd463733906 --- /dev/null +++ b/solutions/92. Reverse Linked List II/92.py @@ -0,0 +1,17 @@ +class Solution: + def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: + if left == 1: + return self.reverseN(head, right) + + head.next = self.reverseBetween(head.next, left - 1, right - 1) + return head + + def reverseN(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + if n == 1: + return head + + newHead = self.reverseN(head.next, n - 1) + headNext = head.next + head.next = headNext.next + headNext.next = head + return newHead diff --git a/solutions/920. Number of Music Playlists/920-2.cpp b/solutions/920. Number of Music Playlists/920-2.cpp new file mode 100644 index 00000000000..9e74063441e --- /dev/null +++ b/solutions/920. Number of Music Playlists/920-2.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int numMusicPlaylists(int n, int goal, int k) { + constexpr int kMod = 1'000'000'007; + // dp[i][j] := the number of playlists with i songs and j different songs + vector> dp(goal + 1, vector(n + 1)); + dp[0][0] = 1; + + for (int i = 1; i <= goal; ++i) + for (int j = 1; j <= n; ++j) { + dp[i][j] += dp[i - 1][j - 1] * (n - (j - 1)); // The last song is new. + dp[i][j] += dp[i - 1][j] * max(0, j - k); // The last song is old. + dp[i][j] %= kMod; + } + + return dp[goal][n]; + } +}; diff --git a/solutions/920. Number of Music Playlists/920-2.java b/solutions/920. Number of Music Playlists/920-2.java new file mode 100644 index 00000000000..5f47b2b9c0d --- /dev/null +++ b/solutions/920. Number of Music Playlists/920-2.java @@ -0,0 +1,17 @@ +class Solution { + public int numMusicPlaylists(int n, int goal, int k) { + final int kMod = 1_000_000_007; + // dp[i][j] := the number of playlists with i songs and j different songs + long[][] dp = new long[goal + 1][n + 1]; + dp[0][0] = 1; + + for (int i = 1; i <= goal; ++i) + for (int j = 1; j <= n; ++j) { + dp[i][j] += dp[i - 1][j - 1] * (n - (j - 1)); // The last song is new. + dp[i][j] += dp[i - 1][j] * Math.max(0, j - k); // The last song is old. + dp[i][j] %= kMod; + } + + return (int) dp[goal][n]; + } +} diff --git a/solutions/920. Number of Music Playlists/920.cpp b/solutions/920. Number of Music Playlists/920.cpp new file mode 100644 index 00000000000..f33d57c59c0 --- /dev/null +++ b/solutions/920. Number of Music Playlists/920.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int numMusicPlaylists(int n, int goal, int k) { + vector> mem(goal + 1, vector(n + 1, -1)); + return numMusicPlaylists(n, k, goal, n, mem); + } + + private: + static constexpr int kMod = 1'000'000'007; + + // Returns the number of playlists with i songs and j different songs. + long numMusicPlaylists(int n, int k, int i, int j, + vector>& mem) { + if (i == 0) + return j == 0; + if (j == 0) + return 0; + if (mem[i][j] >= 0) + return mem[i][j]; + + // The last song is new. + mem[i][j] = numMusicPlaylists(n, k, i - 1, j - 1, mem) * (n - (j - 1)); + // The last song is old. + mem[i][j] += numMusicPlaylists(n, k, i - 1, j, mem) * max(0, j - k); + return mem[i][j] %= kMod; + } +}; diff --git a/solutions/920. Number of Music Playlists/920.java b/solutions/920. Number of Music Playlists/920.java new file mode 100644 index 00000000000..757e32e6dae --- /dev/null +++ b/solutions/920. Number of Music Playlists/920.java @@ -0,0 +1,25 @@ +class Solution { + public int numMusicPlaylists(int n, int goal, int k) { + long[][] mem = new long[goal + 1][n + 1]; + Arrays.stream(mem).forEach(A -> Arrays.fill(A, -1)); + return (int) numMusicPlaylists(n, k, goal, n, mem); + } + + private static final int kMod = 1_000_000_007; + + // Returns the number of playlists with i songs and j different songs. + private long numMusicPlaylists(int n, int k, int i, int j, long[][] mem) { + if (i == 0) + return j == 0 ? 1 : 0; + if (j == 0) + return 0; + if (mem[i][j] >= 0) + return mem[i][j]; + + // The last song is new. + mem[i][j] = numMusicPlaylists(n, k, i - 1, j - 1, mem) * (n - (j - 1)); + // The last song is old. + mem[i][j] += numMusicPlaylists(n, k, i - 1, j, mem) * Math.max(0, j - k); + return mem[i][j] %= kMod; + } +} diff --git a/solutions/921. Minimum Add to Make Parentheses Valid/921.cpp b/solutions/921. Minimum Add to Make Parentheses Valid/921.cpp new file mode 100644 index 00000000000..f2d4c3d4863 --- /dev/null +++ b/solutions/921. Minimum Add to Make Parentheses Valid/921.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minAddToMakeValid(string s) { + int l = 0; + int r = 0; + + for (const char c : s) + if (c == '(') { + ++l; + } else { + if (l == 0) + ++r; + else + --l; + } + + return l + r; + } +}; diff --git a/solutions/921. Minimum Add to Make Parentheses Valid/921.java b/solutions/921. Minimum Add to Make Parentheses Valid/921.java new file mode 100644 index 00000000000..91c7e1b1d41 --- /dev/null +++ b/solutions/921. Minimum Add to Make Parentheses Valid/921.java @@ -0,0 +1,18 @@ +class Solution { + public int minAddToMakeValid(String s) { + int l = 0; + int r = 0; + + for (final char c : s.toCharArray()) + if (c == '(') { + ++l; + } else { + if (l == 0) + ++r; + else + --l; + } + + return l + r; + } +} diff --git a/solutions/921. Minimum Add to Make Parentheses Valid/921.py b/solutions/921. Minimum Add to Make Parentheses Valid/921.py new file mode 100644 index 00000000000..59700b64e15 --- /dev/null +++ b/solutions/921. Minimum Add to Make Parentheses Valid/921.py @@ -0,0 +1,15 @@ +class Solution: + def minAddToMakeValid(self, s: str) -> int: + l = 0 + r = 0 + + for c in s: + if c == '(': + l += 1 + else: + if l == 0: + r += 1 + else: + l -= 1 + + return l + r diff --git a/solutions/922. Sort Array By Parity II/922.cpp b/solutions/922. Sort Array By Parity II/922.cpp new file mode 100644 index 00000000000..8af82436912 --- /dev/null +++ b/solutions/922. Sort Array By Parity II/922.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector sortArrayByParityII(vector& nums) { + const int n = nums.size(); + + for (int i = 0, j = 1; i < n; i += 2, j += 2) { + while (i < n && nums[i] % 2 == 0) + i += 2; + while (j < n && nums[j] % 2 == 1) + j += 2; + if (i < n) + swap(nums[i], nums[j]); + } + + return nums; + } +}; diff --git a/solutions/922. Sort Array By Parity II/922.java b/solutions/922. Sort Array By Parity II/922.java new file mode 100644 index 00000000000..9883b1d7489 --- /dev/null +++ b/solutions/922. Sort Array By Parity II/922.java @@ -0,0 +1,19 @@ +class Solution { + public int[] sortArrayByParityII(int[] nums) { + final int n = nums.length; + + for (int i = 0, j = 1; i < n; i += 2, j += 2) { + while (i < n && nums[i] % 2 == 0) + i += 2; + while (j < n && nums[j] % 2 == 1) + j += 2; + if (i < n) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + } + + return nums; + } +} diff --git a/solutions/922. Sort Array By Parity II/922.py b/solutions/922. Sort Array By Parity II/922.py new file mode 100644 index 00000000000..60d1f6c10b2 --- /dev/null +++ b/solutions/922. Sort Array By Parity II/922.py @@ -0,0 +1,15 @@ +class Solution: + def sortArrayByParityII(self, nums: List[int]) -> List[int]: + n = len(nums) + + i = 0 + j = 1 + while i < n: + while i < n and nums[i] % 2 == 0: + i += 2 + while j < n and nums[j] % 2 == 1: + j += 2 + if i < n: + nums[i], nums[j] = nums[j], nums[i] + + return nums diff --git a/solutions/923. 3Sum With Multiplicity/923.cpp b/solutions/923. 3Sum With Multiplicity/923.cpp new file mode 100644 index 00000000000..5dbc7622136 --- /dev/null +++ b/solutions/923. 3Sum With Multiplicity/923.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int threeSumMulti(vector& arr, int target) { + constexpr int kMod = 1'000'000'007; + int ans = 0; + unordered_map count; + + for (const int a : arr) + ++count[a]; + + for (const auto& [i, x] : count) + for (const auto& [j, y] : count) { + const int k = target - i - j; + const auto it = count.find(k); + if (it == count.cend()) + continue; + if (i == j && j == k) + ans = (ans + static_cast(x) * (x - 1) * (x - 2) / 6) % kMod; + else if (i == j && j != k) + ans = (ans + static_cast(x) * (x - 1) / 2 * it->second) % kMod; + else if (i < j && j < k) + ans = (ans + static_cast(x) * y * it->second) % kMod; + } + + return ans; + } +}; diff --git a/solutions/923. 3Sum With Multiplicity/923.java b/solutions/923. 3Sum With Multiplicity/923.java new file mode 100644 index 00000000000..8e13b68960b --- /dev/null +++ b/solutions/923. 3Sum With Multiplicity/923.java @@ -0,0 +1,30 @@ +class Solution { + public int threeSumMulti(int[] arr, int target) { + final int kMod = 1_000_000_007; + int ans = 0; + Map count = new HashMap<>(); + + for (final int a : arr) + count.merge(a, 1, Integer::sum); + + for (Map.Entry entry : count.entrySet()) { + final int i = entry.getKey(); + final int x = entry.getValue(); + for (Map.Entry entry2 : count.entrySet()) { + final int j = entry2.getKey(); + final int y = entry2.getValue(); + final int k = target - i - j; + if (!count.containsKey(k)) + continue; + if (i == j && j == k) + ans = (int) ((ans + (long) x * (x - 1) * (x - 2) / 6) % kMod); + else if (i == j && j != k) + ans = (int) ((ans + (long) x * (x - 1) / 2 * count.get(k)) % kMod); + else if (i < j && j < k) + ans = (int) ((ans + (long) x * y * count.get(k)) % kMod); + } + } + + return ans; + } +} diff --git a/solutions/923. 3Sum With Multiplicity/923.py b/solutions/923. 3Sum With Multiplicity/923.py new file mode 100644 index 00000000000..9e473fc72b6 --- /dev/null +++ b/solutions/923. 3Sum With Multiplicity/923.py @@ -0,0 +1,19 @@ +class Solution: + def threeSumMulti(self, arr: List[int], target: int) -> int: + kMod = 1_000_000_007 + ans = 0 + count = collections.Counter(arr) + + for i, x in count.items(): + for j, y in count.items(): + k = target - i - j + if k not in count: + continue + if i == j and j == k: + ans = (ans + x * (x - 1) * (x - 2) // 6) % kMod + elif i == j and j != k: + ans = (ans + x * (x - 1) // 2 * count[k]) % kMod + elif i < j and j < k: + ans = (ans + x * y * count[k]) % kMod + + return ans % kMod diff --git a/solutions/924. Minimize Malware Spread/924.cpp b/solutions/924. Minimize Malware Spread/924.cpp new file mode 100644 index 00000000000..c6b10ba13ba --- /dev/null +++ b/solutions/924. Minimize Malware Spread/924.cpp @@ -0,0 +1,66 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + int minMalwareSpread(vector>& graph, vector& initial) { + const int n = graph.size(); + UnionFind uf(n); + vector ufSize(n); + vector malwareCount(n); + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) + if (graph[i][j] == 1) + uf.unionByRank(i, j); + + for (int i = 0; i < n; ++i) + ++ufSize[uf.find(i)]; + + for (const int i : initial) + ++malwareCount[uf.find(i)]; + + ranges::sort(initial); + + int ans = initial[0]; + int maxUfSize = 0; + + // Find the maximum union's malware if it only contains 1 malware. + for (const int i : initial) { + const int id = uf.find(i); + if (ufSize[id] > maxUfSize && malwareCount[id] == 1) { + maxUfSize = ufSize[id]; + ans = i; + } + } + + return ans; + } +}; diff --git a/solutions/924. Minimize Malware Spread/924.java b/solutions/924. Minimize Malware Spread/924.java new file mode 100644 index 00000000000..bb3fe1910c4 --- /dev/null +++ b/solutions/924. Minimize Malware Spread/924.java @@ -0,0 +1,66 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public int minMalwareSpread(int[][] graph, int[] initial) { + final int n = graph.length; + UnionFind uf = new UnionFind(n); + int[] ufSize = new int[n]; + int[] malwareCount = new int[n]; + + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) + if (graph[i][j] == 1) + uf.unionByRank(i, j); + + for (int i = 0; i < n; ++i) + ++ufSize[uf.find(i)]; + + for (final int i : initial) + ++malwareCount[uf.find(i)]; + + Arrays.sort(initial); + + int ans = initial[0]; + int maxUfSize = 0; + + // Find the maximum union's malware if it only contains 1 malware. + for (final int i : initial) { + final int id = uf.find(i); + if (ufSize[id] > maxUfSize && malwareCount[id] == 1) { + maxUfSize = ufSize[id]; + ans = i; + } + } + + return ans; + } +} diff --git a/solutions/925. Long Pressed Name/925.cpp b/solutions/925. Long Pressed Name/925.cpp new file mode 100644 index 00000000000..91d59d7b7bc --- /dev/null +++ b/solutions/925. Long Pressed Name/925.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + bool isLongPressedName(string name, string typed) { + int i = 0; + + for (int j = 0; j < typed.length(); ++j) + if (i < name.length() && name[i] == typed[j]) + ++i; + else if (j == 0 || typed[j] != typed[j - 1]) + return false; + + return i == name.length(); + } +}; diff --git a/solutions/925. Long Pressed Name/925.java b/solutions/925. Long Pressed Name/925.java new file mode 100644 index 00000000000..24c25fa034e --- /dev/null +++ b/solutions/925. Long Pressed Name/925.java @@ -0,0 +1,13 @@ +class Solution { + public boolean isLongPressedName(String name, String typed) { + int i = 0; + + for (int j = 0; j < typed.length(); ++j) + if (i < name.length() && name.charAt(i) == typed.charAt(j)) + ++i; + else if (j == 0 || typed.charAt(j) != typed.charAt(j - 1)) + return false; + + return i == name.length(); + } +} diff --git a/solutions/925. Long Pressed Name/925.py b/solutions/925. Long Pressed Name/925.py new file mode 100644 index 00000000000..b475af1ec30 --- /dev/null +++ b/solutions/925. Long Pressed Name/925.py @@ -0,0 +1,11 @@ +class Solution: + def isLongPressedName(self, name: str, typed: str) -> bool: + i = 0 + + for j, t in enumerate(typed): + if i < len(name) and name[i] == t: + i += 1 + elif j == 0 or t != typed[j - 1]: + return False + + return i == len(name) diff --git a/solutions/926. Flip String to Monotone Increasing/926.cpp b/solutions/926. Flip String to Monotone Increasing/926.cpp new file mode 100644 index 00000000000..f285ac4c4a5 --- /dev/null +++ b/solutions/926. Flip String to Monotone Increasing/926.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int minFlipsMonoIncr(string s) { + // the number of characters to be flilpped to make the substring so far + // monotone increasing + int dp = 0; + int count1 = 0; + + for (const char c : s) + if (c == '0') + // 1. Flip '0'. + // 2. Keep '0' and flip all the previous 1s. + dp = min(dp + 1, count1); + else + ++count1; + + return dp; + } +}; diff --git a/solutions/926. Flip String to Monotone Increasing/926.java b/solutions/926. Flip String to Monotone Increasing/926.java new file mode 100644 index 00000000000..60612ac692b --- /dev/null +++ b/solutions/926. Flip String to Monotone Increasing/926.java @@ -0,0 +1,18 @@ +class Solution { + public int minFlipsMonoIncr(String s) { + // the number of characters to be flilpped to make the substring so far + // monotone increasing + int dp = 0; + int count1 = 0; + + for (final char c : s.toCharArray()) + if (c == '0') + // 1. Flip '0'. + // 2. Keep '0' and flip all the previous 1s. + dp = Math.min(dp + 1, count1); + else + ++count1; + + return dp; + } +} diff --git a/solutions/926. Flip String to Monotone Increasing/926.py b/solutions/926. Flip String to Monotone Increasing/926.py new file mode 100644 index 00000000000..d7ea1cf9284 --- /dev/null +++ b/solutions/926. Flip String to Monotone Increasing/926.py @@ -0,0 +1,16 @@ +class Solution: + def minFlipsMonoIncr(self, s: str) -> int: + # the number of characters to be flilpped to make the substring so far + # monotone increasing + dp = 0 + count1 = 0 + + for c in s: + if c == '0': + # 1. Flip '0'. + # 2. Keep '0' and flip all the previous 1s. + dp = min(dp + 1, count1) + else: + count1 += 1 + + return dp diff --git a/solutions/927. Three Equal Parts/927.cpp b/solutions/927. Three Equal Parts/927.cpp new file mode 100644 index 00000000000..c4f92f4ccce --- /dev/null +++ b/solutions/927. Three Equal Parts/927.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + vector threeEqualParts(vector& arr) { + const int ones = ranges::count_if(arr, [](int a) { return a == 1; }); + + if (ones == 0) + return {0, static_cast(arr.size()) - 1}; + if (ones % 3 != 0) + return {-1, -1}; + + int k = ones / 3; + int i; + int j; + int first; + int second; + int third; + + for (i = 0; i < arr.size(); ++i) + if (arr[i] == 1) { + first = i; + break; + } + + int gapOnes = k; + + for (j = i + 1; j < arr.size(); ++j) + if (arr[j] == 1 && --gapOnes == 0) { + second = j; + break; + } + + gapOnes = k; + + for (i = j + 1; i < arr.size(); ++i) + if (arr[i] == 1 && --gapOnes == 0) { + third = i; + break; + } + + while (third < arr.size() && arr[first] == arr[second] && + arr[second] == arr[third]) { + ++first; + ++second; + ++third; + } + + if (third == arr.size()) + return {first - 1, second}; + return {-1, -1}; + } +}; diff --git a/solutions/927. Three Equal Parts/927.java b/solutions/927. Three Equal Parts/927.java new file mode 100644 index 00000000000..c0c73ad9edd --- /dev/null +++ b/solutions/927. Three Equal Parts/927.java @@ -0,0 +1,53 @@ +class Solution { + public int[] threeEqualParts(int[] arr) { + int ones = 0; + + for (final int a : arr) + if (a == 1) + ++ones; + + if (ones == 0) + return new int[] {0, arr.length - 1}; + if (ones % 3 != 0) + return new int[] {-1, -1}; + + int k = ones / 3; + int i = 0; + int j = 0; + int first = 0; + int second = 0; + int third = 0; + + for (i = 0; i < arr.length; ++i) + if (arr[i] == 1) { + first = i; + break; + } + + int gapOnes = k; + + for (j = i + 1; j < arr.length; ++j) + if (arr[j] == 1 && --gapOnes == 0) { + second = j; + break; + } + + gapOnes = k; + + for (i = j + 1; i < arr.length; ++i) + if (arr[i] == 1 && --gapOnes == 0) { + third = i; + break; + } + + while (third < arr.length && arr[first] == arr[second] && arr[second] == arr[third]) { + ++first; + ++second; + ++third; + } + + if (third == arr.length) + return new int[] {first - 1, second}; + return new int[] {-1, -1}; + } +} diff --git a/solutions/927. Three Equal Parts/927.py b/solutions/927. Three Equal Parts/927.py new file mode 100644 index 00000000000..55dd1aac672 --- /dev/null +++ b/solutions/927. Three Equal Parts/927.py @@ -0,0 +1,43 @@ +class Solution: + def threeEqualParts(self, arr: List[int]) -> List[int]: + ones = sum(a == 1 for a in arr) + + if ones == 0: + return [0, len(arr) - 1] + if ones % 3 != 0: + return [-1, -1] + + k = ones // 3 + i = 0 + + for i in range(len(arr)): + if arr[i] == 1: + first = i + break + + gapOnes = k + + for j in range(i + 1, len(arr)): + if arr[j] == 1: + gapOnes -= 1 + if gapOnes == 0: + second = j + break + + gapOnes = k + + for i in range(j + 1, len(arr)): + if arr[i] == 1: + gapOnes -= 1 + if gapOnes == 0: + third = i + break + + while third < len(arr) and arr[first] == arr[second] == arr[third]: + first += 1 + second += 1 + third += 1 + + if third == len(arr): + return [first - 1, second] + return [-1, -1] diff --git a/solutions/928. Minimize Malware Spread II/928.cpp b/solutions/928. Minimize Malware Spread II/928.cpp new file mode 100644 index 00000000000..65c9b321c8e --- /dev/null +++ b/solutions/928. Minimize Malware Spread II/928.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + int minMalwareSpread(vector>& graph, vector& initial) { + int ans = 0; + int minCount = graph.size(); + + ranges::sort(initial); + + for (const int i : initial) { + const int count = bfs(graph, i, initial); + if (count < minCount) { + minCount = count; + ans = i; + } + } + + return ans; + } + + private: + int bfs(const vector>& graph, int removed, vector& initial) { + queue q; + vector seen(graph.size()); + seen[removed] = true; + + int count = 0; + + for (const int i : initial) + if (i != removed) { + q.push(i); + seen[i] = true; + } + + while (!q.empty()) { + const int u = q.front(); + q.pop(); + ++count; + for (int i = 0; i < graph.size(); ++i) { + if (seen[i]) + continue; + if (i != u && graph[i][u]) { + q.push(i); + seen[i] = true; + } + } + } + + return count; + } +}; diff --git a/solutions/928. Minimize Malware Spread II/928.java b/solutions/928. Minimize Malware Spread II/928.java new file mode 100644 index 00000000000..3e92134ede3 --- /dev/null +++ b/solutions/928. Minimize Malware Spread II/928.java @@ -0,0 +1,47 @@ +class Solution { + public int minMalwareSpread(int[][] graph, int[] initial) { + int ans = 0; + int minCount = graph.length; + + Arrays.sort(initial); + + for (final int i : initial) { + final int count = bfs(graph, i, initial); + if (count < minCount) { + minCount = count; + ans = i; + } + } + + return ans; + } + + private int bfs(int[][] graph, int removed, int[] initial) { + Queue q = new ArrayDeque<>(); + boolean[] seen = new boolean[graph.length]; + seen[removed] = true; + + int count = 0; + + for (final int i : initial) + if (i != removed) { + q.offer(i); + seen[i] = true; + } + + while (!q.isEmpty()) { + final int u = q.poll(); + ++count; + for (int i = 0; i < graph.length; ++i) { + if (seen[i]) + continue; + if (i != u && graph[i][u] == 1) { + q.offer(i); + seen[i] = true; + } + } + } + + return count; + } +} diff --git a/solutions/929. Unique Email Addresses/929.cpp b/solutions/929. Unique Email Addresses/929.cpp new file mode 100644 index 00000000000..94750fe7a7c --- /dev/null +++ b/solutions/929. Unique Email Addresses/929.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int numUniqueEmails(vector& emails) { + unordered_set normalized; + + for (const string& email : emails) { + string local; + for (const char c : email) { + if (c == '+' || c == '@') + break; + if (c == '.') + continue; + local += c; + } + string atDomain = email.substr(email.find('@')); + normalized.insert(local + atDomain); + } + + return normalized.size(); + } +}; diff --git a/solutions/929. Unique Email Addresses/929.java b/solutions/929. Unique Email Addresses/929.java new file mode 100644 index 00000000000..8aa3da1c1f5 --- /dev/null +++ b/solutions/929. Unique Email Addresses/929.java @@ -0,0 +1,13 @@ +class Solution { + public int numUniqueEmails(String[] emails) { + Set normalized = new HashSet<>(); + + for (final String email : emails) { + String[] parts = email.split("@"); + String[] local = parts[0].split("\\+"); + normalized.add(local[0].replace(".", "") + "@" + parts[1]); + } + + return normalized.size(); + } +} diff --git a/solutions/929. Unique Email Addresses/929.py b/solutions/929. Unique Email Addresses/929.py new file mode 100644 index 00000000000..2c10dfd4463 --- /dev/null +++ b/solutions/929. Unique Email Addresses/929.py @@ -0,0 +1,10 @@ +class Solution: + def numUniqueEmails(self, emails: List[str]) -> int: + seen = set() + + for email in emails: + local, domain = email.split('@') + local = local.split('+')[0].replace('.', '') + seen.add(local + '@' + domain) + + return len(seen) diff --git a/solutions/93. Restore IP Addresses/93.cpp b/solutions/93. Restore IP Addresses/93.cpp new file mode 100644 index 00000000000..264efb55c57 --- /dev/null +++ b/solutions/93. Restore IP Addresses/93.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector restoreIpAddresses(const string& s) { + vector ans; + dfs(s, 0, {}, ans); + return ans; + } + + private: + void dfs(const string& s, int start, vector&& path, + vector& ans) { + if (path.size() == 4 && start == s.length()) { + ans.push_back(path[0] + "." + path[1] + "." + path[2] + "." + path[3]); + return; + } + if (path.size() == 4 || start == s.length()) + return; + + for (int length = 1; length <= 3; ++length) { + if (start + length > s.length()) + return; // out-of-bounds + if (length > 1 && s[start] == '0') + return; // leading '0' + const string& num = s.substr(start, length); + if (stoi(num) > 255) + return; + path.push_back(num); + dfs(s, start + length, move(path), ans); + path.pop_back(); + } + } +}; diff --git a/solutions/93. Restore IP Addresses/93.java b/solutions/93. Restore IP Addresses/93.java new file mode 100644 index 00000000000..2c7c568e413 --- /dev/null +++ b/solutions/93. Restore IP Addresses/93.java @@ -0,0 +1,29 @@ +class Solution { + public List restoreIpAddresses(final String s) { + List ans = new ArrayList<>(); + dfs(s, 0, new ArrayList<>(), ans); + return ans; + } + + private void dfs(final String s, int start, List path, List ans) { + if (path.size() == 4 && start == s.length()) { + ans.add(String.join(".", path)); + return; + } + if (path.size() == 4 || start == s.length()) + return; + + for (int length = 1; length <= 3; ++length) { + if (start + length > s.length()) // out-of-bounds + return; + if (length > 1 && s.charAt(start) == '0') // leading '0' + return; + final String num = s.substring(start, start + length); + if (Integer.parseInt(num) > 255) + return; + path.add(num); + dfs(s, start + length, path, ans); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/93. Restore IP Addresses/93.py b/solutions/93. Restore IP Addresses/93.py new file mode 100644 index 00000000000..7ee9ae04b4b --- /dev/null +++ b/solutions/93. Restore IP Addresses/93.py @@ -0,0 +1,23 @@ +class Solution: + def restoreIpAddresses(self, s: str) -> List[str]: + ans = [] + + def dfs(start: int, path: List[int]) -> None: + if len(path) == 4 and start == len(s): + ans.append(path[0] + '.' + path[1] + '.' + path[2] + '.' + path[3]) + return + if len(path) == 4 or start == len(s): + return + + for length in range(1, 4): + if start + length > len(s): + return # out-of-bounds + if length > 1 and s[start] == '0': + return # leading '0' + num = s[start: start + length] + if int(num) > 255: + return + dfs(start + length, path + [num]) + + dfs(0, []) + return ans diff --git a/solutions/930. Binary Subarrays With Sum/930-2.cpp b/solutions/930. Binary Subarrays With Sum/930-2.cpp new file mode 100644 index 00000000000..0180972bc69 --- /dev/null +++ b/solutions/930. Binary Subarrays With Sum/930-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int numSubarraysWithSum(vector& nums, int goal) { + return numSubarraysWithSumAtMost(nums, goal) - + numSubarraysWithSumAtMost(nums, goal - 1); + } + + private: + int numSubarraysWithSumAtMost(const vector& nums, int goal) { + int res = 0; + int count = 0; + for (int l = 0, r = 0; r < nums.size();) { + count += nums[r++]; + while (l < r && count > goal) + count -= nums[l++]; + // nums[l..r), nums[l + 1..r), ..., nums[r - 1] + res += r - l; + } + return res; + } +}; diff --git a/solutions/930. Binary Subarrays With Sum/930-2.java b/solutions/930. Binary Subarrays With Sum/930-2.java new file mode 100644 index 00000000000..706366c4fb3 --- /dev/null +++ b/solutions/930. Binary Subarrays With Sum/930-2.java @@ -0,0 +1,18 @@ +class Solution { + public int numSubarraysWithSum(int[] nums, int goal) { + return numSubarraysWithSumAtMost(nums, goal) - numSubarraysWithSumAtMost(nums, goal - 1); + } + + private int numSubarraysWithSumAtMost(int[] nums, int goal) { + int res = 0; + int count = 0; + for (int l = 0, r = 0; r < nums.length;) { + count += nums[r++]; + while (l < r && count > goal) + count -= nums[l++]; + // nums[l..r), nums[l + 1..r), ..., nums[r - 1] + res += r - l; + } + return res; + } +} diff --git a/solutions/930. Binary Subarrays With Sum/930-2.py b/solutions/930. Binary Subarrays With Sum/930-2.py new file mode 100644 index 00000000000..c8924bd1a7c --- /dev/null +++ b/solutions/930. Binary Subarrays With Sum/930-2.py @@ -0,0 +1,20 @@ +class Solution: + def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: + def numSubarraysWithSumAtMost(goal: int) -> int: + res = 0 + count = 0 + l = 0 + r = 0 + + while r < len(nums): + count += nums[r] + r += 1 + while l < r and count > goal: + count -= nums[l] + l += 1 + # nums[l..r), nums[l + 1..r), ..., nums[r - 1] + res += r - l + + return res + + return numSubarraysWithSumAtMost(goal) - numSubarraysWithSumAtMost(goal - 1) diff --git a/solutions/930. Binary Subarrays With Sum/930.cpp b/solutions/930. Binary Subarrays With Sum/930.cpp new file mode 100644 index 00000000000..4f4706aa91c --- /dev/null +++ b/solutions/930. Binary Subarrays With Sum/930.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int numSubarraysWithSum(vector& nums, int goal) { + int ans = 0; + int prefix = 0; + // {prefix: number of occurrence} + unordered_map count{{0, 1}}; + + for (const int num : nums) { + prefix += num; + if (const auto it = count.find(prefix - goal); it != count.cend()) + ans += it->second; + ++count[prefix]; + } + + return ans; + } +}; diff --git a/solutions/930. Binary Subarrays With Sum/930.java b/solutions/930. Binary Subarrays With Sum/930.java new file mode 100644 index 00000000000..be12ea72b93 --- /dev/null +++ b/solutions/930. Binary Subarrays With Sum/930.java @@ -0,0 +1,19 @@ +class Solution { + public int numSubarraysWithSum(int[] nums, int goal) { + int ans = 0; + int prefix = 0; + // {prefix: number of occurrence} + Map count = new HashMap<>(); + count.put(0, 1); + + for (final int num : nums) { + prefix += num; + final int key = prefix - goal; + if (count.containsKey(key)) + ans += count.get(key); + count.merge(prefix, 1, Integer::sum); + } + + return ans; + } +} diff --git a/solutions/930. Binary Subarrays With Sum/930.py b/solutions/930. Binary Subarrays With Sum/930.py new file mode 100644 index 00000000000..54d21ed23b7 --- /dev/null +++ b/solutions/930. Binary Subarrays With Sum/930.py @@ -0,0 +1,13 @@ +class Solution: + def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: + ans = 0 + prefix = 0 + # {prefix: number of occurrence} + count = collections.Counter({0: 1}) + + for num in nums: + prefix += num + ans += count[prefix - goal] + count[prefix] += 1 + + return ans diff --git a/solutions/931. Minimum Falling Path Sum/931.cpp b/solutions/931. Minimum Falling Path Sum/931.cpp new file mode 100644 index 00000000000..a84e1ab48e8 --- /dev/null +++ b/solutions/931. Minimum Falling Path Sum/931.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minFallingPathSum(vector>& A) { + const int n = A.size(); + + for (int i = 1; i < n; ++i) + for (int j = 0; j < n; ++j) { + int mn = INT_MAX; + for (int k = max(0, j - 1); k < min(n, j + 2); ++k) + mn = min(mn, A[i - 1][k]); + A[i][j] += mn; + } + + return ranges::min(A[n - 1]); + } +}; diff --git a/solutions/931. Minimum Falling Path Sum/931.java b/solutions/931. Minimum Falling Path Sum/931.java new file mode 100644 index 00000000000..01595444951 --- /dev/null +++ b/solutions/931. Minimum Falling Path Sum/931.java @@ -0,0 +1,15 @@ +class Solution { + public int minFallingPathSum(int[][] A) { + final int n = A.length; + + for (int i = 1; i < n; ++i) + for (int j = 0; j < n; ++j) { + int mn = Integer.MAX_VALUE; + for (int k = Math.max(0, j - 1); k < Math.min(n, j + 2); ++k) + mn = Math.min(mn, A[i - 1][k]); + A[i][j] += mn; + } + + return Arrays.stream(A[n - 1]).min().getAsInt(); + } +} diff --git a/solutions/931. Minimum Falling Path Sum/931.py b/solutions/931. Minimum Falling Path Sum/931.py new file mode 100644 index 00000000000..23adbdc2794 --- /dev/null +++ b/solutions/931. Minimum Falling Path Sum/931.py @@ -0,0 +1,12 @@ +class Solution: + def minFallingPathSum(self, A: List[List[int]]) -> int: + n = len(A) + + for i in range(1, n): + for j in range(n): + mn = math.inf + for k in range(max(0, j - 1), min(n, j + 2)): + mn = min(mn, A[i - 1][k]) + A[i][j] += mn + + return min(A[-1]) diff --git a/solutions/932. Beautiful Array/932.cpp b/solutions/932. Beautiful Array/932.cpp new file mode 100644 index 00000000000..b26c04964b0 --- /dev/null +++ b/solutions/932. Beautiful Array/932.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector beautifulArray(int n) { + vector A(n); + iota(A.begin(), A.end(), 1); + divide(A, 0, n - 1, 1); + return A; + } + + private: + void divide(vector& A, int l, int r, int mask) { + if (l >= r) + return; + const int m = partition(A, l, r, mask); + divide(A, l, m, mask << 1); + divide(A, m + 1, r, mask << 1); + } + + int partition(vector& A, int l, int r, int mask) { + int nextSwapped = l; + for (int i = l; i <= r; ++i) + if (A[i] & mask) + swap(A[i], A[nextSwapped++]); + return nextSwapped - 1; + } +}; diff --git a/solutions/932. Beautiful Array/932.java b/solutions/932. Beautiful Array/932.java new file mode 100644 index 00000000000..0d33997a2b0 --- /dev/null +++ b/solutions/932. Beautiful Array/932.java @@ -0,0 +1,31 @@ +class Solution { + public int[] beautifulArray(int n) { + int[] A = new int[n]; + for (int i = 0; i < n; ++i) + A[i] = i + 1; + divide(A, 0, n - 1, 1); + return A; + } + + private void divide(int[] A, int l, int r, int mask) { + if (l >= r) + return; + final int m = partition(A, l, r, mask); + divide(A, l, m, mask << 1); + divide(A, m + 1, r, mask << 1); + } + + private int partition(int[] A, int l, int r, int mask) { + int nextSwapped = l; + for (int i = l; i <= r; ++i) + if ((A[i] & mask) > 0) + swap(A, i, nextSwapped++); + return nextSwapped - 1; + } + + private void swap(int[] A, int i, int j) { + final int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} diff --git a/solutions/932. Beautiful Array/932.py b/solutions/932. Beautiful Array/932.py new file mode 100644 index 00000000000..0c2c20e5244 --- /dev/null +++ b/solutions/932. Beautiful Array/932.py @@ -0,0 +1,21 @@ +class Solution: + def beautifulArray(self, n: int) -> List[int]: + A = [i for i in range(1, n + 1)] + + def partition(l: int, r: int, mask: int) -> int: + nextSwapped = l + for i in range(l, r + 1): + if A[i] & mask: + A[i], A[nextSwapped] = A[nextSwapped], A[i] + nextSwapped += 1 + return nextSwapped - 1 + + def divide(l: int, r: int, mask: int) -> None: + if l >= r: + return + m = partition(l, r, mask) + divide(l, m, mask << 1) + divide(m + 1, r, mask << 1) + + divide(0, n - 1, 1) + return A diff --git a/solutions/933. Number of Recent Calls/933.cpp b/solutions/933. Number of Recent Calls/933.cpp new file mode 100644 index 00000000000..8051d51fa0e --- /dev/null +++ b/solutions/933. Number of Recent Calls/933.cpp @@ -0,0 +1,12 @@ +class RecentCounter { + public: + int ping(int t) { + q.push(t); + while (q.front() < t - 3000) + q.pop(); + return q.size(); + } + + private: + queue q; +}; diff --git a/solutions/933. Number of Recent Calls/933.java b/solutions/933. Number of Recent Calls/933.java new file mode 100644 index 00000000000..5481da8f632 --- /dev/null +++ b/solutions/933. Number of Recent Calls/933.java @@ -0,0 +1,10 @@ +class RecentCounter { + public int ping(int t) { + q.offer(t); + while (q.peek() < t - 3000) + q.poll(); + return q.size(); + } + + private Queue q = new LinkedList<>(); +} diff --git a/solutions/933. Number of Recent Calls/933.py b/solutions/933. Number of Recent Calls/933.py new file mode 100644 index 00000000000..7fdc2028ab1 --- /dev/null +++ b/solutions/933. Number of Recent Calls/933.py @@ -0,0 +1,9 @@ +class RecentCounter: + def __init__(self): + self.q = collections.deque() + + def ping(self, t: int) -> int: + self.q.append(t) + while self.q[0] < t - 3000: + self.q.popleft() + return len(self.q) diff --git a/solutions/934. Shortest Bridge/934-2.cpp b/solutions/934. Shortest Bridge/934-2.cpp new file mode 100644 index 00000000000..6143dc5d8ca --- /dev/null +++ b/solutions/934. Shortest Bridge/934-2.cpp @@ -0,0 +1,56 @@ +class Solution { + public: + int shortestBridge(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int n = grid.size(); + queue> q; + + markGridTwo(grid, q); + + for (int ans = 0; !q.empty(); ++ans) + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (grid[x][y] == 2) + continue; + if (grid[x][y] == 1) + return ans; + grid[x][y] = 2; + q.emplace(x, y); + } + } + + throw; + } + + private: + // Marks one group to 2s by DFS. + void markGridTwo(vector>& grid, queue>& q) { + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == 1) { + markGridTwo(grid, i, j, q); + return; + } + } + + // Marks one group to 2s by DFS and pushes them to the queue. + void markGridTwo(vector>& grid, int i, int j, + queue>& q) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] != 1) + return; + grid[i][j] = 2; + q.emplace(i, j); + markGridTwo(grid, i + 1, j, q); + markGridTwo(grid, i - 1, j, q); + markGridTwo(grid, i, j + 1, q); + markGridTwo(grid, i, j - 1, q); + } +}; diff --git a/solutions/934. Shortest Bridge/934-2.java b/solutions/934. Shortest Bridge/934-2.java new file mode 100644 index 00000000000..86b2d3cf904 --- /dev/null +++ b/solutions/934. Shortest Bridge/934-2.java @@ -0,0 +1,53 @@ +class Solution { + public int shortestBridge(int[][] grid) { + final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + final int n = grid.length; + Queue q = new ArrayDeque<>(); + + markGridTwo(grid, q); + + for (int ans = 0; !q.isEmpty(); ++ans) + for (int sz = q.size(); sz > 0; --sz) { + final int i = q.peek()[0]; + final int j = q.poll()[1]; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x == n || y < 0 || y == n) + continue; + if (grid[x][y] == 2) + continue; + if (grid[x][y] == 1) + return ans; + grid[x][y] = 2; + q.offer(new int[] {x, y}); + } + } + + throw new IllegalArgumentException(); + } + + // Marks one group to 2s by DFS. + private void markGridTwo(int[][] grid, Queue q) { + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 1) { + markGridTwo(grid, i, j, q); + return; + } + } + + // Marks one group to 2s by DFS and pushes them to the queue. + private void markGridTwo(int[][] grid, int i, int j, Queue q) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] != 1) + return; + grid[i][j] = 2; + q.offer(new int[] {i, j}); + markGridTwo(grid, i + 1, j, q); + markGridTwo(grid, i - 1, j, q); + markGridTwo(grid, i, j + 1, q); + markGridTwo(grid, i, j - 1, q); + } +} diff --git a/solutions/934. Shortest Bridge/934.cpp b/solutions/934. Shortest Bridge/934.cpp new file mode 100644 index 00000000000..f64f184effc --- /dev/null +++ b/solutions/934. Shortest Bridge/934.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int shortestBridge(vector>& grid) { + markGridTwo(grid); + + for (int color = 2;; ++color) + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == color) + if (expand(grid, i + 1, j, color) || // + expand(grid, i - 1, j, color) || // + expand(grid, i, j + 1, color) || // + expand(grid, i, j - 1, color)) + return color - 2; + } + + private: + // Marks one group to 2s by DFS. + void markGridTwo(vector>& grid) { + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == 1) { + markGridTwo(grid, i, j); + return; + } + } + + void markGridTwo(vector>& grid, int i, int j) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] != 1) + return; + grid[i][j] = 2; + markGridTwo(grid, i + 1, j); + markGridTwo(grid, i - 1, j); + markGridTwo(grid, i, j + 1); + markGridTwo(grid, i, j - 1); + } + + // Returns true if we touch 1s' group through expanding. + bool expand(vector>& grid, int i, int j, int color) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return false; + if (grid[i][j] == 0) + grid[i][j] = color + 1; + return grid[i][j] == 1; + } +}; diff --git a/solutions/934. Shortest Bridge/934.java b/solutions/934. Shortest Bridge/934.java new file mode 100644 index 00000000000..d5f33ac6d9b --- /dev/null +++ b/solutions/934. Shortest Bridge/934.java @@ -0,0 +1,44 @@ +class Solution { + public int shortestBridge(int[][] grid) { + markGridTwo(grid); + + for (int color = 2;; ++color) + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == color) + if (expand(grid, i + 1, j, color) || expand(grid, i - 1, j, color) || + expand(grid, i, j + 1, color) || expand(grid, i, j - 1, color)) + return color - 2; + } + + // Marks one group to 2s by DFS. + private void markGridTwo(int[][] grid) { + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 1) { + markGridTwo(grid, i, j); + return; + } + } + + private void markGridTwo(int[][] grid, int i, int j) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] != 1) + return; + grid[i][j] = 2; + markGridTwo(grid, i + 1, j); + markGridTwo(grid, i - 1, j); + markGridTwo(grid, i, j + 1); + markGridTwo(grid, i, j - 1); + } + + // Returns true if we touch 1s' group through expanding. + private boolean expand(int[][] grid, int i, int j, int color) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return false; + if (grid[i][j] == 0) + grid[i][j] = color + 1; + return grid[i][j] == 1; + } +} diff --git a/solutions/935. Knight Dialer/935.cpp b/solutions/935. Knight Dialer/935.cpp new file mode 100644 index 00000000000..0a69fd5504d --- /dev/null +++ b/solutions/935. Knight Dialer/935.cpp @@ -0,0 +1,44 @@ +class Solution { + public: + int knightDialer(int n) { + constexpr int dirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, + {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; + constexpr int kMod = 1'000'000'007; + + // dp[i][j] := the number of ways to stand on (i, j) + vector> dp(4, vector(3, 1)); + dp[3][0] = dp[3][2] = 0; + + for (int k = 0; k < n - 1; ++k) { + vector> newDp(4, vector(3)); + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 3; ++j) { + if (isNotNumericCell(i, j)) + continue; + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x >= 4 || y < 0 || y >= 3) + continue; + if (isNotNumericCell(x, y)) + continue; + newDp[i][j] = (newDp[i][j] + dp[x][y]) % kMod; + } + } + dp = move(newDp); + } + + int ans = 0; + + for (const vector& row : dp) + for (const int a : row) + ans = (ans + a) % kMod; + + return ans; + } + + private: + bool isNotNumericCell(int i, int j) { + return i == 3 && (j == 0 || j == 2); + } +}; diff --git a/solutions/935. Knight Dialer/935.java b/solutions/935. Knight Dialer/935.java new file mode 100644 index 00000000000..4b0bff0c1e7 --- /dev/null +++ b/solutions/935. Knight Dialer/935.java @@ -0,0 +1,41 @@ +class Solution { + public int knightDialer(int n) { + final int[][] dirs = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; + final int kMod = 1_000_000_007; + // dp[i][j] := the number of ways to stand on (i, j) + int[][] dp = new int[4][3]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, 1)); + dp[3][0] = dp[3][2] = 0; + + for (int k = 0; k < n - 1; ++k) { + int[][] newDp = new int[4][3]; + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 3; ++j) { + if (isNotNumericCell(i, j)) + continue; + for (int[] dir : dirs) { + final int x = i + dir[0]; + final int y = j + dir[1]; + if (x < 0 || x >= 4 || y < 0 || y >= 3) + continue; + if (isNotNumericCell(x, y)) + continue; + newDp[i][j] = (newDp[i][j] + dp[x][y]) % kMod; + } + } + dp = newDp; + } + + int ans = 0; + + for (int[] row : dp) + for (final int a : row) + ans = (ans + a) % kMod; + + return ans; + } + + private boolean isNotNumericCell(int i, int j) { + return i == 3 && (j == 0 || j == 2); + } +} diff --git a/solutions/935. Knight Dialer/935.py b/solutions/935. Knight Dialer/935.py new file mode 100644 index 00000000000..92ed72f56ed --- /dev/null +++ b/solutions/935. Knight Dialer/935.py @@ -0,0 +1,27 @@ +class Solution: + def knightDialer(self, n: int) -> int: + dirs = ((1, 2), (2, 1), (2, -1), (1, -2), + (-1, -2), (-2, -1), (-2, 1), (-1, 2)) + kMod = 1_000_000_007 + + # dp[i][j] := the number of ways stand on (i, j) + dp = [[1] * 3 for _ in range(4)] + dp[3][0] = dp[3][2] = 0 + + for _ in range(n - 1): + newDp = [[0] * 3 for _ in range(4)] + for i in range(4): + for j in range(3): + if (i, j) in ((3, 0), (3, 2)): + continue + for dx, dy in dirs: + x = i + dx + y = j + dy + if x < 0 or x >= 4 or y < 0 or y >= 3: + continue + if (x, y) in ((3, 0), (3, 2)): + continue + newDp[x][y] = (newDp[x][y] + dp[i][j]) % kMod + dp = newDp + + return sum(map(sum, dp)) % kMod diff --git a/solutions/936. Stamping The Sequence/936.cpp b/solutions/936. Stamping The Sequence/936.cpp new file mode 100644 index 00000000000..3c5e1fb06d0 --- /dev/null +++ b/solutions/936. Stamping The Sequence/936.cpp @@ -0,0 +1,50 @@ +class Solution { + public: + vector movesToStamp(string stamp, string target) { + vector ans; + // stamped[i] := true if we already stamped target by stamping on index i + vector stamped(target.length()); + int stampedCount = 0; // Our goal is to make stampedCount = |target|. + + while (stampedCount < target.length()) { + bool isStamped = false; + // Try to stamp target[i..i + |stamp|) for each index. + for (int i = 0; i <= target.length() - stamp.length(); ++i) { + if (stamped[i]) + continue; + const int stampified = stampify(stamp, target, i); + if (stampified == 0) + continue; + stampedCount += stampified; + isStamped = true; + stamped[i] = true; + ans.push_back(i); + } + // After trying to stamp on each index, we can't find a valid stamp. + if (!isStamped) + return {}; + } + + reverse(ans.begin(), ans.end()); + return ans; + } + + private: + // Stamps target[i..i + |stamp|) and returns the number of newly stamped + // characters. + // e.g. stampify("abc", "ababc", 2) returns 3 because target becomes "ab***". + int stampify(const string& stamp, string& target, int s) { + int stampified = stamp.length(); + + for (int i = 0; i < stamp.length(); ++i) + if (target[s + i] == '*') // It's already been stamped. + --stampified; + else if (target[s + i] != stamp[i]) + return 0; // We can't stamp on the index i. + + if (stampified > 0) + fill(target.begin() + s, target.begin() + s + stamp.length(), '*'); + + return stampified; + } +}; diff --git a/solutions/936. Stamping The Sequence/936.java b/solutions/936. Stamping The Sequence/936.java new file mode 100644 index 00000000000..130d7f071f7 --- /dev/null +++ b/solutions/936. Stamping The Sequence/936.java @@ -0,0 +1,48 @@ +class Solution { + public int[] movesToStamp(String stamp, String target) { + List ans = new ArrayList<>(); + char[] T = target.toCharArray(); + // stamped[i] := true if we already stamped target by stamping on index i + boolean[] stamped = new boolean[target.length()]; + int stampedCount = 0; // Our goal is to make stampedCount = |target|. + + while (stampedCount < T.length) { + boolean isStamped = false; + // Try to stamp target[i..i + |stamp|) for each index. + for (int i = 0; i <= T.length - stamp.length(); ++i) { + if (stamped[i]) + continue; + final int stampified = stampify(stamp, T, i); + if (stampified == 0) + continue; + stampedCount += stampified; + isStamped = true; + stamped[i] = true; + ans.add(i); + } + // After trying to stamp on each index, we can't find a valid stamp. + if (!isStamped) + return new int[] {}; + } + + Collections.reverse(ans); + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + // Stamps target[i..i + |stamp|) and returns the number of newly stamped + // characters. + // e.g. stampify("abc", "ababc", 2) returns 3 because target becomes "ab***". + private int stampify(final String stamp, char[] T, int s) { + int stampified = stamp.length(); + + for (int i = 0; i < stamp.length(); ++i) + if (T[s + i] == '*') // It's already been stamped. + --stampified; + else if (T[s + i] != stamp.charAt(i)) + return 0; // We can't stamp on the index i. + + Arrays.fill(T, s, s + stamp.length(), '*'); + + return stampified; + } +} diff --git a/solutions/936. Stamping The Sequence/936.py b/solutions/936. Stamping The Sequence/936.py new file mode 100644 index 00000000000..58b7f417d4e --- /dev/null +++ b/solutions/936. Stamping The Sequence/936.py @@ -0,0 +1,45 @@ +class Solution: + def movesToStamp(self, stamp: str, target: str) -> List[int]: + def stampify(s: int) -> int: + """ + Stamps target[i..i + |stamp|) and returns the number of newly stamped + characters. + e.g. stampify("abc", "ababc", 2) returns 3 because target becomes "ab***". + """ + stampified = len(stamp) + + for i, st in enumerate(stamp): + if target[s + i] == '*': # It's already been stamped. + stampified -= 1 + elif target[s + i] != st: # We can't stamp on the index i. + return 0 + + for i in range(s, s + len(stamp)): + target[i] = '*' + + return stampified + + ans = [] + target = list(target) + # stamped[i] := True if we already stamped target by stamping on index i + stamped = [False] * len(target) + stampedCount = 0 # Our goal is to make stampedCount = |target|. + + while stampedCount < len(target): + isStamped = False + # Try to stamp target[i..i + |stamp|) for each index. + for i in range(len(target) - len(stamp) + 1): + if stamped[i]: + continue + stampified = stampify(i) + if stampified == 0: + continue + stampedCount += stampified + isStamped = True + stamped[i] = True + ans.append(i) + # After trying to stamp on each index, we can't find a valid stamp. + if not isStamped: + return [] + + return ans[::-1] diff --git a/solutions/937. Reorder Data in Log Files/937.cpp b/solutions/937. Reorder Data in Log Files/937.cpp new file mode 100644 index 00000000000..2367e5b747b --- /dev/null +++ b/solutions/937. Reorder Data in Log Files/937.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + vector reorderLogFiles(vector& logs) { + vector ans; + vector digitLogs; + vector> letterLogs; + + for (const string& log : logs) { + const int i = log.find_first_of(' '); + if (isdigit(log[i + 1])) + digitLogs.push_back(log); + else + letterLogs.emplace_back(log.substr(0, i), log.substr(i + 1)); + } + + ranges::sort(letterLogs, [](const pair& a, + const pair& b) { + return a.second == b.second ? a.first < b.first : a.second < b.second; + }); + + for (const auto& [identifier, letters] : letterLogs) + ans.push_back(identifier + ' ' + letters); + + for (const string& digitLog : digitLogs) + ans.push_back(digitLog); + + return ans; + } +}; diff --git a/solutions/937. Reorder Data in Log Files/937.java b/solutions/937. Reorder Data in Log Files/937.java new file mode 100644 index 00000000000..6ffe07a6e57 --- /dev/null +++ b/solutions/937. Reorder Data in Log Files/937.java @@ -0,0 +1,30 @@ +class Solution { + public String[] reorderLogFiles(String[] logs) { + List ans = new ArrayList<>(); + List digitLogs = new ArrayList<>(); + List letterLogs = new ArrayList<>(); + + for (final String log : logs) { + final int i = log.indexOf(' '); + if (Character.isDigit(log.charAt(i + 1))) + digitLogs.add(log); + else + letterLogs.add(new String[] {log.substring(0, i), log.substring(i + 1)}); + } + + Collections.sort(letterLogs, new Comparator() { + @Override + public int compare(String[] l1, String[] l2) { + return l1[1].compareTo(l2[1]) == 0 ? l1[0].compareTo(l2[0]) : l1[1].compareTo(l2[1]); + } + }); + + for (String[] letterLog : letterLogs) + ans.add(letterLog[0] + " " + letterLog[1]); + + for (final String digitLog : digitLogs) + ans.add(digitLog); + + return ans.toArray(new String[0]); + } +} diff --git a/solutions/937. Reorder Data in Log Files/937.py b/solutions/937. Reorder Data in Log Files/937.py new file mode 100644 index 00000000000..f860fcbbd46 --- /dev/null +++ b/solutions/937. Reorder Data in Log Files/937.py @@ -0,0 +1,15 @@ +class Solution: + def reorderLogFiles(self, logs: List[str]) -> List[str]: + digitLogs = [] + letterLogs = [] + + for log in logs: + i = log.index(' ') + if log[i + 1].isdigit(): + digitLogs.append(log) + else: + letterLogs.append((log[:i], log[i + 1:])) + + letterLogs.sort(key=lambda l: (l[1], l[0])) + + return [identifier + ' ' + letters for identifier, letters in letterLogs] + digitLogs diff --git a/solutions/938. Range Sum of BST/938.cpp b/solutions/938. Range Sum of BST/938.cpp new file mode 100644 index 00000000000..33f62b77cf3 --- /dev/null +++ b/solutions/938. Range Sum of BST/938.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int rangeSumBST(TreeNode* root, int L, int R) { + if (root == nullptr) + return 0; + if (root->val < L) + return rangeSumBST(root->right, L, R); + if (root->val > R) + return rangeSumBST(root->left, L, R); + return root->val + rangeSumBST(root->left, L, R) + + rangeSumBST(root->right, L, R); + } +}; diff --git a/solutions/938. Range Sum of BST/938.java b/solutions/938. Range Sum of BST/938.java new file mode 100644 index 00000000000..ddbf683ca3b --- /dev/null +++ b/solutions/938. Range Sum of BST/938.java @@ -0,0 +1,11 @@ +class Solution { + public int rangeSumBST(TreeNode root, int L, int R) { + if (root == null) + return 0; + if (root.val < L) + return rangeSumBST(root.right, L, R); + if (root.val > R) + return rangeSumBST(root.left, L, R); + return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R); + } +} diff --git a/solutions/939. Minimum Area Rectangle/939.cpp b/solutions/939. Minimum Area Rectangle/939.cpp new file mode 100644 index 00000000000..abf1f4181cc --- /dev/null +++ b/solutions/939. Minimum Area Rectangle/939.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + int minAreaRect(vector>& points) { + int ans = INT_MAX; + unordered_map> xToYs; + + for (const vector& p : points) + xToYs[p[0]].insert(p[1]); + + for (int i = 1; i < points.size(); ++i) + for (int j = 0; j < i; ++j) { + const vector& p = points[i]; + const vector& q = points[j]; + if (p[0] == q[0] || p[1] == q[1]) + continue; + if (xToYs[p[0]].contains(q[1]) && xToYs[q[0]].contains(p[1])) + ans = min(ans, abs(p[0] - q[0]) * abs(p[1] - q[1])); + } + + return ans == INT_MAX ? 0 : ans; + } +}; diff --git a/solutions/939. Minimum Area Rectangle/939.java b/solutions/939. Minimum Area Rectangle/939.java new file mode 100644 index 00000000000..854aeae46e7 --- /dev/null +++ b/solutions/939. Minimum Area Rectangle/939.java @@ -0,0 +1,23 @@ +class Solution { + public int minAreaRect(int[][] points) { + int ans = Integer.MAX_VALUE; + Map> xToYs = new HashMap<>(); + + for (int[] p : points) { + xToYs.putIfAbsent(p[0], new HashSet<>()); + xToYs.get(p[0]).add(p[1]); + } + + for (int i = 1; i < points.length; ++i) + for (int j = 0; j < i; ++j) { + int[] p = points[i]; + int[] q = points[j]; + if (p[0] == q[0] || p[1] == q[1]) + continue; + if (xToYs.get(p[0]).contains(q[1]) && xToYs.get(q[0]).contains(p[1])) + ans = Math.min(ans, Math.abs(p[0] - q[0]) * Math.abs(p[1] - q[1])); + } + + return ans == Integer.MAX_VALUE ? 0 : ans; + } +} diff --git a/solutions/939. Minimum Area Rectangle/939.py b/solutions/939. Minimum Area Rectangle/939.py new file mode 100644 index 00000000000..a861d9d19c5 --- /dev/null +++ b/solutions/939. Minimum Area Rectangle/939.py @@ -0,0 +1,18 @@ +class Solution: + def minAreaRect(self, points: List[List[int]]) -> int: + ans = math.inf + xToYs = collections.defaultdict(set) + + for x, y in points: + xToYs[x].add(y) + + for i in range(len(points)): + for j in range(i): + x1, y1 = points[i] + x2, y2 = points[j] + if x1 == x2 or y1 == y2: + continue + if y2 in xToYs[x1] and y1 in xToYs[x2]: + ans = min(ans, abs(x1 - x2) * abs(y1 - y2)) + + return ans if ans < math.inf else 0 diff --git a/solutions/94. Binary Tree Inorder Traversal/94.cpp b/solutions/94. Binary Tree Inorder Traversal/94.cpp new file mode 100644 index 00000000000..529c9adc3ed --- /dev/null +++ b/solutions/94. Binary Tree Inorder Traversal/94.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + vector inorderTraversal(TreeNode* root) { + vector ans; + stack stack; + + while (root || !stack.empty()) { + while (root) { + stack.push(root); + root = root->left; + } + root = stack.top(), stack.pop(); + ans.push_back(root->val); + root = root->right; + } + + return ans; + } +}; diff --git a/solutions/94. Binary Tree Inorder Traversal/94.java b/solutions/94. Binary Tree Inorder Traversal/94.java new file mode 100644 index 00000000000..48dfc8416af --- /dev/null +++ b/solutions/94. Binary Tree Inorder Traversal/94.java @@ -0,0 +1,18 @@ +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + Deque stack = new ArrayDeque<>(); + + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + root = stack.pop(); + ans.add(root.val); + root = root.right; + } + + return ans; + } +} diff --git a/solutions/94. Binary Tree Inorder Traversal/94.py b/solutions/94. Binary Tree Inorder Traversal/94.py new file mode 100644 index 00000000000..9f7bf245cd5 --- /dev/null +++ b/solutions/94. Binary Tree Inorder Traversal/94.py @@ -0,0 +1,14 @@ +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + stack = [] + + while root or stack: + while root: + stack.append(root) + root = root.left + root = stack.pop() + ans.append(root.val) + root = root.right + + return ans diff --git a/solutions/940. Distinct Subsequences II/940.cpp b/solutions/940. Distinct Subsequences II/940.cpp new file mode 100644 index 00000000000..045f2692fc7 --- /dev/null +++ b/solutions/940. Distinct Subsequences II/940.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + int distinctSubseqII(string s) { + constexpr int kMod = 1'000'000'007; + // endsIn[i] := the number of subsequence that end in ('a' + i) + vector endsIn(26); + + for (const char c : s) + endsIn[c - 'a'] = accumulate(endsIn.begin(), endsIn.end(), 1L) % kMod; + + return accumulate(endsIn.begin(), endsIn.end(), 0L) % kMod; + } +}; diff --git a/solutions/940. Distinct Subsequences II/940.java b/solutions/940. Distinct Subsequences II/940.java new file mode 100644 index 00000000000..69eb8c69e9f --- /dev/null +++ b/solutions/940. Distinct Subsequences II/940.java @@ -0,0 +1,12 @@ +class Solution { + public int distinctSubseqII(String s) { + final int kMod = 1_000_000_007; + // endsIn[i] := the number of subsequence that end in ('a' + i) + long[] endsIn = new long[26]; + + for (final char c : s.toCharArray()) + endsIn[c - 'a'] = (Arrays.stream(endsIn).sum() + 1) % kMod; + + return (int) (Arrays.stream(endsIn).sum() % kMod); + } +} diff --git a/solutions/940. Distinct Subsequences II/940.py b/solutions/940. Distinct Subsequences II/940.py new file mode 100644 index 00000000000..5a9d226c4e5 --- /dev/null +++ b/solutions/940. Distinct Subsequences II/940.py @@ -0,0 +1,10 @@ +class Solution: + def distinctSubseqII(self, s: str) -> int: + kMod = 1_000_000_007 + # endsIn[i] := the number of subsequence that end in ('a' + i) + endsIn = [0] * 26 + + for c in s: + endsIn[ord(c) - ord('a')] = (sum(endsIn) + 1) % kMod + + return sum(endsIn) % kMod diff --git a/solutions/941. Valid Mountain Array/941.cpp b/solutions/941. Valid Mountain Array/941.cpp new file mode 100644 index 00000000000..17218a96500 --- /dev/null +++ b/solutions/941. Valid Mountain Array/941.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool validMountainArray(vector& arr) { + if (arr.size() < 3) + return false; + + int l = 0; + int r = arr.size() - 1; + + while (l + 1 < arr.size() && arr[l] < arr[l + 1]) + ++l; + while (r > 0 && arr[r] < arr[r - 1]) + --r; + + return l > 0 && r < arr.size() - 1 && l == r; + } +}; diff --git a/solutions/941. Valid Mountain Array/941.java b/solutions/941. Valid Mountain Array/941.java new file mode 100644 index 00000000000..a2418baf885 --- /dev/null +++ b/solutions/941. Valid Mountain Array/941.java @@ -0,0 +1,16 @@ +class Solution { + public boolean validMountainArray(int[] arr) { + if (arr.length < 3) + return false; + + int l = 0; + int r = arr.length - 1; + + while (l + 1 < arr.length && arr[l] < arr[l + 1]) + ++l; + while (r > 0 && arr[r] < arr[r - 1]) + --r; + + return l > 0 && r < arr.length - 1 && l == r; + } +} diff --git a/solutions/941. Valid Mountain Array/941.py b/solutions/941. Valid Mountain Array/941.py new file mode 100644 index 00000000000..f98db13302e --- /dev/null +++ b/solutions/941. Valid Mountain Array/941.py @@ -0,0 +1,14 @@ +class Solution: + def validMountainArray(self, arr: List[int]) -> bool: + if len(arr) < 3: + return False + + l = 0 + r = len(arr) - 1 + + while l + 1 < len(arr) and arr[l] < arr[l + 1]: + l += 1 + while r > 0 and arr[r] < arr[r - 1]: + r -= 1 + + return l > 0 and r < len(arr) - 1 and l == r diff --git a/solutions/942. DI String Match/942.cpp b/solutions/942. DI String Match/942.cpp new file mode 100644 index 00000000000..2414efa1860 --- /dev/null +++ b/solutions/942. DI String Match/942.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + vector diStringMatch(string s) { + vector ans; + int mn = 0; + int mx = s.length(); + + for (const char c : s) + ans.push_back(c == 'I' ? mn++ : mx--); + ans.push_back(mn); + + return ans; + } +}; diff --git a/solutions/942. DI String Match/942.java b/solutions/942. DI String Match/942.java new file mode 100644 index 00000000000..d79bb026e05 --- /dev/null +++ b/solutions/942. DI String Match/942.java @@ -0,0 +1,14 @@ +class Solution { + public int[] diStringMatch(String s) { + final int n = s.length(); + int[] ans = new int[n + 1]; + int mn = 0; + int mx = n; + + for (int i = 0; i < n; ++i) + ans[i] = s.charAt(i) == 'I' ? mn++ : mx--; + ans[n] = mn; + + return ans; + } +} diff --git a/solutions/942. DI String Match/942.py b/solutions/942. DI String Match/942.py new file mode 100644 index 00000000000..5070fb6befa --- /dev/null +++ b/solutions/942. DI String Match/942.py @@ -0,0 +1,15 @@ +class Solution: + def diStringMatch(self, s: str) -> List[int]: + ans = [] + mn = 0 + mx = len(s) + + for c in s: + if c == 'I': + ans.append(mn) + mn += 1 + else: + ans.append(mx) + mx -= 1 + + return ans + [mn] diff --git a/solutions/943. Find the Shortest Superstring/943-2.cpp b/solutions/943. Find the Shortest Superstring/943-2.cpp new file mode 100644 index 00000000000..50a3a7000d4 --- /dev/null +++ b/solutions/943. Find the Shortest Superstring/943-2.cpp @@ -0,0 +1,64 @@ +class Solution { + public: + string shortestSuperstring(vector& A) { + const int n = A.size(); + // cost[i][j] := the cost to append A[j] after A[i] + vector> cost(n, vector(n)); + // dp[s][j] := the minimum cost to visit nodes of s ending in j, s is a + // binary Value, e.g. dp[6][2] means the minimum cost to visit {1, 2} ending + // in 2 (6 = 2^1 + 2^2) + vector> dp(1 << n, vector(n, INT_MAX / 2)); + // parent[s][j] := the parent of "nodes of s ending in j" + vector> parent(1 << n, vector(n, -1)); + + // Returns the cost to append b after a. + auto getCost = [](const string& a, const string& b) { + int cost = b.length(); + const int minLength = min(a.length(), b.length()); + for (int k = 1; k <= minLength; ++k) + if (a.substr(a.length() - k) == b.substr(0, k)) + cost = b.length() - k; + return cost; + }; + + // Pre-calculate the `cost` array to save time. + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + cost[i][j] = getCost(A[i], A[j]); + cost[j][i] = getCost(A[j], A[i]); + } + + for (int i = 0; i < n; ++i) + dp[1 << i][i] = A[i].length(); + + // Enumerate all the states ending in different nodes. + for (int s = 1; s < (1 << n); ++s) + for (int i = 0; i < n; ++i) { + if ((s & (1 << i)) == 0) + continue; + for (int j = 0; j < n; ++j) + if (dp[s - (1 << i)][j] + cost[j][i] < dp[s][i]) { + dp[s][i] = dp[s - (1 << i)][j] + cost[j][i]; + parent[s][i] = j; + } + } + + string ans; + const vector& dpBack = dp.back(); + int j = distance(dpBack.begin(), ranges::min_element(dpBack)); + int s = (1 << n) - 1; // 2^0 + 2^1 + ... + 2^(n - 1) + + // Traverse back to build the string. + while (s > 0) { + const int i = parent[s][j]; + if (i == -1) + ans = A[j] + ans; + else + ans = A[j].substr(A[j].length() - cost[i][j]) + ans; + s -= 1 << j; + j = i; + } + + return ans; + } +}; diff --git a/solutions/943. Find the Shortest Superstring/943-2.java b/solutions/943. Find the Shortest Superstring/943-2.java new file mode 100644 index 00000000000..cba388c9321 --- /dev/null +++ b/solutions/943. Find the Shortest Superstring/943-2.java @@ -0,0 +1,71 @@ +class Solution { + public String shortestSuperstring(String[] A) { + final int n = A.length; + // cost[i][j] := the cost to append A[j] after A[i] + int[][] cost = new int[n][n]; + // Pre-calculate the `cost` array to save time. + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + cost[i][j] = getCost(A[i], A[j]); + cost[j][i] = getCost(A[j], A[i]); + } + // dp[s][j] := the minimum cost to visit nodes of s ending in j, s is a + // binary Value, e.g. dp[6][2] means the minimum cost to visit {1, 2} ending + // in 2 (6 = 2^1 + 2^2) + int[][] dp = new int[1 << n][n]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE / 2)); + // parent[s][j] := the parent of "nodes of s ending in j" + int[][] parent = new int[1 << n][n]; + Arrays.stream(parent).forEach(row -> Arrays.fill(row, -1)); + + for (int i = 0; i < n; ++i) + dp[1 << i][i] = A[i].length(); + + // Enumerate all the states ending in different nodes. + for (int s = 1; s < (1 << n); ++s) + for (int i = 0; i < n; ++i) { + if ((s & (1 << i)) == 0) + continue; + for (int j = 0; j < n; ++j) + if (dp[s - (1 << i)][j] + cost[j][i] < dp[s][i]) { + dp[s][i] = dp[s - (1 << i)][j] + cost[j][i]; + parent[s][i] = j; + } + } + + String ans = ""; + int j = getLastNode(dp[(1 << n) - 1]); + int s = (1 << n) - 1; // 2^0 + 2^1 + ... + 2^(n - 1) + + // Traverse back to build the string. + while (s > 0) { + final int i = parent[s][j]; + if (i == -1) + ans = A[j] + ans; + else + ans = A[j].substring(A[j].length() - cost[i][j]) + ans; + s -= 1 << j; + j = i; + } + + return ans; + } + + // Returns the cost to append b after a. + private int getCost(final String a, final String b) { + int cost = b.length(); + final int minLength = Math.min(a.length(), b.length()); + for (int k = 1; k <= minLength; ++k) + if (a.substring(a.length() - k).equals(b.substring(0, k))) + cost = b.length() - k; + return cost; + } + + private int getLastNode(int[] row) { + int minIndex = 0; + for (int i = 1; i < row.length; ++i) + if (row[i] < row[minIndex]) + minIndex = i; + return minIndex; + } +} diff --git a/solutions/943. Find the Shortest Superstring/943.cpp b/solutions/943. Find the Shortest Superstring/943.cpp new file mode 100644 index 00000000000..2a93fab5194 --- /dev/null +++ b/solutions/943. Find the Shortest Superstring/943.cpp @@ -0,0 +1,65 @@ +class Solution { + public: + string shortestSuperstring(vector& A) { + const int n = A.size(); + // cost[i][j] := the cost to append A[j] after A[i] + vector> cost(n, vector(n)); + + // Returns the cost to append b after a. + auto getCost = [](const string& a, const string& b) { + int cost = b.length(); + const int minLength = min(a.length(), b.length()); + for (int k = 1; k <= minLength; ++k) + if (a.substr(a.length() - k) == b.substr(0, k)) + cost = b.length() - k; + return cost; + }; + + // Pre-calculate cost array to save time. + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + cost[i][j] = getCost(A[i], A[j]); + cost[j][i] = getCost(A[j], A[i]); + } + + vector bestPath; + int minLength = n * 20; // given by problem + + dfs(A, cost, {}, bestPath, 0, 0, 0, minLength); + + string ans = A[bestPath[0]]; + + for (int k = 1; k < n; ++k) { + const int i = bestPath[k - 1]; + const int j = bestPath[k]; + ans += A[j].substr(A[j].length() - cost[i][j]); + } + + return ans; + } + + private: + // used: i-th bit means A[i] is used or not + void dfs(const vector& A, const vector>& cost, + vector&& path, vector& bestPath, int used, int depth, + int currLength, int& minLength) { + if (currLength >= minLength) + return; + if (depth == A.size()) { + minLength = currLength; + bestPath = path; + return; + } + + for (int i = 0; i < A.size(); ++i) { + if (1 << i & used) + continue; + path.push_back(i); + const int newLength = + depth == 0 ? A[i].length() : currLength + cost[path[depth - 1]][i]; + dfs(A, cost, move(path), bestPath, used | 1 << i, depth + 1, newLength, + minLength); + path.pop_back(); + } + } +}; diff --git a/solutions/943. Find the Shortest Superstring/943.java b/solutions/943. Find the Shortest Superstring/943.java new file mode 100644 index 00000000000..a619ebbf9cd --- /dev/null +++ b/solutions/943. Find the Shortest Superstring/943.java @@ -0,0 +1,67 @@ +class Solution { + public String shortestSuperstring(String[] A) { + final int n = A.length; + // cost[i][j] := the cost to append A[j] after A[i] + int[][] cost = new int[n][n]; + + // Pre-calculate cost array to save time. + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) { + cost[i][j] = getCost(A[i], A[j]); + cost[j][i] = getCost(A[j], A[i]); + } + + List path = new ArrayList<>(); + List bestPath = new ArrayList<>(); + + minLength = n * 20; // given by problem + + dfs(A, cost, path, bestPath, 0, 0, 0); + + StringBuilder sb = new StringBuilder(A[bestPath.get(0)]); + + for (int k = 1; k < n; ++k) { + final int i = bestPath.get(k - 1); + final int j = bestPath.get(k); + sb.append(A[j].substring(A[j].length() - cost[i][j])); + } + + return sb.toString(); + } + + private int minLength; + + // Returns the cost to append b after a. + private int getCost(final String a, final String b) { + int cost = b.length(); + final int minLength = Math.min(a.length(), b.length()); + for (int k = 1; k <= minLength; ++k) + if (a.substring(a.length() - k).equals(b.substring(0, k))) + cost = b.length() - k; + return cost; + } + + // used: i-th bit means A[i] is used or not + private void dfs(String[] A, int[][] cost, List path, List bestPath, int used, + int depth, int currLength) { + if (currLength >= minLength) + return; + if (depth == A.length) { + minLength = currLength; + bestPath.clear(); + for (final int node : path) { + bestPath.add(node); + } + return; + } + + for (int i = 0; i < A.length; ++i) { + if ((1 << i & used) > 0) + continue; + path.add(i); + final int newLength = depth == 0 ? A[i].length() : currLength + cost[path.get(depth - 1)][i]; + dfs(A, cost, path, bestPath, used | 1 << i, depth + 1, newLength); + path.remove(path.size() - 1); + } + } +} diff --git a/solutions/944. Delete Columns to Make Sorted/944.cpp b/solutions/944. Delete Columns to Make Sorted/944.cpp new file mode 100644 index 00000000000..075f2414cb2 --- /dev/null +++ b/solutions/944. Delete Columns to Make Sorted/944.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minDeletionSize(vector& strs) { + int ans = 0; + + for (int j = 0; j < strs[0].length(); ++j) + for (int i = 0; i + 1 < strs.size(); ++i) + if (strs[i][j] > strs[i + 1][j]) { + ++ans; + break; + } + + return ans; + } +}; diff --git a/solutions/944. Delete Columns to Make Sorted/944.java b/solutions/944. Delete Columns to Make Sorted/944.java new file mode 100644 index 00000000000..7619baeeb12 --- /dev/null +++ b/solutions/944. Delete Columns to Make Sorted/944.java @@ -0,0 +1,14 @@ +class Solution { + public int minDeletionSize(String[] strs) { + int ans = 0; + + for (int j = 0; j < strs[0].length(); ++j) + for (int i = 0; i + 1 < strs.length; ++i) + if (strs[i].charAt(j) > strs[i + 1].charAt(j)) { + ++ans; + break; + } + + return ans; + } +} diff --git a/solutions/944. Delete Columns to Make Sorted/944.py b/solutions/944. Delete Columns to Make Sorted/944.py new file mode 100644 index 00000000000..a48a23e2ef0 --- /dev/null +++ b/solutions/944. Delete Columns to Make Sorted/944.py @@ -0,0 +1,11 @@ +class Solution: + def minDeletionSize(self, strs: List[str]) -> int: + ans = 0 + + for j in range(len(strs[0])): + for i in range(len(strs) - 1): + if strs[i][j] > strs[i + 1][j]: + ans += 1 + break + + return ans diff --git a/solutions/945. Minimum Increment to Make Array Unique/945.cpp b/solutions/945. Minimum Increment to Make Array Unique/945.cpp new file mode 100644 index 00000000000..6e32abbcd90 --- /dev/null +++ b/solutions/945. Minimum Increment to Make Array Unique/945.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int minIncrementForUnique(vector& nums) { + int ans = 0; + int minAvailable = 0; + + ranges::sort(nums); + + for (const int num : nums) { + ans += max(minAvailable - num, 0); + minAvailable = max(minAvailable, num) + 1; + } + + return ans; + } +}; diff --git a/solutions/945. Minimum Increment to Make Array Unique/945.java b/solutions/945. Minimum Increment to Make Array Unique/945.java new file mode 100644 index 00000000000..90d24ef030f --- /dev/null +++ b/solutions/945. Minimum Increment to Make Array Unique/945.java @@ -0,0 +1,15 @@ +class Solution { + public int minIncrementForUnique(int[] nums) { + int ans = 0; + int minAvailable = 0; + + Arrays.sort(nums); + + for (final int num : nums) { + ans += Math.max(minAvailable - num, 0); + minAvailable = Math.max(minAvailable, num) + 1; + } + + return ans; + } +} diff --git a/solutions/945. Minimum Increment to Make Array Unique/945.py b/solutions/945. Minimum Increment to Make Array Unique/945.py new file mode 100644 index 00000000000..cd3ce617679 --- /dev/null +++ b/solutions/945. Minimum Increment to Make Array Unique/945.py @@ -0,0 +1,10 @@ +class Solution: + def minIncrementForUnique(self, nums: List[int]) -> int: + ans = 0 + minAvailable = 0 + + for num in sorted(nums): + ans += max(minAvailable - num, 0) + minAvailable = max(minAvailable, num) + 1 + + return ans diff --git a/solutions/946. Validate Stack Sequences/946.cpp b/solutions/946. Validate Stack Sequences/946.cpp new file mode 100644 index 00000000000..8009d8fce06 --- /dev/null +++ b/solutions/946. Validate Stack Sequences/946.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + bool validateStackSequences(vector& pushed, vector& popped) { + stack stack; + int i = 0; // popped's index + + for (const int x : pushed) { + stack.push(x); + while (!stack.empty() && stack.top() == popped[i]) { + stack.pop(); + ++i; + } + } + + return stack.empty(); + } +}; diff --git a/solutions/946. Validate Stack Sequences/946.java b/solutions/946. Validate Stack Sequences/946.java new file mode 100644 index 00000000000..a9a33821058 --- /dev/null +++ b/solutions/946. Validate Stack Sequences/946.java @@ -0,0 +1,16 @@ +class Solution { + public boolean validateStackSequences(int[] pushed, int[] popped) { + Deque stack = new ArrayDeque<>(); + int i = 0; // popped's index + + for (final int x : pushed) { + stack.push(x); + while (!stack.isEmpty() && stack.peek() == popped[i]) { + stack.pop(); + ++i; + } + } + + return stack.isEmpty(); + } +} diff --git a/solutions/946. Validate Stack Sequences/946.py b/solutions/946. Validate Stack Sequences/946.py new file mode 100644 index 00000000000..14961db313f --- /dev/null +++ b/solutions/946. Validate Stack Sequences/946.py @@ -0,0 +1,12 @@ +class Solution: + def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: + stack = [] + i = 0 # popped's index + + for x in pushed: + stack.append(x) + while stack and stack[-1] == popped[i]: + stack.pop() + i += 1 + + return not stack diff --git a/solutions/947. Most Stones Removed with Same Row or Column/947.cpp b/solutions/947. Most Stones Removed with Same Row or Column/947.cpp new file mode 100644 index 00000000000..ec4e0c9d03a --- /dev/null +++ b/solutions/947. Most Stones Removed with Same Row or Column/947.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int removeStones(vector>& stones) { + int numOfIslands = 0; + vector> graph(stones.size()); + unordered_set seen; + + for (int i = 0; i < stones.size(); ++i) + for (int j = i + 1; j < stones.size(); ++j) + if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) { + graph[i].push_back(j); + graph[j].push_back(i); + } + + for (int i = 0; i < stones.size(); ++i) + if (seen.insert(i).second) { + dfs(graph, i, seen); + ++numOfIslands; + } + + return stones.size() - numOfIslands; + } + + private: + void dfs(const vector>& graph, int u, unordered_set& seen) { + for (const int v : graph[u]) + if (seen.insert(v).second) + dfs(graph, v, seen); + } +}; diff --git a/solutions/947. Most Stones Removed with Same Row or Column/947.java b/solutions/947. Most Stones Removed with Same Row or Column/947.java new file mode 100644 index 00000000000..8f383cea1f8 --- /dev/null +++ b/solutions/947. Most Stones Removed with Same Row or Column/947.java @@ -0,0 +1,31 @@ +class Solution { + public int removeStones(int[][] stones) { + int numOfIslands = 0; + List[] graph = new List[stones.length]; + Set seen = new HashSet<>(); + + for (int i = 0; i < graph.length; ++i) + graph[i] = new ArrayList<>(); + + for (int i = 0; i < stones.length; ++i) + for (int j = i + 1; j < stones.length; ++j) + if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) { + graph[i].add(j); + graph[j].add(i); + } + + for (int i = 0; i < stones.length; ++i) + if (seen.add(i)) { + dfs(graph, i, seen); + ++numOfIslands; + } + + return stones.length - numOfIslands; + } + + private void dfs(List[] graph, int u, Set seen) { + for (final int v : graph[u]) + if (seen.add(v)) + dfs(graph, v, seen); + } +} diff --git a/solutions/948. Bag of Tokens/948.cpp b/solutions/948. Bag of Tokens/948.cpp new file mode 100644 index 00000000000..d7d26479303 --- /dev/null +++ b/solutions/948. Bag of Tokens/948.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int bagOfTokensScore(vector& tokens, int power) { + int ans = 0; + int score = 0; + int i = 0; // the index of the smallest token + int j = tokens.size() - 1; // the index of the largest token + + ranges::sort(tokens); + + while (i <= j && (power >= tokens[i] || score)) { + while (i <= j && power >= tokens[i]) { + // Play the smallest face up. + power -= tokens[i++]; + ++score; + } + ans = max(ans, score); + if (i <= j && score) { + // Play the largest face down. + power += tokens[j--]; + --score; + } + } + + return ans; + } +}; diff --git a/solutions/948. Bag of Tokens/948.java b/solutions/948. Bag of Tokens/948.java new file mode 100644 index 00000000000..9738f5cddf4 --- /dev/null +++ b/solutions/948. Bag of Tokens/948.java @@ -0,0 +1,26 @@ +class Solution { + public int bagOfTokensScore(int[] tokens, int power) { + int ans = 0; + int score = 0; + int i = 0; // the index of the smallest token + int j = tokens.length - 1; // the index of the largest token + + Arrays.sort(tokens); + + while (i <= j && (power >= tokens[i] || score > 0)) { + while (i <= j && power >= tokens[i]) { + // Play the smallest face up. + power -= tokens[i++]; + ++score; + } + ans = Math.max(ans, score); + if (i <= j && score > 0) { + // Play the largest face down. + power += tokens[j--]; + --score; + } + } + + return ans; + } +} diff --git a/solutions/948. Bag of Tokens/948.py b/solutions/948. Bag of Tokens/948.py new file mode 100644 index 00000000000..76ebfe7a72c --- /dev/null +++ b/solutions/948. Bag of Tokens/948.py @@ -0,0 +1,18 @@ +class Solution: + def bagOfTokensScore(self, tokens: List[int], power: int) -> int: + ans = 0 + score = 0 + q = collections.deque(sorted(tokens)) + + while q and (power >= q[0] or score): + while q and power >= q[0]: + # Play the smallest face up. + power -= q.popleft() + score += 1 + ans = max(ans, score) + if q and score: + # Play the largest face down. + power += q.pop() + score -= 1 + + return ans diff --git a/solutions/949. Largest Time for Given Digits/949.cpp b/solutions/949. Largest Time for Given Digits/949.cpp new file mode 100644 index 00000000000..2788a5319ac --- /dev/null +++ b/solutions/949. Largest Time for Given Digits/949.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + string largestTimeFromDigits(vector& arr) { + string ans; + + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + for (int k = 0; k < 4; ++k) { + if (i == j || i == k || j == k) + continue; + const string hours = to_string(arr[i]) + to_string(arr[j]); + const string minutes = + to_string(arr[k]) + to_string(arr[6 - i - j - k]); + if (hours < "24" && minutes < "60") + ans = max(ans, hours + ':' + minutes); + } + + return ans; + } +}; diff --git a/solutions/949. Largest Time for Given Digits/949.java b/solutions/949. Largest Time for Given Digits/949.java new file mode 100644 index 00000000000..f9bbe9209b7 --- /dev/null +++ b/solutions/949. Largest Time for Given Digits/949.java @@ -0,0 +1,19 @@ +class Solution { + public String largestTimeFromDigits(int[] arr) { + String ans = ""; + + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + for (int k = 0; k < 4; ++k) { + if (i == j || i == k || j == k) + continue; + final String hours = "" + arr[i] + arr[j]; + final String minutes = "" + arr[k] + arr[6 - i - j - k]; + final String time = hours + ':' + minutes; + if (hours.compareTo("24") < 0 && minutes.compareTo("60") < 0 && ans.compareTo(time) < 0) + ans = time; + } + + return ans; + } +} diff --git a/solutions/949. Largest Time for Given Digits/949.py b/solutions/949. Largest Time for Given Digits/949.py new file mode 100644 index 00000000000..f2ab7d94359 --- /dev/null +++ b/solutions/949. Largest Time for Given Digits/949.py @@ -0,0 +1,6 @@ +class Solution: + def largestTimeFromDigits(self, arr: List[int]) -> str: + for time in itertools.permutations(sorted(arr, reverse=True)): + if time[:2] < (2, 4) and time[2] < 6: + return '%d%d:%d%d' % time + return '' diff --git a/solutions/95. Unique Binary Search Trees II/95.cpp b/solutions/95. Unique Binary Search Trees II/95.cpp new file mode 100644 index 00000000000..0a997135f3c --- /dev/null +++ b/solutions/95. Unique Binary Search Trees II/95.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + vector generateTrees(int n) { + if (n == 0) + return {}; + return generateTrees(1, n); + } + + private: + vector generateTrees(int min, int max) { + if (min > max) + return {nullptr}; + + vector ans; + + for (int i = min; i <= max; ++i) + for (TreeNode* left : generateTrees(min, i - 1)) + for (TreeNode* right : generateTrees(i + 1, max)) { + ans.push_back(new TreeNode(i)); + ans.back()->left = left; + ans.back()->right = right; + } + + return ans; + } +}; diff --git a/solutions/95. Unique Binary Search Trees II/95.java b/solutions/95. Unique Binary Search Trees II/95.java new file mode 100644 index 00000000000..587b47bc07a --- /dev/null +++ b/solutions/95. Unique Binary Search Trees II/95.java @@ -0,0 +1,24 @@ +class Solution { + public List generateTrees(int n) { + if (n == 0) + return new ArrayList<>(); + return generateTrees(1, n); + } + + private List generateTrees(int mn, int mx) { + if (mn > mx) + return Arrays.asList((TreeNode) null); + + List ans = new ArrayList<>(); + + for (int i = mn; i <= mx; ++i) + for (TreeNode left : generateTrees(mn, i - 1)) + for (TreeNode right : generateTrees(i + 1, mx)) { + ans.add(new TreeNode(i)); + ans.get(ans.size() - 1).left = left; + ans.get(ans.size() - 1).right = right; + } + + return ans; + } +} diff --git a/solutions/95. Unique Binary Search Trees II/95.py b/solutions/95. Unique Binary Search Trees II/95.py new file mode 100644 index 00000000000..a74a46d8004 --- /dev/null +++ b/solutions/95. Unique Binary Search Trees II/95.py @@ -0,0 +1,21 @@ +class Solution: + def generateTrees(self, n: int) -> List[TreeNode]: + if n == 0: + return [] + + def generateTrees(mn: int, mx: int) -> List[Optional[int]]: + if mn > mx: + return [None] + + ans = [] + + for i in range(mn, mx + 1): + for left in generateTrees(mn, i - 1): + for right in generateTrees(i + 1, mx): + ans.append(TreeNode(i)) + ans[-1].left = left + ans[-1].right = right + + return ans + + return generateTrees(1, n) diff --git a/solutions/950. Reveal Cards In Increasing Order/950.cpp b/solutions/950. Reveal Cards In Increasing Order/950.cpp new file mode 100644 index 00000000000..8bf320440e6 --- /dev/null +++ b/solutions/950. Reveal Cards In Increasing Order/950.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector deckRevealedIncreasing(vector& deck) { + ranges::sort(deck, greater()); + + deque dq{deck[0]}; + + for (int i = 1; i < deck.size(); ++i) { + dq.push_front(dq.back()); + dq.pop_back(); + dq.push_front(deck[i]); + } + + return {dq.begin(), dq.end()}; + } +}; diff --git a/solutions/950. Reveal Cards In Increasing Order/950.java b/solutions/950. Reveal Cards In Increasing Order/950.java new file mode 100644 index 00000000000..b98bcda27a6 --- /dev/null +++ b/solutions/950. Reveal Cards In Increasing Order/950.java @@ -0,0 +1,21 @@ +class Solution { + public int[] deckRevealedIncreasing(int[] deck) { + final int n = deck.length; + + Arrays.sort(deck); + + Deque dq = new ArrayDeque<>(); + dq.addFirst(deck[n - 1]); + + for (int i = n - 2; i >= 0; --i) { + dq.addFirst(dq.getLast()); + dq.pollLast(); + dq.addFirst(deck[i]); + } + + for (int i = 0; i < n; ++i) + deck[i] = dq.pollFirst(); + + return deck; + } +} diff --git a/solutions/950. Reveal Cards In Increasing Order/950.py b/solutions/950. Reveal Cards In Increasing Order/950.py new file mode 100644 index 00000000000..dca8a54c5b2 --- /dev/null +++ b/solutions/950. Reveal Cards In Increasing Order/950.py @@ -0,0 +1,9 @@ +class Solution: + def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: + dq = collections.deque() + + for card in reversed(sorted(deck)): + dq.rotate() + dq.appendleft(card) + + return list(dq) diff --git a/solutions/951. Flip Equivalent Binary Trees/951.cpp b/solutions/951. Flip Equivalent Binary Trees/951.cpp new file mode 100644 index 00000000000..b3ad11116df --- /dev/null +++ b/solutions/951. Flip Equivalent Binary Trees/951.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool flipEquiv(TreeNode* root1, TreeNode* root2) { + if (root1 == nullptr) + return root2 == nullptr; + if (root2 == nullptr) + return root1 == nullptr; + if (root1->val != root2->val) + return false; + return flipEquiv(root1->left, root2->left) && + flipEquiv(root1->right, root2->right) || + flipEquiv(root1->left, root2->right) && + flipEquiv(root1->right, root2->left); + } +}; diff --git a/solutions/951. Flip Equivalent Binary Trees/951.java b/solutions/951. Flip Equivalent Binary Trees/951.java new file mode 100644 index 00000000000..5db9ef0078a --- /dev/null +++ b/solutions/951. Flip Equivalent Binary Trees/951.java @@ -0,0 +1,13 @@ +class Solution { + public boolean flipEquiv(TreeNode root1, TreeNode root2) { + if (root1 == null) + return root2 == null; + if (root2 == null) + return root1 == null; + if (root1.val != root2.val) + return false; + return // + flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) || + flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left); + } +} diff --git a/solutions/951. Flip Equivalent Binary Trees/951.py b/solutions/951. Flip Equivalent Binary Trees/951.py new file mode 100644 index 00000000000..97b9c5bbcbd --- /dev/null +++ b/solutions/951. Flip Equivalent Binary Trees/951.py @@ -0,0 +1,11 @@ +class Solution: + def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: + if not root1: + return not root2 + if not root2: + return not root1 + if root1.val != root2.val: + return False + return self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right) or \ + self.flipEquiv(root1.left, root2.right) and self.flipEquiv( + root1.right, root2.left) diff --git a/solutions/952. Largest Component Size by Common Factor/952.cpp b/solutions/952. Largest Component Size by Common Factor/952.cpp new file mode 100644 index 00000000000..4818581d358 --- /dev/null +++ b/solutions/952. Largest Component Size by Common Factor/952.cpp @@ -0,0 +1,51 @@ +class UnionFind { + public: + UnionFind(int n) : id(n), rank(n) { + iota(id.begin(), id.end(), 0); + } + + void unionByRank(int u, int v) { + const int i = find(u); + const int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; + vector rank; +}; + +class Solution { + public: + int largestComponentSize(vector& nums) { + const int n = ranges::max(nums); + int ans = 0; + UnionFind uf(n + 1); + unordered_map count; + + for (const int num : nums) + for (int x = 2; x <= sqrt(num); ++x) + if (num % x == 0) { + uf.unionByRank(num, x); + uf.unionByRank(num, num / x); + } + + for (const int num : nums) + ans = max(ans, ++count[uf.find(num)]); + + return ans; + } +}; diff --git a/solutions/952. Largest Component Size by Common Factor/952.java b/solutions/952. Largest Component Size by Common Factor/952.java new file mode 100644 index 00000000000..4ae4d8bf972 --- /dev/null +++ b/solutions/952. Largest Component Size by Common Factor/952.java @@ -0,0 +1,51 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public int largestComponentSize(int[] nums) { + final int n = Arrays.stream(nums).max().getAsInt(); + int ans = 0; + UnionFind uf = new UnionFind(n + 1); + Map count = new HashMap<>(); + + for (final int num : nums) + for (int x = 2; x <= (int) Math.sqrt(num); ++x) + if (num % x == 0) { + uf.unionByRank(num, x); + uf.unionByRank(num, num / x); + } + + for (final int num : nums) + ans = Math.max(ans, count.merge(uf.find(num), 1, Integer::sum)); + + return ans; + } +} diff --git a/solutions/952. Largest Component Size by Common Factor/952.py b/solutions/952. Largest Component Size by Common Factor/952.py new file mode 100644 index 00000000000..b3c8eee4b26 --- /dev/null +++ b/solutions/952. Largest Component Size by Common Factor/952.py @@ -0,0 +1,42 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + self.rank = [0] * n + + def unionByRank(self, u: int, v: int) -> None: + i = self.find(u) + j = self.find(v) + if i == j: + return + if self.rank[i] < self.rank[j]: + self.id[i] = j + elif self.rank[i] > self.rank[j]: + self.id[j] = i + else: + self.id[i] = j + self.rank[j] += 1 + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def largestComponentSize(self, nums: List[int]) -> int: + ans = 0 + uf = UnionFind(max(nums) + 1) + count = collections.Counter() + + for num in nums: + for x in range(2, math.isqrt(num) + 1): + if num % x == 0: + uf.unionByRank(num, x) + uf.unionByRank(num, num // x) + + for num in nums: + numRoot = uf.find(num) + count[numRoot] += 1 + ans = max(ans, count[numRoot]) + + return ans diff --git a/solutions/953. Verifying an Alien Dictionary/953.cpp b/solutions/953. Verifying an Alien Dictionary/953.cpp new file mode 100644 index 00000000000..4edaba33b69 --- /dev/null +++ b/solutions/953. Verifying an Alien Dictionary/953.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + bool isAlienSorted(vector& words, const string& order) { + vector map(26); // e.g. order = "bca" -> map = ['c', 'a', 'b'] + + for (int i = 0; i < 26; ++i) + map[order[i] - 'a'] = i + 'a'; + + for (string& word : words) + for (char& c : word) + c = map[c - 'a']; + + return is_sorted(words.begin(), words.end()); + } +}; diff --git a/solutions/953. Verifying an Alien Dictionary/953.java b/solutions/953. Verifying an Alien Dictionary/953.java new file mode 100644 index 00000000000..e84d9e0a7f1 --- /dev/null +++ b/solutions/953. Verifying an Alien Dictionary/953.java @@ -0,0 +1,21 @@ +class Solution { + public boolean isAlienSorted(String[] words, String order) { + char[] map = new char[26]; // e.g. order = "bca" -> map = ['c', 'a', 'b'] + + for (int i = 0; i < 26; ++i) + map[order.charAt(i) - 'a'] = (char) (i + 'a'); + + for (int i = 0; i + 1 < words.length; ++i) + if (bigger(words[i], words[i + 1], map)) + return false; + + return true; + } + + private boolean bigger(final String s1, final String s2, final char[] map) { + for (int i = 0; i < s1.length() && i < s2.length(); ++i) + if (s1.charAt(i) != s2.charAt(i)) + return map[s1.charAt(i) - 'a'] > map[s2.charAt(i) - 'a']; + return s1.length() > s2.length(); + } +} diff --git a/solutions/953. Verifying an Alien Dictionary/953.py b/solutions/953. Verifying an Alien Dictionary/953.py new file mode 100644 index 00000000000..f0c09f96ec5 --- /dev/null +++ b/solutions/953. Verifying an Alien Dictionary/953.py @@ -0,0 +1,5 @@ +class Solution: + def isAlienSorted(self, words: List[str], order: str) -> bool: + dict = {c: i for i, c in enumerate(order)} + words = [[dict[c] for c in word] for word in words] + return all(w1 <= w2 for w1, w2 in zip(words, words[1:])) diff --git a/solutions/954. Array of Doubled Pairs/954.cpp b/solutions/954. Array of Doubled Pairs/954.cpp new file mode 100644 index 00000000000..ca54e8a9b48 --- /dev/null +++ b/solutions/954. Array of Doubled Pairs/954.cpp @@ -0,0 +1,22 @@ +class Solution { + public: + bool canReorderDoubled(vector& arr) { + unordered_map count; + + for (const int a : arr) + ++count[a]; + + ranges::sort(arr, [](const int a, const int b) { return abs(a) < abs(b); }); + + for (const int a : arr) { + if (count[a] == 0) + continue; + if (count[2 * a] == 0) + return false; + --count[a]; + --count[2 * a]; + } + + return true; + } +}; diff --git a/solutions/954. Array of Doubled Pairs/954.java b/solutions/954. Array of Doubled Pairs/954.java new file mode 100644 index 00000000000..85aa40e151f --- /dev/null +++ b/solutions/954. Array of Doubled Pairs/954.java @@ -0,0 +1,25 @@ +class Solution { + public boolean canReorderDoubled(int[] arr) { + Map count = new HashMap<>(); + + for (final int a : arr) + count.merge(a, 1, Integer::sum); + + arr = Arrays.stream(arr) + .boxed() + .sorted((a, b) -> Math.abs(a) - Math.abs(b)) + .mapToInt(i -> i) + .toArray(); + + for (final int a : arr) { + if (count.get(a) == 0) + continue; + if (count.getOrDefault(2 * a, 0) == 0) + return false; + count.merge(a, -1, Integer::sum); + count.merge(2 * a, -1, Integer::sum); + } + + return true; + } +} diff --git a/solutions/954. Array of Doubled Pairs/954.py b/solutions/954. Array of Doubled Pairs/954.py new file mode 100644 index 00000000000..157116e5dc5 --- /dev/null +++ b/solutions/954. Array of Doubled Pairs/954.py @@ -0,0 +1,10 @@ +class Solution: + def canReorderDoubled(self, arr: List[int]) -> bool: + count = collections.Counter(arr) + + for key in sorted(count, key=abs): + if count[key] > count[2 * key]: + return False + count[2 * key] -= count[key] + + return True diff --git a/solutions/955. Delete Columns to Make Sorted II/955.cpp b/solutions/955. Delete Columns to Make Sorted II/955.cpp new file mode 100644 index 00000000000..3884d159701 --- /dev/null +++ b/solutions/955. Delete Columns to Make Sorted II/955.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int minDeletionSize(vector& strs) { + const int n = strs.size(); + int ans = 0; + // sorted[i] := true if strs[i] < strs[i + 1] + vector sorted(n - 1); + + for (int j = 0; j < strs[0].length(); ++j) { + int i; + for (i = 0; i + 1 < n; ++i) + if (!sorted[i] && strs[i][j] > strs[i + 1][j]) { + ++ans; + break; + } + // Already compared each pair, so update the sorted array if needed. + if (i + 1 == n) + for (i = 0; i + 1 < n; ++i) + sorted[i] = sorted[i] || strs[i][j] < strs[i + 1][j]; + } + + return ans; + } +}; diff --git a/solutions/955. Delete Columns to Make Sorted II/955.java b/solutions/955. Delete Columns to Make Sorted II/955.java new file mode 100644 index 00000000000..1e93d0eeb37 --- /dev/null +++ b/solutions/955. Delete Columns to Make Sorted II/955.java @@ -0,0 +1,23 @@ +class Solution { + public int minDeletionSize(String[] strs) { + final int n = strs.length; + int ans = 0; + // sorted[i] := true if strs[i] < strs[i + 1] + boolean[] sorted = new boolean[n - 1]; + + for (int j = 0; j < strs[0].length(); ++j) { + int i; + for (i = 0; i + 1 < n; ++i) + if (!sorted[i] && strs[i].charAt(j) > strs[i + 1].charAt(j)) { + ++ans; + break; + } + // strslready compared each pair, so update the sorted array if needed. + if (i + 1 == n) + for (i = 0; i + 1 < n; ++i) + sorted[i] = sorted[i] || strs[i].charAt(j) < strs[i + 1].charAt(j); + } + + return ans; + } +} diff --git a/solutions/956. Tallest Billboard/956-2.cpp b/solutions/956. Tallest Billboard/956-2.cpp new file mode 100644 index 00000000000..c4aa6b04e0c --- /dev/null +++ b/solutions/956. Tallest Billboard/956-2.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int tallestBillboard(vector& rods) { + const int sum = accumulate(rods.begin(), rods.end(), 0); + // dp[i] := the maximum min-height of using rods so far to pile two piles + // that have height difference i + vector dp(sum + 1, -1); + dp[0] = 0; + + for (const int h : rods) { + vector prev(dp); + for (int i = 0; i <= sum - h; ++i) { + if (prev[i] < 0) + continue; + // Don't use this rod. + dp[i] = max(dp[i], prev[i]); + // Put on the taller pile. + dp[i + h] = max(dp[i + h], prev[i]); + // Put on the shorter pile. + dp[abs(i - h)] = max(dp[abs(i - h)], prev[i] + min(i, h)); + } + } + + return dp[0]; + } +}; diff --git a/solutions/956. Tallest Billboard/956-2.java b/solutions/956. Tallest Billboard/956-2.java new file mode 100644 index 00000000000..f84521cc9c1 --- /dev/null +++ b/solutions/956. Tallest Billboard/956-2.java @@ -0,0 +1,26 @@ +class Solution { + public int tallestBillboard(int[] rods) { + final int sum = Arrays.stream(rods).sum(); + // dp[i] := the maximum min-height of using rods so far to pile two piles + // that have height difference i + int[] dp = new int[sum + 1]; + Arrays.fill(dp, -1); + dp[0] = 0; + + for (final int h : rods) { + int[] prev = dp.clone(); + for (int i = 0; i <= sum - h; ++i) { + if (prev[i] < 0) + continue; + // Don't use this rod. + dp[i] = Math.max(dp[i], prev[i]); + // Put on the taller pile. + dp[i + h] = Math.max(dp[i + h], prev[i]); + // Put on the shorter pile. + dp[Math.abs(i - h)] = Math.max(dp[Math.abs(i - h)], prev[i] + Math.min(i, h)); + } + } + + return dp[0]; + } +} diff --git a/solutions/956. Tallest Billboard/956.cpp b/solutions/956. Tallest Billboard/956.cpp new file mode 100644 index 00000000000..79d734fd528 --- /dev/null +++ b/solutions/956. Tallest Billboard/956.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int tallestBillboard(vector& rods) { + const int n = rods.size(); + const int sum = accumulate(rods.begin(), rods.end(), 0); + // dp[i][j] := the maximum min-height of using rods[0..i) to pile two piles + // that have height difference j + vector> dp(n + 1, vector(sum + 1, -1)); + dp[0][0] = 0; + + for (int i = 1; i <= n; ++i) { + const int h = rods[i - 1]; + for (int j = 0; j <= sum - h; ++j) { + if (dp[i - 1][j] < 0) + continue; + // Don't use rods[i - 1]. + dp[i][j] = max(dp[i][j], dp[i - 1][j]); + // Put on the taller pile. + dp[i][j + h] = max(dp[i][j + h], dp[i - 1][j]); + // Put on the shorter pile. + dp[i][abs(j - h)] = max(dp[i][abs(j - h)], dp[i - 1][j] + min(j, h)); + } + } + + return dp[n][0]; + } +}; diff --git a/solutions/956. Tallest Billboard/956.java b/solutions/956. Tallest Billboard/956.java new file mode 100644 index 00000000000..83bd03d4889 --- /dev/null +++ b/solutions/956. Tallest Billboard/956.java @@ -0,0 +1,27 @@ +class Solution { + public int tallestBillboard(int[] rods) { + final int n = rods.length; + final int sum = Arrays.stream(rods).sum(); + // dp[i][j] := the maximum min-height of using rods[0..i) to pile two piles + // that have height difference j + int[][] dp = new int[n + 1][sum + 1]; + Arrays.stream(dp).forEach(A -> Arrays.fill(A, -1)); + dp[0][0] = 0; + + for (int i = 1; i <= n; ++i) { + final int h = rods[i - 1]; + for (int j = 0; j <= sum - h; ++j) { + if (dp[i - 1][j] < 0) + continue; + // Don't use rods[i - 1]. + dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]); + // Put on the taller pile. + dp[i][j + h] = Math.max(dp[i][j + h], dp[i - 1][j]); + // Put on the shorter pile. + dp[i][Math.abs(j - h)] = Math.max(dp[i][Math.abs(j - h)], dp[i - 1][j] + Math.min(j, h)); + } + } + + return dp[n][0]; + } +} diff --git a/solutions/957. Prison Cells After N Days/957.cpp b/solutions/957. Prison Cells After N Days/957.cpp new file mode 100644 index 00000000000..056bdfe83ca --- /dev/null +++ b/solutions/957. Prison Cells After N Days/957.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector prisonAfterNDays(vector& cells, int n) { + vector firstDayCells; + vector nextDayCells(cells.size()); + + for (int day = 0; n-- > 0; cells = nextDayCells, ++day) { + for (int i = 1; i + 1 < cells.size(); ++i) + nextDayCells[i] = cells[i - 1] == cells[i + 1]; + if (day == 0) + firstDayCells = nextDayCells; + else if (nextDayCells == firstDayCells) + n %= day; + } + + return cells; + } +}; diff --git a/solutions/957. Prison Cells After N Days/957.java b/solutions/957. Prison Cells After N Days/957.java new file mode 100644 index 00000000000..f9ccfdb80fd --- /dev/null +++ b/solutions/957. Prison Cells After N Days/957.java @@ -0,0 +1,17 @@ +class Solution { + public int[] prisonAfterNDays(int[] cells, int n) { + int[] firstDayCells = new int[cells.length]; + int[] nextDayCells = new int[cells.length]; + + for (int day = 0; n-- > 0; cells = nextDayCells.clone(), ++day) { + for (int i = 1; i + 1 < cells.length; ++i) + nextDayCells[i] = cells[i - 1] == cells[i + 1] ? 1 : 0; + if (day == 0) + firstDayCells = nextDayCells.clone(); + else if (Arrays.equals(nextDayCells, firstDayCells)) + n %= day; + } + + return cells; + } +} diff --git a/solutions/957. Prison Cells After N Days/957.py b/solutions/957. Prison Cells After N Days/957.py new file mode 100644 index 00000000000..214a613c20e --- /dev/null +++ b/solutions/957. Prison Cells After N Days/957.py @@ -0,0 +1,17 @@ +class Solution: + def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]: + nextDayCells = [0] * len(cells) + day = 0 + + while n > 0: + n -= 1 + for i in range(1, len(cells) - 1): + nextDayCells[i] = 1 if cells[i - 1] == cells[i + 1] else 0 + if day == 0: + firstDayCells = nextDayCells.copy() + elif nextDayCells == firstDayCells: + n %= day + cells = nextDayCells.copy() + day += 1 + + return cells diff --git a/solutions/958. Check Completeness of a Binary Tree/958-2.cpp b/solutions/958. Check Completeness of a Binary Tree/958-2.cpp new file mode 100644 index 00000000000..aa5be96d273 --- /dev/null +++ b/solutions/958. Check Completeness of a Binary Tree/958-2.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + bool isCompleteTree(TreeNode* root) { + const int count = getCount(root); + return validIndex(root, 1, count); + } + + private: + int getCount(TreeNode* root) { + if (root == nullptr) + return 0; + return 1 + getCount(root->left) + getCount(root->right); + } + + // Returns true if there's no index > the number of nodes. + bool validIndex(TreeNode* root, int index, int count) { + if (root == nullptr) + return true; + if (index > count) + return false; + return validIndex(root->left, index * 2, count) && + validIndex(root->right, index * 2 + 1, count); + } +}; diff --git a/solutions/958. Check Completeness of a Binary Tree/958-2.java b/solutions/958. Check Completeness of a Binary Tree/958-2.java new file mode 100644 index 00000000000..447a18db054 --- /dev/null +++ b/solutions/958. Check Completeness of a Binary Tree/958-2.java @@ -0,0 +1,21 @@ +class Solution { + public boolean isCompleteTree(TreeNode root) { + final int count = getCount(root); + return validIndex(root, 1, count); + } + + private int getCount(TreeNode root) { + if (root == null) + return 0; + return 1 + getCount(root.left) + getCount(root.right); + } + + // Returns true if there's no index > the number of nodes. + private boolean validIndex(TreeNode root, int index, int count) { + if (root == null) + return true; + if (index > count) + return false; + return validIndex(root.left, index * 2, count) && validIndex(root.right, index * 2 + 1, count); + } +} diff --git a/solutions/958. Check Completeness of a Binary Tree/958.cpp b/solutions/958. Check Completeness of a Binary Tree/958.cpp new file mode 100644 index 00000000000..9ead949dcec --- /dev/null +++ b/solutions/958. Check Completeness of a Binary Tree/958.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool isCompleteTree(TreeNode* root) { + if (root == nullptr) + return true; + + queue q{{root}}; + + while (q.front() != nullptr) { + TreeNode* node = q.front(); + q.pop(); + q.push(node->left); + q.push(node->right); + } + + while (!q.empty() && q.front() == nullptr) + q.pop(); + + return q.empty(); + } +}; diff --git a/solutions/958. Check Completeness of a Binary Tree/958.java b/solutions/958. Check Completeness of a Binary Tree/958.java new file mode 100644 index 00000000000..3c5cfa46682 --- /dev/null +++ b/solutions/958. Check Completeness of a Binary Tree/958.java @@ -0,0 +1,19 @@ +class Solution { + public boolean isCompleteTree(TreeNode root) { + if (root == null) + return true; + + Queue q = new LinkedList<>(Arrays.asList(root)); + + while (q.peek() != null) { + TreeNode node = q.poll(); + q.offer(node.left); + q.offer(node.right); + } + + while (!q.isEmpty() && q.peek() == null) + q.poll(); + + return q.isEmpty(); + } +} diff --git a/solutions/959. Regions Cut By Slashes/959.cpp b/solutions/959. Regions Cut By Slashes/959.cpp new file mode 100644 index 00000000000..a67a5b48e9f --- /dev/null +++ b/solutions/959. Regions Cut By Slashes/959.cpp @@ -0,0 +1,45 @@ +class Solution { + public: + int regionsBySlashes(vector& grid) { + const int n = grid.size(); + // G := upscaled grid + vector> g(n * 3, vector(n * 3)); + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == '/') { + g[i * 3][j * 3 + 2] = 1; + g[i * 3 + 1][j * 3 + 1] = 1; + g[i * 3 + 2][j * 3] = 1; + } else if (grid[i][j] == '\\') { + g[i * 3][j * 3] = 1; + g[i * 3 + 1][j * 3 + 1] = 1; + g[i * 3 + 2][j * 3 + 2] = 1; + } + + int ans = 0; + + for (int i = 0; i < n * 3; ++i) + for (int j = 0; j < n * 3; ++j) + if (g[i][j] == 0) { + dfs(g, i, j); + ++ans; + } + + return ans; + } + + private: + void dfs(vector>& g, int i, int j) { + if (i < 0 || i == g.size() || j < 0 || j == g[0].size()) + return; + if (g[i][j] != 0) + return; + + g[i][j] = 2; // Mark 2 as visited. + dfs(g, i + 1, j); + dfs(g, i - 1, j); + dfs(g, i, j + 1); + dfs(g, i, j - 1); + } +}; diff --git a/solutions/959. Regions Cut By Slashes/959.java b/solutions/959. Regions Cut By Slashes/959.java new file mode 100644 index 00000000000..b295eb983c2 --- /dev/null +++ b/solutions/959. Regions Cut By Slashes/959.java @@ -0,0 +1,43 @@ +class Solution { + public int regionsBySlashes(String[] grid) { + final int n = grid.length; + // G := upscaled grid + int[][] g = new int[n * 3][n * 3]; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (grid[i].charAt(j) == '/') { + g[i * 3][j * 3 + 2] = 1; + g[i * 3 + 1][j * 3 + 1] = 1; + g[i * 3 + 2][j * 3] = 1; + } else if (grid[i].charAt(j) == '\\') { + g[i * 3][j * 3] = 1; + g[i * 3 + 1][j * 3 + 1] = 1; + g[i * 3 + 2][j * 3 + 2] = 1; + } + + int ans = 0; + + for (int i = 0; i < n * 3; ++i) + for (int j = 0; j < n * 3; ++j) + if (g[i][j] == 0) { + dfs(g, i, j); + ++ans; + } + + return ans; + } + + private void dfs(int[][] g, int i, int j) { + if (i < 0 || i == g.length || j < 0 || j == g[0].length) + return; + if (g[i][j] != 0) + return; + + g[i][j] = 2; // Mark 2 as visited. + dfs(g, i + 1, j); + dfs(g, i - 1, j); + dfs(g, i, j + 1); + dfs(g, i, j - 1); + } +} diff --git a/solutions/96. Unique Binary Search Trees/96.cpp b/solutions/96. Unique Binary Search Trees/96.cpp new file mode 100644 index 00000000000..d60af287022 --- /dev/null +++ b/solutions/96. Unique Binary Search Trees/96.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int numTrees(int n) { + // dp[i] := the number of unique BST's that store values 1..i + vector dp(n + 1); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; ++i) + for (int j = 0; j < i; ++j) + dp[i] += dp[j] * dp[i - j - 1]; + + return dp[n]; + } +}; diff --git a/solutions/96. Unique Binary Search Trees/96.java b/solutions/96. Unique Binary Search Trees/96.java new file mode 100644 index 00000000000..2ec82c019c1 --- /dev/null +++ b/solutions/96. Unique Binary Search Trees/96.java @@ -0,0 +1,14 @@ +class Solution { + public int numTrees(int n) { + // dp[i] := the number of unique BST's that store values 1..i + int[] dp = new int[n + 1]; + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; ++i) + for (int j = 0; j < i; ++j) + dp[i] += dp[j] * dp[i - j - 1]; + + return dp[n]; + } +} diff --git a/solutions/96. Unique Binary Search Trees/96.py b/solutions/96. Unique Binary Search Trees/96.py new file mode 100644 index 00000000000..bf050da8f7a --- /dev/null +++ b/solutions/96. Unique Binary Search Trees/96.py @@ -0,0 +1,10 @@ +class Solution: + def numTrees(self, n: int) -> int: + # dp[i] := the number of unique BST's that store values 1..i + dp = [1, 1] + [0] * (n - 1) + + for i in range(2, n + 1): + for j in range(i): + dp[i] += dp[j] * dp[i - j - 1] + + return dp[n] diff --git a/solutions/960. Delete Columns to Make Sorted III/960.cpp b/solutions/960. Delete Columns to Make Sorted III/960.cpp new file mode 100644 index 00000000000..c471cd3154c --- /dev/null +++ b/solutions/960. Delete Columns to Make Sorted III/960.cpp @@ -0,0 +1,15 @@ +class Solution { + public: + int minDeletionSize(vector& strs) { + const int k = strs[0].length(); + // dp[i] the length of LIS ending in strs[*][i] + vector dp(k, 1); + + for (int i = 1; i < k; ++i) + for (int j = 0; j < i; ++j) + if (ranges::all_of(strs, [&](const string& s) { return s[j] <= s[i]; })) + dp[i] = max(dp[i], dp[j] + 1); + + return k - ranges::max(dp); + } +}; diff --git a/solutions/960. Delete Columns to Make Sorted III/960.java b/solutions/960. Delete Columns to Make Sorted III/960.java new file mode 100644 index 00000000000..f73d52337e5 --- /dev/null +++ b/solutions/960. Delete Columns to Make Sorted III/960.java @@ -0,0 +1,22 @@ +class Solution { + public int minDeletionSize(String[] strs) { + final int k = strs[0].length(); + // dp[i] the length of LIS ending in strs[*][i] + int[] dp = new int[k]; + Arrays.fill(dp, 1); + + for (int i = 1; i < k; ++i) + for (int j = 0; j < i; ++j) + if (isSorted(strs, j, i)) + dp[i] = Math.max(dp[i], dp[j] + 1); + + return k - Arrays.stream(dp).max().getAsInt(); + } + + private boolean isSorted(String[] strs, int j, int i) { + for (final String s : strs) + if (s.charAt(j) > s.charAt(i)) + return false; + return true; + } +} diff --git a/solutions/961. N-Repeated Element in Size 2N Array/961.cpp b/solutions/961. N-Repeated Element in Size 2N Array/961.cpp new file mode 100644 index 00000000000..5b15f6f9579 --- /dev/null +++ b/solutions/961. N-Repeated Element in Size 2N Array/961.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int repeatedNTimes(vector& nums) { + for (int i = 0; i + 2 < nums.size(); ++i) + if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2]) + return nums[i]; + return nums.back(); + } +}; diff --git a/solutions/961. N-Repeated Element in Size 2N Array/961.java b/solutions/961. N-Repeated Element in Size 2N Array/961.java new file mode 100644 index 00000000000..84977275ddb --- /dev/null +++ b/solutions/961. N-Repeated Element in Size 2N Array/961.java @@ -0,0 +1,8 @@ +class Solution { + public int repeatedNTimes(int[] nums) { + for (int i = 0; i + 2 < nums.length; ++i) + if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2]) + return nums[i]; + return nums[nums.length - 1]; + } +} diff --git a/solutions/961. N-Repeated Element in Size 2N Array/961.py b/solutions/961. N-Repeated Element in Size 2N Array/961.py new file mode 100644 index 00000000000..fe39f817855 --- /dev/null +++ b/solutions/961. N-Repeated Element in Size 2N Array/961.py @@ -0,0 +1,6 @@ +class Solution: + def repeatedNTimes(self, nums: List[int]) -> int: + for i in range(len(nums) - 2): + if nums[i] == nums[i + 1] or nums[i] == nums[i + 2]: + return nums[i] + return nums[-1] diff --git a/solutions/962. Maximum Width Ramp/962.cpp b/solutions/962. Maximum Width Ramp/962.cpp new file mode 100644 index 00000000000..09a1938be96 --- /dev/null +++ b/solutions/962. Maximum Width Ramp/962.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int maxWidthRamp(vector& nums) { + int ans = 0; + stack stack; + + for (int i = 0; i < nums.size(); ++i) + if (stack.empty() || nums[i] < nums[stack.top()]) + stack.push(i); + + for (int i = nums.size() - 1; i > ans; --i) + while (!stack.empty() && nums[i] >= nums[stack.top()]) + ans = max(ans, i - stack.top()), stack.pop(); + + return ans; + } +}; diff --git a/solutions/962. Maximum Width Ramp/962.java b/solutions/962. Maximum Width Ramp/962.java new file mode 100644 index 00000000000..4314ac92437 --- /dev/null +++ b/solutions/962. Maximum Width Ramp/962.java @@ -0,0 +1,16 @@ +class Solution { + public int maxWidthRamp(int[] nums) { + int ans = 0; + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < nums.length; ++i) + if (stack.isEmpty() || nums[i] < nums[stack.peek()]) + stack.push(i); + + for (int i = nums.length - 1; i > ans; --i) + while (!stack.isEmpty() && nums[i] >= nums[stack.peek()]) + ans = Math.max(ans, i - stack.pop()); + + return ans; + } +} diff --git a/solutions/962. Maximum Width Ramp/962.py b/solutions/962. Maximum Width Ramp/962.py new file mode 100644 index 00000000000..80e74a6fd26 --- /dev/null +++ b/solutions/962. Maximum Width Ramp/962.py @@ -0,0 +1,14 @@ +class Solution: + def maxWidthRamp(self, nums: List[int]) -> int: + ans = 0 + stack = [] + + for i, num in enumerate(nums): + if stack == [] or num <= nums[stack[-1]]: + stack.append(i) + + for i, num in reversed(list(enumerate(nums))): + while stack and num >= nums[stack[-1]]: + ans = max(ans, i - stack.pop()) + + return ans diff --git a/solutions/963. Minimum Area Rectangle II/963.cpp b/solutions/963. Minimum Area Rectangle II/963.cpp new file mode 100644 index 00000000000..0fe9267f115 --- /dev/null +++ b/solutions/963. Minimum Area Rectangle II/963.cpp @@ -0,0 +1,38 @@ +class Solution { + public: + double minAreaFreeRect(vector>& points) { + long ans = LONG_MAX; + // For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}. + unordered_map>> centerToPoints; + + for (const vector& A : points) + for (const vector& B : points) { + const int center = hash(A, B); + centerToPoints[center].emplace_back(A[0], A[1], B[0], B[1]); + } + + // For all pair points "that share the same center". + for (const auto& [_, points] : centerToPoints) + for (const auto& [ax, ay, bx, by] : points) + for (const auto& [cx, cy, dx, dy] : points) + // AC is perpendicular to AD. + // AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0. + if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) { + const long squaredArea = + dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy); + if (squaredArea > 0) + ans = min(ans, squaredArea); + } + + return ans == LONG_MAX ? 0 : sqrt(ans); + } + + private: + int hash(const vector& p, const vector& q) { + return ((long)(p[0] + q[0]) << 16) + (p[1] + q[1]); + } + + long dist(int px, int py, int qx, int qy) { + return (px - qx) * (px - qx) + (py - qy) * (py - qy); + } +}; diff --git a/solutions/963. Minimum Area Rectangle II/963.java b/solutions/963. Minimum Area Rectangle II/963.java new file mode 100644 index 00000000000..3f877c0630c --- /dev/null +++ b/solutions/963. Minimum Area Rectangle II/963.java @@ -0,0 +1,41 @@ +class Solution { + public double minAreaFreeRect(int[][] points) { + Long ans = Long.MAX_VALUE; + // For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}. + Map> centerToPoints = new HashMap<>(); + + for (int[] A : points) + for (int[] B : points) { + int center = hash(A, B); + if (centerToPoints.get(center) == null) + centerToPoints.put(center, new ArrayList<>()); + centerToPoints.get(center).add(new int[] {A[0], A[1], B[0], B[1]}); + } + + // For all pair points "that share the same center". + for (List pointPairs : centerToPoints.values()) + for (int[] ab : pointPairs) + for (int[] cd : pointPairs) { + final int ax = ab[0], ay = ab[1]; + final int cx = cd[0], cy = cd[1]; + final int dx = cd[2], dy = cd[3]; + // AC is perpendicular to AD. + // AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0. + if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) { + Long squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy); + if (squaredArea > 0) + ans = Math.min(ans, squaredArea); + } + } + + return ans == Long.MAX_VALUE ? 0 : Math.sqrt(ans); + } + + private int hash(int[] p, int[] q) { + return ((p[0] + q[0]) << 16) + (p[1] + q[1]); + } + + private Long dist(long px, long py, long qx, long qy) { + return (px - qx) * (px - qx) + (py - qy) * (py - qy); + } +} diff --git a/solutions/963. Minimum Area Rectangle II/963.py b/solutions/963. Minimum Area Rectangle II/963.py new file mode 100644 index 00000000000..147918ceca2 --- /dev/null +++ b/solutions/963. Minimum Area Rectangle II/963.py @@ -0,0 +1,26 @@ +class Solution: + def minAreaFreeRect(self, points: List[List[int]]) -> float: + ans = math.inf + # For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}. + centerToPoints = collections.defaultdict(list) + + for ax, ay in points: + for bx, by in points: + center = ((ax + bx) / 2, (ay + by) / 2) + centerToPoints[center].append((ax, ay, bx, by)) + + def dist(px: int, py: int, qx: int, qy: int) -> float: + return (px - qx)**2 + (py - qy)**2 + + # For all pair points "that share the same center". + for points in centerToPoints.values(): + for ax, ay, _, _ in points: + for cx, cy, dx, dy in points: + # AC is perpendicular to AD. + # AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0. + if (cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0: + squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy) + if squaredArea > 0: + ans = min(ans, squaredArea) + + return 0 if ans == math.inf else math.sqrt(ans) diff --git a/solutions/964. Least Operators to Express Number/964.cpp b/solutions/964. Least Operators to Express Number/964.cpp new file mode 100644 index 00000000000..eef1c2221dc --- /dev/null +++ b/solutions/964. Least Operators to Express Number/964.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + int leastOpsExpressTarget(int x, int target) { + return dfs(x, target, {}); + } + + private: + int dfs(int x, int target, unordered_map&& mem) { + if (const auto it = mem.find(target); it != mem.cend()) + return it->second; + if (x > target) + return min(2 * target - 1, 2 * (x - target)); + if (x == target) + return 0; + + long prod = x; + int n = 0; + while (prod < target) { + prod *= x; + ++n; + } + if (prod == target) + return mem[target] = n; + + int ans = dfs(x, target - prod / x, move(mem)) + n; + if (prod < 2 * target) + ans = min(ans, dfs(x, prod - target, move(mem)) + n + 1); + return mem[target] = ans; + } +}; diff --git a/solutions/964. Least Operators to Express Number/964.java b/solutions/964. Least Operators to Express Number/964.java new file mode 100644 index 00000000000..f83eb9770b9 --- /dev/null +++ b/solutions/964. Least Operators to Express Number/964.java @@ -0,0 +1,33 @@ +class Solution { + public int leastOpsExpressTarget(int x, int target) { + return dfs(x, target); + } + + private Map mem = new HashMap<>(); + + private int dfs(int x, int target) { + if (mem.containsKey(target)) + return mem.get(target); + if (x > target) + return Math.min(2 * target - 1, 2 * (x - target)); + if (x == target) + return 0; + + long prod = x; + int n = 0; + while (prod < target) { + prod *= x; + ++n; + } + if (prod == target) { + mem.put(target, n); + return mem.get(target); + } + + int ans = dfs(x, target - (int) (prod / (long) x)) + n; + if (prod < 2 * target) + ans = Math.min(ans, dfs(x, (int) (prod - (long) target)) + n + 1); + mem.put(target, ans); + return ans; + } +} diff --git a/solutions/964. Least Operators to Express Number/964.py b/solutions/964. Least Operators to Express Number/964.py new file mode 100644 index 00000000000..7e4dd6f5378 --- /dev/null +++ b/solutions/964. Least Operators to Express Number/964.py @@ -0,0 +1,23 @@ +class Solution: + def leastOpsExpressTarget(self, x: int, target: int) -> int: + @functools.lru_cache(None) + def dfs(target): + if x > target: + return min(2 * target - 1, 2 * (x - target)) + if x == target: + return 0 + + prod = x + n = 0 + while prod < target: + prod *= x + n += 1 + if prod == target: + return n + + ans = dfs(target - prod // x) + n + if prod < 2 * target: + ans = min(ans, dfs(prod - target) + n + 1) + return ans + + return dfs(target) diff --git a/solutions/965. Univalued Binary Tree/965.cpp b/solutions/965. Univalued Binary Tree/965.cpp new file mode 100644 index 00000000000..4ab51b923b1 --- /dev/null +++ b/solutions/965. Univalued Binary Tree/965.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + bool isUnivalTree(TreeNode* root) { + if (root == nullptr) + return true; + if (root->left != nullptr && root->left->val != root->val) + return false; + if (root->right != nullptr && root->right->val != root->val) + return false; + return isUnivalTree(root->left) && isUnivalTree(root->right); + } +}; diff --git a/solutions/965. Univalued Binary Tree/965.java b/solutions/965. Univalued Binary Tree/965.java new file mode 100644 index 00000000000..4465845f2a6 --- /dev/null +++ b/solutions/965. Univalued Binary Tree/965.java @@ -0,0 +1,11 @@ +class Solution { + public boolean isUnivalTree(TreeNode root) { + if (root == null) + return true; + if (root.left != null && root.left.val != root.val) + return false; + if (root.right != null && root.right.val != root.val) + return false; + return isUnivalTree(root.left) && isUnivalTree(root.right); + } +} diff --git a/solutions/965. Univalued Binary Tree/965.py b/solutions/965. Univalued Binary Tree/965.py new file mode 100644 index 00000000000..f44dcf2908a --- /dev/null +++ b/solutions/965. Univalued Binary Tree/965.py @@ -0,0 +1,9 @@ +class Solution: + def isUnivalTree(self, root: Optional[TreeNode]) -> bool: + if not root: + return True + if root.left and root.left.val != root.val: + return False + if root.right and root.right.val != root.val: + return False + return self.isUnivalTree(root.left) and self.isUnivalTree(root.right) diff --git a/solutions/966. Vowel Spellchecker/966.cpp b/solutions/966. Vowel Spellchecker/966.cpp new file mode 100644 index 00000000000..9459ec5dfa8 --- /dev/null +++ b/solutions/966. Vowel Spellchecker/966.cpp @@ -0,0 +1,46 @@ +class Solution { + public: + vector spellchecker(vector& wordlist, + vector& queries) { + vector ans; + unordered_map dict; + + for (const string& word : wordlist) { + dict.insert({word, word}); + dict.insert({lowerKey(word), word}); + dict.insert({vowelKey(word), word}); + } + + for (const string& query : queries) + if (const auto it = dict.find(query); it != dict.cend()) + ans.push_back(it->second); + else if (const auto it = dict.find(lowerKey(query)); it != dict.cend()) + ans.push_back(it->second); + else if (const auto it = dict.find(vowelKey(query)); it != dict.cend()) + ans.push_back(it->second); + else + ans.push_back(""); + + return ans; + } + + private: + string lowerKey(const string& word) { + string s{"$"}; + for (const char c : word) + s += tolower(c); + return s; + } + + string vowelKey(const string& word) { + string s; + for (const char c : word) + s += isVowel(c) ? '*' : tolower(c); + return s; + } + + bool isVowel(char c) { + static constexpr string_view kVowels = "aeiouAEIOU"; + return kVowels.find(c) != string_view::npos; + } +}; diff --git a/solutions/966. Vowel Spellchecker/966.java b/solutions/966. Vowel Spellchecker/966.java new file mode 100644 index 00000000000..22e6e732f15 --- /dev/null +++ b/solutions/966. Vowel Spellchecker/966.java @@ -0,0 +1,39 @@ +class Solution { + public String[] spellchecker(String[] wordlist, String[] queries) { + List ans = new ArrayList<>(); + Map dict = new HashMap<>(); + + for (final String word : wordlist) { + dict.putIfAbsent(word, word); + dict.putIfAbsent(lowerKey(word), word); + dict.putIfAbsent(vowelKey(word), word); + } + + for (final String query : queries) + if (dict.containsKey(query)) + ans.add(dict.get(query)); + else if (dict.containsKey(lowerKey(query))) + ans.add(dict.get(lowerKey(query))); + else if (dict.containsKey(vowelKey(query))) + ans.add(dict.get(vowelKey(query))); + else + ans.add(""); + + return ans.toArray(new String[0]); + } + + private String lowerKey(final String word) { + return "$" + word.toLowerCase(); + } + + private String vowelKey(final String word) { + StringBuilder sb = new StringBuilder(); + for (final char c : word.toCharArray()) + sb.append(isVowel(c) ? '*' : Character.toLowerCase(c)); + return sb.toString(); + } + + private boolean isVowel(char c) { + return "aeiouAEIOU".indexOf(c) != -1; + } +} diff --git a/solutions/966. Vowel Spellchecker/966.py b/solutions/966. Vowel Spellchecker/966.py new file mode 100644 index 00000000000..979ad5ee76a --- /dev/null +++ b/solutions/966. Vowel Spellchecker/966.py @@ -0,0 +1,27 @@ +class Solution: + def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: + def lowerKey(word: str) -> str: + return '$' + ''.join([c.lower() for c in word]) + + def vowelKey(word: str) -> str: + return ''.join(['*' if c.lower() in 'aeiou' else c.lower() for c in word]) + + ans = [] + dict = {} + + for word in wordlist: + dict.setdefault(word, word) + dict.setdefault(lowerKey(word), word) + dict.setdefault(vowelKey(word), word) + + for query in queries: + if query in dict: + ans.append(dict[query]) + elif lowerKey(query) in dict: + ans.append(dict[lowerKey(query)]) + elif vowelKey(query) in dict: + ans.append(dict[vowelKey(query)]) + else: + ans.append('') + + return ans diff --git a/solutions/967. Numbers With Same Consecutive Differences/967.cpp b/solutions/967. Numbers With Same Consecutive Differences/967.cpp new file mode 100644 index 00000000000..ee02f0f1318 --- /dev/null +++ b/solutions/967. Numbers With Same Consecutive Differences/967.cpp @@ -0,0 +1,34 @@ +class Solution { + public: + vector numsSameConsecDiff(int n, int k) { + if (n == 1) + return {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + vector ans; + + if (k == 0) { + for (char c = '1'; c <= '9'; ++c) + ans.push_back(stoi(string(n, c))); + return ans; + } + + for (int num = 1; num <= 9; ++num) + dfs(n - 1, k, num, ans); + + return ans; + } + + private: + void dfs(int n, int k, int num, vector& ans) { + if (n == 0) { + ans.push_back(num); + return; + } + + const int lastDigit = num % 10; + + for (const int nextDigit : {lastDigit - k, lastDigit + k}) + if (0 <= nextDigit && nextDigit <= 9) + dfs(n - 1, k, num * 10 + nextDigit, ans); + } +}; diff --git a/solutions/967. Numbers With Same Consecutive Differences/967.java b/solutions/967. Numbers With Same Consecutive Differences/967.java new file mode 100644 index 00000000000..4e3b34f3ddd --- /dev/null +++ b/solutions/967. Numbers With Same Consecutive Differences/967.java @@ -0,0 +1,34 @@ +class Solution { + public int[] numsSameConsecDiff(int n, int k) { + if (n == 1) + return new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + List ans = new ArrayList<>(); + + if (k == 0) { + for (char c = '1'; c <= '9'; ++c) { + final String s = String.valueOf(c).repeat(n); + ans.add(Integer.parseInt(s)); + } + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + for (int num = 1; num <= 9; ++num) + dfs(n - 1, k, num, ans); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } + + private void dfs(int n, int k, int num, List ans) { + if (n == 0) { + ans.add(num); + return; + } + + final int lastDigit = num % 10; + + for (final int nextDigit : new int[] {lastDigit - k, lastDigit + k}) + if (0 <= nextDigit && nextDigit <= 9) + dfs(n - 1, k, num * 10 + nextDigit, ans); + } +} diff --git a/solutions/968. Binary Tree Cameras/968.cpp b/solutions/968. Binary Tree Cameras/968.cpp new file mode 100644 index 00000000000..1bc1f6d6a4a --- /dev/null +++ b/solutions/968. Binary Tree Cameras/968.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + int minCameraCover(TreeNode* root) { + vector ans = dfs(root); + return min(ans[1], ans[2]); + } + + private: + // 0 := all the nodes below the root are covered except the root + // 1 := all the nodes below and including the root are covered with no camera + // 2 := all nodes below and including the root are covered with a camera + vector dfs(TreeNode* root) { + if (root == nullptr) + return {0, 0, 1000}; + + vector l = dfs(root->left); + vector r = dfs(root->right); + + const int s0 = l[1] + r[1]; + const int s1 = min(l[2] + min(r[1], r[2]), // + r[2] + min(l[1], l[2])); + const int s2 = min({l[0], l[1], l[2]}) + // + min({r[0], r[1], r[2]}) + 1; + return {s0, s1, s2}; + } +}; diff --git a/solutions/968. Binary Tree Cameras/968.java b/solutions/968. Binary Tree Cameras/968.java new file mode 100644 index 00000000000..298da2d45e3 --- /dev/null +++ b/solutions/968. Binary Tree Cameras/968.java @@ -0,0 +1,25 @@ +class Solution { + public int minCameraCover(TreeNode root) { + int[] ans = dfs(root); + return Math.min(ans[1], ans[2]); + } + + // 0 := all the nodes below the root are covered except the root + // 1 := all the nodes below and including the root are covered with no camera + // 2 := all nodes below and including the root are covered with a camera + private int[] dfs(TreeNode root) { + if (root == null) + return new int[] {0, 0, 1000}; + + int[] l = dfs(root.left); + int[] r = dfs(root.right); + + final int s0 = l[1] + r[1]; + final int s1 = Math.min(l[2] + Math.min(r[1], r[2]), // + r[2] + Math.min(l[1], l[2])); + final int s2 = Math.min(l[0], Math.min(l[1], l[2])) + // + Math.min(r[0], Math.min(r[1], r[2])) + 1; + + return new int[] {s0, s1, s2}; + } +} diff --git a/solutions/969. Pancake Sorting/969.cpp b/solutions/969. Pancake Sorting/969.cpp new file mode 100644 index 00000000000..7489a8c0ad6 --- /dev/null +++ b/solutions/969. Pancake Sorting/969.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector pancakeSort(vector& arr) { + vector ans; + + for (int target = arr.size(); target >= 1; --target) { + int index = find(arr, target); + reverse(arr.begin(), arr.begin() + index + 1); + reverse(arr.begin(), arr.begin() + target); + ans.push_back(index + 1); + ans.push_back(target); + } + + return ans; + } + + private: + int find(vector& arr, int target) { + for (int i = 0; i < arr.size(); ++i) + if (arr[i] == target) + return i; + throw; + } +}; diff --git a/solutions/969. Pancake Sorting/969.java b/solutions/969. Pancake Sorting/969.java new file mode 100644 index 00000000000..3c820424e59 --- /dev/null +++ b/solutions/969. Pancake Sorting/969.java @@ -0,0 +1,33 @@ +class Solution { + public List pancakeSort(int[] arr) { + List ans = new ArrayList<>(); + + for (int target = arr.length; target >= 1; --target) { + int index = find(arr, target); + reverse(arr, 0, index); + reverse(arr, 0, target - 1); + ans.add(index + 1); + ans.add(target); + } + + return ans; + } + + private int find(int[] arr, int target) { + for (int i = 0; i < arr.length; ++i) + if (arr[i] == target) + return i; + throw new IllegalArgumentException(); + } + + private void reverse(int[] arr, int l, int r) { + while (l < r) + swap(arr, l++, r--); + } + + private void swap(int[] arr, int l, int r) { + int temp = arr[l]; + arr[l] = arr[r]; + arr[r] = temp; + } +} diff --git a/solutions/969. Pancake Sorting/969.py b/solutions/969. Pancake Sorting/969.py new file mode 100644 index 00000000000..f7d7ae0ae99 --- /dev/null +++ b/solutions/969. Pancake Sorting/969.py @@ -0,0 +1,12 @@ +class Solution: + def pancakeSort(self, arr: List[int]) -> List[int]: + ans = [] + + for target in range(len(arr), 0, -1): + index = arr.index(target) + arr[:index + 1] = arr[:index + 1][::-1] + arr[:target] = arr[:target][::-1] + ans.append(index + 1) + ans.append(target) + + return ans diff --git a/solutions/97. Interleaving String/97-2.cpp b/solutions/97. Interleaving String/97-2.cpp new file mode 100644 index 00000000000..5936983b9b1 --- /dev/null +++ b/solutions/97. Interleaving String/97-2.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + bool isInterleave(string s1, string s2, string s3) { + const int m = s1.length(); + const int n = s2.length(); + if (m + n != s3.length()) + return false; + + vector dp(n + 1); + + for (int i = 0; i <= m; ++i) + for (int j = 0; j <= n; ++j) + if (i == 0 && j == 0) + dp[j] = true; + else if (i == 0) + dp[j] = dp[j - 1] && s2[j - 1] == s3[j - 1]; + else if (j == 0) + dp[j] = dp[j] && s1[i - 1] == s3[i - 1]; + else + dp[j] = dp[j] && s1[i - 1] == s3[i + j - 1] || + dp[j - 1] && s2[j - 1] == s3[i + j - 1]; + + return dp[n]; + } +}; diff --git a/solutions/97. Interleaving String/97-2.java b/solutions/97. Interleaving String/97-2.java new file mode 100644 index 00000000000..e077a2a1929 --- /dev/null +++ b/solutions/97. Interleaving String/97-2.java @@ -0,0 +1,24 @@ +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + final int m = s1.length(); + final int n = s2.length(); + if (m + n != s3.length()) + return false; + + boolean[] dp = new boolean[n + 1]; + + for (int i = 0; i <= m; ++i) + for (int j = 0; j <= n; ++j) + if (i == 0 && j == 0) + dp[j] = true; + else if (i == 0) + dp[j] = dp[j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1); + else if (j == 0) + dp[j] = dp[j] && s1.charAt(i - 1) == s3.charAt(i - 1); + else + dp[j] = dp[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1) || + dp[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1); + + return dp[n]; + } +} diff --git a/solutions/97. Interleaving String/97-2.py b/solutions/97. Interleaving String/97-2.py new file mode 100644 index 00000000000..3c8fd5be851 --- /dev/null +++ b/solutions/97. Interleaving String/97-2.py @@ -0,0 +1,22 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m = len(s1) + n = len(s2) + if m + n != len(s3): + return False + + dp = [False] * (n + 1) + + for i in range(m + 1): + for j in range(n + 1): + if i == 0 and j == 0: + dp[j] = True + elif i == 0: + dp[j] = dp[j - 1] and s2[j - 1] == s3[j - 1] + elif j == 0: + dp[j] = dp[j] and s1[i - 1] == s3[i - 1] + else: + dp[j] = (dp[j] and s1[i - 1] == s3[i + j - 1]) or \ + (dp[j - 1] and s2[j - 1] == s3[i + j - 1]) + + return dp[n] diff --git a/solutions/97. Interleaving String/97.cpp b/solutions/97. Interleaving String/97.cpp new file mode 100644 index 00000000000..6c18e582be6 --- /dev/null +++ b/solutions/97. Interleaving String/97.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + bool isInterleave(string s1, string s2, string s3) { + const int m = s1.length(); + const int n = s2.length(); + if (m + n != s3.length()) + return false; + + // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of + // s1[0..i) and s2[0..j) + vector> dp(m + 1, vector(n + 1)); + dp[0][0] = true; + + for (int i = 1; i <= m; ++i) + dp[i][0] = dp[i - 1][0] && s1[i - 1] == s3[i - 1]; + + for (int j = 1; j <= n; ++j) + dp[0][j] = dp[0][j - 1] && s2[j - 1] == s3[j - 1]; + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1] || + dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]; + + return dp[m][n]; + } +}; diff --git a/solutions/97. Interleaving String/97.java b/solutions/97. Interleaving String/97.java new file mode 100644 index 00000000000..5c8c96cadcf --- /dev/null +++ b/solutions/97. Interleaving String/97.java @@ -0,0 +1,26 @@ +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + final int m = s1.length(); + final int n = s2.length(); + if (m + n != s3.length()) + return false; + + // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of + // s1[0..i) and s2[0..j) + boolean[][] dp = new boolean[m + 1][n + 1]; + dp[0][0] = true; + + for (int i = 1; i <= m; ++i) + dp[i][0] = dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1); + + for (int j = 1; j <= n; ++j) + dp[0][j] = dp[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1); + + for (int i = 1; i <= m; ++i) + for (int j = 1; j <= n; ++j) + dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1) || + dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1); + + return dp[m][n]; + } +} diff --git a/solutions/97. Interleaving String/97.py b/solutions/97. Interleaving String/97.py new file mode 100644 index 00000000000..136abf355b8 --- /dev/null +++ b/solutions/97. Interleaving String/97.py @@ -0,0 +1,24 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m = len(s1) + n = len(s2) + if m + n != len(s3): + return False + + # dp[i][j] := true if s3[0..i + j) is formed by the interleaving of + # s1[0..i) and s2[0..j) + dp = [[False] * (n + 1) for _ in range(m + 1)] + dp[0][0] = True + + for i in range(1, m + 1): + dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1] + + for j in range(1, n + 1): + dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1] + + for i in range(1, m + 1): + for j in range(1, n + 1): + dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or \ + (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]) + + return dp[m][n] diff --git a/solutions/970. Powerful Integers/970.cpp b/solutions/970. Powerful Integers/970.cpp new file mode 100644 index 00000000000..7e86c0a23a0 --- /dev/null +++ b/solutions/970. Powerful Integers/970.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector powerfulIntegers(int x, int y, int bound) { + unordered_set ans; + + for (int i = 1; i < bound; i *= x) { + for (int j = 1; i + j <= bound; j *= y) { + ans.insert(i + j); + if (y == 1) + break; + } + if (x == 1) + break; + } + + return {ans.begin(), ans.end()}; + } +}; diff --git a/solutions/970. Powerful Integers/970.java b/solutions/970. Powerful Integers/970.java new file mode 100644 index 00000000000..02d7a6cf87b --- /dev/null +++ b/solutions/970. Powerful Integers/970.java @@ -0,0 +1,17 @@ +class Solution { + public List powerfulIntegers(int x, int y, int bound) { + Set ans = new HashSet<>(); + + for (int i = 1; i < bound; i *= x) { + for (int j = 1; i + j <= bound; j *= y) { + ans.add(i + j); + if (y == 1) + break; + } + if (x == 1) + break; + } + + return new ArrayList<>(ans); + } +} diff --git a/solutions/970. Powerful Integers/970.py b/solutions/970. Powerful Integers/970.py new file mode 100644 index 00000000000..f898fc8c971 --- /dev/null +++ b/solutions/970. Powerful Integers/970.py @@ -0,0 +1,5 @@ +class Solution: + def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: + xs = {x**i for i in range(20) if x**i < bound} + ys = {y**i for i in range(20) if y**i < bound} + return list({i + j for i in xs for j in ys if i + j <= bound}) diff --git a/solutions/971. Flip Binary Tree To Match Preorder Traversal/971.cpp b/solutions/971. Flip Binary Tree To Match Preorder Traversal/971.cpp new file mode 100644 index 00000000000..4277ddbaf82 --- /dev/null +++ b/solutions/971. Flip Binary Tree To Match Preorder Traversal/971.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector flipMatchVoyage(TreeNode* root, vector& voyage) { + vector ans; + dfs(root, 0, voyage, ans); + return ans; + } + + private: + void dfs(TreeNode* root, int&& i, const vector& voyage, + vector& ans) { + if (root == nullptr) + return; + if (root->val != voyage[i++]) { + ans.clear(); + ans.push_back(-1); + return; + } + + if (i < voyage.size() && root->left && root->left->val != voyage[i]) { + // Flip the root. + ans.push_back(root->val); + dfs(root->right, move(i), voyage, ans); + dfs(root->left, move(i), voyage, ans); + } else { + dfs(root->left, move(i), voyage, ans); + dfs(root->right, move(i), voyage, ans); + } + } +}; diff --git a/solutions/971. Flip Binary Tree To Match Preorder Traversal/971.java b/solutions/971. Flip Binary Tree To Match Preorder Traversal/971.java new file mode 100644 index 00000000000..3f9d43714e0 --- /dev/null +++ b/solutions/971. Flip Binary Tree To Match Preorder Traversal/971.java @@ -0,0 +1,31 @@ +class Solution { + public List flipMatchVoyage(TreeNode root, int[] voyage) { + List ans = new ArrayList<>(); + + dfs(root, voyage, ans); + + return ans; + } + + private int i = 0; + + private void dfs(TreeNode root, int[] voyage, List ans) { + if (root == null) + return; + if (root.val != voyage[i++]) { + ans.clear(); + ans.add(-1); + return; + } + + if (i < voyage.length && root.left != null && root.left.val != voyage[i]) { + // Flip the root. + ans.add(root.val); + dfs(root.right, voyage, ans); + dfs(root.left, voyage, ans); + } else { + dfs(root.left, voyage, ans); + dfs(root.right, voyage, ans); + } + } +} diff --git a/solutions/972. Equal Rational Numbers/972.cpp b/solutions/972. Equal Rational Numbers/972.cpp new file mode 100644 index 00000000000..56b20a007bb --- /dev/null +++ b/solutions/972. Equal Rational Numbers/972.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + bool isRationalEqual(string s, string t) { + return abs(valueOf(s) - valueOf(t)) < 1e-9; + } + + private: + const vector ratios{1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999}; + + double valueOf(const string& s) { + if (s.find('(') == string::npos) + return stod(s); + + // Get the indices.. + const int leftParenIndex = s.find_first_of('('); + const int rightParenIndex = s.find_first_of(')'); + const int dotIndex = s.find_first_of('.'); + + // integerAndNonRepeating := <.> + const double integerAndNonRepeating = stod(s.substr(0, leftParenIndex)); + const int nonRepeatingLength = leftParenIndex - dotIndex - 1; + + // repeating := + const int repeating = stoi(s.substr(leftParenIndex + 1, rightParenIndex)); + const int repeatingLength = rightParenIndex - leftParenIndex - 1; + return integerAndNonRepeating + + repeating * pow(0.1, nonRepeatingLength) * ratios[repeatingLength]; + } +}; diff --git a/solutions/972. Equal Rational Numbers/972.java b/solutions/972. Equal Rational Numbers/972.java new file mode 100644 index 00000000000..ff0ca27f464 --- /dev/null +++ b/solutions/972. Equal Rational Numbers/972.java @@ -0,0 +1,26 @@ +class Solution { + public boolean isRationalEqual(String s, String t) { + return Math.abs(valueOf(s) - valueOf(t)) < 1e-9; + } + + private static double[] ratios = new double[] {1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999}; + + private double valueOf(final String s) { + if (!s.contains("(")) + return Double.valueOf(s); + + // Get the indices.. + final int leftParenIndex = s.indexOf('('); + final int rightParenIndex = s.indexOf(')'); + final int dotIndex = s.indexOf('.'); + + // integerAndNonRepeating := <.> + final double nonRepeating = Double.valueOf(s.substring(0, leftParenIndex)); + final int nonRepeatingLength = leftParenIndex - dotIndex - 1; + + // repeating := + final int repeating = Integer.parseInt(s.substring(leftParenIndex + 1, rightParenIndex)); + final int repeatingLength = rightParenIndex - leftParenIndex - 1; + return nonRepeating + repeating * Math.pow(0.1, nonRepeatingLength) * ratios[repeatingLength]; + } +} diff --git a/solutions/972. Equal Rational Numbers/972.py b/solutions/972. Equal Rational Numbers/972.py new file mode 100644 index 00000000000..71bd30d1ab2 --- /dev/null +++ b/solutions/972. Equal Rational Numbers/972.py @@ -0,0 +1,23 @@ +class Solution: + def isRationalEqual(self, s: str, t: str) -> bool: + ratios = [1, 1 / 9, 1 / 99, 1 / 999, 1 / 9999] + + def valueOf(s: str) -> float: + if s.find('(') == -1: + return float(s) + + # Get the indices. + leftParenIndex = s.find('(') + rightParenIndex = s.find(')') + dotIndex = s.find('.') + + # integerAndNonRepeating := <.> + integerAndNonRepeating = float(s[:leftParenIndex]) + nonRepeatingLength = leftParenIndex - dotIndex - 1 + + # repeating := + repeating = int(s[leftParenIndex + 1:rightParenIndex]) + repeatingLength = rightParenIndex - leftParenIndex - 1 + return integerAndNonRepeating + repeating * 0.1**nonRepeatingLength * ratios[repeatingLength] + + return abs(valueOf(s) - valueOf(t)) < 1e-9 diff --git a/solutions/973. K Closest Points to Origin/973-2.cpp b/solutions/973. K Closest Points to Origin/973-2.cpp new file mode 100644 index 00000000000..f42d14348cf --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973-2.cpp @@ -0,0 +1,30 @@ +class Solution { + public: + vector> kClosest(vector>& points, int k) { + quickSelect(points, 0, points.size() - 1, k); + return {points.begin(), points.begin() + k}; + }; + + private: + void quickSelect(vector>& points, int l, int r, int k) { + const vector pivot = points[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (squareDist(points[i]) <= squareDist(pivot)) + swap(points[nextSwapped++], points[i]); + swap(points[nextSwapped], points[r]); + + const int count = nextSwapped - l + 1; // the number of points <= pivot + if (count == k) + return; + if (count > k) + quickSelect(points, l, nextSwapped - 1, k); + else + quickSelect(points, nextSwapped + 1, r, k - count); + } + + int squareDist(const vector& p) { + return p[0] * p[0] + p[1] * p[1]; + } +}; diff --git a/solutions/973. K Closest Points to Origin/973-2.java b/solutions/973. K Closest Points to Origin/973-2.java new file mode 100644 index 00000000000..f7975b523a0 --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973-2.java @@ -0,0 +1,34 @@ +class Solution { + public int[][] kClosest(int[][] points, int k) { + quickSelect(points, 0, points.length - 1, k); + return Arrays.copyOfRange(points, 0, k); + } + + private void quickSelect(int[][] points, int l, int r, int k) { + final int[] pivot = points[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (squareDist(points[i]) <= squareDist(pivot)) + swap(points, nextSwapped++, i); + swap(points, nextSwapped, r); + + final int count = nextSwapped - l + 1; // the number of points <= pivot + if (count == k) + return; + if (count > k) + quickSelect(points, l, nextSwapped - 1, k); + else + quickSelect(points, nextSwapped + 1, r, k - count); + } + + private int squareDist(int[] p) { + return p[0] * p[0] + p[1] * p[1]; + } + + private void swap(int[][] points, int i, int j) { + final int[] temp = points[i]; + points[i] = points[j]; + points[j] = temp; + } +} diff --git a/solutions/973. K Closest Points to Origin/973-2.py b/solutions/973. K Closest Points to Origin/973-2.py new file mode 100644 index 00000000000..2e1b13e09f6 --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973-2.py @@ -0,0 +1,25 @@ +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + def squareDist(p: List[int]) -> int: + return p[0] * p[0] + p[1] * p[1] + + def quickSelect(l: int, r: int, k: int) -> None: + pivot = points[r] + + nextSwapped = l + for i in range(l, r): + if squareDist(points[i]) <= squareDist(pivot): + points[nextSwapped], points[i] = points[i], points[nextSwapped] + nextSwapped += 1 + points[nextSwapped], points[r] = points[r], points[nextSwapped] + + count = nextSwapped - l + 1 the number of points <= pivot + if count == k: + return + if count > k: + quickSelect(l, nextSwapped - 1, k) + else: + quickSelect(nextSwapped + 1, r, k - count) + + quickSelect(0, len(points) - 1, k) + return points[0:k] diff --git a/solutions/973. K Closest Points to Origin/973-3.cpp b/solutions/973. K Closest Points to Origin/973-3.cpp new file mode 100644 index 00000000000..64a6c03fc81 --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973-3.cpp @@ -0,0 +1,32 @@ +class Solution { + public: + vector> kClosest(vector>& points, int k) { + quickSelect(points, 0, points.size() - 1, k); + return {points.begin(), points.begin() + k}; + }; + + private: + void quickSelect(vector>& points, int l, int r, int k) { + const int randIndex = rand() % (r - l + 1) + l; + swap(points[randIndex], points[r]); + const vector pivot = points[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (squareDist(points[i]) <= squareDist(pivot)) + swap(points[nextSwapped++], points[i]); + swap(points[nextSwapped], points[r]); + + const int count = nextSwapped - l + 1; // the number of points <= pivot + if (count == k) + return; + if (count > k) + quickSelect(points, l, nextSwapped - 1, k); + else + quickSelect(points, nextSwapped + 1, r, k - count); + } + + int squareDist(const vector& p) { + return p[0] * p[0] + p[1] * p[1]; + } +}; diff --git a/solutions/973. K Closest Points to Origin/973-3.java b/solutions/973. K Closest Points to Origin/973-3.java new file mode 100644 index 00000000000..97e78534311 --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973-3.java @@ -0,0 +1,36 @@ +class Solution { + public int[][] kClosest(int[][] points, int k) { + quickSelect(points, 0, points.length - 1, k); + return Arrays.copyOfRange(points, 0, k); + } + + private void quickSelect(int[][] points, int l, int r, int k) { + final int randIndex = new Random().nextInt(r - l + 1) + l; + swap(points, randIndex, r); + final int[] pivot = points[r]; + + int nextSwapped = l; + for (int i = l; i < r; ++i) + if (squareDist(points[i]) <= squareDist(pivot)) + swap(points, nextSwapped++, i); + swap(points, nextSwapped, r); + + final int count = nextSwapped - l + 1; // the number of points <= pivot + if (count == k) + return; + if (count > k) + quickSelect(points, l, nextSwapped - 1, k); + else + quickSelect(points, nextSwapped + 1, r, k - count); + } + + private int squareDist(int[] p) { + return p[0] * p[0] + p[1] * p[1]; + } + + private void swap(int[][] points, int i, int j) { + final int[] temp = points[i]; + points[i] = points[j]; + points[j] = temp; + } +} diff --git a/solutions/973. K Closest Points to Origin/973-3.py b/solutions/973. K Closest Points to Origin/973-3.py new file mode 100644 index 00000000000..13fa647a5b3 --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973-3.py @@ -0,0 +1,54 @@ +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + def squareDist(p: List[int]) -> int: + return p[0] * p[0] + p[1] * p[1] + + def quickSelect(l: int, r: int, k: int) -> None: + randIndex = random.randint(0, r - l + 1) + l + points[randIndex], points[r] = points[r], points[randIndex] + pivot = points[r] + + nextSwapped = l + for i in range(l, r): + if squareDist(points[i]) <= squareDist(pivot): + points[nextSwapped], points[i] = points[i], points[nextSwapped] + nextSwapped += 1 + points[nextSwapped], points[r] = points[r], points[nextSwapped] + + count = nextSwapped - l + 1 the number of points <= pivot + if count == k: + return + if count > k: + quickSelect(l, nextSwapped - 1, k) + else: + quickSelect(nextSwapped + 1, r, k - count) + + quickSelect(0, len(points) - 1, k) + return points[0:k] + + +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + def squareDist(p: List[int]) -> int: + return p[0] * p[0] + p[1] * p[1] + + def quickSelect(l: int, r: int, k: int) -> None: + pivot = points[r] + + nextSwapped = l + for i in range(l, r): + if squareDist(points[i]) <= squareDist(pivot): + points[nextSwapped], points[i] = points[i], points[nextSwapped] + nextSwapped += 1 + points[nextSwapped], points[r] = points[r], points[nextSwapped] + + count = nextSwapped - l + 1 the number of points <= pivot + if count == k: + return + if count > k: + quickSelect(l, nextSwapped - 1, k) + else: + quickSelect(nextSwapped + 1, r, k - count) + + quickSelect(0, len(points) - 1, k) + return points[0:k] diff --git a/solutions/973. K Closest Points to Origin/973.cpp b/solutions/973. K Closest Points to Origin/973.cpp new file mode 100644 index 00000000000..55b54e02b81 --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + vector> kClosest(vector>& points, int k) { + vector> ans; + auto compare = [&](const vector& a, const vector& b) { + return squareDist(a) < squareDist(b); + }; + priority_queue, vector>, decltype(compare)> maxHeap( + compare); + + for (const vector& point : points) { + maxHeap.push(point); + if (maxHeap.size() > k) + maxHeap.pop(); + } + + while (!maxHeap.empty()) + ans.push_back(maxHeap.top()), maxHeap.pop(); + + return ans; + }; + + private: + int squareDist(const vector& p) { + return p[0] * p[0] + p[1] * p[1]; + } +}; diff --git a/solutions/973. K Closest Points to Origin/973.java b/solutions/973. K Closest Points to Origin/973.java new file mode 100644 index 00000000000..15502e1b20c --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973.java @@ -0,0 +1,22 @@ +class Solution { + public int[][] kClosest(int[][] points, int k) { + int[][] ans = new int[k][2]; + PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> squareDist(b) - squareDist(a)); + + for (int[] point : points) { + maxHeap.offer(point); + if (maxHeap.size() > k) + maxHeap.poll(); + } + + int i = k; + while (!maxHeap.isEmpty()) + ans[--i] = maxHeap.poll(); + + return ans; + } + + private int squareDist(int[] p) { + return p[0] * p[0] + p[1] * p[1]; + } +} diff --git a/solutions/973. K Closest Points to Origin/973.py b/solutions/973. K Closest Points to Origin/973.py new file mode 100644 index 00000000000..8128de9e311 --- /dev/null +++ b/solutions/973. K Closest Points to Origin/973.py @@ -0,0 +1,10 @@ +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + maxHeap = [] + + for x, y in points: + heapq.heappush(maxHeap, (- x * x - y * y, [x, y])) + if len(maxHeap) > k: + heapq.heappop(maxHeap) + + return [pair[1] for pair in maxHeap] diff --git a/solutions/974. Subarray Sums Divisible by K/974.cpp b/solutions/974. Subarray Sums Divisible by K/974.cpp new file mode 100644 index 00000000000..872372fffa7 --- /dev/null +++ b/solutions/974. Subarray Sums Divisible by K/974.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int subarraysDivByK(vector& nums, int k) { + int ans = 0; + int prefix = 0; + vector count(k); + count[0] = 1; + + for (const int num : nums) { + prefix = (prefix + num % k + k) % k; + ans += count[prefix]; + ++count[prefix]; + } + + return ans; + } +}; diff --git a/solutions/974. Subarray Sums Divisible by K/974.java b/solutions/974. Subarray Sums Divisible by K/974.java new file mode 100644 index 00000000000..1dfcef73747 --- /dev/null +++ b/solutions/974. Subarray Sums Divisible by K/974.java @@ -0,0 +1,16 @@ +class Solution { + public int subarraysDivByK(int[] nums, int k) { + int ans = 0; + int prefix = 0; + int[] count = new int[k]; + count[0] = 1; + + for (final int num : nums) { + prefix = (prefix + num % k + k) % k; + ans += count[prefix]; + ++count[prefix]; + } + + return ans; + } +} diff --git a/solutions/974. Subarray Sums Divisible by K/974.py b/solutions/974. Subarray Sums Divisible by K/974.py new file mode 100644 index 00000000000..6016efe9ea5 --- /dev/null +++ b/solutions/974. Subarray Sums Divisible by K/974.py @@ -0,0 +1,13 @@ +class Solution: + def subarraysDivByK(self, nums: List[int], k: int) -> int: + ans = 0 + prefix = 0 + count = [0] * k + count[0] = 1 + + for num in nums: + prefix = (prefix + num % k + k) % k + ans += count[prefix] + count[prefix] += 1 + + return ans diff --git a/solutions/975. Odd Even Jump/975.cpp b/solutions/975. Odd Even Jump/975.cpp new file mode 100644 index 00000000000..a35e341b19a --- /dev/null +++ b/solutions/975. Odd Even Jump/975.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int oddEvenJumps(vector& arr) { + const int n = arr.size(); + map map; // {num: min index} + // inc[i] := true if can reach arr[n - 1] from i using increasing jumps + vector inc(n); + // dec[i] := true if can reach arr[n - 1] from i using decreasing jumps + vector dec(n); + + map[arr[n - 1]] = n - 1; + inc.back() = true; + dec.back() = true; + + for (int i = n - 2; i >= 0; --i) { + const auto lo = map.lower_bound(arr[i]); // the minimum value >= arr[i] + const auto hi = map.upper_bound(arr[i]); // the minimum value > arr[i] + if (lo != map.cend()) + inc[i] = dec[lo->second]; + if (hi != map.cbegin()) + dec[i] = inc[prev(hi)->second]; + map[arr[i]] = i; + } + + return ranges::count(inc, true); + } +}; diff --git a/solutions/975. Odd Even Jump/975.java b/solutions/975. Odd Even Jump/975.java new file mode 100644 index 00000000000..4329b246af5 --- /dev/null +++ b/solutions/975. Odd Even Jump/975.java @@ -0,0 +1,28 @@ +class Solution { + public int oddEvenJumps(int[] arr) { + final int n = arr.length; + TreeMap map = new TreeMap<>(); // {num: min index} + // inc[i] := true if can reach arr[n - 1] from i using increasing jumps + int[] inc = new int[n]; + // dec[i] := true if can reach arr[n - 1] from i using increasing jumps + int[] dec = new int[n]; + + map.put(arr[n - 1], n - 1); + inc[n - 1] = 1; + dec[n - 1] = 1; + + for (int i = n - 2; i >= 0; --i) { + // the minimum value >= arr[i] + Map.Entry lo = map.ceilingEntry(arr[i]); + // the maximum value <= arr[i] + Map.Entry hi = map.floorEntry(arr[i]); + if (lo != null) + inc[i] = dec[(int) lo.getValue()]; + if (hi != null) + dec[i] = inc[(int) hi.getValue()]; + map.put(arr[i], i); + } + + return Arrays.stream(inc).sum(); + } +} diff --git a/solutions/976. Largest Perimeter Triangle/976.cpp b/solutions/976. Largest Perimeter Triangle/976.cpp new file mode 100644 index 00000000000..53d3eaddd99 --- /dev/null +++ b/solutions/976. Largest Perimeter Triangle/976.cpp @@ -0,0 +1,12 @@ +class Solution { + public: + int largestPerimeter(vector& nums) { + ranges::sort(nums); + + for (int i = nums.size() - 1; i > 1; --i) + if (nums[i - 2] + nums[i - 1] > nums[i]) + return nums[i - 2] + nums[i - 1] + nums[i]; + + return 0; + } +}; diff --git a/solutions/976. Largest Perimeter Triangle/976.java b/solutions/976. Largest Perimeter Triangle/976.java new file mode 100644 index 00000000000..5667b674886 --- /dev/null +++ b/solutions/976. Largest Perimeter Triangle/976.java @@ -0,0 +1,11 @@ +class Solution { + public int largestPerimeter(int[] nums) { + Arrays.sort(nums); + + for (int i = nums.length - 1; i > 1; --i) + if (nums[i - 2] + nums[i - 1] > nums[i]) + return nums[i - 2] + nums[i - 1] + nums[i]; + + return 0; + } +} diff --git a/solutions/976. Largest Perimeter Triangle/976.py b/solutions/976. Largest Perimeter Triangle/976.py new file mode 100644 index 00000000000..0c7a6b3eed8 --- /dev/null +++ b/solutions/976. Largest Perimeter Triangle/976.py @@ -0,0 +1,9 @@ +class Solution: + def largestPerimeter(self, nums: List[int]) -> int: + nums = sorted(nums) + + for i in range(len(nums) - 1, 1, -1): + if nums[i - 2] + nums[i - 1] > nums[i]: + return nums[i - 2] + nums[i - 1] + nums[i] + + return 0 diff --git a/solutions/977. Squares of a Sorted Array/977.cpp b/solutions/977. Squares of a Sorted Array/977.cpp new file mode 100644 index 00000000000..20bfc57775f --- /dev/null +++ b/solutions/977. Squares of a Sorted Array/977.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + vector sortedSquares(vector& nums) { + const int n = nums.size(); + vector ans(n); + int i = n - 1; + + for (int l = 0, r = n - 1; l <= r;) + if (abs(nums[l]) > abs(nums[r])) + ans[i--] = nums[l] * nums[l++]; + else + ans[i--] = nums[r] * nums[r--]; + + return ans; + } +}; diff --git a/solutions/977. Squares of a Sorted Array/977.java b/solutions/977. Squares of a Sorted Array/977.java new file mode 100644 index 00000000000..aa721916eb3 --- /dev/null +++ b/solutions/977. Squares of a Sorted Array/977.java @@ -0,0 +1,15 @@ +class Solution { + public int[] sortedSquares(int[] nums) { + final int n = nums.length; + int[] ans = new int[n]; + int i = n - 1; + + for (int l = 0, r = n - 1; l <= r;) + if (Math.abs(nums[l]) > Math.abs(nums[r])) + ans[i--] = nums[l] * nums[l++]; + else + ans[i--] = nums[r] * nums[r--]; + + return ans; + } +} diff --git a/solutions/977. Squares of a Sorted Array/977.py b/solutions/977. Squares of a Sorted Array/977.py new file mode 100644 index 00000000000..6a8e089556d --- /dev/null +++ b/solutions/977. Squares of a Sorted Array/977.py @@ -0,0 +1,17 @@ +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + l = 0 + r = n - 1 + ans = [0] * n + + while n: + n -= 1 + if abs(nums[l]) > abs(nums[r]): + ans[n] = nums[l] * nums[l] + l += 1 + else: + ans[n] = nums[r] * nums[r] + r -= 1 + + return ans diff --git a/solutions/978. Longest Turbulent Subarray/978.cpp b/solutions/978. Longest Turbulent Subarray/978.cpp new file mode 100644 index 00000000000..06522be7d86 --- /dev/null +++ b/solutions/978. Longest Turbulent Subarray/978.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int maxTurbulenceSize(vector& arr) { + int ans = 1; + int increasing = 1; + int decreasing = 1; + + for (int i = 1; i < arr.size(); ++i) { + if (arr[i] > arr[i - 1]) { + increasing = decreasing + 1; + decreasing = 1; + } else if (arr[i] < arr[i - 1]) { + decreasing = increasing + 1; + increasing = 1; + } else { + increasing = 1; + decreasing = 1; + } + ans = max({ans, increasing, decreasing}); + } + + return ans; + } +}; diff --git a/solutions/978. Longest Turbulent Subarray/978.java b/solutions/978. Longest Turbulent Subarray/978.java new file mode 100644 index 00000000000..ac532eb9a33 --- /dev/null +++ b/solutions/978. Longest Turbulent Subarray/978.java @@ -0,0 +1,23 @@ +class Solution { + public int maxTurbulenceSize(int[] arr) { + int ans = 1; + int increasing = 1; + int decreasing = 1; + + for (int i = 1; i < arr.length; ++i) { + if (arr[i] > arr[i - 1]) { + increasing = decreasing + 1; + decreasing = 1; + } else if (arr[i] < arr[i - 1]) { + decreasing = increasing + 1; + increasing = 1; + } else { + increasing = 1; + decreasing = 1; + } + ans = Math.max(ans, Math.max(increasing, decreasing)); + } + + return ans; + } +} diff --git a/solutions/978. Longest Turbulent Subarray/978.py b/solutions/978. Longest Turbulent Subarray/978.py new file mode 100644 index 00000000000..dc3b3f5ae6c --- /dev/null +++ b/solutions/978. Longest Turbulent Subarray/978.py @@ -0,0 +1,19 @@ +class Solution: + def maxTurbulenceSize(self, arr: List[int]) -> int: + ans = 1 + increasing = 1 + decreasing = 1 + + for i in range(1, len(arr)): + if arr[i] > arr[i - 1]: + increasing = decreasing + 1 + decreasing = 1 + elif arr[i] < arr[i - 1]: + decreasing = increasing + 1 + increasing = 1 + else: + increasing = 1 + decreasing = 1 + ans = max(ans, max(increasing, decreasing)) + + return ans diff --git a/solutions/979. Distribute Coins in Binary Tree/979.cpp b/solutions/979. Distribute Coins in Binary Tree/979.cpp new file mode 100644 index 00000000000..d2950a59172 --- /dev/null +++ b/solutions/979. Distribute Coins in Binary Tree/979.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int distributeCoins(TreeNode* root) { + int ans = 0; + dfs(root, ans); + return ans; + } + + private: + // Returns the number of coins I can give (positive) / take (negative). + int dfs(TreeNode* root, int& ans) { + if (root == nullptr) + return 0; + + const int l = dfs(root->left, ans); + const int r = dfs(root->right, ans); + ans += abs(l) + abs(r); + return (root->val - 1) + l + r; + } +}; diff --git a/solutions/979. Distribute Coins in Binary Tree/979.java b/solutions/979. Distribute Coins in Binary Tree/979.java new file mode 100644 index 00000000000..5c75c51eec7 --- /dev/null +++ b/solutions/979. Distribute Coins in Binary Tree/979.java @@ -0,0 +1,20 @@ +class Solution { + public int distributeCoins(TreeNode root) { + dfs(root); + return ans; + } + + private int ans = 0; + + // Returns the number of coins I can give (positive) / take (negative). + private int dfs(TreeNode root) { + if (root == null) + return 0; + + final int l = dfs(root.left); + final int r = dfs(root.right); + ans += Math.abs(l) + Math.abs(r); + + return (root.val - 1) + l + r; + } +} diff --git a/solutions/98. Validate Binary Search Tree/98-2.cpp b/solutions/98. Validate Binary Search Tree/98-2.cpp new file mode 100644 index 00000000000..ab2aeeefe7d --- /dev/null +++ b/solutions/98. Validate Binary Search Tree/98-2.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + bool isValidBST(TreeNode* root) { + stack stack; + TreeNode* pred = nullptr; + + while (root || !stack.empty()) { + while (root) { + stack.push(root); + root = root->left; + } + root = stack.top(), stack.pop(); + if (pred && pred->val >= root->val) + return false; + pred = root; + root = root->right; + } + + return true; + } +}; diff --git a/solutions/98. Validate Binary Search Tree/98-2.java b/solutions/98. Validate Binary Search Tree/98-2.java new file mode 100644 index 00000000000..8b516c0d4d4 --- /dev/null +++ b/solutions/98. Validate Binary Search Tree/98-2.java @@ -0,0 +1,20 @@ +class Solution { + public boolean isValidBST(TreeNode root) { + Deque stack = new ArrayDeque<>(); + TreeNode pred = null; + + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + root = stack.pop(); + if (pred != null && pred.val >= root.val) + return false; + pred = root; + root = root.right; + } + + return true; + } +} diff --git a/solutions/98. Validate Binary Search Tree/98-2.py b/solutions/98. Validate Binary Search Tree/98-2.py new file mode 100644 index 00000000000..b7ed9107f4b --- /dev/null +++ b/solutions/98. Validate Binary Search Tree/98-2.py @@ -0,0 +1,16 @@ +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + stack = [] + pred = None + + while root or stack: + while root: + stack.append(root) + root = root.left + root = stack.pop() + if pred and pred.val >= root.val: + return False + pred = root + root = root.right + + return True diff --git a/solutions/98. Validate Binary Search Tree/98.cpp b/solutions/98. Validate Binary Search Tree/98.cpp new file mode 100644 index 00000000000..804fc1252ab --- /dev/null +++ b/solutions/98. Validate Binary Search Tree/98.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + bool isValidBST(TreeNode* root) { + return isValidBST(root, nullptr, nullptr); + } + + private: + bool isValidBST(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) { + if (root == nullptr) + return true; + if (minNode && root->val <= minNode->val) + return false; + if (maxNode && root->val >= maxNode->val) + return false; + + return isValidBST(root->left, minNode, root) && + isValidBST(root->right, root, maxNode); + } +}; diff --git a/solutions/98. Validate Binary Search Tree/98.java b/solutions/98. Validate Binary Search Tree/98.java new file mode 100644 index 00000000000..321cb333b48 --- /dev/null +++ b/solutions/98. Validate Binary Search Tree/98.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isValidBST(TreeNode root) { + return isValidBST(root, null, null); + } + + private boolean isValidBST(TreeNode root, TreeNode minNode, TreeNode maxNode) { + if (root == null) + return true; + if (minNode != null && root.val <= minNode.val) + return false; + if (maxNode != null && root.val >= maxNode.val) + return false; + + return // + isValidBST(root.left, minNode, root) && // + isValidBST(root.right, root, maxNode); + } +} diff --git a/solutions/98. Validate Binary Search Tree/98.py b/solutions/98. Validate Binary Search Tree/98.py new file mode 100644 index 00000000000..53ea628707c --- /dev/null +++ b/solutions/98. Validate Binary Search Tree/98.py @@ -0,0 +1,15 @@ +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + def isValidBST(root: Optional[TreeNode], + minNode: Optional[TreeNode], maxNode: Optional[TreeNode]) -> bool: + if not root: + return True + if minNode and root.val <= minNode.val: + return False + if maxNode and root.val >= maxNode.val: + return False + + return isValidBST(root.left, minNode, root) and \ + isValidBST(root.right, root, maxNode) + + return isValidBST(root, None, None) diff --git a/solutions/980. Unique Paths III/980.cpp b/solutions/980. Unique Paths III/980.cpp new file mode 100644 index 00000000000..6edec7aeef1 --- /dev/null +++ b/solutions/980. Unique Paths III/980.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + int uniquePathsIII(vector>& grid) { + int ans = 0; + int empty = 1; + int sx; + int sy; + int ex; + int ey; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j] == 0) { + ++empty; + } else if (grid[i][j] == 1) { + sx = i; + sy = j; + } else if (grid[i][j] == 2) { + ex = i; + ey = j; + } + + dfs(grid, empty, sx, sy, ex, ey, ans); + + return ans; + } + + private: + void dfs(vector>& grid, int empty, int i, int j, int ex, int ey, + int& ans) { + if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) + return; + if (grid[i][j] < 0) + return; + if (i == ex && j == ey) { + if (empty == 0) + ++ans; + return; + } + + grid[i][j] = -2; + dfs(grid, empty - 1, i + 1, j, ex, ey, ans); + dfs(grid, empty - 1, i - 1, j, ex, ey, ans); + dfs(grid, empty - 1, i, j + 1, ex, ey, ans); + dfs(grid, empty - 1, i, j - 1, ex, ey, ans); + grid[i][j] = 0; + } +}; diff --git a/solutions/980. Unique Paths III/980.java b/solutions/980. Unique Paths III/980.java new file mode 100644 index 00000000000..feb996a661f --- /dev/null +++ b/solutions/980. Unique Paths III/980.java @@ -0,0 +1,46 @@ +class Solution { + public int uniquePathsIII(int[][] grid) { + int empty = 1; + int sx = -1; + int sy = -1; + int ex = -1; + int ey = -1; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 0) { + ++empty; + } else if (grid[i][j] == 1) { + sx = i; + sy = j; + } else if (grid[i][j] == 2) { + ex = i; + ey = j; + } + + dfs(grid, empty, sx, sy, ex, ey); + + return ans; + } + + private int ans = 0; + + private void dfs(int[][] grid, int empty, int i, int j, int ex, int ey) { + if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) + return; + if (grid[i][j] < 0) + return; + if (i == ex && j == ey) { + if (empty == 0) + ++ans; + return; + } + + grid[i][j] = -2; + dfs(grid, empty - 1, i + 1, j, ex, ey); + dfs(grid, empty - 1, i - 1, j, ex, ey); + dfs(grid, empty - 1, i, j + 1, ex, ey); + dfs(grid, empty - 1, i, j - 1, ex, ey); + grid[i][j] = 0; + } +} diff --git a/solutions/981. Time Based Key-Value Store/981.cpp b/solutions/981. Time Based Key-Value Store/981.cpp new file mode 100644 index 00000000000..6df98c2bfd5 --- /dev/null +++ b/solutions/981. Time Based Key-Value Store/981.cpp @@ -0,0 +1,34 @@ +struct T { + string value; + int timestamp; + T(string value, int timestamp) : value(value), timestamp(timestamp) {} +}; + +class TimeMap { + public: + void set(string key, string value, int timestamp) { + map[key].emplace_back(value, timestamp); + } + + string get(string key, int timestamp) { + if (!map.contains(key)) + return ""; + + const vector& A = map[key]; + int l = 0; + int r = A.size(); + + while (l < r) { + const int m = (l + r) / 2; + if (A[m].timestamp > timestamp) + r = m; + else + l = m + 1; + } + + return l == 0 ? "" : A[l - 1].value; + } + + private: + unordered_map> map; +}; diff --git a/solutions/981. Time Based Key-Value Store/981.java b/solutions/981. Time Based Key-Value Store/981.java new file mode 100644 index 00000000000..c2a54576b06 --- /dev/null +++ b/solutions/981. Time Based Key-Value Store/981.java @@ -0,0 +1,36 @@ +class T { + public String value; + public int timestamp; + public T(String value, int timestamp) { + this.value = value; + this.timestamp = timestamp; + } +} + +class TimeMap { + public void set(String key, String value, int timestamp) { + map.putIfAbsent(key, new ArrayList<>()); + map.get(key).add(new T(value, timestamp)); + } + + public String get(String key, int timestamp) { + List A = map.get(key); + if (A == null) + return ""; + + int l = 0; + int r = A.size(); + + while (l < r) { + final int m = (l + r) / 2; + if (A.get(m).timestamp > timestamp) + r = m; + else + l = m + 1; + } + + return l == 0 ? "" : A.get(l - 1).value; + } + + private Map> map = new HashMap<>(); +} diff --git a/solutions/981. Time Based Key-Value Store/981.py b/solutions/981. Time Based Key-Value Store/981.py new file mode 100644 index 00000000000..811f86c8892 --- /dev/null +++ b/solutions/981. Time Based Key-Value Store/981.py @@ -0,0 +1,14 @@ +class TimeMap: + def __init__(self): + self.values = collections.defaultdict(list) + self.timestamps = collections.defaultdict(list) + + def set(self, key: str, value: str, timestamp: int) -> None: + self.values[key].append(value) + self.timestamps[key].append(timestamp) + + def get(self, key: str, timestamp: int) -> str: + if key not in self.timestamps: + return '' + i = bisect.bisect(self.timestamps[key], timestamp) + return self.values[key][i - 1] if i > 0 else '' diff --git a/solutions/982. Triples with Bitwise AND Equal To Zero/982.cpp b/solutions/982. Triples with Bitwise AND Equal To Zero/982.cpp new file mode 100644 index 00000000000..ee08121ceee --- /dev/null +++ b/solutions/982. Triples with Bitwise AND Equal To Zero/982.cpp @@ -0,0 +1,19 @@ +class Solution { + public: + int countTriplets(vector& nums) { + constexpr int kMax = 1 << 16; + int ans = 0; + vector count(kMax); // {nums[i] & nums[j]: times} + + for (const int a : nums) + for (const int b : nums) + ++count[a & b]; + + for (const int num : nums) + for (int i = 0; i < kMax; ++i) + if ((num & i) == 0) + ans += count[i]; + + return ans; + } +}; diff --git a/solutions/982. Triples with Bitwise AND Equal To Zero/982.java b/solutions/982. Triples with Bitwise AND Equal To Zero/982.java new file mode 100644 index 00000000000..d1772a58a5c --- /dev/null +++ b/solutions/982. Triples with Bitwise AND Equal To Zero/982.java @@ -0,0 +1,18 @@ +class Solution { + public int countTriplets(int[] nums) { + final int kMax = 1 << 16; + int ans = 0; + int[] count = new int[kMax]; // {nums[i] & nums[j]: times} + + for (final int a : nums) + for (final int b : nums) + ++count[a & b]; + + for (final int num : nums) + for (int i = 0; i < kMax; ++i) + if ((num & i) == 0) + ans += count[i]; + + return ans; + } +} diff --git a/solutions/982. Triples with Bitwise AND Equal To Zero/982.py b/solutions/982. Triples with Bitwise AND Equal To Zero/982.py new file mode 100644 index 00000000000..4407c8e25e7 --- /dev/null +++ b/solutions/982. Triples with Bitwise AND Equal To Zero/982.py @@ -0,0 +1,16 @@ +class Solution: + def countTriplets(self, nums: List[int]) -> int: + kMax = 1 << 16 + ans = 0 + count = [0] * kMax # {nums[i] & nums[j]: times} + + for a in nums: + for b in nums: + count[a & b] += 1 + + for num in nums: + for i in range(kMax): + if (num & i) == 0: + ans += count[i] + + return ans diff --git a/solutions/983. Minimum Cost For Tickets/983.cpp b/solutions/983. Minimum Cost For Tickets/983.cpp new file mode 100644 index 00000000000..664be96ef4d --- /dev/null +++ b/solutions/983. Minimum Cost For Tickets/983.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + int mincostTickets(vector& days, vector& costs) { + int ans = 0; + queue> last7; + queue> last30; + + for (int day : days) { + while (!last7.empty() && last7.front().first + 7 <= day) + last7.pop(); + while (!last30.empty() && last30.front().first + 30 <= day) + last30.pop(); + last7.emplace(day, ans + costs[1]); + last30.emplace(day, ans + costs[2]); + ans = min({ans + costs[0], last7.front().second, last30.front().second}); + } + + return ans; + } +}; diff --git a/solutions/983. Minimum Cost For Tickets/983.java b/solutions/983. Minimum Cost For Tickets/983.java new file mode 100644 index 00000000000..9db38c4db1e --- /dev/null +++ b/solutions/983. Minimum Cost For Tickets/983.java @@ -0,0 +1,19 @@ +class Solution { + public int mincostTickets(int[] days, int[] costs) { + int ans = 0; + Queue last7 = new ArrayDeque<>(); // [day, cost] + Queue last30 = new ArrayDeque<>(); + + for (int day : days) { + while (!last7.isEmpty() && last7.peek()[0] + 7 <= day) + last7.poll(); + while (!last30.isEmpty() && last30.peek()[0] + 30 <= day) + last30.poll(); + last7.offer(new int[] {day, ans + costs[1]}); + last30.offer(new int[] {day, ans + costs[2]}); + ans = Math.min(ans + costs[0], Math.min(last7.peek()[1], last30.peek()[1])); + } + + return ans; + } +} diff --git a/solutions/983. Minimum Cost For Tickets/983.py b/solutions/983. Minimum Cost For Tickets/983.py new file mode 100644 index 00000000000..4224fe3a4ae --- /dev/null +++ b/solutions/983. Minimum Cost For Tickets/983.py @@ -0,0 +1,16 @@ +class Solution: + def mincostTickets(self, days: List[int], costs: List[int]) -> int: + ans = 0 + last7 = collections.deque() + last30 = collections.deque() + + for day in days: + while last7 and last7[0][0] + 7 <= day: + last7.popleft() + while last30 and last30[0][0] + 30 <= day: + last30.popleft() + last7.append([day, ans + costs[1]]) + last30.append([day, ans + costs[2]]) + ans = min(ans + costs[0], last7[0][1], last30[0][1]) + + return ans diff --git a/solutions/984. String Without AAA or BBB/984.cpp b/solutions/984. String Without AAA or BBB/984.cpp new file mode 100644 index 00000000000..fa40fe146da --- /dev/null +++ b/solutions/984. String Without AAA or BBB/984.cpp @@ -0,0 +1,14 @@ +class Solution { + public: + string strWithout3a3b(int A, int B, char a = 'a', char b = 'b') { + if (A < B) + return strWithout3a3b(B, A, b, a); + if (B == 0) + return string(min(A, 2), a); + + const int useA = min(A, 2); + const int useB = (A - useA >= B) ? 1 : 0; + return string(useA, a) + string(useB, b) + + strWithout3a3b(A - useA, B - useB, a, b); + } +}; diff --git a/solutions/985. Sum of Even Numbers After Queries/985.cpp b/solutions/985. Sum of Even Numbers After Queries/985.cpp new file mode 100644 index 00000000000..abd6f53a2f7 --- /dev/null +++ b/solutions/985. Sum of Even Numbers After Queries/985.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + vector sumEvenAfterQueries(vector& nums, + vector>& queries) { + vector ans; + int sum = + accumulate(nums.begin(), nums.end(), 0, [](int subtotal, int num) { + return subtotal + (num % 2 == 0 ? num : 0); + }); + + for (const vector& query : queries) { + const int val = query[0]; + const int index = query[1]; + if (nums[index] % 2 == 0) + sum -= nums[index]; + nums[index] += val; + if (nums[index] % 2 == 0) + sum += nums[index]; + ans.push_back(sum); + } + + return ans; + } +}; diff --git a/solutions/985. Sum of Even Numbers After Queries/985.java b/solutions/985. Sum of Even Numbers After Queries/985.java new file mode 100644 index 00000000000..e99bb57fa4f --- /dev/null +++ b/solutions/985. Sum of Even Numbers After Queries/985.java @@ -0,0 +1,22 @@ +class Solution { + public int[] sumEvenAfterQueries(int[] nums, int[][] queries) { + int[] ans = new int[queries.length]; + int sum = 0; + + for (final int num : nums) + sum += num % 2 == 0 ? num : 0; + + for (int i = 0; i < queries.length; ++i) { + final int val = queries[i][0]; + final int index = queries[i][1]; + if (nums[index] % 2 == 0) + sum -= nums[index]; + nums[index] += val; + if (nums[index] % 2 == 0) + sum += nums[index]; + ans[i] = sum; + } + + return ans; + } +} diff --git a/solutions/985. Sum of Even Numbers After Queries/985.py b/solutions/985. Sum of Even Numbers After Queries/985.py new file mode 100644 index 00000000000..cedf3b306db --- /dev/null +++ b/solutions/985. Sum of Even Numbers After Queries/985.py @@ -0,0 +1,14 @@ +class Solution: + def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]: + ans = [] + summ = sum(a for a in nums if a % 2 == 0) + + for val, index in queries: + if nums[index] % 2 == 0: + summ -= nums[index] + nums[index] += val + if nums[index] % 2 == 0: + summ += nums[index] + ans.append(summ) + + return ans diff --git a/solutions/986. Interval List Intersections/986.cpp b/solutions/986. Interval List Intersections/986.cpp new file mode 100644 index 00000000000..13abef8cb24 --- /dev/null +++ b/solutions/986. Interval List Intersections/986.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + vector> intervalIntersection(vector>& firstList, + vector>& secondList) { + vector> ans; + short i = 0; + short j = 0; + + while (i < firstList.size() && j < secondList.size()) { + // lo := the start of the intersection + // hi := the end of the intersection + const int lo = max(firstList[i][0], secondList[j][0]); + const int hi = min(firstList[i][1], secondList[j][1]); + if (lo <= hi) + ans.push_back({lo, hi}); + firstList[i][1] < secondList[j][1] ? ++i : ++j; + } + + return ans; + } +}; diff --git a/solutions/986. Interval List Intersections/986.java b/solutions/986. Interval List Intersections/986.java new file mode 100644 index 00000000000..577be18b2e6 --- /dev/null +++ b/solutions/986. Interval List Intersections/986.java @@ -0,0 +1,22 @@ +class Solution { + public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { + List ans = new ArrayList<>(); + short i = 0; + short j = 0; + + while (i < firstList.length && j < secondList.length) { + // lo := the start of the intersection + // hi := the end of the intersection + final int lo = Math.max(firstList[i][0], secondList[j][0]); + final int hi = Math.min(firstList[i][1], secondList[j][1]); + if (lo <= hi) + ans.add(new int[] {lo, hi}); + if (firstList[i][1] < secondList[j][1]) + ++i; + else + ++j; + } + + return ans.toArray(new int[ans.size()][]); + } +} diff --git a/solutions/986. Interval List Intersections/986.py b/solutions/986. Interval List Intersections/986.py new file mode 100644 index 00000000000..568d864322b --- /dev/null +++ b/solutions/986. Interval List Intersections/986.py @@ -0,0 +1,19 @@ +class Solution: + def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: + ans = [] + i = 0 + j = 0 + + while i < len(firstList) and j < len(secondList): + # lo := the start of the intersection + # hi := the end of the intersection + lo = max(firstList[i][0], secondList[j][0]) + hi = min(firstList[i][1], secondList[j][1]) + if lo <= hi: + ans.append([lo, hi]) + if firstList[i][1] < secondList[j][1]: + i += 1 + else: + j += 1 + + return ans diff --git a/solutions/987. Vertical Order Traversal of a Binary Tree/987.cpp b/solutions/987. Vertical Order Traversal of a Binary Tree/987.cpp new file mode 100644 index 00000000000..62399b43935 --- /dev/null +++ b/solutions/987. Vertical Order Traversal of a Binary Tree/987.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector> verticalTraversal(TreeNode* root) { + vector> ans; + map>> xToSortedPairs; // {x: {(-y, val)}} + + dfs(root, 0, 0, xToSortedPairs); + + for (const auto& [_, pairs] : xToSortedPairs) { + vector vals; + for (const pair& pair : pairs) + vals.push_back(pair.second); + ans.push_back(vals); + } + + return ans; + } + + private: + void dfs(TreeNode* root, int x, int y, + map>>& xToSortedPairs) { + if (root == nullptr) + return; + xToSortedPairs[x].emplace(y, root->val); + dfs(root->left, x - 1, y + 1, xToSortedPairs); + dfs(root->right, x + 1, y + 1, xToSortedPairs); + } +}; diff --git a/solutions/987. Vertical Order Traversal of a Binary Tree/987.java b/solutions/987. Vertical Order Traversal of a Binary Tree/987.java new file mode 100644 index 00000000000..e3dc7529fb0 --- /dev/null +++ b/solutions/987. Vertical Order Traversal of a Binary Tree/987.java @@ -0,0 +1,27 @@ +class Solution { + public List> verticalTraversal(TreeNode root) { + List> ans = new ArrayList<>(); + TreeMap> xToSortedPairs = new TreeMap<>(); // {x: {(-y, val)}} + + dfs(root, 0, 0, xToSortedPairs); + + for (List pairs : xToSortedPairs.values()) { + Collections.sort(pairs, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + List vals = new ArrayList<>(); + for (int[] pair : pairs) + vals.add(pair[1]); + ans.add(vals); + } + + return ans; + } + + private void dfs(TreeNode root, int x, int y, TreeMap> xToSortedPairs) { + if (root == null) + return; + xToSortedPairs.putIfAbsent(x, new ArrayList<>()); + xToSortedPairs.get(x).add(new int[] {y, root.val}); + dfs(root.left, x - 1, y + 1, xToSortedPairs); + dfs(root.right, x + 1, y + 1, xToSortedPairs); + } +} diff --git a/solutions/987. Vertical Order Traversal of a Binary Tree/987.py b/solutions/987. Vertical Order Traversal of a Binary Tree/987.py new file mode 100644 index 00000000000..7814085595a --- /dev/null +++ b/solutions/987. Vertical Order Traversal of a Binary Tree/987.py @@ -0,0 +1,18 @@ +class Solution: + def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: + ans = [] + xToNodes = collections.defaultdict(list) + + def dfs(node: Optional[TreeNode], x: int, y: int) -> None: + if not node: + return + xToNodes[x].append((-y, node.val)) + dfs(node.left, x - 1, y - 1) + dfs(node.right, x + 1, y - 1) + + dfs(root, 0, 0) + + for _, nodes in sorted(xToNodes.items(), key=lambda item: item[0]): + ans.append([val for _, val in sorted(nodes)]) + + return ans diff --git a/solutions/988. Smallest String Starting From Leaf/988.cpp b/solutions/988. Smallest String Starting From Leaf/988.cpp new file mode 100644 index 00000000000..d2399397e72 --- /dev/null +++ b/solutions/988. Smallest String Starting From Leaf/988.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + string smallestFromLeaf(TreeNode* root) { + string ans; + dfs(root, "", ans); + return ans; + } + + private: + void dfs(TreeNode* root, string&& path, string& ans) { + if (root == nullptr) + return; + + path.push_back(root->val + 'a'); + + if (root->left == nullptr && root->right == nullptr) { + reverse(path.begin(), path.end()); + if (ans == "" || ans > path) + ans = path; + reverse(path.begin(), path.end()); // Roll back. + } + + dfs(root->left, move(path), ans); + dfs(root->right, move(path), ans); + path.pop_back(); + } +}; diff --git a/solutions/988. Smallest String Starting From Leaf/988.java b/solutions/988. Smallest String Starting From Leaf/988.java new file mode 100644 index 00000000000..44858fd0bf3 --- /dev/null +++ b/solutions/988. Smallest String Starting From Leaf/988.java @@ -0,0 +1,26 @@ +class Solution { + public String smallestFromLeaf(TreeNode root) { + dfs(root, new StringBuilder()); + return ans; + } + + private String ans = null; + + private void dfs(TreeNode root, StringBuilder sb) { + if (root == null) + return; + + sb.append((char) (root.val + 'a')); + + if (root.left == null && root.right == null) { + final String path = sb.reverse().toString(); + sb.reverse(); // Roll back. + if (ans == null || ans.compareTo(path) > 0) + ans = path; + } + + dfs(root.left, sb); + dfs(root.right, sb); + sb.deleteCharAt(sb.length() - 1); + } +} diff --git a/solutions/989. Add to Array-Form of Integer/989.cpp b/solutions/989. Add to Array-Form of Integer/989.cpp new file mode 100644 index 00000000000..2a7bc61831f --- /dev/null +++ b/solutions/989. Add to Array-Form of Integer/989.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + vector addToArrayForm(vector& num, int k) { + for (int i = num.size() - 1; i >= 0; --i) { + num[i] += k; + k = num[i] / 10; + num[i] %= 10; + } + + while (k > 0) { + num.insert(num.begin(), k % 10); + k /= 10; + } + + return num; + } +}; diff --git a/solutions/989. Add to Array-Form of Integer/989.java b/solutions/989. Add to Array-Form of Integer/989.java new file mode 100644 index 00000000000..8d9bd5e1f2b --- /dev/null +++ b/solutions/989. Add to Array-Form of Integer/989.java @@ -0,0 +1,17 @@ +class Solution { + public List addToArrayForm(int[] num, int k) { + List ans = new LinkedList<>(); + + for (int i = num.length - 1; i >= 0; --i) { + ans.add(0, (num[i] + k) % 10); + k = (num[i] + k) / 10; + } + + while (k > 0) { + ans.add(0, k % 10); + k /= 10; + } + + return ans; + } +} diff --git a/solutions/989. Add to Array-Form of Integer/989.py b/solutions/989. Add to Array-Form of Integer/989.py new file mode 100644 index 00000000000..a30ad1a4442 --- /dev/null +++ b/solutions/989. Add to Array-Form of Integer/989.py @@ -0,0 +1,10 @@ +class Solution: + def addToArrayForm(self, num: List[int], k: int) -> List[int]: + for i in reversed(range(len(num))): + k, num[i] = divmod(num[i] + k, 10) + + while k > 0: + num = [k % 10] + num + k //= 10 + + return num diff --git a/solutions/99. Recover Binary Search Tree/99-2.cpp b/solutions/99. Recover Binary Search Tree/99-2.cpp new file mode 100644 index 00000000000..d89c505afcd --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99-2.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + void recoverTree(TreeNode* root) { + TreeNode* pred = nullptr; + TreeNode* x = nullptr; // the first wrong node + TreeNode* y = nullptr; // the second wrong node + + stack stack; + + while (root != nullptr || !stack.empty()) { + while (root != nullptr) { + stack.push(root); + root = root->left; + } + root = stack.top(), stack.pop(); + if (pred && root->val < pred->val) { + y = root; + if (x == nullptr) + x = pred; + } + pred = root; + root = root->right; + } + + swap(x, y); + } + + void swap(TreeNode* x, TreeNode* y) { + const int temp = x->val; + x->val = y->val; + y->val = temp; + } +}; diff --git a/solutions/99. Recover Binary Search Tree/99-2.java b/solutions/99. Recover Binary Search Tree/99-2.java new file mode 100644 index 00000000000..dcd7e7e4703 --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99-2.java @@ -0,0 +1,32 @@ +class Solution { + public void recoverTree(TreeNode root) { + TreeNode pred = null; + TreeNode x = null; + TreeNode y = null; + + Deque stack = new ArrayDeque<>(); + + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + root = stack.pop(); + if (pred != null && root.val < pred.val) { + y = root; + if (x == null) + x = pred; + } + pred = root; + root = root.right; + } + + swap(x, y); + } + + private void swap(TreeNode x, TreeNode y) { + final int temp = x.val; + x.val = y.val; + y.val = temp; + } +} diff --git a/solutions/99. Recover Binary Search Tree/99-2.py b/solutions/99. Recover Binary Search Tree/99-2.py new file mode 100644 index 00000000000..338befd4904 --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99-2.py @@ -0,0 +1,25 @@ +class Solution: + def recoverTree(self, root: Optional[TreeNode]) -> None: + pred = None + x = None # the first wrong node + y = None # the second wrong node + stack = [] + + while root or stack: + while root: + stack.append(root) + root = root.left + root = stack.pop() + if pred and root.val < pred.val: + y = root + if not x: + x = pred + pred = root + root = root.right + + def swap(x: Optional[TreeNode], y: Optional[TreeNode]) -> None: + temp = x.val + x.val = y.val + y.val = temp + + swap(x, y) diff --git a/solutions/99. Recover Binary Search Tree/99-3.cpp b/solutions/99. Recover Binary Search Tree/99-3.cpp new file mode 100644 index 00000000000..5c5558b5a5d --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99-3.cpp @@ -0,0 +1,51 @@ +class Solution { + public: + void recoverTree(TreeNode* root) { + TreeNode* pred = nullptr; + TreeNode* x = nullptr; // the first wrong node + TreeNode* y = nullptr; // the second wrong node + + while (root != nullptr) { + if (root->left != nullptr) { + TreeNode* morrisPred = findPredecessor(root); + if (morrisPred->right) { + // The node has already been connected before. + visit(root, pred, x, y); + morrisPred->right = nullptr; // Break the connection. + root = root->right; + } else { + morrisPred->right = root; // Connect it. + root = root->left; + } + } else { + visit(root, pred, x, y); + root = root->right; + } + } + + swap(x, y); + } + + private: + TreeNode* findPredecessor(TreeNode* root) { + TreeNode* pred = root->left; + while (pred->right && pred->right != root) + pred = pred->right; + return pred; + } + + void visit(TreeNode*& root, TreeNode*& pred, TreeNode*& x, TreeNode*& y) { + if (pred && root->val < pred->val) { + y = root; + if (x == nullptr) + x = pred; + } + pred = root; + } + + void swap(TreeNode* x, TreeNode* y) { + const int temp = x->val; + x->val = y->val; + y->val = temp; + } +}; diff --git a/solutions/99. Recover Binary Search Tree/99-3.java b/solutions/99. Recover Binary Search Tree/99-3.java new file mode 100644 index 00000000000..cb495444184 --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99-3.java @@ -0,0 +1,54 @@ +class Solution { + public void recoverTree(TreeNode root) { + TreeNode pred = null; + TreeNode x = null; // the first wrong node + TreeNode y = null; // the second wrong node + + while (root != null) { + if (root.left == null) { + // Start the main logic. + if (pred != null && root.val < pred.val) { + y = root; + if (x == null) + x = pred; + } + pred = root; + // End of the main logic. + root = root.right; + } else { + TreeNode morrisPred = findPredecessor(root); + if (morrisPred.right == null) { + morrisPred.right = root; // Connect it. + root = root.left; + } else { + // The node has already been connected before. + // Start the main logic. + if (pred != null && root.val < pred.val) { + y = root; + if (x == null) + x = pred; + } + pred = root; + // End of the main logic. + morrisPred.right = null; // Break the connection. + root = root.right; + } + } + } + + swap(x, y); + } + + private TreeNode findPredecessor(TreeNode root) { + TreeNode pred = root.left; + while (pred.right != null && pred.right != root) + pred = pred.right; + return pred; + } + + private void swap(TreeNode x, TreeNode y) { + final int temp = x.val; + x.val = y.val; + y.val = temp; + } +} diff --git a/solutions/99. Recover Binary Search Tree/99-3.py b/solutions/99. Recover Binary Search Tree/99-3.py new file mode 100644 index 00000000000..6cc9d5d7f28 --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99-3.py @@ -0,0 +1,45 @@ +class Solution: + def recoverTree(self, root: Optional[TreeNode]) -> None: + pred = None + x = None # the first wrong node + y = None # the second wrong node + + def findPredecessor(root: Optional[TreeNode]) -> Optional[TreeNode]: + pred = root.left + while pred.right and pred.right != root: + pred = pred.right + return pred + + while root: + if root.left: + morrisPred = findPredecessor(root) + if morrisPred.right: + # The node has already been connected before. + # Start the main logic. + if pred and root.val < pred.val: + y = root + if not x: + x = pred + pred = root + # End of the main logic + morrisPred.right = None # Break the connection. + root = root.right + else: + morrisPred.right = root # Connect it. + root = root.left + else: + # Start the main logic. + if pred and root.val < pred.val: + y = root + if not x: + x = pred + pred = root + # End of the main logic. + root = root.right + + def swap(x: Optional[TreeNode], y: Optional[TreeNode]) -> None: + temp = x.val + x.val = y.val + y.val = temp + + swap(x, y) diff --git a/solutions/99. Recover Binary Search Tree/99.cpp b/solutions/99. Recover Binary Search Tree/99.cpp new file mode 100644 index 00000000000..024bba3e69d --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + void recoverTree(TreeNode* root) { + inorder(root); + swap(x, y); + } + + private: + TreeNode* pred = nullptr; + TreeNode* x = nullptr; // the first wrong node + TreeNode* y = nullptr; // the second wrong node + + void inorder(TreeNode* root) { + if (root == nullptr) + return; + + inorder(root->left); + + if (pred && root->val < pred->val) { + y = root; + if (x == nullptr) + x = pred; + else + return; + } + pred = root; + + inorder(root->right); + } + + void swap(TreeNode* x, TreeNode* y) { + const int temp = x->val; + x->val = y->val; + y->val = temp; + } +}; diff --git a/solutions/99. Recover Binary Search Tree/99.java b/solutions/99. Recover Binary Search Tree/99.java new file mode 100644 index 00000000000..41df5fada06 --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99.java @@ -0,0 +1,34 @@ +class Solution { + public void recoverTree(TreeNode root) { + inorder(root); + swap(x, y); + } + + private TreeNode pred = null; + private TreeNode x = null; // the first wrong node + private TreeNode y = null; // the second wrong node + + private void inorder(TreeNode root) { + if (root == null) + return; + + inorder(root.left); + + if (pred != null && root.val < pred.val) { + y = root; + if (x == null) + x = pred; + else + return; + } + pred = root; + + inorder(root.right); + } + + private void swap(TreeNode x, TreeNode y) { + final int temp = x.val; + x.val = y.val; + y.val = temp; + } +} diff --git a/solutions/99. Recover Binary Search Tree/99.py b/solutions/99. Recover Binary Search Tree/99.py new file mode 100644 index 00000000000..a4698e0ce95 --- /dev/null +++ b/solutions/99. Recover Binary Search Tree/99.py @@ -0,0 +1,29 @@ +class Solution: + def recoverTree(self, root: Optional[TreeNode]) -> None: + def swap(x: Optional[TreeNode], y: Optional[TreeNode]) -> None: + temp = x.val + x.val = y.val + y.val = temp + + def inorder(root: Optional[TreeNode]) -> None: + if not root: + return + + inorder(root.left) + + if self.pred and root.val < self.pred.val: + self.y = root + if not self.x: + self.x = self.pred + else: + return + self.pred = root + + inorder(root.right) + + inorder(root) + swap(self.x, self.y) + + pred = None + x = None # the first wrong node + y = None # the second wrong node diff --git a/solutions/990. Satisfiability of Equality Equations/990.cpp b/solutions/990. Satisfiability of Equality Equations/990.cpp new file mode 100644 index 00000000000..3bde3c68988 --- /dev/null +++ b/solutions/990. Satisfiability of Equality Equations/990.cpp @@ -0,0 +1,41 @@ +class UnionFind { + public: + UnionFind(int n) : id(n) { + iota(id.begin(), id.end(), 0); + } + + void union_(int u, int v) { + id[find(u)] = find(v); + } + + int find(int u) { + return id[u] == u ? u : id[u] = find(id[u]); + } + + private: + vector id; +}; + +class Solution { + public: + bool equationsPossible(vector& equations) { + UnionFind uf(26); + + for (const string& e : equations) + if (e[1] == '=') { + const int x = e[0] - 'a'; + const int y = e[3] - 'a'; + uf.union_(x, y); + } + + for (const string& e : equations) + if (e[1] == '!') { + const int x = e[0] - 'a'; + const int y = e[3] - 'a'; + if (uf.find(x) == uf.find(y)) + return false; + } + + return true; + } +}; diff --git a/solutions/990. Satisfiability of Equality Equations/990.java b/solutions/990. Satisfiability of Equality Equations/990.java new file mode 100644 index 00000000000..157b6d95513 --- /dev/null +++ b/solutions/990. Satisfiability of Equality Equations/990.java @@ -0,0 +1,53 @@ +class UnionFind { + public UnionFind(int n) { + id = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; ++i) + id[i] = i; + } + + public void unionByRank(int u, int v) { + final int i = find(u); + final int j = find(v); + if (i == j) + return; + if (rank[i] < rank[j]) { + id[i] = j; + } else if (rank[i] > rank[j]) { + id[j] = i; + } else { + id[i] = j; + ++rank[j]; + } + } + + public int find(int u) { + return id[u] == u ? u : (id[u] = find(id[u])); + } + + private int[] id; + private int[] rank; +} + +class Solution { + public boolean equationsPossible(String[] equations) { + UnionFind uf = new UnionFind(26); + + for (final String e : equations) + if (e.charAt(1) == '=') { + final int x = e.charAt(0) - 'a'; + final int y = e.charAt(3) - 'a'; + uf.unionByRank(x, y); + } + + for (final String e : equations) + if (e.charAt(1) == '!') { + final int x = e.charAt(0) - 'a'; + final int y = e.charAt(3) - 'a'; + if (uf.find(x) == uf.find(y)) + return false; + } + + return true; + } +} diff --git a/solutions/990. Satisfiability of Equality Equations/990.py b/solutions/990. Satisfiability of Equality Equations/990.py new file mode 100644 index 00000000000..1a625f18713 --- /dev/null +++ b/solutions/990. Satisfiability of Equality Equations/990.py @@ -0,0 +1,24 @@ +class UnionFind: + def __init__(self, n: int): + self.id = list(range(n)) + + def union(self, u: int, v: int) -> None: + self.id[self.find(u)] = self.find(v) + + def find(self, u: int) -> int: + if self.id[u] != u: + self.id[u] = self.find(self.id[u]) + return self.id[u] + + +class Solution: + def equationsPossible(self, equations: List[str]) -> bool: + uf = UnionFind(26) + + for x, op, _, y in equations: + if op == '=': + uf.union(ord(x) - ord('a'), ord(y) - ord('a')) + + return all(uf.find(ord(x) - ord('a')) != uf.find(ord(y) - ord('a')) + for x, op, _, y in equations + if op == '!') diff --git a/solutions/991. Broken Calculator/991.cpp b/solutions/991. Broken Calculator/991.cpp new file mode 100644 index 00000000000..a0f2950bcc5 --- /dev/null +++ b/solutions/991. Broken Calculator/991.cpp @@ -0,0 +1,16 @@ +class Solution { + public: + int brokenCalc(int startValue, int target) { + int ops = 0; + + while (startValue < target) { + if (target % 2 == 0) + target /= 2; + else + ++target; + ++ops; + } + + return ops + startValue - target; + } +}; diff --git a/solutions/991. Broken Calculator/991.java b/solutions/991. Broken Calculator/991.java new file mode 100644 index 00000000000..29275128f7b --- /dev/null +++ b/solutions/991. Broken Calculator/991.java @@ -0,0 +1,15 @@ +class Solution { + public int brokenCalc(int startValue, int target) { + int ops = 0; + + while (startValue < target) { + if (target % 2 == 0) + target /= 2; + else + ++target; + ++ops; + } + + return ops + startValue - target; + } +} diff --git a/solutions/991. Broken Calculator/991.py b/solutions/991. Broken Calculator/991.py new file mode 100644 index 00000000000..0bde91b060c --- /dev/null +++ b/solutions/991. Broken Calculator/991.py @@ -0,0 +1,12 @@ +class Solution: + def brokenCalc(self, startValue: int, target: int) -> int: + ops = 0 + + while startValue < target: + if target % 2 == 0: + target //= 2 + else: + target += 1 + ops += 1 + + return ops + startValue - target diff --git a/solutions/992. Subarrays with K Different Integers/992.cpp b/solutions/992. Subarrays with K Different Integers/992.cpp new file mode 100644 index 00000000000..d15c5c38614 --- /dev/null +++ b/solutions/992. Subarrays with K Different Integers/992.cpp @@ -0,0 +1,24 @@ +class Solution { + public: + int subarraysWithKDistinct(vector& nums, int k) { + return subarrayWithAtMostKDistinct(nums, k) - + subarrayWithAtMostKDistinct(nums, k - 1); + } + + private: + int subarrayWithAtMostKDistinct(const vector& nums, int k) { + int res = 0; + vector count(nums.size() + 1); + + for (int l = 0, r = 0; r < nums.size(); ++r) { + if (++count[nums[r]] == 1) + --k; + while (k == -1) + if (--count[nums[l++]] == 0) + ++k; + res += r - l + 1; // nums[l..r], nums[l + 1..r], ..., nums[r] + } + + return res; + } +}; diff --git a/solutions/992. Subarrays with K Different Integers/992.java b/solutions/992. Subarrays with K Different Integers/992.java new file mode 100644 index 00000000000..1a2b1e8602d --- /dev/null +++ b/solutions/992. Subarrays with K Different Integers/992.java @@ -0,0 +1,21 @@ +class Solution { + public int subarraysWithKDistinct(int[] nums, int k) { + return subarraysWithAtMostKDistinct(nums, k) - subarraysWithAtMostKDistinct(nums, k - 1); + } + + private int subarraysWithAtMostKDistinct(int[] nums, int k) { + int res = 0; + int[] count = new int[nums.length + 1]; + + for (int l = 0, r = 0; r < nums.length; ++r) { + if (++count[nums[r]] == 1) + --k; + while (k == -1) + if (--count[nums[l++]] == 0) + ++k; + res += r - l + 1; // nums[l..r], nums[l + 1..r], ..., nums[r] + } + + return res; + } +} diff --git a/solutions/992. Subarrays with K Different Integers/992.py b/solutions/992. Subarrays with K Different Integers/992.py new file mode 100644 index 00000000000..c7eea10c0ae --- /dev/null +++ b/solutions/992. Subarrays with K Different Integers/992.py @@ -0,0 +1,21 @@ +class Solution: + def subarraysWithKDistinct(self, nums: List[int], k: int) -> int: + def subarraysWithAtMostKDistinct(k: int) -> int: + res = 0 + count = collections.Counter() + + l = 0 + for r, num in enumerate(nums): + count[num] += 1 + if count[num] == 1: + k -= 1 + while k < 0: + count[nums[l]] -= 1 + if count[nums[l]] == 0: + k += 1 + l += 1 + res += r - l + 1 # nums[l..r], nums[l + 1..r], ..., nums[r] + + return res + + return subarraysWithAtMostKDistinct(k) - subarraysWithAtMostKDistinct(k - 1) diff --git a/solutions/993. Cousins in Binary Tree/993.cpp b/solutions/993. Cousins in Binary Tree/993.cpp new file mode 100644 index 00000000000..9deb3a1f7c6 --- /dev/null +++ b/solutions/993. Cousins in Binary Tree/993.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + bool isCousins(TreeNode* root, int x, int y) { + if (root == nullptr) + return false; + + queue queue{{root}}; + + while (!queue.empty()) { + bool isFindX = false; + bool isFindY = false; + for (int i = queue.size(); i > 0; --i) { + root = queue.front(), queue.pop(); + if (root->val == x) + isFindX = true; + else if (root->val == y) + isFindY = true; + else if (root->left && root->right) { + if (root->left->val == x && root->right->val == y) + return false; + if (root->left->val == y && root->right->val == x) + return false; + } + if (root->left) + queue.push(root->left); + if (root->right) + queue.push(root->right); + } + if (isFindX && isFindY) + return true; + else if (isFindX || isFindY) + return false; + } + + return false; + } +}; diff --git a/solutions/994. Rotting Oranges/994-2.cpp b/solutions/994. Rotting Oranges/994-2.cpp new file mode 100644 index 00000000000..8f74fd71015 --- /dev/null +++ b/solutions/994. Rotting Oranges/994-2.cpp @@ -0,0 +1,42 @@ +class Solution { + public: + int orangesRotting(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + int ans = 0; + int countFresh = 0; + queue> q; + + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) + ++countFresh; + else if (grid[i][j] == 2) + q.emplace(i, j); + + if (countFresh == 0) + return 0; + + while (!q.empty()) { + ++ans; + for (int sz = q.size(); sz > 0; --sz) { + const auto [i, j] = q.front(); + q.pop(); + for (const auto& [dx, dy] : dirs) { + const int x = i + dx; + const int y = j + dy; + if (x < 0 || x == m || y < 0 || y == n) + continue; + if (grid[x][y] != 1) + continue; + grid[x][y] = 2; // Mark grid[x][y] as rotten. + q.emplace(x, y); // Push the newly rotten orange to the queue. + --countFresh; // Decrease the count of fresh oranges by 1. + } + } + } + + return countFresh == 0 ? ans - 1 : -1; + } +}; diff --git a/solutions/994. Rotting Oranges/994.cpp b/solutions/994. Rotting Oranges/994.cpp new file mode 100644 index 00000000000..b8c448da249 --- /dev/null +++ b/solutions/994. Rotting Oranges/994.cpp @@ -0,0 +1,49 @@ +class Solution { + public: + int orangesRotting(vector>& grid) { + constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + const int m = grid.size(); + const int n = grid[0].size(); + + auto isNeighborRotten = [&](int i, int j, const vector>& grid) { + for (const auto& [dx, dy] : dirs) { + const int r = i + dx; + const int c = j + dy; + if (r < 0 || r == m || c < 0 || c == n) + continue; + if (grid[r][c] == 2) + return true; + } + return false; + }; + + int ans = 0; + + while (true) { + vector> nextGrid(m, vector(n)); + // Calculate `nextGrid` based on `grid`. + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if (grid[i][j] == 1) { // fresh + // Any of the 4-directionally oranges is rotten + if (isNeighborRotten(i, j, grid)) + nextGrid[i][j] = 2; + else + nextGrid[i][j] = 1; + } else if (grid[i][j] == 2) { // rotten + nextGrid[i][j] = 2; // Keep rotten. + } + if (nextGrid == grid) + break; + grid = nextGrid; + ++ans; + } + + return any_of(grid.begin(), grid.end(), + [&](vector& row) { + return ranges::any_of(row, [&](int orange) { return orange == 1; }); + }) + ? -1 + : ans; + } +}; diff --git a/solutions/995. Minimum Number of K Consecutive Bit Flips/995.cpp b/solutions/995. Minimum Number of K Consecutive Bit Flips/995.cpp new file mode 100644 index 00000000000..3c1e6fdc46b --- /dev/null +++ b/solutions/995. Minimum Number of K Consecutive Bit Flips/995.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + int minKBitFlips(vector& nums, int k) { + int ans = 0; + int flippedTime = 0; + + for (int i = 0; i < nums.size(); ++i) { + if (i >= k && nums[i - k] == 2) + --flippedTime; + if (flippedTime % 2 == nums[i]) { + if (i + k > nums.size()) + return -1; + ++ans; + ++flippedTime; + nums[i] = 2; + } + } + + return ans; + } +}; diff --git a/solutions/995. Minimum Number of K Consecutive Bit Flips/995.java b/solutions/995. Minimum Number of K Consecutive Bit Flips/995.java new file mode 100644 index 00000000000..cbf19231da0 --- /dev/null +++ b/solutions/995. Minimum Number of K Consecutive Bit Flips/995.java @@ -0,0 +1,20 @@ +class Solution { + public int minKBitFlips(int[] nums, int k) { + int ans = 0; + int flippedTime = 0; + + for (int i = 0; i < nums.length; ++i) { + if (i >= k && nums[i - k] == 2) + --flippedTime; + if (flippedTime % 2 == nums[i]) { + if (i + k > nums.length) + return -1; + ++ans; + ++flippedTime; + nums[i] = 2; + } + } + + return ans; + } +} diff --git a/solutions/995. Minimum Number of K Consecutive Bit Flips/995.py b/solutions/995. Minimum Number of K Consecutive Bit Flips/995.py new file mode 100644 index 00000000000..7962c0d8127 --- /dev/null +++ b/solutions/995. Minimum Number of K Consecutive Bit Flips/995.py @@ -0,0 +1,16 @@ +class Solution: + def minKBitFlips(self, nums: List[int], k: int) -> int: + ans = 0 + flippedTime = 0 + + for i, num in enumerate(nums): + if i >= k and nums[i - k] == 2: + flippedTime -= 1 + if flippedTime % 2 == num: + if i + k > len(nums): + return -1 + ans += 1 + flippedTime += 1 + nums[i] = 2 + + return ans diff --git a/solutions/996. Number of Squareful Arrays/996.cpp b/solutions/996. Number of Squareful Arrays/996.cpp new file mode 100644 index 00000000000..55afe2264a7 --- /dev/null +++ b/solutions/996. Number of Squareful Arrays/996.cpp @@ -0,0 +1,37 @@ +class Solution { + public: + int numSquarefulPerms(vector& nums) { + int ans = 0; + ranges::sort(nums); + dfs(nums, vector(nums.size()), {}, ans); + return ans; + } + + private: + void dfs(vector& nums, vector&& used, vector&& path, + int& ans) { + if (path.size() > 1 && !isSquare(path.back() + path[path.size() - 2])) + return; + if (path.size() == nums.size()) { + ++ans; + return; + } + + for (int i = 0; i < nums.size(); ++i) { + if (used[i]) + continue; + if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) + continue; + used[i] = true; + path.push_back(nums[i]); + dfs(nums, move(used), move(path), ans); + path.pop_back(); + used[i] = false; + } + } + + bool isSquare(int num) { + const int root = sqrt(num); + return root * root == num; + } +}; diff --git a/solutions/996. Number of Squareful Arrays/996.java b/solutions/996. Number of Squareful Arrays/996.java new file mode 100644 index 00000000000..a3b53ccf7db --- /dev/null +++ b/solutions/996. Number of Squareful Arrays/996.java @@ -0,0 +1,36 @@ +class Solution { + public int numSquarefulPerms(int[] nums) { + boolean[] used = new boolean[nums.length]; + Arrays.sort(nums); + dfs(nums, used, new ArrayList<>()); + return ans; + } + + private int ans = 0; + + private void dfs(int[] nums, boolean[] used, List path) { + if (path.size() > 1 && !isSquare(path.get(path.size() - 1) + path.get(path.size() - 2))) + return; + if (path.size() == nums.length) { + ++ans; + return; + } + + for (int i = 0; i < nums.length; ++i) { + if (used[i]) + continue; + if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) + continue; + used[i] = true; + path.add(nums[i]); + dfs(nums, used, path); + path.remove(path.size() - 1); + used[i] = false; + } + } + + private boolean isSquare(int num) { + int root = (int) Math.sqrt(num); + return root * root == num; + } +} diff --git a/solutions/996. Number of Squareful Arrays/996.py b/solutions/996. Number of Squareful Arrays/996.py new file mode 100644 index 00000000000..8dff9db61ad --- /dev/null +++ b/solutions/996. Number of Squareful Arrays/996.py @@ -0,0 +1,29 @@ +class Solution: + def numSquarefulPerms(self, nums: List[int]) -> int: + ans = 0 + used = [False] * len(nums) + + def isSquare(num: int) -> bool: + root = math.isqrt(num) + return root * root == num + + def dfs(path: List[int]) -> None: + nonlocal ans + if len(path) > 1 and not isSquare(path[-1] + path[-2]): + return + if len(path) == len(nums): + ans += 1 + return + + for i, a in enumerate(nums): + if used[i]: + continue + if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: + continue + used[i] = True + dfs(path + [a]) + used[i] = False + + nums.sort() + dfs([]) + return ans diff --git a/solutions/997. Find the Town Judge/997.cpp b/solutions/997. Find the Town Judge/997.cpp new file mode 100644 index 00000000000..ed8e5969f11 --- /dev/null +++ b/solutions/997. Find the Town Judge/997.cpp @@ -0,0 +1,17 @@ +class Solution { + public: + int findJudge(int n, vector>& trust) { + vector count(n + 1); + + for (vector& t : trust) { + --count[t[0]]; + ++count[t[1]]; + } + + for (int i = 1; i < n + 1; ++i) + if (count[i] == n - 1) + return i; + + return -1; + } +}; diff --git a/solutions/997. Find the Town Judge/997.java b/solutions/997. Find the Town Judge/997.java new file mode 100644 index 00000000000..a3c7fbbf848 --- /dev/null +++ b/solutions/997. Find the Town Judge/997.java @@ -0,0 +1,16 @@ +class Solution { + public int findJudge(int n, int[][] trust) { + int[] count = new int[n + 1]; + + for (int[] t : trust) { + --count[t[0]]; + ++count[t[1]]; + } + + for (int i = 1; i < n + 1; ++i) + if (count[i] == n - 1) + return i; + + return -1; + } +} diff --git a/solutions/997. Find the Town Judge/997.py b/solutions/997. Find the Town Judge/997.py new file mode 100644 index 00000000000..62ca1116abd --- /dev/null +++ b/solutions/997. Find the Town Judge/997.py @@ -0,0 +1,13 @@ +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + count = [0] * (n + 1) + + for a, b in trust: + count[a] -= 1 + count[b] += 1 + + for i in range(1, n + 1): + if count[i] == n - 1: + return i + + return -1 diff --git a/solutions/998. Maximum Binary Tree II/998-2.cpp b/solutions/998. Maximum Binary Tree II/998-2.cpp new file mode 100644 index 00000000000..1be0183d2e9 --- /dev/null +++ b/solutions/998. Maximum Binary Tree II/998-2.cpp @@ -0,0 +1,13 @@ +class Solution { + public: + TreeNode* insertIntoMaxTree(TreeNode* root, int val) { + if (root->val < val) + return new TreeNode(val, root, nullptr); + TreeNode* curr = root; + while (curr->right && curr->right->val > val) + curr = curr->right; + TreeNode* inserted = new TreeNode(val, curr->right, nullptr); + curr->right = inserted; + return root; + } +}; diff --git a/solutions/998. Maximum Binary Tree II/998-2.java b/solutions/998. Maximum Binary Tree II/998-2.java new file mode 100644 index 00000000000..6328ac1c619 --- /dev/null +++ b/solutions/998. Maximum Binary Tree II/998-2.java @@ -0,0 +1,12 @@ +class Solution { + public TreeNode insertIntoMaxTree(TreeNode root, int val) { + if (root.val < val) + return new TreeNode(val, root, null); + TreeNode curr = root; + while (curr.right != null && curr.right.val > val) + curr = curr.right; + TreeNode inserted = new TreeNode(val, curr.right, null); + curr.right = inserted; + return root; + } +} diff --git a/solutions/998. Maximum Binary Tree II/998-2.py b/solutions/998. Maximum Binary Tree II/998-2.py new file mode 100644 index 00000000000..e0a631a5f3a --- /dev/null +++ b/solutions/998. Maximum Binary Tree II/998-2.py @@ -0,0 +1,10 @@ +class Solution: + def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if root.val < val: + return TreeNode(val, root, None) + curr = root + while curr.right and curr.right.val > val: + curr = curr.right + inserted = TreeNode(val, curr.right, None) + curr.right = inserted + return root diff --git a/solutions/998. Maximum Binary Tree II/998.cpp b/solutions/998. Maximum Binary Tree II/998.cpp new file mode 100644 index 00000000000..b75ecbcd5b4 --- /dev/null +++ b/solutions/998. Maximum Binary Tree II/998.cpp @@ -0,0 +1,11 @@ +class Solution { + public: + TreeNode* insertIntoMaxTree(TreeNode* root, int val) { + if (root == nullptr) + return new TreeNode(val); + if (root->val < val) + return new TreeNode(val, root, nullptr); + root->right = insertIntoMaxTree(root->right, val); + return root; + } +}; diff --git a/solutions/998. Maximum Binary Tree II/998.java b/solutions/998. Maximum Binary Tree II/998.java new file mode 100644 index 00000000000..788999e199c --- /dev/null +++ b/solutions/998. Maximum Binary Tree II/998.java @@ -0,0 +1,10 @@ +class Solution { + public TreeNode insertIntoMaxTree(TreeNode root, int val) { + if (root == null) + return new TreeNode(val); + if (root.val < val) + return new TreeNode(val, root, null); + root.right = insertIntoMaxTree(root.right, val); + return root; + } +} diff --git a/solutions/998. Maximum Binary Tree II/998.py b/solutions/998. Maximum Binary Tree II/998.py new file mode 100644 index 00000000000..d4c46091fab --- /dev/null +++ b/solutions/998. Maximum Binary Tree II/998.py @@ -0,0 +1,8 @@ +class Solution: + def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: + return TreeNode(val) + if root.val < val: + return TreeNode(val, root, None) + root.right = self.insertIntoMaxTree(root.right, val) + return root diff --git a/solutions/999. Available Captures for Rook/999.cpp b/solutions/999. Available Captures for Rook/999.cpp new file mode 100644 index 00000000000..d37cab32ed9 --- /dev/null +++ b/solutions/999. Available Captures for Rook/999.cpp @@ -0,0 +1,27 @@ +class Solution { + public: + int numRookCaptures(vector>& board) { + int ans = 0; + int i0 = 0; + int j0 = 0; + + for (int i = 0; i < 8; ++i) + for (int j = 0; j < 8; ++j) + if (board[i][j] == 'R') { + i0 = i; + j0 = j; + } + + for (const vector& d : + vector>({{1, 0}, {0, 1}, {-1, 0}, {0, -1}})) + for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8; + i += d[0], j += d[1]) { + if (board[i][j] == 'p') + ++ans; + if (board[i][j] != '.') + break; + } + + return ans; + } +}; diff --git a/solutions/999. Available Captures for Rook/999.java b/solutions/999. Available Captures for Rook/999.java new file mode 100644 index 00000000000..d4a30222092 --- /dev/null +++ b/solutions/999. Available Captures for Rook/999.java @@ -0,0 +1,25 @@ +class Solution { + public int numRookCaptures(char[][] board) { + int ans = 0; + int i0 = 0; + int j0 = 0; + + for (int i = 0; i < 8; ++i) + for (int j = 0; j < 8; ++j) + if (board[i][j] == 'R') { + i0 = i; + j0 = j; + } + + for (int[] d : new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}) + for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8; + i += d[0], j += d[1]) { + if (board[i][j] == 'p') + ++ans; + if (board[i][j] != '.') + break; + } + + return ans; + } +} diff --git a/solutions/999. Available Captures for Rook/999.py b/solutions/999. Available Captures for Rook/999.py new file mode 100644 index 00000000000..bcf0a4405fd --- /dev/null +++ b/solutions/999. Available Captures for Rook/999.py @@ -0,0 +1,22 @@ +class Solution: + def numRookCaptures(self, board: List[List[str]]) -> int: + ans = 0 + + for i in range(8): + for j in range(8): + if board[i][j] == 'R': + i0 = i + j0 = j + + for d in [[1, 0], [0, 1], [-1, 0], [0, -1]]: + i = i0 + d[0] + j = j0 + d[1] + while 0 <= i < 8 and 0 <= j < 8: + if board[i][j] == 'p': + ans += 1 + if board[i][j] != '.': + break + i += d[0] + j += d[1] + + return ans